text
stringlengths
3
1.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Example demonstrating spatial filtering using spatial-filters fragment shader. Left and Right Arrow Keys toggle through available filters. """ import numpy as np from vispy.io import load_spatial_filters from vispy import gloo from vispy import app from vispy.util.logs import set_log_level # turn off INFO messages, see PR #1363 # Some shader compilers will optimize out the 'u_shape' and 'u_kernel' # uniforms for the Nearest filter since they are unused, resulting in # an INFO message about them not being active set_log_level('warning') # create 5x5 matrix with border pixels 0, center pixels 1 # and other pixels 0.5 img_array = np.zeros(25).reshape((5, 5)).astype(np.float32) img_array[1:4, 1::2] = 0.5 img_array[1::2, 2] = 0.5 img_array[2, 2] = 1.0 # loading interpolation kernel kernel, names = load_spatial_filters() # A simple texture quad data = np.zeros(4, dtype=[('a_position', np.float32, 2), ('a_texcoord', np.float32, 2)]) data['a_position'] = np.array([[-1, -1], [+1, -1], [-1, +1], [+1, +1]]) data['a_texcoord'] = np.array([[1, 0], [1, 1], [0, 0], [0, 1]]) VERT_SHADER = """ // Attributes attribute vec2 a_position; attribute vec2 a_texcoord; // Varyings varying vec2 v_texcoord; // Main void main (void) { v_texcoord = a_texcoord; gl_Position = vec4(a_position,0.0,1.0); } """ FRAG_SHADER = """ #include "misc/spatial-filters.frag" uniform sampler2D u_texture; uniform vec2 u_shape; varying vec2 v_texcoord; void main() { gl_FragColor = %s(u_texture, u_shape, v_texcoord); } """ class Canvas(app.Canvas): def __init__(self): app.Canvas.__init__(self, keys='interactive', size=((512), (512))) self.program = gloo.Program(VERT_SHADER, FRAG_SHADER % 'Nearest') self.texture = gloo.Texture2D(img_array, interpolation='nearest') # using packed data as discussed in pr #1069 self.kernel = gloo.Texture2D(kernel, interpolation='nearest') self.program['u_texture'] = self.texture self.program['u_shape'] = img_array.shape[1], img_array.shape[0] self.program['u_kernel'] = self.kernel self.names = names self.filter = 16 self.title = 'Spatial Filtering using %s Filter' % \ self.names[self.filter] self.program.bind(gloo.VertexBuffer(data)) self.context.set_clear_color('white') self.context.set_viewport(0, 0, 512, 512) self.show() def on_key_press(self, event): if event.key in ['Left', 'Right']: if event.key == 'Right': step = 1 else: step = -1 self.filter = (self.filter + step) % 17 self.program.set_shaders(VERT_SHADER, FRAG_SHADER % self.names[self.filter]) self.title = 'Spatial Filtering using %s Filter' % \ self.names[self.filter] self.update() def on_resize(self, event): self.context.set_viewport(0, 0, *event.physical_size) def on_draw(self, event): self.context.clear(color=True, depth=True) self.program.draw('triangle_strip') if __name__ == '__main__': c = Canvas() app.run()
// pages/mine/mine.js import { getUserInfo, makePhoneCall } from '../../utils/util' import { logout } from '../../utils/apis' const app = getApp() Page({ data:{}, onLoad:function(options){ // 页面初始化 options为页面跳转所带来的参数 var that = this getUserInfo(userInfo => { this.setData({ userInfo }) }) }, onReady:function(){ // 页面渲染完成 }, onShow:function(){ // 页面显示 var that = this app.getLoginInfo(loginInfo => { that.setData({ loginInfo: loginInfo.user_info }) }) }, onHide:function(){ // 页面隐藏 }, onUnload:function(){ // 页面关闭 }, onPhoneTap(e) { makePhoneCall(e.currentTarget.dataset.phone) }, onLogout(e) { var that = this var {loginInfo: {phone}, loading} = this.data if(loading) { return } this.setData({ loading: true }) logout({ phone, success(data) { app.setLoginInfo(data) that.setData({ loginInfo: null, loading: false }) } }) }, callback(loginInfo) { this.setData({ loginInfo: loginInfo.user_info }) }, onShareAppMessage() { return { title: '我的信息', path: '/pages/mine/mine' } } })
define(["amaze","wx","framework/services/shoppingService"],function (amaze,wx,shopList){ var ctrl = ["$scope","$state","orderList","$q",function($scope,$state,orderList,$q){ var shopInc = new shopList($q); // get select product start $scope.displayOrderList = orderList.getList(); $scope.createOrderAddress = {}; $scope.payProductDetails = []; var header = { headers:$scope.users.setheaders } function selectTimeByDate(){ var a=new Date(); var getHours=a.getHours(); var getMinutes=a.getMinutes(); if(getHours<10){ return 1; } if(getHours<11&&getMinutes<30){ return 1; } if(getHours<14){ return 2; } if(getHours<15&&getMinutes<30){ return 2; } return 3; } var type=selectTimeByDate(); if(type==1){ $scope.selecTime="上午11点" }else if(type==2){ $scope.selecTime="下午三点" }else{ $scope.selecTime="即时配送" } buildTipe(); function buildTipe(){ var a= new Date(); var type=selectTimeByDate(); if($scope.selecTime=="即时配送"){ var tips="三小时内配送"; }else if($scope.selecTime=="上午11点"){ var tips=""; a.setHours(11) if(type>1){ a.setHours(35) var tips="明天"; } tips+=$scope.selecTime; }else{ var tips=""; a.setHours(15) if(type>2){ a.setHours(39) var tips="明天"; } tips+=$scope.selecTime; } $scope.delivery_time=a.Format("yyyy-MM-dd hh:mm:ss"); $scope.tips=tips; } $scope.timeSelects=["即时配送","上午11点","下午三点"] $scope.selectTime=function (time){ $scope.selecTime=time; buildTipe() } // createOrderAndPay $scope.getSigntureAndPay = function(){ // check address if (!($scope.createOrderAddress.address && $scope.createOrderAddress.address.id )) { alert("请先添加收获地址"); $scope.addOrChangeAddr(); // return; }; var shopping_cart_ids=[]; for (var i = 0; i < $scope.displayOrderList.length; i++) { shopping_cart_ids.push($scope.displayOrderList[i].id); }; var details = { "total_price":$scope.allPrice, "buyer_id": $scope.users.customer.id, "buyer_type": "Customer", "shopping_cart_ids": shopping_cart_ids, "delivery_time" :$scope.delivery_time, "address_id": $scope.createOrderAddress.address.id, "pay_away":$scope.payWay } shopInc.createOrderAndPay(header,{order:details}).then(function(data){ if(data.code!==0){ alert(data.message); return; } var createOrderData=data.data.order.data; if($scope.payWay===1){ var signature = createOrderData.prepay_data; WeixinJSBridge.invoke( 'getBrandWCPayRequest', { "appId" : signature.appId, //公众号名称,由商户传入 "timeStamp": signature.timeStamp.toString(), //时间戳,自1970年以来的秒数 "nonceStr" : signature.nonceStr, //随机串 "package" : signature.package, "signType" : signature.signType, //微信签名方式: "paySign" : signature.paySign //微信签名 }, function(res){ // alert(JSON.stringify(res)) if(res.err_msg == "get_brand_wcpay_request:ok" ) { $state.go("orderDet",{orderId:createOrderData.id}); getShopListNum(); }else if(res.err_msg == "get_brand_wcpay_request:cancel"){ alert("取消操作") } } ); }else{ $state.go("orderDet",{orderId:createOrderData.id}); getShopListNum(); } },function(err){ alert("网络较差,请重新操作!") }); } $scope.allPrice = orderList.allPrice; console.log($scope.displayOrderList,"orderlist.....") // get select product end $scope.addOrChangeAddr = function(){ $state.go("receiveAddr"); } // address save function getShopListNum(){ shopInc.getAllOrderList($scope.users.customer.id).then(function(data){ $scope.shopListNum.num = data.data.total_count; },function(err){ alert("网络不流畅,请重新操作!") console.log(err,"shopInc...err....") }); } function initAddress(){ shopInc.getAccountAddress($scope.users.owner_id).then(function(data){ // shopInc.getAccountAddress($scope.users.customer.id).then(function(data){ console.log(data); filterDefault(data.data) console.log($scope.createOrderAddress.address) function filterDefault(data){ if (!data.length) { $scope.createOrderAddress.address = ""; return; }; for (var i = 0; i < data.length; i++) { if (data[i].is_default == true) { var address=data[i]; address.detailed_address=address.name + " "+address.phone + " "+address.address ; $scope.createOrderAddress.address = address; break; }; }; } },function(err){ }); } initAddress(); $scope.payWay=2; $scope.selectPayWay=function (type){ $scope.payWay=type; } }] return ctrl; });
# coding:utf-8 # 版权信息: All rights Reserved, Designed By XHal.cc # 代码作者: Hal # 创建时间: 2021/1/31 16:59 # 文件版本: V1.0.0 # 功能描述: 运算符的优先级 # 优先级0: () 有括号,括号内优先执行 # 优先级1: 算术运算符 ** 》 *,/,//,% 》 *,- # 优先级2: 位运算符 <<,>> 》 & 》 | # 优先级3: 比较运算符 >,<,>=,<=,==,!= # 优先级4: 布尔运算符 and , or # 优先级5: 赋值运算符 =
from allauth.account.adapter import DefaultAccountAdapter class CustomAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=False): user = super().save_user(request, user, form, commit) data = form.cleaned_data user.first_name = data.get('first_name') user.last_name = data.get('last_name') user.address = data.get('address') user.cac_id = data.get('cac_id') user.save() return user
from math import ceil ''' 直观理解 yield 要想通俗理解 yield,可结合函数的返回值关键字 return,yield 是一种特殊的 return。 说是特殊的 return,是因为执行遇到 yield 时,立即返回,这是与 return 的相似之处。 不同之处在于:下次进入函数时直接到 yield 的下一个语句,而 return 后再进入函数, 还是从函数体的第一行代码开始执行。带 yield 的函数是生成器,通常与 next 函数结合用。 下次进入函数,意思是使用 next 函数进入到函数体内。 ''' def f(): print("enter f()...") yield 4 print("i am next sentence of yield.") g = f() active = True i = 0 while(active): i += 1 try: next(g) except StopIteration: print(f"%d times, Iteration Stop" % i) break # yield 与生成器 # 函数带有 yield,就是一个生成器,英文 generator,它的重要优点之一节省内存。 def myrange(stop): start = 0 while start < stop: yield start start += 1 for i in myrange(10): print(i) # send 函数 # 带 yield 的生成器对象里还封装了一个 send 方法。 # 下例暂时send用法,send函数赋值给yield左侧的result变量,然后继续执行yield的下一句 def f(): print('enter f...') while True: result = yield 4 if result: print('send me a value is:%d' % (result,)) return else: print('no send', result) g = f() print(next(g)) print('ready to send') print(g.send(None)) print(g.send('')) print(g.send(False)) # print(g.send(10)) # 1. 完全展开 list # 下面的函数 deep_flatten 定义中使用了 yield 关键字,实现嵌套 list 的完全展开。 def deep_flatten(lst): for i in lst: if type(i) == list: yield from deep_flatten(i) else: yield i gen = deep_flatten([1, ['s', ['a', 'b'], 3], 4, 5]) print(gen) for i in gen: print(i) # 2. 列表分组 #from math import ceil def divide_iter(lst, n): if n <= 0: yield lst return i, div = 0, ceil(len(lst) / n) while i < n: yield lst[i * div: (i + 1) * div] i += 1 print(list(divide_iter([1, 2, 3, 4, 5], 0))) # [[1, 2, 3, 4, 5]] print(list(divide_iter([1, 2, 3, 4, 5], 2))) # [[1, 2, 3], [4, 5]] ''' nonlocal 关键字 关键词 nonlocal 常用于函数嵌套中,声明变量为非局部变量。 ''' def ff(): i = 0 def auto_increase(): nonlocal i # 使用 nonlocal 告诉编译器,i 不是局部变量 if i >= 10: i = 0 i += 1 ret = [] for _ in range(28): auto_increase() ret.append(i) print(ret) ff() #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4,5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8] ####################### #global 关键字 # 先回答为什么要有 global。 # 一个变量被多个函数引用,想让全局变量被所有函数共享。 # 有的伙伴可能会想这还不简单,这样写: i = 5 def f(): print(i) def g(): print(i) pass f() g() # f 和 g 两个函数都能共享变量 i,程序没有报错,所以,至此依然没有真正解释global 存在的价值。 # 但是,如果某个函数要修改 i,实现递增,这样: def h(): i += 1 h() # 此时执行程序,就会出错,抛出异常 UnboundLocalError,原来编译器在解释 i += 1 时, # 会解析 i 为函数 h() 内的局部变量。很显然,在此函数内,解释器找不到对变量 i 的定义,所以报错。 # global 在此种场景下,会大显身手。 # 在函数 h 内,显示地告诉解释器 i 为全局变量,然后,解释器会在函数外面寻找 i 的定义, # 执行完 i += 1 后,i 还为全局变量,值加 1: i = 0 def hh(): global i i += 1 h() print(i)
import CellState from '../src/cell_state'; describe('CellState', () => { test('Should have a ALIVE cell state', () => { expect(CellState.ALIVE).toBe(1); }); test('Should have a DEAD cell state', () => { expect(CellState.DEAD).toBe(0); }); });
/** Negative Nouns */ export const negative_nouns = [ 'Hell', 'Microsoft', 'bastard', 'beggar', 'blister', 'codpiece', 'coward', 'curse', 'death', 'devil', 'draught', 'famine', 'flirt-gill', 'goat', 'hate', 'hog', 'hound', 'leech', 'lie', 'pig', 'plague', 'starvation', 'toad', 'war', 'wolf' ];
/** * Module dependencies. */ var mocha = require("mocha") , Base = mocha.reporters.Base , Spec = mocha.reporters.Spec , utils = mocha.utils , escape = utils.escape , config = { "file": "xunit.xml", "consoleOutput": { "suite": false, "test": false, "fail": false } } , fs = require("fs") , differ = require("./differ") , consoleOutput = config.consoleOutput || {}; /** * Save timer references to avoid Sinon interfering (see GH-237). */ /* global Date: true */ var Date = global.Date /* global setTimeout: true */ , setTimeout = global.setTimeout /* global setInterval: true */ , setInterval = global.setInterval /* global clearTimeout: true */ , clearTimeout = global.clearTimeout /* global clearInterval: true */ , clearInterval = global.clearInterval; function cleanObject(obj){ var o = obj.replace(/\n\s\s/g,',') .replace(/\s+/g,' ').trim() .replace(/\{,/g,"{") .replace(/\n\}/g,"}") .replace(/\"/g, '"') .replace(/\[,/g, '\[') .replace(/\}, \]/g, '\}\]') .replace(/,\s?\}/g, '}') .replace(/\[null\]/g, 'null').toString(); o = JSON.parse(JSON.stringify(o)); return o; } function appendLine(fd, line) { if (process.env.LOG_XUNIT) { console.log(line); } fs.writeSync(fd, line + "\n", null, 'utf8'); } /** * Return cdata escaped CDATA `str`. */ function cdata(str, omit_esc) { omit_esc = (typeof omit_esc == 'undefined') ? false : omit_esc; if (!omit_esc) { return '<![CDATA[' + escape(str) + ']]>'; } else { return '<![CDATA[' + str + ']]>'; } } /** * HTML tag helper. */ function writeTag(name, attrs, close, content) { var end = close ? '/>' : '>' , pairs = [] , tag; for (var key in attrs) { pairs.push(key + '="' + escape(attrs[key]) + '"'); } tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; if (content) { tag += content + '</' + name + end; } return tag; } /** * Output tag for the given `test.` */ function writeTest(fd, test) { var attrs = { classname: test.parent.fullTitle() , name: test.title // , time: test.duration / 1000 //old , time: test.duration ? test.duration / 1000 : 0 //new }; if ('failed' === test.state) { var err = test.err; if (err.showDiff && err.actual.length > 0 && err.expected.length > 0) { var expected = cleanObject(err.expected); var actual = cleanObject(err.actual); //var str = JSON.parse(JSON.stringify(expected)) + "\n" + JSON.parse(JSON.stringify(actual, null, 4)) + "\n" + escape(err.stack); // old original method var differences = differ.diffJSON(expected, actual); var formattedDiff = "Diff => "+ "\n" + JSON.stringify(differences, null, " ") + "\n" + escape(err.stack); appendLine(fd, writeTag('testcase', attrs, false, writeTag('failure', {message: escape(err.message)}, false, cdata(formattedDiff, true)))); } else { appendLine(fd, writeTag('testcase', attrs, false, writeTag('failure', {message: escape(err.message)}, false, cdata(err.stack)))); } } else if (test.pending) { delete attrs.time; appendLine(fd, writeTag('testcase', attrs, false, writeTag('skipped', {}, true))); } else { appendLine(fd, writeTag('testcase', attrs, true)); } } /** * Initialize a new `SpecXUnitFile` reporter. * * @param {Runner} runner * @api public */ function SpecXUnitFile(runner) { var spec = new Spec(runner); Base.call(this, runner); var stats = this.stats , tests = [] , self = this; runner.on('suite', function (suite) { if (consoleOutput.suite) { console.log(' ' + suite.title); } }); runner.on('test', function (test) { if (consoleOutput.test) { console.log(' ◦ ' + test.title); } }); runner.on('pass', function (test) { tests.push(test); }); runner.on('fail', function (test) { if (consoleOutput.fail) { console.log(' - ' + test.title); } tests.push(test); }); runner.on('pending', function (test) { tests.push(test); }); runner.on('end', function () { var filePath = process.env.XUNIT_FILE || config.file || process.cwd() + "/xunit.xml" , fd = fs.openSync(filePath, 'w', 0755) ; appendLine(fd, writeTag('testsuite', { name: 'Mocha Tests' , tests: stats.tests , failures: stats.failures , errors: stats.failures , skipped: stats.tests - stats.failures - stats.passes , timestamp: (new Date()).toUTCString() , time: stats.duration / 1000 }, false)); tests.forEach(function (test) { writeTest(fd, test); }); appendLine(fd, '</testsuite>'); fs.closeSync(fd); }); } /** * Inherit from `Base.prototype`. */ SpecXUnitFile.prototype = Base.prototype; // ============ Begin Exports ==================== exports = module.exports = SpecXUnitFile;
import React, { Component, PropTypes } from "react"; import { connect } from 'react-redux'; import MessageError from '../common/MessageError.js'; import MessageSuccess from '../common/MessageSuccess.js'; import { registerUser } from '../../actions/auth'; class Register extends Component { constructor(props) { super(props); } registerSubmit(event) { event.preventDefault(); const { register } = this.props; let details = { 'email': this.refs.email.value, 'password': this.refs.password.value, 'password_confirmation': this.refs.password_confirmation.value }; register(details); } render () { const { auth } = this.props; let errors; let success; if (auth.isFetching) { errors = (<img src="/images/loading.gif" alt=""/>); } else if (auth.isInvalid) { errors = ( <MessageError title="User error" errors={auth.errors} isVisible={true} /> ); } else if (auth.isSuccess) { success = ( <MessageSuccess title="Thanks for registering" message="Look out for an email from us" isVisible={true} /> ); } else if (auth.isFailed) { errors = ( <MessageError title="System error" message={auth.serverError} isVisible={true} /> ); } return ( <div className="container"> <form className="sign-up-on-home-page" onSubmit={(event) => this.registerSubmit(event)} method="post"> <h1 id="title" className="form-signin-heading text-center">Register</h1> <div className="register-form"> {errors} {success} <p><label htmlFor="inputEmail" className="sr-only">Email address</label></p> <p><input type="text" ref="email" id="inputEmail" name="email" className="form-control" placeholder="Email address" /></p> <p><label htmlFor="inputPassword" className="sr-only">Password</label></p> <p><input type="password" ref="password" id="inputPassword" name="password" className="form-control" placeholder="Password" /></p> <p><label htmlFor="confirmationPassword" className="sr-only">Password</label></p> <p><input type="password" ref="password_confirmation" id="confirmationPassword" name="password_confirmation" className="form-control" placeholder="Password confirmation" /></p> <br/> <p className="text-center"> <button className="btn btn-lg btn-primary" type="submit">Create an account</button> </p> <br/> <p className="text-center">Create an account or <a href="/">login with an existing account</a></p> </div> </form> </div> ); } } function mapStateToProps(state) { return { auth: state.auth }; } function mapDispatchToProps(dispatch) { return { register:(details) => { dispatch(registerUser(details)); } }; } Register.propTypes = { auth: PropTypes.object, register: PropTypes.func }; export default connect( mapStateToProps, mapDispatchToProps )(Register);
#!/usr/bin/env python from fontTools.ttLib import TTFont import sys import json # map of characters to extract metrics_to_extract = { # Font name "AMS-Regular": { u"\u21e2": None, # \dashrightarrow u"\u21e0": None, # \dashleftarrow }, "Main-Regular": { # Skew and italic metrics can't be easily parsed from the TTF. Instead, # we map each character to a "base character", which is a character # from the same font with correct italic and skew metrics. A character # maps to None if it doesn't have a base. #u"\u2209": None, # \notin #u"\u2260": None, # \neq u"\u2245": None, # \cong u"\u2026": None, # \ldots u"\u22ef": None, # \cdots u"\u22f1": None, # \ddots u"\u22ee": None, # \vdots u"\u22ee": None, # \vdots u"\u22a8": None, # \models u"\u22c8": None, # \bowtie u"\u2250": None, # \doteq u"\u23b0": None, # \lmoustache u"\u23b1": None, # \rmoustache u"\u27ee": None, # \lgroup u"\u27ef": None, # \rgroup u"\u27f5": None, # \longleftarrow u"\u27f8": None, # \Longleftarrow u"\u27f6": None, # \longrightarrow u"\u27f9": None, # \Longrightarrow u"\u27f7": None, # \longleftrightarrow u"\u27fa": None, # \Longleftrightarrow u"\u21a6": None, # \mapsto u"\u27fc": None, # \longmapsto u"\u21a9": None, # \hookleftarrow u"\u21aa": None, # \hookrightarrow u"\u21cc": None, # \rightleftharpoons }, "Size1-Regular": { u"\u222c": u"\u222b", # \iint, based on \int u"\u222d": u"\u222b", # \iiint, based on \int }, "Size2-Regular": { u"\u222c": u"\u222b", # \iint, based on \int u"\u222d": u"\u222b", # \iiint, based on \int }, } def main(): start_json = json.load(sys.stdin) for font in start_json: fontInfo = TTFont("../../fonts/KaTeX_" + font + ".ttf") glyf = fontInfo["glyf"] widths = fontInfo.getGlyphSet() unitsPerEm = float(fontInfo["head"].unitsPerEm) # We keep ALL Unicode cmaps, not just fontInfo["cmap"].getcmap(3, 1). # This is playing it extra safe, since it reports inconsistencies. # Platform 0 is Unicode, platform 3 is Windows. For platform 3, # encoding 1 is UCS-2 and encoding 10 is UCS-4. cmap = [t.cmap for t in fontInfo["cmap"].tables if (t.platformID == 0) or (t.platformID == 3 and t.platEncID in (1, 10))] chars = metrics_to_extract.get(font, {}) chars[u"\u0020"] = None # space chars[u"\u00a0"] = None # nbsp for char, base_char in chars.iteritems(): code = ord(char) names = set(t.get(code) for t in cmap) if not names: sys.stderr.write( "Codepoint {} of font {} maps to no name\n" .format(code, font)) continue if len(names) != 1: sys.stderr.write( "Codepoint {} of font {} maps to multiple names: {}\n" .format(code, font, ", ".join(sorted(names)))) continue name = names.pop() height = depth = italic = skew = width = 0 glyph = glyf[name] if glyph.numberOfContours: height = glyph.yMax / unitsPerEm depth = -glyph.yMin / unitsPerEm width = widths[name].width / unitsPerEm if base_char: base_char_str = str(ord(base_char)) base_metrics = start_json[font][base_char_str] italic = base_metrics["italic"] skew = base_metrics["skew"] width = base_metrics["width"] start_json[font][str(code)] = { "height": height, "depth": depth, "italic": italic, "skew": skew, "width": width } sys.stdout.write( json.dumps(start_json, separators=(',', ':'), sort_keys=True)) if __name__ == "__main__": main()
import copy import logging import pickle import re from datetime import datetime import dask.dataframe as dd import numpy as np import pandas as pd import pytest from woodwork.logical_types import ( URL, Boolean, Categorical, CountryCode, Datetime, Double, EmailAddress, Integer, LatLong, NaturalLanguage, Ordinal, PostalCode, SubRegionCode ) import featuretools as ft from featuretools.entityset import EntitySet from featuretools.entityset.entityset import LTI_COLUMN_NAME, WW_SCHEMA_KEY from featuretools.tests.testing_utils import get_df_tags, to_pandas from featuretools.utils.gen_utils import Library, import_or_none from featuretools.utils.koalas_utils import pd_to_ks_clean ks = import_or_none('databricks.koalas') def test_normalize_time_index_as_additional_column(es): error_text = "Not moving signup_date as it is the base time index column. Perhaps, move the column to the copy_columns." with pytest.raises(ValueError, match=error_text): assert "signup_date" in es["customers"].columns es.normalize_dataframe(base_dataframe_name='customers', new_dataframe_name='cancellations', index='cancel_reason', make_time_index='signup_date', additional_columns=['signup_date'], copy_columns=[]) def test_normalize_time_index_as_copy_column(es): assert "signup_date" in es["customers"].columns es.normalize_dataframe(base_dataframe_name='customers', new_dataframe_name='cancellations', index='cancel_reason', make_time_index='signup_date', additional_columns=[], copy_columns=['signup_date']) assert 'signup_date' in es['customers'].columns assert es['customers'].ww.time_index == 'signup_date' assert 'signup_date' in es['cancellations'].columns assert es['cancellations'].ww.time_index == 'signup_date' def test_normalize_time_index_as_copy_column_new_time_index(es): assert "signup_date" in es["customers"].columns es.normalize_dataframe(base_dataframe_name='customers', new_dataframe_name='cancellations', index='cancel_reason', make_time_index=True, additional_columns=[], copy_columns=['signup_date']) assert 'signup_date' in es['customers'].columns assert es['customers'].ww.time_index == 'signup_date' assert 'first_customers_time' in es['cancellations'].columns assert 'signup_date' not in es['cancellations'].columns assert es['cancellations'].ww.time_index == 'first_customers_time' def test_normalize_time_index_as_copy_column_no_time_index(es): assert "signup_date" in es["customers"].columns es.normalize_dataframe(base_dataframe_name='customers', new_dataframe_name='cancellations', index='cancel_reason', make_time_index=False, additional_columns=[], copy_columns=['signup_date']) assert 'signup_date' in es['customers'].columns assert es['customers'].ww.time_index == 'signup_date' assert 'signup_date' in es['cancellations'].columns assert es['cancellations'].ww.time_index is None def test_cannot_re_add_relationships_that_already_exists(es): warn_text = "Not adding duplicate relationship: " + str(es.relationships[0]) before_len = len(es.relationships) rel = es.relationships[0] with pytest.warns(UserWarning, match=warn_text): es.add_relationship(relationship=rel) with pytest.warns(UserWarning, match=warn_text): es.add_relationship(rel._parent_dataframe_name, rel._parent_column_name, rel._child_dataframe_name, rel._child_column_name) after_len = len(es.relationships) assert before_len == after_len def test_add_relationships_convert_type(es): for r in es.relationships: parent_df = es[r.parent_dataframe.ww.name] child_df = es[r.child_dataframe.ww.name] assert parent_df.ww.index == r._parent_column_name assert 'foreign_key' in r.child_column.ww.semantic_tags assert str(parent_df[r._parent_column_name].dtype) == str(child_df[r._child_column_name].dtype) def test_add_relationship_diff_param_logical_types(es): ordinal_1 = Ordinal(order=[0, 1, 2, 3, 4, 5, 6]) ordinal_2 = Ordinal(order=[0, 1, 2, 3, 4, 5]) es['sessions'].ww.set_types(logical_types={'id': ordinal_1}) log_2_df = es['log'].copy() log_logical_types = { 'id': Integer, 'session_id': ordinal_2, 'product_id': Categorical(), 'datetime': Datetime, 'value': Double, 'value_2': Double, 'latlong': LatLong, 'latlong2': LatLong, 'zipcode': PostalCode, 'countrycode': CountryCode, 'subregioncode': SubRegionCode, 'value_many_nans': Double, 'priority_level': Ordinal(order=[0, 1, 2]), 'purchased': Boolean, 'comments': NaturalLanguage, 'url': URL, 'email_address': EmailAddress } log_semantic_tags = { 'session_id': 'foreign_key', 'product_id': 'foreign_key' } assert set(log_logical_types) == set(log_2_df.columns) es.add_dataframe(dataframe_name='log2', dataframe=log_2_df, index='id', logical_types=log_logical_types, semantic_tags=log_semantic_tags, time_index='datetime') assert 'log2' in es.dataframe_dict assert es['log2'].ww.schema is not None assert isinstance(es['log2'].ww.logical_types['session_id'], Ordinal) assert isinstance(es['sessions'].ww.logical_types['id'], Ordinal) assert es['sessions'].ww.logical_types['id'] != es['log2'].ww.logical_types['session_id'] warning_text = 'Logical type Ordinal for child column session_id does not match parent '\ 'column id logical type Ordinal. There is a conflict between the parameters. '\ 'Changing child logical type to match parent.' with pytest.warns(UserWarning, match=warning_text): es.add_relationship(u'sessions', 'id', 'log2', 'session_id') assert isinstance(es['log2'].ww.logical_types['product_id'], Categorical) assert isinstance(es['products'].ww.logical_types['id'], Categorical) def test_add_relationship_different_logical_types_same_dtype(es): log_2_df = es['log'].copy() log_logical_types = { 'id': Integer, 'session_id': Integer, 'product_id': CountryCode, 'datetime': Datetime, 'value': Double, 'value_2': Double, 'latlong': LatLong, 'latlong2': LatLong, 'zipcode': PostalCode, 'countrycode': CountryCode, 'subregioncode': SubRegionCode, 'value_many_nans': Double, 'priority_level': Ordinal(order=[0, 1, 2]), 'purchased': Boolean, 'comments': NaturalLanguage, 'url': URL, 'email_address': EmailAddress, } log_semantic_tags = { 'session_id': 'foreign_key', 'product_id': 'foreign_key' } assert set(log_logical_types) == set(log_2_df.columns) es.add_dataframe(dataframe_name='log2', dataframe=log_2_df, index='id', logical_types=log_logical_types, semantic_tags=log_semantic_tags, time_index='datetime') assert 'log2' in es.dataframe_dict assert es['log2'].ww.schema is not None assert isinstance(es['log2'].ww.logical_types['product_id'], CountryCode) assert isinstance(es['products'].ww.logical_types['id'], Categorical) warning_text = 'Logical type CountryCode for child column product_id does not match parent column id logical type Categorical. Changing child logical type to match parent.' with pytest.warns(UserWarning, match=warning_text): es.add_relationship(u'products', 'id', 'log2', 'product_id') assert isinstance(es['log2'].ww.logical_types['product_id'], Categorical) assert isinstance(es['products'].ww.logical_types['id'], Categorical) assert 'foreign_key' in es['log2'].ww.semantic_tags['product_id'] def test_add_relationship_different_compatible_dtypes(es): log_2_df = es['log'].copy() log_logical_types = { 'id': Integer, 'session_id': Datetime, 'product_id': Categorical, 'datetime': Datetime, 'value': Double, 'value_2': Double, 'latlong': LatLong, 'latlong2': LatLong, 'zipcode': PostalCode, 'countrycode': CountryCode, 'subregioncode': SubRegionCode, 'value_many_nans': Double, 'priority_level': Ordinal(order=[0, 1, 2]), 'purchased': Boolean, 'comments': NaturalLanguage, 'url': URL, 'email_address': EmailAddress, } log_semantic_tags = { 'session_id': 'foreign_key', 'product_id': 'foreign_key' } assert set(log_logical_types) == set(log_2_df.columns) es.add_dataframe(dataframe_name='log2', dataframe=log_2_df, index='id', logical_types=log_logical_types, semantic_tags=log_semantic_tags, time_index='datetime') assert 'log2' in es.dataframe_dict assert es['log2'].ww.schema is not None assert isinstance(es['log2'].ww.logical_types['session_id'], Datetime) assert isinstance(es['customers'].ww.logical_types['id'], Integer) warning_text = 'Logical type Datetime for child column session_id does not match parent column id logical type Integer. Changing child logical type to match parent.' with pytest.warns(UserWarning, match=warning_text): es.add_relationship(u'customers', 'id', 'log2', 'session_id') assert isinstance(es['log2'].ww.logical_types['session_id'], Integer) assert isinstance(es['customers'].ww.logical_types['id'], Integer) def test_add_relationship_errors_child_v_index(es): new_df = es['log'].ww.copy() new_df.ww._schema.name = 'log2' es.add_dataframe(dataframe=new_df) to_match = "Unable to add relationship because child column 'id' in 'log2' is also its index" with pytest.raises(ValueError, match=to_match): es.add_relationship('log', 'id', 'log2', 'id') def test_add_relationship_empty_child_convert_dtype(es): relationship = ft.Relationship(es, "sessions", "id", "log", "session_id") empty_log_df = pd.DataFrame(columns=es['log'].columns) if es.dataframe_type == Library.DASK.value: empty_log_df = dd.from_pandas(empty_log_df, npartitions=2) elif es.dataframe_type == Library.KOALAS.value: empty_log_df = ks.from_pandas(empty_log_df) es.add_dataframe(empty_log_df, 'log') assert len(es['log']) == 0 # session_id will be Unknown logical type with dtype string assert es['log']['session_id'].dtype == 'string' es.relationships.remove(relationship) assert(relationship not in es.relationships) es.add_relationship(relationship=relationship) assert es['log']['session_id'].dtype == 'int64' def test_add_relationship_with_relationship_object(es): relationship = ft.Relationship(es, "sessions", "id", "log", "session_id") es.add_relationship(relationship=relationship) assert relationship in es.relationships def test_add_relationships_with_relationship_object(es): relationships = [ft.Relationship(es, "sessions", "id", "log", "session_id")] es.add_relationships(relationships) assert relationships[0] in es.relationships def test_add_relationship_error(es): relationship = ft.Relationship(es, "sessions", "id", "log", "session_id") error_message = "Cannot specify dataframe and column name values and also supply a Relationship" with pytest.raises(ValueError, match=error_message): es.add_relationship(parent_dataframe_name="sessions", relationship=relationship) def test_query_by_values_returns_rows_in_given_order(): data = pd.DataFrame({ "id": [1, 2, 3, 4, 5], "value": ["a", "c", "b", "a", "a"], "time": [1000, 2000, 3000, 4000, 5000] }) es = ft.EntitySet() es = es.add_dataframe(dataframe=data, dataframe_name="test", index="id", time_index="time", logical_types={"value": "Categorical"}) query = es.query_by_values('test', ['b', 'a'], column_name='value') assert np.array_equal(query['id'], [1, 3, 4, 5]) def test_query_by_values_secondary_time_index(es): end = np.datetime64(datetime(2011, 10, 1)) all_instances = [0, 1, 2] result = es.query_by_values('customers', all_instances, time_last=end) result = to_pandas(result, index='id') for col in ["cancel_date", "cancel_reason"]: nulls = result.loc[all_instances][col].isnull() == [False, True, True] assert nulls.all(), "Some instance has data it shouldn't for column %s" % col def test_query_by_id(es): df = to_pandas(es.query_by_values('log', instance_vals=[0])) assert df['id'].values[0] == 0 def test_query_by_single_value(es): df = to_pandas(es.query_by_values('log', instance_vals=0)) assert df['id'].values[0] == 0 def test_query_by_df(es): instance_df = pd.DataFrame({'id': [1, 3], 'vals': [0, 1]}) df = to_pandas(es.query_by_values('log', instance_vals=instance_df)) assert np.array_equal(df['id'], [1, 3]) def test_query_by_id_with_time(es): df = es.query_by_values( dataframe_name='log', instance_vals=[0, 1, 2, 3, 4], time_last=datetime(2011, 4, 9, 10, 30, 2 * 6)) df = to_pandas(df) if es.dataframe_type == Library.KOALAS.value: # Koalas doesn't maintain order df = df.sort_values('id') assert list(df['id'].values) == [0, 1, 2] def test_query_by_column_with_time(es): df = es.query_by_values( dataframe_name='log', instance_vals=[0, 1, 2], column_name='session_id', time_last=datetime(2011, 4, 9, 10, 50, 0)) df = to_pandas(df) true_values = [ i * 5 for i in range(5)] + [i * 1 for i in range(4)] + [0] if es.dataframe_type == Library.KOALAS.value: # Koalas doesn't maintain order df = df.sort_values('id') assert list(df['id'].values) == list(range(10)) assert list(df['value'].values) == true_values def test_query_by_column_with_no_lti_and_training_window(es): match = "Using training_window but last_time_index is not set for dataframe customers" with pytest.warns(UserWarning, match=match): df = es.query_by_values( dataframe_name='customers', instance_vals=[0, 1, 2], column_name='cohort', time_last=datetime(2011, 4, 11), training_window='3d') df = to_pandas(df) assert list(df['id'].values) == [1] assert list(df['age'].values) == [25] def test_query_by_column_with_lti_and_training_window(es): es.add_last_time_indexes() df = es.query_by_values( dataframe_name='customers', instance_vals=[0, 1, 2], column_name='cohort', time_last=datetime(2011, 4, 11), training_window='3d') # Account for different ordering between pandas and dask/koalas df = to_pandas(df).reset_index(drop=True).sort_values('id') assert list(df['id'].values) == [0, 1, 2] assert list(df['age'].values) == [33, 25, 56] def test_query_by_indexed_column(es): df = es.query_by_values( dataframe_name='log', instance_vals=['taco clock'], column_name='product_id') df = to_pandas(df) assert list(df['id'].values) == [15, 16] @pytest.fixture def pd_df(): return pd.DataFrame({'id': [0, 1, 2], 'category': ['a', 'b', 'c']}) @pytest.fixture def dd_df(pd_df): return dd.from_pandas(pd_df, npartitions=2) @pytest.fixture def ks_df(pd_df): ks = pytest.importorskip('databricks.koalas', reason="Koalas not installed, skipping") return ks.from_pandas(pd_df) @pytest.fixture(params=['pd_df', 'dd_df', 'ks_df']) def df(request): return request.getfixturevalue(request.param) def test_check_columns_and_dataframe(df): # matches logical_types = {'id': Integer, 'category': Categorical} es = EntitySet(id='test') es.add_dataframe(df, dataframe_name='test_dataframe', index='id', logical_types=logical_types) assert isinstance(es.dataframe_dict['test_dataframe'].ww.logical_types['category'], Categorical) assert es.dataframe_dict['test_dataframe'].ww.semantic_tags['category'] == {'category'} def test_make_index_any_location(df): logical_types = {'id': Integer, 'category': Categorical} es = EntitySet(id='test') es.add_dataframe(dataframe_name='test_dataframe', index='id1', make_index=True, logical_types=logical_types, dataframe=df) if es.dataframe_type != Library.PANDAS.value: assert es.dataframe_dict['test_dataframe'].columns[-1] == 'id1' else: assert es.dataframe_dict['test_dataframe'].columns[0] == 'id1' assert es.dataframe_dict['test_dataframe'].ww.index == 'id1' def test_replace_dataframe_and_create_index(es): df = pd.DataFrame({'ints': [3, 4, 5], 'category': ['a', 'b', 'a']}) if es.dataframe_type == Library.DASK.value: df = dd.from_pandas(df, npartitions=2) elif es.dataframe_type == Library.KOALAS.value: df = ks.from_pandas(df) needs_idx_df = df.copy() logical_types = {'ints': Integer, 'category': Categorical} es.add_dataframe(dataframe=df, dataframe_name='test_df', index='id', make_index=True, logical_types=logical_types) assert es['test_df'].ww.index == 'id' # DataFrame that needs the index column added assert 'id' not in needs_idx_df.columns expected_idx_col = [0, 1, 2] es.replace_dataframe('test_df', needs_idx_df) assert es['test_df'].ww.index == 'id' assert all(expected_idx_col == to_pandas(es['test_df']['id'])) def test_replace_dataframe_created_index_present(es): df = pd.DataFrame({'ints': [3, 4, 5], 'category': ['a', 'b', 'a']}) if es.dataframe_type == Library.DASK.value: df = dd.from_pandas(df, npartitions=2) elif es.dataframe_type == Library.KOALAS.value: df = ks.from_pandas(df) logical_types = {'ints': Integer, 'category': Categorical} es.add_dataframe(dataframe=df, dataframe_name='test_df', index='id', make_index=True, logical_types=logical_types) # DataFrame that already has the index column has_idx_df = es['test_df'].replace({0: 100}) if es.dataframe_type == Library.PANDAS.value: has_idx_df.set_index('id', drop=False, inplace=True) assert 'id' in has_idx_df.columns original_idx_col = [100, 1, 2] es.replace_dataframe('test_df', has_idx_df) assert es['test_df'].ww.index == 'id' assert all(original_idx_col == to_pandas(es['test_df']['id'])) def test_index_any_location(df): logical_types = {'id': Integer, 'category': Categorical} es = EntitySet(id='test') es.add_dataframe(dataframe_name='test_dataframe', index='category', logical_types=logical_types, dataframe=df) assert es.dataframe_dict['test_dataframe'].columns[1] == 'category' assert es.dataframe_dict['test_dataframe'].ww.index == 'category' def test_extra_column_type(df): # more columns logical_types = {'id': Integer, 'category': Categorical, 'category2': Categorical} error_text = re.escape("logical_types contains columns that are not present in dataframe: ['category2']") with pytest.raises(LookupError, match=error_text): es = EntitySet(id='test') es.add_dataframe(dataframe_name='test_dataframe', index='id', logical_types=logical_types, dataframe=df) def test_add_parent_not_index_column(es): error_text = "Parent column 'language' is not the index of dataframe régions" with pytest.raises(AttributeError, match=error_text): es.add_relationship(u'régions', 'language', 'customers', u'région_id') @pytest.fixture def pd_df2(): return pd.DataFrame({'category': [1, 2, 3], 'category2': ['1', '2', '3']}) @pytest.fixture def dd_df2(pd_df2): return dd.from_pandas(pd_df2, npartitions=2) @pytest.fixture def ks_df2(pd_df2): ks = pytest.importorskip('databricks.koalas', reason="Koalas not installed, skipping") return ks.from_pandas(pd_df2) @pytest.fixture(params=['pd_df2', 'dd_df2', 'ks_df2']) def df2(request): return request.getfixturevalue(request.param) def test_none_index(df2): es = EntitySet(id='test') copy_df = df2.copy() copy_df.ww.init(name='test_dataframe') error_msg = 'Cannot add Woodwork DataFrame to EntitySet without index' with pytest.raises(ValueError, match=error_msg): es.add_dataframe(dataframe=copy_df) warn_text = "Using first column as index. To change this, specify the index parameter" with pytest.warns(UserWarning, match=warn_text): es.add_dataframe(dataframe_name='test_dataframe', logical_types={'category': 'Categorical'}, dataframe=df2) assert es['test_dataframe'].ww.index == 'category' assert es['test_dataframe'].ww.semantic_tags['category'] == {'index'} assert isinstance(es['test_dataframe'].ww.logical_types['category'], Categorical) @pytest.fixture def pd_df3(): return pd.DataFrame({'category': [1, 2, 3]}) @pytest.fixture def dd_df3(pd_df3): return dd.from_pandas(pd_df3, npartitions=2) @pytest.fixture def ks_df3(pd_df3): ks = pytest.importorskip('databricks.koalas', reason="Koalas not installed, skipping") return ks.from_pandas(pd_df3) @pytest.fixture(params=['pd_df3', 'dd_df3', 'ks_df3']) def df3(request): return request.getfixturevalue(request.param) def test_unknown_index(df3): warn_text = "index id not found in dataframe, creating new integer column" es = EntitySet(id='test') with pytest.warns(UserWarning, match=warn_text): es.add_dataframe(dataframe_name='test_dataframe', dataframe=df3, index='id', logical_types={'category': 'Categorical'}) assert es['test_dataframe'].ww.index == 'id' assert list(to_pandas(es['test_dataframe']['id'], sort_index=True)) == list(range(3)) def test_doesnt_remake_index(df): logical_types = {'id': 'Integer', 'category': 'Categorical'} error_text = "Cannot make index: column with name id already present" with pytest.raises(RuntimeError, match=error_text): es = EntitySet(id='test') es.add_dataframe(dataframe_name='test_dataframe', index='id', make_index=True, dataframe=df, logical_types=logical_types) def test_bad_time_index_column(df3): logical_types = {'category': 'Categorical'} error_text = "Specified time index column `time` not found in dataframe" with pytest.raises(LookupError, match=error_text): es = EntitySet(id='test') es.add_dataframe(dataframe_name='test_dataframe', dataframe=df3, time_index='time', logical_types=logical_types) @pytest.fixture def pd_df4(): df = pd.DataFrame({'id': [0, 1, 2], 'category': ['a', 'b', 'a'], 'category_int': [1, 2, 3], 'ints': ['1', '2', '3'], 'floats': ['1', '2', '3.0']}) df["category_int"] = df["category_int"].astype("category") return df @pytest.fixture def dd_df4(pd_df4): return dd.from_pandas(pd_df4, npartitions=2) @pytest.fixture def ks_df4(pd_df4): ks = pytest.importorskip('databricks.koalas', reason="Koalas not installed, skipping") return ks.from_pandas(pd_to_ks_clean(pd_df4)) @pytest.fixture(params=['pd_df4', 'dd_df4', 'ks_df4']) def df4(request): return request.getfixturevalue(request.param) def test_converts_dtype_on_init(df4): logical_types = {'id': Integer, 'ints': Integer, 'floats': Double} if not isinstance(df4, pd.DataFrame): logical_types['category'] = Categorical logical_types['category_int'] = Categorical es = EntitySet(id='test') df4.ww.init(name='test_dataframe', index='id', logical_types=logical_types) es.add_dataframe(dataframe=df4) df = es['test_dataframe'] assert df['ints'].dtype.name == 'int64' assert df['floats'].dtype.name == 'float64' # this is infer from pandas dtype df = es["test_dataframe"] assert isinstance(df.ww.logical_types['category_int'], Categorical) def test_converts_dtype_after_init(df4): category_dtype = 'category' if ks and isinstance(df4, ks.DataFrame): category_dtype = 'string' df4["category"] = df4["category"].astype(category_dtype) if not isinstance(df4, pd.DataFrame): logical_types = {'id': Integer, 'category': Categorical, 'category_int': Categorical, 'ints': Integer, 'floats': Double} else: logical_types = None es = EntitySet(id='test') es.add_dataframe(dataframe_name='test_dataframe', index='id', dataframe=df4, logical_types=logical_types) df = es['test_dataframe'] df.ww.set_types(logical_types={'ints': 'Integer'}) assert isinstance(df.ww.logical_types['ints'], Integer) assert df['ints'].dtype == 'int64' df.ww.set_types(logical_types={'ints': 'Categorical'}) assert isinstance(df.ww.logical_types['ints'], Categorical) assert df['ints'].dtype == category_dtype df.ww.set_types(logical_types={'ints': Ordinal(order=[1, 2, 3])}) assert df.ww.logical_types['ints'] == Ordinal(order=[1, 2, 3]) assert df['ints'].dtype == category_dtype df.ww.set_types(logical_types={'ints': 'NaturalLanguage'}) assert isinstance(df.ww.logical_types['ints'], NaturalLanguage) assert df['ints'].dtype == 'string' def test_warns_no_typing(df4): es = EntitySet(id='test') if not isinstance(df4, pd.DataFrame): msg = 'Performing type inference on Dask or Koalas DataFrames may be computationally intensive. Specify logical types for each column to speed up EntitySet initialization.' with pytest.warns(UserWarning, match=msg): es.add_dataframe(dataframe_name='test_dataframe', index='id', dataframe=df4) else: es.add_dataframe(dataframe_name='test_dataframe', index='id', dataframe=df4) assert 'test_dataframe' in es.dataframe_dict @pytest.fixture def pd_datetime1(): times = pd.date_range('1/1/2011', periods=3, freq='H') time_strs = times.strftime('%Y-%m-%d') return pd.DataFrame({'id': [0, 1, 2], 'time': time_strs}) @pytest.fixture def dd_datetime1(pd_datetime1): return dd.from_pandas(pd_datetime1, npartitions=2) @pytest.fixture def ks_datetime1(pd_datetime1): ks = pytest.importorskip('databricks.koalas', reason="Koalas not installed, skipping") return ks.from_pandas(pd_datetime1) @pytest.fixture(params=['pd_datetime1', 'dd_datetime1', 'ks_datetime1']) def datetime1(request): return request.getfixturevalue(request.param) def test_converts_datetime(datetime1): # string converts to datetime correctly # This test fails without defining logical types. # Entityset infers time column should be numeric type logical_types = {'id': Integer, 'time': Datetime} es = EntitySet(id='test') es.add_dataframe( dataframe_name='test_dataframe', index='id', time_index="time", logical_types=logical_types, dataframe=datetime1) pd_col = to_pandas(es['test_dataframe']['time']) assert isinstance(es['test_dataframe'].ww.logical_types['time'], Datetime) assert type(pd_col[0]) == pd.Timestamp @pytest.fixture def pd_datetime2(): datetime_format = "%d-%m-%Y" actual = pd.Timestamp('Jan 2, 2011') time_strs = [actual.strftime(datetime_format)] * 3 return pd.DataFrame( {'id': [0, 1, 2], 'time_format': time_strs, 'time_no_format': time_strs}) @pytest.fixture def dd_datetime2(pd_datetime2): return dd.from_pandas(pd_datetime2, npartitions=2) @pytest.fixture def ks_datetime2(pd_datetime2): ks = pytest.importorskip('databricks.koalas', reason="Koalas not installed, skipping") return ks.from_pandas(pd_datetime2) @pytest.fixture(params=['pd_datetime2', 'dd_datetime2', 'ks_datetime2']) def datetime2(request): return request.getfixturevalue(request.param) def test_handles_datetime_format(datetime2): # check if we load according to the format string # pass in an ambiguous date datetime_format = "%d-%m-%Y" actual = pd.Timestamp('Jan 2, 2011') logical_types = {'id': Integer, 'time_format': (Datetime(datetime_format=datetime_format)), 'time_no_format': Datetime} es = EntitySet(id='test') es.add_dataframe( dataframe_name='test_dataframe', index='id', logical_types=logical_types, dataframe=datetime2) col_format = to_pandas(es['test_dataframe']['time_format']) col_no_format = to_pandas(es['test_dataframe']['time_no_format']) # without formatting pandas gets it wrong assert (col_no_format != actual).all() # with formatting we correctly get jan2 assert (col_format == actual).all() def test_handles_datetime_mismatch(): # can't convert arbitrary strings df = pd.DataFrame({'id': [0, 1, 2], 'time': ['a', 'b', 'tomorrow']}) logical_types = {'id': Integer, 'time': Datetime} error_text = "Time index column must contain datetime or numeric values" with pytest.raises(TypeError, match=error_text): es = EntitySet(id='test') es.add_dataframe(df, dataframe_name='test_dataframe', index='id', time_index='time', logical_types=logical_types) def test_dataframe_init(es): df = pd.DataFrame({'id': ['0', '1', '2'], 'time': [datetime(2011, 4, 9, 10, 31, 3 * i) for i in range(3)], 'category': ['a', 'b', 'a'], 'number': [4, 5, 6]}) if es.dataframe_type == Library.DASK.value: df = dd.from_pandas(df, npartitions=2) elif es.dataframe_type == Library.KOALAS.value: df = ks.from_pandas(df) logical_types = {'time': Datetime} if not isinstance(df, pd.DataFrame): extra_logical_types = { 'id': Categorical, 'category': Categorical, 'number': Integer } logical_types.update(extra_logical_types) es.add_dataframe(df.copy(), dataframe_name='test_dataframe', index='id', time_index='time', logical_types=logical_types) if isinstance(df, dd.DataFrame): df_shape = (df.shape[0].compute(), df.shape[1]) else: df_shape = df.shape if es.dataframe_type == Library.DASK.value: es_df_shape = (es['test_dataframe'].shape[0].compute(), es['test_dataframe'].shape[1]) else: es_df_shape = es['test_dataframe'].shape assert es_df_shape == df_shape assert es['test_dataframe'].ww.index == 'id' assert es['test_dataframe'].ww.time_index == 'time' assert set([v for v in es['test_dataframe'].ww.columns]) == set(df.columns) assert es['test_dataframe']['time'].dtype == df['time'].dtype if es.dataframe_type == Library.KOALAS.value: assert set(es['test_dataframe']['id'].to_list()) == set(df['id'].to_list()) else: assert set(es['test_dataframe']['id']) == set(df['id']) @pytest.fixture def pd_bad_df(): return pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 3: ['a', 'b', 'c']}) @pytest.fixture def dd_bad_df(pd_bad_df): return dd.from_pandas(pd_bad_df, npartitions=2) @pytest.fixture(params=['pd_bad_df', 'dd_bad_df']) def bad_df(request): return request.getfixturevalue(request.param) # Skip for Koalas, automatically converts non-str column names to str def test_nonstr_column_names(bad_df): if isinstance(bad_df, dd.DataFrame): pytest.xfail('Dask DataFrames cannot handle integer column names') es = ft.EntitySet(id='Failure') error_text = r"All column names must be strings \(Columns \[3\] are not strings\)" with pytest.raises(ValueError, match=error_text): es.add_dataframe(dataframe_name='str_cols', dataframe=bad_df, index='a') bad_df.ww.init() with pytest.raises(ValueError, match=error_text): es.add_dataframe(dataframe_name='str_cols', dataframe=bad_df) def test_sort_time_id(): transactions_df = pd.DataFrame({"id": [1, 2, 3, 4, 5, 6], "transaction_time": pd.date_range(start="10:00", periods=6, freq="10s")[::-1]}) es = EntitySet("test", dataframes={"t": (transactions_df.copy(), "id", "transaction_time")}) assert es['t'] is not transactions_df times = list(es["t"].transaction_time) assert times == sorted(list(transactions_df.transaction_time)) def test_already_sorted_parameter(): transactions_df = pd.DataFrame({"id": [1, 2, 3, 4, 5, 6], "transaction_time": [datetime(2014, 4, 6), datetime( 2012, 4, 8), datetime( 2012, 4, 8), datetime( 2013, 4, 8), datetime( 2015, 4, 8), datetime(2016, 4, 9)]}) es = EntitySet(id='test') es.add_dataframe(transactions_df.copy(), dataframe_name='t', index='id', time_index="transaction_time", already_sorted=True) assert es['t'] is not transactions_df times = list(es["t"].transaction_time) assert times == list(transactions_df.transaction_time) def test_concat_not_inplace(es): first_es = copy.deepcopy(es) for df in first_es.dataframes: new_df = df.loc[[], :] first_es.replace_dataframe(df.ww.name, new_df) second_es = copy.deepcopy(es) # set the data description first_es.metadata new_es = first_es.concat(second_es) assert new_es == es assert new_es._data_description is None assert first_es._data_description is not None def test_concat_inplace(es): first_es = copy.deepcopy(es) second_es = copy.deepcopy(es) for df in first_es.dataframes: new_df = df.loc[[], :] first_es.replace_dataframe(df.ww.name, new_df) # set the data description es.metadata es.concat(first_es, inplace=True) assert second_es == es assert es._data_description is None def test_concat_with_lti(es): first_es = copy.deepcopy(es) for df in first_es.dataframes: if first_es.dataframe_type == Library.KOALAS.value: # Koalas cannot compute last time indexes on an empty Dataframe new_df = df.head(1) else: new_df = df.loc[[], :] first_es.replace_dataframe(df.ww.name, new_df) second_es = copy.deepcopy(es) first_es.add_last_time_indexes() second_es.add_last_time_indexes() es.add_last_time_indexes() new_es = first_es.concat(second_es) assert new_es == es first_es['stores'].ww.pop(LTI_COLUMN_NAME) first_es['stores'].ww.metadata.pop('last_time_index') second_es['stores'].ww.pop(LTI_COLUMN_NAME) second_es['stores'].ww.metadata.pop('last_time_index') assert not first_es.__eq__(es, deep=False) assert not second_es.__eq__(es, deep=False) assert LTI_COLUMN_NAME not in first_es['stores'] assert LTI_COLUMN_NAME not in second_es['stores'] new_es = first_es.concat(second_es) assert new_es.__eq__(es, deep=True) # stores will get last time index re-added because it has children that will get lti calculated assert LTI_COLUMN_NAME in new_es['stores'] def test_concat_errors(es): # entitysets are not equal copy_es = copy.deepcopy(es) copy_es['customers'].ww.pop('phone_number') error = "Entitysets must have the same dataframes, relationships"\ ", and column names" with pytest.raises(ValueError, match=error): es.concat(copy_es) def test_concat_sort_index_with_time_index(pd_es): # only pandas dataframes sort on the index and time index es1 = copy.deepcopy(pd_es) es1.replace_dataframe(dataframe_name='customers', df=pd_es['customers'].loc[[0, 1], :], already_sorted=True) es2 = copy.deepcopy(pd_es) es2.replace_dataframe(dataframe_name='customers', df=pd_es['customers'].loc[[2], :], already_sorted=True) combined_es_order_1 = es1.concat(es2) combined_es_order_2 = es2.concat(es1) assert list(combined_es_order_1['customers'].index) == [2, 0, 1] assert list(combined_es_order_2['customers'].index) == [2, 0, 1] assert combined_es_order_1.__eq__(pd_es, deep=True) assert combined_es_order_2.__eq__(pd_es, deep=True) assert combined_es_order_2.__eq__(combined_es_order_1, deep=True) def test_concat_sort_index_without_time_index(pd_es): # Sorting is only performed on DataFrames with time indices es1 = copy.deepcopy(pd_es) es1.replace_dataframe(dataframe_name='products', df=pd_es['products'].iloc[[0, 1, 2], :], already_sorted=True) es2 = copy.deepcopy(pd_es) es2.replace_dataframe(dataframe_name='products', df=pd_es['products'].iloc[[3, 4, 5], :], already_sorted=True) combined_es_order_1 = es1.concat(es2) combined_es_order_2 = es2.concat(es1) # order matters when we don't sort assert list(combined_es_order_1['products'].index) == ['Haribo sugar-free gummy bears', 'car', 'toothpaste', 'brown bag', 'coke zero', 'taco clock'] assert list(combined_es_order_2['products'].index) == ['brown bag', 'coke zero', 'taco clock', 'Haribo sugar-free gummy bears', 'car', 'toothpaste' ] assert combined_es_order_1.__eq__(pd_es, deep=True) assert not combined_es_order_2.__eq__(pd_es, deep=True) assert combined_es_order_2.__eq__(pd_es, deep=False) assert not combined_es_order_2.__eq__(combined_es_order_1, deep=True) def test_concat_with_make_index(es): df = pd.DataFrame({'id': [0, 1, 2], 'category': ['a', 'b', 'a']}) if es.dataframe_type == Library.DASK.value: df = dd.from_pandas(df, npartitions=2) elif es.dataframe_type == Library.KOALAS.value: df = ks.from_pandas(df) logical_types = {'id': Categorical, 'category': Categorical} es.add_dataframe(dataframe=df, dataframe_name='test_df', index='id1', make_index=True, logical_types=logical_types) es_1 = copy.deepcopy(es) es_2 = copy.deepcopy(es) assert es.__eq__(es_1, deep=True) assert es.__eq__(es_2, deep=True) # map of what rows to take from es_1 and es_2 for each dataframe emap = { 'log': [list(range(10)) + [14, 15, 16], list(range(10, 14)) + [15, 16]], 'sessions': [[0, 1, 2], [1, 3, 4, 5]], 'customers': [[0, 2], [1, 2]], 'test_df': [[0, 1], [0, 2]], } for i, _es in enumerate([es_1, es_2]): for df_name, rows in emap.items(): df = _es[df_name] _es.replace_dataframe(dataframe_name=df_name, df=df.loc[rows[i]]) assert es.__eq__(es_1, deep=False) assert es.__eq__(es_2, deep=False) if es.dataframe_type == Library.PANDAS.value: assert not es.__eq__(es_1, deep=True) assert not es.__eq__(es_2, deep=True) old_es_1 = copy.deepcopy(es_1) old_es_2 = copy.deepcopy(es_2) es_3 = es_1.concat(es_2) assert old_es_1.__eq__(es_1, deep=True) assert old_es_2.__eq__(es_2, deep=True) assert es_3.__eq__(es, deep=True) @pytest.fixture def pd_transactions_df(): return pd.DataFrame({"id": [1, 2, 3, 4, 5, 6], "card_id": [1, 2, 1, 3, 4, 5], "transaction_time": [10, 12, 13, 20, 21, 20], "fraud": [True, False, False, False, True, True]}) @pytest.fixture def dd_transactions_df(pd_transactions_df): return dd.from_pandas(pd_transactions_df, npartitions=3) @pytest.fixture def ks_transactions_df(pd_transactions_df): ks = pytest.importorskip('databricks.koalas', reason="Koalas not installed, skipping") return ks.from_pandas(pd_transactions_df) @pytest.fixture(params=['pd_transactions_df', 'dd_transactions_df', 'ks_transactions_df']) def transactions_df(request): return request.getfixturevalue(request.param) def test_set_time_type_on_init(transactions_df): # create cards dataframe cards_df = pd.DataFrame({"id": [1, 2, 3, 4, 5]}) if isinstance(transactions_df, dd.DataFrame): cards_df = dd.from_pandas(cards_df, npartitions=3) if ks and isinstance(transactions_df, ks.DataFrame): cards_df = ks.from_pandas(cards_df) if not isinstance(transactions_df, pd.DataFrame): cards_logical_types = {'id': Categorical} transactions_logical_types = { 'id': Integer, 'card_id': Categorical, 'transaction_time': Integer, 'fraud': Boolean } else: cards_logical_types = None transactions_logical_types = None dataframes = { "cards": (cards_df, "id", None, cards_logical_types), "transactions": (transactions_df, "id", "transaction_time", transactions_logical_types) } relationships = [("cards", "id", "transactions", "card_id")] es = EntitySet("fraud", dataframes, relationships) # assert time_type is set assert es.time_type == 'numeric' def test_sets_time_when_adding_dataframe(transactions_df): accounts_df = pd.DataFrame({"id": [3, 4, 5], "signup_date": [datetime(2002, 5, 1), datetime(2006, 3, 20), datetime(2011, 11, 11)]}) accounts_df_string = pd.DataFrame({"id": [3, 4, 5], "signup_date": ["element", "exporting", "editable"]}) if isinstance(transactions_df, dd.DataFrame): accounts_df = dd.from_pandas(accounts_df, npartitions=2) if ks and isinstance(transactions_df, ks.DataFrame): accounts_df = ks.from_pandas(accounts_df) if not isinstance(transactions_df, pd.DataFrame): accounts_logical_types = {'id': Categorical, 'signup_date': Datetime} transactions_logical_types = { 'id': Integer, 'card_id': Categorical, 'transaction_time': Integer, 'fraud': Boolean } else: accounts_logical_types = None transactions_logical_types = None # create empty entityset es = EntitySet("fraud") # assert it's not set assert getattr(es, "time_type", None) is None # add dataframe es.add_dataframe(transactions_df, dataframe_name="transactions", index="id", time_index="transaction_time", logical_types=transactions_logical_types) # assert time_type is set assert es.time_type == 'numeric' # add another dataframe es.normalize_dataframe("transactions", "cards", "card_id", make_time_index=True) # assert time_type unchanged assert es.time_type == 'numeric' # add wrong time type dataframe error_text = "accounts time index is Datetime type which differs from other entityset time indexes" with pytest.raises(TypeError, match=error_text): es.add_dataframe(accounts_df, dataframe_name="accounts", index="id", time_index="signup_date", logical_types=accounts_logical_types) # add non time type as time index, only valid for pandas if isinstance(transactions_df, pd.DataFrame): error_text = "Time index column must contain datetime or numeric values" with pytest.raises(TypeError, match=error_text): es.add_dataframe(accounts_df_string, dataframe_name="accounts", index="id", time_index="signup_date") def test_secondary_time_index_no_primary_time_index(es): es['products'].ww.set_types(logical_types={'rating': 'Datetime'}) assert es['products'].ww.time_index is None error = 'Cannot set secondary time index on a DataFrame that has no primary time index.' with pytest.raises(ValueError, match=error): es.set_secondary_time_index('products', {'rating': ['url']}) assert 'secondary_time_index' not in es['products'].ww.metadata assert es['products'].ww.time_index is None def test_set_non_valid_time_index_type(es): error_text = 'Time index column must be a Datetime or numeric column.' with pytest.raises(TypeError, match=error_text): es['log'].ww.set_time_index('purchased') def test_checks_time_type_setting_secondary_time_index(es): # entityset is timestamp time type assert es.time_type == Datetime # add secondary index that is timestamp type new_2nd_ti = {'upgrade_date': ['upgrade_date', 'favorite_quote'], 'cancel_date': ['cancel_date', 'cancel_reason']} es.set_secondary_time_index("customers", new_2nd_ti) assert es.time_type == Datetime # add secondary index that is numeric type new_2nd_ti = {'age': ['age', 'loves_ice_cream']} error_text = "customers time index is numeric type which differs from other entityset time indexes" with pytest.raises(TypeError, match=error_text): es.set_secondary_time_index("customers", new_2nd_ti) # add secondary index that is non-time type new_2nd_ti = {'favorite_quote': ['favorite_quote', 'loves_ice_cream']} error_text = 'customers time index not recognized as numeric or datetime' with pytest.raises(TypeError, match=error_text): es.set_secondary_time_index("customers", new_2nd_ti) # add mismatched pair of secondary time indexes new_2nd_ti = {'upgrade_date': ['upgrade_date', 'favorite_quote'], 'age': ['age', 'loves_ice_cream']} error_text = "customers time index is numeric type which differs from other entityset time indexes" with pytest.raises(TypeError, match=error_text): es.set_secondary_time_index("customers", new_2nd_ti) # create entityset with numeric time type cards_df = pd.DataFrame({"id": [1, 2, 3, 4, 5]}) transactions_df = pd.DataFrame({ "id": [1, 2, 3, 4, 5, 6], "card_id": [1, 2, 1, 3, 4, 5], "transaction_time": [10, 12, 13, 20, 21, 20], "fraud_decision_time": [11, 14, 15, 21, 22, 21], "transaction_city": ["City A"] * 6, "transaction_date": [datetime(1989, 2, i) for i in range(1, 7)], "fraud": [True, False, False, False, True, True] }) dataframes = { "cards": (cards_df, "id"), "transactions": (transactions_df, "id", "transaction_time") } relationships = [("cards", "id", "transactions", "card_id")] card_es = EntitySet("fraud", dataframes, relationships) assert card_es.time_type == 'numeric' # add secondary index that is numeric time type new_2nd_ti = {'fraud_decision_time': ['fraud_decision_time', 'fraud']} card_es.set_secondary_time_index("transactions", new_2nd_ti) assert card_es.time_type == 'numeric' # add secondary index that is timestamp type new_2nd_ti = {'transaction_date': ['transaction_date', 'fraud']} error_text = "transactions time index is Datetime type which differs from other entityset time indexes" with pytest.raises(TypeError, match=error_text): card_es.set_secondary_time_index("transactions", new_2nd_ti) # add secondary index that is non-time type new_2nd_ti = {'transaction_city': ['transaction_city', 'fraud']} error_text = 'transactions time index not recognized as numeric or datetime' with pytest.raises(TypeError, match=error_text): card_es.set_secondary_time_index("transactions", new_2nd_ti) # add mixed secondary time indexes new_2nd_ti = {'transaction_city': ['transaction_city', 'fraud'], 'fraud_decision_time': ['fraud_decision_time', 'fraud']} with pytest.raises(TypeError, match=error_text): card_es.set_secondary_time_index("transactions", new_2nd_ti) # add bool secondary time index error_text = 'transactions time index not recognized as numeric or datetime' with pytest.raises(TypeError, match=error_text): card_es.set_secondary_time_index("transactions", {'fraud': ['fraud']}) def test_normalize_dataframe(es): error_text = "'additional_columns' must be a list, but received type.*" with pytest.raises(TypeError, match=error_text): es.normalize_dataframe('sessions', 'device_types', 'device_type', additional_columns='log') error_text = "'copy_columns' must be a list, but received type.*" with pytest.raises(TypeError, match=error_text): es.normalize_dataframe('sessions', 'device_types', 'device_type', copy_columns='log') es.normalize_dataframe('sessions', 'device_types', 'device_type', additional_columns=['device_name'], make_time_index=False) assert len(es.get_forward_relationships('sessions')) == 2 assert es.get_forward_relationships( 'sessions')[1].parent_dataframe.ww.name == 'device_types' assert 'device_name' in es['device_types'].columns assert 'device_name' not in es['sessions'].columns assert 'device_type' in es['device_types'].columns def test_normalize_dataframe_add_index_as_column(es): error_text = "Not adding device_type as both index and column in additional_columns" with pytest.raises(ValueError, match=error_text): es.normalize_dataframe('sessions', 'device_types', 'device_type', additional_columns=['device_name', 'device_type'], make_time_index=False) error_text = "Not adding device_type as both index and column in copy_columns" with pytest.raises(ValueError, match=error_text): es.normalize_dataframe('sessions', 'device_types', 'device_type', copy_columns=['device_name', 'device_type'], make_time_index=False) def test_normalize_dataframe_new_time_index_in_base_dataframe_error_check(es): error_text = "'make_time_index' must be a column in the base dataframe" with pytest.raises(ValueError, match=error_text): es.normalize_dataframe(base_dataframe_name='customers', new_dataframe_name='cancellations', index='cancel_reason', make_time_index="non-existent") def test_normalize_dataframe_new_time_index_in_column_list_error_check(es): error_text = "'make_time_index' must be specified in 'additional_columns' or 'copy_columns'" with pytest.raises(ValueError, match=error_text): es.normalize_dataframe(base_dataframe_name='customers', new_dataframe_name='cancellations', index='cancel_reason', make_time_index='cancel_date') def test_normalize_dataframe_new_time_index_copy_success_check(es): es.normalize_dataframe(base_dataframe_name='customers', new_dataframe_name='cancellations', index='cancel_reason', make_time_index='cancel_date', additional_columns=[], copy_columns=['cancel_date']) def test_normalize_dataframe_new_time_index_additional_success_check(es): es.normalize_dataframe(base_dataframe_name='customers', new_dataframe_name='cancellations', index='cancel_reason', make_time_index='cancel_date', additional_columns=['cancel_date'], copy_columns=[]) @pytest.fixture def pd_normalize_es(): df = pd.DataFrame({ "id": [0, 1, 2, 3], "A": [5, 4, 2, 3], 'time': [datetime(2020, 6, 3), (datetime(2020, 3, 12)), datetime(2020, 5, 1), datetime(2020, 4, 22)] }) es = ft.EntitySet("es") return es.add_dataframe( dataframe_name="data", dataframe=df, index="id") @pytest.fixture def dd_normalize_es(pd_normalize_es): es = ft.EntitySet(id=pd_normalize_es.id) dd_df = dd.from_pandas(pd_normalize_es['data'], npartitions=2) dd_df.ww.init(schema=pd_normalize_es['data'].ww.schema) es.add_dataframe(dataframe=dd_df) return es @pytest.fixture def ks_normalize_es(pd_normalize_es): ks = pytest.importorskip('databricks.koalas', reason="Koalas not installed, skipping") es = ft.EntitySet(id=pd_normalize_es.id) ks_df = ks.from_pandas(pd_normalize_es['data']) ks_df.ww.init(schema=pd_normalize_es['data'].ww.schema) es.add_dataframe(dataframe=ks_df) return es @pytest.fixture(params=['pd_normalize_es', 'dd_normalize_es', 'ks_normalize_es']) def normalize_es(request): return request.getfixturevalue(request.param) def test_normalize_time_index_from_none(normalize_es): assert normalize_es['data'].ww.time_index is None normalize_es.normalize_dataframe(base_dataframe_name='data', new_dataframe_name='normalized', index='A', make_time_index='time', copy_columns=['time']) assert normalize_es['normalized'].ww.time_index == 'time' df = normalize_es['normalized'] # only pandas sorts by time index if isinstance(df, pd.DataFrame): assert df['time'].is_monotonic_increasing def test_raise_error_if_dupicate_additional_columns_passed(es): error_text = "'additional_columns' contains duplicate columns. All columns must be unique." with pytest.raises(ValueError, match=error_text): es.normalize_dataframe('sessions', 'device_types', 'device_type', additional_columns=['device_name', 'device_name']) def test_raise_error_if_dupicate_copy_columns_passed(es): error_text = "'copy_columns' contains duplicate columns. All columns must be unique." with pytest.raises(ValueError, match=error_text): es.normalize_dataframe('sessions', 'device_types', 'device_type', copy_columns=['device_name', 'device_name']) def test_normalize_dataframe_copies_logical_types(es): es['log'].ww.set_types(logical_types={'value': Ordinal(order=[0.0, 1.0, 2.0, 3.0, 5.0, 7.0, 10.0, 14.0, 15.0, 20.0])}) assert isinstance(es['log'].ww.logical_types['value'], Ordinal) assert len(es['log'].ww.logical_types['value'].order) == 10 assert isinstance(es['log'].ww.logical_types['priority_level'], Ordinal) assert len(es['log'].ww.logical_types['priority_level'].order) == 3 es.normalize_dataframe('log', 'values_2', 'value_2', additional_columns=['priority_level'], copy_columns=['value'], make_time_index=False) assert len(es.get_forward_relationships('log')) == 3 assert es.get_forward_relationships( 'log')[2].parent_dataframe.ww.name == 'values_2' assert 'priority_level' in es['values_2'].columns assert 'value' in es['values_2'].columns assert 'priority_level' not in es['log'].columns assert 'value' in es['log'].columns assert 'value_2' in es['values_2'].columns assert isinstance(es['values_2'].ww.logical_types['priority_level'], Ordinal) assert len(es['values_2'].ww.logical_types['priority_level'].order) == 3 assert isinstance(es['values_2'].ww.logical_types['value'], Ordinal) assert len(es['values_2'].ww.logical_types['value'].order) == 10 # sorting not supported in Dask, Koalas def test_make_time_index_keeps_original_sorting(): trips = { 'trip_id': [999 - i for i in range(1000)], 'flight_time': [datetime(1997, 4, 1) for i in range(1000)], 'flight_id': [1 for i in range(350)] + [2 for i in range(650)] } order = [i for i in range(1000)] df = pd.DataFrame.from_dict(trips) es = EntitySet('flights') es.add_dataframe(dataframe=df, dataframe_name="trips", index="trip_id", time_index='flight_time') assert (es['trips']['trip_id'] == order).all() es.normalize_dataframe(base_dataframe_name="trips", new_dataframe_name="flights", index="flight_id", make_time_index=True) assert (es['trips']['trip_id'] == order).all() def test_normalize_dataframe_new_time_index(es): new_time_index = 'value_time' es.normalize_dataframe('log', 'values', 'value', make_time_index=True, new_dataframe_time_index=new_time_index) assert es['values'].ww.time_index == new_time_index assert new_time_index in es['values'].columns assert len(es['values'].columns) == 2 df = to_pandas(es['values'], sort_index=True) assert df[new_time_index].is_monotonic_increasing def test_normalize_dataframe_same_index(es): transactions_df = pd.DataFrame({"id": [1, 2, 3], "transaction_time": pd.date_range(start="10:00", periods=3, freq="10s"), "first_df_time": [1, 2, 3]}) es = ft.EntitySet("example") es.add_dataframe(dataframe_name="df", index="id", time_index="transaction_time", dataframe=transactions_df) error_text = "'index' must be different from the index column of the base dataframe" with pytest.raises(ValueError, match=error_text): es.normalize_dataframe(base_dataframe_name="df", new_dataframe_name="new_dataframe", index="id", make_time_index=True) def test_secondary_time_index(es): es.normalize_dataframe('log', 'values', 'value', make_time_index=True, make_secondary_time_index={ 'datetime': ['comments']}, new_dataframe_time_index="value_time", new_dataframe_secondary_time_index='second_ti') assert isinstance(es['values'].ww.logical_types['second_ti'], Datetime) assert (es['values'].ww.semantic_tags['second_ti'] == set()) assert (es['values'].ww.metadata['secondary_time_index'] == { 'second_ti': ['comments', 'second_ti']}) def test_sizeof(es): es.add_last_time_indexes() total_size = 0 for df in es.dataframes: total_size += df.__sizeof__() assert es.__sizeof__() == total_size def test_construct_without_id(): assert ft.EntitySet().id is None def test_repr_without_id(): match = 'Entityset: None\n DataFrames:\n Relationships:\n No relationships' assert repr(ft.EntitySet()) == match def test_getitem_without_id(): error_text = 'DataFrame test does not exist in entity set' with pytest.raises(KeyError, match=error_text): ft.EntitySet()['test'] def test_metadata_without_id(): es = ft.EntitySet() assert es.metadata.id is None @pytest.fixture def pd_datetime3(): return pd.DataFrame({'id': [0, 1, 2], 'ints': ['1', '2', '1']}) @pytest.fixture def dd_datetime3(pd_datetime3): return dd.from_pandas(pd_datetime3, npartitions=2) @pytest.fixture def ks_datetime3(pd_datetime3): ks = pytest.importorskip('databricks.koalas', reason="Koalas not installed, skipping") return ks.from_pandas(pd_datetime3) @pytest.fixture(params=['pd_datetime3', 'dd_datetime3', 'ks_datetime3']) def datetime3(request): return request.getfixturevalue(request.param) def test_datetime64_conversion(datetime3): df = datetime3 df["time"] = pd.Timestamp.now() if ks and isinstance(df, ks.DataFrame): df['time'] = df['time'].astype(np.datetime64) else: df["time"] = df["time"].dt.tz_localize("UTC") if not isinstance(df, pd.DataFrame): logical_types = { 'id': Integer, 'ints': Integer, 'time': Datetime } else: logical_types = None es = EntitySet(id='test') es.add_dataframe(dataframe_name='test_dataframe', index='id', dataframe=df, logical_types=logical_types) es['test_dataframe'].ww.set_time_index('time') assert es['test_dataframe'].ww.time_index == 'time' @pytest.fixture def pd_index_df(): return pd.DataFrame({"id": [1, 2, 3, 4, 5, 6], "transaction_time": pd.date_range(start="10:00", periods=6, freq="10s"), "first_dataframe_time": [1, 2, 3, 5, 6, 6]}) @pytest.fixture def dd_index_df(pd_index_df): return dd.from_pandas(pd_index_df, npartitions=3) @pytest.fixture def ks_index_df(pd_index_df): ks = pytest.importorskip('databricks.koalas', reason="Koalas not installed, skipping") return ks.from_pandas(pd_index_df) @pytest.fixture(params=['pd_index_df', 'dd_index_df', 'ks_index_df']) def index_df(request): return request.getfixturevalue(request.param) def test_same_index_values(index_df): if not isinstance(index_df, pd.DataFrame): logical_types = { 'id': Integer, 'transaction_time': Datetime, 'first_dataframe_time': Integer } else: logical_types = None es = ft.EntitySet("example") error_text = '"id" is already set as the index. An index cannot also be the time index.' with pytest.raises(ValueError, match=error_text): es.add_dataframe(dataframe_name="dataframe", index="id", time_index="id", dataframe=index_df, logical_types=logical_types) es.add_dataframe(dataframe_name="dataframe", index="id", time_index="transaction_time", dataframe=index_df, logical_types=logical_types) error_text = "time_index and index cannot be the same value, first_dataframe_time" with pytest.raises(ValueError, match=error_text): es.normalize_dataframe(base_dataframe_name="dataframe", new_dataframe_name="new_dataframe", index="first_dataframe_time", make_time_index=True) def test_use_time_index(index_df): if not isinstance(index_df, pd.DataFrame): bad_ltypes = { 'id': Integer, 'transaction_time': Datetime, 'first_dataframe_time': Integer } bad_semantic_tags = {'transaction_time': 'time_index'} logical_types = { 'id': Integer, 'transaction_time': Datetime, 'first_dataframe_time': Integer } else: bad_ltypes = {"transaction_time": Datetime} bad_semantic_tags = {'transaction_time': 'time_index'} logical_types = None es = ft.EntitySet() error_text = re.escape("Cannot add 'time_index' tag directly for column transaction_time. To set a column as the time index, use DataFrame.ww.set_time_index() instead.") with pytest.raises(ValueError, match=error_text): es.add_dataframe(dataframe_name="dataframe", index="id", logical_types=bad_ltypes, semantic_tags=bad_semantic_tags, dataframe=index_df) es.add_dataframe(dataframe_name="dataframe", index="id", time_index="transaction_time", logical_types=logical_types, dataframe=index_df) def test_normalize_with_datetime_time_index(es): es.normalize_dataframe(base_dataframe_name="customers", new_dataframe_name="cancel_reason", index="cancel_reason", make_time_index=False, copy_columns=['signup_date', 'upgrade_date']) assert isinstance(es['cancel_reason'].ww.logical_types['signup_date'], Datetime) assert isinstance(es['cancel_reason'].ww.logical_types['upgrade_date'], Datetime) def test_normalize_with_numeric_time_index(int_es): int_es.normalize_dataframe(base_dataframe_name="customers", new_dataframe_name="cancel_reason", index="cancel_reason", make_time_index=False, copy_columns=['signup_date', 'upgrade_date']) assert int_es['cancel_reason'].ww.semantic_tags['signup_date'] == {'numeric'} def test_normalize_with_invalid_time_index(es): error_text = 'Time index column must contain datetime or numeric values' with pytest.raises(TypeError, match=error_text): es.normalize_dataframe(base_dataframe_name="customers", new_dataframe_name="cancel_reason", index="cancel_reason", copy_columns=['upgrade_date', 'favorite_quote'], make_time_index='favorite_quote') def test_entityset_init(): cards_df = pd.DataFrame({"id": [1, 2, 3, 4, 5]}) transactions_df = pd.DataFrame({"id": [1, 2, 3, 4, 5, 6], "card_id": [1, 2, 1, 3, 4, 5], "transaction_time": [10, 12, 13, 20, 21, 20], "upgrade_date": [51, 23, 45, 12, 22, 53], "fraud": [True, False, False, False, True, True]}) logical_types = { 'fraud': 'boolean', 'card_id': 'integer' } dataframes = { "cards": (cards_df.copy(), "id", None, {'id': 'Integer'}), "transactions": (transactions_df.copy(), 'id', 'transaction_time', logical_types, None, False) } relationships = [('cards', 'id', 'transactions', 'card_id')] es = ft.EntitySet(id="fraud_data", dataframes=dataframes, relationships=relationships) assert es['transactions'].ww.index == 'id' assert es['transactions'].ww.time_index == 'transaction_time' es_copy = ft.EntitySet(id="fraud_data") es_copy.add_dataframe(dataframe_name='cards', dataframe=cards_df.copy(), index='id') es_copy.add_dataframe(dataframe_name='transactions', dataframe=transactions_df.copy(), index='id', logical_types=logical_types, make_index=False, time_index='transaction_time') es_copy.add_relationship('cards', 'id', 'transactions', 'card_id') assert es['cards'].ww == es_copy['cards'].ww assert es['transactions'].ww == es_copy['transactions'].ww def test_add_interesting_values_specified_vals(es): product_vals = ['coke zero', 'taco clock'] country_vals = ['AL', 'US'] interesting_values = { 'product_id': product_vals, 'countrycode': country_vals, } es.add_interesting_values(dataframe_name='log', values=interesting_values) assert es['log'].ww['product_id'].ww.metadata['interesting_values'] == product_vals assert es['log'].ww['countrycode'].ww.metadata['interesting_values'] == country_vals def test_add_interesting_values_vals_specified_without_dataframe_name(es): interesting_values = { 'countrycode': ['AL', 'US'], } error_msg = "dataframe_name must be specified if values are provided" with pytest.raises(ValueError, match=error_msg): es.add_interesting_values(values=interesting_values) def test_add_interesting_values_single_dataframe(pd_es): pd_es.add_interesting_values(dataframe_name='log') expected_vals = { 'zipcode': ['02116', '02116-3899', '12345-6789', '1234567890', '0'], 'countrycode': ['US', 'AL', 'ALB', 'USA'], 'subregioncode': ['US-AZ', 'US-MT', 'ZM-06', 'UG-219'], 'priority_level': [0, 1, 2], } for col in pd_es['log'].columns: if col in expected_vals: assert pd_es['log'].ww.columns[col].metadata.get('interesting_values') == expected_vals[col] else: assert pd_es['log'].ww.columns[col].metadata.get('interesting_values') is None def test_add_interesting_values_multiple_dataframes(pd_es): pd_es.add_interesting_values() expected_cols_with_vals = { 'régions': {'language'}, 'stores': {}, 'products': {'department'}, 'customers': {'cancel_reason', 'engagement_level'}, 'sessions': {'device_type', 'device_name'}, 'log': {'zipcode', 'countrycode', 'subregioncode', 'priority_level'}, 'cohorts': {'cohort_name'}, } for df_id, df in pd_es.dataframe_dict.items(): expected_cols = expected_cols_with_vals[df_id] for col in df.columns: if col in expected_cols: assert df.ww.columns[col].metadata.get('interesting_values') is not None else: assert df.ww.columns[col].metadata.get('interesting_values') is None def test_add_interesting_values_verbose_output(caplog): es = ft.demo.load_retail(nrows=200) es['order_products'].ww.set_types({'quantity': 'Categorical'}) es['orders'].ww.set_types({'country': 'Categorical'}) logger = logging.getLogger('featuretools') logger.propagate = True logger_es = logging.getLogger('featuretools.entityset') logger_es.propagate = True es.add_interesting_values(verbose=True, max_values=10) logger.propagate = False logger_es.propagate = False assert 'Column country: Marking United Kingdom as an interesting value' in caplog.text assert 'Column quantity: Marking 6 as an interesting value' in caplog.text def test_entityset_equality(es): first_es = EntitySet() second_es = EntitySet() assert first_es == second_es first_es.add_dataframe(dataframe_name='customers', dataframe=es['customers'].copy(), index='id', time_index='signup_date', logical_types=es['customers'].ww.logical_types, semantic_tags=get_df_tags(es['customers'])) assert first_es != second_es second_es.add_dataframe(dataframe_name='sessions', dataframe=es['sessions'].copy(), index='id', logical_types=es['sessions'].ww.logical_types, semantic_tags=get_df_tags(es['sessions'])) assert first_es != second_es first_es.add_dataframe(dataframe_name='sessions', dataframe=es['sessions'].copy(), index='id', logical_types=es['sessions'].ww.logical_types, semantic_tags=get_df_tags(es['sessions'])) second_es.add_dataframe(dataframe_name='customers', dataframe=es['customers'].copy(), index='id', time_index='signup_date', logical_types=es['customers'].ww.logical_types, semantic_tags=get_df_tags(es['customers'])) assert first_es == second_es first_es.add_relationship('customers', 'id', 'sessions', 'customer_id') assert first_es != second_es assert second_es != first_es second_es.add_relationship('customers', 'id', 'sessions', 'customer_id') assert first_es == second_es def test_entityset_id_equality(): first_es = EntitySet(id='first') first_es_copy = EntitySet(id='first') second_es = EntitySet(id='second') assert first_es != second_es assert first_es == first_es_copy def test_entityset_time_type_equality(): first_es = EntitySet() second_es = EntitySet() assert first_es == second_es first_es.time_type = 'numeric' assert first_es != second_es second_es.time_type = Datetime assert first_es != second_es second_es.time_type = 'numeric' assert first_es == second_es def test_entityset_deep_equality(es): first_es = EntitySet() second_es = EntitySet() first_es.add_dataframe(dataframe_name='customers', dataframe=es['customers'].copy(), index='id', time_index='signup_date', logical_types=es['customers'].ww.logical_types, semantic_tags=get_df_tags(es['customers'])) first_es.add_dataframe(dataframe_name='sessions', dataframe=es['sessions'].copy(), index='id', logical_types=es['sessions'].ww.logical_types, semantic_tags=get_df_tags(es['sessions'])) second_es.add_dataframe(dataframe_name='sessions', dataframe=es['sessions'].copy(), index='id', logical_types=es['sessions'].ww.logical_types, semantic_tags=get_df_tags(es['sessions'])) second_es.add_dataframe(dataframe_name='customers', dataframe=es['customers'].copy(), index='id', time_index='signup_date', logical_types=es['customers'].ww.logical_types, semantic_tags=get_df_tags(es['customers'])) assert first_es.__eq__(second_es, deep=False) assert first_es.__eq__(second_es, deep=True) # Woodwork metadata only gets included in deep equality check first_es['sessions'].ww.metadata['created_by'] = 'user0' assert first_es.__eq__(second_es, deep=False) assert not first_es.__eq__(second_es, deep=True) second_es['sessions'].ww.metadata['created_by'] = 'user0' assert first_es.__eq__(second_es, deep=False) assert first_es.__eq__(second_es, deep=True) updated_df = first_es['customers'].loc[[2, 0], :] first_es.replace_dataframe('customers', updated_df) assert first_es.__eq__(second_es, deep=False) # Uses woodwork equality which only looks at df content for pandas if isinstance(updated_df, pd.DataFrame): assert not first_es.__eq__(second_es, deep=True) else: assert first_es.__eq__(second_es, deep=True) @pytest.fixture(params=['make_es', 'dask_es_to_copy']) def es_to_copy(request): return request.getfixturevalue(request.param) @pytest.fixture def dask_es_to_copy(make_es): es = EntitySet(id=make_es.id) for df in make_es.dataframes: dd_df = dd.from_pandas(df.reset_index(drop=True), npartitions=4) dd_df.ww.init(schema=df.ww.schema) es.add_dataframe(dd_df) for rel in make_es.relationships: es.add_relationship(rel.parent_dataframe.ww.name, rel._parent_column_name, rel.child_dataframe.ww.name, rel._child_column_name) return es def test_deepcopy_entityset(es_to_copy): # Uses make_es since the es fixture uses deepcopy copied_es = copy.deepcopy(es_to_copy) assert copied_es == es_to_copy assert copied_es is not es_to_copy for df_name in es_to_copy.dataframe_dict.keys(): original_df = es_to_copy[df_name] new_df = copied_es[df_name] assert new_df.ww.schema == original_df.ww.schema assert new_df.ww._schema is not original_df.ww._schema pd.testing.assert_frame_equal(to_pandas(new_df), to_pandas(original_df)) assert new_df is not original_df def test_deepcopy_entityset_woodwork_changes(es): copied_es = copy.deepcopy(es) assert copied_es == es assert copied_es is not es copied_es['products'].ww.add_semantic_tags({'id': 'new_tag'}) assert copied_es['products'].ww.semantic_tags['id'] == {'index', 'new_tag'} assert es['products'].ww.semantic_tags['id'] == {'index'} assert copied_es != es def test_deepcopy_entityset_featuretools_changes(es): copied_es = copy.deepcopy(es) assert copied_es == es assert copied_es is not es copied_es.set_secondary_time_index('customers', {'upgrade_date': ['engagement_level']}) assert copied_es['customers'].ww.metadata['secondary_time_index'] == {'upgrade_date': ['engagement_level', 'upgrade_date']} assert es['customers'].ww.metadata['secondary_time_index'] == {'cancel_date': ['cancel_reason', 'cancel_date']} def test_dataframe_type_empty_es(): es = EntitySet("test") assert es.dataframe_type is None def test_dataframe_type_pandas_es(pd_es): assert pd_es.dataframe_type == Library.PANDAS.value def test_es__getstate__key_unique(es): assert not hasattr(es, WW_SCHEMA_KEY) def test_pd_es_pickling(pd_es): pkl = pickle.dumps(pd_es) unpickled = pickle.loads(pkl) assert pd_es.__eq__(unpickled, deep=True) assert not hasattr(unpickled, WW_SCHEMA_KEY) def test_empty_es_pickling(): es = ft.EntitySet(id="empty") pkl = pickle.dumps(es) unpickled = pickle.loads(pkl) assert es.__eq__(unpickled, deep=True)
import React from "react"; import ReactDOM from "react-dom"; import App from './App'; import "./assets/plugins/nucleo/css/nucleo.css"; import "./assets/scss/argon-dashboard-react.scss"; import 'react-notification-alert/dist/animate.css'; import 'react-perfect-scrollbar/dist/css/styles.css'; import "@fortawesome/fontawesome-free/css/all.min.css"; import "./assets/plugins/nucleo/css/nucleo.css"; import './assets/css/styles.css'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') );
from django.conf import settings settings.FORMS_IMPORTED = True
import time from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait # Sleep times to pause the script (given in seconds) shortInterval = 3 mediumInterval = 15 longInterval = 40 # Selenium Chrome driver location chromeDriverPath = 'C:\\Python27\\Custom_tools\\chromedriver.exe' # URL of the page gossipLURL = 'https://www.gossiplankanews.com/2018/12/final-decision.html' # gossipLURL = 'https://www.gossiplankanews.com/2018/12/steave-rixon-for-sri-lanka-cricket.html' # gossipLURL = 'https://www.gossiplankanews.com/2018/10/arjuna-dematagoda-update.html' # Comments vote up / vote down button XPaths list commentXPaths = ['//*[@id="IDComment1067220387"]/div[1]/div/div/a[2]', '//*[@id="IDComment1067220701"]/div[1]/div/div/a[2]', '//*[@id="IDComment1067222914"]/div[1]/div/div/a[2]', '//*[@id="IDComment1067220381"]/div[1]/div/div[2]/a[2]'] # Emoji icon XPaths kujeethaiIconXPath = '//*[@id="Blog1"]/div[3]/div/div[1]/div[2]/div[6]/div/div[1]/img' supiriIconXPath = '//*[@id="Blog1"]/div[3]/div/div[1]/div[2]/div[1]/div/div[1]/img' def commentBot(): while True: browser = webdriver.Chrome(chromeDriverPath) browser.delete_all_cookies() browser.get(gossipLURL) time.sleep(longInterval) # Remove "idc-disabled" class from the already voted comments browser.execute_script(""" var elements = document.getElementsByClassName('idc-disabled'); while(elements.length > 0){ elements[0].classList.remove('idc-disabled'); } """) time.sleep(shortInterval) # Loop thru the selected comments and click their desired button for commentXPath in commentXPaths: commentIcon = browser.find_element_by_xpath(commentXPath) commentIcon.click() time.sleep(shortInterval) browser.quit() # Function to click on the selected emoji def emojiBot(icon): while True: browser = webdriver.Chrome(chromeDriverPath) browser.get(gossipLURL) time.sleep(mediumInterval) myIcon = browser.find_element_by_xpath(icon) myIcon.click() time.sleep(shortInterval) browser.quit() #commentBot() emojiBot(kujeethaiIconXPath)
import 'phaser'; //import pkg from 'phaser/package.json'; import sky from './img/sky.png'; import ground from './img/platform.png'; import star from './img/star.png'; import bomb from './img/bomb.png'; import dude from './img/dude.png'; // This is the entry point of your game. const width = 800; const height = 600; let config = { width, height, type: Phaser.AUTO, physics:{ default: 'arcade', arcade:{ gravity: {y: 300}, debug: false } }, scene: { preload: preload, create:create , update:update } }; let game = new Phaser.Game(config); let platforms; let player; let cursors; let stars; function preload() { this.load.image('sky', sky); this.load.image('ground', ground); this.load.image('star',star); this.load.image('bomb',bomb); this.load.spritesheet('dude',dude,{frameWidth:32,frameHeight:48}); //this.load.image('study', introImage); } function create() { this.add.image(400,300,'sky'); platforms = this.physics.add.staticGroup(); platforms.create(400,568,'ground').setScale(2).refreshBody(); platforms.create(600,400,'ground'); platforms.create(50,250,'ground'); platforms.create(750,220,'ground'); this.add.image(200, 300, 'star'); this.add.image(300, 300, 'star'); this.add.image(400, 200, 'star'); player = this.physics.add.sprite(100,450,'dude'); player.setBounce(0.2); player.setCollideWorldBounds (true); this.anims.create({ key:'left', frames: this.anims.generateFrameNumbers('dude',{start: 0,end: 3}), frameRate:10, repeat:-1 }); this.anims.create({ key:'turn', frames:[{key:'dude',frame:4}], frameRate:20 }); this.anims.create({ key:'right', frames:this.anims.generateFrameNumbers('dude',{start:5,end:8}), framesRate:10, repeat:-1 }); cursors = this.input.keyboard.createCursorKeys(); stars = this.physics.add.group({ key: 'star', repeat: 11, setXY: {x: 12,y:0, stepX: 70} }); stars.children.iterate(function(child){ child.setBounceY(Phaser.Math.FloatBetween(0.4,0.8)) }); } this.physics.add.collider(player,platforms); this.physics.add.collider(stars, platforms); this.physics.add.overlap(player, stars, collectStar, null, this); /*const centerX = width / 2; const centerY = height / 2; const welcomeMessage = `Welcome to Phaser ${pkg.version}`; this.add.image(centerX, centerY * 1.2, 'study'); this.add .text(centerX, centerY * 0.8, welcomeMessage, { font: "bold 19px Arial", fill: "#fff" }) .setOrigin(0.5, 0.5);*/ function update () { if (cursors.left.isDown) { player.setVelocityX(-160); player.anims.play('left', true); } else if (cursors.right.isDown) { player.setVelocityX(160); player.anims.play('right', true); } else { player.setVelocityX(0); player.anims.play('turn'); } if (cursors.up.isDown && player.body.touching.down) { player.setVelocityY(-330); } function collectStar(player, star) { star.disableBody (true, true); } }
"use strict"; exports.default = createStrip; var _type = require("../../core/utils/type"); var _utils = require("../core/utils"); var _extend = require("../../core/utils/extend"); function createStrip(axis, options) { var storedCoord; var lastStoredCoordinates; var labelOptions = options.label || {}; return { options: options, label: null, rect: null, _getCoord: function _getCoord() { var canvas = axis._getCanvasStartEnd(); var range = axis._translator.getBusinessRange(); return axis._getStripPos(options.startValue, options.endValue, canvas.start, canvas.end, range); }, _drawLabel: function _drawLabel(coords) { return axis._renderer.text(labelOptions.text, coords.x, coords.y).css((0, _utils.patchFontOptions)((0, _extend.extend)({}, axis.getOptions().label.font, labelOptions.font))).attr({ align: 'center', 'class': labelOptions.cssClass }).append(axis._axisStripLabelGroup); }, draw: function draw() { if (axis._translator.getBusinessRange().isEmpty()) { return; } if (((0, _type.isDefined)(options.startValue) || (0, _type.isDefined)(options.endValue)) && (0, _type.isDefined)(options.color)) { var stripPos = this._getCoord(); this.labelCoords = labelOptions.text ? axis._getStripLabelCoords(stripPos.from, stripPos.to, labelOptions) : null; if (stripPos.outOfCanvas || !(0, _type.isDefined)(stripPos.to) || !(0, _type.isDefined)(stripPos.from)) { return; } this.rect = axis._createStrip(axis._getStripGraphicAttributes(stripPos.from, stripPos.to)).attr({ fill: options.color }).append(axis._axisStripGroup); this.label = labelOptions.text ? this._drawLabel(this.labelCoords) : null; } }, getContentContainer: function getContentContainer() { return this.label; }, removeLabel: function removeLabel() {}, updatePosition: function updatePosition(animate) { var stripPos = this._getCoord(); if (animate && storedCoord) { this.label && this.label.attr(axis._getStripLabelCoords(storedCoord.from, storedCoord.to, options.label)); this.rect && this.rect.attr(axis._getStripGraphicAttributes(storedCoord.from, storedCoord.to)); this.label && this.label.animate(axis._getStripLabelCoords(stripPos.from, stripPos.to, options.label)); this.rect && this.rect.animate(axis._getStripGraphicAttributes(stripPos.from, stripPos.to)); } else { this.label && this.label.attr(axis._getStripLabelCoords(stripPos.from, stripPos.to, options.label)); this.rect && this.rect.attr(axis._getStripGraphicAttributes(stripPos.from, stripPos.to)); } }, saveCoords: function saveCoords() { lastStoredCoordinates = storedCoord; storedCoord = this._getCoord(); }, resetCoordinates: function resetCoordinates() { storedCoord = lastStoredCoordinates; } }; } module.exports = exports.default;
'use strict'; const Gulp = require('gulp'); const Gutil = require('gulp-util'); const Webpack = require('webpack'); let executionCount = 0; Gulp.task('webpack', (callback) => { const plugins = [ new Webpack.optimize.CommonsChunkPlugin({ name: 'core', filename: '../core.min.js', minSize: 2 }), new Webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': `"${process.env.NODE_ENV}"` } }) ]; let devtool = 'source-map'; if (process.env.NODE_ENV === 'production') { plugins.push(new Webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } })); devtool = 'cheap-module-source-map'; } const config = { watch: global.isWatching, entry: { account: './client/pages/account/index', admin: './client/pages/admin/index', contact: './client/pages/contact/index', login: './client/pages/login/index', signup: './client/pages/signup/index' }, output: { path: './public/pages', filename: '[name].min.js', sourceMapFilename: '[name].map.js' }, resolve: { extensions: ['', '.js', '.jsx'] }, module: { loaders: [{ test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['react', 'es2015'] } }] }, devtool, plugins }; Webpack(config, (err, stats) => { if (err) { throw new Gutil.PluginError('webpack', err); } Gutil.log('[webpack]', stats.toString({ colors: true, chunkModules: false })); if (executionCount === 0) { callback(); } executionCount += 1; }); });
//init WALLS = []; OBJDATA = []; ROOM = []; HISTORY = []; wallSize = 20; partitionSize = 8; var drag = 'off'; var action = 0; var magnetic = 0; var construc = 0; var Rcirclebinder = 8; var mode = 'select_mode'; var modeOption; taille_w = $('#lin').width(); taille_h = $('#lin').height(); var offset = $('#lin').offset(); grid = 20; showRib = true; showArea = true; meter = 60; grid_snap = 'off'; colorbackground = "#ffffff"; colorline = "#fff"; colorroom = "#f0daaf"; colorWall = "#666"; pox = 0; poy = 0; segment = 0; xpath = 0; ypath = 0; var width_viewbox = taille_w; var height_viewbox = taille_h; var ratio_viewbox = height_viewbox / width_viewbox; var originX_viewbox = 0; var originY_viewbox = 0; var zoom = 9; var factor = 1; // ************************************************************************** // ***************** LOAD / SAVE LOCALSTORAGE ************************ // ************************************************************************** function initHistory(boot = false) { HISTORY.index = 0; if (!boot && localStorage.getItem('history')) localStorage.removeItem('history'); if (localStorage.getItem('history') && boot == "recovery") { var historyTemp = JSON.parse(localStorage.getItem('history')); load(historyTemp.length-1, "boot"); save("boot"); } if (boot == "newSquare") { if (localStorage.getItem('history')) localStorage.removeItem('history'); HISTORY.push({"objData":[],"wallData":[{"thick":20,"start":{"x":540,"y":194},"end":{"x":540,"y":734},"type":"normal","parent":3,"child":1,"angle":1.5707963267948966,"equations":{"up":{"A":"v","B":550},"down":{"A":"v","B":530},"base":{"A":"v","B":540}},"coords":[{"x":550,"y":204},{"x":530,"y":184},{"x":530,"y":744},{"x":550,"y":724}],"graph":{"0":{},"context":{},"length":1}},{"thick":20,"start":{"x":540,"y":734},"end":{"x":1080,"y":734},"type":"normal","parent":0,"child":2,"angle":0,"equations":{"up":{"A":"h","B":724},"down":{"A":"h","B":744},"base":{"A":"h","B":734}},"coords":[{"x":550,"y":724},{"x":530,"y":744},{"x":1090,"y":744},{"x":1070,"y":724}],"graph":{"0":{},"context":{},"length":1}},{"thick":20,"start":{"x":1080,"y":734},"end":{"x":1080,"y":194},"type":"normal","parent":1,"child":3,"angle":-1.5707963267948966,"equations":{"up":{"A":"v","B":1070},"down":{"A":"v","B":1090},"base":{"A":"v","B":1080}},"coords":[{"x":1070,"y":724},{"x":1090,"y":744},{"x":1090,"y":184},{"x":1070,"y":204}],"graph":{"0":{},"context":{},"length":1}},{"thick":20,"start":{"x":1080,"y":194},"end":{"x":540,"y":194},"type":"normal","parent":2,"child":0,"angle":3.141592653589793,"equations":{"up":{"A":"h","B":204},"down":{"A":"h","B":184},"base":{"A":"h","B":194}},"coords":[{"x":1070,"y":204},{"x":1090,"y":184},{"x":530,"y":184},{"x":550,"y":204}],"graph":{"0":{},"context":{},"length":1}}],"roomData":[{"coords":[{"x":540,"y":734},{"x":1080,"y":734},{"x":1080,"y":194},{"x":540,"y":194},{"x":540,"y":734}],"coordsOutside":[{"x":1090,"y":744},{"x":1090,"y":184},{"x":530,"y":184},{"x":530,"y":744},{"x":1090,"y":744}],"coordsInside":[{"x":1070,"y":724},{"x":1070,"y":204},{"x":550,"y":204},{"x":550,"y":724},{"x":1070,"y":724}],"inside":[],"way":["0","2","3","1","0"],"area":270400,"surface":"","name":"","color":"gradientWhite","showSurface":true,"action":"add"}]}); HISTORY[0] = JSON.stringify(HISTORY[0]); localStorage.setItem('history', JSON.stringify(HISTORY)); load(0); save(); } if (boot == "newL") { if (localStorage.getItem('history')) localStorage.removeItem('history'); HISTORY.push({"objData":[],"wallData":[{"thick":20,"start":{"x":447,"y":458},"end":{"x":447,"y":744},"type":"normal","parent":5,"child":1,"angle":1.5707963267948966,"equations":{"up":{"A":"v","B":457},"down":{"A":"v","B":437},"base":{"A":"v","B":447}},"coords":[{"x":457,"y":468},{"x":437,"y":448},{"x":437,"y":754},{"x":457,"y":734}],"graph":{"0":{},"context":{},"length":1}},{"thick":20,"start":{"x":447,"y":744},"end":{"x":1347,"y":744},"type":"normal","parent":0,"child":2,"angle":0,"equations":{"up":{"A":"h","B":734},"down":{"A":"h","B":754},"base":{"A":"h","B":744}},"coords":[{"x":457,"y":734},{"x":437,"y":754},{"x":1357,"y":754},{"x":1337,"y":734}],"graph":{"0":{},"context":{},"length":1}},{"thick":20,"start":{"x":1347,"y":744},"end":{"x":1347,"y":144},"type":"normal","parent":1,"child":3,"angle":-1.5707963267948966,"equations":{"up":{"A":"v","B":1337},"down":{"A":"v","B":1357},"base":{"A":"v","B":1347}},"coords":[{"x":1337,"y":734},{"x":1357,"y":754},{"x":1357,"y":134},{"x":1337,"y":154}],"graph":{"0":{},"context":{},"length":1}},{"thick":20,"start":{"x":1347,"y":144},"end":{"x":1020,"y":144},"type":"normal","parent":2,"child":4,"angle":3.141592653589793,"equations":{"up":{"A":"h","B":154},"down":{"A":"h","B":134},"base":{"A":"h","B":144}},"coords":[{"x":1337,"y":154},{"x":1357,"y":134},{"x":1010,"y":134},{"x":1030,"y":154}],"graph":{"0":{},"context":{},"length":1}},{"thick":20,"start":{"x":1020,"y":144},"end":{"x":1020,"y":458},"type":"normal","parent":3,"child":5,"angle":1.5707963267948966,"equations":{"up":{"A":"v","B":1030},"down":{"A":"v","B":1010},"base":{"A":"v","B":1020}},"coords":[{"x":1030,"y":154},{"x":1010,"y":134},{"x":1010,"y":448},{"x":1030,"y":468}],"graph":{"0":{},"context":{},"length":1}},{"thick":20,"start":{"x":1020,"y":458},"end":{"x":447,"y":458},"type":"normal","parent":4,"child":0,"angle":3.141592653589793,"equations":{"up":{"A":"h","B":468},"down":{"A":"h","B":448},"base":{"A":"h","B":458}},"coords":[{"x":1030,"y":468},{"x":1010,"y":448},{"x":437,"y":448},{"x":457,"y":468}],"graph":{"0":{},"context":{},"length":1}}],"roomData":[{"coords":[{"x":447,"y":744},{"x":1347,"y":744},{"x":1347,"y":144},{"x":1020,"y":144},{"x":1020,"y":458},{"x":447,"y":458},{"x":447,"y":744}],"coordsOutside":[{"x":1357,"y":754},{"x":1357,"y":134},{"x":1010,"y":134},{"x":1010,"y":448},{"x":437,"y":448},{"x":437,"y":754},{"x":1357,"y":754}],"coordsInside":[{"x":1337,"y":734},{"x":1337,"y":154},{"x":1030,"y":154},{"x":1030,"y":468},{"x":457,"y":468},{"x":457,"y":734},{"x":1337,"y":734}],"inside":[],"way":["0","2","3","4","5","1","0"],"area":330478,"surface":"","name":"","color":"gradientWhite","showSurface":true,"action":"add"}]}); HISTORY[0] = JSON.stringify(HISTORY[0]); localStorage.setItem('history', JSON.stringify(HISTORY)); load(0); save(); } } document.getElementById('redo').addEventListener("click", function() { if (HISTORY.index < HISTORY.length) { load(HISTORY.index); HISTORY.index++; $('#undo').removeClass('disabled'); if (HISTORY.index == HISTORY.length) { $('#redo').addClass('disabled'); } } }); document.getElementById('undo').addEventListener("click", function() { if (HISTORY.index > 0) { $('#undo').removeClass('disabled'); if (HISTORY.index-1 >0) { HISTORY.index--; load(HISTORY.index-1); $('#redo').removeClass('disabled'); } } if (HISTORY.index == 1) $('#undo').addClass('disabled'); }); function fakeClick(obj) { var ev = document.createEvent("MouseEvents");     ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);     obj.dispatchEvent(ev); } function exportRaw(name, data) {     var urlObject = window.URL || window.webkitURL || window;     var export_blob = new Blob([data]);     var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")     save_link.href = urlObject.createObjectURL(export_blob);     save_link.download = name;     fakeClick(save_link); } document.getElementById("downloada").addEventListener("click", function () { var value = document.getElementById("lin").outerHTML; exportRaw("nicetool.svg",value); }); function save(boot = false) { if (boot) localStorage.removeItem('history'); // FOR CYCLIC OBJ INTO LOCALSTORAGE !!! for (var k in WALLS) { if (WALLS[k].child != null) WALLS[k].child = WALLS.indexOf(WALLS[k].child); if (WALLS[k].parent != null) WALLS[k].parent = WALLS.indexOf(WALLS[k].parent); } if (JSON.stringify({objData: OBJDATA, wallData: WALLS, roomData: ROOM}) == HISTORY[HISTORY.length-1]) { for (var k in WALLS) { if (WALLS[k].child != null) WALLS[k].child = WALLS[WALLS[k].child]; if (WALLS[k].parent != null) WALLS[k].parent = WALLS[WALLS[k].parent]; } return false; } if (HISTORY.index < HISTORY.length) { HISTORY.splice(HISTORY.index, (HISTORY.length - HISTORY.index)); $('#redo').addClass('disabled'); } HISTORY.push(JSON.stringify({objData: OBJDATA, wallData: WALLS, roomData: ROOM})); localStorage.setItem('history', JSON.stringify(HISTORY)); HISTORY.index++; if (HISTORY.index>1) $('#undo').removeClass('disabled'); for (var k in WALLS) { if (WALLS[k].child != null) WALLS[k].child = WALLS[WALLS[k].child]; if (WALLS[k].parent != null) WALLS[k].parent = WALLS[WALLS[k].parent]; } return true; } function load(index = HISTORY.index, boot = false) { if (HISTORY.length == 0 && !boot) return false; for (var k in OBJDATA){ OBJDATA[k].graph.remove(); } OBJDATA = []; var historyTemp = []; historyTemp = JSON.parse(localStorage.getItem('history')); historyTemp = JSON.parse(historyTemp[index]); for (var k in historyTemp.objData) { var OO = historyTemp.objData[k]; // if (OO.family == 'energy') OO.family = 'byObject'; var obj = new editor.obj2D(OO.family, OO.class, OO.type, {x: OO.x, y: OO.y}, OO.angle, OO.angleSign, OO.size, OO.hinge = 'normal', OO.thick, OO.value); obj.limit = OO.limit; OBJDATA.push(obj); $('#boxcarpentry').append(OBJDATA[OBJDATA.length-1].graph); obj.update(); } WALLS = historyTemp.wallData; for (var k in WALLS) { if (WALLS[k].child != null) WALLS[k].child = WALLS[WALLS[k].child]; if (WALLS[k].parent != null) WALLS[k].parent = WALLS[WALLS[k].parent]; } ROOM = historyTemp.roomData; editor.architect(WALLS); editor.showScaleBox(); rib(); } $('svg').each(function() { $(this)[0].setAttribute('viewBox', originX_viewbox + ' ' + originY_viewbox + ' ' + width_viewbox + ' ' + height_viewbox) }); // ************************************************************************** // ***************** FUNCTIONS ON BUTTON click ************************ // ************************************************************************** document.getElementById('report_mode').addEventListener("click", function() { if (typeof(globalArea) == "undefined") return false; mode = "report_mode"; $('#panel').hide(); $('#reportTools').show(200, function() { document.getElementById('reportTotalSurface').innerHTML = "总面积 : <b>"+(globalArea/3600).toFixed(1)+ "</b> m²"; $('#reportTotalSurface').show(1000); document.getElementById('reportNumberSurface').innerHTML = "房间数 : <b>"+ROOM.length+ "</b>"; $('#reportNumberSurface').show(1000); var number = 1; var reportRoom = '<div class="row">\n'; for (var k in ROOM) { var nameRoom = "区域"+number+" <small>(未标注)</small>"; if (ROOM[k].name != "") nameRoom = ROOM[k].name; reportRoom+= '<div class="col-md-6"><p>'+nameRoom+'</p></div>\n'; reportRoom+= '<div class="col-md-6"><p>面积 : <b>'+((ROOM[k].area)/3600).toFixed(2)+'</b> m²</p></div>\n'; number++; } reportRoom+='</div><hr/>\n'; reportRoom+='<div>\n'; var switchNumber = 0; var plugNumber = 0; var lampNumber = 0; for (var k in OBJDATA) { if (OBJDATA[k].class == 'energy') { if (OBJDATA[k].type == 'switch' || OBJDATA[k].type == 'doubleSwitch' || OBJDATA[k].type == 'dimmer') switchNumber++; if (OBJDATA[k].type == 'plug' || OBJDATA[k].type == 'plug20' || OBJDATA[k].type == 'plug32') plugNumber++; if (OBJDATA[k].type == 'wallLight' || OBJDATA[k].type == 'roofLight') lampNumber++; } } reportRoom+='<p>开关数量 : '+switchNumber+'</p>'; reportRoom+='<p>插座数量 : '+plugNumber+'</p>'; reportRoom+='<p>灯光数量 : '+lampNumber+'</p>'; reportRoom+='</div>'; reportRoom+='<div>\n'; //reportRoom+='<h2>明细</h2>\n'; var number = 1; //reportRoom+= '<div class="row">\n'; //reportRoom+= '<div class="col-md-4"><p>区域</p></div>\n'; //reportRoom+= '<div class="col-md-2"><small>Int.</small></div>\n'; //reportRoom+= '<div class="col-md-2"><small>Pri. sec.</small></div>\n'; //reportRoom+= '<div class="col-md-2"><small>Pt lum.</small></div>\n'; //reportRoom+= '<div class="col-md-2"><small>Watts Max</small></div>\n'; //reportRoom+='</div>'; var roomEnergy = []; for (var k in ROOM) { //reportRoom+= '<div class="row">\n'; var nameRoom = "Pièce n°"+number+" <small>(sans nom)</small>"; if (ROOM[k].name != "") nameRoom = ROOM[k].name; //reportRoom+= '<div class="col-md-4"><p>'+nameRoom+'</p></div>\n'; var switchNumber = 0; var plugNumber = 0; var plug20 = 0; var plug32 = 0; var lampNumber = 0; var wattMax = 0; var plug = false; for (var i in OBJDATA) { if (OBJDATA[i].class == 'energy') { if (OBJDATA[i].type == 'switch' || OBJDATA[i].type == 'doubleSwitch' || OBJDATA[i].type == 'dimmer') { if (roomTarget = editor.rayCastingRoom(OBJDATA[i])) { if (isObjectsEquals(ROOM[k], roomTarget)) switchNumber++; } } if (OBJDATA[i].type == 'plug' || OBJDATA[i].type == 'plug20' || OBJDATA[i].type == 'plug32') { if (roomTarget = editor.rayCastingRoom(OBJDATA[i])) { if (isObjectsEquals(ROOM[k], roomTarget)) { plugNumber++; if (OBJDATA[i].type == 'plug' && !plug) {wattMax+=3520;plug = true;} if (OBJDATA[i].type == 'plug20') {wattMax+=4400;plug20++;} if (OBJDATA[i].type == 'plug32') {wattMax+=7040;plug32++;} } } } if (OBJDATA[i].type == 'wallLight' || OBJDATA[i].type == 'roofLight') { if (roomTarget = editor.rayCastingRoom(OBJDATA[i])) { if (isObjectsEquals(ROOM[k], roomTarget)) { lampNumber++; wattMax+=100; } } } } } roomEnergy.push({switch: switchNumber, plug: plugNumber, plug20: plug20, plug32: plug32, light: lampNumber}); //reportRoom+= '<div class="col-md-2"><b>'+switchNumber+'</b></div>\n'; //reportRoom+= '<div class="col-md-2"><b>'+plugNumber+'</b></div>\n'; //reportRoom+= '<div class="col-md-2"><b>'+lampNumber+'</b></div>\n'; //reportRoom+= '<div class="col-md-2"><b>'+wattMax+'</b></div>\n'; number++; //reportRoom+='</div>'; } //reportRoom+='<hr/><h2>Détails Norme NF C 15-100</h2>\n'; var number = 1; for (var k in ROOM) { reportRoom+= '<div class="row" style="display:none;">\n'; var nfc = true; var nameRoom = "Pièce n°"+number+" <small>(sans nom)</small>"; if (ROOM[k].name != "") nameRoom = ROOM[k].name; reportRoom+= '<div class="col-md-4"><p>'+nameRoom+'</p></div>\n'; if (ROOM[k].name == "") { reportRoom+= '<div class="col-md-8"><p><i class="fa fa-ban" aria-hidden="true" style="color:red"></i> La pièce n\'ayant pas de libellé, Home Rough Editor ne peut vous fournir d\'informations.</p></div>\n'; } else { if (ROOM[k].name == "Salon") { for (var g in ROOM) { if (ROOM[g].name == "Salle à manger") { roomEnergy[k].light+=roomEnergy[g].light; roomEnergy[k].plug+=roomEnergy[g].plug; roomEnergy[k].switch+=roomEnergy[g].switch; } } reportRoom+= '<div class="col-md-8">'; if (roomEnergy[k].light == 0) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>1 point lumineux commandé</b> <small>(actuellement '+roomEnergy[k].light+')</small>.</p>\n';nfc=false;} if (roomEnergy[k].plug < 5) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>5 prises de courant</b> <small>(actuellement '+roomEnergy[k].plug+')</small>.</p>\n';nfc=false;} if (nfc) reportRoom+='<i class="fa fa-check" aria-hidden="true" style="color:green"></i>'; reportRoom+= '</div>'; } if (ROOM[k].name == "Salle à manger") { reportRoom+= '<div class="col-md-8"><p><i class="fa fa-info" aria-hidden="true" style="color:blue"></i> Cette pièce est liée au <b>salon / séjour</b> selon la norme.</p></div>\n'; } if (ROOM[k].name.substr(0,7) == "Chambre") { reportRoom+= '<div class="col-md-8">'; if (roomEnergy[k].light == 0) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>1 point lumineux commandé</b> <small>(actuellement '+roomEnergy[k].light+')</small>.</p>\n';nfc=false;} if (roomEnergy[k].plug < 3) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>3 prises de courant</b> <small>(actuellement '+roomEnergy[k].plug+')</small>.</p>\n';nfc=false;} if (nfc) reportRoom+='<i class="fa fa-check" aria-hidden="true" style="color:green"></i>'; reportRoom+= '</div>'; } if (ROOM[k].name == "SdB") { reportRoom+= '<div class="col-md-8">'; if (roomEnergy[k].light == 0) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>1 point lumineux</b> <small>(actuellement '+roomEnergy[k].light+')</small>.</p>\n';nfc=false;} if (roomEnergy[k].plug < 2) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>2 prises de courant</b> <small>(actuellement '+roomEnergy[k].plug+')</small>.</p>\n';nfc=false;} if (roomEnergy[k].switch == 0) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>1 interrupteur</b> <small>(actuellement '+roomEnergy[k].switch+')</small>.</p>\n';nfc=false;} if (nfc) reportRoom+='<i class="fa fa-check" aria-hidden="true" style="color:green"></i>'; reportRoom+= '</div>'; } if (ROOM[k].name == "Couloir") { reportRoom+= '<div class="col-md-8">'; if (roomEnergy[k].light == 0) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>1 point lumineux commandé</b> <small>(actuellement '+roomEnergy[k].light+')</small>.</p>\n';nfc=false;} if (roomEnergy[k].plug < 1) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>1 prise de courant</b> <small>(actuellement '+roomEnergy[k].plug+')</small>.</p>\n';nfc=false;} if (nfc) reportRoom+='<i class="fa fa-check" aria-hidden="true" style="color:green"></i>'; reportRoom+= '</div>'; } if (ROOM[k].name == "Toilette") { reportRoom+= '<div class="col-md-8">'; if (roomEnergy[k].light == 0) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>1 point lumineux</b>. <small>(actuellement '+roomEnergy[k].light+')</small>.</p>\n';nfc=false;} if (nfc) reportRoom+='<i class="fa fa-check" aria-hidden="true" style="color:green"></i>'; reportRoom+= '</div>'; } if (ROOM[k].name == "Cuisine") { reportRoom+= '<div class="col-md-8">'; if (roomEnergy[k].light == 0) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>1 point lumineux commandé</b> <small>(actuellement '+roomEnergy[k].light+')</small>.</p>\n';nfc=false;} if (roomEnergy[k].plug < 6) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>6 prise de courant</b> <small>(actuellement '+roomEnergy[k].plug+')</small>.</p>\n';nfc=false;} if (roomEnergy[k].plug32 == 0) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>1 prise de courant 32A</b> <small>(actuellement '+roomEnergy[k].plug32+')</small>.</p>\n';nfc=false;} if (roomEnergy[k].plug20 < 2) {reportRoom+= '<p><i class="fa fa-exclamation-triangle" style="color:orange" aria-hidden="true"></i> Cette pièce doit disposer d\'au moins <b>2 prise de courant 20A</b> <small>(actuellement '+roomEnergy[k].plug20+')</small>.</p>\n';nfc=false;} if (nfc) reportRoom+='<i class="fa fa-check" aria-hidden="true" style="color:green"></i>'; reportRoom+= '</div>'; } } number++; reportRoom+='</div>'; } document.getElementById('reportRooms').innerHTML = reportRoom; $('#reportRooms').show(1000); }); }); document.getElementById('wallWidth').addEventListener("input", function() { var sliderValue = this.value; binder.wall.thick = sliderValue; binder.wall.type = "normal"; editor.architect(WALLS); var objWall = editor.objFromWall(binder.wall); // LIST OBJ ON EDGE for (var w = 0; w < objWall.length; w++) { objWall[w].thick = sliderValue; objWall[w].update(); } rib(); document.getElementById("wallWidthVal").textContent = sliderValue; }); document.getElementById("bboxTrash").addEventListener("click", function () { binder.obj.graph.remove(); binder.graph.remove(); OBJDATA.splice(OBJDATA.indexOf(binder.obj), 1); $('#objBoundingBox').hide(100); $('#panel').show(200); fonc_button('select_mode'); $('#boxinfo').html('清除对象'); delete binder; rib(); }); document.getElementById("bboxStepsAdd").addEventListener("click", function () { var newValue = document.getElementById("bboxStepsVal").textContent; if (newValue < 15) { newValue++; binder.obj.value = newValue; binder.obj.update(); document.getElementById("bboxStepsVal").textContent = newValue; } }); document.getElementById("bboxStepsMinus").addEventListener("click", function () { var newValue = document.getElementById("bboxStepsVal").textContent; if (newValue > 2) { newValue--; binder.obj.value = newValue; binder.obj.update(); document.getElementById("bboxStepsVal").textContent = newValue; } }); document.getElementById('bboxWidth').addEventListener("input", function() { var sliderValue = this.value; var objTarget = binder.obj; objTarget.size = (sliderValue / 100) * meter; objTarget.update(); binder.size = (sliderValue / 100) * meter; binder.update(); document.getElementById("bboxWidthVal").textContent = sliderValue; }); document.getElementById('bboxHeight').addEventListener("input", function() { var sliderValue = this.value; var objTarget = binder.obj; objTarget.thick = (sliderValue / 100) * meter; objTarget.update(); binder.thick = (sliderValue / 100) * meter; binder.update(); document.getElementById("bboxHeightVal").textContent = sliderValue; }); document.getElementById('bboxRotation').addEventListener("input", function() { var sliderValue = this.value; var objTarget = binder.obj; objTarget.angle = sliderValue; objTarget.update(); binder.angle = sliderValue; binder.update(); document.getElementById("bboxRotationVal").textContent = sliderValue; }); document.getElementById('doorWindowWidth').addEventListener("input", function() { var sliderValue = this.value; var objTarget = binder.obj; var wallBind = editor.rayCastingWalls(objTarget, WALLS); if (wallBind.length > 1) wallBind = wallBind[wallBind.length-1]; var limits = limitObj(wallBind.equations.base, sliderValue, objTarget); if (qSVG.btwn(limits[1].x, wallBind.start.x, wallBind.end.x) && qSVG.btwn(limits[1].y, wallBind.start.y, wallBind.end.y) && qSVG.btwn(limits[0].x, wallBind.start.x, wallBind.end.x) && qSVG.btwn(limits[0].y, wallBind.start.y, wallBind.end.y)) { objTarget.size = sliderValue; objTarget.limit = limits; objTarget.update(); binder.size = sliderValue; binder.limit = limits; binder.update(); document.getElementById("doorWindowWidthVal").textContent = sliderValue; } inWallRib(wallBind); }); document.getElementById("objToolsHinge").addEventListener("click", function () { var objTarget = binder.obj; var hingeStatus = objTarget.hinge; // normal - reverse if (hingeStatus == 'normal') objTarget.hinge = 'reverse'; else objTarget.hinge = 'normal'; objTarget.update(); }); window.addEventListener("load", function(){ document.getElementById('panel').style.transform = "translateX(200px)"; document.getElementById('panel').addEventListener("transitionend", function() { document.getElementById('moveBox').style.transform = "translateX(-165px)"; document.getElementById('zoomBox').style.transform = "translateX(-165px)"; }); if (!localStorage.getItem('history')) $('#recover').html("<p>选择一个模板"); $('#myModal').modal(); }); document.getElementById('sizePolice').addEventListener("input", function() { document.getElementById('labelBox').style.fontSize = this.value+'px'; }); $('#textToLayer').on('hidden.bs.modal', function (e) { fonc_button('select_mode'); action = 0; var textToMake = document.getElementById('labelBox').textContent; if (textToMake != "" && textToMake != "Votre texte") { binder = new editor.obj2D("free", "text", document.getElementById('labelBox').style.color, snap, 0, 0, 0, "normal", 0, {text: textToMake, size: document.getElementById('sizePolice').value}); binder.update(); OBJDATA.push(binder); binder.graph.remove(); $('#boxText').append(OBJDATA[OBJDATA.length-1].graph); OBJDATA[OBJDATA.length-1].update(); delete binder; $('#boxinfo').html('添加文字'); save(); } else { $('#boxinfo').html('选择模式'); } document.getElementById('labelBox').textContent = "Votre texte"; document.getElementById('labelBox').style.color = "#333333"; document.getElementById('labelBox').style.fontSize = "15px"; document.getElementById('sizePolice').value = 15; }) if (!Array.prototype.includes) { Object.defineProperty(Array.prototype, 'includes', { value: function(searchElement, fromIndex) { if (this == null) { throw new TypeError('"this" is null or not defined'); } var o = Object(this); var len = o.length >>> 0; if (len === 0) { return false; } var n = fromIndex | 0; var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (o[k] === searchElement) { return true; } k++; } return false; } }); } function isObjectsEquals(a, b, message = false) { if (message) console.log(message) var isOK = true; for (var prop in a) { if (a[prop] !== b[prop]) { isOK = false; break; } } return isOK; }; function throttle(callback, delay) { var last; var timer; return function () { var context = this; var now = +new Date(); var args = arguments; if (last && now < last + delay) { // le délai n'est pas écoulé on reset le timer clearTimeout(timer); timer = setTimeout(function () { last = now; callback.apply(context, args); }, delay); } else { last = now; callback.apply(context, args); } }; } $("#lin").mousewheel(throttle(function(event) { event.preventDefault(); if (event.deltaY > 0) { zoom_maker('zoomin', 200); } else { zoom_maker('zoomout', 200); } },100)); document.getElementById("showRib").addEventListener("click", function () { if (document.getElementById("showRib").checked) { $('#boxScale').show(200); $('#boxRib').show(200); showRib = true; } else { $('#boxScale').hide(100); $('#boxRib').hide(100); showRib = false; } }); document.getElementById("showArea").addEventListener("click", function () { if (document.getElementById("showArea").checked) { $('#boxArea').show(200); } else { $('#boxArea').hide(100); } }); document.getElementById("showLayerRoom").addEventListener("click", function () { if (document.getElementById("showLayerRoom").checked) { $('#boxRoom').show(200); } else { $('#boxRoom').hide(100); } }); document.getElementById("showLayerEnergy").addEventListener("click", function () { if (document.getElementById("showLayerEnergy").checked) { $('#boxEnergy').show(200); } else { $('#boxEnergy').hide(100); } }); // document.getElementById("showLayerFurniture").addEventListener("click", function () { // if (document.getElementById("showLayerFurniture").checked) { // $('#boxFurniture').show(200); // } // else { // $('#boxFurniture').hide(100); // } // }); document.getElementById("applySurface").addEventListener("click", function () { $('#roomTools').hide(100); $('#panel').show(200); binder.remove(); delete binder; var id = $('#roomIndex').val(); //COLOR var data = $('#roomBackground').val(); ROOM[id].color = data; //ROOM NAME var roomName = $('#roomName').val(); if (roomName == 'None') roomName = ''; ROOM[id].name = roomName; //ROOM SURFACE var area = $('#roomSurface').val(); ROOM[id].surface = area; //SHOW SURFACE var show = document.querySelector("#seeArea").checked; ROOM[id].showSurface = show; //ACTION PARAM var action = document.querySelector('input[type=radio]:checked').value; ROOM[id].action = action; if (action == 'sub') ROOM[id].color = 'hatch'; if (action != 'sub' && data == 'hatch') ROOM[id].color = 'gradientNeutral'; $('#boxRoom').empty(); $('#boxSurface').empty(); editor.roomMaker(Rooms); $('#boxinfo').html('修改部件'); fonc_button('select_mode'); }); document.getElementById("resetRoomTools").addEventListener("click", function () { $('#roomTools').hide(100); $('#panel').show(200); binder.remove(); delete binder; $('#boxinfo').html('修改部件'); fonc_button('select_mode'); }); document.getElementById("wallTrash").addEventListener("click", function () { var wall = binder.wall; for (var k in WALLS) { if (isObjectsEquals(WALLS[k].child, wall)) WALLS[k].child = null; if (isObjectsEquals(WALLS[k].parent, wall)) {WALLS[k].parent = null;} } WALLS.splice(WALLS.indexOf(wall),1); $('#wallTools').hide(100); wall.graph.remove(); binder.graph.remove(); editor.architect(WALLS); rib(); mode = "select_mode"; $('#panel').show(200); }); var textEditorColorBtn = document.querySelectorAll('.textEditorColor'); for (var k = 0; k < textEditorColorBtn.length; k++) { textEditorColorBtn[k].addEventListener('click', function(){ document.getElementById('labelBox').style.color = this.style.color; }); } var zoomBtn = document.querySelectorAll('.zoom'); for (var k = 0; k < zoomBtn.length; k++) { zoomBtn[k].addEventListener("click", function () { lens = this.getAttribute('data-zoom'); zoom_maker(lens, 200, 50); }) } var roomColorBtn = document.querySelectorAll(".roomColor"); for (var k = 0; k < roomColorBtn.length; k++) { roomColorBtn[k].addEventListener("click", function () { var data = this.getAttribute('data-type'); $('#roomBackground').val(data); binder.attr({'fill':'url(#'+data+')'}); }); } var objTrashBtn = document.querySelectorAll(".objTrash"); for (var k = 0; k < objTrashBtn.length; k++) { objTrashBtn[k].addEventListener("click", function () { $('#objTools').hide('100'); var obj = binder.obj; obj.graph.remove(); OBJDATA.splice(OBJDATA.indexOf(obj), 1); fonc_button('select_mode'); $('#boxinfo').html('选择模式'); $('#panel').show('200'); binder.graph.remove(); delete binder; rib(); $('#panel').show('300'); }); } var dropdownMenu = document.querySelectorAll(".dropdown-menu li a"); for (var k = 0; k < dropdownMenu.length; k++) { dropdownMenu[k].addEventListener("click", function () { var selText = this.textContent; $(this).parents('.btn-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>'); if (selText != 'None') $('#roomName').val(selText); else $('#roomName').val(''); }); } // TRY MATRIX CALC FOR BBOX REAL COORDS WITH TRAS + ROT. function matrixCalc(el, message = false) { if (message) console.log("matrixCalc called by -> "+message); var m = el.getCTM(); var bb = el.getBBox(); var tpts = [ matrixXY(m,bb.x,bb.y), matrixXY(m,bb.x+bb.width,bb.y), matrixXY(m,bb.x+bb.width,bb.y+bb.height), matrixXY(m,bb.x,bb.y+bb.height)]; return tpts; } function matrixXY(m,x,y) { return { x: x * m.a + y * m.c + m.e, y: x * m.b + y * m.d + m.f }; } function realBboxShow(coords) { for (var k in coords) { debugPoint(coords[k]); } } function limitObj(equation, size, coords,message = false) { if (message) console.log(message) var Px = coords.x; var Py = coords.y; var Aq = equation.A; var Bq = equation.B; if (Aq == 'v') { var pos1 = {x: Px, y: Py - size/2}; var pos2 = {x: Px, y: Py + size/2}; } else if (Aq == 'h') { var pos1 = {x: Px - size/2, y: Py}; var pos2 = {x: Px + size/2, y: Py}; } else { var A = 1 + Aq*Aq; var B = (-2 * Px) + (2 * Aq * Bq) + (-2 * Py * Aq); var C = (Px*Px) + (Bq*Bq) - (2*Py*Bq) + (Py*Py) - (size*size)/4; // -N var Delta = (B*B) - (4*A*C); var posX1 = (-B-(Math.sqrt(Delta))) / (2*A); var posX2 = (-B+(Math.sqrt(Delta))) / (2*A); var pos1 = {x: posX1, y: (Aq * posX1) + Bq}; var pos2 = {x: posX2, y: (Aq * posX2) + Bq}; } return [pos1, pos2]; } function zoom_maker(lens, xmove, xview) { if (lens == 'zoomout' && zoom > 1 && zoom < 17) { zoom--; width_viewbox += xmove; var ratioWidthZoom = taille_w / width_viewbox; height_viewbox = width_viewbox * ratio_viewbox; myDiv = document.getElementById("scaleVal"); myDiv.style.width = 60*ratioWidthZoom+'px'; originX_viewbox = originX_viewbox - (xmove/2); originY_viewbox = originY_viewbox - (xmove/2 * ratio_viewbox); } if (lens == 'zoomin' && zoom < 14 && zoom > 0) { zoom++; var oldWidth = width_viewbox; width_viewbox -= xmove; var ratioWidthZoom = taille_w / width_viewbox; height_viewbox = width_viewbox * ratio_viewbox; myDiv = document.getElementById("scaleVal"); myDiv.style.width = 60*ratioWidthZoom+'px'; originX_viewbox = originX_viewbox + (xmove/2); originY_viewbox = originY_viewbox + (xmove/2 * ratio_viewbox); } factor = width_viewbox / taille_w; if (lens == 'zoomreset') { originX_viewbox = 0; originY_viewbox = 0; width_viewbox = taille_w; height_viewbox = taille_h; factor = 1; } if (lens == 'zoomright') { originX_viewbox += xview; } if (lens == 'zoomleft') { originX_viewbox -= xview; } if (lens == 'zoomtop') { originY_viewbox -= xview; } if (lens == 'zoombottom') { originY_viewbox += xview; } if (lens == 'zoomdrag') { originX_viewbox -= xmove; originY_viewbox -= xview; } $('svg').each(function() { $(this)[0].setAttribute('viewBox', originX_viewbox + ' ' + originY_viewbox + ' ' + width_viewbox + ' ' + height_viewbox) }); } tactile = false; function calcul_snap(event, state) { if (event.touches) { var touches = event.changedTouches; console.log("toto") eX = touches[0].pageX; eY = touches[0].pageY; tactile = true; } else { eX = event.pageX; eY = event.pageY; } x_mouse = (eX * factor) - (offset.left * factor) + originX_viewbox; y_mouse = (eY * factor) - (offset.top * factor) + originY_viewbox; if (state == 'on') { x_grid = Math.round(x_mouse / grid) * grid; y_grid = Math.round(y_mouse / grid) * grid; } if (state == 'off') { x_grid = x_mouse; y_grid = y_mouse; } return { x: x_grid, y: y_grid, xMouse: x_mouse, yMouse: y_mouse }; } minMoveGrid = function(mouse) { return Math.abs(Math.abs(pox - mouse.x) + Math.abs(poy - mouse.y)); } function intersectionOff() { if (typeof(lineIntersectionP) != 'undefined') { lineIntersectionP.remove(); delete lineIntersectionP; } } function intersection(snap, range = Infinity, except = ['']) { // ORANGE LINES 90° NEAR SEGMENT var bestEqPoint = {}; var equation = {}; bestEqPoint.distance = range; if (typeof(lineIntersectionP) != 'undefined') { lineIntersectionP.remove(); delete lineIntersectionP; } lineIntersectionP = qSVG.create("boxbind", "path", { // ORANGE TEMP LINE FOR ANGLE 0 90 45 -+ d: "", "stroke": "transparent", "stroke-width": 0.5, "stroke-opacity": "1", fill : "none" }); for (index = 0; index < WALLS.length; index++) { if (except.indexOf(WALLS[index]) == -1) { var x1 = WALLS[index].start.x; var y1 = WALLS[index].start.y; var x2 = WALLS[index].end.x; var y2 = WALLS[index].end.y; // EQUATION 90° of segment nf/nf-1 at X2/Y2 Point if (Math.abs(y2 - y1) == 0) { equation.C = 'v'; // C/D equation 90° Coef = -1/E equation.D = x1; equation.E = 'h'; // E/F equation Segment equation.F = y1; equation.G = 'v'; // G/H equation 90° Coef = -1/E equation.H = x2; equation.I = 'h'; // I/J equation Segment equation.J = y2; } else if (Math.abs(x2 - x1) == 0) { equation.C = 'h'; // C/D equation 90° Coef = -1/E equation.D = y1; equation.E = 'v'; // E/F equation Segment equation.F = x1; equation.G = 'h'; // G/H equation 90° Coef = -1/E equation.H = y2; equation.I = 'v'; // I/J equation Segment equation.J = x2; } else { equation.C = (x1 - x2) / (y2 - y1); equation.D = y1 - (x1 * equation.C); equation.E = (y2 - y1) / (x2 - x1); equation.F = y1 - (x1 * equation.E); equation.G = (x1 - x2) / (y2 - y1); equation.H = y2 - (x2 * equation.C); equation.I = (y2 - y1) / (x2 - x1); equation.J = y2 - (x2 * equation.E); } equation.A = equation.C; equation.B = equation.D; eq = qSVG.nearPointOnEquation(equation, snap); if (eq.distance < bestEqPoint.distance) { bestEqPoint.distance = eq.distance; bestEqPoint.node = index; bestEqPoint.x = eq.x; bestEqPoint.y = eq.y; bestEqPoint.x1 = x1; bestEqPoint.y1 = y1; bestEqPoint.x2 = x2; bestEqPoint.y2 = y2; bestEqPoint.way = 1; } equation.A = equation.E; equation.B = equation.F; eq = qSVG.nearPointOnEquation(equation, snap); if (eq.distance < bestEqPoint.distance) { bestEqPoint.distance = eq.distance; bestEqPoint.node = index; bestEqPoint.x = eq.x; bestEqPoint.y = eq.y; bestEqPoint.x1 = x1; bestEqPoint.y1 = y1; bestEqPoint.x2 = x2; bestEqPoint.y2 = y2; bestEqPoint.way = 1; } equation.A = equation.G; equation.B = equation.H; eq = qSVG.nearPointOnEquation(equation, snap); if (eq.distance < bestEqPoint.distance) { bestEqPoint.distance = eq.distance; bestEqPoint.node = index; bestEqPoint.x = eq.x; bestEqPoint.y = eq.y; bestEqPoint.x1 = x1; bestEqPoint.y1 = y1; bestEqPoint.x2 = x2; bestEqPoint.y2 = y2; bestEqPoint.way = 2; } equation.A = equation.I; equation.B = equation.J; eq = qSVG.nearPointOnEquation(equation, snap); if (eq.distance < bestEqPoint.distance) { bestEqPoint.distance = eq.distance; bestEqPoint.node = index; bestEqPoint.x = eq.x; bestEqPoint.y = eq.y; bestEqPoint.x1 = x1; bestEqPoint.y1 = y1; bestEqPoint.x2 = x2; bestEqPoint.y2 = y2; bestEqPoint.way = 2; } } // END INDEXOF EXCEPT TEST } // END LOOP FOR if (bestEqPoint.distance < range) { if (bestEqPoint.way == 2) { lineIntersectionP.attr({ // ORANGE TEMP LINE FOR ANGLE 0 90 45 -+ d: "M"+bestEqPoint.x1+","+bestEqPoint.y1+" L"+bestEqPoint.x2+","+bestEqPoint.y2+" L"+bestEqPoint.x+","+bestEqPoint.y, "stroke": "#d7ac57" }); } else { lineIntersectionP.attr({ // ORANGE TEMP LINE FOR ANGLE 0 90 45 -+ d: "M"+bestEqPoint.x2+","+bestEqPoint.y2+" L"+bestEqPoint.x1+","+bestEqPoint.y1+" L"+bestEqPoint.x+","+bestEqPoint.y, "stroke": "#d7ac57" }); } return ({ x: bestEqPoint.x, y: bestEqPoint.y, wall : WALLS[bestEqPoint.node], distance: bestEqPoint.distance }); } else { return false; } } function debugPoint(point, name, color = "#00ff00") { qSVG.create('boxDebug', 'circle', { cx: point.x, cy: point.y, r: 7, fill: color, id: name, class: "visu" }); } function showVertex() { for (var i=0; i < vertex.length; i++) { debugPoint(vertex[i], i); } } function showJunction() { for (var i=0; i < junction.length; i++) { debugPoint({x: junction[i].values[0], y: junction[i].values[1]}, i); } } $('.visu').mouseover(function() {console.log(this.id)}); var sizeText = []; var showAllSizeStatus = 0; function hideAllSize() { $('#boxbind').empty(); sizeText = []; showAllSizeStatus = 0; } function allRib() { $('#boxRib').empty(); for (var i in WALLS) { inWallRib(WALLS[i], 'all'); } } function inWallRib(wall, option = false) { if (!option) $('#boxRib').empty(); ribMaster = []; ribMaster.push([]); ribMaster.push([]); var inter; var distance; var cross; var angleTextValue = wall.angle*(180/Math.PI); var objWall = editor.objFromWall(wall); // LIST OBJ ON EDGE ribMaster[0].push({wall: wall, crossObj: false, side : 'up', coords: wall.coords[0], distance: 0}); ribMaster[1].push({wall: wall, crossObj: false, side : 'down', coords: wall.coords[1], distance: 0}); for (var ob in objWall) { var objTarget = objWall[ob]; objTarget.up = [ qSVG.nearPointOnEquation(wall.equations.up, objTarget.limit[0]), qSVG.nearPointOnEquation(wall.equations.up, objTarget.limit[1]) ]; objTarget.down = [ qSVG.nearPointOnEquation(wall.equations.down, objTarget.limit[0]), qSVG.nearPointOnEquation(wall.equations.down, objTarget.limit[1]) ]; distance = qSVG.measure(wall.coords[0], objTarget.up[0]) / meter; ribMaster[0].push({wall: objTarget, crossObj: ob, side : 'up', coords: objTarget.up[0], distance: distance.toFixed(2)}); distance = qSVG.measure(wall.coords[0], objTarget.up[1]) / meter; ribMaster[0].push({wall: objTarget, crossObj: ob, side : 'up', coords: objTarget.up[1], distance: distance.toFixed(2)}); distance = qSVG.measure(wall.coords[1], objTarget.down[0]) / meter; ribMaster[1].push({wall: objTarget, crossObj: ob, side : 'down', coords: objTarget.down[0], distance: distance.toFixed(2)}); distance = qSVG.measure(wall.coords[1], objTarget.down[1]) / meter; ribMaster[1].push({wall: objTarget, crossObj: ob, side : 'down', coords: objTarget.down[1], distance: distance.toFixed(2)}); } distance = qSVG.measure(wall.coords[0], wall.coords[3]) / meter; ribMaster[0].push({wall: objTarget, crossObj: false, side : 'up', coords: wall.coords[3], distance: distance}); distance = qSVG.measure(wall.coords[1], wall.coords[2]) / meter; ribMaster[1].push({wall: objTarget, crossObj: false, side : 'down', coords: wall.coords[2], distance: distance}); ribMaster[0].sort(function(a,b) { return (a.distance - b.distance).toFixed(2); }); ribMaster[1].sort(function(a,b) { return (a.distance - b.distance).toFixed(2); }); for (var t in ribMaster) { for (var n = 1; n < ribMaster[t].length; n++) { var found = true; var shift = -5; var valueText = Math.abs(ribMaster[t][n-1].distance - ribMaster[t][n].distance); var angleText = angleTextValue; if (found) { if (ribMaster[t][n-1].side == 'down') {shift = -shift+10;} if (angleText > 89 || angleText < -89) { angleText-=180; if (ribMaster[t][n-1].side == 'down') {shift = -5;} else shift = -shift+10; } sizeText[n] = document.createElementNS('http://www.w3.org/2000/svg', 'text'); var startText = qSVG.middle(ribMaster[t][n-1].coords.x, ribMaster[t][n-1].coords.y, ribMaster[t][n].coords.x, ribMaster[t][n].coords.y); sizeText[n].setAttributeNS(null, 'x', startText.x); sizeText[n].setAttributeNS(null, 'y', (startText.y)+shift); sizeText[n].setAttributeNS(null, 'text-anchor', 'middle'); sizeText[n].setAttributeNS(null, 'font-family', 'roboto'); sizeText[n].setAttributeNS(null, 'stroke', '#ffffff'); sizeText[n].textContent = valueText.toFixed(2); if (sizeText[n].textContent < 1) { sizeText[n].setAttributeNS(null, 'font-size', '0.8em'); sizeText[n].textContent = sizeText[n].textContent.substring(1, sizeText[n].textContent.length); } else sizeText[n].setAttributeNS(null, 'font-size', '1em'); sizeText[n].setAttributeNS(null, 'stroke-width', '0.27px'); sizeText[n].setAttributeNS(null, 'fill', '#666666'); sizeText[n].setAttribute("transform", "rotate("+angleText+" "+startText.x+","+(startText.y)+")"); $('#boxRib').append(sizeText[n]); } } } } function rib(shift = 5) { // return false; var ribMaster = []; ribMaster.push([]); ribMaster.push([]); var inter; var distance; var cross; for (var i in WALLS) { if (WALLS[i].equations.base) { ribMaster[0].push([]); ribMaster[0][i].push({wallIndex: i, crossEdge: i, side : 'up', coords: WALLS[i].coords[0], distance: 0}); ribMaster[1].push([]); ribMaster[1][i].push({wallIndex: i, crossEdge: i, side : 'down', coords: WALLS[i].coords[1], distance: 0}); for (var p in WALLS) { if (i != p && WALLS[p].equations.base) { cross = qSVG.intersectionOfEquations(WALLS[i].equations.base, WALLS[p].equations.base, "object"); if (qSVG.btwn(cross.x, WALLS[i].start.x, WALLS[i].end.x, 'round') && qSVG.btwn(cross.y, WALLS[i].start.y, WALLS[i].end.y, 'round')) { inter = qSVG.intersectionOfEquations(WALLS[i].equations.up, WALLS[p].equations.up, "object"); if (qSVG.btwn(inter.x, WALLS[i].coords[0].x, WALLS[i].coords[3].x, 'round') && qSVG.btwn(inter.y, WALLS[i].coords[0].y, WALLS[i].coords[3].y, 'round') && qSVG.btwn(inter.x, WALLS[p].coords[0].x, WALLS[p].coords[3].x, 'round') && qSVG.btwn(inter.y, WALLS[p].coords[0].y, WALLS[p].coords[3].y, 'round')){ distance = qSVG.measure(WALLS[i].coords[0], inter) / meter; ribMaster[0][i].push({wallIndex: i, crossEdge: p, side : 'up', coords: inter, distance: distance.toFixed(2)}); } inter = qSVG.intersectionOfEquations(WALLS[i].equations.up, WALLS[p].equations.down, "object"); if (qSVG.btwn(inter.x, WALLS[i].coords[0].x, WALLS[i].coords[3].x, 'round') && qSVG.btwn(inter.y, WALLS[i].coords[0].y, WALLS[i].coords[3].y, 'round') && qSVG.btwn(inter.x, WALLS[p].coords[1].x, WALLS[p].coords[2].x, 'round') && qSVG.btwn(inter.y, WALLS[p].coords[1].y, WALLS[p].coords[2].y, 'round')){ distance = qSVG.measure(WALLS[i].coords[0], inter) / meter; ribMaster[0][i].push({wallIndex: i, crossEdge: p, side : 'up', coords: inter, distance: distance.toFixed(2)}); } inter = qSVG.intersectionOfEquations(WALLS[i].equations.down, WALLS[p].equations.up, "object"); if (qSVG.btwn(inter.x, WALLS[i].coords[1].x, WALLS[i].coords[2].x, 'round') && qSVG.btwn(inter.y, WALLS[i].coords[1].y, WALLS[i].coords[2].y, 'round') && qSVG.btwn(inter.x, WALLS[p].coords[0].x, WALLS[p].coords[3].x, 'round') && qSVG.btwn(inter.y, WALLS[p].coords[0].y, WALLS[p].coords[3].y, 'round')){ distance = qSVG.measure(WALLS[i].coords[1], inter) / meter; ribMaster[1][i].push({wallIndex: i, crossEdge: p, side : 'down', coords: inter, distance: distance.toFixed(2)}); } inter = qSVG.intersectionOfEquations(WALLS[i].equations.down, WALLS[p].equations.down, "object"); if (qSVG.btwn(inter.x, WALLS[i].coords[1].x, WALLS[i].coords[2].x, 'round') && qSVG.btwn(inter.y, WALLS[i].coords[1].y, WALLS[i].coords[2].y, 'round') && qSVG.btwn(inter.x, WALLS[p].coords[1].x, WALLS[p].coords[2].x, 'round') && qSVG.btwn(inter.y, WALLS[p].coords[1].y, WALLS[p].coords[2].y, 'round')){ distance = qSVG.measure(WALLS[i].coords[1], inter) / meter; ribMaster[1][i].push({wallIndex: i, crossEdge: p, side : 'down', coords: inter, distance: distance.toFixed(2)}); } } } } distance = qSVG.measure(WALLS[i].coords[0], WALLS[i].coords[3]) / meter; ribMaster[0][i].push({wallIndex: i, crossEdge: i, side : 'up', coords: WALLS[i].coords[3], distance: distance.toFixed(2)}); distance = qSVG.measure(WALLS[i].coords[1], WALLS[i].coords[2]) / meter; ribMaster[1][i].push({wallIndex: i, crossEdge: i, side : 'down', coords: WALLS[i].coords[2], distance: distance.toFixed(2)}); } } for (var a in ribMaster[0]) { ribMaster[0][a].sort(function(a,b) { return (a.distance - b.distance).toFixed(2); }); } for (var a in ribMaster[1]) { ribMaster[1][a].sort(function(a,b) { return (a.distance - b.distance).toFixed(2); }); } var sizeText = []; if (shift == 5) $('#boxRib').empty(); for (var t in ribMaster) { for (var a in ribMaster[t]) { for (var n = 1; n < ribMaster[t][a].length; n++) { if (ribMaster[t][a][n-1].wallIndex == ribMaster[t][a][n].wallIndex) { var edge = ribMaster[t][a][n].wallIndex; var found = true; var valueText = Math.abs(ribMaster[t][a][n-1].distance - ribMaster[t][a][n].distance); // CLEAR TOO LITTLE VALUE if (valueText < 0.15) { found = false; } // CLEAR (thick) BETWEEN CROSS EDGE if (found && ribMaster[t][a][n-1].crossEdge == ribMaster[t][a][n].crossEdge && ribMaster[t][a][n].crossEdge != ribMaster[t][a][n].wallIndex){ found= false; } // CLEAR START INTO EDGE if (found && ribMaster[t][a].length > 2 && n==1) { var polygon = []; for (var pp = 0; pp < 4; pp++) { polygon.push({x: WALLS[ribMaster[t][a][n].crossEdge].coords[pp].x, y: WALLS[ribMaster[t][a][n].crossEdge].coords[pp].y}); // FOR Z } if (qSVG.rayCasting(ribMaster[t][a][0].coords, polygon)) { found = false; } } // CLEAR END INTO EDGE if (found && ribMaster[t][a].length > 2 && n == ribMaster[t][a].length-1){ var polygon = []; for (var pp = 0; pp < 4; pp++) { polygon.push({x: WALLS[ribMaster[t][a][n-1].crossEdge].coords[pp].x, y: WALLS[ribMaster[t][a][n-1].crossEdge].coords[pp].y}); // FOR Z } if (qSVG.rayCasting(ribMaster[t][a][ribMaster[t][a].length-1].coords, polygon)) { found = false; } } if (found) { var angleText = WALLS[ribMaster[t][a][n].wallIndex].angle*(180/Math.PI); var shiftValue = -shift; if (ribMaster[t][a][n-1].side == 'down') {shiftValue = -shiftValue+10;} if (angleText > 90 || angleText < -89) { angleText-=180; if (ribMaster[t][a][n-1].side == 'down') {shiftValue = -shift;} else shiftValue = -shiftValue+10; } sizeText[n] = document.createElementNS('http://www.w3.org/2000/svg', 'text'); var startText = qSVG.middle(ribMaster[t][a][n-1].coords.x, ribMaster[t][a][n-1].coords.y, ribMaster[t][a][n].coords.x, ribMaster[t][a][n].coords.y); sizeText[n].setAttributeNS(null, 'x', startText.x); sizeText[n].setAttributeNS(null, 'y', (startText.y)+(shiftValue)); sizeText[n].setAttributeNS(null, 'text-anchor', 'middle'); sizeText[n].setAttributeNS(null, 'font-family', 'roboto'); sizeText[n].setAttributeNS(null, 'stroke', '#ffffff'); sizeText[n].textContent = valueText.toFixed(2); if (sizeText[n].textContent < 1) { sizeText[n].setAttributeNS(null, 'font-size', '0.73em'); sizeText[n].textContent = sizeText[n].textContent.substring(1, sizeText[n].textContent.length); } else sizeText[n].setAttributeNS(null, 'font-size', '0.9em'); sizeText[n].setAttributeNS(null, 'stroke-width', '0.2px'); sizeText[n].setAttributeNS(null, 'fill', '#555555'); sizeText[n].setAttribute("transform", "rotate("+angleText+" "+startText.x+","+(startText.y)+")"); $('#boxRib').append(sizeText[n]); } } } } } } function cursor(tool) { if (tool == 'grab') tool = "url('https://wiki.openmrs.org/s/en_GB/7502/b9217199c27dd617c8d51f6186067d7767c5001b/_/images/icons/emoticons/add.png') 8 8, auto"; if (tool == 'scissor') tool = "url('https://maxcdn.icons8.com/windows10/PNG/64/Hands/hand_scissors-64.png'), auto"; if (tool == 'trash') tool = "url('https://cdn4.iconfinder.com/data/icons/common-toolbar/36/Cancel-32.png'), auto"; if (tool == 'validation') tool = "url('https://images.fatguymedia.com/wp-content/uploads/2015/09/check.png'), auto"; $('#lin').css('cursor',tool); } function fullscreen() { // go full-screen var i = document.body; if (i.requestFullscreen) { i.requestFullscreen(); } else if (i.webkitRequestFullscreen) { i.webkitRequestFullscreen(); } else if (i.mozRequestFullScreen) { i.mozRequestFullScreen(); } else if (i.msRequestFullscreen) { i.msRequestFullscreen(); } } function outFullscreen() { if(document.exitFullscreen) { document.exitFullscreen(); } else if(document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if(document.webkitExitFullscreen) { document.webkitExitFullscreen(); } } document.addEventListener("fullscreenchange", function() { if ( !document.fullscreenElement && !document.webkitFullscreenElement && !document.mozFullScreenElement && !document.msFullscreenElement) { $('#nofull_mode').display='none';$('#full_mode').show(); } }); function raz_button() { $('#rect_mode').removeClass('btn-success'); $('#rect_mode').addClass('btn-default'); $('#select_mode').removeClass('btn-success'); $('#select_mode').addClass('btn-default'); $('#line_mode').removeClass('btn-success'); $('#line_mode').addClass('btn-default'); $('#partition_mode').removeClass('btn-success'); $('#partition_mode').addClass('btn-default'); $('#door_mode').removeClass('btn-success'); $('#door_mode').addClass('btn-default'); $('#node_mode').removeClass('btn-success'); $('#node_mode').addClass('btn-default'); $('#text_mode').removeClass('btn-success'); $('#text_mode').addClass('btn-default'); $('#room_mode').removeClass('btn-success'); $('#room_mode').addClass('btn-default'); $('#distance_mode').removeClass('btn-success'); $('#distance_mode').addClass('btn-default'); $('#object_mode').removeClass('btn-success'); $('#object_mode').addClass('btn-default'); $('#stair_mode').removeClass('btn-success'); $('#stair_mode').addClass('btn-default'); } function fonc_button(modesetting ,option) { save(); $('.sub').hide(); raz_button(); if (option != 'simpleStair') { $('#' + modesetting).removeClass('btn-default'); $('#' + modesetting).addClass('btn-success'); } mode = modesetting; modeOption = option; if (typeof(lineIntersectionP) != 'undefined') { lineIntersectionP.remove(); delete lineIntersectionP; } } $('#distance_mode').click(function() { $('#lin').css('cursor', 'crosshair'); $('#boxinfo').html('添加距离测量'); fonc_button('distance_mode'); }); $('#room_mode').click(function() { $('#lin').css('cursor', 'pointer'); $('#boxinfo').html('修改房间信息'); fonc_button('room_mode'); }); $('#select_mode').click(function() { $('#boxinfo').html('选择模式'); if (typeof(binder) != 'undefined') { binder.remove(); delete binder; } fonc_button('select_mode'); }); $('#line_mode').click(function() { $('#lin').css('cursor', 'crosshair'); $('#boxinfo').html('创建墙面'); multi = 0; action = 0; // snap = calcul_snap(event, grid_snap); // // pox = snap.x; // poy = snap.y; fonc_button('line_mode'); }); $('#partition_mode').click(function() { $('#lin').css('cursor', 'crosshair'); $('#boxinfo').html('区域创建)'); multi = 0; fonc_button('partition_mode'); }); $('#rect_mode').click(function() { $('#lin').css('cursor', 'crosshair'); $('#boxinfo').html('创建部件'); fonc_button('rect_mode'); }); $('.door').click(function() { $('#lin').css('cursor', 'crosshair'); $('#boxinfo').html('加一扇门'); $('#door_list').hide(200); fonc_button('door_mode', this.id); }); $('.window').click(function() { $('#lin').css('cursor', 'crosshair'); $('#boxinfo').html('加一扇窗'); $('#door_list').hide(200); $('#window_list').hide(200); fonc_button('door_mode', this.id); }); $('.object').click(function() { cursor('move'); $('#boxinfo').html('添加对象'); fonc_button('object_mode', this.id); }); $('#stair_mode').click(function() { cursor('move'); $('#boxinfo').html('添加楼梯'); fonc_button('object_mode', 'simpleStair'); }); $('#node_mode').click(function() { $('#boxinfo').html('修改墙面<br/><span style=\"font-size:0.7em\">提示:切割房间的墙壁可以取消其配置</span>'); fonc_button('node_mode'); }); $('#text_mode').click(function() { $('#boxinfo').html('添加文字<br/><span style=\"font-size:0.7em\">将光标移动到所需位置并键入文本。</span>'); fonc_button('text_mode'); }); $('#grid_mode').click(function() { if (grid_snap == 'on') { grid_snap = 'off'; $('#boxinfo').html('关闭网格'); $('#grid_mode').removeClass('btn-success'); $('#grid_mode').addClass('btn-warning'); $('#grid_mode').html('GRID OFF'); $('#boxgrid').css('opacity', '0.5'); } else { grid_snap = 'on'; $('#boxinfo').html('打开网格'); $('#grid_mode').removeClass('btn-warning'); $('#grid_mode').addClass('btn-success'); $('#grid_mode').html('GRID ON <i class="fa fa-th" aria-hidden="true"></i>'); $('#boxgrid').css('opacity', '1'); } }); // RETURN PATH(s) ARRAY FOR OBJECT + PROPERTY params => bindBox (false = open sideTool), move, resize, rotate function carpentryCalc(classObj, typeObj, sizeObj, thickObj, dividerObj = 10) { var construc = []; construc.params = {}; construc.params.bindBox = false; construc.params.move = false; construc.params.resize = false; construc.params.resizeLimit = {}; construc.params.resizeLimit.width = {min: false, max: false}; construc.params.resizeLimit.height = {min: false, max: false}; construc.params.rotate = false; if (classObj == 'socle') { construc.push({'path':"M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+thickObj/2+" L "+sizeObj/2+","+thickObj/2+" L "+sizeObj/2+","+(-thickObj/2)+" Z", 'fill': "#5cba79", 'stroke': "#5cba79", 'strokeDashArray': ''}); } if (classObj == 'doorWindow') { if (typeObj == 'simple') { construc.push({'path':"M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+thickObj/2+" L "+sizeObj/2+","+thickObj/2+" L "+sizeObj/2+","+(-thickObj/2)+" Z", 'fill': "#ccc", 'stroke': "none", 'strokeDashArray': ''}); construc.push({'path': "M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+(-sizeObj-thickObj/2)+" A"+sizeObj+","+sizeObj+" 0 0,1 "+sizeObj/2+","+(-thickObj/2), 'fill': "none", 'stroke': colorWall, 'strokeDashArray': ''}); construc.params.resize = true; construc.params.resizeLimit.width = {min:40, max:120}; } if (typeObj == 'double') { construc.push({'path':"M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+thickObj/2+" L "+sizeObj/2+","+thickObj/2+" L "+sizeObj/2+","+(-thickObj/2)+" Z", 'fill': "#ccc", 'stroke': "none", 'strokeDashArray': ''}); construc.push({'path': "M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+(-sizeObj/2-thickObj/2)+" A"+sizeObj/2+","+sizeObj/2+" 0 0,1 0,"+(-thickObj/2), 'fill': "none", 'stroke': colorWall, 'strokeDashArray': ''}); construc.push({'path': "M "+(sizeObj/2)+","+(-thickObj/2)+" L "+(sizeObj/2)+","+(-sizeObj/2-thickObj/2)+" A"+sizeObj/2+","+sizeObj/2+" 0 0,0 0,"+(-thickObj/2), 'fill': "none", 'stroke': colorWall, 'strokeDashArray': ''}); construc.params.resize = true; construc.params.resizeLimit.width = {min:40, max:160}; } if (typeObj == 'pocket') { construc.push({'path':"M "+(-sizeObj/2)+","+(-(thickObj/2)-4)+" L "+(-sizeObj/2)+","+thickObj/2+" L "+sizeObj/2+","+thickObj/2+" L "+sizeObj/2+","+(-(thickObj/2)-4)+" Z", 'fill': "#ccc", 'stroke': "none", 'strokeDashArray': 'none'}); construc.push({'path':"M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+thickObj/2+" M "+(sizeObj/2)+","+(thickObj/2)+" L "+(sizeObj/2)+","+(-thickObj/2), 'fill': "none", 'stroke': "#494646", 'strokeDashArray': '5 5'}); construc.push({'path':"M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+(-thickObj/2-5)+" L "+(+sizeObj/2)+","+(-thickObj/2-5)+" L "+(+sizeObj/2)+","+(-thickObj/2)+" Z", 'fill': "url(#hatch)", 'stroke': "#494646", 'strokeDashArray': ''}); construc.params.resize = true; construc.params.resizeLimit.width = {min:60, max:200}; } if (typeObj == 'aperture') { construc.push({'path':"M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+thickObj/2+" L "+sizeObj/2+","+thickObj/2+" L "+sizeObj/2+","+(-thickObj/2)+" Z", 'fill': "#ccc", 'stroke': "#494646", 'strokeDashArray': '5,5'}); construc.push({'path':"M "+(-sizeObj/2)+","+(-(thickObj/2))+" L "+(-sizeObj/2)+","+thickObj/2+" L "+((-sizeObj/2)+5)+","+thickObj/2+" L "+((-sizeObj/2)+5)+","+(-(thickObj/2))+" Z", 'fill': "none", 'stroke': "#494646", 'strokeDashArray': 'none'}); construc.push({'path':"M "+((sizeObj/2)-5)+","+(-(thickObj/2))+" L "+((sizeObj/2)-5)+","+thickObj/2+" L "+(sizeObj/2)+","+thickObj/2+" L "+(sizeObj/2)+","+(-(thickObj/2))+" Z", 'fill': "none", 'stroke': "#494646", 'strokeDashArray': 'none'}); construc.params.resize = true; construc.params.resizeLimit.width = {min:40, max:500}; } if (typeObj == 'fix') { construc.push({'path':"M "+(-sizeObj/2)+",-2 L "+(-sizeObj/2)+",2 L "+sizeObj/2+",2 L "+sizeObj/2+",-2 Z", 'fill': "#ccc", 'stroke': "none", 'strokeDashArray': ''}); construc.push({'path':"M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+thickObj/2+" M "+sizeObj/2+","+thickObj/2+" L "+sizeObj/2+","+(-thickObj/2), 'fill': "none", 'stroke': "#ccc", 'strokeDashArray': ''}); construc.params.resize = true; construc.params.resizeLimit.width = {min:30, max:300}; } if (typeObj == 'flap') { construc.push({'path':"M "+(-sizeObj/2)+",-2 L "+(-sizeObj/2)+",2 L "+sizeObj/2+",2 L "+sizeObj/2+",-2 Z", 'fill': "#ccc", 'stroke': "none", 'strokeDashArray': ''}); construc.push({'path':"M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+thickObj/2+" M "+sizeObj/2+","+thickObj/2+" L "+sizeObj/2+","+(-thickObj/2), 'fill': "none", 'stroke': "#ccc", 'strokeDashArray': ''}); construc.push({'path': "M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+((-sizeObj/2)+((sizeObj)*0.866))+","+((-sizeObj/2)-(thickObj/2))+" A"+sizeObj+","+sizeObj+" 0 0,1 "+sizeObj/2+","+(-thickObj/2), 'fill': "none", 'stroke': colorWall, 'strokeDashArray': ''}); construc.params.resize = true; construc.params.resizeLimit.width = {min:20, max:100}; } if (typeObj == 'twin') { construc.push({'path':"M "+(-sizeObj/2)+",-2 L "+(-sizeObj/2)+",2 L "+sizeObj/2+",2 L "+sizeObj/2+",-2 Z", 'fill': "#ccc", 'stroke': "none", 'strokeDashArray': ''}); construc.push({'path':"M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+thickObj/2+" M "+sizeObj/2+","+thickObj/2+" L "+sizeObj/2+","+(-thickObj/2), 'fill': "none", 'stroke': "#ccc", 'strokeDashArray': ''}); construc.push({'path': "M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+((-sizeObj/2)+((sizeObj/2)*0.866))+","+(-sizeObj/4-thickObj/2)+" A"+sizeObj/2+","+sizeObj/2+" 0 0,1 0,"+(-thickObj/2), 'fill': "none", 'stroke': colorWall, 'strokeDashArray': ''}); construc.push({'path': "M "+(sizeObj/2)+","+(-thickObj/2)+" L "+((sizeObj/2)+((-sizeObj/2)*0.866))+","+(-sizeObj/4-thickObj/2)+" A"+sizeObj/2+","+sizeObj/2+" 0 0,0 0,"+(-thickObj/2), 'fill': "none", 'stroke': colorWall, 'strokeDashArray': ''}); construc.params.resize = true; construc.params.resizeLimit.width = {min:40, max:200}; } if (typeObj == 'bay') { construc.push({'path':"M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+thickObj/2+" M "+sizeObj/2+","+thickObj/2+" L "+sizeObj/2+","+(-thickObj/2), 'fill': "none", 'stroke': "#ccc", 'strokeDashArray': ''}); construc.push({'path':"M "+(-sizeObj/2)+",-2 L "+(-sizeObj/2)+",0 L 2,0 L 2,2 L 3,2 L 3,-2 Z", 'fill': "#ccc", 'stroke': "none", 'strokeDashArray': ''}); construc.push({'path':"M -2,1 L -2,3 L "+sizeObj/2+",3 L "+sizeObj/2+",1 L -1,1 L -1,-1 L -2,-1 Z", 'fill': "#ccc", 'stroke': "none", 'strokeDashArray': ''}); construc.params.resize = true; construc.params.resizeLimit.width = {min:60, max:300}; } } if (classObj == 'measure') { construc.params.bindBox = true; construc.push({'path':"M-"+(sizeObj/2)+",0 l10,-10 l0,8 l"+(sizeObj-20)+",0 l0,-8 l10,10 l-10,10 l0,-8 l-"+(sizeObj-20)+",0 l0,8 Z", 'fill': "#729eeb", 'stroke': "none", 'strokeDashArray': ''}); } if (classObj == 'boundingBox') { construc.push({'path':"M"+(-sizeObj/2-10)+","+(-thickObj/2-10)+" L"+(sizeObj/2+10)+","+(-thickObj/2-10)+" L"+(sizeObj/2+10)+","+(thickObj/2+10)+" L"+(-sizeObj/2-10)+","+(thickObj/2+10)+" Z", 'fill':'none', 'stroke':"#aaa", 'strokeDashArray': ''}); // construc.push({'path':"M"+dividerObj[0].x+","+dividerObj[0].y+" L"+dividerObj[1].x+","+dividerObj[1].y+" L"+dividerObj[2].x+","+dividerObj[2].y+" L"+dividerObj[3].x+","+dividerObj[3].y+" Z", 'fill':'none', 'stroke':"#000", 'strokeDashArray': ''}); } //typeObj = color dividerObj = text if (classObj == 'text') { construc.params.bindBox = true; construc.params.move = true; construc.params.rotate = true; construc.push({'text': dividerObj.text, 'x': '0', 'y':'0', 'fill': typeObj, 'stroke': typeObj, 'fontSize': dividerObj.size+'px',"strokeWidth": "0px"}); } if (classObj == 'stair') { construc.params.bindBox = true; construc.params.move = true; construc.params.resize = true; construc.params.rotate = true; construc.params.width = 60; construc.params.height = 180; if (typeObj == 'simpleStair') { construc.push({'path':"M "+(-sizeObj/2)+","+(-thickObj/2)+" L "+(-sizeObj/2)+","+thickObj/2+" L "+sizeObj/2+","+thickObj/2+" L "+sizeObj/2+","+(-thickObj/2)+" Z", 'fill': "#fff", 'stroke': "#000", 'strokeDashArray': ''}); var heightStep = thickObj / (dividerObj); for (var i =1; i < dividerObj+1; i++) { construc.push({'path':"M "+(-sizeObj/2)+","+((-thickObj/2)+(i*heightStep))+" L "+(sizeObj/2)+","+((-thickObj/2)+(i*heightStep)), 'fill': "none", 'stroke': "#000", 'strokeDashArray': 'none'}); } construc.params.resizeLimit.width = {min:40, max:200}; construc.params.resizeLimit.height = {min:40, max:400}; } } if (classObj == 'energy') { construc.params.bindBox = true; construc.params.move = true; construc.params.resize = false; construc.params.rotate = false; if (typeObj == 'gtl') { construc.push({'path': "m -20,-20 l 40,0 l0,40 l-40,0 Z", 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'text': "GTL", 'x': '0', 'y':'5', 'fill': "#333333", 'stroke': "none", 'fontSize': '0.9em',"strokeWidth": "0.4px"}); construc.params.width = 40; construc.params.height = 40; construc.family = 'stick'; } if (typeObj == 'switch') { construc.push({'path': qSVG.circlePath(0, 0, 16), 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': qSVG.circlePath(-2, 4, 5), 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m 0,0 5,-9", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.params.width = 36; construc.params.height = 36; construc.family = 'stick'; } if (typeObj == 'doubleSwitch') { construc.push({'path': qSVG.circlePath(0, 0, 16), 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': qSVG.circlePath(0,0, 4), 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m 2,-3 5,-8 3,2", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m -2,3 -5,8 -3,-2", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.params.width = 36; construc.params.height = 36; construc.family = 'stick'; } if (typeObj == 'dimmer') { construc.push({'path': qSVG.circlePath(0, 0, 16), 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': qSVG.circlePath(-2, 4, 5), 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m 0,0 5,-9", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "M -2,-6 L 10,-4 L-2,-2 Z", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.params.width = 36; construc.params.height = 36; construc.family = 'stick'; } if (typeObj == 'plug') { construc.push({'path':qSVG.circlePath(0, 0, 16), 'fill': "#fff", 'stroke': "#000", 'strokeDashArray': ''}); construc.push({'path': "M 10,-6 a 10,10 0 0 1 -5,8 10,10 0 0 1 -10,0 10,10 0 0 1 -5,-8", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m 0,3 v 7", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m -10,4 h 20", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.params.width = 36; construc.params.height = 36; construc.family = 'stick'; } if (typeObj == 'plug20') { construc.push({'path':qSVG.circlePath(0, 0, 16), 'fill': "#fff", 'stroke': "#000", 'strokeDashArray': ''}); construc.push({'path': "M 10,-6 a 10,10 0 0 1 -5,8 10,10 0 0 1 -10,0 10,10 0 0 1 -5,-8", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m 0,3 v 7", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m -10,4 h 20", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'text': "20A", 'x': '0', 'y':'-5', 'fill': "#333333", 'stroke': "none", 'fontSize': '0.65em',"strokeWidth": "0.4px"}); construc.params.width = 36; construc.params.height = 36; construc.family = 'stick'; } if (typeObj == 'plug32') { construc.push({'path':qSVG.circlePath(0, 0, 16), 'fill': "#fff", 'stroke': "#000", 'strokeDashArray': ''}); construc.push({'path': "M 10,-6 a 10,10 0 0 1 -5,8 10,10 0 0 1 -10,0 10,10 0 0 1 -5,-8", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m 0,3 v 7", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m -10,4 h 20", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'text': "32A", 'x': '0', 'y':'-5', 'fill': "#333333", 'stroke': "none", 'fontSize': '0.65em',"strokeWidth": "0.4px"}); construc.params.width = 36; construc.params.height = 36; construc.family = 'stick'; } if (typeObj == 'roofLight') { construc.push({'path':qSVG.circlePath(0, 0, 16), 'fill': "#fff", 'stroke': "#000", 'strokeDashArray': ''}); construc.push({'path': "M -8,-8 L 8,8 M -8,8 L 8,-8", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.params.width = 36; construc.params.height = 36; construc.family = 'free'; } if (typeObj == 'wallLight') { construc.push({'path':qSVG.circlePath(0, 0, 16), 'fill': "#fff", 'stroke': "#000", 'strokeDashArray': ''}); construc.push({'path': "M -8,-8 L 8,8 M -8,8 L 8,-8", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "M -10,10 L 10,10", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.params.width = 36; construc.params.height = 36; construc.family = 'stick'; } if (typeObj == 'www') { construc.push({'path': "m -20,-20 l 40,0 l0,40 l-40,0 Z", 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'text': "@", 'x': '0', 'y':'4', 'fill': "#333333", 'stroke': "none", 'fontSize': '1.2em',"strokeWidth": "0.4px"}); construc.params.width = 40; construc.params.height = 40; construc.family = 'free'; } if (typeObj == 'rj45') { construc.push({'path':qSVG.circlePath(0, 0, 16), 'fill': "#fff", 'stroke': "#000", 'strokeDashArray': ''}); construc.push({'path': "m-10,5 l0,-10 m20,0 l0,10", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m 0,5 v 7", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m -10,5 h 20", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'text': "RJ45", 'x': '0', 'y':'-5', 'fill': "#333333", 'stroke': "none", 'fontSize': '0.5em',"strokeWidth": "0.4px"}); construc.params.width = 36; construc.params.height = 36; construc.family = 'stick'; } if (typeObj == 'tv') { construc.push({'path':qSVG.circlePath(0, 0, 16), 'fill': "#fff", 'stroke': "#000", 'strokeDashArray': ''}); construc.push({'path': "m-10,5 l0-10 m20,0 l0,10", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m-7,-5 l0,7 l14,0 l0,-7", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m 0,5 v 7", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m -10,5 h 20", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'text': "TV", 'x': '0', 'y':'-5', 'fill': "#333333", 'stroke': "none", 'fontSize': '0.5em',"strokeWidth": "0.4px"}); construc.params.width = 36; construc.params.height = 36; construc.family = 'stick'; } if (typeObj == 'heater') { construc.push({'path':qSVG.circlePath(0, 0, 16), 'fill': "#fff", 'stroke': "#000", 'strokeDashArray': ''}); construc.push({'path': "m-15,-4 l30,0", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m-14,-8 l28,0", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m-11,-12 l22,0", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m-16,0 l32,0", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m-15,4 l30,0", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m-14,8 l28,0", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "m-11,12 l22,0", 'fill': "none", 'stroke': "#333", 'strokeDashArray': ''}); construc.params.width = 36; construc.params.height = 36; construc.family = 'stick'; } if (typeObj == 'radiator') { construc.push({'path': "m -20,-10 l 40,0 l0,20 l-40,0 Z", 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "M -15,-10 L -15,10", 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "M -10,-10 L -10,10", 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "M -5,-10 L -5,10", 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "M -0,-10 L -0,10", 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "M 5,-10 L 5,10", 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "M 10,-10 L 10,10", 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.push({'path': "M 15,-10 L 15,10", 'fill': "#fff", 'stroke': "#333", 'strokeDashArray': ''}); construc.params.width = 40; construc.params.height = 20; construc.family = 'stick'; } } if (classObj == 'furniture') { construc.params.bindBox = true; construc.params.move = true; construc.params.resize = true; construc.params.rotate = true; } return construc; }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { if (n === 1) return 1; return 5; } root.ng.common.locales['so'] = [ 'so', [['sn.', 'gn.'], u, u], u, [ ['A', 'I', 'T', 'A', 'Kh', 'J', 'S'], ['Axd', 'Isn', 'Tal', 'Arb', 'Kha', 'Jim', 'Sab'], ['Axad', 'Isniin', 'Talaado', 'Arbaco', 'Khamiis', 'Jimco', 'Sabti'], ['Axd', 'Isn', 'Tal', 'Arb', 'Kha', 'Jim', 'Sab'] ], u, [ ['K', 'L', 'S', 'A', 'S', 'L', 'T', 'S', 'S', 'T', 'K', 'L'], ['Kob', 'Lab', 'Sad', 'Afr', 'Sha', 'Lix', 'Tod', 'Sid', 'Sag', 'Tob', 'KIT', 'LIT'], [ 'Bisha Koobaad', 'Bisha Labaad', 'Bisha Saddexaad', 'Bisha Afraad', 'Bisha Shanaad', 'Bisha Lixaad', 'Bisha Todobaad', 'Bisha Sideedaad', 'Bisha Sagaalaad', 'Bisha Tobnaad', 'Bisha Kow iyo Tobnaad', 'Bisha Laba iyo Tobnaad' ] ], [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], ['Kob', 'Lab', 'Sad', 'Afr', 'Sha', 'Lix', 'Tod', 'Sid', 'Sag', 'Tob', 'KIT', 'LIT'], [ 'Bisha Koobaad', 'Bisha Labaad', 'Bisha Saddexaad', 'Bisha Afraad', 'Bisha Shanaad', 'Bisha Lixaad', 'Bisha Todobaad', 'Bisha Sideedaad', 'Bisha Sagaalaad', 'Bisha Tobnaad', 'Bisha Kow iyo Tobnaad', 'Bisha Laba iyo Tobnaad' ] ], [['CK', 'CD'], u, u], 1, [6, 0], ['dd/MM/yy', 'dd-MMM-y', 'dd MMMM y', 'EEEE, MMMM dd, y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1} {0}', u, u, u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'S', 'Shilin soomaali', {'JPY': ['JP¥', '¥'], 'SOS': ['S'], 'USD': ['US$', '$']}, plural, [] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
define(function (require, exports, module) { var items = { '0': { 1: '北京市', 22: '天津市', 44: '上海市', 66: '重庆市', 108: '河北省', 406: '山西省', 622: '内蒙古', 804: '辽宁省', 945: '吉林省', 1036: '黑龙江省', 1226: '江苏省', 1371: '浙江省', 1500: '安徽省', 1679: '福建省', 1812: '江西省', 1992: '山东省', 2197: '河南省', 2456: '湖北省', 2613: '湖南省', 2822: '广东省', 3015: '广西', 3201: '海南省', 3235: '四川省', 3561: '贵州省', 3728: '云南省', 3983: '西藏', 4136: '陕西省', 4334: '甘肃省', 4499: '青海省', 4588: '宁夏', 4624: '新疆', 4802: '香港', 4822: '澳门', 4825: '台湾省' }, '0,1': { 2: '北京市' }, '0,1,2': { 3: '东城区', 4: '西城区', 5: '崇文区', 6: '宣武区', 7: '朝阳区', 8: '丰台区', 9: '石景山区', 10: '海淀区', 11: '门头沟区', 12: '房山区', 13: '通州区', 14: '顺义区', 15: '昌平区', 16: '大兴区', 17: '怀柔区', 18: '平谷区', 19: '密云县', 20: '延庆县', 21: '延庆镇' }, '0,22': { 23: '天津市' }, '0,22,23': { 24: '和平区', 25: '河东区', 26: '河西区', 27: '南开区', 28: '河北区', 29: '红桥区', 30: '塘沽区', 31: '汉沽区', 32: '大港区', 33: '东丽区', 34: '西青区', 35: '津南区', 36: '北辰区', 37: '武清区', 38: '宝坻区', 39: '蓟县', 40: '宁河县', 41: '芦台镇', 42: '静海县', 43: '静海镇' }, '0,44': { 45: '上海市' }, '0,44,45': { 46: '黄浦区', 47: '卢湾区', 48: '徐汇区', 49: '长宁区', 50: '静安区', 51: '普陀区', 52: '闸北区', 53: '虹口区', 54: '杨浦区', 55: '闵行区', 56: '宝山区', 57: '嘉定区', 58: '浦东新区', 59: '金山区', 60: '松江区', 61: '青浦区', 62: '南汇区', 63: '奉贤区', 64: '崇明县', 65: '城桥镇' }, '0,66': { 67: '重庆市' }, '0,66,67': { 68: '渝中区', 69: '大渡口区', 70: '江北区', 71: '沙坪坝区', 72: '九龙坡区', 73: '南岸区', 74: '北碚区', 75: '万盛区', 76: '双桥区', 77: '渝北区', 78: '巴南区', 79: '万州区', 80: '涪陵区', 81: '黔江区', 82: '长寿区', 83: '合川市', 84: '永川区市', 85: '江津市', 86: '南川市', 87: '綦江县', 88: '潼南县', 89: '铜梁县', 90: '大足县', 91: '荣昌县', 92: '璧山县', 93: '垫江县', 94: '武隆县', 95: '丰都县', 96: '城口县', 97: '梁平县', 98: '开县', 99: '巫溪县', 100: '巫山县', 101: '奉节县', 102: '云阳县', 103: '忠县', 104: '石柱土家族自治县', 105: '彭水苗族土家族自治县', 106: '酉阳土家族苗族自治县', 107: '秀山土家族苗族自治县' }, '0,108': { 109: '石家庄市', 145: '张家口市', 176: '承德市', 196: '秦皇岛市', 208: '唐山市', 229: '廊坊市', 246: '保定市', 290: '衡水市', 310: '沧州市', 337: '邢台市', 372: '邯郸市' }, '0,108,109': { 110: '长安区', 111: '桥东区', 112: '桥西区', 113: '新华区', 114: '裕华区', 115: '井陉矿区', 116: '辛集市', 117: '藁城市', 118: '晋州市', 119: '新乐市', 120: '鹿泉市', 121: '井陉县', 122: '微水镇', 123: '正定县', 124: '正定镇', 125: '栾城县', 126: '栾城镇', 127: '行唐县', 128: '龙州镇', 129: '灵寿县', 130: '灵寿镇', 131: '高邑县', 132: '高邑镇', 133: '深泽县', 134: '深泽镇', 135: '赞皇县', 136: '赞皇镇', 137: '无极县', 138: '无极镇', 139: '平山县', 140: '平山镇', 141: '元氏县', 142: '槐阳镇', 143: '赵县', 144: '赵州镇' }, '0,108,145': { 146: '桥西区', 147: '桥东区', 148: '宣化区', 149: '下花园区', 150: '宣化县', 151: '张家口市宣化区', 152: '张北县', 153: '张北镇', 154: '康保县', 155: '康保镇', 156: '沽源县', 157: '平定堡镇', 158: '尚义县', 159: '南壕堑镇', 160: '蔚县', 161: '蔚州镇', 162: '阳原县', 163: '西城镇', 164: '怀安县', 165: '柴沟堡镇', 166: '万全县', 167: '孔家庄镇', 168: '怀来县', 169: '沙城镇', 170: '涿鹿县', 171: '涿鹿镇', 172: '赤城县', 173: '赤城镇', 174: '崇礼县', 175: '西湾子镇' }, '0,108,176': { 177: '双桥区', 178: '双滦区', 179: '鹰手营子矿区', 180: '承德县', 181: '下板城镇', 182: '兴隆县', 183: '兴隆镇', 184: '平泉县', 185: '平泉镇', 186: '滦平县', 187: '滦平镇', 188: '隆化县', 189: '隆化镇', 190: '丰宁满族自治县', 191: '大阁镇', 192: '宽城满族自治县', 193: '宽城镇', 194: '围场满族蒙古族自治县', 195: '围场镇' }, '0,108,196': { 197: '海港区', 198: '山海关区', 199: '北戴河区', 200: '昌黎县', 201: '昌黎镇', 202: '抚宁县', 203: '抚宁镇', 204: '卢龙县', 205: '卢龙镇', 206: '青龙满族自治县', 207: '青龙镇' }, '0,108,208': { 209: '路北区', 210: '路南区', 211: '古冶区', 212: '开平区', 213: '丰润区', 214: '丰南区', 215: '遵化市', 216: '迁安市', 217: '滦县', 218: '滦州镇', 219: '滦南县', 220: '倴城镇', 221: '乐亭县', 222: '乐亭镇', 223: '迁西县', 224: '兴城镇', 225: '玉田县', 226: '玉田镇', 227: '唐海县', 228: '唐海镇' }, '0,108,229': { 230: '安次区', 231: '广阳区', 232: '霸州市', 233: '三河市', 234: '固安县', 235: '固安镇', 236: '永清县', 237: '永清镇', 238: '香河县', 239: '淑阳镇', 240: '大城县', 241: '平舒镇', 242: '文安县', 243: '文安镇', 244: '大厂回族自治县', 245: '大厂镇' }, '0,108,246': { 247: '新市区', 248: '北市区', 249: '南市区', 250: '定州市', 251: '涿州市', 252: '安国市', 253: '高碑店市', 254: '满城县', 255: '满城镇', 256: '清苑县', 257: '清苑镇', 258: '易县', 259: '易州镇', 260: '徐水县', 261: '安肃镇', 262: '涞源县', 263: '涞源镇', 264: '定兴县', 265: '定兴镇', 266: '顺平县', 267: '蒲阳镇', 268: '唐县', 269: '仁厚镇', 270: '望都县', 271: '望都镇', 272: '涞水县', 273: '涞水镇', 274: '高阳县', 275: '高阳镇', 276: '安新县', 277: '安新镇', 278: '雄县', 279: '雄州镇', 280: '容城县', 281: '容城镇', 282: '曲阳县', 283: '恒州镇', 284: '阜平县', 285: '阜平镇', 286: '博野县', 287: '博陵镇', 288: '蠡县', 289: '蠡吾镇' }, '0,108,290': { 291: '桃城区', 292: '冀州市', 293: '深州市', 294: '枣强县', 295: '枣强镇', 296: '武邑县', 297: '武邑镇', 298: '武强县', 299: '武强镇', 300: '饶阳县', 301: '饶阳镇', 302: '安平县', 303: '安平镇', 304: '故城县', 305: '郑口镇', 306: '景县', 307: '景州镇', 308: '阜城县', 309: '阜城镇' }, '0,108,310': { 311: '运河区', 312: '新华区', 313: '泊头市', 314: '任丘市', 315: '黄骅市', 316: '河间市', 317: '沧县', 318: '沧州市新华区', 319: '青县', 320: '清州镇', 321: '东光县', 322: '东光镇', 323: '海兴县', 324: '苏基镇', 325: '盐山县', 326: '盐山镇', 327: '肃宁县', 328: '肃宁镇', 329: '南皮县', 330: '南皮镇', 331: '吴桥县', 332: '桑园镇', 333: '献县', 334: '乐寿镇', 335: '孟村回族自治县', 336: '孟村镇' }, '0,108,337': { 338: '桥东区', 339: '桥西区', 340: '南宫市', 341: '沙河市', 342: '邢台县', 343: '邢台市桥东区', 344: '临城县', 345: '临城镇', 346: '内丘县', 347: '内丘镇', 348: '柏乡县', 349: '柏乡镇', 350: '隆尧县', 351: '隆尧镇', 352: '任县', 353: '任城镇', 354: '南和县', 355: '和阳镇', 356: '宁晋县', 357: '凤凰镇', 358: '巨鹿县', 359: '巨鹿镇', 360: '新河县', 361: '新河镇', 362: '广宗县', 363: '广宗镇', 364: '平乡县', 365: '丰州镇', 366: '威县', 367: '洺州镇', 368: '清河县', 369: '葛仙庄镇', 370: '临西县', 371: '临西镇' }, '0,108,372': { 373: '丛台区', 374: '邯山区', 375: '复兴区', 376: '峰峰矿区', 377: '武安市', 378: '邯郸县', 379: '南堡乡东小屯村', 380: '临漳县', 381: '临漳镇', 382: '成安县', 383: '成安镇', 384: '大名县', 385: '大名镇', 386: '涉县', 387: '涉城镇', 388: '磁县', 389: '磁州镇', 390: '肥乡县', 391: '肥乡镇', 392: '永年县', 393: '临洺关镇', 394: '邱县', 395: '新马头镇', 396: '鸡泽县', 397: '鸡泽镇', 398: '广平县', 399: '广平镇', 400: '馆陶县', 401: '馆陶镇', 402: '魏县', 403: '魏城镇', 404: '曲周县', 405: '曲周镇' }, '0,406': { 407: '太原市', 421: '朔州市', 432: '大同市', 451: '阳泉市', 459: '长治市', 483: '晋城市', 494: '忻州市', 521: '晋中市', 542: '临汾市', 574: '吕梁市', 598: '运城市' }, '0,406,407': { 408: '杏花岭区', 409: '小店区', 410: '迎泽区', 411: '尖草坪区', 412: '万柏林区', 413: '晋源区', 414: '古交市', 415: '清徐县', 416: '清源镇', 417: '阳曲县', 418: '黄寨镇', 419: '娄烦县', 420: '娄烦镇' }, '0,406,421': { 422: '朔城区', 423: '平鲁区', 424: '山阴县', 425: '岱岳乡', 426: '应县', 427: '金城镇', 428: '右玉县', 429: '新城镇', 430: '怀仁县', 431: '云中镇' }, '0,406,432': { 433: '城区', 434: '矿区', 435: '南郊区', 436: '新荣区', 437: '阳高县', 438: '龙泉镇', 439: '天镇县', 440: '玉泉镇', 441: '广灵县', 442: '壶泉镇', 443: '灵丘县', 444: '武灵镇', 445: '浑源县', 446: '永安镇', 447: '左云县', 448: '云兴镇', 449: '大同县', 450: '西坪镇' }, '0,406,451': { 452: '城区', 453: '矿区', 454: '郊区', 455: '平定县', 456: '冠山镇', 457: '盂县', 458: '秀水镇' }, '0,406,459': { 460: '城区', 461: '郊区', 462: '潞城市', 463: '长治县', 464: '韩店镇', 465: '襄垣县', 466: '古韩镇', 467: '屯留县', 468: '麟绛镇', 469: '平顺县', 470: '青羊镇', 471: '黎城县', 472: '黎侯镇', 473: '壶关县', 474: '龙泉镇', 475: '长子县', 476: '丹朱镇', 477: '武乡县', 478: '丰州镇', 479: '沁县', 480: '定昌镇', 481: '沁源县', 482: '沁河镇' }, '0,406,483': { 484: '城区', 485: '高平市', 486: '泽州县', 487: '南村镇', 488: '沁水县', 489: '龙港镇', 490: '阳城县', 491: '凤城镇', 492: '陵川县', 493: '崇文镇' }, '0,406,494': { 495: '忻府区', 496: '原平市', 497: '定襄县', 498: '晋昌镇', 499: '五台县', 500: '台城镇', 501: '代县', 502: '上馆镇', 503: '繁峙县', 504: '繁城镇', 505: '宁武县', 506: '凤凰镇', 507: '静乐县', 508: '鹅城镇', 509: '神池县', 510: '龙泉镇', 511: '五寨县', 512: '砚城镇', 513: '岢岚县', 514: '岚漪镇', 515: '河曲县', 516: '文笔镇', 517: '保德县', 518: '东关镇', 519: '偏关县', 520: '新关镇' }, '0,406,521': { 522: '榆次区', 523: '介休市', 524: '榆社县', 525: '箕城镇', 526: '左权县', 527: '辽阳镇', 528: '和顺县', 529: '义兴镇', 530: '昔阳县', 531: '乐平镇', 532: '寿阳县', 533: '朝阳镇', 534: '太谷县', 535: '明星镇', 536: '祁县', 537: '昭余镇', 538: '平遥县', 539: '古陶镇', 540: '灵石县', 541: '翠峰镇' }, '0,406,542': { 543: '尧都区', 544: '侯马市', 545: '霍州市', 546: '曲沃县', 547: '乐昌镇', 548: '翼城县', 549: '唐兴镇', 550: '襄汾县', 551: '新城镇', 552: '洪洞县', 553: '大槐树镇', 554: '古县', 555: '岳阳镇', 556: '安泽县', 557: '府城镇', 558: '浮山县', 559: '天坛镇', 560: '吉县', 561: '吉昌镇', 562: '乡宁县', 563: '昌宁镇', 564: '蒲县', 565: '蒲城镇', 566: '大宁县', 567: '昕水镇', 568: '永和县', 569: '芝河镇', 570: '隰县', 571: '龙泉镇', 572: '汾西县', 573: '永安镇' }, '0,406,574': { 575: '离石区', 576: '孝义市', 577: '汾阳市', 578: '文水县', 579: '凤城镇', 580: '中阳县', 581: '宁乡镇', 582: '兴县', 583: '蔚汾镇', 584: '临县', 585: '临泉镇', 586: '方山县', 587: '圪洞镇', 588: '柳林县', 589: '柳林镇', 590: '岚县', 591: '东村镇', 592: '交口县', 593: '水头镇', 594: '交城县', 595: '天宁镇', 596: '石楼县', 597: '灵泉镇' }, '0,406,598': { 599: '盐湖区', 600: '永济市', 601: '河津市', 602: '芮城县', 603: '古魏镇', 604: '临猗县', 605: '猗氏镇', 606: '万荣县', 607: '解店镇', 608: '新绛县', 609: '龙兴镇', 610: '稷山县', 611: '稷峰镇', 612: '闻喜县', 613: '桐城镇', 614: '夏县', 615: '瑶峰镇', 616: '绛县', 617: '古绛镇', 618: '平陆县', 619: '圣人涧镇', 620: '垣曲县', 621: '新城镇' }, '0,622': { 623: '呼和浩特市', 638: '包头市', 651: '乌海市', 655: '赤峰市', 677: '通辽市', 692: '呼伦贝尔市', 713: '鄂尔多斯市', 729: '乌兰察布市', 750: '巴彦淖尔市', 764: '兴安盟', 775: '锡林郭勒盟', 798: '阿拉善盟' }, '0,622,623': { 624: '回民区', 625: '新城区', 626: '玉泉区', 627: '赛罕区', 628: '托克托县', 629: '双河镇', 630: '武川县', 631: '可可以力更镇', 632: '和林格尔县', 633: '城关镇', 634: '清水河县', 635: '城关镇', 636: '土默特左旗', 637: '察素齐镇' }, '0,622,638': { 639: '昆都仑区', 640: '东河区', 641: '青山区', 642: '石拐区', 643: '白云矿区', 644: '九原区', 645: '固阳县', 646: '金山镇', 647: '土默特右旗', 648: '萨拉齐镇', 649: '达尔罕茂明安联合旗', 650: '百灵庙镇' }, '0,622,651': { 652: '海勃湾区', 653: '海南区', 654: '乌达区' }, '0,622,655': { 656: '红山区', 657: '元宝山区', 658: '松山区', 659: '宁城县', 660: '天义镇', 661: '林西县', 662: '林西镇', 663: '阿鲁科尔沁旗', 664: '天山镇', 665: '巴林左旗', 666: '林东镇', 667: '巴林右旗', 668: '大板镇', 669: '克什克腾旗', 670: '经棚镇', 671: '翁牛特旗', 672: '乌丹镇', 673: '喀喇沁旗', 674: '锦山镇', 675: '敖汉旗', 676: '新惠镇' }, '0,622,677': { 678: '科尔沁区', 679: '霍林郭勒市', 680: '开鲁县', 681: '开鲁镇', 682: '库伦旗', 683: '库伦镇', 684: '奈曼旗', 685: '大沁他拉镇', 686: '扎鲁特旗', 687: '鲁北镇', 688: '科尔沁左翼中旗', 689: '保康镇', 690: '科尔沁左翼后旗', 691: '甘旗卡镇' }, '0,622,692': { 693: '海拉尔区', 694: '满洲里市', 695: '扎兰屯市', 696: '牙克石市', 697: '根河市', 698: '额尔古纳市', 699: '阿荣旗', 700: '那吉镇', 701: '新巴尔虎右旗', 702: '阿拉坦额莫勒镇', 703: '新巴尔虎左旗', 704: '阿穆古郎镇', 705: '陈巴尔虎旗', 706: '巴彦库仁镇', 707: '鄂伦春自治旗', 708: '阿里河镇', 709: '鄂温克族自治旗', 710: '巴彦托海镇', 711: '莫力达瓦达斡尔族自治旗', 712: '尼尔基镇' }, '0,622,713': { 714: '东胜区', 715: '达拉特旗', 716: '树林召镇', 717: '准格尔旗', 718: '薛家湾镇', 719: '鄂托克前旗', 720: '敖勒召其镇', 721: '鄂托克旗', 722: '乌兰镇', 723: '杭锦旗', 724: '锡尼镇', 725: '乌审旗', 726: '嘎鲁图镇', 727: '伊金霍洛旗', 728: '阿勒腾席热镇' }, '0,622,729': { 730: '集宁区', 731: '丰镇市', 732: '卓资县', 733: '卓资山镇', 734: '化德县', 735: '长顺镇', 736: '商都县', 737: '商都镇', 738: '兴和县', 739: '城关镇', 740: '凉城县', 741: '岱海镇', 742: '察哈尔右翼前旗', 743: '土贵乌拉镇', 744: '察哈尔右翼中旗', 745: '科布尔镇', 746: '察哈尔右翼后旗', 747: '白音察干镇', 748: '四子王旗', 749: '乌兰花镇' }, '0,622,750': { 751: '临河区', 752: '五原县', 753: '隆兴昌镇', 754: '磴口县', 755: '巴彦高勒镇', 756: '乌拉特前旗', 757: '乌拉山镇', 758: '乌拉特中旗', 759: '海流图镇', 760: '乌拉特后旗', 761: '巴音宝力格镇', 762: '杭锦后旗', 763: '陕坝镇' }, '0,622,764': { 765: '乌兰浩特市', 766: '阿尔山市', 767: '突泉县', 768: '突泉镇', 769: '科尔沁右翼前旗', 770: '大坝沟镇', 771: '科尔沁右翼中旗', 772: '巴彦呼硕镇', 773: '扎赉特旗', 774: '音德尔镇' }, '0,622,775': { 776: '锡林浩特市', 777: '二连浩特市', 778: '多伦县', 779: '多伦淖尔镇', 780: '阿巴嘎旗', 781: '别力古台镇', 782: '苏尼特左旗', 783: '满都拉图镇', 784: '苏尼特右旗', 785: '赛汉塔拉镇', 786: '东乌珠穆沁旗', 787: '乌里雅斯太镇', 788: '西乌珠穆沁旗', 789: '巴拉嘎尔郭勒镇', 790: '太仆寺旗', 791: '宝昌镇', 792: '镶黄旗', 793: '新宝拉格镇', 794: '正镶白旗', 795: '明安图镇', 796: '正蓝旗', 797: '上都镇' }, '0,622,798': { 799: '巴彦浩特镇', 800: '阿拉善右旗', 801: '额肯呼都格镇', 802: '额济纳旗', 803: '达来呼布镇' }, '0,804': { 805: '沈阳市', 822: '朝阳市', 832: '阜新市', 842: '铁岭市', 853: '抚顺市', 864: '本溪市', 873: '辽阳市', 882: '鞍山市', 892: '丹东市', 900: '大连市', 912: '营口市', 919: '盘锦市', 926: '锦州市', 936: '葫芦岛市' }, '0,804,805': { 806: '沈河区', 807: '和平区', 808: '大东区', 809: '皇姑区', 810: '铁西区', 811: '苏家屯区', 812: '东陵区', 813: '新城子区', 814: '于洪区', 815: '新民市', 816: '辽中县', 817: '辽中镇', 818: '康平县', 819: '康平镇', 820: '法库县', 821: '法库镇' }, '0,804,822': { 823: '双塔区', 824: '龙城区', 825: '北票市', 826: '凌源市', 827: '朝阳县', 828: '朝阳市双塔区', 829: '建平县', 830: '喀喇沁左翼蒙古族自治县', 831: '大城子镇' }, '0,804,832': { 833: '海州区', 834: '新邱区', 835: '太平区', 836: '清河门区', 837: '细河区', 838: '彰武县', 839: '彰武镇', 840: '阜新蒙古族自治县', 841: '阜新镇' }, '0,804,842': { 843: '银州区', 844: '清河区', 845: '调兵山市', 846: '开原市', 847: '铁岭县', 848: '铁岭市银州区', 849: '西丰县', 850: '西丰镇', 851: '昌图县', 852: '昌图镇' }, '0,804,853': { 854: '顺城区', 855: '新抚区', 856: '东洲区', 857: '望花区', 858: '抚顺县', 859: '抚顺市顺城区', 860: '新宾满族自治县', 861: '新宾镇', 862: '清原满族自治县', 863: '清原镇' }, '0,804,864': { 865: '平山区', 866: '溪湖区', 867: '明山区', 868: '南芬区', 869: '本溪满族自治县', 870: '小市镇', 871: '桓仁满族自治县', 872: '桓仁镇' }, '0,804,873': { 874: '白塔区', 875: '文圣区', 876: '宏伟区', 877: '弓长岭区', 878: '太子河区', 879: '灯塔市', 880: '辽阳县', 881: '首山镇' }, '0,804,882': { 883: '铁东区', 884: '铁西区', 885: '立山区', 886: '千山区', 887: '海城市', 888: '台安县', 889: '台安镇', 890: '岫岩满族自治县', 891: '岫岩镇' }, '0,804,892': { 893: '振兴区', 894: '元宝区', 895: '振安区', 896: '凤城市', 897: '东港市', 898: '宽甸满族自治县', 899: '宽甸镇' }, '0,804,900': { 901: '西岗区', 902: '中山区', 903: '沙河口区', 904: '甘井子区', 905: '旅顺口区', 906: '金州区', 907: '瓦房店市', 908: '普兰店市', 909: '庄河市', 910: '长海县', 911: '大长山岛镇', 5292: '开发区' }, '0,804,912': { 913: '站前区', 914: '西市区', 915: '鲅鱼圈区', 916: '老边区', 917: '大石桥市', 918: '盖州市' }, '0,804,919': { 920: '兴隆台区', 921: '双台子区', 922: '大洼县', 923: '大洼镇', 924: '盘山县', 925: '盘锦市双台子区' }, '0,804,926': { 927: '太和区', 928: '古塔区', 929: '凌河区', 930: '凌海市', 931: '北宁市', 932: '黑山县', 933: '黑山镇', 934: '义县', 935: '义州镇' }, '0,804,936': { 937: '龙港区', 938: '连山区', 939: '南票区', 940: '兴城市', 941: '绥中县', 942: '绥中镇', 943: '建昌县', 944: '建昌镇' }, '0,945': { 946: '长春市', 958: '白城市', 966: '松原市', 976: '吉林市', 987: '四平市', 996: '辽源市', 1003: '通化市', 1014: '白山市', 1025: '延边州' }, '0,945,946': { 947: '朝阳区', 948: '南关区', 949: '宽城区', 950: '二道区', 951: '绿园区', 952: '双阳区', 953: '德惠市', 954: '九台市', 955: '榆树市', 956: '农安县', 957: '农安镇' }, '0,945,958': { 959: '洮北区', 960: '大安市', 961: '洮南市', 962: '镇赉县', 963: '镇赉镇', 964: '通榆县', 965: '开通镇' }, '0,945,966': { 967: '宁江区', 968: '扶余县', 969: '三岔河镇', 970: '长岭县', 971: '长岭镇', 972: '乾安县', 973: '乾安镇', 974: '前郭尔罗斯蒙古族自治县', 975: '前郭镇' }, '0,945,976': { 977: '船营区', 978: '龙潭区', 979: '昌邑区', 980: '丰满区', 981: '磐石市', 982: '蛟河市', 983: '桦甸市', 984: '舒兰市', 985: '永吉县', 986: '口前镇' }, '0,945,987': { 988: '铁西区', 989: '铁东区', 990: '双辽市', 991: '公主岭市', 992: '梨树县', 993: '梨树镇', 994: '伊通满族自治县', 995: '伊通镇' }, '0,945,996': { 997: '龙山区', 998: '西安区', 999: '东丰县', 1000: '东丰镇', 1001: '东辽县', 1002: '白泉镇' }, '0,945,1003': { 1004: '东昌区', 1005: '二道江区', 1006: '梅河口市', 1007: '集安市', 1008: '通化县', 1009: '快大茂镇', 1010: '辉南县', 1011: '朝阳镇', 1012: '柳河县', 1013: '柳河镇' }, '0,945,1014': { 1015: '八道江区', 1016: '临江市', 1017: '江源县', 1018: '孙家堡子镇', 1019: '抚松县', 1020: '抚松镇', 1021: '靖宇县', 1022: '靖宇镇', 1023: '长白朝鲜族自治县', 1024: '长白镇' }, '0,945,1025': { 1026: '延吉市', 1027: '图们市', 1028: '敦化市', 1029: '珲春市', 1030: '龙井市', 1031: '和龙市', 1032: '汪清县', 1033: '汪清镇', 1034: '安图县', 1035: '明月镇' }, '0,1036': { 1037: '哈尔滨市', 1064: '齐齐哈尔市', 1089: '七台河市', 1095: '黑河市', 1105: '大庆市', 1119: '鹤岗市', 1130: '伊春市', 1149: '佳木斯市', 1165: '双鸭山市', 1178: '鸡西市', 1189: '牡丹江市', 1202: '绥化市', 1219: '大兴安岭地区' }, '0,1036,1037': { 1038: '松北区', 1039: '道里区', 1040: '南岗区', 1041: '道外区', 1042: '香坊区', 1043: '动力区', 1044: '平房区', 1045: '呼兰区', 1046: '双城市', 1047: '尚志市', 1048: '五常市', 1049: '阿城市', 1050: '依兰县', 1051: '依兰镇', 1052: '方正县', 1053: '方正镇', 1054: '宾县', 1055: '宾州镇', 1056: '巴彦县', 1057: '巴彦镇', 1058: '木兰县', 1059: '木兰镇', 1060: '通河县', 1061: '通河镇', 1062: '延寿县', 1063: '延寿镇' }, '0,1036,1064': { 1065: '建华区', 1066: '龙沙区', 1067: '铁锋区', 1068: '昂昂溪区', 1069: '富拉尔基区', 1070: '碾子山区', 1071: '梅里斯达斡尔族区', 1072: '讷河市', 1073: '龙江县', 1074: '龙江镇', 1075: '依安县', 1076: '依安镇', 1077: '泰来县', 1078: '泰来镇', 1079: '甘南县', 1080: '甘南镇', 1081: '富裕县', 1082: '富裕镇', 1083: '克山县', 1084: '克山镇', 1085: '克东县', 1086: '克东镇', 1087: '拜泉县', 1088: '拜泉镇' }, '0,1036,1089': { 1090: '桃山区', 1091: '新兴区', 1092: '茄子河区', 1093: '勃利县', 1094: '勃利镇' }, '0,1036,1095': { 1096: '爱辉区', 1097: '北安市', 1098: '五大连池市', 1099: '嫩江县', 1100: '嫩江镇', 1101: '逊克县', 1102: '边疆镇', 1103: '孙吴县', 1104: '孙吴镇' }, '0,1036,1105': { 1106: '萨尔图区', 1107: '龙凤区', 1108: '让胡路区', 1109: '大同区', 1110: '红岗区', 1111: '肇州县', 1112: '肇州镇', 1113: '肇源县', 1114: '肇源镇', 1115: '林甸县', 1116: '林甸镇', 1117: '杜尔伯特蒙古族自治县', 1118: '泰康镇' }, '0,1036,1119': { 1120: '兴山区', 1121: '向阳区', 1122: '工农区', 1123: '南山区', 1124: '兴安区', 1125: '东山区', 1126: '萝北县', 1127: '凤翔镇', 1128: '绥滨县', 1129: '绥滨镇' }, '0,1036,1130': { 1131: '伊春区', 1132: '南岔区', 1133: '友好区', 1134: '西林区', 1135: '翠峦区', 1136: '新青区', 1137: '美溪区', 1138: '金山屯区', 1139: '五营区', 1140: '乌马河区', 1141: '汤旺河区', 1142: '带岭区', 1143: '乌伊岭区', 1144: '红星区', 1145: '上甘岭区', 1146: '铁力市', 1147: '嘉荫县', 1148: '朝阳镇' }, '0,1036,1149': { 1150: '前进区', 1151: '永红区', 1152: '向阳区', 1153: '东风区', 1154: '郊区', 1155: '同江市', 1156: '富锦市', 1157: '桦南县', 1158: '桦南镇', 1159: '桦川县', 1160: '悦来镇', 1161: '汤原县', 1162: '汤原镇', 1163: '抚远县', 1164: '抚远镇' }, '0,1036,1165': { 1166: '尖山区', 1167: '岭东区', 1168: '四方台区', 1169: '宝山区', 1170: '集贤县', 1171: '福利镇', 1172: '友谊县', 1173: '友谊镇', 1174: '宝清县', 1175: '宝清镇', 1176: '饶河县', 1177: '饶河镇' }, '0,1036,1178': { 1179: '鸡冠区', 1180: '恒山区', 1181: '滴道区', 1182: '梨树区', 1183: '城子河区', 1184: '麻山区', 1185: '虎林市', 1186: '密山市', 1187: '鸡东县', 1188: '鸡东镇' }, '0,1036,1189': { 1190: '爱民区', 1191: '东安区', 1192: '阳明区', 1193: '西安区', 1194: '穆棱市', 1195: '绥芬河市', 1196: '海林市', 1197: '宁安市', 1198: '东宁县', 1199: '东宁镇', 1200: '林口县', 1201: '林口镇' }, '0,1036,1202': { 1203: '北林区', 1204: '安达市', 1205: '肇东市', 1206: '海伦市', 1207: '望奎县', 1208: '望奎镇', 1209: '兰西县', 1210: '兰西镇', 1211: '青冈县', 1212: '青冈镇', 1213: '庆安县', 1214: '庆安镇', 1215: '明水县', 1216: '明水镇', 1217: '绥棱县', 1218: '绥棱镇' }, '0,1036,1219': { 1220: '呼玛县', 1221: '呼玛镇', 1222: '塔河县', 1223: '塔河镇', 1224: '漠河县', 1225: '西林吉镇' }, '0,1226': { 1227: '南京市', 1243: '徐州市', 1259: '连云港市', 1271: '宿迁市', 1280: '淮安市', 1293: '盐城市', 1308: '扬州市', 1317: '泰州市', 1324: '南通市', 1335: '镇江市', 1342: '常州市', 1350: '无锡市', 1359: '苏州市' }, '0,1226,1227': { 1228: '玄武区', 1229: '白下区', 1230: '秦淮区', 1231: '建邺区', 1232: '鼓楼区', 1233: '下关区', 1234: '浦口区', 1235: '六合区', 1236: '栖霞区', 1237: '雨花台区', 1238: '江宁区', 1239: '溧水县', 1240: '永阳镇', 1241: '高淳县', 1242: '淳溪镇' }, '0,1226,1243': { 1244: '云龙区', 1245: '鼓楼区', 1246: '九里区', 1247: '贾汪区', 1248: '泉山区', 1249: '邳州市', 1250: '新沂市', 1251: '铜山县', 1252: '铜山镇', 1253: '睢宁县', 1254: '睢城镇', 1255: '沛县', 1256: '沛城镇', 1257: '丰县', 1258: '凤城镇' }, '0,1226,1259': { 1260: '新浦区', 1261: '连云区', 1262: '海州区', 1263: '赣榆县', 1264: '青口镇', 1265: '灌云县', 1266: '伊山镇', 1267: '东海县', 1268: '牛山镇', 1269: '灌南县', 1270: '新安镇' }, '0,1226,1271': { 1272: '宿城区', 1273: '宿豫区', 1274: '沭阳县', 1275: '沭城镇', 1276: '泗阳县', 1277: '众兴镇', 1278: '泗洪县', 1279: '青阳镇' }, '0,1226,1280': { 1281: '清河区', 1282: '清浦区', 1283: '楚州区', 1284: '淮阴区', 1285: '金湖县', 1286: '黎城镇', 1287: '盱眙县', 1288: '盱城镇', 1289: '洪泽县', 1290: '高良涧镇', 1291: '涟水县', 1292: '涟城镇' }, '0,1226,1293': { 1294: '亭湖区', 1295: '盐都区', 1296: '东台市', 1297: '大丰市', 1298: '射阳县', 1299: '合德镇', 1300: '阜宁县', 1301: '阜城镇', 1302: '滨海县', 1303: '东坎镇', 1304: '响水县', 1305: '响水镇', 1306: '建湖县', 1307: '近湖镇' }, '0,1226,1308': { 1309: '维扬区', 1310: '广陵区', 1311: '邗江区', 1312: '仪征市', 1313: '江都市', 1314: '高邮市', 1315: '宝应县', 1316: '安宜镇' }, '0,1226,1317': { 1318: '海陵区', 1319: '高港区', 1320: '靖江市', 1321: '泰兴市', 1322: '姜堰市', 1323: '兴化市' }, '0,1226,1324': { 1325: '崇川区', 1326: '港闸区', 1327: '海门市', 1328: '启东市', 1329: '通州市', 1330: '如皋市', 1331: '如东县', 1332: '掘港镇', 1333: '海安县', 1334: '海安镇' }, '0,1226,1335': { 1336: '京口区', 1337: '润州区', 1338: '丹徒区', 1339: '扬中市', 1340: '丹阳市', 1341: '句容市' }, '0,1226,1342': { 1343: '钟楼区', 1344: '天宁区', 1345: '戚墅堰区', 1346: '新北区', 1347: '武进区', 1348: '金坛市', 1349: '溧阳市' }, '0,1226,1350': { 1351: '崇安区', 1352: '南长区', 1353: '北塘区', 1354: '滨湖区', 1355: '惠山区', 1356: '锡山区', 1357: '江阴市', 1358: '宜兴市', 1600: '新区' }, '0,1226,1359': { 1360: '金阊区', 1361: '沧浪区', 1362: '平江区', 1363: '虎丘区', 1364: '吴中区', 1365: '相城区', 1366: '吴江市', 1367: '昆山市', 1368: '太仓市', 1369: '常熟市', 1370: '张家港市', 5921: '工业园区', 5922: '新区' }, '0,1371': { 1372: '杭州市', 1387: '湖州市', 1396: '嘉兴市', 1406: '舟山市', 1413: '宁波市', 1425: '绍兴市', 1433: '衢州市', 1442: '金华市', 1453: '台州市', 1465: '温州市', 1483: '丽水市' }, '0,1371,1372': { 1373: '拱墅区', 1374: '上城区', 1375: '下城区', 1376: '江干区', 1377: '西湖区', 1378: '滨江区', 1379: '余杭区', 1380: '萧山区', 1381: '临安市', 1382: '富阳市', 1383: '建德市', 1384: '桐庐县', 1385: '淳安县', 1386: '千岛湖镇' }, '0,1371,1387': { 1388: '吴兴区', 1389: '南浔区', 1390: '长兴县', 1391: '雉城镇', 1392: '德清县', 1393: '武康镇', 1394: '安吉县', 1395: '递铺镇' }, '0,1371,1396': { 1397: '南湖区', 1398: '秀洲区', 1399: '平湖市', 1400: '海宁市', 1401: '桐乡市', 1402: '嘉善县', 1403: '魏塘镇', 1404: '海盐县', 1405: '武原镇' }, '0,1371,1406': { 1407: '定海区', 1408: '普陀区', 1409: '岱山县', 1410: '高亭镇', 1411: '嵊泗县', 1412: '菜园镇' }, '0,1371,1413': { 1414: '海曙区', 1415: '江东区', 1416: '江北区', 1417: '北仑区', 1418: '镇海区', 1419: '鄞州区', 1420: '慈溪市', 1421: '余姚市', 1422: '奉化市', 1423: '宁海县', 1424: '象山县' }, '0,1371,1425': { 1426: '越城区', 1427: '诸暨市', 1428: '上虞市', 1429: '嵊州市', 1430: '绍兴县', 1431: '新昌县', 1432: '城关镇' }, '0,1371,1433': { 1434: '柯城区', 1435: '衢江区', 1436: '江山市', 1437: '常山县', 1438: '天马镇', 1439: '开化县', 1440: '城关镇', 1441: '龙游县' }, '0,1371,1442': { 1443: '婺城区', 1444: '金东区', 1445: '兰溪市', 1446: '永康市', 1447: '义乌市', 1448: '东阳市', 1449: '武义县', 1450: '浦江县', 1451: '磐安县', 1452: '安文镇' }, '0,1371,1453': { 1454: '椒江区', 1455: '黄岩区', 1456: '路桥区', 1457: '临海市', 1458: '温岭市', 1459: '三门县', 1460: '海游镇', 1461: '天台县', 1462: '仙居县', 1463: '玉环县', 1464: '珠港镇' }, '0,1371,1465': { 1466: '鹿城区', 1467: '龙湾区', 1468: '瓯海区', 1469: '瑞安市', 1470: '乐清市', 1471: '永嘉县', 1472: '上塘镇', 1473: '文成县', 1474: '大峃镇', 1475: '平阳县', 1476: '昆阳镇', 1477: '泰顺县', 1478: '罗阳镇', 1479: '洞头县', 1480: '北岙镇', 1481: '苍南县', 1482: '灵溪镇' }, '0,1371,1483': { 1484: '莲都区', 1485: '龙泉市', 1486: '缙云县', 1487: '五云镇', 1488: '青田县', 1489: '鹤城镇', 1490: '云和县', 1491: '云和镇', 1492: '遂昌县', 1493: '妙高镇', 1494: '松阳县', 1495: '西屏镇', 1496: '庆元县', 1497: '松源镇', 1498: '景宁畲族自治县', 1499: '鹤溪镇' }, '0,1500': { 1501: '合肥市', 1512: '宿州市', 1522: '淮北市', 1528: '亳州市', 1536: '阜阳市', 1549: '蚌埠市', 1560: '淮南市', 1568: '滁州市', 1581: '马鞍山市', 1587: '芜湖市', 1598: '铜陵市', 1604: '安庆市', 1623: '黄山市', 1635: '六安市', 1648: '巢湖市', 1658: '池州市', 1666: '宣城市' }, '0,1500,1501': { 1502: '庐阳区', 1503: '瑶海区', 1504: '蜀山区', 1505: '包河区', 1506: '长丰县', 1507: '水湖镇', 1508: '肥东县', 1509: '店埠镇', 1510: '肥西县', 1511: '上派镇', 5924: '居巢区', 5925: '经济开发区', 5926: '政务区' }, '0,1500,1512': { 1513: '埇桥区', 1514: '砀山县', 1515: '砀城镇', 1516: '萧县', 1517: '龙城镇', 1518: '灵璧县', 1519: '灵城镇', 1520: '泗县', 1521: '泗城镇' }, '0,1500,1522': { 1523: '相山区', 1524: '杜集区', 1525: '烈山区', 1526: '濉溪县', 1527: '濉溪镇' }, '0,1500,1528': { 1529: '谯城区', 1530: '涡阳县', 1531: '城关镇', 1532: '蒙城县', 1533: '城关镇', 1534: '利辛县', 1535: '城关镇' }, '0,1500,1536': { 1537: '颍州区', 1538: '颍东区', 1539: '颍泉区', 1540: '界首市', 1541: '临泉县', 1542: '城关镇', 1543: '太和县', 1544: '城关镇', 1545: '阜南县', 1546: '城关镇', 1547: '颍上县', 1548: '慎城镇' }, '0,1500,1549': { 1550: '蚌山区', 1551: '龙子湖区', 1552: '禹会区', 1553: '淮上区', 1554: '怀远县', 1555: '城关镇', 1556: '五河县', 1557: '城关镇', 1558: '固镇县', 1559: '城关镇' }, '0,1500,1560': { 1561: '田家庵区', 1562: '大通区', 1563: '谢家集区', 1564: '八公山区', 1565: '潘集区', 1566: '凤台县', 1567: '城关镇' }, '0,1500,1568': { 1569: '琅区', 1570: '南谯区', 1571: '明光市', 1572: '天长市', 1573: '来安县', 1574: '新安镇', 1575: '全椒县', 1576: '襄河镇', 1577: '定远县', 1578: '定城镇', 1579: '凤阳县', 1580: '府城镇' }, '0,1500,1581': { 1582: '雨山区', 1583: '花山区', 1584: '金家庄区', 1585: '当涂县', 1586: '姑孰镇' }, '0,1500,1587': { 1588: '镜湖区', 1589: '弋江区', 1590: '三山区', 1591: '鸠江区', 1592: '芜湖县', 1593: '湾镇', 1594: '繁昌县', 1595: '繁阳镇', 1596: '南陵县', 1597: '籍山镇' }, '0,1500,1598': { 1599: '铜官山区', 1600: '狮子山区', 1601: '郊区', 1602: '铜陵县', 1603: '五松镇' }, '0,1500,1604': { 1605: '迎江区', 1606: '大观区', 1607: '宜秀区', 1608: '桐城市', 1609: '怀宁县', 1610: '高河镇', 1611: '枞阳县', 1612: '枞阳镇', 1613: '潜山县', 1614: '梅城镇', 1615: '太湖县', 1616: '晋熙镇', 1617: '宿松县', 1618: '孚玉镇', 1619: '望江县', 1620: '雷阳镇', 1621: '岳西县', 1622: '天堂镇' }, '0,1500,1623': { 1624: '屯溪区', 1625: '黄山区', 1626: '徽州区', 1627: '歙县', 1628: '徽城镇', 1629: '休宁县', 1630: '海阳镇', 1631: '黟县', 1632: '碧阳镇', 1633: '祁门县', 1634: '祁山镇' }, '0,1500,1635': { 1636: '金安区', 1637: '裕安区', 1638: '寿县', 1639: '寿春镇', 1640: '霍邱县', 1641: '城关镇', 1642: '舒城县', 1643: '城关镇', 1644: '金寨县', 1645: '梅山镇', 1646: '霍山县', 1647: '衡山镇' }, '0,1500,1648': { 1649: '居巢区', 1650: '庐江县', 1651: '庐城镇', 1652: '无为县', 1653: '无城镇', 1654: '含山县', 1655: '环峰镇', 1656: '和县', 1657: '历阳镇' }, '0,1500,1658': { 1659: '贵池区', 1660: '东至县', 1661: '尧渡镇', 1662: '石台县', 1663: '七里镇', 1664: '青阳县', 1665: '蓉城镇' }, '0,1500,1666': { 1667: '宣州区', 1668: '宁国市', 1669: '郎溪县', 1670: '建平镇', 1671: '广德县', 1672: '桃州镇', 1673: '泾县', 1674: '泾川镇', 1675: '旌德县', 1676: '旌阳镇', 1677: '绩溪县', 1678: '华阳镇' }, '0,1679': { 1680: '福州市', 1699: '南平市', 1713: '莆田市', 1719: '三明市', 1740: '泉州市', 1758: '厦门市', 1765: '漳州市', 1785: '龙岩市', 1798: '宁德市' }, '0,1679,1680': { 1681: '鼓楼区', 1682: '台江区', 1683: '仓山区', 1684: '马尾区', 1685: '晋安区', 1686: '福清市', 1687: '长乐市', 1688: '闽侯县', 1689: '连江县', 1690: '凤城镇', 1691: '罗源县', 1692: '凤山镇', 1693: '闽清县', 1694: '梅城镇', 1695: '永泰县', 1696: '樟城镇', 1697: '平潭县', 1698: '潭城镇' }, '0,1679,1699': { 1700: '延平区', 1701: '邵武市', 1702: '武夷山市', 1703: '建瓯市', 1704: '建阳市', 1705: '顺昌县', 1706: '浦城县', 1707: '光泽县', 1708: '杭川镇', 1709: '松溪县', 1710: '松源镇', 1711: '政和县', 1712: '熊山镇' }, '0,1679,1713': { 1714: '城厢区', 1715: '涵江区', 1716: '荔城区', 1717: '秀屿区', 1718: '仙游县' }, '0,1679,1719': { 1720: '梅列区', 1721: '三元区', 1722: '永安市', 1723: '明溪县', 1724: '雪峰镇', 1725: '清流县', 1726: '龙津镇', 1727: '宁化县', 1728: '翠江镇', 1729: '大田县', 1730: '均溪镇', 1731: '尤溪县', 1732: '城关镇', 1733: '沙县', 1734: '将乐县', 1735: '古镛镇', 1736: '泰宁县', 1737: '杉城镇', 1738: '建宁县', 1739: '濉城镇' }, '0,1679,1740': { 1741: '鲤城区', 1742: '丰泽区', 1743: '洛江区', 1744: '泉港区', 1745: '石狮市', 1746: '晋江市', 1747: '南安市', 1748: '惠安县', 1749: '螺城镇', 1750: '安溪县', 1751: '凤城镇', 1752: '永春县', 1753: '桃城镇', 1754: '德化县', 1755: '浔中镇', 1756: '金门县', 1757: '☆' }, '0,1679,1758': { 1759: '思明区', 1760: '海沧区', 1761: '湖里区', 1762: '集美区', 1763: '同安区', 1764: '翔安区' }, '0,1679,1765': { 1766: '芗城区', 1767: '龙文区', 1768: '龙海市', 1769: '云霄县', 1770: '云陵镇', 1771: '漳浦县', 1772: '绥安镇', 1773: '诏安县', 1774: '南诏镇', 1775: '长泰县', 1776: '武安镇', 1777: '东山县', 1778: '西埔镇', 1779: '南靖县', 1780: '山城镇', 1781: '平和县', 1782: '小溪镇', 1783: '华安县', 1784: '华丰镇' }, '0,1679,1785': { 1786: '新罗区', 1787: '漳平市', 1788: '长汀县', 1789: '汀州镇', 1790: '永定县', 1791: '凤城镇', 1792: '上杭县', 1793: '临江镇', 1794: '武平县', 1795: '平川镇', 1796: '连城县', 1797: '莲峰镇' }, '0,1679,1798': { 1799: '蕉城区', 1800: '福安市', 1801: '福鼎市', 1802: '寿宁县', 1803: '鳌阳镇', 1804: '霞浦县', 1805: '柘荣县', 1806: '双城镇', 1807: '屏南县', 1808: '古峰镇', 1809: '古田县', 1810: '周宁县', 1811: '狮城镇' }, '0,1812': { 1813: '南昌市', 1827: '九江市', 1849: '景德镇市', 1855: '鹰潭市', 1860: '新余市', 1864: '萍乡市', 1873: '赣州市', 1907: '上饶市', 1930: '抚州市', 1952: '宜春市', 1967: '吉安市' }, '0,1812,1813': { 1814: '东湖区', 1815: '西湖区', 1816: '青云谱区', 1817: '湾里区', 1818: '青山湖区', 1819: '南昌县', 1820: '莲塘镇', 1821: '新建县', 1822: '长堎镇', 1823: '安义县', 1824: '龙津镇', 1825: '进贤县', 1826: '民和镇' }, '0,1812,1827': { 1828: '浔阳区', 1829: '庐山区', 1830: '瑞昌市', 1831: '九江县', 1832: '沙河街镇', 1833: '武宁县', 1834: '新宁镇', 1835: '修水县', 1836: '义宁镇', 1837: '永修县', 1838: '涂埠镇', 1839: '德安县', 1840: '蒲亭镇', 1841: '星子县', 1842: '南康镇', 1843: '都昌县', 1844: '都昌镇', 1845: '湖口县', 1846: '双钟镇', 1847: '彭泽县', 1848: '龙城镇' }, '0,1812,1849': { 1850: '珠山区', 1851: '昌江区', 1852: '乐平市', 1853: '浮梁县', 1854: '浮梁镇' }, '0,1812,1855': { 1856: '月湖区', 1857: '贵溪市', 1858: '余江县', 1859: '邓埠镇' }, '0,1812,1860': { 1861: '渝水区', 1862: '分宜县', 1863: '分宜镇' }, '0,1812,1864': { 1865: '安源区', 1866: '湘东区', 1867: '莲花县', 1868: '琴亭镇', 1869: '上栗县', 1870: '上栗镇', 1871: '芦溪县', 1872: '芦溪镇' }, '0,1812,1873': { 1874: '章贡区', 1875: '瑞金市', 1876: '南康市', 1877: '赣县', 1878: '梅林镇', 1879: '信丰县', 1880: '嘉定镇', 1881: '大余县', 1882: '南安镇', 1883: '上犹县', 1884: '东山镇', 1885: '崇义县', 1886: '横水镇', 1887: '安远县', 1888: '欣山镇', 1889: '龙南县', 1890: '龙南镇', 1891: '定南县', 1892: '历市镇', 1893: '全南县', 1894: '城厢镇', 1895: '宁都县', 1896: '梅江镇', 1897: '于都县', 1898: '贡江镇', 1899: '兴国县', 1900: '潋江镇', 1901: '会昌县', 1902: '文武坝镇', 1903: '寻乌县', 1904: '长宁镇', 1905: '石城县', 1906: '琴江镇' }, '0,1812,1907': { 1908: '信州区', 1909: '德兴市', 1910: '上饶县', 1911: '旭日镇', 1912: '广丰县', 1913: '永丰镇', 1914: '玉山县', 1915: '冰溪镇', 1916: '铅山县', 1917: '河口镇', 1918: '横峰县', 1919: '岑阳镇', 1920: '弋阳县', 1921: '弋江镇', 1922: '余干县', 1923: '玉亭镇', 1924: '鄱阳县', 1925: '鄱阳镇', 1926: '万年县', 1927: '陈营镇', 1928: '婺源县', 1929: '紫阳镇' }, '0,1812,1930': { 1931: '临川区', 1932: '南城县', 1933: '建昌镇', 1934: '黎川县', 1935: '日峰镇', 1936: '南丰县', 1937: '琴城镇', 1938: '崇仁县', 1939: '巴山镇', 1940: '乐安县', 1941: '鳌溪镇', 1942: '宜黄县', 1943: '凤冈镇', 1944: '金溪县', 1945: '秀谷镇', 1946: '资溪县', 1947: '鹤城镇', 1948: '东乡县', 1949: '孝岗镇', 1950: '广昌县', 1951: '旴江镇' }, '0,1812,1952': { 1953: '袁州区', 1954: '丰城市', 1955: '樟树市', 1956: '高安市', 1957: '奉新县', 1958: '冯川镇', 1959: '万载县', 1960: '上高县', 1961: '宜丰县', 1962: '新昌镇', 1963: '靖安县', 1964: '双溪镇', 1965: '铜鼓县', 1966: '永宁镇' }, '0,1812,1967': { 1968: '吉州区', 1969: '青原区', 1970: '井冈山市', 1971: '厦坪镇', 1972: '吉安县', 1973: '敦厚镇', 1974: '吉水县', 1975: '文峰镇', 1976: '峡江县', 1977: '水边镇', 1978: '新干县', 1979: '金川镇', 1980: '永丰县', 1981: '恩江镇', 1982: '泰和县', 1983: '澄江镇', 1984: '遂川县', 1985: '泉江镇', 1986: '万安县', 1987: '芙蓉镇', 1988: '安福县', 1989: '平都镇', 1990: '永新县', 1991: '禾川镇' }, '0,1992': { 1993: '济南市', 2006: '青岛市', 2019: '聊城市', 2029: '德州市', 2047: '东营市', 2056: '淄博市', 2068: '潍坊市', 2081: '烟台市', 2095: '威海市', 2100: '日照市', 2107: '临沂市', 2129: '枣庄市', 2136: '济宁市', 2154: '泰安市', 2163: '莱芜市', 2166: '滨州市', 2179: '菏泽市' }, '0,1992,1993': { 1994: '市中区', 1995: '历下区', 1996: '槐荫区', 1997: '天桥区', 1998: '历城区', 1999: '长清区', 2000: '章丘市', 2001: '平阴县', 2002: '平阴镇', 2003: '济阳县', 2004: '济阳镇', 2005: '商河县' }, '0,1992,2006': { 2007: '市南区', 2008: '市北区', 2009: '四方区', 2010: '黄岛区', 2011: '崂山区', 2012: '城阳区', 2013: '李沧区', 2014: '胶州市', 2015: '即墨市', 2016: '平度市', 2017: '胶南市', 2018: '莱西市' }, '0,1992,2019': { 2020: '东昌府区', 2021: '临清市', 2022: '阳谷县', 2023: '莘县', 2024: '茌平县', 2025: '东阿县', 2026: '冠县', 2027: '冠城镇', 2028: '高唐县' }, '0,1992,2029': { 2030: '德城区', 2031: '乐陵市', 2032: '禹城市', 2033: '陵县', 2034: '陵城镇', 2035: '平原县', 2036: '夏津县', 2037: '夏津镇', 2038: '武城县', 2039: '武城镇', 2040: '齐河县', 2041: '晏城镇', 2042: '临邑县', 2043: '宁津县', 2044: '宁津镇', 2045: '庆云县', 2046: '庆云镇' }, '0,1992,2047': { 2048: '东营区', 2049: '河口区', 2050: '垦利县', 2051: '垦利镇', 2052: '利津县', 2053: '利津镇', 2054: '广饶县', 2055: '广饶镇' }, '0,1992,2056': { 2057: '张店区', 2058: '淄川区', 2059: '博山区', 2060: '临淄区', 2061: '周村区', 2062: '桓台县', 2063: '索镇', 2064: '高青县', 2065: '田镇', 2066: '沂源县', 2067: '南麻镇' }, '0,1992,2068': { 2069: '潍城区', 2070: '寒亭区', 2071: '坊子区', 2072: '奎文区', 2073: '安丘市', 2074: '昌邑市', 2075: '高密市', 2076: '青州市', 2077: '诸城市', 2078: '寿光市', 2079: '临朐县', 2080: '昌乐县' }, '0,1992,2081': { 2082: '莱山区', 2083: '芝罘区', 2084: '福山区', 2085: '牟平区', 2086: '栖霞市', 2087: '海阳市', 2088: '龙口市', 2089: '莱阳市', 2090: '莱州市', 2091: '蓬莱市', 2092: '招远市', 2093: '长岛县', 2094: '南长山镇' }, '0,1992,2095': { 2096: '环翠区', 2097: '荣成市', 2098: '乳山市', 2099: '文登市' }, '0,1992,2100': { 2101: '东港区', 2102: '岚山区', 2103: '五莲县', 2104: '洪凝镇', 2105: '莒县', 2106: '城阳镇' }, '0,1992,2107': { 2108: '兰山区', 2109: '罗庄区', 2110: '河东区', 2111: '郯城县', 2112: '郯城镇', 2113: '苍山县', 2114: '卞庄镇', 2115: '莒南县', 2116: '十字路镇', 2117: '沂水县', 2118: '沂水镇', 2119: '蒙阴县', 2120: '蒙阴镇', 2121: '平邑县', 2122: '平邑镇', 2123: '费县', 2124: '费城镇', 2125: '沂南县', 2126: '界湖镇', 2127: '临沭县', 2128: '临沭镇' }, '0,1992,2129': { 2130: '薛城区', 2131: '市中区', 2132: '峄城区', 2133: '台儿庄区', 2134: '山亭区', 2135: '滕州市' }, '0,1992,2136': { 2137: '市中区', 2138: '任城区', 2139: '曲阜市', 2140: '兖州市', 2141: '邹城市', 2142: '微山县', 2143: '鱼台县', 2144: '谷亭镇', 2145: '金乡县', 2146: '金乡镇', 2147: '嘉祥县', 2148: '嘉祥镇', 2149: '汶上县', 2150: '汶上镇', 2151: '泗水县', 2152: '梁山县', 2153: '梁山镇' }, '0,1992,2154': { 2155: '泰山区', 2156: '岱岳区', 2157: '新泰市', 2158: '肥城市', 2159: '宁阳县', 2160: '宁阳镇', 2161: '东平县', 2162: '东平镇' }, '0,1992,2163': { 2164: '莱城区', 2165: '钢城区' }, '0,1992,2166': { 2167: '滨城区', 2168: '惠民县', 2169: '惠民镇', 2170: '阳信县', 2171: '阳信镇', 2172: '无棣县', 2173: '无棣镇', 2174: '沾化县', 2175: '富国镇', 2176: '博兴县', 2177: '博兴镇', 2178: '邹平县' }, '0,1992,2179': { 2180: '牡丹区', 2181: '曹县', 2182: '曹城镇', 2183: '定陶县', 2184: '定陶镇', 2185: '成武县', 2186: '成武镇', 2187: '单县', 2188: '单城镇', 2189: '巨野县', 2190: '巨野镇', 2191: '郓城县', 2192: '郓城镇', 2193: '鄄城县', 2194: '鄄城镇', 2195: '东明县', 2196: '城关镇' }, '0,2197': { 2198: '郑州市', 2212: '开封市', 2228: '三门峡市', 2238: '洛阳市', 2262: '焦作市', 2277: '新乡市', 2296: '鹤壁市', 2304: '安阳市', 2318: '濮阳市', 2330: '商丘市', 2346: '许昌市', 2356: '漯河市', 2364: '平顶山市', 2379: '南阳市', 2400: '信阳市', 2417: '周口市', 2436: '驻马店市', 2455: '济源市' }, '0,2197,2198': { 2199: '中原区', 2200: '二七区', 2201: '管城回族区', 2202: '金水区', 2203: '上街区', 2204: '惠济区', 2205: '新郑市', 2206: '登封市', 2207: '新密市', 2208: '巩义市', 2209: '荥阳市', 2210: '中牟县', 2211: '城关镇' }, '0,2197,2212': { 2213: '鼓楼区', 2214: '龙亭区', 2215: '顺河回族区', 2216: '禹王台区', 2217: '金明区', 2218: '杞县', 2219: '城关镇', 2220: '通许县', 2221: '城关镇', 2222: '尉氏县', 2223: '城关镇', 2224: '开封县', 2225: '城关镇', 2226: '兰考县', 2227: '城关镇' }, '0,2197,2228': { 2229: '湖滨区', 2230: '义马市', 2231: '灵宝市', 2232: '渑池县', 2233: '城关镇', 2234: '陕县', 2235: '大营镇', 2236: '卢氏县', 2237: '城关镇' }, '0,2197,2238': { 2239: '西工区', 2240: '老城区', 2241: '瀍河回族区', 2242: '涧西区', 2243: '吉利区', 2244: '洛龙区', 2245: '偃师市', 2246: '孟津县', 2247: '城关镇', 2248: '新安县', 2249: '城关镇', 2250: '栾川县', 2251: '城关镇', 2252: '嵩县', 2253: '城关镇', 2254: '汝阳县', 2255: '城关镇', 2256: '宜阳县', 2257: '城关镇', 2258: '洛宁县', 2259: '城关镇', 2260: '伊川县', 2261: '城关镇' }, '0,2197,2262': { 2263: '解放区', 2264: '山阳区', 2265: '中站区', 2266: '马村区', 2267: '孟州市', 2268: '沁阳市', 2269: '修武县', 2270: '城关镇', 2271: '博爱县', 2272: '清化镇', 2273: '武陟县', 2274: '木城镇', 2275: '温县', 2276: '温泉镇' }, '0,2197,2277': { 2278: '卫滨区', 2279: '红旗区', 2280: '凤泉区', 2281: '牧野区', 2282: '卫辉市', 2283: '辉县市', 2284: '新乡县', 2285: '新乡市红旗区', 2286: '获嘉县', 2287: '城关镇', 2288: '原阳县', 2289: '城关镇', 2290: '延津县', 2291: '城关镇', 2292: '封丘县', 2293: '城关镇', 2294: '长垣县', 2295: '城关镇' }, '0,2197,2296': { 2297: '淇滨区', 2298: '山城区', 2299: '鹤山区', 2300: '浚县', 2301: '城关镇', 2302: '淇县', 2303: '朝歌镇' }, '0,2197,2304': { 2305: '北关区', 2306: '文峰区', 2307: '殷都区', 2308: '龙安区', 2309: '林州市', 2310: '安阳县', 2311: '汤阴县', 2312: '滑县', 2313: '内黄县' }, '0,2197,2318': { 2319: '华龙区', 2320: '清丰县', 2321: '城关镇', 2322: '南乐县', 2323: '城关镇', 2324: '范县', 2325: '城关镇', 2326: '台前县', 2327: '城关镇', 2328: '濮阳县', 2329: '城关镇' }, '0,2197,2330': { 2331: '梁园区', 2332: '睢阳区', 2333: '永城市', 2334: '虞城县', 2335: '城关镇', 2336: '民权县', 2337: '城关镇', 2338: '宁陵县', 2339: '城关镇', 2340: '睢县', 2341: '城关镇', 2342: '夏邑县', 2343: '城关镇', 2344: '柘城县', 2345: '城关镇' }, '0,2197,2346': { 2347: '魏都区', 2348: '禹州市', 2349: '长葛市', 2350: '许昌县', 2351: '许昌市魏都区', 2352: '鄢陵县', 2353: '安陵镇', 2354: '襄城县', 2355: '城关镇' }, '0,2197,2356': { 2357: '源汇区', 2358: '郾城区', 2359: '召陵区', 2360: '舞阳县', 2361: '舞泉镇', 2362: '临颍县', 2363: '城关镇' }, '0,2197,2364': { 2365: '新华区', 2366: '卫东区', 2367: '湛河区', 2368: '石龙区', 2369: '舞钢市', 2370: '汝州市', 2371: '宝丰县', 2372: '城关镇', 2373: '叶县', 2374: '昆阳镇', 2375: '鲁山县', 2376: '鲁阳镇', 2377: '郏县', 2378: '城关镇' }, '0,2197,2379': { 2380: '卧龙区', 2381: '宛城区', 2382: '邓州市', 2383: '南召县', 2384: '城关镇', 2385: '方城县', 2386: '城关镇', 2387: '西峡县', 2388: '镇平县', 2389: '城关镇', 2390: '内乡县', 2391: '城关镇', 2392: '淅川县', 2393: '社旗县', 2394: '赊店镇', 2395: '唐河县', 2396: '新野县', 2397: '城关镇', 2398: '桐柏县', 2399: '城关镇' }, '0,2197,2400': { 2401: '河区', 2402: '平桥区', 2403: '息县', 2404: '城关镇', 2405: '淮滨县', 2406: '城关镇', 2407: '潢川县', 2408: '光山县', 2409: '固始县', 2410: '城关镇', 2411: '商城县', 2412: '城关镇', 2413: '罗山县', 2414: '城关镇', 2415: '新县', 2416: '新集镇' }, '0,2197,2417': { 2418: '川汇区', 2419: '项城市', 2420: '扶沟县', 2421: '城关镇', 2422: '西华县', 2423: '城关镇', 2424: '商水县', 2425: '城关镇', 2426: '太康县', 2427: '城关镇', 2428: '鹿邑县', 2429: '城关镇', 2430: '郸城县', 2431: '城关镇', 2432: '淮阳县', 2433: '城关镇', 2434: '沈丘县', 2435: '槐店镇' }, '0,2197,2436': { 2437: '驿城区', 2438: '确山县', 2439: '盘龙镇', 2440: '泌阳县', 2441: '泌水镇', 2442: '遂平县', 2443: '灈阳镇', 2444: '西平县', 2445: '上蔡县', 2446: '蔡都镇', 2447: '汝南县', 2448: '汝宁镇', 2449: '平舆县', 2450: '古槐镇', 2451: '新蔡县', 2452: '古吕镇', 2453: '正阳县', 2454: '真阳镇' }, '0,2197,2455': { 5173: '玉泉街道', 5174: '北海街道', 5175: '天坛街道', 5176: '沁园街道', 5177: '济水街道', 5178: '五龙口镇', 5179: '下冶镇', 5180: '轵城镇', 5181: '王屋镇', 5182: '思礼镇', 5183: '邵原镇', 5184: '坡头镇', 5185: '梨林镇', 5186: '克井镇', 5187: '大峪镇', 5188: '承留镇' }, '0,2456': { 2457: '武汉市', 2471: '十堰市', 2485: '襄樊市', 2498: '荆门市', 2506: '孝感市', 2517: '黄冈市', 2535: '鄂州市', 2539: '黄石市', 2547: '咸宁市', 2558: '荆州市', 2570: '宜昌市', 2589: '随州市', 2592: '省直辖县级行政单位', 2598: '恩施州' }, '0,2456,2457': { 2458: '江岸区', 2459: '江汉区', 2460: '硚口区', 2461: '汉阳区', 2462: '武昌区', 2463: '青山区', 2464: '洪山区', 2465: '东西湖区', 2466: '汉南区', 2467: '蔡甸区', 2468: '江夏区', 2469: '黄陂区', 2470: '新洲区' }, '0,2456,2471': { 2472: '张湾区', 2473: '茅箭区', 2474: '丹江口市', 2475: '郧县', 2476: '城关镇', 2477: '竹山县', 2478: '城关镇', 2479: '房县', 2480: '城关镇', 2481: '郧西县', 2482: '城关镇', 2483: '竹溪县', 2484: '城关镇' }, '0,2456,2485': { 2486: '襄城区', 2487: '樊城区', 2488: '襄阳区', 2489: '老河口市', 2490: '枣阳市', 2491: '宜城市', 2492: '南漳县', 2493: '城关镇', 2494: '谷城县', 2495: '城关镇', 2496: '保康县', 2497: '城关镇' }, '0,2456,2498': { 2499: '东宝区', 2500: '掇刀区', 2501: '钟祥市', 2502: '沙洋县', 2503: '沙洋镇', 2504: '京山县', 2505: '新市镇' }, '0,2456,2506': { 2507: '孝南区', 2508: '应城市', 2509: '安陆市', 2510: '汉川市', 2511: '孝昌县', 2512: '花园镇', 2513: '大悟县', 2514: '城关镇', 2515: '云梦县', 2516: '城关镇' }, '0,2456,2517': { 2518: '黄州区', 2519: '麻城市', 2520: '武穴市', 2521: '红安县', 2522: '城关镇', 2523: '罗田县', 2524: '凤山镇', 2525: '英山县', 2526: '温泉镇', 2527: '浠水县', 2528: '清泉镇', 2529: '蕲春县', 2530: '漕河镇', 2531: '黄梅县', 2532: '黄梅镇', 2533: '团风县', 2534: '团风镇' }, '0,2456,2535': { 2536: '鄂城区', 2537: '梁子湖区', 2538: '华容区' }, '0,2456,2539': { 2540: '黄石港区', 2541: '西塞山区', 2542: '下陆区', 2543: '铁山区', 2544: '大冶市', 2545: '阳新县', 2546: '兴国镇' }, '0,2456,2547': { 2548: '咸安区', 2549: '赤壁市', 2550: '嘉鱼县', 2551: '鱼岳镇', 2552: '通城县', 2553: '隽水镇', 2554: '崇阳县', 2555: '天城镇', 2556: '通山县', 2557: '通羊镇' }, '0,2456,2558': { 2559: '沙市区', 2560: '荆州区', 2561: '石首市', 2562: '洪湖市', 2563: '松滋市', 2564: '江陵县', 2565: '郝穴镇', 2566: '公安县', 2567: '斗湖堤镇', 2568: '监利县', 2569: '容城镇' }, '0,2456,2570': { 2571: '西陵区', 2572: '伍家岗区', 2573: '点军区', 2574: '猇亭区', 2575: '夷陵区', 2576: '枝江市', 2577: '宜都市', 2578: '当阳市', 2579: '远安县', 2580: '鸣凤镇', 2581: '兴山县', 2582: '古夫镇', 2583: '秭归县', 2584: '茅坪镇', 2585: '长阳土家族自治县', 2586: '龙舟坪镇', 2587: '五峰土家族自治县', 2588: '五峰镇' }, '0,2456,2589': { 2590: '曾都区', 2591: '广水市' }, '0,2456,2592': { 2593: '仙桃市', 2594: '天门市', 2595: '潜江市', 2596: '神农架林区', 2597: '松柏镇' }, '0,2456,2598': { 2599: '恩施市', 2600: '利川市', 2601: '建始县', 2602: '业州镇', 2603: '巴东县', 2604: '信陵镇', 2605: '宣恩县', 2606: '珠山镇', 2607: '咸丰县', 2608: '高乐山镇', 2609: '来凤县', 2610: '翔凤镇', 2611: '鹤峰县', 2612: '容美镇' }, '0,2613': { 2614: '长沙市', 2628: '张家界市', 2635: '常德市', 2651: '益阳市', 2661: '岳阳市', 2675: '株洲市', 2689: '湘潭市', 2696: '衡阳市', 2714: '郴州市', 2734: '永州市', 2755: '邵阳市', 2776: '怀化市', 2799: '娄底市', 2807: '湘西州' }, '0,2613,2614': { 2615: '长沙市', 2616: '岳麓区', 2617: '芙蓉区', 2618: '天心区', 2619: '开福区', 2620: '雨花区', 2621: '浏阳市', 2622: '长沙县', 2623: '星沙镇', 2624: '望城县', 2625: '高塘岭镇', 2626: '宁乡县', 2627: '玉潭镇' }, '0,2613,2628': { 2629: '永定区', 2630: '武陵源区', 2631: '慈利县', 2632: '零阳镇', 2633: '桑植县', 2634: '澧源镇' }, '0,2613,2635': { 2636: '武陵区', 2637: '鼎城区', 2638: '津市市', 2639: '安乡县', 2640: '城关镇', 2641: '汉寿县', 2642: '龙阳镇', 2643: '澧县', 2644: '澧阳镇', 2645: '临澧县', 2646: '安福镇', 2647: '桃源县', 2648: '漳江镇', 2649: '石门县', 2650: '楚江镇' }, '0,2613,2651': { 2652: '赫山区', 2653: '资阳区', 2654: '沅江市', 2655: '南县', 2656: '南洲镇', 2657: '桃江县', 2658: '桃花江镇', 2659: '安化县', 2660: '东坪镇' }, '0,2613,2661': { 2662: '岳阳楼区', 2663: '君山区', 2664: '云溪区', 2665: '汨罗市', 2666: '临湘市', 2667: '岳阳县', 2668: '荣家湾镇', 2669: '华容县', 2670: '城关镇', 2671: '湘阴县', 2672: '文星镇', 2673: '平江县', 2674: '汉昌镇' }, '0,2613,2675': { 2676: '天元区', 2677: '荷塘区', 2678: '芦淞区', 2679: '石峰区', 2680: '醴陵市', 2681: '株洲县', 2682: '渌口镇', 2683: '攸县', 2684: '城关镇', 2685: '茶陵县', 2686: '城关镇', 2687: '炎陵县', 2688: '霞阳镇' }, '0,2613,2689': { 2690: '岳塘区', 2691: '雨湖区', 2692: '湘乡市', 2693: '韶山市', 2694: '湘潭县', 2695: '易俗河镇' }, '0,2613,2696': { 2697: '雁峰区', 2698: '珠晖区', 2699: '石鼓区', 2700: '蒸湘区', 2701: '南岳区', 2702: '常宁市', 2703: '耒阳市', 2704: '衡阳县', 2705: '西渡镇', 2706: '衡南县', 2707: '云集镇', 2708: '衡山县', 2709: '开云镇', 2710: '衡东县', 2711: '城关镇', 2712: '祁东县', 2713: '洪桥镇' }, '0,2613,2714': { 2715: '北湖区', 2716: '苏仙区', 2717: '资兴市', 2718: '桂阳县', 2719: '城关镇', 2720: '永兴县', 2721: '城关镇', 2722: '宜章县', 2723: '城关镇', 2724: '嘉禾县', 2725: '城关镇', 2726: '临武县', 2727: '城关镇', 2728: '汝城县', 2729: '城关镇', 2730: '桂东县', 2731: '城关镇', 2732: '安仁县', 2733: '城关镇' }, '0,2613,2734': { 2735: '冷水滩区', 2736: '零陵区', 2737: '东安县', 2738: '白牙市镇', 2739: '道县', 2740: '道江镇', 2741: '宁远县', 2742: '舜陵镇', 2743: '江永县', 2744: '潇浦镇', 2745: '蓝山县', 2746: '塔峰镇', 2747: '新田县', 2748: '龙泉镇', 2749: '双牌县', 2750: '泷泊镇', 2751: '祁阳县', 2752: '浯溪镇', 2753: '江华瑶族自治县', 2754: '沱江镇' }, '0,2613,2755': { 2756: '双清区', 2757: '大祥区', 2758: '北塔区', 2759: '武冈市', 2760: '邵东县', 2761: '两市镇', 2762: '邵阳县', 2763: '塘渡口镇', 2764: '新邵县', 2765: '酿溪镇', 2766: '隆回县', 2767: '桃洪镇', 2768: '洞口县', 2769: '洞口镇', 2770: '绥宁县', 2771: '长铺镇', 2772: '新宁县', 2773: '金石镇', 2774: '城步苗族自治县', 2775: '儒林镇' }, '0,2613,2776': { 2777: '鹤城区', 2778: '洪江市', 2779: '沅陵县', 2780: '沅陵镇', 2781: '辰溪县', 2782: '辰阳镇', 2783: '溆浦县', 2784: '卢峰镇', 2785: '中方县', 2786: '中方镇', 2787: '会同县', 2788: '林城镇', 2789: '麻阳苗族自治县', 2790: '高村镇', 2791: '新晃侗族自治县', 2792: '新晃镇', 2793: '芷江侗族自治县', 2794: '芷江镇', 2795: '靖州苗族侗族自治县', 2796: '渠阳镇', 2797: '通道侗族自治县', 2798: '双江镇' }, '0,2613,2799': { 2800: '娄星区', 2801: '冷水江市', 2802: '涟源市', 2803: '双峰县', 2804: '永丰镇', 2805: '新化县', 2806: '上梅镇' }, '0,2613,2807': { 2808: '吉首市', 2809: '泸溪县', 2810: '白沙镇', 2811: '凤凰县', 2812: '沱江镇', 2813: '花垣县', 2814: '花垣镇', 2815: '保靖县', 2816: '迁陵镇', 2817: '古丈县', 2818: '古阳镇', 2819: '永顺县', 2820: '灵溪镇', 2821: '龙山县' }, '0,2822': { 2823: '广州市', 2836: '深圳市', 2843: '清远市', 2857: '韶关市', 2872: '河源市', 2884: '梅州市', 2899: '潮州市', 2905: '汕头市', 2914: '揭阳市', 2923: '汕尾市', 2930: '惠州市', 2937: '东莞市', 2938: '深圳市', 2945: '珠海市', 2949: '中山市', 2950: '江门市', 2958: '佛山市', 2964: '肇庆市', 2976: '云浮市', 2985: '阳江市', 2992: '茂名市', 3000: '湛江市' }, '0,2822,2823': { 2824: '越秀区', 2825: '荔湾区', 2826: '海珠区', 2827: '天河区', 2828: '白云区', 2829: '黄埔区', 2830: '番禺区', 2831: '花都区', 2832: '南沙区', 2833: '萝岗区', 2834: '增城市', 2835: '从化市' }, '0,2822,2836': { 2837: '福田区', 2838: '罗湖区', 2839: '南山区', 2840: '宝安区', 2841: '龙岗区', 2842: '盐田区' }, '0,2822,2843': { 2844: '清城区', 2845: '英德市', 2846: '连州市', 2847: '佛冈县', 2848: '石角镇', 2849: '阳山县', 2850: '阳城镇', 2851: '清新县', 2852: '太和镇', 2853: '连山壮族瑶族自治县', 2854: '吉田镇', 2855: '连南瑶族自治县', 2856: '三江镇' }, '0,2822,2857': { 2858: '浈江区', 2859: '武江区', 2860: '曲江区', 2861: '乐昌市', 2862: '南雄市', 2863: '始兴县', 2864: '太平镇', 2865: '仁化县', 2866: '仁化镇', 2867: '翁源县', 2868: '龙仙镇', 2869: '新丰县', 2870: '乳源瑶族自治县', 2871: '乳城镇' }, '0,2822,2872': { 2873: '源城区', 2874: '紫金县', 2875: '紫城镇', 2876: '龙川县', 2877: '老隆镇', 2878: '连平县', 2879: '元善镇', 2880: '和平县', 2881: '阳明镇', 2882: '东源县', 2883: '仙塘镇' }, '0,2822,2884': { 2885: '梅江区', 2886: '兴宁市', 2887: '梅县', 2888: '程江镇', 2889: '大埔县', 2890: '湖寮镇', 2891: '丰顺县', 2892: '汤坑镇', 2893: '五华县', 2894: '水寨镇', 2895: '平远县', 2896: '大柘镇', 2897: '蕉岭县', 2898: '蕉城镇' }, '0,2822,2899': { 2900: '湘桥区', 2901: '潮安县', 2902: '庵埠镇', 2903: '饶平县', 2904: '黄冈镇' }, '0,2822,2905': { 2906: '金平区', 2907: '濠江区', 2908: '龙湖区', 2909: '潮阳区', 2910: '潮南区', 2911: '澄海区', 2912: '南澳县', 2913: '后宅镇' }, '0,2822,2914': { 2915: '榕城区', 2916: '普宁市', 2917: '揭东县', 2918: '曲溪镇', 2919: '揭西县', 2920: '河婆镇', 2921: '惠来县', 2922: '惠城镇' }, '0,2822,2923': { 2924: '城区', 2925: '陆丰市', 2926: '海丰县', 2927: '海城镇', 2928: '陆河县', 2929: '河田镇' }, '0,2822,2930': { 2931: '惠城区', 2932: '惠阳区', 2933: '博罗县', 2934: '罗阳镇', 2935: '惠东县', 2936: '龙门县' }, '0,2822,2937': { 5700: '东城区', 5701: '莞城区', 5702: '南城区', 5703: '长安镇', 5704: '虎门镇', 5705: '寮步镇', 5706: '大岭山镇', 5707: '常平镇', 5708: '万江区', 5709: '中堂镇', 5710: '大朗镇', 5711: '后街镇', 5712: '凤岗镇', 5713: '横沥镇', 5714: '东坑镇', 5715: '黄江镇', 5716: '樟木头镇', 5717: '塘厦镇', 5718: '道滘镇', 5719: '清溪镇', 5720: '沙田镇', 5721: '高步镇', 5722: '石龙镇', 5723: '石排镇' }, '0,2822,2938': { 2939: '福田区', 2940: '罗湖区', 2941: '南山区', 2942: '宝安区', 2943: '龙岗区', 2944: '盐田区' }, '0,2822,2945': { 2946: '香洲区', 2947: '斗门区', 2948: '金湾区' }, '0,2822,2950': { 2951: '江海区', 2952: '蓬江区', 2953: '新会区', 2954: '恩平市', 2955: '台山市', 2956: '开平市', 2957: '鹤山市' }, '0,2822,2949': { 5900: '中山市区', 5901: '火炬开发区', 5902: '小榄镇', 5903: '古镇', 5904: '大涌镇', 5905: '南朗镇', 5906: '坦洲镇', 5907: '黄圃镇', 5908: '三乡镇', 5909: '东凤镇', 5910: '横栏镇', 5911: '三角镇', 5912: '南头镇', 5913: '民众镇', 5914: '沙溪镇', 5915: '五桂山镇', 5916: '阜沙镇', 5917: '东升镇', 5918: '板芙镇', 5919: '神湾镇', 5920: '港口镇' }, '0,2822,2958': { 2959: '禅城区', 2960: '南海区', 2961: '顺德区', 2962: '三水区', 2963: '高明区' }, '0,2822,2964': { 2965: '端州区', 2966: '鼎湖区', 2967: '高要市', 2968: '四会市', 2969: '广宁县', 2970: '南街镇', 2971: '怀集县', 2972: '怀城镇', 2973: '封开县', 2974: '江口镇', 2975: '德庆县' }, '0,2822,2976': { 2977: '云城区', 2978: '罗定市', 2979: '云安县', 2980: '六都镇', 2981: '新兴县', 2982: '新城镇', 2983: '郁南县', 2984: '都城镇' }, '0,2822,2985': { 2986: '江城区', 2987: '阳春市', 2988: '阳西县', 2989: '织镇', 2990: '阳东县', 2991: '东城镇' }, '0,2822,2992': { 2993: '茂南区', 2994: '茂港区', 2995: '化州市', 2996: '信宜市', 2997: '高州市', 2998: '电白县', 2999: '水东镇' }, '0,2822,3000': { 3001: '赤坎区', 3002: '霞山区', 3003: '坡头区', 3004: '麻章区', 3005: '吴川市', 3006: '廉江市', 3007: '雷州市', 3008: '遂溪县', 3009: '遂城镇', 3010: '徐闻县', 3011: '撤销广州市东山区', 3012: '芳村区', 3013: '设立广州市南沙区', 3014: '萝岗区' }, '0,3015': { 3016: '南宁市', 3029: '桂林市', 3059: '柳州市', 3076: '梧州市', 3087: '贵港市', 3094: '玉林市', 3105: '钦州市', 3112: '北海市', 3118: '防城港市', 3124: '崇左市', 3137: '百色市', 3161: '河池市', 3182: '来宾市', 3193: '贺州市' }, '0,3015,3016': { 3017: '青秀区', 3018: '兴宁区', 3019: '江南区', 3020: '西乡塘区', 3021: '良庆区', 3022: '邕宁区', 3023: '武鸣县', 3024: '横县', 3025: '宾阳县', 3026: '上林县', 3027: '隆安县', 3028: '马山县' }, '0,3015,3029': { 3030: '象山区', 3031: '叠彩区', 3032: '秀峰区', 3033: '七星区', 3034: '雁山区', 3035: '阳朔县', 3036: '阳朔镇', 3037: '临桂县', 3038: '临桂镇', 3039: '灵川县', 3040: '灵川镇', 3041: '全州县', 3042: '全州镇', 3043: '兴安县', 3044: '兴安镇', 3045: '永福县', 3046: '永福镇', 3047: '灌阳县', 3048: '灌阳镇', 3049: '资源县', 3050: '资源镇', 3051: '平乐县', 3052: '平乐镇', 3053: '荔浦县', 3054: '荔城镇', 3055: '龙胜各族自治县', 3056: '龙胜镇', 3057: '恭城瑶族自治县', 3058: '恭城镇' }, '0,3015,3059': { 3060: '城中区', 3061: '鱼峰区', 3062: '柳南区', 3063: '柳北区', 3064: '柳江县', 3065: '拉堡镇', 3066: '柳城县', 3067: '大埔镇', 3068: '鹿寨县', 3069: '鹿寨镇', 3070: '融安县', 3071: '长安镇', 3072: '三江侗族自治县', 3073: '古宜镇', 3074: '融水苗族自治县', 3075: '融水镇' }, '0,3015,3076': { 3077: '万秀区', 3078: '蝶山区', 3079: '长洲区', 3080: '岑溪市', 3081: '苍梧县', 3082: '龙圩镇', 3083: '藤县', 3084: '藤州镇', 3085: '蒙山县', 3086: '蒙山镇' }, '0,3015,3087': { 3088: '港北区', 3089: '港南区', 3090: '覃塘区', 3091: '桂平市', 3092: '平南县', 3093: '平南镇' }, '0,3015,3094': { 3095: '玉州区', 3096: '北流市', 3097: '兴业县', 3098: '石南镇', 3099: '容县', 3100: '容州镇', 3101: '陆川县', 3102: '陆城镇', 3103: '博白县', 3104: '博白镇' }, '0,3015,3105': { 3106: '钦南区', 3107: '钦北区', 3108: '灵山县', 3109: '灵城镇', 3110: '浦北县', 3111: '小江镇' }, '0,3015,3112': { 3113: '海城区', 3114: '银海区', 3115: '铁山港区', 3116: '合浦县', 3117: '廉州镇' }, '0,3015,3118': { 3119: '港口区', 3120: '防城区', 3121: '东兴市', 3122: '上思县', 3123: '思阳镇' }, '0,3015,3124': { 3125: '江州区', 3126: '凭祥市', 3127: '扶绥县', 3128: '新宁镇', 3129: '大新县', 3130: '桃城镇', 3131: '天等县', 3132: '天等镇', 3133: '宁明县', 3134: '城中镇', 3135: '龙州县', 3136: '龙州镇' }, '0,3015,3137': { 3138: '右江区', 3139: '田阳县', 3140: '田州镇', 3141: '田东县', 3142: '平马镇', 3143: '平果县', 3144: '马头镇', 3145: '德保县', 3146: '城关镇', 3147: '靖西县', 3148: '新靖镇', 3149: '那坡县', 3150: '城厢镇', 3151: '凌云县', 3152: '泗城镇', 3153: '乐业县', 3154: '同乐镇', 3155: '西林县', 3156: '八达镇', 3157: '田林县', 3158: '乐里镇', 3159: '隆林各族自治县', 3160: '新州镇' }, '0,3015,3161': { 3162: '金城江区', 3163: '宜州市', 3164: '南丹县', 3165: '城关镇', 3166: '天峨县', 3167: '六排镇', 3168: '凤山县', 3169: '凤城镇', 3170: '东兰县', 3171: '东兰镇', 3172: '巴马瑶族自治县', 3173: '巴马镇', 3174: '都安瑶族自治县', 3175: '安阳镇', 3176: '大化瑶族自治县', 3177: '大化镇', 3178: '罗城仫佬族自治县', 3179: '东门镇', 3180: '环江毛南族自治县', 3181: '思恩镇' }, '0,3015,3182': { 3183: '兴宾区', 3184: '合山市', 3185: '象州县', 3186: '象州镇', 3187: '武宣县', 3188: '武宣镇', 3189: '忻城县', 3190: '城关镇', 3191: '金秀瑶族自治县', 3192: '金秀镇' }, '0,3015,3193': { 3194: '八步区', 3195: '昭平县', 3196: '昭平镇', 3197: '钟山县', 3198: '钟山镇', 3199: '富川瑶族自治县', 3200: '富阳镇' }, '0,3201': { 3202: '海口市', 3207: '三亚市', 3208: '省直辖行政单位' }, '0,3201,3202': { 3203: '龙华区', 3204: '秀英区', 3205: '琼山区', 3206: '美兰区' }, '0,3201,3207': { 5923: '其他区' }, '0,3201,3208': { 3209: '文昌市', 3210: '琼海市', 3211: '万宁市', 3212: '五指山市', 3213: '东方市', 3214: '儋州市', 3215: '临高县', 3216: '临城镇', 3217: '澄迈县', 3218: '金江镇', 3219: '定安县', 3220: '定城镇', 3221: '屯昌县', 3222: '屯城镇', 3223: '昌江黎族自治县', 3224: '石碌镇', 3225: '白沙黎族自治县', 3226: '牙叉镇', 3227: '琼中黎族苗族自治县', 3228: '营根镇', 3229: '陵水黎族自治县', 3230: '椰林镇', 3231: '保亭黎族苗族自治县', 3232: '保城镇', 3233: '乐东黎族自治县', 3234: '抱由镇' }, '0,3235': { 3236: '成都市', 3261: '广元市', 3273: '绵阳市', 3289: '德阳市', 3298: '南充市', 3313: '广安市', 3322: '遂宁市', 3331: '内江市', 3340: '乐山市', 3358: '自贡市', 3367: '泸州市', 3379: '宜宾市', 3399: '攀枝花市', 3407: '巴中市', 3415: '达州市', 3428: '资阳市', 3435: '眉山市', 3447: '雅安市', 3463: '阿坝州', 3490: '甘孜州', 3527: '凉山州' }, '0,3235,3236': { 3237: '青羊区', 3238: '锦江区', 3239: '金牛区', 3240: '武侯区', 3241: '成华区', 3242: '龙泉驿区', 3243: '青白江区', 3244: '新都区', 3245: '温江区', 3246: '都江堰市', 3247: '彭州市', 3248: '邛崃市', 3249: '崇州市', 3250: '金堂县', 3251: '赵镇', 3252: '双流县', 3253: '郫县', 3254: '郫筒镇', 3255: '大邑县', 3256: '晋原镇', 3257: '蒲江县', 3258: '鹤山镇', 3259: '新津县', 3260: '五津镇' }, '0,3235,3261': { 3262: '市中区', 3263: '元坝区', 3264: '朝天区', 3265: '旺苍县', 3266: '东河镇', 3267: '青川县', 3268: '乔庄镇', 3269: '剑阁县', 3270: '下寺镇', 3271: '苍溪县', 3272: '陵江镇' }, '0,3235,3273': { 3274: '涪城区', 3275: '游仙区', 3276: '江油市', 3277: '三台县', 3278: '潼川镇', 3279: '盐亭县', 3280: '云溪镇', 3281: '安县', 3282: '花荄镇', 3283: '梓潼县', 3284: '文昌镇', 3285: '北川羌族自治县', 3286: '曲山镇', 3287: '平武县', 3288: '龙安镇' }, '0,3235,3289': { 3290: '旌阳区', 3291: '什邡市', 3292: '广汉市', 3293: '绵竹市', 3294: '罗江县', 3295: '罗江镇', 3296: '中江县', 3297: '凯江镇' }, '0,3235,3298': { 3299: '顺庆区', 3300: '高坪区', 3301: '嘉陵区', 3302: '阆中市', 3303: '南部县', 3304: '南隆镇', 3305: '营山县', 3306: '朗池镇', 3307: '蓬安县', 3308: '周口镇', 3309: '仪陇县', 3310: '新政镇', 3311: '西充县', 3312: '晋城镇' }, '0,3235,3313': { 3314: '广安区', 3315: '华蓥市', 3316: '岳池县', 3317: '九龙镇', 3318: '武胜县', 3319: '沿口镇', 3320: '邻水县', 3321: '鼎屏镇' }, '0,3235,3322': { 3323: '船山区', 3324: '安居区', 3325: '蓬溪县', 3326: '赤城镇', 3327: '射洪县', 3328: '太和镇', 3329: '大英县', 3330: '蓬莱镇' }, '0,3235,3331': { 3332: '市中区', 3333: '东兴区', 3334: '威远县', 3335: '严陵镇', 3336: '资中县', 3337: '重龙镇', 3338: '隆昌县', 3339: '金鹅镇' }, '0,3235,3340': { 3341: '市中区', 3342: '沙湾区', 3343: '五通桥区', 3344: '金口河区', 3345: '峨眉山市', 3346: '犍为县', 3347: '玉津镇', 3348: '井研县', 3349: '研城镇', 3350: '夹江县', 3351: '漹城镇', 3352: '沐川县', 3353: '沐溪镇', 3354: '峨边彝族自治县', 3355: '沙坪镇', 3356: '马边彝族自治县', 3357: '民建镇' }, '0,3235,3358': { 3359: '自流井区', 3360: '大安区', 3361: '贡井区', 3362: '沿滩区', 3363: '荣县', 3364: '旭阳镇', 3365: '富顺县', 3366: '富世镇' }, '0,3235,3367': { 3368: '江阳区', 3369: '纳溪区', 3370: '龙马潭区', 3371: '泸县', 3372: '福集镇', 3373: '合江县', 3374: '合江镇', 3375: '叙永县', 3376: '叙永镇', 3377: '古蔺县', 3378: '古蔺镇' }, '0,3235,3379': { 3380: '翠屏区', 3381: '宜宾县', 3382: '柏溪镇', 3383: '南溪县', 3384: '南溪镇', 3385: '江安县', 3386: '江安镇', 3387: '长宁县', 3388: '长宁镇', 3389: '高县', 3390: '庆符镇', 3391: '筠连县', 3392: '筠连镇', 3393: '珙县', 3394: '巡场镇', 3395: '兴文县', 3396: '中城镇', 3397: '屏山县', 3398: '屏山镇' }, '0,3235,3399': { 3400: '东区', 3401: '西区', 3402: '仁和区', 3403: '米易县', 3404: '攀莲镇', 3405: '盐边县', 3406: '桐子林镇' }, '0,3235,3407': { 3408: '巴州区', 3409: '通江县', 3410: '诺江镇', 3411: '南江县', 3412: '南江镇', 3413: '平昌县', 3414: '江口镇' }, '0,3235,3415': { 3416: '通川区', 3417: '万源市', 3418: '达县', 3419: '南外镇', 3420: '宣汉县', 3421: '东乡镇', 3422: '开江县', 3423: '新宁镇', 3424: '大竹县', 3425: '竹阳镇', 3426: '渠县', 3427: '渠江镇' }, '0,3235,3428': { 3429: '雁江区', 3430: '简阳市', 3431: '乐至县', 3432: '天池镇', 3433: '安岳县', 3434: '岳阳镇' }, '0,3235,3435': { 3436: '东坡区', 3437: '仁寿县', 3438: '文林镇', 3439: '彭山县', 3440: '凤鸣镇', 3441: '洪雅县', 3442: '洪川镇', 3443: '丹棱县', 3444: '丹棱镇', 3445: '青神县', 3446: '城厢镇' }, '0,3235,3447': { 3448: '雨城区', 3449: '名山县', 3450: '蒙阳镇', 3451: '荥经县', 3452: '严道镇', 3453: '汉源县', 3454: '富林镇', 3455: '石棉县', 3456: '新棉镇', 3457: '天全县', 3458: '城厢镇', 3459: '芦山县', 3460: '芦阳镇', 3461: '宝兴县', 3462: '穆坪镇' }, '0,3235,3463': { 3464: '马尔康县', 3465: '马尔康镇', 3466: '汶川县', 3467: '威州镇', 3468: '理县', 3469: '杂谷脑镇', 3470: '茂县', 3471: '凤仪镇', 3472: '松潘县', 3473: '进安镇', 3474: '九寨沟县', 3475: '永乐镇', 3476: '金川县', 3477: '金川镇', 3478: '小金县', 3479: '美兴镇', 3480: '黑水县', 3481: '芦花镇', 3482: '壤塘县', 3483: '壤柯镇', 3484: '阿坝县', 3485: '阿坝镇', 3486: '若尔盖县', 3487: '达扎寺镇', 3488: '红原县', 3489: '邛溪镇' }, '0,3235,3490': { 3491: '康定县', 3492: '炉城镇', 3493: '泸定县', 3494: '泸桥镇', 3495: '丹巴县', 3496: '章谷镇', 3497: '九龙县', 3498: '呷尔镇', 3499: '雅江县', 3500: '河口镇', 3501: '道孚县', 3502: '鲜水镇', 3503: '炉霍县', 3504: '新都镇', 3505: '甘孜县', 3506: '甘孜镇', 3507: '新龙县', 3508: '茹龙镇', 3509: '德格县', 3510: '更庆镇', 3511: '白玉县', 3512: '建设镇', 3513: '石渠县', 3514: '尼呷镇', 3515: '色达县', 3516: '色柯镇', 3517: '理塘县', 3518: '高城镇', 3519: '巴塘县', 3520: '夏邛镇', 3521: '乡城县', 3522: '桑披镇', 3523: '稻城县', 3524: '金珠镇', 3525: '得荣县', 3526: '松麦镇' }, '0,3235,3527': { 3528: '西昌市', 3529: '盐源县', 3530: '盐井镇', 3531: '德昌县', 3532: '德州镇', 3533: '会理县', 3534: '城关镇', 3535: '会东县', 3536: '会东镇', 3537: '宁南县', 3538: '披砂镇', 3539: '普格县', 3540: '普基镇', 3541: '布拖县', 3542: '特木里镇', 3543: '金阳县', 3544: '天地坝镇', 3545: '昭觉县', 3546: '新城镇', 3547: '喜德县', 3548: '光明镇', 3549: '冕宁县', 3550: '城厢镇', 3551: '越西县', 3552: '越城镇', 3553: '甘洛县', 3554: '新市坝镇', 3555: '美姑县', 3556: '巴普镇', 3557: '雷波县', 3558: '锦城镇', 3559: '木里藏族自治县', 3560: '乔瓦镇' }, '0,3561': { 3562: '贵阳市', 3576: '六盘水市', 3583: '遵义市', 3608: '安顺市', 3620: '毕节地区', 3636: '铜仁地区', 3656: '黔东南州', 3688: '黔南州', 3711: '黔西南州' }, '0,3561,3562': { 3563: '乌当区', 3564: '南明区', 3565: '云岩区', 3566: '花溪区', 3567: '白云区', 3568: '小河区', 3569: '清镇市', 3570: '开阳县', 3571: '城关镇', 3572: '修文县', 3573: '龙场镇', 3574: '息烽县', 3575: '永靖镇' }, '0,3561,3576': { 3577: '钟山区', 3578: '盘县', 3579: '红果镇', 3580: '六枝特区', 3581: '平寨镇', 3582: '水城县' }, '0,3561,3583': { 3584: '红花岗区', 3585: '汇川区', 3586: '赤水市', 3587: '仁怀市', 3588: '遵义县', 3589: '南白镇', 3590: '桐梓县', 3591: '娄山关镇', 3592: '绥阳县', 3593: '洋川镇', 3594: '正安县', 3595: '凤仪镇', 3596: '凤冈县', 3597: '龙泉镇', 3598: '湄潭县', 3599: '湄江镇', 3600: '余庆县', 3601: '白泥镇', 3602: '习水县', 3603: '东皇镇', 3604: '道真仡佬族苗族自治县', 3605: '玉溪镇', 3606: '务川仡佬族苗族自治县', 3607: '都濡镇' }, '0,3561,3608': { 3609: '西秀区', 3610: '平坝县', 3611: '城关镇', 3612: '普定县', 3613: '城关镇', 3614: '关岭布依族苗族自治县', 3615: '关索镇', 3616: '镇宁布依族苗族自治县', 3617: '城关镇', 3618: '紫云苗族布依族自治县', 3619: '松山镇' }, '0,3561,3620': { 3621: '毕节市', 3622: '大方县', 3623: '大方镇', 3624: '黔西县', 3625: '城关镇', 3626: '金沙县', 3627: '城关镇', 3628: '织金县', 3629: '城关镇', 3630: '纳雍县', 3631: '雍熙镇', 3632: '赫章县', 3633: '城关镇', 3634: '威宁彝族回族苗族自治县', 3635: '草海镇' }, '0,3561,3636': { 3637: '铜仁市', 3638: '江口县', 3639: '双江镇', 3640: '石阡县', 3641: '汤山镇', 3642: '思南县', 3643: '思唐镇', 3644: '德江县', 3645: '青龙镇', 3646: '玉屏侗族自治县', 3647: '平溪镇', 3648: '印江土家族苗族自治县', 3649: '峨岭镇', 3650: '沿河土家族自治县', 3651: '和平镇', 3652: '松桃苗族自治县', 3653: '蓼皋镇', 3654: '万山特区', 3655: '万山镇' }, '0,3561,3656': { 3657: '凯里市', 3658: '黄平县', 3659: '新州镇', 3660: '施秉县', 3661: '城关镇', 3662: '三穗县', 3663: '八弓镇', 3664: '镇远县', 3665: '阳镇', 3666: '岑巩县', 3667: '思旸镇', 3668: '天柱县', 3669: '凤城镇', 3670: '锦屏县', 3671: '三江镇', 3672: '剑河县', 3673: '革东镇', 3674: '台江县', 3675: '台拱镇', 3676: '黎平县', 3677: '德凤镇', 3678: '榕江县', 3679: '古州镇', 3680: '从江县', 3681: '丙妹镇', 3682: '雷山县', 3683: '丹江镇', 3684: '麻江县', 3685: '杏山镇', 3686: '丹寨县', 3687: '龙泉镇' }, '0,3561,3688': { 3689: '都匀市', 3690: '福泉市', 3691: '荔波县', 3692: '玉屏镇', 3693: '贵定县', 3694: '城关镇', 3695: '瓮安县', 3696: '雍阳镇', 3697: '独山县', 3698: '城关镇', 3699: '平塘县', 3700: '平湖镇', 3701: '罗甸县', 3702: '龙坪镇', 3703: '长顺县', 3704: '长寨镇', 3705: '龙里县', 3706: '龙山镇', 3707: '惠水县', 3708: '和平镇', 3709: '三都水族自治县', 3710: '三合镇' }, '0,3561,3711': { 3712: '兴义市', 3713: '兴仁县', 3714: '城关镇', 3715: '普安县', 3716: '盘水镇', 3717: '晴隆县', 3718: '莲城镇', 3719: '贞丰县', 3720: '珉谷镇', 3721: '望谟县', 3722: '复兴镇', 3723: '册亨县', 3724: '者楼镇', 3725: '安龙县', 3726: '新安镇', 3727: '剑河县人民政府驻地由柳川镇迁至革东镇' }, '0,3728': { 3729: '昆明市', 3752: '曲靖市', 3769: '玉溪市', 3787: '保山市', 3797: '昭通市', 3819: '丽江市', 3829: '思茅市', 3849: '临沧市', 3865: '德宏州', 3874: '怒江州', 3884: '迪庆州', 3891: '大理州', 3915: '楚雄州', 3935: '红河州', 3960: '文山州', 3977: '西双版纳州' }, '0,3728,3729': { 3730: '盘龙区', 3731: '五华区', 3732: '官渡区', 3733: '西山区', 3734: '东川区', 3735: '安宁市', 3736: '呈贡县', 3737: '龙城镇', 3738: '晋宁县', 3739: '昆阳镇', 3740: '富民县', 3741: '永定镇', 3742: '宜良县', 3743: '匡远镇', 3744: '嵩明县', 3745: '嵩阳镇', 3746: '石林彝族自治县', 3747: '鹿阜镇', 3748: '禄劝彝族苗族自治县', 3749: '屏山镇', 3750: '寻甸回族彝族自治县', 3751: '仁德镇' }, '0,3728,3752': { 3753: '麒麟区', 3754: '宣威市', 3755: '马龙县', 3756: '通泉镇', 3757: '沾益县', 3758: '西平镇', 3759: '富源县', 3760: '中安镇', 3761: '罗平县', 3762: '罗雄镇', 3763: '师宗县', 3764: '丹凤镇', 3765: '陆良县', 3766: '中枢镇', 3767: '会泽县', 3768: '金钟镇' }, '0,3728,3769': { 3770: '红塔区', 3771: '江川县', 3772: '大街镇', 3773: '澄江县', 3774: '凤麓镇', 3775: '通海县', 3776: '秀山镇', 3777: '华宁县', 3778: '宁州镇', 3779: '易门县', 3780: '龙泉镇', 3781: '峨山彝族自治县', 3782: '双江镇', 3783: '新平彝族傣族自治县', 3784: '桂山镇', 3785: '元江哈尼族彝族傣族自治县', 3786: '澧江镇' }, '0,3728,3787': { 3788: '隆阳区', 3789: '施甸县', 3790: '甸阳镇', 3791: '腾冲县', 3792: '腾越镇', 3793: '龙陵县', 3794: '龙山镇', 3795: '昌宁县', 3796: '田园镇' }, '0,3728,3797': { 3798: '昭阳区', 3799: '鲁甸县', 3800: '文屏镇', 3801: '巧家县', 3802: '新华镇', 3803: '盐津县', 3804: '盐井镇', 3805: '大关县', 3806: '翠华镇', 3807: '永善县', 3808: '溪落渡镇', 3809: '绥江县', 3810: '中城镇', 3811: '镇雄县', 3812: '乌峰镇', 3813: '彝良县', 3814: '角奎镇', 3815: '威信县', 3816: '扎西镇', 3817: '水富县', 3818: '向家坝镇' }, '0,3728,3819': { 3820: '古城区', 3821: '永胜县', 3822: '永北镇', 3823: '华坪县', 3824: '中心镇', 3825: '玉龙纳西族自治县', 3826: '黄山镇', 3827: '宁蒗彝族自治县', 3828: '大兴镇' }, '0,3728,3829': { 3830: '翠云区', 3831: '普洱哈尼族彝族自治县', 3832: '宁洱镇', 3833: '墨江哈尼族自治县', 3834: '联珠镇', 3835: '景东彝族自治县', 3836: '锦屏镇', 3837: '景谷傣族彝族自治县', 3838: '威远镇', 3839: '镇沅彝族哈尼族拉祜族自治县', 3840: '恩乐镇', 3841: '江城哈尼族彝族自治县', 3842: '勐烈镇', 3843: '孟连傣族拉祜族佤族自治县', 3844: '娜允镇', 3845: '澜沧拉祜族自治县', 3846: '勐朗镇', 3847: '西盟佤族自治县', 3848: '勐梭镇' }, '0,3728,3849': { 3850: '临翔区', 3851: '凤庆县', 3852: '凤山镇', 3853: '云县', 3854: '爱华镇', 3855: '永德县', 3856: '德党镇', 3857: '镇康县', 3858: '南伞镇', 3859: '双江拉祜族佤族布朗族傣族自治县', 3860: '勐勐镇', 3861: '耿马傣族佤族自治县', 3862: '耿马镇', 3863: '沧源佤族自治县', 3864: '勐董镇' }, '0,3728,3865': { 3866: '潞西市', 3867: '瑞丽市', 3868: '梁河县', 3869: '遮岛镇', 3870: '盈江县', 3871: '平原镇', 3872: '陇川县', 3873: '章凤镇' }, '0,3728,3874': { 3875: '泸水县六库镇', 3876: '泸水县', 3877: '六库镇', 3878: '福贡县', 3879: '上帕镇', 3880: '贡山独龙族怒族自治县', 3881: '茨开镇', 3882: '兰坪白族普米族自治县', 3883: '金顶镇' }, '0,3728,3884': { 3885: '香格里拉县', 3886: '建塘镇', 3887: '德钦县', 3888: '升平镇', 3889: '维西傈僳族自治县', 3890: '保和镇' }, '0,3728,3891': { 3892: '大理市', 3893: '祥云县', 3894: '祥城镇', 3895: '宾川县', 3896: '金牛镇', 3897: '弥渡县', 3898: '弥城镇', 3899: '永平县', 3900: '博南镇', 3901: '云龙县', 3902: '诺邓镇', 3903: '洱源县', 3904: '茈碧湖镇', 3905: '剑川县', 3906: '金华镇', 3907: '鹤庆县', 3908: '云鹤镇', 3909: '漾濞彝族自治县', 3910: '苍山西镇', 3911: '南涧彝族自治县', 3912: '南涧镇', 3913: '巍山彝族回族自治县', 3914: '南诏镇' }, '0,3728,3915': { 3916: '楚雄市', 3917: '双柏县', 3918: '妥甸镇', 3919: '牟定县', 3920: '共和镇', 3921: '南华县', 3922: '龙川镇', 3923: '姚安县', 3924: '栋川镇', 3925: '大姚县', 3926: '金碧镇', 3927: '永仁县', 3928: '永定镇', 3929: '元谋县', 3930: '元马镇', 3931: '武定县', 3932: '狮山镇', 3933: '禄丰县', 3934: '金山镇' }, '0,3728,3935': { 3936: '蒙自县', 3937: '文澜镇', 3938: '个旧市', 3939: '开远市', 3940: '绿春县', 3941: '大兴镇', 3942: '建水县', 3943: '临安镇', 3944: '石屏县', 3945: '异龙镇', 3946: '弥勒县', 3947: '弥阳镇', 3948: '泸西县', 3949: '中枢镇', 3950: '元阳县', 3951: '南沙镇', 3952: '红河县', 3953: '迤萨镇', 3954: '金平苗族瑶族傣族自治县', 3955: '金河镇', 3956: '河口瑶族自治县', 3957: '河口镇', 3958: '屏边苗族自治县', 3959: '玉屏镇' }, '0,3728,3960': { 3961: '文山县', 3962: '开化镇', 3963: '砚山县', 3964: '江那镇', 3965: '西畴县', 3966: '西洒镇', 3967: '麻栗坡县', 3968: '麻栗镇', 3969: '马关县', 3970: '马白镇', 3971: '丘北县', 3972: '锦屏镇', 3973: '广南县', 3974: '莲城镇', 3975: '富宁县', 3976: '新华镇' }, '0,3728,3977': { 3978: '景洪市', 3979: '勐海县', 3980: '勐海镇', 3981: '勐腊县', 3982: '勐腊镇' }, '0,3983': { 3984: '拉萨市', 4000: '那曲地区', 4021: '昌都地区', 4044: '林芝地区', 4059: '山南地区', 4084: '日喀则地区', 4120: '阿里地区' }, '0,3983,3984': { 3985: '城关区', 3986: '林周县', 3987: '甘丹曲果镇', 3988: '当雄县', 3989: '当曲卡镇', 3990: '尼木县', 3991: '塔荣镇', 3992: '曲水县', 3993: '曲水镇', 3994: '堆龙德庆县', 3995: '东嘎镇', 3996: '达孜县', 3997: '德庆镇', 3998: '墨竹工卡县', 3999: '工卡镇' }, '0,3983,4000': { 4001: '那曲县', 4002: '那曲镇', 4003: '嘉黎县', 4004: '阿扎镇', 4005: '比如县', 4006: '比如镇', 4007: '聂荣县', 4008: '聂荣镇', 4009: '安多县', 4010: '帕那镇', 4011: '申扎县', 4012: '申扎镇', 4013: '索县', 4014: '亚拉镇', 4015: '班戈县', 4016: '普保镇', 4017: '巴青县', 4018: '拉西镇', 4019: '尼玛县', 4020: '尼玛镇' }, '0,3983,4021': { 4022: '昌都县', 4023: '城关镇', 4024: '江达县', 4025: '江达镇', 4026: '贡觉县', 4027: '莫洛镇', 4028: '类乌齐县', 4029: '桑多镇', 4030: '丁青县', 4031: '丁青镇', 4032: '察雅县', 4033: '烟多镇', 4034: '八宿县', 4035: '白玛镇', 4036: '左贡县', 4037: '旺达镇', 4038: '芒康县', 4039: '嘎托镇', 4040: '洛隆县', 4041: '孜托镇', 4042: '边坝县', 4043: '草卡镇' }, '0,3983,4044': { 4045: '林芝县', 4046: '八一镇', 4047: '工布江达县', 4048: '工布江达镇', 4049: '米林县', 4050: '米林镇', 4051: '墨脱县', 4052: '墨脱镇', 4053: '波密县', 4054: '扎木镇', 4055: '察隅县', 4056: '竹瓦根镇', 4057: '朗县', 4058: '朗镇' }, '0,3983,4059': { 4060: '乃东县', 4061: '泽当镇', 4062: '扎囊县', 4063: '扎塘镇', 4064: '贡嘎县', 4065: '吉雄镇', 4066: '桑日县', 4067: '桑日镇', 4068: '琼结县', 4069: '琼结镇', 4070: '曲松县', 4071: '曲松镇', 4072: '措美县', 4073: '措美镇', 4074: '洛扎县', 4075: '洛扎镇', 4076: '加查县', 4077: '安绕镇', 4078: '隆子县', 4079: '隆子镇', 4080: '错那县', 4081: '错那镇', 4082: '浪卡子县', 4083: '浪卡子镇' }, '0,3983,4084': { 4085: '日喀则市', 4086: '南木林县', 4087: '南木林镇', 4088: '江孜县', 4089: '江孜镇', 4090: '定日县', 4091: '协格尔镇', 4092: '萨迦县', 4093: '萨迦镇', 4094: '拉孜县', 4095: '曲下镇', 4096: '昂仁县', 4097: '卡嘎镇', 4098: '谢通门县', 4099: '卡嘎镇', 4100: '白朗县', 4101: '洛江镇', 4102: '仁布县', 4103: '德吉林镇', 4104: '康马县', 4105: '康马镇', 4106: '定结县', 4107: '江嘎镇', 4108: '仲巴县', 4109: '拉让乡', 4110: '亚东县', 4111: '下司马镇', 4112: '吉隆县', 4113: '宗嘎镇', 4114: '聂拉木县', 4115: '聂拉木镇', 4116: '萨嘎县', 4117: '加加镇', 4118: '岗巴县', 4119: '岗巴镇' }, '0,3983,4120': { 4121: '噶尔县', 4122: '狮泉河镇', 4123: '普兰县', 4124: '普兰镇', 4125: '札达县', 4126: '托林镇', 4127: '日土县', 4128: '日土镇', 4129: '革吉县', 4130: '革吉镇', 4131: '改则县', 4132: '改则镇', 4133: '措勤县', 4134: '措勤镇', 4135: '林芝县人民政府驻地由林芝镇迁至八一镇' }, '0,4136': { 4137: '西安市', 4155: '延安市', 4181: '铜川市', 4187: '渭南市', 4207: '咸阳市', 4232: '宝鸡市', 4254: '汉中市', 4276: '榆林市', 4300: '安康市', 4320: '商洛市' }, '0,4136,4137': { 4138: '莲湖区', 4139: '新城区', 4140: '碑林区', 4141: '灞桥区', 4142: '未央区', 4143: '雁塔区', 4144: '阎良区', 4145: '临潼区', 4146: '长安区', 4147: '蓝田县', 4148: '蓝关镇', 4149: '周至县', 4150: '二曲镇', 4151: '户县', 4152: '甘亭镇', 4153: '高陵县', 4154: '鹿苑镇' }, '0,4136,4155': { 4156: '宝塔区', 4157: '延长县', 4158: '七里村镇', 4159: '延川县', 4160: '延川镇', 4161: '子长县', 4162: '瓦窑堡镇', 4163: '安塞县', 4164: '真武洞镇', 4165: '志丹县', 4166: '保安镇', 4167: '吴起县', 4168: '吴旗镇', 4169: '甘泉县', 4170: '城关镇', 4171: '富县', 4172: '富城镇', 4173: '洛川县', 4174: '凤栖镇', 4175: '宜川县', 4176: '丹州镇', 4177: '黄龙县', 4178: '石堡镇', 4179: '黄陵县', 4180: '桥山镇' }, '0,4136,4181': { 4182: '耀州区', 4183: '王益区', 4184: '印台区', 4185: '宜君县', 4186: '城关镇' }, '0,4136,4187': { 4188: '临渭区', 4189: '华阴市', 4190: '韩城市', 4191: '华县', 4192: '华州镇', 4193: '潼关县', 4194: '城关镇', 4195: '大荔县', 4196: '城关镇', 4197: '蒲城县', 4198: '城关镇', 4199: '澄城县', 4200: '城关镇', 4201: '白水县', 4202: '城关镇', 4203: '合阳县', 4204: '城关镇', 4205: '富平县', 4206: '窦村镇' }, '0,4136,4207': { 4208: '秦都区', 4209: '杨陵区', 4210: '渭城区', 4211: '兴平市', 4212: '三原县', 4213: '城关镇', 4214: '泾阳县', 4215: '泾干镇', 4216: '乾县', 4217: '城关镇', 4218: '礼泉县', 4219: '城关镇', 4220: '永寿县', 4221: '监军镇', 4222: '彬县', 4223: '城关镇', 4224: '长武县', 4225: '昭仁镇', 4226: '旬邑县', 4227: '城关镇', 4228: '淳化县', 4229: '城关镇', 4230: '武功县', 4231: '普集镇' }, '0,4136,4232': { 4233: '渭滨区', 4234: '金台区', 4235: '陈仓区', 4236: '凤翔县', 4237: '城关镇', 4238: '岐山县', 4239: '凤鸣镇', 4240: '扶风县', 4241: '城关镇', 4242: '眉县', 4243: '首善镇', 4244: '陇县', 4245: '城关镇', 4246: '千阳县', 4247: '城关镇', 4248: '麟游县', 4249: '九成宫镇', 4250: '凤县', 4251: '双石铺镇', 4252: '太白县', 4253: '嘴头镇' }, '0,4136,4254': { 4255: '汉台区', 4256: '南郑县', 4257: '城关镇', 4258: '城固县', 4259: '博望镇', 4260: '洋县', 4261: '洋州镇', 4262: '西乡县', 4263: '城关镇', 4264: '勉县', 4265: '勉阳镇', 4266: '宁强县', 4267: '汉源镇', 4268: '略阳县', 4269: '城关镇', 4270: '镇巴县', 4271: '泾洋镇', 4272: '留坝县', 4273: '城关镇', 4274: '佛坪县', 4275: '袁家庄镇' }, '0,4136,4276': { 4277: '榆阳区', 4278: '神木县', 4279: '神木镇', 4280: '府谷县', 4281: '府谷镇', 4282: '横山县', 4283: '横山镇', 4284: '靖边县', 4285: '张家畔镇', 4286: '定边县', 4287: '定边镇', 4288: '绥德县', 4289: '名州镇', 4290: '米脂县', 4291: '银州镇', 4292: '佳县', 4293: '佳芦镇', 4294: '吴堡县', 4295: '宋家川镇', 4296: '清涧县', 4297: '宽洲镇', 4298: '子洲县', 4299: '双湖峪镇' }, '0,4136,4300': { 4301: '汉滨区', 4302: '汉阴县', 4303: '城关镇', 4304: '石泉县', 4305: '城关镇', 4306: '宁陕县', 4307: '城关镇', 4308: '紫阳县', 4309: '城关镇', 4310: '岚皋县', 4311: '城关镇', 4312: '平利县', 4313: '城关镇', 4314: '镇坪县', 4315: '城关镇', 4316: '旬阳县', 4317: '城关镇', 4318: '白河县', 4319: '城关镇' }, '0,4136,4320': { 4321: '商州区', 4322: '洛南县', 4323: '城关镇', 4324: '丹凤县', 4325: '龙驹寨镇', 4326: '商南县', 4327: '城关镇', 4328: '山阳县', 4329: '城关镇', 4330: '镇安县', 4331: '永乐镇', 4332: '柞水县', 4333: '乾佑镇' }, '0,4334': { 4335: '兰州市', 4347: '嘉峪关市', 4352: '白银市', 4361: '天水市', 4374: '武威市', 4382: '酒泉市', 4394: '张掖市', 4406: '庆阳市', 4422: '平凉市', 4436: '定西市', 4450: '陇南市', 4467: '临夏州', 4483: '甘南州' }, '0,4334,4335': { 4336: '城关区', 4337: '七里河区', 4338: '西固区', 4339: '安宁区', 4340: '红古区', 4341: '永登县', 4342: '城关镇', 4343: '皋兰县', 4344: '石洞镇', 4345: '榆中县', 4346: '城关镇' }, '0,4334,4347': { 4348: '金昌市', 4349: '金川区', 4350: '永昌县', 4351: '城关镇' }, '0,4334,4352': { 4353: '白银区', 4354: '平川区', 4355: '靖远县', 4356: '乌兰镇', 4357: '会宁县', 4358: '会师镇', 4359: '景泰县', 4360: '一条山镇' }, '0,4334,4361': { 4362: '秦州区', 4363: '麦积区', 4364: '清水县', 4365: '永清镇', 4366: '秦安县', 4367: '兴国镇', 4368: '甘谷县', 4369: '大像山镇', 4370: '武山县', 4371: '城关镇', 4372: '张家川回族自治县', 4373: '张家川镇' }, '0,4334,4374': { 4375: '凉州区', 4376: '民勤县', 4377: '城关镇', 4378: '古浪县', 4379: '古浪镇', 4380: '天祝藏族自治县', 4381: '华藏寺镇' }, '0,4334,4382': { 4383: '肃州区', 4384: '玉门市', 4385: '敦煌市', 4386: '金塔县', 4387: '金塔镇', 4388: '安西县', 4389: '渊泉镇', 4390: '肃北蒙古族自治县', 4391: '党城湾镇', 4392: '阿克塞哈萨克族自治县', 4393: '红柳湾镇' }, '0,4334,4394': { 4395: '甘州区', 4396: '民乐县', 4397: '洪水镇', 4398: '临泽县', 4399: '沙河镇', 4400: '高台县', 4401: '城关镇', 4402: '山丹县', 4403: '清泉镇', 4404: '肃南裕固族自治县', 4405: '红湾寺镇' }, '0,4334,4406': { 4407: '西峰区', 4408: '庆城县', 4409: '庆城镇', 4410: '环县', 4411: '环城镇', 4412: '华池县', 4413: '柔远镇', 4414: '合水县', 4415: '西华池镇', 4416: '正宁县', 4417: '山河镇', 4418: '宁县', 4419: '新宁镇', 4420: '镇原县', 4421: '城关镇' }, '0,4334,4422': { 4423: '崆峒区', 4424: '泾川县', 4425: '城关镇', 4426: '灵台县', 4427: '中台镇', 4428: '崇信县', 4429: '锦屏镇', 4430: '华亭县', 4431: '东华镇', 4432: '庄浪县', 4433: '水洛镇', 4434: '静宁县', 4435: '城关镇' }, '0,4334,4436': { 4437: '安定区', 4438: '通渭县', 4439: '平襄镇', 4440: '临洮县', 4441: '洮阳镇', 4442: '漳县', 4443: '武阳镇', 4444: '岷县', 4445: '岷阳镇', 4446: '渭源县', 4447: '清源镇', 4448: '陇西县', 4449: '巩昌镇' }, '0,4334,4450': { 4451: '武都区', 4452: '成县', 4453: '城关镇', 4454: '宕昌县', 4455: '城关镇', 4456: '康县', 4457: '文县', 4458: '城关镇', 4459: '西和县', 4460: '汉源镇', 4461: '礼县', 4462: '城关镇', 4463: '两当县', 4464: '城关镇', 4465: '徽县', 4466: '城关镇' }, '0,4334,4467': { 4468: '临夏市', 4469: '临夏县', 4470: '韩集镇', 4471: '康乐县', 4472: '附城镇', 4473: '永靖县', 4474: '刘家峡镇', 4475: '广河县', 4476: '城关镇', 4477: '和政县', 4478: '城关镇', 4479: '东乡族自治县', 4480: '锁南坝镇', 4481: '积石山保安族东乡族撒拉族自治县', 4482: '吹麻滩镇' }, '0,4334,4483': { 4484: '合作市', 4485: '临潭县', 4486: '城关镇', 4487: '卓尼县', 4488: '柳林镇', 4489: '舟曲县', 4490: '城关镇', 4491: '迭部县', 4492: '电尕镇', 4493: '玛曲县', 4494: '尼玛镇', 4495: '碌曲县', 4496: '玛艾镇', 4497: '夏河县', 4498: '拉卜楞镇' }, '0,4499': { 4500: '西宁市', 4511: '海东地区', 4524: '海北州', 4533: '海南州', 4544: '黄南州', 4553: '果洛州', 4566: '玉树州', 4579: '海西州' }, '0,4499,4500': { 4501: '城中区', 4502: '城东区', 4503: '城西区', 4504: '城北区', 4505: '大通回族土族自治县', 4506: '桥头镇', 4507: '湟源县', 4508: '城关镇', 4509: '湟中县', 4510: '鲁沙尔镇' }, '0,4499,4511': { 4512: '平安县', 4513: '平安镇', 4514: '乐都县', 4515: '碾伯镇', 4516: '民和回族土族自治县', 4517: '川口镇', 4518: '互助土族自治县', 4519: '威远镇', 4520: '化隆回族自治县', 4521: '巴燕镇', 4522: '循化撒拉族自治县', 4523: '积石镇' }, '0,4499,4524': { 4525: '海晏县', 4526: '三角城镇', 4527: '祁连县', 4528: '八宝镇', 4529: '刚察县', 4530: '沙柳河镇', 4531: '门源回族自治县', 4532: '浩门镇' }, '0,4499,4533': { 4534: '共和县', 4535: '恰卜恰镇', 4536: '同德县', 4537: '尕巴松多镇', 4538: '贵德县', 4539: '河阴镇', 4540: '兴海县', 4541: '子科滩镇', 4542: '贵南县', 4543: '茫曲镇' }, '0,4499,4544': { 4545: '同仁县', 4546: '隆务镇', 4547: '尖扎县', 4548: '马克唐镇', 4549: '泽库县', 4550: '泽曲镇', 4551: '河南蒙古族自治县', 4552: '优干宁镇' }, '0,4499,4553': { 4554: '玛沁县', 4555: '大武镇', 4556: '班玛县', 4557: '赛来塘镇', 4558: '甘德县', 4559: '柯曲镇', 4560: '达日县', 4561: '吉迈镇', 4562: '久治县', 4563: '智青松多镇', 4564: '玛多县', 4565: '黄河乡' }, '0,4499,4566': { 4567: '玉树县', 4568: '结古镇', 4569: '杂多县', 4570: '萨呼腾镇', 4571: '称多县', 4572: '称文镇', 4573: '治多县', 4574: '加吉博洛镇', 4575: '囊谦县', 4576: '香达镇', 4577: '曲麻莱县', 4578: '约改镇' }, '0,4499,4579': { 4580: '德令哈市', 4581: '格尔木市', 4582: '乌兰县', 4583: '希里沟镇', 4584: '都兰县', 4585: '察汗乌苏镇', 4586: '天峻县', 4587: '新源镇' }, '0,4588': { 4589: '银川市', 4598: '石嘴山市', 4603: '吴忠市', 4610: '固原市', 4620: '中卫市' }, '0,4588,4589': { 4590: '兴庆区', 4591: '金凤区', 4592: '西夏区', 4593: '灵武市', 4594: '永宁县', 4595: '杨和镇', 4596: '贺兰县', 4597: '习岗镇' }, '0,4588,4598': { 4599: '大武口区', 4600: '惠农区', 4601: '平罗县', 4602: '城关镇' }, '0,4588,4603': { 4604: '利通区', 4605: '青铜峡市', 4606: '盐池县', 4607: '花马池镇', 4608: '同心县', 4609: '豫海镇' }, '0,4588,4610': { 4611: '原州区', 4612: '西吉县', 4613: '吉强镇', 4614: '隆德县', 4615: '城关镇', 4616: '泾源县', 4617: '香水镇', 4618: '彭阳县', 4619: '白阳镇' }, '0,4588,4620': { 4621: '沙坡头区', 4622: '中宁县', 4623: '海原县' }, '0,4624': { 4625: '乌鲁木齐市', 4635: '克拉玛依市', 4640: '自治区直辖县级行政单位', 4645: '喀什地区', 4669: '阿克苏地区', 4687: '和田地区', 4702: '吐鲁番地区', 4708: '哈密地区', 4714: '克孜勒苏柯州', 4722: '博尔塔拉州', 4728: '昌吉州', 4742: '巴音郭楞州', 4760: '伊犁州', 4779: '塔城地区', 4792: '阿勒泰地区' }, '0,4624,4625': { 4626: '天山区', 4627: '沙依巴克区', 4628: '新市区', 4629: '水磨沟区', 4630: '头屯河区', 4631: '达坂城区', 4632: '东山区', 4633: '乌鲁木齐县', 4634: '乌鲁木齐市水磨沟区' }, '0,4624,4635': { 4636: '克拉玛依区', 4637: '独山子区', 4638: '白碱滩区', 4639: '乌尔禾区' }, '0,4624,4640': { 4641: '石河子市', 4642: '阿拉尔市', 4643: '图木舒克市', 4644: '五家渠市' }, '0,4624,4645': { 4646: '喀什市', 4647: '疏附县', 4648: '托克扎克镇', 4649: '疏勒县', 4650: '疏勒镇', 4651: '英吉沙县', 4652: '英吉沙镇', 4653: '泽普县', 4654: '泽普镇', 4655: '莎车县', 4656: '莎车镇', 4657: '叶城县', 4658: '喀格勒克镇', 4659: '麦盖提县', 4660: '麦盖提镇', 4661: '岳普湖县', 4662: '岳普湖镇', 4663: '伽师县', 4664: '巴仁镇', 4665: '巴楚县', 4666: '巴楚镇', 4667: '塔什库尔干塔吉克自治县', 4668: '塔什库尔干镇' }, '0,4624,4669': { 4670: '阿克苏市', 4671: '温宿县', 4672: '温宿镇', 4673: '库车县', 4674: '库车镇', 4675: '沙雅县', 4676: '沙雅镇', 4677: '新和县', 4678: '新和镇', 4679: '拜城县', 4680: '拜城镇', 4681: '乌什县', 4682: '乌什镇', 4683: '阿瓦提县', 4684: '阿瓦提镇', 4685: '柯坪县', 4686: '柯坪镇' }, '0,4624,4687': { 4688: '和田市', 4689: '和田县', 4690: '墨玉县', 4691: '喀拉喀什镇', 4692: '皮山县', 4693: '固玛镇', 4694: '洛浦县', 4695: '洛浦镇', 4696: '策勒县', 4697: '策勒镇', 4698: '于田县', 4699: '木尕拉镇', 4700: '民丰县', 4701: '尼雅镇' }, '0,4624,4702': { 4703: '吐鲁番市', 4704: '鄯善县', 4705: '鄯善镇', 4706: '托克逊县', 4707: '托克逊镇' }, '0,4624,4708': { 4709: '哈密市', 4710: '伊吾县', 4711: '伊吾镇', 4712: '巴里坤哈萨克自治县', 4713: '巴里坤镇' }, '0,4624,4714': { 4715: '阿图什市', 4716: '阿克陶县', 4717: '阿克陶镇', 4718: '阿合奇县', 4719: '阿合奇镇', 4720: '乌恰县', 4721: '乌恰镇' }, '0,4624,4722': { 4723: '博乐市', 4724: '精河县', 4725: '精河镇', 4726: '温泉县', 4727: '博格达尔镇' }, '0,4624,4728': { 4729: '昌吉市', 4730: '阜康市', 4731: '米泉市', 4732: '呼图壁县', 4733: '呼图壁镇', 4734: '玛纳斯县', 4735: '玛纳斯镇', 4736: '奇台县', 4737: '奇台镇', 4738: '吉木萨尔县', 4739: '吉木萨尔镇', 4740: '木垒哈萨克自治县', 4741: '木垒镇' }, '0,4624,4742': { 4743: '库尔勒市', 4744: '轮台县', 4745: '轮台镇', 4746: '尉犁县', 4747: '尉犁镇', 4748: '若羌县', 4749: '若羌镇', 4750: '且末县', 4751: '且末镇', 4752: '和静县', 4753: '和静镇', 4754: '和硕县', 4755: '特吾里克镇', 4756: '博湖县', 4757: '博湖镇', 4758: '焉耆回族自治县', 4759: '焉耆镇' }, '0,4624,4760': { 4761: '伊宁市', 4762: '奎屯市', 4763: '伊宁县', 4764: '吉里于孜镇', 4765: '霍城县', 4766: '水定镇', 4767: '巩留县', 4768: '巩留镇', 4769: '新源县', 4770: '新源镇', 4771: '昭苏县', 4772: '昭苏镇', 4773: '特克斯县', 4774: '特克斯镇', 4775: '尼勒克县', 4776: '尼勒克镇', 4777: '察布查尔锡伯自治县', 4778: '察布查尔镇' }, '0,4624,4779': { 4780: '塔城市', 4781: '乌苏市', 4782: '额敏县', 4783: '额敏镇', 4784: '沙湾县', 4785: '三道河子镇', 4786: '托里县', 4787: '托里镇', 4788: '裕民县', 4789: '哈拉布拉镇', 4790: '和布克赛尔蒙古自治县', 4791: '和布克赛尔镇' }, '0,4624,4792': { 4793: '阿勒泰市', 4794: '布尔津县', 4795: '布尔津镇', 4796: '富蕴县', 4797: '库额尔齐斯镇', 4798: '福海县', 4799: '哈巴河县', 4800: '青河县', 4801: '吉木乃县' }, '0,4802': { 4803: '香港特别行政区' }, '0,4802,4803': { 4804: '中西区', 4805: '东区', 4806: '九龙城区', 4807: '观塘区', 4808: '南区', 4809: '深水埗区', 4810: '湾仔区', 4811: '黄大仙区', 4812: '油尖旺区', 4813: '离岛区', 4814: '葵青区', 4815: '北区', 4816: '西贡区', 4817: '沙田区', 4818: '屯门区', 4819: '大埔区', 4820: '荃湾区', 4821: '元朗区' }, '0,4822': { 4823: '澳门特别行政区' }, '0,4822,4823': { 4824: '澳门特别行政区' }, '0,4825': { 4826: '台北', 4827: '高雄', 4828: '台中', 4829: '花莲', 4830: '基隆', 4831: '嘉义', 4832: '金门', 4833: '连江', 4834: '苗栗', 4835: '南投', 4836: '澎湖', 4837: '屏东', 4838: '台东', 4839: '台南', 4840: '桃园', 4841: '新竹', 4842: '宜兰', 4843: '云林', 4844: '彰化' } }; /*last index 2937**->>57** 2949**->>59** */ exports.find = function (id) { if (typeof (items[id]) == "undefined") return false; return items[id]; } exports.fillOption = function (el, loc_id, selector, val ,fn) { var json = this.find(loc_id); if (json) { var i = 1, index = 1, option = ''; $m.node.empty(el); $m.each(json, function (v, k) { option += '<option value="' + k + '">' + v + '</option>'; if ((val && v == selector) || (!val && k == selector)) { index = i; } i++; }); $m.node.append(el, '<option>无</option>') $m.node.append(el, option); el.selectedIndex = index; $m.node.attr(el.options[index], 'selected', true) fn && fn(el) } } exports.init = function (o) { o = $m.merge({ container:'', val: true, s1: null, s2: null, s3: null, fn:null//变更回调函数 }, o || {}); var wrap = $m.node(o.container)[0]; var sel = $m.node("select", wrap); var sProvince = sel.eq(0); var sCity = sel.eq(1); var sCounty = sel.eq(2); var dpv, dcv,that=this; //sProvince.innerHTML = sCity.innerHTML = sCounty.innerHTML = ''; console.log(o) //获得选项的值 function getvalue(el) { return el.options[el.selectedIndex].value; } that.fillOption(sProvince, '0', o.s1, o.val,o.fn); dpv = getvalue(sProvince); that.fillOption(sCity, '0,' + dpv, o.s2, o.val, o.fn); dcv = getvalue(sCity); that.fillOption(sCounty, '0,' + dpv + ',' + dcv, o.s3, o.val, o.fn); $m.event.delegate('select', 'change', function (e) { if (e.target == sProvince) { dpv = getvalue(sProvince); dcv = that.fillOption(sCity, '0,' + dpv, o.s2, o.val, o.fn); dcv = getvalue(sCity); that.fillOption(sCounty, '0,' + dpv + ',' + dcv, o.s3, o.val, o.fn); return; } if (e.target == sCity) { dpv = getvalue(sProvince); dcv = getvalue(sCity); that.fillOption(sCounty, '0,' + dpv + ',' + dcv, o.s3, o.val, o.fn); return; } }); } });
const Discord = require('discord.js'); module.exports = { name: "ucreategame", aliases: ["ucr"], category : "Uno", description : "create uno game", usage: "[command]", author: "[CuSO4-c3c,Hiyoriii,Hellsnakes]", run: async(client, message, args) => { await client.discordUNO.createGame(message); } }
$(document).ready(function() { var url = '/idm/users/' + window.location.pathname.split('/')[3] + '/applications'; load_applications(url); function load_applications(url, panel) { $('#spinner_applications').show('open'); $.get(url, function(data, status) { if (data.applications.length > 0) { applications_pagination(data.applications_number); create_applications_row( data.applications, $('#auth_applications_content') ); } else { $('#auth_applications_content') .find('.alert') .show('open'); } $('#spinner_applications').hide('close'); }); } function create_applications_row(applications, table) { for (var i = 0; i < applications.length; i++) { var application_row = $('#application_row_template').html(); application_row = application_row.replace( /application_id/g, applications[i].id ); application_row = application_row.replace( /application_image/g, applications[i].image ); application_row = application_row.replace( /application_url/g, applications[i].url ); application_row = application_row.replace( /application_name/g, htmlEntities(applications[i].name) ); table.append(application_row); } } var typingTimerApplications; var doneTypingInterval = 500; $('#auth_applications') .find('.form-control') .bind('keyup input', function(e) { $('#spinner_applications').show('open'); clearTimeout(typingTimerApplications); typingTimerApplications = setTimeout( send_filter_request, doneTypingInterval ); }); function send_filter_request() { $.get( url + '?key=' + $('#auth_applications') .find('.form-control') .val() .toUpperCase(), function(data, status) { $('#auth_applications_content') .children('.list-group-item') .remove(); $('#spinner_applications').hide('close'); if (data.applications.length > 0) { $('#auth_applications_content') .find('.alert') .hide(); applications_pagination(data.applications_number); create_applications_row( data.applications, $('#auth_applications_content') ); } else { $('#auth_applications_pagination_container').empty(); $('#auth_applications_content') .find('.alert') .show(); } } ); } function htmlEntities(str) { return String(str) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;'); } function applications_pagination(max) { $('#auth_applications_pagination_container') .bootpag({ total: Math.ceil(max / 5), page: 1, maxVisible: 5, leaps: true, firstLastUse: true, first: navigation.first, last: navigation.last, wrapClass: 'pagination', activeClass: 'active', disabledClass: 'disabled', nextClass: 'next', prevClass: 'prev', lastClass: 'last', firstClass: 'first', }) .on('page', function(event, num) { $.get(url + '?page=' + num, function(data, status) { $('#auth_applications_content') .children('.list-group-item') .remove(); create_applications_row( data.applications, $('#auth_applications_content') ); $('#auth_applications_content') .find('.alert') .hide(); }); }); } });
const faker = require("faker"); faker.locale = "zh_CN"; const generateArticlesData = (n = 1000) => { let articleData = []; let i = 0; while (i < n) { const title = faker.lorem.sentences(1); const postAt = faker.date.past(); const tags = [ faker.random.word(faker.random.number({ min: 2, max: 4 })), faker.random.word(faker.random.number({ min: 2, max: 4 })), faker.random.word(faker.random.number({ min: 2, max: 4 })), faker.random.word(faker.random.number({ min: 2, max: 4 })), ]; const views = faker.random.number({ min: 1, max: 10000 }); const liked = faker.random.number({ min: 1, max: 5000 }); const markdown = `# ${faker.lorem.lines(5)}\r\n## ${faker.lorem.lines( 1 )}\r\n${faker.lorem.paragraph( 15 )}\r\n> Never too old to learn\r\n>> Anything is possible\r\n>>> How many levels can you take\r\n### How about some code?\r\n\`\`\`js\r\n(()=>{console.log('This is an arrow function')})();\r\n\r\nconsole.log('123');\r\n\r\n(function(){console.log('This is an normal functon')})()\r\n\`\`\`\r\n${faker.lorem.paragraphs( 3, "\r\n" )}`; const isPublished = true; const isDeleted = false; const article = { title, postAt, markdown, tags, views, liked, isPublished, isDeleted, }; articleData.push(article); i++; } return articleData; }; module.exports = { generateArticlesData, };
from buche import buche, H # You don't have to set a template, but if you do, it must be the # very first command you emit, before any printing. # You can also give `src=<path-to-file>` instead of `content=...` buche.command_template(content=H.div['my-template'](address="/")) # Use this command to add styles, stylesheets, scripts, etc. buche.command_resource(content=H.style( """ .my-template { background-color: #eee; padding: 5px; display: flex; flex-direction: column; align-items: start; } """ )) # Display simple HTML buche.html.h3('Welcome!') # Display objects buche(1234) buche([x * x for x in range(100)]) buche.dict(avocado="green", banana="yellow", cherry="red") # Open automatically creates an address for an element div1 = buche.open.div(style="border: 3px solid red") # You can also set an address explicitly buche.html.div(address='/two', style="border: 3px solid blue") # Get a printer for the given address div2 = buche['/two'] # These objects will go in the divs div1('One') div2('Two') div1('One again') # Handy tabs component grocery_list = buche.open.boxTabs() fruit = grocery_list.open.tabEntry( label='Fruits', active=True, ) vegetable = grocery_list.open.tabEntry( label='Veggies', ) fruit.html.div(H.s("Pineapple")) fruit.html.div("Raspberry") fruit.html.div("Grape") vegetable.html.div("Carrot") vegetable.html.div("Potato") vegetable.html.div("Yam") # Customize the representation of a class class Color: def __init__(self, r, g, b): self.r = r self.g = g self.b = b def __hrepr__(self, H, hrepr): sz = hrepr.config.swatch_size or 20 return H.div( style=f'display:inline-block;width:{sz}px;height:{sz}px;margin:2px;' f'background-color:rgb({self.r},{self.g},{self.b});' ) # This will call __hrepr__ buche(Color(255, 0, 0)) # Configuration values can be anything and are propagated recursively buche(Color(0, 0, 255), swatch_size=50) # You can evaluate JavaScript on elements button = buche.open.button("Tickle me") button.command_eval(expression="this.onclick = () => alert('Hihihihi!')")
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from uhd_restpy.base import Base from uhd_restpy.files import Files from typing import List, Any, Union class OspfSRLBRangeSubObjectsList(Base): """Ospf SRLB Range Sub Objects The OspfSRLBRangeSubObjectsList class encapsulates a list of ospfSRLBRangeSubObjectsList resources that are managed by the system. A list of resources can be retrieved from the server using the OspfSRLBRangeSubObjectsList.find() method. """ __slots__ = () _SDM_NAME = 'ospfSRLBRangeSubObjectsList' _SDM_ATT_MAP = { 'Count': 'count', 'DescriptiveName': 'descriptiveName', 'Name': 'name', 'SrlbSidCount': 'srlbSidCount', 'SrlbStartSIDLabel': 'srlbStartSIDLabel', } _SDM_ENUM_MAP = { } def __init__(self, parent, list_op=False): super(OspfSRLBRangeSubObjectsList, self).__init__(parent, list_op) @property def Count(self): # type: () -> int """ Returns ------- - number: Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group. """ return self._get_attribute(self._SDM_ATT_MAP['Count']) @property def DescriptiveName(self): # type: () -> str """ Returns ------- - str: Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context. """ return self._get_attribute(self._SDM_ATT_MAP['DescriptiveName']) @property def Name(self): # type: () -> str """ Returns ------- - str: Name of NGPF element, guaranteed to be unique in Scenario """ return self._get_attribute(self._SDM_ATT_MAP['Name']) @Name.setter def Name(self, value): # type: (str) -> None self._set_attribute(self._SDM_ATT_MAP['Name'], value) @property def SrlbSidCount(self): # type: () -> 'Multivalue' """ Returns ------- - obj(uhd_restpy.multivalue.Multivalue): SID Count """ from uhd_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['SrlbSidCount'])) @property def SrlbStartSIDLabel(self): # type: () -> 'Multivalue' """ Returns ------- - obj(uhd_restpy.multivalue.Multivalue): Start SID/Label """ from uhd_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP['SrlbStartSIDLabel'])) def update(self, Name=None): # type: (str) -> OspfSRLBRangeSubObjectsList """Updates ospfSRLBRangeSubObjectsList resource on the server. This method has some named parameters with a type: obj (Multivalue). The Multivalue class has documentation that details the possible values for those named parameters. Args ---- - Name (str): Name of NGPF element, guaranteed to be unique in Scenario Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) def add(self, Name=None): # type: (str) -> OspfSRLBRangeSubObjectsList """Adds a new ospfSRLBRangeSubObjectsList resource on the json, only valid with config assistant Args ---- - Name (str): Name of NGPF element, guaranteed to be unique in Scenario Returns ------- - self: This instance with all currently retrieved ospfSRLBRangeSubObjectsList resources using find and the newly added ospfSRLBRangeSubObjectsList resources available through an iterator or index Raises ------ - Exception: if this function is not being used with config assistance """ return self._add_xpath(self._map_locals(self._SDM_ATT_MAP, locals())) def find(self, Count=None, DescriptiveName=None, Name=None): # type: (int, str, str) -> OspfSRLBRangeSubObjectsList """Finds and retrieves ospfSRLBRangeSubObjectsList resources from the server. All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve ospfSRLBRangeSubObjectsList resources from the server. To retrieve an exact match ensure the parameter value starts with ^ and ends with $ By default the find method takes no parameters and will retrieve all ospfSRLBRangeSubObjectsList resources from the server. Args ---- - Count (number): Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group. - DescriptiveName (str): Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context. - Name (str): Name of NGPF element, guaranteed to be unique in Scenario Returns ------- - self: This instance with matching ospfSRLBRangeSubObjectsList resources retrieved from the server available through an iterator or index Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._select(self._map_locals(self._SDM_ATT_MAP, locals())) def read(self, href): """Retrieves a single instance of ospfSRLBRangeSubObjectsList data from the server. Args ---- - href (str): An href to the instance to be retrieved Returns ------- - self: This instance with the ospfSRLBRangeSubObjectsList resources from the server available through an iterator or index Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ return self._read(href) def get_device_ids(self, PortNames=None, SrlbSidCount=None, SrlbStartSIDLabel=None): """Base class infrastructure that gets a list of ospfSRLBRangeSubObjectsList device ids encapsulated by this object. Use the optional regex parameters in the method to refine the list of device ids encapsulated by this object. Args ---- - PortNames (str): optional regex of port names - SrlbSidCount (str): optional regex of srlbSidCount - SrlbStartSIDLabel (str): optional regex of srlbStartSIDLabel Returns ------- - list(int): A list of device ids that meets the regex criteria provided in the method parameters Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._get_ngpf_device_ids(locals())
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import CSSClassnames from '../utils/CSSClassnames'; const CLASS_ROOT = CSSClassnames.FORM_FIELD; export default class FormField extends Component { constructor(props, context) { super(props, context); this._onFocus = this._onFocus.bind(this); this._onBlur = this._onBlur.bind(this); this._onClick = this._onClick.bind(this); this.state = { focus: false }; } componentDidMount () { const contentsElement = this.contentsRef; if (contentsElement) { const inputElements = ( contentsElement.querySelectorAll('input, textarea, select') ); if (inputElements.length === 1) { this._inputElement = inputElements[0]; this._inputElement.addEventListener('focus', this._onFocus); this._inputElement.addEventListener('blur', this._onBlur); } } } componentWillUnmount () { if (this._inputElement) { this._inputElement.removeEventListener('focus', this._onFocus); this._inputElement.removeEventListener('blur', this._onBlur); delete this._inputElement; } } _onFocus () { this.setState({focus: true}); } _onBlur () { this.setState({focus: false}); } _onClick () { if (this._inputElement) { this._inputElement.focus(); } } render () { let classes = [CLASS_ROOT]; if (this.state.focus) { classes.push(CLASS_ROOT + "--focus"); } if (this.props.hidden) { classes.push(CLASS_ROOT + "--hidden"); } if (this.props.htmlFor) { classes.push(CLASS_ROOT + "--text"); } if (this.props.size) { classes.push(CLASS_ROOT + "--size-" + this.props.size); } if (this.props.strong) { classes.push(`${CLASS_ROOT}--strong`); } if (this.props.className) { classes.push(this.props.className); } let error; if (this.props.error) { classes.push(CLASS_ROOT + "--error"); error = ( <span className={CLASS_ROOT + "__error"}>{this.props.error}</span> ); } let help; if (this.props.help !== null && this.props.help !== undefined) { help = <span className={CLASS_ROOT + "__help"}>{this.props.help}</span>; } let labelNode; if (this.props.label) { labelNode = ( <label className={CLASS_ROOT + "__label"} htmlFor={this.props.htmlFor}> {this.props.label} </label> ); } return ( <div className={classes.join(' ')} onClick={this._onClick}> {error} {labelNode} {help} <span ref={ref => this.contentsRef = ref} className={CLASS_ROOT + "__contents"}> {this.props.children} </span> </div> ); } } FormField.propTypes = { error: PropTypes.node, help: PropTypes.node, hidden: PropTypes.bool, htmlFor: PropTypes.string, label: PropTypes.node, size: PropTypes.oneOf(['medium', 'large']), strong: PropTypes.bool }; FormField.defaultProps = { size: 'medium', strong: false };
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.lang['is'] = { wsc : { btnIgnore : 'Hunsa', btnIgnoreAll : 'Hunsa allt', btnReplace : 'Skipta', btnReplaceAll : 'Skipta öllu', btnUndo : 'Til baka', changeTo : 'Tillaga', errorLoading : 'Error loading application service host: %s.', ieSpellDownload : 'Villuleit ekki sett upp.<br>Viltu setja hana upp?', manyChanges : 'Villuleit lokið: %1 orðum breytt', noChanges : 'Villuleit lokið: Engu orði breytt', noMispell : 'Villuleit lokið: Engin villa fannst', noSuggestions : '- engar tillögur -', notAvailable : 'Sorry, but service is unavailable now.', notInDic : 'Ekki í orðabókinni', oneChange : 'Villuleit lokið: Einu orði breytt', progress : 'Villuleit í gangi...', title : 'Spell Checker', toolbar : 'Villuleit' }, undo : { redo : 'Hætta við afturköllun', undo : 'Afturkalla' }, toolbar : { toolbarCollapse : 'Collapse Toolbar', toolbarExpand : 'Expand Toolbar', toolbarGroups : { document : 'Document', clipboard : 'Clipboard/Undo', editing : 'Editing', forms : 'Forms', basicstyles : 'Basic Styles', paragraph : 'Paragraph', links : 'Links', insert : 'Insert', styles : 'Styles', colors : 'Colors', tools : 'Tools' }, toolbars : 'Editor toolbars' }, table : { border : 'Breidd ramma', caption : 'Titill', cell : { menu : 'Reitur', insertBefore : 'Skjóta inn reiti fyrir aftan', insertAfter : 'Skjóta inn reiti fyrir framan', deleteCell : 'Fella reit', merge : 'Sameina reiti', mergeRight : 'Sameina til hægri', mergeDown : 'Sameina niður á við', splitHorizontal : 'Kljúfa reit lárétt', splitVertical : 'Kljúfa reit lóðrétt', title : 'Cell Properties', cellType : 'Cell Type', rowSpan : 'Rows Span', colSpan : 'Columns Span', wordWrap : 'Word Wrap', hAlign : 'Horizontal Alignment', vAlign : 'Vertical Alignment', alignBaseline : 'Baseline', bgColor : 'Background Color', borderColor : 'Border Color', data : 'Data', header : 'Header', yes : 'Yes', no : 'No', invalidWidth : 'Cell width must be a number.', invalidHeight : 'Cell height must be a number.', invalidRowSpan : 'Rows span must be a whole number.', invalidColSpan : 'Columns span must be a whole number.', chooseColor : 'Choose' }, cellPad : 'Reitaspássía', cellSpace : 'Bil milli reita', column : { menu : 'Dálkur', insertBefore : 'Skjóta inn dálki vinstra megin', insertAfter : 'Skjóta inn dálki hægra megin', deleteColumn : 'Fella dálk' }, columns : 'Dálkar', deleteTable : 'Fella töflu', headers : 'Fyrirsagnir', headersBoth : 'Hvort tveggja', headersColumn : 'Fyrsti dálkur', headersNone : 'Engar', headersRow : 'Fyrsta röð', invalidBorder : 'Border size must be a number.', invalidCellPadding : 'Cell padding must be a positive number.', invalidCellSpacing : 'Cell spacing must be a positive number.', invalidCols : 'Number of columns must be a number greater than 0.', invalidHeight : 'Table height must be a number.', invalidRows : 'Number of rows must be a number greater than 0.', invalidWidth : 'Table width must be a number.', menu : 'Eigindi töflu', row : { menu : 'Röð', insertBefore : 'Skjóta inn röð fyrir ofan', insertAfter : 'Skjóta inn röð fyrir neðan', deleteRow : 'Eyða röð' }, rows : 'Raðir', summary : 'Áfram', title : 'Eigindi töflu', toolbar : 'Tafla', widthPc : 'prósent', widthPx : 'myndeindir', widthUnit : 'width unit' }, stylescombo : { label : 'Stílflokkur', panelTitle : 'Formatting Styles', panelTitle1 : 'Block Styles', panelTitle2 : 'Inline Styles', panelTitle3 : 'Object Styles' }, specialchar : { options : 'Special Character Options', title : 'Velja tákn', toolbar : 'Setja inn merki' }, sourcearea : { toolbar : 'Kóði' }, scayt : { btn_about : 'About SCAYT', btn_dictionaries : 'Dictionaries', btn_disable : 'Disable SCAYT', btn_enable : 'Enable SCAYT', btn_langs : 'Languages', btn_options : 'Options', text_title : 'Spell Check As You Type' }, removeformat : { toolbar : 'Fjarlægja snið' }, pastetext : { button : 'Líma sem ósniðinn texta', title : 'Líma sem ósniðinn texta' }, pastefromword : { confirmCleanup : 'The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?', error : 'It was not possible to clean up the pasted data due to an internal error', title : 'Líma úr Word', toolbar : 'Líma úr Word' }, maximize : { maximize : 'Maximize', minimize : 'Minimize' }, magicline : { title : 'Insert paragraph here' }, list : { bulletedlist : 'Punktalisti', numberedlist : 'Númeraður listi' }, link : { acccessKey : 'Skammvalshnappur', advanced : 'Tæknilegt', advisoryContentType : 'Tegund innihalds', advisoryTitle : 'Titill', anchor : { toolbar : 'Stofna/breyta kaflamerki', menu : 'Eigindi kaflamerkis', title : 'Eigindi kaflamerkis', name : 'Nafn bókamerkis', errorName : 'Sláðu inn nafn bókamerkis!', remove : 'Remove Anchor' }, anchorId : 'Eftir auðkenni einingar', anchorName : 'Eftir akkerisnafni', charset : 'Táknróf', cssClasses : 'Stílsniðsflokkur', emailAddress : 'Netfang', emailBody : 'Meginmál', emailSubject : 'Efni', id : 'Auðkenni', info : 'Almennt', langCode : 'Lesstefna', langDir : 'Lesstefna', langDirLTR : 'Frá vinstri til hægri (LTR)', langDirRTL : 'Frá hægri til vinstri (RTL)', menu : 'Breyta stiklu', name : 'Nafn', noAnchors : '<Engin bókamerki á skrá>', noEmail : 'Sláðu inn netfang!', noUrl : 'Sláðu inn veffang stiklunnar!', other : '<annar>', popupDependent : 'Háð venslum (Netscape)', popupFeatures : 'Eigindi sprettiglugga', popupFullScreen : 'Heilskjár (IE)', popupLeft : 'Fjarlægð frá vinstri', popupLocationBar : 'Fanglína', popupMenuBar : 'Vallína', popupResizable : 'Resizable', popupScrollBars : 'Skrunstikur', popupStatusBar : 'Stöðustika', popupToolbar : 'Verkfærastika', popupTop : 'Fjarlægð frá efri brún', rel : 'Relationship', selectAnchor : 'Veldu akkeri', styles : 'Stíll', tabIndex : 'Raðnúmer innsláttarreits', target : 'Mark', targetFrame : '<rammi>', targetFrameName : 'Nafn markglugga', targetPopup : '<sprettigluggi>', targetPopupName : 'Nafn sprettiglugga', title : 'Stikla', toAnchor : 'Bókamerki á þessari síðu', toEmail : 'Netfang', toUrl : 'Vefslóð', toolbar : 'Stofna/breyta stiklu', type : 'Stikluflokkur', unlink : 'Fjarlægja stiklu', upload : 'Senda upp' }, indent : { indent : 'Minnka inndrátt', outdent : 'Auka inndrátt' }, image : { alt : 'Baklægur texti', border : 'Rammi', btnUpload : 'Hlaða upp', button2Img : 'Do you want to transform the selected image button on a simple image?', hSpace : 'Vinstri bil', img2Button : 'Do you want to transform the selected image on a image button?', infoTab : 'Almennt', linkTab : 'Stikla', lockRatio : 'Festa stærðarhlutfall', menu : 'Eigindi myndar', resetSize : 'Reikna stærð', title : 'Eigindi myndar', titleButton : 'Eigindi myndahnapps', upload : 'Hlaða upp', urlMissing : 'Image source URL is missing.', vSpace : 'Hægri bil', validateBorder : 'Border must be a whole number.', validateHSpace : 'HSpace must be a whole number.', validateVSpace : 'VSpace must be a whole number.' }, horizontalrule : { toolbar : 'Lóðrétt lína' }, format : { label : 'Stílsnið', panelTitle : 'Stílsnið', tag_address : 'Vistfang', tag_div : 'Venjulegt (DIV)', tag_h1 : 'Fyrirsögn 1', tag_h2 : 'Fyrirsögn 2', tag_h3 : 'Fyrirsögn 3', tag_h4 : 'Fyrirsögn 4', tag_h5 : 'Fyrirsögn 5', tag_h6 : 'Fyrirsögn 6', tag_p : 'Venjulegt letur', tag_pre : 'Forsniðið' }, fakeobjects : { anchor : 'Anchor', flash : 'Flash Animation', hiddenfield : 'Hidden Field', iframe : 'IFrame', unknown : 'Unknown Object' }, elementspath : { eleLabel : 'Elements path', eleTitle : '%1 element' }, contextmenu : { options : 'Context Menu Options' }, clipboard : { copy : 'Afrita', copyError : 'Öryggisstillingar vafrans þíns leyfa ekki afritun texta með músaraðgerð. Notaðu lyklaborðið í afrita (Ctrl/Cmd+C).', cut : 'Klippa', cutError : 'Öryggisstillingar vafrans þíns leyfa ekki klippingu texta með músaraðgerð. Notaðu lyklaborðið í klippa (Ctrl/Cmd+X).', paste : 'Líma', pasteArea : 'Paste Area', pasteMsg : 'Límdu í svæðið hér að neðan og (<STRONG>Ctrl/Cmd+V</STRONG>) og smelltu á <STRONG>OK</STRONG>.', securityMsg : 'Vegna öryggisstillinga í vafranum þínum fær ritillinn ekki beinan aðgang að klippuborðinu. Þú verður að líma innihaldið aftur inn í þennan glugga.', title : 'Líma' }, button : { selectedLabel : '%1 (Selected)' }, blockquote : { toolbar : 'Inndráttur' }, basicstyles : { bold : 'Feitletrað', italic : 'Skáletrað', strike : 'Yfirstrikað', subscript : 'Niðurskrifað', superscript : 'Uppskrifað', underline : 'Undirstrikað' }, about : { copy : 'Copyright &copy; $1. All rights reserved.', dlgTitle : 'About CKEditor', help : 'Check $1 for help.', moreInfo : 'For licensing information please visit our web site:', title : 'About CKEditor', userGuide : 'CKEditor User\'s Guide' }, editor : 'Rich Text Editor', editorPanel : 'Rich Text Editor panel', common : { editorHelp : 'Press ALT 0 for help', browseServer : 'Fletta í skjalasafni', url : 'Vefslóð', protocol : 'Samskiptastaðall', upload : 'Senda upp', uploadSubmit : 'Hlaða upp', image : 'Setja inn mynd', flash : 'Flash', form : 'Setja inn innsláttarform', checkbox : 'Setja inn hökunarreit', radio : 'Setja inn valhnapp', textField : 'Setja inn textareit', textarea : 'Setja inn textasvæði', hiddenField : 'Setja inn falið svæði', button : 'Setja inn hnapp', select : 'Setja inn lista', imageButton : 'Setja inn myndahnapp', notSet : '<ekkert valið>', id : 'Auðkenni', name : 'Nafn', langDir : 'Lesstefna', langDirLtr : 'Frá vinstri til hægri (LTR)', langDirRtl : 'Frá hægri til vinstri (RTL)', langCode : 'Tungumálakóði', longDescr : 'Nánari lýsing', cssClass : 'Stílsniðsflokkur', advisoryTitle : 'Titill', cssStyle : 'Stíll', ok : 'Í lagi', cancel : 'Hætta við', close : 'Close', preview : 'Forskoða', resize : 'Resize', generalTab : 'Almennt', advancedTab : 'Tæknilegt', validateNumberFailed : 'This value is not a number.', confirmNewPage : 'Any unsaved changes to this content will be lost. Are you sure you want to load new page?', confirmCancel : 'You have changed some options. Are you sure you want to close the dialog window?', options : 'Options', target : 'Mark', targetNew : 'New Window (_blank)', targetTop : 'Topmost Window (_top)', targetSelf : 'Same Window (_self)', targetParent : 'Parent Window (_parent)', langDirLTR : 'Frá vinstri til hægri (LTR)', langDirRTL : 'Frá hægri til vinstri (RTL)', styles : 'Stíll', cssClasses : 'Stílsniðsflokkur', width : 'Breidd', height : 'Hæð', align : 'Jöfnun', alignLeft : 'Vinstri', alignRight : 'Hægri', alignCenter : 'Miðjað', alignJustify : 'Jafna báðum megin', alignTop : 'Efst', alignMiddle : 'Miðjuð', alignBottom : 'Neðst', alignNone : 'None', invalidValue : 'Invalid value.', invalidHeight : 'Height must be a number.', invalidWidth : 'Width must be a number.', invalidCssLength : 'Value specified for the "%1" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).', invalidHtmlLength : 'Value specified for the "%1" field must be a positive number with or without a valid HTML measurement unit (px or %).', invalidInlineStyle : 'Value specified for the inline style must consist of one or more tuples with the format of "name : value", separated by semi-colons.', cssLengthTooltip : 'Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).', unavailable : '%1<span class="cke_accessibility">, unavailable</span>' } };
# -*- coding: utf-8 -*- _ROMAN_DIGITS = {'M': 1000, 'CM': 900, 'D': 500, 'CD': 400, 'C': 100, 'XC': 90, 'L': 50, 'XL': 40, 'X': 10, 'IX': 9, 'V': 5, 'IV': 4, 'I': 1} class Solution: def romanToInt(self, s: str) -> int: n, i = 0, 0 while i < len(s): if s[i:i + 2] in _ROMAN_DIGITS: n += _ROMAN_DIGITS[s[i:i + 2]] i += 2 else: n += _ROMAN_DIGITS[s[i:i + 1]] i += 1 return n
import axios from 'axios' import environment from '../environment' const CancelToken = axios.CancelToken; const source = CancelToken.source(); /* options请求 */ export const http = axios.create({ // 相对请求域名 baseURL: environment.apiUrl, // 超时时间 timeout: 10000, // 请求数据类型 headers: { 'Content-Type': 'application/json' }, // 服务器响应的数据类型 'arraybuffer', 'blob', 'document', 'json', 'text', responseType: 'json', cancelToken: source.token }) /* 请求拦截器 */ http.interceptors.request.use(function (config) { /* 添加用户认证信息 */ config.headers['X-Requested-With'] = 'tokenInfo=scret123' return config; }, function (error) { console.error('请求错误'); return Promise.reject(error); }) /* 响应拦截器 */ http.interceptors.response.use(function (res) { /* 统一错误处理 */ switch (res.status) { case 200: if (res.data) { // 根据业务状态码定制 return Promise.resolve(res.data) } break; case 500: console.error('服务器内部错误', res.data); return Promise.reject(res.data); default: console.error('未可知错误,大部分是由于后端不支持CORS或无效配置引起', res); return Promise.reject(res); } return res; }, function (error) { console.error('响应错误'); return Promise.reject(error); }); // 取消请求 source.cancel() export { source }
/* * helpers.js: Test helpers for winston * * (C) 2010 Charlie Robbins * MIT LICENSE * */ var assert = require('assert'), fs = require('fs'), path = require('path'), spawn = require('child_process').spawn, util = require('util'), vows = require('vows'), winston = require('../lib/winston'); var helpers = exports; helpers.size = function (obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) { size++; } } return size; }; helpers.tryUnlink = function (file) { try { fs.unlinkSync(file) } catch (ex) { } }; helpers.assertDateInfo = function (info) { assert.isNumber(Date.parse(info)); }; helpers.assertProcessInfo = function (info) { assert.isNumber(info.pid); assert.isNumber(info.uid); assert.isNumber(info.gid); assert.isString(info.cwd); assert.isString(info.execPath); assert.isString(info.version); assert.isArray(info.argv); assert.isObject(info.memoryUsage); }; helpers.assertOsInfo = function (info) { assert.isArray(info.loadavg); assert.isNumber(info.uptime); }; helpers.assertTrace = function (trace) { trace.forEach(function (site) { assert.isTrue(!site.column || typeof site.column === 'number'); assert.isTrue(!site.line || typeof site.line === 'number'); assert.isTrue(!site.file || typeof site.file === 'string'); assert.isTrue(!site.method || typeof site.method === 'string'); assert.isTrue(!site.function || typeof site.function === 'string'); assert.isTrue(typeof site.native === 'boolean'); }); }; helpers.assertLogger = function (logger, level) { assert.instanceOf(logger, winston.Logger); assert.isFunction(logger.log); assert.isFunction(logger.add); assert.isFunction(logger.remove); assert.equal(logger.level, level || "info"); Object.keys(logger.levels).forEach(function (method) { assert.isFunction(logger[method]); }); }; helpers.assertConsole = function (transport) { assert.instanceOf(transport, winston.transports.Console); assert.isFunction(transport.log); }; helpers.assertMemory = function (transport) { assert.instanceOf(transport, winston.transports.Memory); assert.isFunction(transport.log); }; helpers.assertFile = function (transport) { assert.instanceOf(transport, winston.transports.File); assert.isFunction(transport.log); } helpers.assertDailyRotateFile = function (transport) { assert.instanceOf(transport, winston.transports.DailyRotateFile); assert.isFunction(transport.log); } helpers.assertWebhook = function (transport) { assert.instanceOf(transport, winston.transports.Webhook); assert.isFunction(transport.log); }; helpers.assertCouchdb = function (transport) { assert.instanceOf(transport, winston.transports.Couchdb); assert.isFunction(transport.log); }; helpers.assertHandleExceptions = function (options) { return { topic: function () { var that = this, child = spawn('node', [options.script]); helpers.tryUnlink(options.logfile); child.on('exit', function () { fs.readFile(options.logfile, that.callback); }); }, "should save the error information to the specified file": function (err, data) { assert.isTrue(!err); data = JSON.parse(data); assert.isObject(data); helpers.assertProcessInfo(data.process); helpers.assertOsInfo(data.os); helpers.assertTrace(data.trace); if (options.message) { assert.equal('uncaughtException: ' + options.message, data.message); } } }; }; helpers.assertFailedTransport = function (transport) { return { topic: function () { var self = this; transport.on('error', function(emitErr){ transport.log('error', 'test message 2', {}, function(logErr, logged){ self.callback(emitErr, logErr); }); }); transport.log('error', 'test message'); }, "should emit an error": function (emitErr, logErr) { assert.instanceOf(emitErr, Error); assert.equal(emitErr.code, 'ENOENT'); }, "should enter noop failed state": function (emitErr, logErr) { assert.instanceOf(logErr, Error); assert.equal(transport._failures, transport.maxRetries); } }; }; helpers.testNpmLevels = function (transport, assertMsg, assertFn) { return helpers.testLevels(winston.config.npm.levels, transport, assertMsg, assertFn); }; helpers.testSyslogLevels = function (transport, assertMsg, assertFn) { return helpers.testLevels(winston.config.syslog.levels, transport, assertMsg, assertFn); }; helpers.testLevels = function (levels, transport, assertMsg, assertFn) { var tests = {}; Object.keys(levels).forEach(function (level) { var test = { topic: function () { transport.log(level, 'test message', {}, this.callback.bind(this, null)); } }; test[assertMsg] = assertFn; tests['with the ' + level + ' level'] = test; }); var metadatatest = { topic: function () { transport.log('info', 'test message', { metadata: true }, this.callback.bind(this, null)); } }; metadatatest[assertMsg] = assertFn; tests['when passed metadata'] = metadatatest; var primmetadatatest = { topic: function () { transport.log('info', 'test message', 'metadata', this.callback.bind(this, null)); } }; primmetadatatest[assertMsg] = assertFn; tests['when passed primitive metadata'] = primmetadatatest; var circmetadata = { }; circmetadata['metadata'] = circmetadata; var circmetadatatest = { topic: function () { transport.log('info', 'test message', circmetadata, this.callback.bind(this, null)); } }; circmetadatatest[assertMsg] = assertFn; tests['when passed circular metadata'] = circmetadatatest; return tests; };
from examples.gridworld.exceptions.IllegalGridMoveException import IllegalGridMoveException class GridBlockedActionException(IllegalGridMoveException): def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs)
import React from "react"; import { Link } from "gatsby"; import { ThemeProvider } from "styled-components"; import Theme from "../../utils/theme"; // Global Styles import GlobalStyle from "../Styles/GlobalStyles"; // Components import Header from "./Header"; import Footer from "./Footer"; import CookieConsent from "react-cookie-consent"; // Styles const btnStyle = { background: "#FAA916", }; const Layout = props => { return ( <ThemeProvider theme={Theme}> <GlobalStyle /> <Header lingua={props.lingua} /> <main>{props.children}</main> <Footer lingua={props.lingua} /> <CookieConsent location="bottom" buttonText="Accetto" buttonStyle={btnStyle} enableDeclineButton declineButtonText="Non Accetto" style={{ background: "#2B373B" }} expires={150} > Utilizziamo cookies proprietari per i nostri servizi e cookies di terze parti per abilitare importanti funzionalità del sito. Visualizza la{" "} <Link to="/privacy-policy" className="cookies-link"> Privacy Policy </Link>{" "} o la{" "} <Link to="/cookies-policy" className="cookies-link"> Cookies Policy </Link>{" "} per saperne di più. </CookieConsent> </ThemeProvider> ); }; Layout.defaultProps = { lingua: `IT`, }; export default Layout;
# Copyright (c) OpenMMLab. All rights reserved. from .deepfashion_dataset import DeepFashionDataset __all__ = ['DeepFashionDataset']
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M6 8.83V20h12V4h-7.17L6 8.83zm5 .19L13 9v4h3l-4 4-4-4h3V9.02z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M18 2h-8L4 8v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 18H6V8.83L10.83 4H18v16z" }, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "m12 17 4-4h-3V9l-2 .02V13H8z" }, "2")], 'SimCardDownloadTwoTone'); exports.default = _default;
import json import os import random from random import sample import numpy as np import numpy.random import re from collections import Counter import inspect import pandas as pd import matplotlib.pyplot as plt import requests from IPython.display import HTML import seaborn as sns import networkx as nx from pylab import rcParams try: from wordcloud import WordCloud except ImportError: print("wordcloud er ikke installert, kan ikke lage ordskyer") #************** For defining wordbag search def dict2pd(dictionary): res = pd.DataFrame.from_dict(dictionary).fillna(0) s = (res.mean(axis=0)) s = s.rename('snitt') res = res.append(s) return res.sort_values(by='snitt', axis=1, ascending=False).transpose() def def2dict(ddef): res = dict() defs = ddef.split(';') for d in defs: lex = d.split(':') if len(lex) == 2: #print('#'.join(lex)) hyper = lex[0].strip() occurrences = [x.strip() for x in lex[1].split(',')] res[hyper] = occurrences for x in res: for y in res[x]: if y.capitalize() not in res[x]: res[x].append(y.capitalize()) return res def wordbag_eval(wordbag, urns): if type(urns) is list: if isinstance(urns[0], list): urns = [u[0] for u in urns] else: urns = urns else: urns = [urns] param = dict() param['wordbags'] = wordbag param['urns'] = urns r = requests.post("https://api.nb.no/ngram/wordbags", json = param) return dict2pd(r.json()) def wordbag_eval_para(wordbag, urns): if type(urns) is list: if isinstance(urns[0], list): urns = [u[0] for u in urns] else: urns = urns else: urns = [urns] param = dict() param['wordbags'] = wordbag param['urns'] = urns r = requests.post("https://api.nb.no/ngram/wordbags_para", json = param) return r.json() def get_paragraphs(urn, paras): """Return paragraphs for urn""" param = dict() param['paragraphs'] = paras param['urn'] = urn r = requests.get("https://api.nb.no/ngram/paragraphs", json=param) return dict2pd(r.json()) ### ******************* wordbag search end def ner(text = None, dist=False): """Analyze text for named entities - set dist = True will return the four values that go into decision""" r = [] if text != None: r = requests.post("https://api.nb.no/ngram/ner", json={'text':text,'dist':dist}) return r.json() #**** names **** def check_navn(navn, limit=2, remove='Ja Nei Nå Dem De Deres Unnskyld Ikke Ah Hmm Javel Akkurat Jaja Jaha'.split()): """Removes all items in navn with frequency below limit and words in all case as well as all words in list 'remove'""" r = {x:navn[x] for x in navn if navn[x] > limit and x.upper() != x and not x in remove} return r def sentences(urns, num=300): if isinstance(urns[0], list): urns = [str(x[0]) for x in urns] params = {'urns':urns, 'num':num} res = requests.get("https://api.nb.no/ngram/sentences", params=params) return res.json() def names(urn, ratio = 0.3, cutoff = 2): """ Return namens in book with urn. Returns uni- , bi-, tri- and quadgrams """ if type(urn) is list: urn = urn[0] r = requests.get('https://api.nb.no/ngram/names', json={'urn':urn, 'ratio':ratio, 'cutoff':cutoff}) x = r.json() result = ( Counter(x[0][0]), Counter({tuple(x[1][i][0]):x[1][i][1] for i in range(len(x[1]))}), Counter({tuple(x[2][i][0]):x[2][i][1] for i in range(len(x[2]))}), Counter({tuple(x[3][i][0]):x[3][i][1] for i in range(len(x[3]))}) ) return result def name_graph(name_struct): m = [] for n in name_struct[0]: m.append(frozenset([n])) for n in name_struct[1:]: m += [frozenset(x) for x in n] G = [] for x in m: for y in m: if x < y: G.append((' '.join(x), ' '.join(y))) N = [] for x in m: N.append(' '.join(x)) Gg = nx.Graph() Gg.add_nodes_from(N) Gg.add_edges_from(G) return Gg def aggregate_urns(urnlist): """Sum up word frequencies across urns""" if isinstance(urnlist[0], list): urnlist = [u[0] for u in urnlist] r = requests.post("https://api.nb.no/ngram/book_aggregates", json={'urns':urnlist}) return r.json() # Norweigan word bank def word_variant(word, form): """ Find alternative form for a given word form, e.g. word_variant('spiste', 'pres-part') """ r = requests.get("https://api.nb.no/ngram/variant_form", params={'word':word, 'form':form}) return r.json() def word_paradigm(word): """ Find alternative form for a given word form, e.g. word_variant('spiste', 'pres-part') """ r = requests.get("https://api.nb.no/ngram/paradigm", params = {'word': word}) return r.json() def word_form(word): """ Find alternative form for a given word form, e.g. word_variant('spiste', 'pres-part') """ r = requests.get("https://api.nb.no/ngram/word_form", params = {'word': word}) return r.json() def word_lemma(word): """ Find lemma form for a given word form """ r = requests.get("https://api.nb.no/ngram/word_lemma", params = {'word': word}) return r.json() def word_freq(urn, words): """ Find frequency of words within urn """ params = {'urn':urn, 'words':words} r = requests.post("https://api.nb.no/ngram/freq", json=params) return dict(r.json()) def tot_freq(words): """ Find total frequency of words """ params = {'words':words} r = requests.post("https://api.nb.no/ngram/word_frequencies", json=params) return dict(r.json()) def book_count(urns): params = {'urns':urns} r = requests.post("https://api.nb.no/ngram/book_count", json=params) return dict(r.json()) def sttr(urn, chunk=5000): r = requests.get("https://api.nb.no/ngram/sttr", json = {'urn':urn, 'chunk':chunk}) return r.json() def totals(top=200): r = requests.get("https://api.nb.no/ngram/totals", json={'top':top}) return dict(r.json()) def navn(urn): if type(urn) is list: urn = urn[0] r = requests.get('https://api.nb.no/ngram/tingnavn', json={'urn':urn}) return dict(r.json()) def digibokurn_from_text(T): """Return URNs as 13 digits (any sequence of 13 digits is counted as an URN)""" return re.findall("(?<=digibok_)[0-9]{13}", T) def urn_from_text(T): """Return URNs as 13 digits (any sequence of 13 digits is counted as an URN)""" return re.findall("[0-9]{13}", T) def metadata(urn=None): urns = pure_urn(urn) #print(urns) r = requests.post("https://api.nb.no/ngram/meta", json={'urn':urns}) return r.json() def pure_urn(data): """Convert URN-lists with extra data into list of serial numbers. Args: data: May be a list of URNs, a list of lists with URNs as their initial element, or a string of raw texts containing URNs Any pandas dataframe or series. Urns must be in the first column of dataframe. Returns: List[str]: A list of URNs. Empty list if input is on the wrong format or contains no URNs """ korpus_def = [] if isinstance(data, list): if not data: # Empty list korpus_def = [] if isinstance(data[0], list): # List of lists try: korpus_def = [str(x[0]) for x in data] except IndexError: korpus_def = [] else: # Assume data is already a list of URNs korpus_def = [str(int(x)) for x in data] elif isinstance(data, str): korpus_def = [str(x) for x in urn_from_text(data)] elif isinstance(data, (int, np.integer)): korpus_def = [str(data)] elif isinstance(data, pd.DataFrame): col = data.columns[0] urns = pd.to_numeric(data[col]) korpus_def = [str(int(x)) for x in urns.dropna()] elif isinstance(data, pd.Series): korpus_def = [str(int(x)) for x in data.dropna()] return korpus_def #### N-Grams from fulltext updated def unigram(word, period=(1950, 2020), media = 'bok', ddk=None, topic=None, gender=None, publisher=None, lang=None, trans=None): r = requests.get("https://api.nb.no/ngram/unigrams", params={ 'word':word, 'ddk':ddk, 'topic':topic, 'gender':gender, 'publisher':publisher, 'lang':lang, 'trans':trans, 'period0':period[0], 'period1':period[1], 'media':media }) return frame(dict(r.json())) def bigram(first,second, period=(1950, 2020), media = 'bok', ddk=None, topic=None, gender=None, publisher=None, lang=None, trans=None): r = requests.get("https://api.nb.no/ngram/bigrams", params={ 'first':first, 'second':second, 'ddk':ddk, 'topic':topic, 'gender':gender, 'publisher':publisher, 'lang':lang, 'trans':trans, 'period0':period[0], 'period1':period[1], 'media':media }) return frame(dict(r.json())) def book_counts(period=(1800, 2050)): r = requests.get("https://api.nb.no/ngram/book_counts", params={ 'period0':period[0], 'period1':period[1], }) return frame(dict(r.json())) #### def difference(first, second, rf, rs, years=(1980, 2000),smooth=1, corpus='bok'): """Compute difference of difference (first/second)/(rf/rs)""" try: a_first = nb_ngram(first, years=years, smooth=smooth, corpus=corpus) a_second = nb_ngram(second, years=years, smooth=smooth, corpus=corpus) a = a_first.join(a_second) b_first = nb_ngram(rf, years=years, smooth=smooth, corpus=corpus) b_second = nb_ngram(rs, years=years, smooth=smooth, corpus=corpus) if rf == rs: b_second.columns = [rs + '2'] b = b_first.join(b_second) s_a = a.mean() s_b = b.mean() f1 = s_a[a.columns[0]]/s_a[a.columns[1]] f2 = s_b[b.columns[0]]/s_b[b.columns[1]] res = f1/f2 except: res = 'Mangler noen data - har bare for: ' + ', '.join([x for x in a.columns.append(b.columns)]) return res def df_combine(array_df): """Combine one columns dataframes""" import pandas as pd cols = [] for i in range(len(a)): #print(i) if array_df[i].columns[0] in cols: array_df[i].columns = [array_df[i].columns[0] + '_' + str(i)] cols.append(array_df[i].columns[0]) return pd.concat(a, axis=1, sort=True) def col_agg(df, col='sum'): c = df.sum(axis=0) c = pd.DataFrame(c) c.columns = [col] return c def row_agg(df, col='sum'): c = df.sum(axis=1) c = pd.DataFrame(c) c.columns = [col] return c def get_freq(urn, top=50, cutoff=3): """Get frequency list for urn""" if isinstance(urn, list): urn = urn[0] r = requests.get("https://api.nb.no/ngram/urnfreq", json={'urn':urn, 'top':top, 'cutoff':cutoff}) return Counter(dict(r.json())) ####=============== GET URNS ==================########## def book_corpus(words = None, author = None, title = None, subtitle = None, ddk = None, subject = None, period=(1100, 2020), gender=None, lang = None, trans= None, limit=20 ): return frame(book_urn(words, author, title, subtitle, ddk, subject, period, gender, lang, trans, limit), "urn author title year".split()) def book_urn(words = None, author = None, title = None, subtitle = None, ddk = None, subject = None, period=(1100, 2020), gender=None, lang = None, trans= None, limit=20 ): """Get URNs for books with metadata""" frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) query = {i:values[i] for i in args if values[i] != None and i != 'period'} query['year'] = period[0] query['next'] = period[1] - period[0] return get_urn(query) def unique_urns(korpus, newest=True): author_title = {(c[1],c[2]) for c in korpus} corpus = {(c[0], c[1]):[d for d in korpus if c[0] == d[1] and c[1]==d[2]] for c in author_title } for c in corpus: corpus[c].sort(key=lambda c: c[3]) if newest == True: res = [corpus[c][-1] for c in corpus] else: res = [corpus[c][0] for c in corpus] return res def refine_book_urn(urns = None, words = None, author = None, title = None, ddk = None, subject = None, period=(1100, 2020), gender=None, lang = None, trans= None, limit=20 ): """Refine URNs for books with metadata""" # if empty urns nothing to refine if urns is None or urns == []: return [] # check if urns is a metadata list, and pick out first elements if that is the case if isinstance(urns[0], list): urns = [x[0] for x in urns] frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) query = {i:values[i] for i in args if values[i] != None and i != 'period' and i != 'urns'} query['year'] = period[0] query['next'] = period[1] - period[0] #print(query) return refine_urn(urns, query) def best_book_urn(word = None, author = None, title = None, ddk = None, subject = None, period=(1100, 2020), gender=None, lang = None, trans= None, limit=20 ): """Get URNs for books with metadata""" if word is None: return [] frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) query = {i:values[i] for i in args if values[i] != None and i != 'period' and i != 'word'} query['year'] = period[0] query['next'] = period[1] - period[0] return get_best_urn(word, query) def get_urn(metadata=None): """Get urns from metadata""" if metadata is None: metadata = {} if not ('next' in metadata or 'neste' in metadata): metadata['next'] = 100 if not 'year' in metadata: metadata['year'] = 1900 r = requests.get('https://api.nb.no/ngram/urn', json=metadata) return r.json() def refine_urn(urns, metadata=None): """Refine a list urns using extra information""" if metadata is None: metadata = {} metadata['urns'] = urns if not ('words' in metadata): metadata['words'] = [] if not ('next' in metadata or 'neste' in metadata): metadata['next'] = 520 if not 'year' in metadata: metadata['year'] = 1500 r = requests.post('https://api.nb.no/ngram/refineurn', json=metadata) return r.json() def get_best_urn(word, metadata=None): """Get the best urns from metadata containing a specific word""" metadata['word'] = word if not ('next' in metadata or 'neste' in metadata): metadata['next'] = 600 if not 'year' in metadata: metadata['year'] = 1500 r = requests.get('https://api.nb.no/ngram/best_urn', json=metadata) return r.json() def get_papers(top=5, cutoff=5, navn='%', yearfrom=1800, yearto=2020, samplesize=100): """Get newspapers""" div = lambda x, y: (int(x/y), x % y) chunks = 20 # split samplesize into chunks, go through the chunks and then the remainder (first, second) = div(samplesize, chunks) r = [] # collect chunkwise for i in range(first): r += requests.get("https://api.nb.no/ngram/avisfreq", json={'navn':navn, 'top':top, 'cutoff':cutoff, 'yearfrom':yearfrom, 'yearto':yearto,'samplesize':chunks} ).json() # collect the remainder r += requests.get("https://api.nb.no/ngram/avisfreq", json={'navn':navn, 'top':top, 'cutoff':cutoff, 'yearfrom':yearfrom, 'yearto':yearto,'samplesize':second} ).json() return [dict(x) for x in r] def urn_coll(word, urns=[], after=5, before=5, limit=1000): """Find collocations for word in a set of book URNs. Only books at the moment""" if isinstance(urns[0], list): # urns assumed to be list of list with urn-serial as first element urns = [u[0] for u in urns] r = requests.post("https://api.nb.no/ngram/urncoll", json={'word':word, 'urns':urns, 'after':after, 'before':before, 'limit':limit}) res = pd.DataFrame.from_dict(r.json(), orient='index') if not res.empty: res = res.sort_values(by=res.columns[0], ascending = False) return res def urn_coll_words(words, urns=None, after=5, before=5, limit=1000): """Find collocations for a group of words within a set of books given by a list of URNs. Only books at the moment""" coll = pd.DataFrame() if urns != None: if isinstance(urns[0], list): # urns assumed to be list of list with urn-serial as first element urns = [u[0] for u in urns] colls = Counter() if isinstance(words, str): words = words.split() res = Counter() for word in words: try: res += Counter( requests.post( "https://api.nb.no/ngram/urncoll", json={ 'word':word, 'urns':urns, 'after':after, 'before':before, 'limit':limit} ).json() ) except: True coll = pd.DataFrame.from_dict(res, orient='index') if not coll.empty: coll = coll.sort_values(by=coll.columns[0], ascending = False) return coll def get_aggregated_corpus(urns, top=0, cutoff=0): res = Counter() if isinstance(urns[0], list): # urns assumed to be list of list with urn-serial as first element urns = [u[0] for u in urns] for u in urns: #print(u) res += get_freq(u, top = top, cutoff = cutoff) return pd.DataFrame.from_dict(res, orient='index').sort_values(by=0, ascending = False) def compare_word_bags(bag_of_words, another_bag_of_words, first_freq = 0, another_freq = 1, top=100, first_col = 0, another_col= 0): """Compare two columns taken from two or one frame. Parameters x_freq are frequency limits used to cut down candidate words from the bag of words. Compare along the columns where first_col and another_col are column numbers. Typical situation is that bag_of_words is a one column frame and another_bag_of_words is another one column frame. When the columns are all from one frame, just change column numbers to match the columns""" diff = bag_of_words[bag_of_words > first_freq][bag_of_words.columns[first_col]]/another_bag_of_words[another_bag_of_words > another_freq][another_bag_of_words.columns[another_col]] return frame(diff, 'diff').sort_values(by='diff', ascending=False)[:top] def collocation( word, yearfrom=2010, yearto=2018, before=3, after=3, limit=1000, corpus='avis', lang='nob', title='%', ddk='%', subtitle='%'): """Defined collects frequencies for a given word""" data = requests.get( "https://api.nb.no/ngram/collocation", params={ 'word':word, 'corpus':corpus, 'yearfrom':yearfrom, 'before':before, 'after':after, 'limit':limit, 'yearto':yearto, 'title':title, 'ddk':ddk, 'subtitle':subtitle}).json() return pd.DataFrame.from_dict(data['freq'], orient='index') def collocation_data(words, yearfrom = 2000, yearto = 2005, limit = 1000, before = 5, after = 5, title = '%', corpus='bok'): """Collocation for a set of words sum up all the collocations words is a list of words or a blank separated string of words""" import sys a = dict() if isinstance(words, str): words = words.split() for word in words: print(word) try: a[word] = collocation( word, yearfrom = yearfrom, yearto = yearto, limit = limit, corpus = corpus, before = before, after = after, title = title ) a[word].columns = [word] except: print(word, ' feilsituasjon', sys.exc_info()) result = pd.DataFrame() for w in a: result = result.join(a[w], how='outer') return pd.DataFrame(result.sum(axis=1)).sort_values(by=0, ascending=False) class CollocationCorpus: from random import sample def __init__(self, corpus = None, name='', maximum_texts = 500): urns = pure_urn(corpus) if len(urns) > maximum_texts: selection = random(urns, maximum_texts) else: selection = urns self.corpus_def = selection self.corpus = get_aggregated_corpus(self.corpus_def, top=0, cutoff=0) def summary(self, head=10): info = { 'corpus_definition':self.corpus[:head], 'number_of_words':len(self.corpus) } return info def collocation_old(word, yearfrom=2010, yearto=2018, before=3, after=3, limit=1000, corpus='avis'): data = requests.get( "https://api.nb.no/ngram/collocation", params={ 'word':word, 'corpus':corpus, 'yearfrom':yearfrom, 'before':before, 'after':after, 'limit':limit, 'yearto':yearto}).json() return pd.DataFrame.from_dict(data['freq'], orient='index') def heatmap(df, color='green'): return df.fillna(0).style.background_gradient(cmap=sns.light_palette(color, as_cmap=True)) def get_corpus_text(urns, top = 0, cutoff=0): k = dict() if isinstance(urns, list): # a list of urns, or a korpus with urns as first element if isinstance(urns[0], list): urns = [u[0] for u in urns] else: # assume it is a single urn, text or number urns = [urns] for u in urns: #print(u) k[u] = get_freq(u, top = top, cutoff = cutoff) df = pd.DataFrame(k) res = df.sort_values(by=df.columns[0], ascending=False) return res def normalize_corpus_dataframe(df): colsums = df.sum() for x in colsums.index: #print(x) df[x] = df[x].fillna(0)/colsums[x] return True def show_korpus(korpus, start=0, size=4, vstart=0, vsize=20, sortby = ''): """Show corpus as a panda dataframe start = 0 indicates which dokument to show first, dataframe is sorted according to this size = 4 how many documents (or columns) are shown top = 20 how many words (or rows) are shown""" if sortby != '': val = sortby else: val = korpus.columns[start] return korpus[korpus.columns[start:start+size]].sort_values(by=val, ascending=False)[vstart:vstart + vsize] def aggregate(korpus): """Make an aggregated sum of all documents across the corpus, here we use average""" return pd.DataFrame(korpus.fillna(0).mean(axis=1)) def convert_list_of_freqs_to_dataframe(referanse): """The function get_papers() returns a list of frequencies - convert it""" res = [] for x in referanse: res.append( dict(x)) result = pd.DataFrame(res).transpose() normalize_corpus_dataframe(result) return result def get_corpus(top=0, cutoff=0, navn='%', corpus='avis', yearfrom=1800, yearto=2020, samplesize=10): if corpus == 'avis': result = get_papers(top=top, cutoff=cutoff, navn=navn, yearfrom=yearfrom, yearto=yearto, samplesize=samplesize) res = convert_list_of_freqs_to_dataframe(result) else: urns = get_urn({'author':navn, 'year':yearfrom, 'neste':yearto-yearfrom, 'limit':samplesize}) res = get_corpus_text([x[0] for x in urns], top=top, cutoff=cutoff) return res class Cluster: def __init__(self, word = '', filename = '', period = (1950,1960) , before = 5, after = 5, corpus='avis', reference = 200, word_samples=1000): if word != '': self.collocates = collocation(word, yearfrom=period[0], yearto = period[1], before=before, after=after, corpus=corpus, limit=word_samples) self.collocates.columns = [word] if type(reference) is pd.core.frame.DataFrame: reference = reference elif type(reference) is int: reference = get_corpus(yearfrom=period[0], yearto=period[1], corpus=corpus, samplesize=reference) else: reference = get_corpus(yearfrom=period[0], yearto=period[1], corpus=corpus, samplesize=int(reference)) self.reference = aggregate(reference) self.reference.columns = ['reference_corpus'] self.word = word self.period = period self.corpus = corpus else: if filename != '': self.load(filename) def cluster_set(self, exponent=1.1, top = 200, aslist=True): combo_corp = self.reference.join(self.collocates, how='outer') normalize_corpus_dataframe(combo_corp) korpus = compute_assoc(combo_corp, self.word, exponent) korpus.columns = [self.word] if top <= 0: res = korpus.sort_values(by=self.word, ascending=False) else: res = korpus.sort_values(by=self.word, ascending=False).iloc[:top] if aslist == True: res = HTML(', '.join(list(res.index))) return res def add_reference(self, number=20): ref = get_corpus(yearfrom=self.period[0], yearto=self.period[1], samplesize=number) ref = aggregate(ref) ref.columns = ['add_ref'] normalize_corpus_dataframe(ref) self.reference = aggregate(self.reference.join(ref, how='outer')) return True def save(self, filename=''): if filename == '': filename = "{w}_{p}-{q}.json".format(w=self.word,p=self.period[0], q = self.period[1]) model = { 'word':self.word, 'period':self.period, 'reference':self.reference.to_dict(), 'collocates':self.collocates.to_dict(), 'corpus':self.corpus } with open(filename, 'w', encoding = 'utf-8') as outfile: print('lagrer til:', filename) outfile.write(json.dumps(model)) return True def load(self, filename): with open(filename, 'r') as infile: try: model = json.loads(infile.read()) #print(model['word']) self.word = model['word'] self.period = model['period'] self.corpus = model['corpus'] self.reference = pd.DataFrame(model['reference']) self.collocates = pd.DataFrame(model['collocates']) except: print('noe gikk galt') return True def search_words(self, words, exponent=1.1): if type(words) is str: words = [w.strip() for w in words.split()] df = self.cluster_set(exponent=exponent, top=0, aslist=False) sub= [w for w in words if w in df.index] res = df.transpose()[sub].transpose().sort_values(by=df.columns[0], ascending=False) return res def wildcardsearch(params=None): if params is None: params = {'word': '', 'freq_lim': 50, 'limit': 50, 'factor': 2} res = requests.get('https://api.nb.no/ngram/wildcards', params=params) if res.status_code == 200: result = res.json() else: result = {'status':'feil'} resultat = pd.DataFrame.from_dict(result, orient='index') if not(resultat.empty): resultat.columns = [params['word']] return resultat def sorted_wildcardsearch(params): res = wildcardsearch(params) if not res.empty: res = res.sort_values(by=params['word'], ascending=False) return res def make_newspaper_network(key, wordbag, titel='%', yearfrom='1980', yearto='1990', limit=500): if type(wordbag) is str: wordbag = wordbag.split() r = requests.post("https://api.nb.no/ngram/avisgraph", json={ 'key':key, 'words':wordbag, 'yearto':yearto, 'yearfrom':yearfrom, 'limit':limit}) G = nx.Graph() if r.status_code == 200: G.add_weighted_edges_from([(x,y,z) for (x,y,z) in r.json() if z > 0 and x != y]) else: print(r.text) return G def make_network(urn, wordbag, cutoff=0): if type(urn) is list: urn = urn[0] if type(wordbag) is str: wordbag = wordbag.split() G = make_network_graph(urn, wordbag, cutoff) return G def make_network_graph(urn, wordbag, cutoff=0): r = requests.post("https://api.nb.no/ngram/graph", json={'urn':urn, 'words':wordbag}) G = nx.Graph() G.add_weighted_edges_from([(x,y,z) for (x,y,z) in r.json() if z > cutoff and x != y]) return G def make_network_name_graph(urn, tokens, tokenmap=None, cutoff=2): if isinstance(urn, list): urn = urn[0] # tokens should be a list of list of tokens. If it is list of dicts pull out the keys (= tokens) if isinstance(tokens[0], dict): tokens = [list(x.keys()) for x in tokens] r = requests.post("https://api.nb.no/ngram/word_graph", json={'urn':urn, 'tokens':tokens, 'tokenmap':tokenmap}) #print(r.text) G = nx.Graph() G.add_weighted_edges_from([(x,y,z) for (x,y,z) in r.json() if z > cutoff and x != y]) return G def token_convert_back(tokens, sep='_'): """ convert a list of tokens to string representation""" res = [tokens[0]] for y in tokens: res.append([tuple(x.split(sep)) for x in y]) l = len(res) for x in range(1, 4-l): res.append([]) return res def token_convert(tokens, sep='_'): """ convert back to tuples """ tokens = [list(x.keys()) for x in tokens] tokens = [[(x,) for x in tokens[0]], tokens[1], tokens[2], tokens[3]] conversion = [] for x in tokens: conversion.append([sep.join(t) for t in x]) return conversion def token_map_to_tuples(tokens_as_strings, sep='_', arrow='==>'): tuples = [] for x in tokens_as_strings: token = x.split(arrow)[0].strip() mapsto = x.split(arrow)[1].strip() tuples.append((tuple(token.split(sep)), tuple(mapsto.split(sep)))) #tuples = [(tuple(x.split(arrow).strip()[0].split(sep)), tuple(x.split(arrow)[1].strip().split(sep))) for x in tokens_as_strings] return tuples def token_map(tokens, strings=False, sep='_', arrow= '==>'): """ tokens as from nb.names()""" if isinstance(tokens[0], dict): # get the keys(), otherwise it is already just a list of tokens up to length 4 tokens = [list(x.keys()) for x in tokens] # convert tokens to tuples and put them all in one list tokens = [(x,) for x in tokens[0]] + tokens[1] + tokens[2] + tokens[3] tm = [] #print(tokens) for token in tokens: if isinstance(token, str): trep = (token,) elif isinstance(token, list): trep = tuple(token) token = tuple(token) else: trep = token n = len(trep) #print(trep) if trep[-1].endswith('s'): cp = list(trep[:n-1]) cp.append(trep[-1][:-1]) cp = tuple(cp) #print('copy', cp, trep) if cp in tokens: #print(trep, cp) trep = cp larger = [ts for ts in tokens if set(ts) >= set(trep)] #print(trep, ' => ', larger) larger.sort(key=lambda x: len(x), reverse=True) tm.append((token,larger[0])) res = tm if strings == True: res = [sep.join(x[0]) + ' ' + arrow + ' ' + sep.join(x[1]) for x in tm] return res def draw_graph_centrality(G, h=15, v=10, fontsize=20, k=0.2, arrows=False, font_color='black', threshold=0.01): node_dict = nx.degree_centrality(G) subnodes = dict({x:node_dict[x] for x in node_dict if node_dict[x] >= threshold}) x, y = rcParams['figure.figsize'] rcParams['figure.figsize'] = h, v pos =nx.spring_layout(G, k=k) ax = plt.subplot() ax.set_xticks([]) ax.set_yticks([]) G = G.subgraph(subnodes) nx.draw_networkx_labels(G, pos, font_size=fontsize, font_color=font_color) nx.draw_networkx_nodes(G, pos, alpha=0.5, nodelist=subnodes.keys(), node_size=[v * 1000 for v in subnodes.values()]) nx.draw_networkx_edges(G, pos, alpha=0.7, arrows=arrows, edge_color='lightblue', width=1) rcParams['figure.figsize'] = x, y return True def combine(clusters): """Make new collocation analyses from data in clusters""" colls = [] collocates = clusters[0].collocates for c in clusters[1:]: collocates = collocates.join(c.collocates, rsuffix='-' + str(c.period[0])) return collocates def cluster_join(cluster): clusters = [cluster[i] for i in cluster] clst = clusters[0].cluster_set(aslist=False) for c in clusters[1:]: clst = clst.join(c.cluster_set(aslist=False), rsuffix = '_'+str(c.period[0])) return clst def serie_cluster(word, startår, sluttår, inkrement, before=5, after=5, reference=150, word_samples=500): tidscluster = dict() for i in range(startår, sluttår, inkrement): tidscluster[i] = Cluster( word, corpus='avis', period=(i, i + inkrement - 1), before=after, after=after, reference=reference, word_samples=word_samples) print(i, i+inkrement - 1) return tidscluster def save_serie_cluster(tidscluster): for i in tidscluster: tidscluster[i].save() return 'OK' def les_serie_cluster(word, startår, sluttår, inkrement): tcluster = dict() for i in range(startår, sluttår, inkrement): print(i, i+inkrement - 1) tcluster[i] = Cluster(filename='{w}_{f}-{t}.json'.format(w=word, f=i,t=i+inkrement - 1)) return tcluster def make_cloud(json_text, top=100, background='white', stretch=lambda x: 2**(10*x), width=500, height=500, font_path=None): pairs0 = Counter(json_text).most_common(top) pairs = {x[0]:stretch(x[1]) for x in pairs0} wc = WordCloud( font_path=font_path, background_color=background, width=width, #color_func=my_colorfunc, ranks_only=True, height=height).generate_from_frequencies(pairs) return wc def draw_cloud(sky, width=20, height=20, fil=''): plt.figure(figsize=(width,height)) plt.imshow(sky, interpolation='bilinear') figplot = plt.gcf() if fil != '': figplot.savefig(fil, format='png') return def cloud(pd, column='', top=200, width=1000, height=1000, background='black', file='', stretch=10, font_path=None): if column == '': column = pd.columns[0] data = json.loads(pd[column].to_json()) a_cloud = make_cloud(data, top=top, background=background, font_path=font_path, stretch=lambda x: 2**(stretch*x), width=width, height=height) draw_cloud(a_cloud, fil=file) return def make_a_collocation(word, period=(1990, 2000), before=5, after=5, corpus='avis', samplesize=100, limit=2000): collocates = collocation(word, yearfrom=period[0], yearto=period[1], before=before, after=after, corpus=corpus, limit=limit) collocates.columns = [word] reference = get_corpus(yearfrom=period[0], yearto=period[1], samplesize=samplesize) ref_agg = aggregate(reference) ref_agg.columns = ['reference_corpus'] return ref_agg def compute_assoc(coll_frame, column, exponent=1.1, refcolumn = 'reference_corpus'): return pd.DataFrame(coll_frame[column]**exponent/coll_frame.mean(axis=1)) class Corpus: def __init__(self, filename = '', target_urns = None, reference_urns = None, period = (1950,1960), author='%', title='%', ddk='%', gender='%', subject='%', reference = 100, max_books=100): params = { 'year':period[0], 'next': period[1]-period[0], 'subject':subject, 'ddk':ddk, 'author':author, #'gender':gender, ser ikke ut til å virke for get_urn - sjekk opp APIet 'title':title, 'limit':max_books, 'reference':reference } self.params = params self.coll = dict() self.coll_graph = dict() if filename == '': if target_urns != None: målkorpus_def = target_urns else: målkorpus_def = get_urn(params) #print("Antall bøker i målkorpus ", len(målkorpus_def)) if isinstance(målkorpus_def[0], list): målkorpus_urn = [str(x[0]) for x in målkorpus_def] #print(målkorpus_urn) else: målkorpus_urn = målkorpus_def if len(målkorpus_urn) > max_books and max_books > 0: target_urn = list(numpy.random.choice(målkorpus_urn, max_books)) else: target_urn = målkorpus_urn if reference_urns != None: referansekorpus_def = reference_urns else: # select from period, usually used only of target is by metadata referansekorpus_def = get_urn({'year':period[0], 'next':period[1]-period[0], 'limit':reference}) #print("Antall bøker i referanse: ", len(referansekorpus_def)) # referansen skal være distinkt fra målkorpuset referanse_urn = [str(x[0]) for x in referansekorpus_def] self.reference_urn = referanse_urn self.target_urn = target_urn # make sure there is no overlap between target and reference # referanse_urn = list(set(referanse_urn) - set(target_urn)) målkorpus_txt = get_corpus_text(target_urn) normalize_corpus_dataframe(målkorpus_txt) if referanse_urn != []: referanse_txt = get_corpus_text(referanse_urn) normalize_corpus_dataframe(referanse_txt) combo = målkorpus_txt.join(referanse_txt) else: referanse_txt = målkorpus_txt combo = målkorpus_txt self.combo = combo self.reference = referanse_txt self.target = målkorpus_txt self.reference = aggregate(self.reference) self.reference.columns = ['reference_corpus'] ## dokumentfrekvenser mål_docf = pd.DataFrame(pd.DataFrame(målkorpus_txt/målkorpus_txt).sum(axis=1)) combo_docf = pd.DataFrame(pd.DataFrame(combo/combo).sum(axis=1)) ref_docf = pd.DataFrame(pd.DataFrame(referanse_txt/referanse_txt).sum(axis=1)) ### Normaliser dokumentfrekvensene normalize_corpus_dataframe(mål_docf) normalize_corpus_dataframe(combo_docf) normalize_corpus_dataframe(ref_docf) self.målkorpus_tot = aggregate(målkorpus_txt) self.combo_tot = aggregate(combo) self.mål_docf = mål_docf self.combo_docf = combo_docf self.lowest = self.combo_tot.sort_values(by=0)[0][0] else: self.load(filename) return def difference(self, freq_exp=1.1, doc_exp=1.1, top = 200, aslist=True): res = pd.DataFrame( (self.målkorpus_tot**freq_exp/self.combo_tot)*(self.mål_docf**doc_exp/self.combo_docf) ) res.columns = ['diff'] if top > 0: res = res.sort_values(by=res.columns[0], ascending=False).iloc[:top] else: res = res.sort_values(by=res.columns[0], ascending=False) if aslist == True: res = HTML(', '.join(list(res.index))) return res def save(self, filename): model = { 'params':self.params, 'target': self.målkorpus_tot.to_json(), 'combo': self.combo_tot.to_json(), 'target_df': self.mål_docf.to_json(), 'combo_df': self.combo_docf.to_json() } with open(filename, 'w', encoding = 'utf-8') as outfile: outfile.write(json.dumps(model)) return True def load(self, filename): with open(filename, 'r') as infile: try: model = json.loads(infile.read()) #print(model['word']) self.params = model['params'] #print(self.params) self.målkorpus_tot = pd.read_json(model['target']) #print(self.målkorpus_tot[:10]) self.combo_tot = pd.read_json(model['combo']) self.mål_docf = pd.read_json(model['target_df']) self.combo_docf = pd.read_json(model['combo_df']) except: print('noe gikk galt') return True def collocations(self, word, after=5, before=5, limit=1000): """Find collocations for word in a set of book URNs. Only books at the moment""" r = requests.post( "https://api.nb.no/ngram/urncoll", json={ 'word': word, 'urns': self.target_urn, 'after': after, 'before': before, 'limit': limit } ) temp = pd.DataFrame.from_dict(r.json(), orient='index') normalize_corpus_dataframe(temp) self.coll[word] = temp.sort_values(by = temp.columns[0], ascending = False) return True def conc(self, word, before=8, after=8, size=10, combo=0): if combo == 0: urns = self.target_urn + self.reference_urn elif combo == 1: urns = self.target_urn else: urns = self.reference_urn if len(urns) > 300: urns = list(numpy.random.choice(urns, 300, replace=False)) return get_urnkonk(word, {'urns':urns, 'before':before, 'after':after, 'limit':size}) def sort_collocations(self, word, comparison = None, exp = 1.0, above = None): if comparison == None: comparison = self.combo_tot[0] try: res = pd.DataFrame(self.coll[word][0]**exp/comparison) except KeyError: print('Constructing a collocation for {w} with default parameters.'.format(w=word)) self.collocations(word) res = pd.DataFrame(self.coll[word][0]**exp/comparison) if above == None: above = self.lowest res = res[self.combo_tot > above] return res.sort_values(by = 0, ascending = False) def search_collocations(self, word, words, comparison = None, exp = 1.0): if comparison == None: comparison = self.combo_tot[0] try: res = pd.DataFrame(self.coll[word][0]**exp/comparison) except KeyError: print('Constructing a collocation for {w} with default parameters.'.format(w=word)) self.collocations(word) res = pd.DataFrame(self.coll[word][0]**exp/comparison) search_items = list(set(res.index) & set(words)) return res.transpose()[search_items].transpose().sort_values(by = 0, ascending = False) def summary(self, head=10): info = { 'parameters':self.params, 'target_urn':self.target_urn[:head], 'reference urn':self.reference_urn[:head], } return info def search_words(self, words, freq_exp=1.1, doc_exp=1.1): if type(words) is str: words = [w.strip() for w in words.split()] df = self.difference(freq_exp = freq_exp, doc_exp=doc_exp,top=0, aslist=False) sub = [w for w in words if w in df.index] res = df.transpose()[sub].transpose().sort_values(by=df.columns[0], ascending=False) return res def make_collocation_graph(self, target_word, top = 15, before = 4, after = 4, limit = 1000, exp=1): """Make a cascaded network of collocations""" self.collocations(target_word, before=before, after=after, limit=limit) coll = self.sort_collocations(target_word, exp = exp) target_graf = dict() edges = [] for word in coll[:top].index: edges.append((target_word, word)) if word.isalpha(): self.collocations(word, before=before, after=after, limit=limit) for w in self.sort_collocations(word, exp = exp)[:top].index: if w.isalpha(): edges.append((word, w)) target_graph = nx.Graph() target_graph.add_edges_from(edges) self.coll_graph[target_word] = target_graph return target_graph def vekstdiagram(urn, params=None): if params is None: params = {} # if urn is the value of get_urn() it is a list # otherwise it just passes if type(urn) is list: urn = urn[0] para = params para['urn']= urn r = requests.post('https://api.nb.no/ngram/vekstdiagram', json = para) return pd.DataFrame(r.json()) def plot_book_wordbags(urn, wordbags, window=5000, pr = 100): """Generate a diagram of wordbags in book """ return plot_sammen_vekst(urn, wordbags, window=window, pr=pr) def plot_sammen_vekst(urn, ordlister, window=5000, pr = 100): """Plott alle seriene sammen""" rammer = [] c = dict() if isinstance(ordlister, list): if isinstance(ordlister[0], list): for l in ordlister: if l != []: c[l[0]] = l else: c[ordlister[0]] = ordlister else: c = ordlister for key in c: vekst = vekstdiagram(urn, params = {'words': c[key], 'window':window, 'pr': pr} ) vekst.columns = [key] rammer.append(vekst) return pd.concat(rammer) def spurious_names(n=300): topwords = totals(n) Removals = [x.capitalize() for x in topwords if x.isalpha()] return Removals def relaterte_ord(word, number = 20, score=False): G = make_graph(word) res = Counter(nx.eigenvector_centrality(G)).most_common(number) if score == False: res = [x[0] for x in res] return res def check_words(urn, ordbag): if type(urn) is list: urn = urn[0] ordliste = get_freq(urn, top=50000, cutoff=0) res = Counter() for w in ordbag: res[w] = ordliste[w] for p in res.most_common(): if p[1] != 0: print(p[0], p[1]) else: break return True def nb_ngram(terms, corpus='bok', smooth=3, years=(1810, 2010), mode='relative'): df = ngram_conv(get_ngram(terms, corpus=corpus), smooth=smooth, years=years, mode=mode) df.index = df.index.astype(int) return df def get_ngram(terms, corpus='avis'): req = requests.get( "http://www.nb.no/sp_tjenester/beta/ngram_1/ngram/query?terms={terms}&corpus={corpus}".format( terms=terms, corpus=corpus )) if req.status_code == 200: res = req.text else: res = "[]" return json.loads(res) def ngram_conv(ngrams, smooth=1, years=(1810,2013), mode='relative'): ngc = {} # check if relative frequency or absolute frequency is in question if mode.startswith('rel') or mode=='y': arg = 'y' else: arg = 'f' for x in ngrams: if x != []: ngc[x['key']] = {z['x']:z[arg] for z in x['values'] if int(z['x']) <= years[1] and int(z['x']) >= years[0]} return pd.DataFrame(ngc).rolling(window=smooth, win_type='triang').mean() def make_graph(words, lang='nob', cutoff=20, leaves=0): """Get galaxy from ngram-database. English and German provided by Google N-gram. Set leaves=1 to get the leaves. Parameter cutoff only works for lang='nob'. Specify English by setting lang='eng' and German by lang='ger'""" params = dict() params['terms'] = words params['corpus'] = lang params['limit'] = cutoff params['leaves'] = leaves result = requests.get("https://www.nb.no/sp_tjenester/beta/ngram_1/galaxies/query", params=params) G = nx.DiGraph() edgelist = [] if result.status_code == 200: graph = json.loads(result.text) #print(graph) nodes = graph['nodes'] edges = graph['links'] for edge in edges: edgelist += [(nodes[edge['source']]['name'], nodes[edge['target']]['name'], abs(edge['value']))] #print(edgelist) G.add_weighted_edges_from(edgelist) return G def urn_concordance(urns = None, word = None, size = 5, before = None, after = None ): """ Find a concordance within a corpus as list of URNs. This is a wrapper for get_urnkonk """ # exit if list of urns is empty if urns is None or word is None: return [] # The URNs may be presented in different ways. urns = pure_urn(urns) # find values and feed everything to get_urnkonk frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) query = {i:values[i] for i in args if values[i] != None and i != 'word'} return get_urnkonk(word, query) def konk(word, urns=None, before=5, after=5): if urns == None: print('URNer mangler') return urner = refine_book_urn(words=[word], urns=urns) return urn_concordance(word=word, urns = sample(urner, min(20, len(urner))),before = before, after = after) def concordance(word = None, corpus='bok', author=None, title=None, subtitle=None, lang=None, ddk=None, subject=None, yearfrom = None, yearto=None, before=None, after=None, size=5, gender=None, offset=None, kind='html'): if word == None: return [] frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) query = {i:values[i] for i in args if values[i] != None and i != 'word' and i != 'kind'} return get_konk(word, query, kind=kind) def get_konk(word, params=None, kind='html'): if params is None: params = {} para = params para['word']= word corpus = 'bok' if 'corpus' in para: corpus = para['corpus'] else: para['corpus'] = corpus r = requests.get('https://api.nb.no/ngram/konk', params=para) if kind=='html': rows = "" row_template = ("<tr>" "<td><a href='{urn}?searchText={kw}' target='_'>{urnredux}</a></td>" "<td>{b}</td>" "<td>{w}</td>" "<td style='text-align:left'>{a}</td>" "</tr>\n") if corpus == 'bok': for x in r.json(): rows += row_template.format( kw = word, urn=x['urn'], urnredux=','.join([x['author'], x['title'], str(x['year'])]), b=x['before'], w=x['word'], a=x['after']) else: #print(r.json()) for x in r.json(): rows += row_template.format( kw = word, urn=x['urn'], urnredux='-'.join(x['urn'].split('_')[2:6:3]), b=x['before'], w=x['word'], a=x['after']) res = "<table>{rows}</table>".format(rows=rows) res = HTML(res) elif kind == 'json': res = r.json() else: try: if corpus == 'bok': res = pd.DataFrame(r.json()) res = res[['urn','author','title','year','before','word','after']] else: res = pd.DataFrame(r.json()) res = res[['urn','before','word','after']] except: res= pd.DataFrame() #r = r.style.set_properties(subset=['after'],**{'text-align':'left'}) return res def konk_to_html(jsonkonk): rows = "" row_template = ("<tr>" "<td><a href='{urn}' target='_'>{urnredux}</a></td>" "<td>{b}</td>" "<td>{w}</td>" "<td style='text-align:left'>{a}</td>" "</tr>\n") for x in jsonkonk: rows += row_template.format( urn=x['urn'], urnredux=x['urn'], b=x['before'], w=x['word'], a=x['after']) res = "<table>{rows}</table>".format(rows=rows) return res def central_characters(graph, n=10): res = Counter(nx.degree_centrality(graph)).most_common(n) return res def central_betweenness_characters(graph, n=10): res = Counter(nx.betweenness_centrality(graph)).most_common(n) return res def get_urnkonk(word, params=None, html=True): if params is None: params = {} para = params para['word']= word try: para['urns'] = pure_urn(para['urns']) except: print('Parameter urns missing') r = requests.post('https://api.nb.no/ngram/urnkonk', json = para) if html: rows = "" for x in r.json(): rows += """<tr> <td> <a href='{urn}?searchText={kw}' target='_blank' style='text-decoration:none'>{urnredux}</a> </td> <td>{b}</td> <td>{w}</td> <td style='text-align:left'>{a}</td> </tr>\n""".format(kw=word, urn=x['urn'], urnredux="{t}, {f}, {y}".format(t=x['title'], f=x['author'], y=x['year']), b=x['before'], w=x['word'], a=x['after'] ) res = """<table>{rows}</table>""".format(rows=rows) res = HTML(res) else: res = pd.DataFrame(r.json()) res = res[['urn','before','word','after']] #r = r.style.set_properties(subset=['after'],**{'text-align':'left'}) return res def frame(something, name = None): """Try to make a frame out of something and name columns according to name, which should be a string or a list of strings, one for each column. Mismatch in numbers is taken care of.""" if isinstance(something, dict): res = pd.DataFrame.from_dict(something, orient='index') else: res = pd.DataFrame(something) number_of_columns = len(res.columns) if name != None: if isinstance(name, list): if len(name) >= number_of_columns: res.columns = name[:number_of_columns] else: res.columns = name + list(range(len(name), number_of_columns)) else: res.columns = [name] + list(range(1, number_of_columns)) return res def frame_sort(frame, by = 0, ascending = False): """sort a dataframe, if value of key is a column it will sort by that, otherwise value is interpreted as an index into the columns""" if by in frame.columns: res = frame.sort_values(by = by, ascending = ascending) elif isinstance(by, int): col = max(by, len(frame.columns) - 1) res = frame.sort_values(by = frame.columns[col], ascending = ascending) else: res = frame.sort_values(by = frame.columns[0], ascending = ascending) return res def get_urns_from_docx(document): """Find all URNs specified in a Word document - typically .docx""" import sys import zipfile import re from bs4 import BeautifulSoup with zipfile.ZipFile(document, 'r') as zfp: with zfp.open('word/document.xml') as fp: soup = BeautifulSoup(fp.read(), 'xml') return re.findall("[0-9]{13}", str(soup)) def get_urns_from_text(document): """Find all URNs in a text-file""" import re with open(document) as fp: text = fp.read() #print(text) return re.findall("[0-9]{13}", text) def get_urns_from_files(mappe, file_type='txt'): """Find URNs in files in a folder - specify folder""" import os froot, _, files = next(os.walk(mappe)) urns = dict() for f in files: fn = (os.path.join(froot, f)) #print(fn) if f.endswith('.docx'): urns[f] = get_urns_from_docx(fn) elif f.endswith('.txt'): urns[f] = get_urns_from_text(fn) return urns #======================== Utilities def xmlpretty(xmls): from bs4 import BeautifulSoup soup = BeautifulSoup(xmls, features='lxml') soup.prettify() # '<html>\n <head>\n </head>\n <body>\n <a href="http://example.com/">\n...' print(soup.prettify()) def dewey(dewey): r = requests.get("https://api.nb.no:443/dewey/v1/list", params={'class':dewey, 'language':'nob'}) try: ddk = r.json() ddc = dict() if 'deweyPathList' in ddk: for item in ddk['deweyPathList']: ddc[str(item['level'])] = [item['classValue'], item['heading']] except: ddc = [] return ddc def metadata_xml(URN, kind='marcxml'): if isinstance(URN, int): URN = "URN:NBN:no-nb_digibok_{urn}".format(urn=str(URN)) elif isinstance(URN, str): if URN.startswith('URN'): URN = URN else: URN = "URN:NBN:no-nb_digibok_{urn}".format(urn=URN) r = requests.get("https://api.nb.no:443/catalog/v1/metadata/{urn}/{kind}".format(urn=URN, kind=kind)) try: res = r.text except: res = "" return res def save_frame_to_excel(df, filename, index = False): import os if os.path.exists(filename): print('Det eksisterer allerede en fil {filename} - velg nytt navn og prøv igjen'.format(filename=filename)) else: df.to_excel(filename, index=index) return def restore_metadata_from_excel(data): import os df = pd.DataFrame() try: df = pd.read_excel(data) # From excel some stray rows with null values for urn may occur. Drop those. indexNames = df[df[df.columns[0]].isnull()].index df.drop(indexNames , inplace=True) try: urn = df.columns[0] year = df.columns[2] df = df.astype({urn: 'int64', year:'int'}) df = df.astype({urn: 'str'}) except: True except: if not os.path.exists(data): print('filen {data} ble ikke funnet'.format(data=data)) else: print('noe gikk galt ved import av dataene') return df
const getContext = require('./get-context'); const cbBuilder = require('./cb-builder'); const eventBrokenDefault = 'timeoutBroken'; const { EVENT_TIMEOUT: eventTimeOutBrokenName = eventBrokenDefault } = process.env; module.exports = (self) => new Promise((resolve, reject) => { const cb = cbBuilder(self, reject, resolve); const ctx = getContext(self, cb); self.once(eventTimeOutBrokenName, () => cb(new Error(`timeout ${self.timeout} broken`))); try { const response = self.handler.call(self.ctx, self.params, ctx, cb); if (response instanceof Promise) return response .then(res => cb(null, res)) .catch(cb) return response } catch (error) { reject(error); } });
import numpy as np import pandas as pd from tqdm import tqdm from glob import glob from pathlib import Path # from copy import copy import libs.dirs as dirs import libs.utils as utils import libs.dataset_utils as dutils import libs.commons as commons ''' Get class counts from rede 3 dataset csv file resulting from fuse_binary_datasets script ''' # rede = int(input("\nEnter desired net number.\n")) rede = 3 classList = commons.rede3_classes compiledPositivesPath = Path(dirs.iter_folder) / "dataset_rede_{}_positives_binary.csv".format(rede) datasetDf = pd.read_csv(compiledPositivesPath) datasetGroup = datasetDf.groupby('rede3') print(datasetGroup.count()['FrameHash']) countDf = pd.DataFrame(datasetGroup.count()['FrameHash']) countDf['Counts'] = countDf['FrameHash'] total = countDf['Counts'].sum() countDf['Percentage'] = countDf['Counts'].apply(lambda x: x/total) print(countDf) print(total) countDf.drop("FrameHash", axis=1, inplace=True) countDf.to_excel(compiledPositivesPath.with_name("semiauto_class_counts.xlsx"))
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import Paper from '../Paper'; import StepConnector from '../StepConnector'; export const styles = { /* Styles applied to the root element. */ root: { display: 'flex', padding: 24 }, /* Styles applied to the root element if `orientation="horizontal"`. */ horizontal: { flexDirection: 'row', alignItems: 'center' }, /* Styles applied to the root element if `orientation="vertical"`. */ vertical: { flexDirection: 'column' }, /* Styles applied to the root element if `alternativeLabel={true}`. */ alternativeLabel: { alignItems: 'flex-start' } }; const defaultConnector = React.createElement(StepConnector, null); const Stepper = React.forwardRef(function Stepper(props, ref) { const { activeStep = 0, alternativeLabel = false, children, classes, className: classNameProp, connector: connectorProp = defaultConnector, nonLinear = false, orientation = 'horizontal' } = props, other = _objectWithoutPropertiesLoose(props, ["activeStep", "alternativeLabel", "children", "classes", "className", "connector", "nonLinear", "orientation"]); const className = clsx(classes.root, classes[orientation], classNameProp, alternativeLabel && classes.alternativeLabel); const connector = React.isValidElement(connectorProp) ? React.cloneElement(connectorProp, { orientation }) : null; const childrenArray = React.Children.toArray(children); const steps = childrenArray.map((step, index) => { const controlProps = { alternativeLabel, connector: connectorProp, last: index + 1 === childrenArray.length, orientation }; const state = { index, active: false, completed: false, disabled: false }; if (activeStep === index) { state.active = true; } else if (!nonLinear && activeStep > index) { state.completed = true; } else if (!nonLinear && activeStep < index) { state.disabled = true; } return [!alternativeLabel && connector && index !== 0 && React.cloneElement(connector, _extends({ key: index }, state)), React.cloneElement(step, _extends({}, controlProps, {}, state, {}, step.props))]; }); return React.createElement(Paper, _extends({ square: true, elevation: 0, className: className, ref: ref }, other), steps); }); process.env.NODE_ENV !== "production" ? Stepper.propTypes = { /** * Set the active step (zero based index). */ activeStep: PropTypes.number, /** * If set to 'true' and orientation is horizontal, * then the step label will be positioned under the icon. */ alternativeLabel: PropTypes.bool, /** * Two or more `<Step />` components. */ children: PropTypes.node.isRequired, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * An element to be placed between each step. */ connector: PropTypes.element, /** * If set the `Stepper` will not assist in controlling steps for linear flow. */ nonLinear: PropTypes.bool, /** * The stepper orientation (layout flow direction). */ orientation: PropTypes.oneOf(['horizontal', 'vertical']) } : void 0; export default withStyles(styles, { name: 'MuiStepper' })(Stepper);
function insertionSort(valuesToSort) { for (let i = 0; i < valuesToSort.length; i++) { let temp = valuesToSort[i]; let j = i - 1; while (j >= 0 && valuesToSort[j] > temp) { valuesToSort[j + 1] = valuesToSort[j]; j--; } valuesToSort[j + 1] = temp; } return valuesToSort; } function bubbleSort(valuesToSort) { for (let i = 0; i < valuesToSort.length; i++) { for (let j = 0; j < valuesToSort.length - i - 1; j++) { if (valuesToSort[j] > valuesToSort[j + 1]) { let temp = valuesToSort[j]; valuesToSort[j] = valuesToSort[j + 1]; valuesToSort[j + 1] = temp; } } } } function selectionSort(valuesToSort) { for (let i = 0; i < valuesToSort.length - 1; i++) { let min = i; for (let j = i + 1; j < valuesToSort.length; j++) { if (valuesToSort[j] < valuesToSort[min]) { min = j; } } if (min != i) { let temp = valuesToSort[i]; valuesToSort[i] = valuesToSort[min]; valuesToSort[min] = temp; } } }
'use strict'; angular.module('groups').controller('GroupsController', ['$scope', '$http', '$location', 'Authentication', function ($scope, $http, $location, Authentication) { $scope.authentication = Authentication; $scope.getGroups = function () { $http.get('/groups').success(function (response) { $scope.groups = response; }).error(function (response) { $scope.error = response.message; }); }; //If user is signed in then redirect back home if (!$scope.authentication.user) { $location.path('/'); } else { $scope.getGroups(); } } ]);
import _ from 'lodash' import React, { Component } from 'react' import ReactDOM from 'react-dom' import YTSearch from 'youtube-api-search' import VideoList from './components/video_list' import VideoDetail from './components/video_detail' import SearchBar from './components/search_bar'; const API_KEY = 'AIzaSyCcv_oro5oJ81gTRK10sQHAaRL4BTaHnYs'; class App extends Component { constructor(props) { super(props); this.state = { videos : [], selectedVideo : null }; this.videoSearch('PlexusMD'); } videoSearch(term){ YTSearch({key:API_KEY , term : term} , (videos) => { this.setState({ videos:videos, selectedVideo:videos[0] }); }) } //In VideoList we are passing array of videos in the form of props. // onVideoSelect is a function which takes selected Video render() { const videoSearch = _.debounce((term) => {this.videoSearch(term)} , 300); return( <div> <SearchBar onSearchTermChange = {term => this.videoSearch(term)}/> <VideoDetail video={this.state.selectedVideo}/> <VideoList onVideoSelect = {selectedVideo => this.setState({selectedVideo}) } videos = {this.state.videos}/> </div> ); }; } ReactDOM.render(<App />,document.querySelector('.container'));
export const GET_ERRORS = 'GET_ERRORS'; export const SET_CURRENT_USER = 'SET_CURRENT_USER'; export const SET_RESTAURANT = 'SET_RESTAURANT';
export default function (config) { const { hooks, element } = window.wp const { Component } = element class LaravelFilemanager extends Component { constructor () { super(...arguments) this.openMediaManager = this.openMediaManager.bind(this) this.onSelect = this.onSelect.bind(this) this.state = { media: [] } } getMediaType (path) { const video = ['mp4', 'm4v', 'mov', 'wmv', 'avi', 'mpg', 'ogv', '3gp', '3g2'] const audio = ['mp3', 'm4a', 'ogg', 'wav'] const extension = path.split('.').slice(-1).pop() if (video.includes(extension)) { return 'video' } else if (audio.includes(extension)) { return 'audio' } else { return 'image' } } onSelect (items) { this.props.value = null const { multiple, onSelect } = this.props var path, publicUrl for (var i=0, len=items.length; i<len; i++) { path = items[i].path publicUrl = items[i].publicUrl const media = { url: publicUrl, type: this.getMediaType(path) } if (multiple) { this.state.media.push(media) } else if (items.length > 1) { $.oc.alert($.oc.lang.get('mediamanager.invalid_file_single_insert')) return } onSelect(multiple ? this.state.media : media) } } openMediaManager () { let media = new $.oc.mediaManager.popup({ alias: 'ocmediamanager', cropAndInsertButton: true, onInsert: (items) => { if (!items.length) { $.oc.alert($.oc.lang.get('mediamanager.invalid_file_empty_insert')) return } this.onSelect(items) media.hide() } }) } render () { const { render } = this.props return render({ open: this.openMediaManager }) } } hooks.addFilter( 'editor.MediaUpload', 'core/edit-post/components/media-upload/replace-media-upload', () => LaravelFilemanager ) }
#External libs import zipfile import sys import os #This is only here for printing pretty colors class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' def zip_function(lambda_name): ''' Zips up our function and all dependencies to be uploaded to the lambda specified in lambda name args: lambda_name: name of the lambda, retrieved from the config file ''' output_path = os.getcwd() + '/%s.zip' % lambda_name folder_path = os.curdir + '/dist' grab_lambda = os.walk(folder_path) length = len(folder_path) try: zipped_lambda = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) for root, folders, files in grab_lambda: for folder_name in folders: absolute_path = os.path.join(root, folder_name) shortened_path = os.path.join(root[length:], folder_name) print(color.CYAN + "Adding '%s' to package." % shortened_path + color.END) zipped_lambda.write(absolute_path, shortened_path) for file_name in files: absolute_path = os.path.join(root, file_name) shortened_path = os.path.join(root[length:], file_name) print(color.CYAN + "Adding '%s' to package." % shortened_path + color.END) zipped_lambda.write(absolute_path, shortened_path) print(color.CYAN + "'%s' lambda packaged successfully." % lambda_name + color.END) return True except IOError: print(message) sys.exit(1) except OSError: print(message) sys.exit(1) except zipfile.BadZipfile: print(message) sys.exit(1) finally: zipped_lambda.close()
"""Vérifier les données IRIS de l'IGN et de l'Insee. Activer l'environnement virtualenv dédié pour bien avoir toutes les dépendances. *Attention* : Python 3 uniquement ! Usage : > python verification_donnees.py --ign path/to/CONTOURS-IRIS.shp --insee path/to/reference_IRIS_geo2017.xls Testé avec les données 2017 * https://wxs-telechargement.ign.fr/1yhlj2ehpqf3q6dt6a2y7b64/telechargement/inspire/CONTOURS-IRIS-2018-06-08$CONTOURS-IRIS_2-1__SHP__FRA_2018-06-08/file/CONTOURS-IRIS_2-1__SHP__FRA_2018-06-08.7z * https://www.insee.fr/fr/statistiques/fichier/2017499/reference_IRIS_geo2017.zip """ import sys import logging import argparse from pathlib import Path import fiona import pandas as pd import daiquiri daiquiri.setup(level=logging.INFO) logger = daiquiri.getLogger("integrité") # Les champs issus fichier shp IGN IGN_FIELDS = ("INSEE_COM", "NOM_COM", "IRIS", "CODE_IRIS", "NOM_IRIS", "TYP_IRIS") IGN_SRID = "epsg:2154" # Lambert 93 # Les champs de l'export de données QGIS -> CSV QGIS_EXPORT_FIELDS = ('IRIS', 'NOM_IRIS', 'segment', 'id_num', 'IRIST', 'INSEE_COMMUNE', 'NOM_COMMUNE', 'TYP_IRIS', 'PDV', 'MENAGES_2015') # Les champs issues du fichier Excel Insee INSEE_FIELDS = ('CODE_IRIS', 'LIB_IRIS', 'TYP_IRIS', 'MODIF_IRIS', 'TRIRIS', 'GRD_QUART', 'DEPCOM', 'LIBCOM', 'UU2010', 'REG', 'DEP') INSEE_SHEETNAME = "Emboitements_IRIS" DEPARTEMENTS_HORS_METROPOLE = ('971', '972', '973', '974', '976') def _cmd_parser(): parser = argparse.ArgumentParser(usage="python {}".format(__file__), allow_abbrev=False, description="Vérifie les données IRIS IGN et Insee.") parser.add_argument("--ign", type=Path, required=True, help="Fichier shapefile IRIS de l'IGN") group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--insee", type=Path, help="Fichier Excel IRIS de l'Insee") group.add_argument("--export-qgis", type=Path, help="Fichier CSV d'export QGIS des IRIS") return parser def lire_fichier_ign(fpath): """Retourne les données du fichier shapefile IGN Vérifie aussi le nom des champs et le système de projection. Parameters ---------- fpath : Path Chemin du fichier shapefile Returns ------- pd.DataFrame """ logger.info("lecture du fichier shapefile IGN") with fiona.open(fpath) as reader: properties = reader.meta["schema"]["properties"] srid = reader.meta["crs"]["init"] # on vérifie que le nom des champs sont conformes if tuple(properties.keys()) != IGN_FIELDS: logger.error("Les champs IGN ont changé.") logger.info("Champs IGN demandés : %s", IGN_FIELDS) logger.info("Champs IGN trouvés : %s", tuple(properties.keys())) sys.exit(1) # on vérifie que le système de projection est lambert 93 if srid != IGN_SRID: logger.error("Le système de projection devrait être '%s' et non '%s'", IGN_SRID, srid) sys.exit(1) data = [row["properties"] for row in reader] return pd.DataFrame(data) def lire_fichier_insee(fpath): """Retourne les données IRIS de l'Insee Parameters ---------- fpath : Path Chemin du fichier Excel Returns ------- pd.DataFrame """ logger.info("lecture du fichier Excel Insee") data = pd.read_excel(fpath, sheet_name=INSEE_SHEETNAME, skiprows=5) if tuple(data.columns) != INSEE_FIELDS: logger.error("Les champs Insee ont changé") logger.info("Champs Insee demandés : %s", INSEE_FIELDS) logger.info("Champs Insee trouvés : %s", tuple(data.columns)) sys.exit(1) return data def lire_fichier_csv_qgis(fpath): """Retourne les données IRIS de l'export QGIS CSV Parameters ---------- fpath : Path Chemin du fichier CSV Returns ------- pd.DataFrame """ logger.info("lecture du fichier CSV export QGIS") data = pd.read_csv(fpath, dtype={"IRIS": str, "IRIST": str, "INSEE_COMMUNE": str}) if tuple(data.columns) != QGIS_EXPORT_FIELDS: logger.error("Les champs QGIS export Insee ont changé") logger.info("Champs QGIS demandés : %s", QGIS_EXPORT_FIELDS) logger.info("Champs QGIS trouvés : %s", tuple(data.columns)) sys.exit(1) return data def check_unicite(data, field): """Vérifie l'unicité d'un champs. Parameters ---------- data : pd.DataFrame field : str Returns ------- bool """ return len(data) == data[field].nunique() def comparaison_iris(left, right, left_field="CODE_IRIS", right_field="CODE_IRIS"): """On compare les IRIS qui sont dans un dataset et pas dans l'autre dataset """ left, right = set(left[left_field]), set(right[right_field]) return left.difference(right) def comparaison_avec_insee(fpath, data_ign): """On compare les données issues de l'IGN avec celles de l'Insee """ data_insee = lire_fichier_insee(fpath) logger.info("vérification d'unicité des codes IRIS") if not check_unicite(data_ign, "CODE_IRIS"): raise ValueError("Les données CODE_IRIS ne sont pas uniques dans la donnée IGN") if not check_unicite(data_insee, "CODE_IRIS"): raise ValueError("Les données CODE_IRIS ne sont pas uniques dans la donnée Insee") logger.info("Vérification des codes IRIS dans Insee & IGN") diff_insee_ign = comparaison_iris(data_insee, data_ign) if len(diff_insee_ign): logger.warning("Il y a des codes IRIS qui sont dans Insee mais pas dans IGN") # cas particulier de l'Insee qui peut avoir des IRIS dans les départements outre-mer. sample = data_insee[data_insee["CODE_IRIS"].isin(diff_insee_ign)] departement = sample["DEP"].unique() departement.sort() if tuple(departement) == DEPARTEMENTS_HORS_METROPOLE: logger.info("Différences d'IRIS entre Insee et IGN seulement dans les départements hors métropole") else: logger.error("Différences d'IRIS entre Insee et IGN même en métropole") logger.error("Il y en a %s", len(diff_insee_ign)) with open("check_iris_insee_ign.csv", "w") as fobj: sample.to_csv(fobj, index=False) logger.info("Voir fichier 'check_iris_insee_ign.csv' avec l'ensemble des IRIS différents") sys.exit(1) diff_ign_insee = comparaison_iris(data_ign, data_insee) if len(diff_ign_insee): logger.error("Il y a des codes IRIS qui sont dans IGN mais pas dans Insee") logger.error("Il y en a %s", len(diff_ign_insee)) sample = data_ign[data_ign["CODE_IRIS"].isin(diff_ign_insee)] with open("check_iris_ign_insee.csv", "w") as fobj: sample.to_csv(fobj, index=False) logger.info("Voir fichier 'check_iris_insee_ign.csv' avec l'ensemble des IRIS différents") sys.exit(1) logger.info("Vérification OK !") return {"ign": data_ign, "insee": data_insee} def comparaison_avec_export_qgis(fpath, data_ign): """On compare les données issues de l'IGN avec celles issues de l'export QGIS CSV """ data_qgis = lire_fichier_csv_qgis(fpath) logger.info("vérification d'unicité des codes IRIS") if not check_unicite(data_ign, "CODE_IRIS"): raise ValueError("Les données CODE_IRIS ne sont pas uniques dans la donnée IGN") if not check_unicite(data_qgis, "IRIST"): raise ValueError("Les données CODE_IRIS ne sont pas uniques dans la donnée Insee") logger.info("Vérification des codes IRIS dans QGIS export CSV & IGN") diff_qgis_ign = comparaison_iris(data_qgis, data_ign, "IRIST", "CODE_IRIS") if len(diff_qgis_ign): logger.warning("Il y a des codes IRIS qui sont dans export QGIS CSV mais pas dans IGN") # cas particulier on peut avoir des IRIS dans les départements outre-mer. sample = data_qgis[data_qgis["IRIST"].isin(diff_qgis_ign)] communes = sample["INSEE_COMMUNE"].unique().tolist() communes.sort() if all(x.startswith('97') for x in communes): logger.info("Différences d'IRIS entre export QGIS CSV et IGN seulement dans les communes hors métropole") else: logger.error("Différences d'IRIS entre export QGIS CSV et IGN même en métropole") logger.error("Il y en a %s", len(diff_qgis_ign)) with open("check_iris_qgis_export_ign.csv", "w") as fobj: sample.to_csv(fobj, index=False) logger.info("Voir fichier 'check_iris_qgis_export_ign.csv' avec l'ensemble des IRIS différents") sys.exit(1) diff_ign_qgis = comparaison_iris(data_ign, data_qgis, "CODE_IRIS", "IRIST") if len(diff_ign_qgis): logger.error("Il y a des codes IRIS qui sont dans IGN mais pas dans export QGIS CSV") logger.error("Il y en a %s", len(diff_ign_qgis)) sample = data_ign[data_ign["CODE_IRIS"].isin(diff_ign_qgis)] with open("check_iris_ign_qgis_export.csv", "w") as fobj: sample.to_csv(fobj, index=False) logger.info("Voir fichier 'check_iris_qgis_export_ign.csv' avec l'ensemble des IRIS différents") sys.exit(1) logger.info("Vérification OK !") return {"ign": data_ign, "qgis": data_qgis} def main(args): parser = _cmd_parser() opt = parser.parse_args(args) # on vérifie les fichiers logger.info("vérification des fichiers") if not opt.ign.is_file(): logger.error("Aucun fichier IGN '%s'", opt.ign) parser.exit() fichier_a_comparer = opt.insee or opt.export_qgis if not fichier_a_comparer.is_file(): logger.error("Aucun fichier Insee ou export QGIS '%s' à comparer", fichier_a_comparer) parser.exit() if opt.ign.suffix.lower() != ".shp": logger.error("Fichier IGN '%s' doit être un fichier shapefile", opt.ign) parser.exit() if opt.insee and opt.insee.suffix.lower() not in (".xls", ".xlsx"): logger.error("Fichier Insee '%s' doit être un fichier Excel", opt.insee) parser.exit() if opt.export_qgis and opt.export_qgis.suffix.lower() != ".csv": logger.error("Fichier export QGIS '%s' doit être un fichier CSV", opt.export_qgis) parser.exit() # lecture des données IGN et Insee data_ign = lire_fichier_ign(opt.ign) if opt.insee: result = comparaison_avec_insee(opt.insee, data_ign) elif opt.export_qgis: result = comparaison_avec_export_qgis(opt.export_qgis, data_ign) return result if __name__ == '__main__': result = main(sys.argv[1:]) ign = result["ign"] if "insee" in result: insee = result["insee"] if "qgis" in result: qgis = result["qgis"]
var Promise = require('bluebird') , grep = require('grep1') , journal = require('./journaler') , config = require('./config_manager').load() var find = module.exports /** * Configure grep function to use journal root as cwd */ grep.configure({ execOptions: {cwd: config.journal} }) /** * Takes in a search term and returns a function that tests for matches. A * RegExp string will be converted to an actual RegExp. * * @param {String} term * @return {Function} */ find.match_checker = function(term) { term = term.trim() if (/^\/.+\/$/.test(term)) { var regex = new RegExp(term.substring(1, term.length - 1)) return regex.test.bind(regex) } else { term = term.toLowerCase() return function(entry) { return entry.toLowerCase().indexOf(term) >= 0 } } } /** * Search for matches among journal titles * * @param {String} term * @return {Promise<String[]>} */ find.title = function(term) { return journal.get_entries() .filter(find.match_checker(term)) .catch(journal.noEntriesError, function() { return [] }) } /** * Search for matches among text in journal entries * * @param {String} term * @return {Promise<String[]>} */ find.text = function(term) { return new Promise(function(resolve, reject) { grep(['-i', '-l', '-r', term, '.'], function(err, stdout, stderr) { if (err) { return reject(err) } resolve(stdout.trim().split('\n')) }) }) .map(function(entry) { return entry.slice(2) }) .then(journal.filter_entries) .error(function() { return [] }) }
from rdkit import RDConfig import unittest, os from rdkit.SimDivFilters import rdSimDivPickers from rdkit.DataManip.Metric import rdMetricMatrixCalc as rdmmc from rdkit import DataStructs import numpy import random class TestCase(unittest.TestCase): def setUp(self): self.n = 1000 self.m = 80 self.d = 2 self.dataPts = numpy.zeros((self.n, self.d), 'd') for i in range(self.n): for j in range(self.d): self.dataPts[i, j] = random.random() self.dMat = rdmmc.GetEuclideanDistMat(self.dataPts) def test0MaxMin(self): pkr = rdSimDivPickers.MaxMinPicker() maxmin = pkr.Pick(self.dMat, self.n, self.m, (886, 112)) self.assertEqual(maxmin[0], 886) self.assertEqual(maxmin[1], 112) def func(i, j): if i == j: return 0.0 if i < j: j, i = i, j return self.dMat[i * (i - 1) // 2 + j] lmaxmin = pkr.LazyPick(func, self.n, self.m, (886, 112)) self.assertEqual(list(lmaxmin), list(maxmin)) lmaxmin = pkr.LazyPick(func, self.n, self.m, (886, 112), useCache=False) self.assertEqual(list(lmaxmin), list(maxmin)) self.assertRaises(ValueError, lambda: pkr.Pick(self.dMat, self.n, self.m, (1012, ))) self.assertRaises(ValueError, lambda: pkr.Pick(self.dMat, self.n, self.m, (-1, ))) maxmin = pkr.Pick(self.dMat, self.n, self.m) self.assertTrue(maxmin) lmaxmin = pkr.LazyPick(func, self.n, self.m) self.assertTrue(lmaxmin) def test1HierarchPick(self): fname = os.path.join(RDConfig.RDBaseDir, 'Code', 'SimDivPickers', 'Wrap', 'test_data', 'points.csv') with open(fname) as infil: lines = infil.readlines() self.dataPts = numpy.zeros((len(lines), 2), 'd') labels = [] i = 0 for line in lines: tlst = line.strip().split(',') self.dataPts[i, 0] = float(tlst[1]) self.dataPts[i, 1] = float(tlst[2]) labels.append(int(tlst[3])) i += 1 self.dMat = rdmmc.GetEuclideanDistMat(self.dataPts) pkr = rdSimDivPickers.HierarchicalClusterPicker(rdSimDivPickers.ClusterMethod.WARD) clusters = pkr.Cluster(self.dMat, i, 2) # check that each of the clusters have the same label for cl in clusters: clbl = labels[cl[0]] for id in cl: assert clbl == labels[id] hierarch = pkr.Pick(self.dMat, i, 2) self.assertEqual(tuple(hierarch), (1, 30)) def testIssue208(self): sz = 10 N = 3 m = [] for i in range(sz): for j in range(i + 1, sz): m.append(random.random()) m = numpy.array(m) picker = rdSimDivPickers.HierarchicalClusterPicker(rdSimDivPickers.ClusterMethod.WARD) p1 = list(picker.Pick(m, sz, N)) p1.sort() p2 = list(picker.Pick(m, sz, N)) p2.sort() self.assertEqual(p1, p2) def testInts(self): """ make sure we can handle ints too """ sz = 10 N = 3 m = [] for i in range(sz): for j in range(i + 1, sz): m.append(int(100 * random.random())) m = numpy.array(m) picker = rdSimDivPickers.HierarchicalClusterPicker(rdSimDivPickers.ClusterMethod.WARD) p1 = list(picker.Pick(m, sz, N)) p1.sort() p2 = list(picker.Pick(m, sz, N)) p2.sort() self.assertEqual(p1, p2) def testNonUniqueCrash(self): from rdkit import DataStructs sz = 10 nbits = 20 nBitsToSet = int(nbits * .3) N = 12 vs = [] for i in range(sz): bv = DataStructs.ExplicitBitVect(nbits) for j in range(nBitsToSet): val = int(nbits * random.random()) bv.SetBit(val) vs.append(bv) vs.append(bv) def taniFunc(i, j, bvs=vs): d = 1 - DataStructs.FingerprintSimilarity(bvs[i], bvs[j]) return d picker = rdSimDivPickers.MaxMinPicker() mm1 = picker.LazyPick(taniFunc, len(vs), N) self.assertEqual(len(mm1), N) picker = None picker = rdSimDivPickers.MaxMinPicker() mm2 = picker.LazyBitVectorPick(vs, len(vs), N) self.assertEqual(len(mm2), N) self.assertEqual(tuple(mm2), tuple(mm1)) picker = None ds = [] nvs = len(vs) for i in range(nvs): for j in range(i + 1, nvs): d = taniFunc(i, j) ds.append(d) m = numpy.array(ds) picker = rdSimDivPickers.HierarchicalClusterPicker(rdSimDivPickers.ClusterMethod.WARD) p1 = list(picker.Pick(m, nvs, N)) def testBitVectorMaxMin(self): from rdkit import DataStructs sz = 100 nbits = 200 nBitsToSet = int(nbits * .1) N = 10 vs = [] for i in range(sz): bv = DataStructs.ExplicitBitVect(nbits) for j in range(nBitsToSet): val = int(nbits * random.random()) bv.SetBit(val) vs.append(bv) def func(i, j, bvs=vs): d = DataStructs.TanimotoSimilarity(bvs[i], bvs[j], returnDistance=True) return d picker = rdSimDivPickers.MaxMinPicker() mm1 = picker.LazyPick(func, len(vs), N) self.assertEqual(len(mm1), N) mm2 = picker.LazyPick(func, len(vs), N, useCache=False) self.assertEqual(len(mm2), N) self.assertEqual(list(mm1), list(mm2)) mm2 = picker.LazyBitVectorPick(vs, len(vs), N) self.assertEqual(len(mm2), N) self.assertEqual(list(mm1), list(mm2)) mm2 = picker.LazyBitVectorPick(vs, len(vs), N, useCache=False) self.assertEqual(len(mm2), N) self.assertEqual(list(mm1), list(mm2)) def testBitVectorMaxMin2(self): fps = ["11110010101000000000", "00000000000010010000", "11001010000000000001", "00100110101000001000", "01010110000100011001", "11000110101001000011", "00000000001100001111", "00011110110000001101", "00000011011110100010", "11000010110001000000", "00000100010000010000", "10000001000010110010", "00010010000000010100", "00011100100110101000", "10001001100110100000", "10000110100110010000", "00101110000101000000", "11011101100011100000", "10000110000100101000", "00101000100000010001", "01000001000010000000", "00101101010100000110", "10001000100110110001", "00011000010100000001", "00101000001000100011", "00010000100010011001", "01100001000100010001", "10000101000001101101", "00001000011001011000", "11110000100100100000", "10100110000000011010", "00110100010110010010", "00000000000001010010", "00100000000010100001", "11110011000010001000", "10110001010100001000", "00001100100110011011", "00010010100100001110", "10100101100010100010", "01100100010100000001", "10101110011100000000", "01011000000001000001", "00000011100110100010", "01100001010001001001", "00001000000001001100", "10011001110000000100", "10110000001001100100", "00011000000001001011", "11001011010001100010", "10010000000001001011", "00010000100111100000", "00001000001110001000", "11010000010001100110", "01101001100000111000", "01001000001110111000", "10000000000100010010", "11001000010010000000", "01010010000100110001", "00010001010100100001", "01110010000000010000", "10001010000011000001", "00000110000000100100", "00010000010001000000", "11101100011010000011", "00000010100001010001", "00010000110010000101", "00010001001000111001", "01000010001100100110", "00110110000000100001", "00100010010110110010", "01000000110011001111", "00011000001000110010", "01111010101000110100", "00001010000010110110", "00110011000011011010", "00111010111010000110", "00010011101010000011", "00000001011000010000", "00011011101110110000", "00010001101000000001", "00010000001010011010", "00000010100100100010", "00000010001011000100", "11010000000001011100", "00001000110101000001", "00000010000000110010", "10000000010011000001", "11110110100100010000", "10001111000110001001", "00100110000110000100", "00000100100000100100", "00110000101100010100", "00001010100000100000", "01011000000011000111", "00010000100001010001", "10000010100000010000", "00001000000000110010", "00001000101011010001", "00011110000100100000", "11001001010001010100"] N = 5 fps = [DataStructs.CreateFromBitString(x) for x in fps] picker = rdSimDivPickers.MaxMinPicker() mm1 = picker.LazyBitVectorPick(fps, len(fps), N) self.assertEqual(len(mm1), N) self.assertEqual(list(mm1), [37, 1, 43, 38, 16]) mm2 = picker.LazyBitVectorPick(fps, len(fps), N, useCache=False) self.assertEqual(len(mm2), N) self.assertEqual(list(mm1), list(mm2)) if __name__ == '__main__': unittest.main()
import React from "react"; import { Loading } from "../Loading"; const SECURITY_CODE = "paradigma"; class ClassState extends React.Component { constructor(props) { super(props) this.state= { value: "", error: false, loading: false, } } /* UNSAFE_componentWillMount() { console.log("componentWillMount") } componentDidMount(){ console.log("componentDidMount") } */ componentDidUpdate() { console.log(this.state.value) if(this.state.loading) { setTimeout(() => { console.log("Empezando la validación"); if (this.state.value !== SECURITY_CODE) { this.setState({error: true, loading: false}) } else { this.setState({error: false, loading: false}) } console.log("Terminando la validación"); }, 3000) } } render() { const { error, loading, value} = this.state; return ( <div> <h2>Eliminar ClassState</h2> <p>Por favor, escribe el código de seguridad.</p> {(error && !loading) && ( <p>Error: el código es incorrecto</p> )} {loading && <Loading /> } <input placeholder="Código de seguridad" value={value} onChange={(event) => { this.setState({ value: event.target.value}) }} ></input> <button onClick={() => this.setState({error: !error})} onClick={() => this.setState({loading: true})} >Comprobar</button> </div> ) } } export { ClassState};
# coding=utf-8 import pdb import json import datetime import importlib import pandas as pd import sqlalchemy as sa from sqlalchemy import select, and_ from ultron.factor.engine.raw_factors import RawFactors class Polymerization(object): def __init__(self, common_setting = None, file_setting = None): self._file_setting = file_setting self._common_setting = common_setting self._risk_info = {} self._market_info = {} self._load_setting() def _load_setting(self): # 通用数据 if self._file_setting is not None: with open(self._common_setting) as f: common_info = json.load(f) self._market_info['conn'] = sa.create_engine(common_info['market']['conn']) self._risk_info['conn'] = sa.create_engine(common_info['risk']['conn']) self._market_info['table'] = importlib.import_module(common_info['market']['model']).__getattribute__( common_info['market']['table']) self._risk_info['table'] = importlib.import_module(common_info['risk']['model']).__getattribute__( common_info['risk']['table']) self._risk_info['trade_date'] = self._risk_info['table'].__dict__[common_info['risk']['trade_date']] self._market_info['trade_date'] = self._market_info['table'].__dict__[common_info['market']['trade_date']] self._market_info['tclose'] = self._market_info['table'].__dict__[common_info['market']['tclose']] self._market_info['code'] = self._market_info['table'].__dict__[common_info['market']['code']] self._market_info['columns'] = common_info['market']['columns'] #因子数据 if self._common_setting is not None: with open(self._file_setting) as f: self._factors_setting = json.load(f) def on_return_by_interval(self, trade_date_list): db_columns = [] table = self._market_info['table'] db_columns.append(self._market_info['trade_date']) db_columns.append(self._market_info['tclose']) db_columns.append(self._market_info['code']) columns = self._market_info['columns'] for column in columns: db_columns.append(table.__dict__[column]) query = select(db_columns).where( and_( self._market_info['trade_date'].in_(trade_date_list) ) ).order_by(self._market_info['trade_date']) df = pd.read_sql(query, con=self._market_info['conn']) df['trade_date'] = pd.to_datetime(df['trade_date']) df.sort_values(by='trade_date') return df def on_risk_by_interval(self, trade_date_list): db_columns = [] db_columns.append(self._risk_info['table']) query = select(db_columns).where( and_( self._risk_info['trade_date'].in_(trade_date_list) ) ).order_by(self._risk_info['trade_date']) df = pd.read_sql(query, con=self._risk_info['conn']) df['trade_date'] = pd.to_datetime(df['trade_date']) df.sort_values(by='trade_date') return df def on_work_by_factors(self, trade_date_list, factors_setting): factors_sets = None for setting in factors_setting: conn = setting['conn'] factors_list = setting['factors'] for factor in factors_list: raw_factors = RawFactors(conn) model_name = factor['model'] table_name = factor['table'] code_name = factor['code'] trade_date_name = factor['trade_date'] columns = factor['columns'] module = importlib.import_module(model_name) table = module.__getattribute__(table_name) factor_sets = raw_factors.on_work_by_interval(trade_date_list, table, code_name, trade_date_name, columns) if code_name != 'code': factor_sets = factor_sets.rename(columns={'symbol':'code'}) if factors_sets is None: factors_sets = factor_sets else: factors_sets = factors_sets.merge(factor_sets, on=['code','trade_date']) return factors_sets def on_main_factors(self, trade_date_list, factor_sets, return_sets): #以因子日期为主,即把T+1的收益放在T期 trade_date_list.sort(reverse=False) grouped = return_sets.groupby(by='trade_date') new_return_list = [] for k, group in grouped: index = trade_date_list.index(datetime.datetime.strptime(k.strftime('%Y-%m-%d'),'%Y-%m-%d').date()) group.loc[:,'trade_date'] = trade_date_list[index-1] new_return_list += group.to_dict(orient='records') new_return_sets = pd.DataFrame(new_return_list) new_return_sets['trade_date'] = pd.to_datetime(new_return_sets['trade_date']) return factor_sets.merge(new_return_sets, on=['code', 'trade_date']) def on_main_return(self, trade_date_list, factors, return_sets): #以收益率日期为主,即把T期因子放在T+1期 trade_date_list.sort(reverse=False) grouped = factors.groupby(by='trade_date') factors_list = [] for k, group in grouped: index = trade_date_list.index(datetime.datetime.strptime(k.strftime('%Y-%m-%d'),'%Y-%m-%d').date()) group['trade_date'] = trade_date_list[index-1] factors_list += group.to_dict(orient='records') new_factors_sets = pd.DataFrame(factors_list) return new_factors_sets.merge(return_sets, on=['code', 'trade_date']) def custom_work_by_interval(self, trade_date_list, main_type, factor_info): factors_setting = json.loads(factor_info) return self.on_work_by_factors(trade_date_list[:-1], factors_setting) def on_work_by_interval(self, trade_date_list, main_type=1, is_rename = 1): trade_date_list.sort(reverse=False) factors_sets = self.on_work_by_factors(trade_date_list[:-1], self._factors_setting) #获取当期收益率 all_return_sets = self.on_return_by_interval(trade_date_list) now_return_sets = all_return_sets.set_index('trade_date').loc[trade_date_list[:-1]].reset_index() factors_sets = factors_sets.merge(now_return_sets,on=['code','trade_date']).rename(columns={self._market_info['tclose'].name:'oclosePrice'}) return_sets = all_return_sets.set_index('trade_date').loc[trade_date_list[1:]].reset_index() return_sets = return_sets.rename(columns={self._market_info['tclose'].name:'nclosePrice'}) ''' now_return_sets = self.on_return_by_interval(trade_date_list[:-1]) factors_sets = factors_sets.merge(now_return_sets,on=['code','trade_date']).rename(columns={self._market_info['tclose'].name:'oclosePrice'}) return_sets = self.on_return_by_interval(trade_date_list[1:]) return_sets = return_sets.rename(columns={self._market_info['tclose'].name:'nclosePrice'}) ''' if main_type == 1: # 当前日期为T factors_sets = self.on_main_factors(trade_date_list, factors_sets, return_sets) else: # 当前日期为T+1 factors_sets = self.on_main_return(trade_date_list, factors_sets, return_sets) factors_sets['chgPct'] = (factors_sets['nclosePrice'] / factors_sets['oclosePrice']) -1 #加入风险因子 risk_sets = self.on_risk_by_interval(trade_date_list) if is_rename: risk_sets.rename(columns={'Bank':'801780','RealEstate':'801180','Health':'801150', 'Transportation':'801170','Mining':'801020','NonFerMetal':'801050', 'HouseApp':'801110','LeiService':'801210','MachiEquip':'801890', 'BuildDeco':'801720','CommeTrade':'801200','CONMAT':'801710', 'Auto':'801880','Textile':'801130','FoodBever':'801120', 'Electronics':'801080','Computer':'801750','LightIndus':'801140', 'Utilities':'801160','Telecom':'801770','AgriForest':'801010', 'CHEM':'801030','Media':'801760','IronSteel':'801040','NonBankFinan':'801790', 'ELECEQP':'801730','AERODEF':'801740','Conglomerates':'801230'}, inplace=True) factors_sets = factors_sets.merge(risk_sets, on=['code','trade_date']) return factors_sets
version = "1.3.0"
import PinValidation from './pinValidation'; class PinUtils extends PinValidation { constructor(device, callBacks) { super(device, callBacks); } decimalToBinary = num => { let binaryNum = (num >>> 0).toString(2); return "00000000".substr(binaryNum.length) + binaryNum; } stringNumToBool = stringNum => !!+stringNum; findNullTerminatedString = nullTerminatedArray => { let targetIndex; for (let i = 0; i < nullTerminatedArray.length; i++) { if (nullTerminatedArray[i] === 0) { if (nullTerminatedArray[i + 1] === 0 && nullTerminatedArray[i + 2] === 0) { targetIndex = i; break; } } } return (targetIndex) ? this.convertArrayToHexString(nullTerminatedArray.slice(2, targetIndex) ) : this.convertArrayToHexString(nullTerminatedArray.slice(2) ); } findPinLength = (maxLen, minLen) => { let maxLength = 12; let minLength = 4; if (maxLen) { if (typeof maxLen === 'number' && maxLen <= 12) maxLength = (maxLen >= 4) ? maxLen : 12; } if (minLen) { if (typeof minLen === 'number' && minLen >=4) minLength = (minLen <= maxLength) ? minLen : 4; } return parseInt(`${maxLength.toString(16)}${minLength.toString(16)}`, 16); } buildPinOptionsByte = (languageSelection, waitMessage, verifyPin, pinBlockFormat) => { const languagePrompts = Object.freeze({ "disabled": "00", "englishfrench": "01", "allspecified": "10" }); languageSelection = (languageSelection) ? (languagePrompts[ languageSelection.toLowerCase() ] || languagePrompts.disabled) : languagePrompts.disabled; waitMessage = (typeof waitMessage === 'boolean') ? waitMessage : true; verifyPin = (typeof waitMessage === 'boolean') ? waitMessage : true; pinBlockFormat = (typeof(pinBlockFormat) === 'string') ? (pinBlockFormat.toLowerCase() === 'iso0') ? '0' : '1' : '0'; const binaryResult = `000${languageSelection}${((waitMessage) ? '1' : '0')}${((verifyPin) ? '1' : '0')}${pinBlockFormat}`; this.logDeviceState(`[PinOptionsByte]: binary string representation: ${binaryResult} || byte result: ${parseInt(binaryResult, 2)}`) return parseInt(binaryResult, 2); } buildN2Format = num => { const stringNum = num.toString(); const hexNum = (stringNum.length === 2) ? stringNum : `0${stringNum}`; return parseInt(`0x${hexNum[0]}${hexNum[1]}`, 16); } } export default PinUtils;
import enum import time from .._tools import AutoNameEnum from .._immutable import ImmutableDict class Event: """ Event with payload and stop property. """ def __init__(self, name: str, payload: dict): self.name = name self.stop: bool = False self.num = 0 self.payload = ImmutableDict(**payload) self.timestamp = time.time() def __str__(self): # pragma: no cover return self.name def __repr__(self): # pragma: no cover return f'<{self.__class__.__name__} {self.name} {self.timestamp}>' class PreceptEvent(AutoNameEnum): """Precept cli events.""" BEFORE_CLI_START = enum.auto() CLI_PARSED = enum.auto() CLI_STARTED = enum.auto() CLI_STOPPED = enum.auto() # pylint: disable=comparison-with-callable def __eq__(self, other): # pragma: no cover if isinstance(other, PreceptEvent): return self.value == other.value if isinstance(other, str): return other in (self.value, self.name, str(self)) if isinstance(other, Event): return other.name == self.value return False def __hash__(self): return hash(self.value) def __str__(self): # pylint: disable=invalid-str-returned return self.value
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-form-refresh`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'form-refresh'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M17.3333333,9.33333333 C16.3982691,7.36020781 14.3579813,6 12,6 C8.6862915,6 6,8.6862915 6,12 C6,15.3137085 8.6862915,18 12,18 C15.3137085,18 18,15.3137085 18,12 M18.5,6 L18.5,10 L14.5,10"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'FormRefresh'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
const { validationResult } = require('express-validator'); const get = require('lodash/get'); const { validationErrors, createError, } = require('../../lib/validation'); const buildRequestBody = require('../../lib/build-request-body'); const { accountRecoveryApi } = require('../../lib/am-api'); const { hasPrompt } = require('../../lib/callbacks'); const authErrors = require('../../lib/auth-errors'); const logger = require('../../lib/logger')(); /** * Generic function for handling POST requests in account recovery journey. * * @param {object} req The Request. * @param {object} res The Response. * @param {string} currentPage The view to render again if there are errors. * @param {string} expectedPrompt The prompt expected to be requested by ForgeRock. * @param {string} redirectPage The page to redirect to if all ok. * @returns {undefined} */ const accountRecoveryPostHandler = async ( req, res, currentPage, expectedPrompt, redirectPage, ) => { const errors = validationResult(req); if (!errors.isEmpty()) { res.render(`account-recovery/${currentPage}.njk`, validationErrors(req, errors)); } else { const requestBody = buildRequestBody(req); const result = await accountRecoveryApi(req, requestBody); if (hasPrompt(result, expectedPrompt)) { req.session.payload = result.data; res.redirect(`/account-recovery/${redirectPage}`); } else { logger.error(`${expectedPrompt} prompt expected but not received`); res.status(500).render('errors/500.njk'); } } }; /** * Checks for message node prompt in ForgeRock. * * @param {object} req The Request. * @returns {undefined} */ const messageNodeResponse = (req) => { const requestBody = req.session.payload; // Setting the callback value to 0 sends a positive response to the message node. requestBody.callbacks[1].input[0].value = 0; return accountRecoveryApi(req, requestBody) .then((result) => { logger.debug(result.data); req.session.payload = result.data; }).catch((err) => { throw err; }); }; /** * Handles post requests for OTP entries. * * @param {object} req The Request. * @param {object} res The Response. * @param {string} currentPage The page to render again if there are errors. * @param {string} expectedPrompt The prompt expected to be requested by ForgeRock. * @param {string} redirectPage The page to redirect to if all ok. * @returns {undefined} * @throws {object} Throws any unhandled errors. */ const accountRecoveryOTPPost = async ( req, res, currentPage, expectedPrompt, redirectPage, ) => { const errors = validationResult(req); if (!errors.isEmpty()) { res.render(`${currentPage}.njk`, validationErrors(req, errors)); } else { const requestBody = buildRequestBody(req); await accountRecoveryApi(req, requestBody) .then(async (result) => { const messageNodeMessage = get(result, 'data.callbacks[0].output[0].value'); req.session.payload = result.data; if (messageNodeMessage === 'resendExpiredOTP' || messageNodeMessage === 'failedOTPAttempt') { const messageNodeValueLookup = { failedOTPAttempt: 'common:errors.security-code.incorrect-security-code', resendExpiredOTP: 'common:errors.security-code.expired', }; errors.errors.push(createError(req, messageNodeValueLookup[messageNodeMessage])); await messageNodeResponse(req).then(() => { res.render(`${currentPage}.njk`, validationErrors(req, errors)); }); } else if (hasPrompt(result, expectedPrompt)) { res.redirect(redirectPage); req.session.journey = 'account-recovery'; } else { logger.error(`${expectedPrompt} prompt expected but not received`); res.status(500).render('errors/500.njk'); } }).catch((err) => { if (authErrors.isAuthFailure(err)) { const failureUrl = get(err, 'response.data.detail.failureUrl'); if (failureUrl === 'TEMP_LOCKOUT') { res.redirect('/account-recovery/temporary-lockout'); } else if (failureUrl === 'STILL_TEMP_LOCKOUT') { res.redirect('/account-recovery/still-temporary-lockout'); } else if (failureUrl === 'EMAIL_NOT_REGISTERED') { res.redirect('/account-recovery/email-not-registered'); } else { throw err; } } else { throw err; } }); } }; module.exports = { accountRecoveryPostHandler, accountRecoveryOTPPost, };
var navToggle = document.getElementById("nav-toggle"); var navTarget = navToggle.nextElementSibling; // show toggle navToggle.classList.remove("invisible"); // hide nav navTarget.setAttribute("data-expanded", "false"); // toggle nav navToggle.onclick = function() { let expanded = navToggle.getAttribute('aria-expanded') === 'true' || false; navToggle.setAttribute('aria-expanded', !expanded); navTarget.setAttribute("data-expanded", !expanded); }
import React, { useState } from "react"; import EntryCard from './entryCard'; import axiosWithAuth from '../utils/axiosWithAuth' import search from '../search.svg'; export default function SearchForm({ onSearch }) { const [text_entry, setEntry] = useState(''); const [searchPosts, setSearchPosts] = useState([]); const id = localStorage.getItem('user_id'); const onNewSearch = (str) => { axiosWithAuth() .get(`/api/journal/users/${id}/posts/?text_entry=${str}`) .then(res => setSearchPosts(res.data.posts)); } const handleInputChange = (e) => { setEntry(e.target.value) } return ( <section> <form onSubmit={(event) => { event.preventDefault(); onNewSearch(text_entry) }}> <div className='search-div' > <input className='search' onChange={handleInputChange} placeholder="Search Entry" value={text_entry} text_entry="text_entry" /> <img src={search} alt='' className='search-img' onClick={onNewSearch} /> </div> </form> <div className="grid-view"> {searchPosts.map(res => <EntryCard posts={res} />)} </div> </section> ); }
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var Test = (function () { function Test() { } Test.addClass = function (el, className) { if (el.classList) el.classList.add(className); else el.className += ' ' + className; }; Test.addTestGroup = function (body, name) { var testGroup = document.createElement('section'); var testTitle = document.createElement('h1'); Test.addClass(testGroup, 'test-group'); Test.addClass(testTitle, 'title'); testTitle.textContent = name; testGroup.appendChild(testTitle); body.appendChild(testGroup); return testGroup; }; Test.addTest = function (testGroup, name) { var testSection = document.createElement('section'); var title = document.createElement('h2'); Test.addClass(testSection, 'test'); Test.addClass(title, 'title'); title.textContent = name; testSection.appendChild(title); testGroup.appendChild(testSection); return testSection; }; Test.pass = function (testSection) { var pass = document.createElement('span'); Test.addClass(pass, 'passed'); pass.textContent = "Passed"; testSection.appendChild(pass); }; Test.fail = function (testSection, e) { var fail = document.createElement('span'); var error = document.createElement('p'); Test.addClass(fail, 'failed'); Test.addClass(error, 'error'); fail.textContent = "Failed"; error.textContent = e.stack; testSection.appendChild(fail); testSection.appendChild(error); }; Test.run = function () { return __awaiter(this, void 0, void 0, function () { var body, _i, _a, test, instance, testGroup, _b, _c, child, testSection, e_1; return __generator(this, function (_d) { switch (_d.label) { case 0: body = document.querySelector('body'); _i = 0, _a = Test.testClasses; _d.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/, 8]; test = _a[_i]; instance = Object.create(test.obj); instance.constructor.apply(instance); testGroup = Test.addTestGroup(body, instance.constructor.name); _b = 0, _c = test.children; _d.label = 2; case 2: if (!(_b < _c.length)) return [3 /*break*/, 7]; child = _c[_b]; testSection = Test.addTest(testGroup, child.name); _d.label = 3; case 3: _d.trys.push([3, 5, , 6]); return [4 /*yield*/, child.func.apply(instance)]; case 4: _d.sent(); Test.pass(testSection); return [3 /*break*/, 6]; case 5: e_1 = _d.sent(); Test.fail(testSection, e_1); return [3 /*break*/, 6]; case 6: _b++; return [3 /*break*/, 2]; case 7: _i++; return [3 /*break*/, 1]; case 8: return [2 /*return*/]; } }); }); }; Test.testClasses = []; return Test; }()); var Assert = (function () { function Assert() { } Assert.fail = function (message) { throw new Error(message); }; Assert.areEqual = function (expected, actual, message) { if (expected !== actual) { throw new Error(message); } }; Assert.areNotEqual = function (expected, actual, message) { if (expected === actual) { throw new Error(message); } }; Assert.isTrue = function (value, message) { if (value !== true) { throw new Error(message); } }; Assert.isFalse = function (value, message) { if (value !== false) { throw new Error(message); } }; Assert.isTruthy = function (value, message) { if (!value) { throw new Error(message); } }; Assert.isFalsy = function (value, message) { if (value) { throw new Error(message); } }; Assert.delay = function (callBack, milliseconds) { return new Promise(function (resolve, reject) { var handle = window.setTimeout(function (args) { try { callBack(args); window.clearTimeout(handle); resolve(); } catch (e) { reject(e); } }, milliseconds); }); }; return Assert; }()); /// <reference path="index.ts" /> function testMethod() { function getTestClass(target) { for (var _i = 0, _a = Test.testClasses; _i < _a.length; _i++) { var test = _a[_i]; if (test.obj === target) { return test; } } return undefined; } function setTestClass(target) { var t = getTestClass(target); if (!t) { var index = Test.testClasses.push({ obj: target, children: [] }) - 1; t = Test.testClasses[index]; } return t; } return function (target, propertyKey, descriptor) { var t = setTestClass(target); t.children.push({ name: propertyKey, func: target[propertyKey] }); }; } //# sourceMappingURL=index.js.map
#!/usr/bin/env python import json import sys from boto.exception import S3ResponseError from boto.s3.connection import S3Connection from boto.s3.key import Key import config import utils def update_state_list(environment, state, clear=False): c = S3Connection() bucket = c.get_bucket(config.S3_BUCKETS[environment]) k = Key(bucket) k.key = 'states.jsonp' try: data = k.get_contents_as_string() # No existing file if not data: raise S3ResponseError() # Strip off jsonp wrapper contents = utils.gunzip_data(data) data = contents[7:-1] states = json.loads(data) except S3ResponseError: states = [] if clear: states = [state] print 'Reset list of avialable states and added %s' % state else: if state not in states: states.append(state) print '%s added to available state list' % state else: print '%s is already available' % state jsonp = 'states(%s)' % json.dumps(states) compressed = utils.gzip_data(jsonp) k.set_contents_from_string(compressed, headers={ 'Content-encoding': 'gzip', 'Content-Type': 'application/json' }, policy='public-read') if __name__ == '__main__': if len(sys.argv) < 3: sys.exit('You must specify either "staging" or "production" and a state as arguments to this script.') ENVIRONMENT = sys.argv[1] STATE = sys.argv[2] try: CLEAR = sys.argv[3] except: CLEAR = None update_state_list(ENVIRONMENT, STATE, (CLEAR == 'CLEAR'))
from torch.optim import ( SGD, Adam )
const Koa = require("koa") const app = new Koa() app.use(async ctx => { ctx.body = "hi" }) app.listen(3000)
module["exports"]=[ "Mr. aaa", "Mr. bbb", "Mr. ccc", "Mr. ddd", "Mr. eee", "Mr. fff", "Mr. ggg", "Mr. hhh", "Mr. iii", "Mr. jjj" ];
/** * Created by A on 2016/5/15. */ window.onload=function () { // fottor //找人 var box = document.getElementById("box"); var ad = box.children[0]; var ul = document.getElementById("imgs"); var lis = ul.children; var arr = document.getElementById("arr"); var left = document.getElementById("left"); var right = document.getElementById("right"); //alert(ad.offsetWidth); var imgWidth = ad.offsetWidth;//图片宽度 //鼠标经过盒子显示箭头 box.onmouseover = function () { arr.style.display = "block";//把装有箭头的盒子显示出了 } box.onmouseout = function () { arr.style.display = "none";//把装有箭头的盒子隐藏 } var pic = 0; //点击右侧按钮 移动ul到指定位置 right.onclick = function () { if (pic < lis.length - 1) { pic++; //目标 和 pic 有关 和图片宽度有关 而且是负数 var target = -pic * imgWidth; animate(ul, target); } } left.onclick = function () { if (pic > 0) { pic--; //目标 和 pic 有关 和图片宽度有关 而且是负数 var target = -pic * imgWidth; animate(ul, target); } } function animate(obj, target) { clearInterval(obj.timer); obj.timer = setInterval(function () { var leader = obj.offsetLeft; /*//如果offsetLeft<target 说明 盒子在目标左侧 应该往右走 step是正数 if (obj.offsetLeft < target) { var step = 10; } //如果offsetLeft>target 说明 盒子在目标右侧 应该往左走 step是负数 if (obj.offsetLeft > target) { var step = -10; }*/ var step = 20; step = obj.offsetLeft < target ? step : -step; leader = leader + step; if (Math.abs(obj.offsetLeft - target) > Math.abs(step)) { obj.style.left = leader + "px"; } else { obj.style.left = target + "px"; clearInterval(obj.timer); } }, 15) } var footer_div = document.getElementById("footer_div"); var ulid = document.getElementById("ulid"); var ullis=ulid.children; var iwidth = ulid.offsetWidth; var timer = null; var pic = 0; //鼠标经过盒子停止 footer_div.onmouseover = function () { clearInterval(timer); } //鼠标离开盒子移动 footer_div.onmouseout = function () { timer = setInterval(play, 20); } //深度克隆节点 var firstImg=ullis[0].cloneNode(true); ulid.appendChild(firstImg); //让ul移动 定时器 timer = setInterval(play, 20); function play(){ /*if(pic==ullis.length-1){ ulid.style.left="-40px"; pic=0; } pic++; var target = -pic * iwidth; animate(ulid, target);*/ if(ulid.offsetLeft>-3600){ var leader = ulid.offsetLeft; var step = -10; leader = leader + step; ulid.style.left = leader + "px"; }else { ulid.style.left = "10px"; } } /* 1.leader=leader+step 2.让ul往左移动距离为leader 3.移动到最后一个 变回第一个 */ function animate(obj, target) { clearInterval(obj.timer); obj.timer = setInterval(function () { var step = 10; step = obj.offsetLeft > target ? -step : step; var leader = obj.offsetLeft; leader = leader + step; if (Math.abs(obj.offsetLeft - target)>Math.abs(step)) { obj.style.left = leader + "px"; } else { obj.style.left = target + "px"; clearInterval(obj.timer); } }, 20); } };
/** * Copyright IBM Corp. 2016, 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * Code generated by @carbon/icon-build-helpers. DO NOT EDIT. */ 'use strict'; var _24 = { "elem": "svg", "attrs": { "xmlns": "http://www.w3.org/2000/svg", "viewBox": "0 0 32 32", "fill": "currentColor", "width": 24, "height": 24 }, "content": [{ "elem": "path", "attrs": { "d": "M18.7061,27.585a5.2615,5.2615,0,0,1-3.7227-8.9834l1.415,1.414a3.2638,3.2638,0,1,0,4.6153,4.6162l6.03-6.03a3.264,3.264,0,0,0-4.6162-4.6158l-1.414-1.414a5.2637,5.2637,0,0,1,7.4443,7.4438l-6.03,6.03A5.2461,5.2461,0,0,1,18.7061,27.585Z" } }, { "elem": "path", "attrs": { "d": "M10.2642 29.9971A5.2619 5.2619 0 016.542 21.0137l6.03-6.03a5.2636 5.2636 0 117.4438 7.4438l-1.414-1.414a3.2639 3.2639 0 10-4.6158-4.6158l-6.03 6.03a3.264 3.264 0 004.6157 4.6162l1.414 1.4141A5.2452 5.2452 0 0110.2642 29.9971zM2 10H10V12H2zM2 6H14V8H2zM2 2H14V4H2z" } }], "name": "text-link", "size": 24 }; module.exports = _24;
const fs = require('fs') const path = require('path') const pretty = require('pretty') const src = path.join(__dirname, 'dist', 'index.html') const out = path.join(__dirname, 'dist', 'pretty.html') fs.writeFileSync(out, pretty(fs.readFileSync(src, 'utf8'), { ocd: true }))
import os import asyncio import json from aiohttp import web import settings from game import Game async def handle(request): ALLOWED_FILES = ["index.html", "style.css"] name = request.match_info.get('name', 'index.html') if name in ALLOWED_FILES: try: with open(name, 'rb') as index: return web.Response(body=index.read(), content_type='text/html') except FileNotFoundError: pass return web.Response(status=404) async def wshandler(request): print("Connected") app = request.app game = app["game"] ws = web.WebSocketResponse() await ws.prepare(request) player = None while True: msg = await ws.receive() if msg.tp == web.MsgType.text: print("Got message %s" % msg.data) data = json.loads(msg.data) if type(data) == int and player: # Interpret as key code player.keypress(data) if type(data) != list: continue if not player: if data[0] == "new_player": player = game.new_player(data[1], ws) elif data[0] == "join": if not game.running: game.reset_world() print("Starting game loop") asyncio.ensure_future(game_loop(game)) game.join(player) elif msg.tp == web.MsgType.close: break if player: game.player_disconnected(player) print("Closed connection") return ws async def game_loop(game): game.running = True while 1: game.next_frame() if not game.count_alive_players(): print("Stopping game loop") break await asyncio.sleep(1./settings.GAME_SPEED) game.running = False event_loop = asyncio.get_event_loop() event_loop.set_debug(True) app = web.Application() app["game"] = Game() app.router.add_route('GET', '/connect', wshandler) app.router.add_route('GET', '/{name}', handle) app.router.add_route('GET', '/', handle) # get port for heroku port = int(os.environ.get('PORT', 5000)) web.run_app(app, port=port)
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * @class * Initializes a new instance of the DomainRecommendationSearchParameters class. * @constructor * Domain recommendation search parameters * * @member {string} [keywords] Keywords to be used for generating domain * recommendations * * @member {number} [maxDomainRecommendations] Maximum number of * recommendations * */ function DomainRecommendationSearchParameters() { } /** * Defines the metadata of DomainRecommendationSearchParameters * * @returns {object} metadata of DomainRecommendationSearchParameters * */ DomainRecommendationSearchParameters.prototype.mapper = function () { return { required: false, serializedName: 'DomainRecommendationSearchParameters', type: { name: 'Composite', className: 'DomainRecommendationSearchParameters', modelProperties: { keywords: { required: false, serializedName: 'keywords', type: { name: 'String' } }, maxDomainRecommendations: { required: false, serializedName: 'maxDomainRecommendations', type: { name: 'Number' } } } } }; }; module.exports = DomainRecommendationSearchParameters;
import React from "react" import {graphql, Link} from "gatsby" import Img from "gatsby-image" import { slugify } from "../util/utilityFunctions" import Layout from "../pages/components/layout" const SinglePost = ({data}) => { const post = data.markdownRemark.frontmatter return ( <Layout> <div className="content"> <div className="single-post-header"> <h1 className="single-post-title">{post.title}</h1> <span>{post.date}</span> <div className="d-f" style={{ alignItems: 'center', padding: '0.5em 0', }} > by{" "} <Img className="author-avatar f-1" fluid={post.authorImage.childImageSharp.fluid}/> <span>{post.author}</span> </div> <ul className="tags"> {post.tags.map(tag => ( <li key={tag}> <Link to={`/tag/${slugify(tag)}`}> {tag} </Link> </li> ))} </ul> </div> <Img style={{ marginBottom: `2em`, }} className="post-image-main" fluid={post.featuredImage.childImageSharp.fluid}/> <article> <div dangerouslySetInnerHTML={{ __html: data.markdownRemark.html}}/> </article> </div> </Layout> ) } export const postQuery = graphql` query blogPostBySlug($slug: String!){ markdownRemark(fields: { slug: { eq: $slug }}){ id html frontmatter{ title author date(formatString: "MMM Do YYYY") tags featuredImage{ childImageSharp{ fluid(maxWidth: 700){ ...GatsbyImageSharpFluid } } } authorImage{ childImageSharp{ fluid(maxWidth: 100){ ...GatsbyImageSharpFluid } } } } } } ` export default SinglePost
import chai, { expect } from 'chai' import chaiAsPromised from 'chai-as-promised' chai.use(chaiAsPromised) chai.should() describe('Example', function () { it('test', function () { expect(1).to.equal(1) }) })
import PropTypes from 'prop-types'; import moment from 'moment'; import { Box, Button, Dialog, DialogTitle, DialogContent, DialogActions, Divider, IconButton, Paper } from '@material-ui/core'; import CloseIcon from '@material-ui/icons/Close'; import DisplayInfo from 'src/components/DisplayInfo'; import MailBox from 'src/components/MailBox'; import resources from 'src/resources'; const BootstrapDialogTitle = ({ children, onClose, ...other }) => ( <DialogTitle sx={{ m: 0, py: 1.5, px: 2, backgroundColor: 'primary.main', color: 'primary.contrastText', fontSize: '1rem', position: 'relative' }} {...other} > {children} {onClose ? ( <IconButton aria-label="close" onClick={onClose} sx={{ position: 'absolute', right: 5, top: '50%', transform: 'translateY(-50%)', color: 'primary.contrastText' }} > <CloseIcon /> </IconButton> ) : <></>} </DialogTitle> ); BootstrapDialogTitle.propTypes = { children: PropTypes.node, onClose: PropTypes.func.isRequired, }; const InfoDialog = ({ isOpen, onClose, isEdit, currentDetail, mappingData, optionEnum, maxWidth = 'sm', children, loading }) => { const formatTableValue = (row, key) => { const target = mappingData.mappingCurrentDetail.find((item) => item.key === key); const value = row[key]; if (target && value) { switch (target.typeControl.main) { case 'date': return value ? moment(value).format('DD/MM/YYYY') : ''; case 'dateTime': return value ? moment(value).format('DD/MM/YYYY HH:mm') : ''; case 'select': // case column type is select and using foreign key const items = optionEnum[target.foreignName || target.localName] || []; const columnTarget = items.find((item) => item.id === value); if (columnTarget) { if (target.typeControl.sub === 'chip') { return <Box sx={{ color: `${columnTarget.color}.main` }}>{ columnTarget.name }</Box>; } return columnTarget.name; } return ''; case 'checkbox': return value ? 'Yes' : 'No'; default: return value; } } return value; }; const formatAvatarName = (name) => { if (!name) return ''; const names = name.split(' '); if (names.length === 1) { return name.substring(0, 2).toUpperCase(); } return names.slice(-2).map((item) => item.substring(0, 1)); }; const infoList = mappingData.mappingCurrentDetail.map((item) => ({ key: item.key, label: item.header, value: formatTableValue(currentDetail, item.key) })); const mailData = { avatar: formatAvatarName(currentDetail.employeeFullName), name: currentDetail.employeeFullName, to: currentDetail.toUser, cc: currentDetail.ccUser, reciveDate: moment(currentDetail.reciveDate).format('LLLL') }; const mailType = resources.mailTypes.find((item) => item.id === currentDetail.docType); const mailTitle = mailType ? mailType.name : ''; return ( <Dialog sx={{ '& .MuiDialogContent-root': { p: 0 }, '& .MuiDialogActions-root': { padding: (theme) => theme.spacing(1.5, 2) }, '& .MuiDialog-paperScrollPaper': { margin: '0 !important', width: { xs: 'calc(100% - 24px)!important', sm: 'calc(100% - 64px) !important' } } }} onClose={onClose} open={isOpen} scroll="paper" fullWidth maxWidth={maxWidth} > <BootstrapDialogTitle onClose={onClose}> { `Thông tin ${mailTitle.toLowerCase()}` } </BootstrapDialogTitle> <DialogContent dividers> <Box sx={{ p: 2 }}> <Paper sx={{ p: 1, mx: 1, mb: 1.5 }}> <MailBox data={mailData} /> </Paper> <DisplayInfo data={infoList} /> </Box> </DialogContent> <DialogActions> <Button variant="outlined" onClick={onClose}>Đóng</Button> </DialogActions> </Dialog> ); }; InfoDialog.propTypes = { loading: PropTypes.bool, children: PropTypes.node, isOpen: PropTypes.bool, isEdit: PropTypes.bool, onClose: PropTypes.func, mappingData: PropTypes.object, currentDetail: PropTypes.object, optionEnum: PropTypes.object, maxWidth: PropTypes.string }; export default InfoDialog;
console.log('hello node'); console.log('使用node file'); console.log('使用nodemon命令');
n = int(input('Digite um número: ')) print(f'O número sucessor é {n+1}') print(f'O número anterior é {n-1}')
'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var fs$1 = _interopDefault(require('fs')); var path = _interopDefault(require('path')); var customOpenDatabase = _interopDefault(require('websql/custom/index.js')); function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /* eslint-disable no-sync, no-restricted-syntax */ // Todo: Switch to ES6 classes var phases = { NONE: 0, CAPTURING_PHASE: 1, AT_TARGET: 2, BUBBLING_PHASE: 3 }; var ShimDOMException = typeof DOMException === 'undefined' // Todo: Better polyfill (if even needed here) // eslint-disable-next-line no-shadow ? function DOMException(msg, name) { // No need for `toString` as same as for `Error` var err = new Error(msg); err.name = name; return err; } : DOMException; var ev = new WeakMap(); var evCfg = new WeakMap(); // Todo: Set _ev argument outside of this function /* eslint-disable func-name-matching, no-shadow */ /** * We use an adapter class rather than a proxy not only for compatibility * but also since we have to clone native event properties anyways in order * to properly set `target`, etc. * The regular DOM method `dispatchEvent` won't work with this polyfill as * it expects a native event. * @class * @param {string} type */ var ShimEvent = function Event(type) { /* eslint-enable func-name-matching, no-shadow */ // For WebIDL checks of function's `length`, we check `arguments` for the optional arguments this[Symbol.toStringTag] = 'Event'; this.toString = function () { return '[object Event]'; }; // eslint-disable-next-line prefer-rest-params var _arguments = Array.prototype.slice.call(arguments), evInit = _arguments[1], _ev = _arguments[2]; if (!arguments.length) { throw new TypeError("Failed to construct 'Event': 1 argument required, but only 0 present."); } evInit = evInit || {}; _ev = _ev || {}; var _evCfg = {}; if ('composed' in evInit) { _evCfg.composed = evInit.composed; } // _evCfg.isTrusted = true; // We are not always using this for user-created events // _evCfg.timeStamp = new Date().valueOf(); // This is no longer a timestamp, but monotonic (elapsed?) ev.set(this, _ev); evCfg.set(this, _evCfg); this.initEvent(type, evInit.bubbles, evInit.cancelable); Object.defineProperties(this, ['target', 'currentTarget', 'eventPhase', 'defaultPrevented'].reduce(function (obj, prop) { obj[prop] = { get: function get() { return ( /* prop in _evCfg && */ _evCfg[prop] !== undefined ? _evCfg[prop] : prop in _ev ? _ev[prop] : // Defaults prop === 'eventPhase' ? 0 : prop === 'defaultPrevented' ? false : null ); } }; return obj; }, {})); var props = [// Event 'type', 'bubbles', 'cancelable', // Defaults to false 'isTrusted', 'timeStamp', 'initEvent', // Other event properties (not used by our code) 'composedPath', 'composed']; if (this.toString() === '[object CustomEvent]') { props.push('detail', 'initCustomEvent'); } Object.defineProperties(this, props.reduce(function (obj, prop) { obj[prop] = { get: function get() { return prop in _evCfg ? _evCfg[prop] : prop in _ev ? _ev[prop] : ['bubbles', 'cancelable', 'composed'].includes(prop) ? false : undefined; } }; return obj; }, {})); }; ShimEvent.prototype.preventDefault = function () { if (!(this instanceof ShimEvent)) { throw new TypeError('Illegal invocation'); } var _ev = ev.get(this); var _evCfg = evCfg.get(this); if (this.cancelable && !_evCfg._passive) { _evCfg.defaultPrevented = true; if (typeof _ev.preventDefault === 'function') { // Prevent any predefined defaults _ev.preventDefault(); } } }; ShimEvent.prototype.stopImmediatePropagation = function () { var _evCfg = evCfg.get(this); _evCfg._stopImmediatePropagation = true; }; ShimEvent.prototype.stopPropagation = function () { var _evCfg = evCfg.get(this); _evCfg._stopPropagation = true; }; ShimEvent.prototype.initEvent = function (type, bubbles, cancelable) { // Chrome currently has function length 1 only but WebIDL says 3 // const bubbles = arguments[1]; // const cancelable = arguments[2]; var _evCfg = evCfg.get(this); if (_evCfg._dispatched) { return; } _evCfg.type = type; if (bubbles !== undefined) { _evCfg.bubbles = bubbles; } if (cancelable !== undefined) { _evCfg.cancelable = cancelable; } }; ['type', 'target', 'currentTarget'].forEach(function (prop) { Object.defineProperty(ShimEvent.prototype, prop, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); }); ['eventPhase', 'defaultPrevented', 'bubbles', 'cancelable', 'timeStamp'].forEach(function (prop) { Object.defineProperty(ShimEvent.prototype, prop, { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); }); ['NONE', 'CAPTURING_PHASE', 'AT_TARGET', 'BUBBLING_PHASE'].forEach(function (prop, i) { Object.defineProperty(ShimEvent, prop, { enumerable: true, writable: false, value: i }); Object.defineProperty(ShimEvent.prototype, prop, { writable: false, value: i }); }); ShimEvent[Symbol.toStringTag] = 'Function'; ShimEvent.prototype[Symbol.toStringTag] = 'EventPrototype'; Object.defineProperty(ShimEvent, 'prototype', { writable: false }); /* eslint-disable func-name-matching, no-shadow */ /** * * @param {string} type * @class */ var ShimCustomEvent = function CustomEvent(type) { /* eslint-enable func-name-matching, no-shadow */ // eslint-disable-next-line prefer-rest-params var _arguments2 = Array.prototype.slice.call(arguments), evInit = _arguments2[1], _ev = _arguments2[2]; ShimEvent.call(this, type, evInit, _ev); this[Symbol.toStringTag] = 'CustomEvent'; this.toString = function () { return '[object CustomEvent]'; }; // var _evCfg = evCfg.get(this); evInit = evInit || {}; this.initCustomEvent(type, evInit.bubbles, evInit.cancelable, 'detail' in evInit ? evInit.detail : null); }; Object.defineProperty(ShimCustomEvent.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: ShimCustomEvent }); ShimCustomEvent.prototype.initCustomEvent = function (type, bubbles, cancelable, detail) { if (!(this instanceof ShimCustomEvent)) { throw new TypeError('Illegal invocation'); } var _evCfg = evCfg.get(this); ShimCustomEvent.call(this, type, { bubbles: bubbles, cancelable: cancelable, detail: detail // eslint-disable-next-line prefer-rest-params }, arguments[4]); if (_evCfg._dispatched) { return; } if (detail !== undefined) { _evCfg.detail = detail; } Object.defineProperty(this, 'detail', { get: function get() { return _evCfg.detail; } }); }; ShimCustomEvent[Symbol.toStringTag] = 'Function'; ShimCustomEvent.prototype[Symbol.toStringTag] = 'CustomEventPrototype'; Object.defineProperty(ShimCustomEvent.prototype, 'detail', { enumerable: true, configurable: true, get: function get() { throw new TypeError('Illegal invocation'); } }); Object.defineProperty(ShimCustomEvent, 'prototype', { writable: false }); /** * * @param {Event} e * @returns {ShimEvent} */ function copyEvent(e) { var bubbles = e.bubbles, cancelable = e.cancelable, detail = e.detail, type = e.type; if ('detail' in e) { return new ShimCustomEvent(type, { bubbles: bubbles, cancelable: cancelable, detail: detail }, e); } return new ShimEvent(type, { bubbles: bubbles, cancelable: cancelable }, e); } /** * @typedef {PlainObject} ListenerOptions * @property {boolean} once Remove listener after invoking once * @property {boolean} passive Don't allow `preventDefault` * @property {boolean} capture Use `_children` and set `eventPhase` */ /** * @typedef {PlainObject} ListenerAndOptions * @property {listener} listener * @property {ListenerOptions} options */ /** * @typedef {PlainObject} ListenerInfo * @property {ListenerAndOptions[]} listenersByTypeOptions * @property {ListenerOptions} options * @property {ListenerAndOptions[]} listenersByType */ /** * @callback Listener * @param {Event} e * @returns {boolean} */ /** * Keys are event types. * @typedef {Object<string,Listener[]>} Listeners */ /** * * @param {Listeners} listeners * @param {string} type * @param {boolean|ListenerOptions} options * @returns {ListenerInfo} */ function getListenersOptions(listeners, type, options) { var listenersByType = listeners[type]; if (listenersByType === undefined) listeners[type] = listenersByType = []; options = typeof options === 'boolean' ? { capture: options } : options || {}; var stringifiedOptions = JSON.stringify(options); var listenersByTypeOptions = listenersByType.filter(function (obj) { return stringifiedOptions === JSON.stringify(obj.options); }); return { listenersByTypeOptions: listenersByTypeOptions, options: options, listenersByType: listenersByType }; } var methods = { addListener: function addListener(listeners, listener, type, options) { var listenerOptions = getListenersOptions(listeners, type, options); var listenersByTypeOptions = listenerOptions.listenersByTypeOptions; options = listenerOptions.options; var listenersByType = listenerOptions.listenersByType; if (listenersByTypeOptions.some(function (l) { return l.listener === listener; })) return; listenersByType.push({ listener: listener, options: options }); }, removeListener: function removeListener(listeners, listener, type, options) { var listenerOptions = getListenersOptions(listeners, type, options); var listenersByType = listenerOptions.listenersByType; var stringifiedOptions = JSON.stringify(listenerOptions.options); listenersByType.some(function (l, i) { if (l.listener === listener && stringifiedOptions === JSON.stringify(l.options)) { listenersByType.splice(i, 1); if (!listenersByType.length) delete listeners[type]; return true; } return false; }); }, hasListener: function hasListener(listeners, listener, type, options) { var listenerOptions = getListenersOptions(listeners, type, options); var listenersByTypeOptions = listenerOptions.listenersByTypeOptions; return listenersByTypeOptions.some(function (l) { return l.listener === listener; }); } }; /* eslint-disable no-shadow */ /** * @class */ function EventTarget() { /* eslint-enable no-shadow */ throw new TypeError('Illegal constructor'); } Object.assign(EventTarget.prototype, ['Early', '', 'Late', 'Default'].reduce(function (obj, listenerType) { ['add', 'remove', 'has'].forEach(function (method) { obj[method + listenerType + 'EventListener'] = function (type, listener) { // eslint-disable-next-line prefer-rest-params var options = arguments[2]; // We keep the listener `length` as per WebIDL if (arguments.length < 2) throw new TypeError('2 or more arguments required'); if (typeof type !== 'string') { throw new ShimDOMException('UNSPECIFIED_EVENT_TYPE_ERR', 'UNSPECIFIED_EVENT_TYPE_ERR'); } try { // As per code such as the following, handleEvent may throw, // but is uncaught // https://github.com/web-platform-tests/wpt/blob/master/IndexedDB/fire-error-event-exception.html#L54-L56 if (listener.handleEvent && listener.handleEvent.bind) { listener = listener.handleEvent.bind(listener); } } catch (err) { // eslint-disable-next-line no-console console.log('Uncaught `handleEvent` error', err); } var arrStr = '_' + listenerType.toLowerCase() + (listenerType === '' ? 'l' : 'L') + 'isteners'; if (!this[arrStr]) { Object.defineProperty(this, arrStr, { value: {} }); } return methods[method + 'Listener'](this[arrStr], listener, type, options); }; }); return obj; }, {})); Object.assign(EventTarget.prototype, { __setOptions: function __setOptions(customOptions) { customOptions = customOptions || {}; // Todo: Make into event properties? this._defaultSync = customOptions.defaultSync; this._extraProperties = customOptions.extraProperties || []; if (customOptions.legacyOutputDidListenersThrowFlag) { // IndexedDB this._legacyOutputDidListenersThrowCheck = true; this._extraProperties.push('__legacyOutputDidListenersThrowError'); } }, dispatchEvent: function dispatchEvent(e) { return this._dispatchEvent(e, true); }, _dispatchEvent: function _dispatchEvent(e, setTarget) { var _this = this; ['early', '', 'late', 'default'].forEach(function (listenerType) { var arrStr = '_' + listenerType + (listenerType === '' ? 'l' : 'L') + 'isteners'; if (!_this[arrStr]) { Object.defineProperty(_this, arrStr, { value: {} }); } }); var _evCfg = evCfg.get(e); if (_evCfg && setTarget && _evCfg._dispatched) { throw new ShimDOMException('The object is in an invalid state.', 'InvalidStateError'); } var eventCopy; if (_evCfg) { eventCopy = e; } else { eventCopy = copyEvent(e); _evCfg = evCfg.get(eventCopy); _evCfg._dispatched = true; this._extraProperties.forEach(function (prop) { if (prop in e) { eventCopy[prop] = e[prop]; // Todo: Put internal to `ShimEvent`? } }); } var _eventCopy = eventCopy, type = _eventCopy.type; /** * * @returns {void} */ function finishEventDispatch() { _evCfg.eventPhase = phases.NONE; _evCfg.currentTarget = null; delete _evCfg._children; } /** * * @returns {void} */ function invokeDefaults() { // Ignore stopPropagation from defaults _evCfg._stopImmediatePropagation = undefined; _evCfg._stopPropagation = undefined; // We check here for whether we should invoke since may have changed since timeout (if late listener prevented default) if (!eventCopy.defaultPrevented || !_evCfg.cancelable) { // 2nd check should be redundant _evCfg.eventPhase = phases.AT_TARGET; // Temporarily set before we invoke default listeners eventCopy.target.invokeCurrentListeners(eventCopy.target._defaultListeners, eventCopy, type); } finishEventDispatch(); } var continueEventDispatch = function continueEventDispatch() { // Ignore stop propagation of user now _evCfg._stopImmediatePropagation = undefined; _evCfg._stopPropagation = undefined; if (!_this._defaultSync) { setTimeout(invokeDefaults, 0); } else invokeDefaults(); _evCfg.eventPhase = phases.AT_TARGET; // Temporarily set before we invoke late listeners // Sync default might have stopped if (!_evCfg._stopPropagation) { _evCfg._stopImmediatePropagation = undefined; _evCfg._stopPropagation = undefined; // We could allow stopPropagation by only executing upon (_evCfg._stopPropagation) eventCopy.target.invokeCurrentListeners(eventCopy.target._lateListeners, eventCopy, type); } finishEventDispatch(); return !eventCopy.defaultPrevented; }; if (setTarget) _evCfg.target = this; switch (eventCopy.eventPhase) { default: case phases.NONE: { _evCfg.eventPhase = phases.AT_TARGET; // Temporarily set before we invoke early listeners this.invokeCurrentListeners(this._earlyListeners, eventCopy, type); if (!this.__getParent) { _evCfg.eventPhase = phases.AT_TARGET; return this._dispatchEvent(eventCopy, false); } /* eslint-disable consistent-this */ var par = this; var root = this; /* eslint-enable consistent-this */ while (par.__getParent && (par = par.__getParent()) !== null) { if (!_evCfg._children) { _evCfg._children = []; } _evCfg._children.push(root); root = par; } root._defaultSync = this._defaultSync; _evCfg.eventPhase = phases.CAPTURING_PHASE; return root._dispatchEvent(eventCopy, false); } case phases.CAPTURING_PHASE: { if (_evCfg._stopPropagation) { return continueEventDispatch(); } this.invokeCurrentListeners(this._listeners, eventCopy, type); var child = _evCfg._children && _evCfg._children.length && _evCfg._children.pop(); if (!child || child === eventCopy.target) { _evCfg.eventPhase = phases.AT_TARGET; } if (child) child._defaultSync = this._defaultSync; return (child || this)._dispatchEvent(eventCopy, false); } case phases.AT_TARGET: if (_evCfg._stopPropagation) { return continueEventDispatch(); } this.invokeCurrentListeners(this._listeners, eventCopy, type, true); if (!_evCfg.bubbles) { return continueEventDispatch(); } _evCfg.eventPhase = phases.BUBBLING_PHASE; return this._dispatchEvent(eventCopy, false); case phases.BUBBLING_PHASE: { if (_evCfg._stopPropagation) { return continueEventDispatch(); } var parent = this.__getParent && this.__getParent(); if (!parent) { return continueEventDispatch(); } parent.invokeCurrentListeners(parent._listeners, eventCopy, type, true); parent._defaultSync = this._defaultSync; return parent._dispatchEvent(eventCopy, false); } } }, invokeCurrentListeners: function invokeCurrentListeners(listeners, eventCopy, type, checkOnListeners) { var _this2 = this; var _evCfg = evCfg.get(eventCopy); _evCfg.currentTarget = this; var listOpts = getListenersOptions(listeners, type, {}); var listenersByType = listOpts.listenersByType.concat(); var dummyIPos = listenersByType.length ? 1 : 0; listenersByType.some(function (listenerObj, i) { var onListener = checkOnListeners ? _this2['on' + type] : null; if (_evCfg._stopImmediatePropagation) return true; if (i === dummyIPos && typeof onListener === 'function') { // We don't splice this in as could be overwritten; executes here per // https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-attributes:event-handlers-14 _this2.tryCatch(eventCopy, function () { var ret = onListener.call(eventCopy.currentTarget, eventCopy); if (ret === false) { eventCopy.preventDefault(); } }); } var options = listenerObj.options; var once = options.once, passive = options.passive, capture = options.capture; _evCfg._passive = passive; if (capture && eventCopy.target !== eventCopy.currentTarget && eventCopy.eventPhase === phases.CAPTURING_PHASE || eventCopy.eventPhase === phases.AT_TARGET || !capture && eventCopy.target !== eventCopy.currentTarget && eventCopy.eventPhase === phases.BUBBLING_PHASE) { var listener = listenerObj.listener; _this2.tryCatch(eventCopy, function () { listener.call(eventCopy.currentTarget, eventCopy); }); if (once) { _this2.removeEventListener(type, listener, options); } } return false; }); this.tryCatch(eventCopy, function () { var onListener = checkOnListeners ? _this2['on' + type] : null; if (typeof onListener === 'function' && listenersByType.length < 2) { var ret = onListener.call(eventCopy.currentTarget, eventCopy); // Won't have executed if too short if (ret === false) { eventCopy.preventDefault(); } } }); return !eventCopy.defaultPrevented; }, // eslint-disable-next-line promise/prefer-await-to-callbacks tryCatch: function tryCatch(evt, cb) { try { // Per MDN: Exceptions thrown by event handlers are reported // as uncaught exceptions; the event handlers run on a nested // callstack: they block the caller until they complete, but // exceptions do not propagate to the caller. // eslint-disable-next-line promise/prefer-await-to-callbacks, callback-return cb(); } catch (err) { this.triggerErrorEvent(err, evt); } }, triggerErrorEvent: function triggerErrorEvent(err, evt) { var error = err; if (typeof err === 'string') { error = new Error('Uncaught exception: ' + err); } var triggerGlobalErrorEvent; var useNodeImpl = false; if (typeof window === 'undefined' || typeof ErrorEvent === 'undefined' || window && (typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object' && !window.dispatchEvent) { useNodeImpl = true; triggerGlobalErrorEvent = function triggerGlobalErrorEvent() { setTimeout(function () { // Node won't be able to catch in this way if we throw in the main thread // console.log(err); // Should we auto-log for user? throw error; // Let user listen to `process.on('uncaughtException', (err) => {});` }); }; } else { triggerGlobalErrorEvent = function triggerGlobalErrorEvent() { // See https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror // and https://github.com/w3c/IndexedDB/issues/49 // Note that a regular Event will properly trigger // `window.addEventListener('error')` handlers, but it will not trigger // `window.onerror` as per https://html.spec.whatwg.org/multipage/webappapis.html#handler-onerror // Note also that the following line won't handle `window.addEventListener` handlers // if (window.onerror) window.onerror(error.message, err.fileName, err.lineNumber, error.columnNumber, error); // `ErrorEvent` properly triggers `window.onerror` and `window.addEventListener('error')` handlers var errEv = new ErrorEvent('error', { error: err, message: error.message || '', // We can't get the actually useful user's values! filename: error.fileName || '', lineno: error.lineNumber || 0, colno: error.columnNumber || 0 }); window.dispatchEvent(errEv); // console.log(err); // Should we auto-log for user? }; } // Todo: This really should always run here but as we can't set the global // `window` (e.g., using jsdom) since `setGlobalVars` becomes unable to // shim `indexedDB` in such a case currently (apparently due to // <https://github.com/axemclion/IndexedDBShim/issues/280>), we can't // avoid the above Node implementation (which, while providing some // fallback mechanism, is unstable) if (!useNodeImpl || !this._legacyOutputDidListenersThrowCheck) triggerGlobalErrorEvent(); // See https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke and // https://github.com/w3c/IndexedDB/issues/140 (also https://github.com/w3c/IndexedDB/issues/49 ) if (this._legacyOutputDidListenersThrowCheck) { evt.__legacyOutputDidListenersThrowError = error; } } }); EventTarget.prototype[Symbol.toStringTag] = 'EventTargetPrototype'; Object.defineProperty(EventTarget, 'prototype', { writable: false }); var ShimEventTarget = EventTarget; var EventTargetFactory = { createInstance: function createInstance(customOptions) { /* eslint-disable no-shadow */ /** * @class */ function EventTarget() { /* eslint-enable no-shadow */ this.__setOptions(customOptions); } EventTarget.prototype = ShimEventTarget.prototype; return new EventTarget(); } }; EventTarget.ShimEvent = ShimEvent; EventTarget.ShimCustomEvent = ShimCustomEvent; EventTarget.ShimDOMException = ShimDOMException; EventTarget.ShimEventTarget = EventTarget; EventTarget.EventTargetFactory = EventTargetFactory; /** * @returns {void} */ function setPrototypeOfCustomEvent() { // TODO: IDL needs but reported as slow! Object.setPrototypeOf(ShimCustomEvent, ShimEvent); Object.setPrototypeOf(ShimCustomEvent.prototype, ShimEvent.prototype); } // Todo: Move to own library (but allowing WeakMaps to be passed in for sharing here) const map = {}; const CFG = {}; [// Boolean for verbose reporting 'DEBUG', // Effectively defaults to false (ignored unless `true`) // Boolean (effectively defaults to true) on whether to cache WebSQL // `openDatabase` instances 'cacheDatabaseInstances', // Boolean on whether to auto-name databases (based on an // auto-increment) when the empty string is supplied; useful with // `memoryDatabase`; defaults to `false` which means the empty string // will be used as the (valid) database name 'autoName', // Determines whether the slow-performing `Object.setPrototypeOf` // calls required for full WebIDL compliance will be used. Probably // only needed for testing or environments where full introspection // on class relationships is required; see // http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements 'fullIDLSupport', // Effectively defaults to false (ignored unless `true`) // Boolean on whether to perform origin checks in `IDBFactory` methods // Effectively defaults to `true` (must be set to `false` to cancel checks) 'checkOrigin', // Used by `IDBCursor` continue methods for number of records to cache; // Defaults to 100 'cursorPreloadPackSize', // See optional API (`shimIndexedDB.__setUnicodeIdentifiers`); // or just use the Unicode builds which invoke this method // automatically using the large, fully spec-compliant, regular // expression strings of `src/UnicodeIdentifiers.js`) // In the non-Unicode builds, defaults to /[$A-Z_a-z]/ 'UnicodeIDStart', // In the non-Unicode builds, defaults to /[$0-9A-Z_a-z]/ 'UnicodeIDContinue', // Used by SCA.js for optional restructuring of typeson-registry // Structured Cloning Algorithm; should only be needed for ensuring data // created in 3.* versions of IndexedDBShim continue to work; see the // library `typeson-registry-sca-reverter` to get a function to do this 'registerSCA', // BROWSER-SPECIFIC CONFIG 'avoidAutoShim', // Where WebSQL is detected but where `indexedDB` is // missing or poor support is known (non-Chrome Android or // non-Safari iOS9), the shim will be auto-applied without // `shimIndexedDB.__useShim()`. Set this to `true` to avoid forcing // the shim for such cases. // -----------SQL CONFIG---------- // Object (`window` in the browser) on which there may be an // `openDatabase` method (if any) for WebSQL. (The browser // throws if attempting to call `openDatabase` without the window // so this is why the config doesn't just allow the function.) // Defaults to `window` or `self` in browser builds or // a singleton object with the `openDatabase` method set to // the "websql" package in Node. 'win', // For internal `openDatabase` calls made by `IDBFactory` methods; // per the WebSQL spec, "User agents are expected to use the display name // and the estimated database size to optimize the user experience. // For example, a user agent could use the estimated size to suggest an // initial quota to the user. This allows a site that is aware that it // will try to use hundreds of megabytes to declare this upfront, instead // of the user agent prompting the user for permission to increase the // quota every five megabytes." // Defaults to (4 * 1024 * 1024) or (25 * 1024 * 1024) in Safari 'DEFAULT_DB_SIZE', // Whether to create indexes on SQLite tables (and also whether to try // dropping) // Effectively defaults to `false` (ignored unless `true`) 'useSQLiteIndexes', // NODE-IMPINGING SETTINGS (created for sake of limitations in Node // or desktop file system implementation but applied by default in // browser for parity) // Used when setting global shims to determine whether to try to add // other globals shimmed by the library (`ShimDOMException`, // `ShimDOMStringList`, `ShimEvent`, `ShimCustomEvent`, `ShimEventTarget`) // Effectively defaults to `false` (ignored unless `true`) 'addNonIDBGlobals', // Used when setting global shims to determine whether to try to overwrite // other globals shimmed by the library (`DOMException`, `DOMStringList`, // `Event`, `CustomEvent`, `EventTarget`) // Effectively defaults to `false` (ignored unless `true`) 'replaceNonIDBGlobals', // Overcoming limitations with node-sqlite3/storing database name on // file systems // https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words // Defaults to prefixing database with `D_`, escaping // `databaseCharacterEscapeList`, escaping NUL, and // escaping upper case letters, as well as enforcing // `databaseNameLengthLimit` 'escapeDatabaseName', // Not used internally; usable as a convenience method 'unescapeDatabaseName', // Defaults to global regex representing the following // (characters nevertheless commonly reserved in modern, // Unicode-supporting systems): 0x00-0x1F 0x7F " * / : < > ? \ | 'databaseCharacterEscapeList', // Defaults to 254 (shortest typical modern file length limit) 'databaseNameLengthLimit', // Boolean defaulting to true on whether to escape NFD-escaping // characters to avoid clashes on MacOS which performs NFD on files 'escapeNFDForDatabaseNames', // Boolean on whether to add the `.sqlite` extension to file names; // defaults to `true` 'addSQLiteExtension', // Various types of in-memory databases that can auto-delete ['memoryDatabase', val => { if (!/^(?::memory:|file::memory:(\?[^#]*)?(#.*)?)?$/u.test(val)) { throw new TypeError('`memoryDatabase` must be the empty string, ":memory:", or a ' + '"file::memory:[?queryString][#hash] URL".'); } }], // NODE-SPECIFIC CONFIG // Boolean on whether to delete the database file itself after // `deleteDatabase`; defaults to `true` as the database will be empty 'deleteDatabaseFiles', 'databaseBasePath', 'sysDatabaseBasePath', // NODE-SPECIFIC WEBSQL CONFIG 'sqlBusyTimeout', // Defaults to 1000 'sqlTrace', // Callback not used by default 'sqlProfile' // Callback not used by default ].forEach(prop => { let validator; if (Array.isArray(prop)) { [prop, validator] = prop; } Object.defineProperty(CFG, prop, { get() { return map[prop]; }, set(val) { if (validator) { validator(val); } map[prop] = val; } }); }); var unicodeRegex = /[\xC0-\xC5\xC7-\xCF\xD1-\xD6\xD9-\xDD\xE0-\xE5\xE7-\xEF\xF1-\xF6\xF9-\xFD\xFF-\u010F\u0112-\u0125\u0128-\u0130\u0134-\u0137\u0139-\u013E\u0143-\u0148\u014C-\u0151\u0154-\u0165\u0168-\u017E\u01A0\u01A1\u01AF\u01B0\u01CD-\u01DC\u01DE-\u01E3\u01E6-\u01F0\u01F4\u01F5\u01F8-\u021B\u021E\u021F\u0226-\u0233\u0344\u0385\u0386\u0388-\u038A\u038C\u038E-\u0390\u03AA-\u03B0\u03CA-\u03CE\u03D3\u03D4\u0400\u0401\u0403\u0407\u040C-\u040E\u0419\u0439\u0450\u0451\u0453\u0457\u045C-\u045E\u0476\u0477\u04C1\u04C2\u04D0-\u04D3\u04D6\u04D7\u04DA-\u04DF\u04E2-\u04E7\u04EA-\u04F5\u04F8\u04F9\u0622-\u0626\u06C0\u06C2\u06D3\u0929\u0931\u0934\u0958-\u095F\u09CB\u09CC\u09DC\u09DD\u09DF\u0A33\u0A36\u0A59-\u0A5B\u0A5E\u0B48\u0B4B\u0B4C\u0B5C\u0B5D\u0B94\u0BCA-\u0BCC\u0C48\u0CC0\u0CC7\u0CC8\u0CCA\u0CCB\u0D4A-\u0D4C\u0DDA\u0DDC-\u0DDE\u0F43\u0F4D\u0F52\u0F57\u0F5C\u0F69\u0F73\u0F75\u0F76\u0F78\u0F81\u0F93\u0F9D\u0FA2\u0FA7\u0FAC\u0FB9\u1026\u1B06\u1B08\u1B0A\u1B0C\u1B0E\u1B12\u1B3B\u1B3D\u1B40\u1B41\u1B43\u1E00-\u1E99\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FC1-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEE\u1FF2-\u1FF4\u1FF6-\u1FFC\u212B\u219A\u219B\u21AE\u21CD-\u21CF\u2204\u2209\u220C\u2224\u2226\u2241\u2244\u2247\u2249\u2260\u2262\u226D-\u2271\u2274\u2275\u2278\u2279\u2280\u2281\u2284\u2285\u2288\u2289\u22AC-\u22AF\u22E0-\u22E3\u22EA-\u22ED\u2ADC\u304C\u304E\u3050\u3052\u3054\u3056\u3058\u305A\u305C\u305E\u3060\u3062\u3065\u3067\u3069\u3070\u3071\u3073\u3074\u3076\u3077\u3079\u307A\u307C\u307D\u3094\u309E\u30AC\u30AE\u30B0\u30B2\u30B4\u30B6\u30B8\u30BA\u30BC\u30BE\u30C0\u30C2\u30C5\u30C7\u30C9\u30D0\u30D1\u30D3\u30D4\u30D6\u30D7\u30D9\u30DA\u30DC\u30DD\u30F4\u30F7-\u30FA\u30FE\uAC00-\uD7A3\uFB1D\uFB1F\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFB4E]|\uD804[\uDC9A\uDC9C\uDCAB\uDD2E\uDD2F\uDF4B\uDF4C]|\uD805[\uDCBB\uDCBC\uDCBE\uDDBA\uDDBB]|\uD834[\uDD5E-\uDD64\uDDBB-\uDDC0]/; function escapeUnmatchedSurrogates(arg) { // http://stackoverflow.com/a/6701665/271577 return arg.replace(/([\uD800-\uDBFF])(?![\uDC00-\uDFFF])|(^|[^\uD800-\uDBFF])([\uDC00-\uDFFF])/gu, function (_, unmatchedHighSurrogate, precedingLow, unmatchedLowSurrogate) { // Could add a corresponding surrogate for compatibility with `node-sqlite3`: http://bugs.python.org/issue12569 and http://stackoverflow.com/a/6701665/271577 // but Chrome having problems if (unmatchedHighSurrogate) { return '^2' + padStart(unmatchedHighSurrogate.charCodeAt().toString(16), 4, '0'); } return (precedingLow || '') + '^3' + padStart(unmatchedLowSurrogate.charCodeAt().toString(16), 4, '0'); }); } function escapeNameForSQLiteIdentifier(arg) { // http://stackoverflow.com/a/6701665/271577 return '_' + // Prevent empty string escapeUnmatchedSurrogates(arg.replace(/\^/gu, '^^') // Escape our escape // http://www.sqlite.org/src/tktview?name=57c971fc74 .replace(/\0/gu, '^0') // We need to avoid identifiers being treated as duplicates based on SQLite's ASCII-only case-insensitive table and column names // (For SQL in general, however, see http://stackoverflow.com/a/17215009/271577 // See also https://www.sqlite.org/faq.html#q18 re: Unicode (non-ASCII) case-insensitive not working .replace(/([A-Z])/gu, '^$1')); } // The escaping of unmatched surrogates was needed by Chrome but not Node function escapeSQLiteStatement(arg) { return escapeUnmatchedSurrogates(arg.replace(/\^/gu, '^^').replace(/\0/gu, '^0')); } function unescapeSQLiteResponse(arg) { return unescapeUnmatchedSurrogates(arg).replace(/(\^+)0/gu, (_, esc) => { return esc.length % 2 ? esc.slice(1) + '\0' : _; }).replace(/\^\^/gu, '^'); } function sqlEscape(arg) { // https://www.sqlite.org/lang_keywords.html // http://stackoverflow.com/a/6701665/271577 // There is no need to escape ', `, or [], as // we should always be within double quotes // NUL should have already been stripped return arg.replace(/"/gu, '""'); } function sqlQuote(arg) { return '"' + sqlEscape(arg) + '"'; } function escapeDatabaseNameForSQLAndFiles(db) { if (CFG.escapeDatabaseName) { // We at least ensure NUL is escaped by default, but we need to still // handle empty string and possibly also length (potentially // throwing if too long), escaping casing (including Unicode?), // and escaping special characters depending on file system return CFG.escapeDatabaseName(escapeSQLiteStatement(db)); } db = 'D' + escapeNameForSQLiteIdentifier(db); if (CFG.escapeNFDForDatabaseNames !== false) { // ES6 copying of regex with different flags // Todo: Remove `.source` when // https://github.com/babel/babel/issues/5978 completed (see also // https://github.com/axemclion/IndexedDBShim/issues/311#issuecomment-316090147 ) db = db.replace(new RegExp(unicodeRegex.source, 'gu'), function (expandable) { return '^4' + padStart(expandable.codePointAt().toString(16), 6, '0'); }); } if (CFG.databaseCharacterEscapeList !== false) { db = db.replace(CFG.databaseCharacterEscapeList ? new RegExp(CFG.databaseCharacterEscapeList, 'gu') : /[\u0000-\u001F\u007F"*/:<>?\\|]/gu, // eslint-disable-line no-control-regex function (n0) { return '^1' + padStart(n0.charCodeAt().toString(16), 2, '0'); }); } if (CFG.databaseNameLengthLimit !== false && db.length >= (CFG.databaseNameLengthLimit || 254) - (CFG.addSQLiteExtension !== false ? 7 /* '.sqlite'.length */ : 0)) { throw new Error('Unexpectedly long database name supplied; length limit required for Node compatibility; passed length: ' + db.length + '; length limit setting: ' + (CFG.databaseNameLengthLimit || 254) + '.'); } return db + (CFG.addSQLiteExtension !== false ? '.sqlite' : ''); // Shouldn't have quoting (do we even need NUL/case escaping here?) } function unescapeUnmatchedSurrogates(arg) { return arg.replace(/(\^+)3(d[0-9a-f]{3})/gu, (_, esc, lowSurr) => { return esc.length % 2 ? esc.slice(1) + String.fromCharCode(parseInt(lowSurr, 16)) : _; }).replace(/(\^+)2(d[0-9a-f]{3})/gu, (_, esc, highSurr) => { return esc.length % 2 ? esc.slice(1) + String.fromCharCode(parseInt(highSurr, 16)) : _; }); } // Not in use internally but supplied for convenience function escapeStoreNameForSQL(store) { return sqlQuote('S' + escapeNameForSQLiteIdentifier(store)); } function escapeIndexNameForSQL(index) { return sqlQuote('I' + escapeNameForSQLiteIdentifier(index)); } function escapeIndexNameForSQLKeyColumn(index) { return 'I' + escapeNameForSQLiteIdentifier(index); } function sqlLIKEEscape(str) { // https://www.sqlite.org/lang_expr.html#like return sqlEscape(str).replace(/\^/gu, '^^'); } // Babel doesn't seem to provide a means of using the `instanceof` operator with Symbol.hasInstance (yet?) function instanceOf(obj, Clss) { return Clss[Symbol.hasInstance](obj); } function isObj(obj) { return obj && typeof obj === 'object'; } function isDate(obj) { return isObj(obj) && typeof obj.getDate === 'function'; } function isBlob(obj) { return isObj(obj) && typeof obj.size === 'number' && typeof obj.slice === 'function' && !('lastModified' in obj); } function isFile(obj) { return isObj(obj) && typeof obj.name === 'string' && typeof obj.slice === 'function' && 'lastModified' in obj; } function isBinary(obj) { return isObj(obj) && typeof obj.byteLength === 'number' && (typeof obj.slice === 'function' || // `TypedArray` (view on buffer) or `ArrayBuffer` typeof obj.getFloat64 === 'function' // `DataView` (view on buffer) ); } function isIterable(obj) { return isObj(obj) && typeof obj[Symbol.iterator] === 'function'; } function defineOuterInterface(obj, props) { props.forEach(prop => { const o = { get [prop]() { throw new TypeError('Illegal invocation'); }, set [prop](val) { throw new TypeError('Illegal invocation'); } }; const desc = Object.getOwnPropertyDescriptor(o, prop); Object.defineProperty(obj, prop, desc); }); } function defineReadonlyOuterInterface(obj, props) { props.forEach(prop => { const o = { get [prop]() { throw new TypeError('Illegal invocation'); } }; const desc = Object.getOwnPropertyDescriptor(o, prop); Object.defineProperty(obj, prop, desc); }); } function defineListenerProperties(obj, listeners) { listeners = typeof listeners === 'string' ? [listeners] : listeners; listeners.forEach(listener => { const o = { get [listener]() { return obj['__' + listener]; }, set [listener](val) { obj['__' + listener] = val; } }; const desc = Object.getOwnPropertyDescriptor(o, listener); // desc.enumerable = true; // Default // desc.configurable = true; // Default // Needed by support.js in W3C IndexedDB tests (for openListeners) Object.defineProperty(obj, listener, desc); }); listeners.forEach(l => { obj[l] = null; }); } function defineReadonlyProperties(obj, props, getter = null) { props = typeof props === 'string' ? [props] : props; props.forEach(function (prop) { let o; if (getter && prop in getter) { o = getter[prop]; } else { Object.defineProperty(obj, '__' + prop, { enumerable: false, configurable: false, writable: true }); // We must resort to this to get "get <name>" as // the function `name` for proper IDL o = { get [prop]() { return this['__' + prop]; } }; } const desc = Object.getOwnPropertyDescriptor(o, prop); // desc.enumerable = true; // Default // desc.configurable = true; // Default Object.defineProperty(obj, prop, desc); }); } function isIdentifier(item) { // For load-time and run-time performance, we don't provide the complete regular // expression for identifiers, but these can be passed in, using the expressions // found at https://gist.github.com/brettz9/b4cd6821d990daa023b2e604de371407 // ID_Start (includes Other_ID_Start) const UnicodeIDStart = CFG.UnicodeIDStart || '[$A-Z_a-z]'; // ID_Continue (includes Other_ID_Continue) const UnicodeIDContinue = CFG.UnicodeIDContinue || '[$0-9A-Z_a-z]'; const IdentifierStart = '(?:' + UnicodeIDStart + '|[$_])'; const IdentifierPart = '(?:' + UnicodeIDContinue + '|[$_\u200C\u200D])'; return new RegExp('^' + IdentifierStart + IdentifierPart + '*$', 'u').test(item); } function isValidKeyPathString(keyPathString) { return typeof keyPathString === 'string' && (keyPathString === '' || isIdentifier(keyPathString) || keyPathString.split('.').every(pathComponent => { return isIdentifier(pathComponent); })); } function isValidKeyPath(keyPath) { return isValidKeyPathString(keyPath) || Array.isArray(keyPath) && keyPath.length && // Convert array from sparse to dense http://www.2ality.com/2012/06/dense-arrays.html // See also https://heycam.github.io/webidl/#idl-DOMString [...keyPath].every(pathComponent => { return isValidKeyPathString(pathComponent); }); } function enforceRange(number, type) { number = Math.floor(Number(number)); let max, min; switch (type) { case 'unsigned long long': { max = 0x1FFFFFFFFFFFFF; // 2^53 - 1 min = 0; break; } case 'unsigned long': { max = 0xFFFFFFFF; // 2^32 - 1 min = 0; break; } default: throw new Error('Unrecognized type supplied to enforceRange'); } if (isNaN(number) || !isFinite(number) || number > max || number < min) { throw new TypeError('Invalid range: ' + number); } return number; } function convertToDOMString(v, treatNullAs) { return v === null && treatNullAs ? '' : ToString(v); } function ToString(o) { // Todo: See `es-abstract/es7` // `String()` will not throw with Symbols return '' + o; // eslint-disable-line no-implicit-coercion } function convertToSequenceDOMString(val) { // Per <https://heycam.github.io/webidl/#idl-sequence>, converting to a sequence works with iterables if (isIterable(val)) { // We don't want conversion to array to convert primitives // Per <https://heycam.github.io/webidl/#es-DOMString>, converting to a `DOMString` to be via `ToString`: https://tc39.github.io/ecma262/#sec-tostring return [...val].map(item => { return ToString(item); }); } return ToString(val); } function isNullish(v) { return v === null || v === undefined; } function hasOwn(obj, prop) { return {}.hasOwnProperty.call(obj, prop); } // Todo: Replace with `String.prototype.padStart` when targeting supporting Node version function padStart(str, ct, fill) { return new Array(ct - String(str).length + 1).join(fill) + str; } /** * * @param {string} type * @param {Any} debug * @param {EventInit} evInit * @returns {Event} */ function createEvent(type, debug, evInit) { const ev = new ShimEvent(type, evInit); ev.debug = debug; return ev; } // We don't add within polyfill repo as might not always be the desired implementation Object.defineProperty(ShimEvent, Symbol.hasInstance, { value: obj => isObj(obj) && 'target' in obj && typeof obj.bubbles === 'boolean' }); const readonlyProperties = ['oldVersion', 'newVersion']; // Babel apparently having a problem adding `hasInstance` to a class, so we are redefining as a function function IDBVersionChangeEvent(type /* , eventInitDict */ ) { // eventInitDict is a IDBVersionChangeEventInit (but is not defined as a global) ShimEvent.call(this, type); this[Symbol.toStringTag] = 'IDBVersionChangeEvent'; this.toString = function () { return '[object IDBVersionChangeEvent]'; }; // eslint-disable-next-line prefer-rest-params this.__eventInitDict = arguments[1] || {}; } IDBVersionChangeEvent.prototype = Object.create(ShimEvent.prototype); IDBVersionChangeEvent.prototype[Symbol.toStringTag] = 'IDBVersionChangeEventPrototype'; readonlyProperties.forEach(prop => { // Ensure for proper interface testing that "get <name>" is the function name const o = { get [prop]() { if (!(this instanceof IDBVersionChangeEvent)) { throw new TypeError('Illegal invocation'); } return this.__eventInitDict && this.__eventInitDict[prop] || (prop === 'oldVersion' ? 0 : null); } }; const desc = Object.getOwnPropertyDescriptor(o, prop); // desc.enumerable = true; // Default // desc.configurable = true; // Default Object.defineProperty(IDBVersionChangeEvent.prototype, prop, desc); }); Object.defineProperty(IDBVersionChangeEvent, Symbol.hasInstance, { value: obj => isObj(obj) && 'oldVersion' in obj && typeof obj.defaultPrevented === 'boolean' }); Object.defineProperty(IDBVersionChangeEvent.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBVersionChangeEvent }); Object.defineProperty(IDBVersionChangeEvent, 'prototype', { writable: false }); /* globals DOMException */ /** * Creates a native DOMException, for browsers that support it. * @param {string} name * @param {string} message * @returns {DOMException} */ function createNativeDOMException(name, message) { return new DOMException.prototype.constructor(message, name || 'DOMException'); } // From web-platform-tests testharness.js name_code_map (though not in new spec) const codes = { IndexSizeError: 1, HierarchyRequestError: 3, WrongDocumentError: 4, InvalidCharacterError: 5, NoModificationAllowedError: 7, NotFoundError: 8, NotSupportedError: 9, InUseAttributeError: 10, InvalidStateError: 11, SyntaxError: 12, InvalidModificationError: 13, NamespaceError: 14, InvalidAccessError: 15, TypeMismatchError: 17, SecurityError: 18, NetworkError: 19, AbortError: 20, URLMismatchError: 21, QuotaExceededError: 22, TimeoutError: 23, InvalidNodeTypeError: 24, DataCloneError: 25, EncodingError: 0, NotReadableError: 0, UnknownError: 0, ConstraintError: 0, DataError: 0, TransactionInactiveError: 0, ReadOnlyError: 0, VersionError: 0, OperationError: 0, NotAllowedError: 0 }; const legacyCodes = { INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, NO_DATA_ALLOWED_ERR: 6, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INUSE_ATTRIBUTE_ERR: 10, INVALID_STATE_ERR: 11, SYNTAX_ERR: 12, INVALID_MODIFICATION_ERR: 13, NAMESPACE_ERR: 14, INVALID_ACCESS_ERR: 15, VALIDATION_ERR: 16, TYPE_MISMATCH_ERR: 17, SECURITY_ERR: 18, NETWORK_ERR: 19, ABORT_ERR: 20, URL_MISMATCH_ERR: 21, QUOTA_EXCEEDED_ERR: 22, TIMEOUT_ERR: 23, INVALID_NODE_TYPE_ERR: 24, DATA_CLONE_ERR: 25 }; /** * * @returns {DOMException} */ function createNonNativeDOMExceptionClass() { function DOMException(message, name) { // const err = Error.prototype.constructor.call(this, message); // Any use to this? Won't set this.message this[Symbol.toStringTag] = 'DOMException'; this._code = name in codes ? codes[name] : legacyCodes[name] || 0; this._name = name || 'Error'; // We avoid `String()` in this next line as it converts Symbols this._message = message === undefined ? '' : '' + message; // eslint-disable-line no-implicit-coercion Object.defineProperty(this, 'code', { configurable: true, enumerable: true, writable: true, value: this._code }); if (name !== undefined) { Object.defineProperty(this, 'name', { configurable: true, enumerable: true, writable: true, value: this._name }); } if (message !== undefined) { Object.defineProperty(this, 'message', { configurable: true, enumerable: false, writable: true, value: this._message }); } } // Necessary for W3C tests which complains if `DOMException` has properties on its "own" prototype // class DummyDOMException extends Error {}; // Sometimes causing problems in Node // eslint-disable-next-line func-name-matching const DummyDOMException = function DOMException() { /* */ }; DummyDOMException.prototype = Object.create(Error.prototype); // Intended for subclassing ['name', 'message'].forEach(prop => { Object.defineProperty(DummyDOMException.prototype, prop, { enumerable: true, get() { if (!(this instanceof DOMException || this instanceof DummyDOMException || this instanceof Error)) { throw new TypeError('Illegal invocation'); } return this['_' + prop]; } }); }); // DOMException uses the same `toString` as `Error` Object.defineProperty(DummyDOMException.prototype, 'code', { configurable: true, enumerable: true, get() { throw new TypeError('Illegal invocation'); } }); DOMException.prototype = new DummyDOMException(); DOMException.prototype[Symbol.toStringTag] = 'DOMExceptionPrototype'; Object.defineProperty(DOMException, 'prototype', { writable: false }); Object.keys(codes).forEach(codeName => { Object.defineProperty(DOMException.prototype, codeName, { enumerable: true, configurable: false, value: codes[codeName] }); Object.defineProperty(DOMException, codeName, { enumerable: true, configurable: false, value: codes[codeName] }); }); Object.keys(legacyCodes).forEach(codeName => { Object.defineProperty(DOMException.prototype, codeName, { enumerable: true, configurable: false, value: legacyCodes[codeName] }); Object.defineProperty(DOMException, codeName, { enumerable: true, configurable: false, value: legacyCodes[codeName] }); }); Object.defineProperty(DOMException.prototype, 'constructor', { writable: true, configurable: true, enumerable: false, value: DOMException }); return DOMException; } const ShimNonNativeDOMException = createNonNativeDOMExceptionClass(); /** * Creates a generic Error object. * @param {string} name * @param {string} message * @returns {Error} */ function createNonNativeDOMException(name, message) { return new ShimNonNativeDOMException(message, name); } /** * Logs detailed error information to the console. * @param {string} name * @param {string} message * @param {string|Error|null} error * @returns {void} */ function logError(name, message, error) { if (CFG.DEBUG) { if (error && error.message) { error = error.message; } const method = typeof console.error === 'function' ? 'error' : 'log'; console[method](name + ': ' + message + '. ' + (error || '')); console.trace && console.trace(); } } function isErrorOrDOMErrorOrDOMException(obj) { return obj && typeof obj === 'object' && // We don't use util.isObj here as mutual dependency causing problems in Babel with browser typeof obj.name === 'string'; } /** * Finds the error argument. This is useful because some WebSQL callbacks * pass the error as the first argument, and some pass it as the second * argument. * @param {Array} args * @returns {Error|DOMException|undefined} */ function findError(args) { let err; if (args) { if (args.length === 1) { return args[0]; } for (const arg of args) { if (isErrorOrDOMErrorOrDOMException(arg)) { return arg; } if (arg && typeof arg.message === 'string') { err = arg; } } } return err; } /** * * @param {external:WebSQLError} webSQLErr * @returns {DOMException} */ function webSQLErrback(webSQLErr) { let name, message; switch (webSQLErr.code) { case 4: { // SQLError.QUOTA_ERR name = 'QuotaExceededError'; message = 'The operation failed because there was not enough ' + 'remaining storage space, or the storage quota was reached ' + 'and the user declined to give more space to the database.'; break; } /* // Should a WebSQL timeout treat as IndexedDB `TransactionInactiveError` or `UnknownError`? case 7: { // SQLError.TIMEOUT_ERR // All transaction errors abort later, so no need to mark inactive name = 'TransactionInactiveError'; message = 'A request was placed against a transaction which is currently not active, or which is finished (Internal SQL Timeout).'; break; } */ default: { name = 'UnknownError'; message = 'The operation failed for reasons unrelated to the database itself and not covered by any other errors.'; break; } } message += ' (' + webSQLErr.message + ')--(' + webSQLErr.code + ')'; const err = createDOMException(name, message); err.sqlError = webSQLErr; return err; } let test, useNativeDOMException = false; // Test whether we can use the browser's native DOMException class try { test = createNativeDOMException('test name', 'test message'); if (isErrorOrDOMErrorOrDOMException(test) && test.name === 'test name' && test.message === 'test message') { // Native DOMException works as expected useNativeDOMException = true; } } catch (e) {} const createDOMException = useNativeDOMException ? function (name, message, error) { logError(name, message, error); return createNativeDOMException(name, message); } : function (name, message, error) { logError(name, message, error); return createNonNativeDOMException(name, message); }; const ShimDOMException$1 = useNativeDOMException ? DOMException : ShimNonNativeDOMException; const listeners = ['onsuccess', 'onerror']; const readonlyProperties$1 = ['source', 'transaction', 'readyState']; const doneFlagGetters = ['result', 'error']; /** * The IDBRequest Object that is returns for all async calls. * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#request-api * @class */ function IDBRequest() { throw new TypeError('Illegal constructor'); } // eslint-disable-next-line func-name-matching IDBRequest.__super = function IDBRequest() { this[Symbol.toStringTag] = 'IDBRequest'; this.__setOptions({ legacyOutputDidListenersThrowFlag: true // Event hook for IndexedB }); doneFlagGetters.forEach(function (prop) { Object.defineProperty(this, '__' + prop, { enumerable: false, configurable: false, writable: true }); Object.defineProperty(this, prop, { enumerable: true, configurable: true, get() { if (!this.__done) { throw createDOMException('InvalidStateError', "Can't get " + prop + '; the request is still pending.'); } return this['__' + prop]; } }); }, this); defineReadonlyProperties(this, readonlyProperties$1, { readyState: { get readyState() { return this.__done ? 'done' : 'pending'; } } }); defineListenerProperties(this, listeners); this.__result = undefined; this.__error = this.__source = this.__transaction = null; this.__done = false; }; IDBRequest.__createInstance = function () { return new IDBRequest.__super(); }; IDBRequest.prototype = EventTargetFactory.createInstance({ extraProperties: ['debug'] }); IDBRequest.prototype[Symbol.toStringTag] = 'IDBRequestPrototype'; IDBRequest.prototype.__getParent = function () { if (this.toString() === '[object IDBOpenDBRequest]') { return null; } return this.__transaction; }; // Illegal invocations defineReadonlyOuterInterface(IDBRequest.prototype, readonlyProperties$1); defineReadonlyOuterInterface(IDBRequest.prototype, doneFlagGetters); defineOuterInterface(IDBRequest.prototype, listeners); Object.defineProperty(IDBRequest.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBRequest }); IDBRequest.__super.prototype = IDBRequest.prototype; Object.defineProperty(IDBRequest, 'prototype', { writable: false }); const openListeners = ['onblocked', 'onupgradeneeded']; /** * The IDBOpenDBRequest called when a database is opened. * @class */ function IDBOpenDBRequest() { throw new TypeError('Illegal constructor'); } IDBOpenDBRequest.prototype = Object.create(IDBRequest.prototype); Object.defineProperty(IDBOpenDBRequest.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBOpenDBRequest }); const IDBOpenDBRequestAlias = IDBOpenDBRequest; IDBOpenDBRequest.__createInstance = function () { function IDBOpenDBRequest() { IDBRequest.__super.call(this); this[Symbol.toStringTag] = 'IDBOpenDBRequest'; this.__setOptions({ legacyOutputDidListenersThrowFlag: true, // Event hook for IndexedB extraProperties: ['oldVersion', 'newVersion', 'debug'] }); // Ensure EventTarget preserves our properties defineListenerProperties(this, openListeners); } IDBOpenDBRequest.prototype = IDBOpenDBRequestAlias.prototype; return new IDBOpenDBRequest(); }; defineOuterInterface(IDBOpenDBRequest.prototype, openListeners); IDBOpenDBRequest.prototype[Symbol.toStringTag] = 'IDBOpenDBRequestPrototype'; Object.defineProperty(IDBOpenDBRequest, 'prototype', { writable: false }); // Since [immediate](https://github.com/calvinmetcalf/immediate) is // not doing the trick for our WebSQL transactions (at least in Node), // we are forced to make the promises run fully synchronously. function isPromise(p) { return p && typeof p.then === 'function'; } function addReject(prom, reject) { prom.then(null, reject); // Use this style for sake of non-Promise thenables (e.g., jQuery Deferred) } // States var PENDING = 2, FULFILLED = 0, // We later abuse these as array indices REJECTED = 1; function SyncPromise(fn) { var self = this; self.v = 0; // Value, this will be set to either a resolved value or rejected reason self.s = PENDING; // State of the promise self.c = [[], []]; // Callbacks c[0] is fulfillment and c[1] contains rejection callbacks function transist(val, state) { self.v = val; self.s = state; self.c[state].forEach(function (fn) { fn(val); }); // Release memory, but if no handlers have been added, as we // assume that we will resolve/reject (truly) synchronously // and thus we avoid flagging checks about whether we've // already resolved/rejected. if (self.c[state].length) self.c = null; } function resolve(val) { if (!self.c) ; else if (isPromise(val)) { addReject(val.then(resolve), reject); } else { transist(val, FULFILLED); } } function reject(reason) { if (!self.c) ; else if (isPromise(reason)) { addReject(reason.then(reject), reject); } else { transist(reason, REJECTED); } } try { fn(resolve, reject); } catch (err) { reject(err); } } var prot = SyncPromise.prototype; prot.then = function (cb, errBack) { var self = this; return new SyncPromise(function (resolve, reject) { var rej = typeof errBack === 'function' ? errBack : reject; function settle() { try { resolve(cb ? cb(self.v) : self.v); } catch (e) { rej(e); } } if (self.s === FULFILLED) { settle(); } else if (self.s === REJECTED) { rej(self.v); } else { self.c[FULFILLED].push(settle); self.c[REJECTED].push(rej); } }); }; prot.catch = function (cb) { var self = this; return new SyncPromise(function (resolve, reject) { function settle() { try { resolve(cb(self.v)); } catch (e) { reject(e); } } if (self.s === REJECTED) { settle(); } else if (self.s === FULFILLED) { resolve(self.v); } else { self.c[REJECTED].push(settle); self.c[FULFILLED].push(resolve); } }); }; SyncPromise.all = function (promises) { return new SyncPromise(function (resolve, reject, l) { l = promises.length; var newPromises = []; if (!l) { resolve(newPromises); return; } promises.forEach(function (p, i) { if (isPromise(p)) { addReject(p.then(function (res) { newPromises[i] = res; --l || resolve(newPromises); }), reject); } else { newPromises[i] = p; --l || resolve(promises); } }); }); }; SyncPromise.race = function (promises) { var resolved = false; return new SyncPromise(function (resolve, reject) { promises.some(function (p, i) { if (isPromise(p)) { addReject(p.then(function (res) { if (resolved) { return; } resolve(res); resolved = true; }), reject); } else { resolve(p); resolved = true; return true; } }); }); }; SyncPromise.resolve = function (val) { return new SyncPromise(function (resolve, reject) { resolve(val); }); }; SyncPromise.reject = function (val) { return new SyncPromise(function (resolve, reject) { reject(val); }); }; var syncPromiseCommonjs = SyncPromise; /** * Compares two keys. * @param first * @param second * @returns {number} */ function cmp(first, second) { const encodedKey1 = encode(first); const encodedKey2 = encode(second); const result = encodedKey1 > encodedKey2 ? 1 : encodedKey1 === encodedKey2 ? 0 : -1; if (CFG.DEBUG) { // verify that the keys encoded correctly let decodedKey1 = decode(encodedKey1); let decodedKey2 = decode(encodedKey2); if (typeof first === 'object') { first = JSON.stringify(first); decodedKey1 = JSON.stringify(decodedKey1); } if (typeof second === 'object') { second = JSON.stringify(second); decodedKey2 = JSON.stringify(decodedKey2); } // Encoding/decoding mismatches are usually due to a loss of // floating-point precision if (decodedKey1 !== first) { console.warn(first + ' was incorrectly encoded as ' + decodedKey1); } if (decodedKey2 !== second) { console.warn(second + ' was incorrectly encoded as ' + decodedKey2); } } return result; } /** * @module Key */ /** * Encodes the keys based on their types. This is required to maintain collations * We leave space for future keys. */ const keyTypeToEncodedChar = { invalid: 100, number: 200, date: 300, string: 400, binary: 500, array: 600 }; const keyTypes = Object.keys(keyTypeToEncodedChar); keyTypes.forEach(k => { keyTypeToEncodedChar[k] = String.fromCharCode(keyTypeToEncodedChar[k]); }); const encodedCharToKeyType = keyTypes.reduce((o, k) => { o[keyTypeToEncodedChar[k]] = k; return o; }, {}); /** * The sign values for numbers, ordered from least to greatest. * - "negativeInfinity": Sorts below all other values. * - "bigNegative": Negative values less than or equal to negative one. * - "smallNegative": Negative values between negative one and zero, noninclusive. * - "smallPositive": Positive values between zero and one, including zero but not one. * - "largePositive": Positive values greater than or equal to one. * - "positiveInfinity": Sorts above all other values. */ const signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity']; const types = { invalid: { encode(key) { return keyTypeToEncodedChar.invalid + '-'; }, decode(key) { return undefined; } }, // Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa // notation. // // sign: takes a value between zero and five, inclusive. Represents infinite cases // and the signs of both the exponent and the fractional part of the number. // exponent: padded to two base-32 digits, represented by the 32's compliment in the // "smallPositive" and "bigNegative" cases to ensure proper lexical sorting. // mantissa: also called the fractional part. Normed 11-digit base-32 representation. // Represented by the 32's compliment in the "smallNegative" and "bigNegative" // cases to ensure proper lexical sorting. number: { // The encode step checks for six numeric cases and generates 14-digit encoded // sign-exponent-mantissa strings. encode(key) { let key32 = key === Number.MIN_VALUE // Mocha test `IDBFactory/cmp-spec.js` exposed problem for some // Node (and Chrome) versions with `Number.MIN_VALUE` being treated // as 0 // https://stackoverflow.com/questions/43305403/number-min-value-and-tostring ? '0.' + '0'.repeat(214) + '2' : Math.abs(key).toString(32); // Get the index of the decimal. const decimalIndex = key32.indexOf('.'); // Remove the decimal. key32 = decimalIndex !== -1 ? key32.replace('.', '') : key32; // Get the index of the first significant digit. const significantDigitIndex = key32.search(/[^0]/u); // Truncate leading zeros. key32 = key32.slice(significantDigitIndex); let sign, exponent, mantissa; // Finite cases: if (isFinite(key)) { // Negative cases: if (key < 0) { // Negative exponent case: if (key > -1) { sign = signValues.indexOf('smallNegative'); exponent = padBase32Exponent(significantDigitIndex); mantissa = flipBase32(padBase32Mantissa(key32)); // Non-negative exponent case: } else { sign = signValues.indexOf('bigNegative'); exponent = flipBase32(padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length)); mantissa = flipBase32(padBase32Mantissa(key32)); } // Non-negative cases: // Negative exponent case: } else if (key < 1) { sign = signValues.indexOf('smallPositive'); exponent = flipBase32(padBase32Exponent(significantDigitIndex)); mantissa = padBase32Mantissa(key32); // Non-negative exponent case: } else { sign = signValues.indexOf('bigPositive'); exponent = padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length); mantissa = padBase32Mantissa(key32); } // Infinite cases: } else { exponent = zeros(2); mantissa = zeros(11); sign = signValues.indexOf(key > 0 ? 'positiveInfinity' : 'negativeInfinity'); } return keyTypeToEncodedChar.number + '-' + sign + exponent + mantissa; }, // The decode step must interpret the sign, reflip values encoded as the 32's complements, // apply signs to the exponent and mantissa, do the base-32 power operation, and return // the original JavaScript number values. decode(key) { const sign = Number(key.slice(2, 3)); let exponent = key.slice(3, 5); let mantissa = key.slice(5, 16); switch (signValues[sign]) { case 'negativeInfinity': return -Infinity; case 'positiveInfinity': return Infinity; case 'bigPositive': return pow32(mantissa, exponent); case 'smallPositive': exponent = negate(flipBase32(exponent)); return pow32(mantissa, exponent); case 'smallNegative': exponent = negate(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); case 'bigNegative': exponent = flipBase32(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); default: throw new Error('Invalid number.'); } } }, // Strings are encoded as JSON strings (with quotes and unicode characters escaped). // // If the strings are in an array, then some extra encoding is done to make sorting work correctly: // Since we can't force all strings to be the same length, we need to ensure that characters line-up properly // for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON. // To do this, each character of the string is prepended with a dash ("-"), and a space is added to the end of the string. // This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared, // the indexes of each string's characters line up with each other. string: { encode(key, inArray) { if (inArray) { // prepend each character with a dash, and append a space to the end key = key.replace(/(.)/gu, '-$1') + ' '; } return keyTypeToEncodedChar.string + '-' + key; }, decode(key, inArray) { key = key.slice(2); if (inArray) { // remove the space at the end, and the dash before each character key = key.slice(0, -1).replace(/-(.)/gu, '$1'); } return key; } }, // Arrays are encoded as JSON strings. // An extra, value is added to each array during encoding to make // empty arrays sort correctly. array: { encode(key) { const encoded = []; for (const [i, item] of key.entries()) { const encodedItem = encode(item, true); // encode the array item encoded[i] = encodedItem; } encoded.push(keyTypeToEncodedChar.invalid + '-'); // append an extra item, so empty arrays sort correctly return keyTypeToEncodedChar.array + '-' + JSON.stringify(encoded); }, decode(key) { const decoded = JSON.parse(key.slice(2)); decoded.pop(); // remove the extra item for (let i = 0; i < decoded.length; i++) { const item = decoded[i]; const decodedItem = decode(item, true); // decode the item decoded[i] = decodedItem; } return decoded; } }, // Dates are encoded as ISO 8601 strings, in UTC time zone. date: { encode(key) { return keyTypeToEncodedChar.date + '-' + key.toJSON(); }, decode(key) { return new Date(key.slice(2)); } }, binary: { // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`) encode(key) { return keyTypeToEncodedChar.binary + '-' + (key.byteLength ? [...getCopyBytesHeldByBufferSource(key)].map(b => padStart(b, 3, '0')) // e.g., '255,005,254,000,001,033' : ''); }, decode(key) { // Set the entries in buffer's [[ArrayBufferData]] to those in `value` const k = key.slice(2); const arr = k.length ? k.split(',').map(s => parseInt(s)) : []; const buffer = new ArrayBuffer(arr.length); const uint8 = new Uint8Array(buffer); uint8.set(arr); return buffer; } } }; /** * Return a padded base-32 exponent value. * @param {number} n * @returns {string} */ function padBase32Exponent(n) { n = n.toString(32); return n.length === 1 ? '0' + n : n; } /** * Return a padded base-32 mantissa. * @param {string} s * @returns {string} */ function padBase32Mantissa(s) { return (s + zeros(11)).slice(0, 11); } /** * Flips each digit of a base-32 encoded string. * @param {string} encoded * @returns {string} */ function flipBase32(encoded) { let flipped = ''; for (const ch of encoded) { flipped += (31 - parseInt(ch, 32)).toString(32); } return flipped; } /** * Base-32 power function. * RESEARCH: This function does not precisely decode floats because it performs * floating point arithmetic to recover values. But can the original values be * recovered exactly? * Someone may have already figured out a good way to store JavaScript floats as * binary strings and convert back. Barring a better method, however, one route * may be to generate decimal strings that `parseFloat` decodes predictably. * @param {string} mantissa * @param {string} exponent * @returns {number} */ function pow32(mantissa, exponent) { exponent = parseInt(exponent, 32); if (exponent < 0) { return roundToPrecision(parseInt(mantissa, 32) * Math.pow(32, exponent - 10)); } if (exponent < 11) { let whole = mantissa.slice(0, exponent); whole = parseInt(whole, 32); let fraction = mantissa.slice(exponent); fraction = parseInt(fraction, 32) * Math.pow(32, exponent - 11); return roundToPrecision(whole + fraction); } const expansion = mantissa + zeros(exponent - 11); return parseInt(expansion, 32); } /** * @param {Float} num * @param {Float} precision * @returns {Float} */ function roundToPrecision(num, precision) { precision = precision || 16; return parseFloat(num.toPrecision(precision)); } /** * Returns a string of n zeros. * @param {number} n * @returns {string} */ function zeros(n) { return '0'.repeat(n); } /** * Negates numeric strings. * @param {string} s * @returns {string} */ function negate(s) { return '-' + s; } /** * @typedef {"number"|"date"|"string"|"binary"|"array"} module:Key.KeyType */ /** * @param key * @returns {module:Key.KeyType} */ function getKeyType(key) { if (Array.isArray(key)) return 'array'; if (isDate(key)) return 'date'; if (isBinary(key)) return 'binary'; const keyType = typeof key; return ['string', 'number'].includes(keyType) ? keyType : 'invalid'; } /** * Keys must be strings, numbers (besides `NaN`), Dates (if value is not * `NaN`), binary objects or Arrays. * @param input The key input * @param {?(Array)} [seen] An array of already seen keys * @returns {module:Key.keyValueObject} */ function convertValueToKey(input, seen) { return convertValueToKeyValueDecoded(input, seen, false, true); } /** * Currently not in use. * @param input * @returns {module:Key.keyValueObject} */ function convertValueToMultiEntryKey(input) { return convertValueToKeyValueDecoded(input, null, true, true); } /** * * @param O * @throws {TypeError} * @see https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2 * @returns {Uint8Array} */ function getCopyBytesHeldByBufferSource(O) { let offset = 0; let length = 0; if (ArrayBuffer.isView(O)) { // Has [[ViewedArrayBuffer]] internal slot const arrayBuffer = O.buffer; if (arrayBuffer === undefined) { throw new TypeError('Could not copy the bytes held by a buffer source as the buffer was undefined.'); } offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached) length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached) } else { length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached) } // const octets = new Uint8Array(input); // const octets = types.binary.decode(types.binary.encode(input)); return new Uint8Array(O.buffer || O, offset, length); } /** * @typedef {PlainObject} module:Key.keyValueObject * @property {module:Key.KeyType|"NaN"} type * @property {*} [value] * @property {boolean} [invalid] * @property {string} [message] * @todo Specify acceptable `value` more precisely */ /** * Shortcut utility to avoid returning full keys from `convertValueToKey` * and subsequent need to process in calling code unless `fullKeys` is * set; may throw. * @param {module:Key.Key} input * @param {?(Array)} [seen] * @param {boolean} [multiEntry] * @param {boolean} [fullKeys] * @todo Document other allowable `input` * @returns {module:Key.keyValueObject} */ function convertValueToKeyValueDecoded(input, seen, multiEntry, fullKeys) { seen = seen || []; if (seen.includes(input)) { return { type: 'array', invalid: true, message: 'An array key cannot be circular' }; } const type = getKeyType(input); const ret = { type, value: input }; switch (type) { case 'number': { if (Number.isNaN(input)) { // List as 'NaN' type for convenience of consumers in reporting errors return { type: 'NaN', invalid: true }; } return ret; } case 'string': { return ret; } case 'binary': { // May throw (if detached) // Get a copy of the bytes held by the buffer source // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2 const octets = getCopyBytesHeldByBufferSource(input); return { type: 'binary', value: octets }; } case 'array': { // May throw (from binary) const len = input.length; seen.push(input); const keys = []; for (let i = 0; i < len; i++) { // We cannot iterate here with array extras as we must ensure sparse arrays are invalidated if (!multiEntry && !Object.prototype.hasOwnProperty.call(input, i)) { return { type, invalid: true, message: 'Does not have own index property' }; } try { const entry = input[i]; const key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry if (key.invalid) { if (multiEntry) { continue; } return { type, invalid: true, message: 'Bad array entry value-to-key conversion' }; } if (!multiEntry || !fullKeys && keys.every(k => cmp(k, key.value) !== 0) || fullKeys && keys.every(k => cmp(k, key) !== 0)) { keys.push(fullKeys ? key : key.value); } } catch (err) { if (!multiEntry) { throw err; } } } return { type, value: keys }; } case 'date': { if (!Number.isNaN(input.getTime())) { return fullKeys ? { type, value: input.getTime() } : { type, value: new Date(input.getTime()) }; } return { type, invalid: true, message: 'Not a valid date' }; // Falls through } case 'invalid': default: { // Other `typeof` types which are not valid keys: // 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function const type = input === null ? 'null' : typeof input; // Convert `null` for convenience of consumers in reporting errors return { type, invalid: true, message: 'Not a valid key; type ' + type }; } } } /** * @typedef {*} module:Key.Key * @todo Specify possible value more precisely */ /** * * @param {module:Key.Key} key * @param {boolean} fullKeys * @returns {module:Key.keyValueObject} * @todo Document other allowable `key`? */ function convertValueToMultiEntryKeyDecoded(key, fullKeys) { return convertValueToKeyValueDecoded(key, null, true, fullKeys); } /** * An internal utility. * @param input * @param {boolean} seen * @throws {DOMException} `DataError` * @returns {module:Key.keyValueObject} */ function convertValueToKeyRethrowingAndIfInvalid(input, seen) { const key = convertValueToKey(input, seen); if (key.invalid) { throw createDOMException('DataError', key.message || 'Not a valid key; type: ' + key.type); } return key; } /** * * @param value * @param keyPath * @param {boolean} multiEntry * @returns {module:Key.keyValueObject|module:Key.KeyPathEvaluateValue} * @todo Document other possible return? */ function extractKeyFromValueUsingKeyPath(value, keyPath, multiEntry) { return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true); } /** * Not currently in use. * @param value * @param keyPath * @param {boolean} multiEntry * @returns {module:Key.KeyPathEvaluateValue} */ function evaluateKeyPathOnValue(value, keyPath, multiEntry) { return evaluateKeyPathOnValueToDecodedValue(value, keyPath); } /** * May throw, return `{failure: true}` (e.g., non-object on keyPath resolution) * or `{invalid: true}` (e.g., `NaN`). * @param value * @param keyPath * @param {boolean} multiEntry * @param {boolean} fullKeys * @returns {module:Key.keyValueObject|module:Key.KeyPathEvaluateValue} * @todo Document other possible return? */ function extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, fullKeys) { const r = evaluateKeyPathOnValueToDecodedValue(value, keyPath); if (r.failure) { return r; } if (!multiEntry) { return convertValueToKeyValueDecoded(r.value, null, false, fullKeys); } return convertValueToMultiEntryKeyDecoded(r.value, fullKeys); } /** * @typedef {PlainObject} module:Key.KeyPathEvaluateFailure * @property {boolean} failure */ /** * @typedef {PlainObject} module:Key.KeyPathEvaluateValue * @property {undefined|array|string} value */ /** * Returns the value of an inline key based on a key path (wrapped in an * object with key `value`) or `{failure: true}` * @param {object} value * @param {string|array} keyPath * @param {boolean} multiEntry * @param {boolean} [fullKeys] * @returns {module:Key.KeyPathEvaluateValue} */ function evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys) { if (Array.isArray(keyPath)) { const result = []; return keyPath.some(item => { const key = evaluateKeyPathOnValueToDecodedValue(value, item); if (key.failure) { return true; } result.push(key.value); return false; }) ? { failure: true } : { value: result }; } if (keyPath === '') { return { value }; } const identifiers = keyPath.split('.'); return identifiers.some((idntfr, i) => { if (idntfr === 'length' && (typeof value === 'string' || Array.isArray(value))) { value = value.length; } else if (isBlob(value)) { switch (idntfr) { case 'size': case 'type': value = value[idntfr]; break; } } else if (isFile(value)) { switch (idntfr) { case 'name': case 'lastModified': value = value[idntfr]; break; case 'lastModifiedDate': value = new Date(value.lastModified); break; } } else if (!isObj(value) || !Object.prototype.hasOwnProperty.call(value, idntfr)) { return true; } else { value = value[idntfr]; return value === undefined; } return false; }) ? { failure: true } : { value }; } /** * Sets the inline key value. * @param {object} value * @param {*} key * @param {string} keyPath * @returns {void} */ function injectKeyIntoValueUsingKeyPath(value, key, keyPath) { const identifiers = keyPath.split('.'); const last = identifiers.pop(); identifiers.forEach(identifier => { const hop = Object.prototype.hasOwnProperty.call(value, identifier); if (!hop) { value[identifier] = {}; } value = value[identifier]; }); value[last] = key; // key is already a `keyValue` in our processing so no need to convert } /** * * @param value * @param keyPath * @see https://github.com/w3c/IndexedDB/pull/146 * @returns {boolean} */ function checkKeyCouldBeInjectedIntoValue(value, keyPath) { const identifiers = keyPath.split('.'); identifiers.pop(); for (const identifier of identifiers) { if (!isObj(value)) { return false; } const hop = Object.prototype.hasOwnProperty.call(value, identifier); if (!hop) { return true; } value = value[identifier]; } return isObj(value); } /** * * @param {module:Key.Key} key * @param {IDBKeyRange} range * @param {boolean} checkCached * @returns {boolean} */ function isKeyInRange(key, range, checkCached) { let lowerMatch = range.lower === undefined; let upperMatch = range.upper === undefined; const encodedKey = encode(key, true); const lower = checkCached ? range.__lowerCached : encode(range.lower, true); const upper = checkCached ? range.__upperCached : encode(range.upper, true); if (range.lower !== undefined) { if (range.lowerOpen && encodedKey > lower) { lowerMatch = true; } if (!range.lowerOpen && encodedKey >= lower) { lowerMatch = true; } } if (range.upper !== undefined) { if (range.upperOpen && encodedKey < upper) { upperMatch = true; } if (!range.upperOpen && encodedKey <= upper) { upperMatch = true; } } return lowerMatch && upperMatch; } /** * Determines whether an index entry matches a multi-entry key value. * @param {string} encodedEntry The entry value (already encoded) * @param {string} encodedKey The full index key (already encoded) * @returns {boolean} */ function isMultiEntryMatch(encodedEntry, encodedKey) { const keyType = encodedCharToKeyType[encodedKey.slice(0, 1)]; if (keyType === 'array') { return encodedKey.indexOf(encodedEntry) > 1; } return encodedKey === encodedEntry; } /** * * @param {module:Key.Key} keyEntry * @param {IDBKeyRange} range * @returns {module:Key.Key[]} */ function findMultiEntryMatches(keyEntry, range) { const matches = []; if (Array.isArray(keyEntry)) { for (let key of keyEntry) { if (Array.isArray(key)) { if (range && range.lower === range.upper) { continue; } if (key.length === 1) { key = key[0]; } else { const nested = findMultiEntryMatches(key, range); if (nested.length > 0) { matches.push(key); } continue; } } if (isNullish(range) || isKeyInRange(key, range, true)) { matches.push(key); } } } else if (isNullish(range) || isKeyInRange(keyEntry, range, true)) { matches.push(keyEntry); } return matches; } /** * @typedef {number|string|Date|ArrayBuffer|module:Key.ValueTypes[]} module:Key.ValueTypes */ /** * Not currently in use but keeping for spec parity. * @param {module:Key.Key} key * @throws {Error} Upon a "bad key" * @returns {module:Key.ValueTypes} */ function convertKeyToValue(key) { const { type, value } = key; switch (type) { case 'number': case 'string': { return value; } case 'array': { const array = []; const len = value.length; let index = 0; while (index < len) { const entry = convertKeyToValue(value[index]); array[index] = entry; index++; } return array; } case 'date': { return new Date(value); } case 'binary': { const len = value.length; const buffer = new ArrayBuffer(len); // Set the entries in buffer's [[ArrayBufferData]] to those in `value` const uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength); uint8.set(value); return buffer; } case 'invalid': default: throw new Error('Bad key'); } } /** * * @param {module:Key.Key} key * @param {boolean} inArray * @returns {string|null} */ function encode(key, inArray) { // Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation if (key === undefined) { return null; } // array, date, number, string, binary (should already have detected "invalid") return types[getKeyType(key)].encode(key, inArray); } /** * * @param {module:Key.Key} key * @param {boolean} inArray * @throws {Error} Invalid number * @returns {undefined|module:Key.ValueTypes} */ function decode(key, inArray) { if (typeof key !== 'string') { return undefined; } return types[encodedCharToKeyType[key.slice(0, 1)]].decode(key, inArray); } /** * * @param {module:Key.Key} key * @param {boolean} inArray * @returns {undefined|module:Key.ValueTypes} */ function roundTrip(key, inArray) { return decode(encode(key, inArray), inArray); } const MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`) /** * @external WebSQLTransaction */ /** * @typedef {IDBObjectStore} IDBObjectStoreWithCurrentName * @property {string} __currentName */ /** * @callback CurrentNumberCallback * @param {Integer} The current number * @returns {void} */ /** * @callback SQLFailureCallback * @param {DOMException} exception * @returns {void} */ /** * * @param {external:WebSQLTransaction} tx * @param {IDBObjectStoreWithCurrentName} store * @param {CurrentNumberCallback} func * @param {SQLFailureCallback} sqlFailCb * @returns {void} */ function getCurrentNumber(tx, store, func, sqlFailCb) { tx.executeSql('SELECT "currNum" FROM __sys__ WHERE "name" = ?', [escapeSQLiteStatement(store.__currentName)], function (tx, data) { if (data.rows.length !== 1) { func(1); } else { func(data.rows.item(0).currNum); } }, function (tx, error) { sqlFailCb(createDOMException('DataError', 'Could not get the auto increment value for key', error)); }); } /** * * @param {external:WebSQLTransaction} tx * @param {IDBObjectStoreWithCurrentName} store * @param {Integer} num * @param {CurrentNumberCallback} successCb * @param {SQLFailureCallback} failCb * @returns {void} */ function assignCurrentNumber(tx, store, num, successCb, failCb) { const sql = 'UPDATE __sys__ SET "currNum" = ? WHERE "name" = ?'; const sqlValues = [num, escapeSQLiteStatement(store.__currentName)]; CFG.DEBUG && console.log(sql, sqlValues); tx.executeSql(sql, sqlValues, function (tx, data) { successCb(num); }, function (tx, err) { failCb(createDOMException('UnknownError', 'Could not set the auto increment value for key', err)); }); } /** * Bump up the auto-inc counter if the key path-resolved value is valid * (greater than old value and >=1) OR if a manually passed in key is * valid (numeric and >= 1) and >= any primaryKey. * @param {external:WebSQLTransaction} tx * @param {IDBObjectStoreWithCurrentName} store * @param {Integer} num * @param {CurrentNumberCallback} successCb * @param {SQLFailureCallback} failCb * @returns {void} */ function setCurrentNumber(tx, store, num, successCb, failCb) { num = num === MAX_ALLOWED_CURRENT_NUMBER ? num + 2 // Since incrementing by one will have no effect in JavaScript on this unsafe max, we represent the max as a number incremented by two. The getting of the current number is never returned to the user and is only used in safe comparisons, so it is safe for us to represent it in this manner : num + 1; return assignCurrentNumber(tx, store, num, successCb, failCb); } /** * @callback KeyForStoreCallback * @param {"failure"|null} arg1 * @param {Integer} [arg2] * @param {Integer} [arg3] * @returns {void} */ /** * * @param {external:WebSQLTransaction} tx * @param {IDBObjectStoreWithCurrentName} store * @param {KeyForStoreCallback} cb * @param {SQLFailureCallback} sqlFailCb * @returns {void} */ function generateKeyForStore(tx, store, cb, sqlFailCb) { getCurrentNumber(tx, store, function (key) { if (key > MAX_ALLOWED_CURRENT_NUMBER) { // 2 ^ 53 (See <https://github.com/w3c/IndexedDB/issues/147>) cb('failure'); // eslint-disable-line standard/no-callback-literal return; } // Increment current number by 1 (we cannot leverage SQLite's // autoincrement (and decrement when not needed), as decrementing // will be overwritten/ignored upon the next insert) setCurrentNumber(tx, store, key, function () { cb(null, key, key); }, sqlFailCb); }, sqlFailCb); } // Fractional or numbers exceeding the max do not get changed in the result // per https://github.com/w3c/IndexedDB/issues/147 // so we do not return a key /** * * @param {external:WebSQLTransaction} tx * @param {IDBObjectStoreWithCurrentName} store * @param {*|Integer} key * @param {CurrentNumberCallback|void} successCb * @param {SQLFailureCallback} sqlFailCb * @returns {void} */ function possiblyUpdateKeyGenerator(tx, store, key, successCb, sqlFailCb) { // Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers // (or numbers larger than the max) are now to have the explicit effect of // setting the current number (up to the max), so we do not optimize them // out here if (typeof key !== 'number' || key < 1) { // Optimize with no need to get the current number // Auto-increment attempted with a bad key; // we are not to change the current number, but the steps don't call for failure // Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1 successCb(); } else { // If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher // to determine which to use and whether to update the current number getCurrentNumber(tx, store, function (cn) { const value = Math.floor(Math.min(key, MAX_ALLOWED_CURRENT_NUMBER)); const useNewKeyForAutoInc = value >= cn; if (useNewKeyForAutoInc) { setCurrentNumber(tx, store, value, function () { successCb(cn); // Supply old current number in case needs to be reverted }, sqlFailCb); } else { // Not updated successCb(); } }, sqlFailCb); } } var Key = /*#__PURE__*/Object.freeze({ __proto__: null, encode: encode, decode: decode, roundTrip: roundTrip, convertKeyToValue: convertKeyToValue, convertValueToKeyValueDecoded: convertValueToKeyValueDecoded, convertValueToMultiEntryKeyDecoded: convertValueToMultiEntryKeyDecoded, convertValueToKey: convertValueToKey, convertValueToMultiEntryKey: convertValueToMultiEntryKey, convertValueToKeyRethrowingAndIfInvalid: convertValueToKeyRethrowingAndIfInvalid, extractKeyFromValueUsingKeyPath: extractKeyFromValueUsingKeyPath, evaluateKeyPathOnValue: evaluateKeyPathOnValue, extractKeyValueDecodedFromValueUsingKeyPath: extractKeyValueDecodedFromValueUsingKeyPath, injectKeyIntoValueUsingKeyPath: injectKeyIntoValueUsingKeyPath, checkKeyCouldBeInjectedIntoValue: checkKeyCouldBeInjectedIntoValue, isMultiEntryMatch: isMultiEntryMatch, isKeyInRange: isKeyInRange, findMultiEntryMatches: findMultiEntryMatches, assignCurrentNumber: assignCurrentNumber, generateKeyForStore: generateKeyForStore, possiblyUpdateKeyGenerator: possiblyUpdateKeyGenerator }); const readonlyProperties$2 = ['lower', 'upper', 'lowerOpen', 'upperOpen']; /* eslint-disable jsdoc/check-param-names */ /** * The IndexedDB KeyRange object. * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#dfn-key-range * @param {Object} lower * @param {Object} upper * @param {Object} lowerOpen * @param {Object} upperOpen * @throws {TypeError} * @class */ function IDBKeyRange() { /* eslint-enable jsdoc/check-param-names */ throw new TypeError('Illegal constructor'); } const IDBKeyRangeAlias = IDBKeyRange; IDBKeyRange.__createInstance = function (lower, upper, lowerOpen, upperOpen) { function IDBKeyRange() { this[Symbol.toStringTag] = 'IDBKeyRange'; if (lower === undefined && upper === undefined) { throw createDOMException('DataError', 'Both arguments to the key range method cannot be undefined'); } let lowerConverted, upperConverted; if (lower !== undefined) { lowerConverted = roundTrip(lower); // Todo: does this make the "conversions" redundant convertValueToKeyRethrowingAndIfInvalid(lower); } if (upper !== undefined) { upperConverted = roundTrip(upper); // Todo: does this make the "conversions" redundant convertValueToKeyRethrowingAndIfInvalid(upper); } if (lower !== undefined && upper !== undefined && lower !== upper) { if (encode(lower) > encode(upper)) { throw createDOMException('DataError', '`lower` must not be greater than `upper` argument in `bound()` call.'); } } this.__lower = lowerConverted; this.__upper = upperConverted; this.__lowerOpen = Boolean(lowerOpen); this.__upperOpen = Boolean(upperOpen); } IDBKeyRange.prototype = IDBKeyRangeAlias.prototype; return new IDBKeyRange(); }; IDBKeyRange.prototype.includes = function (key) { // We can't do a regular instanceof check as it will create a loop given our hasInstance implementation if (!isObj(this) || typeof this.__lowerOpen !== 'boolean') { throw new TypeError('Illegal invocation'); } if (!arguments.length) { throw new TypeError('IDBKeyRange.includes requires a key argument'); } convertValueToKeyRethrowingAndIfInvalid(key); return isKeyInRange(key, this); }; IDBKeyRange.only = function (value) { if (!arguments.length) { throw new TypeError('IDBKeyRange.only requires a value argument'); } return IDBKeyRange.__createInstance(value, value, false, false); }; IDBKeyRange.lowerBound = function (value /*, open */ ) { if (!arguments.length) { throw new TypeError('IDBKeyRange.lowerBound requires a value argument'); } // eslint-disable-next-line prefer-rest-params return IDBKeyRange.__createInstance(value, undefined, arguments[1], true); }; IDBKeyRange.upperBound = function (value /*, open */ ) { if (!arguments.length) { throw new TypeError('IDBKeyRange.upperBound requires a value argument'); } // eslint-disable-next-line prefer-rest-params return IDBKeyRange.__createInstance(undefined, value, true, arguments[1]); }; IDBKeyRange.bound = function (lower, upper /* , lowerOpen, upperOpen */ ) { if (arguments.length <= 1) { throw new TypeError('IDBKeyRange.bound requires lower and upper arguments'); } // eslint-disable-next-line prefer-rest-params return IDBKeyRange.__createInstance(lower, upper, arguments[2], arguments[3]); }; IDBKeyRange.prototype[Symbol.toStringTag] = 'IDBKeyRangePrototype'; readonlyProperties$2.forEach(prop => { Object.defineProperty(IDBKeyRange.prototype, '__' + prop, { enumerable: false, configurable: false, writable: true }); // Ensure for proper interface testing that "get <name>" is the function name const o = { get [prop]() { // We can't do a regular instanceof check as it will create a loop given our hasInstance implementation if (!isObj(this) || typeof this.__lowerOpen !== 'boolean') { throw new TypeError('Illegal invocation'); } return this['__' + prop]; } }; const desc = Object.getOwnPropertyDescriptor(o, prop); // desc.enumerable = true; // Default // desc.configurable = true; // Default Object.defineProperty(IDBKeyRange.prototype, prop, desc); }); Object.defineProperty(IDBKeyRange, Symbol.hasInstance, { value: obj => isObj(obj) && 'upper' in obj && typeof obj.lowerOpen === 'boolean' }); Object.defineProperty(IDBKeyRange, 'prototype', { writable: false }); function setSQLForKeyRange(range, quotedKeyColumnName, sql, sqlValues, addAnd, checkCached) { if (range && (range.lower !== undefined || range.upper !== undefined)) { if (addAnd) sql.push('AND'); let encodedLowerKey, encodedUpperKey; const hasLower = range.lower !== undefined; const hasUpper = range.upper !== undefined; if (hasLower) { encodedLowerKey = checkCached ? range.__lowerCached : encode(range.lower); } if (hasUpper) { encodedUpperKey = checkCached ? range.__upperCached : encode(range.upper); } if (hasLower) { sqlValues.push(escapeSQLiteStatement(encodedLowerKey)); if (hasUpper && encodedLowerKey === encodedUpperKey && !range.lowerOpen && !range.upperOpen) { sql.push(quotedKeyColumnName, '=', '?'); return; } sql.push(quotedKeyColumnName, range.lowerOpen ? '>' : '>=', '?'); } hasLower && hasUpper && sql.push('AND'); if (hasUpper) { sql.push(quotedKeyColumnName, range.upperOpen ? '<' : '<=', '?'); sqlValues.push(escapeSQLiteStatement(encodedUpperKey)); } } } function convertValueToKeyRange(value, nullDisallowed) { if (instanceOf(value, IDBKeyRange)) { // We still need to validate IDBKeyRange-like objects (the above check is based on loose duck-typing) if (value.toString() !== '[object IDBKeyRange]') { return IDBKeyRange.__createInstance(value.lower, value.upper, value.lowerOpen, value.upperOpen); } return value; } if (isNullish(value)) { if (nullDisallowed) { throw createDOMException('DataError', 'No key or range was specified'); } return undefined; // Represents unbounded } convertValueToKeyRethrowingAndIfInvalid(value); return IDBKeyRange.only(value); } let cleanInterface = false; const testObject = { test: true }; // Test whether Object.defineProperty really works. if (Object.defineProperty) { try { Object.defineProperty(testObject, 'test', { enumerable: false }); if (testObject.test) { cleanInterface = true; } } catch (e) {// Object.defineProperty does not work as intended. } } /** * Shim the DOMStringList object. * @throws {TypeError} * @class */ const DOMStringList = function () { throw new TypeError('Illegal constructor'); }; DOMStringList.prototype = { constructor: DOMStringList, // Interface. contains(str) { if (!arguments.length) { throw new TypeError('DOMStringList.contains must be supplied a value'); } return this._items.includes(str); }, item(key) { if (!arguments.length) { throw new TypeError('DOMStringList.item must be supplied a value'); } if (key < 0 || key >= this.length || !Number.isInteger(key)) { return null; } return this._items[key]; }, // Helpers. Should only be used internally. clone() { const stringList = DOMStringList.__createInstance(); stringList._items = this._items.slice(); stringList._length = this.length; stringList.addIndexes(); return stringList; }, addIndexes() { for (let i = 0; i < this._items.length; i++) { this[i] = this._items[i]; } }, sortList() { // http://w3c.github.io/IndexedDB/#sorted-list // https://tc39.github.io/ecma262/#sec-abstract-relational-comparison this._items.sort(); this.addIndexes(); return this._items; }, forEach(cb, thisArg) { this._items.forEach(cb, thisArg); }, map(cb, thisArg) { return this._items.map(cb, thisArg); }, indexOf(str) { return this._items.indexOf(str); }, push(item) { this._items.push(item); this._length++; this.sortList(); }, splice(...args /* index, howmany, item1, ..., itemX */ ) { this._items.splice(...args); this._length = this._items.length; for (const i in this) { if (i === String(parseInt(i))) { delete this[i]; } } this.sortList(); }, [Symbol.toStringTag]: 'DOMStringListPrototype', // At least because `DOMStringList`, as a [list](https://infra.spec.whatwg.org/#list) // can be converted to a sequence per https://infra.spec.whatwg.org/#list-iterate // and particularly as some methods, e.g., `IDBDatabase.transaction` // expect such sequence<DOMString> (or DOMString), we need an iterator (some of // the Mocha tests rely on these) *[Symbol.iterator]() { let i = 0; while (i < this._items.length) { yield this._items[i++]; } } }; Object.defineProperty(DOMStringList, Symbol.hasInstance, { value(obj) { return {}.toString.call(obj) === 'DOMStringListPrototype'; } }); const DOMStringListAlias = DOMStringList; Object.defineProperty(DOMStringList, '__createInstance', { value() { const DOMStringList = function DOMStringList() { this.toString = function () { return '[object DOMStringList]'; }; // Internal functions on the prototype have been made non-enumerable below. Object.defineProperty(this, 'length', { enumerable: true, get() { return this._length; } }); this._items = []; this._length = 0; }; DOMStringList.prototype = DOMStringListAlias.prototype; return new DOMStringList(); } }); if (cleanInterface) { Object.defineProperty(DOMStringList, 'prototype', { writable: false }); const nonenumerableReadonly = ['addIndexes', 'sortList', 'forEach', 'map', 'indexOf', 'push', 'splice', 'constructor', '__createInstance']; nonenumerableReadonly.forEach(nonenumerableReadonly => { Object.defineProperty(DOMStringList.prototype, nonenumerableReadonly, { enumerable: false }); }); // Illegal invocations Object.defineProperty(DOMStringList.prototype, 'length', { configurable: true, enumerable: true, get() { throw new TypeError('Illegal invocation'); } }); const nonenumerableWritable = ['_items', '_length']; nonenumerableWritable.forEach(nonenumerableWritable => { Object.defineProperty(DOMStringList.prototype, nonenumerableWritable, { enumerable: false, writable: true }); }); } let uniqueID = 0; const listeners$1 = ['onabort', 'oncomplete', 'onerror']; const readonlyProperties$3 = ['objectStoreNames', 'mode', 'db', 'error']; /* eslint-disable jsdoc/check-param-names */ /** * The IndexedDB Transaction. * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBTransaction * @param {IDBDatabase} db * @param {string[]} storeNames * @param {string} mode * @class */ function IDBTransaction() { /* eslint-enable jsdoc/check-param-names */ throw new TypeError('Illegal constructor'); } const IDBTransactionAlias = IDBTransaction; IDBTransaction.__createInstance = function (db, storeNames, mode) { function IDBTransaction() { const me = this; me[Symbol.toStringTag] = 'IDBTransaction'; defineReadonlyProperties(me, readonlyProperties$3); me.__id = ++uniqueID; // for debugging simultaneous transactions me.__active = true; me.__running = false; me.__errored = false; me.__requests = []; me.__objectStoreNames = storeNames; me.__mode = mode; me.__db = db; me.__error = null; me.__setOptions({ legacyOutputDidListenersThrowFlag: true // Event hook for IndexedB }); readonlyProperties$3.forEach(readonlyProp => { Object.defineProperty(this, readonlyProp, { configurable: true }); }); defineListenerProperties(this, listeners$1); me.__storeHandles = {}; // Kick off the transaction as soon as all synchronous code is done setTimeout(() => { me.__executeRequests(); }, 0); } IDBTransaction.prototype = IDBTransactionAlias.prototype; return new IDBTransaction(); }; IDBTransaction.prototype = EventTargetFactory.createInstance({ defaultSync: true, // Ensure EventTarget preserves our properties extraProperties: ['complete'] }); IDBTransaction.prototype.__transFinishedCb = function (err, cb) { cb(Boolean(err)); }; IDBTransaction.prototype.__executeRequests = function () { const me = this; if (me.__running) { CFG.DEBUG && console.log('Looks like the request set is already running', me.mode); return; } me.__running = true; me.db.__db[me.mode === 'readonly' ? 'readTransaction' : 'transaction']( // `readTransaction` is optimized, at least in `node-websql` function executeRequests(tx) { me.__tx = tx; let q = null, i = -1; function success(result, req) { if (me.__errored || me.__requestsFinished) { // We've already called "onerror", "onabort", or thrown within the transaction, so don't do it again. return; } if (req) { q.req = req; // Need to do this in case of cursors } if (q.req.__done) { // Avoid continuing with aborted requests return; } q.req.__done = true; q.req.__result = result; q.req.__error = null; me.__active = true; const e = createEvent('success'); q.req.dispatchEvent(e); // Do not set __active flag to false yet: https://github.com/w3c/IndexedDB/issues/87 if (e.__legacyOutputDidListenersThrowError) { logError('Error', 'An error occurred in a success handler attached to request chain', e.__legacyOutputDidListenersThrowError); // We do nothing else with this error as per spec me.__abortTransaction(createDOMException('AbortError', 'A request was aborted (in user handler after success).')); return; } executeNextRequest(); } function error(...args /* tx, err */ ) { if (me.__errored || me.__requestsFinished) { // We've already called "onerror", "onabort", or thrown within // the transaction, so don't do it again. return; } if (q.req && q.req.__done) { // Avoid continuing with aborted requests return; } const err = findError(args); if (!q.req) { me.__abortTransaction(err); return; } // Fire an error event for the current IDBRequest q.req.__done = true; q.req.__error = err; q.req.__result = undefined; // Must be undefined if an error per `result` getter q.req.addLateEventListener('error', function (e) { if (e.cancelable && e.defaultPrevented && !e.__legacyOutputDidListenersThrowError) { executeNextRequest(); } }); q.req.addDefaultEventListener('error', function () { me.__abortTransaction(q.req.__error); }); me.__active = true; const e = createEvent('error', err, { bubbles: true, cancelable: true }); q.req.dispatchEvent(e); // Do not set __active flag to false yet: https://github.com/w3c/IndexedDB/issues/87 if (e.__legacyOutputDidListenersThrowError) { logError('Error', 'An error occurred in an error handler attached to request chain', e.__legacyOutputDidListenersThrowError); // We do nothing else with this error as per spec e.preventDefault(); // Prevent 'error' default as steps indicate we should abort with `AbortError` even without cancellation me.__abortTransaction(createDOMException('AbortError', 'A request was aborted (in user handler after error).')); } } function executeNextRequest() { if (me.__errored || me.__requestsFinished) { // We've already called "onerror", "onabort", or thrown within the transaction, so don't do it again. return; } i++; if (i >= me.__requests.length) { // All requests in the transaction are done me.__requests = []; if (me.__active) { requestsFinished(); } } else { try { q = me.__requests[i]; if (!q.req) { q.op(tx, q.args, executeNextRequest, error); return; } if (q.req.__done) { // Avoid continuing with aborted requests return; } q.op(tx, q.args, success, error, executeNextRequest); } catch (e) { error(e); } } } executeNextRequest(); }, function webSQLError(webSQLErr) { if (webSQLErr === true) { // Not a genuine SQL error return; } const err = webSQLErrback(webSQLErr); me.__abortTransaction(err); }, function () { // For Node, we don't need to try running here as we can keep // the transaction running long enough to rollback (in the // next (non-standard) callback for this transaction call) if (me.__transFinishedCb !== IDBTransaction.prototype.__transFinishedCb) { // Node return; } if (!me.__transactionEndCallback && !me.__requestsFinished) { me.__transactionFinished = true; return; } if (me.__transactionEndCallback && !me.__completed) { me.__transFinishedCb(me.__errored, me.__transactionEndCallback); } }, function (currentTask, err, done, rollback, commit) { if (currentTask.readOnly || err) { return true; } me.__transFinishedCb = function (err, cb) { if (err) { rollback(err, cb); } else { commit(cb); } }; if (me.__transactionEndCallback && !me.__completed) { me.__transFinishedCb(me.__errored, me.__transactionEndCallback); } return false; }); function requestsFinished() { me.__active = false; me.__requestsFinished = true; function complete() { me.__completed = true; CFG.DEBUG && console.log('Transaction completed'); const evt = createEvent('complete'); try { me.__internal = true; me.dispatchEvent(evt); me.__internal = false; me.dispatchEvent(createEvent('__complete')); } catch (e) { me.__internal = false; // An error occurred in the "oncomplete" handler. // It's too late to call "onerror" or "onabort". Throw a global error instead. // (this may seem odd/bad, but it's how all native IndexedDB implementations work) me.__errored = true; throw e; } finally { me.__storeHandles = {}; } } if (me.mode === 'readwrite') { if (me.__transactionFinished) { complete(); return; } me.__transactionEndCallback = complete; return; } if (me.mode === 'readonly') { complete(); return; } const ev = createEvent('__beforecomplete'); ev.complete = complete; me.dispatchEvent(ev); } }; /** * Creates a new IDBRequest for the transaction. * NOTE: The transaction is not queued until you call {@link IDBTransaction#__pushToQueue}. * @param {IDBDatabase} source * @returns {IDBRequest} * @protected */ IDBTransaction.prototype.__createRequest = function (source) { const me = this; const request = IDBRequest.__createInstance(); request.__source = source !== undefined ? source : me.db; request.__transaction = me; return request; }; /** * Adds a callback function to the transaction queue. * @param {function} callback * @param {*} args * @param {IDBDatabase} source * @returns {IDBRequest} * @protected */ IDBTransaction.prototype.__addToTransactionQueue = function (callback, args, source) { const request = this.__createRequest(source); this.__pushToQueue(request, callback, args); return request; }; /** * Adds a callback function to the transaction queue without generating a * request. * @param {function} callback * @param {*} args * @param {IDBDatabase} source * @returns {void} * @protected */ IDBTransaction.prototype.__addNonRequestToTransactionQueue = function (callback, args, source) { this.__pushToQueue(null, callback, args); }; /** * Adds an IDBRequest to the transaction queue. * @param {IDBRequest} request * @param {function} callback * @param {*} args * @protected * @returns {void} */ IDBTransaction.prototype.__pushToQueue = function (request, callback, args) { this.__assertActive(); this.__requests.push({ op: callback, args, req: request }); }; IDBTransaction.prototype.__assertActive = function () { if (!this.__active) { throw createDOMException('TransactionInactiveError', 'A request was placed against a transaction which is currently not active, or which is finished'); } }; IDBTransaction.prototype.__assertWritable = function () { if (this.mode === 'readonly') { throw createDOMException('ReadOnlyError', 'The transaction is read only'); } }; IDBTransaction.prototype.__assertVersionChange = function () { IDBTransaction.__assertVersionChange(this); }; /** * Returns the specified object store. * @param {string} objectStoreName * @returns {IDBObjectStore} */ IDBTransaction.prototype.objectStore = function (objectStoreName) { const me = this; if (!(me instanceof IDBTransaction)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No object store name was specified'); } IDBTransaction.__assertNotFinished(me); if (me.__objectStoreNames.indexOf(objectStoreName) === -1) { // eslint-disable-line unicorn/prefer-includes throw createDOMException('NotFoundError', objectStoreName + ' is not participating in this transaction'); } const store = me.db.__objectStores[objectStoreName]; if (!store) { throw createDOMException('NotFoundError', objectStoreName + ' does not exist in ' + me.db.name); } if (!me.__storeHandles[objectStoreName] || // These latter conditions are to allow store // recreation to create new clone object me.__storeHandles[objectStoreName].__pendingDelete || me.__storeHandles[objectStoreName].__deleted) { me.__storeHandles[objectStoreName] = IDBObjectStore.__clone(store, me); } return me.__storeHandles[objectStoreName]; }; IDBTransaction.prototype.__abortTransaction = function (err) { const me = this; logError('Error', 'An error occurred in a transaction', err); if (me.__errored) { // We've already called "onerror", "onabort", or thrown, so don't do it again. return; } me.__errored = true; if (me.mode === 'versionchange') { // Steps for aborting an upgrade transaction me.db.__version = me.db.__oldVersion; me.db.__objectStoreNames = me.db.__oldObjectStoreNames; me.__objectStoreNames = me.db.__oldObjectStoreNames; Object.values(me.db.__objectStores).concat(Object.values(me.__storeHandles)).forEach(function (store) { // Store was already created so we restore to name before the rename if ('__pendingName' in store && me.db.__oldObjectStoreNames.indexOf(store.__pendingName) > -1 // eslint-disable-line unicorn/prefer-includes ) { store.__name = store.__originalName; } store.__indexNames = store.__oldIndexNames; delete store.__pendingDelete; Object.values(store.__indexes).concat(Object.values(store.__indexHandles)).forEach(function (index) { // Index was already created so we restore to name before the rename if ('__pendingName' in index && store.__oldIndexNames.indexOf(index.__pendingName) > -1 // eslint-disable-line unicorn/prefer-includes ) { index.__name = index.__originalName; } delete index.__pendingDelete; }); }); } me.__active = false; // Setting here and in requestsFinished for https://github.com/w3c/IndexedDB/issues/87 if (err !== null) { me.__error = err; } if (me.__requestsFinished) { // The transaction has already completed, so we can't call "onerror" or "onabort". // So throw the error instead. setTimeout(() => { throw err; }, 0); } function abort(tx, errOrResult) { if (!tx) { CFG.DEBUG && console.log('Rollback not possible due to missing transaction', me); } else if (errOrResult && typeof errOrResult.code === 'number') { CFG.DEBUG && console.log('Rollback erred; feature is probably not supported as per WebSQL', me); } else { CFG.DEBUG && console.log('Rollback succeeded', me); } me.dispatchEvent(createEvent('__preabort')); me.__requests.filter(function (q, i, arr) { // eslint-disable-line promise/no-promise-in-callback return q.req && !q.req.__done && [i, -1].includes(arr.map(q => q.req).lastIndexOf(q.req)); }).reduce(function (promises, q) { // We reduce to a chain of promises to be queued in order, so we cannot // use `Promise.all`, and I'm unsure whether `setTimeout` currently // behaves first-in-first-out with the same timeout so we could // just use a `forEach`. return promises.then(function () { q.req.__done = true; q.req.__result = undefined; q.req.__error = createDOMException('AbortError', 'A request was aborted (an unfinished request).'); const reqEvt = createEvent('error', q.req.__error, { bubbles: true, cancelable: true }); return new syncPromiseCommonjs(function (resolve) { setTimeout(() => { q.req.dispatchEvent(reqEvt); // No need to catch errors resolve(); }); }); }); }, syncPromiseCommonjs.resolve()).then(function () { // Also works when there are no pending requests const evt = createEvent('abort', err, { bubbles: true, cancelable: false }); setTimeout(() => { me.__abortFinished = true; me.dispatchEvent(evt); me.__storeHandles = {}; me.dispatchEvent(createEvent('__abort')); }); return undefined; }).catch(err => { console.log('Abort error'); throw err; }); } me.__transFinishedCb(true, function (rollback) { if (rollback && me.__tx) { // Not supported in standard SQL (and WebSQL errors should // rollback automatically), but for Node.js, etc., we give chance for // manual aborts which would otherwise not work. if (me.mode === 'readwrite') { if (me.__transactionFinished) { abort(); return; } me.__transactionEndCallback = abort; return; } try { me.__tx.executeSql('ROLLBACK', [], abort, abort); // Not working in some circumstances, even in Node } catch (err) { // Browser errs when transaction has ended and since it most likely already erred here, // we call to abort abort(); } } else { abort(null, { code: 0 }); } }); }; IDBTransaction.prototype.abort = function () { const me = this; if (!(me instanceof IDBTransaction)) { throw new TypeError('Illegal invocation'); } CFG.DEBUG && console.log('The transaction was aborted', me); IDBTransaction.__assertNotFinished(me); me.__abortTransaction(null); }; IDBTransaction.prototype[Symbol.toStringTag] = 'IDBTransactionPrototype'; IDBTransaction.__assertVersionChange = function (tx) { if (!tx || tx.mode !== 'versionchange') { throw createDOMException('InvalidStateError', 'Not a version transaction'); } }; IDBTransaction.__assertNotVersionChange = function (tx) { if (tx && tx.mode === 'versionchange') { throw createDOMException('InvalidStateError', 'Cannot be called during a version transaction'); } }; IDBTransaction.__assertNotFinished = function (tx) { if (!tx || tx.__completed || tx.__abortFinished || tx.__errored) { throw createDOMException('InvalidStateError', 'Transaction finished by commit or abort'); } }; // object store methods behave differently: see https://github.com/w3c/IndexedDB/issues/192 IDBTransaction.__assertNotFinishedObjectStoreMethod = function (tx) { try { IDBTransaction.__assertNotFinished(tx); } catch (err) { if (tx && !tx.__completed && !tx.__abortFinished) { throw createDOMException('TransactionInactiveError', 'A request was placed against a transaction which is currently not active, or which is finished'); } throw err; } }; IDBTransaction.__assertActive = function (tx) { if (!tx || !tx.__active) { throw createDOMException('TransactionInactiveError', 'A request was placed against a transaction which is currently not active, or which is finished'); } }; /** * Used by our `EventTarget.prototype` library to implement bubbling/capturing. * @returns {IDBDatabase} */ IDBTransaction.prototype.__getParent = function () { return this.db; }; defineOuterInterface(IDBTransaction.prototype, listeners$1); defineReadonlyOuterInterface(IDBTransaction.prototype, readonlyProperties$3); Object.defineProperty(IDBTransaction.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBTransaction }); Object.defineProperty(IDBTransaction, 'prototype', { writable: false }); function _typeof$1(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$1 = function (obj) { return typeof obj; }; } else { _typeof$1 = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$1(obj); } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } 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 _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; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } /** * We keep this function minimized so if using two instances of this * library, where one is minimized and one is not, it will still work * with `hasConstructorOf`. * With ES6 classes, we may be able to simply use `class TypesonPromise * extends Promise` and add a string tag for detection. * @param {function} f */ // eslint-disable-next-line max-len // eslint-disable-next-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi, promise/avoid-new var TypesonPromise = function TypesonPromise(f) { _classCallCheck(this, TypesonPromise); this.p = new Promise(f); }; // eslint-disable-next-line max-len // class TypesonPromise extends Promise {get[Symbol.toStringTag](){return 'TypesonPromise'};} // eslint-disable-line keyword-spacing, space-before-function-paren, space-before-blocks, block-spacing, semi TypesonPromise.__typeson__type__ = 'TypesonPromise'; // Note: core-js-bundle provides a `Symbol` polyfill /* istanbul ignore else */ if (typeof Symbol !== 'undefined') { // Ensure `isUserObject` will return `false` for `TypesonPromise` TypesonPromise.prototype[Symbol.toStringTag] = 'TypesonPromise'; } /** * * @param {function} [onFulfilled] * @param {function} [onRejected] * @returns {TypesonPromise} */ TypesonPromise.prototype.then = function (onFulfilled, onRejected) { var _this = this; return new TypesonPromise(function (typesonResolve, typesonReject) { // eslint-disable-next-line promise/catch-or-return _this.p.then(function (res) { // eslint-disable-next-line promise/always-return typesonResolve(onFulfilled ? onFulfilled(res) : res); })["catch"](function (res) { return onRejected ? onRejected(res) : Promise.reject(res); }).then(typesonResolve, typesonReject); }); }; /** * * @param {function} onRejected * @returns {TypesonPromise} */ TypesonPromise.prototype["catch"] = function (onRejected) { return this.then(null, onRejected); }; /** * * @param {Any} v * @returns {TypesonPromise} */ TypesonPromise.resolve = function (v) { return new TypesonPromise(function (typesonResolve) { typesonResolve(v); }); }; /** * * @param {Any} v * @returns {TypesonPromise} */ TypesonPromise.reject = function (v) { return new TypesonPromise(function (typesonResolve, typesonReject) { typesonReject(v); }); }; ['all', 'race'].forEach(function (meth) { /** * * @param {Promise[]} promArr * @returns {TypesonPromise} */ TypesonPromise[meth] = function (promArr) { return new TypesonPromise(function (typesonResolve, typesonReject) { // eslint-disable-next-line promise/catch-or-return Promise[meth](promArr.map(function (prom) { return prom && prom.constructor && prom.constructor.__typeson__type__ === 'TypesonPromise' ? prom.p : prom; })).then(typesonResolve, typesonReject); }); }; }); var _ref = {}, toStr = _ref.toString, hasOwn$1 = {}.hasOwnProperty, getProto = Object.getPrototypeOf, fnToString = hasOwn$1.toString; /** * Second argument not in use internally, but provided for utility. * @param {Any} v * @param {boolean} catchCheck * @returns {boolean} */ function isThenable(v, catchCheck) { return isObject(v) && typeof v.then === 'function' && (!catchCheck || typeof v["catch"] === 'function'); } /** * * @param {Any} val * @returns {string} */ function toStringTag(val) { return toStr.call(val).slice(8, -1); } /** * This function is dependent on both constructors * being identical so any minimization is expected of both. * @param {Any} a * @param {function} b * @returns {boolean} */ function hasConstructorOf(a, b) { if (!a || _typeof$1(a) !== 'object') { return false; } var proto = getProto(a); if (!proto) { return b === null; } var Ctor = hasOwn$1.call(proto, 'constructor') && proto.constructor; if (typeof Ctor !== 'function') { return b === null; } if (b === Ctor) { return true; } if (b !== null && fnToString.call(Ctor) === fnToString.call(b)) { return true; } if (typeof b === 'function' && typeof Ctor.__typeson__type__ === 'string' && Ctor.__typeson__type__ === b.__typeson__type__) { return true; } return false; } /** * * @param {Any} val * @returns {boolean} */ function isPlainObject(val) { // Mirrors jQuery's if (!val || toStringTag(val) !== 'Object') { return false; } var proto = getProto(val); if (!proto) { // `Object.create(null)` return true; } return hasConstructorOf(val, Object); } /** * * @param {Any} val * @returns {boolean} */ function isUserObject(val) { if (!val || toStringTag(val) !== 'Object') { return false; } var proto = getProto(val); if (!proto) { // `Object.create(null)` return true; } return hasConstructorOf(val, Object) || isUserObject(proto); } /** * * @param {Any} v * @returns {boolean} */ function isObject(v) { return v && _typeof$1(v) === 'object'; } /** * * @param {string} keyPathComponent * @returns {string} */ function escapeKeyPathComponent(keyPathComponent) { return keyPathComponent.replace(/~/g, '~0').replace(/\./g, '~1'); } /** * * @param {string} keyPathComponent * @returns {string} */ function unescapeKeyPathComponent(keyPathComponent) { return keyPathComponent.replace(/~1/g, '.').replace(/~0/g, '~'); } /** * @param {PlainObject|GenericArray} obj * @param {string} keyPath * @returns {Any} */ function getByKeyPath(obj, keyPath) { if (keyPath === '') { return obj; } var period = keyPath.indexOf('.'); if (period > -1) { var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))]; return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.slice(period + 1)); } return obj[unescapeKeyPathComponent(keyPath)]; } /** * * @param {PlainObject} obj * @param {string} keyPath * @param {Any} value * @returns {Any} */ function setAtKeyPath(obj, keyPath, value) { if (keyPath === '') { return value; } var period = keyPath.indexOf('.'); if (period > -1) { var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))]; return setAtKeyPath(innerObj, keyPath.slice(period + 1), value); } obj[unescapeKeyPathComponent(keyPath)] = value; return obj; } /** * * @param {external:JSON} value * @returns {"null"|"array"|"undefined"|"boolean"|"number"|"string"| * "object"|"symbol"} */ function getJSONType(value) { return value === null ? 'null' : Array.isArray(value) ? 'array' : _typeof$1(value); } var keys = Object.keys, isArray = Array.isArray, hasOwn$1$1 = {}.hasOwnProperty, internalStateObjPropsToIgnore = ['type', 'replaced', 'iterateIn', 'iterateUnsetNumeric']; /** * Handle plain object revivers first so reference setting can use * revived type (e.g., array instead of object); assumes revived * has same structure or will otherwise break subsequent references. * @param {PlainObjectType} a * @param {PlainObjectType} b * @returns {1|-1|boolean} */ function nestedPathsFirst(a, b) { if (a.keypath === '') { return -1; } var as = a.keypath.match(/\./g) || 0; var bs = b.keypath.match(/\./g) || 0; if (as) { as = as.length; } if (bs) { bs = bs.length; } return as > bs ? -1 : as < bs ? 1 : a.keypath < b.keypath ? -1 : a.keypath > b.keypath; } /** * An instance of this class can be used to call `stringify()` and `parse()`. * Typeson resolves cyclic references by default. Can also be extended to * support custom types using the register() method. * * @class * @param {{cyclic: boolean}} [options] - if cyclic (default true), * cyclic references will be handled gracefully. */ var Typeson = /*#__PURE__*/function () { function Typeson(options) { _classCallCheck(this, Typeson); this.options = options; // Replacers signature: replace (value). Returns falsy if not // replacing. Otherwise ['Date', value.getTime()] this.plainObjectReplacers = []; this.nonplainObjectReplacers = []; // Revivers: [{type => reviver}, {plain: boolean}]. // Sample: [{'Date': value => new Date(value)}, {plain: false}] this.revivers = {}; /** Types registered via `register()`. */ this.types = {}; } /** * @typedef {null|boolean|number|string|GenericArray|PlainObject} JSON */ /** * @callback JSONReplacer * @param {""|string} key * @param {JSON} value * @returns {number|string|boolean|null|PlainObject|undefined} * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter */ /** * Serialize given object to Typeson. * Initial arguments work identical to those of `JSON.stringify`. * The `replacer` argument has nothing to do with our replacers. * @param {Any} obj * @param {JSONReplacer|string[]} replacer * @param {number|string} space * @param {object} opts * @returns {string|Promise} Promise resolves to a string */ _createClass(Typeson, [{ key: "stringify", value: function stringify(obj, replacer, space, opts) { opts = _objectSpread2({}, this.options, {}, opts, { stringification: true }); var encapsulated = this.encapsulate(obj, null, opts); if (isArray(encapsulated)) { return JSON.stringify(encapsulated[0], replacer, space); } return encapsulated.then(function (res) { return JSON.stringify(res, replacer, space); }); } /** * Also sync but throws on non-sync result. * @param {Any} obj * @param {JSONReplacer|string[]} replacer * @param {number|string} space * @param {object} opts * @returns {string} */ }, { key: "stringifySync", value: function stringifySync(obj, replacer, space, opts) { return this.stringify(obj, replacer, space, _objectSpread2({ throwOnBadSyncType: true }, opts, { sync: true })); } /** * * @param {Any} obj * @param {JSONReplacer|string[]} replacer * @param {number|string} space * @param {object} opts * @returns {Promise<string>} */ }, { key: "stringifyAsync", value: function stringifyAsync(obj, replacer, space, opts) { return this.stringify(obj, replacer, space, _objectSpread2({ throwOnBadSyncType: true }, opts, { sync: false })); } /** * Parse Typeson back into an obejct. * Initial arguments works identical to those of `JSON.parse()`. * @param {string} text * @param {function} reviver This JSON reviver has nothing to do with * our revivers. * @param {object} opts * @returns {external:JSON} */ }, { key: "parse", value: function parse(text, reviver, opts) { opts = _objectSpread2({}, this.options, {}, opts, { parse: true }); return this.revive(JSON.parse(text, reviver), opts); } /** * Also sync but throws on non-sync result. * @param {string} text * @param {function} reviver This JSON reviver has nothing to do with * our revivers. * @param {object} opts * @returns {external:JSON} */ }, { key: "parseSync", value: function parseSync(text, reviver, opts) { return this.parse(text, reviver, _objectSpread2({ throwOnBadSyncType: true }, opts, { sync: true })); } /** * @param {string} text * @param {function} reviver This JSON reviver has nothing to do with * our revivers. * @param {object} opts * @returns {Promise} Resolves to `external:JSON` */ }, { key: "parseAsync", value: function parseAsync(text, reviver, opts) { return this.parse(text, reviver, _objectSpread2({ throwOnBadSyncType: true }, opts, { sync: false })); } /** * * @param {Any} obj * @param {object} stateObj * @param {object} [opts={}] * @returns {string[]|false} */ }, { key: "specialTypeNames", value: function specialTypeNames(obj, stateObj) { var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; opts.returnTypeNames = true; return this.encapsulate(obj, stateObj, opts); } /** * * @param {Any} obj * @param {PlainObject} stateObj * @param {PlainObject} [opts={}] * @returns {Promise|GenericArray|PlainObject|string|false} */ }, { key: "rootTypeName", value: function rootTypeName(obj, stateObj) { var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; opts.iterateNone = true; return this.encapsulate(obj, stateObj, opts); } /** * Encapsulate a complex object into a plain Object by replacing * registered types with plain objects representing the types data. * * This method is used internally by `Typeson.stringify()`. * @param {Any} obj - Object to encapsulate. * @param {PlainObject} stateObj * @param {PlainObject} opts * @returns {Promise|GenericArray|PlainObject|string|false} */ }, { key: "encapsulate", value: function encapsulate(obj, stateObj, opts) { opts = _objectSpread2({ sync: true }, this.options, {}, opts); var _opts = opts, sync = _opts.sync; var that = this, types = {}, refObjs = [], // For checking cyclic references refKeys = [], // For checking cyclic references promisesDataRoot = []; // Clone the object deeply while at the same time replacing any // special types or cyclic reference: var cyclic = 'cyclic' in opts ? opts.cyclic : true; var _opts2 = opts, encapsulateObserver = _opts2.encapsulateObserver; var ret = _encapsulate('', obj, cyclic, stateObj || {}, promisesDataRoot); /** * * @param {Any} ret * @returns {GenericArray|PlainObject|string|false} */ function finish(ret) { // Add `$types` to result only if we ever bumped into a // special type (or special case where object has own `$types`) var typeNames = Object.values(types); if (opts.iterateNone) { if (typeNames.length) { return typeNames[0]; } return Typeson.getJSONType(ret); } if (typeNames.length) { if (opts.returnTypeNames) { return _toConsumableArray(new Set(typeNames)); } // Special if array (or a primitive) was serialized // because JSON would ignore custom `$types` prop on it if (!ret || !isPlainObject(ret) || // Also need to handle if this is an object with its // own `$types` property (to avoid ambiguity) hasOwn$1$1.call(ret, '$types')) { ret = { $: ret, $types: { $: types } }; } else { ret.$types = types; } // No special types } else if (isObject(ret) && hasOwn$1$1.call(ret, '$types')) { ret = { $: ret, $types: true }; } if (opts.returnTypeNames) { return false; } return ret; } /** * * @param {Any} ret * @param {GenericArray} promisesData * @returns {Promise<Any>} */ function checkPromises(_x, _x2) { return _checkPromises.apply(this, arguments); } /** * * @param {object} stateObj * @param {object} ownKeysObj * @param {function} cb * @returns {undefined} */ function _checkPromises() { _checkPromises = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(ret, promisesData) { var promResults; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return Promise.all(promisesData.map(function (pd) { return pd[1].p; })); case 2: promResults = _context2.sent; _context2.next = 5; return Promise.all(promResults.map( /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(promResult) { var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: newPromisesData = []; _promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0]; _prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6]; encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType); isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself // returns a `Typeson.Promise` if (!(keyPath && isTypesonPromise)) { _context.next = 11; break; } _context.next = 8; return encaps.p; case 8: encaps2 = _context.sent; parentObj[key] = encaps2; return _context.abrupt("return", checkPromises(ret, newPromisesData)); case 11: if (keyPath) { parentObj[key] = encaps; } else if (isTypesonPromise) { ret = encaps.p; } else { // If this is itself a `Typeson.Promise` (because the // original value supplied was a `Promise` or // because the supplied custom type value resolved // to one), returning it below will be fine since // a `Promise` is expected anyways given current // config (and if not a `Promise`, it will be ready // as the resolve value) ret = encaps; } return _context.abrupt("return", checkPromises(ret, newPromisesData)); case 13: case "end": return _context.stop(); } } }, _callee); })); return function (_x3) { return _ref.apply(this, arguments); }; }())); case 5: return _context2.abrupt("return", ret); case 6: case "end": return _context2.stop(); } } }, _callee2); })); return _checkPromises.apply(this, arguments); } function _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, cb) { Object.assign(stateObj, ownKeysObj); var vals = internalStateObjPropsToIgnore.map(function (prop) { var tmp = stateObj[prop]; delete stateObj[prop]; return tmp; }); // eslint-disable-next-line callback-return cb(); internalStateObjPropsToIgnore.forEach(function (prop, i) { stateObj[prop] = vals[i]; }); } /** * * @param {string} keypath * @param {Any} value * @param {boolean} cyclic * @param {PlainObject} stateObj * @param {boolean} promisesData * @param {boolean} resolvingTypesonPromise * @param {string} detectedType * @returns {Any} */ function _encapsulate(keypath, value, cyclic, stateObj, promisesData, resolvingTypesonPromise, detectedType) { var ret; var observerData = {}; var $typeof = _typeof$1(value); var runObserver = encapsulateObserver ? function (obj) { var type = detectedType || stateObj.type || Typeson.getJSONType(value); encapsulateObserver(Object.assign(obj || observerData, { keypath: keypath, value: value, cyclic: cyclic, stateObj: stateObj, promisesData: promisesData, resolvingTypesonPromise: resolvingTypesonPromise, awaitingTypesonPromise: hasConstructorOf(value, TypesonPromise) }, { type: type })); } : null; if (['string', 'boolean', 'number', 'undefined'].includes($typeof)) { if (value === undefined || $typeof === 'number' && (isNaN(value) || value === -Infinity || value === Infinity)) { if (stateObj.replaced) { ret = value; } else { ret = replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver); } if (ret !== value) { observerData = { replaced: ret }; } } else { ret = value; } if (runObserver) { runObserver(); } return ret; } if (value === null) { if (runObserver) { runObserver(); } return value; } if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric && value && _typeof$1(value) === 'object') { // Options set to detect cyclic references and be able // to rewrite them. var refIndex = refObjs.indexOf(value); if (refIndex < 0) { if (cyclic === true) { refObjs.push(value); refKeys.push(keypath); } } else { types[keypath] = '#'; if (runObserver) { runObserver({ cyclicKeypath: refKeys[refIndex] }); } return '#' + refKeys[refIndex]; } } var isPlainObj = isPlainObject(value); var isArr = isArray(value); var replaced = // Running replace will cause infinite loop as will test // positive again (isPlainObj || isArr) && (!that.plainObjectReplacers.length || stateObj.replaced) || stateObj.iterateIn ? // Optimization: if plain object and no plain-object // replacers, don't try finding a replacer value : replace(keypath, value, stateObj, promisesData, isPlainObj || isArr, null, runObserver); var clone; if (replaced !== value) { ret = replaced; observerData = { replaced: replaced }; } else { // eslint-disable-next-line no-lonely-if if (keypath === '' && hasConstructorOf(value, TypesonPromise)) { promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]); ret = value; } else if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') { clone = new Array(value.length); observerData = { clone: clone }; } else if (!['function', 'symbol'].includes(_typeof$1(value)) && !('toJSON' in value) && !hasConstructorOf(value, TypesonPromise) && !hasConstructorOf(value, Promise) && !hasConstructorOf(value, ArrayBuffer) || isPlainObj || stateObj.iterateIn === 'object') { clone = {}; if (stateObj.addLength) { clone.length = value.length; } observerData = { clone: clone }; } else { ret = value; // Only clone vanilla objects and arrays } } if (runObserver) { runObserver(); } if (opts.iterateNone) { return clone || ret; } if (!clone) { return ret; } // Iterate object or array if (stateObj.iterateIn) { var _loop = function _loop(key) { var ownKeysObj = { ownKeys: hasOwn$1$1.call(value, key) }; _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key); var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); if (hasConstructorOf(val, TypesonPromise)) { promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]); } else if (val !== undefined) { clone[key] = val; } }); }; // eslint-disable-next-line guard-for-in for (var key in value) { _loop(key); } if (runObserver) { runObserver({ endIterateIn: true, end: true }); } } else { // Note: Non-indexes on arrays won't survive stringify so // somewhat wasteful for arrays, but so too is iterating // all numeric indexes on sparse arrays when not wanted // or filtering own keys for positive integers keys(value).forEach(function (key) { var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key); var ownKeysObj = { ownKeys: true }; _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); if (hasConstructorOf(val, TypesonPromise)) { promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]); } else if (val !== undefined) { clone[key] = val; } }); }); if (runObserver) { runObserver({ endIterateOwn: true, end: true }); } } // Iterate array for non-own numeric properties (we can't // replace the prior loop though as it iterates non-integer // keys) if (stateObj.iterateUnsetNumeric) { var vl = value.length; var _loop2 = function _loop2(i) { if (!(i in value)) { // No need to escape numeric var kp = keypath + (keypath ? '.' : '') + i; var ownKeysObj = { ownKeys: false }; _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { var val = _encapsulate(kp, undefined, Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); if (hasConstructorOf(val, TypesonPromise)) { promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, i, stateObj.type]); } else if (val !== undefined) { clone[i] = val; } }); } }; for (var i = 0; i < vl; i++) { _loop2(i); } if (runObserver) { runObserver({ endIterateUnsetNumeric: true, end: true }); } } return clone; } /** * * @param {string} keypath * @param {Any} value * @param {PlainObject} stateObj * @param {GenericArray} promisesData * @param {boolean} plainObject * @param {boolean} resolvingTypesonPromise * @param {function} [runObserver] * @returns {*} */ function replace(keypath, value, stateObj, promisesData, plainObject, resolvingTypesonPromise, runObserver) { // Encapsulate registered types var replacers = plainObject ? that.plainObjectReplacers : that.nonplainObjectReplacers; var i = replacers.length; while (i--) { var replacer = replacers[i]; if (replacer.test(value, stateObj)) { var type = replacer.type; if (that.revivers[type]) { // Record the type only if a corresponding reviver // exists. This is to support specs where only // replacement is done. // For example, ensuring deep cloning of the object, // or replacing a type to its equivalent without // the need to revive it. var existing = types[keypath]; // type can comprise an array of types (see test // "should support intermediate types") types[keypath] = existing ? [type].concat(existing) : type; } Object.assign(stateObj, { type: type, replaced: true }); if ((sync || !replacer.replaceAsync) && !replacer.replace) { if (runObserver) { runObserver({ typeDetected: true }); } return _encapsulate(keypath, value, cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type); } if (runObserver) { runObserver({ replacing: true }); } // Now, also traverse the result in case it contains its // own types to replace var replaceMethod = sync || !replacer.replaceAsync ? 'replace' : 'replaceAsync'; return _encapsulate(keypath, replacer[replaceMethod](value, stateObj), cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type); } } return value; } return promisesDataRoot.length ? sync && opts.throwOnBadSyncType ? function () { throw new TypeError('Sync method requested but async result obtained'); }() : Promise.resolve(checkPromises(ret, promisesDataRoot)).then(finish) : !sync && opts.throwOnBadSyncType ? function () { throw new TypeError('Async method requested but sync result obtained'); }() // If this is a synchronous request for stringification, yet // a promise is the result, we don't want to resolve leading // to an async result, so we return an array to avoid // ambiguity : opts.stringification && sync ? [finish(ret)] : sync ? finish(ret) : Promise.resolve(finish(ret)); } /** * Also sync but throws on non-sync result. * @param {*} obj * @param {object} stateObj * @param {object} opts * @returns {*} */ }, { key: "encapsulateSync", value: function encapsulateSync(obj, stateObj, opts) { return this.encapsulate(obj, stateObj, _objectSpread2({ throwOnBadSyncType: true }, opts, { sync: true })); } /** * @param {*} obj * @param {object} stateObj * @param {object} opts * @returns {*} */ }, { key: "encapsulateAsync", value: function encapsulateAsync(obj, stateObj, opts) { return this.encapsulate(obj, stateObj, _objectSpread2({ throwOnBadSyncType: true }, opts, { sync: false })); } /** * Revive an encapsulated object. * This method is used internally by `Typeson.parse()`. * @param {object} obj - Object to revive. If it has `$types` member, the * properties that are listed there will be replaced with its true type * instead of just plain objects. * @param {object} opts * @throws TypeError If mismatch between sync/async type and result * @returns {Promise|*} If async, returns a Promise that resolves to `*` */ }, { key: "revive", value: function revive(obj, opts) { var types = obj && obj.$types; // No type info added. Revival not needed. if (!types) { return obj; } // Object happened to have own `$types` property but with // no actual types, so we unescape and return that object if (types === true) { return obj.$; } opts = _objectSpread2({ sync: true }, this.options, {}, opts); var _opts3 = opts, sync = _opts3.sync; var keyPathResolutions = []; var stateObj = {}; var ignore$Types = true; // Special when root object is not a trivial Object, it will // be encapsulated in `$`. It will also be encapsulated in // `$` if it has its own `$` property to avoid ambiguity if (types.$ && isPlainObject(types.$)) { obj = obj.$; types = types.$; ignore$Types = false; } var that = this; /** * @callback RevivalReducer * @param {Any} value * @param {string} type * @returns {Any} */ /** * * @param {string} type * @param {Any} val * @returns {[type]} [description] */ function executeReviver(type, val) { var _ref2 = that.revivers[type] || [], _ref3 = _slicedToArray(_ref2, 1), reviver = _ref3[0]; if (!reviver) { throw new Error('Unregistered type: ' + type); } // Only `sync` expected here, as problematic async would // be missing both `reviver` and `reviverAsync`, and // encapsulation shouldn't have added types, so // should have made an early exit if (sync && !('revive' in reviver)) { // Just return value as is return val; } return reviver[sync && reviver.revive ? 'revive' : !sync && reviver.reviveAsync ? 'reviveAsync' : 'revive'](val, stateObj); } /** * * @returns {void|TypesonPromise<void>} */ function revivePlainObjects() { // const references = []; // const reviveTypes = []; var plainObjectTypes = []; Object.entries(types).forEach(function (_ref4) { var _ref5 = _slicedToArray(_ref4, 2), keypath = _ref5[0], type = _ref5[1]; if (type === '#') { /* references.push({ keypath, reference: getByKeyPath(obj, keypath) }); */ return; } [].concat(type).forEach(function (type) { var _ref6 = that.revivers[type] || [null, {}], _ref7 = _slicedToArray(_ref6, 2), plain = _ref7[1].plain; if (!plain) { // reviveTypes.push({keypath, type}); return; } plainObjectTypes.push({ keypath: keypath, type: type }); delete types[keypath]; // Avoid repeating }); }); if (!plainObjectTypes.length) { return undefined; } // console.log(plainObjectTypes.sort(nestedPathsFirst)); /** * @typedef {PlainObject} PlainObjectType * @property {string} keypath * @property {string} type */ return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref8) { var keypath = _ref8.keypath, type = _ref8.type; if (isThenable(possibleTypesonPromise)) { return possibleTypesonPromise.then(function (val) { return reducer(val, { keypath: keypath, type: type }); }); } // console.log('obj', JSON.stringify(keypath), obj); var val = getByKeyPath(obj, keypath); val = executeReviver(type, val); if (hasConstructorOf(val, TypesonPromise)) { return val.then(function (v) { var newVal = setAtKeyPath(obj, keypath, v); if (newVal === v) { obj = newVal; } return undefined; }); } var newVal = setAtKeyPath(obj, keypath, val); if (newVal === val) { obj = newVal; } return undefined; }, undefined // This argument must be explicit ); // references.forEach(({keypath, reference}) => {}); // reviveTypes.sort(nestedPathsFirst).forEach(() => {}); } var revivalPromises = []; /** * * @param {string} keypath * @param {Any} value * @param {?(Array|object)} target * @param {Array|object} [clone] * @param {string} [key] * @returns {Any} */ function _revive(keypath, value, target, clone, key) { if (ignore$Types && keypath === '$types') { return undefined; } var type = types[keypath]; var isArr = isArray(value); if (isArr || isPlainObject(value)) { var _clone = isArr ? new Array(value.length) : {}; // Iterate object or array keys(value).forEach(function (k) { var val = _revive(keypath + (keypath ? '.' : '') + escapeKeyPathComponent(k), value[k], target || _clone, _clone, k); var set = function set(v) { if (hasConstructorOf(v, Undefined)) { _clone[k] = undefined; } else if (v !== undefined) { _clone[k] = v; } return v; }; if (hasConstructorOf(val, TypesonPromise)) { revivalPromises.push(val.then(function (ret) { return set(ret); })); } else { set(val); } }); value = _clone; // Try to resolve cyclic reference as soon as available while (keyPathResolutions.length) { var _keyPathResolutions$ = _slicedToArray(keyPathResolutions[0], 4), _target = _keyPathResolutions$[0], keyPath = _keyPathResolutions$[1], _clone2 = _keyPathResolutions$[2], k = _keyPathResolutions$[3]; var val = getByKeyPath(_target, keyPath); // Typeson.Undefined not expected here as not cyclic or // `undefined` if (val !== undefined) { _clone2[k] = val; } else { break; } keyPathResolutions.splice(0, 1); } } if (!type) { return value; } if (type === '#') { var _ret = getByKeyPath(target, value.slice(1)); if (_ret === undefined) { // Cyclic reference not yet available keyPathResolutions.push([target, value.slice(1), clone, key]); } return _ret; } // `type` can be an array here return [].concat(type).reduce(function reducer(val, typ) { if (hasConstructorOf(val, TypesonPromise)) { return val.then(function (v) { // TypesonPromise here too return reducer(v, typ); }); } return executeReviver(typ, val); }, value); } /** * * @param {Any} retrn * @returns {undefined|Any} */ function checkUndefined(retrn) { return hasConstructorOf(retrn, Undefined) ? undefined : retrn; } var possibleTypesonPromise = revivePlainObjects(); var ret; if (hasConstructorOf(possibleTypesonPromise, TypesonPromise)) { ret = possibleTypesonPromise.then(function () { return obj; }); } else { ret = _revive('', obj, null); if (revivalPromises.length) { // Ensure children resolved ret = TypesonPromise.resolve(ret).then(function (r) { return TypesonPromise.all([// May be a TypesonPromise or not r].concat(revivalPromises)); }).then(function (_ref9) { var _ref10 = _slicedToArray(_ref9, 1), r = _ref10[0]; return r; }); } } return isThenable(ret) ? sync && opts.throwOnBadSyncType ? function () { throw new TypeError('Sync method requested but async result obtained'); }() : hasConstructorOf(ret, TypesonPromise) ? ret.p.then(checkUndefined) : ret : !sync && opts.throwOnBadSyncType ? function () { throw new TypeError('Async method requested but sync result obtained'); }() : sync ? checkUndefined(ret) : Promise.resolve(checkUndefined(ret)); } /** * Also sync but throws on non-sync result. * @param {Any} obj * @param {object} opts * @returns {Any} */ }, { key: "reviveSync", value: function reviveSync(obj, opts) { return this.revive(obj, _objectSpread2({ throwOnBadSyncType: true }, opts, { sync: true })); } /** * @param {Any} obj * @param {object} opts * @returns {Promise} Resolves to `*` */ }, { key: "reviveAsync", value: function reviveAsync(obj, opts) { return this.revive(obj, _objectSpread2({ throwOnBadSyncType: true }, opts, { sync: false })); } /** * Register types. * For examples on how to use this method, see * {@link https://github.com/dfahlander/typeson-registry/tree/master/types}. * @param {object.<string,Function[]>[]} typeSpecSets - Types and * their functions [test, encapsulate, revive]; * @param {object} opts * @returns {Typeson} */ }, { key: "register", value: function register(typeSpecSets, opts) { opts = opts || {}; [].concat(typeSpecSets).forEach(function R(typeSpec) { var _this = this; // Allow arrays of arrays of arrays... if (isArray(typeSpec)) { return typeSpec.map(function (typSpec) { return R.call(_this, typSpec); }); } typeSpec && keys(typeSpec).forEach(function (typeId) { if (typeId === '#') { throw new TypeError('# cannot be used as a type name as it is reserved ' + 'for cyclic objects'); } else if (Typeson.JSON_TYPES.includes(typeId)) { throw new TypeError('Plain JSON object types are reserved as type names'); } var spec = typeSpec[typeId]; var replacers = spec && spec.testPlainObjects ? this.plainObjectReplacers : this.nonplainObjectReplacers; var existingReplacer = replacers.filter(function (r) { return r.type === typeId; }); if (existingReplacer.length) { // Remove existing spec and replace with this one. replacers.splice(replacers.indexOf(existingReplacer[0]), 1); delete this.revivers[typeId]; delete this.types[typeId]; } if (typeof spec === 'function') { // Support registering just a class without replacer/reviver var Class = spec; spec = { test: function test(x) { return x && x.constructor === Class; }, replace: function replace(x) { return _objectSpread2({}, x); }, revive: function revive(x) { return Object.assign(Object.create(Class.prototype), x); } }; } else if (isArray(spec)) { var _spec = spec, _spec2 = _slicedToArray(_spec, 3), test = _spec2[0], replace = _spec2[1], revive = _spec2[2]; spec = { test: test, replace: replace, revive: revive }; } if (!spec || !spec.test) { return; } var replacerObj = { type: typeId, test: spec.test.bind(spec) }; if (spec.replace) { replacerObj.replace = spec.replace.bind(spec); } if (spec.replaceAsync) { replacerObj.replaceAsync = spec.replaceAsync.bind(spec); } var start = typeof opts.fallback === 'number' ? opts.fallback : opts.fallback ? 0 : Infinity; if (spec.testPlainObjects) { this.plainObjectReplacers.splice(start, 0, replacerObj); } else { this.nonplainObjectReplacers.splice(start, 0, replacerObj); } // Todo: We might consider a testAsync type if (spec.revive || spec.reviveAsync) { var reviverObj = {}; if (spec.revive) { reviverObj.revive = spec.revive.bind(spec); } if (spec.reviveAsync) { reviverObj.reviveAsync = spec.reviveAsync.bind(spec); } this.revivers[typeId] = [reviverObj, { plain: spec.testPlainObjects }]; } // Record to be retrieved via public types property. this.types[typeId] = spec; }, this); }, this); return this; } }]); return Typeson; }(); /** * We keep this function minimized so if using two instances of this * library, where one is minimized and one is not, it will still work * with `hasConstructorOf`. * @class */ var Undefined = function Undefined() { _classCallCheck(this, Undefined); }; // eslint-disable-line space-before-blocks Undefined.__typeson__type__ = 'TypesonUndefined'; // The following provide classes meant to avoid clashes with other values // To insist `undefined` should be added Typeson.Undefined = Undefined; // To support async encapsulation/stringification Typeson.Promise = TypesonPromise; // Some fundamental type-checking utilities Typeson.isThenable = isThenable; Typeson.toStringTag = toStringTag; Typeson.hasConstructorOf = hasConstructorOf; Typeson.isObject = isObject; Typeson.isPlainObject = isPlainObject; Typeson.isUserObject = isUserObject; Typeson.escapeKeyPathComponent = escapeKeyPathComponent; Typeson.unescapeKeyPathComponent = unescapeKeyPathComponent; Typeson.getByKeyPath = getByKeyPath; Typeson.getJSONType = getJSONType; Typeson.JSON_TYPES = ['null', 'boolean', 'number', 'string', 'array', 'object']; /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2017 Brett Zamir, 2012 Niklas von Hertzen * Licensed under the MIT license. */ var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index. var lookup = new Uint8Array(256); for (var i = 0; i < chars.length; i++) { lookup[chars.charCodeAt(i)] = i; } var encode$1 = function encode(arraybuffer, byteOffset, length) { if (length === null || length === undefined) { length = arraybuffer.byteLength; // Needed for Safari } var bytes = new Uint8Array(arraybuffer, byteOffset || 0, // Default needed for Safari length); var len = bytes.length; var base64 = ''; for (var _i = 0; _i < len; _i += 3) { base64 += chars[bytes[_i] >> 2]; base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4]; base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6]; base64 += chars[bytes[_i + 2] & 63]; } if (len % 3 === 2) { base64 = base64.substring(0, base64.length - 1) + '='; } else if (len % 3 === 1) { base64 = base64.substring(0, base64.length - 2) + '=='; } return base64; }; var decode$1 = function decode(base64) { var len = base64.length; var bufferLength = base64.length * 0.75; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (base64[base64.length - 1] === '=') { bufferLength--; if (base64[base64.length - 2] === '=') { bufferLength--; } } var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); for (var _i2 = 0; _i2 < len; _i2 += 4) { encoded1 = lookup[base64.charCodeAt(_i2)]; encoded2 = lookup[base64.charCodeAt(_i2 + 1)]; encoded3 = lookup[base64.charCodeAt(_i2 + 2)]; encoded4 = lookup[base64.charCodeAt(_i2 + 3)]; bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return arraybuffer; }; const arraybuffer = { arraybuffer: { test(x) { return Typeson.toStringTag(x) === 'ArrayBuffer'; }, replace(b, stateObj) { if (!stateObj.buffers) { stateObj.buffers = []; } const index = stateObj.buffers.indexOf(b); if (index > -1) { return { index }; } stateObj.buffers.push(b); return encode$1(b); }, revive(b64, stateObj) { if (!stateObj.buffers) { stateObj.buffers = []; } if (typeof b64 === 'object') { return stateObj.buffers[b64.index]; } const buffer = decode$1(b64); stateObj.buffers.push(buffer); return buffer; } } }; // See also typed-arrays! /* globals BigInt */ const bigintObject = { bigintObject: { test(x) { return typeof x === 'object' && Typeson.hasConstructorOf(x, BigInt); }, replace(n) { return String(n); }, revive(s) { // Filed this to avoid error: https://github.com/eslint/eslint/issues/11810 // eslint-disable-next-line no-new-object return new Object(BigInt(s)); } } }; /* globals BigInt */ const bigint = { bigint: { test(x) { return typeof x === 'bigint'; }, replace(n) { return String(n); }, revive(s) { return BigInt(s); } } }; /** * Not currently in use internally, but provided for parity. * @param {ArrayBuffer} buf * @returns {Uint8Array} */ /** * * @param {string} str * @returns {ArrayBuffer} */ function string2arraybuffer(str) { /* // UTF-8 approaches const utf8 = unescape(encodeURIComponent(str)); const arr = new Uint8Array(utf8.length); for (let i = 0; i < utf8.length; i++) { arr[i] = utf8.charCodeAt(i); } return arr.buffer; const utf8 = []; for (let i = 0; i < str.length; i++) { let charcode = str.charCodeAt(i); if (charcode < 0x80) utf8.push(charcode); else if (charcode < 0x800) { utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f)); } else if (charcode < 0xd800 || charcode >= 0xe000) { utf8.push(0xe0 | (charcode >> 12), 0x80 | ((charcode >> 6) & 0x3f), 0x80 | (charcode & 0x3f)); // surrogate pair } else { i++; // UTF-16 encodes 0x10000-0x10FFFF by // subtracting 0x10000 and splitting the // 20 bits of 0x0-0xFFFFF into two halves charcode = 0x10000 + (((charcode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff)); utf8.push(0xf0 | (charcode >> 18), 0x80 | ((charcode >> 12) & 0x3f), 0x80 | ((charcode >> 6) & 0x3f), 0x80 | (charcode & 0x3f)); } } return utf8; */ /* // Working UTF-16 options (equivalents) const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char const bufView = new Uint16Array(buf); for (let i = 0, strLen = str.length; i < strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; */ const array = new Uint8Array(str.length); for (let i = 0; i < str.length; i++) { array[i] = str.charCodeAt(i); // & 0xff; } return array.buffer; } /* globals XMLHttpRequest, Blob, FileReader */ const blob = { blob: { test(x) { return Typeson.toStringTag(x) === 'Blob'; }, replace(b) { // Sync const req = new XMLHttpRequest(); req.overrideMimeType('text/plain; charset=x-user-defined'); // eslint-disable-next-line max-len // eslint-disable-next-line node/no-unsupported-features/node-builtins req.open('GET', URL.createObjectURL(b), false); // Sync req.send(); // Seems not feasible to accurately simulate /* istanbul ignore next */ if (req.status !== 200 && req.status !== 0) { throw new Error('Bad Blob access: ' + req.status); } return { type: b.type, stringContents: req.responseText }; }, revive({ type, stringContents }) { return new Blob([string2arraybuffer(stringContents)], { type }); }, replaceAsync(b) { return new Typeson.Promise((resolve, reject) => { /* if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob reject(new Error('The Blob is closed')); return; } */ const reader = new FileReader(); reader.addEventListener('load', () => { resolve({ type: b.type, stringContents: reader.result }); }); // Seems not feasible to accurately simulate /* istanbul ignore next */ reader.addEventListener('error', () => { reject(reader.error); }); reader.readAsBinaryString(b); }); } } }; /* globals performance */ // The `performance` global is optional /** * @todo We could use `import generateUUID from 'uuid/v4';` (but it needs * crypto library, etc.; `rollup-plugin-node-builtins` doesn't recommend * using its own version and though there is <https://www.npmjs.com/package/crypto-browserify>, * it may be troublesome to bundle and not strongly needed) * @returns {string} */ function generateUUID() { // Adapted from original: public domain/MIT: http://stackoverflow.com/a/8809472/271577 /* istanbul ignore next */ let d = new Date().getTime() + ( // use high-precision timer if available typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : 0); return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/gu, function (c) { /* eslint-disable no-bitwise */ const r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === 'x' ? r : r & 0x3 | 0x8).toString(16); /* eslint-enable no-bitwise */ }); } const cloneableObjectsByUUID = {}; const cloneable = { cloneable: { test(x) { return x && typeof x === 'object' && typeof x[Symbol.for('cloneEncapsulate')] === 'function'; }, replace(clonable) { const encapsulated = clonable[Symbol.for('cloneEncapsulate')](); const uuid = generateUUID(); cloneableObjectsByUUID[uuid] = clonable; return { uuid, encapsulated }; }, revive({ uuid, encapsulated }) { return cloneableObjectsByUUID[uuid][Symbol.for('cloneRevive')](encapsulated); } } }; const dataview = { dataview: { test(x) { return Typeson.toStringTag(x) === 'DataView'; }, replace({ buffer, byteOffset, byteLength }, stateObj) { if (!stateObj.buffers) { stateObj.buffers = []; } const index = stateObj.buffers.indexOf(buffer); if (index > -1) { return { index, byteOffset, byteLength }; } stateObj.buffers.push(buffer); return { encoded: encode$1(buffer), byteOffset, byteLength }; }, revive(b64Obj, stateObj) { if (!stateObj.buffers) { stateObj.buffers = []; } const { byteOffset, byteLength, encoded, index } = b64Obj; let buffer; if ('index' in b64Obj) { buffer = stateObj.buffers[index]; } else { buffer = decode$1(encoded); stateObj.buffers.push(buffer); } return new DataView(buffer, byteOffset, byteLength); } } }; const date = { date: { test(x) { return Typeson.toStringTag(x) === 'Date'; }, replace(dt) { const time = dt.getTime(); if (isNaN(time)) { return 'NaN'; } return time; }, revive(time) { if (time === 'NaN') { return new Date(NaN); } return new Date(time); } } }; const error = { error: { test(x) { return Typeson.toStringTag(x) === 'Error'; }, replace({ name, message }) { return { name, message }; }, revive({ name, message }) { const e = new Error(message); e.name = name; return e; } } }; // See also errors.js that may be registered after having registered this type. /* eslint-env browser, node */ /* istanbul ignore next */ const _global = typeof self === 'undefined' ? global : self; const errors = {}; // Comprises all built-in errors. ['TypeError', 'RangeError', 'SyntaxError', 'ReferenceError', 'EvalError', 'URIError', 'InternalError' // non-standard ].forEach(errName => { const Cnstrctr = _global[errName]; if (Cnstrctr) { errors[errName.toLowerCase()] = { test(x) { return Typeson.hasConstructorOf(x, Cnstrctr); }, replace(e) { return e.message; }, revive(message) { return new Cnstrctr(message); } }; } }); /* globals XMLHttpRequest, File, FileReader */ const file = { file: { test(x) { return Typeson.toStringTag(x) === 'File'; }, replace(f) { // Sync const req = new XMLHttpRequest(); req.overrideMimeType('text/plain; charset=x-user-defined'); // eslint-disable-next-line max-len // eslint-disable-next-line node/no-unsupported-features/node-builtins req.open('GET', URL.createObjectURL(f), false); // Sync req.send(); // Seems not feasible to accurately simulate /* istanbul ignore next */ if (req.status !== 200 && req.status !== 0) { throw new Error('Bad File access: ' + req.status); } return { type: f.type, stringContents: req.responseText, name: f.name, lastModified: f.lastModified }; }, revive({ name, type, stringContents, lastModified }) { return new File([string2arraybuffer(stringContents)], name, { type, lastModified }); }, replaceAsync(f) { return new Typeson.Promise(function (resolve, reject) { /* if (f.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob reject(new Error('The File is closed')); return; } */ const reader = new FileReader(); reader.addEventListener('load', function () { resolve({ type: f.type, stringContents: reader.result, name: f.name, lastModified: f.lastModified }); }); // Seems not feasible to accurately simulate /* istanbul ignore next */ reader.addEventListener('error', function () { reject(reader.error); }); reader.readAsBinaryString(f); }); } } }; const filelist = { file: file.file, filelist: { test(x) { return Typeson.toStringTag(x) === 'FileList'; }, replace(fl) { const arr = []; for (let i = 0; i < fl.length; i++) { arr[i] = fl.item(i); } return arr; }, revive(o) { /** * `FileList` polyfill. */ class FileList { /** * Set private properties and length. */ constructor() { // eslint-disable-next-line prefer-rest-params this._files = arguments[0]; this.length = this._files.length; } /** * @param {Integer} index * @returns {File} */ item(index) { return this._files[index]; } /* eslint-disable class-methods-use-this */ /** * @returns {"FileList"} */ get [Symbol.toStringTag]() { /* eslint-enable class-methods-use-this */ return 'FileList'; } } return new FileList(o); } } }; /* globals createImageBitmap */ const imagebitmap = { imagebitmap: { test(x) { return Typeson.toStringTag(x) === 'ImageBitmap' || // In Node, our polyfill sets the dataset on a canvas // element as JSDom no longer allows overriding toStringTag x && x.dataset && x.dataset.toStringTag === 'ImageBitmap'; }, replace(bm) { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); ctx.drawImage(bm, 0, 0); // Although `width` and `height` are part of `ImageBitMap`, // these will be auto-created for us when reviving with the // data URL (and they are not settable even if they weren't) // return { // width: bm.width, height: bm.height, dataURL: canvas.toDataURL() // }; return canvas.toDataURL(); }, revive(o) { /* var req = new XMLHttpRequest(); req.open('GET', o, false); // Sync if (req.status !== 200 && req.status !== 0) { throw new Error('Bad ImageBitmap access: ' + req.status); } req.send(); return req.responseText; */ const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = document.createElement('img'); // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577 img.addEventListener('load', function () { ctx.drawImage(img, 0, 0); }); img.src = o; // Works in contexts allowing an `ImageBitmap` (We might use // `OffscreenCanvas.transferToBitmap` when supported) return canvas; }, reviveAsync(o) { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = document.createElement('img'); // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577 img.addEventListener('load', function () { ctx.drawImage(img, 0, 0); }); img.src = o; // o.dataURL; return createImageBitmap(canvas); // Returns a promise } } }; /* globals ImageData */ const imagedata = { imagedata: { test(x) { return Typeson.toStringTag(x) === 'ImageData'; }, replace(d) { return { // Ensure `length` gets preserved for revival array: [...d.data], width: d.width, height: d.height }; }, revive(o) { return new ImageData(new Uint8ClampedArray(o.array), o.width, o.height); } } }; const infinity = { infinity: { test(x) { return x === Infinity; }, replace(n) { return 'Infinity'; }, revive(s) { return Infinity; } } }; const IntlCollator = { test(x) { return Typeson.hasConstructorOf(x, Intl.Collator); }, replace(c) { return c.resolvedOptions(); }, revive(options) { return new Intl.Collator(options.locale, options); } }; const IntlDateTimeFormat = { test(x) { return Typeson.hasConstructorOf(x, Intl.DateTimeFormat); }, replace(dtf) { return dtf.resolvedOptions(); }, revive(options) { return new Intl.DateTimeFormat(options.locale, options); } }; const IntlNumberFormat = { test(x) { return Typeson.hasConstructorOf(x, Intl.NumberFormat); }, replace(nf) { return nf.resolvedOptions(); }, revive(options) { return new Intl.NumberFormat(options.locale, options); } }; const intlTypes = { IntlCollator, IntlDateTimeFormat, IntlNumberFormat }; const map$1 = { map: { test(x) { return Typeson.toStringTag(x) === 'Map'; }, replace(mp) { return [...mp.entries()]; }, revive(entries) { return new Map(entries); } } }; const nan = { nan: { test(x) { return typeof x === 'number' && isNaN(x); }, replace(n) { return 'NaN'; }, revive(s) { return NaN; } } }; const negativeInfinity = { negativeInfinity: { test(x) { return x === -Infinity; }, replace(n) { return '-Infinity'; }, revive(s) { return -Infinity; } } }; const nonbuiltinIgnore = { nonbuiltinIgnore: { test(x) { return x && typeof x === 'object' && !Array.isArray(x) && !['Object', // `Proxy` and `Reflect`, two other built-in objects, will also // have a `toStringTag` of `Object`; we don't want built-in // function objects, however 'Boolean', 'Number', 'String', 'Error', 'RegExp', 'Math', 'Date', 'Map', 'Set', 'JSON', 'ArrayBuffer', 'SharedArrayBuffer', 'DataView', 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'Promise', 'String Iterator', 'Array Iterator', 'Map Iterator', 'Set Iterator', 'WeakMap', 'WeakSet', 'Atomics', 'Module'].includes(Typeson.toStringTag(x)); }, replace(rexp) {// Not in use } } }; // This module is for objectified primitives (such as `new Number(3)` or const primitiveObjects = { // String Object (not primitive string which need no type spec) StringObject: { test(x) { return Typeson.toStringTag(x) === 'String' && typeof x === 'object'; }, replace(s) { return String(s); }, // convert to primitive string revive(s) { return new String(s); } // Revive to an objectified string }, // Boolean Object (not primitive boolean which need no type spec) BooleanObject: { test(x) { return Typeson.toStringTag(x) === 'Boolean' && typeof x === 'object'; }, replace(b) { return Boolean(b); }, // convert to primitive boolean revive(b) { // Revive to an objectified Boolean return new Boolean(b); } }, // Number Object (not primitive number which need no type spec) NumberObject: { test(x) { return Typeson.toStringTag(x) === 'Number' && typeof x === 'object'; }, replace(n) { return Number(n); }, // convert to primitive number revive(n) { return new Number(n); } // Revive to an objectified number } }; const regexp = { regexp: { test(x) { return Typeson.toStringTag(x) === 'RegExp'; }, replace(rexp) { return { source: rexp.source, flags: (rexp.global ? 'g' : '') + (rexp.ignoreCase ? 'i' : '') + (rexp.multiline ? 'm' : '') + (rexp.sticky ? 'y' : '') + (rexp.unicode ? 'u' : '') }; }, revive({ source, flags }) { return new RegExp(source, flags); } } }; // Here we allow the exact same non-plain object, function, and symbol const resurrectableObjectsByUUID = {}; const resurrectable = { resurrectable: { test(x) { return x && !Array.isArray(x) && ['object', 'function', 'symbol'].includes(typeof x); }, replace(rsrrctble) { const uuid = generateUUID(); resurrectableObjectsByUUID[uuid] = rsrrctble; return uuid; }, revive(serializedResurrectable) { return resurrectableObjectsByUUID[serializedResurrectable]; } } }; const set = { set: { test(x) { return Typeson.toStringTag(x) === 'Set'; }, replace(st) { return [...st.values()]; }, revive(values) { return new Set(values); } } }; /* eslint-env browser, node */ /* istanbul ignore next */ const _global$1 = typeof self === 'undefined' ? global : self; // Support all kinds of typed arrays (views of ArrayBuffers) const typedArraysSocketIO = {}; ['Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array'].forEach(function (typeName) { const arrType = typeName; const TypedArray = _global$1[typeName]; /* istanbul ignore if */ if (!TypedArray) { return; } typedArraysSocketIO[typeName.toLowerCase()] = { test(x) { return Typeson.toStringTag(x) === arrType; }, replace(a) { return (a.byteOffset === 0 && a.byteLength === a.buffer.byteLength ? a // socket.io supports streaming ArrayBuffers. // If we have a typed array representing a portion // of the buffer, we need to clone // the buffer before leaving it to socket.io. : a.slice(0)).buffer; }, revive(buf) { // One may configure socket.io to revive binary data as // Buffer or Blob. // We should therefore not rely on that the instance we // get here is an ArrayBuffer // If not, let's assume user wants to receive it as // configured with socket.io. return Typeson.toStringTag(buf) === 'ArrayBuffer' ? new TypedArray(buf) : buf; } }; }); /* eslint-env browser, node */ /* istanbul ignore next */ const _global$2 = typeof self === 'undefined' ? global : self; const typedArrays = {}; ['Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array'].forEach(function (typeName) { const arrType = typeName; const TypedArray = _global$2[arrType]; /* istanbul ignore if */ if (!TypedArray) { return; } typedArrays[typeName.toLowerCase()] = { test(x) { return Typeson.toStringTag(x) === arrType; }, replace({ buffer, byteOffset, length: l }, stateObj) { if (!stateObj.buffers) { stateObj.buffers = []; } const index = stateObj.buffers.indexOf(buffer); if (index > -1) { return { index, byteOffset, length: l }; } stateObj.buffers.push(buffer); return { encoded: encode$1(buffer), byteOffset, length: l }; }, revive(b64Obj, stateObj) { if (!stateObj.buffers) { stateObj.buffers = []; } const { byteOffset, length: len, encoded, index } = b64Obj; let buffer; if ('index' in b64Obj) { buffer = stateObj.buffers[index]; } else { buffer = decode$1(encoded); stateObj.buffers.push(buffer); } return new TypedArray(buffer, byteOffset, len); } }; }); // This does not preserve `undefined` in sparse arrays; see the `undefined` const undef = { undef: { test(x, stateObj) { return typeof x === 'undefined' && (stateObj.ownKeys || !('ownKeys' in stateObj)); }, replace(n) { return 0; }, revive(s) { // Will add `undefined` (returning `undefined` would instead // avoid explicitly setting) return new Typeson.Undefined(); } } }; function _defineProperty$1(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; } function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } const userObject = { userObject: { test(x, stateObj) { return Typeson.isUserObject(x); }, replace(n) { return _objectSpread2$1({}, n); }, revive(s) { return s; } } }; const arrayNonindexKeys = [{ arrayNonindexKeys: { testPlainObjects: true, test(x, stateObj) { if (Array.isArray(x)) { if ( // By avoiding serializing arrays into objects which // have only positive-integer keys, we reduce // size and improve revival performance; arrays with // non-index keys will be larger however Object.keys(x).some(k => { // No need to check for `isNaN` or // `isNaN(parseInt())` as `NaN` will be treated // as a string. // No need to do check as `parseInt(Number())` // since scientific notation will be // pre-resolved if a number was given, and it // will otherwise be a string return String(parseInt(k)) !== k; })) { stateObj.iterateIn = 'object'; stateObj.addLength = true; } return true; } return false; }, replace(a, stateObj) { // Catch sparse undefined stateObj.iterateUnsetNumeric = true; return a; }, revive(o) { if (Array.isArray(o)) { return o; } const arr = []; // No map here as may be a sparse array (including // with `length` set) // Todo: Reenable when Node `engines` >= 7 // Object.entries(o).forEach(([key, val]) => { Object.keys(o).forEach(key => { const val = o[key]; arr[key] = val; }); return arr; } } }, { sparseUndefined: { test(x, stateObj) { return typeof x === 'undefined' && stateObj.ownKeys === false; }, replace(n) { return 0; }, revive(s) { return undefined; } // Will avoid adding anything } }]; const specialNumbers = [nan, infinity, negativeInfinity]; /* This preset includes types that are built-in into the JavaScript language itself, this should work universally. Types that were added in ES6 or beyond will be checked before inclusion so that this module can be consumed by both ES5 and ES6 environments. Some types cannot be encapsulated because their inner state is private: `WeakMap`, `WeakSet`. The Function type is not included because their closures would not be serialized, so a revived Function that uses closures would not behave as expected. Symbols are similarly not included. */ const expObj = [undef, // ES5 arrayNonindexKeys, primitiveObjects, specialNumbers, date, error, errors, regexp].concat( // ES2015 (ES6) /* istanbul ignore next */ typeof Map === 'function' ? map$1 : [], /* istanbul ignore next */ typeof Set === 'function' ? set : [], /* istanbul ignore next */ typeof ArrayBuffer === 'function' ? arraybuffer : [], /* istanbul ignore next */ typeof Uint8Array === 'function' ? typedArrays : [], /* istanbul ignore next */ typeof DataView === 'function' ? dataview : [], /* istanbul ignore next */ typeof Intl !== 'undefined' ? intlTypes : [], /* istanbul ignore next */ typeof BigInt !== 'undefined' ? [bigint, bigintObject] : []); /* When communicating via `postMessage()` (`Worker.postMessage()` or `window.postMessage()`), the browser will use a similar algorithm as Typeson does to encapsulate and revive all items in the structure (aka the structured clone algorithm). This algorithm supports all built-in types as well as many DOM types. Therefore, only types that are not included in the structured clone algorithm need to be registered, which is: * Error * Specific Errors like SyntaxError, TypeError, etc. * Any custom type you want to send across window- or worker boundraries This preset will only include the Error types and you can register your custom types after having registered these. */ const postmessage = [error, errors]; const socketio = [expObj, // Leave ArrayBuffer as is, and let socket.io stream it instead. { arraybuffer: null }, // Encapsulate TypedArrays in ArrayBuffers instead of base64 strings. typedArraysSocketIO]; const sparseUndefined = [{ sparseArrays: { testPlainObjects: true, test(x) { return Array.isArray(x); }, replace(a, stateObj) { stateObj.iterateUnsetNumeric = true; return a; } } }, { sparseUndefined: { test(x, stateObj) { return typeof x === 'undefined' && stateObj.ownKeys === false; }, replace(n) { return 0; }, revive(s) { return undefined; } // Will avoid adding anything } }]; /* This preset includes types for the Structured Cloning Algorithm. */ const expObj$1 = [// Todo: Might also register synchronous `ImageBitmap` and // `Blob`/`File`/`FileList`? // ES5 userObject, // Processed last (non-builtin) undef, arrayNonindexKeys, primitiveObjects, specialNumbers, date, regexp, // Non-built-ins imagedata, imagebitmap, // Async return file, filelist, blob].concat( // ES2015 (ES6) /* istanbul ignore next */ typeof Map === 'function' ? map$1 : [], /* istanbul ignore next */ typeof Set === 'function' ? set : [], /* istanbul ignore next */ typeof ArrayBuffer === 'function' ? arraybuffer : [], /* istanbul ignore next */ typeof Uint8Array === 'function' ? typedArrays : [], /* istanbul ignore next */ typeof DataView === 'function' ? dataview : [], /* istanbul ignore next */ typeof Intl !== 'undefined' ? intlTypes : [], /* istanbul ignore next */ typeof BigInt !== 'undefined' ? [bigint, bigintObject] : []); /* globals DOMException */ var structuredCloningThrowing = expObj$1.concat({ // Todo: Waiting on https://github.com/whatwg/html/issues/5158 /* checkDataCloneExceptionPrototype: { testPlainObjects: true, test (val) { // A non-array exotic object but note this is not throwing in // Chrome `postMessage` if (val === Object.prototype) { throw new DOMException( 'The object cannot be cloned.', 'DataCloneError' ); } return false; } }, */ checkDataCloneException: { test(val) { // Should also throw with: // 1. `IsDetachedBuffer` (a process not called within the // ECMAScript spec) // 2. `IsCallable` (covered by `typeof === 'function'` or a // function's `toStringTag`) // 3. internal slots besides [[Prototype]] or [[Extensible]] (e.g., // [[PromiseState]] or [[WeakMapData]]) // 4. exotic object (e.g., `Proxy`) (which does not have default // behavior for one or more of the essential internal methods // that are limited to the following for non-function objects // (we auto-exclude functions): // [[GetPrototypeOf]],[[SetPrototypeOf]],[[IsExtensible]], // [[PreventExtensions]],[[GetOwnProperty]], // [[DefineOwnProperty]],[[HasProperty]], // [[Get]],[[Set]],[[Delete]],[[OwnPropertyKeys]]); // except for the standard, built-in exotic objects, we'd need // to know whether these methods had distinct behaviors // Note: There is no apparent way for us to detect a `Proxy` and // reject (Chrome at least is not rejecting anyways) const stringTag = {}.toString.call(val).slice(8, -1); if ([// Symbol's `toStringTag` is only "Symbol" for its initial // value, so we check `typeof` 'symbol', // All functions including bound function exotic objects 'function'].includes(typeof val) || [// A non-array exotic object 'Arguments', // A non-array exotic object 'Module', // `Error` and other errors have the [[ErrorData]] internal // slot and give "Error" 'Error', // Promise instances have an extra slot ([[PromiseState]]) // but not throwing in Chrome `postMessage` 'Promise', // WeakMap instances have an extra slot ([[WeakMapData]]) // but not throwing in Chrome `postMessage` 'WeakMap', // WeakSet instances have an extra slot ([[WeakSetData]]) // but not throwing in Chrome `postMessage` 'WeakSet', // HTML-SPECIFIC 'Event', // Also in Node `worker_threads` (currently experimental) 'MessageChannel'].includes(stringTag) || /* // isClosed is no longer documented ((stringTag === 'Blob' || stringTag === 'File') && val.isClosed) || */ val && typeof val === 'object' && // Duck-type DOM node objects (non-array exotic? // objects which cannot be cloned by the SCA) typeof val.nodeType === 'number' && typeof val.insertBefore === 'function') { throw new DOMException('The object cannot be cloned.', 'DataCloneError'); } return false; } } }); const undef$1 = [sparseUndefined, undef]; const universal = [expObj // TODO: Add types that are de-facto universal even though not // built-in into ecmasript standard. ]; // This file is auto-generated from `build.js` Typeson.types = { arraybuffer, bigintObject, bigint, blob, cloneable, dataview, date, error, errors, file, filelist, imagebitmap, imagedata, infinity, intlTypes, map: map$1, nan, negativeInfinity, nonbuiltinIgnore, primitiveObjects, regexp, resurrectable, set, typedArraysSocketio: typedArraysSocketIO, typedArrays, undef, userObject }; Typeson.presets = { arrayNonindexKeys, builtin: expObj, postmessage, socketio, sparseUndefined, specialNumbers, structuredCloningThrowing, structuredCloning: expObj$1, undef: undef$1, universal }; let typeson = new Typeson().register(Typeson.presets.structuredCloningThrowing); function register(func) { typeson = new Typeson().register(func(Typeson.presets.structuredCloningThrowing)); } // We are keeping the callback approach for now in case we wish to reexpose // `Blob`, `File`, `FileList` asynchronously (though in such a case, we // should probably refactor as a Promise) function encode$2(obj, func) { let ret; try { ret = typeson.stringifySync(obj); } catch (err) { // SCA in typeson-registry using `DOMException` which is not defined (e.g., in Node) if (Typeson.hasConstructorOf(err, ReferenceError) || // SCA in typeson-registry threw a cloning error and we are in a // supporting environment (e.g., the browser) where `ShimDOMException` is // an alias for `DOMException`; if typeson-registry ever uses our shim // to throw, we can use this condition alone. Typeson.hasConstructorOf(err, ShimDOMException$1)) { throw createDOMException('DataCloneError', 'The object cannot be cloned.'); } // We should rethrow non-cloning exceptions like from // throwing getters (as in the W3C test, key-conversion-exceptions.htm) throw err; } if (func) func(ret); return ret; } function decode$2(obj) { return typeson.parse(obj); } function clone(val) { // We don't return the intermediate `encode` as we'll need to reencode // the clone as it may differ return decode$2(encode$2(val)); } var Sca = /*#__PURE__*/Object.freeze({ __proto__: null, encode: encode$2, decode: decode$2, clone: clone, register: register }); const readonlyProperties$4 = ['objectStore', 'keyPath', 'multiEntry', 'unique']; /* eslint-disable jsdoc/check-param-names */ /** * IDB Index. * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex * @param {IDBObjectStore} store * @param {IDBIndexProperties} indexProperties * @class */ function IDBIndex() { /* eslint-enable jsdoc/check-param-names */ throw new TypeError('Illegal constructor'); } const IDBIndexAlias = IDBIndex; IDBIndex.__createInstance = function (store, indexProperties) { function IDBIndex() { const me = this; me[Symbol.toStringTag] = 'IDBIndex'; defineReadonlyProperties(me, readonlyProperties$4); me.__objectStore = store; me.__name = me.__originalName = indexProperties.columnName; me.__keyPath = Array.isArray(indexProperties.keyPath) ? indexProperties.keyPath.slice() : indexProperties.keyPath; const { optionalParams } = indexProperties; me.__multiEntry = Boolean(optionalParams && optionalParams.multiEntry); me.__unique = Boolean(optionalParams && optionalParams.unique); me.__deleted = Boolean(indexProperties.__deleted); me.__objectStore.__cursors = indexProperties.cursors || []; Object.defineProperty(me, '__currentName', { get() { return '__pendingName' in me ? me.__pendingName : me.name; } }); Object.defineProperty(me, 'name', { enumerable: false, configurable: false, get() { return this.__name; }, set(newName) { const me = this; newName = convertToDOMString(newName); const oldName = me.name; IDBTransaction.__assertVersionChange(me.objectStore.transaction); IDBTransaction.__assertActive(me.objectStore.transaction); IDBIndexAlias.__invalidStateIfDeleted(me); IDBObjectStore.__invalidStateIfDeleted(me); if (newName === oldName) { return; } if (me.objectStore.__indexes[newName] && !me.objectStore.__indexes[newName].__deleted && !me.objectStore.__indexes[newName].__pendingDelete) { throw createDOMException('ConstraintError', 'Index "' + newName + '" already exists on ' + me.objectStore.__currentName); } me.__name = newName; const { objectStore } = me; delete objectStore.__indexes[oldName]; objectStore.__indexes[newName] = me; objectStore.indexNames.splice(objectStore.indexNames.indexOf(oldName), 1, newName); const storeHandle = objectStore.transaction.__storeHandles[objectStore.name]; const oldIndexHandle = storeHandle.__indexHandles[oldName]; oldIndexHandle.__name = newName; // Fix old references storeHandle.__indexHandles[newName] = oldIndexHandle; // Ensure new reference accessible me.__pendingName = oldName; const colInfoToPreserveArr = [['key', 'BLOB ' + (objectStore.autoIncrement ? 'UNIQUE, inc INTEGER PRIMARY KEY AUTOINCREMENT' : 'PRIMARY KEY')], ['value', 'BLOB']].concat([...objectStore.indexNames].filter(indexName => indexName !== newName).map(indexName => [escapeIndexNameForSQL(indexName), 'BLOB'])); me.__renameIndex(objectStore, oldName, newName, colInfoToPreserveArr, function (tx, success) { IDBIndexAlias.__updateIndexList(store, tx, function (store) { delete storeHandle.__pendingName; success(store); }); }); } }); } IDBIndex.prototype = IDBIndexAlias.prototype; return new IDBIndex(); }; IDBIndex.__invalidStateIfDeleted = function (index, msg) { if (index.__deleted || index.__pendingDelete || index.__pendingCreate && index.objectStore.transaction && index.objectStore.transaction.__errored) { throw createDOMException('InvalidStateError', msg || 'This index has been deleted'); } }; /** * Clones an IDBIndex instance for a different IDBObjectStore instance. * @param {IDBIndex} index * @param {IDBObjectStore} store * @protected * @returns {IDBIndex} */ IDBIndex.__clone = function (index, store) { const idx = IDBIndex.__createInstance(store, { columnName: index.name, keyPath: index.keyPath, optionalParams: { multiEntry: index.multiEntry, unique: index.unique } }); ['__pendingCreate', '__pendingDelete', '__deleted', '__originalName', '__recreated'].forEach(p => { idx[p] = index[p]; }); return idx; }; /** * Creates a new index on an object store. * @param {IDBObjectStore} store * @param {IDBIndex} index * @returns {void} * @protected */ IDBIndex.__createIndex = function (store, index) { const indexName = index.name; const storeName = store.__currentName; const idx = store.__indexes[indexName]; index.__pendingCreate = true; // Add the index to the IDBObjectStore store.indexNames.push(indexName); store.__indexes[indexName] = index; // We add to indexes as needs to be available, e.g., if there is a subsequent deleteIndex call let indexHandle = store.__indexHandles[indexName]; if (!indexHandle || index.__pendingDelete || index.__deleted || indexHandle.__pendingDelete || indexHandle.__deleted) { indexHandle = store.__indexHandles[indexName] = IDBIndex.__clone(index, store); } // Create the index in WebSQL const { transaction } = store; transaction.__addNonRequestToTransactionQueue(function createIndex(tx, args, success, failure) { const columnExists = idx && (idx.__deleted || idx.__recreated); // This check must occur here rather than earlier as properties may not have been set yet otherwise let indexValues = {}; function error(tx, err) { failure(createDOMException('UnknownError', 'Could not create index "' + indexName + '"' + err.code + '::' + err.message, err)); } function applyIndex(tx) { // Update the object store's index list IDBIndex.__updateIndexList(store, tx, function () { // Add index entries for all existing records tx.executeSql('SELECT "key", "value" FROM ' + escapeStoreNameForSQL(storeName), [], function (tx, data) { CFG.DEBUG && console.log('Adding existing ' + storeName + ' records to the ' + indexName + ' index'); addIndexEntry(0); function addIndexEntry(i) { if (i < data.rows.length) { try { const value = decode$2(unescapeSQLiteResponse(data.rows.item(i).value)); let indexKey = extractKeyValueDecodedFromValueUsingKeyPath(value, index.keyPath, index.multiEntry); // Todo: Do we need this stricter error checking? if (indexKey.invalid || indexKey.failure) { // Todo: Do we need invalid checks and should we instead treat these as being duplicates? throw new Error('Go to catch; ignore bad indexKey'); } indexKey = encode(indexKey.value, index.multiEntry); if (index.unique) { if (indexValues[indexKey]) { indexValues = {}; failure(createDOMException('ConstraintError', 'Duplicate values already exist within the store')); return; } indexValues[indexKey] = true; } tx.executeSql('UPDATE ' + escapeStoreNameForSQL(storeName) + ' SET ' + escapeIndexNameForSQL(indexName) + ' = ? WHERE "key" = ?', [escapeSQLiteStatement(indexKey), data.rows.item(i).key], function (tx, data) { addIndexEntry(i + 1); }, error); } catch (e) { // Not a valid value to insert into index, so just continue addIndexEntry(i + 1); } } else { delete index.__pendingCreate; delete indexHandle.__pendingCreate; if (index.__deleted) { delete index.__deleted; delete indexHandle.__deleted; index.__recreated = true; indexHandle.__recreated = true; } indexValues = {}; success(store); } } }, error); }, error); } const escapedStoreNameSQL = escapeStoreNameForSQL(storeName); const escapedIndexNameSQL = escapeIndexNameForSQL(index.name); function addIndexSQL(tx) { if (!CFG.useSQLiteIndexes) { applyIndex(tx); return; } tx.executeSql('CREATE INDEX IF NOT EXISTS "' + // The escaped index name must be unique among indexes in the whole database; // so we prefix with store name; as prefixed, will also not conflict with // index on `key` // Avoid quotes and separate with special escape sequence escapedStoreNameSQL.slice(1, -1) + '^5' + escapedIndexNameSQL.slice(1, -1) + '" ON ' + escapedStoreNameSQL + '(' + escapedIndexNameSQL + ')', [], applyIndex, error); } if (columnExists) { // For a previously existing index, just update the index entries in the existing column; // no need to add SQLite index to it either as should already exist applyIndex(tx); } else { // For a new index, add a new column to the object store, then apply the index const sql = ['ALTER TABLE', escapedStoreNameSQL, 'ADD', escapedIndexNameSQL, 'BLOB'].join(' '); CFG.DEBUG && console.log(sql); tx.executeSql(sql, [], addIndexSQL, error); } }, undefined, store); }; /** * Deletes an index from an object store. * @param {IDBObjectStore} store * @param {IDBIndex} index * @protected * @returns {void} */ IDBIndex.__deleteIndex = function (store, index) { // Remove the index from the IDBObjectStore index.__pendingDelete = true; const indexHandle = store.__indexHandles[index.name]; if (indexHandle) { indexHandle.__pendingDelete = true; } store.indexNames.splice(store.indexNames.indexOf(index.name), 1); // Remove the index in WebSQL const { transaction } = store; transaction.__addNonRequestToTransactionQueue(function deleteIndex(tx, args, success, failure) { function error(tx, err) { failure(createDOMException('UnknownError', 'Could not delete index "' + index.name + '"', err)); } function finishDeleteIndex() { // Update the object store's index list IDBIndex.__updateIndexList(store, tx, function (store) { delete index.__pendingDelete; delete index.__recreated; index.__deleted = true; if (indexHandle) { indexHandle.__deleted = true; delete indexHandle.__pendingDelete; } success(store); }, error); } if (!CFG.useSQLiteIndexes) { finishDeleteIndex(); return; } tx.executeSql('DROP INDEX IF EXISTS ' + sqlQuote(escapeStoreNameForSQL(store.name).slice(1, -1) + '^5' + escapeIndexNameForSQL(index.name).slice(1, -1)), [], finishDeleteIndex, error); }, undefined, store); }; /** * Updates index list for the given object store. * @param {IDBObjectStore} store * @param {object} tx * @param {function} success * @param {function} failure * @returns {void} */ IDBIndex.__updateIndexList = function (store, tx, success, failure) { const indexList = {}; for (let i = 0; i < store.indexNames.length; i++) { const idx = store.__indexes[store.indexNames[i]]; /** @type {IDBIndexProperties} **/ indexList[idx.name] = { columnName: idx.name, keyPath: idx.keyPath, optionalParams: { unique: idx.unique, multiEntry: idx.multiEntry }, deleted: Boolean(idx.deleted) }; } CFG.DEBUG && console.log('Updating the index list for ' + store.__currentName, indexList); tx.executeSql('UPDATE __sys__ SET "indexList" = ? WHERE "name" = ?', [JSON.stringify(indexList), escapeSQLiteStatement(store.__currentName)], function () { success(store); }, failure); }; /** * Retrieves index data for the given key. * @param {*|IDBKeyRange} range * @param {string} opType * @param {boolean} nullDisallowed * @param {number} count * @returns {IDBRequest} * @private */ IDBIndex.prototype.__fetchIndexData = function (range, opType, nullDisallowed, count) { const me = this; if (count !== undefined) { count = enforceRange(count, 'unsigned long'); } IDBIndex.__invalidStateIfDeleted(me); IDBObjectStore.__invalidStateIfDeleted(me.objectStore); if (me.objectStore.__deleted) { throw createDOMException('InvalidStateError', "This index's object store has been deleted"); } IDBTransaction.__assertActive(me.objectStore.transaction); if (nullDisallowed && isNullish(range)) { throw createDOMException('DataError', 'No key or range was specified'); } const fetchArgs = buildFetchIndexDataSQL(nullDisallowed, me, range, opType, false); return me.objectStore.transaction.__addToTransactionQueue(function (...args) { executeFetchIndexData(count, ...fetchArgs, ...args); }, undefined, me); }; /* eslint-disable jsdoc/check-param-names */ /** * Opens a cursor over the given key range. * @param {*|IDBKeyRange} query * @param {string} direction * @returns {IDBRequest} */ IDBIndex.prototype.openCursor = function () /* query, direction */ { /* eslint-enable jsdoc/check-param-names */ const me = this; // eslint-disable-next-line prefer-rest-params const [query, direction] = arguments; const cursor = IDBCursorWithValue.__createInstance(query, direction, me.objectStore, me, escapeIndexNameForSQLKeyColumn(me.name), 'value'); me.__objectStore.__cursors.push(cursor); return cursor.__request; }; /* eslint-disable jsdoc/check-param-names */ /** * Opens a cursor over the given key range. The cursor only includes key values, not data. * @param {*|IDBKeyRange} query * @param {string} direction * @returns {IDBRequest} */ IDBIndex.prototype.openKeyCursor = function () /* query, direction */ { /* eslint-enable jsdoc/check-param-names */ const me = this; // eslint-disable-next-line prefer-rest-params const [query, direction] = arguments; const cursor = IDBCursor.__createInstance(query, direction, me.objectStore, me, escapeIndexNameForSQLKeyColumn(me.name), 'key'); me.__objectStore.__cursors.push(cursor); return cursor.__request; }; IDBIndex.prototype.get = function (query) { if (!arguments.length) { // Per https://heycam.github.io/webidl/ throw new TypeError('A parameter was missing for `IDBIndex.get`.'); } return this.__fetchIndexData(query, 'value', true); }; IDBIndex.prototype.getKey = function (query) { if (!arguments.length) { // Per https://heycam.github.io/webidl/ throw new TypeError('A parameter was missing for `IDBIndex.getKey`.'); } return this.__fetchIndexData(query, 'key', true); }; IDBIndex.prototype.getAll = function () /* query, count */ { // eslint-disable-next-line prefer-rest-params const [query, count] = arguments; return this.__fetchIndexData(query, 'value', false, count); }; IDBIndex.prototype.getAllKeys = function () /* query, count */ { // eslint-disable-next-line prefer-rest-params const [query, count] = arguments; return this.__fetchIndexData(query, 'key', false, count); }; IDBIndex.prototype.count = function () /* query */ { const me = this; // eslint-disable-next-line prefer-rest-params const query = arguments[0]; // With the exception of needing to check whether the index has been // deleted, we could, for greater spec parity (if not accuracy), // just call: // `return me.__objectStore.count(query);` if (instanceOf(query, IDBKeyRange)) { // Todo: Do we need this block? // We don't need to add to cursors array since has the count parameter which won't cache return IDBCursorWithValue.__createInstance(query, 'next', me.objectStore, me, escapeIndexNameForSQLKeyColumn(me.name), 'value', true).__request; } return me.__fetchIndexData(query, 'count', false); }; IDBIndex.prototype.__renameIndex = function (store, oldName, newName, colInfoToPreserveArr = [], cb = null) { const newNameType = 'BLOB'; const storeName = store.__currentName; const escapedStoreNameSQL = escapeStoreNameForSQL(storeName); const escapedNewIndexNameSQL = escapeIndexNameForSQL(newName); const escapedTmpStoreNameSQL = sqlQuote('tmp_' + escapeStoreNameForSQL(storeName).slice(1, -1)); const colNamesToPreserve = colInfoToPreserveArr.map(colInfo => colInfo[0]); const colInfoToPreserve = colInfoToPreserveArr.map(colInfo => colInfo.join(' ')); const listColInfoToPreserve = colInfoToPreserve.length ? colInfoToPreserve.join(', ') + ', ' : ''; const listColsToPreserve = colNamesToPreserve.length ? colNamesToPreserve.join(', ') + ', ' : ''; // We could adapt the approach at http://stackoverflow.com/a/8430746/271577 // to make the approach reusable without passing column names, but it is a bit fragile store.transaction.__addNonRequestToTransactionQueue(function renameIndex(tx, args, success, error) { function sqlError(tx, err) { error(err); } function finish() { if (cb) { cb(tx, success); return; } success(); } // See https://www.sqlite.org/lang_altertable.html#otheralter // We don't query for indexes as we already have the info // This approach has the advantage of auto-deleting indexes via the DROP TABLE const sql = 'CREATE TABLE ' + escapedTmpStoreNameSQL + '(' + listColInfoToPreserve + escapedNewIndexNameSQL + ' ' + newNameType + ')'; CFG.DEBUG && console.log(sql); tx.executeSql(sql, [], function () { const sql = 'INSERT INTO ' + escapedTmpStoreNameSQL + '(' + listColsToPreserve + escapedNewIndexNameSQL + ') SELECT ' + listColsToPreserve + escapeIndexNameForSQL(oldName) + ' FROM ' + escapedStoreNameSQL; CFG.DEBUG && console.log(sql); tx.executeSql(sql, [], function () { const sql = 'DROP TABLE ' + escapedStoreNameSQL; CFG.DEBUG && console.log(sql); tx.executeSql(sql, [], function () { const sql = 'ALTER TABLE ' + escapedTmpStoreNameSQL + ' RENAME TO ' + escapedStoreNameSQL; CFG.DEBUG && console.log(sql); tx.executeSql(sql, [], function (tx, data) { if (!CFG.useSQLiteIndexes) { finish(); return; } const indexCreations = colNamesToPreserve.slice(2) // Doing `key` separately and no need for index on `value` .map(escapedIndexNameSQL => new syncPromiseCommonjs(function (resolve, reject) { const escapedIndexToRecreate = sqlQuote(escapedStoreNameSQL.slice(1, -1) + '^5' + escapedIndexNameSQL.slice(1, -1)); // const sql = 'DROP INDEX IF EXISTS ' + escapedIndexToRecreate; // CFG.DEBUG && console.log(sql); // tx.executeSql(sql, [], function () { const sql = 'CREATE INDEX ' + escapedIndexToRecreate + ' ON ' + escapedStoreNameSQL + '(' + escapedIndexNameSQL + ')'; CFG.DEBUG && console.log(sql); tx.executeSql(sql, [], resolve, function (tx, err) { reject(err); }); // }, function (tx, err) { // reject(err); // }); })); indexCreations.push(new syncPromiseCommonjs(function (resolve, reject) { const escapedIndexToRecreate = sqlQuote('sk_' + escapedStoreNameSQL.slice(1, -1)); // Chrome erring here if not dropped first; Node does not const sql = 'DROP INDEX IF EXISTS ' + escapedIndexToRecreate; CFG.DEBUG && console.log(sql); tx.executeSql(sql, [], function () { const sql = 'CREATE INDEX ' + escapedIndexToRecreate + ' ON ' + escapedStoreNameSQL + '("key")'; CFG.DEBUG && console.log(sql); tx.executeSql(sql, [], resolve, function (tx, err) { reject(err); }); }, function (tx, err) { reject(err); }); })); syncPromiseCommonjs.all(indexCreations).then(finish, error).catch(err => { console.log('Index rename error'); throw err; }); }, sqlError); }, sqlError); }, sqlError); }, sqlError); }); }; Object.defineProperty(IDBIndex, Symbol.hasInstance, { value: obj => isObj(obj) && typeof obj.openCursor === 'function' && typeof obj.multiEntry === 'boolean' }); defineReadonlyOuterInterface(IDBIndex.prototype, readonlyProperties$4); defineOuterInterface(IDBIndex.prototype, ['name']); IDBIndex.prototype[Symbol.toStringTag] = 'IDBIndexPrototype'; Object.defineProperty(IDBIndex, 'prototype', { writable: false }); function executeFetchIndexData(count, unboundedDisallowed, index, hasKey, range, opType, multiChecks, sql, sqlValues, tx, args, success, error) { if (unboundedDisallowed) { count = 1; } if (count) { sql.push('LIMIT', count); } const isCount = opType === 'count'; CFG.DEBUG && console.log('Trying to fetch data for Index', sql.join(' '), sqlValues); tx.executeSql(sql.join(' '), sqlValues, function (tx, data) { const records = []; let recordCount = 0; const decode$1 = isCount ? () => { /* */ } : opType === 'key' ? record => { // Key.convertValueToKey(record.key); // Already validated before storage return decode(unescapeSQLiteResponse(record.key)); } : record => { // when opType is value return decode$2(unescapeSQLiteResponse(record.value)); }; if (index.multiEntry) { const escapedIndexNameForKeyCol = escapeIndexNameForSQLKeyColumn(index.name); const encodedKey = encode(range, index.multiEntry); for (let i = 0; i < data.rows.length; i++) { const row = data.rows.item(i); const rowKey = decode(row[escapedIndexNameForKeyCol]); let record; if (hasKey && (multiChecks && range.some(check => rowKey.includes(check)) || // More precise than our SQL isMultiEntryMatch(encodedKey, row[escapedIndexNameForKeyCol]))) { recordCount++; record = row; } else if (!hasKey && !multiChecks) { if (rowKey !== undefined) { recordCount += Array.isArray(rowKey) ? rowKey.length : 1; record = row; } } if (record) { records.push(decode$1(record)); if (unboundedDisallowed) { break; } } } } else { for (let i = 0; i < data.rows.length; i++) { const record = data.rows.item(i); if (record) { records.push(decode$1(record)); } } recordCount = records.length; } if (isCount) { success(recordCount); } else if (recordCount === 0) { success(unboundedDisallowed ? undefined : []); } else { success(unboundedDisallowed ? records[0] : records); } }, error); } function buildFetchIndexDataSQL(nullDisallowed, index, range, opType, multiChecks) { const hasRange = nullDisallowed || !isNullish(range); const col = opType === 'count' ? 'key' : opType; // It doesn't matter which column we use for 'count' as long as it is valid const sql = ['SELECT', sqlQuote(col) + (index.multiEntry ? ', ' + escapeIndexNameForSQL(index.name) : ''), 'FROM', escapeStoreNameForSQL(index.objectStore.__currentName), 'WHERE', escapeIndexNameForSQL(index.name), 'NOT NULL']; const sqlValues = []; if (hasRange) { if (multiChecks) { sql.push('AND ('); range.forEach((innerKey, i) => { if (i > 0) sql.push('OR'); sql.push(escapeIndexNameForSQL(index.name), "LIKE ? ESCAPE '^' "); sqlValues.push('%' + sqlLIKEEscape(encode(innerKey, index.multiEntry)) + '%'); }); sql.push(')'); } else if (index.multiEntry) { sql.push('AND', escapeIndexNameForSQL(index.name), "LIKE ? ESCAPE '^'"); sqlValues.push('%' + sqlLIKEEscape(encode(range, index.multiEntry)) + '%'); } else { const convertedRange = convertValueToKeyRange(range, nullDisallowed); setSQLForKeyRange(convertedRange, escapeIndexNameForSQL(index.name), sql, sqlValues, true, false); } } return [nullDisallowed, index, hasRange, range, opType, multiChecks, sql, sqlValues]; } const readonlyProperties$5 = ['keyPath', 'indexNames', 'transaction', 'autoIncrement']; /* eslint-disable jsdoc/check-param-names */ /** * IndexedDB Object Store. * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBObjectStore * @param {IDBObjectStoreProperties} storeProperties * @param {IDBTransaction} transaction * @class */ function IDBObjectStore() { /* eslint-enable jsdoc/check-param-names */ throw new TypeError('Illegal constructor'); } const IDBObjectStoreAlias = IDBObjectStore; IDBObjectStore.__createInstance = function (storeProperties, transaction) { function IDBObjectStore() { const me = this; me[Symbol.toStringTag] = 'IDBObjectStore'; defineReadonlyProperties(this, readonlyProperties$5); me.__name = me.__originalName = storeProperties.name; me.__keyPath = Array.isArray(storeProperties.keyPath) ? storeProperties.keyPath.slice() : storeProperties.keyPath; me.__transaction = transaction; me.__idbdb = storeProperties.idbdb; me.__cursors = storeProperties.cursors || []; // autoInc is numeric (0/1) on WinPhone me.__autoIncrement = Boolean(storeProperties.autoInc); me.__indexes = {}; me.__indexHandles = {}; me.__indexNames = DOMStringList.__createInstance(); const { indexList } = storeProperties; for (const indexName in indexList) { if (hasOwn(indexList, indexName)) { const index = IDBIndex.__createInstance(me, indexList[indexName]); me.__indexes[index.name] = index; if (!index.__deleted) { me.indexNames.push(index.name); } } } me.__oldIndexNames = me.indexNames.clone(); Object.defineProperty(this, '__currentName', { get() { return '__pendingName' in this ? this.__pendingName : this.name; } }); Object.defineProperty(this, 'name', { enumerable: false, configurable: false, get() { return this.__name; }, set(name) { const me = this; name = convertToDOMString(name); const oldName = me.name; IDBObjectStoreAlias.__invalidStateIfDeleted(me); IDBTransaction.__assertVersionChange(me.transaction); IDBTransaction.__assertActive(me.transaction); if (oldName === name) { return; } if (me.__idbdb.__objectStores[name] && !me.__idbdb.__objectStores[name].__pendingDelete) { throw createDOMException('ConstraintError', 'Object store "' + name + '" already exists in ' + me.__idbdb.name); } me.__name = name; const oldStore = me.__idbdb.__objectStores[oldName]; oldStore.__name = name; // Fix old references me.__idbdb.__objectStores[name] = oldStore; // Ensure new reference accessible delete me.__idbdb.__objectStores[oldName]; // Ensure won't be found me.__idbdb.objectStoreNames.splice(me.__idbdb.objectStoreNames.indexOf(oldName), 1, name); const oldHandle = me.transaction.__storeHandles[oldName]; oldHandle.__name = name; // Fix old references me.transaction.__storeHandles[name] = oldHandle; // Ensure new reference accessible me.__pendingName = oldName; const sql = 'UPDATE __sys__ SET "name" = ? WHERE "name" = ?'; const sqlValues = [escapeSQLiteStatement(name), escapeSQLiteStatement(oldName)]; CFG.DEBUG && console.log(sql, sqlValues); me.transaction.__addNonRequestToTransactionQueue(function objectStoreClear(tx, args, success, error) { tx.executeSql(sql, sqlValues, function (tx, data) { // This SQL preserves indexes per https://www.sqlite.org/lang_altertable.html const sql = 'ALTER TABLE ' + escapeStoreNameForSQL(oldName) + ' RENAME TO ' + escapeStoreNameForSQL(name); CFG.DEBUG && console.log(sql); tx.executeSql(sql, [], function (tx, data) { delete me.__pendingName; success(); }); }, function (tx, err) { error(err); }); }); } }); } IDBObjectStore.prototype = IDBObjectStoreAlias.prototype; return new IDBObjectStore(); }; /** * Clones an IDBObjectStore instance for a different IDBTransaction instance. * @param {IDBObjectStore} store * @param {IDBTransaction} transaction * @protected * @returns {IDBObjectStore} */ IDBObjectStore.__clone = function (store, transaction) { const newStore = IDBObjectStore.__createInstance({ name: store.__currentName, keyPath: Array.isArray(store.keyPath) ? store.keyPath.slice() : store.keyPath, autoInc: store.autoIncrement, indexList: {}, idbdb: store.__idbdb, cursors: store.__cursors }, transaction); ['__indexes', '__indexNames', '__oldIndexNames', '__deleted', '__pendingDelete', '__pendingCreate', '__originalName'].forEach(p => { newStore[p] = store[p]; }); return newStore; }; IDBObjectStore.__invalidStateIfDeleted = function (store, msg) { if (store.__deleted || store.__pendingDelete || store.__pendingCreate && store.transaction && store.transaction.__errored) { throw createDOMException('InvalidStateError', msg || 'This store has been deleted'); } }; /** * Creates a new object store in the database. * @param {IDBDatabase} db * @param {IDBObjectStore} store * @protected * @returns {IDBObjectStore} */ IDBObjectStore.__createObjectStore = function (db, store) { // Add the object store to the IDBDatabase const storeName = store.__currentName; store.__pendingCreate = true; db.__objectStores[storeName] = store; db.objectStoreNames.push(storeName); // Add the object store to WebSQL const transaction = db.__versionTransaction; const storeHandles = transaction.__storeHandles; if (!storeHandles[storeName] || // These latter conditions are to allow store // recreation to create new clone object storeHandles[storeName].__pendingDelete || storeHandles[storeName].__deleted) { storeHandles[storeName] = IDBObjectStore.__clone(store, transaction); } transaction.__addNonRequestToTransactionQueue(function createObjectStore(tx, args, success, failure) { function error(tx, err) { CFG.DEBUG && console.log(err); failure(createDOMException('UnknownError', 'Could not create object store "' + storeName + '"', err)); } const escapedStoreNameSQL = escapeStoreNameForSQL(storeName); // key INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE const sql = ['CREATE TABLE', escapedStoreNameSQL, '(key BLOB', store.autoIncrement ? 'UNIQUE, inc INTEGER PRIMARY KEY AUTOINCREMENT' : 'PRIMARY KEY', ', value BLOB)'].join(' '); CFG.DEBUG && console.log(sql); tx.executeSql(sql, [], function (tx, data) { function insertStoreInfo() { const encodedKeyPath = JSON.stringify(store.keyPath); tx.executeSql('INSERT INTO __sys__ VALUES (?,?,?,?,?)', [escapeSQLiteStatement(storeName), encodedKeyPath, store.autoIncrement, '{}', 1], function () { delete store.__pendingCreate; delete store.__deleted; success(store); }, error); } if (!CFG.useSQLiteIndexes) { insertStoreInfo(); return; } tx.executeSql('CREATE INDEX IF NOT EXISTS ' + sqlQuote('sk_' + escapedStoreNameSQL.slice(1, -1)) + ' ON ' + escapedStoreNameSQL + '("key")', [], insertStoreInfo, error); }, error); }); return storeHandles[storeName]; }; /** * Deletes an object store from the database. * @param {IDBDatabase} db * @param {IDBObjectStore} store * @protected * @returns {void} */ IDBObjectStore.__deleteObjectStore = function (db, store) { // Remove the object store from the IDBDatabase store.__pendingDelete = true; // We don't delete the other index holders in case need reversion store.__indexNames = DOMStringList.__createInstance(); db.objectStoreNames.splice(db.objectStoreNames.indexOf(store.__currentName), 1); const storeHandle = db.__versionTransaction.__storeHandles[store.__currentName]; if (storeHandle) { storeHandle.__indexNames = DOMStringList.__createInstance(); storeHandle.__pendingDelete = true; } // Remove the object store from WebSQL const transaction = db.__versionTransaction; transaction.__addNonRequestToTransactionQueue(function deleteObjectStore(tx, args, success, failure) { function error(tx, err) { CFG.DEBUG && console.log(err); failure(createDOMException('UnknownError', 'Could not delete ObjectStore', err)); } tx.executeSql('SELECT "name" FROM __sys__ WHERE "name" = ?', [escapeSQLiteStatement(store.__currentName)], function (tx, data) { if (data.rows.length > 0) { tx.executeSql('DROP TABLE ' + escapeStoreNameForSQL(store.__currentName), [], function () { tx.executeSql('DELETE FROM __sys__ WHERE "name" = ?', [escapeSQLiteStatement(store.__currentName)], function () { delete store.__pendingDelete; store.__deleted = true; if (storeHandle) { delete storeHandle.__pendingDelete; storeHandle.__deleted = true; } success(); }, error); }, error); } }); }); }; /** * @typedef {GenericArray} KeyValueArray * @property {module:Key.Key} 0 * @property {*} 1 */ // Todo: Although we may end up needing to do cloning genuinely asynchronously (for Blobs and FileLists), // and we'll want to ensure the queue starts up synchronously, we nevertheless do the cloning // before entering the queue and its callback since the encoding we do is preceded by validation // which we must do synchronously anyways. If we reimplement Blobs and FileLists asynchronously, // we can detect these types (though validating synchronously as possible) and once entering the // queue callback, ensure they load before triggering success or failure (perhaps by returning and // a `SyncPromise` from the `Sca.clone` operation and later detecting and ensuring it is resolved // before continuing). /** * Determines whether the given inline or out-of-line key is valid, * according to the object store's schema. * @param {*} value Used for inline keys * @param {*} key Used for out-of-line keys * @param {boolean} cursorUpdate * @throws {DOMException} * @returns {KeyValueArray} * @private */ IDBObjectStore.prototype.__validateKeyAndValueAndCloneValue = function (value, key, cursorUpdate) { const me = this; if (me.keyPath !== null) { if (key !== undefined) { throw createDOMException('DataError', 'The object store uses in-line keys and the key parameter was provided', me); } // Todo Binary: Avoid blobs loading async to ensure cloning (and errors therein) // occurs sync; then can make cloning and this method without callbacks (except where ok // to be async) const clonedValue = clone(value); key = extractKeyValueDecodedFromValueUsingKeyPath(clonedValue, me.keyPath); // May throw so "rethrow" if (key.invalid) { throw createDOMException('DataError', 'KeyPath was specified, but key was invalid.'); } if (key.failure) { if (!cursorUpdate) { if (!me.autoIncrement) { throw createDOMException('DataError', 'Could not evaluate a key from keyPath and there is no key generator'); } if (!checkKeyCouldBeInjectedIntoValue(clonedValue, me.keyPath)) { throw createDOMException('DataError', 'A key could not be injected into a value'); } // A key will be generated return [undefined, clonedValue]; } throw createDOMException('DataError', 'Could not evaluate a key from keyPath'); } // An `IDBCursor.update` call will also throw if not equal to the cursor’s effective key return [key.value, clonedValue]; } if (key === undefined) { if (!me.autoIncrement) { throw createDOMException('DataError', 'The object store uses out-of-line keys and has no key generator and the key parameter was not provided.', me); } // A key will be generated key = undefined; } else { convertValueToKeyRethrowingAndIfInvalid(key); } const clonedValue = clone(value); return [key, clonedValue]; }; /** * From the store properties and object, extracts the value for the key in * the object store * If the table has auto increment, get the current number (unless it has * a keyPath leading to a valid but non-numeric or < 1 key). * @param {Object} tx * @param {Object} value * @param {Object} key * @param {function} success * @param {function} failCb * @returns {void} */ IDBObjectStore.prototype.__deriveKey = function (tx, value, key, success, failCb) { const me = this; // Only run if cloning is needed function keyCloneThenSuccess(oldCn) { // We want to return the original key, so we don't need to accept an argument here encode$2(key, function (key) { key = decode$2(key); success(key, oldCn); }); } if (me.autoIncrement) { // If auto-increment and no valid primaryKey found on the keyPath, get and set the new value, and use if (key === undefined) { generateKeyForStore(tx, me, function (failure, key, oldCn) { if (failure) { failCb(createDOMException('ConstraintError', 'The key generator\'s current number has reached the maximum safe integer limit')); return; } if (me.keyPath !== null) { // Should not throw now as checked earlier injectKeyIntoValueUsingKeyPath(value, key, me.keyPath); } success(key, oldCn); }, failCb); } else { possiblyUpdateKeyGenerator(tx, me, key, keyCloneThenSuccess, failCb); } // Not auto-increment } else { keyCloneThenSuccess(); } }; IDBObjectStore.prototype.__insertData = function (tx, encoded, value, clonedKeyOrCurrentNumber, oldCn, success, error) { const me = this; // The `ConstraintError` to occur for `add` upon a duplicate will occur naturally in attempting an insert // We process the index information first as it will stored in the same table as the store const paramMap = {}; const indexPromises = Object.keys( // We do not iterate `indexNames` as those can be modified synchronously (e.g., // `deleteIndex` could, by its synchronous removal from `indexNames`, prevent // iteration here of an index though per IndexedDB test // `idbobjectstore_createIndex4-deleteIndex-event_order.js`, `createIndex` // should be allowed to first fail even in such a case). me.__indexes).map(indexName => { // While this may sometimes resolve sync and sometimes async, the // idea is to avoid, where possible, unnecessary delays (and // consuming code ought to only see a difference in the browser // where we can't control the transaction timeout anyways). return new syncPromiseCommonjs((resolve, reject) => { const index = me.__indexes[indexName]; if ( // `createIndex` was called synchronously after the current insertion was added to // the transaction queue so although it was added to `__indexes`, it is not yet // ready to be checked here for the insertion as it will be when running the // `createIndex` operation (e.g., if two items with the same key were added and // *then* a unique index was created, it should not continue to err and abort // yet, as we're still handling the insertions which must be processed (e.g., to // add duplicates which then cause a unique index to fail)) index.__pendingCreate || // If already deleted (and not just slated for deletion (by `__pendingDelete` // after this add), we avoid checks index.__deleted) { resolve(); return; } let indexKey; try { indexKey = extractKeyValueDecodedFromValueUsingKeyPath(value, index.keyPath, index.multiEntry); // Add as necessary to this and skip past this index if exceptions here) if (indexKey.invalid || indexKey.failure) { throw new Error('Go to catch'); } } catch (err) { resolve(); return; } indexKey = indexKey.value; function setIndexInfo(index) { if (indexKey === undefined) { return; } paramMap[index.__currentName] = encode(indexKey, index.multiEntry); } if (index.unique) { const multiCheck = index.multiEntry && Array.isArray(indexKey); const fetchArgs = buildFetchIndexDataSQL(true, index, indexKey, 'key', multiCheck); executeFetchIndexData(null, ...fetchArgs, tx, null, function success(key) { if (key === undefined) { setIndexInfo(index); resolve(); return; } reject(createDOMException('ConstraintError', 'Index already contains a record equal to ' + (multiCheck ? 'one of the subkeys of' : '') + '`indexKey`')); }, reject); } else { setIndexInfo(index); resolve(); } }); }); return syncPromiseCommonjs.all(indexPromises).then(() => { const sqlStart = ['INSERT INTO', escapeStoreNameForSQL(me.__currentName), '(']; const sqlEnd = [' VALUES (']; const insertSqlValues = []; if (clonedKeyOrCurrentNumber !== undefined) { // Key.convertValueToKey(primaryKey); // Already run sqlStart.push(sqlQuote('key'), ','); sqlEnd.push('?,'); insertSqlValues.push(escapeSQLiteStatement(encode(clonedKeyOrCurrentNumber))); } Object.entries(paramMap).forEach(([key, stmt]) => { sqlStart.push(escapeIndexNameForSQL(key) + ','); sqlEnd.push('?,'); insertSqlValues.push(escapeSQLiteStatement(stmt)); }); // removing the trailing comma sqlStart.push(sqlQuote('value') + ' )'); sqlEnd.push('?)'); insertSqlValues.push(escapeSQLiteStatement(encoded)); const insertSql = sqlStart.join(' ') + sqlEnd.join(' '); CFG.DEBUG && console.log('SQL for adding', insertSql, insertSqlValues); tx.executeSql(insertSql, insertSqlValues, function (tx, data) { success(clonedKeyOrCurrentNumber); }, function (tx, err) { // Should occur for `add` operation error(createDOMException('ConstraintError', err.message, err)); }); return undefined; }).catch(function (err) { function fail() { // Todo: Add a different error object here if `assignCurrentNumber` fails in reverting? error(err); } if (typeof oldCn === 'number') { assignCurrentNumber(tx, me, oldCn, fail, fail); return; } fail(); }); }; IDBObjectStore.prototype.add = function (value /* , key */ ) { const me = this; // eslint-disable-next-line prefer-rest-params const key = arguments[1]; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No value was specified'); } IDBObjectStore.__invalidStateIfDeleted(me); IDBTransaction.__assertActive(me.transaction); me.transaction.__assertWritable(); const request = me.transaction.__createRequest(me); const [ky, clonedValue] = me.__validateKeyAndValueAndCloneValue(value, key, false); IDBObjectStore.__storingRecordObjectStore(request, me, true, clonedValue, true, ky); return request; }; IDBObjectStore.prototype.put = function (value /*, key */ ) { const me = this; // eslint-disable-next-line prefer-rest-params const key = arguments[1]; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No value was specified'); } IDBObjectStore.__invalidStateIfDeleted(me); IDBTransaction.__assertActive(me.transaction); me.transaction.__assertWritable(); const request = me.transaction.__createRequest(me); const [ky, clonedValue] = me.__validateKeyAndValueAndCloneValue(value, key, false); IDBObjectStore.__storingRecordObjectStore(request, me, true, clonedValue, false, ky); return request; }; IDBObjectStore.prototype.__overwrite = function (tx, key, cb, error) { const me = this; // First try to delete if the record exists // Key.convertValueToKey(key); // Already run const sql = 'DELETE FROM ' + escapeStoreNameForSQL(me.__currentName) + ' WHERE "key" = ?'; const encodedKey = encode(key); tx.executeSql(sql, [escapeSQLiteStatement(encodedKey)], function (tx, data) { CFG.DEBUG && console.log('Did the row with the', key, 'exist?', data.rowsAffected); cb(tx); }, function (tx, err) { error(err); }); }; IDBObjectStore.__storingRecordObjectStore = function (request, store, invalidateCache, value, noOverwrite /* , key */ ) { // eslint-disable-next-line prefer-rest-params const key = arguments[5]; store.transaction.__pushToQueue(request, function (tx, args, success, error) { store.__deriveKey(tx, value, key, function (clonedKeyOrCurrentNumber, oldCn) { encode$2(value, function (encoded) { function insert(tx) { store.__insertData(tx, encoded, value, clonedKeyOrCurrentNumber, oldCn, function (...args) { if (invalidateCache) { store.__cursors.forEach(cursor => { cursor.__invalidateCache(); }); } success(...args); }, error); } if (!noOverwrite) { store.__overwrite(tx, clonedKeyOrCurrentNumber, insert, error); return; } insert(tx); }); }, error); }); }; IDBObjectStore.prototype.__get = function (query, getKey, getAll, count) { const me = this; if (count !== undefined) { count = enforceRange(count, 'unsigned long'); } IDBObjectStore.__invalidStateIfDeleted(me); IDBTransaction.__assertActive(me.transaction); const range = convertValueToKeyRange(query, !getAll); const col = getKey ? 'key' : 'value'; let sql = ['SELECT', sqlQuote(col), 'FROM', escapeStoreNameForSQL(me.__currentName)]; const sqlValues = []; if (range !== undefined) { sql.push('WHERE'); setSQLForKeyRange(range, sqlQuote('key'), sql, sqlValues); } if (!getAll) { count = 1; } if (count) { if (typeof count !== 'number' || isNaN(count) || !isFinite(count)) { throw new TypeError('The count parameter must be a finite number'); } sql.push('LIMIT', count); } sql = sql.join(' '); return me.transaction.__addToTransactionQueue(function objectStoreGet(tx, args, success, error) { CFG.DEBUG && console.log('Fetching', me.__currentName, sqlValues); tx.executeSql(sql, sqlValues, function (tx, data) { CFG.DEBUG && console.log('Fetched data', data); let ret; try { // Opera can't deal with the try-catch here. if (data.rows.length === 0) { if (getAll) { success([]); } else { success(); } return; } ret = []; if (getKey) { for (let i = 0; i < data.rows.length; i++) { // Key.convertValueToKey(data.rows.item(i).key); // Already validated before storage ret.push(decode(unescapeSQLiteResponse(data.rows.item(i).key), false)); } } else { for (let i = 0; i < data.rows.length; i++) { ret.push(decode$2(unescapeSQLiteResponse(data.rows.item(i).value))); } } if (!getAll) { ret = ret[0]; } } catch (e) { // If no result is returned, or error occurs when parsing JSON CFG.DEBUG && console.log(e); } success(ret); }, function (tx, err) { error(err); }); }, undefined, me); }; IDBObjectStore.prototype.get = function (query) { if (!arguments.length) { throw new TypeError('A parameter was missing for `IDBObjectStore.get`.'); } return this.__get(query); }; IDBObjectStore.prototype.getKey = function (query) { if (!arguments.length) { throw new TypeError('A parameter was missing for `IDBObjectStore.getKey`.'); } return this.__get(query, true); }; IDBObjectStore.prototype.getAll = function () /* query, count */ { // eslint-disable-next-line prefer-rest-params const [query, count] = arguments; return this.__get(query, false, true, count); }; IDBObjectStore.prototype.getAllKeys = function () /* query, count */ { // eslint-disable-next-line prefer-rest-params const [query, count] = arguments; return this.__get(query, true, true, count); }; IDBObjectStore.prototype.delete = function (query) { const me = this; if (!(this instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } if (!arguments.length) { throw new TypeError('A parameter was missing for `IDBObjectStore.delete`.'); } IDBObjectStore.__invalidStateIfDeleted(me); IDBTransaction.__assertActive(me.transaction); me.transaction.__assertWritable(); const range = convertValueToKeyRange(query, true); const sqlArr = ['DELETE FROM', escapeStoreNameForSQL(me.__currentName), 'WHERE']; const sqlValues = []; setSQLForKeyRange(range, sqlQuote('key'), sqlArr, sqlValues); const sql = sqlArr.join(' '); return me.transaction.__addToTransactionQueue(function objectStoreDelete(tx, args, success, error) { CFG.DEBUG && console.log('Deleting', me.__currentName, sqlValues); tx.executeSql(sql, sqlValues, function (tx, data) { CFG.DEBUG && console.log('Deleted from database', data.rowsAffected); me.__cursors.forEach(cursor => { cursor.__invalidateCache(); // Delete }); success(); }, function (tx, err) { error(err); }); }, undefined, me); }; IDBObjectStore.prototype.clear = function () { const me = this; if (!(this instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } IDBObjectStore.__invalidStateIfDeleted(me); IDBTransaction.__assertActive(me.transaction); me.transaction.__assertWritable(); return me.transaction.__addToTransactionQueue(function objectStoreClear(tx, args, success, error) { tx.executeSql('DELETE FROM ' + escapeStoreNameForSQL(me.__currentName), [], function (tx, data) { CFG.DEBUG && console.log('Cleared all records from database', data.rowsAffected); me.__cursors.forEach(cursor => { cursor.__invalidateCache(); // Clear }); success(); }, function (tx, err) { error(err); }); }, undefined, me); }; IDBObjectStore.prototype.count = function () /* query */ { const me = this; // eslint-disable-next-line prefer-rest-params const query = arguments[0]; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } IDBObjectStore.__invalidStateIfDeleted(me); IDBTransaction.__assertActive(me.transaction); // We don't need to add to cursors array since has the count parameter which won't cache return IDBCursorWithValue.__createInstance(query, 'next', me, me, 'key', 'value', true).__request; }; IDBObjectStore.prototype.openCursor = function () /* query, direction */ { const me = this; // eslint-disable-next-line prefer-rest-params const [query, direction] = arguments; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } IDBObjectStore.__invalidStateIfDeleted(me); const cursor = IDBCursorWithValue.__createInstance(query, direction, me, me, 'key', 'value'); me.__cursors.push(cursor); return cursor.__request; }; IDBObjectStore.prototype.openKeyCursor = function () /* query, direction */ { const me = this; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } IDBObjectStore.__invalidStateIfDeleted(me); // eslint-disable-next-line prefer-rest-params const [query, direction] = arguments; const cursor = IDBCursor.__createInstance(query, direction, me, me, 'key', 'key'); me.__cursors.push(cursor); return cursor.__request; }; IDBObjectStore.prototype.index = function (indexName) { const me = this; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No index name was specified'); } IDBObjectStore.__invalidStateIfDeleted(me); IDBTransaction.__assertNotFinished(me.transaction); const index = me.__indexes[indexName]; if (!index || index.__deleted) { throw createDOMException('NotFoundError', 'Index "' + indexName + '" does not exist on ' + me.__currentName); } if (!me.__indexHandles[indexName] || me.__indexes[indexName].__pendingDelete || me.__indexes[indexName].__deleted) { me.__indexHandles[indexName] = IDBIndex.__clone(index, me); } return me.__indexHandles[indexName]; }; /* eslint-disable jsdoc/check-param-names */ /** * Creates a new index on the object store. * @param {string} indexName * @param {string} keyPath * @param {object} optionalParameters * @returns {IDBIndex} */ IDBObjectStore.prototype.createIndex = function (indexName, keyPath /* , optionalParameters */ ) { /* eslint-enable jsdoc/check-param-names */ const me = this; // eslint-disable-next-line prefer-rest-params let optionalParameters = arguments[2]; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } indexName = String(indexName); // W3C test within IDBObjectStore.js seems to accept string conversion if (arguments.length === 0) { throw new TypeError('No index name was specified'); } if (arguments.length === 1) { throw new TypeError('No key path was specified'); } IDBTransaction.__assertVersionChange(me.transaction); IDBObjectStore.__invalidStateIfDeleted(me); IDBTransaction.__assertActive(me.transaction); if (me.__indexes[indexName] && !me.__indexes[indexName].__deleted && !me.__indexes[indexName].__pendingDelete) { throw createDOMException('ConstraintError', 'Index "' + indexName + '" already exists on ' + me.__currentName); } keyPath = convertToSequenceDOMString(keyPath); if (!isValidKeyPath(keyPath)) { throw createDOMException('SyntaxError', 'A valid keyPath must be supplied'); } if (Array.isArray(keyPath) && optionalParameters && optionalParameters.multiEntry) { throw createDOMException('InvalidAccessError', 'The keyPath argument was an array and the multiEntry option is true.'); } optionalParameters = optionalParameters || {}; /** @name IDBIndexProperties **/ const indexProperties = { columnName: indexName, keyPath, optionalParams: { unique: Boolean(optionalParameters.unique), multiEntry: Boolean(optionalParameters.multiEntry) } }; const index = IDBIndex.__createInstance(me, indexProperties); IDBIndex.__createIndex(me, index); return index; }; IDBObjectStore.prototype.deleteIndex = function (name) { const me = this; if (!(me instanceof IDBObjectStore)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No index name was specified'); } IDBTransaction.__assertVersionChange(me.transaction); IDBObjectStore.__invalidStateIfDeleted(me); IDBTransaction.__assertActive(me.transaction); const index = me.__indexes[name]; if (!index) { throw createDOMException('NotFoundError', 'Index "' + name + '" does not exist on ' + me.__currentName); } IDBIndex.__deleteIndex(me, index); }; defineReadonlyOuterInterface(IDBObjectStore.prototype, readonlyProperties$5); defineOuterInterface(IDBObjectStore.prototype, ['name']); IDBObjectStore.prototype[Symbol.toStringTag] = 'IDBObjectStorePrototype'; Object.defineProperty(IDBObjectStore, 'prototype', { writable: false }); const listeners$2 = ['onabort', 'onclose', 'onerror', 'onversionchange']; const readonlyProperties$6 = ['name', 'version', 'objectStoreNames']; /** * IDB Database Object. * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#database-interface * @class */ function IDBDatabase() { throw new TypeError('Illegal constructor'); } const IDBDatabaseAlias = IDBDatabase; IDBDatabase.__createInstance = function (db, name, oldVersion, version, storeProperties) { function IDBDatabase() { this[Symbol.toStringTag] = 'IDBDatabase'; defineReadonlyProperties(this, readonlyProperties$6); this.__db = db; this.__closePending = false; this.__oldVersion = oldVersion; this.__version = version; this.__name = name; this.__upgradeTransaction = null; defineListenerProperties(this, listeners$2); this.__setOptions({ legacyOutputDidListenersThrowFlag: true // Event hook for IndexedB }); this.__objectStores = {}; this.__objectStoreNames = DOMStringList.__createInstance(); const itemCopy = {}; for (let i = 0; i < storeProperties.rows.length; i++) { const item = storeProperties.rows.item(i); // Safari implements `item` getter return object's properties // as readonly, so we copy all its properties (except our // custom `currNum` which we don't need) onto a new object itemCopy.name = item.name; itemCopy.keyPath = JSON.parse(item.keyPath); ['autoInc', 'indexList'].forEach(function (prop) { itemCopy[prop] = JSON.parse(item[prop]); }); itemCopy.idbdb = this; const store = IDBObjectStore.__createInstance(itemCopy); this.__objectStores[store.name] = store; this.objectStoreNames.push(store.name); } this.__oldObjectStoreNames = this.objectStoreNames.clone(); } IDBDatabase.prototype = IDBDatabaseAlias.prototype; return new IDBDatabase(); }; IDBDatabase.prototype = EventTargetFactory.createInstance(); IDBDatabase.prototype[Symbol.toStringTag] = 'IDBDatabasePrototype'; /* eslint-disable jsdoc/check-param-names */ /** * Creates a new object store. * @param {string} storeName * @param {object} [createOptions] * @returns {IDBObjectStore} */ IDBDatabase.prototype.createObjectStore = function (storeName /* , createOptions */ ) { /* eslint-enable jsdoc/check-param-names */ // eslint-disable-next-line prefer-rest-params let createOptions = arguments[1]; storeName = String(storeName); // W3C test within IDBObjectStore.js seems to accept string conversion if (!(this instanceof IDBDatabase)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No object store name was specified'); } IDBTransaction.__assertVersionChange(this.__versionTransaction); // this.__versionTransaction may not exist if called mistakenly by user in onsuccess this.throwIfUpgradeTransactionNull(); IDBTransaction.__assertActive(this.__versionTransaction); createOptions = _objectSpread2$1({}, createOptions); let { keyPath } = createOptions; keyPath = keyPath === undefined ? null : convertToSequenceDOMString(keyPath); if (keyPath !== null && !isValidKeyPath(keyPath)) { throw createDOMException('SyntaxError', 'The keyPath argument contains an invalid key path.'); } if (this.__objectStores[storeName] && !this.__objectStores[storeName].__pendingDelete) { throw createDOMException('ConstraintError', 'Object store "' + storeName + '" already exists in ' + this.name); } const autoInc = createOptions.autoIncrement; if (autoInc && (keyPath === '' || Array.isArray(keyPath))) { throw createDOMException('InvalidAccessError', 'With autoIncrement set, the keyPath argument must not be an array or empty string.'); } /** @name IDBObjectStoreProperties **/ const storeProperties = { name: storeName, keyPath, autoInc, indexList: {}, idbdb: this }; const store = IDBObjectStore.__createInstance(storeProperties, this.__versionTransaction); return IDBObjectStore.__createObjectStore(this, store); }; /** * Deletes an object store. * @param {string} storeName * @throws {TypeError|DOMException} * @returns {void} */ IDBDatabase.prototype.deleteObjectStore = function (storeName) { if (!(this instanceof IDBDatabase)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('No object store name was specified'); } IDBTransaction.__assertVersionChange(this.__versionTransaction); this.throwIfUpgradeTransactionNull(); IDBTransaction.__assertActive(this.__versionTransaction); const store = this.__objectStores[storeName]; if (!store) { throw createDOMException('NotFoundError', 'Object store "' + storeName + '" does not exist in ' + this.name); } IDBObjectStore.__deleteObjectStore(this, store); }; IDBDatabase.prototype.close = function () { if (!(this instanceof IDBDatabase)) { throw new TypeError('Illegal invocation'); } this.__closePending = true; if (this.__unblocking) { this.__unblocking.check(); } }; /* eslint-disable jsdoc/check-param-names */ /** * Starts a new transaction. * @param {string|string[]} storeNames * @param {string} mode * @returns {IDBTransaction} */ IDBDatabase.prototype.transaction = function (storeNames /* , mode */ ) { /* eslint-enable jsdoc/check-param-names */ if (arguments.length === 0) { throw new TypeError('You must supply a valid `storeNames` to `IDBDatabase.transaction`'); } // eslint-disable-next-line prefer-rest-params let mode = arguments[1]; storeNames = isIterable(storeNames) // Creating new array also ensures sequence is passed by value: https://heycam.github.io/webidl/#idl-sequence ? [...new Set( // to be unique convertToSequenceDOMString(storeNames) // iterables have `ToString` applied (and we convert to array for convenience) )].sort() // must be sorted : [convertToDOMString(storeNames)]; /* (function () { throw new TypeError('You must supply a valid `storeNames` to `IDBDatabase.transaction`'); }())); */ // Since SQLite (at least node-websql and definitely WebSQL) requires // locking of the whole database, to allow simultaneous readwrite // operations on transactions without overlapping stores, we'd probably // need to save the stores in separate databases (we could also consider // prioritizing readonly but not starving readwrite). // Even for readonly transactions, due to [issue 17](https://github.com/nolanlawson/node-websql/issues/17), // we're not currently actually running the SQL requests in parallel. mode = mode || 'readonly'; IDBTransaction.__assertNotVersionChange(this.__versionTransaction); if (this.__closePending) { throw createDOMException('InvalidStateError', 'An attempt was made to start a new transaction on a database connection that is not open'); } const objectStoreNames = DOMStringList.__createInstance(); storeNames.forEach(storeName => { if (!this.objectStoreNames.contains(storeName)) { throw createDOMException('NotFoundError', 'The "' + storeName + '" object store does not exist'); } objectStoreNames.push(storeName); }); if (storeNames.length === 0) { throw createDOMException('InvalidAccessError', 'No valid object store names were specified'); } if (mode !== 'readonly' && mode !== 'readwrite') { throw new TypeError('Invalid transaction mode: ' + mode); } // Do not set transaction state to "inactive" yet (will be set after // timeout on creating transaction instance): // https://github.com/w3c/IndexedDB/issues/87 const trans = IDBTransaction.__createInstance(this, objectStoreNames, mode); return trans; }; // See https://github.com/w3c/IndexedDB/issues/192 IDBDatabase.prototype.throwIfUpgradeTransactionNull = function () { if (this.__upgradeTransaction === null) { throw createDOMException('InvalidStateError', 'No upgrade transaction associated with database.'); } }; // Todo __forceClose: Add tests for `__forceClose` /** * * @param {string} msg * @returns {void} */ IDBDatabase.prototype.__forceClose = function (msg) { const me = this; me.close(); }; defineOuterInterface(IDBDatabase.prototype, listeners$2); defineReadonlyOuterInterface(IDBDatabase.prototype, readonlyProperties$6); Object.defineProperty(IDBDatabase.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBDatabase }); Object.defineProperty(IDBDatabase, 'prototype', { writable: false }); const fs = {}.toString.call(process) === '[object process]' ? fs$1 : null; const getOrigin = () => { return typeof location !== 'object' || !location ? 'null' : location.origin; }; const hasNullOrigin = () => CFG.checkOrigin !== false && getOrigin() === 'null'; // Todo: This really should be process and tab-independent so the // origin could vary; in the browser, this might be through a // `SharedWorker` const connectionQueue = {}; function processNextInConnectionQueue(name, origin = getOrigin()) { const queueItems = connectionQueue[origin][name]; if (!queueItems[0]) { // Nothing left to process return; } const { req, cb } = queueItems[0]; // Keep in queue to prevent continuation function removeFromQueue() { queueItems.shift(); processNextInConnectionQueue(name, origin); } req.addEventListener('success', removeFromQueue); req.addEventListener('error', removeFromQueue); cb(req); } // eslint-disable-next-line default-param-last function addRequestToConnectionQueue(req, name, origin = getOrigin(), cb) { if (!connectionQueue[origin][name]) { connectionQueue[origin][name] = []; } connectionQueue[origin][name].push({ req, cb }); if (connectionQueue[origin][name].length === 1) { // If there are no items in the queue, we have to start it processNextInConnectionQueue(name, origin); } } function triggerAnyVersionChangeAndBlockedEvents(openConnections, req, oldVersion, newVersion) { // Todo: For Node (and in browser using service workers if available?) the // connections ought to involve those in any process; should also // auto-close if unloading const connectionIsClosed = connection => connection.__closePending; const connectionsClosed = () => openConnections.every(conn => { return connectionIsClosed(conn); }); return openConnections.reduce(function (promises, entry) { if (connectionIsClosed(entry)) { return promises; } return promises.then(function () { if (connectionIsClosed(entry)) { // Prior onversionchange must have caused this connection to be closed return undefined; } const e = new IDBVersionChangeEvent('versionchange', { oldVersion, newVersion }); return new syncPromiseCommonjs(function (resolve) { setTimeout(() => { entry.dispatchEvent(e); // No need to catch errors resolve(); }); }); }); }, syncPromiseCommonjs.resolve()).then(function () { if (connectionsClosed()) { return undefined; } return new syncPromiseCommonjs(function (resolve) { const unblocking = { check() { if (connectionsClosed()) { resolve(); } } }; const e = new IDBVersionChangeEvent('blocked', { oldVersion, newVersion }); setTimeout(() => { req.dispatchEvent(e); // No need to catch errors if (!connectionsClosed()) { openConnections.forEach(connection => { if (!connectionIsClosed(connection)) { connection.__unblocking = unblocking; } }); } else { resolve(); } }); }); }); } const websqlDBCache = {}; let sysdb; let nameCounter = 0; function getLatestCachedWebSQLVersion(name) { return Object.keys(websqlDBCache[name]).map(version => { return Number(version); }).reduce((prev, curr) => { return curr > prev ? curr : prev; }, 0); } function getLatestCachedWebSQLDB(name) { return websqlDBCache[name] && websqlDBCache[name][getLatestCachedWebSQLVersion(name)]; } function cleanupDatabaseResources(__openDatabase, name, escapedDatabaseName, databaseDeleted, dbError) { const useMemoryDatabase = typeof CFG.memoryDatabase === 'string'; if (useMemoryDatabase) { const latestSQLiteDBCached = websqlDBCache[name] ? getLatestCachedWebSQLDB(name) : null; if (!latestSQLiteDBCached) { console.warn('Could not find a memory database instance to delete.'); databaseDeleted(); return; } const sqliteDB = latestSQLiteDBCached._db && latestSQLiteDBCached._db._db; if (!sqliteDB || !sqliteDB.close) { console.error('The `openDatabase` implementation does not have the expected `._db._db.close` method for closing the database'); return; } sqliteDB.close(function (err) { if (err) { console.warn('Error closing (destroying) memory database'); return; } databaseDeleted(); }); return; } if (fs && CFG.deleteDatabaseFiles !== false) { fs.unlink(path.join(CFG.databaseBasePath || '', escapedDatabaseName), err => { if (err && err.code !== 'ENOENT') { // Ignore if file is already deleted dbError({ code: 0, message: 'Error removing database file: ' + escapedDatabaseName + ' ' + err }); return; } databaseDeleted(); }); return; } const sqliteDB = __openDatabase(path.join(CFG.databaseBasePath || '', escapedDatabaseName), 1, name, CFG.DEFAULT_DB_SIZE); sqliteDB.transaction(function (tx) { tx.executeSql('SELECT "name" FROM __sys__', [], function (tx, data) { const tables = data.rows; (function deleteTables(i) { if (i >= tables.length) { // If all tables are deleted, delete the housekeeping tables tx.executeSql('DROP TABLE IF EXISTS __sys__', [], function () { databaseDeleted(); }, dbError); } else { // Delete all tables in this database, maintained in the sys table tx.executeSql('DROP TABLE ' + escapeStoreNameForSQL(unescapeSQLiteResponse( // Avoid double-escaping tables.item(i).name)), [], function () { deleteTables(i + 1); }, function () { deleteTables(i + 1); }); } })(0); }, function (e) { // __sys__ table does not exist, but that does not mean delete did not happen databaseDeleted(); }); }); } /** * @callback CreateSysDBSuccessCallback * @returns {void} */ /** * Creates the sysDB to keep track of version numbers for databases. * @param {openDatabase} __openDatabase * @param {CreateSysDBSuccessCallback} success * @param {DOMException} failure * @returns {void} */ function createSysDB(__openDatabase, success, failure) { function sysDbCreateError(tx, err) { err = webSQLErrback(err || tx); CFG.DEBUG && console.log('Error in sysdb transaction - when creating dbVersions', err); failure(err); } if (sysdb) { success(); } else { sysdb = __openDatabase(typeof CFG.memoryDatabase === 'string' ? CFG.memoryDatabase : path.join(typeof CFG.sysDatabaseBasePath === 'string' ? CFG.sysDatabaseBasePath : CFG.databaseBasePath || '', '__sysdb__' + (CFG.addSQLiteExtension !== false ? '.sqlite' : '')), 1, 'System Database', CFG.DEFAULT_DB_SIZE); sysdb.transaction(function (systx) { systx.executeSql('CREATE TABLE IF NOT EXISTS dbVersions (name BLOB, version INT);', [], function (systx) { if (!CFG.useSQLiteIndexes) { success(); return; } systx.executeSql('CREATE INDEX IF NOT EXISTS dbvname ON dbVersions(name)', [], success, sysDbCreateError); }, sysDbCreateError); }, sysDbCreateError); } } /** * IDBFactory Class. * @see https://w3c.github.io/IndexedDB/#idl-def-IDBFactory * @class */ function IDBFactory() { throw new TypeError('Illegal constructor'); } const IDBFactoryAlias = IDBFactory; IDBFactory.__createInstance = function () { function IDBFactory() { this[Symbol.toStringTag] = 'IDBFactory'; this.__connections = {}; } IDBFactory.prototype = IDBFactoryAlias.prototype; return new IDBFactory(); }; /* eslint-disable jsdoc/check-param-names */ /** * The IndexedDB Method to create a new database and return the DB. * @param {string} name * @param {number} version * @throws {TypeError} Illegal invocation or no arguments (for database name) * @returns {IDBOpenDBRequest} */ IDBFactory.prototype.open = function (name /* , version */ ) { /* eslint-enable jsdoc/check-param-names */ const me = this; if (!(me instanceof IDBFactory)) { throw new TypeError('Illegal invocation'); } // eslint-disable-next-line prefer-rest-params let version = arguments[1]; if (arguments.length === 0) { throw new TypeError('Database name is required'); } if (version !== undefined) { version = enforceRange(version, 'unsigned long long'); if (version === 0) { throw new TypeError('Version cannot be 0'); } } if (hasNullOrigin()) { throw createDOMException('SecurityError', 'Cannot open an IndexedDB database from an opaque origin.'); } const req = IDBOpenDBRequest.__createInstance(); let calledDbCreateError = false; if (CFG.autoName && name === '') { name = 'autoNamedDatabase_' + nameCounter++; } name = String(name); // cast to a string const sqlSafeName = escapeSQLiteStatement(name); const useMemoryDatabase = typeof CFG.memoryDatabase === 'string'; const useDatabaseCache = CFG.cacheDatabaseInstances !== false || useMemoryDatabase; let escapedDatabaseName; // eslint-disable-next-line no-useless-catch try { escapedDatabaseName = escapeDatabaseNameForSQLAndFiles(name); // eslint-disable-next-line sonarjs/no-useless-catch } catch (err) { throw err; // new TypeError('You have supplied a database name which does not match the currently supported configuration, possibly due to a length limit enforced for Node compatibility.'); } function dbCreateError(tx, err) { if (calledDbCreateError) { return; } err = err ? webSQLErrback(err) : tx; calledDbCreateError = true; // Re: why bubbling here (and how cancelable is only really relevant for `window.onerror`) see: https://github.com/w3c/IndexedDB/issues/86 const evt = createEvent('error', err, { bubbles: true, cancelable: true }); req.__done = true; req.__error = err; req.__result = undefined; // Must be undefined if an error per `result` getter req.dispatchEvent(evt); } function setupDatabase(tx, db, oldVersion) { tx.executeSql('SELECT "name", "keyPath", "autoInc", "indexList" FROM __sys__', [], function (tx, data) { function finishRequest() { req.__result = connection; req.__done = true; } const connection = IDBDatabase.__createInstance(db, name, oldVersion, version, data); if (!me.__connections[name]) { me.__connections[name] = []; } me.__connections[name].push(connection); if (oldVersion < version) { const openConnections = me.__connections[name].slice(0, -1); triggerAnyVersionChangeAndBlockedEvents(openConnections, req, oldVersion, version).then(function () { // DB Upgrade in progress let sysdbFinishedCb = function (systx, err, cb) { if (err) { try { systx.executeSql('ROLLBACK', [], cb, cb); } catch (er) { // Browser may fail with expired transaction above so // no choice but to manually revert sysdb.transaction(function (systx) { function reportError(msg) { throw new Error('Unable to roll back upgrade transaction!' + (msg || '')); } // Attempt to revert if (oldVersion === 0) { systx.executeSql('DELETE FROM dbVersions WHERE "name" = ?', [sqlSafeName], function () { cb(reportError); // eslint-disable-line promise/no-callback-in-promise }, reportError); } else { systx.executeSql('UPDATE dbVersions SET "version" = ? WHERE "name" = ?', [oldVersion, sqlSafeName], cb, reportError); } }); } return; } // In browser, should auto-commit cb(); // eslint-disable-line promise/no-callback-in-promise }; sysdb.transaction(function (systx) { function versionSet() { const e = new IDBVersionChangeEvent('upgradeneeded', { oldVersion, newVersion: version }); req.__result = connection; connection.__upgradeTransaction = req.__transaction = req.__result.__versionTransaction = IDBTransaction.__createInstance(req.__result, req.__result.objectStoreNames, 'versionchange'); req.__done = true; req.transaction.__addNonRequestToTransactionQueue(function onupgradeneeded(tx, args, finished, error) { req.dispatchEvent(e); if (e.__legacyOutputDidListenersThrowError) { logError('Error', 'An error occurred in an upgradeneeded handler attached to request chain', e.__legacyOutputDidListenersThrowError); // We do nothing else with this error as per spec req.transaction.__abortTransaction(createDOMException('AbortError', 'A request was aborted.')); return; } finished(); }); req.transaction.on__beforecomplete = function (ev) { connection.__upgradeTransaction = null; req.__result.__versionTransaction = null; sysdbFinishedCb(systx, false, function () { req.transaction.__transFinishedCb(false, function () { ev.complete(); req.__transaction = null; }); }); }; req.transaction.on__preabort = function () { connection.__upgradeTransaction = null; // We ensure any cache is deleted before any request error events fire and try to reopen if (useDatabaseCache) { if (name in websqlDBCache) { delete websqlDBCache[name][version]; } } }; req.transaction.on__abort = function () { req.__transaction = null; // `readyState` and `result` will be reset anyways by `dbCreateError` but we follow spec. req.__result = undefined; req.__done = false; connection.close(); setTimeout(() => { const err = createDOMException('AbortError', 'The upgrade transaction was aborted.'); sysdbFinishedCb(systx, err, function (reportError) { if (oldVersion === 0) { cleanupDatabaseResources(me.__openDatabase, name, escapedDatabaseName, dbCreateError.bind(null, err), reportError || dbCreateError); return; } dbCreateError(err); }); }); }; req.transaction.on__complete = function () { if (req.__result.__closePending) { req.__transaction = null; const err = createDOMException('AbortError', 'The connection has been closed.'); dbCreateError(err); return; } // Since this is running directly after `IDBTransaction.complete`, // there should be a new task. However, while increasing the // timeout 1ms in `IDBTransaction.__executeRequests` can allow // `IDBOpenDBRequest.onsuccess` to trigger faster than a new // transaction as required by "transaction-create_in_versionchange" in // w3c/Transaction.js (though still on a timeout separate from this // preceding `IDBTransaction.oncomplete`), this causes a race condition // somehow with old transactions (e.g., for the Mocha test, // in `IDBObjectStore.deleteIndex`, "should delete an index that was // created in a previous transaction"). // setTimeout(() => { finishRequest(); req.__transaction = null; const e = createEvent('success'); req.dispatchEvent(e); // }); }; } if (oldVersion === 0) { systx.executeSql('INSERT INTO dbVersions VALUES (?,?)', [sqlSafeName, version], versionSet, dbCreateError); } else { systx.executeSql('UPDATE dbVersions SET "version" = ? WHERE "name" = ?', [version, sqlSafeName], versionSet, dbCreateError); } }, dbCreateError, null, function (currentTask, err, done, rollback, commit) { if (currentTask.readOnly || err) { return true; } sysdbFinishedCb = function (systx, err, cb) { if (err) { rollback(err, cb); } else { commit(cb); } }; return false; }); return undefined; }).catch(err => { console.log('Error within `triggerAnyVersionChangeAndBlockedEvents`'); throw err; }); } else { finishRequest(); const e = createEvent('success'); req.dispatchEvent(e); } }, dbCreateError); } function openDB(oldVersion) { let db; if ((useMemoryDatabase || useDatabaseCache) && name in websqlDBCache && websqlDBCache[name][version]) { db = websqlDBCache[name][version]; } else { db = me.__openDatabase(useMemoryDatabase ? CFG.memoryDatabase : path.join(CFG.databaseBasePath || '', escapedDatabaseName), 1, name, CFG.DEFAULT_DB_SIZE); if (useDatabaseCache) { if (!(name in websqlDBCache)) { websqlDBCache[name] = {}; } websqlDBCache[name][version] = db; } } if (version === undefined) { version = oldVersion || 1; } if (oldVersion > version) { const err = createDOMException('VersionError', 'An attempt was made to open a database using a lower version than the existing version.', version); if (useDatabaseCache) { setTimeout(() => { dbCreateError(err); }); } else { dbCreateError(err); } return; } db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS __sys__ (name BLOB, keyPath BLOB, autoInc BOOLEAN, indexList BLOB, currNum INTEGER)', [], function () { function setup() { setupDatabase(tx, db, oldVersion); } if (!CFG.createIndexes) { setup(); return; } tx.executeSql('CREATE INDEX IF NOT EXISTS sysname ON __sys__(name)', [], setup, dbCreateError); }, dbCreateError); }, dbCreateError); } addRequestToConnectionQueue(req, name, /* origin */ undefined, function (req) { let latestCachedVersion; if (useDatabaseCache) { if (!(name in websqlDBCache)) { websqlDBCache[name] = {}; } latestCachedVersion = getLatestCachedWebSQLVersion(name); } if (latestCachedVersion) { openDB(latestCachedVersion); } else { createSysDB(me.__openDatabase, function () { sysdb.readTransaction(function (sysReadTx) { sysReadTx.executeSql('SELECT "version" FROM dbVersions WHERE "name" = ?', [sqlSafeName], function (sysReadTx, data) { if (data.rows.length === 0) { // Database with this name does not exist openDB(0); } else { openDB(data.rows.item(0).version); } }, dbCreateError); }, dbCreateError); }, dbCreateError); } }); return req; }; /** * Deletes a database. * @param {string} name * @returns {IDBOpenDBRequest} */ IDBFactory.prototype.deleteDatabase = function (name) { const me = this; if (!(me instanceof IDBFactory)) { throw new TypeError('Illegal invocation'); } if (arguments.length === 0) { throw new TypeError('Database name is required'); } if (hasNullOrigin()) { throw createDOMException('SecurityError', 'Cannot delete an IndexedDB database from an opaque origin.'); } name = String(name); // cast to a string const sqlSafeName = escapeSQLiteStatement(name); let escapedDatabaseName; // eslint-disable-next-line no-useless-catch try { escapedDatabaseName = escapeDatabaseNameForSQLAndFiles(name); // eslint-disable-next-line sonarjs/no-useless-catch } catch (err) { throw err; // throw new TypeError('You have supplied a database name which does not match the currently supported configuration, possibly due to a length limit enforced for Node compatibility.'); } const useMemoryDatabase = typeof CFG.memoryDatabase === 'string'; const useDatabaseCache = CFG.cacheDatabaseInstances !== false || useMemoryDatabase; const req = IDBOpenDBRequest.__createInstance(); let calledDBError = false; let version = 0; let sysdbFinishedCbDelete = function (err, cb) { cb(err); }; // Although the spec has no specific conditions where an error // may occur in `deleteDatabase`, it does provide for // `UnknownError` as we may require upon a SQL deletion error function dbError(tx, err) { if (calledDBError || err === true) { return; } err = webSQLErrback(err || tx); sysdbFinishedCbDelete(true, function () { req.__done = true; req.__error = err; req.__result = undefined; // Must be undefined if an error per `result` getter // Re: why bubbling here (and how cancelable is only really relevant for `window.onerror`) see: https://github.com/w3c/IndexedDB/issues/86 const e = createEvent('error', err, { bubbles: true, cancelable: true }); req.dispatchEvent(e); calledDBError = true; }); } addRequestToConnectionQueue(req, name, /* origin */ undefined, function (req) { createSysDB(me.__openDatabase, function () { // function callback (cb) { cb(); } // callback(function () { function completeDatabaseDelete() { req.__result = undefined; req.__done = true; const e = new IDBVersionChangeEvent('success', { oldVersion: version, newVersion: null }); req.dispatchEvent(e); } function databaseDeleted() { sysdbFinishedCbDelete(false, function () { if (useDatabaseCache && name in websqlDBCache) { delete websqlDBCache[name]; // New calls will treat as though never existed } delete me.__connections[name]; completeDatabaseDelete(); }); } sysdb.readTransaction(function (sysReadTx) { sysReadTx.executeSql('SELECT "version" FROM dbVersions WHERE "name" = ?', [sqlSafeName], function (sysReadTx, data) { if (data.rows.length === 0) { completeDatabaseDelete(); return undefined; } ({ version } = data.rows.item(0)); const openConnections = me.__connections[name] || []; triggerAnyVersionChangeAndBlockedEvents(openConnections, req, version, null).then(function () { // eslint-disable-line promise/catch-or-return // Since we need two databases which can't be in a single transaction, we // do this deleting from `dbVersions` first since the `__sys__` deleting // only impacts file memory whereas this one is critical for avoiding it // being found via `open` or `databases`; however, we will // avoid committing anyways until all deletions are made and rollback the // `dbVersions` change if they fail sysdb.transaction(function (systx) { systx.executeSql('DELETE FROM dbVersions WHERE "name" = ? ', [sqlSafeName], function () { // Todo: We should also check whether `dbVersions` is empty and if so, delete upon // `deleteDatabaseFiles` config. We also ought to do this when aborting (see // above code with `DELETE FROM dbVersions`) cleanupDatabaseResources(me.__openDatabase, name, escapedDatabaseName, databaseDeleted, dbError); }, dbError); }, dbError, null, function (currentTask, err, done, rollback, commit) { if (currentTask.readOnly || err) { return true; } sysdbFinishedCbDelete = function (err, cb) { if (err) { rollback(err, cb); } else { commit(cb); } }; return false; }); return undefined; }, dbError); return undefined; }, dbError); }); }, dbError); }); return req; }; IDBFactory.prototype.cmp = function (key1, key2) { if (!(this instanceof IDBFactory)) { throw new TypeError('Illegal invocation'); } if (arguments.length < 2) { throw new TypeError('You must provide two keys to be compared'); } // We use encoding facilities already built for proper sorting; // the following "conversions" are for validation only convertValueToKeyRethrowingAndIfInvalid(key1); convertValueToKeyRethrowingAndIfInvalid(key2); return cmp(key1, key2); }; /** * May return outdated information if a database has since been deleted. * @see https://github.com/w3c/IndexedDB/pull/240/files * @returns {Promise<string[]>} */ IDBFactory.prototype.databases = function () { const me = this; let calledDbCreateError = false; return new Promise(function (resolve, reject) { // eslint-disable-line promise/avoid-new if (!(me instanceof IDBFactory)) { throw new TypeError('Illegal invocation'); } if (hasNullOrigin()) { throw createDOMException('SecurityError', 'Cannot get IndexedDB database names from an opaque origin.'); } function dbGetDatabaseNamesError(tx, err) { if (calledDbCreateError) { return; } err = err ? webSQLErrback(err) : tx; calledDbCreateError = true; reject(err); } createSysDB(me.__openDatabase, function () { sysdb.readTransaction(function (sysReadTx) { sysReadTx.executeSql('SELECT "name", "version" FROM dbVersions', [], function (sysReadTx, data) { const dbNames = []; for (let i = 0; i < data.rows.length; i++) { const { name, version } = data.rows.item(i); dbNames.push({ name: unescapeSQLiteResponse(name), version }); } resolve(dbNames); }, dbGetDatabaseNamesError); }, dbGetDatabaseNamesError); }, dbGetDatabaseNamesError); }); }; /** * @todo forceClose: Test * This is provided to facilitate unit-testing of the * closing of a database connection with a forced flag: * <http://w3c.github.io/IndexedDB/#steps-for-closing-a-database-connection> * @param {string} dbName * @param {Integer} connIdx * @param {string} msg * @throws {TypeError} * @returns {void} */ IDBFactory.prototype.__forceClose = function (dbName, connIdx, msg) { const me = this; function forceClose(conn) { conn.__forceClose(msg); } if (isNullish(dbName)) { Object.values(me.__connections).forEach(conn => { forceClose(conn); }); } else if (!me.__connections[dbName]) { console.log('No database connections with that name to force close'); } else if (isNullish(connIdx)) { me.__connections[dbName].forEach(conn => { forceClose(conn); }); } else if (!Number.isInteger(connIdx) || connIdx < 0 || connIdx > me.__connections[dbName].length - 1) { throw new TypeError('If providing an argument, __forceClose must be called with a ' + 'numeric index to indicate a specific connection to lose'); } else { forceClose(me.__connections[dbName][connIdx]); } }; IDBFactory.prototype.__setConnectionQueueOrigin = function (origin = getOrigin()) { connectionQueue[origin] = {}; }; IDBFactory.prototype[Symbol.toStringTag] = 'IDBFactoryPrototype'; Object.defineProperty(IDBFactory, 'prototype', { writable: false }); const shimIndexedDB = IDBFactory.__createInstance(); function IDBCursor() { throw new TypeError('Illegal constructor'); } const IDBCursorAlias = IDBCursor; /* eslint-disable func-name-matching */ /** * The IndexedDB Cursor Object. * @see http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBCursor * @param {IDBKeyRange} query * @param {string} direction * @param {IDBObjectStore} store * @param {IDBObjectStore|IDBIndex} source * @param {string} keyColumnName * @param {string} valueColumnName * @param {boolean} count * @returns {void} */ IDBCursor.__super = function IDBCursor(query, direction, store, source, keyColumnName, valueColumnName, count) { /* eslint-enable func-name-matching */ this[Symbol.toStringTag] = 'IDBCursor'; defineReadonlyProperties(this, ['key', 'primaryKey', 'request']); IDBObjectStore.__invalidStateIfDeleted(store); this.__indexSource = instanceOf(source, IDBIndex); if (this.__indexSource) IDBIndex.__invalidStateIfDeleted(source); IDBTransaction.__assertActive(store.transaction); const range = convertValueToKeyRange(query); if (direction !== undefined && !['next', 'prev', 'nextunique', 'prevunique'].includes(direction)) { throw new TypeError(direction + 'is not a valid cursor direction'); } Object.defineProperties(this, { // Babel is not respecting default writable false here, so make explicit source: { writable: false, value: source }, direction: { writable: false, value: direction || 'next' } }); this.__key = undefined; this.__primaryKey = undefined; this.__store = store; this.__range = range; this.__request = IDBRequest.__createInstance(); this.__request.__source = source; this.__request.__transaction = this.__store.transaction; this.__keyColumnName = keyColumnName; this.__valueColumnName = valueColumnName; this.__keyOnly = valueColumnName === 'key'; this.__valueDecoder = this.__keyOnly ? Key : Sca; this.__count = count; this.__prefetchedIndex = -1; this.__multiEntryIndex = this.__indexSource ? source.multiEntry : false; this.__unique = this.direction.includes('unique'); this.__sqlDirection = ['prev', 'prevunique'].includes(this.direction) ? 'DESC' : 'ASC'; if (range !== undefined) { // Encode the key range and cache the encoded values, so we don't have to re-encode them over and over range.__lowerCached = range.lower !== undefined && encode(range.lower, this.__multiEntryIndex); range.__upperCached = range.upper !== undefined && encode(range.upper, this.__multiEntryIndex); } this.__gotValue = true; this.continue(); }; IDBCursor.__createInstance = function (...args) { const IDBCursor = IDBCursorAlias.__super; IDBCursor.prototype = IDBCursorAlias.prototype; return new IDBCursor(...args); }; IDBCursor.prototype.__find = function (...args /* key, tx, success, error, recordsToLoad */ ) { if (this.__multiEntryIndex) { this.__findMultiEntry(...args); } else { this.__findBasic(...args); } }; IDBCursor.prototype.__findBasic = function (key, primaryKey, tx, success, error, recordsToLoad) { const continueCall = recordsToLoad !== undefined; recordsToLoad = recordsToLoad || 1; const me = this; const quotedKeyColumnName = sqlQuote(me.__keyColumnName); const quotedKey = sqlQuote('key'); let sql = ['SELECT * FROM', escapeStoreNameForSQL(me.__store.__currentName)]; const sqlValues = []; sql.push('WHERE', quotedKeyColumnName, 'NOT NULL'); setSQLForKeyRange(me.__range, quotedKeyColumnName, sql, sqlValues, true, true); // Determine the ORDER BY direction based on the cursor. const direction = me.__sqlDirection; const op = direction === 'ASC' ? '>' : '<'; if (primaryKey !== undefined) { sql.push('AND', quotedKey, op + '= ?'); // Key.convertValueToKey(primaryKey); // Already checked by `continuePrimaryKey` sqlValues.push(encode(primaryKey)); } if (key !== undefined) { sql.push('AND', quotedKeyColumnName, op + '= ?'); // Key.convertValueToKey(key); // Already checked by `continue` or `continuePrimaryKey` sqlValues.push(encode(key)); } else if (continueCall && me.__key !== undefined) { sql.push('AND', quotedKeyColumnName, op + ' ?'); // Key.convertValueToKey(me.__key); // Already checked when stored sqlValues.push(encode(me.__key)); } if (!me.__count) { // 1. Sort by key sql.push('ORDER BY', quotedKeyColumnName, direction); if (me.__keyColumnName !== 'key') { // Avoid adding 'key' twice if (!me.__unique) { // 2. Sort by primaryKey (if defined and not unique) // 3. Sort by position (if defined) sql.push(',', quotedKey, direction); } else if (me.direction === 'prevunique') { // Sort by first record with key matching sql.push(',', quotedKey, 'ASC'); } } if (!me.__unique && me.__indexSource) { // 4. Sort by object store position (if defined and not unique) sql.push(',', sqlQuote(me.__valueColumnName), direction); } sql.push('LIMIT', recordsToLoad); } sql = sql.join(' '); CFG.DEBUG && console.log(sql, sqlValues); tx.executeSql(sql, sqlValues, function (tx, data) { if (me.__count) { success(undefined, data.rows.length, undefined); } else if (data.rows.length > 1) { me.__prefetchedIndex = 0; me.__prefetchedData = data.rows; CFG.DEBUG && console.log('Preloaded ' + me.__prefetchedData.length + ' records for cursor'); me.__decode(data.rows.item(0), success); } else if (data.rows.length === 1) { me.__decode(data.rows.item(0), success); } else { CFG.DEBUG && console.log('Reached end of cursors'); success(undefined, undefined, undefined); } }, function (tx, err) { CFG.DEBUG && console.log('Could not execute Cursor.continue', sql, sqlValues); error(err); }); }; const leftBracketRegex = /\[/gu; IDBCursor.prototype.__findMultiEntry = function (key, primaryKey, tx, success, error) { const me = this; if (me.__prefetchedData && me.__prefetchedData.length === me.__prefetchedIndex) { CFG.DEBUG && console.log('Reached end of multiEntry cursor'); success(undefined, undefined, undefined); return; } const quotedKeyColumnName = sqlQuote(me.__keyColumnName); let sql = ['SELECT * FROM', escapeStoreNameForSQL(me.__store.__currentName)]; const sqlValues = []; sql.push('WHERE', quotedKeyColumnName, 'NOT NULL'); if (me.__range && me.__range.lower !== undefined && Array.isArray(me.__range.upper)) { if (me.__range.upper.indexOf(me.__range.lower) === 0) { sql.push('AND', quotedKeyColumnName, "LIKE ? ESCAPE '^'"); sqlValues.push('%' + sqlLIKEEscape(me.__range.__lowerCached.slice(0, -1)) + '%'); } } // Determine the ORDER BY direction based on the cursor. const direction = me.__sqlDirection; const op = direction === 'ASC' ? '>' : '<'; const quotedKey = sqlQuote('key'); if (primaryKey !== undefined) { sql.push('AND', quotedKey, op + '= ?'); // Key.convertValueToKey(primaryKey); // Already checked by `continuePrimaryKey` sqlValues.push(encode(primaryKey)); } if (key !== undefined) { sql.push('AND', quotedKeyColumnName, op + '= ?'); // Key.convertValueToKey(key); // Already checked by `continue` or `continuePrimaryKey` sqlValues.push(encode(key)); } else if (me.__key !== undefined) { sql.push('AND', quotedKeyColumnName, op + ' ?'); // Key.convertValueToKey(me.__key); // Already checked when entered sqlValues.push(encode(me.__key)); } if (!me.__count) { // 1. Sort by key sql.push('ORDER BY', quotedKeyColumnName, direction); // 2. Sort by primaryKey (if defined and not unique) if (!me.__unique && me.__keyColumnName !== 'key') { // Avoid adding 'key' twice sql.push(',', sqlQuote('key'), direction); } // 3. Sort by position (if defined) if (!me.__unique && me.__indexSource) { // 4. Sort by object store position (if defined and not unique) sql.push(',', sqlQuote(me.__valueColumnName), direction); } } sql = sql.join(' '); CFG.DEBUG && console.log(sql, sqlValues); tx.executeSql(sql, sqlValues, function (tx, data) { if (data.rows.length > 0) { if (me.__count) { // Avoid caching and other processing below let ct = 0; for (let i = 0; i < data.rows.length; i++) { const rowItem = data.rows.item(i); const rowKey = decode(rowItem[me.__keyColumnName], true); const matches = findMultiEntryMatches(rowKey, me.__range); ct += matches.length; } success(undefined, ct, undefined); return; } const rows = []; for (let i = 0; i < data.rows.length; i++) { const rowItem = data.rows.item(i); const rowKey = decode(rowItem[me.__keyColumnName], true); const matches = findMultiEntryMatches(rowKey, me.__range); for (const matchingKey of matches) { const clone = { matchingKey: encode(matchingKey, true), key: rowItem.key }; clone[me.__keyColumnName] = rowItem[me.__keyColumnName]; clone[me.__valueColumnName] = rowItem[me.__valueColumnName]; rows.push(clone); } } const reverse = me.direction.indexOf('prev') === 0; rows.sort(function (a, b) { if (a.matchingKey.replace(leftBracketRegex, 'z') < b.matchingKey.replace(leftBracketRegex, 'z')) { return reverse ? 1 : -1; } if (a.matchingKey.replace(leftBracketRegex, 'z') > b.matchingKey.replace(leftBracketRegex, 'z')) { return reverse ? -1 : 1; } if (a.key < b.key) { return me.direction === 'prev' ? 1 : -1; } if (a.key > b.key) { return me.direction === 'prev' ? -1 : 1; } return 0; }); if (rows.length > 1) { me.__prefetchedIndex = 0; me.__prefetchedData = { data: rows, length: rows.length, item(index) { return this.data[index]; } }; CFG.DEBUG && console.log('Preloaded ' + me.__prefetchedData.length + ' records for multiEntry cursor'); me.__decode(rows[0], success); } else if (rows.length === 1) { CFG.DEBUG && console.log('Reached end of multiEntry cursor'); me.__decode(rows[0], success); } else { CFG.DEBUG && console.log('Reached end of multiEntry cursor'); success(undefined, undefined, undefined); } } else { CFG.DEBUG && console.log('Reached end of multiEntry cursor'); success(undefined, undefined, undefined); } }, function (tx, err) { CFG.DEBUG && console.log('Could not execute Cursor.continue', sql, sqlValues); error(err); }); }; /** * @callback module:IDBCursor.SuccessArg * @param value * @param {IDBRequest} req * @returns {void} */ /** * @callback module:IDBCursor.SuccessCallback * @param key * @param value * @param primaryKey * @returns {void} */ /** * Creates an "onsuccess" callback. * @private * @param {module:IDBCursor.SuccessArg} success * @returns {module:IDBCursor.SuccessCallback} */ IDBCursor.prototype.__onsuccess = function (success) { const me = this; return function (key, value, primaryKey) { if (me.__count) { success(value, me.__request); } else { if (key !== undefined) { me.__gotValue = true; } me.__key = key === undefined ? null : key; me.__primaryKey = primaryKey === undefined ? null : primaryKey; me.__value = value === undefined ? null : value; const result = key === undefined ? null : me; success(result, me.__request); } }; }; IDBCursor.prototype.__decode = function (rowItem, callback) { const me = this; if (me.__multiEntryIndex && me.__unique) { if (!me.__matchedKeys) { me.__matchedKeys = {}; } if (me.__matchedKeys[rowItem.matchingKey]) { callback(undefined, undefined, undefined); return; } me.__matchedKeys[rowItem.matchingKey] = true; } const encKey = unescapeSQLiteResponse(me.__multiEntryIndex ? rowItem.matchingKey : rowItem[me.__keyColumnName]); const encVal = unescapeSQLiteResponse(rowItem[me.__valueColumnName]); const encPrimaryKey = unescapeSQLiteResponse(rowItem.key); const key = decode(encKey, me.__multiEntryIndex); const val = me.__valueDecoder.decode(encVal); const primaryKey = decode(encPrimaryKey); callback(key, val, primaryKey, encKey /*, encVal, encPrimaryKey */ ); }; IDBCursor.prototype.__sourceOrEffectiveObjStoreDeleted = function () { IDBObjectStore.__invalidStateIfDeleted(this.__store, "The cursor's effective object store has been deleted"); if (this.__indexSource) IDBIndex.__invalidStateIfDeleted(this.source, "The cursor's index source has been deleted"); }; IDBCursor.prototype.__invalidateCache = function () { this.__prefetchedData = null; }; IDBCursor.prototype.__continue = function (key, advanceContinue) { const me = this; const advanceState = me.__advanceCount !== undefined; IDBTransaction.__assertActive(me.__store.transaction); me.__sourceOrEffectiveObjStoreDeleted(); if (!me.__gotValue && !advanceContinue) { throw createDOMException('InvalidStateError', 'The cursor is being iterated or has iterated past its end.'); } if (key !== undefined) { convertValueToKeyRethrowingAndIfInvalid(key); const cmpResult = cmp(key, me.key); if (cmpResult === 0 || me.direction.includes('next') && cmpResult === -1 || me.direction.includes('prev') && cmpResult === 1) { throw createDOMException('DataError', 'Cannot ' + (advanceState ? 'advance' : 'continue') + ' the cursor in an unexpected direction'); } } this.__continueFinish(key, undefined, advanceState); }; IDBCursor.prototype.__continueFinish = function (key, primaryKey, advanceState) { const me = this; const recordsToPreloadOnContinue = me.__advanceCount || CFG.cursorPreloadPackSize || 100; me.__gotValue = false; me.__request.__done = false; me.__store.transaction.__pushToQueue(me.__request, function cursorContinue(tx, args, success, error, executeNextRequest) { function triggerSuccess(k, val, primKey) { if (advanceState) { if (me.__advanceCount >= 2 && k !== undefined) { me.__advanceCount--; me.__key = k; me.__continue(undefined, true); executeNextRequest(); // We don't call success yet but do need to advance the transaction queue return; } me.__advanceCount = undefined; } me.__onsuccess(success)(k, val, primKey); } if (me.__prefetchedData) { // We have pre-loaded data for the cursor me.__prefetchedIndex++; if (me.__prefetchedIndex < me.__prefetchedData.length) { me.__decode(me.__prefetchedData.item(me.__prefetchedIndex), function (k, val, primKey, encKey) { function checkKey() { const cmpResult = key === undefined || cmp(k, key); if (cmpResult > 0 || cmpResult === 0 && (me.__unique || primaryKey === undefined || cmp(primKey, primaryKey) >= 0)) { triggerSuccess(k, val, primKey); return; } cursorContinue(tx, args, success, error); } if (me.__unique && !me.__multiEntryIndex && encKey === encode(me.key, me.__multiEntryIndex)) { cursorContinue(tx, args, success, error); return; } checkKey(); }); return; } } // No (or not enough) pre-fetched data, do query me.__find(key, primaryKey, tx, triggerSuccess, function (...args) { me.__advanceCount = undefined; error(...args); }, recordsToPreloadOnContinue); }); }; IDBCursor.prototype.continue = function () /* key */ { // eslint-disable-next-line prefer-rest-params this.__continue(arguments[0]); }; IDBCursor.prototype.continuePrimaryKey = function (key, primaryKey) { const me = this; IDBTransaction.__assertActive(me.__store.transaction); me.__sourceOrEffectiveObjStoreDeleted(); if (!me.__indexSource) { throw createDOMException('InvalidAccessError', '`continuePrimaryKey` may only be called on an index source.'); } if (!['next', 'prev'].includes(me.direction)) { throw createDOMException('InvalidAccessError', '`continuePrimaryKey` may not be called with unique cursors.'); } if (!me.__gotValue) { throw createDOMException('InvalidStateError', 'The cursor is being iterated or has iterated past its end.'); } convertValueToKeyRethrowingAndIfInvalid(key); convertValueToKeyRethrowingAndIfInvalid(primaryKey); const cmpResult = cmp(key, me.key); if (me.direction === 'next' && cmpResult === -1 || me.direction === 'prev' && cmpResult === 1) { throw createDOMException('DataError', 'Cannot continue the cursor in an unexpected direction'); } function noErrors() { me.__continueFinish(key, primaryKey, false); } if (cmpResult === 0) { encode$2(primaryKey, function (encPrimaryKey) { encode$2(me.primaryKey, function (encObjectStorePos) { if (encPrimaryKey === encObjectStorePos || me.direction === 'next' && encPrimaryKey < encObjectStorePos || me.direction === 'prev' && encPrimaryKey > encObjectStorePos) { throw createDOMException('DataError', 'Cannot continue the cursor in an unexpected direction'); } noErrors(); }); }); } else { noErrors(); } }; IDBCursor.prototype.advance = function (count) { const me = this; count = enforceRange(count, 'unsigned long'); if (count === 0) { throw new TypeError('Calling advance() with count argument 0'); } if (me.__gotValue) { // Only set the count if not running in error (otherwise will override earlier good advance calls) me.__advanceCount = count; } me.__continue(); }; IDBCursor.prototype.update = function (valueToUpdate) { const me = this; if (!arguments.length) throw new TypeError('A value must be passed to update()'); IDBTransaction.__assertActive(me.__store.transaction); me.__store.transaction.__assertWritable(); me.__sourceOrEffectiveObjStoreDeleted(); if (!me.__gotValue) { throw createDOMException('InvalidStateError', 'The cursor is being iterated or has iterated past its end.'); } if (me.__keyOnly) { throw createDOMException('InvalidStateError', 'This cursor method cannot be called when the key only flag has been set.'); } const request = me.__store.transaction.__createRequest(me); const key = me.primaryKey; function addToQueue(clonedValue) { // We set the `invalidateCache` argument to `false` since the old value shouldn't be accessed IDBObjectStore.__storingRecordObjectStore(request, me.__store, false, clonedValue, false, key); } if (me.__store.keyPath !== null) { const [evaluatedKey, clonedValue] = me.__store.__validateKeyAndValueAndCloneValue(valueToUpdate, undefined, true); if (cmp(me.primaryKey, evaluatedKey) !== 0) { throw createDOMException('DataError', 'The key of the supplied value to `update` is not equal to the cursor\'s effective key'); } addToQueue(clonedValue); } else { const clonedValue = clone(valueToUpdate); addToQueue(clonedValue); } return request; }; IDBCursor.prototype.delete = function () { const me = this; IDBTransaction.__assertActive(me.__store.transaction); me.__store.transaction.__assertWritable(); me.__sourceOrEffectiveObjStoreDeleted(); if (!me.__gotValue) { throw createDOMException('InvalidStateError', 'The cursor is being iterated or has iterated past its end.'); } if (me.__keyOnly) { throw createDOMException('InvalidStateError', 'This cursor method cannot be called when the key only flag has been set.'); } return this.__store.transaction.__addToTransactionQueue(function cursorDelete(tx, args, success, error) { me.__find(undefined, undefined, tx, function (key, value, primaryKey) { const sql = 'DELETE FROM ' + escapeStoreNameForSQL(me.__store.__currentName) + ' WHERE "key" = ?'; CFG.DEBUG && console.log(sql, key, primaryKey); // Key.convertValueToKey(primaryKey); // Already checked when entered tx.executeSql(sql, [escapeSQLiteStatement(encode(primaryKey))], function (tx, data) { if (data.rowsAffected === 1) { // We don't invalidate the cache (as we don't access it anymore // and it will set the index off) success(undefined); } else { error('No rows with key found' + key); } }, function (tx, data) { error(data); }); }, error); }, undefined, me); }; IDBCursor.prototype[Symbol.toStringTag] = 'IDBCursorPrototype'; defineReadonlyOuterInterface(IDBCursor.prototype, ['source', 'direction', 'key', 'primaryKey', 'request']); Object.defineProperty(IDBCursor, 'prototype', { writable: false }); function IDBCursorWithValue() { throw new TypeError('Illegal constructor'); } IDBCursorWithValue.prototype = Object.create(IDBCursor.prototype); Object.defineProperty(IDBCursorWithValue.prototype, 'constructor', { enumerable: false, writable: true, configurable: true, value: IDBCursorWithValue }); const IDBCursorWithValueAlias = IDBCursorWithValue; IDBCursorWithValue.__createInstance = function (...args) { function IDBCursorWithValue() { IDBCursor.__super.call(this, ...args); this[Symbol.toStringTag] = 'IDBCursorWithValue'; defineReadonlyProperties(this, 'value'); } IDBCursorWithValue.prototype = IDBCursorWithValueAlias.prototype; return new IDBCursorWithValue(); }; defineReadonlyOuterInterface(IDBCursorWithValue.prototype, ['value']); IDBCursorWithValue.prototype[Symbol.toStringTag] = 'IDBCursorWithValuePrototype'; Object.defineProperty(IDBCursorWithValue, 'prototype', { writable: false }); /* globals self */ function setConfig(prop, val) { if (prop && typeof prop === 'object') { Object.entries(prop).forEach(([p, val]) => { setConfig(p, val); }); return; } if (!(prop in CFG)) { throw new Error(prop + ' is not a valid configuration property'); } CFG[prop] = val; if (prop === 'registerSCA' && typeof val === 'function') { register(val); } } function setGlobalVars(idb, initialConfig) { if (initialConfig) { setConfig(initialConfig); } const IDB = idb || (typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : typeof global !== 'undefined' ? global : {}); function shim(name, value, propDesc) { if (!propDesc || !Object.defineProperty) { try { // Try setting the property. This will fail if the property is read-only. IDB[name] = value; } catch (e) { console.log(e); } } if (IDB[name] !== value && Object.defineProperty) { // Setting a read-only property failed, so try re-defining the property try { let desc = propDesc || {}; if (!('get' in desc)) { if (!('value' in desc)) { desc.value = value; } if (!('writable' in desc)) { desc.writable = true; } } else { const o = { get [name]() { return propDesc.get.call(this); } }; desc = Object.getOwnPropertyDescriptor(o, name); } Object.defineProperty(IDB, name, desc); } catch (e) {// With `indexedDB`, PhantomJS fails here and below but // not above, while Chrome is reverse (and Firefox doesn't // get here since no WebSQL to use for shimming) } } if (IDB[name] !== value) { typeof console !== 'undefined' && console.warn && console.warn('Unable to shim ' + name); } } if (CFG.win.openDatabase !== undefined) { shim('shimIndexedDB', shimIndexedDB, { enumerable: false, configurable: true }); } if (IDB.shimIndexedDB) { IDB.shimIndexedDB.__useShim = function () { function setNonIDBGlobals(prefix = '') { shim(prefix + 'DOMException', ShimDOMException$1); shim(prefix + 'DOMStringList', DOMStringList, { enumerable: false, configurable: true, writable: true, value: DOMStringList }); shim(prefix + 'Event', ShimEvent, { configurable: true, writable: true, value: ShimEvent, enumerable: false }); shim(prefix + 'CustomEvent', ShimCustomEvent, { configurable: true, writable: true, value: ShimCustomEvent, enumerable: false }); shim(prefix + 'EventTarget', EventTarget, { configurable: true, writable: true, value: EventTarget, enumerable: false }); } const shimIDBFactory = IDBFactory; if (CFG.win.openDatabase !== undefined) { shimIndexedDB.__openDatabase = CFG.win.openDatabase.bind(CFG.win); // We cache here in case the function is overwritten later as by the IndexedDB support promises tests // Polyfill ALL of IndexedDB, using WebSQL shim('indexedDB', shimIndexedDB, { enumerable: true, configurable: true, get() { if (this !== IDB && !isNullish(this) && !this.shimNS) { // Latter is hack for test environment throw new TypeError('Illegal invocation'); } return shimIndexedDB; } }); [['IDBFactory', shimIDBFactory], ['IDBDatabase', IDBDatabase], ['IDBObjectStore', IDBObjectStore], ['IDBIndex', IDBIndex], ['IDBTransaction', IDBTransaction], ['IDBCursor', IDBCursor], ['IDBCursorWithValue', IDBCursorWithValue], ['IDBKeyRange', IDBKeyRange], ['IDBRequest', IDBRequest], ['IDBOpenDBRequest', IDBOpenDBRequest], ['IDBVersionChangeEvent', IDBVersionChangeEvent]].forEach(([prop, obj]) => { shim(prop, obj, { enumerable: false, configurable: true }); }); if (CFG.fullIDLSupport) { // Slow per MDN so off by default! Though apparently needed for WebIDL: http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements Object.setPrototypeOf(IDB.IDBOpenDBRequest, IDB.IDBRequest); Object.setPrototypeOf(IDB.IDBCursorWithValue, IDB.IDBCursor); Object.setPrototypeOf(IDBDatabase, EventTarget); Object.setPrototypeOf(IDBRequest, EventTarget); Object.setPrototypeOf(IDBTransaction, EventTarget); Object.setPrototypeOf(IDBVersionChangeEvent, ShimEvent); Object.setPrototypeOf(ShimDOMException$1, Error); Object.setPrototypeOf(ShimDOMException$1.prototype, Error.prototype); setPrototypeOfCustomEvent(); } if (IDB.indexedDB && !IDB.indexedDB.toString().includes('[native code]')) { if (CFG.addNonIDBGlobals) { // As `DOMStringList` exists per IDL (and Chrome) in the global // thread (but not in workers), we prefix the name to avoid // shadowing or conflicts setNonIDBGlobals('Shim'); } if (CFG.replaceNonIDBGlobals) { setNonIDBGlobals(); } } IDB.shimIndexedDB.__setConnectionQueueOrigin(); } }; IDB.shimIndexedDB.__debug = function (val) { CFG.DEBUG = val; }; IDB.shimIndexedDB.__setConfig = setConfig; IDB.shimIndexedDB.__getConfig = function (prop) { if (!(prop in CFG)) { throw new Error(prop + ' is not a valid configuration property'); } return CFG[prop]; }; IDB.shimIndexedDB.__setUnicodeIdentifiers = function ({ UnicodeIDStart, UnicodeIDContinue }) { setConfig({ UnicodeIDStart, UnicodeIDContinue }); }; } else { // We no-op the harmless set-up properties and methods with a warning; the `IDBFactory` methods, // however (including our non-standard methods), are not stubbed as they ought // to fail earlier rather than potentially having side effects. IDB.shimIndexedDB = {}; ['__useShim', '__debug', '__setConfig', '__getConfig', '__setUnicodeIdentifiers'].forEach(prop => { IDB.shimIndexedDB[prop] = function () { console.warn('This browser does not have WebSQL to shim.'); }; }); } // Workaround to prevent an error in Firefox if (!('indexedDB' in IDB) && typeof window !== 'undefined') { // 2nd condition avoids problems in Node IDB.indexedDB = IDB.indexedDB || IDB.webkitIndexedDB || IDB.mozIndexedDB || IDB.oIndexedDB || IDB.msIndexedDB; } // Detect browsers with known IndexedDB issues (e.g. Android pre-4.4) let poorIndexedDbSupport = false; if (typeof navigator !== 'undefined' && // Not apparently defined in React Native navigator.userAgent && ( // Ignore Node or other environments // Bad non-Chrome Android support /Android (?:2|3|4\.[0-3])/u.test(navigator.userAgent) && !navigator.userAgent.includes('Chrome') || // Bad non-Safari iOS9 support (see <https://github.com/axemclion/IndexedDBShim/issues/252>) (!navigator.userAgent.includes('Safari') || navigator.userAgent.includes('Chrome')) && // Exclude genuine Safari: http://stackoverflow.com/a/7768006/271577 // Detect iOS: http://stackoverflow.com/questions/9038625/detect-if-device-is-ios/9039885#9039885 // and detect version 9: http://stackoverflow.com/a/26363560/271577 /(iPad|iPhone|iPod).* os 9_/ui.test(navigator.userAgent) && !window.MSStream // But avoid IE11 )) { poorIndexedDbSupport = true; } if (!CFG.DEFAULT_DB_SIZE) { CFG.DEFAULT_DB_SIZE = ( // Safari currently requires larger size: (We don't need a larger size for Node as node-websql doesn't use this info) // https://github.com/axemclion/IndexedDBShim/issues/41 // https://github.com/axemclion/IndexedDBShim/issues/115 typeof navigator !== 'undefined' && // React Native navigator.userAgent && navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') ? 25 : 4) * 1024 * 1024; } if (!CFG.avoidAutoShim && (!IDB.indexedDB || poorIndexedDbSupport) && CFG.win.openDatabase !== undefined) { IDB.shimIndexedDB.__useShim(); } else { IDB.IDBDatabase = IDB.IDBDatabase || IDB.webkitIDBDatabase; IDB.IDBTransaction = IDB.IDBTransaction || IDB.webkitIDBTransaction || {}; IDB.IDBCursor = IDB.IDBCursor || IDB.webkitIDBCursor; IDB.IDBKeyRange = IDB.IDBKeyRange || IDB.webkitIDBKeyRange; } return IDB; } // Expose for ease in simulating such exceptions during testing function SQLiteResult(error, insertId, rowsAffected, rows) { this.error = error; this.insertId = insertId; this.rowsAffected = rowsAffected; this.rows = rows; } var SQLiteResult_1 = SQLiteResult; var sqlite3 = require('sqlite3'); var READ_ONLY_ERROR = new Error('could not prepare statement (23 not authorized)'); function SQLiteDatabase(name, opts) { opts = opts || {}; this._db = new sqlite3.Database(name); if (opts.busyTimeout) { this._db.configure('busyTimeout', opts.busyTimeout); // Default is 1000 } if (opts.trace) { this._db.configure('trace', opts.trace); } if (opts.profile) { this._db.configure('profile', opts.profile); } } function runSelect(db, sql, args, cb) { db.all(sql, args, function (err, rows) { if (err) { return cb(new SQLiteResult_1(err)); } var insertId = void 0; var rowsAffected = 0; var resultSet = new SQLiteResult_1(null, insertId, rowsAffected, rows); cb(resultSet); }); } function runNonSelect(db, sql, args, cb) { db.run(sql, args, function (err) { if (err) { return cb(new SQLiteResult_1(err)); } /* jshint validthis:true */ var executionResult = this; var insertId = executionResult.lastID; var rowsAffected = executionResult.changes; var rows = []; var resultSet = new SQLiteResult_1(null, insertId, rowsAffected, rows); cb(resultSet); }); } SQLiteDatabase.prototype.exec = function exec(queries, readOnly, callback) { var db = this._db; var len = queries.length; var results = new Array(len); var i = 0; function checkDone() { if (++i === len) { callback(null, results); } else { doNext(); } } function onQueryComplete(i) { return function (res) { results[i] = res; checkDone(); }; } function doNext() { var query = queries[i]; var sql = query.sql; var args = query.args; // TODO: It seems like the node-sqlite3 API either allows: // 1) all(), which returns results but not rowsAffected or lastID // 2) run(), which doesn't return results, but returns rowsAffected and lastID // So we try to sniff whether it's a SELECT query or not. // This is inherently error-prone, although it will probably work in the 99% // case. var isSelect = /^\s*SELECT\b/i.test(sql); if (readOnly && !isSelect) { onQueryComplete(i)(new SQLiteResult_1(READ_ONLY_ERROR)); } else if (isSelect) { runSelect(db, sql, args, onQueryComplete(i)); } else { runNonSelect(db, sql, args, onQueryComplete(i)); } } doNext(); }; var SQLiteDatabase_1 = SQLiteDatabase; function wrappedSQLiteDatabase(name) { const db = new SQLiteDatabase_1(name); if (CFG.sqlBusyTimeout) { db._db.configure('busyTimeout', CFG.sqlBusyTimeout); // Default is 1000 } if (CFG.sqlTrace) { db._db.configure('trace', CFG.sqlTrace); } if (CFG.sqlProfile) { db._db.configure('profile', CFG.sqlProfile); } return db; } const nodeWebSQL = customOpenDatabase(wrappedSQLiteDatabase); CFG.win = { openDatabase: nodeWebSQL }; module.exports = setGlobalVars; //# sourceMappingURL=indexeddbshim-node.js.map
import React, { useState, useCallback } from "react"; import * as S from "./styles"; import ModalForm from "../ModalForm"; import { requestApiWithBodyWithoutToken } from "../../../../lib/REQUEST_API"; import { Register } from "../../../../lib/LOG"; const RegisterModalForm = () => { // registerForm const [localRegisterForm, setLocalRegisterForm] = useState({ id: "", nickname: "", password: "", passwordConfirm: "", }); // isError 상태에 따라 input 박스의 색이 달라지고 input 아래에 에러 메세지 출력 여부가 결정됨 const [isError, setIsError] = useState({ id: false, nickname: false, password: false, passwordConfirm: false, }); // isError 상태가 true일 때 input 아래에 출력되는 에러 메세지 const [errorText, setErrorText] = useState({ id: "", nickname: "", password: "", passwordConfirm: "", }); // id와 닉네임의 중복확인 체크 여부 const [isOkay, setIsOkay] = useState({ id: false, nickname: false, }); // registerForm 변경 const onChangeForm = useCallback( (e) => { setLocalRegisterForm({ ...localRegisterForm, [e.target.name]: e.target.value, }); }, [localRegisterForm], ); // 중복 확인 const onClickOverlap = (e) => { switch (e.target.name) { case "id": { // 아이디 공란인지 검사 if (localRegisterForm.id === "") { setIsError({ ...isError, id: true }); setErrorText({ ...errorText, id: "아이디를 입력해주세요" }); break; } // 아이디 형식 검사 const regExp = new RegExp(/^[a-zA-Z0-9]{8,12}$/g); if (regExp.test(localRegisterForm.id) === false) { setIsError({ ...isError, id: true }); setErrorText({ ...errorText, id: "형식에 맞지 않습니다 ( 영어 + 숫자, 8 ~ 12 자리)", }); break; } // 서버 연동 requestApiWithBodyWithoutToken("post", "/check/id", { id: localRegisterForm.id }, {}).then((res) => { switch (res.data.status) { case "true": { setIsError({ ...isError, id: false }); setIsOkay({ ...isOkay, id: true }); alert("사용 가능한 아이디입니다."); break; } case "false": { setIsError({ ...isError, id: true }); setErrorText({ ...errorText, id: "이미 존재하는 아이디입니다." }); break; } default: { break; } } }); break; } case "nickname": { // 닉네임 공란인지 검사 if (localRegisterForm.nickname === "") { setIsError({ ...isError, nickname: true }); setErrorText({ ...errorText, nickname: "닉네임을 입력해주세요" }); break; } // 서버 연동 requestApiWithBodyWithoutToken("post", "/check/username", { username: localRegisterForm.nickname }, {}).then( (res) => { switch (res.data.status) { case "true": { setIsError({ ...isError, nickname: false }); setIsOkay({ ...isOkay, nickname: true }); alert("사용 가능한 닉네임입니다."); break; } case "false": { setIsError({ ...isError, nickname: true }); setErrorText({ ...errorText, nickname: "이미 존재하는 닉네임입니다." }); break; } default: { break; } } }, ); break; } default: break; } }; const checkNoError = () => { for (let [key, value] of Object.entries(isOkay)) { if (value === false) return false; } return true; }; const onClickSubmitBtn = () => { // 비밀번호 형식 검사 const regExp = new RegExp(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,20}$/g); if (regExp.test(localRegisterForm.password) === false) { setIsError({ ...isError, password: true }); setErrorText({ ...errorText, password: "형식에 맞지 않습니다 ( 영어 + 숫자 + 특수문자, 8 ~ 20 자리 )", }); return; } // 비밀번호 확인과 같은지 검사 if ((localRegisterForm.password === localRegisterForm.passwordConfirm) === false) { setIsError({ ...isError, passwordConfirm: true }); setErrorText({ ...errorText, passwordConfirm: "비밀번호가 일치하지 않습니다.", }); return; } // 서버 로직 if (checkNoError()) { requestApiWithBodyWithoutToken( "post", "/user", { id: localRegisterForm.id, username: localRegisterForm.nickname, password: localRegisterForm.password, }, {}, ).then((res) => { switch (res.status) { case 200: { setIsError({ id: false, nickname: false, password: false, passwordConfirm: false }); Register(); break; } case 403: { alert("이미 가입된 정보입니다."); break; } } }); } else { alert("중복 확인을 해주세요"); } }; return ( <ModalForm> <S.BodyWrapper> <S.FormInputWrapper> <S.FormInputDiv> <S.FormButtonInput name="id" placeholder="아이디" autoComplete="off" onChange={onChangeForm} isError={isError.id} /> <S.FormButton name="id" onClick={onClickOverlap}> 중복확인 </S.FormButton> </S.FormInputDiv> <S.FormErrorText isError={isError.id}>{errorText.id}</S.FormErrorText> </S.FormInputWrapper> <S.FormInputWrapper> <S.FormInputDiv> <S.FormButtonInput name="nickname" placeholder="별명" autoComplete="off" onChange={onChangeForm} isError={isError.nickname} /> <S.FormButton name="nickname" onClick={onClickOverlap}> 중복확인 </S.FormButton> </S.FormInputDiv> <S.FormErrorText isError={isError.nickname}>{errorText.nickname}</S.FormErrorText> </S.FormInputWrapper> <S.FormInput name="password" type="password" placeholder="비밀번호" onChange={onChangeForm} isError={isError.password} /> <S.FormErrorText isError={isError.password}>{errorText.password}</S.FormErrorText> <S.FormInput name="passwordConfirm" type="password" placeholder="비밀번호 재확인" onChange={onChangeForm} isError={isError.passwordConfirm} /> <S.FormErrorText isError={isError.passwordConfirm}>{errorText.passwordConfirm}</S.FormErrorText> <S.FormSubmitButton onClick={onClickSubmitBtn}>가입하기</S.FormSubmitButton> </S.BodyWrapper> </ModalForm> ); }; export default RegisterModalForm;
//1.0.0 components import Flex from './flex'; import FlexItem from './flex_item'; export default { Flex, FlexItem };
from __future__ import print_function import numpy as np import cv2 import os import math import sys import random from ..config import config def brightness_aug(src, x): alpha = 1.0 + random.uniform(-x, x) src *= alpha return src def contrast_aug(src, x): alpha = 1.0 + random.uniform(-x, x) coef = np.array([[[0.299, 0.587, 0.114]]]) gray = src * coef gray = (3.0 * (1.0 - alpha) / gray.size) * np.sum(gray) src *= alpha src += gray return src def saturation_aug(src, x): alpha = 1.0 + random.uniform(-x, x) coef = np.array([[[0.299, 0.587, 0.114]]]) gray = src * coef gray = np.sum(gray, axis=2, keepdims=True) gray *= (1.0 - alpha) src *= alpha src += gray return src def color_aug(img, x): if config.COLOR_MODE > 1: augs = [brightness_aug, contrast_aug, saturation_aug] random.shuffle(augs) else: augs = [brightness_aug] for aug in augs: # print(img.shape) img = aug(img, x) # print(img.shape) return img def get_image(roidb, scale=False): """ preprocess image and return processed roidb :param roidb: a list of roidb :return: list of img as in mxnet format roidb add new item['im_info'] 0 --- x (width, second dim of im) | y (height, first dim of im) """ num_images = len(roidb) processed_ims = [] processed_roidb = [] for i in range(num_images): roi_rec = roidb[i] if 'stream' in roi_rec: im = cv2.imdecode(roi_rec['stream'], cv2.IMREAD_COLOR) else: assert os.path.exists(roi_rec['image']), '{} does not exist'.format(roi_rec['image']) im = cv2.imread(roi_rec['image']) if roidb[i]['flipped']: im = im[:, ::-1, :] new_rec = roi_rec.copy() if scale: scale_range = config.TRAIN.SCALE_RANGE im_scale = np.random.uniform(scale_range[0], scale_range[1]) im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) elif not config.ORIGIN_SCALE: scale_ind = random.randrange(len(config.SCALES)) target_size = config.SCALES[scale_ind][0] max_size = config.SCALES[scale_ind][1] im, im_scale = resize(im, target_size, max_size, stride=config.IMAGE_STRIDE) else: im_scale = 1.0 im_tensor = transform(im, config.PIXEL_MEANS, config.PIXEL_STDS) if 'boxes_mask' in roi_rec: im = im.astype(np.float32) boxes_mask = roi_rec['boxes_mask'].copy() * im_scale boxes_mask = boxes_mask.astype(np.int) for j in range(boxes_mask.shape[0]): m = boxes_mask[j] im_tensor[:, :, m[1]:m[3], m[0]:m[2]] = 0.0 # print('find mask', m, file=sys.stderr) processed_ims.append(im_tensor) new_rec['boxes'] = roi_rec['boxes'].copy() * im_scale if config.TRAIN.IMAGE_ALIGN > 0: if im_tensor.shape[2] % config.TRAIN.IMAGE_ALIGN != 0 or im_tensor.shape[3] % config.TRAIN.IMAGE_ALIGN != 0: new_height = math.ceil(float(im_tensor.shape[2]) / config.TRAIN.IMAGE_ALIGN) * config.TRAIN.IMAGE_ALIGN new_width = math.ceil(float(im_tensor.shape[3]) / config.TRAIN.IMAGE_ALIGN) * config.TRAIN.IMAGE_ALIGN new_im_tensor = np.zeros((1, 3, int(new_height), int(new_width))) new_im_tensor[:, :, 0:im_tensor.shape[2], 0:im_tensor.shape[3]] = im_tensor print(im_tensor.shape, new_im_tensor.shape, file=sys.stderr) im_tensor = new_im_tensor # print('boxes', new_rec['boxes'], file=sys.stderr) im_info = [im_tensor.shape[2], im_tensor.shape[3], im_scale] new_rec['im_info'] = im_info processed_roidb.append(new_rec) return processed_ims, processed_roidb TMP_ID = -1 # bakup method def __get_crop_image(roidb): """ preprocess image and return processed roidb :param roidb: a list of roidb :return: list of img as in mxnet format roidb add new item['im_info'] 0 --- x (width, second dim of im) | y (height, first dim of im) """ # roidb and each roi_rec can not be changed as it will be reused in next epoch num_images = len(roidb) processed_ims = [] processed_roidb = [] for i in range(num_images): roi_rec = roidb[i] if 'stream' in roi_rec: im = cv2.imdecode(roi_rec['stream'], cv2.IMREAD_COLOR) else: assert os.path.exists(roi_rec['image']), '{} does not exist'.format(roi_rec['image']) im = cv2.imread(roi_rec['image']) if roidb[i]['flipped']: im = im[:, ::-1, :] if 'boxes_mask' in roi_rec: # im = im.astype(np.float32) boxes_mask = roi_rec['boxes_mask'].copy() boxes_mask = boxes_mask.astype(np.int) for j in range(boxes_mask.shape[0]): m = boxes_mask[j] im[m[1]:m[3], m[0]:m[2], :] = 0 # print('find mask', m, file=sys.stderr) new_rec = roi_rec.copy() # choose one gt randomly SIZE = config.SCALES[0][0] TARGET_BOX_SCALES = np.array([16, 32, 64, 128, 256, 512]) assert roi_rec['boxes'].shape[0] > 0 candidates = [] for i in range(roi_rec['boxes'].shape[0]): box = roi_rec['boxes'][i] box_size = max(box[2] - box[0], box[3] - box[1]) if box_size < config.TRAIN.MIN_BOX_SIZE: continue # if box[0]<0 or box[1]<0: # continue # if box[2]>im.shape[1] or box[3]>im.shape[0]: # continue; candidates.append(i) assert len(candidates) > 0 box_ind = random.choice(candidates) box = roi_rec['boxes'][box_ind] box_size = max(box[2] - box[0], box[3] - box[1]) dist = np.abs(TARGET_BOX_SCALES - box_size) nearest = np.argmin(dist) target_ind = random.randrange(min(len(TARGET_BOX_SCALES), nearest + 2)) target_box_size = TARGET_BOX_SCALES[target_ind] im_scale = float(target_box_size) / box_size # min_scale = float(SIZE)/np.min(im.shape[0:2]) # if im_scale<min_scale: # im_scale = min_scale im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) new_rec['boxes'] = roi_rec['boxes'].copy() * im_scale box_scale = new_rec['boxes'][box_ind].copy().astype(np.int) ul_min = box_scale[2:4] - SIZE ul_max = box_scale[0:2] assert ul_min[0] <= ul_max[0] assert ul_min[1] <= ul_max[1] # print('ul', ul_min, ul_max, box) up, left = np.random.randint(ul_min[1], ul_max[1] + 1), np.random.randint(ul_min[0], ul_max[0] + 1) # print('box', box, up, left) M = [[1.0, 0.0, -left], [0.0, 1.0, -up], ] M = np.array(M) im = cv2.warpAffine(im, M, (SIZE, SIZE), borderValue=tuple(config.PIXEL_MEANS)) # tbox = np.array([left, left+SIZE, up, up+SIZE], dtype=np.int) # im_new = np.zeros( (SIZE, SIZE,3), dtype=im.dtype) # for i in range(3): # im_new[:,:,i] = config.PIXEL_MEANS[i] new_rec['boxes'][:, 0] -= left new_rec['boxes'][:, 2] -= left new_rec['boxes'][:, 1] -= up new_rec['boxes'][:, 3] -= up # box_trans = new_rec['boxes'][box_ind].copy().astype(np.int) # print('sel box', im_scale, box, box_scale, box_trans, file=sys.stderr) # print('before', new_rec['boxes'].shape[0]) boxes_new = [] classes_new = [] for i in range(new_rec['boxes'].shape[0]): box = new_rec['boxes'][i] box_size = max(box[2] - box[0], box[3] - box[1]) center = np.array(([box[0], box[1]] + [box[2], box[3]])) / 2 if center[0] < 0 or center[1] < 0 or center[0] >= im.shape[1] or center[1] >= im.shape[0]: continue if box_size < config.TRAIN.MIN_BOX_SIZE: continue boxes_new.append(box) classes_new.append(new_rec['gt_classes'][i]) new_rec['boxes'] = np.array(boxes_new) new_rec['gt_classes'] = np.array(classes_new) # print('after', new_rec['boxes'].shape[0]) # assert new_rec['boxes'].shape[0]>0 DEBUG = True if DEBUG: global TMP_ID if TMP_ID < 10: tim = im.copy() for i in range(new_rec['boxes'].shape[0]): box = new_rec['boxes'][i].copy().astype(np.int) cv2.rectangle(tim, (box[0], box[1]), (box[2], box[3]), (255, 0, 0), 1) filename = './trainimages/train%d.png' % TMP_ID TMP_ID += 1 cv2.imwrite(filename, tim) im_tensor = transform(im, config.PIXEL_MEANS, config.PIXEL_STDS, config.PIXEL_SCALE) processed_ims.append(im_tensor) # print('boxes', new_rec['boxes'], file=sys.stderr) im_info = [im_tensor.shape[2], im_tensor.shape[3], im_scale] new_rec['im_info'] = im_info processed_roidb.append(new_rec) return processed_ims, processed_roidb def expand_bboxes(bboxes, image_width, image_height, expand_left=2., expand_up=2., expand_right=2., expand_down=2.): """ Expand bboxes, expand 2 times by defalut. """ expand_boxes = [] for bbox in bboxes: xmin = bbox[0] ymin = bbox[1] xmax = bbox[2] ymax = bbox[3] w = xmax - xmin h = ymax - ymin ex_xmin = max(xmin - w / expand_left, 0.) ex_ymin = max(ymin - h / expand_up, 0.) ex_xmax = min(xmax + w / expand_right, image_width) ex_ymax = min(ymax + h / expand_down, image_height) expand_boxes.append([ex_xmin, ex_ymin, ex_xmax, ex_ymax]) return expand_boxes def get_crop_image1(roidb): """ preprocess image and return processed roidb :param roidb: a list of roidb :return: list of img as in mxnet format roidb add new item['im_info'] 0 --- x (width, second dim of im) | y (height, first dim of im) """ # roidb and each roi_rec can not be changed as it will be reused in next epoch num_images = len(roidb) processed_ims = [] processed_roidb = [] for i in range(num_images): roi_rec = roidb[i] if 'stream' in roi_rec: im = cv2.imdecode(roi_rec['stream'], cv2.IMREAD_COLOR) else: assert os.path.exists(roi_rec['image']), '{} does not exist'.format(roi_rec['image']) im = cv2.imread(roi_rec['image']) if roidb[i]['flipped']: im = im[:, ::-1, :] if 'boxes_mask' in roi_rec: # im = im.astype(np.float32) boxes_mask = roi_rec['boxes_mask'].copy() boxes_mask = boxes_mask.astype(np.int) for j in range(boxes_mask.shape[0]): m = boxes_mask[j] im[m[1]:m[3], m[0]:m[2], :] = 127 # print('find mask', m, file=sys.stderr) SIZE = config.SCALES[0][0] PRE_SCALES = [0.3, 0.45, 0.6, 0.8, 1.0] # PRE_SCALES = [0.3, 0.45, 0.6, 0.8, 1.0, 0.8, 1.0, 0.8, 1.0] _scale = random.choice(PRE_SCALES) # _scale = np.random.uniform(PRE_SCALES[0], PRE_SCALES[-1]) size = int(np.min(im.shape[0:2]) * _scale) # size = int(np.round(_scale*np.min(im.shape[0:2]))) im_scale = float(SIZE) / size # origin_im_scale = im_scale # size = np.round(np.min(im.shape[0:2])*im_scale) # im_scale *= (float(SIZE)/size) # origin_shape = im.shape if _scale > 10.0: # avoid im.size<SIZE, never? sizex = int(np.round(im.shape[1] * im_scale)) sizey = int(np.round(im.shape[0] * im_scale)) if sizex < SIZE: sizex = SIZE print('keepx', sizex) if sizey < SIZE: sizey = SIZE print('keepy', sizex) im = cv2.resize(im, (sizex, sizey), interpolation=cv2.INTER_LINEAR) else: im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) assert im.shape[0] >= SIZE and im.shape[1] >= SIZE # print('image size', origin_shape, _scale, SIZE, size, im_scale) new_rec = roi_rec.copy() new_rec['boxes'] = roi_rec['boxes'].copy() * im_scale if config.FACE_LANDMARK: new_rec['landmarks'] = roi_rec['landmarks'].copy() new_rec['landmarks'][:, :, 0:2] *= im_scale retry = 0 LIMIT = 25 size = SIZE while retry < LIMIT: up, left = (np.random.randint(0, im.shape[0] - size + 1), np.random.randint(0, im.shape[1] - size + 1)) boxes_new = new_rec['boxes'].copy() im_new = im[up:(up + size), left:(left + size), :] # print('crop', up, left, size, im_scale) boxes_new[:, 0] -= left boxes_new[:, 2] -= left boxes_new[:, 1] -= up boxes_new[:, 3] -= up if config.FACE_LANDMARK: landmarks_new = new_rec['landmarks'].copy() landmarks_new[:, :, 0] -= left landmarks_new[:, :, 1] -= up # for i in range(0,10,2): # landmarks_new[:,i] -= left # for i in range(1,10,2): # landmarks_new[:,i] -= up valid_landmarks = [] # im_new = cv2.resize(im_new, (SIZE, SIZE), interpolation=cv2.INTER_LINEAR) # boxes_new *= im_scale # print(origin_shape, im_new.shape, im_scale) valid = [] valid_boxes = [] for i in range(boxes_new.shape[0]): box = boxes_new[i] # center = np.array(([box[0], box[1]]+[box[2], box[3]]))/2 centerx = (box[0] + box[2]) / 2 centery = (box[1] + box[3]) / 2 # box[0] = max(0, box[0]) # box[1] = max(0, box[1]) # box[2] = min(im_new.shape[1], box[2]) # box[3] = min(im_new.shape[0], box[3]) box_size = max(box[2] - box[0], box[3] - box[1]) if centerx < 0 or centery < 0 or centerx >= im_new.shape[1] or centery >= im_new.shape[0]: continue if box_size < config.TRAIN.MIN_BOX_SIZE: continue # filter by landmarks? TODO valid.append(i) valid_boxes.append(box) if config.FACE_LANDMARK: valid_landmarks.append(landmarks_new[i]) if len(valid) > 0 or retry == LIMIT - 1: im = im_new new_rec['boxes'] = np.array(valid_boxes) new_rec['gt_classes'] = new_rec['gt_classes'][valid] if config.FACE_LANDMARK: new_rec['landmarks'] = np.array(valid_landmarks) if config.HEAD_BOX: face_box = new_rec['boxes'] head_box = expand_bboxes(face_box, image_width=im.shape[1], image_height=im.shape[0]) new_rec['boxes_head'] = np.array(head_box) break retry += 1 if config.COLOR_MODE > 0 and config.COLOR_JITTERING > 0.0: im = im.astype(np.float32) im = color_aug(im, config.COLOR_JITTERING) # assert np.all(new_rec['landmarks'][:,10]>0.0) global TMP_ID if TMP_ID >= 0 and TMP_ID < 10: tim = im.copy().astype(np.uint8) for i in range(new_rec['boxes'].shape[0]): box = new_rec['boxes'][i].copy().astype(np.int) cv2.rectangle(tim, (box[0], box[1]), (box[2], box[3]), (255, 0, 0), 1) print('draw box:', box) if config.FACE_LANDMARK: for i in range(new_rec['landmarks'].shape[0]): landmark = new_rec['landmarks'][i].copy() if landmark[0][2] < 0: print('zero', landmark) continue landmark = landmark.astype(np.int) print('draw landmark', landmark) for k in range(5): color = (0, 0, 255) if k == 0 or k == 3: color = (0, 255, 0) pp = (landmark[k][0], landmark[k][1]) cv2.circle(tim, (pp[0], pp[1]), 1, color, 2) filename = './trainimages/train%d.png' % TMP_ID print('write', filename) cv2.imwrite(filename, tim) TMP_ID += 1 im_tensor = transform(im, config.PIXEL_MEANS, config.PIXEL_STDS, config.PIXEL_SCALE) processed_ims.append(im_tensor) # print('boxes', new_rec['boxes'], file=sys.stderr) im_info = [im_tensor.shape[2], im_tensor.shape[3], im_scale] new_rec['im_info'] = np.array(im_info, dtype=np.float32) processed_roidb.append(new_rec) return processed_ims, processed_roidb def do_mixup(im1, roidb1, im2, roidb2): im = (im1 + im2) / 2.0 roidb = {} # print(roidb1.keys()) # for k in roidb1: for k in ['boxes', 'landmarks', 'gt_classes', 'im_info']: v1 = roidb1[k] v2 = roidb2[k] if k != 'im_info': # print('try', k, v1.shape, v2.shape) if v1.shape[0] > 0 and v2.shape[0] > 0: v = np.concatenate((v1, v2), axis=0) else: v = v1 else: v = v1 # print(k, v1.shape, v2.shape, v.shape) roidb[k] = v return im, roidb def get_crop_image(roidb): ims, roidbs = get_crop_image1(roidb) if config.MIXUP > 0.0 and np.random.random() < config.MIXUP: for i in range(len(ims)): im = ims[i] roidb = roidbs[i] j = np.random.randint(0, len(ims) - 1) if j >= i: j += 1 im, roidb = do_mixup(im, roidb, ims[j], roidbs[j]) ims[i] = im roidbs[i] = roidb return ims, roidbs def resize(im, target_size, max_size, stride=0, min_size=0): """ only resize input image to target size and return scale :param im: BGR image input by opencv :param target_size: one dimensional size (the short side) :param max_size: one dimensional max size (the long side) :param stride: if given, pad the image to designated stride :return: """ im_shape = im.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) im_scale = float(target_size) / float(im_size_min) # prevent bigger axis from being more than max_size: if np.round(im_scale * im_size_max) > max_size: im_scale = float(max_size) / float(im_size_max) if min_size > 0 and np.round(im_scale * im_size_min) < min_size: im_scale = float(min_size) / float(im_size_min) im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) if stride == 0: return im, im_scale else: # pad to product of stride im_height = int(np.ceil(im.shape[0] / float(stride)) * stride) im_width = int(np.ceil(im.shape[1] / float(stride)) * stride) im_channel = im.shape[2] padded_im = np.zeros((im_height, im_width, im_channel)) padded_im[:im.shape[0], :im.shape[1], :] = im return padded_im, im_scale def transform(im, pixel_means, pixel_stds, pixel_scale): """ transform into mxnet tensor, subtract pixel size and transform to correct format :param im: [height, width, channel] in BGR :param pixel_means: [B, G, R pixel means] :return: [batch, channel, height, width] """ im_tensor = np.zeros((1, 3, im.shape[0], im.shape[1])) for i in range(3): im_tensor[0, i, :, :] = (im[:, :, 2 - i] / pixel_scale - pixel_means[2 - i]) / pixel_stds[2 - i] return im_tensor def transform_inverse(im_tensor, pixel_means): """ transform from mxnet im_tensor to ordinary RGB image im_tensor is limited to one image :param im_tensor: [batch, channel, height, width] :param pixel_means: [B, G, R pixel means] :return: im [height, width, channel(RGB)] """ assert im_tensor.shape[0] == 1 im_tensor = im_tensor.copy() # put channel back channel_swap = (0, 2, 3, 1) im_tensor = im_tensor.transpose(channel_swap) im = im_tensor[0] assert im.shape[2] == 3 im += pixel_means[[2, 1, 0]] im = im.astype(np.uint8) return im def tensor_vstack(tensor_list, pad=0): """ vertically stack tensors :param tensor_list: list of tensor to be stacked vertically :param pad: label to pad with :return: tensor with max shape """ ndim = len(tensor_list[0].shape) dtype = tensor_list[0].dtype islice = tensor_list[0].shape[0] dimensions = [] first_dim = sum([tensor.shape[0] for tensor in tensor_list]) dimensions.append(first_dim) for dim in range(1, ndim): dimensions.append(max([tensor.shape[dim] for tensor in tensor_list])) if pad == 0: all_tensor = np.zeros(tuple(dimensions), dtype=dtype) elif pad == 1: all_tensor = np.ones(tuple(dimensions), dtype=dtype) else: all_tensor = np.full(tuple(dimensions), pad, dtype=dtype) if ndim == 1: for ind, tensor in enumerate(tensor_list): all_tensor[ind * islice:(ind + 1) * islice] = tensor elif ndim == 2: for ind, tensor in enumerate(tensor_list): all_tensor[ind * islice:(ind + 1) * islice, :tensor.shape[1]] = tensor elif ndim == 3: for ind, tensor in enumerate(tensor_list): all_tensor[ind * islice:(ind + 1) * islice, :tensor.shape[1], :tensor.shape[2]] = tensor elif ndim == 4: for ind, tensor in enumerate(tensor_list): all_tensor[ind * islice:(ind + 1) * islice, :tensor.shape[1], :tensor.shape[2], :tensor.shape[3]] = tensor elif ndim == 5: for ind, tensor in enumerate(tensor_list): all_tensor[ind * islice:(ind + 1) * islice, :tensor.shape[1], :tensor.shape[2], :tensor.shape[3], :tensor.shape[ 4]] = tensor else: print(tensor_list[0].shape) raise Exception('Sorry, unimplemented.') return all_tensor
import React from "react"; export default function FrontEnd() { return ( <div style={{ textAlign: "left" }} id="frontend"> <h2>Front End</h2> <h3>User Interface + Git</h3> <h3>CSS</h3> <h3>JavaScript</h3> <h3>React</h3> <h3>Redux</h3> <hr /> </div> ); }
export function removeTrailing0x(str) { if (str.startsWith('0x')) return str.substring(2);else return str; } export function addTrailing0x(str) { if (!str.startsWith('0x')) return '0x' + str;else return str; }
/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ define([ "knockback", "validation", "layout-handler", "core-constants", "query-form-view", "controller-basedir/reports/qe/ui/js/models/FlowSeriesFormModel", "core-basedir/reports/qe/ui/js/common/qe.utils", ], function(kb, kbValidation, LayoutHandler, coreConstants, QueryFormView, FlowSeriesFormModel, qeUtils) { var layoutHandler = new LayoutHandler(); var FlowSeriesFormView = QueryFormView.extend({ render: function() { var self = this, viewConfig = self.attributes.viewConfig, modelMap = contrail.handleIfNull(self.modelMap, {}), hashParams = layoutHandler.getURLHashParams(), queryPageTmpl = contrail.getTemplate4Id(coreConstants.TMPL_QUERY_PAGE), queryType = contrail.checkIfExist(hashParams.queryType) ? hashParams.queryType : null, widgetConfig = contrail.checkIfExist(viewConfig.widgetConfig) ? viewConfig.widgetConfig : null, queryPrefix = cowc.FS_QUERY_PREFIX, queryFormId = cowc.QE_HASH_ELEMENT_PREFIX + cowc.FS_QUERY_PREFIX + cowc.QE_FORM_SUFFIX, flowSeriesId = cowl.QE_FLOW_SERIES_ID, queryFormAttributes = contrail.checkIfExist(hashParams.queryFormAttributes) ? hashParams.queryFormAttributes : {}; if (queryType === cowc.QUERY_TYPE_MODIFY) { queryFormAttributes.from_time = parseInt(queryFormAttributes.from_time_utc); queryFormAttributes.to_time = parseInt(queryFormAttributes.to_time_utc); } self.model = new FlowSeriesFormModel(queryFormAttributes); self.$el.append(queryPageTmpl({ queryPrefix: cowc.FS_QUERY_PREFIX })); self.renderView4Config($(queryFormId), self.model, self.getViewConfig(), cowc.KEY_RUN_QUERY_VALIDATION, null, modelMap, function () { self.model.showErrorAttr(flowSeriesId, false); kb.applyBindings(self.model, document.getElementById(flowSeriesId)); kbValidation.bind(self); $("#run_query").on("click", function() { if (self.model.model().isValid(true, cowc.KEY_RUN_QUERY_VALIDATION)) { self.renderQueryResult(); } }); qeUtils.adjustHeight4FormTextarea(queryPrefix); if (queryType === cowc.QUERY_TYPE_RERUN) { self.renderQueryResult(); } }); if (widgetConfig !== null) { self.renderView4Config($(queryFormId), self.model, widgetConfig, null, null, null); } }, renderQueryResult: function() { var self = this, viewConfig = self.attributes.viewConfig, widgetConfig = contrail.checkIfExist(viewConfig.widgetConfig) ? viewConfig.widgetConfig : null, modelMap = contrail.handleIfNull(self.modelMap, {}), queryFormModel = self.model, queryFormId = cowc.QE_HASH_ELEMENT_PREFIX + cowc.FS_QUERY_PREFIX + cowc.QE_FORM_SUFFIX, queryResultId = cowc.QE_HASH_ELEMENT_PREFIX + cowc.FS_QUERY_PREFIX + cowc.QE_RESULTS_SUFFIX, queryResultTabId = cowl.QE_FLOW_SERIES_TAB_ID; if (widgetConfig !== null) { $(queryFormId).parents(".widget-box").data("widget-action").collapse(); } queryFormModel.is_request_in_progress(true); qeUtils.fetchServerCurrentTime(function(serverCurrentTime) { var queryRequestPostData = queryFormModel.getQueryRequestPostData(serverCurrentTime); self.renderView4Config($(queryResultId), self.model, getQueryResultTabViewConfig(queryRequestPostData, queryResultTabId), null, null, modelMap, function() { var queryResultTabView = self.childViewMap[queryResultTabId], queryResultListModel = modelMap[cowc.UMID_QUERY_RESULT_LIST_MODEL]; if (!(queryResultListModel.isRequestInProgress()) && queryResultListModel.getItems().length > 0) { self.renderQueryResultChartTab(queryResultTabView, queryResultTabId, queryFormModel, queryRequestPostData); queryFormModel.is_request_in_progress(false); } else { queryResultListModel.onAllRequestsComplete.subscribe(function() { if (queryResultListModel.getItems().length > 0) { self.renderQueryResultChartTab(queryResultTabView, queryResultTabId, queryFormModel, queryRequestPostData); } queryFormModel.is_request_in_progress(false); }); } }); }); }, renderSessionAnalyzer: function(elementId, sessionAnalyzerViewConfig) { var self = this, childViewMap = self.childViewMap, modelMap = contrail.handleIfNull(self.modelMap, {}), queryResultTabsId = cowl.QE_FLOW_SERIES_TAB_ID, queryResultTabsView = contrail.checkIfExist(childViewMap[queryResultTabsId]) ? childViewMap[queryResultTabsId] : null; if (contrail.checkIfExist(queryResultTabsView)) { queryResultTabsView.renderNewTab(queryResultTabsId, [sessionAnalyzerViewConfig], true, modelMap, null); } }, renderQueryResultChartTab: function(queryResultTabView, queryResultTabId, queryFormModel, queryRequestPostData) { var self = this, viewConfig = self.attributes.viewConfig, queryFormAttributes = contrail.checkIfExist(viewConfig.queryFormAttributes) ? viewConfig.queryFormAttributes : {}, formQueryIdSuffix = (!$.isEmptyObject(queryFormAttributes)) ? "-" + queryFormAttributes.queryId : "", flowSeriesChartId = cowl.QE_FLOW_SERIES_CHART_ID + formQueryIdSuffix, selectArray = queryFormModel.select().replace(/ /g, "").split(","); if (selectArray.indexOf("T=") !== -1 && $("#" + flowSeriesChartId).length === 0) { queryResultTabView.renderNewTab(queryResultTabId, getQueryResultChartViewConfig(queryRequestPostData, self.el.id)); } }, getViewConfig: function() { var self = this; return { view: "SectionView", viewConfig: { rows: [{ columns: [{ elementId: "time_range", view: "FormDropdownView", viewConfig: { path: "time_range", help: { target: "modal", content: "reports/qe/flows/flow_series/time_range" }, dataBindValue: "time_range", class: "col-xs-3", elementConfig: { dataTextField: "text", dataValueField: "id", data: cowc.TIMERANGE_DROPDOWN_VALUES } } }, { elementId: "from_time", view: "FormDateTimePickerView", viewConfig: { style: "display: none;", path: "from_time", dataBindValue: "from_time", class: "col-xs-3", elementConfig: qeUtils.getFromTimeElementConfig("from_time", "to_time"), visible: "isTimeRangeCustom()" } }, { elementId: "to_time", view: "FormDateTimePickerView", viewConfig: { style: "display: none;", path: "to_time", dataBindValue: "to_time", class: "col-xs-3", elementConfig: qeUtils.getToTimeElementConfig("from_time", "to_time"), visible: "isTimeRangeCustom()" } }] }, { columns: [{ elementId: "select", view: "FormTextAreaView", viewConfig: { path: "select", help: { target: "modal", content: "reports/qe/flows/flow_series/select" }, dataBindValue: "select", class: "col-xs-9", editPopupConfig: { renderEditFn: function() { self.renderSelect({ className: cowc.QE_MODAL_CLASS_700 }); } } } }, { elementId: "time-granularity-section", view: "FormCompositeView", viewConfig: { class: "col-xs-3", style: "display: none;", path: "time_granularity", label: "Time Granularity", visible: "isSelectTimeChecked()", childView: [{ elementId: "time_granularity", view: "FormNumericTextboxView", viewConfig: { label: false, path: "time_granularity", dataBindValue: "time_granularity", class: "col-xs-5", elementConfig: { min: 1 } } }, { elementId: "time_granularity_unit", view: "FormDropdownView", viewConfig: { label: false, path: "time_granularity_unit", dataBindValue: "time_granularity_unit", dataBindOptionList: "getTimeGranularityUnits()", class: "col-xs-7", elementConfig: {} } }] } }] }, { viewConfig: { visible: "show_advanced_options()" }, columns: [{ elementId: "where", view: "FormTextAreaView", viewConfig: { path: "where", dataBindValue: "where", class: "col-xs-9", placeHolder: "*", editPopupConfig: { renderEditFn: function() { self.renderWhere({ className: cowc.QE_MODAL_CLASS_700 }); } } } }, { elementId: "direction", view: "FormDropdownView", viewConfig: { path: "direction", dataBindValue: "direction", class: "col-xs-3", elementConfig: { dataTextField: "text", dataValueField: "id", data: cowc.DIRECTION_DROPDOWN_VALUES } } }] }, { viewConfig: { visible: "show_advanced_options()" }, columns: [{ elementId: "filters", view: "FormTextAreaView", viewConfig: { path: "filters", dataBindValue: "filters", class: "col-xs-9", label: cowl.TITLE_QE_FILTER, editPopupConfig: { renderEditFn: function() { self.renderFilters({ className: cowc.QE_MODAL_CLASS_700 }); } } } }] }, { columns: [{ elementId: "advanced_options", view: "FormTextView", viewConfig: { text: "getAdvancedOptionsText()", class: "col-xs-6 margin-0-0-10", elementConfig: { class: "advanced-options-link" }, click: "toggleAdvancedFields" } }] }, { columns: [{ elementId: "run_query", view: "FormButtonView", label: "Run Query", viewConfig: { class: "display-inline-block margin-0-0-0-15", disabled: "is_request_in_progress()", elementConfig: { btnClass: "btn-primary" } } }, { elementId: "reset_query", view: "FormButtonView", label: "Reset", viewConfig: { label: "Reset", class: "display-inline-block margin-0-0-0-15", elementConfig: { onClick: "function(data, event) {reset(data, event, true, false);}" } } }] }] } }; } }); function getQueryResultTabViewConfig(queryRequestPostData, queryResultTabId) { return { elementId: queryResultTabId, view: "TabsView", viewConfig: { theme: cowc.TAB_THEME_WIDGET_CLASSIC, tabs: [getQueryResultGridViewConfig(queryRequestPostData)] } }; } function getQueryResultGridViewConfig(queryRequestPostData) { var queryResultGridId = cowl.QE_QUERY_RESULT_GRID_ID; return { elementId: queryResultGridId, title: cowl.TITLE_RESULTS, iconClass: "fa fa-table", view: "QueryResultGridView", tabConfig: { activate: function() { if ($("#" + queryResultGridId).data("contrailGrid")) { $("#" + queryResultGridId).data("contrailGrid").refreshView(); } } }, viewConfig: { queryRequestPostData: queryRequestPostData, gridOptions: { titleText: cowl.TITLE_FLOW_SERIES, queryQueueUrl: cowc.URL_QUERY_FLOW_QUEUE, queryQueueTitle: cowl.TITLE_FLOW } } }; } function getQueryResultChartViewConfig(queryRequestPostData, clickOutElementId) { var queryResultChartId = cowl.QE_FLOW_SERIES_CHART_ID, queryResultChartGridId = cowl.QE_FLOW_SERIES_CHART_GRID_ID, flowSeriesChartTabViewConfig = []; flowSeriesChartTabViewConfig.push({ elementId: queryResultChartId, title: cowl.TITLE_CHART, iconClass: "fa fa-bar-chart-o", view: "QueryResultLineChartView", tabConfig: { activate: function() { $("#" + queryResultChartId).find("svg").trigger("refresh"); if ($("#" + queryResultChartGridId).data("contrailGrid")) { $("#" + queryResultChartGridId).data("contrailGrid").refreshView(); } }, renderOnActivate: true }, viewConfig: { queryId: queryRequestPostData.queryId, queryFormAttributes: queryRequestPostData.formModelAttrs, queryResultChartId: queryResultChartId, queryResultChartGridId: queryResultChartGridId, clickOutElementId: clickOutElementId } }); return flowSeriesChartTabViewConfig; } return FlowSeriesFormView; });
"use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } exports.__esModule = true; var index = require("@syncfusion/ej2-dropdowns"); index.MultiSelect.Inject(index.CheckBoxSelection); __export(require("@syncfusion/ej2-dropdowns"));
# coding=utf-8 ''' # Author: shikanon (shikanon@tensorbytes.com) # File Created Time: 2020-03-31 11:04:51 # # Project: settings # File: config.py # Description: # ''' import configparser class Config: '''配置 ''' def __init__(self): self.config = configparser.ConfigParser() self.mysqldb = "" self.redis = "" def parse(self, path): self.config.read(path) if "db" not in self.config.sections(): raise ValueError("config file can not find db section") host = self.config.get("db", "host") port = self.config.get("db", "port") username = self.config.get("db", "username") passwd = self.config.get("db", "passwd") self.mysqldb = "mysql+pymysql://%s:%s@%s:%s/ovision"%(username,passwd,host,port)
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { InjectFlags } from '../di/interface/injector'; import { ElementRef as ViewEngine_ElementRef } from '../linker/element_ref'; import { TemplateRef as ViewEngine_TemplateRef } from '../linker/template_ref'; import { createTemplateRef, injectChangeDetectorRef } from './view_engine_compatibility'; /** * Retrieves `TemplateRef` instance from `Injector` when a local reference is placed on the * `<ng-template>` element. * * @codeGenApi */ export function ɵɵtemplateRefExtractor(tNode, currentView) { return createTemplateRef(ViewEngine_TemplateRef, ViewEngine_ElementRef, tNode, currentView); } /** * Returns the appropriate `ChangeDetectorRef` for a pipe. * * @codeGenApi */ export function ɵɵinjectPipeChangeDetectorRef(flags = InjectFlags.Default) { const value = injectChangeDetectorRef(true); if (value == null && !(flags & InjectFlags.Optional)) { throw new Error(`No provider for ChangeDetectorRef!`); } else { return value; } } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld19lbmdpbmVfY29tcGF0aWJpbGl0eV9wcmVib3VuZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uLy4uL3BhY2thZ2VzL2NvcmUvc3JjL3JlbmRlcjMvdmlld19lbmdpbmVfY29tcGF0aWJpbGl0eV9wcmVib3VuZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7O0dBTUc7QUFJSCxPQUFPLEVBQUMsV0FBVyxFQUFDLE1BQU0sMEJBQTBCLENBQUM7QUFDckQsT0FBTyxFQUFDLFVBQVUsSUFBSSxxQkFBcUIsRUFBQyxNQUFNLHVCQUF1QixDQUFDO0FBQzFFLE9BQU8sRUFBQyxXQUFXLElBQUksc0JBQXNCLEVBQUMsTUFBTSx3QkFBd0IsQ0FBQztBQUk3RSxPQUFPLEVBQUMsaUJBQWlCLEVBQUUsdUJBQXVCLEVBQUMsTUFBTSw2QkFBNkIsQ0FBQztBQUl2Rjs7Ozs7R0FLRztBQUNILE1BQU0sVUFBVSxzQkFBc0IsQ0FBQyxLQUFZLEVBQUUsV0FBa0I7SUFDckUsT0FBTyxpQkFBaUIsQ0FBQyxzQkFBc0IsRUFBRSxxQkFBcUIsRUFBRSxLQUFLLEVBQUUsV0FBVyxDQUFDLENBQUM7QUFDOUYsQ0FBQztBQUdEOzs7O0dBSUc7QUFDSCxNQUFNLFVBQVUsNkJBQTZCLENBQUMsS0FBSyxHQUFHLFdBQVcsQ0FBQyxPQUFPO0lBQ3ZFLE1BQU0sS0FBSyxHQUFHLHVCQUF1QixDQUFDLElBQUksQ0FBQyxDQUFDO0lBQzVDLElBQUksS0FBSyxJQUFJLElBQUksSUFBSSxDQUFDLENBQUMsS0FBSyxHQUFHLFdBQVcsQ0FBQyxRQUFRLENBQUMsRUFBRTtRQUNwRCxNQUFNLElBQUksS0FBSyxDQUFDLG9DQUFvQyxDQUFDLENBQUM7S0FDdkQ7U0FBTTtRQUNMLE9BQU8sS0FBSyxDQUFDO0tBQ2Q7QUFDSCxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBAbGljZW5zZVxuICogQ29weXJpZ2h0IEdvb2dsZSBMTEMgQWxsIFJpZ2h0cyBSZXNlcnZlZC5cbiAqXG4gKiBVc2Ugb2YgdGhpcyBzb3VyY2UgY29kZSBpcyBnb3Zlcm5lZCBieSBhbiBNSVQtc3R5bGUgbGljZW5zZSB0aGF0IGNhbiBiZVxuICogZm91bmQgaW4gdGhlIExJQ0VOU0UgZmlsZSBhdCBodHRwczovL2FuZ3VsYXIuaW8vbGljZW5zZVxuICovXG5cblxuaW1wb3J0IHtDaGFuZ2VEZXRlY3RvclJlZn0gZnJvbSAnLi4vY2hhbmdlX2RldGVjdGlvbi9jaGFuZ2VfZGV0ZWN0b3JfcmVmJztcbmltcG9ydCB7SW5qZWN0RmxhZ3N9IGZyb20gJy4uL2RpL2ludGVyZmFjZS9pbmplY3Rvcic7XG5pbXBvcnQge0VsZW1lbnRSZWYgYXMgVmlld0VuZ2luZV9FbGVtZW50UmVmfSBmcm9tICcuLi9saW5rZXIvZWxlbWVudF9yZWYnO1xuaW1wb3J0IHtUZW1wbGF0ZVJlZiBhcyBWaWV3RW5naW5lX1RlbXBsYXRlUmVmfSBmcm9tICcuLi9saW5rZXIvdGVtcGxhdGVfcmVmJztcblxuaW1wb3J0IHtUTm9kZX0gZnJvbSAnLi9pbnRlcmZhY2VzL25vZGUnO1xuaW1wb3J0IHtMVmlld30gZnJvbSAnLi9pbnRlcmZhY2VzL3ZpZXcnO1xuaW1wb3J0IHtjcmVhdGVUZW1wbGF0ZVJlZiwgaW5qZWN0Q2hhbmdlRGV0ZWN0b3JSZWZ9IGZyb20gJy4vdmlld19lbmdpbmVfY29tcGF0aWJpbGl0eSc7XG5cblxuXG4vKipcbiAqIFJldHJpZXZlcyBgVGVtcGxhdGVSZWZgIGluc3RhbmNlIGZyb20gYEluamVjdG9yYCB3aGVuIGEgbG9jYWwgcmVmZXJlbmNlIGlzIHBsYWNlZCBvbiB0aGVcbiAqIGA8bmctdGVtcGxhdGU+YCBlbGVtZW50LlxuICpcbiAqIEBjb2RlR2VuQXBpXG4gKi9cbmV4cG9ydCBmdW5jdGlvbiDJtcm1dGVtcGxhdGVSZWZFeHRyYWN0b3IodE5vZGU6IFROb2RlLCBjdXJyZW50VmlldzogTFZpZXcpIHtcbiAgcmV0dXJuIGNyZWF0ZVRlbXBsYXRlUmVmKFZpZXdFbmdpbmVfVGVtcGxhdGVSZWYsIFZpZXdFbmdpbmVfRWxlbWVudFJlZiwgdE5vZGUsIGN1cnJlbnRWaWV3KTtcbn1cblxuXG4vKipcbiAqIFJldHVybnMgdGhlIGFwcHJvcHJpYXRlIGBDaGFuZ2VEZXRlY3RvclJlZmAgZm9yIGEgcGlwZS5cbiAqXG4gKiBAY29kZUdlbkFwaVxuICovXG5leHBvcnQgZnVuY3Rpb24gybXJtWluamVjdFBpcGVDaGFuZ2VEZXRlY3RvclJlZihmbGFncyA9IEluamVjdEZsYWdzLkRlZmF1bHQpOiBDaGFuZ2VEZXRlY3RvclJlZnxudWxsIHtcbiAgY29uc3QgdmFsdWUgPSBpbmplY3RDaGFuZ2VEZXRlY3RvclJlZih0cnVlKTtcbiAgaWYgKHZhbHVlID09IG51bGwgJiYgIShmbGFncyAmIEluamVjdEZsYWdzLk9wdGlvbmFsKSkge1xuICAgIHRocm93IG5ldyBFcnJvcihgTm8gcHJvdmlkZXIgZm9yIENoYW5nZURldGVjdG9yUmVmIWApO1xuICB9IGVsc2Uge1xuICAgIHJldHVybiB2YWx1ZTtcbiAgfVxufVxuIl19
// OP_0 [signatures ...] var Buffer = require('safe-buffer').Buffer var bscript = require('../../script') var p2mso = require('./output') var typeforce = require('typeforce') var OPS = require('@psf/bitcoincash-ops') function partialSignature (value) { return value === OPS.OP_0 || bscript.isCanonicalSignature(value) } function check (script, allowIncomplete) { var chunks = bscript.decompile(script) if (chunks.length < 2) return false if (chunks[0] !== OPS.OP_0) return false if (allowIncomplete) { return chunks.slice(1).every(partialSignature) } return chunks.slice(1).every(bscript.isCanonicalSignature) } check.toJSON = function () { return 'multisig input' } var EMPTY_BUFFER = Buffer.allocUnsafe(0) function encodeStack (signatures, scriptPubKey) { typeforce([partialSignature], signatures) if (scriptPubKey) { var scriptData = p2mso.decode(scriptPubKey) if (signatures.length < scriptData.m) { throw new TypeError('Not enough signatures provided') } if (signatures.length > scriptData.pubKeys.length) { throw new TypeError('Too many signatures provided') } } return [].concat(EMPTY_BUFFER, signatures.map(function (sig) { if (sig === OPS.OP_0) { return EMPTY_BUFFER } return sig })) } function encode (signatures, scriptPubKey) { return bscript.compile(encodeStack(signatures, scriptPubKey)) } function decodeStack (stack, allowIncomplete) { typeforce(typeforce.Array, stack) typeforce(check, stack, allowIncomplete) return stack.slice(1) } function decode (buffer, allowIncomplete) { var stack = bscript.decompile(buffer) return decodeStack(stack, allowIncomplete) } module.exports = { check: check, decode: decode, decodeStack: decodeStack, encode: encode, encodeStack: encodeStack }
#example program on Condiion statement (IBM Digital Nation Africa) cost = float(10.5) money = float(20.5) if money>cost : print("I can afford the Apple") print("After the if statement") #end-of-the-program
class Node: def __init__(self, data) -> None: self.data = data self.next = None class LinkedList: def __init__(self) -> None: self.head = None def __len__(self): return len(self.to_list()) def __str__(self): return f'{self.to_list()}' def __getitem__(self, index): return self.to_list()[index] def __add__(self, data): self.append(data) def append(self, data): new_node = Node(data) if self.head is None: self.head = new_node return current_node = self.head while current_node.next: current_node = current_node.next current_node.next = new_node return def pop(self): node = self.head while node.next.next != None: node = node.next last_data = node.next.data node.next = None return last_data def index(self, index): node = self.head to_increment = 0 while node: if node.data==index: return to_increment node = node.next to_increment+=1 raise ValueError(f'{index} is not in linked list') def to_list(self): node = self.head node_data = [node.data] while node.next: node = node.next node_data.append(node.data) return node_data
import time import pytest import requests from tempfile import NamedTemporaryFile from helpers.hdfs_api import HDFSApi import os from helpers.cluster import ClickHouseCluster import subprocess SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) cluster = ClickHouseCluster(__file__) node1 = cluster.add_instance('node1', with_hdfs=True, config_dir="configs", main_configs=['configs/log_conf.xml']) @pytest.fixture(scope="module") def started_cluster(): try: cluster.start() yield cluster except Exception as ex: print(ex) raise ex finally: cluster.shutdown() def test_read_write_storage(started_cluster): hdfs_api = HDFSApi("root") node1.query("create table SimpleHDFSStorage (id UInt32, name String, weight Float64) ENGINE = HDFS('hdfs://hdfs1:9000/simple_storage', 'TSV')") node1.query("insert into SimpleHDFSStorage values (1, 'Mark', 72.53)") assert hdfs_api.read_data("/simple_storage") == "1\tMark\t72.53\n" assert node1.query("select * from SimpleHDFSStorage") == "1\tMark\t72.53\n" def test_read_write_storage_with_globs(started_cluster): hdfs_api = HDFSApi("root") node1.query("create table HDFSStorageWithRange (id UInt32, name String, weight Float64) ENGINE = HDFS('hdfs://hdfs1:9000/storage{1..5}', 'TSV')") node1.query("create table HDFSStorageWithEnum (id UInt32, name String, weight Float64) ENGINE = HDFS('hdfs://hdfs1:9000/storage{1,2,3,4,5}', 'TSV')") node1.query("create table HDFSStorageWithQuestionMark (id UInt32, name String, weight Float64) ENGINE = HDFS('hdfs://hdfs1:9000/storage?', 'TSV')") node1.query("create table HDFSStorageWithAsterisk (id UInt32, name String, weight Float64) ENGINE = HDFS('hdfs://hdfs1:9000/storage*', 'TSV')") for i in ["1", "2", "3"]: hdfs_api.write_data("/storage" + i, i + "\tMark\t72.53\n") assert hdfs_api.read_data("/storage" + i) == i + "\tMark\t72.53\n" assert node1.query("select count(*) from HDFSStorageWithRange") == "3\n" assert node1.query("select count(*) from HDFSStorageWithEnum") == "3\n" assert node1.query("select count(*) from HDFSStorageWithQuestionMark") == "3\n" assert node1.query("select count(*) from HDFSStorageWithAsterisk") == "3\n" try: node1.query("insert into HDFSStorageWithEnum values (1, 'NEW', 4.2)") assert False, "Exception have to be thrown" except Exception as ex: print ex assert "in readonly mode" in str(ex) try: node1.query("insert into HDFSStorageWithQuestionMark values (1, 'NEW', 4.2)") assert False, "Exception have to be thrown" except Exception as ex: print ex assert "in readonly mode" in str(ex) try: node1.query("insert into HDFSStorageWithAsterisk values (1, 'NEW', 4.2)") assert False, "Exception have to be thrown" except Exception as ex: print ex assert "in readonly mode" in str(ex) def test_read_write_table(started_cluster): hdfs_api = HDFSApi("root") data = "1\tSerialize\t555.222\n2\tData\t777.333\n" hdfs_api.write_data("/simple_table_function", data) assert hdfs_api.read_data("/simple_table_function") == data assert node1.query("select * from hdfs('hdfs://hdfs1:9000/simple_table_function', 'TSV', 'id UInt64, text String, number Float64')") == data def test_write_table(started_cluster): hdfs_api = HDFSApi("root") node1.query("create table OtherHDFSStorage (id UInt32, name String, weight Float64) ENGINE = HDFS('hdfs://hdfs1:9000/other_storage', 'TSV')") node1.query("insert into OtherHDFSStorage values (10, 'tomas', 55.55), (11, 'jack', 32.54)") result = "10\ttomas\t55.55\n11\tjack\t32.54\n" assert hdfs_api.read_data("/other_storage") == result assert node1.query("select * from OtherHDFSStorage order by id") == result def test_bad_hdfs_uri(started_cluster): try: node1.query("create table BadStorage1 (id UInt32, name String, weight Float64) ENGINE = HDFS('hads:hgsdfs100500:9000/other_storage', 'TSV')") except Exception as ex: print ex assert "Illegal HDFS URI" in str(ex) try: node1.query("create table BadStorage2 (id UInt32, name String, weight Float64) ENGINE = HDFS('hdfs://hdfs100500:9000/other_storage', 'TSV')") except Exception as ex: print ex assert "Unable to create builder to connect to HDFS" in str(ex) try: node1.query("create table BadStorage3 (id UInt32, name String, weight Float64) ENGINE = HDFS('hdfs://hdfs1:9000/<>', 'TSV')") except Exception as ex: print ex assert "Unable to open HDFS file" in str(ex) def test_globs_in_read_table(started_cluster): hdfs_api = HDFSApi("root") some_data = "1\tSerialize\t555.222\n2\tData\t777.333\n" globs_dir = "/dir_for_test_with_globs/" files = ["dir1/dir_dir/file1", "dir2/file2", "simple_table_function", "dir/file", "some_dir/dir1/file", "some_dir/dir2/file", "some_dir/file", "table1_function", "table2_function", "table3_function"] for filename in files: hdfs_api.write_data(globs_dir + filename, some_data) test_requests = [("dir{1..5}/dir_dir/file1", 1), ("*_table_functio?", 1), ("dir/fil?", 1), ("table{3..8}_function", 1), ("table{2..8}_function", 2), ("dir/*", 1), ("dir/*?*?*?*?*", 1), ("dir/*?*?*?*?*?*", 0), ("some_dir/*/file", 2), ("some_dir/dir?/*", 2), ("*/*/*", 3), ("?", 0)] for pattern, value in test_requests: assert node1.query("select * from hdfs('hdfs://hdfs1:9000" + globs_dir + pattern + "', 'TSV', 'id UInt64, text String, number Float64')") == value * some_data def test_read_write_gzip_table(started_cluster): hdfs_api = HDFSApi("root") data = "1\tHello Jessica\t555.222\n2\tI rolled a joint\t777.333\n" hdfs_api.write_gzip_data("/simple_table_function.gz", data) assert hdfs_api.read_gzip_data("/simple_table_function.gz") == data assert node1.query("select * from hdfs('hdfs://hdfs1:9000/simple_table_function.gz', 'TSV', 'id UInt64, text String, number Float64')") == data def test_read_write_gzip_table_with_parameter_gzip(started_cluster): hdfs_api = HDFSApi("root") data = "1\tHello Jessica\t555.222\n2\tI rolled a joint\t777.333\n" hdfs_api.write_gzip_data("/simple_table_function", data) assert hdfs_api.read_gzip_data("/simple_table_function") == data assert node1.query("select * from hdfs('hdfs://hdfs1:9000/simple_table_function', 'TSV', 'id UInt64, text String, number Float64', 'gzip')") == data def test_read_write_table_with_parameter_none(started_cluster): hdfs_api = HDFSApi("root") data = "1\tHello Jessica\t555.222\n2\tI rolled a joint\t777.333\n" hdfs_api.write_data("/simple_table_function.gz", data) assert hdfs_api.read_data("/simple_table_function.gz") == data assert node1.query("select * from hdfs('hdfs://hdfs1:9000/simple_table_function.gz', 'TSV', 'id UInt64, text String, number Float64', 'none')") == data def test_read_write_gzip_table_with_parameter_auto_gz(started_cluster): hdfs_api = HDFSApi("root") data = "1\tHello Jessica\t555.222\n2\tI rolled a joint\t777.333\n" hdfs_api.write_gzip_data("/simple_table_function.gz", data) assert hdfs_api.read_gzip_data("/simple_table_function.gz") == data assert node1.query("select * from hdfs('hdfs://hdfs1:9000/simple_table_function.gz', 'TSV', 'id UInt64, text String, number Float64', 'auto')") == data def test_write_gz_storage(started_cluster): hdfs_api = HDFSApi("root") node1.query("create table GZHDFSStorage (id UInt32, name String, weight Float64) ENGINE = HDFS('hdfs://hdfs1:9000/storage.gz', 'TSV')") node1.query("insert into GZHDFSStorage values (1, 'Mark', 72.53)") assert hdfs_api.read_gzip_data("/storage.gz") == "1\tMark\t72.53\n" assert node1.query("select * from GZHDFSStorage") == "1\tMark\t72.53\n" def test_write_gzip_storage(started_cluster): hdfs_api = HDFSApi("root") node1.query("create table GZIPHDFSStorage (id UInt32, name String, weight Float64) ENGINE = HDFS('hdfs://hdfs1:9000/gzip_storage', 'TSV', 'gzip')") node1.query("insert into GZIPHDFSStorage values (1, 'Mark', 72.53)") assert hdfs_api.read_gzip_data("/gzip_storage") == "1\tMark\t72.53\n" assert node1.query("select * from GZIPHDFSStorage") == "1\tMark\t72.53\n"
!function(e){function t(t){for(var r,o,s=t[0],d=t[1],f=t[2],u=0,p=[];u<s.length;u++)o=s[u],Object.prototype.hasOwnProperty.call(a,o)&&a[o]&&p.push(a[o][0]),a[o]=0;for(r in d)Object.prototype.hasOwnProperty.call(d,r)&&(e[r]=d[r]);for(i&&i(t);p.length;)p.shift()();return c.push.apply(c,f||[]),n()}function n(){for(var e,t=0;t<c.length;t++){for(var n=c[t],r=!0,o=1;o<n.length;o++){var d=n[o];0!==a[d]&&(r=!1)}r&&(c.splice(t--,1),e=s(s.s=n[0]))}return e}var r={},o={6:0},a={6:0},c=[];function s(t){if(r[t])return r[t].exports;var n=r[t]={i:t,l:!1,exports:{}};return e[t].call(n.exports,n,n.exports,s),n.l=!0,n.exports}s.e=function(e){var t=[];o[e]?t.push(o[e]):0!==o[e]&&{5:1}[e]&&t.push(o[e]=new Promise((function(t,n){for(var r=({0:"17007de1",1:"1bfc9850",2:"70b165ca",3:"commons",4:"d0447323",5:"styles",8:"component---src-pages-404-js",9:"component---src-pages-about-js",10:"component---src-pages-destination-js",11:"component---src-pages-index-js",12:"component---src-pages-using-typescript-tsx"}[e]||e)+"."+{0:"31d6cfe0d16ae931b73c",1:"31d6cfe0d16ae931b73c",2:"31d6cfe0d16ae931b73c",3:"31d6cfe0d16ae931b73c",4:"31d6cfe0d16ae931b73c",5:"6bbf1dc0630c4d3ce8f1",8:"31d6cfe0d16ae931b73c",9:"31d6cfe0d16ae931b73c",10:"31d6cfe0d16ae931b73c",11:"31d6cfe0d16ae931b73c",12:"31d6cfe0d16ae931b73c"}[e]+".css",a=s.p+r,c=document.getElementsByTagName("link"),d=0;d<c.length;d++){var f=(i=c[d]).getAttribute("data-href")||i.getAttribute("href");if("stylesheet"===i.rel&&(f===r||f===a))return t()}var u=document.getElementsByTagName("style");for(d=0;d<u.length;d++){var i;if((f=(i=u[d]).getAttribute("data-href"))===r||f===a)return t()}var p=document.createElement("link");p.rel="stylesheet",p.type="text/css",p.onload=t,p.onerror=function(t){var r=t&&t.target&&t.target.src||a,c=new Error("Loading CSS chunk "+e+" failed.\n("+r+")");c.code="CSS_CHUNK_LOAD_FAILED",c.request=r,delete o[e],p.parentNode.removeChild(p),n(c)},p.href=a,document.getElementsByTagName("head")[0].appendChild(p)})).then((function(){o[e]=0})));var n=a[e];if(0!==n)if(n)t.push(n[2]);else{var r=new Promise((function(t,r){n=a[e]=[t,r]}));t.push(n[2]=r);var c,d=document.createElement("script");d.charset="utf-8",d.timeout=120,s.nc&&d.setAttribute("nonce",s.nc),d.src=function(e){return s.p+""+({0:"17007de1",1:"1bfc9850",2:"70b165ca",3:"commons",4:"d0447323",5:"styles",8:"component---src-pages-404-js",9:"component---src-pages-about-js",10:"component---src-pages-destination-js",11:"component---src-pages-index-js",12:"component---src-pages-using-typescript-tsx"}[e]||e)+"-"+{0:"3d066fb0a0ed20d2629e",1:"9ce487527042896887b9",2:"f821a436695fbd58159a",3:"354dd1ba2382340a75a0",4:"9fd2604e3e843679b523",5:"29163f9dced6fe4a408a",8:"bba2594a3c691c0a1e46",9:"09aee8c8086cf8142ce1",10:"d5fd61abacaacc31243a",11:"1f12d16d0af41f9991c0",12:"fc6f27354290f5994fbe"}[e]+".js"}(e);var f=new Error;c=function(t){d.onerror=d.onload=null,clearTimeout(u);var n=a[e];if(0!==n){if(n){var r=t&&("load"===t.type?"missing":t.type),o=t&&t.target&&t.target.src;f.message="Loading chunk "+e+" failed.\n("+r+": "+o+")",f.name="ChunkLoadError",f.type=r,f.request=o,n[1](f)}a[e]=void 0}};var u=setTimeout((function(){c({type:"timeout",target:d})}),12e4);d.onerror=d.onload=c,document.head.appendChild(d)}return Promise.all(t)},s.m=e,s.c=r,s.d=function(e,t,n){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(s.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)s.d(n,r,function(t){return e[t]}.bind(null,r));return n},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="/",s.oe=function(e){throw console.error(e),e};var d=window.webpackJsonp=window.webpackJsonp||[],f=d.push.bind(d);d.push=t,d=d.slice();for(var u=0;u<d.length;u++)t(d[u]);var i=f;n()}([]); //# sourceMappingURL=webpack-runtime-d40947842817917791c5.js.map
// http://mrl.nyu.edu/~perlin/noise/ var ImprovedNoise = function () { var p = [ 151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10, 23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87, 174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211, 133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208, 89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5, 202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119, 248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232, 178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249, 14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205, 93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 ]; for (var i = 0; i < 256 ; i ++) { p[256 + i] = p[i]; } function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); } function lerp(t, a, b) { return a + t * (b - a); } function grad(hash, x, y, z) { var h = hash & 15; var u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } return { noise: function (x, y, z) { var floorX = ~~x, floorY = ~~y, floorZ = ~~z; var X = floorX & 255, Y = floorY & 255, Z = floorZ & 255; x -= floorX; y -= floorY; z -= floorZ; var xMinus1 = x - 1, yMinus1 = y - 1, zMinus1 = z - 1; var u = fade(x), v = fade(y), w = fade(z); var A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z; return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], xMinus1, y, z)), lerp(u, grad(p[AB], x, yMinus1, z), grad(p[BB], xMinus1, yMinus1, z))), lerp(v, lerp(u, grad(p[AA + 1], x, y, zMinus1), grad(p[BA + 1], xMinus1, y, z - 1)), lerp(u, grad(p[AB + 1], x, yMinus1, zMinus1), grad(p[BB + 1], xMinus1, yMinus1, zMinus1)))); } } };
# -*- coding: utf-8 -*- """Utility functions for B-splines, potentially useful for converting MATLAB codes to Python. CAVEATS: - Only a very minimal set of functionality is implemented here. - Some technical details differ from the MATLAB equivalents. Particularly, we use spline order `p` **as-is** instead of MATLAB's `k` parameter (`k` = `p` + 1) in the function parameters. Created on Fri Mar 24 13:52:37 2017 @author: Juha Jeronen, juha.jeronen@tut.fi """ from __future__ import division, print_function, absolute_import import numpy as np import bspline def augknt(knots, order): """Augment a knot vector. Parameters: knots: Python list or rank-1 array, the original knot vector (without endpoint repeats) order: int, >= 0, order of spline Returns: list_of_knots: rank-1 array that has (`order` + 1) copies of ``knots[0]``, then ``knots[1:-1]``, and finally (`order` + 1) copies of ``knots[-1]``. Caveats: `order` is the spline order `p`, not `p` + 1, and existing knots are never deleted. The knot vector always becomes longer by calling this function. """ if isinstance(knots, np.ndarray) and knots.ndim > 1: raise ValueError("knots must be a list or a rank-1 array") knots = list(knots) # ensure Python list # One copy of knots[0] and knots[-1] will come from "knots" itself, # so we only need to prepend/append "order" copies. # return np.array( [knots[0]] * order + knots + [knots[-1]] * order ) def aveknt(t, k): """Compute the running average of `k` successive elements of `t`. Return the averaged array. Parameters: t: Python list or rank-1 array k: int, >= 2, how many successive elements to average Returns: rank-1 array, averaged data. If k > len(t), returns a zero-length array. Caveat: This is slightly different from MATLAB's aveknt, which returns the running average of `k`-1 successive elements of ``t[1:-1]`` (and the empty vector if ``len(t) - 2 < k - 1``). """ t = np.atleast_1d(t) if t.ndim > 1: raise ValueError("t must be a list or a rank-1 array") n = t.shape[0] u = max(0, n - (k-1)) # number of elements in the output array out = np.empty( (u,), dtype=t.dtype ) for j in range(u): out[j] = sum( t[j:(j+k)] ) / k return out def aptknt(tau, order): """Create an acceptable knot vector. Minimal emulation of MATLAB's ``aptknt``. The returned knot vector can be used to generate splines of desired `order` that are suitable for interpolation to the collocation sites `tau`. Note that this is only possible when ``len(tau)`` >= `order` + 1. When this condition does not hold, a valid knot vector is returned, but using it to generate a spline basis will not have the desired effect (the spline will return a length-zero array upon evaluation). Parameters: tau: Python list or rank-1 array, collocation sites order: int, >= 0, order of spline Returns: rank-1 array, `k` copies of ``tau[0]``, then ``aveknt(tau[1:-1], k-1)``, and finally `k` copies of ``tau[-1]``, where ``k = min(order+1, len(tau))``. """ tau = np.atleast_1d(tau) k = order + 1 if tau.ndim > 1: raise ValueError("tau must be a list or a rank-1 array") # emulate MATLAB behavior for the "k" parameter # # See # https://se.mathworks.com/help/curvefit/aptknt.html # if len(tau) < k: k = len(tau) if not (tau == sorted(tau)).all(): raise ValueError("tau must be nondecreasing") # last processed element needs to be: # i + k - 1 = len(tau)- 1 # => i + k = len(tau) # => i = len(tau) - k # u = len(tau) - k for i in range(u): if tau[i+k-1] == tau[i]: raise ValueError("k-fold (or higher) repeated sites not allowed, but tau[i+k-1] == tau[i] for i = %d, k = %d" % (i,k)) # form the output sequence # prefix = [ tau[0] ] * k suffix = [ tau[-1] ] * k # https://se.mathworks.com/help/curvefit/aveknt.html # MATLAB's aveknt(): # - averages successive k-1 entries, but ours averages k # - seems to ignore the endpoints # tmp = aveknt(tau[1:-1], k-1) middle = tmp.tolist() return np.array( prefix + middle + suffix, dtype=tmp.dtype ) def knt2mlt(t): """Count multiplicities of elements in a sorted list or rank-1 array. Minimal emulation of MATLAB's ``knt2mlt``. Parameters: t: Python list or rank-1 array. Must be sorted! Returns: out rank-1 array such that out[k] = #{ t[i] == t[k] for i < k } Example: If ``t = [1, 1, 2, 3, 3, 3]``, then ``out = [0, 1, 0, 0, 1, 2]``. Caveat: Requires input to be already sorted (this is not checked). """ t = np.atleast_1d(t) if t.ndim > 1: raise ValueError("t must be a list or a rank-1 array") out = [] e = None for k in range(t.shape[0]): if t[k] != e: e = t[k] count = 0 else: count += 1 out.append(count) return np.array( out ) def spcol(knots, order, tau): """Return collocation matrix. Minimal emulation of MATLAB's ``spcol``. Parameters: knots: rank-1 array, knot vector (with appropriately repeated endpoints; see `augknt`, `aptknt`) order: int, >= 0, order of spline tau: rank-1 array, collocation sites Returns: rank-2 array A such that A[i,j] = D**{m(i)} B_j(tau[i]) where m(i) = multiplicity of site tau[i] D**k = kth derivative (0 for function value itself) """ m = knt2mlt(tau) B = bspline.Bspline(knots, order) dummy = B(0.) nbasis = len(dummy) # perform dummy evaluation to get number of basis functions A = np.empty( (tau.shape[0], nbasis), dtype=dummy.dtype ) for i,item in enumerate(zip(tau,m)): taui,mi = item f = B.diff(order=mi) A[i,:] = f(taui) return A
import React from "react"; import PropTypes from "prop-types"; const Message = ({ msg }) => { return ( <div className="alert alert-warning alert-dismissible fade show" role="alert" > {msg} <button type="button" className="close" data-dismiss="alert" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> ); }; Message.propTypes = { msg: PropTypes.string.isRequired }; export default Message;
const expect = require('chai').expect; const isOddOrEven = require('../00.isOddOrEven'); describe("even or odd", () => { it("isString", () => { expect(isOddOrEven(3)).to.undefined; }); it('isOdd', () => { expect(isOddOrEven('s')).to.equal('odd'); }) it('isEven', () => { expect(isOddOrEven('aa')).to.equal('even'); }) }); describe("Test group #2", function () { });
const Campground = require("../models/campground"); const mbxGeocoding = require("@mapbox/mapbox-sdk/services/geocoding"); const mapBoxToken = process.env.MAPBOX_TOKEN; const geocoder = mbxGeocoding({ accessToken: mapBoxToken }); const { cloudinary } = require("../cloudinary"); module.exports.index = async (req, res) => { const campgrounds = await Campground.find({}); res.render("campgrounds/index", { campgrounds }); }; module.exports.renderNewForm = (req, res) => { res.render("campgrounds/new"); }; module.exports.renderNewComp = (req, res) => { res.render("campgrounds/companion"); }; module.exports.createCampground = async (req, res, next) => { const geoData = await geocoder .forwardGeocode({ query: req.body.campground.location, limit: 1, }) .send(); const campground = new Campground(req.body.campground); campground.geometry = geoData.body.features[0].geometry; campground.images = req.files.map((f) => ({ url: f.path, filename: f.filename, })); campground.author = req.user._id; await campground.save(); console.log(campground); req.flash("success", "Successfully made a new campground!"); res.redirect(`/campgrounds/${campground._id}`); }; module.exports.showCampground = async (req, res) => { const campground = await Campground.findById(req.params.id) .populate({ path: "reviews", populate: { path: "author", }, }) .populate("author"); if (!campground) { req.flash("error", "Cannot find that campground!"); return res.redirect("/campgrounds"); } res.render("campgrounds/show", { campground }); }; module.exports.renderEditForm = async (req, res) => { const { id } = req.params; const campground = await Campground.findById(id); if (!campground) { req.flash("error", "Cannot find that campground!"); return res.redirect("/campgrounds"); } res.render("campgrounds/edit", { campground }); }; module.exports.updateCampground = async (req, res) => { const { id } = req.params; console.log(req.body); const campground = await Campground.findByIdAndUpdate(id, { ...req.body.campground, }); const imgs = req.files.map((f) => ({ url: f.path, filename: f.filename })); campground.images.push(...imgs); await campground.save(); if (req.body.deleteImages) { for (let filename of req.body.deleteImages) { await cloudinary.uploader.destroy(filename); } await campground.updateOne({ $pull: { images: { filename: { $in: req.body.deleteImages } } }, }); } req.flash("success", "Successfully updated campground!"); res.redirect(`/campgrounds/${campground._id}`); }; module.exports.deleteCampground = async (req, res) => { const { id } = req.params; await Campground.findByIdAndDelete(id); req.flash("success", "Successfully deleted campground"); res.redirect("/campgrounds"); };
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[118],{ /***/ "./frontend/src/@core/comp-functions/forms/form-validation.js": /*!********************************************************************!*\ !*** ./frontend/src/@core/comp-functions/forms/form-validation.js ***! \********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return formValidation; }); /* harmony import */ var _vue_composition_api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @vue/composition-api */ "./frontend/node_modules/@vue/composition-api/dist/vue-composition-api.esm.js"); // =========================================================== // ! This is coupled with "veeValidate" plugin // =========================================================== function formValidation(resetFormData) { var clearFormData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {}; // ------------------------------------------------ // refFormObserver // ! This is for veeValidate Observer // * Used for veeValidate form observer // ------------------------------------------------ var refFormObserver = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["ref"])(null); // ------------------------------------------------ // resetObserver // ! This function is coupled with veeValidate // * It resets form observer // ------------------------------------------------ var resetObserver = function resetObserver() { refFormObserver.value.reset(); }; // ------------------------------------------------ // getValidationState // ! This function is coupled with veeValidate // * It returns true/false based on validation // ------------------------------------------------ // eslint-disable-next-line object-curly-newline var getValidationState = function getValidationState(_ref) { var dirty = _ref.dirty, validated = _ref.validated, fieldRequired = _ref.required, changed = _ref.changed, _ref$valid = _ref.valid, valid = _ref$valid === void 0 ? null : _ref$valid; var result = dirty || validated ? valid : null; return !fieldRequired && !changed ? null : result; }; // ------------------------------------------------ // resetForm // ! This function is coupled with veeValidate // * This uses resetFormData arg to reset form data // ------------------------------------------------ var resetForm = function resetForm() { resetFormData(); Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["nextTick"])(function () { resetObserver(); }); }; // ------------------------------------------------ // clearForm // ! This function is coupled with veeValidate // * This uses clearFormData arg to reset form data // ------------------------------------------------ var clearForm = function clearForm() { clearFormData(); Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["nextTick"])(function () { resetObserver(); }); }; return { refFormObserver: refFormObserver, resetObserver: resetObserver, getValidationState: getValidationState, resetForm: resetForm, clearForm: clearForm }; } /***/ }), /***/ "./frontend/src/@core/components/toastification/ToastificationContent.vue": /*!********************************************************************************!*\ !*** ./frontend/src/@core/components/toastification/ToastificationContent.vue ***! \********************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _ToastificationContent_vue_vue_type_template_id_2fedfe59_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ToastificationContent.vue?vue&type=template&id=2fedfe59&scoped=true& */ "./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=template&id=2fedfe59&scoped=true&"); /* harmony import */ var _ToastificationContent_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ToastificationContent.vue?vue&type=script&lang=js& */ "./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=script&lang=js&"); /* empty/unused harmony star reexport *//* harmony import */ var _ToastificationContent_vue_vue_type_style_index_0_id_2fedfe59_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true& */ "./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true&"); /* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js"); /* normalize component */ var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__["default"])( _ToastificationContent_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"], _ToastificationContent_vue_vue_type_template_id_2fedfe59_scoped_true___WEBPACK_IMPORTED_MODULE_0__["render"], _ToastificationContent_vue_vue_type_template_id_2fedfe59_scoped_true___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"], false, null, "2fedfe59", null ) /* hot reload */ if (false) { var api; } component.options.__file = "frontend/src/@core/components/toastification/ToastificationContent.vue" /* harmony default export */ __webpack_exports__["default"] = (component.exports); /***/ }), /***/ "./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=script&lang=js&": /*!*********************************************************************************************************!*\ !*** ./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=script&lang=js& ***! \*********************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ToastificationContent_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/babel-loader/lib??ref--4-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./ToastificationContent.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=script&lang=js&"); /* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ToastificationContent_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]); /***/ }), /***/ "./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true&": /*!******************************************************************************************************************************************!*\ !*** ./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true& ***! \******************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ToastificationContent_vue_vue_type_style_index_0_id_2fedfe59_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/style-loader!../../../../../node_modules/css-loader!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/src??ref--7-2!../../../../../node_modules/sass-loader/dist/cjs.js??ref--7-3!../../../../../node_modules/sass-loader/dist/cjs.js??ref--11-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true& */ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true&"); /* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ToastificationContent_vue_vue_type_style_index_0_id_2fedfe59_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ToastificationContent_vue_vue_type_style_index_0_id_2fedfe59_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0__); /* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ToastificationContent_vue_vue_type_style_index_0_id_2fedfe59_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0__) if(["default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_ToastificationContent_vue_vue_type_style_index_0_id_2fedfe59_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__)); /***/ }), /***/ "./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=template&id=2fedfe59&scoped=true&": /*!***************************************************************************************************************************!*\ !*** ./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=template&id=2fedfe59&scoped=true& ***! \***************************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_ToastificationContent_vue_vue_type_template_id_2fedfe59_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../../node_modules/vue-loader/lib??vue-loader-options!./ToastificationContent.vue?vue&type=template&id=2fedfe59&scoped=true& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=template&id=2fedfe59&scoped=true&"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_ToastificationContent_vue_vue_type_template_id_2fedfe59_scoped_true___WEBPACK_IMPORTED_MODULE_0__["render"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_ToastificationContent_vue_vue_type_template_id_2fedfe59_scoped_true___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; }); /***/ }), /***/ "./frontend/src/@core/utils/filter.js": /*!********************************************!*\ !*** ./frontend/src/@core/utils/filter.js ***! \********************************************/ /*! exports provided: kFormatter, title, avatarText, formatDate, formatDateToMonthShort, filterTags */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "kFormatter", function() { return kFormatter; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "title", function() { return title; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "avatarText", function() { return avatarText; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatDate", function() { return formatDate; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "formatDateToMonthShort", function() { return formatDateToMonthShort; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterTags", function() { return filterTags; }); /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils */ "./frontend/src/@core/utils/utils.js"); var kFormatter = function kFormatter(num) { return num > 999 ? "".concat((num / 1000).toFixed(1), "k") : num; }; var title = function title(value) { var replacer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ' '; if (!value) return ''; var str = value.toString(); var arr = str.split(replacer); var capitalizedArray = []; arr.forEach(function (word) { var capitalized = word.charAt(0).toUpperCase() + word.slice(1); capitalizedArray.push(capitalized); }); return capitalizedArray.join(' '); }; var avatarText = function avatarText(value) { if (!value) return ''; var nameArray = value.split(' '); return nameArray.map(function (word) { return word.charAt(0).toUpperCase(); }).join(''); }; /** * Format and return date in Humanize format * Intl docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format * Intl Constructor: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat * @param {String} value date to format * @param {Object} formatting Intl object to format with */ var formatDate = function formatDate(value) { var formatting = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { month: 'short', day: 'numeric', year: 'numeric' }; if (!value) return value; return new Intl.DateTimeFormat('en-US', formatting).format(new Date(value)); }; /** * Return short human friendly month representation of date * Can also convert date to only time if date is of today (Better UX) * @param {String} value date to format * @param {Boolean} toTimeForCurrentDay Shall convert to time if day is today/current */ var formatDateToMonthShort = function formatDateToMonthShort(value) { var toTimeForCurrentDay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var date = new Date(value); var formatting = { month: 'short', day: 'numeric' }; if (toTimeForCurrentDay && Object(_utils__WEBPACK_IMPORTED_MODULE_0__["isToday"])(date)) { formatting = { hour: 'numeric', minute: 'numeric' }; } return new Intl.DateTimeFormat('en-US', formatting).format(new Date(value)); }; // Strip all the tags from markup and return plain text var filterTags = function filterTags(value) { return value.replace(/<\/?[^>]+(>|$)/g, ''); }; /***/ }), /***/ "./frontend/src/@core/utils/utils.js": /*!*******************************************!*\ !*** ./frontend/src/@core/utils/utils.js ***! \*******************************************/ /*! exports provided: isObject, isToday, getRandomBsVariant, isDynamicRouteActive, useRouter */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return isObject; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isToday", function() { return isToday; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRandomBsVariant", function() { return getRandomBsVariant; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDynamicRouteActive", function() { return isDynamicRouteActive; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "useRouter", function() { return useRouter; }); /* harmony import */ var _router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @/router */ "./frontend/src/router/index.js"); /* harmony import */ var _vue_composition_api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @vue/composition-api */ "./frontend/node_modules/@vue/composition-api/dist/vue-composition-api.esm.js"); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } 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; } function _typeof(obj) { "@babel/helpers - typeof"; 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); } // eslint-disable-next-line object-curly-newline var isObject = function isObject(obj) { return _typeof(obj) === 'object' && obj !== null; }; var isToday = function isToday(date) { var today = new Date(); return ( /* eslint-disable operator-linebreak */ date.getDate() === today.getDate() && date.getMonth() === today.getMonth() && date.getFullYear() === today.getFullYear() /* eslint-enable */ ); }; var getRandomFromArray = function getRandomFromArray(array) { return array[Math.floor(Math.random() * array.length)]; }; // ? Light and Dark variant is not included // prettier-ignore var getRandomBsVariant = function getRandomBsVariant() { return getRandomFromArray(['primary', 'secondary', 'success', 'warning', 'danger', 'info']); }; var isDynamicRouteActive = function isDynamicRouteActive(route) { var _router$resolve = _router__WEBPACK_IMPORTED_MODULE_0__["default"].resolve(route), resolvedRoute = _router$resolve.route; return resolvedRoute.path === _router__WEBPACK_IMPORTED_MODULE_0__["default"].currentRoute.path; }; // Thanks: https://medium.com/better-programming/reactive-vue-routes-with-the-composition-api-18c1abd878d1 var useRouter = function useRouter() { var vm = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_1__["getCurrentInstance"])().proxy; var state = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_1__["reactive"])({ route: vm.$route }); Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_1__["watch"])(function () { return vm.$route; }, function (r) { state.route = r; }); return _objectSpread(_objectSpread({}, Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_1__["toRefs"])(state)), {}, { router: vm.$router }); }; /** * This is just enhancement over Object.extend [Gives deep extend] * @param {target} a Object which contains values to be overridden * @param {source} b Object which contains values to override */ // export const objectExtend = (a, b) => { // // Don't touch 'null' or 'undefined' objects. // if (a == null || b == null) { // return a // } // Object.keys(b).forEach(key => { // if (Object.prototype.toString.call(b[key]) === '[object Object]') { // if (Object.prototype.toString.call(a[key]) !== '[object Object]') { // // eslint-disable-next-line no-param-reassign // a[key] = b[key] // } else { // // eslint-disable-next-line no-param-reassign // a[key] = objectExtend(a[key], b[key]) // } // } else { // // eslint-disable-next-line no-param-reassign // a[key] = b[key] // } // }) // return a // } /***/ }), /***/ "./frontend/src/@core/utils/validations/validations.js": /*!*************************************************************!*\ !*** ./frontend/src/@core/utils/validations/validations.js ***! \*************************************************************/ /*! exports provided: required, email, min, confirmed, regex, between, alpha, integer, digits, alphaDash, alphaNum, length, positive, credit, password, url */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "required", function() { return required; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "email", function() { return email; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "min", function() { return min; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "confirmed", function() { return confirmed; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "regex", function() { return regex; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "between", function() { return between; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alpha", function() { return alpha; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "integer", function() { return integer; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "digits", function() { return digits; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alphaDash", function() { return alphaDash; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alphaNum", function() { return alphaNum; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "length", function() { return length; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "positive", function() { return positive; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "credit", function() { return credit; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "password", function() { return password; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "url", function() { return url; }); /* harmony import */ var vee_validate__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vee-validate */ "./frontend/node_modules/vee-validate/dist/vee-validate.esm.js"); /* harmony import */ var vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! vee-validate/dist/rules */ "./frontend/node_modules/vee-validate/dist/rules.js"); /* harmony import */ var vee_validate_dist_locale_ar_json__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! vee-validate/dist/locale/ar.json */ "./frontend/node_modules/vee-validate/dist/locale/ar.json"); var vee_validate_dist_locale_ar_json__WEBPACK_IMPORTED_MODULE_2___namespace = /*#__PURE__*/__webpack_require__.t(/*! vee-validate/dist/locale/ar.json */ "./frontend/node_modules/vee-validate/dist/locale/ar.json", 1); /* harmony import */ var vee_validate_dist_locale_en_json__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! vee-validate/dist/locale/en.json */ "./frontend/node_modules/vee-validate/dist/locale/en.json"); var vee_validate_dist_locale_en_json__WEBPACK_IMPORTED_MODULE_3___namespace = /*#__PURE__*/__webpack_require__.t(/*! vee-validate/dist/locale/en.json */ "./frontend/node_modules/vee-validate/dist/locale/en.json", 1); /* harmony import */ var _validators__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./validators */ "./frontend/src/@core/utils/validations/validators.js"); // eslint-disable-next-line object-curly-newline // //////////////////////////////////////////////////////// // General // //////////////////////////////////////////////////////// var required = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('required', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["required"]); var email = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('email', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["email"]); var min = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('min', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["min"]); var confirmed = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('confirmed', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["confirmed"]); var regex = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('regex', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["regex"]); var between = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('between', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["between"]); var alpha = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('alpha', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["alpha"]); var integer = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('integer', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["integer"]); var digits = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('digits', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["digits"]); var alphaDash = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('alpha-dash', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["alpha_dash"]); var alphaNum = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('alpha-num', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["alpha_num"]); var length = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('length', vee_validate_dist_rules__WEBPACK_IMPORTED_MODULE_1__["length"]); var positive = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('positive', { validate: _validators__WEBPACK_IMPORTED_MODULE_4__["validatorPositive"], message: 'Please enter positive number!' }); var credit = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('credit-card', { validate: _validators__WEBPACK_IMPORTED_MODULE_4__["validatorCreditCard"], message: 'It is not valid credit card!' }); var password = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('password', { validate: _validators__WEBPACK_IMPORTED_MODULE_4__["validatorPassword"], message: 'Your {_field_} must contain at least one uppercase, one lowercase, one special character and one digit' }); var url = Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["extend"])('url', { validate: _validators__WEBPACK_IMPORTED_MODULE_4__["validatorUrlValidator"], message: 'URL is invalid' }); // Install English and Arabic localizations. Object(vee_validate__WEBPACK_IMPORTED_MODULE_0__["localize"])({ en: { messages: vee_validate_dist_locale_en_json__WEBPACK_IMPORTED_MODULE_3__.messages, names: { email: 'Email', password: 'Password' }, fields: { password: { min: '{_field_} is too short, you want to get hacked?' } } }, ar: { messages: vee_validate_dist_locale_ar_json__WEBPACK_IMPORTED_MODULE_2__.messages, names: { email: 'البريد الإلكتروني', password: 'كلمة السر' }, fields: { password: { min: 'كلمة السر قصيرة جداً سيتم اختراقك' } } } }); // //////////////////////////////////////////////////////// // NOTE: // Quasar validation for reference only // Remove this note once development is finished and make sure to // to convert all of them in veevalidate version // //////////////////////////////////////////////////////// // export const required = (val) => { // return (val && val.length > 0) || '*Field is required' // } // export const required_obj = (obj) => { // if (obj === null || obj === undefined) return '*Field is required' // return (Object.entries(obj).length > 0 && obj.constructor === Object) || '*Field is required' // } // export const no_blank_spaces_arr = (arr) => { // return arr.every(val => (val.trim() && val.trim().length > 0)) || 'Blank Spaces are not allowed' // } // export const url = val => { // // If blank return // if (val === undefined || val === null || val.length === 0) return true // // Used // // https://stackoverflow.com/questions/4314741/url-regex-validation // // Other // // https://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-a-url // // https://www.w3resource.com/javascript-exercises/javascript-regexp-exercise-9.php // // https://www.geeksforgeeks.org/how-to-validate-url-using-regular-expression-in-javascript/ // /* eslint-disable no-useless-escape */ // const re = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/ // /* eslint-enable no-useless-escape */ // return re.test(val) || 'URL is invalid' // } // export const date = val => { // // If blank return // if (val === undefined || val === null || val.length === 0) return true // // https://github.com/quasarframework/quasar/blob/dev/ui/src/utils/patterns.js // return /^-?[\d]+\/[0-1]\d\/[0-3]\d$/.test(val) || 'Date is invalid' // } // export const max = (val, max) => { // // If blank return // if (val === undefined || val === null) return true // return val.length <= max || `More than ${max} characters are not allowed` // } // export const max_arr = (val, max) => { // return val.length <= max || `More than ${max} values are not allowed` // } // export const min = (val, min) => { // // If blank return // if (val === undefined || val === null || val.length === 0) return true // return val.length >= min || `Minimum ${min} characters are required` // } // export const num_range = (val, min, max) => { // // If blank return // if (val === undefined || val === null || val.length === 0) return true // const msg = 'Value is invalid' // if (min === null) return val <= max || msg // else if (max === null) return val >= min || msg // else return (val >= min && val <= max) || msg // } /***/ }), /***/ "./frontend/src/@core/utils/validations/validators.js": /*!************************************************************!*\ !*** ./frontend/src/@core/utils/validations/validators.js ***! \************************************************************/ /*! exports provided: validatorPositive, validatorPassword, validatorCreditCard, validatorUrlValidator */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validatorPositive", function() { return validatorPositive; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validatorPassword", function() { return validatorPassword; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validatorCreditCard", function() { return validatorCreditCard; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validatorUrlValidator", function() { return validatorUrlValidator; }); var validatorPositive = function validatorPositive(value) { if (value >= 0) { return true; } return false; }; var validatorPassword = function validatorPassword(password) { /* eslint-disable no-useless-escape */ var regExp = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&*()]).{8,}/; /* eslint-enable no-useless-escape */ var validPassword = regExp.test(password); return validPassword; }; var validatorCreditCard = function validatorCreditCard(creditnum) { /* eslint-disable no-useless-escape */ var cRegExp = /^(?:3[47][0-9]{13})$/; /* eslint-enable no-useless-escape */ var validCreditCard = cRegExp.test(creditnum); return validCreditCard; }; var validatorUrlValidator = function validatorUrlValidator(val) { if (val === undefined || val === null || val.length === 0) { return true; } /* eslint-disable no-useless-escape */ var re = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/; /* eslint-enable no-useless-escape */ return re.test(val); }; /***/ }), /***/ "./frontend/src/@fake-db/data/other/countries.js": /*!*******************************************************!*\ !*** ./frontend/src/@fake-db/data/other/countries.js ***! \*******************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony default export */ __webpack_exports__["default"] = (['Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burundi', "Côte d'Ivoire", 'Cabo Verde', 'Cambodia', 'Cameroon', 'Canada', 'Central African Republic', 'Chad', 'Chile', 'China', 'Colombia', 'Comoros', 'Congo', 'Costa Rica', 'Croatia', 'Cuba', 'Cyprus', 'Czechia', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Eswatini', 'Ethiopia', 'Fiji', 'Finland', 'France', 'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Holy See', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Montenegro', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepal', 'Netherlands', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'North Korea', 'North Macedonia', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Palestine State', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russia', 'Rwanda', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent & the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Korea', 'South Sudan', 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Sweden', 'Switzerland', 'Syria', 'Tajikistan', 'Tanzania', 'Thailand', 'Timor-Leste', 'Togo', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'USA', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela', 'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe']); /***/ }), /***/ "./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue": /*!*****************************************************************************!*\ !*** ./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue ***! \*****************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _InventoryListAddNew_vue_vue_type_template_id_0c1e10d7___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./InventoryListAddNew.vue?vue&type=template&id=0c1e10d7& */ "./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=template&id=0c1e10d7&"); /* harmony import */ var _InventoryListAddNew_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./InventoryListAddNew.vue?vue&type=script&lang=js& */ "./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=script&lang=js&"); /* empty/unused harmony star reexport *//* harmony import */ var _InventoryListAddNew_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./InventoryListAddNew.vue?vue&type=style&index=0&lang=scss& */ "./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=style&index=0&lang=scss&"); /* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js"); /* normalize component */ var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__["default"])( _InventoryListAddNew_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"], _InventoryListAddNew_vue_vue_type_template_id_0c1e10d7___WEBPACK_IMPORTED_MODULE_0__["render"], _InventoryListAddNew_vue_vue_type_template_id_0c1e10d7___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"], false, null, null, null ) /* hot reload */ if (false) { var api; } component.options.__file = "frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue" /* harmony default export */ __webpack_exports__["default"] = (component.exports); /***/ }), /***/ "./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=script&lang=js&": /*!******************************************************************************************************!*\ !*** ./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=script&lang=js& ***! \******************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_InventoryListAddNew_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/babel-loader/lib??ref--4-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./InventoryListAddNew.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=script&lang=js&"); /* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_InventoryListAddNew_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]); /***/ }), /***/ "./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=style&index=0&lang=scss&": /*!***************************************************************************************************************!*\ !*** ./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=style&index=0&lang=scss& ***! \***************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_InventoryListAddNew_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/style-loader!../../../../../node_modules/css-loader!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/src??ref--7-2!../../../../../node_modules/sass-loader/dist/cjs.js??ref--7-3!../../../../../node_modules/sass-loader/dist/cjs.js??ref--11-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./InventoryListAddNew.vue?vue&type=style&index=0&lang=scss& */ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=style&index=0&lang=scss&"); /* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_InventoryListAddNew_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_InventoryListAddNew_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__); /* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_InventoryListAddNew_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__) if(["default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _node_modules_style_loader_index_js_node_modules_css_loader_index_js_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_7_2_node_modules_sass_loader_dist_cjs_js_ref_7_3_node_modules_sass_loader_dist_cjs_js_ref_11_0_node_modules_vue_loader_lib_index_js_vue_loader_options_InventoryListAddNew_vue_vue_type_style_index_0_lang_scss___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__)); /***/ }), /***/ "./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=template&id=0c1e10d7&": /*!************************************************************************************************************!*\ !*** ./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=template&id=0c1e10d7& ***! \************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_InventoryListAddNew_vue_vue_type_template_id_0c1e10d7___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../../node_modules/vue-loader/lib??vue-loader-options!./InventoryListAddNew.vue?vue&type=template&id=0c1e10d7& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=template&id=0c1e10d7&"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_InventoryListAddNew_vue_vue_type_template_id_0c1e10d7___WEBPACK_IMPORTED_MODULE_0__["render"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_InventoryListAddNew_vue_vue_type_template_id_0c1e10d7___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; }); /***/ }), /***/ "./frontend/src/views/inventory/inventory-list/useUsersList.js": /*!*********************************************************************!*\ !*** ./frontend/src/views/inventory/inventory-list/useUsersList.js ***! \*********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return useUsersList; }); /* harmony import */ var _vue_composition_api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @vue/composition-api */ "./frontend/node_modules/@vue/composition-api/dist/vue-composition-api.esm.js"); /* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @/store */ "./frontend/src/store/index.js"); /* harmony import */ var _core_utils_filter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @core/utils/filter */ "./frontend/src/@core/utils/filter.js"); /* harmony import */ var vue_toastification_composition__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! vue-toastification/composition */ "./frontend/node_modules/vue-toastification/composition/index.js"); /* harmony import */ var vue_toastification_composition__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(vue_toastification_composition__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var _core_components_toastification_ToastificationContent_vue__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @core/components/toastification/ToastificationContent.vue */ "./frontend/src/@core/components/toastification/ToastificationContent.vue"); // Notification function useUsersList() { // Use toast var toast = Object(vue_toastification_composition__WEBPACK_IMPORTED_MODULE_3__["useToast"])(); var refUserListTable = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["ref"])(null); // Table Handlers var tableColumns = [{ key: 'date', sortable: true }, { key: 'vinnumber', sortable: true }, { key: 'Year|Make|Model', sortable: true }, { key: 'customer', sortable: true }, { key: 'location', sortable: true }, { key: 'duration', sortable: true }, { key: 'balance', sortable: true }, { key: 'status', sortable: true }, { key: 'actions' }]; var perPage = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["ref"])(10); var totalUsers = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["ref"])(0); var currentPage = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["ref"])(1); var perPageOptions = [10, 25, 50, 100]; var searchQuery = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["ref"])(''); var sortBy = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["ref"])('id'); var isSortDirDesc = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["ref"])(true); var roleFilter = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["ref"])(null); var planFilter = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["ref"])(null); var statusFilter = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["ref"])(null); var dataMeta = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["computed"])(function () { var localItemsCount = refUserListTable.value ? refUserListTable.value.localItems.length : 0; return { from: perPage.value * (currentPage.value - 1) + (localItemsCount ? 1 : 0), to: perPage.value * (currentPage.value - 1) + localItemsCount, of: totalUsers.value }; }); var refetchData = function refetchData() { refUserListTable.value.refresh(); }; Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_0__["watch"])([currentPage, perPage, searchQuery, roleFilter, planFilter, statusFilter], function () { refetchData(); }); var fetchUsers = function fetchUsers(ctx, callback) { _store__WEBPACK_IMPORTED_MODULE_1__["default"].dispatch('app-user/fetchUsers', { q: searchQuery.value, perPage: perPage.value, page: currentPage.value, sortBy: sortBy.value, sortDesc: isSortDirDesc.value, role: roleFilter.value, plan: planFilter.value, status: statusFilter.value }).then(function (response) { var _response$data = response.data, users = _response$data.users, total = _response$data.total; callback(users); totalUsers.value = total; })["catch"](function () { toast({ component: _core_components_toastification_ToastificationContent_vue__WEBPACK_IMPORTED_MODULE_4__["default"], props: { title: 'Error fetching users list', icon: 'AlertTriangleIcon', variant: 'danger' } }); }); }; // *===============================================---* // *--------- UI ---------------------------------------* // *===============================================---* var resolveUserRoleVariant = function resolveUserRoleVariant(role) { if (role === 'subscriber') return 'primary'; if (role === 'author') return 'warning'; if (role === 'maintainer') return 'success'; if (role === 'editor') return 'info'; if (role === 'admin') return 'danger'; return 'primary'; }; var resolveUserRoleIcon = function resolveUserRoleIcon(role) { if (role === 'subscriber') return 'UserIcon'; if (role === 'author') return 'SettingsIcon'; if (role === 'maintainer') return 'DatabaseIcon'; if (role === 'editor') return 'Edit2Icon'; if (role === 'admin') return 'ServerIcon'; return 'UserIcon'; }; var resolveUserStatusVariant = function resolveUserStatusVariant(status) { if (status === 'pending') return 'warning'; if (status === 'active') return 'success'; if (status === 'inactive') return 'secondary'; return 'primary'; }; return { fetchUsers: fetchUsers, tableColumns: tableColumns, perPage: perPage, currentPage: currentPage, totalUsers: totalUsers, dataMeta: dataMeta, perPageOptions: perPageOptions, searchQuery: searchQuery, sortBy: sortBy, isSortDirDesc: isSortDirDesc, refUserListTable: refUserListTable, resolveUserRoleVariant: resolveUserRoleVariant, resolveUserRoleIcon: resolveUserRoleIcon, resolveUserStatusVariant: resolveUserStatusVariant, refetchData: refetchData, // Extra Filters roleFilter: roleFilter, planFilter: planFilter, statusFilter: statusFilter }; } /***/ }), /***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=script&lang=js&": /*!*****************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=script&lang=js& ***! \*****************************************************************************************************************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bootstrap-vue */ "./frontend/node_modules/bootstrap-vue/esm/index.js"); // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ __webpack_exports__["default"] = ({ components: { BAvatar: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BAvatar"] }, props: { variant: { type: String, "default": 'primary' }, icon: { type: String, "default": null }, title: { type: String, "default": null }, text: { type: String, "default": null }, hideClose: { type: Boolean, "default": false } } }); /***/ }), /***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=script&lang=js&": /*!**************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=script&lang=js& ***! \**************************************************************************************************************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bootstrap-vue */ "./frontend/node_modules/bootstrap-vue/esm/index.js"); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js"); /* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var vee_validate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! vee-validate */ "./frontend/node_modules/vee-validate/dist/vee-validate.esm.js"); /* harmony import */ var _vue_composition_api__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @vue/composition-api */ "./frontend/node_modules/@vue/composition-api/dist/vue-composition-api.esm.js"); /* harmony import */ var _validations__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @validations */ "./frontend/src/@core/utils/validations/validations.js"); /* harmony import */ var _core_comp_functions_forms_form_validation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @core/comp-functions/forms/form-validation */ "./frontend/src/@core/comp-functions/forms/form-validation.js"); /* harmony import */ var vue_ripple_directive__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! vue-ripple-directive */ "./frontend/node_modules/vue-ripple-directive/src/ripple.js"); /* harmony import */ var vue_select__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! vue-select */ "./frontend/node_modules/vue-select/dist/vue-select.js"); /* harmony import */ var vue_select__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(vue_select__WEBPACK_IMPORTED_MODULE_7__); /* harmony import */ var _fake_db_data_other_countries__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/@fake-db/data/other/countries */ "./frontend/src/@fake-db/data/other/countries.js"); /* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/store */ "./frontend/src/store/index.js"); /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! axios */ "./frontend/node_modules/axios/index.js"); /* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_10__); /* harmony import */ var _router_routes_apps__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/router/routes/apps */ "./frontend/src/router/routes/apps.js"); // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ __webpack_exports__["default"] = ({ components: { BSidebar: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BSidebar"], BModal: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BModal"], BAlert: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BAlert"], BCardText: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BCardText"], BForm: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BForm"], axios: axios__WEBPACK_IMPORTED_MODULE_10___default.a, BFormGroup: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BFormGroup"], BFormInput: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BFormInput"], BFormInvalidFeedback: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BFormInvalidFeedback"], BButton: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["BButton"], vSelect: vue_select__WEBPACK_IMPORTED_MODULE_7___default.a, VBModal: bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["VBModal"], // Form Validation ValidationProvider: vee_validate__WEBPACK_IMPORTED_MODULE_2__["ValidationProvider"], ValidationObserver: vee_validate__WEBPACK_IMPORTED_MODULE_2__["ValidationObserver"] }, directives: { 'b-modal': bootstrap_vue__WEBPACK_IMPORTED_MODULE_0__["VBModal"], Ripple: vue_ripple_directive__WEBPACK_IMPORTED_MODULE_6__["default"] }, // directives: { // Ripple, // }, model: { prop: 'isAddNewUserSidebarActive', event: 'update:is-add-new-user-sidebar-active' }, props: { isAddNewUserSidebarActive: { type: Boolean, required: true }, roleOptions: { type: Array, required: true }, planOptions: { type: Array, required: true } }, data: function data() { return { vinnumberdetails: false, //showModal: false, required: _validations__WEBPACK_IMPORTED_MODULE_4__["required"], alphaNum: _validations__WEBPACK_IMPORTED_MODULE_4__["alphaNum"], email: _validations__WEBPACK_IMPORTED_MODULE_4__["email"], countries: _fake_db_data_other_countries__WEBPACK_IMPORTED_MODULE_8__["default"], customers: [{ value: 1, title: 'Abdul sSalam' }, { title: 'Frank' }, { title: 'Ademola' }, { title: 'Adeolu' }], //option: [{ title: 'Square'}, { title: 'Rectangle' }, { title: 'Rombo' }, { title: 'Romboid' }], option: [], customerinfo: { first_name: "", last_name: "", email: "", phone: "", gender: "", address: "", customer_type: "" }, customergroupdropdownlist: [], customerswithcompany: [], customergroups: [], selected: '', modal: true, isActive: false, isVisible: false }; }, setup: function setup(props, _ref) { var emit = _ref.emit; var blankUserData = { firstNam: '', lastName: '', username: '', email: '', role: null, currentPlan: null, company: '', country: '', contact: '' }; var userData = Object(_vue_composition_api__WEBPACK_IMPORTED_MODULE_3__["ref"])(JSON.parse(JSON.stringify(blankUserData))); var resetuserData = function resetuserData() { userData.value = JSON.parse(JSON.stringify(blankUserData)); }; var onSubmit = function onSubmit() {// let currentObj = this; // console.log(userData.value.vin_number); // // axios.post('http://koboautos.com/twic-terminal/connect/api/create_inspections?vin_number=' + userData.value.vin_number+'&driver_name=' + userData.value.driver_name+'&company_name=' + userData.value.companyName+'&customer=Abdul sSalam') // // .then(response => { // // // this.laravelData = response.data.Inspection; // // console.log(response); // // gotoviewpage(response.key); // // }); // //router.push("/inventory/list/1"); // //router.stateService.go('inventory/list/1'); // // isAddNewUserSidebarActive = false; // // router.push('terminal'); // currentObj.router.push({ path : '/terminal' }); }; var _formValidation = Object(_core_comp_functions_forms_form_validation__WEBPACK_IMPORTED_MODULE_5__["default"])(resetuserData), refFormObserver = _formValidation.refFormObserver, getValidationState = _formValidation.getValidationState, resetForm = _formValidation.resetForm; return { userData: userData, onSubmit: onSubmit, refFormObserver: refFormObserver, getValidationState: getValidationState, resetForm: resetForm }; }, mounted: function mounted() { this.allcustomers(); this.allcompanies(); this.allcustomersgroups(); }, methods: { // showModal() { // let element = this.$refs.modal.$el // $(element).modal('show') // }, allcustomersgroups: function allcustomersgroups(e) { var _this = this; axios__WEBPACK_IMPORTED_MODULE_10___default.a.post('http://koboautos.com/twic-terminal/connect/api/create_group').then(function (response) { // console.log(response); _this.customergroups = response.data.customergroups; }); }, showModal: function showModal() { // document.getElementById('modal').classList.add('is-active') this.isActive = true; this.isVisible = true; }, closeModal: function closeModal() { // document.getElementById('modal').classList.remove('is-active') this.isActive = false; this.isVisible = false; }, formSubmit: function formSubmit(e) { e.preventDefault(); var currentObj = this; axios__WEBPACK_IMPORTED_MODULE_10___default()({ method: 'post', url: 'http://koboautos.com/twic-terminal/connect/api/create_inspections?vin_number=' + this.userData.vin_number + '&driver_name=' + this.userData.driver_name + '&company_name=' + this.userData.companyName + '&customer=' + this.userData.customerName.value }).then(function (response) { console.log(response); if (response.status == 200) { currentObj.$router.push({ path: '/inventory/view/' + response.data.key }); } })["catch"](function (response) { if (response.status == 422) { this.errors = response.data.errors; return; } if (response.status == 500) { flash({ 'error': 'Server Error' }); } }); }, customerformSubmit: function customerformSubmit(e) { e.preventDefault(); var currentObj = this; axios__WEBPACK_IMPORTED_MODULE_10___default()({ method: 'post', url: 'http://koboautos.com/twic-terminal/connect/api/create_customer?first_name=' + this.userData.first_name + '&last_name=' + this.userData.last_name + '&email=' + this.userData.email + '&phone=' + this.userData.contact + '&gender=' + this.userData.gender + '&customer_type=' + this.userData.role.id + '&address=' + this.userData.address }).then(function (response) { console.log(response); if (response.status == 200) { currentObj.$emit('hide'); // console.log(response.data.value); // console.log(response.data.title); //this.customerswithcompany.push(response.data.newcustomer); //this.$root.$on("bv::close::modal", "modal-1"); //$('#modal-1').modal('hide'); //this.$refs.Close.click(); // this.$root.$on('bv::modal::hide', (bvEvent, modalId) => { // console.log('Modal is about to be shown', bvEvent, modalId) // }) //currentObj.$router.push({ path : '/inventory/view/'+response.data.key }); //location.reload(); } })["catch"](function (response) { if (response.status == 422) { this.errors = response.data.errors; return; } if (response.status == 500) { flash({ 'error': 'Server Error' }); } }); }, // Our method to GET results from a Laravel endpoint vindecorder: function vindecorder(e) { var _this2 = this; var vin_number = e.target.value; axios__WEBPACK_IMPORTED_MODULE_10___default.a.post('https://shipafrika.com/api/getcrossdata/decodevin.php?vin=' + vin_number).then(function (response) { _this2.userData.year_make_model = response.data.model_year + ' | ' + response.data.make + ' | ' + response.data.model; }); // axios.post('http://koboautos.com/twic-terminal/scrapping/getcrossdata/decodevin.php?vin='+vin_number) // .then(response => { // this.userData.year_make_model = response.data.model_year+' | '+ response.data.make+' | '+ response.data.model; // }); }, allcustomers: function allcustomers(e) { var _this3 = this; axios__WEBPACK_IMPORTED_MODULE_10___default.a.post('http://koboautos.com/twic-terminal/connect/api/customerwithcompany').then(function (response) { _this3.customerswithcompany = response.data.customers; }); }, allcompanies: function allcompanies(e) { var _this4 = this; axios__WEBPACK_IMPORTED_MODULE_10___default.a.post('http://koboautos.com/twic-terminal/connect/api/all-companies').then(function (response) { _this4.option = response.data.companies; }); }, gotoviewpage: function gotoviewpage(id) { this.$router.push("/inventory/list/1"); } }, watch: { 'userData.customerName': function userDataCustomerName(val, oldval) { console.log(val.value); if (val.value == 'add') { this.$root.$emit("bv::show::modal", "modal-1"); } } } }); /***/ }), /***/ "./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true&": /*!******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--7-2!./node_modules/sass-loader/dist/cjs.js??ref--7-3!./node_modules/sass-loader/dist/cjs.js??ref--11-0!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true& ***! \******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(/*! ../../../../../node_modules/css-loader/lib/css-base.js */ "./node_modules/css-loader/lib/css-base.js")(false); // imports // module exports.push([module.i, ".toastification-close-icon[data-v-2fedfe59],\n.toastification-title[data-v-2fedfe59] {\n line-height: 26px;\n}\n.toastification-title[data-v-2fedfe59] {\n color: inherit;\n}", ""]); // exports /***/ }), /***/ "./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=style&index=0&lang=scss&": /*!***************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--7-2!./node_modules/sass-loader/dist/cjs.js??ref--7-3!./node_modules/sass-loader/dist/cjs.js??ref--11-0!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=style&index=0&lang=scss& ***! \***************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(/*! ../../../../../node_modules/css-loader/lib/css-base.js */ "./node_modules/css-loader/lib/css-base.js")(false); // imports // module exports.push([module.i, ".v-select {\n position: relative;\n font-family: inherit;\n}\n.v-select,\n.v-select * {\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n}\n\n/* KeyFrames */\n@-webkit-keyframes vSelectSpinner-ltr {\n0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n}\n100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n}\n}\n@-webkit-keyframes vSelectSpinner-rtl {\n0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n}\n100% {\n -webkit-transform: rotate(-360deg);\n transform: rotate(-360deg);\n}\n}\n@keyframes vSelectSpinner-ltr {\n0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n}\n100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n}\n}\n@keyframes vSelectSpinner-rtl {\n0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n}\n100% {\n -webkit-transform: rotate(-360deg);\n transform: rotate(-360deg);\n}\n}\n/* Dropdown Default Transition */\n.vs__fade-enter-active,\n.vs__fade-leave-active {\n pointer-events: none;\n -webkit-transition: opacity 0.15s cubic-bezier(1, 0.5, 0.8, 1);\n transition: opacity 0.15s cubic-bezier(1, 0.5, 0.8, 1);\n}\n[dir] .vs__fade-enter-active, [dir] .vs__fade-leave-active {\n -webkit-transition: opacity 0.15s cubic-bezier(1, 0.5, 0.8, 1);\n}\n.vs__fade-enter,\n.vs__fade-leave-to {\n opacity: 0;\n}\n\n/** Component States */\n/*\n * Disabled\n *\n * When the component is disabled, all interaction\n * should be prevented. Here we modify the bg color,\n * and change the cursor displayed on the interactive\n * components.\n */\n[dir] .vs--disabled .vs__dropdown-toggle, [dir] .vs--disabled .vs__clear, [dir] .vs--disabled .vs__search, [dir] .vs--disabled .vs__selected, [dir] .vs--disabled .vs__open-indicator {\n cursor: not-allowed;\n background-color: #f8f8f8;\n}\n\n/*\n * RTL - Right to Left Support\n *\n * Because we're using a flexbox layout, the `dir=\"rtl\"`\n * HTML attribute does most of the work for us by\n * rearranging the child elements visually.\n */\n.v-select[dir=rtl] .vs__actions {\n padding: 0 3px 0 6px;\n}\n.v-select[dir=rtl] .vs__clear {\n margin-left: 6px;\n margin-right: 0;\n}\n.v-select[dir=rtl] .vs__deselect {\n margin-left: 0;\n margin-right: 2px;\n}\n.v-select[dir=rtl] .vs__dropdown-menu {\n text-align: right;\n}\n\n/**\n Dropdown Toggle\n\n The dropdown toggle is the primary wrapper of the component. It\n has two direct descendants: .vs__selected-options, and .vs__actions.\n\n .vs__selected-options holds the .vs__selected's as well as the\n main search input.\n\n .vs__actions holds the clear button and dropdown toggle.\n */\n.vs__dropdown-toggle {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n white-space: normal;\n}\n[dir] .vs__dropdown-toggle {\n padding: 0 0 4px 0;\n background: none;\n border: 1px solid #d8d6de;\n border-radius: 0.357rem;\n}\n.vs__selected-options {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -ms-flex-preferred-size: 100%;\n flex-basis: 100%;\n -webkit-box-flex: 1;\n -ms-flex-positive: 1;\n flex-grow: 1;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n position: relative;\n}\n[dir] .vs__selected-options {\n padding: 0 2px;\n}\n.vs__actions {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n}\n[dir=ltr] .vs__actions {\n padding: 4px 6px 0 3px;\n}\n[dir=rtl] .vs__actions {\n padding: 4px 3px 0 6px;\n}\n\n/* Dropdown Toggle States */\n[dir] .vs--searchable .vs__dropdown-toggle {\n cursor: text;\n}\n[dir] .vs--unsearchable .vs__dropdown-toggle {\n cursor: pointer;\n}\n[dir] .vs--open .vs__dropdown-toggle {\n border-bottom-color: transparent;\n}\n[dir=ltr] .vs--open .vs__dropdown-toggle {\n border-bottom-left-radius: 0;\n border-bottom-right-radius: 0;\n}\n[dir=rtl] .vs--open .vs__dropdown-toggle {\n border-bottom-right-radius: 0;\n border-bottom-left-radius: 0;\n}\n.vs__open-indicator {\n fill: rgba(60, 60, 60, 0.5);\n -webkit-transform: scale(1);\n transition: -webkit-transform 150ms cubic-bezier(1, -0.115, 0.975, 0.855);\n -webkit-transition: -webkit-transform 150ms cubic-bezier(1, -0.115, 0.975, 0.855);\n transition: transform 150ms cubic-bezier(1, -0.115, 0.975, 0.855);\n transition: transform 150ms cubic-bezier(1, -0.115, 0.975, 0.855), -webkit-transform 150ms cubic-bezier(1, -0.115, 0.975, 0.855);\n -webkit-transition-timing-function: cubic-bezier(1, -0.115, 0.975, 0.855);\n}\n[dir] .vs__open-indicator {\n -webkit-transform: scale(1);\n transform: scale(1);\n -webkit-transition: -webkit-transform 150ms cubic-bezier(1, -0.115, 0.975, 0.855);\n -webkit-transition-timing-function: cubic-bezier(1, -0.115, 0.975, 0.855);\n transition-timing-function: cubic-bezier(1, -0.115, 0.975, 0.855);\n}\n[dir=ltr] .vs--open .vs__open-indicator {\n -webkit-transform: rotate(180deg) scale(1);\n transform: rotate(180deg) scale(1);\n}\n[dir=rtl] .vs--open .vs__open-indicator {\n -webkit-transform: rotate(-180deg) scale(1);\n transform: rotate(-180deg) scale(1);\n}\n.vs--loading .vs__open-indicator {\n opacity: 0;\n}\n\n/* Clear Button */\n.vs__clear {\n fill: rgba(60, 60, 60, 0.5);\n}\n[dir] .vs__clear {\n padding: 0;\n border: 0;\n background-color: transparent;\n cursor: pointer;\n}\n[dir=ltr] .vs__clear {\n margin-right: 8px;\n}\n[dir=rtl] .vs__clear {\n margin-left: 8px;\n}\n\n/* Dropdown Menu */\n.vs__dropdown-menu {\n display: block;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n position: absolute;\n top: calc(100% - 1px);\n z-index: 1000;\n width: 100%;\n max-height: 350px;\n min-width: 160px;\n overflow-y: auto;\n -webkit-box-shadow: 0px 4px 25px 0px rgba(0, 0, 0, 0.1);\n list-style: none;\n}\n[dir] .vs__dropdown-menu {\n padding: 5px 0;\n margin: 0;\n -webkit-box-shadow: 0px 4px 25px 0px rgba(0, 0, 0, 0.1);\n box-shadow: 0px 4px 25px 0px rgba(0, 0, 0, 0.1);\n border: 1px solid #d8d6de;\n border-top-style: none;\n border-radius: 0 0 0.357rem 0.357rem;\n background: #fff;\n}\n[dir=ltr] .vs__dropdown-menu {\n left: 0;\n text-align: left;\n}\n[dir=rtl] .vs__dropdown-menu {\n right: 0;\n text-align: right;\n}\n[dir] .vs__no-options {\n text-align: center;\n}\n\n/* List Items */\n.vs__dropdown-option {\n line-height: 1.42857143;\n /* Normalize line height */\n display: block;\n color: #333;\n /* Overrides most CSS frameworks */\n white-space: nowrap;\n}\n[dir] .vs__dropdown-option {\n padding: 3px 20px;\n clear: both;\n}\n[dir] .vs__dropdown-option:hover {\n cursor: pointer;\n}\n.vs__dropdown-option--highlight {\n color: #7367f0 !important;\n}\n[dir] .vs__dropdown-option--highlight {\n background: rgba(115, 103, 240, 0.12);\n}\n.vs__dropdown-option--disabled {\n color: rgba(60, 60, 60, 0.5);\n}\n[dir] .vs__dropdown-option--disabled {\n background: inherit;\n}\n[dir] .vs__dropdown-option--disabled:hover {\n cursor: inherit;\n}\n\n/* Selected Tags */\n.vs__selected {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n color: #333;\n line-height: 1.8;\n z-index: 0;\n}\n[dir] .vs__selected {\n background-color: #7367f0;\n border: 0 solid rgba(60, 60, 60, 0.26);\n border-radius: 0.357rem;\n margin: 4px 2px 0px 2px;\n padding: 0 0.25em;\n}\n.vs__deselect {\n display: -webkit-inline-box;\n display: -ms-inline-flexbox;\n display: inline-flex;\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n fill: rgba(60, 60, 60, 0.5);\n}\n[dir] .vs__deselect {\n padding: 0;\n border: 0;\n cursor: pointer;\n background: none;\n text-shadow: 0 1px 0 #fff;\n}\n[dir=ltr] .vs__deselect {\n margin-left: 4px;\n}\n[dir=rtl] .vs__deselect {\n margin-right: 4px;\n}\n\n/* States */\n[dir] .vs--single .vs__selected {\n background-color: transparent;\n border-color: transparent;\n}\n.vs--single.vs--open .vs__selected {\n position: absolute;\n opacity: 0.4;\n}\n.vs--single.vs--searching .vs__selected {\n display: none;\n}\n\n/* Search Input */\n/**\n * Super weird bug... If this declaration is grouped\n * below, the cancel button will still appear in chrome.\n * If it's up here on it's own, it'll hide it.\n */\n.vs__search::-webkit-search-cancel-button {\n display: none;\n}\n.vs__search::-webkit-search-decoration,\n.vs__search::-webkit-search-results-button,\n.vs__search::-webkit-search-results-decoration,\n.vs__search::-ms-clear {\n display: none;\n}\n.vs__search,\n.vs__search:focus {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n line-height: 1.8;\n font-size: 1em;\n outline: none;\n -webkit-box-shadow: none;\n width: 0;\n max-width: 100%;\n -webkit-box-flex: 1;\n -ms-flex-positive: 1;\n flex-grow: 1;\n z-index: 1;\n}\n[dir] .vs__search, [dir] .vs__search:focus {\n border: 1px solid transparent;\n margin: 4px 0 0 0;\n padding: 0 7px;\n background: none;\n -webkit-box-shadow: none;\n box-shadow: none;\n}\n[dir=ltr] .vs__search, [dir=ltr] .vs__search:focus {\n border-left: none;\n}\n[dir=rtl] .vs__search, [dir=rtl] .vs__search:focus {\n border-right: none;\n}\n.vs__search::-webkit-input-placeholder {\n color: #6e6b7b;\n}\n.vs__search::-moz-placeholder {\n color: #6e6b7b;\n}\n.vs__search:-ms-input-placeholder {\n color: #6e6b7b;\n}\n.vs__search::-ms-input-placeholder {\n color: #6e6b7b;\n}\n.vs__search::placeholder {\n color: #6e6b7b;\n}\n\n/**\n States\n */\n.vs--unsearchable .vs__search {\n opacity: 1;\n}\n[dir] .vs--unsearchable:not(.vs--disabled) .vs__search:hover {\n cursor: pointer;\n}\n.vs--single.vs--searching:not(.vs--open):not(.vs--loading) .vs__search {\n opacity: 0.2;\n}\n\n/* Loading Spinner */\n.vs__spinner {\n -ms-flex-item-align: center;\n align-self: center;\n opacity: 0;\n font-size: 5px;\n text-indent: -9999em;\n overflow: hidden;\n -webkit-transform: translateZ(0);\n -webkit-transition: opacity 0.1s;\n transition: opacity 0.1s;\n}\n[dir] .vs__spinner {\n border-top: 0.9em solid rgba(100, 100, 100, 0.1);\n border-bottom: 0.9em solid rgba(100, 100, 100, 0.1);\n -webkit-transform: translateZ(0);\n transform: translateZ(0);\n -webkit-transition: opacity 0.1s;\n}\n[dir=ltr] .vs__spinner {\n border-right: 0.9em solid rgba(100, 100, 100, 0.1);\n border-left: 0.9em solid rgba(60, 60, 60, 0.45);\n -webkit-animation: vSelectSpinner-ltr 1.1s infinite linear;\n animation: vSelectSpinner-ltr 1.1s infinite linear;\n}\n[dir=rtl] .vs__spinner {\n border-left: 0.9em solid rgba(100, 100, 100, 0.1);\n border-right: 0.9em solid rgba(60, 60, 60, 0.45);\n -webkit-animation: vSelectSpinner-rtl 1.1s infinite linear;\n animation: vSelectSpinner-rtl 1.1s infinite linear;\n}\n.vs__spinner,\n.vs__spinner:after {\n width: 5em;\n height: 5em;\n}\n[dir] .vs__spinner, [dir] .vs__spinner:after {\n border-radius: 50%;\n}\n\n/* Loading Spinner States */\n.vs--loading .vs__spinner {\n opacity: 1;\n}\n.vs__open-indicator {\n fill: none;\n}\n[dir] .vs__open-indicator {\n margin-top: 0.15rem;\n}\n.vs__dropdown-toggle {\n -webkit-transition: all 0.25s ease-in-out;\n transition: all 0.25s ease-in-out;\n}\n[dir] .vs__dropdown-toggle {\n padding: 0.59px 0 4px 0;\n -webkit-transition: all 0.25s ease-in-out;\n}\n[dir=ltr] .vs--single .vs__dropdown-toggle {\n padding-left: 6px;\n}\n[dir=rtl] .vs--single .vs__dropdown-toggle {\n padding-right: 6px;\n}\n.vs__dropdown-option--disabled {\n opacity: 0.5;\n}\n[dir] .vs__dropdown-option--disabled.vs__dropdown-option--selected {\n background: #7367f0 !important;\n}\n.vs__dropdown-option {\n color: #6e6b7b;\n}\n[dir] .vs__dropdown-option, [dir] .vs__no-options {\n padding: 7px 20px;\n}\n.vs__dropdown-option--selected {\n background-color: #7367f0;\n color: #fff;\n position: relative;\n}\n.vs__dropdown-option--selected::after {\n content: \"\";\n height: 1.1rem;\n width: 1.1rem;\n display: inline-block;\n position: absolute;\n top: 50%;\n -webkit-transform: translateY(-50%);\n transform: translateY(-50%);\n right: 20px;\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23fff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-check'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E\");\n background-repeat: no-repeat;\n background-position: center;\n background-size: 1.1rem;\n}\n[dir=rtl] .vs__dropdown-option--selected::after {\n left: 20px;\n right: unset;\n}\n.vs__dropdown-option--selected.vs__dropdown-option--highlight {\n color: #fff !important;\n background-color: #7367f0 !important;\n}\n.vs__clear svg {\n color: #6e6b7b;\n}\n.vs__selected {\n color: #fff;\n}\n.v-select.vs--single .vs__selected {\n color: #6e6b7b;\n transition: -webkit-transform 0.2s ease;\n -webkit-transition: -webkit-transform 0.2s ease;\n transition: transform 0.2s ease;\n transition: transform 0.2s ease, -webkit-transform 0.2s ease;\n}\n[dir] .v-select.vs--single .vs__selected {\n margin-top: 5px;\n -webkit-transition: -webkit-transform 0.2s ease;\n}\n[dir=ltr] .v-select.vs--single .vs__selected input {\n padding-left: 0;\n}\n[dir=rtl] .v-select.vs--single .vs__selected input {\n padding-right: 0;\n}\n[dir=ltr] .vs--single.vs--open .vs__selected {\n -webkit-transform: translateX(5px);\n transform: translateX(5px);\n}\n[dir=rtl] .vs--single.vs--open .vs__selected {\n -webkit-transform: translateX(-5px);\n transform: translateX(-5px);\n}\n.vs__selected .vs__deselect {\n color: inherit;\n}\n.v-select:not(.vs--single) .vs__selected {\n font-size: 0.9rem;\n}\n[dir] .v-select:not(.vs--single) .vs__selected {\n border-radius: 3px;\n padding: 0 0.6em;\n}\n[dir=ltr] .v-select:not(.vs--single) .vs__selected {\n margin: 5px 2px 2px 5px;\n}\n[dir=rtl] .v-select:not(.vs--single) .vs__selected {\n margin: 5px 5px 2px 2px;\n}\n.v-select:not(.vs--single) .vs__deselect svg {\n -webkit-transform: scale(0.8);\n vertical-align: text-top;\n}\n[dir] .v-select:not(.vs--single) .vs__deselect svg {\n -webkit-transform: scale(0.8);\n transform: scale(0.8);\n}\n.vs__dropdown-menu {\n top: calc(100% + 1rem);\n}\n[dir] .vs__dropdown-menu {\n border: none;\n border-radius: 6px;\n padding: 0;\n}\n.vs--open .vs__dropdown-toggle {\n -webkit-box-shadow: 0 3px 10px 0 rgba(34, 41, 47, 0.1);\n}\n[dir] .vs--open .vs__dropdown-toggle {\n border-color: #7367f0;\n border-bottom-color: #7367f0;\n -webkit-box-shadow: 0 3px 10px 0 rgba(34, 41, 47, 0.1);\n box-shadow: 0 3px 10px 0 rgba(34, 41, 47, 0.1);\n}\n[dir=ltr] .vs--open .vs__dropdown-toggle {\n border-bottom-left-radius: 0.357rem;\n border-bottom-right-radius: 0.357rem;\n}\n[dir=rtl] .vs--open .vs__dropdown-toggle {\n border-bottom-right-radius: 0.357rem;\n border-bottom-left-radius: 0.357rem;\n}\n.select-size-lg .vs__selected {\n font-size: 1rem !important;\n}\n[dir] .select-size-lg.vs--single.vs--open .vs__selected {\n margin-top: 6px;\n}\n.select-size-lg .vs__dropdown-toggle,\n.select-size-lg .vs__selected {\n font-size: 1.25rem;\n}\n[dir] .select-size-lg .vs__dropdown-toggle {\n padding: 5px;\n}\n[dir] .select-size-lg .vs__dropdown-toggle input {\n margin-top: 0;\n}\n.select-size-lg .vs__deselect svg {\n -webkit-transform: scale(1) !important;\n vertical-align: middle !important;\n}\n[dir] .select-size-lg .vs__deselect svg {\n -webkit-transform: scale(1) !important;\n transform: scale(1) !important;\n}\n[dir] .select-size-sm .vs__dropdown-toggle {\n padding-bottom: 0;\n padding: 1px;\n}\n[dir] .select-size-sm.vs--single .vs__dropdown-toggle {\n padding: 2px;\n}\n.select-size-sm .vs__dropdown-toggle,\n.select-size-sm .vs__selected {\n font-size: 0.9rem;\n}\n[dir] .select-size-sm .vs__actions {\n padding-top: 2px;\n padding-bottom: 2px;\n}\n.select-size-sm .vs__deselect svg {\n vertical-align: middle !important;\n}\n[dir] .select-size-sm .vs__search {\n margin-top: 0;\n}\n.select-size-sm.v-select .vs__selected {\n font-size: 0.75rem;\n}\n[dir] .select-size-sm.v-select .vs__selected {\n padding: 0 0.3rem;\n}\n[dir] .select-size-sm.v-select:not(.vs--single) .vs__selected {\n margin: 4px 5px;\n}\n[dir] .select-size-sm.v-select.vs--single .vs__selected {\n margin-top: 1px;\n}\n[dir] .select-size-sm.vs--single.vs--open .vs__selected {\n margin-top: 4px;\n}\n.dark-layout .vs__dropdown-toggle {\n color: #b4b7bd;\n}\n[dir] .dark-layout .vs__dropdown-toggle {\n background: #283046;\n border-color: #404656;\n}\n.dark-layout .vs__selected-options input {\n color: #b4b7bd;\n}\n.dark-layout .vs__selected-options input::-webkit-input-placeholder {\n color: #676d7d;\n}\n.dark-layout .vs__selected-options input::-moz-placeholder {\n color: #676d7d;\n}\n.dark-layout .vs__selected-options input:-ms-input-placeholder {\n color: #676d7d;\n}\n.dark-layout .vs__selected-options input::-ms-input-placeholder {\n color: #676d7d;\n}\n.dark-layout .vs__selected-options input::placeholder {\n color: #676d7d;\n}\n.dark-layout .vs__actions svg {\n fill: #404656;\n}\n[dir] .dark-layout .vs__dropdown-menu {\n background: #283046;\n}\n.dark-layout .vs__dropdown-menu li {\n color: #b4b7bd;\n}\n.dark-layout .v-select:not(.vs--single) .vs__selected {\n color: #7367f0;\n}\n[dir] .dark-layout .v-select:not(.vs--single) .vs__selected {\n background-color: rgba(115, 103, 240, 0.12);\n}\n.dark-layout .v-select.vs--single .vs__selected {\n color: #b4b7bd !important;\n}\n.dark-layout .vs--disabled .vs__dropdown-toggle,\n.dark-layout .vs--disabled .vs__clear,\n.dark-layout .vs--disabled .vs__search,\n.dark-layout .vs--disabled .vs__selected,\n.dark-layout .vs--disabled .vs__open-indicator {\n opacity: 0.5;\n}\n[dir] .dark-layout .vs--disabled .vs__dropdown-toggle, [dir] .dark-layout .vs--disabled .vs__clear, [dir] .dark-layout .vs--disabled .vs__search, [dir] .dark-layout .vs--disabled .vs__selected, [dir] .dark-layout .vs--disabled .vs__open-indicator {\n background-color: #283046;\n}\n#add-new-user-sidebar .vs__dropdown-menu {\n max-height: 200px !important;\n}", ""]); // exports /***/ }), /***/ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true&": /*!**********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/style-loader!./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--7-2!./node_modules/sass-loader/dist/cjs.js??ref--7-3!./node_modules/sass-loader/dist/cjs.js??ref--11-0!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true& ***! \**********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var content = __webpack_require__(/*! !../../../../../node_modules/css-loader!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/src??ref--7-2!../../../../../node_modules/sass-loader/dist/cjs.js??ref--7-3!../../../../../node_modules/sass-loader/dist/cjs.js??ref--11-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true& */ "./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=style&index=0&id=2fedfe59&lang=scss&scoped=true&"); if(typeof content === 'string') content = [[module.i, content, '']]; var transform; var insertInto; var options = {"hmr":true} options.transform = transform options.insertInto = undefined; var update = __webpack_require__(/*! ../../../../../node_modules/style-loader/lib/addStyles.js */ "./node_modules/style-loader/lib/addStyles.js")(content, options); if(content.locals) module.exports = content.locals; if(false) {} /***/ }), /***/ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=style&index=0&lang=scss&": /*!*******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/style-loader!./node_modules/css-loader!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--7-2!./node_modules/sass-loader/dist/cjs.js??ref--7-3!./node_modules/sass-loader/dist/cjs.js??ref--11-0!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=style&index=0&lang=scss& ***! \*******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var content = __webpack_require__(/*! !../../../../../node_modules/css-loader!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/src??ref--7-2!../../../../../node_modules/sass-loader/dist/cjs.js??ref--7-3!../../../../../node_modules/sass-loader/dist/cjs.js??ref--11-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./InventoryListAddNew.vue?vue&type=style&index=0&lang=scss& */ "./node_modules/css-loader/index.js!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=style&index=0&lang=scss&"); if(typeof content === 'string') content = [[module.i, content, '']]; var transform; var insertInto; var options = {"hmr":true} options.transform = transform options.insertInto = undefined; var update = __webpack_require__(/*! ../../../../../node_modules/style-loader/lib/addStyles.js */ "./node_modules/style-loader/lib/addStyles.js")(content, options); if(content.locals) module.exports = content.locals; if(false) {} /***/ }), /***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=template&id=2fedfe59&scoped=true&": /*!*********************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/@core/components/toastification/ToastificationContent.vue?vue&type=template&id=2fedfe59&scoped=true& ***! \*********************************************************************************************************************************************************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; }); var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c("div", { staticClass: "toastification" }, [ _c( "div", { staticClass: "d-flex align-items-start" }, [ _c( "b-avatar", { staticClass: "mr-75 flex-shrink-0", attrs: { variant: _vm.variant, size: "1.8rem" } }, [_c("feather-icon", { attrs: { icon: _vm.icon, size: "15" } })], 1 ), _vm._v(" "), _c("div", { staticClass: "d-flex flex-grow-1" }, [ _c("div", [ _vm.title ? _c("h5", { staticClass: "mb-0 font-weight-bolder toastification-title", class: "text-" + _vm.variant, domProps: { textContent: _vm._s(_vm.title) } }) : _vm._e(), _vm._v(" "), _vm.text ? _c("small", { staticClass: "d-inline-block text-body", domProps: { textContent: _vm._s(_vm.text) } }) : _vm._e() ]), _vm._v(" "), _c( "span", { staticClass: "cursor-pointer toastification-close-icon ml-auto ", on: { click: function($event) { return _vm.$emit("close-toast") } } }, [ !_vm.hideClose ? _c("feather-icon", { staticClass: "text-body", attrs: { icon: "XIcon" } }) : _vm._e() ], 1 ) ]) ], 1 ) ]) } var staticRenderFns = [] render._withStripped = true /***/ }), /***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=template&id=0c1e10d7&": /*!******************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./frontend/src/views/inventory/inventory-list/InventoryListAddNew.vue?vue&type=template&id=0c1e10d7& ***! \******************************************************************************************************************************************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; }); var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c("b-sidebar", { attrs: { id: "add-new-user-sidebar", visible: _vm.isAddNewUserSidebarActive, "bg-variant": "white", "sidebar-class": "sidebar-lg", shadow: "", backdrop: "", "no-header": "", right: "" }, on: { hidden: _vm.resetForm, change: function(val) { return _vm.$emit("update:is-add-new-user-sidebar-active", val) } }, scopedSlots: _vm._u([ { key: "default", fn: function(ref) { var hide = ref.hide return [ _c( "div", { staticClass: "d-flex justify-content-between align-items-center content-sidebar-header px-2 py-1" }, [ _c("h5", { staticClass: "mb-0" }, [ _vm._v("\n Create Inventory\n ") ]), _vm._v(" "), _c("feather-icon", { staticClass: "ml-1 cursor-pointer", attrs: { icon: "XIcon", size: "16" }, on: { click: hide } }) ], 1 ), _vm._v(" "), _c("validation-observer", { ref: "refFormObserver", scopedSlots: _vm._u( [ { key: "default", fn: function(ref) { var handleSubmit = ref.handleSubmit return [ _c( "b-form", { staticClass: "p-2", on: { submit: [ function($event) { $event.preventDefault() return handleSubmit(_vm.onSubmit) }, _vm.formSubmit ], reset: function($event) { $event.preventDefault() return _vm.resetForm($event) } } }, [ _c("validation-provider", { attrs: { name: "Vin Number", rules: "required" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "Vin Number", "label-for": "vin-number" } }, [ _c("b-form-input", { attrs: { id: "full-name", autofocus: "", state: _vm.getValidationState( validationContext ), trim: "", placeholder: "" }, on: { focusout: _vm.vindecorder }, model: { value: _vm.userData.vin_number, callback: function($$v) { _vm.$set( _vm.userData, "vin_number", $$v ) }, expression: "userData.vin_number" } }), _vm._v(" "), _c("b-form-invalid-feedback", [ _vm._v( "\n " + _vm._s( validationContext.errors[0] ) + "\n " ) ]) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c("validation-provider", { attrs: { name: "Year Make Model", rules: "required" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "Year | Make | model", "label-for": "year_make_model" } }, [ _c("b-form-input", { attrs: { id: "year_make_model", autofocus: "", trim: "", placeholder: "", readonly: "readonly" }, model: { value: _vm.userData.year_make_model, callback: function($$v) { _vm.$set( _vm.userData, "year_make_model", $$v ) }, expression: "userData.year_make_model" } }) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c("validation-provider", { attrs: { name: "Driver Name", rules: "required" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "Driver Name", "label-for": "driver-name" } }, [ _c("b-form-input", { attrs: { id: "full-name", autofocus: "", state: _vm.getValidationState( validationContext ), trim: "", placeholder: "" }, model: { value: _vm.userData.driver_name, callback: function($$v) { _vm.$set( _vm.userData, "driver_name", $$v ) }, expression: "userData.driver_name" } }), _vm._v(" "), _c("b-form-invalid-feedback", [ _vm._v( "\n " + _vm._s( validationContext.errors[0] ) + "\n " ) ]) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c("validation-provider", { attrs: { name: "Company Name", rules: "required" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "Company Name", "label-for": "company-name", state: _vm.getValidationState( validationContext ) } }, [ _c("v-select", { attrs: { dir: _vm.$store.state.appConfig .isRTL ? "rtl" : "ltr", label: "title", options: _vm.option }, model: { value: _vm.userData.companyName, callback: function($$v) { _vm.$set( _vm.userData, "companyName", $$v ) }, expression: "userData.companyName" } }), _vm._v(" "), _c( "b-form-invalid-feedback", { attrs: { state: _vm.getValidationState( validationContext ) } }, [ _vm._v( "\n " + _vm._s( validationContext .errors[0] ) + "\n " ) ] ) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c("validation-provider", { attrs: { name: "Customer", rules: "required" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "Customer", "label-for": "customer", state: _vm.getValidationState( validationContext ) } }, [ _c("v-select", { attrs: { dir: _vm.$store.state.appConfig .isRTL ? "rtl" : "ltr", label: "title", options: _vm.customerswithcompany }, model: { value: _vm.userData.customerName, callback: function($$v) { _vm.$set( _vm.userData, "customerName", $$v ) }, expression: "userData.customerName" } }), _vm._v(" "), _c( "b-form-invalid-feedback", { attrs: { state: _vm.getValidationState( validationContext ) } }, [ _vm._v( "\n " + _vm._s( validationContext .errors[0] ) + "\n " ) ] ) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c("div", { staticClass: "form-grou" }, [ _c("label", [_vm._v("Note")]), _vm._v(" "), _c("textarea", { directives: [ { name: "model", rawName: "v-model", value: _vm.userData.note, expression: "userData.note" } ], staticClass: "form-control", domProps: { value: _vm.userData.note }, on: { input: function($event) { if ($event.target.composing) { return } _vm.$set( _vm.userData, "note", $event.target.value ) } } }) ]), _vm._v(" "), _c( "div", { staticClass: "d-flex mt-2" }, [ _c( "b-button", { directives: [ { name: "ripple", rawName: "v-ripple.400", value: "rgba(255, 255, 255, 0.15)", expression: "'rgba(255, 255, 255, 0.15)'", modifiers: { "400": true } } ], staticClass: "mr-2", attrs: { variant: "primary", type: "submit" } }, [_vm._v("\n Submit\n ")] ), _vm._v(" "), _c( "b-button", { directives: [ { name: "ripple", rawName: "v-ripple.400", value: "rgba(186, 191, 199, 0.15)", expression: "'rgba(186, 191, 199, 0.15)'", modifiers: { "400": true } } ], attrs: { type: "button", variant: "outline-secondary" }, on: { click: hide } }, [_vm._v("\n Cancel\n ")] ) ], 1 ) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c( "b-modal", { attrs: { id: "modal-1", title: "Create New Customer", "ok-only": "", "ok-title": "Close" } }, [ _c( "b-card-text", [ _c("validation-observer", { ref: "refFormObserver", scopedSlots: _vm._u( [ { key: "default", fn: function(ref) { var handleSubmit = ref.handleSubmit return [ _c( "b-form", { staticClass: "p-2", on: { submit: [ function($event) { $event.preventDefault() return handleSubmit(_vm.onSubmit) }, _vm.customerformSubmit ], reset: function($event) { $event.preventDefault() return _vm.resetForm($event) } } }, [ _c("validation-provider", { attrs: { name: "First Name", rules: "required" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "First Name", "label-for": "first-name" } }, [ _c("b-form-input", { attrs: { id: "full-name", autofocus: "", state: _vm.getValidationState( validationContext ), trim: "", placeholder: "" }, model: { value: _vm.userData .first_name, callback: function( $$v ) { _vm.$set( _vm.userData, "first_name", $$v ) }, expression: "userData.first_name" } }), _vm._v(" "), _c( "b-form-invalid-feedback", [ _vm._v( "\n " + _vm._s( validationContext .errors[0] ) + "\n " ) ] ) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c("validation-provider", { attrs: { name: "Last Name", rules: "required" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "Last Name", "label-for": "last-name" } }, [ _c("b-form-input", { attrs: { id: "full-name", autofocus: "", state: _vm.getValidationState( validationContext ), trim: "", placeholder: "" }, model: { value: _vm.userData .last_name, callback: function( $$v ) { _vm.$set( _vm.userData, "last_name", $$v ) }, expression: "userData.last_name" } }), _vm._v(" "), _c( "b-form-invalid-feedback", [ _vm._v( "\n " + _vm._s( validationContext .errors[0] ) + "\n " ) ] ) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c("validation-provider", { attrs: { name: "Email", rules: "required|email" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "Email", "label-for": "email" } }, [ _c("b-form-input", { attrs: { id: "email", state: _vm.getValidationState( validationContext ), trim: "" }, model: { value: _vm.userData.email, callback: function( $$v ) { _vm.$set( _vm.userData, "email", $$v ) }, expression: "userData.email" } }), _vm._v(" "), _c( "b-form-invalid-feedback", [ _vm._v( "\n " + _vm._s( validationContext .errors[0] ) + "\n " ) ] ) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c("validation-provider", { attrs: { name: "Phone", rules: "required" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "Phone", "label-for": "phone" } }, [ _c("b-form-input", { attrs: { id: "contact", state: _vm.getValidationState( validationContext ), trim: "" }, model: { value: _vm.userData.contact, callback: function( $$v ) { _vm.$set( _vm.userData, "contact", $$v ) }, expression: "userData.contact" } }), _vm._v(" "), _c( "b-form-invalid-feedback", [ _vm._v( "\n " + _vm._s( validationContext .errors[0] ) + "\n " ) ] ) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c("validation-provider", { attrs: { name: "Gender", rules: "required" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "Gender", "label-for": "gender", state: _vm.getValidationState( validationContext ) } }, [ _c( "select", { directives: [ { name: "model", rawName: "v-model", value: _vm.userData .gender, expression: "userData.gender" } ], staticClass: "form-control vue-select", on: { change: function( $event ) { var $$selectedVal = Array.prototype.filter .call( $event.target .options, function(o) { return o.selected } ) .map(function(o) { var val = "_value" in o ? o._value : o.value return val }) _vm.$set( _vm.userData, "gender", $event.target .multiple ? $$selectedVal : $$selectedVal[0] ) } } }, [ _c( "option", { attrs: { value: "" } }, [_vm._v("Select")] ), _vm._v(" "), _c( "option", { attrs: { value: "Male" } }, [_vm._v("Male")] ), _vm._v(" "), _c( "option", { attrs: { value: "Female" } }, [_vm._v("Female")] ) ] ), _vm._v(" "), _c( "b-form-invalid-feedback", { attrs: { state: _vm.getValidationState( validationContext ) } }, [ _vm._v( "\n " + _vm._s( validationContext .errors[0] ) + "\n " ) ] ) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c("validation-provider", { attrs: { name: "Customer", rules: "required" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "Customer Type", "label-for": "customer", state: _vm.getValidationState( validationContext ) } }, [ _c("v-select", { attrs: { dir: _vm.$store.state .appConfig.isRTL ? "rtl" : "ltr", label: "title", options: _vm.customergroups }, model: { value: _vm.userData.role, callback: function( $$v ) { _vm.$set( _vm.userData, "role", $$v ) }, expression: "userData.role" } }), _vm._v(" "), _c( "b-form-invalid-feedback", { attrs: { state: _vm.getValidationState( validationContext ) } }, [ _vm._v( "\n " + _vm._s( validationContext .errors[0] ) + "\n " ) ] ) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c("validation-provider", { attrs: { name: "Address", rules: "required" }, scopedSlots: _vm._u( [ { key: "default", fn: function(validationContext) { return [ _c( "b-form-group", { attrs: { label: "Address", "label-for": "address" } }, [ _c("b-form-input", { attrs: { id: "contact", state: _vm.getValidationState( validationContext ), trim: "" }, model: { value: _vm.userData.address, callback: function( $$v ) { _vm.$set( _vm.userData, "address", $$v ) }, expression: "userData.address" } }), _vm._v(" "), _c( "b-form-invalid-feedback", [ _vm._v( "\n " + _vm._s( validationContext .errors[0] ) + "\n " ) ] ) ], 1 ) ] } } ], null, true ) }), _vm._v(" "), _c( "div", { staticClass: "d-flex mt-2" }, [ _c( "b-button", { directives: [ { name: "ripple", rawName: "v-ripple.400", value: "rgba(255, 255, 255, 0.15)", expression: "'rgba(255, 255, 255, 0.15)'", modifiers: { "400": true } } ], staticClass: "mr-2", attrs: { variant: "primary", type: "submit" } }, [ _vm._v( "\n Submit\n " ) ] ) ], 1 ) ], 1 ) ] } } ], null, true ) }) ], 1 ) ], 1 ) ] } } ]) }) } var staticRenderFns = [] render._withStripped = true /***/ }) }]);
/* eslint no-undef: "off"*/ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3')) : typeof define === 'function' && define.amd ? define(['exports', 'd3'], factory) : (factory((global.youdrawit = {}),global.d3)); }(this, (function (exports,d3) { 'use strict'; var debounce = function debounce(func, wait, immediate) { var timeout = void 0; return function () { var context = this, args = arguments; var later = function later() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; var ƒ = function ƒ() { var functions = arguments; //convert all string arguments into field accessors for (var i = 0; i < functions.length; i++) { if (typeof functions[i] === "string" || typeof functions[i] === "number") { functions[i] = function (str) { return function (d) { return d[str]; }; }(functions[i]); } } //return composition of functions return function (d) { var i = 0, l = functions.length; while (i++ < l) { d = functions[i - 1].call(this, d); }return d; }; }; var formatValue = function formatValue(val, unit, precision, defaultPrecision) { var data = precision ? Number(val).toFixed(precision) : defaultPrecision !== 0 ? Number(val).toFixed(defaultPrecision) : defaultPrecision === 0 ? Number(val).toFixed() : val; // revert decimal and thousands separator based on country var dataDelimited = numberWithCommas(data); if (getLanguage() === "de") { var temp1 = dataDelimited.replace(/\./g, "whatever"); var temp2 = temp1.replace(/,/g, "."); dataDelimited = temp2.replace(/whatever/g, ","); } else if (getLanguage() === "fr") { var _temp = dataDelimited.replace(/\./g, "whatever"); var _temp2 = _temp.replace(/,/g, " "); dataDelimited = _temp2.replace(/whatever/g, ","); } return dataDelimited + (unit ? " " + unit : ""); }; var numberWithCommas = function numberWithCommas(x) { var parts = x.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); return parts.join("."); }; var clamp = function clamp(a, b, c) { return Math.max(a, Math.min(b, c)); }; function getRandom(min, max) { return Math.random() * (max - min) + min; } var yourData = "yourData"; var resultShown = "resultShown"; var completed = "completed"; var score = "score"; var predictionDiff = "predictionDiff"; var prediction = "prediction"; var truth = "truth"; function compareGuess(truth$$1, guess, graphMaxY, graphMinY) { var maxDiff = 0; var predDiff = 0; truth$$1.forEach(function (ele, i) { maxDiff += Math.max(graphMaxY - ele.value, ele.value - graphMinY); predDiff += Math.abs(ele.value - guess[i].value); }); return { maxDiff: maxDiff, predDiff: predDiff }; } function getScore(key, truth$$1, state, graphMaxY, graphMinY, resultSection, scoreTitle, scoreButtonText, scoreButtonTooltip, scoreHtml) { var myScore = 0; var guess = state.getResult(key, yourData); var r = compareGuess(truth$$1, guess, graphMaxY, graphMinY); var maxDiff = r.maxDiff; var predDiff = r.predDiff; var scoreFunction = d3.scaleLinear().domain([0, maxDiff]).range([100, 0]); myScore = scoreFunction(predDiff).toFixed(1); state.set(key, predictionDiff, predDiff); state.set(key, score, +myScore); getFinalScore(key, state, resultSection, scoreTitle, scoreButtonText, scoreButtonTooltip, scoreHtml); console.log(state.get(key, yourData)); console.log("The pred is: " + predDiff); console.log("The maxDiff is: " + maxDiff); console.log("The score is: " + myScore); console.log(state.getState()); } function getFinalScore(key, state, resultSection, scoreTitle, scoreButtonText, scoreButtonTooltip, scoreHtml) { var completed$$1 = true; state.getAllQuestions().forEach(function (ele) { completed$$1 = completed$$1 && typeof state.get(ele, score) !== "undefined"; }); if (completed$$1) { var scores = 0; state.getAllQuestions().forEach(function (ele) { scores = scores + state.get(ele, score); }); var finalScoreFunction = d3.scaleLinear().domain([0, 100 * state.getAllQuestions().length]).range([0, 100]); var finalScore = finalScoreFunction(scores).toFixed(); console.log("The final score is: " + finalScore); drawScore(+finalScore, resultSection, key, scoreTitle, scoreButtonText, scoreButtonTooltip, scoreHtml); } } function drawScore(finalScore, resultSection, key, scoreTitle, scoreButtonText, scoreButtonTooltip, scoreHtml) { // add final result button var ac = resultSection.append("div").attr("class", "actionContainer finalScore"); var button = ac.append("button").attr("class", "showAction"); button.append("div").attr("class", "globals-scoreButtonText update-font").text(scoreButtonText); var tt = ac.append("div").attr("class", "tooltipcontainer").append("span").attr("class", "tooltiptext globals-scoreButtonTooltip update-font") //.attr("class", "tooltiptext") .text(scoreButtonTooltip); // add final result graph var fs = {}; fs.div = resultSection.select("div.text").append("div").attr("class", "finalScore text").style("visibility", "hidden"); fs.div.append("div") //.attr("class", "before-finalScore globals-scoreTitle update-font") .attr("class", "before-finalScore").append("strong").append("div").attr("class", "globals-scoreTitle update-font").text(scoreTitle); var svgWidth = window.innerWidth > 500 ? 500 : window.innerWidth - 10; fs.svg = fs.div.append("svg").attr("width", svgWidth).attr("height", 75); var ch = resultSection.select("div.text").append("div").attr("class", "customHtml").style("visibility", "hidden").style("text-align", "center"); if (typeof scoreHtml !== "undefined") { var sHtml = scoreHtml.filter(function (d) { return d.lower <= finalScore && d.upper > finalScore; }); ch.selectAll("p").data(sHtml).enter().append("p").append("div").attr("class", "globals-scoreHtml update-font").html(function (d) { return d.html; }); } // adding some space at the bottom to reserved the final display space and // to have space below the botton (for the tooltip) // (30 = margin-top from fs.div) , 70 = margin-bottom from div.result.finished.shown) var h = fs.div.node().offsetHeight + ch.node().offsetHeight + 30 + 70 - ac.node().clientHeight; fs.div.style("display", "none").style("visibility", "visible"); // reset to avoid taking up space ch.style("display", "none").style("visibility", "visible"); var dummy = resultSection.append("div").attr("class", "dummy").style("height", h + "px"); button.on("click", function () { d3.select("div.actionContainer.finalScore").style("display", "none"); //d3.select(this).style("display", "none"); tt.style("display", "none"); dummy.remove(); showFinalScore(finalScore, resultSection, key, svgWidth); }); } function showFinalScore(finalScore, resultSection, key, svgWidth) { function showText() { d3.select(".result." + key).select("text.scoreText").style("opacity", 1); resultSection.select("div.customHtml").style("visibility", "visible"); } resultSection.select("div.finalScore.text").style("display", "block"); resultSection.select("div.customHtml").style("display", "block").style("visibility", "hidden"); var fs = {}; fs.g = resultSection.select(".finalScore.text > svg").append("g").attr("transform", "translate(5, 10)"); // const xScale = d3.scaleLinear().domain([0, 100]).range([0, 400]); var xScale = d3.scaleLinear().domain([0, 100]).range([0, svgWidth - 80]); var xAxis = d3.axisBottom(xScale).ticks(4); fs.g.append("g").attr("transform", "translate(0, 45)").attr("class", "x axis").call(xAxis); fs.rect = fs.g.append("rect").attr("class", "final-score-result").attr("x", 0).attr("y", 0).attr("height", 40).attr("width", 0); fs.txt = fs.g.append("text").attr("class", "scoreText globals-scoreText update-font").attr("x", xScale(finalScore) + 5).attr("dy", 27).text("(" + finalScore + "/100)"); fs.rect.transition().duration(3000).attr("width", xScale(finalScore)).on("end", showText); } /* * params: * sel: DOM selection for the text label of the reference value. A <span> is added with the text * svg: SVG for the lines connecting the graph with the label * referenceValues: question.referenceValues * c: object constant with graphical DOM selections as properties */ function addReferenceLines(sel, svg, referenceValues, c) { var gRef = void 0; var data = void 0; var referenceLine = d3.line().x(ƒ("year", c.x)).y(ƒ("value", c.y)).curve(d3.curveMonotoneX); referenceValues.forEach(function (ref, i) { data = ref.value.map(function (ele, index) { return { year: index, value: ele[Object.keys(ele)[0]] }; }); data.text = ref.text; data.anchor = parsePosition(ref.textPosition); data.offset = getOffset(data.anchor); gRef = svg.append("g").attr("class", "reference question-referenceValues referenceLine controls line-" + data.text.trim()); gRef.append("path").attr("d", referenceLine(data)).attr("class", "line referencePath").attr("id", "curvedPath-" + i); gRef.append("text").attr("class", "question-referenceText update-font").attr("dy", "-5").append("textPath").attr("class", "referenceTextPath").attr("text-anchor", data.anchor).attr("startOffset", data.offset).attr("xlink:href", "#curvedPath-" + i).text(data.text); }); } function parsePosition(pos) { if (pos !== "start" && pos !== "end") { pos = "middle"; } return pos; } function getOffset(pos) { var offset = void 0; if (pos === "start") { offset = "2%"; } else if (pos === "end") { offset = "98%"; } else { offset = "50%"; } return offset; } function addReferenceValuesDefault(sel, svg, referenceValues, c) { var gRef = void 0; var len = void 0; len = svg.select("g.grid").node().getBBox().width / 2; referenceValues.forEach(function (ref) { gRef = svg.append("g").attr("class", "reference question-referenceValues referenceLine controls"); gRef.append("line").attr("x1", 0).attr("y1", c.y(ref.value)).attr("x2", len).attr("y2", c.y(ref.value)).attr("class", "line referencePath"); sel.append("span").style("left", "10px").style("right", len - 10 + "px").style("top", c.y(ref.value) - 18 + "px").append("div").attr("class", "question-referenceValues update-font").style("text-align", "center").text(ref.text); }); } /* * params: * sel: DOM selection for the text label of the reference value. A <span> is added with the text * svg: SVG for the lines connecting the graph with the label * referenceValues: question.referenceValues * c: object constant with graphical DOM selections as properties * line: true or false (= ticks) */ function addReferenceValues(sel, svg, referenceValues, c, line) { if (line) { return addReferenceValuesDefault(sel, svg, referenceValues, c); } var len = 10; var shiftSpan = 8; var rectHeight = 30; var data = referenceValues.map(function (d) { return c.y(d.value) - shiftSpan; }); var positions = getPositions(data, rectHeight, c.height); var gRef = void 0; referenceValues.forEach(function (ref, i) { gRef = svg.append("g").attr("class", "reference question-referenceValues controls"); gRef.append("line").attr("x1", 0).attr("y1", c.y(ref.value)).attr("x2", len / 2).attr("y2", c.y(ref.value)); gRef.append("line").attr("x1", len / 2).attr("y1", c.y(ref.value)).attr("x2", len).attr("y2", positions[i] + shiftSpan); sel.append("span").style("left", len + 3 + "px").style("top", positions[i] + "px").append("div").attr("class", "question-referenceValues update-font").text(ref.text); }); } function getPositions(data, rectHeight) { var newPositions = void 0; var dataObject = createObject(data, rectHeight); dataObject = adjustBottoms(dataObject); newPositions = trimObject(dataObject); // drawRectangles(g, data2, "after"); if (newPositions[newPositions.length - 1] < 0) { dataObject = adjustTops(dataObject); newPositions = trimObject(dataObject); // drawRectangles(g, data3, "final"); } return newPositions; } function createObject(data, rectHeight, height) { // setup data structure with rectangles from bottom to the top var dataObject = []; var obj = { top: height, bottom: height + rectHeight }; // add dummy rect for lower bound dataObject.push(obj); data.forEach(function (d) { obj = { top: d, bottom: d + rectHeight }; dataObject.push(obj); }); obj = { top: 0 - rectHeight, bottom: 0 }; // add dummy rect for upper bound dataObject.push(obj); return dataObject; } function trimObject(dataObject) { // convert back to original array of values, also remove dummies var data3 = []; dataObject.forEach(function (d, i) { if (!(i === 0 || i === dataObject.length - 1)) { data3.push(d.top); } }); return data3; } function adjustBottoms(dataObject) { dataObject.forEach(function (d, i) { if (!(i === 0 || i === dataObject.length - 1)) { var diff = dataObject[i - 1].top - d.bottom; if (diff < 0) { // move rect up d.top += diff; d.bottom += diff; } } }); return dataObject; } function adjustTops(dataObject) { for (var i = dataObject.length; i-- > 0;) { if (!(i === 0 || i === dataObject.length - 1)) { var diff = dataObject[i + 1].bottom - dataObject[i].top; if (diff > 0) { // move rect down dataObject[i].top += diff; dataObject[i].bottom += diff; } } } return dataObject; } function ydLine(isMobile, state, sel, key, question, globals, data, indexedTimepoint, indexedData) { var minX = data[0].timePointIndex; var maxX = data[data.length - 1].timePointIndex; var minY = d3.min(data, function (d) { return d.value; }); var maxY = d3.max(data, function (d) { return d.value; }); var lastPointShownAtIndex = indexedTimepoint.indexOf(question.lastPointShownAt.toString()); var periods = [{ year: lastPointShownAtIndex, class: "blue", title: "" }, { year: maxX, class: "blue", title: globals.drawAreaTitle }]; var segmentBorders = [minX].concat(periods.map(function (d) { return d.year; })); var drawAxes = function drawAxes(c) { c.axis.append("g").attr("class", "x axis").attr("transform", "translate(0," + c.height + ")").call(c.xAxis); c.axis.append("g").attr("class", "y axis").call(c.yAxis); }; var makeLabel = function makeLabel(lowerPos, pos, addClass) { var x = c.x(pos); var y = c.y(indexedData[pos]); var text = formatValue(indexedData[pos], question.unit, question.precision); var label = c.labels.append("div").classed("data-label", true).classed(addClass, true).style("left", x + "px").style("top", y + "px"); label.append("span").append("div").attr("class", "question-label update-font").text(text); if (pos == minX && isMobile) { label.classed("edge-left", true); } if (pos == maxX && isMobile) { label.classed("edge-right", true); } var circles = void 0; var counter = 0; for (var between = lowerPos + 1; between <= pos; between++) { c.dots.append("circle").attr("r", 4.5).attr("cx", c.x(between)).attr("cy", c.y(indexedData[between])).attr("class", addClass); counter = counter + 1; } circles = c.dots.selectAll("circle:nth-last-child(-n+" + counter + ")"); /* return [ c.dots.append("circle") .attr("r", 4.5) .attr("cx", x) .attr("cy", y) .attr("class", addClass), label ]; */ return [circles, label]; }; var drawChart = function drawChart(lower, upper, addClass) { var definedFn = function definedFn(d) { return d.year >= lower && d.year <= upper; }; var area = d3.area().curve(d3.curveMonotoneX).x(ƒ("year", c.x)).y0(ƒ("value", c.y)).y1(c.height).defined(definedFn); var line = d3.area().curve(d3.curveMonotoneX).x(ƒ("year", c.x)).y(ƒ("value", c.y)).defined(definedFn); if (lower == minX) { makeLabel(minX - 1, minX, addClass); } var svgClass = addClass + (upper == lastPointShownAtIndex ? " median" : ""); var group = c.charts.append("g"); group.append("path").attr("d", area(data)).attr("class", "area " + svgClass).attr("fill", "url(#gradient-" + addClass + ")"); group.append("path").attr("d", line(data)).attr("class", "line " + svgClass); return [group].concat(makeLabel(lower, upper, svgClass)); }; // make visual area empty sel.html(""); var margin = { top: 44, // right: isMobile ? 20 : 50, right: 50, bottom: 30, // left: isMobile ? 20 : 100 left: 100 }; var heightCap = 84; var width = sel.node().offsetWidth; var height = 400; var c = { width: width - (margin.left + margin.right), height: height - (margin.top + margin.bottom) }; // configure scales var graphMinY = question.yAxisMin ? question.yAxisMin : minY >= 0 ? 0 : minY * getRandom(1, 1.5); var graphMaxY = question.yAxisMax ? question.yAxisMax : maxY + (maxY - graphMinY) * getRandom(0.4, 1); // add 40 - 100% for segment titles c.x = d3.scaleLinear().range([0, c.width]); c.x.domain([minX, maxX]); c.y = d3.scaleLinear().range([c.height, 0]); c.y.domain([graphMinY, graphMaxY]); c.svg = sel.append("svg").attr("width", width).attr("height", height).append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")").attr("width", c.width).attr("height", c.height); // gradients c.defs = d3.select(c.svg.node().parentNode).append("defs"); ["black", "red", "blue"].forEach(function (color) { var gradient = c.defs.append("linearGradient").attr("id", "gradient-" + color).attr("x1", "0%").attr("y1", "0%").attr("x2", "0%").attr("y2", "100%"); gradient.append("stop").attr("offset", "0%").attr("class", "start"); gradient.append("stop").attr("offset", "100%").attr("class", "end"); }); c.defs.append("marker").attr("id", "preview-arrowp").attr("orient", "auto").attr("viewBox", "0 0 10 10").attr("markerWidth", 6).attr("markerHeight", 6).attr("refX", 1).attr("refY", 5).append("path").attr("d", "M 0 0 L 10 5 L 0 10 z"); // make background grid c.grid = c.svg.append("g").attr("class", "grid"); c.grid.append("g").attr("class", "horizontal").call(d3.axisBottom(c.x).tickValues(c.x.ticks(maxX - minX)).tickFormat("").tickSize(c.height)).selectAll("line").attr("class", function (d) { return segmentBorders.indexOf(d) !== -1 ? "highlight" : ""; }); c.grid.append("g").attr("class", "vertical").call(d3.axisLeft(c.y).tickValues(c.y.ticks(6)).tickFormat("").tickSize(-c.width)); var applyMargin = function applyMargin(sel) { sel.style("left", margin.left + "px").style("top", margin.top + "px").style("width", c.width + "px").style("height", c.height + "px"); }; // invisible rect for dragging to work var dragArea = c.svg.append("rect").attr("class", "draggable").attr("x", c.x(lastPointShownAtIndex)).attr("width", c.x(maxX) - c.x(lastPointShownAtIndex)).attr("height", c.height).attr("opacity", 0); setTimeout(function () { var clientRect = c.svg.node().getBoundingClientRect(); c.top = clientRect.top + window.scrollY; c.bottom = clientRect.bottom + window.scrollY; }, 1000); c.labels = sel.append("div").attr("class", "labels").call(applyMargin); c.axis = c.svg.append("g"); c.charts = c.svg.append("g"); var userSel = c.svg.append("path").attr("class", "your-line"); c.dots = c.svg.append("g").attr("class", "dots"); // configure axes c.xAxis = d3.axisBottom().scale(c.x); c.xAxis.tickFormat(function (d) { return indexedTimepoint[d]; }).ticks(maxX - minX); c.yAxis = d3.axisLeft().scale(c.y); //.tickValues(c.y.ticks(6)); c.yAxis.tickFormat(function (d) { return formatValue(d, question.unit, question.precision); }); drawAxes(c); c.titles = sel.append("div").attr("class", "titles").call(applyMargin).style("top", "0px"); // add a preview pointer var xs = c.x(lastPointShownAtIndex); var ys = c.y(indexedData[lastPointShownAtIndex]); var xArrowStart = ys <= 300 ? xs + 45 : xs + 70; var yArrowStart = ys <= 300 ? ys + 30 : ys - 30; var yTextStart = ys <= 300 ? c.y(indexedData[lastPointShownAtIndex]) + 30 : c.y(indexedData[lastPointShownAtIndex]) - 65; var xTextStart = ys <= 300 ? c.x(lastPointShownAtIndex) + 30 : c.x(lastPointShownAtIndex) + 65; c.preview = c.svg.append("path").attr("class", "controls preview-pointer").attr("marker-end", "url(#preview-arrowp)").attr("d", "M" + xArrowStart + "," + yArrowStart + " Q" + xArrowStart + "," + ys + " " + (xs + 15) + "," + ys); // add preview wave var arc = d3.arc().startAngle(0).endAngle(Math.PI); var nrWaves = initializeWaves(4); c.wave = c.svg.append("g").attr("class", "wave controls"); c.wave.append("clipPath").attr("id", "wave-clip-" + key).append("rect").attr("width", c.width).attr("height", c.height); c.wave = c.wave.append("g").attr("clip-path", "url(#wave-clip-" + key + ")").append("g").attr("transform", "translate(" + xs + ", " + ys + ")").selectAll("path").data(nrWaves).enter().append("path").attr("class", "wave").attr("d", arc); moveWave(); function moveWave() { console.log("moveWave"); c.wave.style("opacity", .6).transition().ease(d3.easeLinear).delay(function (d, i) { return 1000 + i * 300; }).duration(4000).attrTween("d", arcTween()).style("opacity", 0).on("end", restartWave); } function initializeWaves(nr) { var nrWaves = []; for (var i = 0; i < nr; i++) { nrWaves.push({}); } return nrWaves; } function restartWave(d, i) { if (i === nrWaves.length - 1) { // restart after last wave is finished var nrWaves2 = initializeWaves(4); c.wave = c.wave.data(nrWaves2); c.wave.attr("d", arc); moveWave(); } } function arcTween() { return function (d) { if (sel.classed("drawn")) { c.wave.interrupt(); console.log("waves interrupted"); return; } var interpolate = d3.interpolate(0, 100); return function (t) { d.innerRadius = interpolate(t); d.outerRadius = interpolate(t) + 3; return arc(d); }; }; } // add preview notice c.controls = sel.append("div").attr("class", "controls").call(applyMargin).style("padding-left", c.x(minX) + "px"); c.controls.append("span").style("left", xTextStart + "px").style("top", yTextStart + "px").append("div").attr("class", "globals-drawLine update-font").text(globals.drawLine); if (typeof question.referenceValues !== "undefined") { addReferenceLines(c.controls, c.svg, question.referenceValues, c); } // make chart var charts = periods.map(function (entry, key) { var lower = key > 0 ? periods[key - 1].year : minX; var upper = entry.year; // segment title var t = c.titles.append("span").style("left", Math.ceil(c.x(lower) + 1) + "px").style("width", Math.floor(c.x(upper) - c.x(lower) - 1) + "px"); t.append("div").attr("class", "globals-drawAreaTitle update-font").text(entry.title); // assign prediction period to variable to use it later in interactionHandler if (key === 1) { c.predictionTitle = t; } return drawChart(lower, upper, entry.class); }); var resultChart = charts[charts.length - 1][0]; var resultClip = c.charts.append("clipPath").attr("id", "result-clip-" + key).append("rect").attr("width", c.x(lastPointShownAtIndex)).attr("height", c.height); var resultLabel = charts[charts.length - 1].slice(1, 3); resultChart.attr("clip-path", "url(#result-clip-" + key + ")").append("rect").attr("width", c.width).attr("height", c.height).attr("fill", "none"); resultLabel.map(function (e) { return e.style("opacity", 0); }); // Interactive user selection part var userLine = d3.line().x(ƒ("year", c.x)).y(ƒ("value", c.y)).curve(d3.curveMonotoneX); if (!state.get(key, yourData)) { var val = data.map(function (d) { return { year: d.year, value: indexedData[lastPointShownAtIndex], defined: 0 }; }).filter(function (d) { if (d.year == lastPointShownAtIndex) d.defined = true; return d.year >= lastPointShownAtIndex; }); state.set(key, "yourData", val); } var resultSection = d3.select(".result." + key); var drawUserLine = function drawUserLine(year) { userSel.attr("d", userLine.defined(ƒ("defined"))(state.get(key, yourData))); var d = state.get(key, yourData).filter(function (d) { return d.year === year; })[0]; var dDefined = state.get(key, yourData).filter(function (d) { return d.defined && d.year !== lastPointShownAtIndex; }); if (!d.defined) { return; } var dot = c.dots.selectAll("circle.result").data(dDefined); dot.enter().append("circle").merge(dot).attr("r", 4.5).attr("cx", function (de) { return c.x(de.year); }).attr("cy", function (de) { return c.y(de.value); }).attr("class", "result"); var yourResult = c.labels.selectAll(".your-result").data([d]); yourResult.enter().append("div").classed("data-label your-result", true).classed("edge-right", isMobile).merge(yourResult).style("z-index", function () { return year === lastPointShownAtIndex ? 1 : 2; }) // should always be != , z-index=2 .style("left", function () { return c.x(year) + "px"; }).style("top", function (r) { return c.y(r.value) + "px"; }).html("").append("span").append("div").attr("class", "question-label update-font").text(function (r) { return question.precision ? formatValue(r.value, question.unit, question.precision) : formatValue(r.value, question.unit, question.precision, 0); }); }; drawUserLine(lastPointShownAtIndex); var interactionHandler = function interactionHandler() { if (state.get(key, resultShown)) { return; } sel.node().classList.add("drawn"); var pos = d3.mouse(c.svg.node()); // if (pos[1] < margin.top + 4) { return; } if (pos[1] < 0) { return; } var year = clamp(lastPointShownAtIndex, maxX, c.x.invert(pos[0])); var value = clamp(c.y.domain()[0], c.y.domain()[1], c.y.invert(pos[1])); var yearPoint = lastPointShownAtIndex; state.get(key, yourData).forEach(function (d) { if (d.year > lastPointShownAtIndex) { if (Math.abs(d.year - year) < .5) { d.value = value; yearPoint = d.year; } if (d.year - year < 0.5) { d.defined = true; yearPoint = d.year; } } }); if (pos[1] < heightCap) { c.predictionTitle.style("opacity", 0); } else if (pos[1] >= heightCap) { c.predictionTitle.style("opacity", 1); } drawUserLine(yearPoint); if (!state.get(key, completed) && d3.mean(state.get(key, yourData), ƒ("defined")) == 1) { state.set(key, completed, true); resultSection.node().classList.add("finished"); resultSection.select("button").node().removeAttribute("disabled"); } }; c.svg.call(d3.drag().on("drag", interactionHandler)); c.svg.on("click", interactionHandler); var showResultChart = function showResultChart() { if (!state.get(key, completed)) { return; } c.labels.selectAll(".your-result").node().classList.add("hideLabels"); resultClip.transition().duration(700).attr("width", c.x(maxX)); dragArea.attr("class", ""); resultLabel[0].transition().duration(30).delay(function (d, i) { return (i + 1) / resultLabel[0].size() * 700; }).style("opacity", 1); setTimeout(function () { resultLabel.map(function (e) { return e.style("opacity", 1); }); resultSection.node().classList.add("shown"); if (!state.get(key, score) && globals.showScore) { var truth$$1 = data.filter(function (d) { return d.year > lastPointShownAtIndex; }); getScore(key, truth$$1, state, graphMaxY, graphMinY, resultSection, globals.scoreTitle, globals.scoreButtonText, globals.scoreButtonTooltip, globals.scoreHtml); } state.set(key, resultShown, true); }, 700); }; resultSection.select("button").on("click", showResultChart); if (state.get(key, resultShown)) { showResultChart(); } } function ydBar(isMobile, state, sel, key, question, globals, data, indexedTimepoint, indexedData) { var minX = data[0].timePointIndex; var maxX = data[data.length - 1].timePointIndex; var minY = d3.min(data, function (d) { return d.value; }); var maxY = d3.max(data, function (d) { return d.value; }); var lastPointShownAtIndex = indexedTimepoint.indexOf(question.lastPointShownAt.toString()); var drawAxes = function drawAxes(c) { c.axis.append("g").attr("class", "x axis").attr("transform", "translate(0," + c.height + ")"); // .call(c.xAxis); c.axis.append("g").attr("class", "y axis").call(c.yAxis); }; var makeLabel = function makeLabel(pos, addClass) { var x = c.x(truth) + c.x.bandwidth() / 2; var truthValue = data[0].value; var y = c.y(truthValue); var text = formatValue(truthValue, question.unit, question.precision); var label = c.labels.append("div").classed("data-label", true).classed(addClass, true).style("opacity", 0).style("left", x + "px").style("top", y + "px"); label.append("span") // .classed("no-dot question-label update-font", true) .classed("no-dot", true).append("div").classed("question-label update-font", true).text(text); if (pos == minX && isMobile) { label.classed("edge-left", true); } if (pos == maxX && isMobile) { label.classed("edge-right", true); } return [{}, label]; }; var drawChart = function drawChart(addClass) { var group = c.charts.append("g").attr("class", "truth"); makeLabel(truth, addClass); var truthSelection = group.append("rect").attr("class", "bar").attr("x", c.x(truth)).attr("y", c.height).attr("height", 0).attr("width", c.x.bandwidth()); return truthSelection; }; // make visual area empty sel.html(""); var margin = { top: 40, // right: isMobile ? 20 : 50, right: 50, bottom: 30, // left: isMobile ? 20 : 100 left: 100 }; var width = sel.node().offsetWidth; var height = 400; var c = { width: width - (margin.left + margin.right), height: height - (margin.top + margin.bottom) }; var graphMinY = question.yAxisMin ? question.yAxisMin : minY >= 0 ? 0 : minY * getRandom(1, 1.5); var graphMaxY = question.yAxisMax ? question.yAxisMax : maxY + (maxY - graphMinY) * getRandom(0.4, 1); // add 40 - 100% for segment titles c.x = d3.scaleBand().rangeRound([0, c.width]).padding(0.1); c.x.domain([prediction, truth]); c.y = d3.scaleLinear().range([c.height, 0]); c.y.domain([graphMinY, graphMaxY]); c.svg = sel.append("svg").attr("width", width).attr("height", height).append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")").attr("width", c.width).attr("height", c.height); // gradients c.defs = d3.select(c.svg.node().parentNode).append("defs"); ["black", "red", "blue"].forEach(function (color) { var gradient = c.defs.append("linearGradient").attr("id", "gradient-" + color).attr("x1", "0%").attr("y1", "0%").attr("x2", "0%").attr("y2", "100%"); gradient.append("stop").attr("offset", "0%").attr("class", "start"); gradient.append("stop").attr("offset", "100%").attr("class", "end"); }); c.defs.append("marker").attr("id", "preview-arrowp").attr("orient", "auto").attr("viewBox", "0 0 10 10").attr("markerWidth", 6).attr("markerHeight", 6).attr("refX", 1).attr("refY", 5).append("path").attr("d", "M 0 0 L 10 5 L 0 10 z"); // make background grid c.grid = c.svg.append("g").attr("class", "grid"); c.grid.append("g").attr("class", "vertical").call(d3.axisLeft(c.y).tickValues(c.y.ticks(6)).tickFormat("").tickSize(-c.width)); var applyMargin = function applyMargin(sel) { sel.style("left", margin.left + "px").style("top", margin.top + "px").style("width", c.width + "px").style("height", c.height + "px"); }; setTimeout(function () { var clientRect = c.svg.node().getBoundingClientRect(); c.top = clientRect.top + window.scrollY; c.bottom = clientRect.bottom + window.scrollY; }, 1000); c.labels = sel.append("div").attr("class", "labels").call(applyMargin); c.axis = c.svg.append("g"); c.charts = c.svg.append("g").attr("class", "charts"); c.xPredictionCenter = c.x(prediction) + c.x.bandwidth() / 2; var userSel = c.svg.append("rect").attr("class", "your-rect"); // invisible rect for dragging to work var dragArea = c.svg.append("rect").attr("class", "draggable").attr("x", c.x(prediction)).attr("width", c.x.bandwidth()).attr("height", c.height).attr("opacity", 0); // configure axes c.xAxis = d3.axisBottom().scale(c.x); c.yAxis = d3.axisLeft().scale(c.y).tickValues(c.y.ticks(6)); c.yAxis.tickFormat(function (d) { return formatValue(d, question.unit, question.precision); }); drawAxes(c); c.titles = sel.append("div").attr("class", "titles").call(applyMargin).style("top", "0px"); // add a preview pointer var xs = c.xPredictionCenter; var ys = c.height - 30; var xArrowStart = xs + 45; var yArrowStart = ys - 50; var xTextStart = xArrowStart + 5; var yTextStart = yArrowStart - 10; c.preview = c.svg.append("path").attr("class", "controls preview-pointer").attr("marker-end", "url(#preview-arrowp)").attr("d", "M" + xArrowStart + "," + yArrowStart + " Q" + xs + "," + yArrowStart + " " + xs + "," + (ys - 10)); // add preview wave var arc = d3.arc().startAngle(0).endAngle(2 * Math.PI); var nrWaves = initializeWaves(4); c.wave = c.svg.append("g").attr("class", "wave controls"); c.wave.append("clipPath").attr("id", "wave-clip-" + key).append("rect").attr("width", c.width).attr("height", c.height); c.wave = c.wave.append("g").attr("clip-path", "url(#wave-clip-" + key + ")").append("g").attr("transform", "translate(" + xs + ", " + ys + ")").selectAll("path").data(nrWaves).enter().append("path").attr("class", "wave").attr("d", arc); moveWave(); function moveWave() { c.wave.style("opacity", .6).transition().ease(d3.easeLinear).delay(function (d, i) { return 1000 + i * 300; }).duration(4000).attrTween("d", arcTween()).style("opacity", 0).on("end", restartWave); } function initializeWaves(nr) { var nrWaves = []; for (var i = 0; i < nr; i++) { nrWaves.push({}); } return nrWaves; } function restartWave(d, i) { if (i === nrWaves.length - 1) { // restart after last wave is finished var nrWaves2 = initializeWaves(4); c.wave = c.wave.data(nrWaves2); c.wave.attr("d", arc); moveWave(); } } function arcTween() { return function (d) { if (sel.classed("drawn")) { c.wave.interrupt(); console.log("waves interrupted"); return; } var interpolate = d3.interpolate(0, 100); return function (t) { d.innerRadius = interpolate(t); d.outerRadius = interpolate(t) + 3; return arc(d); }; }; } // add preview notice c.controls = sel.append("div").attr("class", "controls").call(applyMargin).style("padding-left", c.xPredictionCenter); c.controls.append("span").style("left", xTextStart + "px").style("top", yTextStart + "px").append("div").attr("class", "globals-drawBar update-font").text(globals.drawBar); if (typeof question.referenceValues !== "undefined") { if (question.referenceShape === "tick") { addReferenceValues(c.controls, c.svg, question.referenceValues, c, false); } else { //question.referenceShape === "line" addReferenceValues(c.controls, c.svg, question.referenceValues, c, true); } } // make chart var truthSelection = drawChart("blue"); // segment title c.predictionTitle = c.titles.append("span").style("left", "1px").style("width", c.width / 2 - 1 + "px"); c.predictionTitle.append("div").attr("class", "globals-drawAreaTitle update-font").text(globals.drawAreaTitle); // Interactive user selection part userSel.attr("x", c.x(prediction)).attr("y", c.height - 30).attr("width", c.x.bandwidth()).attr("height", 30); if (!state.get(key, yourData)) { var val = data.map(function (d) { return { year: d.year, value: indexedData[lastPointShownAtIndex], defined: 0 }; }).filter(function (d) { if (d.year == lastPointShownAtIndex) d.defined = true; return d.year >= lastPointShownAtIndex; }); state.set(key, "yourData", val); } var resultSection = d3.select(".result." + key); var drawUserBar = function drawUserBar(year) { var h = c.y(state.get(key, yourData)[0].value); userSel.attr("y", h).attr("height", c.height - h); var d = state.get(key, yourData).filter(function (d) { return d.year === year; })[0]; // const dDefined = state.get(key, yourData).filter(d => d.defined && (d.year !== lastPointShownAtIndex)); if (!d.defined) { return; } var yourResult = c.labels.selectAll(".your-result").data([d]); yourResult.enter().append("div").classed("data-label your-result", true).classed("edge-right", isMobile).merge(yourResult).style("left", c.xPredictionCenter + "px").style("top", function (r) { return c.y(r.value) + "px"; }).html("").append("span").classed("no-dot", true).append("div").classed("question-label update-font", true).text(function (r) { return question.precision ? formatValue(r.value, question.unit, question.precision) : formatValue(r.value, question.unit, question.precision, 0); }); }; if (sel.classed("drawn")) { drawUserBar(lastPointShownAtIndex); } var interactionHandler = function interactionHandler() { if (state.get(key, resultShown)) { return; } sel.node().classList.add("drawn"); var pos = d3.mouse(c.svg.node()); // if (pos[1] < margin.top) { return; } if (pos[1] < 0) { return; } var value = clamp(c.y.domain()[0], c.y.domain()[1], c.y.invert(pos[1])); var yearPoint = lastPointShownAtIndex; state.get(key, yourData).forEach(function (d) { d.value = value; d.defined = true; yearPoint = d.year; }); if (pos[1] < 80) { c.predictionTitle.style("opacity", 0); } else if (pos[1] >= 80) { c.predictionTitle.style("opacity", 1); } drawUserBar(yearPoint); if (!state.get(key, completed) && d3.mean(state.get(key, yourData), ƒ("defined")) == 1) { state.set(key, completed, true); resultSection.node().classList.add("finished"); resultSection.select("button").node().removeAttribute("disabled"); } }; c.svg.call(d3.drag().on("drag", interactionHandler)); c.svg.on("click", interactionHandler); var showResultChart = function showResultChart() { if (!state.get(key, completed)) { return; } c.labels.selectAll(".your-result").node().classList.add("hideLabels"); var h = c.y(data[0].value); truthSelection.transition().duration(1300).attr("y", h).attr("height", c.height - h); dragArea.attr("class", ""); setTimeout(function () { c.labels.select("div.data-label").style("opacity", 1); resultSection.node().classList.add("shown"); if (!state.get(key, score) && globals.showScore) { var _truth = data.filter(function (d) { return d.year === lastPointShownAtIndex; }); getScore(key, _truth, state, graphMaxY, graphMinY, resultSection, globals.scoreTitle, globals.scoreButtonText, globals.scoreButtonTooltip, globals.scoreHtml); } state.set(key, resultShown, true); }, 1300); }; resultSection.select("button").on("click", showResultChart); if (state.get(key, resultShown)) { showResultChart(); } } /* import { ƒ } from "./helpers/function"; import { formatValue } from "./helpers/formatValue"; import { clamp } from "./helpers/clamp"; import { getRandom } from "./helpers/getRandom"; import { yourData, resultShown, completed, score, prediction, truth } from "./helpers/constants"; import { getScore } from "./results/score"; import { addReferenceValues } from "./helpers/referenceValues"; */ function ydCheckbox(isMobile, state, sel, key, question, globals, data) { sel.html(""); var selDiv = sel.append("div"); var selLabel = void 0; var prediction$$1 = []; var cb = void 0; data.forEach(function (ele, i) { selLabel = selDiv.append("label").attr("class", "question-multipleChoice update-font answer-container l-" + i).html(ele.timePoint); // checkbox for answers selLabel.append("span").attr("class", "answer-checkmark-truth t-" + i).append("div").attr("class", "input"); // checkbox for guesses cb = selLabel.append("input").attr("type", "checkbox").attr("name", "cb").attr("value", "v" + i).on("click", handleClick); selLabel.append("span").attr("class", "answer-checkmark"); // preset the checkboxes with the guesses already made for resize event prediction$$1[i] = state.get(key, yourData) ? state.get(key, yourData)[i] : false; cb.node().checked = prediction$$1[i]; }); var resultSection = d3.select(".result." + key); resultSection.select("button").on("click", showResultChart); if (state.get(key, resultShown)) { showResultChart(); } function handleClick() { if (state.get(key, resultShown)) { return; } var index = d3.select(this).attr("value").substring(1); console.log("Clicked, new value [" + index + "] = " + d3.select(this).node().checked); prediction$$1[index] = d3.select(this).node().checked; state.set(key, yourData, prediction$$1); resultSection.node().classList.add("finished"); resultSection.select("button").node().removeAttribute("disabled"); } function showResultChart() { state.set(key, completed, true); // disable hovers var css = ".answer-container:hover input ~ .answer-checkmark { background-color: #eee;}"; css = css + " .answer-container input:checked ~ .answer-checkmark { background-color: orange;}"; var style = document.createElement("style"); if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } document.getElementsByTagName("head")[0].appendChild(style); // disable checkboxes sel.selectAll("div input").each(function () { d3.select(this).node().disabled = true; }); // display result (with transition) var correctAnswers = 0; data.forEach(function (ele, i) { if (ele.value === prediction$$1[i]) { correctAnswers = correctAnswers + 1; } sel.select("div span.answer-checkmark-truth.t-" + i).classed("checked", ele.value).style("background-color", "#fff").transition().ease(ele.value ? d3.easeExpIn : d3.easeLinear).duration(100).delay(i * 100).style("background-color", ele.value ? "#00345e" : "#eee"); sel.select("div span.answer-checkmark-truth.t-" + i + " div.input").classed("checked", ele.value); sel.select("div .answer-container.l-" + i).transition().duration(100).delay(i * 100).style("color", ele.value ? "#00345e" : "#eee"); }); // call getScore var durationTrans = 100 * (data.length + 1); setTimeout(function () { resultSection.node().classList.add("shown"); if (!state.get(key, score) && globals.showScore) { var myScore = Math.round(correctAnswers / prediction$$1.length * 100); console.log("score: " + myScore); state.set(key, score, myScore); getFinalScore(key, state, resultSection, globals.scoreTitle, globals.scoreButtonText, globals.scoreButtonTooltip, globals.scoreHtml); } state.set(key, resultShown, true); }, durationTrans); } } function myState () { var state = {}; stateAPI(); function stateAPI() { state = {}; } stateAPI.setQuestion = function (question) { if (!state[question]) { state[question] = {}; } }; stateAPI.getQuestion = function (question) { return state[question]; }; stateAPI.getAllQuestions = function () { return Object.keys(state); }; stateAPI.getState = function () { return state; }; stateAPI.set = function (question, key, value) { if (!state[question][key]) { state[question][key] = {}; } state[question][key] = value; }; stateAPI.get = function (question, key) { return state[question][key]; }; // for calculating the score stateAPI.getResult = function (question, key) { var oldArray = state[question][key]; // remove first element for line charts, which was not a prediction but the starting point for the line var newArray = oldArray.length > 1 ? oldArray.slice(1) : oldArray; return newArray; }; return stateAPI; } var globals = {}; function youdrawit(_globals, questions) { var isMobile = window.innerWidth < 760; globals = _globals; var state = myState(); var drawGraphs = function drawGraphs() { console.log("drawing graphs"); d3.selectAll(".you-draw-it").each(function (d, i) { var sel = d3.select(this); var question = questions[i]; var key = question.key; var originalData = question.data; var data = originalData.map(function (ele, index) { return { year: index, timePointIndex: index, timePoint: Object.keys(ele)[0], value: ele[Object.keys(ele)[0]] }; }); var indexedTimepoint = data.map(function (ele) { return ele.timePoint; }); var indexedData = data.map(function (ele) { return ele.value; }); state.setQuestion(key); if (data.length < 1) { console.log("No data available for:", key); return; } if (question.chartType === "barChart") { ydBar(isMobile, state, sel, key, question, globals, data, indexedTimepoint, indexedData); } else if (question.chartType === "timeSeries") { ydLine(isMobile, state, sel, key, question, globals, data, indexedTimepoint, indexedData); } else if (question.chartType === "multipleChoice") { ydCheckbox(isMobile, state, sel, key, question, globals, data); } }); }; // document.addEventListener("DOMContentLoaded", drawGraphs); drawGraphs(); window.addEventListener("resize", debounce(function () { drawGraphs(); }, 500)); } function getLanguage() { return globals.default; } function _interface () { var options = {}; options.containerDiv = d3.select("body"); options.globals = {}; /* option.globals contain: g.default g.header g.subHeader g.drawAreaTitle g.drawLine g.drawBar g.resultButtonText g.resultButtonTooltip g.showScore g.scoreTitle g.scoreButtonText g.scoreButtonTooltip g.scoreHtml */ options.questions = []; /* options.questions is an array of question objects q with: q.data q.heading q.subHeading q.resultHtml q.unit q.precision q.lastPointShownAt q.yAxisMin q.yAxisMax q.referenceValues q.referenceShape // the following are internal properties q.chartType q.key */ // API for external access function chartAPI(selection) { selection.each(function () { options.containerDiv = d3.select(this); if (!options.questions) { console.log("no questions specified!"); } if (Object.keys(options.globals).length === 0) { setGlobalDefault("English"); } completeQuestions(); completeDOM(); youdrawit(options.globals, options.questions); }); return chartAPI; } chartAPI.questions = function (_) { if (!arguments.length) return options.questions; options.questions = _; return chartAPI; }; chartAPI.globals = function (_) { if (!arguments.length) return options.globals; for (var key in _) { if (_.hasOwnProperty(key)) { options.globals[key] = _[key]; if (key === "default") { setGlobalDefault(_[key]); } } } return chartAPI; }; function setGlobalDefault(lang) { var g = options.globals; g.showScore = typeof g.showScore === "undefined" ? true : g.showScore; if (lang === "de") { // de (German) g.resultButtonText = typeof g.resultButtonText === "undefined" ? "Zeig mir die Lösung!" : g.resultButtonText; g.resultButtonTooltip = typeof g.resultButtonTooltip === "undefined" ? "Zeichnen Sie Ihre Einschätzung. Der Klick verrät, ob sie stimmt." : g.resultButtonTooltip; g.scoreTitle = typeof g.scoreTitle === "undefined" ? "Ihr Ergebnis:" : g.scoreTitle; g.scoreButtonText = typeof g.scoreButtonText === "undefined" ? "Zeig mir, wie gut ich war!" : g.scoreButtonText; g.scoreButtonTooltip = typeof g.scoreButtonTooltip === "undefined" ? "Klicken Sie hier, um Ihr Gesamtergebnis zu sehen" : g.scoreButtonTooltip; g.drawAreaTitle = typeof g.drawAreaTitle === "undefined" ? "Ihre\nEinschätzung" : g.drawAreaTitle; g.drawLine = typeof g.drawLine === "undefined" ? "Zeichnen Sie von hier\nden Verlauf zu Ende" : g.drawLine; g.drawBar = typeof g.drawBar === "undefined" ? "Ziehen Sie den Balken\nauf die entsprechende Höhe" : g.drawBar; } else if (lang === "fr") { // fr (French) g.default = "fr"; g.resultButtonText = typeof g.resultButtonText === "undefined" ? "Montrez-moi le résultat" : g.resultButtonText; g.resultButtonTooltip = typeof g.resultButtonTooltip === "undefined" ? "A vous de dessiner la courbe. Pour voir la bonne réponse, cliquez ici" : g.resultButtonTooltip; g.scoreTitle = typeof g.scoreTitle === "undefined" ? "Votre résultat:" : g.scoreTitle; g.scoreButtonText = typeof g.scoreButtonText === "undefined" ? "Montrez-moi la bonne réponse" : g.scoreButtonText; g.scoreButtonTooltip = typeof g.scoreButtonTooltip === "undefined" ? "Cliquez ici pour obtenir des explications" : g.scoreButtonTooltip; g.drawAreaTitle = typeof g.drawAreaTitle === "undefined" ? "Votre\nsupposition" : g.drawAreaTitle; g.drawLine = typeof g.drawLine === "undefined" ? "Placez votre doigt\nou votre souris ici\net dessinez la courbe" : g.drawLine; g.drawBar = typeof g.drawBar === "undefined" ? "Montez la barre\njusqu’à la hauteur supposée" : g.drawBar; } else { // lang === "en" (English) g.default = "en"; g.resultButtonText = typeof g.resultButtonText === "undefined" ? "Show me the result!" : g.resultButtonText; g.resultButtonTooltip = typeof g.resultButtonTooltip === "undefined" ? "Draw your guess. Upon clicking here, you see if you're right." : g.resultButtonTooltip; g.scoreTitle = typeof g.scoreTitle === "undefined" ? "Your result:" : g.scoreTitle; g.scoreButtonText = typeof g.scoreButtonText === "undefined" ? "Show me how good I am!" : g.scoreButtonText; g.scoreButtonTooltip = typeof g.scoreButtonTooltip === "undefined" ? "Click here to see your result" : g.scoreButtonTooltip; g.drawAreaTitle = typeof g.drawAreaTitle === "undefined" ? "Your\nguess" : g.drawAreaTitle; g.drawLine = typeof g.drawLine === "undefined" ? "draw the graph\nfrom here to the end" : g.drawLine; g.drawBar = typeof g.drawBar === "undefined" ? "drag the bar\nto the estimated height" : g.drawBar; } } function completeQuestions() { if (typeof options.globals.scoreHtml !== "undefined") { if (typeof options.globals.scoreHtml === "string" || options.globals.scoreHtml instanceof String) { if (!checkResult(options.globals.scoreHtml)) { console.log("invalid scoreHtml!"); options.globals.scoreHtml = void 0; // set to undefined } else { options.globals.scoreHtml = [{ lower: 0, upper: 101, html: options.globals.scoreHtml }]; } } else { // options.globals.scoreHtml is an array if (typeof options.globals.scoreHtml.length !== "undefined") { options.globals.scoreHtml.forEach(function (range) { var exp = range.html; if (!checkResult(exp)) { console.log("invalid scoreHtml! -> set to empty string"); range.html = ""; } }); } } } options.questions.forEach(function (q, index) { if (!q.data) { console.log("no data specified!"); } if (!checkResult(q.resultHtml)) { console.log("invalid result!"); } q.chartType = getChartType(q.data); q.heading = typeof q.heading === "undefined" ? "" : q.heading; q.subHeading = typeof q.subHeading === "undefined" ? "" : q.subHeading; q.resultHtml = typeof q.resultHtml === "undefined" ? "<br>" : q.resultHtml; q.unit = typeof q.unit === "undefined" ? "" : q.unit; q.precision = typeof q.precision === "undefined" ? 1 : q.precision; q.referenceShape = typeof q.referenceShape === "undefined" ? "line" : q.referenceShape; q.key = "q" + (index + 1); if (q.chartType === "barChart") { q.data = [{ value: q.data }]; } if (!q.lastPointShownAt) { if (q.chartType === "timeSeries") { var nextToLast = q.data[q.data.length - 2]; q.lastPointShownAt = Object.keys(nextToLast)[0]; } else if (q.chartType === "barChart") { var onlyElement = q.data[0]; q.lastPointShownAt = Object.keys(onlyElement)[0]; } } console.log("display question " + index + " as " + q.chartType); }); } function getChartType(data) { var chartType = void 0; if (isNumber(data)) { chartType = "barChart"; } else { var firstObj = data[0]; var num = true; for (var key in firstObj) { if (firstObj.hasOwnProperty(key)) { num = num && isNumber(firstObj[key]); } } chartType = num ? "timeSeries" : "multipleChoice"; } return chartType; } function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function completeDOM() { var art = options.containerDiv.append("article").attr("id", "content").attr("class", "container"); var intro = art.append("div").attr("class", "intro"); intro.append("h1").append("div").attr("class", "globals-header update-font").html(options.globals.header); intro.append("p").append("div").attr("class", "globals-subHeader update-font").html(options.globals.subHeader); var questions = art.append("div").attr("class", "questions"); options.questions.forEach(function (q) { var question = questions.append("div").attr("class", "question"); question.append("h2").append("div").attr("class", "question-heading update-font").html(q.heading); question.append("h3").append("div").attr("class", "question-subHeading update-font").html(q.subHeading); question.append("div").attr("class", "you-draw-it " + q.key).attr("data-key", q.key); var res = question.append("div").attr("class", "result " + q.key); var ac = res.append("div").attr("class", "actionContainer"); ac.append("button").attr("class", "showAction").attr("disabled", "disabled").append("div").attr("class", "globals-resultButtonText update-font").text(options.globals.resultButtonText); ac.append("div").attr("class", "tooltipcontainer").append("span").attr("class", "tooltiptext globals-resultButtonTooltip update-font").text(options.globals.resultButtonTooltip); res.append("div").attr("class", "text").append("p").append("div").attr("class", "question-resultHtml update-font").html(q.resultHtml); }); } function checkResult(exp) { // checks if html might contain javascript if (!exp) { return true; } var expUC = exp.toUpperCase(); if (expUC.indexOf("<") !== -1 && expUC.indexOf("SCRIPT") !== -1 && expUC.indexOf(">") !== -1) { console.log("--- invalid html!"); console.log("--- expression was: "); console.log(exp); return false; } else { return true; } } return chartAPI; } exports.chart = _interface; Object.defineProperty(exports, '__esModule', { value: true }); })));
import { REHYDRATE } from 'redux-persist/lib/constants' import Rate from "../services/rate" import * as BLOCKCHAIN_INFO from "../../../env" import constants from "../services/constants" import * as converter from "../utils/converter" function initTokens() { //var network = network ? network: "ropsten" let tokens = {} // var length = pinTokens? pinTokens.length: 0 // var index = 0 // Object.keys(BLOCKCHAIN_INFO[network].tokens).forEach((key) => { // tokens[key] = BLOCKCHAIN_INFO[network].tokens[key] // tokens[key].rate = 0 // tokens[key].minRate = 0 // tokens[key].rateEth = 0 // tokens[key].minRateEth = 0 // tokens[key].balance = 0 // tokens[key].rateUSD = 0 // if (pinTokens){ // if(pinTokens.includes(key)){ // tokens[key].priority = true; // tokens[key].index = pinTokens.indexOf(key); // }else{ // tokens[key].priority = false // } // } // }) return { tokens: tokens, count: { storageKey: constants.STORAGE_KEY } } } const initState = initTokens() const tokens = (state = initState, action) => { switch (action.type) { // case REHYDRATE: { // if (action.key === "tokens") { // var payload = action.payload // var tokens = {} // if (payload) { // // check load from loaclforage or initstate // var loadedTokens = payload.tokens // if (payload.count && payload.count.storageKey !== constants.STORAGE_KEY) { // loadedTokens = initState.tokens // } // Object.keys(loadedTokens).forEach((id) => { // var tokenMap = loadedTokens[id] // var token = new Rate( // tokenMap.name, // tokenMap.symbol, // tokenMap.icon, // tokenMap.address, // tokenMap.decimal, // tokenMap.rate ? tokenMap.rate : 0, // tokenMap.minRate ? tokenMap.minRate : 0, // 0, // tokenMap.rateEth ? tokenMap.rateEth : 0, // tokenMap.minRateEth ? tokenMap.minRateEth : 0, // tokenMap.rateUSD ? tokenMap.rateUSD : 0 // ) // tokens[id] = token // }) // return Object.assign({}, state, { // tokens: tokens, // count: { storageKey: constants.STORAGE_KEY } // }) // } else { // return state; // } // } // return state // } case 'GLOBAL.ALL_RATE_UPDATED_FULFILLED': { var tokens = { ...state.tokens } var rates = action.payload.rates if (!rates){ return state } //map token var mapToken = {} rates.map(rate => { if (rate.source !== "ETH") { if (!mapToken[rate.source]) { mapToken[rate.source] = {} } mapToken[rate.source].rate = rate.rate mapToken[rate.source].minRate = converter.getMinrate(rate.rate, rate.minRate) } else { if (!mapToken[rate.dest]) { mapToken[rate.dest] = {} } mapToken[rate.dest].rateEth = rate.rate mapToken[rate.dest].minRateEth = converter.getMinrate(rate.rate, rate.minRate) } }) //push data var newTokens = {} Object.keys(tokens).map(key => { var token = tokens[key] if (mapToken[key] && mapToken[key].rate) { token.rate = mapToken[key].rate token.minRate = mapToken[key].minRate } if (mapToken[key] && mapToken[key].rateEth) { token.rateEth = mapToken[key].rateEth token.minRateEth = mapToken[key].minRateEth } newTokens[key] = token }) return Object.assign({}, state, { tokens: newTokens }) } case 'GLOBAL.UPDATE_RATE_USD_FULFILLED': { var tokens = { ...state.tokens } var rates = action.payload.rates //map token var mapToken = {} rates.map(rate => { mapToken[rate.symbol] = rate.price_usd }) //push data var newTokens = {} Object.keys(tokens).map(key => { var token = tokens[key] token.rateUSD = mapToken[token.symbol] newTokens[key] = token }) return Object.assign({}, state, { tokens: newTokens }) } case 'GLOBAL.SET_BALANCE_TOKEN':{ const {balances} = action.payload var tokens = { ...state.tokens } Object.keys(balances).map(key => { var token = tokens[key] token.balance = balances[key] tokens[key] = token //newTokens[key] = token }) //var balances = action.payload.balances // var mapBalance = {} // balances.map(balance=>{ // mapBalance[balance.symbol] = balance.balance // }) // var newTokens = {} // Object.keys(tokens).map(key => { // var token = tokens[key] // token.balance = mapBalance[token.symbol] // newTokens[key] = token // }) return Object.assign({}, state, { tokens: tokens }) } case 'EXCHANGE.INIT_PARAMS_EXCHANGE':{ const {tokens, network, listPinTokens, disabledTokens} = action.payload var newTokens = JSON.parse(JSON.stringify(tokens)); const isPinnedTokensEmpty = listPinTokens.length === 0; const isDisabledTokensEmpty = disabledTokens.length === 0; if (BLOCKCHAIN_INFO[network].tokens_gas){ Object.keys(BLOCKCHAIN_INFO[network].tokens_gas).map(key => { if (newTokens[key]){ newTokens[key].gasLimit = BLOCKCHAIN_INFO[network].tokens_gas[key] } }) } if (!isPinnedTokensEmpty || !isDisabledTokensEmpty) { for (let symbol in newTokens) { if (!isPinnedTokensEmpty && symbol != "ETH" && listPinTokens.includes(symbol)) { newTokens[symbol].priority = true; newTokens[symbol].index = listPinTokens.indexOf(symbol); } if (!isDisabledTokensEmpty && disabledTokens.includes(symbol)) { delete newTokens[symbol]; } } } return Object.assign({}, state, { tokens: newTokens }) } case 'GLOBAL.CLEAR_SESSION_FULFILLED': { let tokens = {...state.tokens} Object.keys(state.tokens).forEach((key) => { tokens[key].balance = 0 }) state.tokens = tokens return state } case 'EXCHANGE.SET_APPROVE_TX':{ const {hash, symbol} = action.payload var tokens = { ...state.tokens } tokens[symbol].approveTx = hash console.log(tokens) return Object.assign({}, state, { tokens: tokens }) } case 'EXCHANGE.REMOVE_APPROVE_TX':{ const {symbol} = action.payload var tokens = { ...state.tokens } delete tokens[symbol].approveTx return Object.assign({}, state, { tokens: tokens }) } case 'TOKEN.INIT_LIST_TOKEN':{ const {network} = action.payload var tokens = {} Object.keys(BLOCKCHAIN_INFO[network].tokens).forEach((key) => { tokens[key] = BLOCKCHAIN_INFO[network].tokens[key] tokens[key].rate = 0 tokens[key].minRate = 0 tokens[key].rateEth = 0 tokens[key].minRateEth = 0 tokens[key].balance = 0 tokens[key].rateUSD = 0 // if (pinTokens){ // if(pinTokens.includes(key)){ // tokens[key].priority = true; // tokens[key].index = pinTokens.indexOf(key); // }else{ // tokens[key].priority = false // } // } }) return Object.assign({}, state, { tokens: tokens }) } default: return state } } export {initState, tokens}
(window.webpackJsonp=window.webpackJsonp||[]).push([[2,6],{293:function(n,i,t){},295:function(n,i,t){"use strict";var s=t(293);t.n(s).a},296:function(n,i,t){},299:function(n,i,t){"use strict";t.r(i);var s={data:function(){return{}},components:{},mounted:function(){}},a=(t(295),t(1)),e=Object(a.a)(s,function(){var n=this,i=n.$createElement,t=n._self._c||i;return t("div",[t("p",{staticClass:"htmlshow"},[n._v("HTML")]),n._v(" "),t("pre",{staticClass:"preshow"},[n._v(" "),t("code",{staticClass:"colorf"},[n._v(" \n "),n._t("htmlshow"),n._v("\n ")],2),n._v(" \n ")]),n._v(" "),t("p",{staticClass:"cssshow"},[n._v("CSS")]),n._v(" "),t("pre",{staticClass:"preshow"},[n._v(" "),t("code",{staticClass:"colorf"},[n._v(" \n "),n._t("cssshow"),n._v("\n ")],2),n._v(" \n ")])])},[],!1,null,"49e252c8",null);i.default=e.exports},301:function(n,i,t){"use strict";var s=t(296);t.n(s).a},310:function(n,i,t){"use strict";t.r(i);var s={data:function(){return{htmlshow:'\n <div class="bouncing-loader">\n <div></div>\n <div></div>\n <div></div>\n </div>\n ',htmlcssshow:"\n @keyframes bouncing-loader {\n from {\n opacity: 1;\n transform: translateY(0);\n }\n to {\n opacity: 0.1;\n transform: translateY(-1rem);\n }\n }\n .bouncing-loader {\n display: flex;\n justify-content: center;\n }\n .bouncing-loader > div {\n width: 1rem;\n height: 1rem;\n margin: 3rem 0.2rem;\n background: #409eff;\n border-radius: 50%;\n animation: bouncing-loader 0.6s infinite alternate;\n }\n .bouncing-loader > div:nth-child(2) {\n animation-delay: 0.2s;\n }\n .bouncing-loader > div:nth-child(3) {\n animation-delay: 0.4s;\n }\n ",htmlshow1:'\n <div class="spinner">\n <div class="double-bounce1"></div>\n <div class="double-bounce2"></div>\n </div>\n ',htmlcssshow1:"\n .spinner {\n width: 60px;\n height: 60px;\n position: relative;\n margin: 100px auto;\n }\n \n .double-bounce1, .double-bounce2 {\n width: 100%;\n height: 100%;\n border-radius: 50%;\n background-color: #409eff;\n opacity: 0.6;\n position: absolute;\n top: 0;\n left: 0;\n \n -webkit-animation: bounce 2.0s infinite ease-in-out;\n animation: bounce 2.0s infinite ease-in-out;\n }\n \n .double-bounce2 {\n -webkit-animation-delay: -1.0s;\n animation-delay: -1.0s;\n }\n \n @-webkit-keyframes bounce {\n 0%, 100% { -webkit-transform: scale(0.0) }\n 50% { -webkit-transform: scale(1.0) }\n }\n \n @keyframes bounce {\n 0%, 100% {\n transform: scale(0.0);\n -webkit-transform: scale(0.0);\n } 50% {\n transform: scale(1.0);\n -webkit-transform: scale(1.0);\n }\n }\n ",htmlshow2:'\n <div class="spinnercir">\n <div class="spinnercir-container container1">\n <div class="circle1"></div>\n <div class="circle2"></div>\n <div class="circle3"></div>\n <div class="circle4"></div>\n </div>\n <div class="spinnercir-container container2">\n <div class="circle1"></div>\n <div class="circle2"></div>\n <div class="circle3"></div>\n <div class="circle4"></div>\n </div>\n <div class="spinnercir-container container3">\n <div class="circle1"></div>\n <div class="circle2"></div>\n <div class="circle3"></div>\n <div class="circle4"></div>\n </div>\n </div>\n ',htmlcssshow2:"\n .spinnercir {\n margin: 100px auto;\n width: 40px;\n height: 40px;\n position: relative;\n }\n \n .container1 > div, .container2 > div, .container3 > div {\n width: 10px;\n height: 10px;\n background-color: #409eff;\n \n border-radius: 100%;\n position: absolute;\n -webkit-animation: bouncedelay 1.2s infinite ease-in-out;\n animation: bouncedelay 1.2s infinite ease-in-out;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n \n .spinnercir .spinnercir-container {\n position: absolute;\n width: 100%;\n height: 100%;\n }\n \n .container2 {\n -webkit-transform: rotateZ(45deg);\n transform: rotateZ(45deg);\n }\n \n .container3 {\n -webkit-transform: rotateZ(90deg);\n transform: rotateZ(90deg);\n }\n \n .circle1 { top: 0; left: 0; }\n .circle2 { top: 0; right: 0; }\n .circle3 { right: 0; bottom: 0; }\n .circle4 { left: 0; bottom: 0; }\n \n .container2 .circle1 {\n -webkit-animation-delay: -1.1s;\n animation-delay: -1.1s;\n }\n \n .container3 .circle1 {\n -webkit-animation-delay: -1.0s;\n animation-delay: -1.0s;\n }\n \n .container1 .circle2 {\n -webkit-animation-delay: -0.9s;\n animation-delay: -0.9s;\n }\n \n .container2 .circle2 {\n -webkit-animation-delay: -0.8s;\n animation-delay: -0.8s;\n }\n \n .container3 .circle2 {\n -webkit-animation-delay: -0.7s;\n animation-delay: -0.7s;\n }\n \n .container1 .circle3 {\n -webkit-animation-delay: -0.6s;\n animation-delay: -0.6s;\n }\n \n .container2 .circle3 {\n -webkit-animation-delay: -0.5s;\n animation-delay: -0.5s;\n }\n \n .container3 .circle3 {\n -webkit-animation-delay: -0.4s;\n animation-delay: -0.4s;\n }\n \n .container1 .circle4 {\n -webkit-animation-delay: -0.3s;\n animation-delay: -0.3s;\n }\n \n .container2 .circle4 {\n -webkit-animation-delay: -0.2s;\n animation-delay: -0.2s;\n }\n \n .container3 .circle4 {\n -webkit-animation-delay: -0.1s;\n animation-delay: -0.1s;\n }\n \n @-webkit-keyframes bouncedelay {\n 0%, 80%, 100% { -webkit-transform: scale(0.0) }\n 40% { -webkit-transform: scale(1.0) }\n }\n \n @keyframes bouncedelay {\n 0%, 80%, 100% {\n transform: scale(0.0);\n -webkit-transform: scale(0.0);\n } 40% {\n transform: scale(1.0);\n -webkit-transform: scale(1.0);\n }\n }\n "}},components:{htmlshow:t(299).default}},a=(t(301),t(1)),e=Object(a.a)(s,function(){var n=this,i=n.$createElement,t=n._self._c||i;return t("div",[t("p",{staticClass:"listtip"},[n._v("①")]),n._v(" "),t("hr"),n._v(" "),n._m(0),n._v(" "),t("el-collapse",{attrs:{accordion:""}},[t("el-collapse-item",[t("template",{slot:"title"},[t("span",{staticClass:"btnshow"},[n._v("显示代码")])]),n._v(" "),t("htmlshow",[t("div",{attrs:{slot:"htmlshow"},slot:"htmlshow"},[n._v("\n "+n._s(n.htmlshow)+"\n ")]),n._v(" "),t("div",{attrs:{slot:"cssshow"},slot:"cssshow"},[n._v("\n "+n._s(n.htmlcssshow)+"\n ")])])],2)],1),n._v(" "),t("p",{staticClass:"listtip"},[n._v("②")]),n._v(" "),t("hr"),n._v(" "),n._m(1),n._v(" "),t("el-collapse",{attrs:{accordion:""}},[t("el-collapse-item",[t("template",{slot:"title"},[t("span",{staticClass:"btnshow"},[n._v("显示代码")])]),n._v(" "),t("htmlshow",[t("div",{attrs:{slot:"htmlshow"},slot:"htmlshow"},[n._v("\n "+n._s(n.htmlshow1)+"\n ")]),n._v(" "),t("div",{attrs:{slot:"cssshow"},slot:"cssshow"},[n._v("\n "+n._s(n.htmlcssshow1)+"\n ")])])],2)],1),n._v(" "),t("p",{staticClass:"listtip"},[n._v("③")]),n._v(" "),t("hr"),n._v(" "),n._m(2),n._v(" "),t("el-collapse",{attrs:{accordion:""}},[t("el-collapse-item",[t("template",{slot:"title"},[t("span",{staticClass:"btnshow"},[n._v("显示代码")])]),n._v(" "),t("htmlshow",[t("div",{attrs:{slot:"htmlshow"},slot:"htmlshow"},[n._v("\n "+n._s(n.htmlshow2)+"\n ")]),n._v(" "),t("div",{attrs:{slot:"cssshow"},slot:"cssshow"},[n._v("\n "+n._s(n.htmlcssshow2)+"\n ")])])],2)],1)],1)},[function(){var n=this.$createElement,i=this._self._c||n;return i("div",{staticClass:"bouncing-loader"},[i("div"),this._v(" "),i("div"),this._v(" "),i("div")])},function(){var n=this.$createElement,i=this._self._c||n;return i("div",{staticClass:"spinner"},[i("div",{staticClass:"double-bounce1"}),this._v(" "),i("div",{staticClass:"double-bounce2"})])},function(){var n=this,i=n.$createElement,t=n._self._c||i;return t("div",{staticClass:"spinnercir"},[t("div",{staticClass:"spinnercir-container container1"},[t("div",{staticClass:"circle1"}),n._v(" "),t("div",{staticClass:"circle2"}),n._v(" "),t("div",{staticClass:"circle3"}),n._v(" "),t("div",{staticClass:"circle4"})]),n._v(" "),t("div",{staticClass:"spinnercir-container container2"},[t("div",{staticClass:"circle1"}),n._v(" "),t("div",{staticClass:"circle2"}),n._v(" "),t("div",{staticClass:"circle3"}),n._v(" "),t("div",{staticClass:"circle4"})]),n._v(" "),t("div",{staticClass:"spinnercir-container container3"},[t("div",{staticClass:"circle1"}),n._v(" "),t("div",{staticClass:"circle2"}),n._v(" "),t("div",{staticClass:"circle3"}),n._v(" "),t("div",{staticClass:"circle4"})])])}],!1,null,"61bebd9a",null);i.default=e.exports}}]);
// moment.js language configuration // language : euskara (eu) // author : Eneko Illarramendi : https://github.com/eillarra require('../moment').lang('eu', { months : "urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"), monthsShort : "urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"), weekdays : "igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"), weekdaysShort : "ig._al._ar._az._og._ol._lr.".split("_"), weekdaysMin : "ig_al_ar_az_og_ol_lr".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "YYYYko MMMMren D[a]", LLL : "YYYYko MMMMren D[a] LT", LLLL : "dddd, YYYYko MMMMren D[a] LT", l : "YYYY-M-D", ll : "YYYYko MMM D[a]", lll : "YYYYko MMM D[a] LT", llll : "ddd, YYYYko MMM D[a] LT" }, calendar : { sameDay : '[gaur] LT[etan]', nextDay : '[bihar] LT[etan]', nextWeek : 'dddd LT[etan]', lastDay : '[atzo] LT[etan]', lastWeek : '[aurreko] dddd LT[etan]', sameElse : 'L' }, relativeTime : { future : "%s barru", past : "duela %s", s : "segundo batzuk", m : "minutu bat", mm : "%d minutu", h : "ordu bat", hh : "%d ordu", d : "egun bat", dd : "%d egun", M : "hilabete bat", MM : "%d hilabete", y : "urte bat", yy : "%d urte" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } });
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isnan = require( '@stdlib/math-base-assert-is-nan' ); var pow = require( '@stdlib/math-base-special-pow' ); var SQRT_PI = require( '@stdlib/constants-float64-sqrt-pi' ); var PI = require( '@stdlib/constants-float64-pi' ); // VARIABLES // var SKEWNESS = 2.0 * SQRT_PI * ( PI-3.0 ) / pow( 4.0-PI, 1.5 ); // MAIN // /** * Returns the skewness of a Rayleigh distribution. * * @param {NonNegativeNumber} sigma - scale parameter * @returns {NonNegativeNumber} skewness * * @example * var v = skewness( 9.0 ); * // returns ~0.631 * * @example * var v = skewness( 2.0 ); * // returns ~0.631 * * @example * var v = skewness( -0.2 ); * // returns NaN * * @example * var v = skewness( NaN ); * // returns NaN */ function skewness( sigma ) { if ( isnan( sigma ) || sigma < 0.0 ) { return NaN; } return SKEWNESS; } // EXPORTS // module.exports = skewness;
# pylint:disable=line-too-long import logging from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool from ...calling_conventions import SimCCStdcall, SimCCMicrosoftAMD64 from .. import SIM_PROCEDURES as P from . import SimLibrary _l = logging.getLogger(name=__name__) lib = SimLibrary() lib.set_default_cc('X86', SimCCStdcall) lib.set_default_cc('AMD64', SimCCMicrosoftAMD64) lib.set_library_names("imm32.dll") prototypes = \ { # 'ImmInstallIMEA': SimTypeFunction([SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypeChar(label="Byte"), offset=0)], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["lpszIMEFileName", "lpszLayoutText"]), # 'ImmInstallIMEW': SimTypeFunction([SimTypePointer(SimTypeChar(label="Char"), offset=0), SimTypePointer(SimTypeChar(label="Char"), offset=0)], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["lpszIMEFileName", "lpszLayoutText"]), # 'ImmGetDefaultIMEWnd': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["param0"]), # 'ImmGetDescriptionA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeChar(label="Byte"), label="LPArray", offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "lpszDescription", "uBufLen"]), # 'ImmGetDescriptionW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeChar(label="Char"), label="LPArray", offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "lpszDescription", "uBufLen"]), # 'ImmGetIMEFileNameA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeChar(label="Byte"), label="LPArray", offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "lpszFileName", "uBufLen"]), # 'ImmGetIMEFileNameW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeChar(label="Char"), label="LPArray", offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "lpszFileName", "uBufLen"]), # 'ImmGetProperty': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "param1"]), # 'ImmIsIME': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0"]), # 'ImmSimulateHotKey': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1"]), # 'ImmCreateContext': SimTypeFunction([], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)), # 'ImmDestroyContext': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0"]), # 'ImmGetContext': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["param0"]), # 'ImmReleaseContext': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1"]), # 'ImmAssociateContext': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["param0", "param1"]), # 'ImmAssociateContextEx': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1", "param2"]), # 'ImmGetCompositionStringA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1", "lpBuf", "dwBufLen"]), # 'ImmGetCompositionStringW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1", "lpBuf", "dwBufLen"]), # 'ImmSetCompositionStringA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="SET_COMPOSITION_STRING_TYPE"), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "dwIndex", "lpComp", "dwCompLen", "lpRead", "dwReadLen"]), # 'ImmSetCompositionStringW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="SET_COMPOSITION_STRING_TYPE"), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "dwIndex", "lpComp", "dwCompLen", "lpRead", "dwReadLen"]), # 'ImmGetCandidateListCountA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0)], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "lpdwListCount"]), # 'ImmGetCandidateListCountW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0)], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "lpdwListCount"]), # 'ImmGetCandidateListA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimStruct({"dwSize": SimTypeInt(signed=False, label="UInt32"), "dwStyle": SimTypeInt(signed=False, label="UInt32"), "dwCount": SimTypeInt(signed=False, label="UInt32"), "dwSelection": SimTypeInt(signed=False, label="UInt32"), "dwPageStart": SimTypeInt(signed=False, label="UInt32"), "dwPageSize": SimTypeInt(signed=False, label="UInt32"), "dwOffset": SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0)}, name="CANDIDATELIST", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "deIndex", "lpCandList", "dwBufLen"]), # 'ImmGetCandidateListW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimStruct({"dwSize": SimTypeInt(signed=False, label="UInt32"), "dwStyle": SimTypeInt(signed=False, label="UInt32"), "dwCount": SimTypeInt(signed=False, label="UInt32"), "dwSelection": SimTypeInt(signed=False, label="UInt32"), "dwPageStart": SimTypeInt(signed=False, label="UInt32"), "dwPageSize": SimTypeInt(signed=False, label="UInt32"), "dwOffset": SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0)}, name="CANDIDATELIST", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "deIndex", "lpCandList", "dwBufLen"]), # 'ImmGetGuideLineA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="GET_GUIDE_LINE_TYPE"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "dwIndex", "lpBuf", "dwBufLen"]), # 'ImmGetGuideLineW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="GET_GUIDE_LINE_TYPE"), SimTypePointer(SimTypeChar(label="Char"), offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "dwIndex", "lpBuf", "dwBufLen"]), # 'ImmGetConversionStatus': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lpfdwConversion", "lpfdwSentence"]), # 'ImmSetConversionStatus': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1", "param2"]), # 'ImmGetOpenStatus': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0"]), # 'ImmSetOpenStatus': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=True, label="Int32")], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1"]), # 'ImmGetCompositionFontA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimStruct({"lfHeight": SimTypeInt(signed=True, label="Int32"), "lfWidth": SimTypeInt(signed=True, label="Int32"), "lfEscapement": SimTypeInt(signed=True, label="Int32"), "lfOrientation": SimTypeInt(signed=True, label="Int32"), "lfWeight": SimTypeInt(signed=True, label="Int32"), "lfItalic": SimTypeChar(label="Byte"), "lfUnderline": SimTypeChar(label="Byte"), "lfStrikeOut": SimTypeChar(label="Byte"), "lfCharSet": SimTypeChar(label="Byte"), "lfOutPrecision": SimTypeChar(label="Byte"), "lfClipPrecision": SimTypeChar(label="Byte"), "lfQuality": SimTypeChar(label="Byte"), "lfPitchAndFamily": SimTypeChar(label="Byte"), "lfFaceName": SimTypeFixedSizeArray(SimTypeBottom(label="CHAR"), 32)}, name="LOGFONTA", pack=False, align=None), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lplf"]), # 'ImmGetCompositionFontW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimStruct({"lfHeight": SimTypeInt(signed=True, label="Int32"), "lfWidth": SimTypeInt(signed=True, label="Int32"), "lfEscapement": SimTypeInt(signed=True, label="Int32"), "lfOrientation": SimTypeInt(signed=True, label="Int32"), "lfWeight": SimTypeInt(signed=True, label="Int32"), "lfItalic": SimTypeChar(label="Byte"), "lfUnderline": SimTypeChar(label="Byte"), "lfStrikeOut": SimTypeChar(label="Byte"), "lfCharSet": SimTypeChar(label="Byte"), "lfOutPrecision": SimTypeChar(label="Byte"), "lfClipPrecision": SimTypeChar(label="Byte"), "lfQuality": SimTypeChar(label="Byte"), "lfPitchAndFamily": SimTypeChar(label="Byte"), "lfFaceName": SimTypeFixedSizeArray(SimTypeChar(label="Char"), 32)}, name="LOGFONTW", pack=False, align=None), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lplf"]), # 'ImmSetCompositionFontA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimStruct({"lfHeight": SimTypeInt(signed=True, label="Int32"), "lfWidth": SimTypeInt(signed=True, label="Int32"), "lfEscapement": SimTypeInt(signed=True, label="Int32"), "lfOrientation": SimTypeInt(signed=True, label="Int32"), "lfWeight": SimTypeInt(signed=True, label="Int32"), "lfItalic": SimTypeChar(label="Byte"), "lfUnderline": SimTypeChar(label="Byte"), "lfStrikeOut": SimTypeChar(label="Byte"), "lfCharSet": SimTypeChar(label="Byte"), "lfOutPrecision": SimTypeChar(label="Byte"), "lfClipPrecision": SimTypeChar(label="Byte"), "lfQuality": SimTypeChar(label="Byte"), "lfPitchAndFamily": SimTypeChar(label="Byte"), "lfFaceName": SimTypeFixedSizeArray(SimTypeBottom(label="CHAR"), 32)}, name="LOGFONTA", pack=False, align=None), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lplf"]), # 'ImmSetCompositionFontW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimStruct({"lfHeight": SimTypeInt(signed=True, label="Int32"), "lfWidth": SimTypeInt(signed=True, label="Int32"), "lfEscapement": SimTypeInt(signed=True, label="Int32"), "lfOrientation": SimTypeInt(signed=True, label="Int32"), "lfWeight": SimTypeInt(signed=True, label="Int32"), "lfItalic": SimTypeChar(label="Byte"), "lfUnderline": SimTypeChar(label="Byte"), "lfStrikeOut": SimTypeChar(label="Byte"), "lfCharSet": SimTypeChar(label="Byte"), "lfOutPrecision": SimTypeChar(label="Byte"), "lfClipPrecision": SimTypeChar(label="Byte"), "lfQuality": SimTypeChar(label="Byte"), "lfPitchAndFamily": SimTypeChar(label="Byte"), "lfFaceName": SimTypeFixedSizeArray(SimTypeChar(label="Char"), 32)}, name="LOGFONTW", pack=False, align=None), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lplf"]), # 'ImmConfigureIMEA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeBottom(label="Void"), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1", "param2", "param3"]), # 'ImmConfigureIMEW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeBottom(label="Void"), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1", "param2", "param3"]), # 'ImmEscapeA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeBottom(label="Void"), offset=0)], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["param0", "param1", "param2", "param3"]), # 'ImmEscapeW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeBottom(label="Void"), offset=0)], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["param0", "param1", "param2", "param3"]), # 'ImmGetConversionListA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimStruct({"dwSize": SimTypeInt(signed=False, label="UInt32"), "dwStyle": SimTypeInt(signed=False, label="UInt32"), "dwCount": SimTypeInt(signed=False, label="UInt32"), "dwSelection": SimTypeInt(signed=False, label="UInt32"), "dwPageStart": SimTypeInt(signed=False, label="UInt32"), "dwPageSize": SimTypeInt(signed=False, label="UInt32"), "dwOffset": SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0)}, name="CANDIDATELIST", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypeInt(signed=False, label="GET_CONVERSION_LIST_FLAG")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "param1", "lpSrc", "lpDst", "dwBufLen", "uFlag"]), # 'ImmGetConversionListW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeChar(label="Char"), offset=0), SimTypePointer(SimStruct({"dwSize": SimTypeInt(signed=False, label="UInt32"), "dwStyle": SimTypeInt(signed=False, label="UInt32"), "dwCount": SimTypeInt(signed=False, label="UInt32"), "dwSelection": SimTypeInt(signed=False, label="UInt32"), "dwPageStart": SimTypeInt(signed=False, label="UInt32"), "dwPageSize": SimTypeInt(signed=False, label="UInt32"), "dwOffset": SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0)}, name="CANDIDATELIST", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypeInt(signed=False, label="GET_CONVERSION_LIST_FLAG")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "param1", "lpSrc", "lpDst", "dwBufLen", "uFlag"]), # 'ImmNotifyIME': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="NOTIFY_IME_ACTION"), SimTypeInt(signed=False, label="NOTIFY_IME_INDEX"), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "dwAction", "dwIndex", "dwValue"]), # 'ImmGetStatusWindowPos': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimStruct({"x": SimTypeInt(signed=True, label="Int32"), "y": SimTypeInt(signed=True, label="Int32")}, name="POINT", pack=False, align=None), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lpptPos"]), # 'ImmSetStatusWindowPos': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimStruct({"x": SimTypeInt(signed=True, label="Int32"), "y": SimTypeInt(signed=True, label="Int32")}, name="POINT", pack=False, align=None), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lpptPos"]), # 'ImmGetCompositionWindow': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimStruct({"dwStyle": SimTypeInt(signed=False, label="UInt32"), "ptCurrentPos": SimStruct({"x": SimTypeInt(signed=True, label="Int32"), "y": SimTypeInt(signed=True, label="Int32")}, name="POINT", pack=False, align=None), "rcArea": SimStruct({"left": SimTypeInt(signed=True, label="Int32"), "top": SimTypeInt(signed=True, label="Int32"), "right": SimTypeInt(signed=True, label="Int32"), "bottom": SimTypeInt(signed=True, label="Int32")}, name="RECT", pack=False, align=None)}, name="COMPOSITIONFORM", pack=False, align=None), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lpCompForm"]), # 'ImmSetCompositionWindow': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimStruct({"dwStyle": SimTypeInt(signed=False, label="UInt32"), "ptCurrentPos": SimStruct({"x": SimTypeInt(signed=True, label="Int32"), "y": SimTypeInt(signed=True, label="Int32")}, name="POINT", pack=False, align=None), "rcArea": SimStruct({"left": SimTypeInt(signed=True, label="Int32"), "top": SimTypeInt(signed=True, label="Int32"), "right": SimTypeInt(signed=True, label="Int32"), "bottom": SimTypeInt(signed=True, label="Int32")}, name="RECT", pack=False, align=None)}, name="COMPOSITIONFORM", pack=False, align=None), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lpCompForm"]), # 'ImmGetCandidateWindow': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimStruct({"dwIndex": SimTypeInt(signed=False, label="UInt32"), "dwStyle": SimTypeInt(signed=False, label="UInt32"), "ptCurrentPos": SimStruct({"x": SimTypeInt(signed=True, label="Int32"), "y": SimTypeInt(signed=True, label="Int32")}, name="POINT", pack=False, align=None), "rcArea": SimStruct({"left": SimTypeInt(signed=True, label="Int32"), "top": SimTypeInt(signed=True, label="Int32"), "right": SimTypeInt(signed=True, label="Int32"), "bottom": SimTypeInt(signed=True, label="Int32")}, name="RECT", pack=False, align=None)}, name="CANDIDATEFORM", pack=False, align=None), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1", "lpCandidate"]), # 'ImmSetCandidateWindow': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimStruct({"dwIndex": SimTypeInt(signed=False, label="UInt32"), "dwStyle": SimTypeInt(signed=False, label="UInt32"), "ptCurrentPos": SimStruct({"x": SimTypeInt(signed=True, label="Int32"), "y": SimTypeInt(signed=True, label="Int32")}, name="POINT", pack=False, align=None), "rcArea": SimStruct({"left": SimTypeInt(signed=True, label="Int32"), "top": SimTypeInt(signed=True, label="Int32"), "right": SimTypeInt(signed=True, label="Int32"), "bottom": SimTypeInt(signed=True, label="Int32")}, name="RECT", pack=False, align=None)}, name="CANDIDATEFORM", pack=False, align=None), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lpCandidate"]), # 'ImmIsUIMessageA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeInt(signed=False, label="UInt"), label="UIntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1", "param2", "param3"]), # 'ImmIsUIMessageW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeInt(signed=False, label="UInt"), label="UIntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1", "param2", "param3"]), # 'ImmGetVirtualKey': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0"]), # 'ImmRegisterWordA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lpszReading", "param2", "lpszRegister"]), # 'ImmRegisterWordW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeChar(label="Char"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Char"), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lpszReading", "param2", "lpszRegister"]), # 'ImmUnregisterWordA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lpszReading", "param2", "lpszUnregister"]), # 'ImmUnregisterWordW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeChar(label="Char"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Char"), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lpszReading", "param2", "lpszUnregister"]), # 'ImmGetRegisterWordStyleA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimStruct({"dwStyle": SimTypeInt(signed=False, label="UInt32"), "szDescription": SimTypeFixedSizeArray(SimTypeBottom(label="CHAR"), 32)}, name="STYLEBUFA", pack=False, align=None), label="LPArray", offset=0)], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "nItem", "lpStyleBuf"]), # 'ImmGetRegisterWordStyleW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimStruct({"dwStyle": SimTypeInt(signed=False, label="UInt32"), "szDescription": SimTypeFixedSizeArray(SimTypeChar(label="Char"), 32)}, name="STYLEBUFW", pack=False, align=None), label="LPArray", offset=0)], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "nItem", "lpStyleBuf"]), # 'ImmEnumRegisterWordA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeFunction([SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["lpszReading", "param1", "lpszString", "param3"]), offset=0), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0)], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "param1", "lpszReading", "param3", "lpszRegister", "param5"]), # 'ImmEnumRegisterWordW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeFunction([SimTypePointer(SimTypeChar(label="Char"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Char"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["lpszReading", "param1", "lpszString", "param3"]), offset=0), SimTypePointer(SimTypeChar(label="Char"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Char"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0)], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "param1", "lpszReading", "param3", "lpszRegister", "param5"]), # 'ImmDisableIME': SimTypeFunction([SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=True, label="Int32"), arg_names=["param0"]), # 'ImmEnumInputContext': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1"]), offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["idThread", "lpfn", "lParam"]), # 'ImmGetImeMenuItemsA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimStruct({"cbSize": SimTypeInt(signed=False, label="UInt32"), "fType": SimTypeInt(signed=False, label="UInt32"), "fState": SimTypeInt(signed=False, label="UInt32"), "wID": SimTypeInt(signed=False, label="UInt32"), "hbmpChecked": SimTypeBottom(label="HBITMAP"), "hbmpUnchecked": SimTypeBottom(label="HBITMAP"), "dwItemData": SimTypeInt(signed=False, label="UInt32"), "szString": SimTypeFixedSizeArray(SimTypeBottom(label="CHAR"), 80), "hbmpItem": SimTypeBottom(label="HBITMAP")}, name="IMEMENUITEMINFOA", pack=False, align=None), offset=0), SimTypePointer(SimStruct({"cbSize": SimTypeInt(signed=False, label="UInt32"), "fType": SimTypeInt(signed=False, label="UInt32"), "fState": SimTypeInt(signed=False, label="UInt32"), "wID": SimTypeInt(signed=False, label="UInt32"), "hbmpChecked": SimTypeBottom(label="HBITMAP"), "hbmpUnchecked": SimTypeBottom(label="HBITMAP"), "dwItemData": SimTypeInt(signed=False, label="UInt32"), "szString": SimTypeFixedSizeArray(SimTypeBottom(label="CHAR"), 80), "hbmpItem": SimTypeBottom(label="HBITMAP")}, name="IMEMENUITEMINFOA", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "param1", "param2", "lpImeParentMenu", "lpImeMenu", "dwSize"]), # 'ImmGetImeMenuItemsW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimStruct({"cbSize": SimTypeInt(signed=False, label="UInt32"), "fType": SimTypeInt(signed=False, label="UInt32"), "fState": SimTypeInt(signed=False, label="UInt32"), "wID": SimTypeInt(signed=False, label="UInt32"), "hbmpChecked": SimTypeBottom(label="HBITMAP"), "hbmpUnchecked": SimTypeBottom(label="HBITMAP"), "dwItemData": SimTypeInt(signed=False, label="UInt32"), "szString": SimTypeFixedSizeArray(SimTypeChar(label="Char"), 80), "hbmpItem": SimTypeBottom(label="HBITMAP")}, name="IMEMENUITEMINFOW", pack=False, align=None), offset=0), SimTypePointer(SimStruct({"cbSize": SimTypeInt(signed=False, label="UInt32"), "fType": SimTypeInt(signed=False, label="UInt32"), "fState": SimTypeInt(signed=False, label="UInt32"), "wID": SimTypeInt(signed=False, label="UInt32"), "hbmpChecked": SimTypeBottom(label="HBITMAP"), "hbmpUnchecked": SimTypeBottom(label="HBITMAP"), "dwItemData": SimTypeInt(signed=False, label="UInt32"), "szString": SimTypeFixedSizeArray(SimTypeChar(label="Char"), 80), "hbmpItem": SimTypeBottom(label="HBITMAP")}, name="IMEMENUITEMINFOW", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0", "param1", "param2", "lpImeParentMenu", "lpImeMenu", "dwSize"]), # 'ImmDisableTextFrameService': SimTypeFunction([SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=True, label="Int32"), arg_names=["idThread"]), # 'ImmDisableLegacyIME': SimTypeFunction([], SimTypeInt(signed=True, label="Int32")), # 'ImmGetHotKey': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0), SimTypePointer(SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "lpuModifiers", "lpuVKey", "phKL"]), # 'ImmSetHotKey': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypeInt(signed=False, label="UInt32"), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1", "param2", "param3"]), # 'ImmGenerateMessage': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0"]), # 'ImmRequestMessageA': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=False, label="UInt"), label="UIntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["param0", "param1", "param2"]), # 'ImmRequestMessageW': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypePointer(SimTypeInt(signed=False, label="UInt"), label="UIntPtr", offset=0), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["param0", "param1", "param2"]), # 'ImmCreateSoftKeyboard': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=True, label="Int32"), SimTypeInt(signed=True, label="Int32")], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["param0", "param1", "param2", "param3"]), # 'ImmDestroySoftKeyboard': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0"]), # 'ImmShowSoftKeyboard': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=True, label="Int32")], SimTypeInt(signed=True, label="Int32"), arg_names=["param0", "param1"]), # 'ImmLockIMC': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypePointer(SimStruct({"hWnd": SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), "fOpen": SimTypeInt(signed=True, label="Int32"), "ptStatusWndPos": SimStruct({"x": SimTypeInt(signed=True, label="Int32"), "y": SimTypeInt(signed=True, label="Int32")}, name="POINT", pack=False, align=None), "ptSoftKbdPos": SimStruct({"x": SimTypeInt(signed=True, label="Int32"), "y": SimTypeInt(signed=True, label="Int32")}, name="POINT", pack=False, align=None), "fdwConversion": SimTypeInt(signed=False, label="UInt32"), "fdwSentence": SimTypeInt(signed=False, label="UInt32"), "lfFont": SimUnion({"A": SimTypeBottom(label="LOGFONTA"), "W": SimTypeBottom(label="LOGFONTW")}, name="<anon>", label="None"), "cfCompForm": SimStruct({"dwStyle": SimTypeInt(signed=False, label="UInt32"), "ptCurrentPos": SimStruct({"x": SimTypeInt(signed=True, label="Int32"), "y": SimTypeInt(signed=True, label="Int32")}, name="POINT", pack=False, align=None), "rcArea": SimStruct({"left": SimTypeInt(signed=True, label="Int32"), "top": SimTypeInt(signed=True, label="Int32"), "right": SimTypeInt(signed=True, label="Int32"), "bottom": SimTypeInt(signed=True, label="Int32")}, name="RECT", pack=False, align=None)}, name="COMPOSITIONFORM", pack=False, align=None), "cfCandForm": SimTypeFixedSizeArray(SimStruct({"dwIndex": SimTypeInt(signed=False, label="UInt32"), "dwStyle": SimTypeInt(signed=False, label="UInt32"), "ptCurrentPos": SimStruct({"x": SimTypeInt(signed=True, label="Int32"), "y": SimTypeInt(signed=True, label="Int32")}, name="POINT", pack=False, align=None), "rcArea": SimStruct({"left": SimTypeInt(signed=True, label="Int32"), "top": SimTypeInt(signed=True, label="Int32"), "right": SimTypeInt(signed=True, label="Int32"), "bottom": SimTypeInt(signed=True, label="Int32")}, name="RECT", pack=False, align=None)}, name="CANDIDATEFORM", pack=False, align=None), 4), "hCompStr": SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), "hCandInfo": SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), "hGuideLine": SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), "hPrivate": SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), "dwNumMsgBuf": SimTypeInt(signed=False, label="UInt32"), "hMsgBuf": SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), "fdwInit": SimTypeInt(signed=False, label="UInt32"), "dwReserve": SimTypeFixedSizeArray(SimTypeInt(signed=False, label="UInt32"), 3)}, name="INPUTCONTEXT", pack=False, align=None), offset=0), arg_names=["param0"]), # 'ImmUnlockIMC': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0"]), # 'ImmGetIMCLockCount': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0"]), # 'ImmCreateIMCC': SimTypeFunction([SimTypeInt(signed=False, label="UInt32")], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["param0"]), # 'ImmDestroyIMCC': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["param0"]), # 'ImmLockIMCC': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypePointer(SimTypeBottom(label="Void"), offset=0), arg_names=["param0"]), # 'ImmUnlockIMCC': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=True, label="Int32"), arg_names=["param0"]), # 'ImmGetIMCCLockCount': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0"]), # 'ImmReSizeIMCC': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["param0", "param1"]), # 'ImmGetIMCCSize': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0)], SimTypeInt(signed=False, label="UInt32"), arg_names=["param0"]), } lib.set_prototypes(prototypes)
import { getFragmentByHash, toBoolean } from '../utils/utils'; export default { props: { type: { type: String, default: null, }, expandable: { type: Boolean, default: true, }, isOpen: { type: Boolean, default: null, }, expanded: { type: Boolean, default: null, }, minimized: { type: Boolean, default: false, }, noSwitch: { type: Boolean, default: false, }, noClose: { type: Boolean, default: false, }, popupUrl: { type: String, default: null, }, src: { type: String, }, bottomSwitch: { type: Boolean, default: true, }, preload: { type: Boolean, default: false, }, addClass: { type: String, default: '', }, expandHeaderless: { type: Boolean, default: false, }, peek: { type: Boolean, default: false, }, }, computed: { // Vue 2.0 coerce migration expandableBool() { return toBoolean(this.expandable); }, isOpenBool() { return toBoolean(this.isOpen); }, expandedBool() { return toBoolean(this.expanded); }, minimizedBool() { return toBoolean(this.minimized); }, noSwitchBool() { return toBoolean(this.noSwitch); }, noCloseBool() { return toBoolean(this.noClose); }, bottomSwitchBool() { return toBoolean(this.bottomSwitch); }, preloadBool() { return toBoolean(this.preload); }, // Vue 2.0 coerce migration end hasHeaderBool() { return this.$scopedSlots.header; }, isExpandableCard() { return this.expandableBool; }, hasSrc() { return this.src && this.src.length > 0; }, srcWithoutFragment() { return this.src.split('#')[0]; }, shouldShowHeader() { return (!this.localExpanded) || (!this.expandHeaderless); }, shouldShowPeek() { return this.peek && !this.localExpanded; }, collapsedPanelHeight() { return this.peek ? 125 : 0; }, }, data() { return { localExpanded: false, localMinimized: false, wasRetrieverLoaded: false, isRetrieverLoadDone: !this.src, // Load is done by default if there is no src fragment: '', }; }, methods: { toggle() { if (!this.wasRetrieverLoaded) { this.open(); return; } if (this.localExpanded) { /* Collapse panel. Panel's maxHeight is 'none' at the moment, as event listener set it to 'none' after expansion. Thus, we need to reset the maxHeight to its current height for collapse transition to work. */ this.$refs.panel.style.maxHeight = `${this.$refs.panel.scrollHeight}px`; requestAnimationFrame(() => { // To enable behaviour of auto window scrolling during panel collapse if (this.$el.getBoundingClientRect().top < 0) { jQuery('html').animate({ scrollTop: window.scrollY + this.$el.getBoundingClientRect().top - 3, }, 500, 'swing'); } this.$refs.panel.style.maxHeight = `${this.collapsedPanelHeight}px`; }); } else { // Expand panel this.$refs.panel.style.maxHeight = `${this.$refs.panel.scrollHeight}px`; } this.localExpanded = !this.localExpanded; }, close() { this.localMinimized = true; this.localExpanded = false; }, open() { this.localMinimized = false; /* After setting minimized to false, we have to wait for panel to be rendered in the DOM update (nextTick) before we can initialize the panel with event listeners. */ this.$nextTick(() => { this.initPanel(); this.localExpanded = true; this.wasRetrieverLoaded = true; /* After setting wasRetrieverLoaded to true, we have to wait for DOM update (nextTick) before setting maxHeight for transition. */ this.$nextTick(() => { this.$refs.panel.style.maxHeight = `${this.$refs.panel.scrollHeight}px`; }); }); }, openPopup() { window.open(this.popupUrl); }, retrieverUpdateMaxHeight() { // src has finished loaded -- we set this flag to true so our event listener can set maxHeight to none this.isRetrieverLoadDone = true; if (!this.localExpanded) { return; } // Don't play the transition for this case as the loading should feel 'instant'. if (this.expandedBool) { this.$refs.panel.style.maxHeight = 'none'; return; } // For expansion transition to 'continue' after src is loaded. this.$refs.panel.style.maxHeight = `${this.$refs.panel.scrollHeight}px`; }, initPanel() { this.$refs.panel.addEventListener('transitionend', (event) => { /* If the panel's content grows, its maxHeight should accomodate it accordingly (e.g. nested panels). However, if the panel has a 'src' attribute and it has not finished loading, then this is delegated later to the retriever src-loaded event handler, allowing a second maxHeight transition once it is loaded. */ if (this.localExpanded && this.isRetrieverLoadDone && event.target === this.$refs.panel) { this.$refs.panel.style.maxHeight = 'none'; } }); // Set the initial height of panel. if (this.localExpanded) { /* User has indicated expanded option for the panel. We have to set the maxHeight to none immediately since there won't be any transitions to trigger the event listener to set maxHeight to none. */ this.$refs.panel.style.maxHeight = 'none'; } else { this.$refs.panel.style.maxHeight = `${this.collapsedPanelHeight}px`; } }, }, created() { if (this.src) { const hash = getFragmentByHash(this.src); if (hash) { this.fragment = hash; } } // Edge case where user might want non-expandable card that isn't expanded by default const notExpandableNoExpand = !this.expandableBool && this.expanded !== 'false'; // Set local data to computed prop value // Ensure this expr ordering is maintained this.localExpanded = notExpandableNoExpand || this.expandedBool; if (this.localExpanded === null) { this.localExpanded = false; } this.wasRetrieverLoaded = this.localExpanded || this.peek; this.localMinimized = this.minimizedBool; }, mounted() { if (!this.localMinimized) { this.initPanel(); } }, };