hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
fee55807eced1a54a7ce9d416954765d0c6eb561
533
js
JavaScript
example.js
metrico/node-logql
c4f97ca6b003fc8d3eb2c49d99ea3873befd81be
[ "Apache-2.0" ]
5
2021-12-06T23:51:43.000Z
2022-01-27T01:33:08.000Z
example.js
metrico/node-logql
c4f97ca6b003fc8d3eb2c49d99ea3873befd81be
[ "Apache-2.0" ]
null
null
null
example.js
metrico/node-logql
c4f97ca6b003fc8d3eb2c49d99ea3873befd81be
[ "Apache-2.0" ]
null
null
null
const logql = require('./'); process.argv.splice(0, 2); var query = process.argv[0] || `{job="cortex-ops/query-frontend"} |= "logging.go" | logfmt | line_format "{{.msg}}"` var logline = process.argv[1] || `level=debug ts=2020-10-02T10:10:42.092268913Z caller=logging.go:66 traceID=a9d4d8a928d8db1 msg="POST /api/prom/api/v1/query_range (200) 1.5s"` try { const parsed = logql.parse(query, logline); console.log("query:", query); console.log("log:", logline); console.log("output:", parsed); } catch(e){ console.log(e); }
38.071429
176
0.673546
fee6fe329b16594cd63743f8c808a167496da815
291
js
JavaScript
test/fixtures/Brocfile.js
benignware/broccoli-extract-comments
0eb2ac5c4bb6cca6726b2c2f8e914ef8686d5c4a
[ "MIT" ]
null
null
null
test/fixtures/Brocfile.js
benignware/broccoli-extract-comments
0eb2ac5c4bb6cca6726b2c2f8e914ef8686d5c4a
[ "MIT" ]
null
null
null
test/fixtures/Brocfile.js
benignware/broccoli-extract-comments
0eb2ac5c4bb6cca6726b2c2f8e914ef8686d5c4a
[ "MIT" ]
null
null
null
var extractComments = require('../..'); var commentsTree = extractComments('src', { /*filter: function(comment) { return comment.text.indexOf('Hello World!') >= 0; },*/ /*raw: true,*/ inputFiles: [ '**.*' ], outputFile: 'comments.txt' }); module.exports = commentsTree;
20.785714
53
0.608247
fee76133982e6d95e7fed141487a565e6ebc256e
179
js
JavaScript
src/webui/utils/sec-utils.js
abc3660170/pelipper-ui
399cf9d44045d233774401eeae4a30bf8e7e1aeb
[ "MIT" ]
2
2019-05-03T14:35:44.000Z
2019-10-16T00:18:00.000Z
src/webui/utils/sec-utils.js
abc3660170/pelipper-ui
399cf9d44045d233774401eeae4a30bf8e7e1aeb
[ "MIT" ]
null
null
null
src/webui/utils/sec-utils.js
abc3660170/pelipper-ui
399cf9d44045d233774401eeae4a30bf8e7e1aeb
[ "MIT" ]
null
null
null
/** * @prettier * @flow */ // $FlowFixMe import parseXSS from 'xss'; export function preventXSS(text: string) { const encodedText = parseXSS(text); return encodedText; }
13.769231
42
0.675978
fee885477a95162fb03ef1d8678fb5b237a4f776
5,723
js
JavaScript
packages/resolve-url-loader-filesearch/index.js.js
jigs1212/resolve-url-loader
3b8e300b6318d5ccd8ce2f5751148c5ea6042428
[ "MIT" ]
null
null
null
packages/resolve-url-loader-filesearch/index.js.js
jigs1212/resolve-url-loader
3b8e300b6318d5ccd8ce2f5751148c5ea6042428
[ "MIT" ]
null
null
null
packages/resolve-url-loader-filesearch/index.js.js
jigs1212/resolve-url-loader
3b8e300b6318d5ccd8ce2f5751148c5ea6042428
[ "MIT" ]
null
null
null
/* * MIT License http://opensource.org/licenses/MIT * Author: Ben Holloway @bholloway */ 'use strict'; var fs = require('fs'), path = require('path'); var PACKAGE_NAME = require('./package.json').name; /** * Factory for find-file with the given <code>options</code> hash. * @param {{debug:boolean, root:string, includeRoot:boolean, attempts:number}} options Options hash */ function fileSearch(options) { var resolvedRoot = options.root && path.resolve(options.root) || process.cwd(); var log = (typeof options.debug === 'function') && options.debug || !!options.debug && console.log; return absolute; /** * Search for the relative file reference from the <code>startPath</code> up to the process * working directory, avoiding any other directories with a <code>package.json</code> or <code>bower.json</code>. * @param {string} startPath The location of the uri declaration and the place to start the search from * @param {string} uri The content of the url() statement, expected to be a relative file path * @returns {string|null} <code>null</code> where not found else the absolute path to the file */ function absolute(startPath, uri) { var basePath = base(startPath, uri); return !!basePath && path.resolve(basePath, uri) || null; } /** * Search for the relative file reference from the <code>startPath</code> up to the process * working directory, avoiding any other directories with a <code>package.json</code> or <code>bower.json</code>. * @param {string} startPath The location of the uri declaration and the place to start the search from * @param {string} uri The content of the url() statement, expected to be a relative file path * @returns {string|null} <code>null</code> where not found else the base path upon which the uri may be resolved */ function base(startPath, uri) { var messages = []; // #69 limit searching: make at least one attempt var remaining = Math.max(0, options.attempts) || 1E+9; // ignore explicit URLs and ensure we are at a valid start path var absoluteStart = path.resolve(startPath); // find path to the root, stopping at cwd, package.json or bower.json var pathToRoot = []; var isWorking; do { pathToRoot.push(absoluteStart); isWorking = testWithinLimit(absoluteStart) && testNotPackage(absoluteStart); absoluteStart = path.resolve(absoluteStart, '..'); } while (isWorking); // #62 support stylus nib: optionally force that path to include the root var appendRoot = options.includeRoot && (pathToRoot.indexOf(resolvedRoot) < 0); var queue = pathToRoot.concat(appendRoot ? resolvedRoot : []); // the queue pattern ensures that we favour paths closest the the start path // process the queue until empty or until we exhaust our attempts while (queue.length && (remaining-- > 0)) { // shift the first item off the queue, consider it the base for our relative uri var basePath = queue.shift(); var fullPath = path.resolve(basePath, uri); messages.push(basePath); // file exists so end if (fs.existsSync(fullPath)) { flushMessages('FOUND'); return basePath; } // enqueue subdirectories that are not packages and are not in the root path else { enqueue(queue, basePath); } } // interrupted by options.attempts if (queue.length) { flushMessages('NOT FOUND (INTERRUPTED)'); } // not found else { flushMessages('NOT FOUND'); return null; } /** * Enqueue subdirectories that are not packages and are not in the root path * @param {Array} queue The queue to add to * @param {string} basePath The path to consider */ function enqueue(queue, basePath) { fs.readdirSync(basePath) .filter(function notHidden(filename) { return (filename.charAt(0) !== '.'); }) .map(function toAbsolute(filename) { return path.join(basePath, filename); }) .filter(function directoriesOnly(absolutePath) { return fs.existsSync(absolutePath) && fs.statSync(absolutePath).isDirectory(); }) .filter(function notInRootPath(absolutePath) { return (pathToRoot.indexOf(absolutePath) < 0); }) .filter(testNotPackage) .forEach(function enqueue(absolutePath) { queue.push(absolutePath); }); } /** * Test whether the given directory is above but not equal to any of the project root directories. * @param {string} absolutePath An absolute path * @returns {boolean} True where a package.json or bower.json exists, else False */ function testWithinLimit(absolutePath) { var relative = path.relative(resolvedRoot, absolutePath); return !!relative && (relative.slice(0, 2) !== '..'); } /** * Print verbose debug info where <code>options.debug</code> is in effect. * @param {string} result Final text to append to the message */ function flushMessages(result) { if (log) { var text = ['\n' + PACKAGE_NAME + ': ' + uri] .concat(messages) .concat(result) .join('\n '); log(text); } } } /** * Test whether the given directory is the root of its own package. * @param {string} absolutePath An absolute path * @returns {boolean} True where a package.json or bower.json exists, else False */ function testNotPackage(absolutePath) { return ['package.json', 'bower.json'].every(function fileFound(file) { return !fs.existsSync(path.resolve(absolutePath, file)); }); } } module.exports = fileSearch;
36.922581
115
0.654552
fee8ae5ea2eca0183f52a713c4a539b5dc0a16af
1,863
js
JavaScript
src/tests/FeatureTests/UnknownPointerKey.js
dwighthouse/json-complete
001c53510b1c6eab60ad896bbca1476d6053fbe9
[ "BSL-1.0" ]
269
2019-07-24T01:30:18.000Z
2022-01-07T17:31:56.000Z
src/tests/FeatureTests/UnknownPointerKey.js
dwighthouse/json-complete
001c53510b1c6eab60ad896bbca1476d6053fbe9
[ "BSL-1.0" ]
7
2019-07-24T00:15:45.000Z
2020-09-18T17:15:15.000Z
src/tests/FeatureTests/UnknownPointerKey.js
dwighthouse/json-complete
001c53510b1c6eab60ad896bbca1476d6053fbe9
[ "BSL-1.0" ]
9
2019-01-23T04:33:10.000Z
2019-08-12T08:40:38.000Z
import test from '/tests/tape.js'; import jsonComplete from '/main.js'; const decode = jsonComplete.decode; test('Unknown Pointer Key: Inner Data', (t) => { t.plan(1); const innerData = JSON.stringify([ 'Q0', '2', ['Q', 'NOTUSED0'], ['NOTUSED', ['a']], ]); t.equal(decode(innerData, { compat: true, })[0], 'NOTUSED0'); }); test('Unknown Pointer Key: Root Value', (t) => { t.plan(1); const valueData = JSON.stringify([ 'NOTUSED0', '2', ['NOTUSED', ['a']], ]); t.equal(decode(valueData, { compat: true, }), 'NOTUSED0'); }); test('Unknown Pointer Key: Key Data', (t) => { t.plan(2); const objectKeyData = JSON.stringify([ 'O0', '2', ['O', 'NOTUSED0 S0'], ['S', ['1']], ['NOTUSED', ['a']], ]); const decodedObjectKeys = Object.keys(decode(objectKeyData, { compat: true, })); t.equal(decodedObjectKeys.length, 1); t.equal(decodedObjectKeys[0], 'NOTUSED0'); }); test('Unknown Pointer Key: Non-Compat Mode', (t) => { t.plan(1); const innerData = JSON.stringify([ 'Q0', '2', ['Q', 'NOTUSED0'], ['NOTUSED', ['a']], ]); try { decode(innerData, { compat: false, }); t.ok(false); } catch (e) { t.equal(e.message, 'Cannot decode unrecognized pointer type "NOTUSED".'); } }); test('Unknown Pointer Key: Root Value Non-Compat Mode', (t) => { t.plan(1); const valueData = JSON.stringify([ 'NOTUSED0', '2', ['NOTUSED', ['a']], ]); try { decode(valueData, { compat: false, }); t.ok(false); } catch (e) { t.equal(e.message, 'Cannot decode unrecognized pointer type "NOTUSED".'); } });
20.25
81
0.49329
fee9101b8f313c421dd389846eb1538535abe9da
950
js
JavaScript
src/components/About/Objectives.js
kallpaludica/tiendita-de-juegos
ff63c3638ef505c611f13fdbf67cf75f19ce1537
[ "MIT" ]
2
2020-10-01T05:39:59.000Z
2021-09-14T00:16:07.000Z
src/components/About/Objectives.js
kallpaludica/tiendita-de-juegos
ff63c3638ef505c611f13fdbf67cf75f19ce1537
[ "MIT" ]
1
2020-10-01T05:47:43.000Z
2020-10-01T05:47:43.000Z
src/components/About/Objectives.js
kallpaludica/tiendita-de-juegos
ff63c3638ef505c611f13fdbf67cf75f19ce1537
[ "MIT" ]
1
2020-10-01T05:40:13.000Z
2020-10-01T05:40:13.000Z
import { graphql, useStaticQuery } from "gatsby" import React from "react" import FormatText from "../serializers" const ObjectivesComponent = () => { const data = useStaticQuery(graphql` query ObjectivesQuery { objetivos: contentfulSobreElProyecto(slug: { eq: "objetivos" }) { id title textoPrincipal { raw } } } `) return ( <> <div className="w-full text-left "> <h1 className="max-w-4xl pb-6 mx-auto font-mono text-4xl text-center text-yellow-600"> {data.objetivos.title} </h1> <hr className="w-16 mx-auto my-8 border-t-4 border-yellow-600" /> <div className="max-w-4xl mx-auto font-sans text-2xl prose prose-xl prose-red"> {data.objetivos.textoPrincipal && ( <FormatText FormatText={data.objetivos.textoPrincipal} /> )} </div> </div> </> ) } export default ObjectivesComponent
26.388889
94
0.598947
fee9458c8f4473756944fb36d21a1cfeb7809a94
470
js
JavaScript
public/javascripts/confirm.js
kdoomsday/doomcart
184037474ab17c7c2f8e628c8926261237d85b5c
[ "Apache-2.0", "Unlicense" ]
1
2016-11-03T03:16:38.000Z
2016-11-03T03:16:38.000Z
public/javascripts/confirm.js
kdoomsday/doomcart
184037474ab17c7c2f8e628c8926261237d85b5c
[ "Apache-2.0", "Unlicense" ]
null
null
null
public/javascripts/confirm.js
kdoomsday/doomcart
184037474ab17c7c2f8e628c8926261237d85b5c
[ "Apache-2.0", "Unlicense" ]
null
null
null
/* Create confirmation dialogs. Requires that alertify was loaded */ /** Create a normal confirmation * title - Title text * message - Body text * okText - Ok button text * cancelText - Cancel button text * fOk - Function to be called if ok is pressed */ function confirm(title, message, okText, cancelText, fOk) { alertify.confirm(title, message, fOk, function() { }).set( 'labels', {ok: okText, cancel: cancelText} ); }
31.333333
68
0.644681
fee9d122184eb066a03a6bede79883e151769ada
947
js
JavaScript
node_modules/caniuse-lite/data/features/input-search.js
hemeshreddys/gatsbyProject
b27f9782517c0d690ca9d8e0130912e113514920
[ "MIT" ]
6
2019-04-08T15:09:30.000Z
2020-08-11T02:44:50.000Z
cspersonalization/node_modules/caniuse-lite/data/features/input-search.js
ReesesSnickers/Testing_Personal-CSPersonalization
8e4ba88fe679fe8095f557f0fe14272b0a8bb038
[ "MIT" ]
14
2019-04-10T11:08:18.000Z
2022-02-26T01:39:42.000Z
cspersonalization/node_modules/caniuse-lite/data/features/input-search.js
ReesesSnickers/Testing_Personal-CSPersonalization
8e4ba88fe679fe8095f557f0fe14272b0a8bb038
[ "MIT" ]
3
2019-02-26T11:05:05.000Z
2019-02-27T20:25:11.000Z
module.exports={A:{A:{"2":"H D G E JB","129":"A B"},B:{"129":"1 C p J L N I"},C:{"2":"eB EB cB WB","129":"0 1 2 3 4 5 6 7 8 9 F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z AB CB DB"},D:{"1":"0 2 3 4 5 6 7 8 9 V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z AB CB DB QB gB KB IB LB MB NB OB","16":"1 F K H D G E A B C p Q R S T U","129":"J L N I O P"},E:{"1":"H D G E A B C RB SB TB UB VB c XB","16":"F K PB HB"},F:{"1":"0 4 C J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z dB BB","2":"E YB ZB aB bB","16":"B c FB"},G:{"1":"G hB iB jB kB lB mB nB oB pB qB rB","16":"HB fB GB"},H:{"129":"sB"},I:{"1":"3 xB yB","16":"tB uB","129":"EB F vB wB GB"},J:{"1":"D","129":"A"},K:{"1":"C","2":"A","16":"B c FB","129":"M BB"},L:{"1":"IB"},M:{"129":"2"},N:{"129":"A B"},O:{"1":"zB"},P:{"1":"F K 0B 1B"},Q:{"1":"2B"},R:{"1":"3B"}},B:1,C:"Search input type"};
473.5
946
0.469905
feeb7244b1a3afa8ba5cc9341d7c654ee83a4ab3
2,271
js
JavaScript
js/web-components/data-list.js
eGirlAsm/dataformsjs
9d9797b4c16198ed5ddd5a65cfc38624eb225d06
[ "MIT" ]
null
null
null
js/web-components/data-list.js
eGirlAsm/dataformsjs
9d9797b4c16198ed5ddd5a65cfc38624eb225d06
[ "MIT" ]
null
null
null
js/web-components/data-list.js
eGirlAsm/dataformsjs
9d9797b4c16198ed5ddd5a65cfc38624eb225d06
[ "MIT" ]
null
null
null
/** * DataFormsJS <ul is="data-list"> Web Component * * This component renders a standard <table> after [value] is set from JavaScript * with an array of objects. This component works with the <json-data> to display * data once it is downloaded. */ /* Validates with both [jshint] and [eslint] */ /* For online eslint - Source Type = 'module' must be manually selected. */ /* jshint esversion:8 */ /* eslint-env browser, es6 */ /* eslint quotes: ["error", "single", { "avoidEscape": true }] */ /* eslint spaced-comment: ["error", "always"] */ /* eslint-disable no-console */ import { render } from './utils.js'; /** * Shadow DOM for Custom Elements */ const shadowTmpl = document.createElement('template'); shadowTmpl.innerHTML = ` <style>:host { display:block; }</style> <slot></slot> `; class DataList extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({mode: 'open'}); shadowRoot.appendChild(shadowTmpl.content.cloneNode(true)); this.setAttribute('not-setup', ''); this.state = { list: null }; } get value() { return this.state.list; } set value(list) { this.state.list = list; this.renderList(); } renderList() { // Ignore if [value] has not yet been set const list = this.state.list; if (list === null || list === '') { this.innerHTML = ''; return; } // Show no-data if empty if (Array.isArray(list) && list.length === 0) { this.removeAttribute('not-setup'); return; } // Validate data type if (!Array.isArray(list)) { console.error('Invalid list data type for [data-list]'); console.log(this); this.removeAttribute('not-setup'); return; } // List Items const html = ['<ul>']; for (const item of list) { html.push(render`<li>${item}</li>`); } html.push('</ul>') this.innerHTML = html.join(''); // Remove this attribute after the first time a list has been rendered this.removeAttribute('not-setup'); } } window.customElements.define('data-list', DataList);
27.695122
81
0.571554
feecbba51af8d1ae7b8c1f4ad8e615e16dafb9fa
12,384
js
JavaScript
usercenter-front/src/main/resources/static/modules/openReservation/stationAppointmentTwo.js
osgvsun/lubanlou
16d87a30edcb677bb399e001a2020e8527ba26f2
[ "BSD-3-Clause" ]
1
2022-01-20T04:42:37.000Z
2022-01-20T04:42:37.000Z
usercenter-front/target/classes/static/modules/openReservation/stationAppointmentTwo.js
osgvsun/lubanlou
16d87a30edcb677bb399e001a2020e8527ba26f2
[ "BSD-3-Clause" ]
null
null
null
usercenter-front/target/classes/static/modules/openReservation/stationAppointmentTwo.js
osgvsun/lubanlou
16d87a30edcb677bb399e001a2020e8527ba26f2
[ "BSD-3-Clause" ]
null
null
null
layui.use(['laypage', 'layer', 'table', 'element', 'form', 'laydate', 'formSelects'], function() { var admin = layui.admin, laypage = layui.laypage, layer = layui.layer, table = layui.table, $ = layui.jquery, element = layui.element, form = layui.form, laydate = layui.laydate, formSelects = layui.formSelects //向世界问个好 //layer.msg(''); form.render(null, 'stationappointmenttwobox'); let userSchoolAcademy = ''; // 当前登录人所在院区 // 获取用户信息 $.ajax({ url: 'getCurrentUser', type: 'GET', success: function (res) { let data = res; userSchoolAcademy = data.schoolAcademy; $("input[name=person]").val(data.cname); $("input[name=email]").val(data.email); $("input[name=telephone]").val(data.phone); } }); let configUid = ''; let pointStatus = ''; let instructions = ''; let fileId = ''; let maxInterval = ''; //最大预约时间段 let minInterval = ''; //最小预约时间段 let openScope = ''; //预约接待对象 let academyNumber = ''; //预约须知 $.ajax({ url: deviceHost + "getAppBasicSettings", type: 'GET', async: false, data: { "configType": configType, "insUid": uid }, dataType: "JSON", success: function (res) { let data = res.data; maxInterval = data.maxInterval; minInterval = data.minInterval; openScope = data.openScope; academyNumber = data.academyNumber; configUid = data.uid pointStatus = data.laboratoryLayoutImagesPointInfo; instructions = data.basicAttention; fileId = data.laboratoryLayoutImages; } }) $.ajax({ url: deviceHost + 'getAppOpeningCustomFieldList', type: 'GET', // async: false, data: {"configUid": configUid}, success: function (res) { let data = res.data; for (let i = 0; i < data.length; i++) { if (data[i].displayStyle === "TEXT") { let input_text = `<div class="layui-col-lg12 other_field"> <label class="layui-form-label">${data[i].note}:</label> <div class="layui-input-block"> <input type="text" class="layui-input va_save" name="${data[i].uid}" autocomplete="off" ${data[i].necessary == 1 ? "lay-verify='required'" : ""}/> </div> </div>`; $('.reason').before(input_text); } else { let input_radio = `<div class="layui-col-lg12 other_field"> <label class="layui-form-label">${data[i].note}:</label> <div class="layui-input-block"> ${setOptions(data[i].displayStyle, data[i].openSettingCustomFieldValueVOList, data[i].uid, this)} </div> </div>`; $('.reason').before(input_radio); } form.render(); } } }); let drawingStyle = {}; // 绘制过程中样式 let gImageLayer; //涂层绘制 let gMap; //容器标注 let gFirstFeatureLayer; // 实例化 let gFirstMaskLayer; // 涂抹层 var mv = new Vue({ el: '#app', data() { return { imageUrl: '', pointStatus: '', instructions: '', fileId: '', appTime: '', initArr: [], selectArr: [], popArr: [] } }, mounted() { this.setInformation(); this.setImage(); let timeScope = setPeriodTime(new Date('2021-10-13 00:00:00'), new Date('2021-10-14 00:00:00'), 60, '~'); var appPeriodTime = xmSelect.render({ el: '#appPeriod', radio: true, style: { width: '180px' }, theme: {color: '#0081ff'}, toolbar: {show: true}, data: timeScope, on: function (data) { var change = data.change; $('.appTime').val(change[0].value); } }) //选择时间段 laydate.render({ elem: '#searchdate', type: 'date', min: new Date().format("yyyy-MM-dd"), done: function (value, date, endDate) { $('.appoiontment_time_after').find('label').text(value); } }); }, methods: { setInformation() { this.pointStatus = pointStatus; this.instructions = instructions; this.fileId = fileId; }, getFileById(id) { return new Promise((resolve, reject) => { resourceContainer.getFileById({ success: function (data) { resolve(data.url) }, fail: function (reason) { console.log("失败:" + reason); }, fileId: id, needToken: true }); }); }, async setImage() { this.imageUrl = await this.getFileById(this.fileId) this.setCoating(); }, // 设置涂层 setCoating() { gMap = new AILabel.Map('dot_map', { center: {x: 250, y: 177}, // 为了让图片居中 zoom: 800, mode: 'PAN', // 绘制线段 refreshDelayWhenZooming: true, // 缩放时是否允许刷新延时,性能更优 zoomWhenDrawing: true, panWhenDrawing: true, zoomWheelRatio: 5, // 控制滑轮缩放缩率[0, 10), 值越小,则缩放越快,反之越慢 withHotKeys: true // 关闭快捷键 }); gImageLayer = new AILabel.Layer.Image( 'first-layer-image', // id { // src: 'http://ali.download.lubanlou.com/group1/M00/03/40/rBJ0pV7jPGeAAtALAAIZ4U7sKWQ213.jpg', // src: '../modules/openReservation/static/images/user_head.jpg', src: this.imageUrl, width: 500, height: 354, crossOrigin: true, // 如果跨域图片,需要设置为true position: { // 左上角相对中心点偏移量 x: 0, y: 0 }, grid: { // 3 * 3 columns: [{color: '#9370DB'}, {color: '#FF6347'}], rows: [{color: '#9370DB'}, {color: '#FF6347'}] } }, // imageInfo {name: '第一个图片图层'}, // props {zIndex: 5} // style ); gMap.addLayer(gImageLayer); // 实例化 gFirstFeatureLayer = new AILabel.Layer.Feature( 'first-layer-feature', // id {name: '第一个矢量图层'}, // props {zIndex: 10} // style ); gMap.addLayer(gFirstFeatureLayer); // 涂抹层 gFirstMaskLayer = new AILabel.Layer.Mask( 'first-layer-mask', // id {name: '第一个涂抹图层'}, // props {zIndex: 11, opacity: .5} // style ); gMap.addLayer(gFirstMaskLayer); // 绘制结束 let tracingPointData = [] if (this.pointStatus != '') { tracingPointData = JSON.parse(this.pointStatus) } this.initArr = tracingPointData; for (let i = 0; i < tracingPointData.length; i++) { let point = new AILabel.Feature.Point( tracingPointData[i].id, tracingPointData[i].shape, { name: "预约状态"}, { fillStyle: tracingPointData[i].style.fillStyle, lineCap: tracingPointData[i].style.lineCap} ) gFirstFeatureLayer.addFeature(point); }; gMap.events.on('dblClick', (feature, shape) => { console.log(feature) let pointShape = gFirstFeatureLayer.getTargetFeatureWithPoint(feature.global); console.log(pointShape) if (pointShape.style.fillStyle === '#e63522') { layer.msg('当前工位处于忙碌状态,请预约其他工位'); } else if (pointShape.style.fillStyle === '#7d7d7d') { layer.msg('当前工位暂不开放,请预约其他工位'); } else { const featureUpdate = new AILabel.Feature.Point( pointShape.id, pointShape.shape, { name: "预约状态"}, { fillStyle: '#fcf', lineCap: pointShape.style.lineCap} ) gFirstFeatureLayer.removeFeatureById(pointShape.id); gFirstFeatureLayer.addFeature(featureUpdate); this.selectArr.push(pointShape.id) } this.popArr.push(this.selectArr) }) }, zoomIn() { gMap.zoomIn(); }, zoomOut() { gMap.zoomOut(); }, setMode(mode, type) { gMap.setMode(mode); // 后续对应模式处理 switch (gMap.mode) { case 'PAN': { break; } default: break; } }, refresh() { this.setImage(); }, reply() { // 撤回操作,记录当前点位,存储当前选择点位,点击撤销时,移除当前最后一个记录,根据愿点位重新上色 console.log(this.selectArr); console.log(this.initArr) let id = this.popArr[0].pop(); for (let i = 0; i < this.initArr.length; i++) { if (this.initArr[i].id == id) { const featureUpdate = new AILabel.Feature.Point( this.initArr[i].id, this.initArr[i].shape, this.initArr[i].props, this.initArr[i].style, ) gFirstFeatureLayer.removeFeatureById(this.initArr[i].id); gFirstFeatureLayer.addFeature(featureUpdate); } } }, savebtn() { console.log(this.selectArr) let pass = 0; let openScopeTwo = 0; let appTime = $('.appTime').val(); if (appTime) { let timeArr = appTime.split('~') let d1 = new Date('2021-11-11 ' + timeArr[0]); let d2 = new Date('2021-11-11 ' + timeArr[1]); let model = parseInt(d2 - d1) / 1000 /60 /60; // if (minInterval > model || model > maxInterval) { // pass = 1; // } } if (pass === 1 || !appTime) { layer.msg("请选择时间段"); return false; } //判断,校内开放是,当前用户有没有预约权限 if (openScope == 2 && pass === 0) { if (academyNumber) { let arr = academyNumber.split(','); if (userSchoolAcademy) { for (let i = 0; i < arr.length; i++) { if (arr[i] === userSchoolAcademy.academyNumber) { openScopeTwo = 1; } } } } if (openScopeTwo === 0) { layer.msg('当前用户为开放预约权限,请联系管理员处理'); return false; } else { let other_arr = [] $.each($('.other_field'), function (index, obj) { let newObj = {}; newObj[$(obj).find('label').text().replace(/:/g, '')] = $(obj).find('input').attr('class') === 'va_save_checkbox' ? getCheckedBox($(obj).find('input')): $(obj).find('.va_save').val(); other_arr.push(newObj) }) let appPoint = [] for (let i = 0; i < this.selectArr.length; i++) { for (let j = 0; j < this.initArr.length; j++) { if (this.selectArr[i] == this.initArr[j].id) { appPoint.push(this.initArr[j]) j = this.initArr.length } } } let obj_all = { "appUser": currentUsername, "appUserMail": $("input[name=email]").val(), "appUserPhone": $("input[name=telephone]").val(), "appReason": $("input[name=reason]").val(), "configUid": configUid, "extendsFieldValue": other_arr, "appType": configType, "appPoint": appPoint}; let arr = []; $.each($('.appoiontment_time_after'), function (index, obj) { let obj_arr = { "appDate": $(obj).find('label').text(), "appTime": $(obj).find('input').val() + ','}; arr.push(Object.assign(obj_arr, obj_all)); }) $.ajax({ url: `${appointmentHost}/saveAppInfo`, type: 'POST', async: false, data: {"appInfoVOListJson": JSON.stringify(arr)}, success: function (res) { console.log() if (res.code === 0) { layer.msg('预约成功'); } else { layer.msg(res.msg); } } }) } } if (pass === 0 && openScope !== 2) { let other_arr = [] $.each($('.other_field'), function (index, obj) { let newObj = {}; newObj[$(obj).find('label').text().replace(/:/g, '')] = $(obj).find('input').attr('class') === 'va_save_checkbox' ? getCheckedBox($(obj).find('input')): $(obj).find('.va_save').val(); other_arr.push(newObj) }) let appPoint = [] for (let i = 0; i < this.selectArr.length; i++) { for (let j = 0; j < this.initArr.length; j++) { if (this.selectArr[i] == this.initArr[j].id) { appPoint.push(this.initArr[j]) j = this.initArr.length } } } let obj_all = { "appUser": currentUsername, "appUserMail": $("input[name=email]").val(), "appUserPhone": $("input[name=telephone]").val(), "appReason": $("input[name=reason]").val(), "configUid": configUid, "extendsFieldValue": other_arr, "appType": configType, "appPoint": appPoint}; let arr = []; $.each($('.appoiontment_time_after'), function (index, obj) { let obj_arr = { "appDate": $(obj).find('label').text(), "appTime": $(obj).find('input').val() + ','}; arr.push(Object.assign(obj_arr, obj_all)); }) $.ajax({ url: `${appointmentHost}/saveAppInfo`, type: 'POST', async: false, data: {"appInfoVOListJson": JSON.stringify(arr)}, success: function (res) { console.log() if (res.code === 0) { layer.msg('预约成功'); } else { layer.msg(res.msg); } } }) } else { layer.msg('当前用户暂无预约权限') } } } }) });
29.985472
190
0.547884
feecbe1cf7cbb1e1da1afa9315db518af9736c76
564
js
JavaScript
src/parser/code_span.js
Reefstah/markdown-api
a0f9ac1e6f3ef04703d00ebf2999e8d4e1b94c10
[ "MIT" ]
1
2018-06-06T15:35:08.000Z
2018-06-06T15:35:08.000Z
src/parser/code_span.js
Reefstah/markdown-api
a0f9ac1e6f3ef04703d00ebf2999e8d4e1b94c10
[ "MIT" ]
null
null
null
src/parser/code_span.js
Reefstah/markdown-api
a0f9ac1e6f3ef04703d00ebf2999e8d4e1b94c10
[ "MIT" ]
null
null
null
import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/empty'; import 'rxjs/add/observable/of'; import 'rxjs/add/observable/from'; export class CodeSpanParser { constructor() { this.regEx = /^(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/g } parse(text) { const result = this.regEx.exec(text); return result ? Observable.of(new CodeSpan(result[3])) : Observable.empty(); } } export class CodeSpan { constructor(text) { this.text = text; } get() { return {codeSpan: this.text} } }
19.448276
84
0.579787
feecdfbfc578b2ababf4258a899eced93d843e14
871
js
JavaScript
lib/gelf.js
lnys/gelf-cli
7d1403d2a3305cf6924314207c627820a3aa5334
[ "MIT" ]
null
null
null
lib/gelf.js
lnys/gelf-cli
7d1403d2a3305cf6924314207c627820a3aa5334
[ "MIT" ]
null
null
null
lib/gelf.js
lnys/gelf-cli
7d1403d2a3305cf6924314207c627820a3aa5334
[ "MIT" ]
null
null
null
var logger = require('gelf-pro'); module.exports.send = function(msg, params = {}, callback) { logger.setConfig({ fields: {facility: "CI", stage: "clone"}, filter: [], transform: [], broadcast: [], levels: {}, aliases: {}, adapterName: 'udp', adapterOptions: { host: params.host, port: params.port, family: 4, timeout: 10000, protocol: 'udp4', } }); if (msg.length) { let level = params.hasOwnProperty('level') ? params.level : "error"; switch (level) { case 'emergency': // 0 case 'alert': // 1 case 'critical': // 2 case 'error': // 3 case 'warning': // 4 case 'notice': // 5 case 'info': // 6 case 'debug': // 7 logger[level](msg); break; default: logger.error(msg); } callback(); } };
22.333333
73
0.50287
feece2a6535e3fda6b7a38639500b563905c222d
9,782
js
JavaScript
docs/sierpinski/game.js
willstott101/inthenameoffun
4727b1a0ec34e720df1148887e34fefcaaa5e176
[ "Apache-2.0" ]
null
null
null
docs/sierpinski/game.js
willstott101/inthenameoffun
4727b1a0ec34e720df1148887e34fefcaaa5e176
[ "Apache-2.0" ]
null
null
null
docs/sierpinski/game.js
willstott101/inthenameoffun
4727b1a0ec34e720df1148887e34fefcaaa5e176
[ "Apache-2.0" ]
null
null
null
var RENDER_SCALE = 1; var MAX_FRACTAL_SIZE = 48; var INITIAL_SIZE = 200; var INITIAL_SCALE_RATE = 15; var SCALE_ACCELERATION = 1.8; var GeomUtils = { // Defines some vectors which can be composed to traverse equilateral triangles. rightEdge: (new paper.Point(1, 0)).rotate(60, [0, 0]), downLeft: (new paper.Point(1, 0)).rotate(120, [0, 0]), pathTriangle: function (ctx, position, size) { ctx.beginPath(); ctx.moveTo(position.x, position.y); var point = this.rightEdge.multiply(size).add(position); ctx.lineTo(point.x, point.y); ctx.lineTo(point.x - size, point.y); ctx.closePath(); }, splitTrianglePositions: function (trianglePositions, size) { var rightEdge = this.rightEdge.multiply(size); var downLeft = this.downLeft.multiply(size); return trianglePositions.reduce(function (tps, tp) { tps.push(tp, tp.add(rightEdge), tp.add(downLeft)); return tps; }, []); } }; GeomUtils.triHeight = GeomUtils.rightEdge.y; // Thanks http://stackoverflow.com/a/2901298 function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } function Line(point1, point2) { this.point1 = point1; this.point2 = point2; } Line.prototype._distanceSq = function (v, w) { return Math.pow(v.x - w.x, 2) + Math.pow(v.y - w.y, 2); }; // Thanks https://stackoverflow.com/a/1501725/4021086 Line.prototype.distanceToPointSquared = function (point) { var v = this.point1; var w = this.point2; var p = point; var l2 = this._distanceSq(v, w); if (l2 == 0) return this._distanceSq(p, v); var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; t = Math.max(0, Math.min(1, t)); return this._distanceSq(p, { x: v.x + t * (w.x - v.x), y: v.y + t * (w.y - v.y) }); }; Line.prototype.distanceToPoint = function (point) { return Math.sqrt(this.distToPointSquared(point)); }; Line.prototype.getDx = function () { return this.point2.x - this.point1.x; }; Line.prototype.getDy = function () { return this.point2.y - this.point1.y; }; Line.prototype.getC = function () { var p1 = this.point1; return p1.y - (p1.x * this.getM()); }; Line.prototype.getM = function () { return this.getDy() / this.getDx(); }; Line.prototype.getKey = function () { return this.getM().toFixed(4) + '::' + this.getC().toFixed(1); }; Line.prototype.start = function () { return new paper.Point(0, this.getC()) }; Line.prototype.vector = function () { return new paper.Point(1, this.getM()) }; Line.prototype.path = function (canvas, ctx) { ctx.beginPath(); var c = this.getC(); ctx.moveTo(0, c); var width = canvas.width; ctx.lineTo(width, (this.getM() * width) + c); }; Line.prototype.dots = function (ctx) { var v = this.point1; var w = this.point2; ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'; ctx.fillRect(v.x - 5, v.y - 5, 10, 10); ctx.fillStyle = 'rgba(0, 0, 255, 0.5)'; ctx.fillRect(w.x - 5, w.y - 5, 10, 10); }; function Sierpinski(paperScope) { var paper = this._paper = paperScope; this.version = 1; this.canvas = paper.view.element; this.context = paper.view._context; this.scoreEl = document.getElementById('game-score'); this.hiscoreEl = document.getElementById('game-hiscore'); this.msgEl = document.getElementById('game-msg'); document.addEventListener('mousedown', this.onMouseDown.bind(this)); paper.view.onFrame = this.onFrame.bind(this); paper.view.onMouseMove = this.onMouseMove.bind(this); this.reset(); } Sierpinski.prototype.reset = function() { this.state = { score: 0, finished: false, start_time: (new Date()).getTime() / 1000, size: INITIAL_SIZE, }; this.updateHighScore(); this.setScore(0); var paper = this.getPaper(); this.state.triangles = [paper.view.center.add(0,(- GeomUtils.triHeight * this.state.size / 2) + 1)]; this.state.mouse_pos = new paper.Point(paper.view.center); this.setMsg(false); }; Sierpinski.prototype.finish = function() { this.state.finished = true; this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); this.setMsg(true); this.saveHighScore(); }; Sierpinski.prototype.getPaper = function() { this._paper.activate(); return window.paper; }; Sierpinski.prototype.setScore = function(score) { this.state.score = score; this.renderScore(); }; Sierpinski.prototype.renderScore = _.throttle(function() { this.scoreEl.innerHTML = numberWithCommas(Math.round(this.state.score)); }, 80); Sierpinski.prototype.updateHighScore = function() { var hs = localStorage['highscore_v' + this.version]; if (hs) this.hiscoreEl.innerHTML = numberWithCommas(parseInt(hs)); }; Sierpinski.prototype.saveHighScore = function() { var score = localStorage['highscore_v' + this.version]; if (!score || parseInt(score) < this.state.score) localStorage['highscore_v' + this.version] = this.state.score; }; Sierpinski.prototype.onMouseDown = function() { if (this.state.finished) // TODO: newGame was called this.reset(); }; Sierpinski.prototype.onMouseMove = function(evt) { this.state.mouse_pos = evt.point; }; Sierpinski.prototype.setMsg = function(msg) { if (msg) { if (msg !== true) this.msgEl.innerHTML = msg; this.msgEl.classList.remove('hidden'); } else this.msgEl.classList.add('hidden'); }; Sierpinski.prototype.onFrame = function(evt) { if (this.state.finished) return; this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); var time = ((new Date()).getTime() / 1000) - this.state.start_time; this.setScore(time * 1000); this._doZoom(evt, time); this._realignTriangles(); this._cullTriangles(); this._renderTriangles(); // var edges = this._findEdges(); // this._drawEdges(edges); if (this.state.triangles.length === 0) { this.finish(); return; } }; Sierpinski.prototype._doZoom = function(evt, time) { var increase = (INITIAL_SCALE_RATE + (time * SCALE_ACCELERATION)) * evt.delta; if (increase > 0) scale = (increase / this.state.size) + 1; else scale = 1; this.state.size += increase; // Original: // zoomRate = 0.00001; // size *= 1 + zoomRate*dt // zoomRate += (5e-8) * dt; while (this.state.size > MAX_FRACTAL_SIZE) { console.debug('DOING SPLIT'); this.state.size /= 2; this.state.triangles = GeomUtils.splitTrianglePositions(this.state.triangles, this.state.size); } // Move the triangles out to adjust for the scaling. var centerOfScaling = this.state.mouse_pos; this.state.triangles = this.state.triangles.map(function (tp) { return centerOfScaling.add(tp.subtract(centerOfScaling).multiply(scale)); }); }; Sierpinski.prototype._realignTriangles = function() { var halfEdgeSize = this.state.size / 2; var triHeight = GeomUtils.triHeight * this.state.size; // QDH: Avoid compound error in triangle list by aligning with the first one. var firstTriangleX = this.state.triangles[0].x; var firstTriangleY = this.state.triangles[0].y; this.state.triangles.forEach(function (tp) { var x = tp.x - firstTriangleX; x = (Math.round(x / halfEdgeSize) * halfEdgeSize); tp.x = x + firstTriangleX; var y = tp.y - firstTriangleY; y = (Math.round(y / triHeight) * triHeight); tp.y = y + firstTriangleY; }); }; Sierpinski.prototype._cullTriangles = function() { var bounds = this.getPaper().view.bounds; var width = bounds.width; var height = bounds.height; var halfEdgeSize = this.state.size / 2; // Filter the triangles which are off the screen. var triangleHeight = GeomUtils.rightEdge.y * this.state.size; this.state.triangles = this.state.triangles.filter(function (tp) { return !( tp.y > height || tp.y < - triangleHeight || tp.x - halfEdgeSize > width || tp.x + halfEdgeSize < 0); }); }; Sierpinski.prototype._renderTriangles = function() { // Draw the remaining triangles to the canvas. this.context.fillStyle = 'black'; this.state.triangles.forEach(function (tp) { GeomUtils.pathTriangle(this.context, tp, this.state.size); this.context.fill(); }, this); }; Sierpinski.prototype._findEdges = function() { var edges = {}; var rightEdge = GeomUtils.rightEdge.multiply(this.state.size); var downLeft = GeomUtils.downLeft.multiply(this.state.size); this.state.triangles.forEach(function (tp) { var br = tp.add(rightEdge); var bl = tp.add(downLeft); var bottom = new Line(bl, br); var left = new Line(tp, bl); var right = new Line(tp, br); var k = bottom.getKey(); if (!edges.hasOwnProperty(k)) edges[k] = bottom; k = left.getKey(); if (!edges.hasOwnProperty(k)) edges[k] = left; k = right.getKey(); if (!edges.hasOwnProperty(k)) edges[k] = right; console.debug(right.getM(), left.getM()); }, this); return edges; }; Sierpinski.prototype._drawEdges = function(edges) { var canvas = this.canvas; var ctx = this.context; ctx.strokeStyle = "pink"; _.forOwn(edges, function(line, key) { line.path(canvas, ctx); line.dots(ctx); ctx.stroke(); }); console.debug('triangles', this.state.triangles.length, 'lines', _.size(edges)); }; var main = function () { var paper = new window.paper.PaperScope(); paper.setup('game-canvas'); window.Game = new Sierpinski(paper); }; document.addEventListener('DOMContentLoaded', main, false);
27.022099
103
0.63484
feedccad053379aacf8e71798585bb72ea694618
3,272
js
JavaScript
api/controllers/requestController.js
Aravind-N-s/Youtube-API
203f351ff32441cf23c4d3c2b75a67b3b3681a2e
[ "Apache-2.0" ]
null
null
null
api/controllers/requestController.js
Aravind-N-s/Youtube-API
203f351ff32441cf23c4d3c2b75a67b3b3681a2e
[ "Apache-2.0" ]
null
null
null
api/controllers/requestController.js
Aravind-N-s/Youtube-API
203f351ff32441cf23c4d3c2b75a67b3b3681a2e
[ "Apache-2.0" ]
null
null
null
/** request Controller * @module api/controllers */ /** * @namespace requestController */ /** * Loading env variables to application */ require("dotenv").config; /** * An implementation of JSON Web Tokens in Node.JS. * @const */ const jwt = require("jsonwebtoken"); /** * Mongoose Model for request. * @const */ const { Request } = require("../models/Request"); /** * Constants enumerating the HTTP status codes. * @const */ const HttpStatus = require("http-status-codes"); /** * Constants having logger function. * @const */ const { logger } = require("../../config/logger"); /** * Socket values imported from index * @const */ module.exports = { /** * Controller to handle request search * @name search * @function * @memberof module:api/controllers~requestController * @inner * @param {Object} request - Request Object * @param {Object} response - Response Object */ async searchRequest({ route, query }, res) { logger.addContext("route", route.path); const searchRequest = query.search; const limitRequest = Number(query.paginate) || 5; try { const requestInfo = await Request.find({ $or: [ { title: { $regex: searchRequest, $options: "$i" }, description: { $regex: searchRequest, $options: "$i" }, }, ], }) .limit(limitRequest) .sort({ publishTime: -1 }); if (!requestInfo.length) { return res .status(HttpStatus.NOT_ACCEPTABLE) .json({ requestInfo, message: `${searchRequest} not found.` }); } logger.info(`requestInfo search ${requestInfo._id}`); requestInfo.forEach(async (ele) => { await Request.updateMany( { _id: ele._id }, { $set: { count: ele.count + 1 } }, ); }); return res .status(HttpStatus.OK) .json({ data: requestInfo, message: "-Data Response -" }); } catch (err) { logger.error(`${err} errors are existed`); return res.status(HttpStatus.NOT_ACCEPTABLE).json({ err, message: err }); } }, /** * Controller to handle request dashboard * @name dashboard * @function * @memberof module:api/controllers~requestController * @inner * @param {Object} request - Request Object * @param {Object} response - Response Object */ async dashboard({ route, query }, res) { logger.addContext("route", route.path); const limitRequest = Number(query.paginate) || 5; const sortOption = query.sort === "asc" ? 1 : -1; try { const requestInfo = await Request.find({}) .limit(limitRequest) .sort({ count: sortOption || -1 }); if (!requestInfo.length) { return res .status(HttpStatus.NOT_ACCEPTABLE) .json({ message: "Dashboard not generated." }); } logger.info(`requestInfo search ${requestInfo._id}`); return res.status(HttpStatus.OK).json({ data: requestInfo, message: "-Data Response -", }); } catch (err) { const { errors } = err; logger.error(`${Object.keys(errors)} errors are existed`); return res .status(HttpStatus.NOT_ACCEPTABLE) .json({ errors, message: errors }); } }, };
24.977099
79
0.588631
feef07c9c9a2b960a424b755a4c953cc4f1c1cc7
603
js
JavaScript
sapui5-sdk-1.74.0/resources/sap/ui/vk/FlexibleControlLayoutData.js
juanfelipe82193/opensap
568c01843a07b8a1be88f8fb8ccb49845fb8110e
[ "Apache-2.0" ]
null
null
null
sapui5-sdk-1.74.0/resources/sap/ui/vk/FlexibleControlLayoutData.js
juanfelipe82193/opensap
568c01843a07b8a1be88f8fb8ccb49845fb8110e
[ "Apache-2.0" ]
null
null
null
sapui5-sdk-1.74.0/resources/sap/ui/vk/FlexibleControlLayoutData.js
juanfelipe82193/opensap
568c01843a07b8a1be88f8fb8ccb49845fb8110e
[ "Apache-2.0" ]
null
null
null
/*! * SAP UI development toolkit for HTML5 (SAPUI5) (c) Copyright 2009-2015 SAP SE. All rights reserved */ sap.ui.define(["sap/ui/core/LayoutData"],function(L){"use strict";var F=L.extend("sap.ui.vk.FlexibleControlLayoutData",{metadata:{library:"sap.ui.vk",properties:{size:{type:"sap.ui.core.CSSSize",group:"Dimension",defaultValue:"auto"},minSize:{type:"sap.ui.core.CSSSize",group:"Dimension",defaultValue:"0px"},marginTop:{type:"sap.ui.core.CSSSize",group:"Dimension",defaultValue:"0px"},marginBottom:{type:"sap.ui.core.CSSSize",group:"Dimension",defaultValue:"0px"}}}});return F;});
75.375
479
0.723051
feef2e296e77ca8e0c06661ff53e79b5b13c52fb
427
js
JavaScript
examples/tiles/Sparks.js
onion2k/neon
683de8c143c747544f148b75d668379ee1f7e4b6
[ "MIT" ]
5
2018-09-27T18:10:35.000Z
2022-01-25T12:35:17.000Z
examples/tiles/Sparks.js
onion2k/neon
683de8c143c747544f148b75d668379ee1f7e4b6
[ "MIT" ]
null
null
null
examples/tiles/Sparks.js
onion2k/neon
683de8c143c747544f148b75d668379ee1f7e4b6
[ "MIT" ]
null
null
null
import React from "react"; import Tile from "../Tile.js"; import withNeon, { fx } from "../../src/index.js"; class SparksTile extends React.Component { render(){ return ( <Tile bg="black" className="one"> <div style={{ backgroundImage: "url(https://source.unsplash.com/random?s)" }}></div> </Tile> ) } }; const effect = new fx.Sparks(); export default withNeon(SparksTile, effect);
23.722222
94
0.613583
feefe1ba329ff8af4c7a98e80e09bb8cc6659bef
12,212
js
JavaScript
public/component---src-pages-clients-search-clients-js-bcc2a6222ab480beeb7e.js
juanitoabelo/touchstoneapex
eb5c0a04ce671faea6f8001ae14483a5fccc7a10
[ "MIT" ]
null
null
null
public/component---src-pages-clients-search-clients-js-bcc2a6222ab480beeb7e.js
juanitoabelo/touchstoneapex
eb5c0a04ce671faea6f8001ae14483a5fccc7a10
[ "MIT" ]
null
null
null
public/component---src-pages-clients-search-clients-js-bcc2a6222ab480beeb7e.js
juanitoabelo/touchstoneapex
eb5c0a04ce671faea6f8001ae14483a5fccc7a10
[ "MIT" ]
null
null
null
(window.webpackJsonp=window.webpackJsonp||[]).push([[17],{"1UGr":function(e,a,t){"use strict";t.r(a),t.d(a,"default",(function(){return k}));var l=t("JX7q"),n=t("dI71"),r=(t("ToJy"),t("0HrA")),o=t("G9dV"),c=t("jGo9"),i=t("DAwz"),s=(t("Wbzz"),t("paqj")),m=t("eUAm"),u=t("q1tI"),d=t.n(u),p=t("vOnD"),b=t("1Yd/"),h=t("vDqi"),v=t.n(h),E=t("Ji2X"),g=t("PoRk"),f=t("kzC8"),C=Object(p.e)(o.a).withConfig({displayName:"search-clients__Input",componentId:"au1kwd-0"})(["margin-bottom:10px;"]),y=Object(p.e)(r.a).withConfig({displayName:"search-clients__SelectStyled",componentId:"au1kwd-1"})(["margin-bottom:1rem;"]),N=(p.e.div.withConfig({displayName:"search-clients__ErrorStyle",componentId:"au1kwd-2"})(["width:100%;display:flex;flex-direction:column;align-items:center;margin-bottom:2rem;small{margin-bottom:3rem;}h1{margin-bottom:0.5rem;}a{max-width:20rem;}"]),"undefined"!=typeof window),k=function(e){function a(){for(var a,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return(a=e.call.apply(e,[this].concat(n))||this).state={company:{label:"All",value:0},searchBy:{label:"Email",value:"EmailAddress"},searchFor:"",data:[],loader:"",error:!1,errorMsg:"",perpage:10,current:0,pagination:1},a.saveState=function(e){a.setState(e)},a.onChangeDropdown=function(e,t){var l;a.saveState(((l={})[e]={label:t.label,value:t.value},l))},a.onChangeInputText=function(e){a.saveState({searchFor:e.target.value})},a.onSearchLeads=function(){var e=Object(l.a)(a),t=e.state,n=t.company,r=t.searchBy,o=t.searchFor,c=e.saveState;c({loader:"Loading!!!",error:!1,errorMsg:"",data:[]}),v.a.get("https://touchstone-api.abelocreative.com/touchstone-ajax/ajax.php",{params:{tblName:"tblClients",queryType:"searchClientsByCompanyForBy",company:n.value,searchBy:r.value,searchFor:o}}).then((function(e){var a=e.data,t=!1,l="";a.length<=0&&(t=!0,l=f.c),c({data:a,error:t,errorMsg:l})})).catch((function(e){console.log(e),c({error:"error"})}))},a.pageFunc=function(e,t,l,n,r){if(void 0===n&&(n=0),r.preventDefault(),void 0===e)return"type required";if(void 0===t)return"perpage required";if(void 0===l)return"max required";var o=a.state,c=o.pagination,i=o.current,s=o.data,m=Object(f.j)({lengthData:s.length,pagination:c,current:i,perpage:t,max:l,number:n,type:e});a.saveState(m)},a.sortCol=function(e){var t,l=a.state,n=l.data,r=l.toggleDate,o=l.toggleFName,c=l.toggleLName,i=l.toggleEmailAddress,s=l.toggleHomePhone,m=l.toggleService;n.sort((function(a,l){var n,u="",d="";switch(e){case"Date":u=a.Date.toUpperCase(),d=l.Date.toUpperCase(),n=r,t={toggleDate:!r};break;case"FirstName":u=a.FirstName.toUpperCase(),d=l.FirstName.toUpperCase(),n=o,t={toggleFName:!o};break;case"LastName":u=a.LastName.toUpperCase(),d=l.LastName.toUpperCase(),n=c,t={toggleLName:!c};break;case"EmailAddress":u=a.EmailAddress.toUpperCase(),d=l.EmailAddress.toUpperCase(),n=i,t={toggleEmailAddress:!i};break;case"HomePhone":u=a.HomePhone.toUpperCase(),d=l.HomePhone.toUpperCase(),n=s,t={toggleHomePhone:!s};break;case"Service":null!=a.Service&&(u=a.Service.toUpperCase()),null!=l.Service&&(d=l.Service.toUpperCase()),n=m,t={toggleService:!m};break;default:u=a.Date.toUpperCase(),d=l.Date.toUpperCase(),n=r}return Object(f.o)(u,d,n)})),a.saveState(Object.assign({data:n},t))},a.display=function(e){var t=e.data,n=e.loader,r=e.error,o=e.errorMsg,c=e.current,i=e.perpage,s=e.pagination;if(void 0!==t&&t.length>0){var m=Object(l.a)(a),u=(m.editViewProduct,m.pageFunc),p=m.sortCol,b=t.slice(c,c+i),h=Math.floor(t.length/i)+(Math.floor(t.length%i)>0?1:0);return d.a.createElement("div",null,d.a.createElement("table",{className:"table table-striped table-hover"},d.a.createElement("thead",null,d.a.createElement("tr",null,d.a.createElement("th",{scope:"col",onClick:p.bind(Object(l.a)(a),"Date")},"DATE"),d.a.createElement("th",{scope:"col",onClick:p.bind(Object(l.a)(a),"FirstName")},"FIRST NAME"),d.a.createElement("th",{scope:"col",onClick:p.bind(Object(l.a)(a),"LastName")},"LAST NAME"),d.a.createElement("th",{scope:"col",onClick:p.bind(Object(l.a)(a),"EmailAddress")},"EMAIL"),d.a.createElement("th",{scope:"col",onClick:p.bind(Object(l.a)(a),"HomePhone")},"HOME #"),d.a.createElement("th",{scope:"col",onClick:p.bind(Object(l.a)(a),"Service")},"SERVICE"))),d.a.createElement("tbody",null,b.map((function(e){var a=e.ClientID,t=e.Date,l=e.FirstName,n=e.LastName,r=e.EmailAddress,o=e.HomePhone,c=e.Service;return d.a.createElement("tr",{key:a},d.a.createElement("td",null,t),d.a.createElement("td",null,d.a.createElement("a",{className:"color-red text-decoration-none",href:"/product/edit-product?leadID="+a},l)),d.a.createElement("td",null,d.a.createElement("a",{className:"color-red text-decoration-none",href:"/product/edit-product?leadID="+a},n)),d.a.createElement("td",null,d.a.createElement("a",{className:"color-red text-decoration-none",href:"/product/edit-product?leadID="+a},r)),d.a.createElement("td",null,o),d.a.createElement("td",null,c))})))),d.a.createElement("nav",{"aria-label":"Page navigation example"},d.a.createElement("ul",{class:"pagination"},d.a.createElement("li",{class:"page-item"},d.a.createElement("a",{href:"/#",class:"page-link",onClick:u.bind(Object(l.a)(a),"first",i,h,0)},"«")),d.a.createElement("li",{class:"page-item"},d.a.createElement("a",{href:"/#",class:"page-link",onClick:u.bind(Object(l.a)(a),"prev",i,h,0)},"‹")),Object(f.h)(h,u,i,s),d.a.createElement("li",{class:"page-item"},d.a.createElement("a",{href:"/#",class:"page-link",onClick:u.bind(Object(l.a)(a),"next",i,h,0)},"›")),d.a.createElement("li",{class:"page-item"},d.a.createElement("a",{href:"/#",class:"page-link",onClick:u.bind(Object(l.a)(a),"last",i,h,0)},"»")))))}if(r)switch(o){case f.c:return d.a.createElement("table",{className:"table table-striped table-hover"},d.a.createElement("thead",null,d.a.createElement("tr",null,d.a.createElement("th",null,"DATE"),d.a.createElement("th",null,"FIRST NAME"),d.a.createElement("th",null,"LAST NAME"),d.a.createElement("th",null,"EMAIL"),d.a.createElement("th",null,"HOME #"),d.a.createElement("th",null,"SERVICE"))))}return n},a}Object(n.a)(a,e);var t=a.prototype;return t.componentDidMount=function(){!Object(g.c)()&&N&&(window.location.href="/")},t.render=function(){var e,a,t,l,n,r=this.onSearchLeads,o=this.onChangeDropdown,u=this.onChangeInputText,p=this.display,h=this.state,v=h.company,g=h.searchBy,N=h.searchFor;return d.a.createElement(d.a.Fragment,null,d.a.createElement(b.a,{title:"CLIENT ADMIN"}),d.a.createElement("div",{className:"content-wrapper px-4 py-4"},d.a.createElement(c.a,null,d.a.createElement(c.b,null,d.a.createElement(E.a,null,d.a.createElement(m.a,null,d.a.createElement(s.a,{breakPoint:{xs:12}},d.a.createElement("h1",{className:"text-center mb-5"},"CLIENT ADMIN"))),d.a.createElement(m.a,{className:"justify-content-center align-items-center mb-5"},d.a.createElement(s.a,{className:"col-lg-12"},d.a.createElement(c.a,null,d.a.createElement(c.b,{className:"p-5"},d.a.createElement(m.a,null,d.a.createElement(s.a,((e={breakPoint:{xs:12}}).breakPoint={md:4},e),d.a.createElement("label",{htmlFor:"CompanyID"},"Company"),d.a.createElement(y,{options:f.l,placeholder:v.label,value:v.value,id:"CompanyID",name:"CompanyID",onChange:o.bind(this,"company")})),d.a.createElement(s.a,((a={breakPoint:{xs:12}}).breakPoint={md:4},a),d.a.createElement("label",{htmlFor:"SearchVal"},"Search For"),d.a.createElement(C,{fullWidth:!0,size:"Medium",className:"notes"},d.a.createElement("input",{type:"text",placeholder:N,value:N,id:"SearchVal",name:"SearchVal",onChange:u.bind(this)}))),d.a.createElement(s.a,((t={breakPoint:{xs:12}}).breakPoint={md:4},t),d.a.createElement("label",{htmlFor:"SearchBy"},"Search By"),d.a.createElement(y,{options:f.n,placeholder:g.label,value:g.value,id:"SearchBy",name:"SearchBy",onChange:o.bind(this,"searchBy")})),d.a.createElement(s.a,((l={breakPoint:{xs:12}}).breakPoint={md:6},l),d.a.createElement(i.a,{status:"Success",type:"button",shape:"SemiRound",onClick:r},"View Clients"))))))),d.a.createElement(m.a,{className:"justify-content-center align-items-center mb-4"},d.a.createElement(s.a,((n={breakPoint:{xs:12}}).breakPoint={md:12},n),d.a.createElement("h2",{className:"mb-0"},"Results"))),d.a.createElement(m.a,{className:"mb-5"},d.a.createElement(s.a,{id:"main_view"},p(h))))))))},a}(u.Component)},kzC8:function(e,a,t){"use strict";t.d(a,"h",(function(){return r})),t.d(a,"i",(function(){return o})),t.d(a,"c",(function(){return c})),t.d(a,"j",(function(){return i})),t.d(a,"d",(function(){return s})),t.d(a,"o",(function(){return m})),t.d(a,"a",(function(){return u})),t.d(a,"b",(function(){return p})),t.d(a,"e",(function(){return b})),t.d(a,"m",(function(){return h})),t.d(a,"l",(function(){return v})),t.d(a,"n",(function(){return E})),t.d(a,"f",(function(){return g})),t.d(a,"k",(function(){return f}));var l=t("q1tI"),n=t.n(l),r=function(e,a,t,l){var r,o=[],c=1,i=5;l>1&&(c=l,i+=l);for(var s=e>i?i:e,m=e>i,u=c;u<=s;u++)r={},l===u&&(r={fontWeight:600,textDecoration:"underline"}),o[u]=n.a.createElement("li",{className:"page-item",key:u},n.a.createElement("a",{className:"page-link",style:r,href:"/#",onClick:a.bind(void 0,null,t,e,u)},u));if(m){var d=s;1===l&&(d+=1),o[d]=n.a.createElement("li",{className:"page-item"},n.a.createElement("button",{className:"page-link",style:r},"..."))}return o},o=function(e,a,t){return n.a.createElement("div",null,n.a.createElement("input",{type:"number",value:t,onChange:a.bind(void 0,e)}),"/",e)},c="no-product",i=function(e){var a,t,l,n=e.lengthData,r=e.pagination,o=e.current,c=e.perpage,i=e.max,s=e.number;switch(e.type){case"prev":a=1===r?1:r-1,l=o-c,0===o&&(l=o),t=Object.assign({},t,{current:l,pagination:a});break;case"next":a=r===i?i:r+1,l=o+c,o===n-n%c&&(l=o),t=Object.assign({},t,{current:l,pagination:a});break;case"first":t=Object.assign({},t,{pagination:1,current:0});break;case"last":t=Object.assign({},t,{current:c*i-c,pagination:i});break;default:l=s*c-c,1===s&&(l=0),s===n&&(l=n-n%c),t=Object.assign({},t,{current:l,pagination:s})}return t},s=function(e){return null!=e?e.toUpperCase():""},m=function(e,a,t){return e<a?t?1:-1:e>a?t?-1:1:0},u=["None","SP (Self Pay)","NFU (Needs Followup)","NS (Needs Scholarship)","RL (Revisit Later)","TY (Too Young)","TO (Too Old)","M (Medicaid)","PI (Private Insurance)","L (Location)","NC (No Call)"],d=[];d[4]="Phone Call",d[5]="Missed Call",d[6]="Form Fill";var p=[].concat(d),b={Active:"Success",Referred:"Success",Deactivated:"Success",Admin:"Success",All:"Success"},h=[{value:"EmailAddress",label:"Email"},{value:"FirstName",label:"First Name"},{value:"LastName",label:"Last Name"},{value:"CompanyName",label:"Company Name"},{value:"HomePhone",label:"Home Phone"},{value:"WorkPhone",label:"WorkPhone"},{value:"CellPhone",label:"CellPhone"}],v=[{value:"0",label:"All"},{value:"12",label:"Advanced Recovery Systems"},{value:"1",label:"Apex Notes"},{value:"20",label:"At The Crossroads"},{value:"3",label:"Cedar Ridge"},{value:"22",label:"Clearview Girls Academy"},{value:"2",label:"Clearview Horizon"},{value:"7",label:"Elevations"},{value:"21",label:"Elk Mountain"},{value:"10",label:"Family First"},{value:"6",label:"Family Positive Impact"},{value:"16",label:"Gulf Coast Treatment Center"},{value:"13",label:"Journey Pure"},{value:"9",label:"Makana"},{value:"4",label:"MiBoSpi Recovery"},{value:"17",label:"Newport Academy"},{value:"14",label:"Palm Shores Behavioral Health Center"},{value:"8",label:"Red Frog"},{value:"19",label:"Second Chances of Southern Utah"},{value:"23",label:"Soulegria"},{value:"5",label:"Therapy Insider"},{value:"18",label:"Visions Teen Center"},{value:"11",label:"Voyage Recovery"},{value:"15",label:"Voyage Recovery Center"}],E=[{value:"EmailAddress",label:"Email"},{value:"FirstName",label:"First Name"},{value:"LastName",label:"Last Name"},{value:"HomePhone",label:"Home Phone"},{value:"WorkPhone",label:"WorkPhone"},{value:"CellPhone",label:"CellPhone"},{value:"First4",label:"First 4"},{value:"Last4",label:"Last 4"}],g=function(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e)},f=[{value:10,label:"10"},{value:20,label:"20"},{value:30,label:"30"},{value:40,label:"40"}]}}]); //# sourceMappingURL=component---src-pages-clients-search-clients-js-bcc2a6222ab480beeb7e.js.map
6,106
12,115
0.693908
fef07b914c81caf553644f0e817264aefa66b8e8
6,929
js
JavaScript
skin/frontend/ultimo/default/js/tm/ajaxpro/integration.js
stagemteam/magento-tm-ajax-pro
dba7f73aa94372d2f4c41d86d7f19d116cf93e0f
[ "MIT" ]
1
2018-10-15T13:36:52.000Z
2018-10-15T13:36:52.000Z
skin/frontend/ultimo/default/js/tm/ajaxpro/integration.js
stagemteam/magento-tm-ajax-pro
dba7f73aa94372d2f4c41d86d7f19d116cf93e0f
[ "MIT" ]
null
null
null
skin/frontend/ultimo/default/js/tm/ajaxpro/integration.js
stagemteam/magento-tm-ajax-pro
dba7f73aa94372d2f4c41d86d7f19d116cf93e0f
[ "MIT" ]
null
null
null
/* _ _ ____ / \ (_) __ ___ _| _ \ _ __ ___ / _ \ | |/ _` \ \/ / |_) | '__/ _ \ / ___ \ | | (_| |> <| __/| | | (_) | /_/ \_\/ |\__,_/_/\_\_| |_| \___/ |__/ */ document.observe("dom:loaded", function (){ if ('undefined' == typeof SmartHeader) { SmartHeader = false; } /* catalog/product/compare.js*/ AjaxPro.observe('onFailure:catalog:product_compare', function() { if (!AjaxPro.opacity) { return; } if (SmartHeader && jQuery) { jQuery('.sticky-container #mini-compare').last().remove(); } }); AjaxPro.observe('onSuccess:catalog:product_compare', function() { if (SmartHeader && jQuery) { jQuery('.sticky-container #mini-compare').last().remove(); } }); beforeSmartHeaderFix = function () { if (SmartHeader && AjaxPro.config.get('isMobile') == '1') { // console.log('before '); // console.log(jQuery(".mini-compare").length); // jQuery("#mini-compare").remove(); // SmartHeader.moveElementsToRegularPosition(); } }; afterSmartHeaderFix = function() { if (SmartHeader && AjaxPro.config.get('isMobile') == '1') { var length = jQuery('#mini-compare ol li').length; var countEl = jQuery("a[href='#header-compare'] .count"); if (length > 0 && !countEl.length) { jQuery("a[href='#header-compare'] span").last() .before('<span class="count">1</span>'); } if (length == 0) { jQuery("a[href='#header-compare'] .count").remove(); } else { jQuery("a[href='#header-compare'] .count").html(length); } SmartHeader.init(); jQuery('#mini-compare').removeClass('dropdown'); jQuery('.skip-active').removeClass('skip-active'); jQuery(function($) { //Skip Links var skipContents = $('.skip-content'); var skipLinks = $('.skip-link'); skipLinks.off('click').on('click', function (e) { e.preventDefault(); var self = $(this); var target = self.attr('href'); //Get target element var elem = $(target); //Check if stub is open var isSkipContentOpen = elem.hasClass('skip-active') ? 1 : 0; //Hide all stubs skipLinks.removeClass('skip-active'); skipContents.removeClass('skip-active'); //Toggle stubs if (isSkipContentOpen) { self.removeClass('skip-active'); } else { self.addClass('skip-active'); elem.addClass('skip-active'); } }); }); } }; AjaxPro.observe('onSuccess:catalog:product_compare:before', beforeSmartHeaderFix); AjaxPro.observe('onSuccess:catalog:product_compare:after', afterSmartHeaderFix); // AjaxPro.observe('onFailure:catalog:product_compare:before', beforeSmartHeaderFix); // AjaxPro.observe('onFailure:catalog:product_compare:after', afterSmartHeaderFix); console.log('ajaxpro ultimo compare.js patch was running'); /* checkout/cart.js*/ AjaxPro.observe('onFailure:checkout', function() { if (!AjaxPro.opacity) { return; } if (SmartHeader && jQuery) { jQuery('.sticky-container #mini-cart').last().remove(); } }); AjaxPro.observe('onSuccess:checkout', function() { if (SmartHeader && jQuery) { jQuery('.sticky-container #mini-cart').last().remove(); } }); // if (AjaxPro.config.get('isMobile') == '1') { beforeSmartHeaderFix = function () { if (SmartHeader && AjaxPro.config.get('isMobile') == '1') { jQuery("#mini-cart").remove(); // SmartHeader.moveElementsToRegularPosition(); } }; afterSmartHeaderFix = function() { if (SmartHeader && AjaxPro.config.get('isMobile') == '1') { jQuery('#mini-cart-wrapper-mobile').prepend(jQuery('#mini-cart')); jQuery('#mini-cart').removeClass('dropdown'); jQuery('.skip-active').removeClass('skip-active'); //Skip Links var skipContents = jQuery('.skip-content'); var skipLinks = jQuery('.skip-link'); skipLinks.off('click').on('click', function (e) { e.preventDefault(); var self = jQuery(this); var target = self.attr('href'); //Get target element var elem = jQuery(target); //Check if stub is open var isSkipContentOpen = elem.hasClass('skip-active') ? 1 : 0; //Hide all stubs skipLinks.removeClass('skip-active'); skipContents.removeClass('skip-active'); //Toggle stubs if (isSkipContentOpen) { self.removeClass('skip-active'); } else { self.addClass('skip-active'); elem.addClass('skip-active'); } }); } }; AjaxPro.observe('onSuccess:checkout:before', beforeSmartHeaderFix); AjaxPro.observe('onSuccess:checkout:after', afterSmartHeaderFix); // AjaxPro.observe('onFailure:checkout:before', beforeSmartHeaderFix); // AjaxPro.observe('onFailure:checkout:after', afterSmartHeaderFix); console.log('ajaxpro ultimo cart.js patch running'); // } // var theHeaderContainer = jQuery('#header-container'); if ("function" == typeof theHeaderContainer.smartheader && "undefined" != typeof smartHeaderSettings) { // jQuery.widget("infortis.smartheader", jQuery.infortis.smartheader, { // reinit: function() { // this._deferredInit(); // return true; // } // }); var theHeaderContainer = jQuery('#header-container'); if ("function" == typeof theHeaderContainer.smartheader && "undefined" != typeof smartHeaderSettings) { ajxproSmartHeaderReinit = function(){ theHeaderContainer.smartheader(smartHeaderSettings); theHeaderContainer.smartheader('reinit'); }; AjaxPro.observe('onComplete:checkout:after', ajxproSmartHeaderReinit); AjaxPro.observe('onComplete:catalog:product_compare:after', ajxproSmartHeaderReinit); } } });
34.994949
93
0.51335
fef0a53f80c8da89684719e8c2833e6aca869f08
33
js
JavaScript
es/can-key.js
DesignByOnyx/canjs
4252bf3d07a125910ccad147f351f32c107ffb73
[ "MIT" ]
823
2015-10-30T18:18:20.000Z
2022-03-31T19:44:59.000Z
es/can-key.js
MedRedha/canjs
f897f937751ca27c3b918b1f16e8d17f267c5a58
[ "MIT" ]
2,023
2015-10-29T20:20:54.000Z
2022-03-06T09:01:50.000Z
es/can-key.js
MedRedha/canjs
f897f937751ca27c3b918b1f16e8d17f267c5a58
[ "MIT" ]
203
2015-11-03T14:01:55.000Z
2022-02-03T17:58:16.000Z
export {default} from "can-key";
16.5
32
0.69697
fef14d387cfeac503d7e49c58ecb7520d5eb5cf6
2,003
js
JavaScript
src/components/parts/listItem/index.js
Abdi-VGW/front-end-testin
fbc2dfefe08112ea5920f3d43ae2fc26f0f087b4
[ "MIT" ]
1
2020-06-09T14:53:41.000Z
2020-06-09T14:53:41.000Z
src/components/parts/listItem/index.js
Abdi-VGW/front-end-testin
fbc2dfefe08112ea5920f3d43ae2fc26f0f087b4
[ "MIT" ]
5
2021-10-19T07:03:37.000Z
2021-10-19T07:03:39.000Z
src/components/parts/listItem/index.js
Abdi-VGW/front-end-testin
fbc2dfefe08112ea5920f3d43ae2fc26f0f087b4
[ "MIT" ]
3
2020-05-03T06:22:47.000Z
2020-05-04T08:47:44.000Z
import React, { useRef, useState } from 'react'; import Delete from '../../icons/delete'; import Edit from '../../icons/edit'; import Close from '../../icons/close'; import Check from '../../icons/check'; const Item = ({ index, taskId, id, completed, name, functions }) => { const ref = useRef(null), [editTaskOpen, openEditTask] = useState(false); return ( <li key={index} ref={ref} data-id={id}> <input type="checkbox" name={`checkbox`} defaultChecked={completed} onChange={(e) => { functions.completeTask(ref, e); }} id={`${taskId}_checkbox`} /> <label htmlFor={`${taskId}_checkbox`} > <Check className="check" /> <span>{name}</span> </label> <button className="icon" onClick={() => openEditTask(!editTaskOpen)}> <Edit /> <span className="sr-only">Edit Task</span> </button> <div className="modal" open={editTaskOpen}> <button className="icon close" onClick={() => openEditTask(!editTaskOpen)}> <Close /> <span className="sr-only">Close Modal</span> </button> <form onSubmit={(e) => { functions.changeLabelForm(ref, e); }}> <legend>Edit Task</legend> <input type="checkbox" name={`checkbox_modal`} defaultChecked={completed} onChange={(e) => { functions.completeTask(ref, e); }} id={`${taskId}_checkbox_modal`} /> <label htmlFor={`${taskId}_checkbox_modal`} > <Check className="check" /> <span className="sr-only"> {completed ? `Uncomplete` : `Complete`} {name} </span> </label> <label className="sr-only">Edit {name}</label> <input type="text" defaultValue={name} name={`label`} onChange={(e) => { functions.changeLabel(ref, e); }} /> <button className="icon remove" type="button" onClick={() => functions.deleteTask(index)}> <Delete /> <span className="sr-only">Delete Task</span> </button> </form> </div> </li> ); }; export default Item;
27.438356
95
0.589116
fef2203ab1128cca12c1a97f21d91a1a118ee313
599
js
JavaScript
assets/quotes.js
burhan1122/hi-ava
1cfa65fb8847e3a23cef4b796ec07bf3ad5b0336
[ "MIT" ]
null
null
null
assets/quotes.js
burhan1122/hi-ava
1cfa65fb8847e3a23cef4b796ec07bf3ad5b0336
[ "MIT" ]
null
null
null
assets/quotes.js
burhan1122/hi-ava
1cfa65fb8847e3a23cef4b796ec07bf3ad5b0336
[ "MIT" ]
null
null
null
// prettier-ignore export default [ { author: "Ahmad Burhanuddin", quotes: "jangan berubah ya aku udah sayang kamu" }, { author: "Ahmad Burhanuddin", quotes: "jaga kesehatan terus kamu ❤" }, { author: "Ahmad Burhanuddin", quotes: "Thanks , For Loving Me❤" }, { author: "Ahmad Burhanuddin", quotes: "kapan ketemu lagi udah kangen berat nih" }, { author: "Ahmad Burhanuddin", quotes: "kapan aku bisa main ke rumah kamu ?" }, { author: "Ahmad Burhanuddin", quotes: "apakah aku bisa menjadi imam kamu ?" }, { author: "Ahmad Burhanuddin", quotes: "ILY , so much dear ❤" }, ];
54.454545
87
0.659432
fef292252b0aa2141501fffd85513eb30ced3abb
4,649
js
JavaScript
GloryMorning_front/src/container/Popup.js
westkite1201/gloryMorning
2c654ef38d9c793e9339ca1d442810497cbfef04
[ "MIT" ]
null
null
null
GloryMorning_front/src/container/Popup.js
westkite1201/gloryMorning
2c654ef38d9c793e9339ca1d442810497cbfef04
[ "MIT" ]
10
2019-07-06T11:16:35.000Z
2021-05-09T06:56:05.000Z
GloryMorning_front/src/container/Popup.js
westkite1201/gloryMorning
2c654ef38d9c793e9339ca1d442810497cbfef04
[ "MIT" ]
null
null
null
/*global kakao */ import React, { useEffect } from 'react'; import './popup.scss'; import { observer } from 'mobx-react'; import UseStores from '../components/Setting/UseStores'; import SearchAddressDaum from '../components/Setting/SearchAddress/SearchAddressDaum'; let map; const Map = observer(() => { const { search } = UseStores(); useEffect(() => { mapscript(); }, []); function panTo(lat, lng) { console.log('[seo] lat = ', lat, 'lng = ', lng); // 이동할 위도 경도 위치를 생성합니다 var moveLatLon = new kakao.maps.LatLng(lat, lng); // 지도 중심을 부드럽게 이동시킵니다 // 만약 이동할 거리가 지도 화면보다 크면 부드러운 효과 없이 이동합니다 map.panTo(moveLatLon); } useEffect(() => { console.log('[seo] selectedAddress', search.selectedAddress); const { x, y } = search.selectedAddress; let lat = parseFloat(y); let lng = parseFloat(x); if (lat && lng) panTo(lat, lng); }, [search.selectedAddress]); const mapscript = () => { let container = document.getElementById('map'); let options = { center: new kakao.maps.LatLng(37.624915253753194, 127.15122688059974), level: 5, }; //map map = new kakao.maps.Map(container, options); //마커가 표시 될 위치 let markerPosition = new kakao.maps.LatLng( 37.62197524055062, 127.16017523675508, ); // 마커를 생성 // let marker = new kakao.maps.Marker({ // position: markerPosition, // }); // // 마커를 지도 위에 표시 // marker.setMap(map); // 주소-좌표 변환 객체를 생성합니다 var geocoder = new kakao.maps.services.Geocoder(); var marker = new kakao.maps.Marker(), // 클릭한 위치를 표시할 마커입니다 infowindow = new kakao.maps.InfoWindow({ zindex: 1 }); // 클릭한 위치에 대한 주소를 표시할 인포윈도우입니다 // 현재 지도 중심좌표로 주소를 검색해서 지도 좌측 상단에 표시합니다 searchAddrFromCoords(map.getCenter(), displayCenterInfo); // 지도를 클릭했을 때 클릭 위치 좌표에 대한 주소정보를 표시하도록 이벤트를 등록합니다 kakao.maps.event.addListener(map, 'click', function(mouseEvent) { searchDetailAddrFromCoords(mouseEvent.latLng, function(result, status) { if (status === kakao.maps.services.Status.OK) { var detailAddr = !!result[0].road_address ? '<div>도로명주소 : ' + result[0].road_address.address_name + '</div>' : ''; detailAddr += '<div>지번 주소 : ' + result[0].address.address_name + '</div>'; var content = '<div class="bAddr">' + '<span class="title">법정동 주소정보</span>' + detailAddr + '</div>'; // 마커를 클릭한 위치에 표시합니다 marker.setPosition(mouseEvent.latLng); marker.setMap(map); // 인포윈도우에 클릭한 위치에 대한 법정동 상세 주소정보를 표시합니다 infowindow.setContent(content); infowindow.open(map, marker); } }); }); // 중심 좌표나 확대 수준이 변경됐을 때 지도 중심 좌표에 대한 주소 정보를 표시하도록 이벤트를 등록합니다 kakao.maps.event.addListener(map, 'idle', function() { searchAddrFromCoords(map.getCenter(), displayCenterInfo); }); function searchAddrFromCoords(coords, callback) { // 좌표로 행정동 주소 정보를 요청합니다 geocoder.coord2RegionCode(coords.getLng(), coords.getLat(), callback); } function searchDetailAddrFromCoords(coords, callback) { // 좌표로 법정동 상세 주소 정보를 요청합니다 geocoder.coord2Address(coords.getLng(), coords.getLat(), callback); } // 지도 좌측상단에 지도 중심좌표에 대한 주소정보를 표출하는 함수입니다 function displayCenterInfo(result, status) { if (status === kakao.maps.services.Status.OK) { var infoDiv = document.getElementById('centerAddr'); for (var i = 0; i < result.length; i++) { // 행정동의 region_type 값은 'H' 이므로 if (result[i].region_type === 'H') { infoDiv.innerHTML = result[i].address_name; break; } } } } }; // function setCenter() { // // 이동할 위도 경도 위치를 생성합니다 // var moveLatLon = new kakao.maps.LatLng(33.452613, 126.570888); // // 지도 중심을 이동 시킵니다 // map.setCenter(moveLatLon); // } // function panTo() { // // 이동할 위도 경도 위치를 생성합니다 // var moveLatLon = new kakao.maps.LatLng(33.45058, 126.574942); // // 지도 중심을 부드럽게 이동시킵니다 // // 만약 이동할 거리가 지도 화면보다 크면 부드러운 효과 없이 이동합니다 // map.panTo(moveLatLon); // } return ( <div className="map_wrap"> <SearchAddressDaum /> <div id="map" style={{ width: '100%', height: '100%', position: 'relative', overflow: 'hidden', }} > <div className="hAddr"> <span className="title">지도중심기준 행정동 주소정보</span> <span id="centerAddr"></span> </div> </div> </div> ); }); export default Map;
28.875776
91
0.579049
fef2ae7f710dfedff68c40a5631240de511298a0
1,264
js
JavaScript
angularjs/app/components/requests/requests.controller.js
henryqrm/studies
910bbdcc0b2b702e54a48b196a7b686771979ace
[ "MIT" ]
null
null
null
angularjs/app/components/requests/requests.controller.js
henryqrm/studies
910bbdcc0b2b702e54a48b196a7b686771979ace
[ "MIT" ]
null
null
null
angularjs/app/components/requests/requests.controller.js
henryqrm/studies
910bbdcc0b2b702e54a48b196a7b686771979ace
[ "MIT" ]
null
null
null
angular.module('angular.requests.controller',[]) .controller('RequestsCtrl',['$q','$http','$scope', function ($q, $http, $scope) { // Aqui deveria ser um service var _token = null; var API_ENDPOINT = 'http://45.55.153.158/api'; var GetProfile = API_ENDPOINT + '/profile'; var Authenticate = API_ENDPOINT + '/auth/authorize'; console.log(Authenticate); $scope.email = 'autop@autopveiculos.com.br'; $scope.password = '123456'; $scope.methodPost = function () { var defer = $q.defer(); $http.post(Authenticate, { email: $scope.email, password: $scope.password }).success(function (token) { console.log(token); _token = token; defer.resolve(token); }).error(function (error) { console.log(error); defer.reject(error); }); return defer.promise; }; $scope.methodGet = function () { if(_token === null){ console.log("Execute o post"); return; } var defer = $q.defer(); $http.defaults.headers.common.Authorization = _token.access_token; $http.get(GetProfile) .success(function (userDate) { console.log(userDate); defer.resolve(userDate); }) .error(function (error) { defer.reject(error); console.log(error); }); return defer.promise; }; } ]);
25.795918
69
0.634494
fef323870a42c37aed2f09005b5ed516ab8473f0
133
js
JavaScript
lib/sw_services/xilskey/doc/html/api/xilskey__puf__registration_8c.js
simonbeaudoin0935/embeddedsw
a60c084a0862559e2fa58fd4c82b0fe39b923e33
[ "BSD-2-Clause", "MIT" ]
1
2021-06-02T22:36:08.000Z
2021-06-02T22:36:08.000Z
lib/sw_services/xilskey/doc/html/api/xilskey__puf__registration_8c.js
simonbeaudoin0935/embeddedsw
a60c084a0862559e2fa58fd4c82b0fe39b923e33
[ "BSD-2-Clause", "MIT" ]
null
null
null
lib/sw_services/xilskey/doc/html/api/xilskey__puf__registration_8c.js
simonbeaudoin0935/embeddedsw
a60c084a0862559e2fa58fd4c82b0fe39b923e33
[ "BSD-2-Clause", "MIT" ]
1
2020-11-03T00:52:01.000Z
2020-11-03T00:52:01.000Z
var xilskey__puf__registration_8c = [ [ "main", "xilskey__puf__registration_8c.html#ae66f6b31b5ad750f1fe042a706a4e3d4", null ] ];
33.25
92
0.796992
fef340cf010e228c5edbe9640836ee65decfe45d
1,430
js
JavaScript
example-pwa/nothing/src/play-type.js
raoul2000/js-playground
d5d0024691ab7723478b8b939b5c35e6986aa7e7
[ "MIT" ]
1
2017-10-15T01:49:27.000Z
2017-10-15T01:49:27.000Z
example-pwa/nothing/src/play-type.js
raoul2000/js-playground
d5d0024691ab7723478b8b939b5c35e6986aa7e7
[ "MIT" ]
21
2020-06-18T14:35:38.000Z
2022-03-23T10:57:32.000Z
example-pwa/nothing/src/play-type.js
raoul2000/js-playground
d5d0024691ab7723478b8b939b5c35e6986aa7e7
[ "MIT" ]
null
null
null
// ts-check // chack : https://github.com/mike-works/vscode-fundamentals/blob/master/docs/1_using/type-checking.md /** @type {number} */ let value; value = "ee"; /** @type {number} */ let age; // @ts-ignore age = "young"; /** * @type {Element} holds a referenbce to the password * field containers. Use with care ! */ //let myDiv = document.querySelector('.passwordField'); let myDiv = "ee"; /** * describe function * * @param {string} a param a * @param {number} b a number */ function f1(a,b){ console.log("boo"); } f1(1,"E"); /** * Create a Widget * * @param {number} id the widget id * @returns {Widget} */ function createWidget(id) { return { "name" : "weather", "id" : id, "color" : "red", "renderToDashboard" : function(A,Z) { return "ee"; } }; } let w1 = getWidget(1); w1.renderToDashboard(12); w1.id = "ZZ"; /** * @type {Greeter} */ let greet; greet = new Greeter("hello"); greet.showGreeting("hi"); let labelObject = { "label" : "hello", "qty" : 12 }; printLabel(labelObject); let wrongLabelObject = { "no_label" : "hello", "qty" : 12 }; printLabel(wrongLabelObject);// ERROR printLabel({label : "ee"}); // ERROR printLabel({label : "ee", "prop" : "ee"}); // ERROR printLabel(3); /** * Let's play with readonly property * @type {Point} */ let p1; p1 = { "x" : 12, "y" : 33 }; p1.x = 4; // ERROR
16.25
102
0.572727
fef3aa7e1beddd95543dffa6e2c80e13565f2241
1,722
js
JavaScript
app/core/boot.js
homercade/cosoblanca
e54477f3d1e6c12b33913cdf05a710e7694d1717
[ "MIT" ]
null
null
null
app/core/boot.js
homercade/cosoblanca
e54477f3d1e6c12b33913cdf05a710e7694d1717
[ "MIT" ]
1
2019-03-04T08:54:38.000Z
2019-03-04T08:58:14.000Z
app/core/boot.js
homercade/cosoblanca
e54477f3d1e6c12b33913cdf05a710e7694d1717
[ "MIT" ]
null
null
null
var morgan = require('morgan'); var path = require('path'); var bodyParser = require('body-parser'); var serveStatic = require('serve-static'); var sessions = require('express-session'); var expressValidator = require('express-validator'); // var flash = require('connect-flash'); // var crypto = require('crypto'); // var passport = require('passport'); // var LocalStrategy = require('passport-local').Strategy; // var sess = require('express-session'); // var Store = require('express-session').Store; // var BetterMemoryStore = require(__dirname + '/memory'); module.exports = app => { app.set('port', process.argv[2] || process.env.PORT || 3000); app.set('view engine', 'pug'); app.set('views', path.join(path.dirname(__dirname), 'modules')); app.use(morgan('dev')); app.use(serveStatic(path.join(path.dirname(path.dirname(__dirname)), 'public'))); app.use(expressValidator()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(sessions({ secret: 'qnJxRTHpJlDSGCtkUSxtPbuNfrWBHFSaKWlWPLnCIJYijzy', resave: false, saveUninitialized: true })) // app.use(flash()); // app.use(passport.initialize()); // app.use(passport.session()); // app.use(cors()); // app.use(session({ secret: 'passport-cosdd', cookie: { maxAge: 600000 }, resave: false, saveUninitialized: false })) // app.get('/', (req, res) => res.redirect('/login')); // var store = new BetterMemoryStore({ expires: 60 * 60 * 1000, debug: true }); // app.use(sess({ // name: 'JSESSION', // secret: 'MYSECRETISVERYSECRET', // store: store, // resave: true, // saveUninitialized: true // })); }
31.309091
122
0.635308
5783e6de483399d4fb26ac3e818e470f1c6af99f
817
js
JavaScript
xiaojingzhao/examples/worker-threads/work-thread.js
bricktile/onehoureveryday
f75a44dd708bc1755d4a5683b1bdfb256fc361ba
[ "MIT" ]
3
2020-03-04T15:14:39.000Z
2020-06-06T07:49:39.000Z
xiaojingzhao/examples/worker-threads/work-thread.js
bricktile/onehoureveryday
f75a44dd708bc1755d4a5683b1bdfb256fc361ba
[ "MIT" ]
3
2020-03-20T15:32:16.000Z
2020-03-20T15:41:19.000Z
xiaojingzhao/examples/worker-threads/work-thread.js
bricktile/happy-hour
f75a44dd708bc1755d4a5683b1bdfb256fc361ba
[ "MIT" ]
null
null
null
const { Worker, isMainThread, parentPort, workerData } = require("worker_threads"); let a = 10; if (isMainThread) { module.exports = async function parseJSAsync(num) { return new Promise((resolve, reject) => { const worker = new Worker(__filename, { workerData: num }); worker.on("message", resolve); worker.on("error", reject); worker.on("exit", code => { if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`)); }); for (let i = 0; i < num; i++) { console.log("master: ", a); a++; } }); }; } else { const num = workerData; let result = 1; for (let i = 1; i < num; i++) { console.log("worker: ", a); a--; result = result * i; } parentPort.postMessage(result); }
20.948718
69
0.536108
5784d96b5c1e157cb162ca23256eeb555e3c1e8f
1,248
js
JavaScript
src/components/Steps.bojagi.js
Bojagi/example-ant-design
e113bb7d953340cb15112642d908574b94273129
[ "MIT" ]
null
null
null
src/components/Steps.bojagi.js
Bojagi/example-ant-design
e113bb7d953340cb15112642d908574b94273129
[ "MIT" ]
24
2020-09-14T23:31:05.000Z
2022-02-26T23:26:28.000Z
src/components/Steps.bojagi.js
Bojagi/example-ant-design
e113bb7d953340cb15112642d908574b94273129
[ "MIT" ]
null
null
null
import React from 'react'; import Steps from './Steps'; import { Icon } from 'antd'; const { Step } = Steps; export default { title: 'Steps', }; export const Basic = () => <Steps current={1}> <Step title="Finished" description="This is a description." /> <Step title="In Progress" subTitle="Left 00:00:08" description="This is a description." /> <Step title="Waiting" description="This is a description." /> </Steps> export const MiniVersion = () => <Steps size="small" current={1}> <Step title="Finished" /> <Step title="In Progress" /> <Step title="Waiting" /> </Steps> export const WithIcons = () => <Steps> <Step status="finish" title="Login" icon={<Icon type="user" />} /> <Step status="finish" title="Verification" icon={<Icon type="solution" />} /> <Step status="process" title="Pay" icon={<Icon type="loading" />} /> <Step status="wait" title="Done" icon={<Icon type="smile-o" />} /> </Steps> export const Vertical = () => <Steps direction="vertical" current={1}> <Step title="Finished" description="This is a description." /> <Step title="In Progress" description="This is a description." /> <Step title="Waiting" description="This is a description." /> </Steps>
32.842105
94
0.633013
57851b39bb67469999329325f3d3e4606d322119
680
js
JavaScript
nvison/TEST/api-test/colon/colon.tst.js
navegador5/nvison
03b6665ddc5b4649727e13de50378e29b0dd96bf
[ "ISC" ]
null
null
null
nvison/TEST/api-test/colon/colon.tst.js
navegador5/nvison
03b6665ddc5b4649727e13de50378e29b0dd96bf
[ "ISC" ]
null
null
null
nvison/TEST/api-test/colon/colon.tst.js
navegador5/nvison
03b6665ddc5b4649727e13de50378e29b0dd96bf
[ "ISC" ]
null
null
null
const ison = require("/opt/JS/NV5_/nvison/nvison/index") const path = require("path"); console.log(path.resolve(__dirname,__filename)) var real = ison.parse_from_file("./colon.ison"); var should_be = [ { a: 'b', c: 'd', e: 'f' }, { a: 'b', c: 'd', e: 'f' }, { a: 'b', c: 'd', e: 'f', g: 'h' }, { a: 'b', key: 'value' }, { a: 'b', key: 'value' }, { a: 'b', key: 'value' }, [ 100, 'xy' ], [ 'abc', 123 ], { k: 'abc', k3: 'v3' }, { k: 'abc', k3: 'v3' }, { k: 'abc', k3: 'v3' }, { k: 'abc', k2: 'v2' }, [ 'abc', 666 ], { '100': 200, k: 'v', key: 'value' } ] const assert = require("assert") assert.deepStrictEqual(real,should_be) console.log(real);
22.666667
56
0.494118
5785444ac7ce69ebfbe632904c4b4a2f40fec169
459
js
JavaScript
generators/app/templates/gulpfile.babel.js
MasahiroHarada/generator-hypertext
b5d9773d6ccd8cfa9c66876aa6e036118c619b49
[ "MIT" ]
null
null
null
generators/app/templates/gulpfile.babel.js
MasahiroHarada/generator-hypertext
b5d9773d6ccd8cfa9c66876aa6e036118c619b49
[ "MIT" ]
2
2020-05-01T04:06:22.000Z
2021-05-10T23:43:30.000Z
generators/app/templates/gulpfile.babel.js
MasahiroHarada/generator-hypertext
b5d9773d6ccd8cfa9c66876aa6e036118c619b49
[ "MIT" ]
null
null
null
import { parallel, series } from 'gulp'; import { serve } from './tasks/server'; import { ejs } from './tasks/ejs'; import { bundle } from './tasks/bundle'; import { stylelint } from './tasks/styles'; import { clear } from './tasks/clear'; import { watchFiles } from './tasks/watch'; export const dev = series( clear, parallel(ejs, stylelint, bundle), serve, watchFiles ); export const build = series( clear, parallel(ejs, stylelint, bundle) );
22.95
43
0.666667
5785965154af224c1c25dc8d31bb0d726d5be97a
448
js
JavaScript
API/src/appConfig/routing.js
kingoftherats/hotdamn
a0aa279b1ff77061fee6cbee0dac8604a61543d4
[ "MIT" ]
null
null
null
API/src/appConfig/routing.js
kingoftherats/hotdamn
a0aa279b1ff77061fee6cbee0dac8604a61543d4
[ "MIT" ]
1
2021-05-11T16:45:43.000Z
2021-05-11T16:45:43.000Z
API/src/appConfig/routing.js
kingoftherats/hotdamn
a0aa279b1ff77061fee6cbee0dac8604a61543d4
[ "MIT" ]
null
null
null
import storeController from '../controllers/storeController' const routing = () => { return { registerRoutes: (expressApp, appConfig) => { //Add application controllers storeController(expressApp, appConfig); //Catch-all route expressApp.get('*', function(req, res) { res.send('Sorry, this is an invalid URL.'); }); } } } export default routing;
26.352941
60
0.560268
57868177ed2b0795dbbf5d747904a07857e11f87
189
js
JavaScript
src/module-system/a-mail/backend/src/model/mail.js
husirb/cabloy
a450e6d7724895b5b9dde1dac2b605bfbddacdb9
[ "MIT" ]
553
2018-07-17T15:52:19.000Z
2022-03-31T14:00:36.000Z
src/module-system/a-mail/backend/src/model/mail.js
kisskillkiss/cabloy
998970a35ef0f992ddce871bfaed3a4df4044242
[ "MIT" ]
18
2018-08-21T05:02:42.000Z
2022-02-19T03:44:57.000Z
src/module-system/a-mail/backend/src/model/mail.js
kisskillkiss/cabloy
998970a35ef0f992ddce871bfaed3a4df4044242
[ "MIT" ]
89
2018-07-18T08:51:23.000Z
2022-03-06T23:09:04.000Z
module.exports = app => { class Mail extends app.meta.Model { constructor(ctx) { super(ctx, { table: 'aMail', options: { disableDeleted: false } }); } } return Mail; };
21
73
0.592593
5786f42851d61524e6bfa32202ca991c10d051cb
713
js
JavaScript
tests/baselines/reference/ts-ignore.js
monciego/TypeScript
06fb30725d4a70708b28f2a4613543ce8c4cd645
[ "Apache-2.0" ]
49,134
2015-01-01T02:37:27.000Z
2019-05-06T20:38:53.000Z
tests/baselines/reference/ts-ignore.js
IvanJasenov/TypeScript
ff2ff98ee45a18cd221a425508a1e0c8a1bbe4a2
[ "Apache-2.0" ]
26,488
2015-01-01T13:57:03.000Z
2019-05-06T20:40:00.000Z
tests/baselines/reference/ts-ignore.js
IvanJasenov/TypeScript
ff2ff98ee45a18cd221a425508a1e0c8a1bbe4a2
[ "Apache-2.0" ]
8,518
2015-01-05T03:29:29.000Z
2019-05-06T14:37:49.000Z
//// [ts-ignore.ts] // @ts-ignore with additional commenting var invalidCommentedFancy: number = 'nope'; // @ts-ignore with additional commenting var validCommentedFancy: string = 'nope'; // @ts-ignore var invalidCommentedPlain: number = 'nope'; // @ts-ignore var validCommentedPlain: string = 'nope'; var invalidPlain: number = 'nope'; var validPlain: string = 'nope'; //// [ts-ignore.js] // @ts-ignore with additional commenting var invalidCommentedFancy = 'nope'; // @ts-ignore with additional commenting var validCommentedFancy = 'nope'; // @ts-ignore var invalidCommentedPlain = 'nope'; // @ts-ignore var validCommentedPlain = 'nope'; var invalidPlain = 'nope'; var validPlain = 'nope';
23.766667
43
0.706872
578890d237dcc1a0ab2f610d9482a1ab63b66aab
4,479
js
JavaScript
src/components/SearchScreen/index.js
Poussinou/M-Droid
1a18cc525486edf89b70018ab5fd06290f15f0a9
[ "MIT" ]
82
2017-12-27T22:24:41.000Z
2022-03-26T11:21:54.000Z
src/components/SearchScreen/index.js
Poussinou/M-Droid
1a18cc525486edf89b70018ab5fd06290f15f0a9
[ "MIT" ]
27
2017-12-29T16:28:28.000Z
2021-09-25T15:39:34.000Z
src/components/SearchScreen/index.js
Poussinou/M-Droid
1a18cc525486edf89b70018ab5fd06290f15f0a9
[ "MIT" ]
8
2018-01-04T16:09:33.000Z
2021-10-05T15:51:57.000Z
import React, { Component } from 'react'; import { View, Text, FlatList } from 'react-native'; import PropTypes from 'prop-types'; import Icon from 'react-native-vector-icons/MaterialIcons'; import SearchInput, { createFilter } from 'react-native-search-filter'; import MenuButton from '../MenuButton'; import SearchResultRow from '../SearchResultRow'; import EmptyPlaceholder from '../EmptyPlaceholder'; import sharedStyles from '../../styles/sharedStyles'; import styles from './styles'; import { removeDuplicates } from '../../utils'; const KEYS_TO_FILTERS = ['name', 'summary', 'description', 'id', 'author']; class SearchScreen extends Component { constructor(props) { super(props); } render() { const { params } = this.props.navigation.state; const { apps } = this.props; const searchResults = params.searchQuery === '' ? null : apps.filter(createFilter(params.searchQuery, KEYS_TO_FILTERS)); if (searchResults === null) { return ( <View style={styles.container}> <View style={sharedStyles.emptyWrapper}> <EmptyPlaceholder animate={true} animType={'shake'} animLoop={false} icon={'regex'} title={'Type to search'} tagline={'We\'ll show you a list of results once you type something...'} /> </View> </View> ); } return <View style={styles.container}>{this.renderResults(searchResults)}</View>; } renderItem = ({ item }) => ( <SearchResultRow elevation={2} appName={item.name} appIconPath={item.icon} appSummary={item.summary} onPress={() => this.props.openDetails(item)} /> ); renderResults = results => { const { params } = this.props.navigation.state; if (results.length <= 0) { return ( <View style={sharedStyles.emptyWrapper}> <EmptyPlaceholder animate={true} animType={'shake'} animLoop={false} icon={'emoticon-dead'} title={'Snap! No results!'} tagline={'Try with a different query or use differents keywords...'} /> </View> ); } const uniqResults = removeDuplicates( results, (item, t) => t.id === item.id && t.name === item.name ); return ( <View style={styles.container}> <FlatList ListHeaderComponent={() => ( <View style={styles.row}> <Icon name={'search'} size={22} color={'black'} /> <Text style={styles.resultsTitle}> Results for <Text style={styles.resultHighlight}>{params.searchQuery}</Text> </Text> </View> )} style={styles.results} showsVerticalScrollIndicator={false} keyboardDismissMode={'on-drag'} keyboardShouldPersistTaps={'handled'} keyExtractor={item => item.id} data={uniqResults} renderItem={this.renderItem} /> </View> ); }; } SearchScreen.propTypes = { navigation: PropTypes.any.isRequired, apps: PropTypes.array.isRequired, openDetails: PropTypes.func.isRequired }; SearchScreen.navigationOptions = ({ navigation }) => ({ title: 'Search', headerTintColor: sharedStyles.HEADER_COLOR, headerStyle: { backgroundColor: sharedStyles.HEADER_COLOR }, headerTitleStyle: styles.searchInput, headerTitle: ( <View style={styles.headerWrapper}> <SearchInput autoFocus={true} fuzzy={true} sortResults={true} inputViewStyles={styles.searchInput} style={styles.searchInputText} placeholder={'Search app...'} placeholderTextColor={sharedStyles.HEADER_TEXT_COLOR} onChangeText={term => { navigation.setParams({ searchQuery: term }); }} value={navigation.state.params.searchQuery && navigation.state.params.searchQuery} /> </View> ), headerLeft: ( <MenuButton navigation={navigation} iconName={'arrow-back'} color={sharedStyles.HEADER_TEXT_COLOR} onPress={() => navigation.goBack()} /> ), headerRight: ( <MenuButton iconName={navigation.state.params.searchQuery === '' ? 'search' : 'close'} color={sharedStyles.HEADER_TEXT_COLOR} onPress={() => navigation.setParams({ searchQuery: '' })} /> ) }); export default SearchScreen;
28.896774
92
0.597008
578997d1ec061e3c2849a23410d5e123685783af
21,898
js
JavaScript
app/webroot/js/vendor/tigomusic.bak.js
jnartey/Tigo-Music-Ghana
6b489baece44469467cd14ad8fb85bcc74d6d203
[ "MIT" ]
null
null
null
app/webroot/js/vendor/tigomusic.bak.js
jnartey/Tigo-Music-Ghana
6b489baece44469467cd14ad8fb85bcc74d6d203
[ "MIT" ]
null
null
null
app/webroot/js/vendor/tigomusic.bak.js
jnartey/Tigo-Music-Ghana
6b489baece44469467cd14ad8fb85bcc74d6d203
[ "MIT" ]
null
null
null
//Custom Deezer player by Jacob Nartey $(document).ready(function() { $("#controls input").attr('disabled', true); $("#slider_seek").click(function(evt, arg) { var left = evt.offsetX; DZ.player.seek((evt.offsetX / $(this).width()) * 100); }); }); function addStyleAttribute($element, styleAttribute) { $element.attr('style', $element.attr('style') + '; ' + styleAttribute); } //Format numbers less than 9 to 2 digits function twoDigits(n) { return n > 9 ? "" + n : "0" + n; } //convert seconds to minutes and seconds function secondsToTime(secs) { var hours = Math.floor(secs / (60 * 60)); var divisor_for_minutes = secs % (60 * 60); var minutes = Math.floor(divisor_for_minutes / 60); var divisor_for_seconds = divisor_for_minutes % 60; var seconds = Math.ceil(divisor_for_seconds); return minutes + ':' + twoDigits(seconds); } $('#controls #play').on('click', function() { DZ.player.play(); }); $('#controls #pause').on('click', function() { DZ.player.pause(); }); $('#controls #play').on('click', function() { DZ.player.play(); }); $('#controls #pause').on('click', function() { DZ.player.pause(); }); $('#controls #previous').on('click', function() { DZ.player.prev(); }); $('#controls #next').on('click', function() { DZ.player.next(); }); $('#deezer-volume #sound').on('click', function() { DZ.player.setVolume(0); $('#d-volume').val("0"); $('#deezer-volume #sound').hide(); $('#deezer-volume #mute').show(); }); $('#deezer-volume #mute').on('click', function() { DZ.player.setVolume(50); $('#d-volume').val("50"); $('#deezer-volume #mute').hide(); $('#deezer-volume #sound').show(); }); $('#deezer-volume #repeat-i').on('click', function() { DZ.player.setRepeat(1); $('#deezer-volume #repeat').show(); $('#deezer-volume #repeat-i').hide(); $('#deezer-volume #repeat-one').hide(); }); $('#deezer-volume #repeat').on('click', function() { DZ.player.setRepeat(2); $('#deezer-volume #repeat').hide(); $('#deezer-volume #repeat-i').hide(); $('#deezer-volume #repeat-one').show(); }); $('#deezer-volume #repeat-one').on('click', function() { DZ.player.setRepeat(0); $('#deezer-volume #repeat').hide(); $('#deezer-volume #repeat-i').show(); $('#deezer-volume #repeat-one').hide(); }); $('#playing #slider_seek').on('click', function(e) { var slider = $(e.delegateTarget); var x = e.clientX - slider.offset().left; var xMax = slider.width(); DZ.player.seek(x / xMax * 100); }); $("#d-volume").bind("slider:changed", function(event, data) { // The currently selected value of the slider DZ.player.setVolume(data.value); if (data.value == 0) { $('#deezer-volume #mute').show(); $('#deezer-volume #sound').hide(); } if (data.value > 0) { $('#deezer-volume #mute').hide(); $('#deezer-volume #sound').show(); } }); function onPlayerLoaded() { $("#controls input").attr('disabled', false); //event_listener_append('player_loaded'); /*DZ.Event.subscribe('player_buffering', function(arg) { $('#playing').html('loading...'); });*/ DZ.player.setVolume(50); DZ.Event.subscribe('player_play', function(e) { $('#controls #play').hide(); $('#controls #pause').show(); }); DZ.Event.subscribe('player_paused', function(e) { $('#controls #play').show(); $('#controls #pause').hide(); }); DZ.Event.subscribe('current_track', function(arg) { var time = arg.track.duration; //event_listener_append('current_track', arg.index, arg.track.title, arg.track.album.title); $('#playing #playing_meta').html('<span>' + arg.track.title + ' - ' + arg.track.artist.name + '</span>'); //Displaying total duration and converting duration to minutes and seconds if (time && time > 0.0) { var sec = parseInt(time % 60); $('#times #time_total').html(parseInt(time / 60) + ':' + (sec < 10 ? '0' + sec : sec)); } else { $('#times #time_total').html('0.00'); } }); DZ.Event.subscribe('player_position', function(arg) { //event_listener_append('position', arg[0], arg[1]); $('#times #time_current').html(secondsToTime(arg[0])); $("#playing #slider_seek").find('.bar').css('width', (100 * arg[0] / arg[1]) + '%'); }); DZ.Event.subscribe('track_end', function(arg) { //event_listener_append('track_end'); $('#controls #play').show(); $('#controls #pause').hide(); $('.fa-play').show(); $('.fa-pause').hide(); $(".cap-overlay-current").addClass('cap-overlay'); $(".cap-overlay-current").removeClass('cap-overlay-current'); $(".cap-overlay").hide(); }); } $('body').on('click', '.playlist-item .fa-play, .playlist-l-item .fa-play', function() { DZ.player.play(); $('.fa-play').show(); $('.fa-pause').hide(); $(".cap-overlay-current").addClass('cap-overlay'); $(".cap-overlay-current").removeClass('cap-overlay-current'); $(this).parent().parent().find('.fa-play').hide(); //addStyleAttribute($(this).parent().find('.fa-play.flash-support'), 'display: none !important'); //addStyleAttribute($(this).parent().find('.fa-play.no-flash'), 'display: none !important'); $(this).parent().parent().find('.fa-pause').show(); $(this).parent().parent().addClass('cap-overlay-current'); $(this).parent().parent().removeClass('cap-overlay'); $(".cap-overlay").hide(); //$(this).parent().find(".cap-overlay-current").show(); }); $('body').on('click', '.playlist-item .fa-pause, .playlist-l-item .fa-pause', function() { DZ.player.play(); //$(".cap-overlay-current").addClass('cap-overlay'); //$(".cap-overlay-current").removeClass('cap-overlay-current'); $(this).parent().parent().find('.fa-play').show(); $(this).parent().parent().find('.fa-pause').hide(); //addStyleAttribute($(this).parent().find('.fa-play.flash-support'), 'display: block !important'); //addStyleAttribute($(this).parent().find('.fa-play.no-flash'), 'display: none !important'); $(this).parent().parent().addClass('cap-overlay'); $(this).parent().parent().removeClass('cap-overlay-current'); $(this).parent().parent().find(".cap-overlay").show(); //$(this).parent().find(".cap-overlay-current").show(); }); //Layerslider plugin jQuery("#layerslider").layerSlider({ responsive: false, responsiveUnder: 960, layersContainer: 960, skin: 'fullwidth', hoverPrevNext: false, skinsPath: './layerslider/skins/' }); //WOW animations plugin // wow = new WOW( // { // animateClass: 'animated', // offset: 100 // } // ); // wow.init(); $(function() { //Animsition plugin // $(".animsition").animsition({ // inClass : 'fade-in', // outClass : 'fade-out', // inDuration : 1500, // outDuration : 800, // linkElement : '.animsition-link', // loading : true, // loadingParentElement : 'body', //animsition wrapper element // loadingClass : 'animsition-loading', // unSupportCss : [ 'animation-duration', // '-webkit-animation-duration', // '-o-animation-duration' // ], // //"unSupportCss" option allows you to disable the "animsition" in case the css property in the array is not supported by your browser. // //The default setting is to disable the "animsition" in a browser that does not support "animation-duration". // // overlay : false, // // overlayClass : 'animsition-overlay-slide', // overlayParentElement : 'body' // }); // // //News ticker plugin // $('.news-ticker').easyTicker({ // direction: 'up', // easing: 'swing', // speed: 'slow', // interval: 8000, // height: 'auto', // visible: 4, // mousePause: 1, // controls: { // up: '', // down: '', // toggle: '', // playText: 'Play', // stopText: 'Stop' // } // }); //Playing meta marquee $('.marquee').marquee({ duplicated: true, pauseOnHover: true, gap: 50, duration: 7000 }); // First setup a router which will be the responder for URL changes: var AppRouter = Backbone.Router.extend({ routes: { "*path": "load_content", "*actions": "defaultRoute", "/" : "load_content", "" : "load_content" }, load_content: function(path) { $('#load-page').show(); $('#load-page').html("<p id='page-loading'>...loading...</p>"); //hideLoader(); //var toLoad = $(this).attr('href'); //$('#load-page').fadeIn('slow', loadContent('#load-page', path)); if(!path) { path = 'pages/index'; } if(path.hash){ path = path.replace("#",""); } loadContent('#load-page', '/' + path); //ga('send', 'pageview'); ga('send', 'pageview', {'page': '/' + path}); return false; } }); var appRouter = new AppRouter; // Then initialize Backbone's history //Backbone.history.start({pushState: true, root: "/"}); $(function(event){ if (!(window.history && history.pushState)) { Backbone.history.start({ pushState: false, silent: false, root: '/' }); var fragment = window.location.pathname.substr(Backbone.history.options.root.length); Backbone.history.navigate(fragment, { trigger: true }); } else { Backbone.history.start({ pushState: true }); } }); // $(function(){ // new WorkspaceRouter(); // new HelpPaneRouter(); // Backbone.history.start({pushState: true, root: "/"}); // }); $('.main-menu .top-bar .top-bar-section ul li a').on('click', function(event) { event.preventDefault(); Backbone.history.navigate(event.currentTarget.pathname, { trigger: true }); $('.top-bar .top-bar-section ul li').removeClass("active"); $(this).parent().addClass("active"); $(this).parent().parent().parent().addClass("active"); }); $('.logo h1 a').on('click', function(event) { event.preventDefault(); Backbone.history.navigate(event.currentTarget.pathname, { trigger: true }); $('.top-bar .top-bar-section ul li').removeClass("active"); $('.top-bar .top-bar-section ul li.home-target').addClass("active"); $('.top-bar .top-bar-section ul li.home-target').addClass("active"); }); $('body').on('click', "a[class*='d-menu']", function(event) { event.preventDefault(); Backbone.history.navigate(event.currentTarget.pathname, { trigger: true }); $("a[class*='d-menu']").removeClass("active"); $(this).parent().addClass("active"); }); $('body').on('click', ".pagination span[class*='d-menu'] a", function(event) { event.preventDefault(); Backbone.history.navigate(event.currentTarget.pathname, { trigger: true }); $(".pagination span[class*='d-menu'] a").removeClass("current"); $(this).parent().addClass("current"); }); var wds = $('body').width(); if(wds < 800){ $('body').on('click', ".top-bar-section ul li a", function(event) { $('.toggle-topbar').click(); }); } /************************************************************************ Play mp4 videos with mediaelement.js in fancyBox Francisco Diaz (JFK) / picssel.com Version 1.0 ************************************************************************/ // Detecting IE more effectively : http://msdn.microsoft.com/en-us/library/ms537509.aspx function getInternetExplorerVersion() { // Returns the version of Internet Explorer or -1 (other browser) var rv = -1; // Return value assumes failure. if (navigator.appName == 'Microsoft Internet Explorer') { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat(RegExp.$1); }; return rv; }; // set some general variables var $video_player, _videoHref, _videoPoster, _videoWidth, _videoHeight, _dataCaption, _player, _isPlaying = false, _dataYoutube, _verIE = getInternetExplorerVersion(); jQuery(document).ready(function ($) { jQuery(".fancy_video") .attr('rel', 'videos') .prepend("<span class=\"playbutton\"/>") //cosmetic : append a play button image .fancybox({ // set type of content (remember, we are building the HTML5 <video> tag as content) type : "html", // other API options scrolling : "no", width : '100%', maxWidth : 600, maxHeight : 340, padding : 0, nextEffect : "fade", prevEffect : "fade", nextSpeed : 0, prevSpeed : 0, fitToView : false, autoSize : false, modal : true, // hide default close and navigation buttons helpers : { title : { type : "over" }, //media : {}, buttons: {} // use buttons helpers so navigation button won't overlap video controls }, beforeLoad : function () { // if video is playing and we navigate to next/prev element of a fancyBox gallery // safely remove Flash objects in IE if (_isPlaying && (_verIE > -1)) { // video is playing AND we are using IE _verIE < 9.0 ? _player.remove() : $video_player.remove(); // remove player instance for IE _isPlaying = false; // reinitialize flag }; // build the HTML5 video structure for fancyBox content with specific parameters _videoHref = this.href; // validates if data values were passed otherwise set defaults _videoPoster = typeof this.element.data("poster") !== "undefined" ? this.element.data("poster") : ""; _videoWidth = typeof this.element.data("width") !== "undefined" ? this.element.data("width") : 360; _videoHeight = typeof this.element.data("height") !== "undefined" ? this.element.data("height") : 360; _dataCaption = typeof this.element.data("caption") !== "undefined" ? this.element.data("caption") : ""; _dataYoutube = typeof this.element.data("youtube") !== "undefined" ? this.element.data("youtube") : ""; // construct fancyBox title (optional) this.title = _dataCaption ? _dataCaption : (this.title ? this.title : ""); if(_dataYoutube == 'on'){ // set fancyBox content and pass parameters this.content = "<video id='video_player' src='" + _videoHref + "' style='width:100%;height:100%;' width='100%' height='100%' controls='controls' type='video/youtube' preload='none' autoplay='true'></video>"; }else{ // set fancyBox content and pass parameters this.content = "<video id='video_player' src='" + _videoHref + "' poster='" + _videoPoster + "' style='width:100%;height:100%;' width='100%' height='100%' controls='controls' preload='none' ></video>"; } // set fancyBox dimensions //this.width = _videoWidth; //this.height = _videoHeight; }, afterShow : function () { // initialize MEJS player var $video_player = new MediaElementPlayer('#video_player', { defaultVideoWidth : this.width, defaultVideoHeight : this.height, success : function (mediaElement, domObject) { _player = mediaElement; // override the "mediaElement" instance to be used outside the success setting _player.load(); // fixes webkit firing any method before player is ready _player.play(); // autoplay video (optional) _player.addEventListener('playing', function () { _isPlaying = true; }, false); } // success }); }, beforeClose : function () { // if video is playing and we close fancyBox // safely remove Flash objects in IE if (_isPlaying && (_verIE > -1)) { // video is playing AND we are using IE _verIE < 9.0 ? _player.remove() : $video_player.remove(); // remove player instance for IE _isPlaying = false; // reinitialize flag }; } }); }); // ready function loadContent(target, toLoad) { $(target).load(toLoad, '', function(response, status, xhr) { if (status == 'error') { if (xhr.status == 0) { var msg = "<p id='page-loading'>Connection timed out, please check your internet connection</p>"; $(target).html(msg); } else { var msg = "Sorry but there was an error: "; $(target).html(msg + xhr.status + " " + xhr.statusText); } } var a = !1, b = ""; function c(d) { d = d.match(/[\d]+/g); d.length = 3; return d.join(".") } if (navigator.plugins && navigator.plugins.length) { var e = navigator.plugins["Shockwave Flash"]; e && (a = !0, e.description && (b = c(e.description))); navigator.plugins["Shockwave Flash 2.0"] && (a = !0, b = "2.0.0.11") } else { if (navigator.mimeTypes && navigator.mimeTypes.length) { var f = navigator.mimeTypes["application/x-shockwave-flash"]; (a = f && f.enabledPlugin) && (b = c(f.enabledPlugin.description)) } else { try { var g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"), a = !0, b = c(g.GetVariable("$version")) } catch (h) { try { g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"), a = !0, b = "6.0.21" } catch (i) { try { g = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"), a = !0, b = c(g.GetVariable("$version")) } catch (j) {} } } } } var k = b; if(a){ //alert("flash version: " + k); addStyleAttribute($('.no-flash'), 'display: none !important'); addStyleAttribute($('.flash-support'), 'display: block !important'); //addStyleAttribute($('.flash-support'), 'display: block !important'); }else{ addStyleAttribute($('.no-flash'), 'display: block !important'); addStyleAttribute($('.flash-support'), 'display: none !important'); addStyleAttribute($('.notification'), 'display: block !important; z-index:9999;'); //alert("no flash found"); } //Layerslider plugin jQuery("#layerslider").layerSlider({ responsive: false, responsiveUnder: 1024, layersContainer: 1024, skin: 'noskin', hoverPrevNext: false, skinsPath: './layerslider/skins/' }); $('ul.links a').on('click', function() { var load_target = $(this).attr('href'); $.scrollTo(load_target, 800, { offset: 0 }); }); //Jquery hcaptions plugin // $('.hover-caption').hcaptions({ // effect: "fade" // }); // $('.event-caption').hcaptions({ // effect: "fade" // }); //Image hover overlay $('.playlist-item').hover(function() { $(".cap-overlay", this).fadeIn('slow'); }, function() { $(".cap-overlay", this).fadeOut('slow'); }); $('.playlist-l-item').hover(function() { $(".cap-overlay", this).fadeIn('slow'); }, function() { $(".cap-overlay", this).fadeOut('slow'); }); $('.music-item').hover(function() { $(".cap-overlay", this).fadeIn('slow'); }, function() { $(".cap-overlay", this).fadeOut('slow'); }); $('.event-item').hover(function() { $(".event-overlay", this).fadeIn('slow'); }, function() { $(".event-overlay", this).fadeOut('slow'); }); //News ticker plugin $('.news-ticker').easyTicker({ direction: 'up', easing: 'swing', speed: 'slow', interval: 8000, height: 'auto', visible: 4, mousePause: 1, controls: { up: '', down: '', toggle: '', playText: 'Play', stopText: 'Stop' } }); $('#dy-table').dataTable({ searching: false, "pageLength": 20, "lengthMenu": [20, 40, 60, 80, 100] }); var ws = $('.ws').width(); $('.item-text').width(ws - 165); $(window).resize(function() { //Fires when window is resized var ws = $('.ws').width(); $('.item-text').width(ws - 165); }); var artist_info = $('.upcoming-artist-home').width(); if($('body').width() < 801){ $('.artist-info').width(); }else{ $('.artist-info').width(artist_info - 320); } $(window).resize(function() { //Fires when window is resized var artist_info = $('.upcoming-artist-home').width(); if($('body').width() < 801){ $('.artist-info').width(); }else{ $('.artist-info').width(artist_info - 320); } }); var d_height = $('.banner-right').height(); $('.banner-right').height(d_height); $('#layerslider').height(d_height); $(window).resize(function() { //Fires when window is resized var d_height = $('.banner-right').height(); $('.banner-right').height(d_height); $('#layerslider').height(d_height); }); twttr.widgets.load(); $(document).foundation(); var playerx, isPlayingx = false; // initialize MEJS player var video_playerx = new MediaElementPlayer('#player', { pluginPath: '/js/vendor/', defaultVideoWidth : 600, defaultVideoHeight : 400, success : function (mediaElement, domObject) { playerx = mediaElement; // override the "mediaElement" instance to be used outside the success setting playerx.load(); // fixes webkit firing any method before player is ready //playerx.play(); // autoplay video (optional) playerx.addEventListener('playing', function () { isPlayingx = true; }, false); } // success }); }); } function hideLoader() { $('#paging-loading').fadeOut('normal'); } $(document).foundation(); });
31.598846
216
0.568956
5789a36d91c8e1767045c02eb7edd521dace5f75
1,422
js
JavaScript
node_modules/@antv/x6/es/geometry/util.js
leaderli/li-runner-flow
bb51a8a408c3f7b2754236c08aa35710e1252579
[ "MIT" ]
null
null
null
node_modules/@antv/x6/es/geometry/util.js
leaderli/li-runner-flow
bb51a8a408c3f7b2754236c08aa35710e1252579
[ "MIT" ]
null
null
null
node_modules/@antv/x6/es/geometry/util.js
leaderli/li-runner-flow
bb51a8a408c3f7b2754236c08aa35710e1252579
[ "MIT" ]
null
null
null
export function round(num, precision = 0) { return Number.isInteger(num) ? num : +num.toFixed(precision); } export function random(min, max) { let mmin; let mmax; if (max == null) { mmax = min == null ? 1 : min; mmin = 0; } else { mmax = max; mmin = min == null ? 0 : min; } if (mmax < mmin) { const temp = mmin; mmin = mmax; mmax = temp; } return Math.floor(Math.random() * (mmax - mmin + 1) + mmin); } export function clamp(value, min, max) { if (Number.isNaN(value)) { return NaN; } if (Number.isNaN(min) || Number.isNaN(max)) { return 0; } return min < max ? value < min ? min : value > max ? max : value : value < max ? max : value > min ? min : value; } export function snapToGrid(value, gridSize) { return gridSize * Math.round(value / gridSize); } export function containsPoint(rect, point) { return (point != null && rect != null && point.x >= rect.x && point.x <= rect.x + rect.width && point.y >= rect.y && point.y <= rect.y + rect.height); } export function squaredLength(p1, p2) { const dx = p1.x - p2.x; const dy = p1.y - p2.y; return dx * dx + dy * dy; } //# sourceMappingURL=util.js.map
24.947368
65
0.492968
5789b4e959bc1497062dd19bb3fe8beea999e65e
1,118
js
JavaScript
public/scripts/directives/list-of-channels.directive.js
ianemcallister/team-29kettle
68bb343b4ec934ec285aebd0c2e7b6a0a28bb08a
[ "MIT" ]
1
2022-03-11T01:58:55.000Z
2022-03-11T01:58:55.000Z
public/scripts/directives/list-of-channels.directive.js
ianemcallister/team-29kettle
68bb343b4ec934ec285aebd0c2e7b6a0a28bb08a
[ "MIT" ]
null
null
null
public/scripts/directives/list-of-channels.directive.js
ianemcallister/team-29kettle
68bb343b4ec934ec285aebd0c2e7b6a0a28bb08a
[ "MIT" ]
null
null
null
ckc.directive('listOfChannels', listOfChannels); /* @ngInject */ function listOfChannels() { //define the directive var directive = { restrict: "AECM", templateUrl: 'assets/views/directives/list-of-channels.htm', replace: true, scope: { channels: "=" }, link: linkFunc, controller: listOfChannelsController, controllerAs: 'vm', bindToController: true }; /* @ngInject */ function linkFunc(scope, el, attr, ctrl) { scope.$watch('vm.channels', function loadChannelsData(newVal, oldVal) { }); } listOfChannelsController.$inject = ['$scope']; /* @ngInject */ function listOfChannelsController($scope) { // DEFINE LOCAL VARIABLES var vm = this; // DEFINE VIEW MODEL VARIABLES vm.sortBy = 'name'; vm.sortedChannels = [] // DEFINE LOCAL METHODS // DEFINE VIEW MODEL METHODS console.log('in the list of channels directive', $scope); }; return directive; };
23.291667
79
0.553667
578a049764eba440a926b427b76e9eb2f6c395bf
319
js
JavaScript
react-ui/src/components/EmailInput.js
dEMillerb/heroku-cra-node
cb5031bc284edc2ec8e875c70033670ff6c6111c
[ "MIT" ]
null
null
null
react-ui/src/components/EmailInput.js
dEMillerb/heroku-cra-node
cb5031bc284edc2ec8e875c70033670ff6c6111c
[ "MIT" ]
null
null
null
react-ui/src/components/EmailInput.js
dEMillerb/heroku-cra-node
cb5031bc284edc2ec8e875c70033670ff6c6111c
[ "MIT" ]
null
null
null
import React from 'react'; import '../App.scss'; const Email = props => { let formControl = "tgb-input"; if (props.touched && !props.valid) { formControl = 'tgb-error'; } return ( <> <input type="email" className={formControl} {...props} /> </> ); } export default Email;
16.789474
63
0.551724
578a16b7803f4301c4a2ae6038997083a76ff296
2,778
js
JavaScript
words_discoverer_chrome/import.js
fezhengjin/word-discoverer
6247283c58c0a71c259950e5f8e2eeaa8cd0335d
[ "MIT" ]
96
2017-02-26T08:28:29.000Z
2020-09-16T02:36:34.000Z
words_discoverer_chrome/import.js
fezhengjin/word-discoverer
6247283c58c0a71c259950e5f8e2eeaa8cd0335d
[ "MIT" ]
21
2017-05-11T09:04:36.000Z
2020-08-18T06:00:01.000Z
words_discoverer_chrome/import.js
fezhengjin/word-discoverer
6247283c58c0a71c259950e5f8e2eeaa8cd0335d
[ "MIT" ]
32
2017-01-19T13:35:23.000Z
2020-07-31T07:45:21.000Z
function parse_vocabulary(text) { var lines = text.split('\n'); var found = []; for (var i = 0; i < lines.length; ++i) { var word = lines[i]; if (i + 1 === lines.length && word.length <= 1) break; if (word.slice(-1) === '\r') { word = word.slice(0, -1); } found.push(word); } return found; } function add_new_words(new_words) { chrome.storage.local.get(['wd_user_vocabulary', 'wd_user_vocab_added', 'wd_user_vocab_deleted'], function(result) { var user_vocabulary = result.wd_user_vocabulary; var wd_user_vocab_added = result.wd_user_vocab_added; var wd_user_vocab_deleted = result.wd_user_vocab_deleted; var num_added = 0; var new_state = {"wd_user_vocabulary": user_vocabulary}; for (var i = 0; i < new_words.length; ++i) { var word = new_words[i]; if (!(user_vocabulary.hasOwnProperty(word))) { user_vocabulary[word] = 1; ++num_added; if (typeof wd_user_vocab_added !== 'undefined') { wd_user_vocab_added[word] = 1; new_state['wd_user_vocab_added'] = wd_user_vocab_added; } if (typeof wd_user_vocab_deleted !== 'undefined') { delete wd_user_vocab_deleted[word]; new_state['wd_user_vocab_deleted'] = wd_user_vocab_deleted; } } } if (num_added) { chrome.storage.local.set(new_state, sync_if_needed); } var num_skipped = new_words.length - num_added; document.getElementById("addedInfo").textContent = "Added " + num_added + " new words."; document.getElementById("skippedInfo").textContent = "Skipped " + num_skipped + " existing words."; }); } function process_change() { var inputElem = document.getElementById("doLoadVocab"); var baseName = inputElem.files[0].name; document.getElementById("fnamePreview").textContent = baseName; } function process_submit() { //TODO add a radio button with two options: 1. merge vocabulary [default]; 2. replace vocabulary var inputElem = document.getElementById("doLoadVocab"); var file = inputElem.files[0]; var reader = new FileReader(); reader.onload = function(e) { var new_words = parse_vocabulary(reader.result); add_new_words(new_words); } reader.readAsText(file); } function init_controls() { window.onload=function() { localizeHtmlPage(); document.getElementById("vocabSubmit").addEventListener("click", process_submit); document.getElementById("doLoadVocab").addEventListener("change", process_change); } } init_controls();
37.540541
119
0.612671
578a219bc2ab26fc7e7e620964b2ad5eb590a17b
85,453
js
JavaScript
examples/nano-sql.min.js
artisin/Nano-SQL
f62455974f3ef0cca3abc6e28025d4c230ae5ec1
[ "MIT" ]
null
null
null
examples/nano-sql.min.js
artisin/Nano-SQL
f62455974f3ef0cca3abc6e28025d4c230ae5ec1
[ "MIT" ]
null
null
null
examples/nano-sql.min.js
artisin/Nano-SQL
f62455974f3ef0cca3abc6e28025d4c230ae5ec1
[ "MIT" ]
null
null
null
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(window,function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=16)}([function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var r=n(1);t.Promise="undefined"!=typeof window&&window.Promise?window.Promise:"undefined"!=typeof global&&global.Promise?global.Promise:r.Promise,t._assign=function(e){return e?JSON.parse(JSON.stringify(e)):null},t.fastCHAIN=function(e,n){return new t.Promise(function(t,i){if(e&&e.length){var o=[],s=function(){o.length<e.length?n(e[o.length],o.length,function(e){o.push(e),r.setFast(s)}):t(o)};s()}else t([])})},t.fastRACE=function(e,n){return new t.Promise(function(t,r){if(e&&e.length){var i=!1,o=0,s=function(){o<e.length&&(n(e[o],o,function(e){i||(i=!0,t([e]))}),o++,s())};s()}else t([])})},t.fastALL=function(e,n){return t.Promise.all((e||[]).map(function(e,r){return new t.Promise(function(t,i){n(e,r,function(e){t(e)})})}))};var i="undefined"==typeof window?"":navigator.userAgent||"";t.isSafari=0!==i.length&&(/^((?!chrome|android).)*safari/i.test(i)||/iPad|iPhone|iPod/.test(i)&&!window.MSStream),t.isMSBrowser=0!==i.length&&(i.indexOf("MSIE ")>0||i.indexOf("Trident/")>0||i.indexOf("Edge/")>0),t.isAndroid=/Android/.test(i),t.random16Bits=function(){if("undefined"==typeof crypto)return Math.round(Math.random()*Math.pow(2,16));if(crypto.getRandomValues){var e=new Uint16Array(1);return crypto.getRandomValues(e),e[0]}return"undefined"!=typeof global&&global._crypto.randomBytes?global._crypto.randomBytes(2).reduce(function(e,t){return t*e}):Math.round(Math.random()*Math.pow(2,16))},t.timeid=function(e){for(var n=Math.round((new Date).getTime()/(e?1:1e3)).toString();n.length<(e?13:10);)n="0"+n;return n+"-"+(t.random16Bits()+t.random16Bits()).toString(16)},t.intersect=function(e,t){return!(!e||!t)&&!(!e.length||!t.length)&&(e||[]).filter(function(e){return-1!==(t||[]).indexOf(e)}).length>0},t.uuid=function(){var e,n,r="";return[r,r,r,r,r,r,r,r].reduce(function(i,o,s){for(e=t.random16Bits(),n=3===s?4:4===s?(e%16&3|8).toString(16):r,e=e.toString(16);e.length<4;)e="0"+e;return i+([2,3,4,5].indexOf(s)>-1?"-":r)+(n+e).slice(0,4)},r)};var o={int:function(e){return e},uuid:t.uuid,timeId:function(){return t.timeid()},timeIdms:function(){return t.timeid(!0)}};t.hash=function(e){for(var t=5381,n=e.length;n;)t=33*t^e.charCodeAt(--n);return(t>>>0).toString(16)},t.generateID=function(e,t){return o[e]?o[e](t||1):""},t.cleanArgs=function(e,n){for(var r={},i=e.length;i--;){var o=e[i].split(":");o.length>1?r[o[0]]=t.cast(o[1],n[o[0]]||void 0):r[o[0]]=n[o[0]]||void 0}return r},t.isObject=function(e){return"[object Object]"===Object.prototype.toString.call(e)},t.cast=function(e,n){if("any"===e||"blob"===e)return n;var r=typeof n;if("undefined"===r||null===n)return n;var i={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"},o=function(e,n){switch(e){case"safestr":return o("string",n).replace(/[&<>"'`=\/]/gim,function(e){return i[e]});case"int":return"number"!==r||n%1!=0?parseInt(n||0):n;case"number":case"float":return"number"!==r?parseFloat(n||0):n;case"any[]":case"array":return Array.isArray(n)?n:[];case"uuid":case"timeId":case"timeIdms":case"string":return"string"!==r?String(n):n;case"object":case"obj":case"map":return t.isObject(n)?n:{};case"boolean":case"bool":return!0===n}return n},s=o(String(e||"").toLowerCase(),n);if(-1!==e.indexOf("[]")){var a=e.slice(0,e.lastIndexOf("[]"));return(n||[]).map(function(e){return t.cast(a,e)})}return void 0!==s?["int","float","number"].indexOf(e)>-1&&isNaN(s)?0:s:void 0},t.sortedInsert=function(e,n,r,i){return e.length?(e.splice(t.binarySearch(e,n),0,n),e):(e.push(n),e)},t.binarySearch=function(e,n,r,i){var o=e.length,s=r||0,a=void 0!==i?i:o-1;if(0===o)return 0;if(n>e[a])return a+1;if(n<e[s])return s;if(s>=a)return 0;var u=s+Math.floor((a-s)/2);return n<e[u]?t.binarySearch(e,n,s,u-1):n>e[u]?t.binarySearch(e,n,u+1,a):0},t.removeDuplicates=function(e){if(!e.length)return[];for(var t=[e[0]],n=1;n<e.length;n++)e[n]!==e[n-1]&&t.push(e[n]);return t},t.deepFreeze=function(e){return Object.getOwnPropertyNames(e||{}).forEach(function(n){var r=e[n];"object"==typeof r&&null!==r&&(e[n]=t.deepFreeze(r))}),Object.freeze(e)};var s={};t.objQuery=function(e,t,n){var r=function(e,t,n){return e[t]&&n?r(e,t+1,n[e[t]]):n},i=e+(n?"1":"0");if(s[i])return r(s[i],0,t);var o=[];if(o=e.indexOf("[")>-1?[].concat.apply([],e.split(".").map(function(e){return e.match(/([^\[]+)|\[([^\]]+)\]\[/gim)||e})).map(function(e){return e.replace(/\[|\]/gim,"")}):e.split("."),n){var a=o.shift()+"."+o.shift();o.unshift(a)}return s[i]=o,r(s[i],0,t)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=0,i={},o=Array.prototype.slice,s="undefined"!=typeof window&&window.setImmediate?window.setImmediate:!("undefined"==typeof global||!global.setImmediate)&&global.setImmediate,a="undefined"!=typeof window&&window.postMessage&&window.addEventListener,u="undefined"!=typeof window&&window.Promise?window.Promise:!("undefined"==typeof global||!global.Promise)&&global.Promise,c=function(e){return e[0].apply(null,o.call(e,1))};a&&window.addEventListener("message",function(e){var t,n=e.data;"string"==typeof n&&0===n.indexOf("setMsg")&&(t=i[n])&&(delete i[n],c(t))});t.setFast=s?function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];s(function(){c(e)})}:u?function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];u.resolve().then(function(){c(e)})}:a?function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=r++,o="setMsg"+n;return i[o]=e,window.postMessage(o,"*"),n}:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];setTimeout(function(){c(e)},0)};var f=function(){},l=["R"],h=["F"],_=["P"],d=function(){function e(e){this._state=_,this._queue=[],this._outcome=void 0,e!==f&&v(this,e)}return e.doPolyFill=function(){"undefined"!=typeof global&&(global.Promise||(global.Promise=this)),"undefined"!=typeof window&&(window.Promise||(window.Promise=this))},e.prototype.catch=function(e){return this.then(function(){},e)},e.prototype.then=function(t,n){if("function"!=typeof t&&this._state===h||"function"!=typeof n&&this._state===l)return this;var r=new e(f);return this._state!==_?y(r,this._state===h?t:n,this._outcome):this._queue.push(new p(r,t,n)),r},e.resolve=function(t){return t instanceof this?t:b._resolve(new e(f),t)},e.reject=function(t){return b._reject(new e(f),t)},e.all=function(t){return new e(function(e,n){var r=[];if(t.length)for(var i=function(n,i,o){void 0!==o?r.push(o):r.push(i),r.length==t.length&&e(r)},o=function(e){t[e].then(function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];i(0,e,void 0)}).catch(function(e){i(0,void 0,e)})},s=0;s<t.length;s++)o(s);else e([])})},e.race=function(t){var n,r=t.length,i=!1,o=-1,s=new e(f);if(!1!==Array.isArray(t))return this.reject(new TypeError);if(!r)return this.resolve([]);for(;++o<r;)n=t[o],this.resolve(n).then(function(e){i||(i=!0,b._resolve(s,e))},function(e){i||(i=!0,b._reject(s,e))});return s},e}();t.Promise=d;var p=function(){function e(e,t,n){this._promise=e,"function"==typeof t&&(this._onFulfilled=t,this._callFulfilled=this._otherCallFulfilled),"function"==typeof n&&(this._onRejected=n,this._callRejected=this._otherCallRejected)}return e.prototype._callFulfilled=function(e){b._resolve(this._promise,e)},e.prototype._otherCallFulfilled=function(e){y(this._promise,this._onFulfilled,e)},e.prototype._callRejected=function(e){b._reject(this._promise,e)},e.prototype._otherCallRejected=function(e){y(this._promise,this._onRejected,e)},e}();function y(e,n,r){t.setFast(function(){var t;try{t=n.apply(null,r)}catch(t){return b._reject(e,t)}return t===e?b._reject(e,new TypeError):b._resolve(e,t),null})}t._QueueItem=p;var b=function(){function e(){}return e._resolve=function(t,n){var r=m(g,n),i=r._value,o=-1,s=t._queue.length;if("error"===r._status)return e._reject(t,r._value);if(i)v(t,i);else for(t._state=h,t._outcome=n;++o<s;)t._queue[o]._callFulfilled(n);return t},e._reject=function(e,t){e._state=l,e._outcome=t;for(var n=-1,r=e._queue.length;++n<r;)e._queue[n]._callRejected(t);return e},e}();function g(e){var t=e&&e.then;return!e||"object"!=typeof e&&"function"!=typeof e||"function"!=typeof t?null:function(){t.apply(e,arguments)}}function v(e,t){var n=!1;function r(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];n||(n=!0,b._reject(e,t))}function i(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];n||(n=!0,b._resolve(e,t))}var o=m(function(){t(i,r)});"error"===o._status&&r(o._value)}function m(e,t){var n={_status:null,_value:null};try{n._value=e(t),n._status="success"}catch(e){n._status="error",n._value=e}return n}},function(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});var r=n(0),i=function(){function e(){this._sorted=[],this._indexOf={},this.ai=1,this.doAI=!1}return e.prototype.set=function(e){var t=this;if(this._sorted=e||[],this._indexOf={},this._sorted.forEach(function(e,n){t._indexOf[String(e)]=n}),this.doAI&&this._sorted.length){var n=this._sorted.length;this.ai=this._sorted[n-1]+1}},e.prototype.getLocation=function(e){var t=this.indexOf(e);return-1!==t?t:r.binarySearch(this._sorted,e)},e.prototype.add=function(e){if(this.doAI)parseInt(e)>=this.ai&&this.ai++,this._indexOf[String(e)]=this._sorted.length,this._sorted.push(e);else{var t=r.binarySearch(this._sorted,e);this._sorted.splice(t,0,e),this._indexOf[String(e)]=t;for(var n=t+1;n<this._sorted.length;n++)this._indexOf[String(this._sorted[n])]++}},e.prototype.keys=function(){return this._sorted},e.prototype.indexOf=function(e){return void 0!==this._indexOf[String(e)]?this._indexOf[String(e)]:-1},e.prototype.remove=function(e){var t=this._indexOf[String(e)];if(void 0!==t){delete this._indexOf[String(e)],this._sorted.splice(t,1);for(var n=t;n<this._sorted.length;n++)this._indexOf[String(this._sorted[n])]--}},e}();t.DatabaseIndex=i},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e};Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),o=n(15),s=n(14),a=n(13),u=n(0),c=n(12),f=n(4),l=1.41,h=["_util"],_=function(){function e(){this.version=l,this._onConnectedCallBacks=[];var e=this;e._actions={},e._views={},e.dataModels={},e._events=["*","change","delete","upsert","drop","select","error"],e._hasEvents={},e.tableNames=[],e.plugins=[],e.hasPK={},e.skipPurge={},e.toRowFns={},e.tablePKs={},e.toColFns={},e.toColRules={},e._randoms=[],e._randomPtr=0,e.hasAnyEvents=!1;for(var t=0;t<200;t++)e._randoms.push(u.random16Bits().toString(16));e._callbacks={},e._callbacks["*"]=new a.ReallySmallEvents,e.iB=new c.NanoSQLDefaultBackend;var n={models:{},actions:{},views:{},config:{},parent:this};e.iB.willConnect&&e.iB.willConnect(n,function(){e.iB.didConnect&&e.iB.didConnect(n,function(){})})}return e.prototype.toColumn=function(e){return this.toColFns[this.sTable]||(this.toColFns[this.sTable]={}),this.toColFns[this.sTable]=e,this},e.prototype.toRow=function(e){return this.toRowFns[this.sTable]||(this.toRowFns[this.sTable]={}),this.toRowFns[this.sTable]=e,this},e.prototype.fastRand=function(){return this._randomPtr++,this._randomPtr>=this._randoms.length&&(this._randomPtr=0),this._randoms[this._randomPtr]},e.prototype.table=function(e){return e&&(this.sTable=e),this},e.prototype.connect=function(){var e=this,t=this;return new u.Promise(function(n,r){var i={models:t.dataModels,actions:t._actions,views:t._views,config:t._config,parent:e};i.models[h[0]]=[{key:"key",type:"string",props:["pk()","ai()"]},{key:"value",type:"any"}],t._config&&t._config.history&&e.use(new f._NanoSQLHistoryPlugin(t._config.historyMode)),t._config&&!1===t._config.mode||e.use(new c.NanoSQLDefaultBackend),u.fastCHAIN(e.plugins,function(e,t,n){e.willConnect?e.willConnect(i,function(e){i=e,n()}):n()}).then(function(){e.dataModels=i.models,e._actions=i.actions,e._views=i.views,e._config=i.config,Object.keys(e.dataModels).forEach(function(t){var n=!1;e.dataModels[t]=e.dataModels[t].filter(function(e){return"*"!==e.key||"*"!==e.type||(n=!0,!1)}),e.skipPurge[t]=n}),e.plugins.forEach(function(t){t.didExec&&(e.pluginHasDidExec=!0)}),t.tableNames=Object.keys(e.dataModels);var r=function(){u.fastALL(e.plugins,function(e,t,n){e.didConnect?e.didConnect(i,function(){n()}):n()}).then(function(){e.isConnected=!0,e._onConnectedCallBacks.length&&e._onConnectedCallBacks.forEach(function(e){return e()}),n(t.tableNames)})},o=function(t){e.query("upsert",{key:"version",value:e.version}).manualExec({table:"_util"}).then(function(){t?e.extend("rebuild_idx").then(function(){r()}):r()})};e.query("select").where(["key","=","version"]).manualExec({table:"_util"}).then(function(e){e.length?e[0].value<=1.21?o(!0):e[0].value<l?o(!1):r():o(!0)})})})},e.prototype.getActions=function(e){return this._actions[e].map(function(e){return{name:e.name,args:e.args}})},e.prototype.getViews=function(e){return this._views[e].map(function(e){return{name:e.name,args:e.args}})},e.prototype.getConfig=function(){return this._config},e.prototype.avFilter=function(e){return this._AVMod=e,this},e.prototype.use=function(e){return this.plugins.push(e),this},e.prototype.on=function(e,t){var n=this,r=n.sTable,i=n._events.length,o=e.split(" ");if(Array.isArray(r))return this;for(n._callbacks[r]||(n._callbacks[r]=new a.ReallySmallEvents),i=o.length;i--;)-1!==n._events.indexOf(o[i])&&n._callbacks[r].on(o[i],t);return n._refreshEventChecker()},e.prototype.off=function(e,t){var n=this,r=e.split(" "),i=r.length,o=n.sTable;if(Array.isArray(o))return this;for(;i--;)-1!==n._events.indexOf(r[i])&&n._callbacks[o].off(r[i],t);return n._refreshEventChecker()},e.prototype._refreshEventChecker=function(){var e=this;return this._hasEvents={},Object.keys(this._callbacks).concat(["*"]).forEach(function(t){e._hasEvents[t]=e._events.reduce(function(n,r){return n+(e._callbacks[t]&&e._callbacks[t].eventListeners[r]?e._callbacks[t].eventListeners[r].length:0)},0)>0}),this.hasAnyEvents=!1,Object.keys(this._hasEvents).forEach(function(t){e.hasAnyEvents=e.hasAnyEvents||e._hasEvents[t]}),this},e.prototype.model=function(e,t,n){var r=this,i=this,o=i.sTable;if(Array.isArray(o))return this;i._callbacks[o]||(i._callbacks[o]=new a.ReallySmallEvents);var s=!1;if(!n){if(-1!==["string","safestr","timeId","timeIdms","uuid","int","float","number","array","map","bool","blob","any"].indexOf(o.replace(/\W/gim,""))||0===o.indexOf("_")||null!==o.match(/[\(\)\]\[\.]/g))throw Error("Invalid Table Name! https://docs.nanosql.io/setup/data-models");(e||[]).forEach(function(e){if(null!==e.key.match(/[\(\)\]\[\.]/g)||0===e.key.indexOf("_"))throw Error("Invalid Data Model! https://docs.nanosql.io/setup/data-models")})}return i.toColRules[o]={},(e||[]).forEach(function(e){e.props&&e.props.forEach(function(t){if(-1!==t.indexOf("from=>")&&-1!==t.indexOf("(")){var n=t.replace("from=>","").split("(").shift(),r=t.replace("from=>","").split("(").pop().replace(")","").split(",").map(function(e){return e.trim()});i.toColRules[o][e.key]=[n].concat(r)}0===t.indexOf("toColumn.")&&(n=t.replace(/toColumn\.(.*)\(.*\)/gim,"$1"),r=t.replace(/toColumn\..*\((.*)\)/gim,"$1").split(",").map(function(e){return e.trim()}),i.toColRules[o][e.key]=[n].concat(r))}),e.props&&u.intersect(["pk","pk()"],e.props)&&(r.tablePKs[o]=e.key,s=!0)}),this.hasPK[o]=s,s||(this.tablePKs[o]="_id_",e.unshift({key:"_id_",type:"uuid",props:["pk()"]})),i.dataModels[o]=e,i._views[o]=[],i._actions[o]=[],i},e.prototype.views=function(e){return Array.isArray(this.sTable)?this:(this._views[this.sTable]=e,this)},e.prototype.getView=function(e,t){return void 0===t&&(t={}),Array.isArray(this.sTable)?new u.Promise(function(e,t){return t()}):this._doAV("View",this._views[this.sTable],e,t)},e.prototype.actions=function(e){return Array.isArray(this.sTable)?this:(this._actions[this.sTable]=e,this)},e.prototype.doAction=function(e,t){return Array.isArray(this.sTable)?new u.Promise(function(e,t){return t()}):this._doAV("Action",this._actions[this.sTable],e,t)},e.prototype.queryFilter=function(e){return this.queryMod=e,this},e.prototype._doAV=function(e,t,n,r){var i=this,o=this,s=t.reduce(function(e,t){return t.name===n?t:e},null);return s?(o._activeAV=n,o._AVMod?new u.Promise(function(t,n){o._AVMod(i.sTable,e,o._activeAV||"",r,function(e){s.call(s.args?u.cleanArgs(s.args,e):{},o).then(t).catch(n)},function(e){n(e)})}):s.call(s.args?u.cleanArgs(s.args,r):{},o)):new u.Promise(function(e,t){return t("Action/View Not Found!")})},e.prototype.query=function(e,t){var n=this._activeAV;return this._activeAV=void 0,new o._NanoSQLQuery(this,this.sTable,e,t,n)},e.prototype.onConnected=function(e){this.isConnected?e():this._onConnectedCallBacks.push(e)},e.prototype.triggerEvent=function(e){var t=this;if(t._hasEvents["*"]||t._hasEvents[e.table]){if("*"===e.table)return this;i.setFast(function(){e.types.forEach(function(n){t._callbacks["*"].trigger(n,e,t),t._callbacks["*"].trigger("*",e,t),e.table&&t._callbacks[e.table]&&t._callbacks[e.table].trigger(n,e,t)})})}return t},e.prototype.default=function(e){var t={},n=this;return Array.isArray(n.sTable)?{}:(n.dataModels[n.sTable].forEach(function(n){t[n.key]=e&&e[n.key]?e[n.key]:n.default,void 0===t[n.key]&&(t[n.key]=u.cast(n.type,null))}),t)},e.prototype.rawDump=function(e){var t=this;return new u.Promise(function(n,i){var o={};u.fastCHAIN(t.plugins,function(t,n,i){t.dumpTables?t.dumpTables(e).then(function(e){o=r({},o,e),i(o)}):i()}).then(function(){n(o)})})},e.prototype.rawImport=function(e){var t=this;return new u.Promise(function(n,r){u.fastCHAIN(t.plugins,function(t,n,r){t.importTables?t.importTables(e).then(r):r()}).then(function(){n()})})},e.prototype.disconnect=function(){return u.fastCHAIN(this.plugins,function(e,t,n){e.willDisconnect?e.willDisconnect(n):n()})},e.prototype.doTransaction=function(e){var t=this,n=this,i=[],o=u.random16Bits().toString(16);return new u.Promise(function(a,c){n.plugins.length?u.fastCHAIN(n.plugins,function(e,t,n){e.transactionBegin?e.transactionBegin(o,n):n()}).then(function(){Array.isArray(n.sTable)||e(function(e){var t=e||n.sTable;return{query:function(e,n){return new s._NanoSQLTransactionQuery(e,n,t,i,o)}}},function(){var e=[];u.fastCHAIN(i,function(t,i,s){e.push(t.table),n.query(t.action,t.actionArgs).manualExec(r({},t,{table:t.table,transaction:!0,queryID:o})).then(s)}).then(function(r){u.fastCHAIN(t.plugins,function(e,t,n){e.transactionEnd?e.transactionEnd(o,n):n()}).then(function(){e.filter(function(e,t,n){return n.indexOf(e)===t}).forEach(function(e){0!==e.indexOf("_")&&n.triggerEvent({query:i[0],table:e,time:(new Date).getTime(),result:r,types:["transaction"],actionOrView:"",notes:[],transactionID:o,affectedRowPKS:[],affectedRows:[]})}),a(r)})})})}):c("Nothing to do, no plugins!")})},e.prototype.config=function(e){return this._config=e,this},e.prototype.extend=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=this;return new u.Promise(function(t,r){if(n.plugins.length){var i=e,o=[];u.fastCHAIN(n.plugins,function(e,t,n){e.extend?e.extend(function(e,t){i=e,o=t,n()},i,o):n()}).then(function(){t(o)})}else r("No plugins!")})},e.prototype.loadJS=function(e,t,n,r){var i=this;return n?this.doTransaction(function(n,r){t.forEach(function(t){n(e).query("upsert",t).exec()}),r()}):new u.Promise(function(n,o){u.fastCHAIN(t,function(n,o,s){r&&r(Math.round((o+1)/t.length*1e4)/100),i.query("upsert",n).manualExec({table:e}).then(s)}).then(function(e){n(e.map(function(e){return e.shift()}))})})},e.prototype.loadCSV=function(e,t,n,r,i){var o=this,s=[],a=t.split("\n").map(function(e,t){if(0!==t){var n={},i=e.match(/(,)|(["|\[|\{].*?["|\]|\}]|[^",\s]+)(?=\s*,|\s*$)/g)||[],o=!1;","===i[0]&&i.unshift("");for(var a=function(){var e=!1;if(i.forEach(function(t,n){e||","===t&&(void 0!==i[n+1]&&","!==i[n+1]||(e=!0,i.splice(n+1,0,"")))}),e)return"break";o=!0};!o&&"break"!==a(););i=i.filter(function(e,t){return t%2==0});for(var u=s.length;u--;)1===i[u].indexOf("{")||1===i[u].indexOf("[")?i[u]=JSON.parse(i[u].slice(1,i[u].length-1).replace(/'/gm,'"')):0===i[u].indexOf('"')&&(i[u]=i[u].slice(1,i[u].length-1)),n[s[u]]=i[u];return r?r(n):n}s=e.split(",")}).filter(function(e){return e});return n?this.doTransaction(function(t,n){a.forEach(function(n){t(e).query("upsert",n).exec()}),n()}):new u.Promise(function(t,n){u.fastCHAIN(a,function(t,n,r){i&&i(Math.round((n+1)/a.length*1e4)/100),o.query("upsert",t).manualExec({table:e}).then(r)}).then(function(e){t(e.map(function(e){return e.shift()}))})})},e}();t.NanoSQLInstance=_,_.functions={COUNT:{type:"A",call:function(e,t,n){t(n&&"*"!==n?e.filter(function(e){return u.objQuery(n,e)}).length:e.length)}},MAX:{type:"A",call:function(e,t,n){if(e.length){var r=u.objQuery(n,e[0])||0;e.forEach(function(e){u.objQuery(n,e),u.objQuery(n,e)>r&&(r=u.objQuery(n,e))}),t(r)}else t(0)}},MIN:{type:"A",call:function(e,t,n){if(e.length){var r=u.objQuery(n,e[0])||0;e.forEach(function(e){var t=u.objQuery(n,e);t<r&&(r=t)}),t(r)}else t(0)}},AVG:{type:"A",call:function(e,t,n){t(e.reduce(function(e,t){return e+(u.objQuery(n,t)||0)},0)/e.length)}},SUM:{type:"A",call:function(e,t,n){t(e.reduce(function(e,t){return e+(u.objQuery(n,t)||0)},0))}},LOWER:{type:"S",call:function(e,t,n){t(e.map(function(e){return String(u.objQuery(n,e)).toLowerCase()}))}},UPPER:{type:"S",call:function(e,t,n){t(e.map(function(e){return String(u.objQuery(n,e)).toUpperCase()}))}},CAST:{type:"S",call:function(e,t,n,r){t(e.map(function(e){return u.cast(r,u.objQuery(n,e))}))}},ABS:{type:"S",call:function(e,t,n){t(e.map(function(e){return Math.abs(u.objQuery(n,e))}))}},CEIL:{type:"S",call:function(e,t,n){t(e.map(function(e){return Math.ceil(u.objQuery(n,e))}))}},POW:{type:"S",call:function(e,t,n,r){t(e.map(function(e){return Math.pow(u.objQuery(n,e),parseInt(r))}))}},ROUND:{type:"S",call:function(e,t,n){t(e.map(function(e){return Math.round(u.objQuery(n,e))}))}},SQRT:{type:"S",call:function(e,t,n){t(e.map(function(e){return Math.sqrt(u.objQuery(n,e))}))}}};var d=new _;t.nSQL=function(e){return d.table(e)},"undefined"!=typeof window&&(window["nano-sql"]={nSQL:t.nSQL,NanoSQLInstance:_})},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e};Object.defineProperty(t,"__esModule",{value:!0});var i=n(0),o=["_hist","_hist_ptr","_id"],s=function(){function e(e){this.historyModeArgs=e,this._tablePkKeys={},this._tablePkTypes={},this._tableKeys={}}return e.prototype.willConnect=function(e,t){var n=this;this.parent=e.parent;var s={};Object.keys(e.models).forEach(function(t){if(0!==t.indexOf("_")){var r=i._assign(e.models[t]).map(function(e){return e.props&&i.intersect(["pk","pk()"],e.props)&&(n._tablePkKeys[t]=e.key,n._tablePkTypes[t]=e.type,n._tableKeys[t]={}),delete e.props,delete e.default,e});r.unshift({key:"_id",type:"timeIdms",props:["pk()"]}),s["_"+t+"__hist_rows"]=r,s["_"+t+"__hist_idx"]=[{key:"id",type:n._tablePkTypes[t],props:["pk()"]},{key:"histRows",type:"timeIdms[]"},{key:"histPtr",type:"number"}]}});var a="string"!=typeof this.historyModeArgs,u=[{key:"id",type:"timeIdms",props:["pk()"]},{key:"table",type:"string"},{key:"keys",type:"any[]"}],c=[{key:"id",type:"timeIdms",props:["pk()"]},{key:"ptr",type:"int"}];"database"!==this.historyModeArgs&&this.historyModeArgs?("database"!==this.historyModeArgs||a)&&(this.historyModes={},a?this.historyModes=i._assign(this.historyModeArgs):Object.keys(this._tablePkKeys).forEach(function(e){n.historyModes[e]=n.historyModeArgs}),Object.keys(this.historyModes).forEach(function(e){"table"===n.historyModes[e]&&(s["_"+e+"__hist"]=u,s["_"+e+"__hist_ptr"]=c)})):(s[o[0]]=u,s[o[1]]=c),e.models=r({},e.models,s),t(e)},e.prototype._histTable=function(e){return e?this.historyModes?"table"===this.historyModes[e]?"_"+e+"__hist":null:"_hist":"__null"},e.prototype._generateHistoryPointers=function(e,t){var n=this,r=this._histTable(e);r?this.parent.query("select").manualExec({table:r+"_ptr"}).then(function(o){o.length?t():n.parent.query("upsert",{id:i.timeid(!0),table:e,ptr:0}).manualExec({table:r+"_ptr"}).then(t)}):t()},e.prototype.didConnect=function(e,t){var n=this,r=function(){i.fastALL(Object.keys(n._tableKeys),function(e,t,r){n.parent.extend("idx","_"+e+"__hist_idx").then(function(t){t.forEach(function(t){n._tableKeys[e][t]=!0}),n.historyModes?n._generateHistoryPointers(e,r):r()})}).then(t)};this.historyModes?r():this.parent.query("select").manualExec({table:"_hist_ptr"}).then(function(e){e.length?r():n.parent.query("upsert",{id:i.timeid(!0),table:"",ptr:0}).manualExec({table:"_hist_ptr"}).then(r)})},e.prototype._purgeRowHistory=function(e,t,n,r){var o=this,s="_"+e+"__hist_rows",a="_"+e+"__hist_idx";i.fastALL(t,function(t,n,u){o.parent.query("select").where(["id","=",t]).manualExec({table:a}).then(function(n){if(n.length){var c=Object.isFrozen(n[0])?i._assign(n[0]):n[0],f=[];if(r)f=f.concat(c.histRows.filter(function(e){return-1!==e})),c.histPtr=0,c.histRows=[];else{for(;c.histPtr--;)f.push(c.histRows.shift());c.histPtr=0}f.length?o.parent.query("upsert",c).comment("History Purge").where(["id","=",t]).manualExec({table:a}).then(function(){o.parent.query("delete").comment("History Purge").where(["_id","IN",f]).manualExec({table:s}).then(function(){r?o.parent.query("select").where([o._tablePkKeys[e],"=",t]).manualExec({table:e}).then(function(n){o._unshiftSingleRow(e,["change"],t,n[0],!1,u)}):u()})}):u()}else u()})}).then(n)},e.prototype._purgeTableHistory=function(e,t,n){var r=this;this.parent.query("select").manualExec({table:e+"_ptr"}).then(function(o){var s=Object.isFrozen(o[0])?i._assign(o[0]):o[0];if(n||s.ptr>0){var a=r.parent.query("select");n||a.range(-1*s.ptr,0),a.manualExec({table:e}).then(function(o){if(o.length){var a={};o.forEach(function(e){a[e.table]||(a[e.table]=[]),a[e.table]=a[e.table].concat(e.keys)}),i.fastALL(Object.keys(a),function(e,t,i){r._purgeRowHistory(e,a[e],i,n)}).then(function(){r.parent.query("delete").comment("History Purge").where(["id","IN",o.map(function(e){return e.id})]).manualExec({table:e}).then(function(){s.ptr=0,r.parent.query("upsert",s).comment("History Purge").where(["id","=",s.id]).manualExec({table:e+"_ptr"}).then(t)})})}else t()})}else t()})},e.prototype._purgeParentHistory=function(e,t,n){if(this.historyModes){var r=this._histTable(e);r?this._purgeTableHistory(r,n):this._purgeRowHistory(e,t,n)}else this._purgeTableHistory("_hist",n)},e.prototype._purgeAllHistory=function(e,t,n){if(this.historyModes){var r=this._histTable(e);r?this._purgeTableHistory(r,n,!0):this._purgeRowHistory(e,[t],n,!0)}else this._purgeTableHistory("_hist",n,!0)},e.prototype.didExec=function(e,t){var n=this;e.table&&0!==e.table.indexOf("_")&&e.types.indexOf("change")>-1&&-1===e.query.comments.indexOf("History Write")?this._purgeParentHistory(e.table,e.affectedRowPKS,function(){i.fastALL(e.affectedRows,function(t,r,i){var o=t[n._tablePkKeys[e.table]];n._tableKeys[e.table][o]?n._unshiftSingleRow(e.table,e.types,o,t,!1,function(e){i(o)}):(n._tableKeys[e.table][o]=!0,n._unshiftSingleRow(e.table,e.types,o,t,!0,function(t){n.parent.query("upsert",{id:o,histRows:[t,-1],histPtr:0}).manualExec({table:"_"+e.table+"__hist_idx"}).then(function(){i(o)})}))}).then(function(r){n._unshiftParent(e,r,t)})}):t(e)},e.prototype._unshiftParent=function(e,t,n){var r=this._histTable(e.table);r?this.parent.query("upsert",{id:i.timeid(!0),table:e.table,keys:t}).manualExec({table:r}).then(function(){n(e)}):n(e)},e.prototype._unshiftSingleRow=function(e,t,n,o,s,a){var u=this,c="_"+e+"__hist_idx",f=i.timeid(!0),l=function(e){u.parent.query("select").where(["id","=",n]).manualExec({table:c}).then(function(t){var r=Object.isFrozen(t[0])?i._assign(t[0]):t[0];r.histRows.unshift(e),u.parent.query("upsert",r).where(["id","=",n]).manualExec({table:c}).then(function(){a(e)})})};t.indexOf("delete")>-1||t.indexOf("drop")>-1?l(-1):this.parent.query("upsert",r({_id:f},o)).manualExec({table:"_"+e+"__hist_rows"}).then(function(){s?a(f):l(f)})},e.prototype.extend=function(e,t,n){if("hist"===t[0]){var r=t[1],i=t[2],o=t[3];switch(r){case"<":case">":this._shiftHistory(r,i,o,function(n){e(t,[n])});break;case"?":this._queryHistory(i,o,function(n){e(t,n)});break;case"rev":this._getRevisionHistory(i,o,function(n){e(t,n)});break;case"clear":this._purgeAllHistory(i,o,function(){e(t,n)})}}else e(t,n)},e.prototype._getRevisionHistory=function(e,t,n){var r=this,s="_"+e+"__hist_idx";this.parent.query("select").where(["id","=",t]).manualExec({table:s}).then(function(t){var s=t[0].histRows.filter(function(e){return-1!==e});r.parent.query("select").where(["_id","IN",s]).manualExec({table:"_"+e+"__hist_rows"}).then(function(e){var r={};e.forEach(function(e){r[e[o[2]]]=Object.isFrozen(e)?i._assign(e):e,delete r[e[o[2]]][o[2]]}),n([{pointer:t[0].histRows.length-t[0].histPtr-1,revisions:t[0].histRows.reverse().map(function(e){return-1===e?null:r[e]})}])})})},e.prototype._getTableHistory=function(e,t){var n=this;this.parent.extend("idx.length",e).then(function(r){n.parent.query("select").manualExec({table:e+"_ptr"}).then(function(e){e.length?t([r,r-e[0].ptr]):t([0,0])})})},e.prototype._queryHistory=function(e,t,n){if(this.historyModes){var r=this._histTable(e);if(r){if(!e)throw Error("Need a table to query this history!");this._getTableHistory(r,n)}else{if(!t)throw Error("Need a row primary key to query this history!");var i="_"+e+"__hist_idx";this.parent.query("select").where(["id","=",t]).manualExec({table:i}).then(function(e){var t=e[0];n([t.histRows.length,t.histRows.length-t.histPtr-1])})}}else this._getTableHistory("_hist",function(e){n(e)})},e.prototype._shiftTableHistory=function(e,t,n){var r=this;this.parent.query("select").manualExec({table:t+"_ptr"}).then(function(o){var s=i._assign(o[0]);s.ptr+="<"===e?1:-1,s.ptr<0&&(s.ptr=0),r.parent.extend("idx.length",t).then(function(a){s.ptr>a&&(s.ptr=a),o[0].ptr!==s.ptr?r.parent.query("select").range(-1,"<"===e?o[0].ptr:s.ptr).manualExec({table:t}).then(function(o){r.parent.query("upsert",s).manualExec({table:t+"_ptr"}).then(function(){i.fastALL(o[0].keys,function(t,n,i){r._shiftRowHistory(e,o[0].table,t,i)}).then(function(e){n(e.indexOf(!0)>-1)})})}):n(!1)})})},e.prototype._shiftRowHistory=function(e,t,n,r){var o=this,s=function(e){o.parent.query("upsert",e).where([o._tablePkKeys[t],"=",n]).manualExec({table:"_"+t+"__hist_idx"}).then(function(){r(!0)})};this.parent.query("select").where([this._tablePkKeys[t],"=",n]).manualExec({table:"_"+t+"__hist_idx"}).then(function(a){var u=i._assign(a[0]);if(u.histPtr+="<"===e?1:-1,u.histPtr<0&&(u.histPtr=0),u.histPtr>u.histRows.length-1&&(u.histPtr=u.histRows.length-1),u.histPtr!==a[0].histPtr){var c=u.histRows[u.histPtr];-1===c?o.parent.query("delete").comment("History Write").where([o._tablePkKeys[t],"=",n]).manualExec({table:t}).then(function(){s(u)}):o.parent.query("select").where(["_id","=",c]).manualExec({table:"_"+t+"__hist_rows"}).then(function(e){o.parent.query("upsert",e[0]).comment("History Write").manualExec({table:t}).then(function(){s(u)})})}else r(!1)})},e.prototype._shiftHistory=function(e,t,n,r){if(this.historyModes){var i=this._histTable(t);if(i){if(!t)throw Error("Need a table to change this history!");this._shiftTableHistory(e,i,r)}else{if(!n)throw Error("Need a row primary key to change this history!");this._shiftRowHistory(e,t,n,r)}}else this._shiftTableHistory(e,"_hist",r)},e}();t._NanoSQLHistoryPlugin=s},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e};Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),o=n(0),s=n(2),a=function(){function e(e){this._pkKey={},this._pkType={},this._dbIndex={},this._size=1e3*(e||0)*1e3}return e.prototype.setID=function(e){this._id=e},e.prototype.connect=function(e){var t=this;this._db=window.openDatabase(this._id,"1.0",this._id,this._size||o.isAndroid?5e6:1),o.fastALL(Object.keys(this._pkKey),function(e,n,r){t._sql(!0,"CREATE TABLE IF NOT EXISTS "+e+" (id BLOB PRIMARY KEY UNIQUE, data TEXT)",[],function(){t._sql(!1,"SELECT id FROM "+e,[],function(n){for(var i=[],o=0;o<n.rows.length;o++)i.push(n.rows.item(o).id);i=i.sort(),t._dbIndex[e].set(i),r()})})}).then(e)},e.prototype._chkTable=function(e){if(-1===Object.keys(this._pkType).indexOf(e))throw Error("No table "+e+" found!");return e},e.prototype.makeTable=function(e,t){var n=this;this._dbIndex[e]=new s.DatabaseIndex,t.forEach(function(t){t.props&&t.props.indexOf("pk")>-1&&(n._pkType[e]=t.type,n._pkKey[e]=t.key),t.props&&t.props.indexOf("ai")>-1&&t.props.indexOf("pk")>-1&&"int"===t.type&&(n._dbIndex[e].doAI=!0)})},e.prototype._sql=function(e,t,n,r){var i=function(e){e.executeSql(t,n,function(e,t){r(t)},function(e,r){return console.error(t,n,r),!1})};e?this._db.transaction(i):this._db.readTransaction(i)},e.prototype.write=function(e,t,n,i){if(!(t=t||o.generateID(this._pkType[e],this._dbIndex[e].ai)))throw new Error("Can't add a row without a primary key!");var s,a,u=!1;if(-1===this._dbIndex[e].indexOf(t)&&(u=!0,this._dbIndex[e].add(t)),u){var c=r({},n,((s={})[this._pkKey[e]]=t,s));this._sql(!0,"INSERT into "+this._chkTable(e)+" (id, data) VALUES (?, ?)",[t,JSON.stringify(c)],function(e){i(c)})}else{var f=r({},n,((a={})[this._pkKey[e]]=t,a));this._sql(!0,"UPDATE "+this._chkTable(e)+" SET data = ? WHERE id = ?",[JSON.stringify(f),t],function(){i(f)})}},e.prototype.delete=function(e,t,n){-1!==this._dbIndex[e].indexOf(t)&&this._dbIndex[e].remove(t),this._sql(!0,"DELETE FROM "+this._chkTable(e)+" WHERE id = ?",[t],function(){n()})},e.prototype.read=function(e,t,n){this._sql(!1,"SELECT data FROM "+this._chkTable(e)+" WHERE id = ?",[t],function(e){e.rows.length?n(JSON.parse(e.rows.item(0).data)):n(void 0)})},e.prototype.batchRead=function(e,t,n){this._sql(!1,"SELECT data from "+this._chkTable(e)+" WHERE id IN ("+t.map(function(e){return"?"}).join(", ")+") ORDER BY id",t,function(e){for(var t=e.rows.length,r=[];t--;)r.unshift(JSON.parse(e.rows.item(t).data));n(r)})},e.prototype.rangeRead=function(e,t,n,r,o,s){var a=this,u=this._dbIndex[e].keys(),c=-1===[typeof r,typeof o].indexOf("undefined"),f=c?[r,o]:[];if(u.length){s&&c&&(f=f.map(function(t){return a._dbIndex[e].getLocation(t)}));var l=f[0]||0,h=[],_=f[0],d="SELECT data from "+this._chkTable(e);if(f.length){for(u[_];_<=f[1];)h.push(u[_]),_++;d+=" WHERE id IN ("+h.map(function(e){return"?"}).join(", ")+")"}d+=" ORDER BY id",this._sql(!1,d,h,function(e){var r=0,o=function(){e.rows.length>r?t(JSON.parse(e.rows.item(r).data),l,function(){l++,++r%500==0?i.setFast(o):o()}):n()};o()})}else n()},e.prototype.drop=function(e,t){var n=new s.DatabaseIndex;n.doAI=this._dbIndex[e].doAI,this._dbIndex[e]=n,this._sql(!0,"DELETE FROM "+this._chkTable(e),[],function(e){t()})},e.prototype.getIndex=function(e,t,n){n(t?this._dbIndex[e].keys().length:this._dbIndex[e].keys())},e.prototype.destroy=function(e){var t=this;o.fastALL(Object.keys(this._dbIndex),function(e,n,r){t.drop(e,r)}).then(e)},e}();t._WebSQLStore=a},function(e,t){e.exports='function o(r){this.go=function(t){var o=0;r&&r.length||t([]),r.forEach(function(e,n){e(function(){++o===r.length&&t([])})})}}var s={db:null,store:function(e,n,t){var o=s.db.transaction(e,n);t(o,o.objectStore(e),function(e,n){return function(){postMessage({do:e,args:n})}})},init:function(){addEventListener("message",function(e){var n=e.data;s[n.do]&&s[n.do](n.args)},!1)},setup:function(n){var e=indexedDB.open(n.id,1),t=!1,a={};e.onupgradeneeded=function(e){t=!0,s.db=e.target.result,Object.keys(n.pkKeys).forEach(function(e){s.db.createObjectStore(e,{keyPath:n.pkKeys[e]}),a[e]=[]})},e.onsuccess=function(e){if(s.db=e.target.result,t)postMessage({do:"rdy",args:a});else{new o(Object.keys(n.pkKeys).map(function(t){return function(n){var e,o,r;e=t,o=function(e){a[t]=e,n()},r=[],s.store(e,"readonly",function(e,n,t){n.openCursor().onsuccess=function(e){var n=e.target.result;n&&(r.push(n.key),n.continue())},e.oncomplete=function(){o(r)}})}})).go(function(){postMessage({do:"rdy",args:a})})}}},write:function(o){s.store(o.table,"readwrite",function(e,n,t){n.put(o.row),e.oncomplete=t("write_"+o.id,null)})},read:function(r){s.store(r.table,"readonly",function(e,n,t){var o=n.get(r.pk);o.onsuccess=function(){postMessage({do:"read_"+r.id,args:o.result})}})},readRange:function(a){s.store(a.table,"readonly",function(e,n,t){var o=[],r=-1===a.range.indexOf(void 0)?n.openCursor(IDBKeyRange.bound(a.range[0],a.range[1])):n.openCursor();e.oncomplete=t("readRange_"+a.id+"_done",o),r.onsuccess=function(e){var n=e.target.result;n&&(o.push(n.value),n.continue())}})},delete:function(o){s.store(o.table,"readwrite",function(e,n,t){e.oncomplete=t("delete_"+o.id,!0),e.onerror=t("delete_"+o.id,!1),"_clear_"===o.pk?n.clear():n.delete(o.pk)})}};s.init();'},function(module,exports,__webpack_require__){var __assign=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e};Object.defineProperty(exports,"__esModule",{value:!0});var lie_ts_1=__webpack_require__(1),utilities_1=__webpack_require__(0),db_idx_1=__webpack_require__(2),_evalContext=function(source,context){var compiled=eval("(function("+Object.keys(context).join(", ")+") {"+source+"})");return compiled.apply(context,Object.keys(context).map(function(e){return context[e]}))},_IndexedDBStore=function(){function e(e){this._worker=__webpack_require__(6),this._pkKey={},this._pkType={},this._dbIndex={},this._waitingCBs={},this._useWorker=e}return e.prototype.connect=function(e){var t=this;if(this._useWorker)this._w=new Worker(window.URL.createObjectURL(new Blob([this._worker]))),this._w.addEventListener("message",function(e){t._handleWWMessage(e.data.do,e.data.args)});else{var n=[];_evalContext(this._worker,{postMessage:function(e){t._handleWWMessage(e.do,e.args)},addEventListener:function(e,t){n.push(t)}}),this._w={addEventListener:null,postMessage:function(e,t){n.forEach(function(t){t({data:e})})}}}this._waitingCBs.rdy=function(n){Object.keys(n).forEach(function(e){t._dbIndex[e].set(n[e])}),e()},this._w.postMessage({do:"setup",args:{pkKeys:this._pkKey,id:this._id}})},e.prototype.setID=function(e){this._id=e},e.prototype._handleWWMessage=function(e,t){this._waitingCBs[e]&&(this._waitingCBs[e](t),delete this._waitingCBs[e])},e.prototype.makeTable=function(e,t){var n=this;this._dbIndex[e]=new db_idx_1.DatabaseIndex,t.forEach(function(t){t.props&&utilities_1.intersect(["pk","pk()"],t.props)&&(n._pkType[e]=t.type,n._pkKey[e]=t.key,t.props&&utilities_1.intersect(["ai","ai()"],t.props)&&("int"===t.type||"number"===t.type)&&(n._dbIndex[e].doAI=!0))})},e.prototype.write=function(e,t,n,r){if(!(t=t||utilities_1.generateID(this._pkType[e],this._dbIndex[e].ai)))throw new Error("Can't add a row without a primary key!");-1===this._dbIndex[e].indexOf(t)&&this._dbIndex[e].add(t);var i,o=utilities_1.uuid(),s=__assign({},n,((i={})[this._pkKey[e]]=t,i));this._waitingCBs["write_"+o]=function(e){r(s)},this._w.postMessage({do:"write",args:{table:e,id:o,row:s}})},e.prototype.delete=function(e,t,n){-1!==this._dbIndex[e].indexOf(t)&&this._dbIndex[e].remove(t);var r=utilities_1.uuid();this._waitingCBs["delete_"+r]=function(e){n()},this._w.postMessage({do:"delete",args:{table:e,id:r,pk:t}})},e.prototype.read=function(e,t,n){var r=utilities_1.uuid();-1!==this._dbIndex[e].indexOf(t)?(this._waitingCBs["read_"+r]=function(e){n(e)},this._w.postMessage({do:"read",args:{table:e,id:r,pk:t}})):n(null)},e.prototype.rangeRead=function(e,t,n,r,i,o){var s=this,a=this._dbIndex[e].keys(),u=-1===[typeof r,typeof i].indexOf("undefined"),c=u?[r,i]:[0,a.length-1];if(a.length){var f=utilities_1.uuid(),l=[],h=c[0],_=0;this._waitingCBs["readRange_"+f+"_done"]=function(e){delete s._waitingCBs["readRange_"+f],l=e;var r=function(){h<=c[1]?t(l[_],h,function(){h++,++_%500==0?lie_ts_1.setFast(r):r()}):n()};r()},this._w.postMessage({do:"readRange",args:{table:e,id:f,range:o&&u?c:c.map(function(e){return a[e]})}})}else n()},e.prototype.drop=function(e,t){var n=new db_idx_1.DatabaseIndex;n.doAI=this._dbIndex[e].doAI,this._dbIndex[e]=n;var r=utilities_1.uuid();this._waitingCBs["delete_"+r]=function(e){t()},this._w.postMessage({do:"delete",args:{table:e,id:r,pk:"_clear_"}})},e.prototype.getIndex=function(e,t,n){n(t?this._dbIndex[e].keys().length:this._dbIndex[e].keys())},e.prototype.destroy=function(e){var t=this;utilities_1.fastALL(Object.keys(this._dbIndex),function(e,n,r){t.drop(e,r)}).then(e)},e}();exports._IndexedDBStore=_IndexedDBStore},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e};Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),o=n(0),s=n(2),a=function(){function e(e){this._pkKey={},this._pkType={},this._rows={},this._dbIndex={},this._ls=e||!1}return e.prototype.connect=function(e){e()},e.prototype.setID=function(e){this._id=e},e.prototype.makeTable=function(e,t){var n=this;this._rows[e]={},this._dbIndex[e]=new s.DatabaseIndex,t.forEach(function(t){if(t.props&&o.intersect(["pk","pk()"],t.props)&&(n._pkType[e]=t.type,n._pkKey[e]=t.key),t.props&&o.intersect(["pk","pk()"],t.props)&&o.intersect(["ai","ai()"],t.props)&&"int"===t.type&&(n._dbIndex[e].doAI=!0),n._ls){var r=localStorage.getItem(n._id+"*"+e+"_idx");r&&n._dbIndex[e].set(JSON.parse(r))}})},e.prototype.write=function(e,t,n,i){if(!(t=t||o.generateID(this._pkType[e],this._dbIndex[e].ai)))throw new Error("Can't add a row without a primary key!");if(-1===this._dbIndex[e].indexOf(t)&&(this._dbIndex[e].add(t),this._ls&&localStorage.setItem(this._id+"*"+e+"_idx",JSON.stringify(this._dbIndex[e].keys()))),this._ls){var s=r({},n,((a={})[this._pkKey[e]]=t,a));localStorage.setItem(this._id+"*"+e+"__"+t,JSON.stringify(s)),i(s)}else s=r({},n,((u={})[this._pkKey[e]]=t,u)),this._rows[e][t]=o.deepFreeze(s),i(s);var a,u},e.prototype.delete=function(e,t,n){-1!==this._dbIndex[e].indexOf(t)&&(this._dbIndex[e].remove(t),this._ls&&localStorage.setItem(this._id+"*"+e+"_idx",JSON.stringify(this._dbIndex[e].keys()))),this._ls?localStorage.removeItem(this._id+"*"+e+"__"+t):delete this._rows[e][t],n()},e.prototype.read=function(e,t,n){if(this._ls){var r=localStorage.getItem(this._id+"*"+e+"__"+t);n(r?JSON.parse(r):void 0)}else n(this._rows[e][t])},e.prototype.rangeRead=function(e,t,n,r,o,s){var a=this,u=this._dbIndex[e].keys(),c=-1===[typeof r,typeof o].indexOf("undefined"),f=c?[r,o]:[0,u.length-1];if(u.length){s&&c&&(f=f.map(function(t){return a._dbIndex[e].getLocation(t)}));var l=f[0],h=0,_=function(){l++,++h%500==0?i.setFast(d):d()},d=function(){if(l<=f[1])if(a._ls){var r=localStorage.getItem(a._id+"*"+e+"__"+u[l]);t(r?JSON.parse(r):void 0,l,_)}else t(a._rows[e][u[l]],l,_);else n()};d()}else n()},e.prototype.drop=function(e,t){var n=this;this._ls?(localStorage.setItem(this._id+"*"+e+"_idx",JSON.stringify([])),this._dbIndex[e].keys().forEach(function(t){localStorage.removeItem(n._id+"*"+e+"__"+t)})):this._rows[e]={};var r=new s.DatabaseIndex;r.doAI=this._dbIndex[e].doAI,this._dbIndex[e]=r,t()},e.prototype.getIndex=function(e,t,n){n(t?this._dbIndex[e].keys().length:this._dbIndex[e].keys())},e.prototype.destroy=function(e){var t=this;o.fastALL(Object.keys(this._dbIndex),function(e,n,r){t.drop(e,r)}).then(e)},e}();t._SyncStore=a},function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(t){this._trie=e._create(t)}return e.prototype.getIndex=function(){return this._trie},e.prototype.setIndex=function(e){this._trie=e},e.prototype.addWord=function(t){return t.toLowerCase().split("").reduce(function(t,n,r,i){return e._append(t,n,r,i)},this._trie),this},e.prototype.removeWord=function(t){var n=e._checkPrefix(this._trie,t),r=n.prefixFound,i=n.prefixNode;return r&&delete i.$,this},e.prototype.getWords=function(){return e._recursePrefix(this._trie,"")},e.prototype.getPrefix=function(t){if(t=t.toLowerCase(),!this._isPrefix(t))return[];var n=e._checkPrefix(this._trie,t).prefixNode;return e._recursePrefix(n,t)},e.prototype._isPrefix=function(t){return e._checkPrefix(this._trie,t).prefixFound},e._append=function(e,t,n,r){return e[t]=e[t]||{},e=e[t],n===r.length-1&&(e.$=1),e},e._checkPrefix=function(e,t){return{prefixFound:t.toLowerCase().split("").every(function(t,n){return!!e[t]&&(e=e[t])}),prefixNode:e}},e._create=function(t){return(t||[]).reduce(function(t,n){return n.toLowerCase().split("").reduce(e._append,t),t},{})},e._recursePrefix=function(t,n,r){void 0===r&&(r=[]);var i=n;for(var o in t)"$"===o&&(r.push(i),i=""),e._recursePrefix(t[o],n+o,r);return r.sort()},e}();t.Trie=n},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e};Object.defineProperty(t,"__esModule",{value:!0});var i=n(9),o=n(0),s=n(8),a=n(7),u=n(5),c=function(){function e(e,t){if(this._tableNames=[],this._nsql=e,this._mode=t.persistent?"PERM":t.mode||"TEMP",this._id=t.id,this._size=t.size||5,this.adapters=[],this.models={},this.tableInfo={},this._trieIndexes={},this._tableNames=[],this._doCache=t.cache||!0,this._cache={},this._cacheKeys={},this.adapters[0]={adapter:null,waitForWrites:!0},"string"==typeof this._mode)switch("PERM"===this._mode&&(this._mode=this._detectStorageMethod()||this._mode),this._mode){case"IDB":this.adapters[0].adapter=new a._IndexedDBStore(!1);break;case"IDB_WW":this.adapters[0].adapter=new a._IndexedDBStore(!0);break;case"WSQL":this.adapters[0].adapter=new u._WebSQLStore(this._size);break;case"LS":this.adapters[0].adapter=new s._SyncStore(!0);break;case"TEMP":this.adapters[0].adapter=new s._SyncStore(!1)}else this.adapters[0].adapter=this._mode}return e.prototype.init=function(e,t){var n=this;this._id||(this._id=o.hash(JSON.stringify(e)).toString()),this.models=this._createSecondaryIndexTables(e),this._tableNames=Object.keys(this.models),this.adapters.forEach(function(e){e.adapter.setID(n._id)}),this._tableNames.forEach(function(t){n._newTable(t,e[t])}),this._relFromTable={},this._relToTable={},this._relationColumns={},this._columnsAreTables={},this._tableNames.forEach(function(e){n.tableInfo[e]._viewTables=Object.keys(n.tableInfo).reduce(function(t,r){return r===e?t:(-1!==Object.keys(n.tableInfo[r]._views).indexOf(e)&&t.push({table:r,column:n.tableInfo[r]._views[e].pkColumn}),t)},[]);var t=n.models[e].length;n._relFromTable[e]={},n._relationColumns[e]=[],n._relToTable[e]=[],n._columnsAreTables[e]={};for(var r=function(){var r=n.models[e][t];if(-1!==n._tableNames.indexOf(r.type.replace("[]",""))){var i="";n._columnsAreTables[e][r.key]={_toTable:r.type.replace("[]",""),_thisType:-1===r.type.indexOf("[]")?"single":"array"},r.props&&(r.props.forEach(function(e){-1!==e.indexOf("ref=>")&&(i=e.replace("ref=>","")),0===e.indexOf("orm(")&&(i=e.replace(/orm\((.*)\)/gim,"$1"))}),i&&(n._hasORM=!0,n._relationColumns[e].push(r.key),n._relFromTable[e][r.key]={_toTable:r.type.replace("[]",""),_toColumn:i.replace("[]",""),_toType:-1===i.indexOf("[]")?"single":"array",_thisType:-1===r.type.indexOf("[]")?"single":"array"}))}};t--;)r()}),Object.keys(this._relFromTable).forEach(function(e){Object.keys(n._relFromTable[e]).forEach(function(t){var r=n._relFromTable[e][t];n._relToTable[r._toTable].push({_thisColumn:r._toColumn,_thisType:r._toType,_fromTable:e,_fromColumn:t,_fromType:r._thisType})})}),o.fastALL(this.adapters,function(e,t,r){e.adapter.connect(function(){e.adapter.setNSQL&&e.adapter.setNSQL(n._nsql),r()})}).then(function(){o.fastALL(Object.keys(n._trieIndexes),function(e,t,r){var i=n._trieIndexes[e];Object.keys(i).length?o.fastALL(Object.keys(i),function(t,r,i){var o="_"+e+"_idx_"+t;n.adapters[0].adapter.getIndex(o,!1,function(r){r.forEach(function(r){n._trieIndexes[e][t].addWord(String(r))}),i()})}).then(r):r()}).then(function(){t(n.models)})})},e.prototype._invalidateCache=function(e,t){var n=this;this._doCache&&Object.keys(this._cacheKeys[e]).forEach(function(r){for(var i=t.length,o=!0;i--&&o;)n._cacheKeys[e][r][t[i]]&&(delete n._cache[e][r],delete n._cacheKeys[e][r],o=!1)})},e.prototype.rebuildIndexes=function(e,t){var n=this,r=(new Date).getTime();o.fastALL(Object.keys(this.tableInfo),function(t,r,i){if("_ALL_"!==e&&e!==t||0===t.indexOf("_"))i();else{var s=n.tableInfo[t]._secondaryIndexes;o.fastALL(s,function(e,r,i){var o="_"+t+"_idx_"+e;n._drop(o,i)}).then(function(){var e=n.tableInfo[t]._pk,r={};s.forEach(function(e){r[e]={}}),n._read(t,function(t,n,i){t[e]?(s.forEach(function(n){t[n]&&(r[n][t[n]]||(r[n][t[n]]=[]),r[n][t[n]].push(t[e]))}),i(!1)):i(!1)},function(){o.fastALL(s,function(e,i,s){var a="_"+t+"_idx_"+e;o.fastALL(Object.keys(r[e]),function(t,i,o){n.adapterWrite(a,t,{id:t,rows:r[e][t].sort()},o)}).then(s)}).then(function(){i()})})})}}).then(function(){t((new Date).getTime()-r)})},e.prototype._secondaryIndexKey=function(e){return o.isObject(e)||Array.isArray(e)?JSON.stringify(e).substr(0,12):"number"==typeof e?e:String(e).substr(0,32)},e.prototype._detectStorageMethod=function(){if("undefined"==typeof window)return"LVL";if(o.isSafari)return"WSQL";if(o.isMSBrowser)return"undefined"!=typeof indexedDB?"IDB":"LS";if(-1===[typeof Worker,typeof Blob,typeof indexedDB].indexOf("undefined")&&window.URL&&window.URL.createObjectURL)try{var e=new Worker(window.URL.createObjectURL(new Blob(["var t = 't';"])));return e.postMessage(""),e.terminate(),indexedDB.open("1234",1),indexedDB.deleteDatabase("1234"),"IDB_WW"}catch(e){if("undefined"!=typeof indexedDB)return"IDB"}return"LS"},e.prototype._secondaryIndexRead=function(e,t,n,r){var i=this;this.adapters[0].adapter.read("_"+e+"_idx_"+t,this._secondaryIndexKey(n),function(t){void 0!==t&&null!==t?i._read(e,t.rows||[],r):r([])})},e.prototype._rangeRead=function(e,t,n,r,i){var o=[];this.adapters[0].adapter.rangeRead(e,function(e,t,n){o.push(e),n()},function(){i(o)},t,n,r)},e.prototype._read=function(e,t,n){var r=this;if(Array.isArray(t)){var i=this.adapters[0].adapter.batchRead;i?i.apply(this.adapters[0].adapter,[e,t,n]):o.fastALL(t,function(t,n,i){r.adapters[0].adapter.read(e,t,i)}).then(function(e){n(e.filter(function(e){return e}))})}else{var s=[];"function"!=typeof t||this.adapters[0].adapter.rangeRead(e,function(e,n,r){t(e,n,function(t){t&&s.push(e),r()})},function(){n(s)})}},e.prototype._trieRead=function(e,t,n,r){var i=this,s=this._trieIndexes[e][t].getPrefix(n);o.fastALL(s,function(n,r,o){i._secondaryIndexRead(e,t,n,o)}).then(function(e){r([].concat.apply([],e))})},e.prototype._clearSecondaryIndexes=function(e,t,n,r,i){var s=this;o.fastALL(this.tableInfo[e]._secondaryIndexes.filter(function(e){return-1===r.indexOf(e)}),function(r,i,a){var u=s._secondaryIndexKey(n[r]),c="_"+e+"_idx_"+r;s.adapters[0].adapter.read(c,u,function(e){if(e){var n=e.rows.indexOf(t);if(-1!==n){var r=e?Object.isFrozen(e)?o._assign(e):e:{id:null,rows:[]};r.rows.splice(n,1),r.rows.sort(),r.rows=o.removeDuplicates(r.rows),s.adapterWrite(c,r.id,r,a)}else a()}else a()})}).then(i)},e.prototype._setSecondaryIndexes=function(e,t,n,r,i){var s=this;o.fastALL(this.tableInfo[e]._secondaryIndexes.filter(function(e){return-1===r.indexOf(e)}),function(r,i,a){var u=s._secondaryIndexKey(n[r]);if(u){s._trieIndexes[e][r]&&s._trieIndexes[e][r].addWord(String(n[r]));var c="_"+e+"_idx_"+r;s.adapters[0].adapter.read(c,u,function(e){var n=e?Object.isFrozen(e)?o._assign(e):e:{id:u,rows:[]};n.rows.push(t),n.rows.sort(),n.rows=o.removeDuplicates(n.rows),s.adapterWrite(c,u,n,a)})}else a()}).then(i)},e.prototype._write=function(e,t,n,i,o){var s,a=this;if(n){var u=r({},n,i,((s={})[this.tableInfo[e]._pk]=t,s)),c=Object.keys(u).filter(function(e){return u[e]===n[e]});this.tableInfo[e]._secondaryIndexes.length?this._clearSecondaryIndexes(e,t,n,c,function(){a._setSecondaryIndexes(e,t,u,c,function(){a.adapterWrite(e,t,u,o)})}):this.adapterWrite(e,t,u,o)}else this.adapterWrite(e,t,i,function(t){a.tableInfo[e]._secondaryIndexes.length?a._setSecondaryIndexes(e,t[a.tableInfo[e]._pk],i,[],function(){o(t)}):o(t)})},e.prototype._delete=function(e,t,n){var r=this;if(!t)throw new Error("Can't delete without a primary key!");this.adapters[0].adapter.read(e,t,function(i){r._clearSecondaryIndexes(e,t,i,[],function(){r.adapterDelete(e,t,function(){n(i)})})})},e.prototype._drop=function(e,t){var n=this;o.fastALL(this.tableInfo[e]._secondaryIndexes,function(t,r,i){n.adapterDrop("_"+e+"_idx_"+t,i)}).then(function(){n._trieIndexes[e]={},n.tableInfo[e]._trieColumns.forEach(function(t){n._trieIndexes[e][t]=new i.Trie([])}),n.adapterDrop(e,t)})},e.prototype._createSecondaryIndexTables=function(e){return Object.keys(e).forEach(function(t){var n=!1,r=!1;if(e[t].forEach(function(i){i.props&&o.intersect(["pk","pk()"],i.props)&&(n=!0),i.props&&o.intersect(["trie","idx","idx()","trie()"],i.props)&&(r=!0,e["_"+t+"_idx_"+i.key]=[{key:"id",type:-1!==["number","float","int"].indexOf(i.type)?i.type:"string",props:["pk"]},{key:"rows",type:"any[]"}])}),r&&!n)throw new Error("Tables with secondary indexes must have a primary key!")}),e},e.prototype._newTable=function(e,t){var n=this;this.tableInfo[e]={_pk:"",_pkType:"",_keys:[],_defaults:[],_secondaryIndexes:[],_trieColumns:[],_name:e,_views:{},_viewTables:[]},this._cache[e]={},this._cacheKeys[e]={},this._trieIndexes[e]={},this.adapters.forEach(function(n){n.adapter.makeTable(e,t)});for(var r=this.models[e].length,s=function(){var t=a.models[e][r];if(a.tableInfo[e]._keys.unshift(t.key),a.tableInfo[e]._defaults[r]=t.default,t.props&&t.props.length){var s=!1;t.props.forEach(function(r){if(-1!==r.indexOf("from=>")){n._hasViews=!0;var i=t.type;"from=>GHOST"!==r&&"from=>LIVE"!==r&&(i=r.replace("from=>","").split(".").shift()),n.tableInfo[e]._views[i]||(n.tableInfo[e]._views[i]={pkColumn:"",mode:"",columns:[]}),"from=>GHOST"===r||"from=>LIVE"===r?(s=!0,n.tableInfo[e]._views[i].pkColumn=t.key,n.tableInfo[e]._views[i].mode=r.replace("from=>","")):n.tableInfo[e]._views[i].columns.push({thisColumn:t.key,otherColumn:r.replace("from=>","").split(".").pop()})}}),o.intersect(["pk","pk()"],t.props)&&(a.tableInfo[e]._pk=t.key,a.tableInfo[e]._pkType=t.type),(o.intersect(["trie","idx","idx()","trie()"],t.props)||s)&&a.tableInfo[e]._secondaryIndexes.push(t.key),o.intersect(["trie","trie()"],t.props)&&(a.tableInfo[e]._trieColumns.push(t.key),a._trieIndexes[e][t.key]=new i.Trie([]))}},a=this;r--;)s();return e},e.prototype.adapterWrite=function(e,t,n,r,i){var s;o.fastALL(this.adapters,function(r,i,o){r.waitForWrites?r.adapter.write(e,t,n,function(e){s=e,o()}):(o(),r.adapter.write(e,t,n,function(e){}))}).then(function(){r(s)}).catch(function(e){i&&i(e)})},e.prototype.adapterDelete=function(e,t,n,r){o.fastALL(this.adapters,function(n,r,i){n.waitForWrites?n.adapter.delete(e,t,function(){i()}):(i(),n.adapter.delete(e,t,function(){}))}).then(function(){n()}).catch(function(e){r&&r(e)})},e.prototype.adapterDrop=function(e,t,n){o.fastALL(this.adapters,function(t,n,r){t.waitForWrites?t.adapter.drop(e,function(){r()}):(r(),t.adapter.drop(e,function(){}))}).then(function(){t()}).catch(function(e){n&&n(e)})},e}();t._NanoSQLStorage=c},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e};Object.defineProperty(t,"__esModule",{value:!0});var i=n(3),o=n(0),s={select:function(e,t){e._select(t)},upsert:function(e,t){e._upsert(t)},delete:function(e,t){e._delete(t)},drop:function(e,t){e._drop(t)},"show tables":function(e,t){e._query.result=Object.keys(e._store.tableInfo),t(e._query)},describe:function(e,t){"string"==typeof e._query.table?(e._query.result=o._assign(e._store.models[e._query.table]),t(e._query)):t(e._query)}},a=function(){function e(e){this._store=e}return e.prototype.doQuery=function(e,t){this._query=e,this._isInstanceTable=Array.isArray(e.table),s[e.action](this,t)},e.prototype._getRows=function(e){this._isInstanceTable?new f(this._query).getRows(e):new c(this._query,this._store,function(t){e(t.filter(function(e){return e}))})},e.prototype._setCache=function(e){var t=this;this._store._cache[this._query.table][this._hash]=e,this._store._cacheKeys[this._query.table][this._hash]={},e.forEach(function(e){t._store._cacheKeys[t._query.table][t._hash][e[t._store.tableInfo[t._query.table]._pk]]=!0})},e.prototype._select=function(e){var t=this;this._hash=o.hash(JSON.stringify(r({},this._query,{queryID:null})));var n=!this._query.join&&!this._query.orm&&this._store._doCache&&!Array.isArray(this._query.table);this._getRows(function(r){["having","orderBy","offset","limit","actionArgs","groupBy","orm","join"].filter(function(e){return t._query[e]}).length?new u(t._query,t._store)._executeQueryArguments(r,function(i){n&&t._setCache(r),t._query.result=i,e(t._query)}):(n&&t._setCache(r),t._query.result=r,e(t._query))})},e.prototype._updateORMRows=function(e,t,n,r,i){var s=this;this._store.tableInfo[e._fromTable]._pk,this._store._read(e._fromTable,t,function(t){o.fastALL(t,function(t,i,a){var u=Object.isFrozen(t)?o._assign(t):t;if("array"===e._fromType){u[e._fromColumn]=u[e._fromColumn]||[];var c=u[e._fromColumn].indexOf(r);n?-1===c?u[e._fromColumn].push(r):a():-1!==c?u[e._fromColumn].splice(c,1):a(),u[e._fromColumn].sort()}else u[e._fromColumn]=n?r:null;s._store._nsql.query("upsert",u).comment("_orm_skip").manualExec({table:e._fromTable}).then(a)}).then(i)})},e.prototype._syncORM=function(e,t,n,r){var i=this;if(this._store._hasORM){var s=this._store._relToTable[this._query.table];if(-1===this._query.comments.indexOf("_orm_skip"))if(s&&s.length){for(var a=Math.max(t.length,n.length),u=[];a--;)u.push(" ");o.fastCHAIN(u,function(r,a,u){o.fastALL(s,function(r,s,u){var c,f;switch(e){case"del":var l=t[a][i._store.tableInfo[i._query.table]._pk],h="array"===r._thisType?t[a][r._thisColumn]||[]:[t[a][r._thisColumn]].filter(function(e){return e});i._updateORMRows(r,h,!1,l,u);break;case"add":var _=n[a][i._store.tableInfo[i._query.table]._pk];if(t[a])if(c=t[a][r._thisColumn],f=n[a][r._thisColumn],Array.isArray(c)&&Array.isArray(f)?c.length===f.length&&c.filter(function(e,t){return e!==f[t]}).length>0:c===f)u();else if("array"===r._thisType){var d=(n[a][r._thisColumn]||[]).filter(function(e){return-1===(t[a][r._thisColumn]||[]).indexOf(e)}),p=(t[a][r._thisColumn]||[]).filter(function(e){return-1===(n[a][r._thisColumn]||[]).indexOf(e)});o.fastALL([d,p],function(e,t,n){i._updateORMRows(r,e,0===t,_,n)}).then(u)}else{var y=function(){null!==n[a][r._thisColumn]&&void 0!==n[a][r._thisColumn]?i._updateORMRows(r,[n[a][r._thisColumn]],!0,_,u):u()};null!==t[a][r._thisColumn]&&void 0!==t[a][r._thisColumn]?i._updateORMRows(r,[t[a][r._thisColumn]],!1,_,y):y()}else{var b="array"===r._thisType?n[a][r._thisColumn]||[]:[n[a][r._thisColumn]].filter(function(e){return e});b&&b.length?i._updateORMRows(r,b,!0,_,u):u()}}}).then(u)}).then(r)}else r();else r()}else r()},e.prototype._updateRowViews=function(e,t,n){var r=this;this._store._hasViews?null!==e&&void 0!==e?o.fastALL(Object.keys(this._store.tableInfo[this._query.table]._views),function(n,i,o){var s=r._store.tableInfo[r._query.table]._views[n].pkColumn;if(void 0!==e[s]){if(e[s]!==t[s])return null===e[s]?(r._store.tableInfo[r._query.table]._views[n].columns.forEach(function(t){e[t.thisColumn]=null}),void o()):void r._store._read(n,[e[s]],function(t){if(!t.length&&"LIVE"===r._store.tableInfo[r._query.table]._views[n].mode)return r._store.tableInfo[r._query.table]._views[n].columns.forEach(function(t){e[t.thisColumn]=null}),void o();r._store.tableInfo[r._query.table]._views[n].columns.forEach(function(n){e[n.thisColumn]=t[0][n.otherColumn]}),o()});o()}else o()}).then(function(){n(e)}):n(e||{}):n(e)},e.prototype._updateRemoteViews=function(e,t,n){var r=this,i=this._store.tableInfo[this._query.table]._pk;o.fastALL(e,function(e,n,s){o.fastALL(r._store.tableInfo[r._query.table]._viewTables,function(n,s,a){t&&"GHOST"===r._store.tableInfo[n.table]._views[r._query.table].mode?a():r._store._secondaryIndexRead(n.table,n.column,e[i],function(i){if(i.length){var s=r._store.tableInfo[n.table]._views[r._query.table].columns,u=r._store.tableInfo[n.table]._views[r._query.table].pkColumn;o.fastALL(i,function(i,o,a){var c=s.length,f=!1;if(t){if("LIVE"===r._store.tableInfo[n.table]._views[r._query.table].mode)for(f=!0,i[u]=null;c--;)i[s[c].otherColumn]=null}else for(;c--;)i[s[c].otherColumn]!==e[s[c].thisColumn]&&(i[s[c].otherColumn]=e[s[c].thisColumn],f=!0);if(f){var l=r._store.tableInfo[n.table]._pk;r._store.adapterWrite(n.table,i[l],i,a)}else a()}).then(a)}else a()})}).then(s)}).then(n)},e.prototype._doAfterQuery=function(e,t,n){var r=this;this._store._hasViews&&this._store.tableInfo[this._query.table]._viewTables.length?this._updateRemoteViews(e,t,function(){n(r._query)}):n(this._query)},e.prototype._upsert=function(e){var t=this,n=this._store.tableInfo[this._query.table]._pk;if(this._isInstanceTable)this._getRows(function(n){t._query.result=t._query.table.map(function(e){return-1===n.indexOf(e)?e:r({},t._query.actionArgs,e)}),e(t._query)});else if(this._query.where)this._getRows(function(r){r.length?o.fastCHAIN(r,function(e,r,i){t._updateRowViews(t._query.actionArgs||{},e,function(r){t._store._write(t._query.table,e[n],e,r,i)})}).then(function(i){var o=i.map(function(e){return e[n]});t._store._invalidateCache(t._query.table,o),t._query.result=[{msg:i.length+" row(s) modfied.",affectedRowPKS:o,affectedRows:i}],t._syncORM("add",r,i,function(){t._doAfterQuery(i,!1,e)})}):(t._query.result=[{msg:"0 row(s) modfied.",affectedRowPKS:[],affectedRows:[]}],e(t._query))});else{var i=this._query.actionArgs||{};this._store._cache[this._query.table]={};var s=function(r){t._updateRowViews(i,r,function(o){t._store._write(t._query.table,i[n],r,o,function(i){t._query.result=[{msg:"1 row inserted.",affectedRowPKS:[i[n]],affectedRows:[i]}],t._store._hasORM?t._syncORM("add",[r].filter(function(e){return e}),[i],function(){t._doAfterQuery([i],!1,e)}):t._doAfterQuery([i],!1,e)})})};void 0!==i[n]?this._store._read(this._query.table,[i[n]],function(e){e.length?s(e[0]):s(null)}):s(null)}},e.prototype._delete=function(e){var t=this;this._isInstanceTable?this._query.where?this._getRows(function(n){t._query.result=t._query.table.filter(function(e){return-1===n.indexOf(e)}),e(t._query)}):(this._query.result=[],e(this._query)):this._query.where?this._getRows(function(n){(n=n.filter(function(e){return e})).length?o.fastALL(n,function(e,n,r){t._store._delete(t._query.table,e[t._store.tableInfo[t._query.table]._pk],r)}).then(function(r){t._store._cache[t._query.table]={};var i=n.map(function(e){return e[t._store.tableInfo[t._query.table]._pk]});t._store._invalidateCache(t._query.table,i),t._query.result=[{msg:n.length+" row(s) deleted.",affectedRowPKS:i,affectedRows:n}],t._syncORM("del",n,[],function(){t._doAfterQuery(n,!0,e)})}):(t._query.result=[{msg:"0 row(s) deleted.",affectedRowPKS:[],affectedRows:[]}],e(t._query))}):this._drop(e)},e.prototype._drop=function(e){var t=this;if(this._isInstanceTable)return this._query.result=[],void e(this._query);this._store._rangeRead(this._query.table,void 0,void 0,!1,function(n){t._store._cache[t._query.table]={},t._store._cacheKeys[t._query.table]={},t._store._drop(t._query.table,function(){t._query.result=[{msg:"'"+t._query.table+"' table dropped.",affectedRowPKS:n.map(function(e){return e[t._store.tableInfo[t._query.table]._pk]}),affectedRows:n}],t._syncORM("del",n,[],function(){t._doAfterQuery(n,!0,e)})})})},e}();t._NanoSQLStorageQuery=a;var u=function(){function e(e,t){this.q=e,this.s=t,this._groupByColumns=[]}return e.prototype._join=function(e,t){var n=this;if(this.q.join){var r={};"cross"!==this.q.join.type&&this.q.join.where&&(r={_left:this.q.join.where[0],_check:this.q.join.where[1],_right:this.q.join.where[2]});var i=this.q.table,o=this.q.join.table;this._doJoin(this.q.join.type,i,o,r,function(e){n.q.where?t(e.filter(function(e,t){return Array.isArray(n.q.where)?l(e,n.q.where||[],t,!0):n.q.where(e,t)})):n.q.range?t(e.filter(function(e,t){return n.q.range&&n.q.range[0]>=t&&n.q.range[1]<=t})):t(e)})}else t(e)},e.prototype._groupByKey=function(e,t){return e.reduce(function(e,n){return-1!==n.indexOf(".length")?e+"."+String((t[n.replace(".length","")]||[]).length):e+"."+String(t[n])},"").slice(1)},e.prototype._groupBy=function(e){var t=this,n=this.q.groupBy||{},r=e.sort(function(e,r){return t._sortObj(e,r,n,!0)});return r.forEach(function(e,r){var i=Object.keys(n).map(function(t){return String(e[t])||""}).join(".");t._sortGroups||(t._sortGroups={}),t._sortGroups[i]||(t._sortGroups[i]=[]),t._sortGroups[i].push(r)}),r},e.prototype._having=function(e){var t=this;return e.filter(function(e,n){return Array.isArray(t.q.having)?l(e,t.q.having||[],n,!0):t.q.having(e,n)})},e.prototype._orderBy=function(e){var t=this;return e.sort(function(e,n){return t._sortObj(e,n,t.q.orderBy||{},!1)})},e.prototype._offset=function(e){var t=this;return e.filter(function(e,n){return!t.q.offset||n>=t.q.offset})},e.prototype._limit=function(e){var t=this;return e.filter(function(e,n){return!t.q.limit||n<t.q.limit})},e.prototype._orm=function(e,t){var n=this,r=this.q.orm?this.q.orm.map(function(e){return"string"==typeof e?{key:e,limit:5}:e}):[];o.fastALL(e,function(e,t,s){e=Object.isFrozen(e)?o._assign(e):e,o.fastALL(r,function(t,r,o){if(e[t.key]&&e[t.key].length){var s=n.s._columnsAreTables[n.q.table][t.key];s?n.s._nsql.query("select").where([n.s.tableInfo[s._toTable]._pk,"array"===s._thisType?"IN":"=",e[t.key]]).manualExec({table:s._toTable}).then(function(n){var r=i.nSQL().query("select",t.select);t.where&&r.where(t.where),void 0!==t.limit&&r.limit(t.limit),void 0!==t.offset&&r.offset(t.offset),t.orderBy&&r.orderBy(t.orderBy),t.groupBy&&r.groupBy(t.groupBy),r.manualExec({table:n}).then(function(r){n.filter(function(e){return e}).length?e[t.key]="array"===s._thisType?r:r[0]:e[t.key]="array"===s._thisType?[]:void 0,o()})}):o()}else o()}).then(function(){s(e)})}).then(t)},e.prototype._doJoin=function(e,t,n,r,i){var o="left",s="right",a="outer",u=this,c=u.s.tableInfo[e===s?n:t],f=u.s.tableInfo[e===s?t:n],h=function(e,t){return[c,f].reduce(function(n,r,i){return r._keys.forEach(function(o){n[r._name+"."+o]=((0===i?e:t)||{})[o]}),n},{})},_=[],d=r&&r._right&&r._right.split(".").pop()||"",p={},y=[];u.s._read(c._name,function(t,n,i){var b=!1;u.s._read(f._name,function(n,i,o){var u;r&&"cross"!==e?l(((u={})[c._name]=t,u[f._name]=n,u),[r._left,r._check,e===s?t[d]:n[d]],0)?(e===a&&(p[i]=!0),_.push(h(t,n)),b=!0):e===a&&(y[i]=n):(_.push(h(t,n)),b=!0),o(!1)},function(){!b&&[o,s,a].indexOf(e)>-1&&_.push(h(t,null)),i(!1)})},function(){if(e===a){for(var t=y.filter(function(e,t){return!p[t]}),n=0;n<t.length;)_.push(h(null,t[n])),n++;i(_)}else i(_)})},e.prototype._sortObj=function(e,t,n,r){return Object.keys(n).reduce(function(i,s){var a=r?o.objQuery(s,e):e[s],u=r?o.objQuery(s,t):t[s];return i||(a===u?0:(a>u?1:-1)*("desc"===n[s]?-1:1))},0)},e.prototype._mutateRows=function(e,t){var n=this,r=this.q.actionArgs,s={},a={};if(r&&r.length){var u=!1,c={};r.forEach(function(e){if(-1!==e.indexOf("(")){var t=(e.match(/^.*\(/g)||[""])[0].replace(/\(|\)/g,"").toUpperCase(),n=i.NanoSQLInstance.functions[t],r=1===e.split(" AS ").length?t:(e.split(" AS ").pop()||"").trim();if(!n)throw new Error("'"+t+"' is not a valid function!");"A"===n.type&&(u=!0),c[e]={fn:n,key:r}}}),o.fastALL(r,function(t,r,i){if(t.indexOf("(")>-1){var f=(t.match(/\(.*\)/g)||[""])[0].replace(/\(|\)/g,"").split(",").map(function(e){return e.trim()});n._sortGroups&&u?o.fastALL(Object.keys(n._sortGroups),function(r,i,o){var s;a[r]||(a[r]={}),(s=c[t].fn).call.apply(s,[e.filter(function(e,t){return n._sortGroups[r].indexOf(t)>-1}),function(e){a[r][c[t].key]=e,o()}].concat(f))}).then(i):(l=c[t].fn).call.apply(l,[e,function(e){s[c[t].key]=e,i()}].concat(f))}else i();var l}).then(function(){var i=function(e,t,i){var s={};return r.forEach(function(r){var a=r.indexOf("(")>-1,u=a?c[r].fn.type:"";if(r.indexOf(" AS ")>-1){var f=r.split(" AS "),l=a?c[r].key:f[0].trim();s[f[1]]=a?"A"===u?i[l]:i[l][t]:o.objQuery(l,e,void 0!==n.q.join)}else l=a?c[r].key:r,s[r]=a?"A"===u?i[l]:i[l][t]:o.objQuery(l,e,void 0!==n.q.join)}),s};if(!e.length&&u){var f=[{}];return Object.keys(c).forEach(function(e){void 0!==s[c[e].key]&&(f[0][e]=s[c[e].key])}),void t(f)}if(n._sortGroups&&u){var l=[];Object.keys(n._sortGroups).forEach(function(t){var r=e.filter(function(e,r){return n._sortGroups[t].indexOf(r)>-1}).filter(function(e,t){return t<1});r&&r.length&&l.push(i(r[0],0,a[t]))}),t(l)}else t(u?e.filter(function(e,t){return t<1}).map(function(e,t){return i(e,t,s)}):e.map(function(e,t){return i(e,t,s)}))})}else t(e)},e.prototype._executeQueryArguments=function(e,t){var n=this,r=function(){n.q.having&&(e=n._having(e)),n.q.orderBy&&(e=n._orderBy(e)),n.q.offset&&(e=n._offset(e)),n.q.limit&&(e=n._limit(e)),t(e)},i=function(){n.q.actionArgs&&n.q.actionArgs.length?n._mutateRows(e,function(t){e=t,r()}):r()},o=function(){n.q.groupBy&&(e=n._groupBy(e)),n.q.orm?n._orm(e,function(t){e=t,i()}):i()};this.q.join?this._join(e,function(t){e=t,o()}):o()},e}();t._MutateSelection=u;var c=function(){function e(e,t,n){var r=this;if(this.q=e,this.s=t,this.q.join&&this.q.orm)throw new Error("Cannot do a JOIN and ORM command at the same time!");if([this.q.where,this.q.range,this.q.trie].filter(function(e){return e}).length>1)throw new Error("Can only have ONE of Trie, Range or Where!");if(this.q.join)n([]);else if(this.q.trie&&this.q.trie.column&&this.q.trie.search)this._selectByTrie(n);else if(this.q.range&&this.q.range.length)this._selectByRange(n);else if(this.q.where&&this.q.where.length&&Array.isArray(this.q.where))if("string"==typeof this.q.where[0]?0===this._isOptimizedWhere(this.q.where):0===(this.q.where||[]).reduce(function(e,t,n){return n%2==1?e:e+r._isOptimizedWhere(t)},0))this._selectByKeys(this.q.where,n);else{var i=this._isSubOptimizedWhere(this.q.where);if(i>0){var o=this.q.where.slice(0,i),s=this.q.where.slice(i+1);this._selectByKeys(o,function(e){n(e.filter(function(e,t){return l(e,s,t)}))})}else this._fullTableScan(n)}else this._fullTableScan(n)}return e.prototype._selectByKeys=function(e,t){var n=this;if(e&&"string"==typeof e[0])this._selectRowsByIndex(e,t);else if(e){var r=[],i="";o.fastCHAIN(e,function(e,t,o){if("string"==typeof e)return i=e,void o();n._selectRowsByIndex(e,function(e){if("AND"===i){for(var t={},s=e.length;s--;)t[e[s][n.s.tableInfo[n.q.table]._pk]]=!0;r=r.filter(function(e){return t[e[n.s.tableInfo[n.q.table]._pk]]})}else r=r.concat(e);o()})}).then(function(){t(r)})}},e.prototype._selectRowsByIndex=function(e,t){var n=this;if("BETWEEN"!==e[1]){var r=[];switch(e[1]){case"IN":r=e[2];break;case"=":r=[e[2]]}e[0]===this.s.tableInfo[this.q.table]._pk?this.s._read(this.q.table,r,t):o.fastALL(r,function(t,r,i){n.s._secondaryIndexRead(n.q.table,e[0],t,i)}).then(function(e){t([].concat.apply([],e))})}else{var i=e[0]===this.s.tableInfo[this.q.table]._pk?"":e[0];if(i){var s="_"+this.q.table+"_idx_"+i;this.s._rangeRead(s,e[2][0],e[2][1],!0,function(e){for(var r=[],i=e.length;i--;)r=r.concat(e[i].rows);n.s._read(n.q.table,r,t)})}else this.s._rangeRead(this.q.table,e[2][0],e[2][1],!0,function(e){t(e)})}},e.prototype._selectByRange=function(e){var t=this;if(this.q.range){var n=this.q.range;n[0]>0?this.s._rangeRead(this.q.table,n[1],n[1]+n[0],!1,e):this.s.adapters[0].adapter.getIndex(this.q.table,!0,function(r){for(var i=n[0]>0?n[1]:r+n[0]-n[1],o=i,s=Math.abs(n[0])-1;s--;)o++;t.s._rangeRead(t.q.table,i,o,!1,e)})}else e([])},e.prototype._selectByTrie=function(e){this.q.trie?this.s._trieRead(this.q.table,this.q.trie.column,this.q.trie.search,e):e([])},e.prototype._fullTableScan=function(e){var t=this,n=void 0!==this.q.where,r=n&&Array.isArray(this.q.where);this.s._read(this.q.table,function(e,i,o){o(!n||(r?l(e,t.q.where,i):t.q.where(e,i)))},e)},e.prototype._isSubOptimizedWhere=function(e){var t=this;if("string"==typeof e[0])return 0;if(0===this._isOptimizedWhere(e[0])){var n=0;return e.forEach(function(r,i){i%2==0&&0===t._isOptimizedWhere(r)&&e[i+1]&&(n=i+1)}),"AND"!==e[n]?0:n}return 0},e.prototype._isOptimizedWhere=function(e){var t=this.s.tableInfo[this.q.table];return["=","IN","BETWEEN"].indexOf(e[1])>-1&&(e[0]===t._pk||t._secondaryIndexes.indexOf(e[0])>-1)?0:1},e}();t._RowSelection=c;var f=function(){function e(e){this.q=e}return e.prototype.getRows=function(e){var t=this;if(this.q.join||this.q.orm||this.q.trie)throw new Error("Cannot do a JOIN, ORM or TRIE command with instance table!");if(this.q.range&&this.q.range.length){var n,r,i=this.q.range;n=i[0]<0?this.q.table.length+i[0]-i[1]:i[1];var o=Math.abs(i[0])-1;for(r=n;o--;)r++;e(this.q.table.filter(function(e,t){return t>=n&&t<=r}))}else e(this.q.table.filter(function(e,n){return!t.q.where||(Array.isArray(t.q.where)?l(e,t.q.where||[],n):t.q.where(e,n))}))},e}();t.InstanceSelection=f;var l=function(e,t,n,r){var i=["AND","OR"];if("string"!=typeof t[0]){var s=t.map(function(t,n){return-1!==i.indexOf(t)?t:0===h(t[2],t[1],o.objQuery(t[0],e,r))});return s.forEach(function(e,t){"OR"===e&&(s[t]=s[t-1]||s[t+1],s[t-1]=void 0,s[t+1]=void 0)}),-1===s.indexOf(!1)}return 0===h(t[2],t[1],o.objQuery(t[0],e,r))},h=function(e,t,n){var r=function(e){return["LIKE","NOT LIKE"].indexOf(t)>-1?String(e||"").toLowerCase():e},i=r(n),o=r(e);if("NULL"===e||"NOT NULL"===e){var s="="===t||"LIKE"===t;return("NULL"===e?null===n||void 0===n:null!==n&&void 0!==n)?s?0:1:s?1:0}switch(t){case"=":return i===o?0:1;case"!=":return i!==o?0:1;case">":return i>o?0:1;case"<":return i<o?0:1;case"<=":return i<=o?0:1;case">=":return i>=o?0:1;case"IN":return(o||[]).indexOf(i)<0?1:0;case"NOT IN":return(o||[]).indexOf(i)<0?0:1;case"REGEX":return i.match(o).length?0:1;case"LIKE":return i.indexOf(o)<0?1:0;case"NOT LIKE":return i.indexOf(o)>=0?1:0;case"BETWEEN":return o[0]<=i&&o[1]>=i?0:1;case"HAVE":return(i||[]).indexOf(o)<0?1:0;case"NOT HAVE":return(i||[]).indexOf(o)<0?0:1;case"INTERSECT":return(i||[]).filter(function(e){return(o||[]).indexOf(e)>-1}).length>0?0:1;case"NOT INTERSECT":return 0===(i||[]).filter(function(e){return(o||[]).indexOf(e)>-1}).length?0:1;default:return 1}}},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e};Object.defineProperty(t,"__esModule",{value:!0});var i=n(3),o=n(11),s=n(0),a=n(10),u=function(){function e(){this._queryPool=[],this._queryPtr=0}return e.prototype.willConnect=function(e,t){this.parent=e.parent,this._store=new a._NanoSQLStorage(e.parent,r({},e.config)),this._store.init(e.models,function(n){e.models=r({},e.models,n),t(e)})},e.prototype.doExec=function(e,t){e.state="complete",new o._NanoSQLStorageQuery(this._store).doQuery(e,t)},e.prototype.dumpTables=function(e){var t=this;return new s.Promise(function(n,r){var i={},o=e&&e.length?e:Object.keys(t._store.tableInfo);s.fastALL(o,function(e,n,r){i[e]=[],t._store.adapters[0].adapter.rangeRead(e,function(t,n,r){i[e].push(t),r()},r)}).then(function(){n(i)})})},e.prototype.importTables=function(e){var t=this;return new s.Promise(function(n,r){s.fastALL(Object.keys(e),function(n,r,i){var o=t._store.tableInfo[n]._pk;s.fastALL(e[n],function(e,r,i){e[o]?t._store.adapters[0].adapter.write(n,e[o],e,i):i()}).then(i)}).then(function(){n()})})},e.prototype.willDisconnect=function(e){s.fastALL(this._store.adapters||[],function(e,t,n){e.disconnect?e.disconnect(n):n()}).then(e)},e.prototype.extend=function(e,t,n){var r=this;switch(t[0]){case"clone":var o=new i.NanoSQLInstance;Object.keys(this.parent.dataModels).forEach(function(e){o.table(e).model(r.parent.dataModels[e],[],!0)}),o.config({id:this._store._id,mode:t[1]}).connect().then(function(){s.fastCHAIN(Object.keys(r.parent.dataModels),function(e,t,n){console.log("Importing "+e+"..."),r.parent.rawDump([e]).then(function(e){return o.rawImport(e)}).then(n)}).then(function(){e(t,[])})});break;case"flush":var a;a=t[1]?[t[1]]:this.parent.tableNames,s.fastCHAIN(a,function(e,t,n){r._store._drop(e,n)}).then(function(){e(t,a)});break;case"get_adapter":t[1]?e(t,[this._store.adapters[t[1]].adapter]):e(t,[this._store.adapters[0].adapter]);break;case"idx.length":case"idx":var u=t[1];Object.keys(this._store.tableInfo).indexOf(u)>-1?this._store.adapters[0].adapter.getIndex(u,"idx"!==t[0],function(n){e(t,n)}):e(t,[]);break;case"rebuild_idx":t[1]?this._store.rebuildIndexes(t[1],function(n){e(t,[n])}):s.fastALL(Object.keys(this._store.tableInfo),function(e,t,n){r._store.rebuildIndexes(e,n)}).then(function(n){e(t,n)});break;case"clear_cache":t[1]&&t[2]?this._store._invalidateCache(t[1],t[2]):t[1]?(this._store._cache[t[1]]={},this._store._cacheKeys[t[1]]={}):Object.keys(this._store.tableInfo).forEach(function(e){r._store._cache[e]={},r._store._cacheKeys[e]={}}),e(t,t[1]||Object.keys(this._store.tableInfo));break;default:e(t,n)}},e}();t.NanoSQLDefaultBackend=u},function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){this.eventListeners={}}return e.prototype.on=function(e,t){this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(t)},e.prototype.off=function(e,t){var n=this;this.eventListeners[e]&&this.eventListeners[e].length&&this.eventListeners[e].forEach(function(r,i){r===t&&n.eventListeners[e].splice(i,1)})},e.prototype.trigger=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.eventListeners[e]&&this.eventListeners[e].forEach(function(e){return e.apply(void 0,t)})},e}();t.ReallySmallEvents=n,t.RSE=new n},function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t,n,r,i){this.thisQ={state:"pending",table:n,action:e,actionArgs:t,queryID:i,transaction:!0,result:[],comments:[]},this._queries=r}return e.prototype.where=function(e){return this.thisQ.where=e,this},e.prototype.exec=function(){this._queries.push(this.thisQ)},e}();t._NanoSQLTransactionQuery=n},function(e,t,n){var r=this&&this.__assign||Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e};Object.defineProperty(t,"__esModule",{value:!0});var i=n(0),o={affectedRowPKS:[],affectedRows:[]},s=function(e,t){1!==e._db.plugins.length||e._db.hasAnyEvents?i.fastCHAIN(e._db.plugins,function(t,n,r){t.doExec?t.doExec(e._query,function(t){e._query=t||e._query,r()}):r()}).then(function(){if(e._db.hasPK[e._query.table]?t(e._query.result):t(e._query.result.map(function(e){return r({},e,{_id_:void 0})})),e._db.hasAnyEvents||e._db.pluginHasDidExec){var n=function(){switch(e._query.action){case"select":return[e._query.action];case"delete":case"upsert":case"drop":return[e._query.action,"change"];default:return[]}}(),s=e._query.result&&e._query.result.length,a={table:e._query.table,query:e._query,time:Date.now(),result:e._query.result,notes:[],types:n,actionOrView:e._AV,transactionID:e._query.transaction?e._query.queryID:void 0,affectedRowPKS:s?(e._query.result[0]||o).affectedRowPKS:[],affectedRows:s?(e._query.result[0]||o).affectedRows:[]};i.fastCHAIN(e._db.plugins,function(e,t,n){e.didExec?e.didExec(a,function(e){a=e,n()}):n()}).then(function(){e._db.triggerEvent(a)})}}):e._db.plugins[0].doExec(e._query,function(n){e._query=n,e._db.hasPK[e._query.table]?t(e._query.result):t(e._query.result.map(function(e){return r({},e,{_id_:void 0})}))})},a={},u=function(){function e(e,t,n,r,i){this._db=e,this._AV=i||"",this._query={table:t,comments:[],state:"pending",queryID:Date.now()+"."+this._db.fastRand(),action:n,actionArgs:r,result:[]}}return e.prototype.where=function(e){return this._query.where=e,this},e.prototype.range=function(e,t){return this._query.range=[e,t],this},e.prototype.on=function(e){return this._query.on=e,this},e.prototype.debounce=function(e){return this._query.debounce=e||250,this},e.prototype.orm=function(e){return this._query.orm=e,this},e.prototype.orderBy=function(e){return this._query.orderBy=e,this},e.prototype.groupBy=function(e){return this._query.groupBy=e,this},e.prototype.having=function(e){return e.length&&Array.isArray(e)||(this._error="Having condition requires an array!"),this._query.having=e,this},e.prototype.join=function(e){if(Array.isArray(this._query.table))throw Error("Can't JOIN with instance table!");return e.table&&e.type||(this._error="Join command requires table and type arguments!"),this._query.join=e,this},e.prototype.limit=function(e){return this._query.limit=e,this},e.prototype.trieSearch=function(e,t){return this._query.trie={column:e,search:t},this},e.prototype.comment=function(e){return this._query.comments.push(e),this},e.prototype.extend=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._query.extend=e,this},e.prototype.offset=function(e){return this._query.offset=e,this},e.prototype.toCSV=function(e){var t=this;return new i.Promise(function(n,r){t.exec().then(function(r){var i=[];r.length||n("",t),e&&i.push(Object.keys(r[0]).join(",")),r.forEach(function(e){i.push(Object.keys(e).map(function(t){return null===e[t]||void 0===e[t]?"":"object"==typeof e[t]?'"'+JSON.stringify(e[t]).replace(/\"/g,"'")+'"':e[t]}).join(","))}),n(i.join("\n"),t)})})},e.prototype.manualExec=function(e){return this._query=r({},this._query,e),this.exec()},e.prototype.denormalizationQuery=function(e){var t=this;return new i.Promise(function(n,r){switch(e){case"tocolumn":var o={};t._query.actionArgs&&t._query.actionArgs.length?Object.keys(t._db.toColRules[t._query.table]).filter(function(e){return-1!==t._query.actionArgs.indexOf(e)}).forEach(function(e){o[e]=t._db.toColRules[t._query.table][e]}):o=t._db.toColRules[t._query.table],t._query.action="select",t._query.actionArgs=void 0;var a=Object.keys(o);s(t,function(e){i.fastCHAIN(e,function(e,n,r){Object.isFrozen(e)&&(e=i._assign(e)),i.fastALL(a,function(n,r,i){var s=t._db.toColFns[t._query.table][o[n][0]];s?s.apply(null,[e[n],function(t){e[n]=t,i()}].concat(o[n].filter(function(e,t){return t>0}).map(function(t){return e[t]}))):i()}).then(function(){t._db.query("upsert",e).manualExec({table:t._query.table}).then(r).catch(r)})}).then(function(){n({msg:e.length+" rows modified"})})});break;case"torow":var u=(t._query.actionArgs||"").replace("()","");if(!t._db.toRowFns[t._query.table]||!t._db.toRowFns[t._query.table][u])return void r("No function "+t._query.actionArgs+" found to perform updates!");var c=t._db.toRowFns[t._query.table][u],f=t._db.tablePKs[t._query.table];if(t._query.on&&t._query.on.length)return void i.fastALL(t._query.on,function(e,n,r){c(e,{},function(n){n[f]=e,t._db.query("upsert",n).manualExec({table:t._query.table}).then(r).catch(r)})}).then(function(){n([{msg:(t._query.on||[]).length+" rows modified or added."}])});t._query.action="select",t._query.actionArgs=void 0,s(t,function(e){i.fastALL(e,function(e,n,r){Object.isFrozen(e)&&(e=i._assign(e)),c(e[f],e,function(n){n[f]=e[f],t._db.query("upsert",n).manualExec({table:t._query.table}).then(r).catch(r)})}).then(function(){n({msg:e.length+" rows modified"})})})}})},e.prototype.exec=function(){var e=this;if("*"!==this._query.table){var t=this,n=this._query.action.toLowerCase();if(["tocolumn","torow"].indexOf(n)>-1){if(this._query.debounce){var r=i.hash(JSON.stringify([this._query.table,n,this._query.actionArgs,this._query.on,this._query.where].filter(function(e){return e})));return new i.Promise(function(t,i){a[r]&&clearTimeout(a[r]),a[r]=setTimeout(function(){e.denormalizationQuery(n).then(t)},e._query.debounce)})}return this.denormalizationQuery(n)}if(!(["select","upsert","delete","drop","show tables","describe"].indexOf(n)>-1))throw Error("No valid database action!");var o=this._query.actionArgs||("select"===n||"delete"===n?[]:{});if("upsert"===n){for(var u={},c=this._db.dataModels[this._query.table],f=0;f<c.length;)void 0!==o[c[f].key]&&(u[c[f].key]=i.cast(c[f].type,o[c[f].key])),f++;if(this._db.skipPurge[this._query.table]){var l=c.map(function(e){return e.key});Object.keys(o).filter(function(e){return-1===l.indexOf(e)}).forEach(function(e){u[e]=o[e]})}o=u}return this._query.action=n,this._query.actionArgs=this._query.actionArgs?o:void 0,new i.Promise(function(n,r){Array.isArray(e._query.table)?e._db.iB.doExec&&e._db.iB.doExec(e._query,function(e){n(e.result)}):(t._db.plugins.length||(t._error="No plugins, nothing to do!"),t._error?r(t._error,e._db):e._db.queryMod?e._db.queryMod(e._query,function(t){e._query=t,s(e,n)}):s(e,n))})}},e}();t._NanoSQLQuery=u},function(e,t,n){e.exports=n(3)}])});
85,453
85,453
0.68997
578ae9b579b94427a9133079bb776b46d7be353e
275
js
JavaScript
src/utils/getComponentName.js
kettanaito/react-advanced-form
e5a1ae20ac32e2dfcb29db2db507bd44e0062a3e
[ "MIT" ]
214
2017-12-24T14:43:08.000Z
2022-01-29T13:19:49.000Z
src/utils/getComponentName.js
zubiaarturo1990/react-advanced-form
e5a1ae20ac32e2dfcb29db2db507bd44e0062a3e
[ "MIT" ]
253
2017-11-27T13:35:35.000Z
2021-08-23T13:21:55.000Z
src/utils/getComponentName.js
zubiaarturo1990/react-advanced-form
e5a1ae20ac32e2dfcb29db2db507bd44e0062a3e
[ "MIT" ]
30
2017-12-05T09:56:05.000Z
2021-11-10T12:17:16.000Z
// @flow import * as React from 'react' /** * Returns the verbose name of the provided React component. */ export default function getComponentName( component: React.Component<any, any, any>, ): string { return component.displayName || component.name || 'Component' }
22.916667
63
0.716364
578b2942d23c0f67ad033afe7104393d95d61288
278
js
JavaScript
lib/helpers.js
Hilaryous/snake
f64e39f8510410350e7aeb0e1a505f0eb2dcd448
[ "MIT" ]
null
null
null
lib/helpers.js
Hilaryous/snake
f64e39f8510410350e7aeb0e1a505f0eb2dcd448
[ "MIT" ]
null
null
null
lib/helpers.js
Hilaryous/snake
f64e39f8510410350e7aeb0e1a505f0eb2dcd448
[ "MIT" ]
null
null
null
export function getRandomNumberWithin(min, max) { return Math.round(Math.random() * (max - min) + min); } export function withinFive(num1, num2, num3, num4) { let xdiff = Math.abs(num1 - num2); let ydiff = Math.abs(num3 - num4); return (xdiff <= 5 && ydiff <= 5); }
21.384615
55
0.643885
578bedcb70c4997bbba01bf1c1e82994190b6ffb
850
js
JavaScript
src/server-communication/signaling-server/callbacks/onconnect.js
videoClerk/SkylinkJS
1fc6072ae364ac319548d6e5b0916b407ebbbde0
[ "Apache-2.0" ]
275
2015-01-11T13:38:11.000Z
2021-09-23T13:28:06.000Z
src/server-communication/signaling-server/callbacks/onconnect.js
videoClerk/SkylinkJS
1fc6072ae364ac319548d6e5b0916b407ebbbde0
[ "Apache-2.0" ]
173
2015-01-13T02:17:47.000Z
2022-03-24T04:24:35.000Z
src/server-communication/signaling-server/callbacks/onconnect.js
videoClerk/SkylinkJS
1fc6072ae364ac319548d6e5b0916b407ebbbde0
[ "Apache-2.0" ]
67
2015-01-27T04:41:57.000Z
2021-09-14T10:38:07.000Z
import clone from 'clone'; import Skylink from '../../../index'; import HandleSignalingStats from '../../../skylink-stats/handleSignalingStats'; import { dispatchEvent } from '../../../utils/skylinkEventManager'; import { channelOpen } from '../../../skylink-events'; import { STATES } from '../../../constants'; const onConnection = (signaling, resolve, roomKey) => { const state = Skylink.getSkylinkState(roomKey); const { socketSession, user } = state; const peerId = signaling.socket.id || user.sid || null; new HandleSignalingStats().send(roomKey, STATES.SIGNALING.CONNECT, peerId, null); if (!state.channelOpen) { state.channelOpen = true; Skylink.setSkylinkState(state, roomKey); } dispatchEvent(channelOpen({ socketSession: clone(socketSession), peerId, })); resolve(); }; export default onConnection;
29.310345
83
0.689412
578c038a09f9cda23c275e83ced94d1e0f38340a
788
js
JavaScript
src/000_common/extensions/Tweener.js
minimo/holysword
04974cbbeaf6659e1677aacb44284cf5c0a3a6d5
[ "MIT" ]
3
2019-08-29T16:34:33.000Z
2019-08-31T07:55:19.000Z
src/000_common/extensions/Tweener.js
minimo/holysword
04974cbbeaf6659e1677aacb44284cf5c0a3a6d5
[ "MIT" ]
2
2020-04-06T02:35:33.000Z
2022-03-24T13:50:07.000Z
src/000_common/extensions/Tweener.js
minimo/holysword
04974cbbeaf6659e1677aacb44284cf5c0a3a6d5
[ "MIT" ]
null
null
null
phina.namespace(function() { phina.accessory.Tweener.prototype.$method("_updateTween", function(app) { //※これないとpauseがうごかない if (!this.playing) return; var tween = this._tween; var time = this._getUnitTime(app); tween.forward(time); this.flare('tween'); if (tween.time >= tween.duration) { delete this._tween; this._tween = null; this._update = this._updateTask; } }); phina.accessory.Tweener.prototype.$method("_updateWait", function(app) { //※これないとpauseがうごかない if (!this.playing) return; var wait = this._wait; var time = this._getUnitTime(app); wait.time += time; if (wait.time >= wait.limit) { delete this._wait; this._wait = null; this._update = this._updateTask; } }); });
21.888889
75
0.621827
578c0fbf5c8eb9e37b7c3f86f6639865c125dd39
746
js
JavaScript
gulpfile.js/tasks/lint.js
hmrc/frontend-excercise
79956a639d5df36e787d70bb0667f2ce1c695c5c
[ "Apache-2.0" ]
null
null
null
gulpfile.js/tasks/lint.js
hmrc/frontend-excercise
79956a639d5df36e787d70bb0667f2ce1c695c5c
[ "Apache-2.0" ]
null
null
null
gulpfile.js/tasks/lint.js
hmrc/frontend-excercise
79956a639d5df36e787d70bb0667f2ce1c695c5c
[ "Apache-2.0" ]
3
2017-04-20T11:38:08.000Z
2021-04-10T23:54:19.000Z
'use strict' var gulp = require('gulp') var standard = require('gulp-standard') var config = require('../config') gulp.task('lint:gulpTasks', function () { return gulp.src(config.scripts.gulpTasks) .pipe(standard()) .pipe(standard.reporter('default', { breakOnError: true })) }) gulp.task('lint:scripts', function () { var scripts = config.scripts.src.concat([ config.scripts.entryPoint, '!**/*.polyfill.js' ]) return gulp.src(scripts) .pipe(standard()) .pipe(standard.reporter('default', { breakOnError: true })) }) gulp.task('lint:tests', function () { return gulp.src(config.test.src) .pipe(standard()) .pipe(standard.reporter('default', { breakOnError: true })) })
21.314286
43
0.631367
578c14815a8919db09c2c3153b1fef58a49aef0f
896
js
JavaScript
src/js/sketchbook.js
sloothes/sketchbook
303e07b358128e3ac42fc7b7e2ca10d631a77665
[ "MIT" ]
2
2019-02-12T18:11:43.000Z
2019-03-13T13:34:45.000Z
src/js/sketchbook.js
sloothes/sketchbook
303e07b358128e3ac42fc7b7e2ca10d631a77665
[ "MIT" ]
null
null
null
src/js/sketchbook.js
sloothes/sketchbook
303e07b358128e3ac42fc7b7e2ca10d631a77665
[ "MIT" ]
null
null
null
import '../css/dat.gui.css'; import '../css/main.css'; export { CameraController } from './sketchbook/CameraController'; export { Character } from './characters/Character'; export { CharacterAI } from './characters/CharacterAI'; export { CharacterStates } from './characters/CharacterStates'; export { Controls } from './sketchbook/Controls'; export { GameModes } from './sketchbook/GameModes'; export { InputManager } from './sketchbook/InputManager'; export { Item } from './objects/Item'; export { Object } from './objects/Object'; export { ObjectPhysics } from './objects/ObjectPhysics'; export { Shaders } from './lib/shaders/Shaders'; export { Springs } from './simulation/Springs'; export { Utilities } from './sketchbook/Utilities'; export { World } from './sketchbook/World'; export { FBXLoader } from './lib/utils/FBXLoader'; export { default as GLTFLoader } from 'three-gltf-loader';
44.8
65
0.722098
578d8029a2cadc0e49ee12fe7e6350b32acb3717
1,215
js
JavaScript
src/app/lib/init-server.js
Nmotta/electerm
d91328c4484c8cb43b10662b1b54ef2d1e40c3c6
[ "MIT" ]
2
2020-04-01T01:15:35.000Z
2021-06-03T05:47:38.000Z
src/app/lib/init-server.js
Nmotta/electerm
d91328c4484c8cb43b10662b1b54ef2d1e40c3c6
[ "MIT" ]
4
2020-10-06T19:29:41.000Z
2022-03-25T19:13:24.000Z
src/app/lib/init-server.js
Nmotta/electerm
d91328c4484c8cb43b10662b1b54ef2d1e40c3c6
[ "MIT" ]
null
null
null
/** * server init script */ const { getConfig } = require('./get-config') const createChildServer = require('../server/child-process') const rp = require('phin').promisified const { initLang } = require('./locales') const { saveUserConfig } = require('./user-config-controller') /** * wait async */ function wait (time) { return new Promise(resolve => { setTimeout(resolve, time) }) } async function waitUntilServerStart (url) { let serverStarted = false while (!serverStarted) { await wait(10) await rp({ url, timeout: 100 }) .then(() => { serverStarted = true }) .catch(() => null) } } module.exports = async (env) => { const { config, userConfig } = await getConfig() const language = initLang(userConfig) if (!config.language) { await saveUserConfig({ language }) config.language = language } const child = await createChildServer(config, env) child.on('exit', () => { global.childPid = null }) global.childPid = child.pid const childServerUrl = `http://${config.host}:${config.port}/run` await waitUntilServerStart(childServerUrl) return { config, localeRef: require('./locales') } }
21.696429
67
0.628807
578d819fd32253ea739fb1f24628d025d25963ae
686
js
JavaScript
HotUpdateDemo/tools/BuildBeforeSetting.js
Lmz521/CocosCreatorTutorial
43ad296e77bd91b96d75d3bfa79d79a6fbfb3033
[ "Apache-2.0" ]
512
2018-04-24T14:57:38.000Z
2022-03-22T06:23:41.000Z
HotUpdateDemo/tools/BuildBeforeSetting.js
xlearns/CocosCreatorTutorial
43ad296e77bd91b96d75d3bfa79d79a6fbfb3033
[ "Apache-2.0" ]
2
2019-03-06T14:28:11.000Z
2019-06-30T04:33:43.000Z
HotUpdateDemo/tools/BuildBeforeSetting.js
xlearns/CocosCreatorTutorial
43ad296e77bd91b96d75d3bfa79d79a6fbfb3033
[ "Apache-2.0" ]
281
2018-03-31T11:03:29.000Z
2022-03-13T13:53:35.000Z
const fileUtil = require('./FileUtil'); let version, androidVersionXml; function initParams(configPath) { let data = JSON.parse(fileUtil.read(configPath)); version = data.version; androidVersionXml = data.root + 'frameworks/runtime-src/proj.android/AndroidManifest.xml'; } function repreatAndroidVersion(path) { let old = fileUtil.read(path); old = old.replace(/android:versionName="([1-9]\d|[1-9])(\.([1-9]\d|\d)){2}"/, `android:versionName="${version}"`); let result = Buffer.from(old); return fileUtil.write(path, result) } function main(params) { initParams('./GameConfig.json'); //修改android 版本号 repreatAndroidVersion(androidVersionXml); }
32.666667
118
0.695335
578ec3a420ca80be8bc38b88e01ce40ef6455539
1,848
js
JavaScript
analysis_tools/PYTHON_RICARDO/output_ergonomics/settings.js
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
analysis_tools/PYTHON_RICARDO/output_ergonomics/settings.js
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
analysis_tools/PYTHON_RICARDO/output_ergonomics/settings.js
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
{ "metrics_file" : "CADAssembly_metrics.xml", "path_to_instance_xmls" : "ComponentACMs", "path_to_instance_stls" : "STL_BINARY", "instance_file" : "component_index.json", "output_json_file" : "output.json", "mil_std" : { "01_SRP_to_roof" : { "min" : 0.960, "max" : 1.173}, "02_seat_to_steering_wheel" : { "min" : 0.366, "max" : 0.447}, "03_seat_to_dash" : { "min" : 0.663, "max" : 0.810}, "04_seat_to_under_steering_wheel" : { "min" : 0.217, "max" : 0.265}, "05_seat_height" : { "min" : 0.152, "max" : 0.381}, "06_seat_to_accel" : { "min" : 0.320, "max" : 0.391}, "07_steering_clearance" : { "min" : 0.069, "max" : 0.084}, "08_brake_to_under_steering_wheel" : { "min" : 0.594, "max" : 0.726}, "09_driver_center_to_brake_right" : { "min" : 0.137, "max" : 0.168}, "10_brake_right_to_accel_right" : { "min" : 0.137, "max" : 0.168}} }
47.384615
56
0.287879
578f078b8b199ccd86c91309b623a4b666cca7d7
1,105
js
JavaScript
App.js
martinfengshenxiang/what_are_human
12501db46ec6f64bf0cdd4c932cea44d5ab9455f
[ "MIT" ]
1
2018-03-11T20:27:43.000Z
2018-03-11T20:27:43.000Z
App.js
martinfengshenxiang/what_are_human
12501db46ec6f64bf0cdd4c932cea44d5ab9455f
[ "MIT" ]
null
null
null
App.js
martinfengshenxiang/what_are_human
12501db46ec6f64bf0cdd4c932cea44d5ab9455f
[ "MIT" ]
null
null
null
import React from 'react'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { createLogger } from 'redux-logger'; import { ApolloClient } from 'apollo-client'; import { ApolloProvider } from 'react-apollo'; import { createHttpLink } from 'apollo-link-http'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { composeWithDevTools } from 'redux-devtools-extension'; import app from './src/Reducer/app'; import initState from './initState'; import WhatAreHuman from './whatAreHuman'; const link = createHttpLink({ uri: 'http://127.0.0.1:5000/whatAreHuman/', credentials: 'same-origin', }); const client = new ApolloClient({ link, cache: new InMemoryCache(), }); const loggerMiddleware = createLogger({ predicate: () => __DEV__ }); const store = createStore( app, initState, composeWithDevTools(applyMiddleware(loggerMiddleware)), ); const App = () => ( <Provider store={store}> <ApolloProvider client={client}> <WhatAreHuman /> </ApolloProvider> </Provider> ); export default App;
26.95122
68
0.695023
578fc9a0db603dd0e3268f62ce004da6cd45c315
345
js
JavaScript
app/components/Pokedex/selectors.js
Cryserrrrr/Pokedex
2ac0c5f8fc99945225440ba0cca311a9c62756bc
[ "MIT" ]
null
null
null
app/components/Pokedex/selectors.js
Cryserrrrr/Pokedex
2ac0c5f8fc99945225440ba0cca311a9c62756bc
[ "MIT" ]
null
null
null
app/components/Pokedex/selectors.js
Cryserrrrr/Pokedex
2ac0c5f8fc99945225440ba0cca311a9c62756bc
[ "MIT" ]
null
null
null
/** * Homepage selectors */ import { createSelector } from 'reselect'; import { initialState } from './reducer'; const selectPokedex = state => state.pokedex || initialState; const makeSelectPokename = () => createSelector( selectPokedex, pokedexState => pokedexState.pokename, ); export { selectPokedex, makeSelectPokename };
20.294118
61
0.707246
578fd74545c306b3231c768c8756705a56f5028f
966
js
JavaScript
doc/html/interfacebsort_1_1quick__sort__dec.js
arinrb/bsort
17cc0e2cbe52af808bae860d53dd4e4d691f4674
[ "Apache-2.0" ]
1
2015-11-08T18:36:23.000Z
2015-11-08T18:36:23.000Z
doc/html/interfacebsort_1_1quick__sort__dec.js
arinrb/bsort
17cc0e2cbe52af808bae860d53dd4e4d691f4674
[ "Apache-2.0" ]
null
null
null
doc/html/interfacebsort_1_1quick__sort__dec.js
arinrb/bsort
17cc0e2cbe52af808bae860d53dd4e4d691f4674
[ "Apache-2.0" ]
null
null
null
var interfacebsort_1_1quick__sort__dec = [ [ "quick_sort_vec_dec_dble", "interfacebsort_1_1quick__sort__dec_adf6a3abbf7bf0d73be0adc00219d06ad.html#adf6a3abbf7bf0d73be0adc00219d06ad", null ], [ "quick_sort_vec_dec_int", "interfacebsort_1_1quick__sort__dec_af462a197807612458c71f90cb701d3b3.html#af462a197807612458c71f90cb701d3b3", null ], [ "quick_sort_vec_dec_map_dble", "interfacebsort_1_1quick__sort__dec_a87da355e38220c57b80d7908af1c08c4.html#a87da355e38220c57b80d7908af1c08c4", null ], [ "quick_sort_vec_dec_map_int", "interfacebsort_1_1quick__sort__dec_ab392966ad76e62ac51a29032ce28df0a.html#ab392966ad76e62ac51a29032ce28df0a", null ], [ "quick_sort_vec_dec_map_real", "interfacebsort_1_1quick__sort__dec_a49fbbedb0ad1f73d07cc45aa997d2cf2.html#a49fbbedb0ad1f73d07cc45aa997d2cf2", null ], [ "quick_sort_vec_dec_real", "interfacebsort_1_1quick__sort__dec_afda629b21343c8eecc050bb0b3102b12.html#afda629b21343c8eecc050bb0b3102b12", null ] ];
107.333333
155
0.86853
578fee8a6e389c79f4ae29c915153c5b3c07d621
275
js
JavaScript
src/components/faq/index.js
oleg-serf/ringsavvy.com
20a64c8129ce6433d5278b9532dbc6c45613053a
[ "MIT" ]
null
null
null
src/components/faq/index.js
oleg-serf/ringsavvy.com
20a64c8129ce6433d5278b9532dbc6c45613053a
[ "MIT" ]
3
2021-03-05T14:53:49.000Z
2021-06-23T14:59:17.000Z
src/components/faq/index.js
oleg-serf/ringsavvy.com
20a64c8129ce6433d5278b9532dbc6c45613053a
[ "MIT" ]
1
2021-11-11T10:07:57.000Z
2021-11-11T10:07:57.000Z
import React from 'react'; import * as Styled from './style'; const Faq = ({ faq }) => { const { question, answer } = faq; return ( <Styled.Faq> <Styled.Question>{question}</Styled.Question> <p>{answer}</p> </Styled.Faq> ); }; export default Faq;
18.333333
51
0.581818
578ff4e0d917dd18165afc7ef579eaf83de7fc88
5,710
js
JavaScript
src/utils/index.js
vobi-io/vobi-core
d1fa275fa160673bc069b11bb4ad15673111d067
[ "MIT" ]
1
2018-12-06T21:08:57.000Z
2018-12-06T21:08:57.000Z
src/utils/index.js
vobi-io/vobi-core
d1fa275fa160673bc069b11bb4ad15673111d067
[ "MIT" ]
2
2021-05-07T18:42:22.000Z
2021-05-08T07:54:18.000Z
src/utils/index.js
vobi-io/vobi-core
d1fa275fa160673bc069b11bb4ad15673111d067
[ "MIT" ]
null
null
null
var randomstring = require('randomstring') var multer = require('multer') var crypto = require('crypto') var mime = require('mime') var path = require('path') var axios = require('axios') var AUTH_HEADER = 'authorization' var DEFAULT_TOKEN_BODY_FIELD = 'access_token' var DEFAULT_TOKEN_QUERY_PARAM_NAME = 'access_token' class Utils { compare (sort) { if (Object.keys(sort).length <= 0) { return () => true } const name = Object.keys(sort)[0] const desc = sort[name] return (a, b) => { if (typeof a[name] === 'string') { return desc === '-1' ? a[name].localeCompare(b[name]) : !a[name].localeCompare(b[name]) } return desc === '-1' ? a[name] < b[name] : a[name] > b[name] } } isObject (obj) { return typeof obj === 'object' } generateHash (password) { var bcrypt = require('bcrypt-nodejs') return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null) } generateRandomHash () { var bcrypt = require('bcrypt-nodejs') var randomText = crypto.randomBytes(16) .toString('hex') return bcrypt .hashSync(randomText, bcrypt.genSaltSync(5), null) .replace(/\+/g, '0') // replace '+' with '0' .replace(/\//g, '0') // replace '/' with '0'; .replace(/\./g, '0') // replace '.' with '0'; } /** * Generate Random password * @param {any} length of generated string * @returns {String} generated random string * * @memberOf Utils */ generateRandomPassword (length) { return randomstring.generate(length) } /** * Generates AlphNumeric random string for object_codes * @returns {String} generated string with alphanumeric characters * @memberOf Utils */ generateCode (length = 6) { return randomstring.generate({ length, charset: 'alphanumeric', capitalization: 'uppercase' }) } extractToken (req) { var token = null // Extract the jwt from the request // Try the header first if (req.headers[AUTH_HEADER]) token = req.headers[AUTH_HEADER] // If not in the header try the body if (!token && req.body) token = req.body[DEFAULT_TOKEN_BODY_FIELD] // if not in the body try query params if (!token) token = req.query[DEFAULT_TOKEN_QUERY_PARAM_NAME] return token } parseAuthHeader (hdrValue) { if (typeof hdrValue !== 'string') { return null } var re = /(\S+)\s+(\S+)/ var matches = hdrValue.match(re) return matches && { scheme: matches[1], value: matches[2] } } /** * extracts file using multer * @param {Request} req request * @param {Response} res response * @param {string} what type of files should be upload ex: "images", "excel" * @returns {Promise<Express.Multer.File>} file */ extractFiles (req, res, type, uploadDir) { const logoFormats = ['.jpg', '.png'] const excelFormats = ['.xlsx', '.xls'] const vcfFormats = ['.vcf'] let ROOT_DIR = uploadDir if (type === 'logo') { ROOT_DIR = `${ROOT_DIR}/images` } return new Promise((resolve, reject) => { var storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, ROOT_DIR) }, filename: function(req, file, cb) { crypto.randomBytes(16, (err, raw) => { if (err) { reject(err) } cb( null, raw.toString('hex') + Date.now() + '.' + (mime.extension(file.mimetype) || file.originalname.split('.').pop()) ) }) } }) const upload = multer({ storage: storage, fileFilter: function(req, file, cb) { switch (type) { case 'logo': if (!logoFormats.includes(path.extname(file.originalname))) { return cb(new Error('Only formats .jpg .png are allowed!')) } cb(null, true) break case 'excel': if (!excelFormats.includes(path.extname(file.originalname))) { return cb(new Error('Only formats .xlsx .xls are allowed!')) } cb(null, true) break case 'vcf': if (!vcfFormats.includes(path.extname(file.originalname))) { return cb(new Error('Only formats .vcf are allowed!')) } cb(null, true) break default: cb(null, true) } } }).any() upload(req, res, err => { if (err) return reject(err) if (req.files.length === 0) { return Promise.reject(new Error('There is no files selected!')) } resolve(req.files) }) }) } getAddressByIP (ip) { return axios.get(`http://ip-api.com/json/${ip}?lang=en`).then(data => data) } getAddressByIPByCordiantes (lat, long, key) { return axios // eslint-disable-next-line .get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=${key}`) .then(result => { const { data } = result let country = '' const city = '' if (data.results[0].address_components[6]) { country = data.results[0].address_components[6].long_name } if (data.results[0].address_components[4]) { country = data.results[0].address_components[4].long_name } return { city, country } }) } padToZeros (digit, pad = '000000') { const str = '' + digit return pad.substring(0, pad.length - str.length) + str } } module.exports = new Utils()
27.718447
96
0.555166
57906a1856345142867a3204e702f936c95b6220
3,460
js
JavaScript
index.js
Bramzor/lambda-sync-private-elb-ips
30bbacb29e5b5ab6e78a2479fc1dffcd6dc619cc
[ "MIT" ]
7
2019-10-31T22:12:49.000Z
2022-01-20T18:40:39.000Z
index.js
Bramzor/lambda-sync-private-elb-ips
30bbacb29e5b5ab6e78a2479fc1dffcd6dc619cc
[ "MIT" ]
1
2019-10-31T21:56:41.000Z
2020-06-20T03:45:09.000Z
index.js
Bramzor/lambda-sync-private-elb-ips
30bbacb29e5b5ab6e78a2479fc1dffcd6dc619cc
[ "MIT" ]
5
2019-08-08T20:55:29.000Z
2021-05-07T16:07:52.000Z
const REGION = process.env.AWS_REGION const EVENT_NAME = '' // SET NAME OF EVENT const DNS_RECORD_NAME = '' // SET DNS RECORD NAME YOU WANT TO UPDATE const HOSTED_ZONE_ID = '' // SET ROUTE53 ZONE ID HOSTING THE RECORD YOU WANT TO UPDATE const AWS = require('aws-sdk'); AWS.config.region = REGION; const events = new AWS.CloudWatchEvents(); const route53 = new AWS.Route53(); function updateTargetInput(target, newData) { const Input = JSON.stringify(newData) const params = { Rule: EVENT_NAME, Targets: [ { Arn: target.Arn, Id: target.Id, Input } ] }; console.log('Updating input parameters to: ' + JSON.stringify(params)) return events.putTargets(params).promise(); } function updateIteration(data) { return events.listTargetsByRule({Rule: EVENT_NAME}).promise().then(({Targets}) => { if (Targets.length > 1) console.warn('More than one Target found?: ' + JSON.stringify(Targets)) return Targets[0] }).then(target => updateTargetInput(target, data)) } function updateRoute53(newips) { console.log('Updating Route53 A record ' + DNS_RECORD_NAME + ' with newips: ' + newips) var newRecord = { HostedZoneId: HOSTED_ZONE_ID, ChangeBatch: { Changes: [{ Action: 'UPSERT', ResourceRecordSet: { Name: DNS_RECORD_NAME, Type: 'A', ResourceRecords: newips.map(x => { return { Value: x } }), TTL: 31, } }] } } return route53.changeResourceRecordSets(newRecord).promise(); } exports.handler = (event, context) => { let newips = false console.log('Received event with parameters:', JSON.stringify(event, null, 2)); if (!event.lastknownips || event.lastknownips.length < 2) throw new Error('lastknownips from event') var ec2 = new AWS.EC2(); let result ec2.describeNetworkInterfaces((err, data) => { if (err) { console.log(err, err.stack); // an error occurred } else { if (!data.NetworkInterfaces) { console.error('No networkinterfaces returned') return false } let interfaces = data.NetworkInterfaces.filter(x => { return x.RequesterId === 'amazon-elb' }) if (interfaces.length < 1) { console.error('no amazon-elb interfaces found') return false } let ipobjects = interfaces.map(x => x.PrivateIpAddresses).filter(x => x) // console.log(ipobjects) let privateips = ipobjects.map(x => x.map(y => y.PrivateIpAddress)).filter(x => x) console.log(privateips) let flatten = Array.prototype.concat.apply([], privateips) result = flatten.sort() if (result.toString() !== event.lastknownips.sort().toString()) { newips = true } else { console.log('Previous IPs: ' + event.lastknownips.sort().toString() + ', new IPs: ' + result.toString()) } } if (!result || !newips) { context.done(null, 'No IP updates required'); return } updateRoute53(result) .then(() => { console.log('Route53 updated!') }) .then(() => updateIteration({ "lastknownips": result, "lastupdated": new Date(Date.now()) })) .then(() => { context.done(null, 'Function Finished with result: ' + result.join(',')); }) .catch((err) => { console.log('Error occurred: ' + err.message) context.done(null, 'Function Finished with result: ' + result.join(',')); }) }) };
32.641509
112
0.616763
579147acfb44a045cd82c3bc660eb9bf24514def
766
js
JavaScript
client/assets/js/services/ClientStatsService.js
qkombur/lucidworks-view
e8e1924d01fc7f200202a269efac6db9d3dc50e9
[ "Apache-2.0" ]
48
2016-04-12T22:38:14.000Z
2020-08-09T13:22:47.000Z
client/assets/js/services/ClientStatsService.js
qkombur/lucidworks-view
e8e1924d01fc7f200202a269efac6db9d3dc50e9
[ "Apache-2.0" ]
45
2016-04-14T15:32:34.000Z
2020-02-25T12:10:13.000Z
client/assets/js/services/ClientStatsService.js
qkombur/lucidworks-view
e8e1924d01fc7f200202a269efac6db9d3dc50e9
[ "Apache-2.0" ]
28
2016-04-13T13:07:39.000Z
2021-05-18T17:27:57.000Z
(function () { 'use strict'; angular .module('lucidworksView.services.clientStats', []) .factory('ClientStatsService', ClientStatsService); function ClientStatsService($window) { 'ngInject'; return { getBrowserLanguage: getBrowserLanguage, getBrowserPlatform: getBrowserPlatform, getBrowserUserAgent: getBrowserUserAgent }; /** * Returns information related to the client * @return {string} The value of the specific client information */ function getBrowserLanguage(){ return $window.navigator.language; } function getBrowserPlatform(){ return $window.navigator.platform; } function getBrowserUserAgent(){ return $window.navigator.userAgent; } } })();
22.529412
68
0.672324
57927fa056cd2ae3173462ae3e2785747901fdf4
1,567
js
JavaScript
src/views/budget/BudgetListView/index.js
muraliyeturi/simple-react-app
2f2105e4a200c24c3aff38cf5b7e3855af76c4e7
[ "MIT" ]
null
null
null
src/views/budget/BudgetListView/index.js
muraliyeturi/simple-react-app
2f2105e4a200c24c3aff38cf5b7e3855af76c4e7
[ "MIT" ]
null
null
null
src/views/budget/BudgetListView/index.js
muraliyeturi/simple-react-app
2f2105e4a200c24c3aff38cf5b7e3855af76c4e7
[ "MIT" ]
null
null
null
import React, { useEffect, useState } from 'react'; import { Box, Container, makeStyles, CircularProgress, } from '@material-ui/core'; import { Alert } from '@material-ui/lab'; import Page from 'src/components/Page'; import Results from './Results'; import Toolbar from './Toolbar'; const useStyles = makeStyles((theme) => ({ root: { backgroundColor: theme.palette.background.dark, minHeight: '100%', paddingBottom: theme.spacing(3), paddingTop: theme.spacing(3) } })); const BudgetListView = () => { const classes = useStyles(); const [budgetListData, updateData] = useState([]); const headers = { Authorization: `Bearer ${process.env.REACT_APP_APIKey}` }; let error = false; let errorDetails; try { useEffect(() => { const getData = async () => { const resp = await fetch(`${process.env.REACT_APP_BASE}${process.env.REACT_APP_BUDGET_API}`, { headers }); const json = await resp.json(); updateData(json.data.budgets); }; getData(); }, []); } catch (err) { error = true; errorDetails = err.detail; } return ( <Page className={classes.root} title="Budget" > {error && <Alert severity="error">{errorDetails}</Alert>} <Container maxWidth={false}> <Toolbar /> <Box mt={3}> {budgetListData.length > 0 && <Results budgetList={budgetListData} />} {budgetListData.length === 0 && <CircularProgress />} </Box> </Container> </Page> ); }; export default BudgetListView;
25.688525
114
0.60753
57928fe304b124ec7d3dc8b45324f7ca2b73824f
1,189
js
JavaScript
public/js/scheda_utente.js
AldoBarca/hw2
7719e1d4186a4a67c93959fb216f7fa5a990932e
[ "MIT" ]
null
null
null
public/js/scheda_utente.js
AldoBarca/hw2
7719e1d4186a4a67c93959fb216f7fa5a990932e
[ "MIT" ]
null
null
null
public/js/scheda_utente.js
AldoBarca/hw2
7719e1d4186a4a67c93959fb216f7fa5a990932e
[ "MIT" ]
null
null
null
fetch("http://localhost/hw2/public/home/inizializza").then(onResponse, onError).then(inizializza); function inizializza(json) { console.log(json); const immagine = document.createElement('img'); immagine.src = json[16].immagine; immagine.classList.add('centra'); const container = document.querySelector('#immagine') if (container != null) { container.prepend(immagine); document.querySelector('.centra').addEventListener('click', richiediPosto); } } function onResponse(response) { if (!response.ok) { console.log('Problema con la riposta'); return null; } return response.json(); } function onError(error) { console.log('Errore' + error); } function richiediPosto() { fetch('/hw2/public/Scheda_utente/Richiedi_Posto_Auto').then(onResponse, onError).then(onJson); } function onJson(json) { console.log(json); document.querySelector('#informazione').textContent = json['numero']; document.querySelector('#immagine').classList.add('hidden'); document.querySelector('#prenotazione_effettuata').classList.remove('hidden'); document.querySelector('.centra').removeEventListener('click', richiediPosto); }
29.725
98
0.708999
5792e2acc0a3351a65aeb0d3b6d54d253eeeb3f8
3,601
js
JavaScript
test/calculator.test.js
thoughtsunificator/eval_expr
283ceb07be324556bdc95e6ac3b6e4103fe42fbb
[ "MIT" ]
null
null
null
test/calculator.test.js
thoughtsunificator/eval_expr
283ceb07be324556bdc95e6ac3b6e4103fe42fbb
[ "MIT" ]
null
null
null
test/calculator.test.js
thoughtsunificator/eval_expr
283ceb07be324556bdc95e6ac3b6e4103fe42fbb
[ "MIT" ]
null
null
null
import assert from "assert" import { Calculator } from '../index.js' describe("calculator", () => { it("addition", () => { assert.strictEqual(Calculator.compute( "5 + 1" ), 6) assert.strictEqual(Calculator.compute( "1 + 1 + 1" ), 3) assert.strictEqual(Calculator.compute( "100 + 25 + 0 + 0 + 9" ), 134) assert.strictEqual(Calculator.compute( "51 + 111 + 5 + 1000 + 2" ), 1169) assert.strictEqual(Calculator.compute( "234 + 324 + 23543.5 + 1.5" ), 24103) assert.strictEqual(Calculator.compute( "38 +- 14 + 91 + 1 + 3 +- 2" ), 117) }) it("substraction", () => { assert.strictEqual(Calculator.compute( "0 - 1" ), -1) assert.strictEqual(Calculator.compute( "1 - 1 - 13243" ), -13243) assert.strictEqual(Calculator.compute( "51 - 111 - 5 - 1000 - 2" ), -1067) assert.strictEqual(Calculator.compute( "234 - 324 - 23543.5 - 1.5" ), -23635) assert.strictEqual(Calculator.compute( "-25 - 25 - 0 - -120 - 9" ), 61) }) it("division", () => { assert.strictEqual(Calculator.compute( "0 / 1" ), 0) assert.ok(isNaN(Calculator.compute( "0 / 0" ))) assert.strictEqual(Calculator.compute( "-25 / 25 / 0 / -0 / 9" ), Infinity) assert.strictEqual(Calculator.compute( "51 / 111 / 5 / 1000 / 2" ), 0.00004594594594594595) }) it("multiplication", () => { assert.strictEqual(Calculator.compute( "0 * 1" ), 0) assert.strictEqual(Calculator.compute( "2 * + 150" ), 300) assert.strictEqual(Calculator.compute( "5 * - 180" ), -900) assert.strictEqual(Calculator.compute( "51 * 111 * 5 * 1000 * 2" ), 56610000) assert.strictEqual(Calculator.compute( "3 * 111.5" ), 334.5) }) it("modulo", () => { assert.strictEqual(Calculator.compute( "0 % 1" ), 0) assert.strictEqual(Calculator.compute( "0 % + 121" ), 0) assert.strictEqual(Calculator.compute( "0 % - 990" ), 0) assert.strictEqual(Calculator.compute( "23 % 12 % 511" ), 11) assert.strictEqual(Calculator.compute( "5 % 1555 % 555" ), 5) assert.ok(isNaN(Calculator.compute( "1 % 0" ))) assert.strictEqual(Calculator.compute( "3 % 111.5" ), 3) }) it("order", () => { assert.strictEqual(Calculator.compute( "5 + 5 * 2" ), 20) assert.strictEqual(Calculator.compute( "5 - 1 / 2" ), 4.5) assert.strictEqual(Calculator.compute( "990 - 7 % 10" ), 983) }) it("parentheses", () => { assert.strictEqual(Calculator.compute( "38 +- 14 + (91 + 1) + 3 +- 2" ), 117) assert.strictEqual(Calculator.compute( "234 - (324 - 23543.5) - 1.5" ), 23452) assert.strictEqual(Calculator.compute( "51 / 111 / (5 / 1000) / 2" ), 45.94594594594595) }) it("multipleParentheses", () => { assert.strictEqual(Calculator.compute( "122 * (54534 * 5) * 1 * (2 * 4)" ), 266125920) assert.strictEqual(Calculator.compute( "122 * (525.34 / 5) % 1 * (2 + 4)" ), 1.7760000000125729) assert.strictEqual(Calculator.compute( "122 * (54534 * 5) / 6.5 * (2 - 4)" ), -10235612.307692308) }) it("nestedParentheses", () => { assert.strictEqual(Calculator.compute( "51 * 111 * (5 * 1000 * (5 * 5)) * 2" ), 1415250000) assert.strictEqual(Calculator.compute( "51 * 111 * (5 * -1000 * (5 * 5)) * 2" ), -1415250000) assert.strictEqual(Calculator.compute( "51 * 111 * (5 * 1000.231243 * (5 * 5))" ), 707788633.327875) assert.strictEqual(Calculator.compute( "5 + (5 * (2 * 2.432423 / (5 * 2)))" ), 7.432423) assert.strictEqual(Calculator.compute( "(2 * (5 + (5 * (2 * 2.432423 / (5 * 2)))))" ), 14.864846) assert.strictEqual(Calculator.compute( "51 * 111 * (5 * 1000.231243 * (5 * 5)) * (2 * (5 + (5 * (2 * 2.432423 / (5 * 2)))))" ), 10521169034.96933) assert.strictEqual(Calculator.compute( "511 % (111 % 5)" ), 0) }) })
46.766234
148
0.619272
57937a54d3dfab6e4e1de5407b59b62c9d3ab247
531
js
JavaScript
backend/routes/index.js
elisechant/quick-express-postgresql
45f83b41c135ede7fa9f8b57d61bffb14d6dfe0c
[ "MIT" ]
null
null
null
backend/routes/index.js
elisechant/quick-express-postgresql
45f83b41c135ede7fa9f8b57d61bffb14d6dfe0c
[ "MIT" ]
null
null
null
backend/routes/index.js
elisechant/quick-express-postgresql
45f83b41c135ede7fa9f8b57d61bffb14d6dfe0c
[ "MIT" ]
null
null
null
const express = require('express'); const router = express.Router(); const ProjectsController = require('./../controllers/projectsController'); const {catchErrors} = require('./../handlers/errorHandlers'); router.get('/', catchErrors(ProjectsController.index)); router.get('/projects', catchErrors(ProjectsController.index)); router.get('/projects/:id', catchErrors(ProjectsController.detail)); router.get('/contact', (req, res, next) => { res.render('contact', { title: 'Contact us', }) }); module.exports = router;
26.55
74
0.708098
57938150a154cb01c5f4eb38d86c4f96c013f647
239
js
JavaScript
babel.config.js
HubSpot/draft-extend
6475e7fab6f5ee0f7838c9b6f3155bef34586aad
[ "Apache-2.0" ]
118
2016-07-19T18:22:37.000Z
2021-11-08T10:13:35.000Z
babel.config.js
HubSpot/draft-extend
6475e7fab6f5ee0f7838c9b6f3155bef34586aad
[ "Apache-2.0" ]
25
2016-07-20T21:59:21.000Z
2021-09-01T07:38:20.000Z
babel.config.js
HubSpot/draft-extend
6475e7fab6f5ee0f7838c9b6f3155bef34586aad
[ "Apache-2.0" ]
21
2016-07-20T21:10:31.000Z
2020-11-27T10:38:02.000Z
module.exports = { env: { commonjs: { presets: ['@babel/env', '@babel/react'], plugins: ['@babel/transform-runtime'], }, esm: { presets: [ ['@babel/react', { useBuiltIns: true }] ] } } };
18.384615
47
0.468619
57956388aa634943d2b0e97c2dfb4d6b742e1015
305
sjs
JavaScript
src/application/custom/sjs/getDBPediaInfo.sjs
mmalgeri/pocapp
e1b35bdbc3e983850d2a1e031a46729f6fd4cf1b
[ "Apache-2.0" ]
null
null
null
src/application/custom/sjs/getDBPediaInfo.sjs
mmalgeri/pocapp
e1b35bdbc3e983850d2a1e031a46729f6fd4cf1b
[ "Apache-2.0" ]
null
null
null
src/application/custom/sjs/getDBPediaInfo.sjs
mmalgeri/pocapp
e1b35bdbc3e983850d2a1e031a46729f6fd4cf1b
[ "Apache-2.0" ]
null
null
null
var pocappLib = require("/application/xquery/getDBPediaActorInfo.xqy"); var res = pocappLib.getDBPediaActorInfo("Tom Cruise"); res; /* var pocappLib = require("/application/xquery/getDBPediaMovieInfo.xqy"); var res = pocappLib.getDBPediaMovieInfo("Cary_Elwes", "Wallace_Shawn", "Robin_Wright"); res; */
27.727273
87
0.767213
57975b4735debe41ec2e209e4c2231815be0e786
4,489
js
JavaScript
2. Application/src/components/WelcomeComp/assets/RobotIntDraw.js
EnriOv/portfolio2.0
c3d200df6b211ba3ee9ea7a1e47b85a1e71387ea
[ "MIT" ]
null
null
null
2. Application/src/components/WelcomeComp/assets/RobotIntDraw.js
EnriOv/portfolio2.0
c3d200df6b211ba3ee9ea7a1e47b85a1e71387ea
[ "MIT" ]
null
null
null
2. Application/src/components/WelcomeComp/assets/RobotIntDraw.js
EnriOv/portfolio2.0
c3d200df6b211ba3ee9ea7a1e47b85a1e71387ea
[ "MIT" ]
null
null
null
const RobotIntDraw = (props) => { const {className} = props; return ( <svg xmlns="http://www.w3.org/2000/svg" width="593.703" height="347.171" version="1.1" viewBox="0 0 157.084 91.856" className={className} > <defs> <marker orient="auto" overflow="visible" refX="0" refY="0"> <path fillRule="evenodd" strokeOpacity="1" strokeWidth="1.067" d="M10 0l4-4L0 0l14 4z" ></path> </marker> </defs> <g transform="translate(-18.627 -83.202)"> <g strokeLinejoin="miter" strokeMiterlimit="4" strokeOpacity="1" > <circle cx="97.325" cy="125.702" r="41.949" strokeDasharray="26.4581593, 1.10242331" strokeDashoffset="0" strokeLinecap="round" strokeWidth="1.102" paintOrder="normal" ></circle> <path strokeDasharray="none" strokeDashoffset="0" strokeLinecap="round" strokeWidth="1" d="M98.42 109.628a16.959 16.959 90 0114.862 8.461 16.959 16.959 90 01-.064 17.102 16.959 16.959 90 01-14.924 8.35" paintOrder="normal" ></path> <path strokeDasharray="none" strokeDashoffset="0" strokeLinecap="round" strokeWidth="0.108" d="M117.14 104.979a2.945 2.943 0 012.968-2.912 2.945 2.943 0 012.922 2.957 2.945 2.943 0 01-2.95 2.928 2.945 2.943 0 01-2.94-2.94" paintOrder="normal" transform="rotate(11.094) skewX(-.018)" ></path> <path strokeDasharray="none" strokeDashoffset="0" strokeLinecap="round" strokeWidth="1" d="M96.447 143.542a16.96 16.959 0 01-16.78-17.043 16.96 16.959 0 0116.95-16.874" paintOrder="normal" ></path> <circle cx="124.306" cy="126.111" r="8.459" strokeDasharray="none" strokeDashoffset="0" strokeLinecap="round" strokeWidth="0.385" paintOrder="normal" ></circle> <circle cx="70.785" cy="125.884" r="8.459" strokeDasharray="none" strokeDashoffset="0" strokeLinecap="round" strokeWidth="0.385" paintOrder="normal" ></circle> <path strokeDasharray="none" strokeLinecap="butt" strokeWidth="1.065" d="M124.883 126.08h47.625v0" ></path> <path strokeDasharray="none" strokeLinecap="butt" strokeWidth="1.065" d="M21.696 126.08H69.32v0" ></path> <path className='rotate-pie' strokeDasharray="none" strokeDashoffset="0" strokeLinecap="round" strokeWidth="0.342" d="M135.596 156.77a49.115 49.115 0 01-38.114 18.117 49.115 49.115 0 01-38.1-18.143L97.5 125.772z" paintOrder="normal" ></path> <path strokeDasharray="none" strokeDashoffset="0" strokeLinecap="round" strokeWidth="0.019" d="M42.892 120.143a.525.518 0 01.53-.513.525.518 0 01.52.521.525.518 0 01-.526.515.525.518 0 01-.524-.517" paintOrder="normal" transform="matrix(.98181 .18986 -.1953 .98074 0 0)" ></path> <path strokeDasharray="none" strokeDashoffset="0" strokeLinecap="round" strokeWidth="0.019" d="M195.901 90.508a.525.518 0 01.53-.512.525.518 0 01.52.52.525.518 0 01-.526.516.525.518 0 01-.524-.518" paintOrder="normal" transform="matrix(.98181 .18986 -.1953 .98074 0 0)" ></path> <path strokeDasharray="none" strokeLinecap="butt" strokeWidth="0.465" d="M27.781 131.2c25.136 0 25.23-.094 25.23-.094v0" ></path> <path strokeDasharray="none" strokeLinecap="butt" strokeWidth="0.465" d="M142.755 131.104c25.136 0 25.23-.095 25.23-.095v0" ></path> </g> </g> </svg> ); } export default RobotIntDraw;
31.836879
142
0.489196
579865966cba873fa227d8be17309444bda0554b
3,463
js
JavaScript
test/eslint-plugin-next/no-duplicate-head.test.js
Waryserpant122/next.js
79ed8e13b0567889782461d8a3f20e48c6d65a4d
[ "MIT" ]
11,216
2020-02-19T16:54:26.000Z
2022-03-31T08:08:22.000Z
test/eslint-plugin-next/no-duplicate-head.test.js
Waryserpant122/next.js
79ed8e13b0567889782461d8a3f20e48c6d65a4d
[ "MIT" ]
2,332
2020-02-20T22:12:29.000Z
2022-03-30T12:35:13.000Z
test/eslint-plugin-next/no-duplicate-head.test.js
Waryserpant122/next.js
79ed8e13b0567889782461d8a3f20e48c6d65a4d
[ "MIT" ]
810
2020-02-21T16:54:57.000Z
2022-03-30T05:31:34.000Z
const rule = require('@next/eslint-plugin-next/lib/rules/no-duplicate-head') const RuleTester = require('eslint').RuleTester RuleTester.setDefaultConfig({ parserOptions: { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { modules: true, jsx: true, }, }, }) var ruleTester = new RuleTester() ruleTester.run('no-duplicate-head', rule, { valid: [ { code: `import Document, { Html, Head, Main, NextScript } from 'next/document' class MyDocument extends Document { static async getInitialProps(ctx) { //... } render() { return ( <Html> <Head/> </Html> ) } } export default MyDocument `, filename: 'pages/_document.js', }, { code: `import Document, { Html, Head, Main, NextScript } from 'next/document' class MyDocument extends Document { render() { return ( <Html> <Head> <meta charSet="utf-8" /> <link href="https://fonts.googleapis.com/css2?family=Sarabun:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet" /> </Head> </Html> ) } } export default MyDocument `, filename: 'pages/_document.tsx', }, ], invalid: [ { code: ` import Document, { Html, Main, NextScript } from 'next/document' import Head from 'next/head' class MyDocument extends Document { render() { return ( <Html> <Head /> <Head /> <Head /> </Html> ) } } export default MyDocument `, filename: 'pages/_document.js', errors: [ { message: 'Do not include multiple instances of <Head/>. See: https://nextjs.org/docs/messages/no-duplicate-head', type: 'JSXElement', }, { message: 'Do not include multiple instances of <Head/>. See: https://nextjs.org/docs/messages/no-duplicate-head', type: 'JSXElement', }, ], }, { code: ` import Document, { Html, Main, NextScript } from 'next/document' import Head from 'next/head' class MyDocument extends Document { render() { return ( <Html> <Head> <meta charSet="utf-8" /> <link href="https://fonts.googleapis.com/css2?family=Sarabun:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet" /> </Head> <body> <Main /> <NextScript /> </body> <Head> <script dangerouslySetInnerHTML={{ __html: '', }} /> </Head> </Html> ) } } export default MyDocument `, filename: 'pages/_document.page.tsx', errors: [ { message: 'Do not include multiple instances of <Head/>. See: https://nextjs.org/docs/messages/no-duplicate-head', type: 'JSXElement', }, ], }, ], })
24.216783
120
0.456541
5799e99a0490bc8124248024844386357a99558f
78
js
JavaScript
sencha/plugins/define-rewriter.js
lovekpo/meen
f3d0db3afa4304740133f9d912e081247e5ad38e
[ "MIT" ]
null
null
null
sencha/plugins/define-rewriter.js
lovekpo/meen
f3d0db3afa4304740133f9d912e081247e5ad38e
[ "MIT" ]
null
null
null
sencha/plugins/define-rewriter.js
lovekpo/meen
f3d0db3afa4304740133f9d912e081247e5ad38e
[ "MIT" ]
null
null
null
// This code is common to Optimizer define rewriting for both touch and extjs
39
77
0.794872
579a163e64f26f9d98171b20bc862e29626620b6
2,629
js
JavaScript
src/PeripheralView.js
andrewthehan/peripheral-view
0d6456d387dce0d15d293d7391c66080f049e65e
[ "MIT" ]
1
2017-12-14T21:17:37.000Z
2017-12-14T21:17:37.000Z
src/PeripheralView.js
andrewthehan/peripheral-view
0d6456d387dce0d15d293d7391c66080f049e65e
[ "MIT" ]
null
null
null
src/PeripheralView.js
andrewthehan/peripheral-view
0d6456d387dce0d15d293d7391c66080f049e65e
[ "MIT" ]
null
null
null
import React, { Component } from "react"; import ReactDOM from "react-dom"; import { Waypoint } from "react-waypoint"; class PeripheralView extends Component { constructor(props) { super(props); this.state = { currentIndex: 0, isScrolling: false }; this.handleWaypoint = this.handleWaypoint.bind(this); } scrollTo(index) { const { handleChange } = this.props; if (handleChange) { handleChange(index); } this.setState({ currentIndex: index, isScrolling: true }); } componentDidUpdate(prevProps, prevState) { const { isScrolling } = this.state; if (isScrolling === prevState.isScrolling) { return; } if (!isScrolling) { const node = ReactDOM.findDOMNode(this.currentElement); let scrollableParent = node; let isScrollable; do { scrollableParent = scrollableParent.parentNode; if (scrollableParent == null) { throw new Error("Unable to find scrollable parent."); } const overflowY = window.getComputedStyle(scrollableParent).overflowY; isScrollable = overflowY !== "visible" && overflowY !== "hidden"; } while ( !isScrollable || scrollableParent.scrollHeight < scrollableParent.clientHeight ); scrollableParent.scrollTop = node.offsetTop - scrollableParent.offsetTop; } else { this.setState({ isScrolling: false }); } } handleWaypoint(wp, index) { const { previousPosition, currentPosition } = wp; if ( previousPosition === Waypoint.above || previousPosition === Waypoint.below ) { const { handleChange } = this.props; if (handleChange) { handleChange(index); } this.setState({ currentIndex: index }); } } render() { const { length, radius, renderMap } = this.props; const { currentIndex, isScrolling } = this.state; if (isScrolling) { return []; } const start = Math.max(0, currentIndex - radius); const end = Math.min(length, currentIndex + radius); const waypoints = []; for (let i = start; i < end; ++i) { waypoints[i - start] = ( <Waypoint {...(i === currentIndex ? { ref: r => (this.currentElement = r) } : {})} key={-(i + 1)} onEnter={wp => this.handleWaypoint(wp, i)} fireOnRapidScroll /> ); } const view = waypoints.reduce( (a, x, i) => a.concat(x, renderMap(i + start)), [] ); return view; } } export default PeripheralView;
22.86087
79
0.580068
579a6ed607a99be1fcd7f9d85666b28895c4f255
47,073
js
JavaScript
commands/mashups-gentourcode.js
WeWuzNidokangz/Iolanthe
bfcb616af5aa11edf37be83b72011a09917e9bcb
[ "MIT" ]
null
null
null
commands/mashups-gentourcode.js
WeWuzNidokangz/Iolanthe
bfcb616af5aa11edf37be83b72011a09917e9bcb
[ "MIT" ]
null
null
null
commands/mashups-gentourcode.js
WeWuzNidokangz/Iolanthe
bfcb616af5aa11edf37be83b72011a09917e9bcb
[ "MIT" ]
null
null
null
/* Commands for tour code generation */ // FIXME: HERE: Auto unban abilities like Drizzle from lower-tier AAA mashups var Mashups = exports.Mashups = require('./../features/mashups/index.js'); var c_sIgnoreRuleArray = ['Pokemon', 'Standard', 'Team Preview']; var c_nCodeBroadcastCharacterLimit = 8192; var c_nCodeBroadcastLeeway = 10; var c_nCodeBroadcastWarningCharacterCount = (c_nCodeBroadcastCharacterLimit - c_nCodeBroadcastLeeway); var extractedRuleArray = []; var nExtractedRuleCount = 0; var extractedBanArray = []; var nExtractedBanCount = 0; var extractedUnbanArray = []; var nExtractedUnbanCount = 0; var extractedRestrictionArray = []; var nExtractedRestrictionCount = 0; var formatStackedAddOnsDictionary = new Object(); var baseFormatDetails = null; var baseFormatTierDetails = null; var sBaseModName; var nBaseGen; var nBaseGameType; var nTierId; var bTierModified; var bTierIncreased; var bIsLC; var TryAddRule = function(sCurrentRule, params, sourceFormat, bTierCheck) { var bIgnoreRule = false; if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG ruleset: ${sCurrentRule}`); var sCurrentRuleId = toId(sCurrentRule); // Tier rules have no value on a separate base and disrupt mashups with invisible compound bans for (nExistingRuleItr = 0; nExistingRuleItr < Mashups.Tier.Count; ++nExistingRuleItr) { if (toId(Mashups.getGenName(nBaseGen) + Mashups.tierDataArray[nExistingRuleItr].name) === sCurrentRuleId) { bIgnoreRule = true; // Format stacking needs to remove internal tier format specifications in some cases if(!bTierCheck) { // We can't be stacked during tier check if(sourceFormat.name in formatStackedAddOnsDictionary) { // Stacked format if(nTierId < nExistingRuleItr) { // Mashup's tier is above (<) this; it will be disruptive if(Mashups.MASHUPS_DEBUG_ON) monitor(`Inverting ruleset: ${sCurrentRule} (nTierId: ${nTierId}, nExistingRuleItr: ${nExistingRuleItr})`); bIgnoreRule = false; // Invert rule instead of ignoring it sCurrentRule = '!' + sCurrentRule; sCurrentRuleId = '!' + sCurrentRuleId; } } } break; } if (bIgnoreRule) return; } // Banned (redundant) rules for (nExistingRuleItr = 0; nExistingRuleItr < c_sIgnoreRuleArray.length; ++nExistingRuleItr) { if (toId(c_sIgnoreRuleArray[nExistingRuleItr]) === sCurrentRuleId) { bIgnoreRule = true; break; } if (bIgnoreRule) return; } // Ignore certain 'disruptive' rules like Standard with nested bans and that are generally redundant for (nExistingRuleItr = 0; nExistingRuleItr < Mashups.DisruptiveRuleArray.length; ++nExistingRuleItr) { if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG disruptive: ${Mashups.DisruptiveRuleArray[nExistingRuleItr]}, ${sCurrentRule}`); if (toId(Mashups.DisruptiveRuleArray[nExistingRuleItr]) === sCurrentRuleId) { bIgnoreRule = true; break; } if (bIgnoreRule) return; } // Ignore rules that are already in the base format if(baseFormatDetails.ruleset) { for (nExistingRuleItr = 0; nExistingRuleItr < baseFormatDetails.ruleset.length; ++nExistingRuleItr) { if (baseFormatDetails.ruleset[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } if (bIgnoreRule) return; } } if (params.additionalRules) { // Ignore rules that are redundant because they have already been added in params for (nExistingRuleItr = 0; nExistingRuleItr < params.additionalRules.length; ++nExistingRuleItr) { if (params.additionalRules[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } if (extractedRuleArray) { // Ignore rules that are already in extractedRuleArray for (nExistingRuleItr = 0; nExistingRuleItr < extractedRuleArray.length; ++nExistingRuleItr) { if (extractedRuleArray[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG ruleset survived culling: ${sCurrentRule}`); // Add relevant rule extractedRuleArray[nExtractedRuleCount] = sCurrentRule; nExtractedRuleCount++; } var TryAddBan = function(sCurrentRule, params, nSourceTier, bTierCheck=false) { var bIgnoreRule = false; if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG banlist: ${sCurrentRule}`); if(Mashups.MASHUPS_DEBUG_ON) monitor(`base: ${baseFormatDetails.name}`); // Ignore bans that are already in the base format if(baseFormatDetails.banlist) { for (nExistingRuleItr = 0; nExistingRuleItr < baseFormatDetails.banlist.length; ++nExistingRuleItr) { if (baseFormatDetails.banlist[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } if (bIgnoreRule) return; } } // Ignore bans that are already in the base format's tier format (e.g. Baton Pass for OU-based metas) if(baseFormatTierDetails.banlist) { for (nExistingRuleItr = 0; nExistingRuleItr < baseFormatTierDetails.banlist.length; ++nExistingRuleItr) { if (baseFormatTierDetails.banlist[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } if (bIgnoreRule) return; } } if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG ban survived culling 0: ${sCurrentRule}`); if (params.additionalBans) { // Ignore bans that are redundant because they have already been added in params for (nExistingRuleItr = 0; nExistingRuleItr < params.additionalBans.length; ++nExistingRuleItr) { if (params.additionalBans[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG ban survived culling 1: ${sCurrentRule}`); if (params.additionalUnbans) { // Ignore unbans that are in unbans params because we want that to take priority for (nExistingRuleItr = 0; nExistingRuleItr < params.additionalUnbans.length; ++nExistingRuleItr) { if (params.additionalUnbans[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } if (extractedBanArray) { // Ignore bans that are already in extractedBanArray for (nExistingRuleItr = 0; nExistingRuleItr < extractedBanArray.length; ++nExistingRuleItr) { if (extractedBanArray[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } var goAsPoke = Mashups.getGameObjectAsPokemon(sCurrentRule); if(goAsPoke) { // As Pokemon checks // Ignore specific Pokemon bans if it would already be banned by tier if(!bTierCheck && bTierModified && !bIsLC) { var nPokeTier = Mashups.calcPokemonTier(goAsPoke); if(Mashups.isABannedInTierB(nPokeTier, nTierId)) { return; } } // Ignore Pokemon bans if the final tier is higher than the source formats's tier if(!bTierCheck && (nTierId < nSourceTier) ) { var nPokeTier = Mashups.calcPokemonTier(goAsPoke); if(!Mashups.isABannedInTierB(nPokeTier, nTierId)) { return; } } } if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG ban survived culling: ${sCurrentRule}`); // Add relevant ban extractedBanArray[nExtractedBanCount] = sCurrentRule; nExtractedBanCount++; if (extractedUnbanArray) { // If a Pokemon is banned in one component meta and banned in another, prioritise ban: remove it from prior extracted unbans for (nExistingRuleItr = 0; nExistingRuleItr < nExtractedUnbanCount; ++nExistingRuleItr) { if (extractedUnbanArray[nExistingRuleItr] === sCurrentRule) { extractedUnbanArray.splice(nExistingRuleItr, 1); nExtractedUnbanCount--; } } } } var TryAddRestriction = function(sCurrentRule, params) { var bIgnoreRule = false; // Ignore restrictions that are already in the base format if(baseFormatDetails.restricted) { for (nExistingRuleItr = 0; nExistingRuleItr < baseFormatDetails.restricted.length; ++nExistingRuleItr) { if (baseFormatDetails.restricted[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } if (bIgnoreRule) return; } } if (params.additionalRestrictions) { // Ignore restrictions that are redundant because they have already been added in params for (nExistingRuleItr = 0; nExistingRuleItr < params.additionalRestrictions.length; ++nExistingRuleItr) { if (params.additionalRestrictions[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } if (extractedRestrictionArray) { // Ignore restrictions that are already in extractedRestrictionArray for (nExistingRuleItr = 0; nExistingRuleItr < extractedRestrictionArray.length; ++nExistingRuleItr) { if (extractedRestrictionArray[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG restriction survived culling: ${sCurrentRule}`); // Add relevant restrictiom extractedRestrictionArray[nExtractedRestrictionCount] = sCurrentRule; nExtractedRestrictionCount++; } var TryAddUnban = function(sCurrentRule, params, nSourceTier, bTierCheck=false) { var bIgnoreRule = false; if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG unbanlist: ${sCurrentRule}`); // Ignore unbans that are already in the base format if(baseFormatDetails.unbanlist) { for (nExistingRuleItr = 0; nExistingRuleItr < baseFormatDetails.unbanlist.length; ++nExistingRuleItr) { if (baseFormatDetails.unbanlist[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } if (params.additionalUnbans) { // Ignore unbans that are redundant because they have already been added in params for (nExistingRuleItr = 0; nExistingRuleItr < params.additionalUnbans.length; ++nExistingRuleItr) { if (params.additionalUnbans[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } if (extractedUnbanArray) { // Ignore unbans that are already in extractedUnbanArray for (nExistingRuleItr = 0; nExistingRuleItr < extractedUnbanArray.length; ++nExistingRuleItr) { if (extractedUnbanArray[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } if (params.additionalBans) { // Ignore unbans that are in ban params under all circumstances because we clearly want to definitely ban that thing for (nExistingRuleItr = 0; nExistingRuleItr < params.additionalBans.length; ++nExistingRuleItr) { if (params.additionalBans[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } if (extractedBanArray) { // Ignore unbans that were implicitely banned by another meta (if they were in unban params also we would already have continued) for (nExistingRuleItr = 0; nExistingRuleItr < extractedBanArray.length; ++nExistingRuleItr) { if (extractedBanArray[nExistingRuleItr] === sCurrentRule) { bIgnoreRule = true; break; } } if (bIgnoreRule) return; } var goAsPoke = Mashups.getGameObjectAsPokemon(sCurrentRule); if(goAsPoke) { // As Pokemon checks // Autoreject overtiered pokes if base tier altered if(!bTierCheck && bTierModified && !bIsLC) { // FIXME: LC needs separate processing var nPokeTier = Mashups.calcPokemonTier(goAsPoke); if(Mashups.isABannedInTierB(nPokeTier, nTierId)) { return; } } } if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG unban survived culling: ${sCurrentRule}`); // Add relevant unban extractedUnbanArray[nExtractedUnbanCount] = sCurrentRule; nExtractedUnbanCount++; } var ExtractFormatRules = function(formatDetails, params, bTierCheck=false) { if(!formatDetails) return; if(!formatDetails.name) return; var sCurrentRule; var nFormatGen = Mashups.determineFormatGen(formatDetails); var nFormatBasisTier = Mashups.determineFormatBasisTierId(formatDetails, nFormatGen); // ruleset if (formatDetails.ruleset) { //monitor(`DEBUG ruleset`); for (nRuleItr = 0; nRuleItr < formatDetails.ruleset.length; ++nRuleItr) { sCurrentRule = formatDetails.ruleset[nRuleItr]; TryAddRule(sCurrentRule, params, formatDetails, bTierCheck); } } // banlist if (formatDetails.banlist) { if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG banlist`); for (nRuleItr = 0; nRuleItr < formatDetails.banlist.length; ++nRuleItr) { sCurrentRule = formatDetails.banlist[nRuleItr]; TryAddBan(sCurrentRule, params, nFormatBasisTier, bTierCheck); } } // unbanlist if (formatDetails.unbanlist) { if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG unbanlist`); for (nRuleItr = 0; nRuleItr < formatDetails.unbanlist.length; ++nRuleItr) { sCurrentRule = formatDetails.unbanlist[nRuleItr]; TryAddUnban(sCurrentRule, params, nFormatBasisTier, bTierCheck); } } // 20/08/02 restrictions should work now if (formatDetails.restricted) { if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG restricted`); for (nRuleItr = 0; nRuleItr < formatDetails.restricted.length; ++nRuleItr) { sCurrentRule = formatDetails.restricted[nRuleItr]; TryAddRestriction(sCurrentRule, params); } } // Special cases var sGenericMetaName = Mashups.genericiseMetaName(formatDetails.name); if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG sGenericMetaName: ${sGenericMetaName}`); switch(sGenericMetaName) { // 20/08/02: New restrictions system /*case 'stabmons': ExtractStabmonsRestricted(formatDetails.restrictedMoves, params, bTierCheck, nFormatBasisTier); ExtractStabmonsRestricted(formatDetails.restricted, params, bTierCheck, nFormatBasisTier); break;*/ } } var ExtractStabmonsRestricted = function(restrictedArray, params, bTierCheck, nFormatBasisTier) { if (!restrictedArray) return; if(params.useRestrictions) { // Create restrictions for (nRuleItr = 0; nRuleItr < restrictedArray.length; ++nRuleItr) { sCurrentRule = restrictedArray[nRuleItr]; TryAddRestriction(sCurrentRule, params); } } else { // In a 'short' tour code, treat restricted moves as extra bans for (nRuleItr = 0; nRuleItr < restrictedArray.length; ++nRuleItr) { sCurrentRule = restrictedArray[nRuleItr]; TryAddBan(sCurrentRule, params, nFormatBasisTier, bTierCheck); } } } //#region eCommandParam var eCommandParam = { 'BaseFormat':0, 'AddOnFormats':1, 'LaunchTour':2, 'useRestrictions':3, 'AdditionalBans':4, 'AdditionalUnbans':5, 'AdditionalRules':6, 'AdditionalUnrules':7, 'AdditionalRestrictions':8, 'CustomTitle':9, 'TimeToStart':10, 'AutoDQ':11, 'Count':12, }; Object.freeze(eCommandParam); //#endregion exports.commands = { genmashup: 'gentourcode', generatemashup: 'gentourcode', generatetourcode: 'gentourcode', gentourcode: 'gentourcode', gentour: 'gentourcode', generatetour: 'gentourcode', gentourcode: function (arg, user, room, cmd) { if (!this.isRanked(Tools.getGroup('voice'))) return false; if (!arg || !arg.length) { this.reply(`No formats specified!`); return; } var args = arg.split(','); var params = { baseFormat: null, addOnFormats: null, additionalBans: null, additionalUnbans: null, additionalRestrictions: null, additionalRules: null, additionalUnrules: null, customTitle: null, timeToStart: 10, autodq: null, type: 'elimination', useCompression: true, useRestrictions: true, }; for (var i = 0; i < args.length; i++) { args[i] = args[i].trim(); if (!args[i]) continue; switch (i) { case eCommandParam.BaseFormat: // baseFormat // Search base format as a server native format params.baseFormat = Mashups.getFormatKey(args[i]); // FIXME: Add support for common compound bases like PH if (null === params.baseFormat) { this.reply(`Base format: "${args[i]}" not found on this server!`); return; } // (Tier definition formats as bases now supported) break; case eCommandParam.AddOnFormats: { // addOnFormats // Start add-ons with empty array var nAddOnCount = 0; params.addOnFormats = []; // Split add-ons var sAddOnFormatsString = args[i]; var addOnFormatsArray = sAddOnFormatsString.split('|'); var sAddOnKey; if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG sAddOnFormatsString: ${sAddOnFormatsString}`); for (var nAddOn = 0; nAddOn < addOnFormatsArray.length; ++nAddOn) { if (!addOnFormatsArray[nAddOn]) continue; if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG addOnFormatsArray[${nAddOn}]: ${addOnFormatsArray[nAddOn]}`); addOnFormatsArray[nAddOn].trim(); // Search add-on format as a server native format sAddOnKey = Mashups.getFormatKey(addOnFormatsArray[nAddOn]); // FIXME: Add support for common compound bases like PH if (null === sAddOnKey) { this.reply(`Add-on format: "${addOnFormatsArray[nAddOn]}" not found on this server!`); return; } params.addOnFormats[nAddOnCount] = sAddOnKey; nAddOnCount++; } } break; case eCommandParam.LaunchTour: { } break; case eCommandParam.useRestrictions: { var sUseComplexBansString = args[i]; params.useRestrictions = 'true' === toId(sUseComplexBansString) ? true : false; } break; case eCommandParam.AdditionalBans: { // additionalBans // Start addition bans with empty array var nAdditionalBanCount = 0; params.additionalBans = []; // Split addition bans var sAdditionalBansString = args[i]; var additionalBansArray = sAdditionalBansString.split('|'); var sBanGOKey; for (var nGO = 0; nGO < additionalBansArray.length; ++nGO) { sBanGOKey = additionalBansArray[nGO].trim(); // Do validation in warnings for reliability params.additionalBans[nAdditionalBanCount] = sBanGOKey; nAdditionalBanCount++; } } break; case eCommandParam.AdditionalUnbans: { // additionalUnbans // Start addition unbans with empty array var nAdditionalUnbanCount = 0; params.additionalUnbans = []; // Split addition unbans var sAdditionalUnbansString = args[i]; var additionalUnbansArray = sAdditionalUnbansString.split('|'); var sUnbanGOKey; for (var nGO = 0; nGO < additionalUnbansArray.length; ++nGO) { sUnbanGOKey = additionalUnbansArray[nGO].trim(); // Do validation in warnings for reliability params.additionalUnbans[nAdditionalUnbanCount] = sUnbanGOKey; nAdditionalUnbanCount++; } } break; case eCommandParam.AdditionalRules: { // additionalRules var nAdditionalRuleCount = 0; params.additionalRules = []; // Split addition restrictions var sAdditionalRulesString = args[i]; var additionalRulesArray = sAdditionalRulesString.split('|'); var sRuleKey; for (var nRule = 0; nRule < additionalRulesArray.length; ++nRule) { sRuleKey = additionalRulesArray[nRule].trim(); // FIXME: Somehow pull and validate rules? params.additionalRules[nAdditionalRuleCount] = sRuleKey; nAdditionalRuleCount++; } } break; case eCommandParam.AdditionalUnrules: { } break; case eCommandParam.AdditionalRestrictions: { // additionalRestrictions // Start addition restrictions with empty array var nAdditionalRestrictionCount = 0; params.additionalRestrictions = []; // Split addition restrictions var sAdditionalRestrictionsString = args[i]; var additionalRestrictionsArray = sAdditionalRestrictionsString.split('|'); var sRestrictionGOKey; for (var nGO = 0; nGO < additionalRestrictionsArray.length; ++nGO) { additionalRestrictionsArray[nGO].trim(); // Get GameObject id; check it exists sRestrictionGOKey = Mashups.getGameObjectKey(additionalRestrictionsArray[nGO]); if (null === sRestrictionGOKey) { this.reply(`Additionally restricted GameObject: "${additionalRestrictionsArray[nGO]}" could not be identified!`); return; } params.additionalRestrictions[nAdditionalRestrictionCount] = sRestrictionGOKey; nAdditionalRestrictionCount++; } } break; case eCommandParam.CustomTitle: // customTitle if ((args[i]) && ('' !== args[i])) { params.customTitle = args[i]; } break; case eCommandParam.TimeToStart: // timeToStart params.timeToStart = args[i]; break; case eCommandParam.AutoDQ: // autodq params.autodq = args[i]; break; } } // Old but useful? /* if (params.baseFormat) { // FIXME: Need to subsplit here var format = Tools.parseAliases(params.baseFormat); if (!Formats[format] || !Formats[format].chall) return this.reply(this.trad('e31') + ' ' + format + ' ' + this.trad('e32')); details.format = format; } */ // Reset module globals extractedRuleArray = []; nExtractedRuleCount = 0; extractedBanArray = []; nExtractedBanCount = 0; extractedUnbanArray = []; nExtractedUnbanCount = 0; extractedRestrictionArray = []; nExtractedRestrictionCount = 0; // Determine format name and base format var sFormatName = Formats[params.baseFormat].name; if (params.useCompression) { sFormatName = toId(sFormatName); } baseFormatDetails = Mashups.findFormatDetails(params.baseFormat); if(Mashups.MASHUPS_DEBUG_ON) this.reply(`DEBUG baseFormatDetails: ${JSON.stringify(baseFormatDetails)}`); if(null === baseFormatDetails) { this.reply(`Could not find format details for ${params.baseFormat}! format.js may not be updated yet.`); return; } nBaseGen = Mashups.determineFormatGen(baseFormatDetails); if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG nBaseGen: ${nBaseGen}`); var nBaseFormatTierId = Mashups.determineFormatBasisTierId(baseFormatDetails, nBaseGen); if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG nBaseFormatTierId: ${nBaseFormatTierId}`); nBaseGameType = Mashups.determineFormatGameTypeId(baseFormatDetails); sBaseModName = Mashups.determineFormatMod(baseFormatDetails); baseFormatTierDetails = Mashups.findTierFormatDetails(nBaseFormatTierId, nBaseGen); if(Mashups.MASHUPS_DEBUG_ON) this.reply(`DEBUG baseFormatTierDetails: ${JSON.stringify(baseFormatTierDetails)}`); if(null === baseFormatTierDetails) { this.reply(`Could not find any format to use as base tier! (Gen: ${nBaseGen}, Tier Id: ${nBaseFormatTierId}`); return; } var nAddOn; var addOnFormat; var nRuleItr; // Check same meta is not included multiple times (pointless, fatal error) if (params.addOnFormats) { var nSubAddOn; var subAddOnFormat; for (nAddOn = 0; nAddOn < params.addOnFormats.length; ++nAddOn) { addOnFormat = Mashups.findFormatDetails(params.addOnFormats[nAddOn]); if(!addOnFormat) { this.reply(`Unknown add-on! : ${params.addOnFormats[nAddOn]}`); return; } // Check add-on is not the same as the base if(baseFormatDetails.name === addOnFormat.name) { this.reply(`An add-on format is the same as the base! : ${addOnFormat.name}`); return; } // Check same add-on is not included multiple times for (nSubAddOn = nAddOn+1; nSubAddOn < params.addOnFormats.length; ++nSubAddOn) { if(nAddOn === nSubAddOn) continue; subAddOnFormat = Mashups.findFormatDetails(params.addOnFormats[nSubAddOn]); if(addOnFormat.name === subAddOnFormat.name) { this.reply(`An add-on format appeared multiple times! : ${addOnFormat.name}`); return; } } } } // Put all involved metas into an array for robust accessing var sMetaArray = [params.baseFormat]; var metaDetailsArray = [baseFormatDetails]; for ( nAddOn = 0; nAddOn < params.addOnFormats.length; ++nAddOn) { sMetaArray[nAddOn+1] = params.addOnFormats[nAddOn]; metaDetailsArray[nAddOn+1] = Mashups.findFormatDetails(params.addOnFormats[nAddOn]); } // Determine tier nTierId = nBaseFormatTierId; // Assume the base format's tier by default bTierModified = false; bTierIncreased = false; // Search add-ons for tier-altering formats var nTierFormatAddOnIdx = -1; var nTierFormatMetaIdx = -1; var nLoopTierId; if (params.addOnFormats) { for (nAddOn = 0; nAddOn < params.addOnFormats.length; ++nAddOn) { addOnFormat = Mashups.findFormatDetails(params.addOnFormats[nAddOn]); if(!addOnFormat) continue; if(!addOnFormat.name) continue; nLoopTierId = Mashups.determineFormatDefinitionTierId(addOnFormat.name, nBaseGen); if( -1 !== nLoopTierId ) { // Found matching tier if(-1 !== nTierFormatAddOnIdx) { this.reply(`Found conflicting tier candidates, including : ${Mashups.tierDataArray[nTierId].name} and ${Mashups.tierDataArray[nLoopTierId].name}!`); return; } nTierId = nLoopTierId; nTierFormatAddOnIdx = nAddOn; nTierFormatMetaIdx = nAddOn + 1; bTierModified = true; } } } if( -1 === nTierFormatMetaIdx ) { // If no add-on modifies the tier, check if the base is a tier-defining format if(Mashups.isFormatTierDefinition(sFormatName, nBaseGen)) { nTierFormatMetaIdx = 0; } } bIsLC = (Mashups.Tier.LC == nTierId) || (Mashups.Tier.LCUbers == nTierId); if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG Using tier format: ${Mashups.tierDataArray[nTierId].name}`); // Deconstruct tier and build up bans atomically so they can be edited properly var nDeltaTier = nBaseFormatTierId - nTierId; var deltaUnbanArray = []; var nDeltaUnbanCount = 0; var bIsUbersBase = Mashups.tierDataArray[nTierId].isUbers; var bReachedLimit = false; var nRecursiveTierId; var bFirstLoop = true; var formatDetails; var sTierName; var nTierParent; if(nDeltaTier < 0) { // Final tier is reduced from base by an add-on tier format nRecursiveTierId = nTierId; while(!bReachedLimit) { sTierName = Mashups.tierDataArray[nRecursiveTierId].name; //monitor(`sTierName: ${sTierName}`); // Extract rules if this tier has a format formatDetails = Mashups.findFormatDetails(Mashups.getGenName(nBaseGen) + sTierName); if(null !== formatDetails) { //monitor(`Extract tier`); ExtractFormatRules(formatDetails, params, true); } // Ban the whole tier if it is above base if(!bFirstLoop) { TryAddBan(sTierName, params, nRecursiveTierId); } // Move on to next tier or end nTierParent = Mashups.tierDataArray[nRecursiveTierId].parent; //monitor(`nTierParent: ${nTierParent}`); if( (nTierParent <= nBaseFormatTierId) || (Mashups.Tier.Undefined === nTierParent) || (!bIsUbersBase && Mashups.tierDataArray[nTierParent].isUbers) ) { bReachedLimit = true; } else { nRecursiveTierId = nTierParent; } bFirstLoop = false; } } else if(nDeltaTier > 0) { // Final tier is increased over base by an add-on tier format bTierIncreased = true; nRecursiveTierId = nBaseFormatTierId; var nDeltaUnbanIndexOf; while(!bReachedLimit) { sTierName = Mashups.tierDataArray[nRecursiveTierId].name; //monitor(`sTierName: ${sTierName}`); // Extract rules if this tier has a format (only needed if above base) formatDetails = Mashups.findFormatDetails(Mashups.getGenName(nBaseGen) + sTierName); if(!bFirstLoop) { if(null !== formatDetails) { //monitor(`Extract tier`); ExtractFormatRules(formatDetails, params, true); } } // Determine if this will be the final loop nTierParent = Mashups.tierDataArray[nRecursiveTierId].parent; //monitor(`nTierParent: ${nTierParent}`); if( (nTierParent < nTierId) || (Mashups.Tier.Undefined === nTierParent) /*|| (!bIsUbersBase && Mashups.tierDataArray[nTierParent].isUbers)*/ ) { bReachedLimit = true; } else { nRecursiveTierId = nTierParent; } // Prevent unbans from previous tiers if they are rebanned in the upper tier if(null !== formatDetails) { //monitor(`Extract bans for rebanning`); if(formatDetails.banlist) { for(nRuleItr = 0; nRuleItr < formatDetails.banlist.length; ++nRuleItr) { nDeltaUnbanIndexOf = deltaUnbanArray.indexOf(formatDetails.banlist[nRuleItr]); if(nDeltaUnbanIndexOf < 0) continue; deltaUnbanArray[nDeltaUnbanIndexOf] = null; } deltaUnbanArray = deltaUnbanArray.filter(function (el) { return el != null; }); nDeltaUnbanCount = deltaUnbanArray.length; } } // Prepare to unban all the bans in the tier if we haven't reached limit if(!bReachedLimit) { if(null !== formatDetails) { //monitor(`Extract bans so we can reverse them`); if(formatDetails.banlist) { for(nRuleItr = 0; nRuleItr < formatDetails.banlist.length; ++nRuleItr) { if(deltaUnbanArray.includes(formatDetails.banlist[nRuleItr])) continue; deltaUnbanArray[nDeltaUnbanCount++] = formatDetails.banlist[nRuleItr]; } } } } bFirstLoop = false; } // Delta unban Pokemon from the base format tiered below the new tier var goAsPoke; for(nRuleItr = 0; nRuleItr < baseFormatDetails.banlist.length; ++nRuleItr) { goAsPoke = Mashups.getGameObjectAsPokemon(baseFormatDetails.banlist[nRuleItr]); if(goAsPoke) { // As Pokemon checks var nPokeTier = Mashups.calcPokemonTier(goAsPoke); //monitor(`${goAsPoke.name}: nPokeTier: ${nPokeTier}, nTierId: ${nTierId}`); if(!Mashups.isABannedInTierB(nPokeTier, nTierId)) { deltaUnbanArray[nDeltaUnbanCount++] = baseFormatDetails.banlist[nRuleItr]; } } } // Effect the delta unbans for(nRuleItr = 0; nRuleItr < deltaUnbanArray.length; ++nRuleItr) { TryAddUnban(deltaUnbanArray[nRuleItr], params, nTierId, true); } } // Otherwise, the base and final tier match, so we don't need to do anything // Determine tour name { // FIXME: Make tier meta last var sGenStrippedName; var nAAAIdx = -1; var sAAAPlaceholderToken = '@@@'; var sMnMPlaceholderToken = '$$$'; var bIncludesMnM = false; var bIncludesSubstantiveNonMnM = false; var bIncludesStabmons = false; var sMetaNameBasis; var sReplacePlaceholderContent; var sTourName = Mashups.getGenNameDisplayFormatted(nBaseGen) + ' '; for(var nMetaItr = 0; nMetaItr < sMetaArray.length; ++nMetaItr) { if(nMetaItr === nTierFormatMetaIdx) continue; // Tier-defining format should always go last // Special cases sGenStrippedName = Mashups.genStripName(sMetaArray[nMetaItr]); switch(sGenStrippedName) { case 'almostanyability': nAAAIdx = nMetaItr; sTourName += sAAAPlaceholderToken; continue; case 'mixandmega': bIncludesMnM = true; sTourName += sMnMPlaceholderToken; continue; case 'stabmons': bIncludesStabmons = true; bIncludesSubstantiveNonMnM = true; break; default: if(nTierFormatMetaIdx !== nMetaItr) { bIncludesSubstantiveNonMnM = true; } break; } // Spacing if(nMetaItr > 0) sTourName += ' '; // Append name as normal if(metaDetailsArray[nMetaItr]) { sMetaNameBasis = Mashups.genStripName(metaDetailsArray[nMetaItr].name); } else { sMetaNameBasis = sMetaArray[nMetaItr]; } sTourName += sMetaNameBasis; } // Post-process for special case meta names if(bIncludesMnM) { sReplacePlaceholderContent = ''; if(bIncludesSubstantiveNonMnM) { sTourName += ' n Mega'; } else { sReplacePlaceholderContent = 'Mix and Mega'; } sTourName = sTourName.replace(sMnMPlaceholderToken, sReplacePlaceholderContent); } if( nAAAIdx >= 0 ) { sReplacePlaceholderContent = ''; if(sTourName.includes('STABmons')) { // Prioritise stabmons sTourName = sTourName.replace('STABmons', 'STAAABmons'); } else if(sTourName.includes('a')) { // Replace letter a/A if we can sTourName = sTourName.replace('a', 'AAA'); } else if(sTourName.includes('A')) { sTourName = sTourName.replace('A', 'AAA'); } else { // Otherwise just fill in as AAA in ordered place if(0 === nAAAIdx) { sReplacePlaceholderContent += 'AAA'; } else { sReplacePlaceholderContent += ' AAA'; } } sTourName = sTourName.replace(sAAAPlaceholderToken, sReplacePlaceholderContent); } if(-1 !== nTierFormatMetaIdx) { sTourName += ' '; // Append name as normal if(metaDetailsArray[nTierFormatMetaIdx]) { sMetaNameBasis = Mashups.genStripName(metaDetailsArray[nTierFormatMetaIdx].name); } else { sMetaNameBasis = sMetaArray[nTierFormatMetaIdx]; } sTourName += sMetaNameBasis; } // Remove double spaces sTourName = sTourName.replace(' ', ' '); // Custom name option if (params.customTitle) { sTourName = params.customTitle; } } // Determine tour rules var tourRulesArray = []; var nTourRuleCount = 0; { // Add rules from add-ons if (params.addOnFormats) { if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG reached addOnFormats`); // Add rules created through format-stacking for ( nAddOn = 0; nAddOn < params.addOnFormats.length; ++nAddOn) { addOnFormat = Mashups.findFormatDetails(params.addOnFormats[nAddOn]); if(!Mashups.doesFormatHaveKeyCustomCallbacks(addOnFormat)) continue; // Format has custom callbacks and must be stacked to make them effective extractedRuleArray[nExtractedRuleCount] = addOnFormat.name; nExtractedRuleCount++; // Add to stacked dictionary formatStackedAddOnsDictionary[addOnFormat.name] = true; } var nExistingRuleItr; var bIgnoreRule; var sCurrentRule; for ( nAddOn = 0; nAddOn < params.addOnFormats.length; ++nAddOn) { //addOnFormat = Formats[params.addOnFormats[nAddOn]]; addOnFormat = Mashups.findFormatDetails(params.addOnFormats[nAddOn]); if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG addOnFormats[${nAddOn}]: ${JSON.stringify(addOnFormat)}`); // Don't do anything here with a tier add-on, as that should be handled above if(nTierFormatAddOnIdx === nAddOn) { if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG Ignoring as tier format...`); continue; } ExtractFormatRules(addOnFormat, params); // Format-exclusive unique behaviours if(!addOnFormat) continue; switch(Mashups.genStripName(toId(addOnFormat.name))) { case 'cap': if (extractedUnbanArray) { extractedUnbanArray[nExtractedUnbanCount++] = 'Crucibellite'; deltaUnbanArray[nDeltaUnbanCount++] = 'Crucibellite'; } break; } } } // Post-processes if(extractedUnbanArray) { // Cull extracted unbans that aren't included in base and every add-on (unbans are an intersection not union) var goAsPoke; var nPokeTier; for (var nRuleItr = 0; nRuleItr < extractedUnbanArray.length; ++nRuleItr) { // Delta unbans are whitelisted if(deltaUnbanArray.includes(extractedUnbanArray[nRuleItr])) continue; // Whitelist pokes that have been legalised by final tier to support ubers, etc goAsPoke = Mashups.getGameObjectAsPokemon(extractedUnbanArray[nRuleItr]); if(goAsPoke) { // As Pokemon checks nPokeTier = Mashups.calcPokemonTier(goAsPoke); if(!Mashups.isABannedInTierB(nPokeTier, nTierId)) { continue; } } // Nullify unbans that are banned by base format if(!baseFormatDetails.unbanlist || (!baseFormatDetails.unbanlist.includes(extractedUnbanArray[nRuleItr]))) { extractedUnbanArray[nRuleItr] = null; continue; } if (params.addOnFormats) { // Nullify unbans that are banned by any add-on for ( nAddOn = 0; nAddOn < params.addOnFormats.length; ++nAddOn) { addOnFormat = Mashups.findFormatDetails(params.addOnFormats[nAddOn]); if(!addOnFormat) continue; if(!addOnFormat.unbanlist || !addOnFormat.unbanlist.includes(extractedUnbanArray[nRuleItr])) { extractedUnbanArray[nRuleItr] = null; continue; } } } } extractedUnbanArray = extractedUnbanArray.filter(function (el) { return el != null; }); nExtractedUnbanCount = extractedUnbanArray.length; } // Special cases var sGenericMetaName = Mashups.genericiseMetaName(sFormatName); if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG sGenericMetaName: ${sGenericMetaName}`); switch(sGenericMetaName) { case 'mixandmega': { var restrictedArray = []; if (baseFormatDetails.restricted) restrictedArray = restrictedArray.concat(baseFormatDetails.restricted); if (params.additionalRestrictions) restrictedArray = restrictedArray.concat(params.additionalRestrictions); if (extractedRestrictionArray) restrictedArray = restrictedArray.concat(extractedRestrictionArray); if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG restrictedArray: ${restrictedArray.length}`); var unrestrictedArray = []; var unrestrictedCount = 0; for (nRuleItr = 0; nRuleItr < restrictedArray.length; ++nRuleItr) { var goAsPokemon = Mashups.getGameObjectAsPokemon(restrictedArray[nRuleItr]); if (!goAsPokemon) continue; if (extractedUnbanArray && extractedUnbanArray.includes(restrictedArray[nRuleItr]) ) { unrestrictedArray[unrestrictedCount++] = restrictedArray[nRuleItr]; } else if (params.additionalUnbans && params.additionalUnbans.includes(restrictedArray[nRuleItr]) ) { unrestrictedArray[unrestrictedCount++] = restrictedArray[nRuleItr]; } } if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG unrestrictedCount: ${unrestrictedCount}`); if (unrestrictedCount > 0) { var megaStoneArray = []; for (const itemValue of Object.values(Mashups.ItemsArray)) { if (!itemValue) continue; if (!itemValue.megaStone) continue; megaStoneArray.push(itemValue.name); } if(Mashups.MASHUPS_DEBUG_ON) monitor(`DEBUG megaStoneArray: ${megaStoneArray}`); var itemItr; for (nRuleItr = 0; nRuleItr < unrestrictedArray.length; ++nRuleItr) { for (itemItr = 0; itemItr < megaStoneArray.length; ++itemItr) { extractedBanArray[nExtractedBanCount++] = unrestrictedArray[nRuleItr] + ' + ' + megaStoneArray[itemItr]; } } } } break; } // 20/08/02: New restrictions system // Convert restrictions to complex bans /*if(params.useRestrictions && (nExtractedRestrictionCount > 0) ) { var pokedexKeys = Object.keys(Mashups.PokedexArray); var nPokeItr; var sPokeName; var pokeGO; var sTypeName; for (var nRuleItr = 0; nRuleItr < extractedRestrictionArray.length; ++nRuleItr) { var goAsMove = Mashups.getGameObjectAsMove(extractedRestrictionArray[nRuleItr]); if(goAsMove) { // As Move checks // Only STABmons adds moves as restrictions currently if(!goAsMove.type) continue; if(!goAsMove.name) continue; sTypeName = goAsMove.type; for (nPokeItr = 0; nPokeItr < pokedexKeys.length; ++nPokeItr) { sPokeName = pokedexKeys[nPokeItr]; // Don't complex ban the move if we actually learn it if(Mashups.doesPokemonLearnMove(sPokeName, goAsMove.name) ) continue; // Don't complex ban the move if we could learn it through Sketch if(Mashups.doesPokemonLearnMove(sPokeName, 'Sketch') ) continue; // Don't need complex ban if we don't have the typing to get it from STABmons Rule if(!Mashups.DoesPokemonHavePreBattleAccessToTyping(pokedexKeys[nPokeItr], sTypeName, true) ) continue; pokeGO = Mashups.getGameObjectAsPokemon(sPokeName); if(pokeGO && pokeGO.species) { sPokeName = pokeGO.species; } extractedBanArray[nExtractedBanCount++] = sPokeName + ' + ' + goAsMove.name; } } } }*/ // Generate warning list var warningArray = []; if (params.addOnFormats) { var nAddOnGameType; var nAddOnGen; var sAddOnMod; var sWarningStatement; var sGenericMetaName; var sGOKey; for ( nAddOn = 0; nAddOn < params.addOnFormats.length; ++nAddOn) { addOnFormat = Mashups.findFormatDetails(params.addOnFormats[nAddOn]); if(!addOnFormat) continue; // Mod conflict check - this is almost certain to be a fatal problem sAddOnMod = Mashups.determineFormatMod(addOnFormat); if( (sAddOnMod !== sBaseModName) && (!Mashups.isDefaultModName(sAddOnMod)) ) { sWarningStatement = `Mod Conflict: "${sAddOnMod}" in add-on "${addOnFormat.name}" conflicts with base mod "${sBaseModName}"!`; warningArray.push(sWarningStatement); } // Whitelist certain add-ons that we know will work cross-gen/gametype sGenericMetaName = Mashups.genericiseMetaName(addOnFormat.name); switch(sGenericMetaName) { case 'almostanyability': case 'stabmons': case 'balancedhackmons': continue; } // GameType conflict check nAddOnGameType = Mashups.determineFormatGameTypeId(addOnFormat); if(nAddOnGameType !== nBaseGameType) { sWarningStatement = `GameType Conflict: gametype "${Mashups.GameTypeDataArray[nAddOnGameType].name}" of add-on "${addOnFormat.name}" conflicts with base gametype "${Mashups.GameTypeDataArray[nBaseGameType].name}"!`; warningArray.push(sWarningStatement); } // Gen conflict check nAddOnGen = Mashups.determineFormatGen(addOnFormat); if(nAddOnGen !== nBaseGen) { sWarningStatement = `Generation Conflict: addOn "${addOnFormat.name}" is [Gen ${nAddOnGen.toString()}] but base format is [Gen ${nBaseGen.toString()}]!`; warningArray.push(sWarningStatement); } } if(params.additionalBans) { // Check param bans are real GameObjects for(nRuleItr = 0; nRuleItr < params.additionalBans.length; ++nRuleItr) { // Get GameObject id; check it exists sGOKey = Mashups.getGameObjectKey(params.additionalBans[nRuleItr]); if(sGOKey) continue; sWarningStatement = `Unidentified additional ban: "${params.additionalBans[nRuleItr]}" could not be identified as a real GameObject!`; warningArray.push(sWarningStatement); } } if(params.additionalUnbans) { // Added param unbans for(nRuleItr = 0; nRuleItr < params.additionalUnbans.length; ++nRuleItr) { // Get GameObject id; check it exists sGOKey = Mashups.getGameObjectKey(params.additionalUnbans[nRuleItr]); if(sGOKey) continue; sWarningStatement = `Unidentified additional unban: "${params.additionalUnbans[nRuleItr]}" could not be identified as a real GameObject!`; warningArray.push(sWarningStatement); } } } // Lock bans/unbans/restrictions at this point and concatenate '+'/'-'/'*' if(extractedBanArray) { // Inherent bans for (nRuleItr = 0; nRuleItr < extractedBanArray.length; ++nRuleItr) { extractedBanArray[nRuleItr] = '-' + extractedBanArray[nRuleItr]; } } if(params.additionalBans) { // Added param bans for (nRuleItr = 0; nRuleItr < params.additionalBans.length; ++nRuleItr) { params.additionalBans[nRuleItr] = '-' + params.additionalBans[nRuleItr]; } } if(extractedUnbanArray) { // Inherent unbans for (nRuleItr = 0; nRuleItr < extractedUnbanArray.length; ++nRuleItr) { extractedUnbanArray[nRuleItr] = '+' + extractedUnbanArray[nRuleItr]; } } if(params.additionalUnbans) { // Added param unbans for (nRuleItr = 0; nRuleItr < params.additionalUnbans.length; ++nRuleItr) { params.additionalUnbans[nRuleItr] = '+' + params.additionalUnbans[nRuleItr]; } } if(extractedRestrictionArray) { // Inherent restrictions for (nRuleItr = 0; nRuleItr < extractedRestrictionArray.length; ++nRuleItr) { extractedRestrictionArray[nRuleItr] = '*' + extractedRestrictionArray[nRuleItr]; } } if(params.additionalRestrictions) { // Added param restrictions for (nRuleItr = 0; nRuleItr < params.additionalRestrictions.length; ++nRuleItr) { params.additionalRestrictions[nRuleItr] = '*' + params.additionalRestrictions[nRuleItr]; } } // Construct final rules array from concatenated content if (extractedRuleArray) { // Put inherent rules in first tourRulesArray = tourRulesArray.concat(extractedRuleArray); } if (params.additionalRules) { // Then added param rules tourRulesArray = tourRulesArray.concat(params.additionalRules); } if(extractedRestrictionArray) { // Inherent restrictions tourRulesArray = tourRulesArray.concat(extractedRestrictionArray); } if(params.additionalRestrictions) { // Added param restrictions tourRulesArray = tourRulesArray.concat(params.additionalRestrictions); } if(extractedBanArray) { // Inherent bans tourRulesArray = tourRulesArray.concat(extractedBanArray); } if(params.additionalBans) { // Added param bans tourRulesArray = tourRulesArray.concat(params.additionalBans); } if(extractedUnbanArray) { // Inherent unbans tourRulesArray = tourRulesArray.concat(extractedUnbanArray); } if(params.additionalUnbans) { // Added param unbans tourRulesArray = tourRulesArray.concat(params.additionalUnbans); } nTourRuleCount = tourRulesArray.length; } // Construct tour code string let sTourCode = ''; sTourCode += `/tour new ${sFormatName}, ${params.type}, 32,1\n`; sTourCode += `/tour autostart ${params.timeToStart}\n`; if (nTourRuleCount > 0) { // Constructed rules sTourCode += `/tour rules `; for (nRuleItr = 0; nRuleItr < tourRulesArray.length; ++nRuleItr) { if (nRuleItr > 0) { sTourCode += `, `; } sTourCode += `${tourRulesArray[nRuleItr]}`; } sTourCode += `\n`; } sTourCode += `/tour name ${sTourName}\n`; let nTourCodeCharCount = sTourCode.length; // Split !code outputs let nCodeBlocksNeeded = Math.ceil( nTourCodeCharCount / c_nCodeBroadcastWarningCharacterCount ); if( nCodeBlocksNeeded > 1 ) { let sSplitTourCode; for(var nBlockItr=0; nBlockItr<nCodeBlocksNeeded; ++nBlockItr ) { sSplitTourCode = sTourCode.substr( nBlockItr * c_nCodeBroadcastWarningCharacterCount, c_nCodeBroadcastWarningCharacterCount ); if (sSplitTourCode) this.reply('!code ' + sSplitTourCode); } this.reply(`The generated tour code exceeded !code's ${c_nCodeBroadcastCharacterLimit.toString()} character limit, and had to be split into ${nCodeBlocksNeeded} blocks.`); } else {// Print out as !code let sStatement = '!code ' + sTourCode; if (sStatement) this.reply(sStatement); } // Warning about !code character limit errors /*if( nTourCodeCharCount > c_nCodeBroadcastWarningCharacterCount ) { this.reply(`The generated tour code may exceed !code's ${c_nCodeBroadcastCharacterLimit.toString()} character limit, preventing it from being displayed.`); }*/ // Print out warnings (after, so we don't hit message limit with tour code output itself) if(warningArray.length > 0) { var sWarningPlural = ( warningArray.length > 1 ) ? 'warnings' : 'warning'; this.reply(`Code generation triggered ${warningArray.length.toString()} ${sWarningPlural}:-`); var sWarningStatement = '!code '; for(var nWarnItr=0; nWarnItr<warningArray.length; ++nWarnItr) { sWarningStatement += warningArray[nWarnItr]; sWarningStatement += `\n`; } if (sWarningStatement) this.reply(sWarningStatement); } } };
36.016067
221
0.703227
579b92e94f7a1dd42584a1e12d545f4c26cdee82
1,895
js
JavaScript
app/score_stuff/renderer.js
tananamusic/tanana
0738e856e75d97453bbe0e3caa8fd95d7b46d957
[ "BSD-4-Clause" ]
11
2018-07-18T15:33:57.000Z
2020-10-09T12:52:16.000Z
app/score_stuff/renderer.js
tananamusic/tanana
0738e856e75d97453bbe0e3caa8fd95d7b46d957
[ "BSD-4-Clause" ]
1
2019-02-17T00:27:04.000Z
2019-02-17T00:27:04.000Z
app/score_stuff/renderer.js
tananamusic/tanana
0738e856e75d97453bbe0e3caa8fd95d7b46d957
[ "BSD-4-Clause" ]
5
2018-01-01T01:33:27.000Z
2022-03-28T19:25:31.000Z
const { OpenSheetMusicDisplay } = require('opensheetmusicdisplay') const { ipcRenderer } = require('electron') const { dialog } = require('electron').remote const Player = require('./Player.js') let libPath ipcRenderer.send('read-file') ipcRenderer.send('back-to-lib-window') ipcRenderer.on('back-to-lib-window-reply', (event, arg) => (libPath = arg)) const renderSheet = async fileData => { const scoreElem = document.querySelector('#main-score') const osmd = new OpenSheetMusicDisplay(scoreElem) await osmd.load(fileData, true) // removing loading warning document.querySelectorAll('.loading').forEach(e => e.remove()) osmd.render() console.log('osmd', osmd) return new Player({ osmd }) } const spacebarToggle = player => document.addEventListener('keyup', ev => { // space bar if (ev.keyCode === 32) { ev.preventDefault() player.toggle() } return false }) const toggleButton = player => document.querySelector('#play-button') .addEventListener('click', () => player.toggle()) const stopButton = player => document.querySelector('#stop-button') .addEventListener('click', () => player.end()) ipcRenderer.on('read-file-reply', async (event, { fileData }) => { try { const player = await renderSheet(fileData) spacebarToggle(player) toggleButton(player) stopButton(player) } catch (err) { console.log(err) dialog.showErrorBox('Tananã - erro', err.message) } // TODO get title from osmd let title = false title = title ? title + ' | Tananã' : 'Tananã | Música Desconhecida' document.title = title }) const goBack = () => { if (libPath) ipcRenderer.send('open-lib', libPath) else ipcRenderer.send('open-main-window') } document.querySelector('#back-button').addEventListener('click', goBack) document.addEventListener('keyup', (ev) => { // escape key if (ev.keyCode === 27) goBack() else return false })
29.153846
75
0.687071
579cbe0fd51231f7027d85194a64044d6e869cf6
3,293
js
JavaScript
src/utils/pkg.js
darkXmo/xmo-cli
dfa2138061cbc89356b56d805dd7823e4432970f
[ "MIT" ]
3
2021-09-29T07:24:33.000Z
2021-09-30T10:31:32.000Z
src/utils/pkg.js
darkXmo/xmo-cli
dfa2138061cbc89356b56d805dd7823e4432970f
[ "MIT" ]
null
null
null
src/utils/pkg.js
darkXmo/xmo-cli
dfa2138061cbc89356b56d805dd7823e4432970f
[ "MIT" ]
null
null
null
import { readFile, writeFile } from 'fs/promises'; import { cwd } from 'process'; import path from 'path'; import lg from './console.js'; /** * @param {string} dir路径 * @returns { Promise<{ * name?: "string"; * version?: string; * description?: string; * keywords?: string[]; author?: string; * main?: string; * type?: string; * license: string; * scripts?: { [key: string]: string; prepare?: string; commit?: string; "docker:dev"?: string; "docker:build"?: string; "docker:deploy"?: string}; * bin?: { [key: string]: string }; * repository?: { [key: string]: string }; * dependencies: { [key: string]: string }; * devDependencies?: { [key: string]: string }; * config?: { [key: string]: { [keyInside: string]: } ; commitizen?: { [keyInside: string]: } }; * "lint-staged"?: { [key: string]: { [keyInside: string]: string | string[] } }; * husky: any; * }> } */ export const getPackage = async (dir = cwd()) => { return JSON.parse(await readFile(path.join(dir, 'package.json'))); }; /** * 将对象写入package.json * @param {Object} pack * @param {string} dir */ export const writePackage = async (pack, dir = cwd()) => { await writeFile( path.join(dir, 'package.json'), JSON.stringify(pack, null, 2) ); }; /** * 将package.json部分对象用于修改 * @param {Object} options * @param {string} dir */ const modPackage = async (options, dir = cwd()) => { const pack = await getPackage(dir); Object.assign(pack, options); await writePackage(pack, dir); }; /** * @param {...("lint-staged" | "prettier" | "eslint" | "eslint-plugin-vue" | "eslint-config-prettier" | * "@commitlint/cli" | "@commitlint/config-conventional" | "cz-conventional-changelog")} type */ export const addDevDependence = async (...type) => { const devDependency = { 'lint-staged': '^11.1.2', prettier: '2.4.1', eslint: '^7.32.0', 'eslint-plugin-vue': '^7.18.0', 'eslint-config-prettier': '^8.3.0', '@commitlint/cli': '^13.1.0', '@commitlint/config-conventional': '^13.1.0', 'cz-conventional-changelog': '^3.3.0', }; const pack = await getPackage(); let devDependencies = pack['devDependencies'] ?? {}; type.forEach((value) => Object.assign(devDependencies, { [value]: devDependency[value], }) ); Object.assign(pack, { devDependencies }); await writePackage(pack); type.forEach((value) => { lg.createPackConfig('devDependency: ' + value); }); }; /** * @param {string} name * @param {string} value */ export const addScript = async (name, value) => { const pack = await getPackage(); const scripts = pack['scripts'] ?? {}; Object.assign(scripts, { [name]: value, }); Object.assign(pack, { scripts }); await writePackage(pack); lg.createPackConfig('scripts: ' + name); }; /** * @param { string } name * @param { any } value */ export const addConfig = async (name, value) => { const pack = await getPackage(); const config = pack['config'] ?? {}; Object.assign(config, { [name]: value, }); Object.assign(pack, { config }); await writePackage(pack); lg.createPackConfig('config'); }; export default { get: getPackage, write: writePackage, mod: modPackage, add: { script: addScript, devDependency: addDevDependence, config: addConfig, }, };
25.726563
148
0.6116
579d5122d11d455f10e62105438069344604b281
9,663
js
JavaScript
webapproot/pages/CreateShipmentDD/CreateShipmentDD.widgets.js
AlfredGerke/Intraship
be33cc888ae4a79b568cc9cc28abd4462c512fe9
[ "MIT" ]
null
null
null
webapproot/pages/CreateShipmentDD/CreateShipmentDD.widgets.js
AlfredGerke/Intraship
be33cc888ae4a79b568cc9cc28abd4462c512fe9
[ "MIT" ]
null
null
null
webapproot/pages/CreateShipmentDD/CreateShipmentDD.widgets.js
AlfredGerke/Intraship
be33cc888ae4a79b568cc9cc28abd4462c512fe9
[ "MIT" ]
null
null
null
CreateShipmentDD.widgets = { srvCreateShipmentDD: ["wm.ServiceVariable", {"inFlightBehavior":"executeLast","operation":"createShipmentDD","service":"ISService_1_0_de"}, {"onError":"srvCreateShipmentDDError","onResult":"srvCreateShipmentDDResult"}, { input: ["wm.ServiceInput", {"type":"createShipmentDDInputs"}, {}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"varResultByGetShipmentDDRequest","targetProperty":"part1"}, {}], wire1: ["wm.Wire", {"expression":undefined,"source":"app.varResultByGetAuthentication","targetProperty":"header"}, {}] }] }], binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"pnlLabelResponse","targetProperty":"loadingDialog"}, {}] }] }], srvGetShipmentDDRequest: ["wm.ServiceVariable", {"inFlightBehavior":"executeLast","operation":"getShipmentDDRequest","service":"RequestBuilder"}, {"onSuccess":"srvCreateShipmentDD","onSuccess1":"srvGetShipmentDDRequestSuccess1"}, { input: ["wm.ServiceInput", {"type":"getShipmentDDRequestInputs"}, {}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"cbxDoXMLLabel.dataValue","targetProperty":"isXMLLabel"}, {}] }] }], binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"pnlLabelResponse","targetProperty":"loadingDialog"}, {}] }] }], varResultByCreateShipmentDD: ["wm.Variable", {"type":"intraship.ws.de.CreateShipmentResponse"}, {}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"srvCreateShipmentDD","targetProperty":"dataSet"}, {}] }] }], varResultByGetShipmentDDRequest: ["wm.Variable", {"type":"intraship.ws.de.CreateShipmentDDRequest"}, {}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"srvGetShipmentDDRequest","targetProperty":"dataSet"}, {}] }] }], varSelectedItemShipmentNr: ["wm.Variable", {"type":"StringData"}, {}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"gridDetails.selectedItem.shipmentNumber.shipmentNumber","targetProperty":"dataSet.dataValue"}, {}] }] }], lbxMain: ["wm.Layout", {"horizontalAlign":"left","styles":{},"verticalAlign":"top","width":"1455px"}, {}, { pnlCreateShipmentDD: ["wm.FancyPanel", {"margin":"0,0,0,0","styles":{},"title":"CreateShipmentDD"}, {}, { pnlTop: ["wm.Panel", {"desktopHeight":"40px","enableTouchHeight":true,"height":"40px","horizontalAlign":"left","layoutKind":"left-to-right","mobileHeight":"40px","verticalAlign":"top","width":"100%"}, {}, { btnCreateShipmentDD: ["wm.Button", {"caption":"Execute","margin":"4","width":"154px"}, {"onclick":"btnCreateShipmentDDClick"}], cbxDoXMLLabel: ["wm.Checkbox", {"caption":"Create XML-Label","captionSize":"300px","dataValue":true,"desktopHeight":"35px","displayValue":true,"height":"35px","startChecked":true,"width":"155px"}, {"onchange":"cbxDoXMLLabelChange"}] }], pnlClient: ["wm.Panel", {"height":"100%","horizontalAlign":"left","layoutKind":"left-to-right","verticalAlign":"top","width":"100%"}, {}, { pnlResponse: ["wm.FancyPanel", {"margin":"0,0,0,0","styles":{},"title":"Response by CreateShipmentDD"}, {}, { pnlLabelResponse: ["wm.Panel", {"height":"100%","horizontalAlign":"left","verticalAlign":"top","width":"100%"}, {}, { pnlWSVersion: ["wm.Panel", {"desktopHeight":"35px","enableTouchHeight":true,"height":"35px","horizontalAlign":"left","layoutKind":"left-to-right","mobileHeight":"35px","styles":{},"verticalAlign":"top","width":"100%"}, {}, { edtMajorVersion: ["wm.Text", {"caption":"Major","captionSize":"50px","displayValue":"","emptyValue":"emptyString","helpText":"Versionshauptnummer des verarbeitenden WebService","placeHolder":"Major","readonly":true,"styles":{},"width":"125px"}, {}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"varResultByCreateShipmentDD.version.majorRelease","targetProperty":"dataValue"}, {}] }] }], edtMinorVersion: ["wm.Text", {"caption":"Minor","captionSize":"50px","displayValue":"","emptyValue":"emptyString","helpText":"Versionsunternummer des verarbeitenden WebService","placeHolder":"Minor","readonly":true,"styles":{},"width":"125px"}, {}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"varResultByCreateShipmentDD.version.minorRelease","targetProperty":"dataValue"}, {}] }] }] }], edtLabelURL: ["wm.Text", {"caption":undefined,"displayValue":"","emptyValue":"emptyString","helpText":"URL kann über einen PDF-Reader direkt im Browser verarbeitet werden","placeHolder":"Label URL","singleLine":false,"styles":{},"width":"100%"}, {}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"varResultByCreateShipmentDD.creationStates.labelurl","targetProperty":"dataValue"}, {}] }] }], edtXMLLabel: ["wm.LargeTextArea", {"caption":undefined,"captionPosition":"left","captionSize":"100px","displayValue":"","emptyValue":"emptyString","height":"100%","helpText":undefined,"styles":{},"width":"100%"}, {"onchange":"edtXMLLabelChange"}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"varResultByCreateShipmentDD.creationStates.XMLLabel","targetProperty":"dataValue"}, {}] }] }], gridDetails: ["wm.DojoGrid", {"columns":[ {"show":true,"field":"statusCode","title":"StatusCode","width":"125px","align":"left","formatFunc":"","mobileColumn":false}, {"show":true,"field":"shipmentNumber.shipmentNumber","title":"ShipmentNumber","width":"100%","align":"left","formatFunc":"","mobileColumn":false}, {"show":false,"field":"PHONE COLUMN","title":"-","width":"100%","align":"left","expression":"\"<div class='MobileRowTitle'>\" +\n\"StatusCode: \" + ${statusCode} +\n\"</div>\"\n\n+ \"<div class='MobileRow'>\" +\n\"ShipmentNumber: \" + ${shipmentNumber.shipmentNumber}\n + \"</div>\"\n\n","mobileColumn":true}, {"show":false,"field":"shipmentNumber.identCode","title":"ShipmentNumber.identCode","width":"100%","align":"left","formatFunc":"","mobileColumn":false}, {"show":false,"field":"shipmentNumber.licensePlate","title":"ShipmentNumber.licensePlate","width":"100%","align":"left","formatFunc":"","mobileColumn":false}, {"show":false,"field":"shipmentNumber.airwayBill","title":"ShipmentNumber.airwayBill","width":"100%","align":"left","formatFunc":"","mobileColumn":false}, {"show":false,"field":"labelurl","title":"Labelurl","width":"100%","align":"left","formatFunc":"","mobileColumn":false}, {"show":false,"field":"XMLLabel","title":"XMLLabel","width":"100%","align":"left","formatFunc":"","mobileColumn":false}, {"show":false,"field":"sequenceNumber","title":"SequenceNumber","width":"100%","align":"left","formatFunc":"","mobileColumn":false}, {"show":false,"field":"pickupConfirmationNumber","title":"PickupConfirmationNumber","width":"100%","align":"left","formatFunc":"","mobileColumn":false} ],"desktopHeight":"100px","deviceType":["desktop","tablet"],"enableTouchHeight":true,"height":"100px","localizationStructure":{},"margin":"4","minDesktopHeight":60,"minMobileHeight":60,"minWidth":400,"mobileHeight":"100px","singleClickEdit":true,"styles":{}}, {"onSelect":"gridDetailsSelect"}, { binding: ["wm.Binding", {}, {}, { wire1: ["wm.Wire", {"expression":undefined,"source":"varResultByCreateShipmentDD.creationStates","targetProperty":"dataSet"}, {}] }] }], gridDetailMessages: ["wm.DojoGrid", {"columns":[ {"show":true,"field":"dataValue","title":"StatusMessages","width":"100%","align":"left","formatFunc":"","mobileColumn":false}, {"show":false,"field":"PHONE COLUMN","title":"-","width":"100%","align":"left","expression":"\"<div class='MobileRowTitle'>\" +\n\"StatusMessages: \" + ${dataValue} +\n\"</div>\"\n\n","mobileColumn":true} ],"desktopHeight":"100px","dsType":"AnyData","enableTouchHeight":true,"height":"100px","margin":"4","minDesktopHeight":60,"minMobileHeight":60,"minWidth":400,"mobileHeight":"100px","singleClickEdit":true}, {}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"app.varResultByStatusMessages","targetProperty":"dataSet"}, {}] }] }] }], pnlStatusResponse: ["wm.Panel", {"desktopHeight":"35px","enableTouchHeight":true,"height":"35px","horizontalAlign":"left","mobileHeight":"37px","styles":{},"verticalAlign":"top","width":"100%"}, {}, { pnlStatusResponse1: ["wm.Panel", {"enableTouchHeight":true,"height":"100%","horizontalAlign":"left","layoutKind":"left-to-right","styles":{},"verticalAlign":"top","width":"100%"}, {}, { edtStatusCpde: ["wm.Number", {"caption":"StatusCode","displayValue":"","helpText":"Allgemeiner StatusCode","placeHolder":"Code","readonly":true,"width":"165px"}, {}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"varResultByCreateShipmentDD.status.statusCode","targetProperty":"dataValue"}, {}] }] }], edtStatusMessage: ["wm.Text", {"caption":"StatusMessage","captionSize":"150px","displayValue":"","emptyValue":"emptyString","helpText":"Allgemeine Statusmeldung","placeHolder":"Message","readonly":true,"width":"100%"}, {}, { binding: ["wm.Binding", {}, {}, { wire: ["wm.Wire", {"expression":undefined,"source":"varResultByCreateShipmentDD.status.statusMessage","targetProperty":"dataValue"}, {}] }] }] }] }] }] }] }] }] }
86.276786
309
0.651247
579d7405a6ce43b4158f445b73020e2303c432d5
1,906
js
JavaScript
elm-docs-download.js
pablomayobre/elm-docs-download
61e6e871f91978fc8d6b3afb3d870ad19dffffa5
[ "MIT" ]
2
2017-11-10T17:43:17.000Z
2018-05-13T10:09:48.000Z
elm-docs-download.js
Positive07/elm-docs-download
61e6e871f91978fc8d6b3afb3d870ad19dffffa5
[ "MIT" ]
1
2019-09-02T06:40:45.000Z
2019-09-02T06:40:45.000Z
elm-docs-download.js
Positive07/elm-docs-download
61e6e871f91978fc8d6b3afb3d870ad19dffffa5
[ "MIT" ]
null
null
null
#!/usr/bin/env node const commander = require('commander'); const scraper = require('./scraper.js'); const json = require('./json.js'); const download = require('./download.js'); const Pool = require('./pool.js'); let cwd; commander .description('Downloads documentation.json for all your installed dependencies') .version('0.1.1') .arguments('[dir]') .description(' [dir] optional search directory (default is current directory)') .action((argument) => { cwd = argument; }); commander.parse(process.argv); const pool = new Pool('MAIN', () => { console.log('-----FINISHED-----'); }); function waitFor(list) { let wait = 0; const packs = Object.keys(list); packs.forEach((pack) => { const versions = Object.keys(list[pack]); versions.forEach(() => { wait += 1; }); }); return wait; } function forVersions(list, cb) { const packs = Object.keys(list); packs.forEach((pack) => { const versions = Object.keys(list[pack]); versions.forEach((version) => { cb(pack, version); }); }); } cwd = cwd || process.cwd(); let list; let ignore = false; try { list = scraper(cwd); } catch (e) { console.error(e.message); ignore = true; } if (!ignore && list.length === 0) { console.error('ERROR - No packages found'); } else if (!ignore) { pool.wait(waitFor(list)); forVersions(list, (pack, version) => { const lib = list[pack][version]; const str = `${pack}/${version}`; pool.add(str); json(lib, (found) => { if (!found) { download(lib, (result, error) => { const success = result ? 'Success' : 'Failed'; console.log(`Downloaded: ${pack}@${version} - ${success}`); if (!result && error) console.error(`${error}\n`); pool.remove(str); }); } else { console.log(`Found: ${pack}@${version}`); pool.remove(str); } }); }); }
21.41573
82
0.580273
579e00295fd81f5efce426b692ae2a40b30c6b4b
7,285
js
JavaScript
dist/index.js
cukejianya/simple-pomodoro
dea0169b7a27b9402d94c235d39c8fa55c1e77b0
[ "MIT" ]
null
null
null
dist/index.js
cukejianya/simple-pomodoro
dea0169b7a27b9402d94c235d39c8fa55c1e77b0
[ "MIT" ]
3
2021-01-28T20:17:44.000Z
2022-03-25T18:55:30.000Z
dist/index.js
cukejianya/simple-pomodoro
dea0169b7a27b9402d94c235d39c8fa55c1e77b0
[ "MIT" ]
null
null
null
const pointer = document.getElementById('pointer'); const circle = document.getElementById('circle'); const progressCircle = document.getElementById('progress'); const control = document.getElementById('control'); const clock = document.getElementById('clock'); const session = document.getElementById('session'); const modal = document.getElementById('modal'); const modalOverlay = document.getElementById('modal-overlay'); const addButton = document.querySelector('.add'); const cancelButton = document.querySelector('.fa.fa-times'); const workInput = document.getElementById('work-time'); const breakInput = document.getElementById('break-time'); let currentSessionDiv; const radius = parseInt(progressCircle.getAttribute('r')); const centerPoint = 110; const circumfernce = Math.PI * radius * 2; const warningBeep = new Audio('warningBeep.mp3'); const endBeep = new Audio('endBeep.mp3'); let timer = Timer({ onTick: update, onStart: ready, onEnd: finish, onReset: reset, }); timer.reset(); document.addEventListener('keydown', (evt) => { if (evt.keyCode === 32) { toggleControl(); } }) control.addEventListener('click', toggleControl); addButton.addEventListener('click', openModal); cancelButton.addEventListener('click', closeModal); let inputs = [workInput, breakInput]; inputs.forEach(elm => elm.addEventListener('keydown', () => { if (elm.value.length === 2) { elm.value = ""; } })); workInput.addEventListener('input', (evt) => { if (workInput.value.length === 2) { breakInput.focus(); } }); breakInput.addEventListener('input', (evt) => { if (breakInput.value.length === 2) { modal.focus(); } }); modal.addEventListener('keypress', (evt) => { if (evt.keyCode === 13) { let workMins = parseInt(workInput.value || workInput.placeholder) * 60; let breakMins = parseInt(breakInput.value || breakInput.placeholder) * 60; workInput.value = ""; breakInput.value = ""; addSession(workMins, breakMins); closeModal(); } }); function update(timeLeft, timeTotal) { let timePercentage = timeLeft/timeTotal; if (timeLeft === 0) { endBeep.play(); } else if (timeLeft < 10) { warningBeep.play(); } updatePointer(timePercentage); updateProgress(timePercentage); updateClock(timeLeft); } function updatePointer(percentage) { let angle = 360 * (1 - percentage); let rotateVal = `rotate(${angle} ${centerPoint} ${centerPoint})`; pointer.setAttribute('transform', rotateVal); } function updateProgress(percentage) { let partCircumfernce = circumfernce * percentage; let fill = Math.ceil(partCircumfernce); let blank = Math.floor(circumfernce - partCircumfernce); progressCircle.setAttribute('stroke-dasharray', `${blank}, ${fill}`); } function updateClock(seconds) { let [min, sec] = convertSecondsToString(seconds); clock.innerHTML = `${min}:${sec}`; } function convertSecondsToString(seconds) { let min = parseInt(seconds / 60) + ''; let sec = parseInt(seconds % 60) + ''; return [min, sec].map(elm => elm.length === 1 ? '0' + elm : elm); } function toggleControl() { if (!timer.isActive()) { control.className = 'fa fa-play'; return; } if (control.className === 'fa fa-play') { play(); } else { pause(); } } function play() { control.className = 'fa fa-pause'; timer.play(); } function pause() { control.className = 'fa fa-play'; timer.pause(); } function openModal() { modal.classList.toggle('closed'); modal.focus(); modalOverlay.classList.toggle('closed'); } function closeModal() { modal.classList.toggle('closed'); modalOverlay.classList.toggle('closed'); workInput.value = ""; breakInput.value = ""; } function addSession(workSecs, breakSecs) { let newSession = document.createElement('div'); let xIcon = document.createElement('i'); let sessionId = timer.addSession(workSecs, breakSecs); newSession.setAttribute('class', 'session-circle'); xIcon.setAttribute('class', 'fa fa-times delete'); newSession.sessionId = sessionId; newSession.addEventListener('click', deleteSession); newSession.appendChild(xIcon); session.insertBefore(newSession, addButton); } function deleteSession(evt, sessionType) { let target = evt.currentTarget; let sessionId = target.sessionId; if (!timer.isSessionActive(sessionId) || !target.classList.contains('work')) { target.remove(); } pause(); timer.deleteSession(sessionId); } function ready(sessionId, sessionType) { let sessionDivs = Array.from(document.querySelectorAll('.session-circle')); currentSessionDiv = sessionDivs.find(sessionDiv => { return sessionDiv.sessionId == sessionId; }); currentSessionDiv.classList.add(sessionType); sessionColor(progressCircle, sessionType); sessionColor(pointer, sessionType) } function finish(sessionType) { if (!sessionType) { return; } currentSessionDiv.classList.remove(sessionType); currentSessionDiv.classList.add('done'); if (sessionType === 'break') { currentSessionDiv.removeEventListener('click', deleteSession); currentSessionDiv.childNodes.forEach(child => child.remove()); } updateProgress(1); updatePointer(1); if (!timer.isActive()) { pause(); } } function reset() { pause(); updateProgress(1); updatePointer(1); updateClock(0); } function sessionColor(elm, sessionType) { elm.style.stroke = (sessionType === 'break') ? 'var(--sec-complementary-color)' : ""; } function Timer(options) { let state = {}; let timer = { start() { let session = state.sessions.shift(); let [seconds, sessionType, symbol] = session; state.sessionId = symbol; state.sessionType = sessionType; state.onStart(symbol, sessionType); state.onTick(seconds, seconds); state.total = seconds; state.duration = seconds; }, pause() { timer.clear(); }, play() { timer.clear(); if (!state.duration) { timer.end(); } state.liveTimer = setInterval(timer.tick, 1000); }, tick() { state.duration -= 1; if (state.duration < 0) { timer.end(); return; } if (state.onTick) { state.onTick(state.duration, state.total); } }, end() { state.onEnd(state.sessionType); if (state.sessions.length) { timer.start(); } else { timer.reset(); } }, clear() { clearInterval(state.liveTimer); }, reset() { timer.clear(); let defaultState = { sessions: state.sessions || [], ...options } state = Object.assign({}, defaultState); state.onReset(); }, addSession(workSecs, breakSecs) { let symbol = Symbol(); state.sessions.push([workSecs, 'work', symbol]); state.sessions.push([breakSecs, 'break', symbol]); return symbol; }, deleteSession(symbol) { if (state.sessionId === symbol) { timer.clear(); timer.end(); return; } state.sessions = state.sessions.filter((session) => session[2] !== symbol); }, isActive() { return !!(state.sessions.length || state.sessionId); }, isSessionActive(symbol) { return state.sessionId === symbol; } } return timer; }
25.651408
81
0.654358
579eb7cf7306ce2f1460a5707de13df6729aafea
614
js
JavaScript
src/plugins/recordTypes/conditioncheck/columns.js
ray-lee/cspace-ui-plugin-profile-lhmc.js
85bd919b622685cbc405fcea18d96bf55c9c7b5f
[ "ECL-2.0" ]
null
null
null
src/plugins/recordTypes/conditioncheck/columns.js
ray-lee/cspace-ui-plugin-profile-lhmc.js
85bd919b622685cbc405fcea18d96bf55c9c7b5f
[ "ECL-2.0" ]
1
2019-12-21T06:40:42.000Z
2019-12-21T06:40:42.000Z
src/plugins/recordTypes/conditioncheck/columns.js
ray-lee/cspace-ui-plugin-profile-lhmc.js
85bd919b622685cbc405fcea18d96bf55c9c7b5f
[ "ECL-2.0" ]
1
2019-03-20T05:17:31.000Z
2019-03-20T05:17:31.000Z
import { defineMessages } from 'react-intl'; export default (configContext) => { const { formatRefName, } = configContext.formatHelpers; return { default: { condition: { disabled: true, }, conditionLHMC: { formatValue: formatRefName, messages: defineMessages({ label: { id: 'column.conditioncheck.default.conditionLHMC', defaultMessage: 'Condition', }, }), order: 20, sortBy: 'conditionchecks_lhmc:conditionCheckLHMCGroupList/0/conditionLHMC', width: 450, }, }, }; };
21.928571
83
0.566775
579ed26efe695193255f990a5e239d049d98ef06
1,640
js
JavaScript
js/scripts.js
nasonmangeli/weather-map
a9ef7b053564808145eb327fccc3c8153d1deba9
[ "MIT" ]
null
null
null
js/scripts.js
nasonmangeli/weather-map
a9ef7b053564808145eb327fccc3c8153d1deba9
[ "MIT" ]
null
null
null
js/scripts.js
nasonmangeli/weather-map
a9ef7b053564808145eb327fccc3c8153d1deba9
[ "MIT" ]
null
null
null
// $.ajax({ // method: 'GET', // url: 'http://api.openweathermap.org/data/2.5/weather?q=San%20Francisco&mode=json&units=imperial&APPID=964b618a488e3dd53cdc4192294e9b98', // success: function(weather_data){ // console.log(weather_data) // } // }) // Backend var to_be_run_on_server_response = function(weather_data) { $('#temp').append(weather_data.main.temp); $('#highTemp').append(weather_data.main.temp_max); $('#lowTemp').append(weather_data.main.temp_min); $('#description').append(weather_data.weather[0].description); $('#windspeed').append(weather_data.wind.speed); var sunRise = new Date(weather_data.sys.sunrise * 1000); $('#sunrise').append(sunRise); var sunSet = new Date(weather_data.sys.sunset * 1000); $('#sunset').append(sunSet); } // Frontend $(document).ready(function(){ $('#city1').click(function(event) { event.preventDefault(); $('.clearField').empty(); alert("The data is currently being fetched"); $.get({ url: 'https://api.openweathermap.org/data/2.5/weather?q=Nairobi&mode=json&units=imperial&APPID=964b618a488e3dd53cdc4192294e9b98', success: function(weather_data){ to_be_run_on_server_response(weather_data); } }) }); $('#city2').click(function(event) { event.preventDefault(); $('.clearField').empty(); alert("The data is currently being fetched"); $.get({ url: 'https://api.openweathermap.org/data/2.5/weather?q=Mombasa&mode=json&units=imperial&APPID=964b618a488e3dd53cdc4192294e9b98', success: function(weather_data){ to_be_run_on_server_response(weather_data); } }) }); });
32.8
141
0.677439
579ed8083a53ac4c40c86fce5e24f0f19993c81b
2,072
js
JavaScript
lib/mq/responder.js
ballantyne/livecoin-tcp
e0136078382b44ee99dfaf7c14608d0fdb6b5171
[ "MIT" ]
null
null
null
lib/mq/responder.js
ballantyne/livecoin-tcp
e0136078382b44ee99dfaf7c14608d0fdb6b5171
[ "MIT" ]
null
null
null
lib/mq/responder.js
ballantyne/livecoin-tcp
e0136078382b44ee99dfaf7c14608d0fdb6b5171
[ "MIT" ]
1
2018-02-18T18:35:56.000Z
2018-02-18T18:35:56.000Z
const path = require('path'); const klass = require('klass'); const zmq = require('zeromq'); const _ = require('underscore'); const polo = require('polo'); const EventEmitter = require('events'); const isJSON = require('is-json'); const Serializer = require(path.join(__dirname, 'serializer')); var serializer = new Serializer(); module.exports = klass(function(options) { var self = this; _.extend(this, options); self.events = new EventEmitter(); if (self.port == undefined) { self.port = 12000; } if (self.address == undefined) { self.address = '127.0.0.1'; } var services = polo(); services.put('livecoin-api', self.port); this.connect('stream'); this.socket.on('message', function(data) { self.emit('message', serializer.deserializeBuffer(data.toString())); }); }).methods({ send: function(data) { this.socket.send(this.serialize(data)); }, serialize: function(data) { return serializer.serializeObject(data); }, connect: function(name, register) { var self = this; this.socket = zmq.socket('rep'); if (register) { this.services = this.discovery(); this.services.put(name, self.port); } this.bind(); }, bind: function() { var self = this; this.socket.bind('tcp://'+this.address+':'+this.port, function(err) { if (err) { console.log(err); } else { console.log("Listening on", self.port); } }); process.on('SIGINT', function() { self.socket.close(); }); }, discovery: function() { var services = polo(); services.on('up', function(name, service) { console.log('[up]', name, service.host+':'+service.port); }); services.on('down', function(name, service) { console.log('[down]', name, service.host+':'+service.port); }); return services; }, emit: function(e, d) { this.events.emit(e, d); }, on: function(e, func) { this.events.on(e, func); }, stop: function() { this.socket.unmonitor(); } })
22.769231
73
0.588803
579fa3263214f990aa801dea932148abd16b36cd
841
js
JavaScript
constants/skills.js
jontsai/www.easygoats.com
93d7e53074dd9b5d60c5f17472aca8fb7263c85e
[ "MIT" ]
1
2021-05-31T17:58:58.000Z
2021-05-31T17:58:58.000Z
constants/skills.js
jontsai/www.easygoats.com
93d7e53074dd9b5d60c5f17472aca8fb7263c85e
[ "MIT" ]
null
null
null
constants/skills.js
jontsai/www.easygoats.com
93d7e53074dd9b5d60c5f17472aca8fb7263c85e
[ "MIT" ]
null
null
null
const headers = ['Web and Frontend', 'Backend', 'Server']; const items = [['JavaScript', 'CSS', 'HTML', 'NextJS', 'ReactJS', 'LESS CSS'], ['Python', 'Django', 'Linux', 'BASH and other Unix utilities'], ['MySQL', 'Redis', 'RabbitMQ']]; const links = [['https://www.javascript.com/', 'https://developer.mozilla.org/en-US/docs/Web/CSS', 'https://developer.mozilla.org/en-US/docs/Web/HTML', 'https://nextjs.org/', 'https://reactjs.org/', 'http://lesscss.org/'], ['https://www.python.org/', 'https://www.djangoproject.com/', 'https://www.linux.org/', null], ['https://www.mysql.com/', 'https://redis.io/', 'https://www.rabbitmq.com/']]; const SKILLS = []; for(var i = 0; i < headers.length; i++) { var col = {}; col.header = headers[i]; col.items = items[i]; col.links = links[i]; SKILLS.push(col); } export default SKILLS;
56.066667
396
0.62069
579ff6cd6df11aab5e80fa755b29d09a33991c3f
116
js
JavaScript
NodeJS/05.ViewEngines/server/controllers/wearables-controller.js
emilti/Telerik-Academy-My-Courses
75c3734318ddcaed8fa1aa25c6bcbb4397707fb1
[ "MIT" ]
null
null
null
NodeJS/05.ViewEngines/server/controllers/wearables-controller.js
emilti/Telerik-Academy-My-Courses
75c3734318ddcaed8fa1aa25c6bcbb4397707fb1
[ "MIT" ]
null
null
null
NodeJS/05.ViewEngines/server/controllers/wearables-controller.js
emilti/Telerik-Academy-My-Courses
75c3734318ddcaed8fa1aa25c6bcbb4397707fb1
[ "MIT" ]
null
null
null
module.exports = { getWearables: function (req, res, next) { res.render('wearables/wearables'); } }
19.333333
45
0.603448
57a032d379ceaa6789d2f34df9de2e27ad72fee0
4,086
js
JavaScript
js/gameState.js
psych-play/psych-play.github.io
400cea6e47bc875ec2f5a3b1c7bb899218c642c8
[ "BSD-3-Clause" ]
null
null
null
js/gameState.js
psych-play/psych-play.github.io
400cea6e47bc875ec2f5a3b1c7bb899218c642c8
[ "BSD-3-Clause" ]
null
null
null
js/gameState.js
psych-play/psych-play.github.io
400cea6e47bc875ec2f5a3b1c7bb899218c642c8
[ "BSD-3-Clause" ]
null
null
null
function GameState() { this.turn = -1; this.phase = -1; // -1 - selecting qPack, 0 - answers input, 1 - answers select, 2 - score show this.qPack = null; this.players = {}; this.ordered = []; } GameState.prototype.loadRemote = function (otherGS) { } GameState.prototype.showCurrentScreen = function () { switch (this.phase) { //case -1: //input.showQPackSelScreen(qPacks.questions, this.getAllPlayersByOrder()); //break; case 0: input.showQuestionScreen(this.getQuestion()); break; case 1: input.showSelectionScreen(game.getShuffledAnswers()); break; case 2: input.showScoreScreen(game.player.lastAnswer, game.getShuffledAnswers(), this.getAllPlayersByScore()); break; } } GameState.prototype.refreshCurrentScreen = function () { if (this.phase !== 2) input.refreshWaitForReady(this.getAllPlayersByOrder()); // TODO: clean this up else input.showScoreScreen(game.player.lastAnswer, game.getShuffledAnswers(), this.getAllPlayersByScore()); } GameState.prototype.pickQPack = function (idx) { input.enableReadyButton(); this.qPack = qPacks.questions[idx]; input.setQsPackPick(this.qPack.name); } GameState.prototype.getActivePlayerCount = function () { let count = 0; for (let name in this.players) { if (this.players[name].active) count++; } return count; } GameState.prototype.checkAllReady = function () { for (let i = 0; i < this.ordered.length; i++) { if (!this.players[this.ordered[i].name].ready) return false; } return true; } GameState.prototype.clearAnswers = function () { for (let name in this.players) { this.players[name].lastAnswer = { name:name, text:null, pickedCount:0, pickedBy:[], id:null }; this.players[name].ready = false; } } GameState.prototype.clearAllReady = function () { for (let name in this.players) this.players[name].ready = false; } GameState.prototype.calculateOrder = function () { this.ordered = []; for (let name in this.players) { if (this.players[name].active) this.ordered.push({ name:name, id:this.players[name].id }); } this.ordered.sort(function(a, b) { return a.id - b.id; }); game.saveLastName(this.ordered[this.ordered[0].name === game.player.name ? 1 : 0].name); } GameState.prototype.getAllActivePlayers = function () { let activePlayers = []; for (let i = 0; i < this.ordered.length; i++) activePlayers.push(this.players[this.ordered[i].name]); return activePlayers; } GameState.prototype.getAllPlayersByOrder = function () { let allPlayers = Object.values(this.players); allPlayers.sort(function(a, b) { return a.id - b.id; }); return allPlayers; } GameState.prototype.getAllPlayersByScore = function () { let allPlayers = Object.values(this.players); allPlayers.sort(function(a, b) { return b.score - a.score; }); return allPlayers; } GameState.prototype.removePlayer = function (name) { if (this.checkPlayerExists(name)) { if (this.phase === -1) delete this.players[name]; else { //this.players[name].ready = false; this.players[name].active = false; } } else console.error("Cannot find " + name + " to remove!"); } GameState.prototype.addPlayer = function (player) { if (this.checkPlayerExists(player.name)) { this.players[player.name].active = true; return; } // Adding player during game? if (this.phase !== -1) { player.lastAnswer = { name:player.name, text:null, pickedCount:0, pickedBy:[], id:null }; // TODO: duplicated code } this.players[player.name] = player; } GameState.prototype.checkPlayerExists = function (name) { return name in this.players; } GameState.prototype.getQuestion = function () { let selQ = this.qPack.qs[this.turn % this.qPack.qs.length]; let player = this.ordered[this.turn % this.ordered.length]; return selQ.replace(/_/g, player.name); }
34.05
122
0.646109
57a0f99475f9e833e9103932a9d2eac3c3b413f8
874
js
JavaScript
public/modules/articles/services/articles.client.service.js
mentheosis/truckcenter
fb0b8fb812912487e2f2b6714b254826fa8f7e08
[ "MIT" ]
1
2016-04-21T21:15:40.000Z
2016-04-21T21:15:40.000Z
public/modules/articles/services/articles.client.service.js
mentheosis/truckcenter
fb0b8fb812912487e2f2b6714b254826fa8f7e08
[ "MIT" ]
null
null
null
public/modules/articles/services/articles.client.service.js
mentheosis/truckcenter
fb0b8fb812912487e2f2b6714b254826fa8f7e08
[ "MIT" ]
null
null
null
'use strict'; //Articles service used for communicating with the articles REST endpoints angular.module('articles') .factory('Articles', //the name of the resource Class ['$resource', function($resource) { return $resource('articles/:articleId', { articleId: '@_id', }, { update: { method: 'PUT' }, kismet: { method: 'POST', params: { jsonrpc:'2.0', method:'send_kismet', params:{amt:1}, id:Date.now, } }, list: { method: 'GET', isArray: true, params: { sortBy: '@sortBy' //$scope.sorter } } }); } ]); //Comments service used for communicating with the articles REST endpoints angular.module('articles') .factory('Comments', //the name of the resource Class ['$resource', function($resource) { return $resource('comments/:parentId', { parentId: '@parent', }); } ]);
18.208333
74
0.602975
57a2048a40a567f88e1c0c7d05196b934e2a4d3a
2,532
js
JavaScript
server/app/services/project.service.js
hackforla/tdm-calculator
b6f48ba942daa5225c644adad75e8a3596e6ef6b
[ "MIT" ]
22
2019-08-17T19:18:40.000Z
2022-02-27T14:22:50.000Z
server/app/services/project.service.js
hackforla/tdm-calculator
b6f48ba942daa5225c644adad75e8a3596e6ef6b
[ "MIT" ]
710
2019-07-23T03:54:57.000Z
2022-03-31T17:27:52.000Z
server/app/services/project.service.js
hackforla/tdm-calculator
b6f48ba942daa5225c644adad75e8a3596e6ef6b
[ "MIT" ]
17
2019-07-24T02:15:30.000Z
2022-02-03T06:08:26.000Z
const { pool, poolConnect } = require("./tedious-pool"); const mssql = require("mssql"); const getAll = async loginId => { try { await poolConnect; const request = pool.request(); request.input("LoginId", mssql.Int, loginId); const response = await request.execute("Project_SelectAll"); return response.recordset; } catch (err) { console.log(err); } }; const getById = async (loginId, id) => { try { await poolConnect; const request = pool.request(); request.input("LoginId", mssql.Int, loginId); request.input("Id", mssql.Int, id); const response = await request.execute("Project_SelectById"); if (response.recordset && response.recordset.length > 0) { return response.recordset[0]; } else { return null; } } catch (err) { return Promise.reject(err); } }; const post = async item => { try { await poolConnect; const request = pool.request(); request.input("name", mssql.NVarChar, item.name); // 200 request.input("address", mssql.NVarChar, item.address); // 200 request.input("description", mssql.NVarChar, item.description); // max request.input("formInputs", mssql.NVarChar, item.formInputs); // max request.input("loginId", mssql.Int, item.loginId); request.input("calculationId", mssql.Int, item.calculationId); request.output("id", mssql.Int, null); const response = await request.execute("Project_Insert"); return response.output; } catch (err) { return Promise.reject(err); } }; const put = async item => { try { await poolConnect; const request = pool.request(); request.input("name", mssql.NVarChar, item.name); // 200 request.input("address", mssql.NVarChar, item.address); // 200 request.input("description", mssql.NVarChar, item.description); // max request.input("formInputs", mssql.NVarChar, item.formInputs); // max request.input("loginId", mssql.Int, item.loginId); request.input("calculationId", mssql.Int, item.calculationId); request.input("id", mssql.Int, item.id); await request.execute("Project_Update"); } catch (err) { return Promise.reject(err); } }; const del = async (loginId, id) => { try { await poolConnect; const request = pool.request(); request.input("loginId", mssql.Int, loginId); request.input("id", mssql.Int, id); await request.execute("Project_Delete"); } catch (err) { return Promise.reject(err); } }; module.exports = { getAll, getById, post, put, del };
28.772727
74
0.652844
57a342e7e5fe8284e220e6d70af37943687f2bac
924
js
JavaScript
components/header/styles.js
gustavpursche/verdi-ryanair
4e061557f4289b77b4b4409e5ca06417fbf3277f
[ "MIT" ]
null
null
null
components/header/styles.js
gustavpursche/verdi-ryanair
4e061557f4289b77b4b4409e5ca06417fbf3277f
[ "MIT" ]
4
2021-03-08T23:14:34.000Z
2021-12-09T00:56:50.000Z
components/header/styles.js
zoff-kollektiv/verdi-ryanair
4e061557f4289b77b4b4409e5ca06417fbf3277f
[ "MIT" ]
null
null
null
import css from 'styled-jsx/css'; import { colors, fonts, mq } from '../../tokens'; export default css` header { background-color: ${colors.yellow}; color: ${colors.blue}; display: flex; flex-direction: row; justify-content: center; margin-bottom: 0; margin-top: 0; padding: 1.5rem 1.5rem; } .inner { display: flex; flex-direction: row; flex-wrap: wrap; max-width: 1200px; } .logo { height: 2.25rem; margin-bottom: -0.5rem; margin-right: 1rem; margin-top: -0.5rem; position: relative; top: 0.25rem; width: 2.25rem; } @media ${mq.tablet} { .logo { height: 3.8rem; margin-right: 2rem; width: 3.8rem; } } .name { font-family: ${fonts.novel.family.black}; font-size: 2rem; margin-bottom: 0; margin-top: 0; } @media ${mq.tablet} { .name { font-size: 2.35rem; } } `;
16.8
49
0.557359
57a422aeb0c82f15ab2c60f375a2dfa266ae7b0a
359
js
JavaScript
src/app.js
fmussap/To-Do-List-App
96f3ac3164533c8c59a63a5824c7867ab70b0773
[ "MIT" ]
null
null
null
src/app.js
fmussap/To-Do-List-App
96f3ac3164533c8c59a63a5824c7867ab70b0773
[ "MIT" ]
null
null
null
src/app.js
fmussap/To-Do-List-App
96f3ac3164533c8c59a63a5824c7867ab70b0773
[ "MIT" ]
null
null
null
'use strict' import React from 'react' import Form from 'components/form' import TodosList from 'components/todos-list' import Filter from 'components/filter' const App = ({ todos, handleAddTodo, handleToggleTodo }) => ( <div> <Form /> <TodosList handleToggleTodo={handleToggleTodo} todos={todos} /> <Filter /> </div> ) export default App
19.944444
67
0.70195
57a47e6fe2d81181d4100a3fda852384b01a1ac9
398
js
JavaScript
src/TutorialExamples/Page02Example01.js
trajanmcgill/www.concertjs.com
68e06e387c7f4fcab468dbb82b3ed0d57c2f92c1
[ "MIT" ]
null
null
null
src/TutorialExamples/Page02Example01.js
trajanmcgill/www.concertjs.com
68e06e387c7f4fcab468dbb82b3ed0d57c2f92c1
[ "MIT" ]
188
2019-11-02T02:28:14.000Z
2020-03-10T05:19:11.000Z
src/TutorialExamples/Page02Example01.js
trajanmcgill/www.concertjs.com
68e06e387c7f4fcab468dbb82b3ed0d57c2f92c1
[ "MIT" ]
null
null
null
(function () { "use strict"; let sequence = new Concert.Sequence(); sequence.addTransformations( { target: document.getElementById("HelloDiv"), feature: "height", unit: "px", applicator: Concert.Applicators.Style, keyframes: { times: [0, 2000], values: [0, 24] } }); document.getElementById("GoButton").onclick = function () { sequence.begin(); }; })();
22.111111
82
0.61809
57a5d5a44f64814759c7e721418e5bbed11ce139
1,704
js
JavaScript
main.js
Richieace22/richieace.github.io
75874dfc7d220c3169e7003ebbd48469cc109287
[ "MIT", "Unlicense" ]
null
null
null
main.js
Richieace22/richieace.github.io
75874dfc7d220c3169e7003ebbd48469cc109287
[ "MIT", "Unlicense" ]
null
null
null
main.js
Richieace22/richieace.github.io
75874dfc7d220c3169e7003ebbd48469cc109287
[ "MIT", "Unlicense" ]
null
null
null
// swiper js (testimonial section) const swiper = new Swiper('.swiper', { scrollbar: { el: '.swiper-scrollbar', draggable: true, }, }); const menuBtn = document.querySelector('#menu-btn'); const closeBtn = document.querySelector('#close-btn'); const menu = document.querySelector('nav .container ul'); // SHOW MENU menuBtn.addEventListener('click', () => { menu.style.display = 'block'; menuBtn.style.display = 'none'; closeBtn.style.display = 'inline-block'; }) // HIDE MENU closeBtn.addEventListener('click', () => { menu.style.display = 'none'; menuBtn.style.display = 'inline-block'; closeBtn.style.display = 'none'; }) const navItems = menu.querySelectorAll('li'); // remove active class from clicked nav item const changeActiveItem = () => { navItems.forEach(item => { const link = item.querySelector('a'); link.classList.remove('active'); }) } // Add active class to clicked nav item navItems.forEach(item => { const link = item.querySelector('a'); link.addEventListener('click', () => { changeActiveItem(); link.classList.add('active'); }) }) // show more in about section const readMoreBtn = document.querySelector('.read-more'); const readMoreContent = document.querySelector('.read-more-content'); readMoreBtn.addEventListener('click', () => { readMoreContent.classList.toggle('show-content'); if(readMoreContent.classList.contains('show-content')){ readMoreBtn.textContent = "Show Less"; } else { readMoreBtn.textContent = "Show More"; } }) // add box shadow to nav bar on scroll window.addEventListener('scroll', () => { document.querySelector('nav').classList.toggle('show-box-shadow',window.scrollY > 0) })
26.625
81
0.684859
57a7001a055625dbef265530255d82ed0f8efc90
1,556
js
JavaScript
slashCommands/moderationSlash/warningsSlash.js
FinnyMarigold58/Redworth
58b095478734fa11ac7c558ce4c4ff06ad537823
[ "MIT" ]
3
2021-12-20T07:32:23.000Z
2022-03-26T11:22:34.000Z
slashCommands/moderationSlash/warningsSlash.js
FinnyMarigold58/Sneeky
cbea397fcda6be2427005f1f7ec40d0831caa43c
[ "MIT" ]
null
null
null
slashCommands/moderationSlash/warningsSlash.js
FinnyMarigold58/Sneeky
cbea397fcda6be2427005f1f7ec40d0831caa43c
[ "MIT" ]
null
null
null
const { moderations } = require("../../db.js") const { MessageEmbed } = require("discord.js") module.exports = { command: { name: "warnings", description: "Display warnings", options: [ { type: "USER", name: "user", description: "User to get warnings from", required: false } ], }, run: async (interaction, client) => { let user = interaction.options.getUser("user") || interaction.user let target = interaction.guild.members.resolve(user.id) if (target != interaction.member && !interaction.member.permissions.has("MANAGE_MESSAGES")) return interaction.reply({content: `You do not have permissions to view other's warnings`, ephemeral: true}) let data = await moderations.find({ user: target.id, action: "Warn", guild: interaction.guild.id }) if (!data?.length) return interaction.reply({content: `\`${target.user.username}\` has no warnings.`, ephemeral: true}) const embedDescription = data.map((warn) => { const moderator = interaction.guild.members.resolve(warn.mod) return [ `Id: ${warn.id}`, `Moderator: ${moderator || "Moderator has left"}`, `Reason: ${warn.reason}`, `Date: ${warn.date}`, `-------------------------` ].join("\n") }) const embed = new MessageEmbed() .setTitle(`${target.user.username}'s warnings`) .setDescription(embedDescription.join("\n")) .setColor("RANDOM") interaction.reply({ embeds: [embed], ephemeral: true}) } }
31.755102
204
0.599614
57a78ac95c7c68871187cb27a88dcb2c318c97cb
2,830
js
JavaScript
src/components/LogoIcon.js
brandonjcreek/Gridview-Design-Photography-Website
923ade2ac5ad5942c1d06b222fbf63ba8b69b91b
[ "MIT" ]
null
null
null
src/components/LogoIcon.js
brandonjcreek/Gridview-Design-Photography-Website
923ade2ac5ad5942c1d06b222fbf63ba8b69b91b
[ "MIT" ]
null
null
null
src/components/LogoIcon.js
brandonjcreek/Gridview-Design-Photography-Website
923ade2ac5ad5942c1d06b222fbf63ba8b69b91b
[ "MIT" ]
null
null
null
import React from "react" import styled from "styled-components" import Block from "./Layout/Block" const LogoWrap = styled.div`{ display: flex; flex-flow: column; justify-content: center; align-items: center; margin: 0px 30px; } ` const LogoBound = styled.div` width: 90px; height: 90px; ` const LogoIcon = ()=>( <LogoWrap> <LogoBound> <svg id="Layer_1" viewBox="0 0 108 108"> <defs> <linearGradient id="linear-gradient" x1="75.52" y1="38.13" x2="107.98" y2="69.86" gradientUnits="userSpaceOnUse"> <stop offset="0" stopColor="#3bb7ff" /> <stop offset="1" stopColor="#66b7c7" /> </linearGradient> <linearGradient id="linear-gradient-2" x1="116.98" y1="122.01" x2="-12.51" y2="-14.05" gradientUnits="userSpaceOnUse"> <stop offset="0" stopColor="#808080" /> <stop offset="1" stopColor="#E6E6E6" /> </linearGradient> <linearGradient id="linear-gradient-3" x1="80.12" y1="157.09" x2="-49.37" y2="21.03" xlinkHref="#linear-gradient-2" /> <linearGradient id="linear-gradient-4" x1="118.89" y1="120.19" x2="-10.61" y2="-15.87" xlinkHref="#linear-gradient-2" /> <linearGradient id="linear-gradient-5" x1="155.71" y1="85.14" x2="26.22" y2="-50.92" xlinkHref="#linear-gradient-2" /> <linearGradient id="linear-gradient-6" x1="130.34" y1="96.5" x2=".84" y2="-39.55" xlinkHref="#linear-gradient-2" /> <linearGradient id="linear-gradient-7" x1="91.8" y1="133.18" x2="-37.69" y2="-2.88" xlinkHref="#linear-gradient-2" /> <linearGradient id="linear-gradient-8" x1="111.58" y1="114.35" x2="-17.91" y2="-21.71" xlinkHref="#linear-gradient-2" /> <linearGradient id="linear-gradient-9" x1="92.73" y1="132.29" x2="-36.76" y2="-3.76" xlinkHref="#linear-gradient-2" /> </defs> <title> Gridview-icon </title> <path className="cls-1" d="M75.3 37.6H108v32.6H75.3z" /> <path className="cls-2" d="M5 0h27.7v32.6H0V4.9A4.93 4.93 0 0 1 5 0z" /> <path className="cls-3" d="M0 102.9V75.3h32.7v32.6H5a5 5 0 0 1-5-5z" /> <path className="cls-4" d="M103 107.9H75.3V75.3H108V103a5 5 0 0 1-5 4.9z" /> <path className="cls-5" d="M108 5v27.7H75.3V0H103a5 5 0 0 1 5 5z" /> <path className="cls-6" d="M37.7 0h32.7v32.7H37.7z" /> <path className="cls-7" d="M0 37.6h32.7v32.6H0z" /> <path className="cls-8" d="M37.7 37.6h32.7v32.6H37.7z" /> <path className="cls-9" d="M37.7 75.3h32.7V108H37.7z" /> </svg> </LogoBound> </LogoWrap> ) export default LogoIcon
50.535714
136
0.556184
57a80661eb20704c5278d69f3effb628f1b7454f
457
js
JavaScript
mock/active.js
IGUIZP/element-list
37b7a14ddb97cf4c53e97e9a15c6a81a4602b30c
[ "MIT" ]
null
null
null
mock/active.js
IGUIZP/element-list
37b7a14ddb97cf4c53e97e9a15c6a81a4602b30c
[ "MIT" ]
null
null
null
mock/active.js
IGUIZP/element-list
37b7a14ddb97cf4c53e97e9a15c6a81a4602b30c
[ "MIT" ]
null
null
null
const actives = [] module.exports = [ { url: '/vue-element-admin/active/list', type: 'get', response: () => { console.log(actives) return { code: 20000, data: actives } } }, { url: '/vue-element-admin/active/create', type: 'post', response: (req) => { console.log(req.body) actives.push(req.body) return { code: 20000, data: 'success' } } } ]
16.925926
44
0.483589
57a8824ab47237fd0f3c41805a1e00451747834f
3,294
js
JavaScript
screens/welcome/WelcomeScreen.js
EtsTest-ReactNativeApps/hobee-application
3dbc2f9d798845e3404ec21814fedcbb2b9b20b5
[ "MIT" ]
null
null
null
screens/welcome/WelcomeScreen.js
EtsTest-ReactNativeApps/hobee-application
3dbc2f9d798845e3404ec21814fedcbb2b9b20b5
[ "MIT" ]
null
null
null
screens/welcome/WelcomeScreen.js
EtsTest-ReactNativeApps/hobee-application
3dbc2f9d798845e3404ec21814fedcbb2b9b20b5
[ "MIT" ]
null
null
null
import React from "react"; import { View, Image, AsyncStorage } from "react-native"; import { connect } from 'react-redux'; import { Video } from 'expo-av'; import { Notifications } from 'expo'; import { Button } from 'react-native-elements'; import LottieView from 'lottie-react-native'; import Toast from 'react-native-root-toast'; import { HobeePermissions } from '../../constants/Permissions'; import Styles from "./Styles"; const permissions = new HobeePermissions(); const mapStateToProps = (state, ownProps) => ({ // ... computed data from state and optionally ownProps theme: state.theme, userInfo: state.user.info }); const mapDispatchToProps = { // ... normally is an object full of action creators }; class WelcomeScreen extends React.Component { state = { userToken: '' }; componentDidMount = async () => { await permissions.getNotificationsPermission(); const userToken = await AsyncStorage.getItem('userToken'); this.setState({ userToken }); this._notificationSubscription = Notifications.addListener(this._handleNotification); }; _handleNotification = (notification) => { if (notification.origin === 'received') { if (notification.data.mode === 'hobeeTime') { // When notification is a hobee time Toast.show(notification.data.body, { duration: Toast.durations.LONG, position: Toast.positions.BOTTOM, backgroundColor: this.props.theme.fontTitleColor, shadowColor: this.props.theme.fontColor, textColor: this.props.theme.bgTop, opacity: 1 }); } else if (notification.data.mode === 'message') { // When notification is a chat Toast.show(notification.data.body, { duration: Toast.durations.LONG, position: Toast.positions.BOTTOM, backgroundColor: this.props.theme.fontTitleColor, shadowColor: this.props.theme.fontColor, textColor: this.props.theme.bgTop, opacity: 1 }); } }; }; _onBuffer() { return ( <LottieView loop autoPlay style={{ backgroundColor: this.props.theme.bgBottom }} source={this.state.loaders[Math.floor(Math.random() * this.state.loaders.length)]} /> ); }; _onNavigate() { if (this.state.userToken) { this.props.navigation.navigate('Home'); } else { this.props.navigation.navigate('SignIn'); } }; render() { const backgroundVideo = require('../../assets/welcomeScreen.mp4'); return ( <View style={{ backgroundColor: this.props.theme.bgBottom, ...Styles.root }}> <Video source={backgroundVideo} rate={1.0} volume={1.0} isMuted={true} resizeMode="cover" shouldPlay isLooping style={Styles.video} /> <View style={Styles.imageContainer}> <Image source={require('../../assets/icon.png')} style={Styles.image} /> </View> <View style={Styles.buttonContainer}> <Button onPress={() => this._onNavigate()} raised title='GET STARTED' titleStyle={{ color: this.props.theme.fontTitleColor, fontWeight: 'bold' }} containerStyle={{ marginVertical: 10, marginHorizontal: 20 }} buttonStyle={{ backgroundColor: this.props.theme.primaryColor, borderRadius: 10 }} /> </View> </View> ); } } export default connect( mapStateToProps, mapDispatchToProps )(WelcomeScreen);
25.534884
91
0.670613
57a8824b583470aa21de60da76b2957ca605e27d
316
js
JavaScript
src/util/accountToNEP6.js
XaroRSA/client
6e780100f96703111039f7ef5f95ea66c9ef6b67
[ "MIT" ]
null
null
null
src/util/accountToNEP6.js
XaroRSA/client
6e780100f96703111039f7ef5f95ea66c9ef6b67
[ "MIT" ]
null
null
null
src/util/accountToNEP6.js
XaroRSA/client
6e780100f96703111039f7ef5f95ea66c9ef6b67
[ "MIT" ]
null
null
null
import { wallet } from '@cityofzion/neon-js'; export default function accountToNEP6({ address, key, label = address, isDefault = true }) { const newAccount = new wallet.Account({ address, key, label, isDefault }); const newWallet = new wallet.Wallet({ accounts: [newAccount] }); return newWallet.export(); }
35.111111
92
0.708861
57a9276e4ce6d51bad0530cfdb7379bef840d5c8
7,906
js
JavaScript
src/redux/selectors/files/files.test.js
richardscarrott/snippets
4eaed0001fc0b1111d88dcc4c40ba9d431d2212e
[ "MIT" ]
56
2018-04-27T14:57:50.000Z
2021-11-26T00:24:48.000Z
src/redux/selectors/files/files.test.js
richardscarrott/snippets
4eaed0001fc0b1111d88dcc4c40ba9d431d2212e
[ "MIT" ]
27
2018-04-10T21:27:29.000Z
2018-10-18T09:36:41.000Z
src/redux/selectors/files/files.test.js
richardscarrott/snippets
4eaed0001fc0b1111d88dcc4c40ba9d431d2212e
[ "MIT" ]
6
2018-10-16T13:35:32.000Z
2021-11-11T10:20:06.000Z
import { filePathsSelector } from './files'; const state = { entities: { sources: { 'e9e84e90-52ee-11e8-ac0c-b93e83eaf21a': { url: 'https://github.com/richardscarrott/test-snippets/tree/master/snippets', name: 'Test', accessToken: '35c2725f65e15f48a4becc6c8b3dec39d4029ce1', id: 'e9e84e90-52ee-11e8-ac0c-b93e83eaf21a', content: [ { id: '14302100-52ef-11e8-9986-dd586b391786', schema: 'dirs' }, { id: '14477990-52ef-11e8-9986-dd586b391786', schema: 'files' }, { id: '144e5760-52ef-11e8-9986-dd586b391786', schema: 'files' }, { id: '1450ef70-52ef-11e8-9986-dd586b391786', schema: 'dirs' }, { id: '1452c430-52ef-11e8-9986-dd586b391786', schema: 'files' }, { id: '144f41c0-52ef-11e8-9986-dd586b391786', schema: 'files' }, { id: '144fde00-52ef-11e8-9986-dd586b391786', schema: 'dirs' }, { id: '145f4750-52ef-11e8-9986-dd586b391786', schema: 'dirs' }, { id: '14667340-52ef-11e8-9986-dd586b391786', schema: 'files' }, { id: '146784b0-52ef-11e8-9986-dd586b391786', schema: 'files' } ] }, '166b6b00-52ef-11e8-ac0c-b93e83eaf21a': { name: 'Test (file)', accessToken: '35c2725f65e15f48a4becc6c8b3dec39d4029ce1', url: 'https://github.com/richardscarrott/test-snippets/tree/master/snippets/account/register-autofill.js', id: '166b6b00-52ef-11e8-ac0c-b93e83eaf21a', content: [ { id: '26a0bd90-52ef-11e8-9986-dd586b391786', schema: 'files' } ] } }, dirs: { '14302100-52ef-11e8-9986-dd586b391786': { id: '14302100-52ef-11e8-9986-dd586b391786', name: 'account', content: [ { id: '14670f80-52ef-11e8-9986-dd586b391786', schema: 'files' } ] }, '1450ef70-52ef-11e8-9986-dd586b391786': { id: '1450ef70-52ef-11e8-9986-dd586b391786', name: 'foo', content: [ { id: '1467f9e0-52ef-11e8-9986-dd586b391786', schema: 'files' } ] }, '147f5270-52ef-11e8-9986-dd586b391786': { id: '147f5270-52ef-11e8-9986-dd586b391786', name: 'very-very-nested', content: [ { id: '1495c0a0-52ef-11e8-9986-dd586b391786', schema: 'files' }, { id: '14980a90-52ef-11e8-9986-dd586b391786', schema: 'files' } ] }, '14667341-52ef-11e8-9986-dd586b391786': { id: '14667341-52ef-11e8-9986-dd586b391786', name: 'very-nested', content: [ { id: '147f5270-52ef-11e8-9986-dd586b391786', schema: 'dirs' } ] }, '144fde00-52ef-11e8-9986-dd586b391786': { id: '144fde00-52ef-11e8-9986-dd586b391786', name: 'nested', content: [ { id: '14667341-52ef-11e8-9986-dd586b391786', schema: 'dirs' } ] }, '145f4750-52ef-11e8-9986-dd586b391786': { id: '145f4750-52ef-11e8-9986-dd586b391786', name: 'nojs', content: [ { id: '147e4100-52ef-11e8-9986-dd586b391786', schema: 'files' }, { id: '147fa090-52ef-11e8-9986-dd586b391786', schema: 'files' } ] } }, files: { '14670f80-52ef-11e8-9986-dd586b391786': { id: '14670f80-52ef-11e8-9986-dd586b391786', name: 'register-autofill.js', content: 'Y29uc29sZS5sb2coJ1J1bm5pbmcgcmVnaXN0ZXIgYXV0b2ZpbGwnKTsK\n' }, '14477990-52ef-11e8-9986-dd586b391786': { id: '14477990-52ef-11e8-9986-dd586b391786', name: 'barrel-roll.png', content: '' }, '144e5760-52ef-11e8-9986-dd586b391786': { id: '144e5760-52ef-11e8-9986-dd586b391786', name: 'checkout-autofill.ts', content: 'Y29uc29sZS5sb2coJ1J1bm5pbmcgY2hlY2tvdXQgYXV0b2ZpbGwnKTsKCmNv\nbnN0IHRoaXNTaG91bGROb3RCZUxlYWtlZFRvVGhlR2xvYmFsID0gdHJ1ZTsK\n' }, '1467f9e0-52ef-11e8-9986-dd586b391786': { id: '1467f9e0-52ef-11e8-9986-dd586b391786', name: 'bar.js', content: 'YWxlcnQoJ1J1bm5pbmcgYmFyJyk7Cg==\n' }, '1452c430-52ef-11e8-9986-dd586b391786': { id: '1452c430-52ef-11e8-9986-dd586b391786', name: 'log-query.js', content: 'Y29uc29sZS5sb2coJ0xvZ2dpbmcgcXVlcnknKTsK\n' }, '144f41c0-52ef-11e8-9986-dd586b391786': { id: '144f41c0-52ef-11e8-9986-dd586b391786', name: 'log-store.js', content: 'Y29uc29sZS5sb2coJ0xvZ2dpbmcgc3RvcmUnKTsK\n' }, '1495c0a0-52ef-11e8-9986-dd586b391786': { id: '1495c0a0-52ef-11e8-9986-dd586b391786', name: 'nested.js', content: 'Ly8gbmVzdGVkLmpzCmNvbnNvbGUubG9nKCduZXN0ZWQuanMnKTsK\n' }, '14980a90-52ef-11e8-9986-dd586b391786': { id: '14980a90-52ef-11e8-9986-dd586b391786', name: 'nested.md', content: 'IyBOZXN0ZWQgbWFya2Rvd24K\n' }, '147e4100-52ef-11e8-9986-dd586b391786': { id: '147e4100-52ef-11e8-9986-dd586b391786', name: 'an-image.png', content: '' }, '147fa090-52ef-11e8-9986-dd586b391786': { id: '147fa090-52ef-11e8-9986-dd586b391786', name: 'some-markdown.md', content: '' }, '14667340-52ef-11e8-9986-dd586b391786': { id: '14667340-52ef-11e8-9986-dd586b391786', name: 'search-autofill.js', content: 'Y29uc29sZS5sb2coJ1J1bm5pbmcgc2VhcmNoIGF1dG9maWxsJyk7Cg==\n' }, '146784b0-52ef-11e8-9986-dd586b391786': { id: '146784b0-52ef-11e8-9986-dd586b391786', name: 'source-autofill.js', content: 'dmFyIHNldElucHV0ID0gKGlucHV0LCB2YWx1ZSkgPT4gewogICAgdmFyIG5h\ndGl2ZUlucHV0VmFsdWVTZXR0ZXIgPSBPYmplY3QuZ2V0T3duUHJvcGVydHlE\nZXNjcmlwdG9yKHdpbmRvdy5IVE1MSW5wdXRFbGVtZW50LnByb3RvdHlwZSwg\nInZhbHVlIikuc2V0OwpuYXRpdmVJbnB1dFZhbHVlU2V0dGVyLmNhbGwoaW5w\ndXQsIHZhbHVlKTsKdmFyIGV2MiA9IG5ldyBFdmVudCgnaW5wdXQnLCB7IGJ1\nYmJsZXM6IHRydWV9KTsKaW5wdXQuZGlzcGF0Y2hFdmVudChldjIpOwp9OwoK\nc2V0SW5wdXQoJCgnW25hbWU9Im5hbWUiXScpLCAnVHJhaW5saW5lIFdlYicp\nCnNldElucHV0KCQoJ1tuYW1lPSJhcGkiXScpLCAnaHR0cHM6Ly9hcGkuZ2l0\naHViLmNvbScpCnNldElucHV0KCQoJ1tuYW1lPSJhY2Nlc3NUb2tlbiJdJyks\nICcxMGIxYjRmMDdmNjAyZjljNjE3YzlhNGFkMjQ1ZjQ1NjA1YzAyODIwJykK\nLy9zZXRJbnB1dCgkKCdbbmFtZT0iYWNjZXNzVG9rZW4iXScpLCAnMTBiMWI0\nZjA3ZjYwMmY5YzYxN2M5YTRhZDI0NWY0NTYwNWMwMjgyMEJVRycpCnNldElu\ncHV0KCQoJ1tuYW1lPSJvd25lciJdJyksICdyaWNoYXJkc2NhcnJvdHQnKQpz\nZXRJbnB1dCgkKCdbbmFtZT0icmVwbyJdJyksICd0ZXN0LXNuaXBwZXRzJykK\nc2V0SW5wdXQoJCgnW25hbWU9InBhdGgiXScpLCAnc25pcHBldHMnKQo=\n' }, '26a0bd90-52ef-11e8-9986-dd586b391786': { id: '26a0bd90-52ef-11e8-9986-dd586b391786', name: 'register-autofill.js', content: 'Y29uc29sZS5sb2coJ1J1bm5pbmcgcmVnaXN0ZXIgYXV0b2ZpbGwnKTsK\n' } } }, sources: { meta: { 'e9e84e90-52ee-11e8-ac0c-b93e83eaf21a': { status: 'SUCCESS', receivedAt: 1525804743099 }, '166b6b00-52ef-11e8-ac0c-b93e83eaf21a': { status: 'SUCCESS', receivedAt: 1525804773354 } }, data: [ 'e9e84e90-52ee-11e8-ac0c-b93e83eaf21a', '166b6b00-52ef-11e8-ac0c-b93e83eaf21a' ] } }; describe('filePathsSelector', () => { it('works', () => { expect(filePathsSelector(state)).toMatchSnapshot(); }); });
34.077586
938
0.592588
57a96015125f9c93b53aad8f740e737886e9b4a8
5,084
js
JavaScript
src/scripts/notecontrol.js
dhirajv2000/NoteKeeper
50d8ca36fe18fbf3816e8c5ae514ef288d00dbd4
[ "MIT" ]
null
null
null
src/scripts/notecontrol.js
dhirajv2000/NoteKeeper
50d8ca36fe18fbf3816e8c5ae514ef288d00dbd4
[ "MIT" ]
null
null
null
src/scripts/notecontrol.js
dhirajv2000/NoteKeeper
50d8ca36fe18fbf3816e8c5ae514ef288d00dbd4
[ "MIT" ]
null
null
null
//Manages Operations on notes function NoteControl(noteView) { const self = this; let clickID, noteContent, noteTitle, note, noteArray = [], timer = null; const grid = document.querySelector('.grid') //this.isUnsaved = false; //Adds a new note to local storage this.addNewNote = function () { let note = new CreateNote(generateID()); noteArray = self.getStorage(); noteArray.push(note); self.setStorage(noteArray) self.renderNote(note); } //Displays the note on the page this.renderNote = function (note) { let tempelate = getTemplate(); const wrapper = document.createElement('div'); wrapper.setAttribute('id', note.id); wrapper.setAttribute('class', 'note-wrapper'); wrapper.innerHTML += tempelate; if (note.title) { wrapper.querySelector('.note-title').innerHTML = note.title; } if (note.content) wrapper.querySelector('.note-content').innerHTML = note.content; if (note.font.bold) wrapper.querySelector('.note-content').classList.add('bold') if (note.font.italic) wrapper.querySelector('.note-content').classList.add('italic') if (note.font.underline) wrapper.querySelector('.note-content').classList.add('underline') if (note.font.strike) wrapper.querySelector('.note-content').classList.add('strike') self.appendListeners(wrapper); grid.appendChild(wrapper) } //Updates notes on click of save button this.updateNote = function (id) { clickID = id; const wrapper = document.getElementById(clickID); noteTitle = wrapper.querySelector('.note-title') noteContent = wrapper.querySelector('.note-content') noteArray = self.getStorage(); note = noteArray.find(note => note.id == clickID); note.title = noteTitle.innerHTML; note.content = noteContent.innerHTML; self.setStorage(noteArray) //self.isUnsaved = false; } //Deletes a note and updates local storage this.deleteNote = function () { clickID = self.getButtonId(this); if (!confirm('Are you sure you want to delete? Notes once deleted cannot be undone.')) return; note = noteArray.find(note => note.id == clickID); noteArray.splice(noteArray.findIndex(obj => obj.id === note.id), 1) self.setStorage(noteArray) self.displayAll(); } //Displays all the notes this.displayAll = function () { noteArray = self.getStorage(); grid.innerHTML = ''; noteArray.forEach(note => self.renderNote(note)) } //Saves all notes this.saveAll = function () { noteArray = self.getStorage(); noteArray.forEach(note => self.updateNote(note.id)) } //Clears all the notes and local storage. this.clearNotes = function () { if (!confirm('Are you sure you want to delete? Notes once deleted cannot be undone.')) return; self.clearStorage(); self.displayAll(); } //returns the id of the button whic is clicked this.getButtonId = function (node) { return node.parentNode.parentNode.id; } //Detects changes and updates the note this.detectChange = function () { clearTimeout(timer) let id = this.id timer = setTimeout(function () { self.updateNote(id); }, 3000) } //appends event listeners to a new note object this.appendListeners = function (wrapper) { let boldButton = wrapper.querySelector('.note-btns').querySelector('#bold-btn') boldButton.addEventListener('mousedown', function (e) { e.preventDefault() }) boldButton.addEventListener("click", noteView.changeFont) let italicButton = wrapper.querySelector('.note-btns').querySelector('#italic-btn') italicButton.addEventListener('mousedown', function (e) { e.preventDefault() }) italicButton.addEventListener("click", noteView.changeFont) let underlineButton = wrapper.querySelector('.note-btns').querySelector('#underline-btn') underlineButton.addEventListener('mousedown', function (e) { e.preventDefault() }) underlineButton.addEventListener("click", noteView.changeFont) let strikeButton = wrapper.querySelector('.note-btns').querySelector('#strike-btn') strikeButton.addEventListener('mousedown', function (e) { e.preventDefault() }) strikeButton.addEventListener("click", noteView.changeFont) let deleteButton = wrapper.querySelector('#delete-btn') deleteButton.addEventListener('click', self.deleteNote) wrapper.addEventListener('input', self.detectChange) //wrapper.querySelector('.note-title').addEventListener('focusin', noteView.clearPlaceholder) //wrapper.querySelector('.note-title').addEventListener('focusout', noteView.addPlaceholder) } }
36.314286
102
0.633556
57a97081c0a0c3088c5cfb4db93857e5aa2090ff
74
js
JavaScript
app/helpers/band-scale.js
jdurand/ember-d3-helpers
fa8a21a9ed13ead349fbce7eb87507867a80ff2c
[ "MIT" ]
42
2016-06-28T18:50:49.000Z
2019-04-17T09:08:42.000Z
app/helpers/band-scale.js
jdurand/ember-d3-helpers
fa8a21a9ed13ead349fbce7eb87507867a80ff2c
[ "MIT" ]
34
2016-06-04T00:08:13.000Z
2018-06-25T19:34:14.000Z
app/helpers/band-scale.js
jdurand/ember-d3-helpers
fa8a21a9ed13ead349fbce7eb87507867a80ff2c
[ "MIT" ]
13
2016-07-27T13:10:04.000Z
2020-07-15T14:00:14.000Z
export { default, bandScale } from 'ember-d3-helpers/helpers/band-scale';
37
73
0.756757
57a9871c02423acb0ec1c3835b41d958c000b926
1,885
js
JavaScript
application/frontend/src/components/Footer.js
ktpog/SFStateEats
d59ef75aa193a281e332653accd827bc1da801f9
[ "MIT" ]
null
null
null
application/frontend/src/components/Footer.js
ktpog/SFStateEats
d59ef75aa193a281e332653accd827bc1da801f9
[ "MIT" ]
1
2021-04-06T17:56:09.000Z
2021-04-06T17:56:09.000Z
application/frontend/src/components/Footer.js
ktpog/SFStateEats
d59ef75aa193a281e332653accd827bc1da801f9
[ "MIT" ]
null
null
null
import React from 'react'; import { Container, Dropdown, Row, Button, Card, Carousel, Modal, Col, } from 'react-bootstrap'; import { Link, BrowserRouter as Router, Route } from 'react-router-dom'; import SFstateLogo from '../assets/SFstateLogo.png'; const Footer = () => { const [show, setShow] = React.useState(false); const handleClose = () => setShow(false); const handleShow = (id) => { setShow(true); } return ( <> <div id="footer" className="shadow-sm fixed-bot container-fluid"> <Row> <Col style={{ color: 'white' }}> <h4>Quick Links</h4> <p style={{ align: 'left' }}> <Link>All Restaurants</Link> </p> </Col> <Col style={{ color: 'white' }}> <h4>Contact Us</h4> <p style={{ align: 'left' }}> <Button onClick={handleShow}>Click for info</Button> </p> </Col> <Col> <img className="FooterLogo" src={SFstateLogo}></img> </Col> </Row> </div> <Modal show={show} onHide={handleClose}> <Modal.Header closeButton> <Modal.Title>Contact the devs</Modal.Title> </Modal.Header> <Modal.Body> <h6>Rachit Joshi (Team Lead): rjoshi@mail.sfsu.edu</h6> <h6>Pedro Souto (Backend Lead): Pedro.Souto.SFSU@gmail.com</h6> <h6>John Pham (GitHub Lead): JohnPhamDeveloper@hotmail.com</h6> <h6>Samhita Brigeda (Frontend Lead): pandu.barigeda@gmail.com</h6> <h6>Khang Tran (Frontend Dev): ktran26@mail.sfsu.edu</h6> <h6>Vicent Tran (Database Lead): vtran6@mail.sfsu.edu</h6> </Modal.Body> <Modal.Footer> <Button variant="danger" onClick={handleClose}> Close </Button> </Modal.Footer> </Modal> </> ); }; export default Footer;
25.821918
76
0.552255
57a99755878aa28eb7997f4ae6ae4bc7ae866c4b
14,766
js
JavaScript
pepdb/core/static/js/cytograph_init.js
dchaplinsky/pep.org.ua
8633a65fb657d7f04dbdb12eb8ae705fa6be67e3
[ "MIT" ]
7
2015-12-21T03:52:46.000Z
2020-07-24T19:17:23.000Z
pepdb/core/static/js/cytograph_init.js
dchaplinsky/pep.org.ua
8633a65fb657d7f04dbdb12eb8ae705fa6be67e3
[ "MIT" ]
12
2016-03-05T18:11:05.000Z
2021-06-17T20:20:03.000Z
pepdb/core/static/js/cytograph_init.js
dchaplinsky/pep.org.ua
8633a65fb657d7f04dbdb12eb8ae705fa6be67e3
[ "MIT" ]
4
2016-07-17T20:19:38.000Z
2021-03-23T12:47:20.000Z
$(function() { function get_json_from_url(url) { if (!url) url = location.search; var query = url.substr(1); var result = {}; query.split("&").forEach(function(part) { var item = part.split("="); result[item[0]] = decodeURIComponent(item[1]); }); return result; } function get_edge_description(obj) { var share = obj.data("share"); if (share > 0) { return obj.data("relation") + "\n " + share + "%"; } else { return obj.data("relation") } } var preview_style = [{ selector: "edge", style: { "curve-style": "bezier", "target-arrow-shape": "triangle", width: 0 } }, { selector: "edge[?is_latest]", style: { width: 1 } }, { selector: 'node', style: { "content": "", "font-size": 20, "ghost": "yes", "text-wrap": "wrap", "text-max-width": 100, "text-valign": "bottom", "text-halign": "center", "width": 60, "height": 60, color: "#FAFAFA", "border-width": 1, "border-style": "solid", "border-color": "#B3B3B3" } }, { selector: 'node[model="person"]', style: { "background-image": "/static/images/cytoscape/person.svg?1", "background-fit": "cover", "background-color": "white" } }, { selector: 'node[model="company"]', style: { "background-image": "/static/images/cytoscape/company.svg?1", "background-fit": "cover", "background-color": "white", "shape": "octagon" } }, { selector: 'node.hover', style: { "text-background-color": "#265eb7", "text-background-opacity": 0.8, "text-background-shape": "roundrectangle", "text-background-padding": "3px", "z-index": 100, content: "data(name)" } }, { selector: 'node[?is_pep]', style: { "width": 50, "height": 50, "background-color": "white", "background-image": "/static/images/cytoscape/pep_person.svg?1" } }, { // (4, _("Пов'язана особа")), selector: 'node[type_of_official=4]', style: { "background-image": "/static/images/cytoscape/affiliated_person.svg?1" } }, { // (5, _("Член сім'ї")), selector: 'node[type_of_official=5]', style: { "background-image": "/static/images/cytoscape/relative_person.svg?1" } }, { selector: 'node[?state_company]', style: { "width": 50, "height": 50, "background-color": "white", "background-image": "/static/images/cytoscape/state_company.svg?1" } }, { selector: 'node[model="person"][?is_dead]', style: { "background-image": "/static/images/cytoscape/dead/person.svg?1", } }, { selector: 'node[model="company"][?is_closed]', style: { "background-image": "/static/images/cytoscape/dead/company.svg?1", } }, { selector: 'node[?is_pep][?is_dead]', style: { "background-image": "/static/images/cytoscape/dead/pep_person.svg?1" } }, { // (4, _("Пов'язана особа")), selector: 'node[type_of_official=4][?is_dead]', style: { "background-image": "/static/images/cytoscape/dead/affiliated_person.svg?1" } }, { // (5, _("Член сім'ї")), selector: 'node[type_of_official=5][?is_dead]', style: { "background-image": "/static/images/cytoscape/dead/relative_person.svg?1" } }, { selector: 'node[?state_company][?is_closed]', style: { "background-image": "/static/images/cytoscape/dead/state_company.svg?1" } }, { selector: 'node[?is_main]', style: { "width": 80, "height": 80, "text-background-color": "#265eb7", "text-background-opacity": 0.8, "text-background-shape": "roundrectangle", "text-background-padding": "3px", content: "data(name)", "z-index": 90 } }]; var full_style = preview_style.concat([{ selector: 'node', style: { "content": "data(name)", "color": "#666666", "min-zoomed-font-size": 18, "font-size": 12 } }, { selector: 'node[?is_main]', style: { "width": 80, "height": 80, "color": "#444444", "text-background-color": "white", "text-background-opacity": 0, content: "data(name)", "z-index": 90 } }, { selector: "edge", style: { width: 0 } }, { selector: "edge.hover", style: { label: get_edge_description, "text-wrap": "wrap", "text-max-width": 100, "color": "#666666", "font-size": 14, "min-zoomed-font-size": 10, "text-background-color": "white", "z-index": 140, "text-background-opacity": 0.8, "text-background-shape": "roundrectangle", } }, { selector: "edge.active", style: { label: get_edge_description, "line-color": "red", "font-size": 10, "text-wrap": "wrap", "text-max-width": 80, "color": "#666666", width: "mapData(share, 0, 100, 0.5, 5)" } }, { selector: "edge[?is_latest]", style: { width: "mapData(share, 0, 100, 0.5, 5)" } }, { selector: 'edge[model="person2person"]', style: { "line-style": "dashed" } }]); function init_preview(elements) { var cy_preview = cytoscape({ userPanningEnabled: false, autoungrabify: true, container: $('#cy-preview'), elements: elements, layout: { name: 'cose', quality: 'default' }, style: preview_style }).on('mouseover', 'node', function(event) { event.target.addClass("hover"); }).on('mouseout', 'node', function(event) { event.target.removeClass("hover"); }); } var makeTippy = function(node, text, theme, placement) { return tippy(node.popperRef(), { content: function() { var div = document.createElement('div'); div.innerHTML = text; return div; }, trigger: 'manual', arrow: false, placement: placement, hideOnClick: false, multiple: true, distance: 0, interactive: true, animateFill: false, theme: theme, sticky: true }); }; function init_full(elements, layout) { var cy_full = cytoscape({ container: $('.cy-full'), elements: elements, style: full_style }), min_zoom = 0.01, edge_length = Math.max(50, 3 * elements["nodes"].length), partial_layout_options = { name: layout, animate: "end", fit: true, padding: 10, initialTemp: 100, animationDuration: 1500, nodeOverlap: 6, maxIterations: 3000, idealEdgeLength: edge_length, nodeDimensionsIncludeLabels: true, springLength: edge_length * 3, gravity: -15, theta: 1, stop: function() { cy_full.resize(); min_zoom = Math.max(0.01, cy_full.zoom() * 0.5); } }, layout_options = { name: layout, animationDuration: 1500, animate: "end", springLength: edge_length * 3, gravity: -15, theta: 1, maxIterations: 3000, padding: 10, theta: 1, dragCoeff: 0.01, pull: 0.0001, nodeOverlap: 6, initialTemp: 2500, numIter: 2500, idealEdgeLength: edge_length, nodeDimensionsIncludeLabels: true, stop: function() { min_zoom = Math.max(0.01, cy_full.zoom() * 0.5); } }, layout = cy_full.layout(layout_options), previousTapStamp; cy_full.fit(); layout.run(); cy_full.on('doubleTap', 'node', function(tap_event, event) { var tippyA = event.target.data("tippy"); if (tippyA) { tippyA.hide(); event.target.data("tippy", null); } event.target.addClass("active"); if (typeof(event.target.data("expanded")) == "undefined") { $.getJSON(event.target.data("details"), function(new_elements) { var root_position = cy_full.$("node[?is_main]").renderedPosition(), pos = event.target.renderedPosition(), misplaced_pos = { x: pos.x + (pos.x - root_position.x) * 0.5, y: pos.y + (pos.y - root_position.y) * 0.5 }; event.target.data("expanded", true); for (var i = new_elements["nodes"].length - 1; i >= 0; i--) { new_elements["nodes"][i]["data"]["parent_entity"] = event.target.id(); } var eles = cy_full.add(new_elements); if (eles.length > 0) { eles.renderedPosition(misplaced_pos); layout.stop(); layout = cy_full.layout(partial_layout_options); layout.run(); } }); } }).on('mouseover', 'node', function(event) { var outbound = cy_full.$('edge[source="' + event.target.id() + '"]'), inbound = cy_full.$('edge[target="' + event.target.id() + '"]'), connections = event.target.data("all_connected") || [], neighbours = [], connections_to_open = 0; inbound.addClass("active"); outbound.addClass("active"); inbound.forEach(function(edge) { neighbours.push(edge.data("source")); }); outbound.forEach(function(edge) { neighbours.push(edge.data("target")); }); for (var i = connections.length - 1; i >= 0; i--) { if (neighbours.indexOf(connections[i]) == -1) { connections_to_open += 1; } } var tippyA = makeTippy(event.target, connections_to_open, "pep", "top"); tippyA.show(); event.target.data("tippy", tippyA); }).on('mouseout', 'node', function(event) { cy_full.$('edge[source="' + event.target.id() + '"], edge[target="' + event.target.id() + '"]').removeClass("active"); var tippyA = event.target.data("tippy"); if (tippyA) { tippyA.hide(); event.target.data("tippy", null); } }).on('mouseover', 'edge', function(event) { event.target.addClass("hover"); }).on('mouseout', 'edge', function(event) { event.target.removeClass("hover"); }).on('tap', function(e) { var currentTapStamp = e.timeStamp; var msFromLastTap = currentTapStamp - previousTapStamp; if (msFromLastTap < 250) { e.target.trigger('doubleTap', e); var tippyPopoverToRemove = e.target.data("tippy_popover"); if (tippyPopoverToRemove) { tippyPopoverToRemove.hide(); e.target.data("tippy_popover", null); } } else { cy_full.$(".has_popover").forEach(function(node) { var tippyPopoverToRemove = node.data("tippy_popover"); if (tippyPopoverToRemove) { tippyPopoverToRemove.hide(); node.data("tippy_popover", null); } }); if (e.target.isNode()) { var tippyPopover = makeTippy(e.target, '<a href="' + e.target.data("url") + '" target="_blank">' + e.target.data("full_name") + '</a><br />' + e.target.data("kind") + "<br/>" + e.target.data("description"), "light", "right"); tippyPopover.show(); e.target.addClass("has_popover"); e.target.data("tippy_popover", tippyPopover); } } previousTapStamp = currentTapStamp; }); // visualization zoom $('.zoom-in, .zoom-out').on('click', function () { var root_position = cy_full.$("node[?is_main]").renderedPosition(), current_zoom = cy_full.zoom(), el = $(this); if (el.hasClass("zoom-out")) { current_zoom = Math.max(min_zoom, current_zoom - 0.3) } else { current_zoom = Math.min(10, current_zoom + 0.3) } cy_full.zoom({ level: current_zoom, renderedPosition: root_position, }); }); } $(".visualization-btn").on("click", function(e) { e.preventDefault(); var anchor = $(this).data("target"); $("#visualization-modal").addClass("modal--open"); $.getJSON($(this).closest("button").data("url"), function(elements) { // document.location.search.indexOf("euler") != -1 ? 'cise' : "dagre" var parsed_url = get_json_from_url(), layout = "cose"; if ("layout" in parsed_url) { layout = parsed_url["layout"]; } init_full(elements, layout); }); }); });
35.157143
245
0.458283
57aa7264880b8bdfdb5bcdec130d0342e3e57b66
297
js
JavaScript
4.node/school.js
webfrontup/mini-node
01e348eda646a448453235cc4457cae979360d35
[ "MIT" ]
null
null
null
4.node/school.js
webfrontup/mini-node
01e348eda646a448453235cc4457cae979360d35
[ "MIT" ]
null
null
null
4.node/school.js
webfrontup/mini-node
01e348eda646a448453235cc4457cae979360d35
[ "MIT" ]
null
null
null
module.exports = 'yyccQQu' // require方法 传入了一个路径 // Module有一个_load // 会解析一个绝对路径 // 模块有缓存,如果缓存有 直接取缓存的 // id 模块的标识 // 每个模块里还有一个exports对象 (function (exports, require, module, __filename, __dirname) { module.exports = 'yyccQQu' }) //runInThisContext 将这个方法运行,并且在一个没有作用域的环境下执行
15.631579
62
0.693603
57aa9eb76aa4d4c6709c1cdb33627c6f2c1c43c1
177
js
JavaScript
lib/private/toPartials.js
nspragg/asyncify
791bbd8e88e287c958047a15bf94c8088bd5974e
[ "Apache-2.0" ]
null
null
null
lib/private/toPartials.js
nspragg/asyncify
791bbd8e88e287c958047a15bf94c8088bd5974e
[ "Apache-2.0" ]
null
null
null
lib/private/toPartials.js
nspragg/asyncify
791bbd8e88e287c958047a15bf94c8088bd5974e
[ "Apache-2.0" ]
null
null
null
'use strict'; const _ = require('lodash'); function toPartials(iterable, asyncfn) { return iterable.map((item) => _.partial(asyncfn, item)); } module.exports = toPartials;
17.7
58
0.700565
57ab5692191fc2f2c83ec9d494c5b16e235328dc
985
js
JavaScript
app/modules/common/filesUpload/draggable.js
theseushu/funong-web
420d4c0b6d44644d830d9082b9171fa2d5fef6be
[ "MIT" ]
1
2016-12-03T03:50:45.000Z
2016-12-03T03:50:45.000Z
app/modules/common/filesUpload/draggable.js
theseushu/funong-web
420d4c0b6d44644d830d9082b9171fa2d5fef6be
[ "MIT" ]
null
null
null
app/modules/common/filesUpload/draggable.js
theseushu/funong-web
420d4c0b6d44644d830d9082b9171fa2d5fef6be
[ "MIT" ]
null
null
null
import React, { Component, PropTypes } from 'react'; import { DragSource } from 'react-dnd'; import styles from '../styles'; class Draggable extends Component { static propTypes = { connectDragSource: PropTypes.func.isRequired, isDragging: PropTypes.bool.isRequired, children: PropTypes.any, } render() { const { connectDragSource, isDragging } = this.props; return ( connectDragSource( <div className={`${styles.contentCenter} mdl-animation--default`} style={{ transitionProperty: 'all', transitionDuration: '500ms', opacity: isDragging ? 0.8 : undefined }} > {this.props.children} </div> ) ); } } const source = { beginDrag({ index }) { return { index }; }, }; function collectSource(connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), }; } export default DragSource('FILE', source, collectSource)(Draggable);
25.25641
115
0.645685
57acfc5d2c72a6aa2103487b6501bd68faf6f6c3
22,306
js
JavaScript
node_modules/@plasmicapp/cli/dist/actions/init.js
plasmicapp/plasmic-action
82a70c66b63dcaa943e59f93486a9cf99a94d200
[ "MIT" ]
1
2022-02-23T03:10:14.000Z
2022-02-23T03:10:14.000Z
node_modules/@plasmicapp/cli/dist/actions/init.js
plasmicapp/plasmic-action
82a70c66b63dcaa943e59f93486a9cf99a94d200
[ "MIT" ]
1
2021-11-29T21:39:43.000Z
2021-12-03T18:32:32.000Z
node_modules/@plasmicapp/cli/dist/actions/init.js
plasmicapp/plasmic-action
82a70c66b63dcaa943e59f93486a9cf99a94d200
[ "MIT" ]
2
2021-04-14T21:34:57.000Z
2021-12-03T18:25:18.000Z
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 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) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getYargsOption = exports.getInitArgsChoices = exports.getInitArgsQuestion = exports.getInitArgsLongDescription = exports.getInitArgsShortDescription = exports.initPlasmic = void 0; const chalk_1 = __importDefault(require("chalk")); const inquirer_1 = __importDefault(require("inquirer")); const lodash_1 = __importDefault(require("lodash")); const upath_1 = __importDefault(require("upath")); const deps_1 = require("../deps"); const auth_utils_1 = require("../utils/auth-utils"); const config_utils_1 = require("../utils/config-utils"); const envdetect_1 = require("../utils/envdetect"); const file_utils_1 = require("../utils/file-utils"); const lang_utils_1 = require("../utils/lang-utils"); const npm_utils_1 = require("../utils/npm-utils"); const user_utils_1 = require("../utils/user-utils"); function initPlasmic(opts) { return __awaiter(this, void 0, void 0, function* () { if (!opts.baseDir) opts.baseDir = process.cwd(); yield auth_utils_1.getOrStartAuth(opts); const configFile = opts.config || config_utils_1.findConfigFile(opts.baseDir, { traverseParents: false }); if (configFile && file_utils_1.existsBuffered(configFile)) { deps_1.logger.error("You already have a plasmic.json file! Please either delete or edit it directly."); return; } // path to plasmic.json const newConfigFile = opts.config || upath_1.default.join(opts.baseDir, config_utils_1.CONFIG_FILE_NAME); const answers = yield deriveInitAnswers(opts); yield config_utils_1.writeConfig(newConfigFile, createInitConfig(answers), opts.baseDir); if (!process.env.QUIET) { deps_1.logger.info("Successfully created plasmic.json.\n"); } const answer = yield user_utils_1.confirmWithUser("@plasmicapp/react-web is a small runtime required by Plasmic-generated code.\n Do you want to add it now?", opts.yes); if (answer) { npm_utils_1.installUpgrade("@plasmicapp/react-web", opts.baseDir); } }); } exports.initPlasmic = initPlasmic; function createInitConfig(opts) { return config_utils_1.fillDefaults(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ srcDir: opts.srcDir, defaultPlasmicDir: opts.plasmicDir }, (opts.platform === "nextjs" && { nextjsConfig: { pagesDir: opts.pagesDir, }, })), (opts.platform === "gatsby" && { gatsbyConfig: { pagesDir: opts.pagesDir, }, })), { code: Object.assign(Object.assign(Object.assign({}, (opts.codeLang && { lang: opts.codeLang })), (opts.codeScheme && { scheme: opts.codeScheme })), (opts.reactRuntime && { reactRuntime: opts.reactRuntime })), style: Object.assign({}, (opts.styleScheme && { scheme: opts.styleScheme })), images: Object.assign(Object.assign(Object.assign({}, (opts.imagesScheme && { scheme: opts.imagesScheme })), (opts.imagesScheme && { publicDir: opts.imagesPublicDir })), (opts.imagesScheme && { publicUrlPrefix: opts.imagesPublicUrlPrefix })) }), (opts.platform && { platform: opts.platform })), { cliVersion: npm_utils_1.getCliVersion() })); } /** * Pretty-print the question along with the default answer, as if that was the choice * being made. Don't actually interactively prompt for a response. */ function simulatePrompt(question, defaultAnswer, bold = false) { var _a, _b, _c; const message = question.message.endsWith(">") ? question.message : question.message + ">"; process.stdout.write((bold ? chalk_1.default.bold(message) : message) + " "); deps_1.logger.info(chalk_1.default.cyan((_c = (_b = (_a = question.choices) === null || _a === void 0 ? void 0 : _a.call(question).find((choice) => choice.value === defaultAnswer)) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : defaultAnswer)); } function deriveInitAnswers(opts) { return __awaiter(this, void 0, void 0, function* () { const plasmicRootDir = opts.config ? upath_1.default.dirname(opts.config) : opts.baseDir; const platform = !!opts.platform ? opts.platform : envdetect_1.detectNextJs() ? "nextjs" : envdetect_1.detectGatsby() ? "gatsby" : "react"; const isCra = envdetect_1.detectCreateReactApp(); const isNext = platform === "nextjs"; const isGatsby = platform === "gatsby"; const isGeneric = !isCra && !isNext && !isGatsby; const isTypescript = envdetect_1.detectTypescript(); if (isNext) { deps_1.logger.info("Detected Next.js..."); } else if (isGatsby) { deps_1.logger.info("Detected Gatsby..."); } else if (isCra) { deps_1.logger.info("Detected create-react-app..."); } // Platform-specific defaults that take precedent const deriver = isNext ? getNextDefaults(plasmicRootDir) : isGatsby ? getGatsbyDefaults(plasmicRootDir) : isCra ? getCraDefaults(plasmicRootDir) : getGenericDefaults(plasmicRootDir); const srcDir = lang_utils_1.ensureString(deriver.srcDir); const getDefaultAnswer = (name, defaultAnswer) => { // Try to get the user CLI arg override first if (opts[name]) { return opts[name]; } else if (deriver[name]) { // Then get the platform-specific default if (lodash_1.default.isFunction(deriver[name])) { const fn = deriver[name]; return fn(srcDir); } return deriver[name]; } else { // Other specified default return defaultAnswer; } }; // Start with a complete set of defaults. Some of these are not worth displaying. const answers = { host: getDefaultAnswer("host", ""), platform, codeLang: getDefaultAnswer("codeLang", isTypescript ? "ts" : "js"), codeScheme: getDefaultAnswer("codeScheme", config_utils_1.DEFAULT_CONFIG.code.scheme), styleScheme: getDefaultAnswer("styleScheme", config_utils_1.DEFAULT_CONFIG.style.scheme), imagesScheme: getDefaultAnswer("imagesScheme", config_utils_1.DEFAULT_CONFIG.images.scheme), imagesPublicDir: getDefaultAnswer("imagesPublicDir", lang_utils_1.ensure(config_utils_1.DEFAULT_PUBLIC_FILES_CONFIG.publicDir)), imagesPublicUrlPrefix: getDefaultAnswer("imagesPublicUrlPrefix", lang_utils_1.ensure(config_utils_1.DEFAULT_PUBLIC_FILES_CONFIG.publicUrlPrefix)), srcDir: getDefaultAnswer("srcDir", config_utils_1.DEFAULT_CONFIG.srcDir), plasmicDir: getDefaultAnswer("plasmicDir", config_utils_1.DEFAULT_CONFIG.defaultPlasmicDir), pagesDir: getDefaultAnswer("pagesDir", undefined), reactRuntime: getDefaultAnswer("reactRuntime", "classic"), }; const prominentAnswers = lodash_1.default.omit(answers, "codeScheme"); if (process.env.QUIET) { return answers; } deps_1.logger.info(chalk_1.default.bold("Plasmic Express Setup -- Here are the default settings we recommend:\n")); yield performAsks(true); // Allow a user to short-circuit const useExpressQuestion = { name: "continue", message: `Would you like to accept these defaults?`, type: "list", choices: () => [ { value: "yes", name: "Accept these defaults", }, { value: "no", name: "Customize the choices", }, ], }; deps_1.logger.info(""); if (opts.yes) { simulatePrompt(useExpressQuestion, "yes", true); return answers; } else { const useExpress = yield inquirer_1.default.prompt([useExpressQuestion]); if (useExpress.continue === "yes") { return answers; } } /** * @param express When true, we pretty-print the question along with the default answer, as if that was the choice * being made. This is for displaying the default choices in the express setup. */ function performAsks(express) { return __awaiter(this, void 0, void 0, function* () { // Proceed with platform-specific prompts function maybePrompt(question) { return __awaiter(this, void 0, void 0, function* () { const name = lang_utils_1.ensure(question.name); const message = lang_utils_1.ensure(question.message); if (opts[name]) { deps_1.logger.info(message + answers[name] + "(specified in CLI arg)"); } else if (express) { const defaultAnswer = answers[name]; simulatePrompt(question, defaultAnswer); } else if (!opts.yes && !deriver.alwaysDerived.includes(name)) { const ans = yield inquirer_1.default.prompt(Object.assign(Object.assign({}, question), { default: answers[name] })); // Not sure why TS complains here without this cast. answers[name] = ans[name]; } // Other questions are silently skipped }); } yield maybePrompt({ name: "srcDir", message: `${getInitArgsQuestion("srcDir")}\n>`, }); yield maybePrompt({ name: "plasmicDir", message: `${getInitArgsQuestion("plasmicDir")} (This is relative to "${answers.srcDir}")\n>`, }); if (config_utils_1.isPageAwarePlatform(platform)) { yield maybePrompt({ name: "pagesDir", message: `${getInitArgsQuestion("pagesDir")} (This is relative to "${answers.srcDir}")\n>`, }); } yield maybePrompt({ name: "codeLang", message: `${getInitArgsQuestion("codeLang")}\n`, type: "list", choices: () => [ { name: `Typescript${isTypescript ? " (tsconfig.json detected)" : ""}`, value: "ts", }, { name: `Javascript${!isTypescript ? " (no tsconfig.json detected)" : ""}`, value: "js", }, ], }); yield maybePrompt({ name: "styleScheme", message: `${getInitArgsQuestion("styleScheme")}\n`, type: "list", choices: () => [ { name: `CSS modules, imported as "import sty from './plasmic.module.css'"`, value: "css-modules", }, { name: `Plain CSS stylesheets, imported as "import './plasmic.css'"`, value: "css", }, ], }); yield maybePrompt({ name: "imagesScheme", message: `${getInitArgsQuestion("imagesScheme")}\n`, type: "list", choices: () => [ { name: `Imported as files, like "import img from './image.png'". ${isGeneric ? "Not all bundlers support this." : ""}`, value: "files", }, { name: `Images stored in a public folder, referenced like <img src="/static/image.png"/>`, value: "public-files", }, { name: `Inlined as base64-encoded data URIs`, value: "inlined", }, ], }); if (answers.imagesScheme === "public-files") { yield maybePrompt({ name: "imagesPublicDir", message: `${getInitArgsQuestion("imagesPublicDir")} (This is relative to "${answers.srcDir}")\n>`, }); yield maybePrompt({ name: "imagesPublicUrlPrefix", message: `${getInitArgsQuestion("imagesPublicUrlPrefix")} ${isNext ? `(for Next.js, this is usually "/")` : ""}\n>`, }); } }); } yield performAsks(false); return answers; }); } function getNextDefaults(plasmicRootDir) { var _a; const projectRootDir = (_a = npm_utils_1.findPackageJsonDir(plasmicRootDir)) !== null && _a !== void 0 ? _a : plasmicRootDir; return { srcDir: upath_1.default.relative(plasmicRootDir, upath_1.default.join(projectRootDir, "components")), pagesDir: (srcDir) => upath_1.default.relative(upath_1.default.join(plasmicRootDir, srcDir), upath_1.default.join(projectRootDir, "pages")), styleScheme: "css-modules", imagesScheme: "public-files", imagesPublicDir: (srcDir) => upath_1.default.relative(upath_1.default.join(plasmicRootDir, srcDir), upath_1.default.join(projectRootDir, "public")), imagesPublicUrlPrefix: "/", alwaysDerived: [ "styleScheme", "imagesScheme", "imagesPublicDir", "pagesDir", ], }; } function getGatsbyDefaults(plasmicRootDir) { var _a; const projectRootDir = (_a = npm_utils_1.findPackageJsonDir(plasmicRootDir)) !== null && _a !== void 0 ? _a : plasmicRootDir; return { srcDir: upath_1.default.relative(plasmicRootDir, upath_1.default.join(projectRootDir, "src", "components")), pagesDir: (srcDir) => { const absSrcDir = upath_1.default.join(plasmicRootDir, srcDir); const absPagesDir = upath_1.default.join(projectRootDir, "src", "pages"); const relDir = upath_1.default.relative(absSrcDir, absPagesDir); return relDir; }, styleScheme: "css-modules", imagesScheme: "files", imagesPublicDir: (srcDir) => upath_1.default.relative(upath_1.default.join(plasmicRootDir, srcDir), upath_1.default.join(projectRootDir, "static")), imagesPublicUrlPrefix: "/", alwaysDerived: ["imagesScheme", "pagesDir"], }; } function getCraDefaults(plasmicRootDir) { var _a; const projectRootDir = (_a = npm_utils_1.findPackageJsonDir(plasmicRootDir)) !== null && _a !== void 0 ? _a : plasmicRootDir; return { srcDir: upath_1.default.relative(plasmicRootDir, upath_1.default.join(projectRootDir, "src", "components")), styleScheme: "css-modules", imagesScheme: "files", imagesPublicDir: (srcDir) => upath_1.default.relative(upath_1.default.join(plasmicRootDir, srcDir), upath_1.default.join(projectRootDir, "public")), alwaysDerived: [], }; } function getGenericDefaults(plasmicRootDir) { var _a; const projectRootDir = (_a = npm_utils_1.findPackageJsonDir(plasmicRootDir)) !== null && _a !== void 0 ? _a : plasmicRootDir; const srcDir = file_utils_1.existsBuffered(upath_1.default.join(projectRootDir, "src")) ? upath_1.default.join(projectRootDir, "src", "components") : upath_1.default.join(projectRootDir, "components"); return { srcDir: upath_1.default.relative(plasmicRootDir, srcDir), alwaysDerived: [], }; } /** * Consolidating where we are specifying the descriptions of InitArgs */ const INIT_ARGS_DESCRIPTION = { host: { shortDescription: "Plasmic host to use", }, platform: { shortDescription: "Target platform", longDescription: "Target platform to generate code for", choices: ["react", "nextjs", "gatsby"], }, codeLang: { shortDescription: "Target language", longDescription: "Target language to generate code for", question: `What target language should Plasmic generate code in?`, choices: ["js", "ts"], }, codeScheme: { shortDescription: "Code generation scheme", longDescription: "Code generation scheme to use", choices: ["blackbox", "direct"], }, styleScheme: { shortDescription: "Styling framework", longDescription: "Styling framework to use", question: "How should we generate css for Plasmic components?", choices: ["css", "css-modules"], }, imagesScheme: { shortDescription: "Image scheme", longDescription: "How to reference used image files", question: "How should we reference image files used in Plasmic components?", choices: ["inlined", "files", "public-files"], }, imagesPublicDir: { shortDescription: "Directory of public static files", longDescription: "Default directory to put public static files", question: "What directory should static image files be put into?", }, imagesPublicUrlPrefix: { shortDescription: "URL prefix for static files", longDescription: "URL prefix from which the app will serve static files", question: "What's the URL prefix from which the app will serve static files?", }, srcDir: { shortDescription: "Source directory", longDescription: "Default directory to put React component files (that you edit) into", question: "What directory should React component files (that you edit) be put into?", }, plasmicDir: { shortDescription: "Plasmic-managed directory", longDescription: "Default directory to put Plasmic-managed files into; relative to src-dir", question: "What directory should Plasmic-managed files (that you should not edit) be put into?", }, pagesDir: { shortDescription: "Pages directory", longDescription: "Default directory to put page files (that you edit) into", question: "What directory should pages be put into?", }, }; /** * Get the short description, which exists for all args * @param key * @returns */ function getInitArgsShortDescription(key) { var _a; return (_a = INIT_ARGS_DESCRIPTION[key]) === null || _a === void 0 ? void 0 : _a.shortDescription; } exports.getInitArgsShortDescription = getInitArgsShortDescription; /** * Try to get a long description, falling back to the short description * @param key * @returns */ function getInitArgsLongDescription(key) { var _a, _b, _c; return ((_b = (_a = INIT_ARGS_DESCRIPTION[key]) === null || _a === void 0 ? void 0 : _a.longDescription) !== null && _b !== void 0 ? _b : (_c = INIT_ARGS_DESCRIPTION[key]) === null || _c === void 0 ? void 0 : _c.shortDescription); } exports.getInitArgsLongDescription = getInitArgsLongDescription; /** * Try to get a question form, falling back to the description * @param key * @returns */ function getInitArgsQuestion(key) { var _a, _b, _c, _d, _e; return ((_d = (_b = (_a = INIT_ARGS_DESCRIPTION[key]) === null || _a === void 0 ? void 0 : _a.question) !== null && _b !== void 0 ? _b : (_c = INIT_ARGS_DESCRIPTION[key]) === null || _c === void 0 ? void 0 : _c.longDescription) !== null && _d !== void 0 ? _d : (_e = INIT_ARGS_DESCRIPTION[key]) === null || _e === void 0 ? void 0 : _e.shortDescription); } exports.getInitArgsQuestion = getInitArgsQuestion; /** * Get the possible choices for an arg * @param key * @returns */ function getInitArgsChoices(key) { var _a; return (_a = INIT_ARGS_DESCRIPTION[key]) === null || _a === void 0 ? void 0 : _a.choices; } exports.getInitArgsChoices = getInitArgsChoices; /** * Get a `opt` object for use with the `yargs` library. * If no choices are specified, assume it's freeform string input * All options use "" as the default, unless overridden * @param key * @param defaultOverride * @returns */ function getYargsOption(key, defaultOverride) { const arg = lang_utils_1.ensure(INIT_ARGS_DESCRIPTION[key]); return !arg.choices ? { describe: lang_utils_1.ensure(getInitArgsLongDescription(key)), string: true, default: defaultOverride !== null && defaultOverride !== void 0 ? defaultOverride : "", } : { describe: lang_utils_1.ensure(getInitArgsLongDescription(key)), choices: ["", ...lang_utils_1.ensure(getInitArgsChoices(key))], default: defaultOverride !== null && defaultOverride !== void 0 ? defaultOverride : "", }; } exports.getYargsOption = getYargsOption;
48.386117
639
0.583296
57ad9f41d71aac587aa5a191c15b996f2400dffc
380
js
JavaScript
packages/embedded-media/src/utils/get-tag-matches.js
solocommand/base-cms
af6b79dd35b8aaa826f225f8554c65e439db40dd
[ "MIT" ]
8
2018-11-14T23:04:43.000Z
2021-06-25T14:47:34.000Z
packages/embedded-media/src/utils/get-tag-matches.js
solocommand/base-cms
af6b79dd35b8aaa826f225f8554c65e439db40dd
[ "MIT" ]
104
2021-01-08T04:35:31.000Z
2022-03-31T22:17:24.000Z
packages/embedded-media/src/utils/get-tag-matches.js
solocommand/base-cms
af6b79dd35b8aaa826f225f8554c65e439db40dd
[ "MIT" ]
13
2018-11-09T20:09:18.000Z
2020-11-03T20:51:29.000Z
const pattern = require('./tag-match-pattern'); /** * @param {string} html The HTML to extract embedded tags from. * @returns {string[]} An array of matched embedded tag strings. */ module.exports = (html) => { const matches = []; let match; do { match = pattern.exec(html); if (match && match[0]) matches.push(match[0]); } while (match); return matches; };
23.75
64
0.631579
57adf2351c58fffafc1ade05b38a5ff566edb388
641
js
JavaScript
my_env/lib/python3.8/site-packages/star_ratings/static/star-ratings/js/src/utils.js
David5627/AWWARD
a22a2b2f7d7d6377435bfd475e82268e4e907141
[ "MIT" ]
296
2015-09-07T16:04:01.000Z
2022-03-27T06:31:43.000Z
my_env/lib/python3.8/site-packages/star_ratings/static/star-ratings/js/src/utils.js
David5627/AWWARD
a22a2b2f7d7d6377435bfd475e82268e4e907141
[ "MIT" ]
189
2015-09-07T14:56:32.000Z
2022-01-31T09:17:22.000Z
my_env/lib/python3.8/site-packages/star_ratings/static/star-ratings/js/src/utils.js
David5627/AWWARD
a22a2b2f7d7d6377435bfd475e82268e4e907141
[ "MIT" ]
115
2015-09-17T08:36:36.000Z
2022-03-09T12:36:14.000Z
/************************** * Check if an element has a class **************************/ function hasClass (el, name) { return (' ' + el.className + ' ').indexOf(' ' + name + ' ') > -1; } /************************** * Find parent element **************************/ function findParent(el, className) { var parentNode = el.parentNode; while (hasClass(parentNode, className) === false) { if (parentNode.parentNode === undefined) { return null; } parentNode = parentNode.parentNode; } return parentNode } module.exports = { hasClass: hasClass, findParent: findParent };
22.892857
69
0.49922