max_stars_repo_path
stringlengths
3
961
max_stars_repo_name
stringlengths
5
122
max_stars_count
int64
0
224k
id
stringlengths
1
8
content
stringlengths
2
1.07M
score
float64
-0.95
3.88
int_score
int64
0
4
src/js/event_replayer.js
yongjik/croquis
30
15992316
// Utility class for recording and replaying events, for debugging. import { get_timestamp_str } from './util.js'; export const REPLAY_DISABLED = 0; export const REPLAY_RECORDING = 1; export const REPLAY_RUNNING = 2; const REPLAY_SPEED = 0.2; // Currently it only supports replaying for highlight tiles. Not sure if we'll // ever support other features ... export class EventReplayer { // For each `event_type` in the record, fn_map[event_type] is a function // that takes a single dict as argument, and optionally returns a Promise // object that completes the callback. constructor(btns_div, fn_map) { this.btns_div = btns_div; if (btns_div == null) { this.enabled = false; // We're disabled. return; } this.enabled = true; this.status_area = btns_div.querySelector('span'); this.fn_map = fn_map; this.reset(REPLAY_DISABLED); // Hook up buttons for replay. let buttons = btns_div.querySelectorAll('button'); // Buttons are: record/stop/save/load/replay/clear. buttons[0].onclick = () => { this.start_recording(); } buttons[1].onclick = () => { this.stop_recording(); } buttons[2].onclick = () => { this.save(); } buttons[3].onclick = () => { this.load(); } buttons[4].onclick = () => { this.start_replay(); } buttons[5].onclick = () => { this.clear(); } } clear() { if (!this.enabled) return; this.reset(REPLAY_DISABLED); this.run_cb('reset', {}).then(); this.status_area.textContent = '(Empty)'; } start_recording() { if (!this.enabled) return; this.reset(REPLAY_RECORDING); this.run_cb('reset', {}).then(); this.status_area.textContent = 'Recording ...'; } stop_recording() { if (!this.enabled) return; this.status = REPLAY_DISABLED; this.status_area.textContent = `Stopped: has ${this.events.length} events.`; } save() { if (!this.enabled) return; // Stolen from https://stackoverflow.com/a/30832210 const data = this.event_log.join('\n'); const contents = new Blob([data], {type: 'text/plain'}); let a = document.createElement('a'); let url = URL.createObjectURL(contents); a.href = url; a.download = 'event_log.txt'; document.body.appendChild(a); a.click(); setTimeout(() => { document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 0); } load() { if (!this.enabled) return; // Stolen from https://stackoverflow.com/a/50782106 let input = document.createElement('input'); input.type = 'file'; input.style.display = 'none'; let onload = (ev) => { let contents = ev.target.result; document.body.removeChild(input); this.load_handler(contents); }; input.onchange = (ev) => { let file = ev.target.files[0]; if (file == null) return; let reader = new FileReader(); reader.onload = onload; reader.readAsText(file); }; document.body.appendChild(input); input.click(); } load_handler(contents) { if (!this.enabled) return; this.events = []; this.event_log = []; for (const line of contents.split('\n')) { let m = line.match(/[0-9:.]+ +#[0-9]+: *(\[.*\])$/); if (m) this.events.push(JSON.parse(m[1])); } this.status_area.textContent = `Loaded ${this.events.length} events.`; } // Record an event: we later call this.fn_map[event_type](args). // // Currently we support the following events: // 'mouse': mouse cursor moves // 'leave': mouse leaves the area // 'tile': highlight tile received from BE record_event(event_type, args) { if (!this.enabled) return; if (this.status != REPLAY_RUNNING) this.rel_time = Date.now() - this.start_T; if (this.status != REPLAY_RECORDING) return; const event_idx = this.events.length; const event_entry = [this.rel_time, event_type, args]; this.events.push(event_entry); this.event_log.push(`${get_timestamp_str()} #${event_idx}: ` + JSON.stringify(event_entry)); this.status_area.textContent = `Recorded ${event_idx + 1} events ...`; } start_replay() { if (!this.enabled) return; if (this.events.length > 0) { this.reset(REPLAY_RUNNING); this.run_cb('reset', {}).then(); this.replay_event(0); } } replay_event(idx) { if (!this.enabled) return; if (this.status != REPLAY_RUNNING) return; // Reply disabled. const event_entry = this.events[idx]; this.event_log.push(`${get_timestamp_str()} #${idx}: ` + JSON.stringify(event_entry)); let event_type, args; [this.rel_time, event_type, args] = this.events[idx]; const event_str = `event #${idx} of ${this.events.length} : ` + `at ${this.rel_time}: ${event_type}(${JSON.stringify(args)})`; this.status_area.textContent = `Replaying ${event_str} ...`; this.run_cb(event_type, args).then(() => { idx += 1; if (idx >= this.events.length) { this.status_area.textContent = `Replay finished for ${this.events.length} events.`; return; } // Instead of starting at a fixed time, let's compute wait time // based on the current time - in this way we can set breakpoints in // dev tools and continue debugfging. let next_rel_T = this.events[idx][0]; setTimeout(() => { this.replay_event(idx) }, (next_rel_T - this.rel_time) / REPLAY_SPEED); this.status_area.textContent = `Executed ${event_str}.`; }) .catch(error => { this.status_area.textContent = `Error executing ${event_str}: ${error}`; this.status = REPLAY_DISABLED; }); } // Internal utility function. reset(status) { if (!this.enabled) return; // `rel_time` keeps the "elapsed time" since the start of // recording/replay. During replay, it is actually "fake time" and // moves lockstep with the recorded timestamp (so that the replay // behavior matches the original execution as much as possible). this.start_T = Date.now(); this.rel_time = 0; if (status != REPLAY_RUNNING) this.events = []; this.event_log = []; this.status = status; } run_cb(event_type, args) { if (!this.enabled) return; let retval = this.fn_map[event_type](args); return retval || Promise.resolve(true /* unused */); } // Add debug logging. log(...args) { if (!this.enabled) return; if (this.status == REPLAY_DISABLED) return; const rel_T = (this.status == REPLAY_RUNNING) ? this.rel_time : Date.now() - this.start_T; const s = args.map( e => ((typeof(e) == 'object') ? JSON.stringify(e) : e) ).join(' '); this.event_log.push(`${get_timestamp_str()} [${rel_T}] ${s}`); } }
1.851563
2
src/routes/v1/sales.route.js
BlackHoleUsa/KyleNFTBackend
1
15992324
const express = require('express'); const validate = require('../../middlewares/validate'); const salesController = require('../../controllers/sales.controller'); const { auctionValidation } = require('../../validations'); const router = express.Router(); router.get('/getSaleListing', [validate(auctionValidation.getOpenSalesVS)], salesController.getSaleListing); router.get('/getSaleDetails', [validate(auctionValidation.getSaleDetailsVs)], salesController.getSaleDetails); module.exports = router;
0.921875
1
src/components/DayOverView/mixEchart.js
sunhk123456/abcf
0
15992332
/* eslint-disable prefer-template,react/no-array-index-key,arrow-body-style,no-else-return */ import React,{Component} from 'react'; import {connect} from 'dva'; import {Tooltip,Icon} from 'antd'; import classNames from 'classnames'; import echart from 'echarts'; import EarlyWarning from './earlyWarning'; import styles from './mixEchart.less'; import Cookie from '@/utils/cookie'; import iconFont from '../../icon/Icons/iconfont'; const IconFont = Icon.createFromIconfontCN({ scriptUrl:iconFont }); @connect(({dayOverViewHeader,billingRevenue})=>({ dateType:dayOverViewHeader.dateType, date:dayOverViewHeader.selectedDate, tabId:dayOverViewHeader.tabId, proId:billingRevenue.proId, proName:billingRevenue.proName })) class MixEchart extends Component{ constructor(props){ super(props); this.state = { mixEchartData:[],// 全部省的数据 }; this.lineAndBarRef = React.createRef(); this.mixEchartsGaugeRef = React.createRef(); } componentDidMount(){ const {power} = Cookie.getCookie('loginStatus'); const { date,tabId,dateType,proId } = this.props; if(date !== "" && tabId !== "" && dateType !== ""){ if(power==='city' || power==='specialCity'){ this.initRequest(); }else if((power==='all' || power==='prov') && proId !== undefined ){ this.initRequest(); } } } componentDidUpdate(prevProps,prevState){ // 账期、切换标签变化去请求 const {power} = Cookie.getCookie('loginStatus'); const { date,tabId,proId} = this.props; if(prevProps.date !== date && tabId !== "" && date !== ""){ if(power==='city' || power==='specialCity'){ this.initRequest(); }else if((power==='all' || power==='prov') && proId !== undefined ){ this.initRequest(); } } const { mixEchartData } = prevState; if(proId !== undefined && proId !== prevProps.proId ){ if(mixEchartData.length>0){ this.handleData(mixEchartData); } } } /** * 根据数据绘制折线图和柱状图 * @param */ setLineAndBar(mixData) { const {signPosition,dateType,tabId} = this.props; let barColor = "#569DE4"; if(dateType === "2"){ barColor= signPosition === "1" || signPosition === "4"?"#569DE4":"#56D5E4"; } if(dateType === "1" && tabId==="TAB_104" && (signPosition === "3" || signPosition === "4")){ barColor= "#56D5E4"; } const {month,title,rating,monthSum,unit} = mixData; const ratingRes = []; // 环比值 const monthSumRes = []; // 累计值 rating.forEach((data) => { ratingRes.push(this.dataFormat(data)); }); monthSum.forEach((data) => { monthSumRes.push(this.dataFormat(data)); }); const line = echart.init(this.lineAndBarRef.current); // 初始化折线图所需dom const lineOption = { tooltip: { trigger: "axis", show: true, position: (point, params, dom, rect, size)=> { // 固定在顶部 if (point[0] > size.viewSize[0] * 0.6) { // 防止提示框溢出外层 return [ point[0] - ((point[0] - size.viewSize[0] * 0.6) * 2) / 3, 40 ]; } return [point[0], 40]; }, formatter: (params)=> { let showTip = ""; params.forEach((par)=> { if (par.axisDim === "x") { if(par.componentSubType==="bar"){ showTip += par.marker + " " + par.seriesName + ":" + monthSum[par.dataIndex] + unit + "<br/>"; }else{ showTip += par.marker + " " + par.seriesName + ":" + rating[par.dataIndex] + "<br/>"; } } }); return params[0].axisValue + "<br/>" + showTip; }, axisPointer: { type: "shadow", lineStyle: { color: "rgba(86,84,86,0.2)" } }, backgroundColor: "rgba(108,109,111,0.7)", showDelay: 0 // 显示延迟,添加显示延迟可以避免频繁切换,单位ms }, grid: [ { left: "0%", top: "10%", right:"0%", height: "30%" }, { left: "0%", top: "40%", right:"0%", height: "30%" } ], legend: { data: title, left:'center', bottom: 5, selectedMode: false, textStyle:{ color:"#999", } }, axisPointer: { show: true, type: "none", link: [{ xAxisIndex: [0, 1] }], label: { show: false } }, xAxis: [ { type: "category", show: false, gridIndex: 0, // 对应前面grid的索引位置(第一个) data: month }, { type: "category", show: true, gridIndex: 1, // 对应前面grid的索引位置(第二个) boundaryGap: [0, 0], // 坐标轴两边留白策略 axisLine: { show: true, lineStyle: { color: "#99a5bd", width: 1 } }, splitLine: { show: false }, axisLabel: { margin: 2, fontFamily: "Microsoft YaHei", color: "#999999" }, axisTick: { show: false }, splitArea: { show: false }, data: month } ], yAxis: [ { type: "value", show: false, gridIndex: 0 // 对应前面grid的索引位置(第一个) }, { type: "value", show: false, gridIndex: 1 // 对应前面grid的索引位置(第二个) } ], series: [ { name: title[1], type: "line", xAxisIndex: 0, // 对应前面x的索引位置(第一个) yAxisIndex: 0, // 对应前面y的索引位置(第一个) smooth: false, // 是否平滑曲线显示。 symbol: "emptyCircle", itemStyle: { color: "#cccccc" }, label: { show: true, formatter: (params)=> { return rating[params.dataIndex]; }, position: "top" }, data: ratingRes }, { name: title[0], type: "bar", smooth: false, // 是否平滑曲线显示。 symbol: "emptyCircle", xAxisIndex: 1, // 对应前面x的索引位置(第二个) yAxisIndex: 1, // 对应前面y的索引位置(第一个) itemStyle: { color: barColor }, data: monthSumRes } ] }; line.setOption(lineOption,true); } /** * 返回某一个省的数据 * @param mixEchartData */ handleDataRender= (mixEchartData)=>{ const {power,provOrCityId} = Cookie.getCookie('loginStatus'); const { proId } = this.props; let provData; if(power==='city' || power === "specialCity"){ provData = mixEchartData.find((item)=>{return item.proId === provOrCityId}); }else{ provData = mixEchartData.find((item)=>{return item.proId === proId}); } if(provData===undefined){ return null; } return provData.data[0]; }; /** * 处理数据、绘制图形 * @param mixEchartData */ handleData= (mixEchartData)=>{ const {power,provOrCityId} = Cookie.getCookie('loginStatus'); const { proId,dateType } = this.props; let provData; if(power==='city' || power === "specialCity"){ provData = mixEchartData.find((item)=>{return item.proId === provOrCityId}); }else{ provData = mixEchartData.find((item)=>{return item.proId === proId}); } if(provData!==undefined){ this.setLineAndBar(provData.data[0]); if(dateType === '1'){ this.setGauge(provData.data[0]); } } }; /** * 数据格式化:去百分号 * @param value * @returns {*} */ dataFormat = value => { return value.replace(/%/g, "").replace(/,/g,''); }; // 根据传入数据改变颜色,无数据时为灰色,负数为红色,非负数为绿色 ratioDataColor =(data)=>{ let color; if(data === '-' || data === undefined){ // 正常灰色 color = 'dataBlank'; }else{ const res = data.replace(/%/g, "").replace(/,/g,'').replace(/pp/g,''); color = parseFloat(res)>=0?'dateGreen':'dataRed'; } return color; }; /** * 根据数据绘制仪表盘 * @param data */ setGauge =(data)=> { let percent = "-"; // 判断data是否为空,是否有items属性 if (data && data.items !== undefined && data.items[2] !== undefined && data.items[2] !== "-") { percent = parseFloat(data.items[2]); } let fontSize = 14; if(window.screen.width>1870){ fontSize = 16; } const gauge = echart.init(this.mixEchartsGaugeRef.current); const option = { series: [ { name: '占网上用户比', type: 'gauge', radius: 26, splitNumber: 5, startAngle: 225, endAngle: 270 - percent * 360 / 100, data: [{value: percent, name: '占网上用户比'}], pointer: { show: false }, // 刻度标签 axisLabel: { show: false, }, // 刻度样式 axisTick: { show: true, length: 6, lineStyle: { width: 1, color: '#f39ba2', } }, // 分隔线样式 splitLine: { show: true, length: 6, lineStyle: { // 控制线条样式 color: '#f39ba2', width: 1 } }, detail: { show: true, offsetCenter: [0, '10%'], formatter: ()=> { if(percent === "-"){ return "-" }else { return percent+"%" } }, fontStyle: 'normal', // 样式 fontWeight: 400, // 粗细 color: '#666666', // 颜色 fontSize, // 字号 fontFamily: 'Arial', // 字体系列 }, // 仪表盘轴线 axisLine: { show: false, lineStyle: { width: 0 } }, title: { show: false } } ] }; gauge.setOption(option,true); }; /** * 弹出层 * @param kpiCode */ popUpShow = (kpiCode) =>{ const {dispatch} = this.props; dispatch({ type:"overviewIndexDetail/setKpiCode", payload:kpiCode }); dispatch({ type:"overviewIndexDetail/setPopUpShow", payload:true }); }; /* * 请求总入口 * */ initRequest() { const {dispatch,dateType,tabId,date,signPosition} = this.props; const mixId = tabId +'_mix_'+ signPosition; dispatch({type:"mixEcharts/fetchMixEcharts", payload:{dateType,tabId,date,mixId}}) .then((mixEchartData)=>{ this.setState({ mixEchartData },()=>{this.handleData(mixEchartData)}); }); }; render(){ const { mixEchartData } = this.state; const { dateType } = this.props; if(mixEchartData.length>0){ const provData = this.handleDataRender(mixEchartData); if (provData !== null && JSON.stringify(provData) !== "{}" ) { let mixChartTop; const { items,title,unit,name,kpiCode,showEarlyWarning,desc,warningLevel,showException,excepDiscription} = provData; // 智能预警 const warning = showEarlyWarning === "0"|| showEarlyWarning === undefined?null:<EarlyWarning warningLevel={warningLevel} desc={desc} />; // 指标异动 const exception = showException === "0" || showException=== undefined? null : <Tooltip placement="bottomLeft" title={excepDiscription} overlayClassName={styles.earlyTip} className={styles.early}><Icon type="exclamation-circle" theme="filled" style={{color:"#D44545"}} /></Tooltip>; if(dateType === '1'){ const ringRatingDataColorF = this.ratioDataColor(items[1]); const ringRatingDataColorS = this.ratioDataColor(items[3]); const monthSumNum = showEarlyWarning === "0"|| showEarlyWarning === undefined? <span className={classNames(styles.monthSumNum,styles.monthSumNumRight)}>{items[0]}</span>: <Tooltip placement="bottom" title={warning} overlayClassName={styles.warningTip}> <span className={styles.monthSumNum}>{items[0]}</span> <IconFont className={styles.starIcon} type="icon-jiufuqianbaoicon14" /> </Tooltip>; mixChartTop = ( <div className={styles.mixChartTop}> <div className={styles.monthSum}> <div className={styles.monthSumText}>{title[0]}</div> <div className={styles.monthSumData}> {monthSumNum} <span className={styles.monthSumUnit}>{unit}</span> </div> </div> <div className={styles.ringRating}> <div className={styles.middleText}>{title[1]}</div> <div className={classNames(styles.ringRatingData,styles[ringRatingDataColorF])}>{items[1]}</div> </div> <div className={styles.net}> <div className={styles.middleText}>{title[2]}</div> <div ref={this.mixEchartsGaugeRef} className={styles.mixEchartsGauge} /> </div> <div className={styles.samerating}> <div className={styles.middleText}>{title[3]}</div> <div className={classNames(styles.ringRatingData,styles[ringRatingDataColorS])}>{items[3] || "-"} </div> </div> </div> ); }else{ const monthShow = items.map((data,index)=> { let dataShow = data; let valueColor = "blank"; if(index >0){ valueColor = this.ratioDataColor(data); } let unitShow; let monthData = "monthData"; if(index === 0){ monthData = "monthDataFirst"; unitShow = <span className={styles.monthUnit}>{unit}</span>; dataShow = showEarlyWarning === "0"|| showEarlyWarning === undefined? <span>{dataShow}</span>: <Tooltip placement="bottom" title={warning} overlayClassName={styles.warningTip}> <span>{dataShow}</span> <IconFont className={styles.starIcon} type="icon-jiufuqianbaoicon14" /> </Tooltip> } return ( <div key={"mixEcharts"+index} className={styles[monthData]}> <span className={styles.monthName}>{title[index]}</span> <span className={classNames(styles.monthValue,styles[valueColor])}>{dataShow}{unitShow}</span> </div>) }); mixChartTop =( <div className={styles.mixChartTop}> {monthShow} </div> ) } return ( <div className={styles.mixEchart}> <div className={styles.kpiName}><span className={styles.titleSpan} id={kpiCode} onClick={()=>{this.popUpShow(kpiCode)}}>{exception}{name}</span></div> {mixChartTop} <div ref={this.lineAndBarRef} className={styles.lineAndBarEchart} /> </div> ); } else{ return null; } }else{ return null; } } } export default MixEchart;
1.335938
1
packages/swingset-runner/demo/justReply/bootstrap.js
TerryvanWalen/agoric-sdk
0
15992340
import harden from '@agoric/harden'; console.log(`=> loading bootstrap.js`); export default function setup(syscall, state, helpers) { function log(what) { helpers.log(what); console.log(what); } log(`=> setup called`); return helpers.makeLiveSlots( syscall, state, E => harden({ bootstrap(argv, vats) { console.log('=> bootstrap() called'); E(vats.alice) .sayHelloTo(vats.bob) .then( r => log(`=> alice.hello(bob) resolved to '${r}'`), e => log(`=> alice.hello(bob) rejected as '${e}'`), ); }, }), helpers.vatID, ); }
1.085938
1
lib/emitter.test.js
smujmaiku/objdb
1
15992348
const common = require('./common'); const Emitter = require('./emitter'); describe('Emitter', () => { it('should construct', () => { expect(new Emitter()).toBeDefined(); expect(new Emitter(1)._debounce).toEqual(1); }); describe('getRelatedListeners', () => { it('should return an Array', () => { const emitter = new Emitter(); expect(emitter.getRelatedListeners()).toEqual([]); expect(emitter.getRelatedListeners('a')).toEqual([]); }); it('should return related listeners', () => { const emitter = new Emitter(); emitter.on('a', () => 0); emitter.on('a.b', () => 0); emitter.on('a$meta', () => 0); emitter.on('c.d', () => 0); expect(emitter.getRelatedListeners('')).toEqual(['a', 'a.b', 'c.d']); expect(emitter.getRelatedListeners('a')).toEqual(['a', 'a.b']); expect(emitter.getRelatedListeners('a.b')).toEqual(['a', 'a.b']); expect(emitter.getRelatedListeners('a.c')).toEqual(['a']); expect(emitter.getRelatedListeners('c')).toEqual(['c.d']); }); }); describe('on', () => { it('should set a listener', () => { const emitter = new Emitter(); emitter.on('a', () => 0); emitter.on('b.c$meta', () => 0); expect(emitter.getRelatedListeners('')).toEqual(['a', 'b.c']); }); it('should set lists of listeners', () => { const emitter = new Emitter(); emitter.on(['a', 'b'], () => 0); emitter.on('c$meta, d.e,f', () => 0); expect(emitter.getRelatedListeners('')).toEqual(['a', 'b', 'c', 'd.e', 'f']); }); it('should not listen to invalid parameters', () => { const emitter = new Emitter(); emitter.on('a'); emitter.on('a', ''); emitter.on('', () => 0); emitter.on({}, () => 0); emitter.on(1, () => 0); expect(emitter.getRelatedListeners('')).toEqual([]); }); it('should emit initial data', () => { const cb = jest.fn(); const data = { data: 'important' }; const emitter = new Emitter(); emitter._get = data; emitter.on('a', cb); return Promise.resolve().then(() => { expect(cb).toBeCalledWith(data); }); }); it('should skip initial data', () => { const cb = jest.fn(); const data = { data: 'important' }; const emitter = new Emitter(); emitter._get = data; emitter.on('a', cb, true); return Promise.resolve().then(() => { expect(cb).not.toBeCalled(); }); }); }); describe('once', () => { it('should emit initial data', () => { const cb = jest.fn(); const data = { data: 'important' }; const emitter = new Emitter(); emitter._get = data; emitter.once('a', cb); return Promise.resolve().then(() => { expect(cb).toBeCalledWith(data); emitter.emit('a', data); expect(cb).toBeCalledTimes(1); }); }); it('should emit once data exists', () => { const cb = jest.fn(); const data = { data: 'important' }; const emitter = new Emitter(); emitter.once('a', cb); return Promise.resolve().then(() => { expect(cb).not.toBeCalled(); emitter.emit('a', data); emitter.emit('a', data); expect(cb).toBeCalledWith(data); expect(cb).toBeCalledTimes(1); }); }); }); describe('off', () => { it('should not fail on invalid parameters', () => { const cb = jest.fn(); const emitter = new Emitter(); emitter.on('c', cb); emitter.off(); emitter.off(undefined, () => 0); emitter.off('b', cb); emitter.off('c'); expect(emitter.getRelatedListeners('')).toEqual(['c']); }); it('should remove a listener', () => { const cb = jest.fn(); const data = { data: 'important' }; const emitter = new Emitter(); emitter.on('a', cb); emitter.on('a', () => 0); emitter.off('a', cb); emitter.emit('a', data); expect(emitter.getRelatedListeners('a')).toEqual(['a']); expect(cb).not.toBeCalled(); }); it('should remove groups of listeners', () => { const cb = jest.fn(); const data = { data: 'important' }; const emitter = new Emitter(); emitter.on('a', cb); emitter.on('a', () => 0); emitter.off('a', true); emitter.emit('a', data); expect(emitter.getRelatedListeners('a')).toEqual([]); expect(cb).not.toBeCalled(); }); it('should remove lists of listeners', () => { const emitter = new Emitter(); emitter.on('a', () => 0); emitter.on('b', () => 0); emitter.on('c', () => 0); emitter.off(['a', 'c'], true); expect(emitter.getRelatedListeners('')).toEqual(['b']); }); it('should remove all listeners', () => { const emitter = new Emitter(); emitter.on('a', () => 0); emitter.on('b', () => 0); emitter.off(true); expect(emitter.getRelatedListeners('')).toEqual([]); }); it('should run the clean function', () => { const cb = jest.fn(); cb._clean = jest.fn(); const emitter = new Emitter(); emitter.on('a', cb); emitter.off(true); expect(cb._clean).toBeCalled(); }); }); describe('onDeep', () => { it('should not fail on invalid parameters', () => { const emitter = new Emitter(); expect(emitter.onDeep()).toBe(emitter); emitter.onDeep(''); emitter.onDeep('a'); emitter.onDeep('b', 0); emitter.onDeep('c', '', () => 0); emitter.onDeep('d', -1, () => 0); expect(emitter.getRelatedListeners('')).toEqual(['d']); }); it('should create a deep listener', () => { const data = { 'a.b$keys': ['c', 'd'], 'a.b.c': 1, 'a.b.d': 2, }; const emit = key => emitter.emit(key, emitter.get(key)); const emitter = new Emitter(); emitter.get = (name) => data[name]; const cb = jest.fn(); emitter.onDeep('a.b', 1, cb); emit('a.b$keys'); return common.delay(1).then(() => { expect(cb).toBeCalledWith('c', 1); expect(cb).toBeCalledWith('d', 2); }); }); it('should create a really deep listener', () => { const data = { 'a$keys': ['b'], 'a.b$keys': ['c', 'd'], 'a.b.c': 1, 'a.b.d': 2, }; const emit = key => emitter.emit(key, emitter.get(key)); const emitter = new Emitter(); emitter.get = (name) => data[name]; const cb = jest.fn(); emitter.onDeep('a', 2, cb); emit('a$keys'); return common.delay(1).then(() => { expect(cb).toBeCalledWith('b.c', 1); expect(cb).toBeCalledWith('b.d', 2); }); }); it('should create a deep listener on root', () => { const data = { '$keys': ['a'], 'a$keys': ['b'], 'a.b': 1, }; const emit = key => emitter.emit(key, emitter.get(key)); const emitter = new Emitter(); emitter.get = (name) => data[name]; const cb = jest.fn(); emitter.onDeep('', 2, cb); emit('$keys'); return common.delay(1).then(() => { expect(cb).toBeCalledWith('a.b', 1); }); }); it('should clean up its listeners', () => { const data = { 'a$keys': ['b'], 'a.b$keys': ['c', 'd'], 'a.b.c': 1, 'a.b.d': 2, }; const emit = key => emitter.emit(key, emitter.get(key)); const emitter = new Emitter(); emitter.get = (name) => data[name]; const cb = jest.fn(); emitter.onDeep('a', 2, cb); emit('a$keys'); emitter.off('a$deep', cb); expect(emitter.getRelatedListeners('')).toEqual([]); }); }); describe('emit', () => { it('should not fail on invalid parameters', () => { const emitter = new Emitter(); expect(emitter.emit()).toBe(emitter); expect(emitter.emit('a')).toBe(emitter); }); it('should emit to listeners', () => { const acb = jest.fn(); const akeycb = jest.fn(); const bcb = jest.fn(); const data = { a: 1, b: 2 }; const emitter = new Emitter(); emitter.on('a', acb); emitter.on('a$keys', akeycb); emitter.on('b', bcb); emitter.emit('a', data); expect(acb).toBeCalledWith(data); expect(akeycb).toBeCalledWith(Object.keys(data)); expect(bcb).not.toBeCalled(); }); }); describe('debounce', () => { it('should not fail on invalid parameters', () => { const emitter = new Emitter(); expect(emitter.debounce('a')).toBe(emitter); emitter.on('a', () => 0); expect(emitter.debounce()).toBe(emitter); expect(emitter.debounce('a')).toBe(emitter); expect(emitter.debounce('a', undefined, '')).toBe(emitter); }); it('should emit after debounce time', () => { const cb = jest.fn(); const data = { data: 'important' }; const wait = 2; const emitter = new Emitter(); emitter.on('a', cb); emitter.debounce('a', data, wait); expect(cb).not.toBeCalled(); return common.delay(wait).then(() => { expect(cb).toBeCalledWith(data); }); }); it('should debounce emitting', () => { const cb = jest.fn(); const data = { data: 'important' }; const wait = 2; const emitter = new Emitter(); emitter.on('a', cb); emitter.debounce('a', '', wait); emitter.debounce('a', data, wait); return common.delay(wait).then(() => { expect(cb).toBeCalledWith(data); expect(cb).toBeCalledTimes(1); }); }); it('should resolve data as a function before emitting', () => { const cb = jest.fn(); const data = { data: 'important' }; const datacb = jest.fn(() => data); const wait = 2; const emitter = new Emitter(); emitter.on('a', cb); emitter.debounce('a', datacb, wait); expect(cb).not.toBeCalled(); return common.delay(wait).then(() => { expect(datacb).toBeCalled(); expect(cb).toBeCalledWith(data); }); }); it('should emit again if the data function takes longer than the next debounce', () => { const cb = jest.fn(); const data = { data: 'important' }; const moredata = { more: 'data' }; let dataresolve; const datacb = jest.fn(() => new Promise((resolve) => { dataresolve = resolve; })); const wait = 2; const emitter = new Emitter(); emitter.on('a', cb); emitter.debounce('a', '', wait); emitter.debounce('a', datacb, wait); expect(cb).not.toBeCalled(); return common.delay(wait + 1).then(() => { expect(datacb).toBeCalled(); expect(cb).not.toBeCalled(); emitter.debounce('a', '', wait); emitter.debounce('a', moredata, wait); return common.delay(wait + 1); }).then(() => { expect(cb).not.toBeCalled(); dataresolve(data); return common.delay(1); }).then(() => { expect(cb).toBeCalledWith(data); return common.delay(wait + 1); }).then(() => { expect(cb).toBeCalledWith(moredata); expect(cb).toBeCalledTimes(2); }); }); }); describe('send', () => { it('should debounce related emitters', () => { const db = new Emitter(5); db.on('a', () => 0); db.on('a.b', () => 0); db.on('a.c', () => 0); db.on('a.b.c', () => 0); db.on('b', () => 0); db.debounce = jest.fn((k, cb) => cb(k)); db.get = jest.fn(); db.send('a.b'); expect(db.debounce).toBeCalledWith('a', expect.any(Function)); expect(db.debounce).toBeCalledWith('a.b', expect.any(Function)); expect(db.debounce).toBeCalledWith('a.b.c', expect.any(Function)); expect(db.debounce).toBeCalledTimes(3); expect(db.get).toBeCalledWith('a'); expect(db.get).toBeCalledWith('a.b'); expect(db.get).toBeCalledWith('a.b.c'); expect(db.get).toBeCalledTimes(3); }); it('should allow directly calling emit', () => { const db = new Emitter(5); db.on('a', () => 0); db.emit = jest.fn(); db._get = '1'; db.send('a.b', false); return common.delay(1).then(() => { expect(db.emit).toBeCalledWith('a', '1'); }); }); }); describe('get', () => { it('should return this._get for testing', () => { const data = { data: 'important' }; const emitter = new Emitter(); emitter._get = data; expect(emitter.get()).toBe(data); }); }); });
1.484375
1
src/Select/ListItem.js
edenlabllc/react-components
0
15992356
import React from 'react'; import classnames from 'classnames'; import Icon from '../Icon'; import styles from './styles.scss'; const ListItem = ({ active, disabled, title, onClick }) => ( <li onClick={onClick} className={classnames(active && styles.active, disabled && styles.disabled)} > {title} {active ? <span className={styles.icon}><Icon name="check-right" /></span> : null } </li> ); export default ListItem;
0.988281
1
main.js
Dobis19/ioBroker.admin
2
15992364
/** * Admin backend * * Controls Adapter-Processes * * Copyright 2014-2019 bluefox <<EMAIL>>, * MIT License * */ /* jshint -W097 */ /* jshint strict: false */ /* jslint node: true */ 'use strict'; const adapterName = require('./package.json').name.split('.').pop(); const utils = require('@iobroker/adapter-core'); // Get common adapter utils const tools = require(utils.controllerDir + '/lib/tools.js'); const SocketIO = require('./lib/socket'); const Web = require('./lib/web'); let socket = null; let webServer = null; let objects = {}; let states = {}; let secret = '<KEY>'; // Will be generated by first start let adapter; function startAdapter(options) { options = options || {}; Object.assign(options, { name: adapterName, // adapter name dirname: __dirname, // say own position logTransporter: true, // receive the logs systemConfig: true, install: callback => typeof callback === 'function' && callback() }); adapter = new utils.Adapter(options); adapter.on('objectChange', (id, obj) => { if (obj) { //console.log('objectChange: ' + id); objects[id] = obj; if (id === 'system.repositories') { writeUpdateInfo(); } } else { //console.log('objectDeleted: ' + id); if (objects[id]) { delete objects[id]; } } // TODO Build in some threshold of messages if (socket) { socket.objectChange(id, obj); } }); adapter.on('stateChange', (id, state) => { if (!state) { if (states[id]) { delete states[id]; } } else { states[id] = state; } if (socket) { socket.stateChange(id, state); } }); adapter.on('ready', () => { adapter.getForeignObject('system.config', (err, obj) => { if (!err && obj) { obj.native = obj.native || {}; if (!obj.native.secret) { require('crypto').randomBytes(24, (ex, buf) => { adapter.config.secret = buf.toString('hex'); adapter.extendForeignObject('system.config', {native: {secret: adapter.config.secret}}); main(); }); } else { adapter.config.secret = obj.native.secret; main(); } } else { adapter.config.secret = secret; adapter.log.error('Cannot find object system.config'); } }); }); adapter.on('message', obj => { if (!obj || !obj.message) { return false; } if (socket) { socket.sendCommand(obj); } return true; }); adapter.on('unload', callback => { if (socket) { // unsubscribe all socket.unsubscribeAll(); } try { adapter.log.info('terminating http' + (adapter.config.secure ? 's' : '') + ' server on port ' + adapter.config.port); webServer.close(); callback(); } catch (e) { callback(); } }); // obj = {message: msg, severity: level, from: this.namespace, ts: (new Date()).getTime()} adapter.on('log', obj => socket && socket.sendLog(obj)); return adapter; } function createUpdateInfo() { // create connected object and state let updatesNumberObj = objects[adapter.namespace + '.info.updatesNumber']; if (!updatesNumberObj || !updatesNumberObj.common || updatesNumberObj.common.type !== 'number') { let obj = { _id: 'info.updatesNumber', type: 'state', common: { role: 'indicator.updates', name: 'Number of adapters to update', type: 'number', read: true, write: false, def: 0 }, native: {} }; adapter.setObject(obj._id, obj); } let updatesListObj = objects[adapter.namespace + '.info.updatesList']; if (!updatesListObj || !updatesListObj.common || updatesListObj.common.type !== 'string') { let obj = { _id: 'info.updatesList', type: 'state', common: { role: 'indicator.updates', name: 'List of adapters to update', type: 'string', read: true, write: false, def: '' }, native: {} }; adapter.setObject(obj._id, obj); } let newUpdatesObj = objects[adapter.namespace + '.info.newUpdates']; if (!newUpdatesObj || !newUpdatesObj.common || newUpdatesObj.common.type !== 'boolean') { let obj = { _id: 'info.newUpdates', type: 'state', common: { role: 'indicator.updates', name: 'Indicator if new adapter updates are available', type: 'boolean', read: true, write: false, def: false }, native: {} }; adapter.setObject(obj._id, obj); } let updatesJsonObj = objects[adapter.namespace + '.info.updatesJson']; if (!updatesJsonObj || !updatesJsonObj.common || updatesJsonObj.common.type !== 'string') { let obj = { _id: 'info.updatesJson', type: 'state', common: { role: 'indicator.updates', name: 'JSON string with adapter update information', type: 'string', read: true, write: false, def: '{}' }, native: {} }; adapter.setObject(obj._id, obj); } let lastUpdateCheckObj = objects[adapter.namespace + '.info.lastUpdateCheck']; if (!lastUpdateCheckObj || !lastUpdateCheckObj.common || lastUpdateCheckObj.common.type !== 'string') { let obj = { _id: 'info.lastUpdateCheck', type: 'state', common: { role: 'value.datetime', name: 'Timestamp of last update check', type: 'string', read: true, write: false, def: '{}' }, native: {} }; adapter.setObject(obj._id, obj); } } // Helper methods function upToDate(a, b) { a = a.split('.'); b = b.split('.'); a[0] = parseInt(a[0], 10); b[0] = parseInt(b[0], 10); if (a[0] > b[0]) { return false; } else if (a[0] < b[0]) { return true; } else if (a[0] === b[0]) { a[1] = parseInt(a[1], 10); b[1] = parseInt(b[1], 10); if (a[1] > b[1]) { return false; } else if (a[1] < b[1]) { return true; } else if (a[1] === b[1]) { a[2] = parseInt(a[2], 10); b[2] = parseInt(b[2], 10); return a[2] <= b[2]; } } else { return true; } } function writeUpdateInfo(sources) { if (!sources) { let obj = objects['system.repositories']; if (!objects['system.config'] || !objects['system.config'].common) { adapter.log.warn('Repository cannot be read. Invalid "system.config" object.'); return; } const activeRepo = objects['system.config'].common.activeRepo; if (obj && obj.native && obj.native.repositories && obj.native.repositories[activeRepo] && obj.native.repositories[activeRepo].json) { sources = obj.native.repositories[activeRepo].json; } else { adapter.setState('info.updatesNumber', 0, true); adapter.setState('info.updatesList', '', true); adapter.setState('info.newUpdates', false, true); adapter.setState('info.updatesJson', '{}', true); let updateTime = new Date(); adapter.setState('info.lastUpdateCheck', new Date(updateTime - updateTime.getTimezoneOffset() * 60000).toISOString(), true); if (obj && obj.native && obj.native.repositories && obj.native.repositories[activeRepo]) { adapter.log.warn('Repository cannot be read'); } else { adapter.log.warn('No repository source configured'); } return; } } let installed = tools.getInstalledInfo(); let list = []; let updatesJson = {}; let newUpdateIndicator = false; adapter.getState('info.updatesJson', (err, state) => { let oldUpdates; if (state && state.val) oldUpdates = JSON.parse(state.val) || {}; else oldUpdates = {}; for (let name in sources) { if (!sources.hasOwnProperty(name)) continue; if (installed[name] && installed[name].version && sources[name].version) { if (sources[name].version !== installed[name].version && !upToDate(sources[name].version, installed[name].version)) { // Check if updates are new or already known to user if (!oldUpdates || !oldUpdates[name] || oldUpdates[name].availableVersion !== sources[name].version) { newUpdateIndicator = true; } // endIf updatesJson[name] = { availableVersion: sources[name].version, installedVersion: installed[name].version }; // remove first part of the name const n = name.indexOf('.'); list.push(n === -1 ? name : name.substring(n + 1)); } } } adapter.setState('info.updatesNumber', list.length, true); adapter.setState('info.updatesList', list.join(', '), true); adapter.setState('info.newUpdates', newUpdateIndicator, true); adapter.setState('info.updatesJson', JSON.stringify(updatesJson), true); let updateTime = new Date(); adapter.setState('info.lastUpdateCheck', new Date(updateTime - updateTime.getTimezoneOffset() * 60000).toISOString(), true); }); } // to do => remove it later, when all repositories patched. function patchRepos(callback) { return callback && callback(); // do not patch any more. Delete it later 2018.04.23 /* adapter.getForeignObject('system.repositories', (err, obj) => { let changed = false; if (obj && obj.native && obj.native.repositories) { // default link should point to stable if (!obj.native.repositories.default || obj.native.repositories.default.link !== 'http://download.iobroker.net/sources-dist.json') { changed = true; obj.native.repositories.default = { link: 'http://download.iobroker.net/sources-dist.json' }; } // latest link should point to latest if (!obj.native.repositories.latest) { obj.native.repositories.latest = { link: 'http://download.iobroker.net/sources-dist-latest.json' }; changed = true; } // change URL of raw sources from ioBroker.js-controller to ioBroker.repositories for (let r in obj.native.repositories) { if (obj.native.repositories.hasOwnProperty(r) && obj.native.repositories[r].link === 'https://raw.githubusercontent.com/ioBroker/ioBroker.js-controller/master/conf/sources-dist.json') { obj.native.repositories[r].link = 'https://raw.githubusercontent.com/ioBroker/ioBroker.repositories/master/sources-dist.json'; changed = true; } } } if (changed) { adapter.setForeignObject(obj._id, obj, function () { callback && callback(); }); } else { callback && callback(); } });*/ } function initSocket(server, store) { socket = new SocketIO(server, adapter.config, adapter, objects, states, store); socket.subscribe(null, 'objectChange', '*'); } function main() { // adapter.subscribeForeignStates('*'); // adapter.subscribeForeignObjects('*'); adapter.config.defaultUser = adapter.config.defaultUser || 'admin'; if (!adapter.config.defaultUser.match(/^system\.user\./)) { adapter.config.defaultUser = 'system.user.' + adapter.config.defaultUser; } if (adapter.config.secure) { // Load certificates adapter.getCertificates((err, certificates, leConfig) => { adapter.config.certificates = certificates; adapter.config.leConfig = leConfig; getData(() => webServer = new Web(adapter.config, adapter, initSocket)); }); } else { getData(() => webServer = new Web(adapter.config, adapter, initSocket)); } patchRepos(() => { // By default update repository every 24 hours if (adapter.config.autoUpdate === undefined) { adapter.config.autoUpdate = 24; } adapter.config.autoUpdate = parseInt(adapter.config.autoUpdate, 10) || 0; if (adapter.config.autoUpdate) { setInterval(() => updateRegister(), adapter.config.autoUpdate * 3600000); updateRegister(); } }); } function getData(callback) { adapter.log.info('requesting all states'); let tasks = 0; tasks++; adapter.getForeignStates('*', (err, res) => { adapter.log.info('received all states'); states = res; if (!--tasks && callback) callback(); }); adapter.log.info('requesting all objects'); tasks++; adapter.objects.getObjectList({include_docs: true}, (err, res) => { adapter.log.info('received all objects'); res = res.rows; objects = {}; let tmpPath = ''; for (let i = 0; i < res.length; i++) { objects[res[i].doc._id] = res[i].doc; if (res[i].doc.type === 'instance' && res[i].doc.common && res[i].doc.common.tmpPath) { if (tmpPath) { adapter.log.warn('tmpPath has multiple definitions!!'); } tmpPath = res[i].doc.common.tmpPath; } } // Some adapters want access on specified tmp directory if (tmpPath) { adapter.config.tmpPath = tmpPath; adapter.config.tmpPathAllow = true; } createUpdateInfo(); writeUpdateInfo(); if (!--tasks && callback) callback(); }); } // read repository information from active repository function updateRegister() { adapter.log.info('Request actual repository...'); adapter.getForeignObject('system.config', (err, data) => { if (data && data.common) { adapter.sendToHost(adapter.host, 'getRepository', { repo: data.common.activeRepo, update: true }, _repository => { if (_repository === 'permissionError') { adapter.log.error('May not read "getRepository"'); } else { adapter.log.info('Repository received successfully.'); if (socket) { socket.repoUpdated(); } } }); } }); } // If started as allInOne mode => return function to create instance if (module && module.parent) { module.exports = startAdapter; } else { // or start the instance directly startAdapter(); }
1.4375
1
templates/main/info/outputs.js
jessebuildersday/awsbuildersday
157
15992372
module.exports={ "CodeBucket":{ "Value":{"Ref":"CodeBucket"} }, "TrainingRoleArn":{ "Value":{"Fn::GetAtt":["TrainingRole","Arn"]} }, "TrainingRole":{ "Value":{"Ref":"TrainingRole"} }, "ModelRole":{ "Value":{"Ref":"ModelRole"} }, "AlexaLambdaArn":{ "Value":{"Fn::GetAtt":["AlexaLambda","Arn"]}, "Description":"Lambda function for creating an alexa skill" }, "ParameterStore":{ "Value":{"Ref":"ParameterStore"} }, "NoteBookUrl":{ "Value":{"Fn::If":[ "NoteBookInstance", {"Fn::Sub":"https://console.aws.amazon.com/sagemaker/home?region=${AWS::Region}#/notebook-instances/openNotebook/${Notebook.Name}"}, "EMPTY" ]}, "Description":"AWS Console url of your sagemaker notebook instance, from here you can open the instance" }, "NoteBookInstance":{ "Value":{"Fn::If":[ "NoteBookInstance", {"Fn::Sub":"https://console.aws.amazon.com/sagemaker/home?region=${AWS::Region}#/notebook-instances/${Notebook.Name}"}, "EMPTY" ]}, "Description":"AWS Console url of your sagemaker notebook instance, from here you can open the instance" }, "NoteBookInstanceName":{ "Value":{"Fn::If":[ "NoteBookInstance", {"Fn::Sub":"${Notebook.Name}"}, "EMPTY" ]}, "Description":"AWS Console url of your sagemaker notebook instance, from here you can open the instance" }, "DashboardUrl":{ "Value":{"Fn::Join":["",[ "https://console.aws.amazon.com/cloudwatch/home?", "region=",{"Ref":"AWS::Region"}, "#dashboards:name=",{"Ref":"dashboard"} ]]}, "Description":"CloudWatch Dashboard that tracks Lambda, SageMaker, and step function metrics" }, "TrainStatusTopic":{ "Value":{"Ref":"TrainStatusTopic"}, "Description":"SNS topic that gives success or failure updates of build" }, "LaunchTopic":{ "Value":{"Ref":"LaunchTopic"}, "Description":"Topic that triggers a new build/train. Use this value to setup github webhook triggers." }, "RollbackTopic":{ "Value":{"Ref":"RollbackTopic"}, "Description":"Topic that triggers a rollback fo the endpoint to the previous config" }, "SageMakerEndpoint":{ "Value":{"Fn::GetAtt":["Variables","EndpointName"]}, "Description":"Name of the SageMaker endpoint" }, "StateMachine":{ "Value":{"Ref":"StateMachine"}, "Description":"StepFunction StateMachine the runs the build" }, "DataBucket":{ "Value":{"Fn::GetAtt":["Variables","DataBucket"]}, "Description":"S3 Bucket to put data for training in, will automaticaly trigger a new build" }, "TrainingConfigLambda":{ "Value":{"Fn::Sub":"${LambdaVariables.TrainingConfig}"}, "Description":"Lambda function that returns the Training Job Config" }, "EndpointConfigLambda":{ "Value":{"Fn::Sub":"${LambdaVariables.EndpointConfig}"}, "Description":"Lambda function that returns the Endpoint Config" }, "ModelConfigLambda":{ "Value":{"Fn::Sub":"${LambdaVariables.ModelConfig}"}, "Description":"Lambda function that returns Model Configuration" }, "RepoUrl":{ "Value":{"Fn::GetAtt":["Variables","RepoUrl"]}, "Description":"CodeCommit repo to put Dockerfile code in, will automatically trigger a new build" }, "StepFunctionConsole":{ "Value":{"Fn::Sub":"https://console.aws.amazon.com/states/home?region=${AWS::Region}#/statemachines/view/${StateMachine}"}, "Description":"AWS Console for the StepFunction StateMachine that controls the build" } }
1.367188
1
markup/components/house/data/data.js
AdreeUA/lorus
0
15992380
var data = {house: {}}
0.109863
0
src/kvlt06/Canvas/_index.js
mtoutside/webgl-kvlt
0
15992388
import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import Config from './_Config'; export default class Canvas { constructor() { this.canvas = document.createElement('canvas'); this.ctx = this.canvas.getContext('2d'); this.clock = new THREE.Clock(); this.container = document.getElementById('CanvasContainer'); this.particleIndexArray = []; this.setConfig(); this.renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true, }); this.renderer.setSize(Config.width, Config.height); this.renderer.setPixelRatio(Config.dpr); this.container.appendChild(this.renderer.domElement); this.resizeFunction = this.resize.bind(this); this.updateFunction = this.update.bind(this); // リサイズイベントを設定 window.addEventListener('resize', this.resizeFunction); this.scene = new THREE.Scene(); // Cameraを作成 this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000); this.camera.position.set(0, 0, 1000); this.z = Math.min(window.innerWidth, window.innerHeight); this.camera.lookAt(0, 0, this.z); this.controls = new OrbitControls(this.camera, this.renderer.domElement); // 初期化 this.init(); } setConfig() { // 親要素のサイズを取得 const domRect = this.container.getBoundingClientRect(); const width = domRect.width; const height = domRect.height; Config.dpr = Math.min(window.devicePixelRatio, 2); Config.width = width; Config.height = height; Config.halfWidth = Config.width / 2; Config.halfHeight = Config.height / 2; Config.aspectRatio = Config.width / Config.height; } resizeScene() { this.renderer.setSize(Config.width, Config.height); } init() { this.navigatorMediaDevices = navigator.mediaDevices || (navigator.mozGetUserMedia || navigator.webkitGetUserMedia ? { getUserMedia: c => { return new Promise((y, n) => { (navigator.mozGetUserMedia || navigator.webkitGetUserMedia).call( navigator, c, y, n ); }); }, } : null); if (this.navigatorMediaDevices) { this.initVideo(); } this.start(); } /** * initVideo. * カメラ初期化 */ initVideo() { this.video = document.getElementById('video'); this.video.autoplay = true; const option = { video: true, audio: false, }; navigator.mediaDevices .getUserMedia(option) .then(stream => { this.video.srcObject = stream; this.video.addEventListener('loadeddata', () => { this.videoWidth = this.video.videoWidth; this.videoHeight = this.video.videoHeight; this.createParticles(); }); }) .catch(error => { console.log(error); // this.showAlert(); }); } createParticles() { const imageData = this.getImageData(this.video); this.geometry = new THREE.BufferGeometry(); this.geometry.morphAttributes = {}; this.material = new THREE.PointsMaterial({ size: 1, color: 0xff3b6c, sizeAttenuation: false, }); const vertices = []; // 格子状にパーティクルを並べる for (let y = 0, height = imageData.height; y < height; y++) { for (let x = 0, width = imageData.width; x < width; x++) { let index = (x + y * width) * 4; this.particleIndexArray.push(index); let gray = (imageData.data[index] + imageData.data[index + 1] + imageData.data[index + 2]) / 3; let z = gray < 300 ? gray : 10000; vertices.push(x - imageData.width / 2, -y + imageData.height / 2, 0); } } console.log(vertices); const verticesArray = new Float32Array(vertices); this.geometry.setAttribute('position', new THREE.BufferAttribute(verticesArray, 3)); this.particles = new THREE.Points(this.geometry, this.material); this.scene.add(this.particles); } getImageData(image, useCache) { // フレーム止まる if (useCache && this.imageCache) { return this.imageCache; } const w = image.videoWidth; const h = image.videoHeight; this.canvas.width = w; this.canvas.height = h; this.ctx.translate(w, 0); this.ctx.scale(-1, 1); this.ctx.drawImage(image, 0, 0); this.imageCache = this.ctx.getImageData(0, 0, w, h); return this.imageCache; } start() { this.checkFirst = true; // 初回描画判定 this.resize(); this.update(); } resize() { this.setConfig(); this.resizeScene(); } update() { this.clock.getDelta(); this.t = this.clock.elapsedTime * 50; // video if (this.particles) { this.particles.material.color.r = 1; this.particles.material.color.g = 1; this.particles.material.color.b = 1; const density = 2; const useCache = parseInt(this.t) % 2 === 0; const imageData = this.getImageData(this.video, useCache); let count = 0; const particliCount = this.particles.geometry.attributes.position.array.length; const segment = (Math.floor(this.t) * imageData.width * 3) % particliCount; // 一番最初なにも描画されないので一回だけ実行 if (this.checkFirst) { for (let i = 0, length = particliCount; i < length; i += 3) { if (i + (2 % density) === 0) { this.particles.geometry.attributes.position.array[i + 2] = 10000; continue; } // let index = i * 4; let index = this.particleIndexArray[count]; let gray = (imageData.data[index] + imageData.data[index + 1] + imageData.data[index + 2]) / 3; let threshold = 400; if (gray < threshold) { this.particles.geometry.attributes.position.array[i + 2] = gray * 1; } else { this.particles.geometry.attributes.position.array[i + 2] = 10000; } count++; } this.particles.geometry.attributes.position.needsUpdate = true; this.checkFirst = false; count = 0; } for (let i = segment, length = particliCount; i < length; i += 3) { let index = this.particleIndexArray[i / 3]; if (i + (2 % density) === 0) { this.particles.geometry.attributes.position.array[i + 2] = 10000; continue; } let gray = (imageData.data[index] + imageData.data[index + 1] + imageData.data[index + 2]) / 3; let threshold = 300; if (gray < threshold) { this.particles.geometry.attributes.position.array[i + 2] = gray; } else { this.particles.geometry.attributes.position.array[i + 2] = 10000; } count++; } this.particles.geometry.attributes.position.needsUpdate = true; } requestAnimationFrame(this.updateFunction); this.renderer.render(this.scene, this.camera); } }
1.773438
2
test/GithubSpec.js
j-san/ScrHub
0
15992396
require('../src/utils/logging').useSilenteLogger(); var sinon = require('sinon'), sholud = require('should'), nock = require('nock'), q = require('q'), GithubApi = require('../src/models/GithubApi'); nock.disableNetConnect(); describe("Github Api", function(done) { it("should request to Github", function() { nock("https://api.github.com") .get("/user") .reply(200, {}) .get("/user/repos") .reply(200, {}) .get("/orgs/hello/repos") .reply(200, {}) .get("/repos/hello/world/issues") .reply(200, {}) .get("/repos/hello/world/labels") .reply(200, {}) .get("/repos/hello/world/issues?milestone=x") .reply(200, {}); var api = new GithubApi({}); q.all([ api.getUser(), api.listProjects(), api.listOrgProjects('hello'), api.allStories('hello/world'), api.allLabels('hello/world'), api.dashboardStories('hello/world', 'x') ]).then(function () { done(); }).fail(function (err) { done(err); }); }); it("should return fetched data", function() { nock("https://api.github.com") .get("/repos/hello/world/milestones?state=open") .reply(200, [ {number: 1, title: "V0.1"}, {number: 2, title: "V0.2"}, {number: 3, title: "V0.3"} ]); (new GithubApi({})).listSprints('hello/world').then(function (sprints) { sprints.length.should.be(3); done(); }).fail(function (err) { done(err); }); }); it("should generate a new token", function() { nock("https://github.com") .post("/login/oauth/access_token") .reply(200, { access_token: 'xxxx' }); (new GithubApi({code: "fake"})).getToken().then(function (data) { data.should.have.property('access_token'); done(); }); }); });
1.546875
2
espruino/modules/OBD.js
ipepe/euro-ep3-cruise-control
0
15992404
function OBD(wifi){ console.log("Hello! I'm OBD module! Constructor linked from outside") } OBD.prototype.setup = function(){ console.log("Hello! I'm OBD module! Setup") } OBD.prototype.loop = function(){ console.log("Hello! I'm OBD module! Loop") } exports = OBD;
0.742188
1
grunt.js
brianloveswords/johnny-five
1
15992412
var inspect = require("util").inspect, path = require("path"); module.exports = function(grunt) { var task = grunt.task; var file = grunt.file; var utils = grunt.utils; var log = grunt.log; var verbose = grunt.verbose; var fail = grunt.fail; var option = grunt.option; var config = grunt.config; var template = grunt.template; var _ = utils._; var templates = { doc: _.template( file.read("tpl/.docs.md") ), img: _.template( file.read("tpl/.img.md") ), fritzing: _.template( file.read("tpl/.fritzing.md") ), doclink: _.template( file.read("tpl/.readme.doclink.md") ), readme: _.template( file.read("tpl/.readme.md") ) }; // Project configuration. grunt.initConfig({ pkg: "<json:package.json>", docs: { files: ["eg/**/*.js"] }, test: { files: ["test/board.js"] }, lint: { files: ["grunt.js", "lib/!(johnny-five)**/*.js", "test/**/*.js", "eg/**/*.js"] }, watch: { files: "<config:lint.files>", tasks: "default" }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, node: true, strict: false, es5: true }, globals: { exports: true } } }); // Default task. grunt.registerTask("default", "lint test"); grunt.registerMultiTask("docs", "generate simple docs from examples", function() { // Concat specified files. var files = file.expandFiles( this.file.src ), readme = []; files.forEach(function( filepath ) { var values, eg = file.read( filepath ), md = filepath.replace("eg", "docs").replace(".js", ".md"), png = filepath.replace("eg", "docs/breadboard").replace(".js", ".png"), fritz = filepath.replace("eg", "docs/breadboard").replace(".js", ".fzz"), title = filepath, fritzfile, fritzpath; // Generate a title string from the file name [ [ /^.+\//, "" ], [ /\.js/, "" ], [ /\-/g, " " ] ].forEach(function( args ) { title = "".replace.apply( title, args ); }); fritzpath = fritz.split("/"); fritzfile = fritzpath[ fritzpath.length - 1 ]; // Modify code in example to appear as it would if installed via npm eg = eg.replace("../lib/johnny-five.js", "johnny-five"); values = { title: _.titleize(title), example: eg, file: md, breadboard: path.existsSync(png) ? templates.img({ png: png }) : "", fritzing: path.existsSync(png) ? templates.fritzing({ fritzfile: fritzfile, fritz: fritz }) : "" }; // Write the file to /docs/* file.write( md, templates.doc(values) ); // Push a rendered markdown link into the readme "index" readme.push( templates.doclink(values) ); }); // Write the readme with doc link index file.write( "README.md", templates.readme({ doclinks: readme.join("") }) ); log.writeln("Docs created."); }); };
1.265625
1
server/publications/other.js
alagiboy/dalil_app
0
15992420
Meteor.publish('invites', function (userSlug){ var currentUser = Meteor.users.findOne(this.userId); if (currentUser && canView(currentUser) && ( isAdmin(currentUser) || currentUser.slug === userSlug )) { var user = Meteor.users.findOne({slug: userSlug}); return Invites.find({invitingUserId: user._id}); } else { return []; } });
1.078125
1
recipes/JavaScript/577634_Post_to_Pastebincom/recipe-577634.js
tdiprima/code
2,023
15992428
var pastebin = { post : function() { var selection = ko.views.manager.currentView.selection, lang = this.ko2pastebinLanguage(), properties, m, hop = Object.hasOwnProperty, url = [], xhr, response; if (selection == "") { return; } properties = { 'format' : lang, 'code' : selection, 'name' : ko.interpolate.interpolateString('%f', false, 'Filename'), 'expire_date' : "1D", // {N: never, 10M: 10 minutes, 1H: 1 hour, 1D: 1 day, 1M: 1 month} 'subdomain' : "subdomain", 'private' : 1, // 0: public, 1: private, '' : 'Send' }; for (m in properties) { if (hop.call(properties, m)) { url.push([ 'paste', m ? '_' + m : '', '=', encodeURIComponent(properties[m]) ].join('')); } } xhr = new XMLHttpRequest(); xhr.open("post", "http://pastebin.com/api_public.php", false); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(url.join('&')); response = this.getReturnURL(xhr); this.copyText(response); ko.statusBar.AddMessage("Url " + response + " copied on clipboard using lang " + lang, "pastebin_macro", 10000, true) }, getReturnURL : function(xhr) { return xhr.responseText; }, copyText : function(str) { Components.classes["@mozilla.org/widget/clipboardhelper;1"] .getService(Components.interfaces.nsIClipboardHelper) .copyString(str); }, ko2pastebinLanguage : function() { var language, langMap = { 'ABAP' : 'abap', 'ASM (NASM based)' : 'asm', 'ASP' : 'asp', 'ActionScript' : 'actionscript', 'Ada' : 'ada', 'Apache Log File' : 'apache', 'AppleScript' : 'applescript', 'AutoIt' : 'autoit', 'BNF' : 'bnf', 'Bash' : 'bash', 'Blitz Basic' : 'blitzbasic', 'C for Macs' : 'c_mac', 'C#' : 'csharp', 'C' : 'c', 'C++' : 'cpp', 'CAD DCL' : 'caddcl', 'CAD Lisp' : 'cadlisp', 'CSS' : 'css', 'ColdFusion' : 'cfm', 'D' : 'd', 'DOS' : 'dos', 'Delphi' : 'delphi', 'Diff' : 'diff', 'Eiffel' : 'eiffel', 'Erlang' : 'erlang', 'Fortran' : 'fortran', 'FreeBasic' : 'freebasic', 'Game Maker' : 'gml', 'Genero' : 'genero', 'Groovy' : 'groovy', 'HTML' : 'html4strict', 'Haskell' : 'haskell', 'INI file' : 'ini', 'Inno Script' : 'inno', 'Java' : 'java', 'JavaScript' : 'javascript', 'Latex' : 'latex', 'Linden Scripting Language' : 'lsl2', 'Lisp' : 'lisp', 'Lua' : 'lua', 'M68000 Assembler' : 'm68k', 'MPASM' : 'mpasm', 'MatLab' : 'matlab', 'MySQL' : 'mysql', 'NullSoft Installer' : 'nsis', 'OCaml' : 'ocaml', 'Objective C' : 'objc', 'Openoffice.org BASIC' : 'oobas', 'Oracle 8' : 'oracle8', 'PHP' : 'php', 'PL/SQL' : 'plsql', 'Pascal' : 'pascal', 'Perl' : 'perl', 'Python' : 'python', 'QBasic/QuickBASIC' : 'qbasic', 'Rails' : 'rails', 'Robots' : 'robots', 'Ruby' : 'ruby', 'SQL' : 'sql', 'Scheme' : 'scheme', 'Smalltalk' : 'smalltalk', 'Smarty' : 'smarty', 'TCL' : 'tcl', 'Text' : 'text', 'VB.NET' : 'vbnet', 'VisualBasic' : 'vb', 'VisualFoxPro' : 'visualfoxpro', 'XML' : 'xml', 'XUL' : 'xml', 'Z80 Assembler' : 'z80', 'mIRC' : 'mirc', 'unrealScript' : 'unreal' }; language = langMap[ko.views.manager.currentView.document.language]; if (!language) { return "text"; } return language; } }; pastebin.post();
1.507813
2
packages/curriculum-compiler-string/plugins/question/headline.js
enkidevs/curriculum-processors
5
15992436
const unified = require('unified'); const markdown = require('../markdown'); module.exports = function questionHeadline() { const { Compiler } = this; if (Compiler) { const { visitors } = Compiler.prototype; if (visitors) { visitors.questionHeadline = function visitQuestionHeadline(qh) { const content = unified().use(markdown).stringify({ type: 'root', children: qh.children, }); return `### ${content}`; }; } } };
1.226563
1
src/utils/errors.js
fredriklindberg/exposr-cli
1
15992444
class CustomError extends Error { constructor(code, message) { super(); this.code = `${code}`; this.errno = code; this.message = message || this.code; } } export default CustomError; export class ClientError extends Error { constructor(code, detailed) { super(code); this.code = code; this.detailed = detailed instanceof Array ? detailed.join(', ') : detailed; const m = {}; m[SERVER_ERROR_TUNNEL_NOT_FOUND] = 'Tunnel not found'; m[SERVER_ERROR_TUNNEL_NOT_CONNECTED] = 'Tunnel not connected'; m[SERVER_ERROR_TUNNEL_ALREADY_CONNECTED] = 'Tunnel already connected'; m[SERVER_ERROR_TUNNEL_HTTP_INGRESS_DISABLED] = 'HTTP ingress not enabled for tunnel'; m[SERVER_ERROR_TUNNEL_TRANSPORT_REQUEST_LIMIT] = 'Tunnel transport concurrent connection limit'; m[SERVER_ERROR_TUNNEL_UPSTREAM_CON_REFUSED] = 'Upstream connection refused'; m[SERVER_ERROR_TUNNEL_INGRESS_BAD_ALT_NAMES] = detailed ? `The altname ${detailed} can not be configured for this tunnel` : 'Ingress altname can not be configured'; m[SERVER_ERROR_HTTP_INGRESS_REQUEST_LOOP] = 'Request loop at ingress'; m[SERVER_ERROR_UNKNOWN_ERROR] = 'Unknown server error'; m[SERVER_ERROR_BAD_INPUT] = detailed ? `Bad input: ${detailed}` : 'Bad input'; m[SERVER_ERROR_AUTH_NO_ACCESS_TOKEN] = 'Access token missing'; m[SERVER_ERROR_AUTH_PERMISSION_DENIED] = 'Permission denied'; m[ERROR_UNKNOWN] = 'Unknown client error'; m[ERROR_ACCOUNT_REGISTRATION_DISABLED] = 'Account registration not enabled'; m[ERROR_SERVER_TIMEOUT] = 'Timeout'; m[ERROR_NO_ACCOUNT] = 'No account was provided'; m[ERROR_NO_TUNNEL] = 'No tunnel was provided'; m[ERROR_NO_TUNNEL_ENDPOINT] = 'No tunnel endpoint available'; this.message = m[code] || 'Unknown error'; } } // Error ENUMs from exposr-server export const SERVER_ERROR_TUNNEL_NOT_FOUND = 'TUNNEL_NOT_FOUND'; export const SERVER_ERROR_TUNNEL_NOT_CONNECTED = 'TUNNEL_NOT_CONNECTED'; export const SERVER_ERROR_TUNNEL_ALREADY_CONNECTED = 'TUNNEL_ALREADY_CONNECTED'; export const SERVER_ERROR_TUNNEL_HTTP_INGRESS_DISABLED = 'TUNNEL_HTTP_INGRESS_DISABLED'; export const SERVER_ERROR_TUNNEL_TRANSPORT_REQUEST_LIMIT = 'TUNNEL_TRANSPORT_REQUEST_LIMIT'; export const SERVER_ERROR_TUNNEL_TRANSPORT_CON_TIMEOUT = 'TUNNEL_TRANSPORT_CON_TIMEOUT'; export const SERVER_ERROR_TUNNEL_UPSTREAM_CON_REFUSED = 'TUNNEL_UPSTREAM_CON_RESET'; export const SERVER_ERROR_TUNNEL_UPSTREAM_CON_FAILED = 'TUNNEL_UPSTREAM_CON_FAILED'; export const SERVER_ERROR_TUNNEL_INGRESS_BAD_ALT_NAMES = 'TUNNEL_INGRESS_BAD_ALT_NAMES'; export const SERVER_ERROR_HTTP_INGRESS_REQUEST_LOOP = 'HTTP_INGRESS_REQUEST_LOOP'; export const SERVER_ERROR_UNKNOWN_ERROR = 'UNKNOWN_ERROR'; export const SERVER_ERROR_BAD_INPUT = 'BAD_INPUT'; export const SERVER_ERROR_AUTH_NO_ACCESS_TOKEN = 'AUTH_NO_TOKEN'; export const SERVER_ERROR_AUTH_PERMISSION_DENIED = 'PERMISSION_DENIED'; // Client error codes export const ERROR_UNKNOWN = 0; export const ERROR_ACCOUNT_REGISTRATION_DISABLED = 1; export const ERROR_SERVER_TIMEOUT = 2; export const ERROR_NO_ACCOUNT = 3; export const ERROR_NO_TUNNEL = 4; export const ERROR_NO_TUNNEL_ENDPOINT = 5; export const ERROR_NO_TUNNEL_UPSTREAM = 6;
1.539063
2
src/communication/component.js
vendoor/vendoor-server
0
15992452
const comlink = require('./comlink/comlink') const config = require('../config/config') const fastify = require('./fastify/fastify') module.exports = { name: 'communication', dependencies: ['database'], async setup () { await fastify.setup() await comlink.setup(fastify.instance().server) const rpc = require('./rpc') rpc.setup(comlink.rpc()) const messaging = require('./messaging') messaging.setup(comlink.messaging()) const notification = require('./notification') notification.setup(comlink.notification()) return { fastify: fastify.instance(), rpc, messaging, notification, listen } async function listen () { await fastify.instance().listen(config.get('server.port')) } }, async teardown () { await comlink.teardown() await fastify.teardown() } }
0.84375
1
src/hooks/Database.test.js
jacobpatterson1549/macro-measure
0
15992460
import { waitFor } from '@testing-library/react'; import { renderHook } from '@testing-library/react-hooks' import { createHandlers, useItem, useItems } from './Database'; import { GROUPS, WAYPOINTS, createItem, readItem, readItems, updateItem, deleteItem, moveItemUp, moveItemDown } from '../utils/Database'; import { View } from '../utils/View'; jest.mock('../utils/Database'); describe('Database', () => { const db = '[mock database]'; describe('createHandlers', () => { beforeEach(() => { jest.resetAllMocks(); }); const testData = { objectStoreNames: [GROUPS, WAYPOINTS], viewTypes: [View.isGroup, View.isWaypoint], handlerParams: { // [inParams, outParams] createStart: [[], [Number.MAX_SAFE_INTEGER]], // max integer to make it clear that new item is after others createEnd: [['item'], ['item']], read: [[{ id: 'id' }], ['id']], list: [[], []], updateStart: [[{ id: 'id' }], ['id']], updateEnd: [['item'], ['item']], deleteStart: [[{ id: 'id' }], ['id']], deleteEnd: [[{ id: 'id' }], ['id']], moveUp: [['item'], ['item']], moveDown: [['item'], ['item']], }, expectedViews: { createStart: [View.Group_Create, View.Waypoint_Create], createEnd: [View.Group_Read, View.Waypoint_Read], read: [View.Group_Read, View.Waypoint_Read], list: [View.Group_List, View.Waypoint_List], updateStart: [View.Group_Update, View.Waypoint_Update], updateEnd: [View.Group_Read, View.Waypoint_Read], deleteStart: [View.Group_Delete, View.Waypoint_Delete], deleteEnd: [View.Group_List, View.Waypoint_List], moveUp: [View.Group_List, View.Waypoint_List], moveDown: [View.Group_List, View.Waypoint_List], }, expectedSetItemIDActions: [ 'createStart', 'read', 'updateStart', 'deleteStart', ], expectedDatabaseActions: { createEnd: createItem, updateEnd: updateItem, deleteEnd: deleteItem, moveUp: moveItemUp, moveDown: moveItemDown, }, }; describe.each(testData.objectStoreNames.map((objectStoreName, index) => [objectStoreName, index]))('%s', (objectStoreName, index) => { it.each(Object.entries(testData.expectedViews))('should set correct view when calling %s', (handlerFuncName, views) => { const setItemID = jest.fn(); const setView = jest.fn(); const getViewType = testData.viewTypes[index]; const params = testData.handlerParams[handlerFuncName]; const [inParams] = params; const handlers = createHandlers(db, objectStoreName, setItemID, setView, getViewType); const expected = views[index]; handlers[handlerFuncName](...inParams); expect(setView).toBeCalledWith(expected); }); it.each(testData.expectedSetItemIDActions)('should setItemID when calling %s', (handlerFuncName) => { const setItemID = jest.fn(); const setView = jest.fn(); const getViewType = testData.viewTypes[index]; const params = testData.handlerParams[handlerFuncName]; const [inParams, outParams] = params const handlers = createHandlers(db, objectStoreName, setItemID, setView, getViewType); const expected = outParams; handlers[handlerFuncName](...inParams); expect(setItemID).toBeCalledWith(...expected); }); it.each(Object.entries(testData.expectedDatabaseActions))('should call %s with correct params', (handlerFuncName, databaseFunc) => { const setItemID = jest.fn(); const setView = jest.fn(); const getViewType = testData.viewTypes[index]; const params = testData.handlerParams[handlerFuncName]; const [inParams, outParams] = params const handlers = createHandlers(db, objectStoreName, setItemID, setView, getViewType); const expected = [db, objectStoreName, ...outParams]; handlers[handlerFuncName](...inParams); expect(databaseFunc).toBeCalledWith(...expected); }); it('should also setID for create-end actions', async () => { const expected = 'newID'; createItem.mockReturnValue(expected) const handlerFuncName = 'createEnd'; const setItemID = jest.fn(); const setView = jest.fn(); const getViewType = testData.viewTypes[index]; const inParam = { name: 'name' }; const handlers = createHandlers(db, objectStoreName, setItemID, setView, getViewType); handlers[handlerFuncName](inParam); await waitFor(() => expect(setItemID).toBeCalledWith(expected)); }); }); }); describe('useDatabase', () => { beforeEach(() => { jest.resetAllMocks(); }); describe('useItem', () => { it('should have have item', async () => { const objectStoreName = 'os1'; const filter = 'f1'; const expected = 'value1' readItem.mockReturnValue(expected); const { result } = renderHook(() => useItem(db, objectStoreName, filter)); expect(result.current[0]).toBeFalsy(); await waitFor(() => expect(readItem).toBeCalledWith(db, objectStoreName, filter)); const value = result.current[0]; expect(value).toBe(expected); }); }); describe('useItems', () => { it('should have have items', async () => { const objectStoreName = 'os2'; const filter = 'f2'; const expected = 'value2' readItems.mockReturnValue(expected); const { result } = renderHook(() => useItems(db, objectStoreName, filter)); await waitFor(() => expect(readItems).toBeCalledWith(db, objectStoreName, filter)); const value = result.current[0]; expect(value).toBe(expected); }); it('should have have updated items when reloadValue is triggered', async () => { const objectStoreName = 'os3'; const filter = 'f3'; const initialItems = 'value3'; // will be overwritten after button is clicked const expected = 'value4'; readItems.mockReturnValueOnce(initialItems).mockReturnValueOnce(expected); const { result } = renderHook(() => useItems(db, objectStoreName, filter)); const reloadValue = result.current[1]; await waitFor(reloadValue); const value = result.current[0]; expect(value).toBe(expected); }); it('should not cause unmounted component to re-render', () => { const objectStoreName = 'os4'; const filter = 'f4'; let lateResolve; const longRead = new Promise((resolve) => lateResolve = resolve); readItems.mockReturnValue(longRead); const { unmount } = renderHook(() => useItems(db, objectStoreName, filter)); unmount(); // the test will throw an error from the late resolve lateResolve(); }); }); }); });
1.71875
2
todo-ui/js/r/klass/events.js
revnode/todo
0
15992468
var Events = new Class({ $events: {}, removeOn: function(string) { return string.replace(/^on([A-Z])/, function(full, first) { return first.toLowerCase(); }); }, addEvent: function(type, fn, internal) { type = this.removeOn(type); this.$events[type] = (this.$events[type] || []).include(fn); if(internal) { fn.internal = true; } return this; }, fireEvent: function(type, args, delay) { type = this.removeOn(type); var events = this.$events[type]; if(!events) { return this; } args = Array.from(args); events.forEach(function(fn) { if(delay) { fn.delay(delay, this, args); } else { fn.apply(this, args); } }, this); return this; }, removeEvent: function(type, fn) { type = this.removeOn(type); var events = this.$events[type]; if(events && !fn.internal) { var index = events.indexOf(fn); if(index != -1) { delete events[index]; } } return this; }, removeEvents: function(events) { var type; if(is_object(events)) { for(type in events) { this.removeEvent(type, events[type]); } return this; } if(events) { events = this.removeOn(events); } for(type in this.$events) { if(events && events != type) { continue; } for(var fns = this.$events[type], i = fns.length; i--;) { if(i in fns) { this.removeEvent(type, fns[i]); } } } return this; } });
1.671875
2
test/fixtures/importNonLiteralsSrc/actual.js
gvelo/babel-plugin-transform-react-jsx-img-import
37
15992476
var base = './assets/'; var profile = <div> <img src={base+"avatar.png"} className="profile" /> </div>;
0.621094
1
packages/material-ui/src/Radio/Radio.test.js
josiahbryan/material-ui
3
15992484
import React from 'react'; import { assert } from 'chai'; import { getClasses, createMount } from '@material-ui/core/test-utils'; import describeConformance from '@material-ui/core/test-utils/describeConformance'; import Radio from './Radio'; import IconButton from '../IconButton'; describe('<Radio />', () => { let classes; let mount; before(() => { classes = getClasses(<Radio />); // StrictModeViolation: uses Switchbase mount = createMount({ strict: false }); }); after(() => { mount.cleanUp(); }); describeConformance(<Radio />, () => ({ classes, inheritComponent: IconButton, mount, refInstanceof: window.HTMLSpanElement, skip: ['componentProp'], })); describe('styleSheet', () => { it('should have the classes required for SwitchBase', () => { assert.strictEqual(typeof classes.root, 'string'); assert.strictEqual(typeof classes.checked, 'string'); assert.strictEqual(typeof classes.disabled, 'string'); }); }); describe('prop: unchecked', () => { it('should render an unchecked icon', () => { const wrapper = mount(<Radio />); assert.strictEqual(wrapper.find('svg[data-mui-test="RadioButtonUncheckedIcon"]').length, 1); }); }); describe('prop: checked', () => { it('should render a checked icon', () => { const wrapper = mount(<Radio checked />); assert.strictEqual(wrapper.find('svg[data-mui-test="RadioButtonCheckedIcon"]').length, 1); }); }); });
1.5625
2
backend/js/components/agenda/agenda.api.js
faustofjunqueira/hack-timer
1
15992492
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const express_1 = require("express"); const agenda_service_1 = require("./agenda.service"); function configureAgendaRouter(app) { const router = express_1.Router(); router.get('/', async (req, res) => res.json(await agenda_service_1.getActivities())); router.delete('/', async (req, res) => res.json(await agenda_service_1.resetActivities())); router.put('/', async (req, res) => { res.json(await agenda_service_1.saveActivities(req.body)); }); return app.use('/agenda', router); } exports.configureAgendaRouter = configureAgendaRouter;
1.03125
1
src/pages/marketing.js
lizzkats/launchpad-gatsbyjs
0
15992500
import React from "react"; import Link from "gatsby-link"; import NavBar from '../components/navbar.js'; import Category from '../components/category.js'; import MarketingCards from '../components/marketingcards.js'; export default () => ( <div> <NavBar /> <Category currentCategory="Marketing"/> <MarketingCards /> </div> );
0.824219
1
web/app/themes/ixda_vina/Gulpfile.js
felipelavinz/ixda-vina
0
15992508
;(function(){ 'use strict'; var gulp = require('gulp'), sass = require('gulp-sass'), livereload = require('gulp-livereload'), gulpicon = require('gulpicon/tasks/gulpicon'), glob = require('glob'), sourcemaps = require('gulp-sourcemaps'); gulp.task('sass', function(){ return gulp.src('./style/style.scss') .pipe( sourcemaps.init() ) .pipe( sass().on('error', sass.logError) ) .pipe( sourcemaps.write('.') ) .pipe( gulp.dest('./style/') ) .pipe( livereload() ); }); gulp.task('editor_style', function(){ return gulp.src('./style/editor-style.scss') .pipe( sourcemaps.init() ) .pipe( sass().on('error', sass.logError) ) .pipe( sourcemaps.write('.') ) .pipe( gulp.dest('./style/') ) .pipe( livereload() ); }); gulp.task('svgmin', function(){ return gulp.src('./img/src/*.svg') .pipe(svgmin()) .pipe(gulp.dest('./img/dist')); }); var config = require('./node_modules/gulpicon/example/config.js'); config.dest = 'img/output'; var files = glob.sync('img/src/*.svg'); gulp.task('icons', gulpicon(files, config)); // gulp.task('iconify', function(){ // iconify({ // src : './img/src/*.svg', // pngOutput : './img/output/png', // scssOutput : './style', // cssOutput : './style', // defaultWidth : '36px', // defaultHeight : '36px' // }); // }); gulp.task('sass:watch', function(){ livereload.listen(); gulp.watch( './style/**/*.scss', ['sass'] ); }); gulp.task('default', ['sass:watch']); gulp.task('public', ['sass:watchPublic']); })();
1.1875
1
client/app/containers/WishList/actions.js
mohamedsamara/MERN-Ecommerce
0
15992516
/* * * WishList actions * */ import { success, warning } from 'react-notification-system-redux'; import axios from 'axios'; import { FETCH_WISHLIST, SET_WISHLIST_LOADING } from './constants'; import handleError from '../../utils/error'; export const updateWishlist = (isLiked, productId) => { return async (dispatch, getState) => { try { if (getState().authentication.authenticated === true) { const response = await axios.post(`/api/wishlist`, { isLiked, product: productId }); const successfulOptions = { title: `${response.data.message}`, position: 'tr', autoDismiss: 1 }; if (response.data.success === true) { dispatch(success(successfulOptions)); dispatch(fetchWishlist()); } } else { const retryOptions = { title: `Please login to wishlist a product`, position: 'tr', autoDismiss: 1 }; dispatch(warning(retryOptions)); } } catch (error) { handleError(error, dispatch); } }; }; // fetch wishlist api export const fetchWishlist = () => { return async (dispatch, getState) => { try { dispatch({ type: SET_WISHLIST_LOADING, payload: true }); const response = await axios.get(`/api/wishlist`); dispatch({ type: FETCH_WISHLIST, payload: response.data.wishlist }); } catch (error) { handleError(error, dispatch); } finally { dispatch({ type: SET_WISHLIST_LOADING, payload: false }); } }; };
1.492188
1
tasks/utils/repos/getHubRepos.js
keg-hub/keg-hub
0
15992524
const path = require('path') const { scripts } = require('../../paths') const { getRepoPaths } = require(path.join(scripts, 'postinstall/getRepoPaths')) const { isFunc, pickKeys, eitherArr } = require('@keg-hub/jsutils') /** * Gets the repo name, location and package json for all repos in the /repos folder * @param {Object} args.params - Pre-Parsed options array as an object * * @returns {Object} - Repos as (key)folder => (value) object with the repos name, location and package.json */ const getHubRepos = async ({ context }) => { const repos = getRepoPaths() const filter = eitherArr(context, [context]) return Object.entries(repos) .reduce((acc, [repo, location]) => { try { // If a filter is passed, then check if the repo matches const include = filter.find(name => repo.includes(name)) // If not repo match, then return if(filter[0] !== 'all' && !include) return acc const package = require(path.join(location, 'package.json')) acc[repo] = { repo, location, package } } catch(err){} return acc }, {}) } module.exports = { getHubRepos }
1.484375
1
client/src/components/Footer.js
cryslebron/TeamsCapacity2
0
15992532
import React from "react"; import { MDBContainer, MDBFooter } from "mdbreact"; const FooterPage = () => { return ( <MDBFooter color="blue" className="font-small pt-4 mt-4"> <MDBContainer fluid className="text-center text-md-left"> </MDBContainer> <div className="footer-copyright text-center py-3"> <MDBContainer fluid> &copy; {new Date().getFullYear()} Copyright: <NAME> - Capacity Planner <a href="https://www.TeamsCapacity.com" target="_blank" rel="noopener noreferrer">TeamsCapacity.com </a> </MDBContainer> </div> </MDBFooter> ); } export default FooterPage;
1.09375
1
src/views/index-sections/Footer.js
juliekimkk/hompage-final
0
15992540
import React, { useEffect } from "react"; import Aos from "aos"; import "aos/dist/aos.css"; import styled, { keyframes } from "styled-components"; const MarketingSecondOneline = styled.div` marginTop: "130px", // border: "solid 1px black", position: "relative", width: "80%", display: "inline-block", marginLeft: "10%", marginRight: "10%", `; const Footer = () => { React.useEffect(() => { Aos.init({}); }, []); return ( <> {/* <div className="divider" style={{ marginTop: "30px" }}></div> {/* background: "#f5f5f7", */}{" "} <div class="footer" style={{ height: "1000px", padding: "0px" }}> <div style={{ height: "200px" }}></div> <div className="marketing" style={{ fontFamily: "Helvetica Neue, Arial, sans-serif", maxWidth: "1600px", margin: "0 auto", }} > <h2 style={{ fontWeight: "500", lineHeight: "1.4", fontSize: "33px", textAlign: "center", fontFamily: "NotoKR San-Serif", }} data-aos="fade-up" data-aos-offset="200" data-aos-duration="350" data-aos-easing="ease-in-out" > 프로젝트별 명쾌한 자사, 경쟁사 분석 및 <br /> IT 트렌드 반영을 통해 고객사의 문제를 해결하고, <br /> 비지니스 성장을 돕고 있습니다. </h2> <div style={{ height: "200px" }}></div> {/*첫번째 */} <div className="marketing_second_onebox" style={{ // border: "solid green 1px", position: "relative", display: "inline-block", margin: "0 auto", // padding: "1%", width: "25%", textAlign: "center", }} data-aos="fade-up" data-aos-offset="200" data-aos-duration="350" data-aos-easing="ease-in-out" > <img className="clickimage" src={require("assets/img/1.5x/handout.png")} style={{ width: "10%", // display: "block", align: "center", justifyContent: "center", position: "relative", marginBottom: "8px", }} ></img> <h4 style={{ // display: "block", height: "42px", margin: "0", fontWeight: "600", fontSize: "27px", textAlign: "center", transform: "translate(50%)", width: "50%", }} > {/* <img className="clickimage" src={require("assets/img/1.5x/handout.png")} style={{ width: "10%" }} ></img> */} 전략 · 기획 </h4> <div className="company_marketing_detail" style={{ height: "130px", textAlign: "center", marginTop: "20px", color: "#878890", }} > 사전 인터뷰, 요구사항 분석 단계를 통해 <br /> 고객사의 프로젝트를 파악하고, <br /> 시사점을 도출해 프로젝트 전략과 </div> <div style={{ display: "block;", width: "1px", backgroundColor: "#eee", position: "absolute", top: "0", bottom: "0", left: "100%", }} ></div> </div> {/*두번째 */} <div className="marketing_second_onebox" style={{ // border: "solid green 1px", position: "relative", display: "inline-block", margin: "0 auto", // padding: "1%", width: "25%", textAlign: "center", }} > <img className="clickimage" src={require("assets/img/1.5x/design.png")} style={{ width: "10%", // display: "block", align: "center", justifyContent: "center", position: "relative", marginBottom: "8px", }} data-aos="fade-up" data-aos-delay="600" data-aos-duration="350" data-aos-easing="ease-in-out" ></img> <h4 style={{ // display: "block", height: "42px", margin: "0", fontWeight: "600", fontSize: "27px", textAlign: "center", transform: "translate(50%)", width: "50%", }} data-aos="fade-down" data-aos-delay="600" data-aos-duration="350" data-aos-easing="ease-in-out" > 디자인 </h4> <div className="company_marketing_detail" style={{ height: "130px", textAlign: "center", marginTop: "20px", color: "#878890", }} data-aos="fade-up" data-aos-delay="600" data-aos-duration="350" data-aos-easing="ease-in-out" > 최신 트렌드 디자인을 적용 및 <br /> 사용자 편의성을 증대할 수 있는 <br /> 매력적인 디자인을 제공해 드리고 있습니다. </div> <div style={{ display: "block;", width: "1px", backgroundColor: "#eee", position: "absolute", top: "0", bottom: "0", left: "100%", }} ></div> </div> {/*세번째 */} <div className="marketing_second_onebox" style={{ // border: "solid green 1px", position: "relative", display: "inline-block", margin: "0 auto", // padding: "1%", width: "25%", textAlign: "center", }} > <img className="clickimage" src={require("assets/img/1.5x/widget.png")} style={{ width: "10%", // display: "block", align: "center", justifyContent: "center", position: "relative", marginBottom: "8px", // margin: "0 auto", }} data-aos="fade-up" data-aos-delay="900" data-aos-duration="350" data-aos-easing="ease-in-out" ></img> <h4 style={{ display: "block", height: "42px", margin: "0", fontWeight: "700", fontSize: "27px", textAlign: "center", // backgroundColor: "#F1F1F1", transform: "translate(50%)", width: "50%", }} data-aos="fade-up" data-aos-delay="900" data-aos-duration="350" data-aos-easing="ease-in-out" > 개발 · 구현 </h4> <div className="company_marketing_detail" style={{ height: "130px", textAlign: "center", marginTop: "20px", color: "#878890", }} data-aos="fade-up" data-aos-delay="900" data-aos-duration="350" data-aos-easing="ease-in-out" > 사용자 및 관리자 목적 중심으로 개발하며, <br /> 유연한 내부 시스템 연계, 인프라 재정립을 통해 <br /> 성공적으로 오픈할 수 있도록 구현합니다. <br /> </div> <div style={{ display: "block;", width: "1px", backgroundColor: "#eee", position: "absolute", top: "0", bottom: "0", left: "100%", }} ></div> </div> {/*네번째 */} <div className="marketing_second_onebox" style={{ // border: "solid green 1px", position: "relative", display: "inline-block", margin: "0 auto", // padding: "1%", width: "25%", textAlign: "center", }} > <img className="clickimage" src={require("assets/img/1.5x/video.png")} style={{ width: "10%", // display: "block", align: "center", justifyContent: "center", position: "relative", marginBottom: "8px", // margin: "0 auto", }} data-aos="fade-up" data-aos-delay="1200" data-aos-duration="350" data-aos-easing="ease-in-out" ></img> <h4 style={{ display: "block", height: "42px", margin: "0", fontWeight: "600", fontSize: "27px", textAlign: "center", // backgroundColor: "rgb(241 241 241 / 73%)", transform: "translate(50%)", width: "50%", }} data-aos="fade-up" data-aos-delay="1200" data-aos-duration="350" data-aos-easing="ease-in-out" > 영상 · 이미지 </h4> <div className="company_marketing_detail" style={{ height: "130px", textAlign: "center", marginTop: "20px", color: "#878890", }} data-aos="fade-up" data-aos-delay="1200" data-aos-duration="350" data-aos-easing="ease-in-out" > 보다 풍부한 기업 및 제품 브랜딩을 위한 <br /> 디지털 이미지 및 영상물을 촬영, 제작하고 있습니다. <br /> 더불어 컨텐츠 사업또한 진행중입니다 </div> </div> </div> <div style={{ height: "300px" }}></div> </div> </> ); }; export default Footer;
1.578125
2
api-client/src/endpoints/createOffersEndpoint.js
f1sh1918/integreat-app
0
15992548
// @flow import OfferModel from '../models/OfferModel' import EndpointBuilder from '../EndpointBuilder' import type { JsonOfferPostType, JsonOfferType } from '../types' import Endpoint from '../Endpoint' export const OFFERS_ENDPOINT_NAME = 'offers' const createPostMap = (jsonPost: JsonOfferPostType): Map<string, string> => { const map = new Map() Object.keys(jsonPost).forEach(key => map.set(key, jsonPost[key])) return map } type ParamsType = { city: string, language: string } export default (baseUrl: string): Endpoint<ParamsType, Array<OfferModel>> => new EndpointBuilder(OFFERS_ENDPOINT_NAME) .withParamsToUrlMapper(params => { return `${baseUrl}/${params.city}/${params.language}/wp-json/extensions/v3/extras` }) .withMapper((json: Array<JsonOfferType>) => json.map( offer => new OfferModel({ alias: offer.alias, title: offer.name, path: offer.url, thumbnail: offer.thumbnail, postData: offer.post ? createPostMap(offer.post) : null }) ) ) .build()
1.359375
1
src/components/List.js
cartifon/grapesjs-blocks-bootstrap4
92
15992556
export const ListBlock = (bm, label) => { bm.add('list', { label: label, category: 'Basic', attributes: {class:'fa fa-list'}, content: { type: 'list' } }); }; export default (domc) => { const defaultType = domc.getType('default'); const defaultModel = defaultType.model; const defaultView = defaultType.view; domc.addType('list', { model: defaultModel.extend({ defaults: Object.assign({}, defaultModel.prototype.defaults, { 'custom-name': 'List', tagName: 'ul', resizable: 1, traits: [ { type: 'select', options: [ {value: 'ul', name: 'No'}, {value: 'ol', name: 'Yes'} ], label: 'Ordered?', name: 'tagName', changeProp: 1 } ].concat(defaultModel.prototype.defaults.traits) }) }, { isComponent: function(el) { if(el && ['UL','OL'].includes(el.tagName)) { return {type: 'list'}; } } }), view: defaultView }); }
1.382813
1
test/index.spec.js
mwinche/each-version
1
15992564
const test = require('ava'); const proxyquire = require('proxyquire'); const sinon = require('sinon'); const ngLatest = { name: 'ng latest', libs: { 'angular': 'latest', 'angular-resource': 'latest', 'angular-cookies': 'latest', 'angular-mocks': 'latest', 'angular-sanitize': 'latest', 'angular-animate': 'latest' } }; const ng1_4_x = { name: 'ng 1.4.x', libs: { 'angular': '1.4.x', 'angular-resource': '1.4.x', 'angular-cookies': '1.4.x', 'angular-mocks': '1.4.x', 'angular-sanitize': '1.4.x', 'angular-animate': '1.4.x' } }; const ng1_5_x = { name: 'ng 1.5.x', libs: { 'angular': '1.5.x', 'angular-resource': '1.5.x', 'angular-cookies': '1.5.x', 'angular-mocks': '1.5.x', 'angular-sanitize': '1.5.x', 'angular-animate': '1.5.x' } }; test('should run through a valid config', t => { const execute = sinon.stub().returns(Promise.resolve({ pass: true })); const check = sinon.stub(); const api = proxyquire('../lib', { './executeAgainstLibs': execute, './eachJsonCheck': check }); const command = `echo du mah testz`; const config = [ ngLatest, ng1_4_x, ng1_5_x ]; return api(command, config) .then(result => { t.true(execute.withArgs(command, ngLatest).calledOnce); t.true(execute.withArgs(command, ng1_4_x).calledOnce); t.true(execute.withArgs(command, ng1_5_x).calledOnce); t.true(check.withArgs(config).calledOnce); t.true(result[0].pass); t.true(result[1].pass); t.true(result[2].pass); }) .catch(err => { t.fail('should not have failed'); }); }); test('report results if one of the executions failed', t => { const execute = sinon.stub(); const check = sinon.stub(); const api = proxyquire('../lib', { './executeAgainstLibs': execute, './eachJsonCheck': check }); const command = `echo du mah testz`; const config = [ ngLatest, ng1_4_x, ng1_5_x ]; execute.withArgs(command, ngLatest).returns(Promise.resolve({ pass: false })); execute.returns(Promise.resolve({ pass: true })); return api(command, config) .then(result => { t.true(execute.withArgs(command, ngLatest).calledOnce); t.true(execute.withArgs(command, ng1_4_x).calledOnce); t.true(execute.withArgs(command, ng1_5_x).calledOnce); t.true(check.withArgs(config).calledOnce); t.false(result[0].pass); t.true(result[1].pass); t.true(result[2].pass); }) .catch(err => { t.fail('should not have failed'); }); }); test('bail when an execution promise rejects (bail setting)', t => { const execute = sinon.stub(); const check = sinon.stub(); const api = proxyquire('../lib', { './executeAgainstLibs': execute, './eachJsonCheck': check }); const command = `echo du mah testz`; const config = [ ngLatest, ng1_4_x, ng1_5_x ]; const message = `Dat thing broke...`; execute.withArgs(command, ng1_4_x).returns(Promise.reject({ pass: false, error: message, command })); execute.returns(Promise.resolve({ pass: true })); return api(command, config) .then(result => { t.fail('should not have passed'); }) .catch(err => { t.false(err.pass); t.is(err.error, message); t.is(err.command, command); }); }); test(`should report failures that didn't reject the promise (fail setting)`, t => { const execute = sinon.stub(); const check = sinon.stub(); const api = proxyquire('../lib', { './executeAgainstLibs': execute, './eachJsonCheck': check }); const command = `echo du mah testz`; const config = [ ngLatest, ng1_4_x, ng1_5_x ]; const message = `Dat thing broke...`; execute.withArgs(command, ng1_4_x).returns(Promise.resolve({ pass: false, error: message, command })); execute.returns(Promise.resolve({ pass: true })); return api(command, config) .then(result => { t.true(result[0].pass); t.false(result[1].pass); t.true(result[2].pass); }) .catch(err => { t.fail('should not have failed'); }); }); test(`should report passing status even if there is an error message (warn setting)`, t => { const execute = sinon.stub(); const check = sinon.stub(); const api = proxyquire('../lib', { './executeAgainstLibs': execute, './eachJsonCheck': check }); const command = `echo du mah testz`; const config = [ ngLatest, ng1_4_x, ng1_5_x ]; const message = `Dat thing broke...`; execute.withArgs(command, ng1_4_x).returns(Promise.resolve({ pass: true, error: message, command })); execute.returns(Promise.resolve({ pass: true })); return api(command, config) .then(result => { t.true(result[0].pass); t.true(result[1].pass); t.true(result[2].pass); t.is(result[1].error, message); t.is(result[1].command, command); }) .catch(err => { t.fail('should not have failed'); }); });
1.367188
1
qml/scripts/ExternalLinks.js
cow-n-berg/sailfishos-daily-comics
6
15992572
/** * Copyright (c) 2015 <NAME> * * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. **/ .pragma library function browse(url) { Qt.openUrlExternally(url) } function mail(email, subject, body) { var subjectText = (subject !== undefined) ? subject : ''; var bodyText = (body !== undefined) ? body : ''; Qt.openUrlExternally("mailto:"+email+"?subject="+subjectText+"&body="+bodyText) }
1.101563
1
__tests__/Manager.test.js
itsclairehi/employee-info-generator
0
15992580
const Manager = require('../lib/Manager') test("office number", ()=>{ const manager = new Manager('bob', 1, '<EMAIL>', 2) expect(manager.officeNumber).toEqual(2) }) test("manager role", ()=>{ const manager = new Manager('bob', 1, '<EMAIL>', 2) expect(manager.getRole()).toBe('Manager') })
1.460938
1
src/specs/controllers/CodeController.spec.js
snippet-io/Backend
3
15992588
jest.mock("../../querybuilders/Code"); jest.mock("../../querybuilders/Staring"); jest.mock("../../external/GithubApp"); jest.mock("../../authentication"); const { AccessToken } = require("../../authentication"); const controllers = require("../../controllers/CodeController"); const { BadRequest, NotFound } = require("../../errors/HttpException"); const { CodeBuilder } = require("../../models/Code"); const FakeRequestBuilder = require("../FakeRequest"); const FakeResponse = require("../FakeResponse"); const CodeQueryBuilder = require("../../querybuilders/Code"); const StaringQueryBuilder = require("../../querybuilders/Staring"); describe("CodeController 단위 테스트", () => { beforeEach(() => { CodeQueryBuilder.mockClear(); StaringQueryBuilder.mockClear(); }); it("code 생성", async () => { AccessToken.mockImplementation(() => { return { getUserId: () => 1, }; }); AccessToken.issue = jest.fn().mockImplementation(() => new AccessToken()); const req = new FakeRequestBuilder() .setBody({ title: "title", content: "content", language: "language", description: "description", }) .setAuth(await AccessToken.issue("access_token")) .build(); const res = new FakeResponse(); await controllers.createCode(req, res); const codes = await new CodeQueryBuilder().findAll().excute(); const expected_new_code = new CodeBuilder("title", "language", 1) .setContent("content") .setDescription("description") .build(); expected_new_code.description = undefined; expect( codes.map((code) => { code.id = undefined; code.description = undefined; code.created_datetime = undefined; return code; }) ).toContainEqual(expected_new_code); expect(res.getStatus()).toBe(201); }); it("code 생성 실패(400) - content 없음", async () => { AccessToken.mockImplementation(() => { return { getUserId: () => 1, }; }); AccessToken.issue = jest.fn().mockImplementation(() => new AccessToken()); const req = new FakeRequestBuilder() .setBody({ title: "title", language: "language", description: "description", }) .setAuth(await AccessToken.issue("access_token")) .build(); const res = new FakeResponse(); await expect(controllers.createCode(req, res)).rejects.toThrow(BadRequest); }); it("code 삭제", async () => { AccessToken.mockImplementation(() => { return { getUserId: () => 1, }; }); AccessToken.issue = jest.fn().mockImplementation(() => new AccessToken()); const req = new FakeRequestBuilder() .setParams({ id: 1 }) .setAuth(AccessToken.issue()) .build(); await controllers.deleteCode(req); const codes = await new CodeQueryBuilder().findAll().excute(); expect(codes).toEqual([]); }); it("code 삭제 실패(400)", async () => { await expect( controllers.deleteCode(new FakeRequestBuilder().build()) ).rejects.toThrow(BadRequest); }); it("code 삭제 실패(404) - 해당 code를 찾을 수 없음", async () => { AccessToken.mockImplementation(() => { return { getUserId: () => 1, }; }); AccessToken.issue = jest.fn().mockImplementation(() => new AccessToken()); const req = new FakeRequestBuilder() .setParams({ id: 2 }) .setAuth(AccessToken.issue()) .build(); await expect(controllers.deleteCode(req)).rejects.toThrow(NotFound); }); it("code 수정", async () => { AccessToken.mockImplementation(() => { return { getUserId: () => 1, }; }); AccessToken.issue = jest.fn().mockImplementation(() => new AccessToken()); const req = new FakeRequestBuilder() .setAuth(AccessToken.issue("access_token")) .setParams({ id: 1 }) .setBody({ title: "수정된 코드", content: "내", language: "c++", }) .build(); await controllers.modifyCode(req, new FakeResponse()); const codes = await new CodeQueryBuilder().findAll().excute(); expect( codes.map((code) => { code.created_datetime = undefined; return code; }) ).toEqual([ new CodeBuilder("수정된 코드", "c++", 1) .setContent("내") .setDescription("설명") .setId(1) .build(), ]); }); it("code 수정 실패(400)", async () => { await expect( controllers.modifyCode(new FakeRequestBuilder().build()) ).rejects.toThrow(BadRequest); }); it("code list 얻기", async () => { const req = new FakeRequestBuilder().setQuery({ limit: 5, offset: 0 }); const codes = await controllers.getCodes(req, new FakeResponse()); expect(codes.map((c) => c.toJSON())).toEqual([ { id: 1, title: "코드제목", content: "내용", language: "rust", description: "설명", author: 1, created_datetime: "2021-04-19T09:00:00.000+09:00", star_count: 1, }, ]); }); it("code list 얻기 실패(400)", async () => { await expect( controllers.getCodes(new FakeRequestBuilder().build()) ).rejects.toThrow(BadRequest); }); it("code 얻기", async () => { const req = new FakeRequestBuilder().setParams({ id: 1 }).build(); const result = await controllers.getCode(req); expect(result.toJSON()).toEqual({ id: 1, title: "코드제목", author: 1, language: "rust", content: "내용", description: "설명", created_datetime: "2021-04-19T09:00:00.000+09:00", star_count: 1, }); }); it("code 얻기 실패(400)", async () => { await expect( controllers.getCode(new FakeRequestBuilder().build()) ).rejects.toThrow(BadRequest); }); it("code 검색 성공", async () => { const req = new FakeRequestBuilder() .setQuery({ limit: 5, offset: 0, search: "내", }) .build(); const codes = await controllers.getCodes(req); expect(codes.map((code) => code.toJSON())).toEqual([ { id: 1, title: "코드제목", author: 1, language: "rust", content: "내용", description: "설명", created_datetime: "2021-04-19T09:00:00.000+09:00", star_count: 1, }, ]); }); it("code 언어로 얻기", async () => { const req = new FakeRequestBuilder() .setQuery({ limit: 5, offset: 0, language: "rust", }) .build(); const codes = await controllers.getCodes(req); expect(codes.map((code) => code.toJSON())).toEqual([ { id: 1, title: "코드제목", author: 1, language: "rust", content: "내용", description: "설명", created_datetime: "2021-04-19T09:00:00.000+09:00", star_count: 1, }, ]); }); it("code list 스타 갯수로 정렬해 얻기", async () => { const req = new FakeRequestBuilder().setQuery({ offset: 0, limit: 1, order: "stars", }); const codes = await controllers.getCodes(req, new FakeResponse()); expect(codes.map((c) => c.toJSON())).toEqual([ { id: 1, title: "코드제목", content: "내용", language: "rust", description: "설명", author: 1, created_datetime: "2021-04-19T09:00:00.000+09:00", star_count: 1, }, ]); }); it("유저가 해당 code를 스타했는지 확인 - 204", async () => { const req = new FakeRequestBuilder().setParams({ code_id: 1, user_id: 1, }); const res = new FakeResponse(); await controllers.isStarredUser(req, res); expect(res.getStatus()).toBe(204); }); it("유저가 해당 code를 스타했는지 확인 - 404", async () => { const req = new FakeRequestBuilder().setParams({ code_id: 1, user_id: 2, }); const res = new FakeResponse(); await expect(controllers.isStarredUser(req, res)).rejects.toThrow(NotFound); }); });
1.492188
1
js/config.js
EricPoitras/nAnnotator2.0
0
15992596
config = { user: '<NAME>', url: '', persona: 'asset/per1.png', session: '', instructor: ['<NAME>'] }
0.412109
0
client/src/components/Conent.js
fosslife/delta
111
15992604
import FileUploader from './FileUploader'; import URLShortner from './URLShortner'; function Content({ tab }) { return tab === 'fileuploader' ? ( <FileUploader /> ) : tab === 'urlshortner' ? ( <URLShortner /> ) : null; } export default Content;
0.664063
1
script.js
Tim232/webhook
1
15992612
function send(){ let url = document.forms["form"].elements[0].value let send = document.forms["form"].elements[1].value $.post(url, send, function(data, status){ $("#results").text(data); $("#status").text(status); }); }
0.945313
1
src/items/Letter.js
timkurvers/grumbles
3
15992620
import BaseEntity from '../BaseEntity.js'; import { stripIndent } from '../utils.js'; class Letter extends BaseEntity { describe() { return stripIndent` <NAME>! No doubt you’ve heard of the princess that went missing not long ago. We’ve tracked her GPS-enabled crown to a vault in the castle south of here, but no sane person dares venture there. In this kingdom, <a href="https://www.google.com/search?q=http+methods" target="_blank">HTTP verbs</a> are used to interact with its inhabitants, locations and items. To get started, try the following commands: &gt; <strong>TRACE me</strong> &gt; <strong>SEARCH me</strong> &gt; <strong>SEARCH room</strong> &gt; <strong>MOVE courtyard</strong> For all of the available commands, read the game manual: &gt; <strong>TRACE game_manual</strong> Yours truly, ’Friend’ `; } } export default Letter;
1.148438
1
src/property/components/filters/Button.js
ochui/real-estate-app-ui
173
15992628
/** * @flow */ import React, {Component, PropTypes} from 'react'; import {StyleSheet, Text, View} from 'react-native'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import colors from '../../../common/colors'; export default class Button extends Component { static propTypes = { selected: PropTypes.string.isRequired, range: PropTypes.array.isRequired, onPress: PropTypes.func.isRequired, title: PropTypes.string.isRequired, icon: PropTypes.string.isRequired, incrementText: PropTypes.string, decrementText: PropTypes.string, style: View.propTypes.style, }; increment = () => { const {selected, range} = this.props; let arrayIndex, currentValue; try { arrayIndex = (range.indexOf(selected) + 1) % range.length; currentValue = range[arrayIndex]; this.props.onPress(currentValue); } catch (e) {} }; decrement = () => { const {selected, range} = this.props; let arrayIndex, currentValue; try { arrayIndex = range.indexOf(selected); arrayIndex = arrayIndex == 0 ? range.length : arrayIndex; currentValue = range[arrayIndex - 1]; this.props.onPress(currentValue); } catch (e) {} }; render() { const { title, titleStyle, selected, icon, incrementText, decrementText, } = this.props; return ( <View style={styles.container}> <Text style={[styles.button]} onPress={() => this.decrement()}> {decrementText} </Text> <View style={styles.infoWrapper}> <View style={styles.iconWrapper}> <FontAwesome name={icon} color="black" size={20} style={styles.icon} /> <Text style={[styles.title, titleStyle]}>{title}</Text> </View> <View style={styles.selected}> <Text style={styles.selectedText}>{selected}</Text> </View> </View> <Text style={[styles.button]} onPress={() => this.increment()}> {incrementText} </Text> </View> ); } } Button.defaultProps = { incrementText: '+', decrementText: '-', }; const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', alignItems: 'center', }, infoWrapper: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, title: { fontWeight: '400', fontSize: 12, }, price: { fontSize: 14, }, icon: { fontSize: 20, }, iconWrapper: { // backgroundColor:'white', alignItems: 'center', }, selected: { marginLeft: 10, }, selectedText: { color: colors.tomato, fontWeight: '500', }, button: { paddingHorizontal: 10, fontSize: 35, fontWeight: '200', color: '#202226', }, });
1.84375
2
Farmework/Util/wx/api.js
dreamllq/node-L-farmeword
0
15992636
/** * Created by lvlq on 16/1/14. */ var WechatAPI = require('wechat-api'); var config = Config(); var R = Util("R"); var urllib = require("urllib"); var bluebird = require("bluebird"); bluebird.promisifyAll(WechatAPI.prototype); var api = new WechatAPI(config.wx_app_id, config.wx_app_secret, function (callback) { R(config.wx_name + ":access_token").get() .then(function (token) { callback(null, token); }) .catch(function (err) { callback(err); }); }, function (token, callback) { R(config.wx_name + ":access_token").set(token) .then(function () { callback(null); }) .catch(function (err) { callback(err); }); }); api.registerTicketHandle(function (type, callback) { R(config.wx_name + ":" + type + ":ticketToken").get() .then(function (token) { callback(null, token); }) .catch(function (err) { callback(err); }); }, function (type, ticketToken, callback) { R(config.wx_name + ":" + type + ":ticketToken").set(ticketToken) .then(function () { callback(null); }) .catch(function (err) { callback(err); }); }); module.exports = api;
1.171875
1
src/routes/food.js
GhofranDayyat/api-server
0
15992644
'use strict'; const express=require('express'); const router = express.Router(); const foodModel = require('../models/food.js'); const clothesModel = require('../models/clothes.js'); const modelCollection =require('../models/data-collection-class.js') ; const newFoodInst= new modelCollection(foodModel); const newClothesInst= new modelCollection(clothesModel); let newModels; function checkingEndPoint(req, res, next){ console.log( req.path,'checking path' ); if (req.path==='/food'){ newModels= newFoodInst; }else if(req.path==='/clothes'){ newModels= newClothesInst; } next(); } //add router router.get('/',getModel); router.get('/:id',getOneMode); router.post('/',createModel); router.put('/:id',updatModel); router.delete('/:id',deletModel); //function //using then function getModel(req,res){ let getAll = newModels.get().then(result=>{ res.status(200).json(result); }); } //using async // async function getModel(req,res){ // let getAll =await newModels.get() // res.status(200).json(getAll); // } function getOneMode(req,res){ const id=req.params.id; console.log(id); let getOneModel = newModels.get(id).then(result=>{ res.status(200).json(result); }); } function createModel(req,res){ let obj = req.body; let newModel =newModels.create(obj).then(e=>{ res.status(201).json(e); }); } function updatModel(req,res){ const id = req.params.id; const obj = req.body; console.log(obj); let updateModel = newModels.update(id,obj).then(result=>{ res.status(200).json(result); }); } function deletModel(req,res){ const id = req.params.id; console.log(id); let deleteModel = newModels.delete(id).then(result=>{ res.status(202).json({result}); }); } module.exports={ router, checkingEndPoint };
1.570313
2
frontend/node_modules/.pnpm/@[email protected][email protected][email protected]/node_modules/@rsuite/icons/es/icons/legacy/Lock.js
koenw/fullstack-hello
2
15992652
// Generated by script, don't edit it please. import createSvgIcon from '../../createSvgIcon'; import LockSvg from '@rsuite/icon-font/lib/legacy/Lock'; var Lock = createSvgIcon({ as: LockSvg, ariaLabel: 'lock', category: 'legacy', displayName: 'Lock' }); export default Lock;
0.632813
1
antdRn/src/pages/IndexHome/index.js
rbowui/react-native-template
4
15992660
import React, { Component } from 'react'; import { View, Text, SafeAreaView, Image } from 'react-native'; import { Icon, List } from '@ant-design/react-native'; // import { outlineGlyphMap } from '@ant-design/icons-react-native/lib/outline'; import { connect } from 'react-redux'; const Item = List.Item; const DashboardScreen = (props) => { console.log('props', props.groupTypeData) return ( <SafeAreaView style={{ flex: 1 }}> <View style={{ flex: 1 }}> <List renderHeader={'带缩略图'}> {props.groupTypeData.map(item => <Item key={item.id} thumb="https://os.alipayobjects.com/rmsportal/mOoPurdIfmcuqtr.png" arrow="horizontal"> {item.aliasName} </Item> )} {/* {props.groupTypeData.map(item => <Item extra={ <Image source={{ uri: 'https://os.alipayobjects.com/rmsportal/mOoPurdIfmcuqtr.png', }} style={{ width: 29, height: 29 }} /> } arrow="horizontal" > {item.aliasName} </Item> )} */} </List> </View> </SafeAreaView> ) } export default connect(({ demo }) => { return { groupTypeData: demo.groupTypeData, }; })(DashboardScreen); // export default class MyScreen extends Component { // render() { // const { navigation } = this.props; // return ( // <SafeAreaView style={{flex:1}}> // <View style={{ flex: 1 }}> // <List renderHeader={'带缩略图'}> // <Item thumb="https://os.alipayobjects.com/rmsportal/mOoPurdIfmcuqtr.png"> // thumb // </Item> // {/* <Item // thumb="https://os.alipayobjects.com/rmsportal/mOoPurdIfmcuqtr.png" // arrow="horizontal" // > // thumb // </Item> */} // {/* <Item // extra={ // <Image // source={{ // uri: // 'https://os.alipayobjects.com/rmsportal/mOoPurdIfmcuqtr.png', // }} // style={{ width: 29, height: 29 }} // /> // } // arrow="horizontal" // > // extra为Image // </Item> */} // </List> // {/* <List // flat={true} // data={[ // { title: '企业开票' }, // { title: '我的熟车' }, // { title: '设置', onPress: () => navigation.navigate('MyHomeSetting') }, // { title: '退出登录', onPress: () => navigation.replace('SignIn') }, // ]} // renderItem={({ item, index }) => { // return ( // <List.Item // key={index} // extra={<Icon name="right" fill="#abb0b5" size={14} />} // size="large" // paddingLeft={15} // style={{ borderBottomWidth: 0, }} // onPress={item.onPress || null} // > // <View> // <Text>{item.title}</Text> // </View> // </List.Item> // ) // }} // /> */} // </View> // </SafeAreaView> // ); // } // }
1.429688
1
src/middleware/index.js
brian32768/rfr-test
0
15992668
import mapMiddleware from './map' export { mapMiddleware }
-0.049805
0
auth-server/util/data-worker.js
splincode/simple-authorize-service
0
15992676
const fs = require("fs"); const path = require('path'); module.exports = function(databasePath) { let currentPath = path.resolve(__dirname, "..", databasePath); let instanceDB = JSON.parse(fs.readFileSync(currentPath, 'utf8')); instanceDB.save = function() { fs.writeFileSync(currentPath, JSON.stringify(this, null, 4)); } return instanceDB; }
1.015625
1
packages/pocky/lib/read-rollup-config.js
egoist/pocky
36
15992684
const rollup = require('rollup') const requireFromString = require('require-from-string') module.exports = filepath => { return rollup.rollup({ entry: filepath }).then(bundle => { const res = bundle.generate({ format: 'cjs' }) return requireFromString(res.code, filepath) }) }
0.96875
1
src/common/cleartimer.js
seydx/camera.ui
49
15992692
'use-strict'; import fs from 'fs-extra'; import moment from 'moment'; import LoggerService from '../services/logger/logger.service.js'; const { log } = LoggerService; export default class Cleartimer { static #interfaceDB; static #recordingsDB; static #notificationsTimer = new Map(); static #recordingsTimer = new Map(); constructor() {} static async start(interfaceDB, recordingsDB) { if (interfaceDB) { Cleartimer.#interfaceDB = interfaceDB; } if (recordingsDB) { Cleartimer.#recordingsDB = recordingsDB; } try { //log.debug('Initializing clear timer'); const notSettings = await Cleartimer.#interfaceDB.chain.get('settings').get('notifications').cloneDeep().value(); const notRemoveAfter = notSettings.removeAfter; if (notRemoveAfter > 0) { const notifications = await Cleartimer.#interfaceDB.chain.get('notifications').cloneDeep().value(); for (const notification of notifications) { let timestampNow = moment(); let timestampFile = moment(moment.unix(notification.timestamp)); let timestampDif = timestampNow.diff(timestampFile, 'minutes'); let removeAfterTimer = notRemoveAfter * 60; if (removeAfterTimer > timestampDif) { removeAfterTimer -= timestampDif; } if (timestampDif > notRemoveAfter * 60) { Cleartimer.#notificationsTimer.set(notification.id, false); await Cleartimer.#clearNotification(notification.id); } else { Cleartimer.#timeout(removeAfterTimer / 60, 'hours', notification.id, notification.timestamp, false); } } } const recSettings = await Cleartimer.#interfaceDB.chain.get('settings').get('recordings').cloneDeep().value(); const recRemoveAfter = recSettings.removeAfter; if (recRemoveAfter) { const recordings = Cleartimer.#recordingsDB.chain.get('recordings').cloneDeep().value(); for (const recording of recordings) { let timestampNow = moment(); let timestampFile = moment(moment.unix(recording.timestamp)); let timestampDif = timestampNow.diff(timestampFile, 'hours'); let removeAfterTimer = recRemoveAfter * 24; if (removeAfterTimer > timestampDif) { removeAfterTimer -= timestampDif; } if (timestampDif > recRemoveAfter * 24) { Cleartimer.#recordingsTimer.set(recording.id, false); await Cleartimer.#clearRecording(recording.id); } else { Cleartimer.#timeout(removeAfterTimer / 24, 'days', recording.id, recording.timestamp, true); } } } } catch (error) { log.info('An error occured during starting clear timer', 'Cleartimer', 'interface'); log.error(error, 'Cleartimer', 'interface'); } } static stop() { Cleartimer.stopNotifications(); Cleartimer.stopRecordings(); } static async startNotifications() { try { const notSettings = await Cleartimer.#interfaceDB.chain.get('settings').get('notifications').cloneDeep().value(); const notRemoveAfter = notSettings.removeAfter; if (notRemoveAfter > 0) { const notifications = await Cleartimer.#interfaceDB.chain.get('notifications').cloneDeep().value(); for (const notification of notifications) { let timestampNow = moment(); let timestampFile = moment(moment.unix(notification.timestamp)); let timestampDif = timestampNow.diff(timestampFile, 'minutes'); let removeAfterTimer = notRemoveAfter * 60; if (removeAfterTimer > timestampDif) { removeAfterTimer -= timestampDif; } if (timestampDif > notRemoveAfter * 60) { Cleartimer.#notificationsTimer.set(notification.id, false); await Cleartimer.#clearNotification(notification.id); } else { Cleartimer.#timeout(removeAfterTimer / 60, 'hours', notification.id, notification.timestamp, false); } } } } catch (error) { log.info('An error occured during starting notifications clear timer', 'Cleartimer', 'interface'); log.error(error, 'Cleartimer', 'interface'); } } static async startRecordings() { try { const recSettings = await Cleartimer.#interfaceDB.chain.get('settings').get('recordings').cloneDeep().value(); const recRemoveAfter = recSettings.removeAfter; if (recRemoveAfter) { const recordings = Cleartimer.#recordingsDB.chain.get('recordings').cloneDeep().value(); for (const recording of recordings) { let timestampNow = moment(); let timestampFile = moment(moment.unix(recording.timestamp)); let timestampDif = timestampNow.diff(timestampFile, 'hours'); let removeAfterTimer = recRemoveAfter * 24; if (removeAfterTimer > timestampDif) { removeAfterTimer -= timestampDif; } if (timestampDif > recRemoveAfter * 24) { Cleartimer.#recordingsTimer.set(recording.id, false); await Cleartimer.#clearRecording(recording.id); } else { Cleartimer.#timeout(removeAfterTimer / 24, 'days', recording.id, recording.timestamp, true); } } } } catch (error) { log.info('An error occured during starting clear timer', 'Cleartimer', 'interface'); log.error(error, 'Cleartimer', 'interface'); } } static stopNotifications() { for (const entry of Cleartimer.#notificationsTimer.entries()) { const id = entry[0]; const timer = entry[1]; clearInterval(timer); Cleartimer.#notificationsTimer.delete(id); } } static stopRecordings() { for (const entry of Cleartimer.#recordingsTimer.entries()) { const id = entry[0]; const timer = entry[1]; clearInterval(timer); Cleartimer.#recordingsTimer.delete(id); } } static async setNotification(id, timestamp) { try { const settings = await Cleartimer.#interfaceDB.chain.get('settings').get('notifications').cloneDeep().value(); const clearTimer = settings.removeAfter; Cleartimer.#timeout(clearTimer, 'hours', id, timestamp, false); } catch (error) { log.info(`An error occured during setting up cleartimer for notification (${id})`, 'Cleartimer', 'interface'); log.error(error, 'Cleartimer', 'interface'); } } static async setRecording(id, timestamp) { try { const settings = await Cleartimer.#interfaceDB.chain.get('settings').get('recordings').cloneDeep().value(); const clearTimer = settings.removeAfter; Cleartimer.#timeout(clearTimer, 'days', id, timestamp, true); } catch (error) { log.info(`An error occured during setting up cleartimer for recording (${id})`, 'Cleartimer', 'interface'); log.error(error, 'Cleartimer', 'interface'); } } static removeNotificationTimer(id) { if (Cleartimer.#notificationsTimer.has(id)) { const timer = Cleartimer.#notificationsTimer.get(id); clearInterval(timer); Cleartimer.#notificationsTimer.delete(id); } } static removeRecordingTimer(id) { if (Cleartimer.#recordingsTimer.has(id)) { const timer = Cleartimer.#recordingsTimer.get(id); clearInterval(timer); Cleartimer.#recordingsTimer.delete(id); } } static async #clearNotification(id) { try { if (Cleartimer.#notificationsTimer.has(id)) { log.debug(`Clear timer for notification (${id}) reached`); await Cleartimer.#interfaceDB.chain .get('notifications') .remove((not) => not.id === id) .value(); } } catch (error) { log.info(`An error occured during removing notification (${id}) due to cleartimer`, 'Cleartimer', 'interface'); log.error(error, 'Cleartimer', 'interface'); } } static async #clearRecording(id) { try { if (Cleartimer.#recordingsTimer.has(id)) { log.debug(`Clear timer for recording (${id}) reached`); const recPath = Cleartimer.#recordingsDB.chain.get('path').cloneDeep().value(); const recording = Cleartimer.#recordingsDB.chain .get('recordings') .find((rec) => rec.id === id) .cloneDeep() .value(); if (recording) { await fs.remove(recPath + '/' + recording.fileName); if (recording.recordType === 'Video') { let placehoalder = recording.fileName.split('.')[0] + '@2.jpeg'; await fs.remove(recPath + '/' + placehoalder); } } Cleartimer.#recordingsDB.chain .get('recordings') .remove((rec) => rec.id === id) .value(); } } catch (error) { log.info(`An error occured during removing recording (${id}) due to cleartimer`, 'Cleartimer', 'interface'); log.error(error, 'Cleartimer', 'interface'); } } static #timeout(timeValue, timeTyp, id, timestamp, isRecording) { if (timeValue) { const endTime = moment.unix(timestamp).add(timeValue, timeTyp); /*log.debug( `SET cleartimer for ${ isRecording ? 'Recording' : 'Notification' } (${id}) - Removing after ${timeValue} ${timeTyp} - Endtime: ${endTime}` );*/ const interval = isRecording ? 6 * 60 * 60 * 1000 : 30 * 60 * 1000; const timer = setInterval(async () => { const now = moment(); if (now > endTime) { await (isRecording ? Cleartimer.#clearRecording(id) : Cleartimer.#clearNotification(id)); clearInterval(timer); } }, interval); if (isRecording) { Cleartimer.#recordingsTimer.set(id, timer); } else { Cleartimer.#notificationsTimer.set(id, timer); } } } }
1.507813
2
src/actions/index.test.js
Senderek/WSTM
0
15992700
import { addMessage, addUser } from '../actions' import * as types from '../constants/ActionTypes' describe('adding a message', () => { it('should create an action to add a message with id 0', () => { const message = 'Something' const action = { type: types.ADD_MESSAGE, message, author: 'Me', id: 0 } expect(addMessage(message)).toEqual(action) }) }) describe('adding a second message', () => { it('should create an action to add a message with id 1', () => { const message = 'Something' const action = { type: types.ADD_MESSAGE, message, author: 'Me', id: 1 } expect(addMessage(message)).toEqual(action) }) }) describe('adding a user', () => { it('should create an action to add a user with id 0', () => { const user = 'Mark' const action = { type: types.ADD_USER, name: user, id: 0 } expect(addUser(user)).toEqual(action) }) }) describe('adding a second user', () => { it('should create an action to add a message with id 1', () => { const user = 'Tony' const action = { type: types.ADD_USER, name: user, id: 1 } expect(addUser(user)).toEqual(action) }) })
1.476563
1
src/server/api/handlers/vote.js
nhardy/sep
2
15992708
import r from 'server/api/rethink'; const ALLOWED_VALUES = [-1, 1]; export default async function voteHandler(req, res, next) { const { id } = req.params; const { username } = res.locals; const { value } = req.body; if (!ALLOWED_VALUES.includes(value)) { const error = new Error(`Value: '${value}' is not valid`); error.status = 400; next(error); return; } try { await r.table('posts') .filter({ id }) .run() .then(([post]) => { if (post) return; const error = new Error(`Post with id: '${id}' could not be found`); error.status = 404; throw error; }); await r.table('votes') .insert({ id: [id, username], post: id, username, value, }, { conflict: 'replace' }) .run(); } catch (e) { next(e); return; } next(); }
1.148438
1
webpack.prod.js
sdarmaputra/wwwid-feed
6
15992716
const merge = require('webpack-merge') const common = require('./webpack.common.js') const MinifyPlugin = require('babel-minify-webpack-plugin') const UglifyPlugin = require('uglifyjs-webpack-plugin') const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin const config = merge(common, { plugins: [ new MinifyPlugin(), new UglifyPlugin(), new BundleAnalyzerPlugin() ] }) module.exports = config
0.671875
1
UI-Test/d3BarTest.js
Nandhini119/node_assignment
0
15992724
describe('the svg ', function() { let svg = document.getElementsByTagName('svg'); // to test number of svgs it('svg should be created',function() { expect(svg.length).to.equal(3); }); // to test value of rectangular bar it('svg contains rectagle bars',function() { expect(document.getElementsByTagName("rect")).to.not.be.null; }); function getSvg() { return d3.select('svg'); } });
1.78125
2
packages/2025/06/25/index.js
antonmedv/year
7
15992732
module.exports = new Date(2025, 5, 25)
-0.130859
0
exercicios-jquery/03- Eventos Jquery/script.js
PedroPadilhaPortella/Exercicios_Logica_com_Javascript
0
15992740
$().ready(function(){ $("button").click(function(e){ console.log(e.target); console.log("Id do elemento: "+ e.target.id); console.log(e.which); console.log(`PageX: ${e.pageX}`); console.log(`PageY: ${e.pageY}`); console.log(`Tipo: ${e.type}`); console.log(`Tipo: ${e.bubbles}`); }); });
1.015625
1
src/composables/useWebWorker.js
tedbreehq/helpers
0
15992748
import { ref, onMounted, onUnmounted } from '@vue/composition-api' export function useWebWorker (url) { const data = ref(null); let worker; const post = function post (val) { if (!worker) return; worker.postMessage(val); }; const terminate = function terminate () { if (!worker) return; worker.terminate() }; onMounted(() => { worker = new Worker(url); worker.onmessage = (e) => { data.value = e.data } }); onUnmounted(() => { worker.terminate() }); return { data, post, terminate, } }
1.25
1
commands/role-management/inrole.js
CutieCat6778/ModeratorBot
0
15992756
const { MessageEmbed } = require('discord.js'); module.exports = { config: { name: "inrole", aliases: ["inr"], perms: ["SEND_MESSAGES"], category: "role-management", bot: ["MANAGE_ROLES"] }, async execute(client, message, args, guildCache) { try { if (!args[0]) { return require('../../tools/function/sendMessage')(message, require('../../noArgs/role-management/inrole.js')(guildCache.prefix)); } const role = message.guild.roles.cache.get(require('mention-converter')(args[0])); if (!role) return message.channel.send("Role not found"); const embed = new MessageEmbed() .setColor("#40598F") .setTitle(`List of users has ${role.name} role`) .setTimestamp() .setFooter(`Requested by ${message.member.displayName}`, message.author.displayAvatarURL()) .setDescription(`${message.guild.members.cache.map(member => { if(member.roles.cache.has(role.id)){return member.user.username+"\n"}})}`.split(',').join("")) require('../../tools/function/sendMessage')(message, embed); } catch (e) { return require('../../tools/function/error')(e, message); } } }
1.523438
2
router/socket.js
skyneton/webrtc-p2p
1
15992764
const session = require("./session"); const crypto = require("crypto"); module.exports = (io) => { io.sockets.on("connection", (client) => { // log("::Socket Connection:: " + client.handshake.address); client.on("disconnect", () => { // log("::Socket Disconnect:: " + client.handshake.address); if(client.room) { sendPacketInRoom(client.room, "PlayerDisconnection", client.id); if(io.sockets.adapter.rooms[client.room]) client.leave(client.room); if(io.sockets.adapter.rooms[client.room] && io.sockets.adapter.rooms[client.room].allow && io.sockets.adapter.rooms[client.room].allow.includes(session.data[client.key].uid)) io.sockets.adapter.rooms[client.room].allow.splice(io.sockets.adapter.rooms[client.room].allow.indexOf(session.data[client.key].uid), 1); if(io.sockets.adapter.rooms[client.room] && io.sockets.adapter.rooms[client.room].sockets.length <= 0) delete io.sockets.adapter.rooms[client.room] } if(client.key) { session.used.splice(session.used.indexOf(client.key), 1); delete session.data[client.key]; } }); client.on("callClose", () => { if(client.room && io.sockets.adapter.rooms[client.room] && session.data[client.key] && client.room == session.data[client.key].uid) { for(const sockets in io.sockets.adapter.rooms[client.room].sockets) { if(sockets != client.id) { const player = io.sockets.connected[sockets]; if(player) { player.emit("callClose"); player.disconnect(); } } } } if(session.data[client.key] && io.sockets.adapter.rooms[client.room] && io.sockets.adapter.rooms[client.room].allow && io.sockets.adapter.rooms[client.room].allow.includes(session.data[client.key].uid)) io.sockets.adapter.rooms[client.room].allow.splice(io.sockets.adapter.rooms[client.room].allow.indexOf(session.data[client.key].uid), 1); client.emit("callClose"); client.disconnect(); }); client.on("session", key => { if(session.used.includes(key)) { client.emit("serverError", 1); client.disconnect(); return; }if(!session.data[key]) { client.emit("serverError", 2); client.disconnect(); return; }if(session.data[key].uid == null || session.data[key].uid == undefined) { client.emit("serverError", 3); client.disconnect(); return; } for(const skey in session.data) { if(skey == key) continue; if(session.data[skey].uid == session.data[key].uid) { if(!session.data[skey].socket || io.sockets.connected[session.data[skey.socket]]) { delete session.data[skey]; continue; } client.emit("serverError", 4); client.disconnect(); return; } } client.key = key; if(client.room) { sendPacketInRoom(client.room, "PlayerDisconnection", client.id); if(io.sockets.adapter.rooms[client.room]) client.leave(client.room); } client.room = undefined; if(session.data[client.key].room) { if(io.sockets.adapter.rooms[session.data[client.key].room]) { client.room = session.data[client.key].room; }else client.emit("serverMsg", {"type": 1, "message": "삭제되었거나 존재하지 않는 방입니다." }); } if(!client.room) { client.room = session.data[key].uid; client.join(client.room); io.sockets.adapter.rooms[client.room].allow = []; }else client.join(client.room); session.used.push(key); socketEmitNotPlayer(client.room, client.id, "PlayerConnection", client.id, session.data[client.key].name); client.emit("JoinRoom", client.id, session.data[client.key].name); session.data[client.key].socket = client.id; }); client.on("createToken", () => { if(!client.room || !io.sockets.adapter.rooms[client.room]) return; if(session.data[client.key] && client.room == session.data[client.key].uid) { const token = createRandomToken(); session.tokens[token] = client.room; io.sockets.adapter.rooms[client.room].token = token; //client.emit("createToken", `${client.room}/${io.sockets.adapter.rooms[client.room].token}`); client.emit("createToken", `${token}`); } }); client.on("RTCConnection", () => { // log("::RTCConnection::" + client.id); socketEmitNotPlayer(client.room, client.id, "RTCConnection", client.id, session.data[client.key].name); }); client.on("RTCConnection2", () => { if(!client.room || !io.sockets.adapter.rooms[client.room]) return; for(const sockets in io.sockets.adapter.rooms[client.room].sockets) { if(sockets != client.id) { client.emit("RTCConnection", sockets); } } }); client.on("RTCData", (data, to) => { if(to && client.room && io.sockets.adapter.rooms[client.room]) { const x = io.sockets.connected[to]; if(x && x.room == client.room) x.emit("RTCData", data, client.id, session.data[client.key].name); } }); client.on("audioStatus", (data, to) => { if(!client.room || !io.sockets.adapter.rooms[client.room]) return; if(to) { const x = io.sockets.connected[to]; if(x && x.room == client.room) { x.emit("audioStatus", { uid: client.id, status: data.status, streamId: data.streamId }); } }else io.sockets.in(client.room).emit("audioStatus", { uid: client.id, status: data.status, streamId: data.streamId }); }); client.on("videoStatus", (data, to) => { if(!client.room || !io.sockets.adapter.rooms[client.room]) return; if(to) { const x = io.sockets.connected[to]; if(x && x.room == client.room) { x.emit("videoStatus", { uid: client.id, status: data.status, streamId: data.streamId }); } }else io.sockets.in(client.room).emit("videoStatus", { uid: client.id, status: data.status, streamId: data.streamId }); }); client.on("desktopStatus", (data, to) => { if(!client.room || !io.sockets.adapter.rooms[client.room]) return; if(to) { const x = io.sockets.connected[to]; if(x && x.room == client.room) { x.emit("desktopStatus", { uid: client.id, status: data.status, streamId: data.streamId }); } }else io.sockets.in(client.room).emit("desktopStatus", { uid: client.id, status: data.status, streamId: data.streamId }); }); client.on("chat", msg => { if(!client.room || !io.sockets.adapter.rooms[client.room]) return; if(msg.replace(/ /, "").replace(/\n/, "").length == 0) return; msg = splitTags(msg.trim()); msg = msg.replace(/\n/gi, "<br>").replace(/ /gi, ""); const day = new Date(); const packet = { "sender": client.id, "msg": msg, "time": `${day.getHours()}H ${day.getMinutes()}M`, "name": session.data[client.key].name }; io.sockets.in(client.room).emit("chat", JSON.stringify(packet)); }); }); const socketEmitNotPlayer = (room, uid, type, data, data2) => { if(!room || !io.sockets.adapter.rooms[room]) return; for(const sockets in io.sockets.adapter.rooms[room].sockets) { if(sockets != uid) { const player = io.sockets.connected[sockets]; if(player) player.emit(type, data, data2); } } } const sendPacketInRoom = (room, type, data) => { if(!room || !io.sockets.adapter.rooms[room]) return; io.sockets.in(room).emit(type, data); } } const log = msg => { const logDate = new Date(); const logD = "[" + logDate.getFullYear().toString().substring(2) + "/" + (logDate.getMonth() + 1).toString().padStart(2,'0') + " " + logDate.getHours().toString().padStart(2,'0') + ":" + logDate.getMinutes().toString().padStart(2,'0') + ":" + logDate.getSeconds().toString().padStart(2,'0') + "]"; console.log(logD + " " + msg); } const splitTags = (data) => { return data.replace(/&/gi, "&#38;") .replace(/#/gi, "&#35;") .replace(/&&#35;38;/gi, "&#38;") .replace(/</gi, "&lt;") .replace(/>/gi, "&gt;") .replace(/\(/gi, "&#40;") .replace(/\)/gi, "&#41;") .replace(/ /gi, "&nbsp;") .replace(/=/gi, "&#61;") .replace(/'/gi, "&#39;") .replace(/"/gi, "&quot;"); }; const splitTagsReverse = (data) => { return data.replace("&#38;", "&") .replace(/&#35;/gi, "#") .replace(/&lt;/gi, "<") .replace(/&gt;/gi, ">") .replace(/&#40;/gi, "(") .replace(/&#41;/gi, ")") .replace(/&nbsp;/gi, " ") .replace(/&#61;/gi, "=") .replace(/&#39;/gi, "'") .replace(/&#34;/gi, '"'); }; const createRandomToken = () => { return crypto.randomBytes(4).toString("hex"); //return crypto.randomBytes(28).toString("hex"); }
1.492188
1
migration/1631406679976-AddedKycCustomerId.js
topaccina/api
10
15992772
const { MigrationInterface, QueryRunner } = require("typeorm"); module.exports = class AddedKycCustomerId1631406679976 { name = 'AddedKycCustomerId1631406679976' async up(queryRunner) { await queryRunner.query(`ALTER TABLE "dbo"."user_data" ADD "kycCustomerId" int`); } async down(queryRunner) { await queryRunner.query(`ALTER TABLE "dbo"."user_data" DROP COLUMN "kycCustomerId"`); } }
1
1
assets/index.js
paulbrimicombe/picture-to-colouring-page
0
15992780
if (window.location.host !== null && navigator.serviceWorker != null) { navigator.serviceWorker .register("service-worker.js") .then(function (registration) { console.log("Registered events at scope: ", registration.scope); }) .catch((error) => { console.error("Failed to register service worker", error); }); } const allowDrop = (event) => { event.preventDefault(); }; const extractFromGoogleImagesDrop = (dataTransfer) => { const uriList = dataTransfer.getData("text/uri-list"); const url = new URL(uriList); if (!url.hostname === "www.google.com") { return ""; } if (url.pathname === "/url" && url.searchParams.get("source") === "images") { const htmlData = dataTransfer.getData("text/html"); const parser = new DOMParser(); const imageDoc = parser.parseFromString(htmlData, "text/html"); const image = imageDoc.querySelector("img"); return image.src; } if (url.pathname === "/imgres") { return url.searchParams.get("imgurl"); } }; const getImageUrl = (dataTransfer) => { if (!dataTransfer) { return ""; } const googleImagesImageUrl = extractFromGoogleImagesDrop(dataTransfer); if (googleImagesImageUrl) { return googleImagesImageUrl; } const text = dataTransfer.getData("text"); if (text) { return text; } const uriList = dataTransfer.getData("text/uri-list"); if (uriList) { return uriList; } return ""; }; const drop = (event) => { event.preventDefault(); const imageUrl = getImageUrl(event.dataTransfer); const imageElement = document.getElementById("image"); imageElement.src = imageUrl; imageElement.className = "bright"; messageElement = document.getElementById("drop-message-box"); messageElement.className = "hidden"; }; const reset = (event) => { event.preventDefault(); const imageElement = document.getElementById("image"); imageElement.className = "hidden"; delete imageElement.style.opacity; messageElement = document.getElementById("drop-message"); messageElement.className = ""; }; const updateOpacity = (event) => { const newOpacity = 1 - parseFloat(event.target.value, 10); const imageElement = document.getElementById("image"); imageElement.style.opacity = newOpacity; }; const print = (event) => { event.preventDefault(); window.print(); };
1.390625
1
upload/histogram.js
stevewithington/scripts
0
15992788
var percentFormat = d3.format(".0%"); function generateMovieData (callback) { var data = []; for(var m in moviesObj){ var movie = moviesObj[m]; movie.males = 0; movie.females = 0; movie.questions = 0; movie.male_words = 0; movie.female_words = 0; movie.question_words = 0; movie.total_words = 0; for(var c in movie.characters){ var char_id = movie.characters[c]; var character = characters[char_id]; var char_words = character_words[char_id]; //movie.total_words += char_words; if(character.gender === "m"){ movie.males++; movie.male_words += char_words; } else if (character.gender === "f"){ movie.females++; movie.female_words += char_words; } else { movie.questions++; movie.question_words += char_words; } } movie.total_words = movie.female_words + movie.male_words; data.push(movie); } callback(data) } function drawHistogram(){ generateMovieData((movieData) => { var values = []; for(var d in movieData){ if(movieData[d].total_words > 0){ values.push(movieData[d].female_words / movieData[d].total_words); } } // A formatter for counts. var formatCount = d3.format(".0%"); // var margin = {top: 10, right: 30, bottom: 30, left: 50}, width = 700 - margin.left - margin.right, height = 450 - margin.top - margin.bottom; var x = d3.scale.linear() .domain([0, 1]) .range([0, width]); console.log(movieData); // var interpolateScale = d3.interpolate("#0091E6", "#ff1b84"); // var rangeColors = d3.range(.2,1.2,0.2).map(function(d){ // console.log(d); // return interpolateScale(d); // }); // console.log(rangeColors); // var colorScale = d3.scale.threshold().domain([0.2,0.4,0.6,0.8,1.1]).range(rangeColors); // console.log(colorScale(1)); var interpolateOne = d3.interpolate("#0091E6","#ddd"); var interpolateTwo = d3.interpolate("#ddd","#ff1b84"); var colorScale = d3.scale.threshold().domain([0.2,0.4,0.6,0.8,1.1]).range(["#0091E6",interpolateOne(0.5),"#ddd",interpolateTwo(0.5), "#ff1b84"]); console.log(colorScale(1)); var bucketScale = d3.scale.threshold().domain([0.2,0.4,0.6,0.8,1.1]).range(["bucket-a","bucket-b","bucket-c","bucket-d","bucket-e"]); // // Generate a histogram using twenty uniformly-spaced bins. // var data = d3.layout.histogram() // .bins(x.ticks(5)) // (values); // // var bucketData = []; var bucketSize = 20; var bucketIndexes = {}; // console.log(movieData); // for(var d in movieData){ var point = movieData[d]; if(point.total_words > 0){ point.female_percent = point.female_words / point.total_words; point.x = point.female_percent; point.bucket = x(Math.floor(point.female_percent * bucketSize) / bucketSize) if(typeof bucketIndexes[point.bucket] === "undefined"){ bucketIndexes[point.bucket] = 0; } bucketIndexes[point.bucket]++; point.bucketNumber = bucketScale(point.female_percent); point.y = bucketIndexes[point.bucket]; bucketData.push(point) } } var bucketDataNest = d3.nest().key(function(d) { return d.bucketNumber }) .sortKeys(d3.ascending) .entries(bucketData); var histogramChartBuckets = d3.select(".histogram-two").append("div").attr("class","histogram-two-data") .selectAll("div") .data(bucketDataNest) .enter() .append("div") .attr("class",function(d){ return "histogram-two-bucket " + d.values[0].bucketNumber; }); var histogramChartData = histogramChartBuckets .selectAll("div") .data(function(d){ return d.values; }) .enter() .append("div") .attr("class",function(d){ return "histogram-two-line " + bucketScale(d.female_percent); }) .style("background-color",function(d){ return colorScale(d.female_percent); }) ; d3.select(".bucket-a") .append("p") .attr("class","axis-label tk-futura-pt") .html("90%+<br>Male") ; d3.select(".bucket-a") .append("p") .attr("class","axis-count tk-futura-pt") .style("color",function(d){ return d3.rgb(colorScale.range()[0]).darker(1.5); }) .html(d3.selectAll(".bucket-a").size() - 1 +" films") ; d3.select(".bucket-c") .append("p") .attr("class","axis-label tk-futura-pt") .html("Gender Parity<br>(50/50 Male:Female)") ; d3.select(".bucket-c") .append("p") .attr("class","axis-count tk-futura-pt") .style("color",function(d){ return d3.rgb(colorScale.range()[2]).darker(1.5); }) .html(d3.selectAll(".bucket-c").size() - 1 + " films") ; d3.select(".bucket-e") .append("p") .attr("class","axis-label tk-futura-pt") .html("90%+<br>Female") ; d3.select(".bucket-e") .append("p") .attr("class","axis-count tk-futura-pt") .style("color",function(d){ return d3.rgb(colorScale.range()[4]).darker(1.5); }) .html(d3.selectAll(".bucket-e").size() - 1) ; var marker = d3.select(".histogram-two-data") .append("div") .attr("class","histogram-two-marker") ; var previewNameContainer = d3.select(".histogram-two-data") .append("div") .attr("class","histogram-two-name-container tk-futura-pt") ; var previewName = previewNameContainer.append("div") .attr("class","histogram-two-name tk-futura-pt") .text("hello") ; var previewDataBarScale = d3.scale.linear().domain([0,1]).range([0,50]) var previewData = previewNameContainer .append("div") .attr("class","histogram-two-data-preview tk-futura-pt") .selectAll("div") .data([0.5,0.6],function(d){ return d; }) .enter() .append("div") .attr("class","histogram-two-data-preview-row") ; var previewDataLabel = previewData.append("p") .attr("class","histogram-two-data-preview-label tk-futura-pt") .text(function(d,i){ if(i==0){ return "female lines"; } return "male lines"; }); var previewDataBar = previewData.append("div") .attr("class","histogram-two-data-preview-bar") .style("width",function(d){ return previewDataBarScale(d) + "px"; }) .style("background-color",function(d,i){ if (i==0){ return "#ff1b84" } return "#0091E6"; }); var previewDataPercent = previewData.append("p") .attr("class","histogram-two-data-preview-percent tk-futura-pt") .text(function(d,i){ return percentFormat(d); }); histogramChartData .on("mouseover",function(d){ previewName.text(d.title).style("color",colorScale(d.female_percent)); previewData .data([d.female_percent,1-d.female_percent]) .enter(); previewData.select(".histogram-two-data-preview-percent") .text(function(d,i){ return percentFormat(d); }); previewData.select(".histogram-two-data-preview-bar") .transition() .duration(200) .style("width",function(d){ return previewDataBarScale(d) + "px"; }); }) d3.select(".histogram-two-data") .on("mousemove",function(d){ var coordinates = d3.mouse(this); console.log(coordinates[0]); marker.style("left",coordinates[0]-3+"px"); previewNameContainer.style("left",coordinates[0]-3+"px"); }) .on("mouseover",function(d){ marker.style("display","block"); d3.selectAll(".axis-count").style("visibility","hidden") previewNameContainer.style("visibility","visible"); }) .on("mouseout",function(d){ marker.style("display",null); d3.selectAll(".axis-count").style("visibility","visible") previewNameContainer.style("visibility",null); }) .on("click",function(d){ scriptLines .transition() .duration(500) .style("left",valuesLines.length*2+"px") // scriptLines.transition().duration(500) // .style("left",function(d,i){ // return d.index*2 + "px"; // }) // ; }) ; console.log(movie_lines); var valuesLines = [] var thisMovieLines = movie_lines["m555"]; thisMovieLines.female_lines.forEach((x) => { valuesLines.push({gender: "f", index: x}) }); thisMovieLines.male_lines.forEach((x) => { valuesLines.push({gender: "m", index: x}) }); valuesLines = valuesLines.sort(function(a, b){ var o1 = a.index; var o2 = b.index; if (o1 < o2) return -1; if (o1 > o2) return 1; return 0; }) var scriptLines = d3.select(".histogram-two").append("div").style("width","100%").append("div") .attr("class","histogram-two-script-data") .style("width",valuesLines.length*2 + "px") .selectAll("div") .data(valuesLines) .enter() .append("div") .attr("class","line") .style("background",function(d){ if(d.gender == "f"){ return "#FF1B84"; } return "#0091E6"; }) .style("margin-top",function(d){ if(d.gender == "f"){ return "0px"; } return "18px"; }) .on("click",function(d){ }) ; scriptLines.filter(function(d){ return d.gender == "f" }) .style("left",function(d,i){ return i*2 + "px"; }) ; scriptLines.filter(function(d){ return d.gender == "m" }) .style("left",function(d,i){ return i*2 + "px"; }) ; ; // var bucketLengths = []; // var bucketLengthsCumulative = []; // // for (bucket in bucketScale.range()){ // var length = d3.selectAll("."+bucketScale.range()[bucket]).size(); // bucketLengths.push(length); // if (bucket == 0){ // bucketLengthsCumulative.push(bucketLengths[bucket]); // } // else{ // var length = bucketLengths[bucket]+bucketLengthsCumulative[bucket-1]; // bucketLengthsCumulative.push(length); // } // } // console.log(bucketLengths,bucketLengthsCumulative); // // histogramChart // .style("margin-right",function(d,i){ // if(bucketLengthsCumulative.indexOf(i+1) > -1){ // return "2px"; // } // return null; // }) // console.log(bucketData); // // // var y = d3.scale.linear() // .domain([0, d3.max(data, function(d) { return d.y; })]) // .range([height, 0]); // // // // // var svg = d3.select("#histogram") // .attr("width", width + margin.left + margin.right) // .attr("height", height + margin.top + margin.bottom) // .append("g") // .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // // // // // var axisTickValues = [0.25, 0.5, 0.75]; // // // var yScale = d3.scale.linear() // .domain([0, 1]) // .range([0, height - (margin.top)]); // // // var tickLine = svg.append("g") // .attr("class", "tick-line") // // .attr("transform", // // "translate(" + margin + ",0)"); // // // for(var v in axisTickValues){ // tickLine.append("line") // .attr("x1", 0 - margin.left) // .attr("x2", width + margin.right) // .attr("y1", yScale(axisTickValues[v])) // .attr("y2", yScale(axisTickValues[v])); // } // // // var lineBreakdown = svg.append("g") // .attr("class", "line-breakdown") // .attr("width", width + margin.left + margin.right) // .attr("height", 20) // // // var buckets = svg.selectAll(".blocks") // .data(bucketData) // .enter().append("g") // .attr("transform", function(d, i) { // return "translate(" + d.bucket + "," + y(d.y) + ")"; // }); // // buckets.append("rect") // .attr("class", "block") // .style("fill", (d) => { // // var color = "black"; // if(d.x < 0.5){ // color = "#146089"; // } else { // color = "#FF1782"; // } // return color; // // // var colorScale = chroma.scale(['#146089', '#FF1782']); // // return colorScale(d.x).css() // // }) // .attr("x", 0) // .attr("width", 30) // .attr("height", 2) // .on("mouseover", (d, i) => { // // var values = [] // var thisMovieLines = movie_lines[d.movieID]; // thisMovieLines.female_lines.forEach((x) => { values.push({gender: "f", index: x}) }); // thisMovieLines.male_lines.forEach((x) => { values.push({gender: "m", index: x}) }); // lineBreakdown.append("text").text(d.title); // lineBreakdown.selectAll(".line-block") // .data(values) // .enter().append("rect") // //.attr("class", "line-block") // .attr("height", 10) // .attr("width", 2) // .attr("x", (l) => { return l.index * 2}) // .attr("y", (l) => { // if(l.gender === "f") return 10; // return 20 // }) // .style("fill", (l) => { // if(l.gender === "f") return "#FF1782"; // return "#146089" // }) // }) // .on("mouseout", (d, i) => { // lineBreakdown.selectAll("*").remove(); // }) // // // var xAxis = d3.svg.axis() // .scale(x) // .orient("bottom") // .tickValues([0, 0.25, 0.5, 0.75, 1]) // .tickFormat((tick) => { // if(tick === 0.5){ return "Gender Parity"; // } else if(tick === 0){ return "All Men"; // } else if(tick === 1){ return "All Women"; // } else if(tick === 0.25){ return "75% Men"; // } else { return "75% Women"; } // }); // // svg.append("g") // .attr("class", "x axis tk-futura-pt") // .attr("transform", "translate(0," + height + ")") // .call(xAxis); }) } //$(document).ready(() => { drawHistogram(); //});
2.234375
2
src/services/send-mail/send-mail.service.js
suutil/server
0
15992796
// Initializes the `sendMail` service on path `/send-mail` const createService = require('./send-mail.class.js'); const hooks = require('./send-mail.hooks'); const filters = require('./send-mail.filters'); module.exports = function () { const app = this; const paginate = app.get('paginate'); let mailConfig = app.get('mailConfig') const options = { name: 'send-mail', paginate, mailConfig }; // Initialize our service with any options it requires app.use('/send-mail', createService(options)); // Get our initialized service so that we can register hooks and filters const service = app.service('send-mail'); service.hooks(hooks); if (service.filter) { service.filter(filters); } };
1.351563
1
app/components/nrg-responsive-takeover.js
nadeemhemani/ember-nrg-ui
15
15992804
export { default } from 'ember-nrg-ui/components/nrg-responsive-takeover';
0.324219
0
src/app/editFormEvent/index.js
krisScript/Task-app
0
15992812
import { getFormData } from "../utilities/utilities"; import { editTaskLS } from "../utilitiesLS/utilitiesLS"; import createTaskElement from "../createTaskElement/createTaskElement"; const formEvent = () => { const form = document.getElementById("edit-form"); if (form !== null) { form.addEventListener("submit", e => { e.preventDefault(); const task = { ...getFormData(e.target.children) }; editTaskLS(task.id, task); const oldTaskElement = document.getElementById(task.id); document .getElementById("tasks-container") .replaceChild(createTaskElement(task), oldTaskElement); const editFormModal = document.getElementById("edit-form-modal"); editFormModal.classList.remove("modal-active"); e.target.reset(); }); } }; export default formEvent;
1.148438
1
index.js
denkylabs/easy-mongodb
2
15992820
const Mongoose = require('mongoose'); const EventEmmiter = require('events'); module.exports = class DatabaseMongooseConnection extends EventEmmiter { constructor (url, name = 'easy-mongodb', config) { super(); this.url = url; this.config = config; this.name = name; this.firstConnect = true; this._usefulMethods(); } // Connect to mongodb connect () { Mongoose.connect(this.url, this.config ? this.config : { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }); this.db = Mongoose.connection; if(this.firstConnect) this._setupEvents(); this.firstConnect = false; this.schema = new Mongoose.Schema({ name: {}, value: {} }); this.model = Mongoose.model(this.name, this.schema); return Mongoose.connection; } // Disconnect from mongodb disconnect () { this.forcedDisconnect = true; return Mongoose.disconnect(); } // Get database connection get connection () { return Mongoose.connection; } // Set database value async set (key, value) { // We search for the key object const obj = await this.model.findOne({ name: key }); // We check if the key already exists, if it exists, we just change the value if (obj) { obj.value = value; return obj.save(); } // If it doesn't exist, we create a new object else { const newObj = new this.model({ name: key, value: value }); return newObj.save(); } } // Get database value async get (key) { const obj = await this.model.findOne({ name: key }); return obj ? obj.value : undefined; } // Remove database value async remove (key) { const obj = await this.model.findOne({ name: key }); return obj ? obj.remove() : null; } // Remove database value async delete (key) { const obj = await this.model.findOne({ name: key }); return obj ? obj.remove() : null; } // Get all database values async getAll () { const obj = await this.model.find({}).exec(); return obj ? obj : []; } // Get all database keys async getKeys () { const obj = await this.model.find({}).exec(); return obj ? obj.map(o => o.name) : []; } // Delete all database values async deleteAll () { const obj = await this.model.find({}).exec(); return obj ? obj.map(o => o.remove()) : []; } // Exists database value async exists (key) { const obj = await this.model.findOne({ name: key }); return obj ? true : false; } // Increment database value async inc (key, value) { const obj = await this.model.findOne({ name: key }); if (obj) { obj.value = obj.value + value; return obj.save(); } else { const newObj = new this.model({ name: key, value: value }); return newObj.save(); } } // Decrement database value async dec (key, value) { const obj = await this.model.findOne({ name: key }); if (obj) { obj.value = obj.value - value; return obj.save(); } else { const newObj = new this.model({ name: key, value: value }); return newObj.save(); } } // Pull database value (array) async pull (key, value) { const obj = await this.model.findOne({ name: key }); if (obj) { obj.value = obj.value.filter(v => v !== value); return obj.save(); } else { const newObj = new this.model({ name: key, value: value }); return newObj.save(); } } // Push database value (array) async push (key, value) { const obj = await this.model.findOne({ name: key }); if (obj) { obj.value.push(value); return obj.save(); } else { const newObj = new this.model({ name: key, value: value }); return newObj.save(); } } // Database value includes (array) async includes (key, value) { const obj = await this.model.findOne({ name: key }); if (obj) { return obj.value.includes(value); } else { return false; } }; // Moongose object get mongoose () { return this.model; }; // Setup events _setupEvents () { this.db.on('open', () => this.emit('ready')); this.db.on('error', e => this.emit('error', e)); this.db.on('disconnect', () => { this.emit('disconnect'); // Reconnect to mongodb if(!this.forcedDisconnect) Mongoose.connect(this.url, this.config ? this.config : { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }); }); } // Useful methods _usefulMethods () { this.add = this.inc; this.rem = this.dec; this.aumentar = this.inc; this.diminuir = this.dec; this.adicionar = this.inc; this.remover = this.dec; this.all = this.getAll; this.keyArray = this.getAll; this.clear = this.deleteAll; this.has = this.exists; this.keys = this.getKeys; } };
1.921875
2
src/components/clientList.js
sethburtonhall/dks2.0
0
15992828
import React from "react" import { StaticQuery, graphql } from "gatsby" // Styles import { Container } from "../styles/GlobalStyles" const Clients = () => { return ( <StaticQuery query={clientQuery} render={data => { const { client } = data.allFile.nodes[0].childMdx.frontmatter return ( <Container> <h1>Clients</h1> <ul> {client.map((c, index) => ( <li key={index}>{c.clientName}</li> ))} </ul> </Container> ) }} /> ) } const clientQuery = graphql` query ClientQuery { allFile(filter: { name: { eq: "clients" } }) { nodes { childMdx { frontmatter { client { clientName } } } } } } ` export default Clients
1.304688
1
test/fixtures/basic_expect.js
dictav/rollup-plugin-regenerator
0
15992836
var marked0$0 = [anotherGenerator, generator].map(regeneratorRuntime.mark); // https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/function* function anotherGenerator(i) { return regeneratorRuntime.wrap(function anotherGenerator$(context$1$0) { while (1) switch (context$1$0.prev = context$1$0.next) { case 0: context$1$0.next = 2; return i + 1; case 2: context$1$0.next = 4; return i + 2; case 4: context$1$0.next = 6; return i + 3; case 6: case "end": return context$1$0.stop(); } }, marked0$0[0], this); } function generator(i) { return regeneratorRuntime.wrap(function generator$(context$1$0) { while (1) switch (context$1$0.prev = context$1$0.next) { case 0: context$1$0.next = 2; return i; case 2: return context$1$0.delegateYield(anotherGenerator(i), "t0", 3); case 3: context$1$0.next = 5; return i + 10; case 5: case "end": return context$1$0.stop(); } }, marked0$0[1], this); } var gen = generator(10); // 10 console.log(gen.next().value); // 11 console.log(gen.next().value); // 12 console.log(gen.next().value); // 13 console.log(gen.next().value); // 20 console.log(gen.next().value);
2.15625
2
lib/matcher.js
davidfirst/search-index-searcher
1
15992844
const Readable = require('stream').Readable const Transform = require('stream').Transform const util = require('util') const MatcherStream = function (q, options) { this.options = options Transform.call(this, { objectMode: true }) } util.inherits(MatcherStream, Transform) MatcherStream.prototype._transform = function (q, encoding, end) { const sep = this.options.keySeparator const that = this var results = [] const formatMatches = function (item) { if (q.type === 'ID') { that.push([item.key.split(sep)[2], item.value]) } else if (q.type === 'count') { that.push([item.key.split(sep)[2], item.value.length]) } else { that.push(item.key.split(sep)[2]) } } const sortResults = function (err) { err // TODO: what to do with this? results.sort(function (a, b) { return b.value.length - a.value.length }) .slice(0, q.limit) .forEach(formatMatches) end() } this.options.indexes.createReadStream({ start: 'DF' + sep + q.field + sep + q.beginsWith, end: 'DF' + sep + q.field + sep + q.beginsWith + sep }) .on('data', function (data) { results.push(data) }) .on('error', function (err) { that.options.log.error('Oh my!', err) }) .on('end', sortResults) } exports.match = function (q, options) { var s = new Readable({ objectMode: true }) q = Object.assign({}, { beginsWith: '', field: '*', threshold: 3, limit: 10, type: 'simple' }, q) if (q.beginsWith.length < q.threshold) { s.push(null) return s } s.push(q) s.push(null) return s.pipe(new MatcherStream(q, options)) }
1.609375
2
template/helpers.js
Waxolunist/gwt-api-generator
43
15992852
var _ = require('lodash'); module.exports = { marked: require('marked').setOptions({ gfm: true, tables: true, breaks: true, pedantic: true, sanitize: false, smartLists: true, smartypants: true }), javaKeywords: ['for', 'switch'], // TODO: if it's necessary add other keywords as well findBehavior: function(name) { for (var i = 0; name && i < global.parsed.length; i++) { var item = global.parsed[i]; if (this.isBehavior(item) && this.className(item.is) == this.className(name)) { return global.parsed[i]; } } }, findElement: function(name) { for (var i = 0; name && i < global.parsed.length; i++) { var item = global.parsed[i]; if (!this.isBehavior(item) && this.className(item.is) == this.className(name)) { return global.parsed[i]; } } }, isBehavior: function(item) { return ((item && item.type) || this.type) == 'behavior'; }, getNestedBehaviors: function(item, name) { var _this = this; var properties = []; var events = []; var behavior = this.findBehavior(name) if (behavior) { events = behavior.events; behavior.properties.forEach(function(prop) { prop.isBehavior = true; prop.behavior = _this.className(item.is); prop.signature = _this.signParamString(prop); properties.push(prop); }); if(behavior.behaviors) { behavior.behaviors.forEach(function(b) { var nestedBehaviors = _this.getNestedBehaviors(item, b); properties = _.union(properties, nestedBehaviors.properties); events = _.union(events, nestedBehaviors.events); }); } } return {properties: properties, events: events}; }, className: function (name) { return this.camelCase(name || this['name']); }, elementClassName: function(name) { return this.className(name) + (this.isBehavior() ? '' : 'Element'); }, baseClassName: function () { var _this = this; // Always extend native HTMLElement var e = ['HTMLElement']; if (this.behaviors && this.behaviors.length) { this.behaviors.forEach(function(name){ // CoreResizable -> CoreResizableElement, core-input -> CoreInputElment if (name && name.match(/[A-Z\-]/)) { if (_this.findBehavior(name)) { e.push(_this.camelCase(name)); } else { console.log("NOT FOUND: " + name + " " + _this.camelCase(name)); } } else { // input -> HTMLInputElement, table -> HTMLTableElement e.push('HTML' + _this.elementClassName(name)); } }); } return "extends " + e.join(','); }, camelCase: function(s) { return (s || '').replace(/^Polymer\./, '').replace(/[^\-\w\.]/g,'').replace(/(\b|-|\.)\w/g, function (m) { return m.toUpperCase().replace(/[-\.]/g, ''); }); }, hyphenize: function(s) { return s.replace(/([A-Z])/g, "-$1").toLowerCase(); }, computeMethodName: function(s) { return (s || '').replace(/-\w/g, function (m) { return m.toUpperCase().replace(/-/, ''); }); }, computeName: function(s) { return (s || '').replace(/[^\w\-\.:]/g, ''); }, computeType: function(t) { if (!t) return 'Object'; // TODO: Sometimes type have a syntax like: (number|string) // We should be able to overload those methods instead of using // Object, but JsInterop does not support well overloading if (/.*\|.*/.test(t)) return 'Object'; if (/^string|^computed/i.test(t)) return 'String'; if (/^boolean/i.test(t)) return 'boolean'; if (/^array/i.test(t)) return 'JsArray<E>'; if (/^element/i.test(t)) return 'Element'; if (/^htmlelement/i.test(t)) return 'HTMLElement'; if (/^number/i.test(t)) return 'double'; if (/^function/i.test(t)) return 'PolymerFunction'; if (this.findBehavior(t)) { return this.camelCase(t); } if (this.findElement(t)) { return this.camelCase(t) + 'Element'; } return "JavaScriptObject"; }, computeGenericType: function(t) { if (!t) return ''; // TODO: Sometimes type have a syntax like: (number|string) // We should be able to overload those methods instead of using // Object, but JsInterop does not support well overloading if (/^array/i.test(t)) return '<E>'; return ""; }, sortProperties: function(properties) { }, getGettersAndSetters: function(properties) { // Sorting properties so no-typed and String methods are at end properties.sort(function(a, b) { var t1 = this.computeType(a.type); var t2 = this.computeType(b.type); return t1 == t2 ? 0: !a.type && b.type ? 1 : a.type && !b.type ? -1: t1 == 'String' ? 1 : -1; }.bind(this)); var ret = []; // We use done hash to avoid generate same property with different signature (unsupported in JsInterop) var done = {}; // We use cache to catch especial cases of getter/setter no defined in the // properties block but as 'set foo:{}, get foo:{}' pairs. The hack is that // first we see a method with the a valid type (setter) and then we visit // a method with the same name but empty type (getter). var cache = {}; _.forEach(properties, function(item) { // We consider as properties: if ( // Items with the published tag (those defined in the properties section) item.published || // Non function items !item.private && item.type && !/function/i.test(item.type) || // Properties defined with customized get/set syntax !item.type && cache[item.name] && cache[item.name].type) { // defined with customized get/set, if we are here is because // this item.type is undefined and cached one has the correct type item = cache[item.name] ? cache[item.name] : item; item.getter = item.getter || this.computeGetterWithPrefix(item); item.setter = item.setter || (this.computeSetterWithPrefix(item) + '(' + this.computeType(item.type) + ' value)'); // JsInterop does not support a property with two signatures if (!done[item.getter]) { ret.push(item); done[item.getter] = true; } } else { cache[item.name] = item; } }.bind(this)); return ret; }, getStringSetters: function(properties) { var ret = []; var arr = this.getGettersAndSetters(properties); _.forEach(arr, function(item) { var itType = this.computeType(item.type) ; if (!/(PolymerFunction|String|boolean)/.test(itType)) { for (var j = 0; j< arr.length; j++) { if (arr[j].name == item.name && arr[j].type == 'String') { return; } } ret.push(item); } }.bind(this)); return ret; }, computeSignature: function(method) { return method.replace(/\s+\w+\s*([,\)])/g, '$1'); }, getMethods: function(properties) { // Sorting properties so Object methods are at first properties.sort(function(a, b) { var t1 = this.typedParamsString(a); var t2 = this.typedParamsString(b); return t1 == t2 ? 0: /^Object/.test(t1) ? -1 : 1; }.bind(this)); // Skip functions with name equal to a getter/setter var gsetters = {}; _.forEach(properties, function(item) { if (item.getter) { gsetters[item.getter] = true; gsetters[item.setter] = true; gsetters[item.name] = true; } }.bind(this)); var ret = []; var done = {}; _.forEach(properties, function(item) { if (!gsetters[item.name] && !item.getter && !item.private && !item.published && /function/i.test(item.type)) { item.method = item.method || item.name + '(' + this.typedParamsString(item) + ')'; // JsInterop + SDM do not support method overloading if one signature is object var other = item.method.replace(/String/, 'Object'); var signature = this.computeSignature(item.method); var other_sig = this.computeSignature(other); if (!gsetters[signature] && !done[signature] && !done[other_sig]) { ret.push(item); done[signature] = true; } } }.bind(this)); return ret; }, removePrivateApi: function(arr, prop) { for (var i = arr.length - 1; i >= 0; i--) { if (/^(_.*|ready|created)$/.test(arr[i][prop])) { arr.splice(i, 1); } } }, hasItems: function(array) { return array && array.length > 0; }, hasEvents: function() { return this.hasItems(this.events); }, hasProperties: function() { return this.hasItems(this.properties); }, hasParams: function() { return this.hasItems(this.params); }, capitalizeFirstLetter: function(string) { return string.charAt(0).toUpperCase() + string.slice(1); }, computeGetterWithPrefix: function(item) { var name = item.name.replace(/^detail\./,''); // replaced isXXX methods with getXXX temporary because of bug in JsInterop // because in the case of isNarrow, the JS generated is something like $object.arrow //var prefix = /^boolean/i.test(item.type) ? 'is' : 'get'; var prefix = 'get'; if (this.startsWith(name, prefix)) { return name; } else { return prefix + this.capitalizeFirstLetter(this.computeMethodName(name)); } }, computeSetterWithPrefix: function(item) { return 'set' + this.capitalizeFirstLetter(this.computeMethodName(item.name)); }, startsWith: function (str, substr){ return str.indexOf(substr) === 0; }, signParamString: function(method) { if (method.type != 'PolymerFunction') { return method.type; } var result = []; if (method.params) { method.params.forEach(function(param) { var type = this.computeType(param.type); result.push(type); }, this); } return result.join(','); }, typedParamsString: function(method) { var result = []; if (method.params) { method.params.forEach(function(param) { var type = this.computeType(param.type); result.push(type + ' ' + this.computeMethodName(param.name)); }, this); } return result.join(', '); }, paramsString: function(method) { var result = []; if (method.params) { method.params.forEach(function(param) { result.push(this.computeMethodName(param.name)); }, this); } return result.join(', '); }, returnString: function(method) { if (method['return'] && method['return']['type']) { return this.computeType(method['return']['type']) } return 'void'; }, getDescription: function(spaces, o) { o = o || this; var desc = o.description || o.desc || ''; desc = this.marked(desc); return (desc).trim().split('\n').join('\n' + spaces + '* ').replace(/\*\//g, "* /"); }, disclaimer: function() { var projectName = this.bowerData.name || "unknown"; var projectLicense = this.bowerData.license || "unknown"; var projectAuthors = this.bowerData.authors || this.bowerData.author; if (projectAuthors && projectAuthors.map) { projectAuthors = projectAuthors.map(function(author) { return author.name ? author.name : author; }).toString(); } projectAuthors = projectAuthors || "unknown author"; return "/*\n" + " * This code was generated with Vaadin Web Component GWT API Generator, \n" + " * from " + projectName + " project by " + projectAuthors + "\n" + " * that is licensed with " + projectLicense + " license.\n" + " */"; }, j2s: function(json, msg) { msg = msg || ''; var cache = []; console.log(msg + JSON.stringify(json, function(key, value) { if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { return; } cache.push(value); } return value; })); } };
1.476563
1
node_modules/@fluentui/react-northstar/dist/es/themes/teams/components/List/listItemContentMediaVariables.js
paige-ingram/nwhacks2022
0
15992860
export { listItemVariables as listItemContentMediaVariables } from './listItemVariables'; //# sourceMappingURL=listItemContentMediaVariables.js.map
0.251953
0
whiteboard-challenge-6/__test__/solution.test.js
YohanesDemissie/whiteboard-challenge
0
15992868
'use strict'; const loop = require('../lib/solution.js'); describe('loop module', function () { describe('#counter', function () { it('should return a number', function () { expect(loop.check(10, () => { console.log(counter)})) }) it('it should contain numeric data and not a string', function () { expect(loop.check(10, () => { console.log(counter) })) }) it('should have 2 arguments', function () { expect(loop.check(2, () => {console.log(counter) })) }) }) })
1.117188
1
src/options/getStore.js
empreinte-digitale/assistant-rgaa
18
15992876
import createStore from '../common/createStore'; import reducer from '../common/reducers'; import getInitialState from '../common/store/getInitialState'; /** * */ export default () => getInitialState().then((state) => createStore('options', reducer, undefined, state) );
0.800781
1
client/src/components/signup/signup.js
ZweatMonash/Square_Hacks
1
15992884
import React, { useState } from "react"; import { ColorButton, useStyles, NextButton } from "../button/button"; import swordLogo from "../../Images/sword.png"; import "./signup.css"; const SignUp = () => { const classes = useStyles(); const [identity, setIdentity] = useState(""); const identitySetter = async (val) => { await setIdentity(val); console.log(identity); }; return ( <div className="signInWrapper"> <div className="signInContainer"> <ul className="signInList"> <li className="signInItem"> <h2>Sign Up</h2> </li> <li className="signInItem"> <ColorButton variant="contained" color="primary" className={classes.margin} value="Individual" onClick={() => identitySetter("Individual")} > <h3>Individual</h3> </ColorButton> <ColorButton variant="contained" color="primary" className={classes.margin} value="Business" onClick={() => identitySetter("Business")} > <h3>Business</h3> </ColorButton> </li> {identity === "Business" ? ( <li className="signInItem inputBox"> <h5>Business Name</h5> <input className="signInInput" placeholder="Enter Business Name" type="text" required ></input> </li> ) : ( <li className="signInItem inputBox"> <h5>User Name</h5> <input className="signInInput" placeholder="Enter User Name" type="text" required ></input> </li> )} <li className="signInItem inputBox"> <h5>Email</h5> <input className="signInInput" placeholder="<EMAIL>" type="text" min="5" max="20" required ></input> </li> <li className="signInItem inputBox"> <h5>Phone Number</h5> <input className="signInInput" placeholder="0459058069" type="text" min="5" max="20" required ></input> </li> <li className="signInItem inputBox"> <h5>Choose Password</h5> <input className="signInInput" placeholder="Enter Password" type="password" max="15" required ></input> </li> <li className="signInItem"> <ColorButton variant="contained" color="primary" className={classes.margin} > <h3>Next</h3> </ColorButton> </li> </ul> </div> </div> ); }; export default SignUp;
1.710938
2
public/helpers/procOut.js
Push-EDX/APE
10
15992892
const exec = require('child_process').exec; exec('tasklist /fo csv /nh', (err, stdout, stderr) => { if (err) { console.error(err); return; } console.log(stdout); });
0.867188
1
examples/todos/store.js
hy-dev/exim
75
15992900
var Link = Exim.Link; var getRandomId = function() { return (Date.now() + Math.floor(Math.random() * 999999)).toString(36); }; var textIsEmpty = function(text) { return text.trim() === ''; }; var areAllComplete = function(todos) { for (var id in todos) { if (!todos[id].complete) { return false; } } return true; }; var TodoStore = Exim.createStore({ actions: [ 'create', 'updateText', 'toggleComplete', 'toggleCompleteAll', 'destroy', 'destroyCompleted', 'updateTodo', 'updateAll' ], initial: { todos: {} }, updateTodo: function(id, updates) { var todos = this.get('todos'); for(var update in updates) { todos[id][update] = updates[update]; } this.set({todos: todos}); }, updateAll: function(updates) { var todos = this.get('todos'); for (var id in todos) { this.actions.updateTodo(id, updates); } this.set({todos: todos}); }, create: function(text) { if(textIsEmpty(text)) return false; var todos = this.get('todos'); var id = getRandomId(); todos[id] = {id: id, complete: false, text: text.trim()}; this.set('todos', todos); }, updateText: { will: function(id, text) { return [id, text.trim()]; }, on: function(id, text) { if(text && id > 0) this.actions.updateTodo(id, {text: text}) } }, toggleComplete: function(id) { var todo = this.get('todos')[id]; this.actions.updateTodo(id, {complete: !todo.complete}) }, toggleCompleteAll: function() { var complete = !areAllComplete(this.get('todos')); this.actions.updateAll({complete: complete}) }, destroy: function(id) { var todos = this.get('todos') delete todos[id]; this.set('todos', todos); }, destroyCompleted: function() { var todos = this.get('todos'); for (var id in todos) { if (todos[id].complete) { delete todos[id]; } } this.set('todos', todos); } });
1.414063
1
Classes/Database.js
Legocro/Kapparina
0
15992908
class DatabaseClient { constructor(MainClient) { this._Client = MainClient; this.sql = require("sqlite"); this.start(); } async start() { await this.sql.open("./bot.sqlite"); await this.sql.run("CREATE TABLE IF NOT EXISTS FishGame (UserId TEXT PRIMARY KEY, Points INTEGER, Timestamp TEXT)") } async createRow(id) { await this.sql.run(`INSERT OR IGNORE INTO FishGame (UserId, Points, Timestamp) VALUES ("${id}", 0, "xx")`); } async getPoints(id) { let fish = await this.sql.get(`SELECT Points FROM FishGame WHERE UserId = "${id}"`).catch((e) => { console.error; this.sql.run("CREATE TABLE IF NOT EXISTS FishGame (UserId TEXT PRIMARY KEY, Points DOUBLE PRECISION, Timestamp TEXT)").then(async () => { //this.sql.run(`INSERT INTO Coins (UserId, Coins, Address, LastBalance) VALUES ("${id}", 0, "xx", 0)`); await this.createRow(id); }) }) if (fish != undefined) return fish.Points; return 0; } async setPoints(id, points) { let success = await this.sql.run(`UPDATE FishGame SET Points = ${points} WHERE UserId = "${id}"`).catch(e => console.error(e)); } async addPoints(id, points) { let currentPoints = await this.getPoints(id); this.setPoints(id, currentPoints + points); } async getPosition(id) { let rows = await this.sql.all("SELECT UserId FROM FishGame ORDER BY Points DESC").catch(console.error); return rows.findIndex((row) => row.UserId == id) + 1; } async getTopFiveScores(){ let rows = await this.sql.all("SELECT UserId, Points from FishGame ORDER BY Points DESC LIMIT 5").catch(console.error); return rows; } } module.exports = DatabaseClient
2.15625
2
router/main.js
LEEJINJU-1214/Medity
1
15992916
const crypto = require('crypto'); const session = require('express-session'); const MySQLStore = require('express-mysql-session')(session); const bodyParser = require('body-parser'); const { join } = require('path'); // const { test2 } = require('../public/js/argiculture'); // const argi = require('../public/js/argiculture'); // import argiculture from "js/argiculture.js" // const { web3 } = window // const selectedAddress = web3.eth.defaultAccount // var mysql = require('mysql'); // var dbConfig = require('./dbconfig'); // var conn = mysql.createConnection(dbOptions); // conn.connect(); module.exports = function (app) { app.use(session({ secret: '!@#$%^&*', // store: new MySQLStore(dbOptions), resave: false, saveUninitialized: false })); app.use(bodyParser.json()); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.get('/', function (req, res) { if (!req.session.name) res.redirect('/login'); else res.redirect('/main'); }); app.get('/login', function (req, res) { if (!req.session.name) res.render('login', { message: 'input your id and password.' }); else res.redirect('/main'); }); app.get('/main', function (req, res) { if (!req.session.name) return res.redirect('/login'); else res.render('customer', { name: req.session.name }); }); app.get('/main2', function (req, res) { if (!req.session.name) return res.redirect('/login'); else if(!req.session.cus_addr) res.render('doctor', { name: req.session.name, cus_name: "아래에환자Address를입력해주세요" }); else res.render('doctor', { name: req.session.name, cus_name: req.session.cus_addr }); }); // app.get('/addrsave', function (req, res) { // if (!req.session.name) // return res.redirect('/login'); // else if(!req.session.cus_addr) // res.render('doctor', { name: req.session.name, cus_name: "환자Address입력" }); // else // res.render('doctor', { name: req.session.name, cus_name: req.session.cus_addr }); // }); app.get('/about', function (req, res) { res.render('about.html',{ name: req.session.name }); }); app.get('/contact', function (req, res) { if(!req.session.cus_addr) res.render('contact.html', { cus_name: "Home에서환자Address를저장해주세요" }); else res.render('contact.html', { cus_name: req.session.cus_addr }); }); app.get('/Gall_doc', function (req, res) { res.render('Gall_doc.html',{ name: req.session.name, cus_name: req.session.cus_addr }); }); app.get('/Gall_cus', function (req, res) { res.render('Gall_cus.html',{ name: req.session.name }); }); app.get('/logout', function (req, res) { req.session.destroy(function (err) { res.redirect('/'); }); }); // app.post('/upload', function (req, res) { // let proloc = req.body.proloc; // let prohospital = req.body.prohospital; // contract.addProStru(howMany, productName, whereIs, function(err, result) { // if (err) // return showError("Smart contract call failed: " + err); // showInfo(`Document ${result} <b>successfully added</b> to the registry.`); // }); // }); // document.write("<script type='text/javascript' src='js/argiculture.js'><"+"/script>"); app.post('/main', function(req, res) { let id = req.body.addr; req.session.name = id; console.log("환자 addr : ",id); req.session.save(function () { return res.redirect('/main'); }); }); app.post('/main2', function(req, res) { let id = req.body.addr; req.session.name = id; console.log("의사 addr : ", id); req.session.save(function () { return res.redirect('/main2'); }); }); app.post('/addrsave', function(req, res) { let cus_addr = req.body.cus_addr; req.session.cus_addr = cus_addr; console.log("customer address(addrsave) : ", cus_addr); // req.session.save(); req.session.save(function () { return res.redirect('/main2'); }); // res.render('contact.html'); }); app.post('/login', function (req, res) { let id = req.body.username; let password = req.body.password; let salt = ''; let pw = ''; // if (window.ethereum) // try { // await window.ethereum.enable(); // } catch (err) { // return showError("Access to your Ethereum account rejected."); // } // if (typeof web3 === 'undefined') // return showError("Please install MetaMask to access the Ethereum Web3 injected API from your Web browser."); // let account = selectedAddress // console.log("my account " , account); crypto.randomBytes(64, (err, buf) => { if (err) throw err; salt = buf.toString('hex'); }); crypto.pbkdf2(password, salt, 100000, 64, 'sha512', (err, derivedKey) => { if (err) throw err; pw = derivedKey.toString('hex'); }); // var user = results[0]; crypto.pbkdf2(password, salt, 100000, 64, 'sha512', function (err, derivedKey) { if (err) console.log(err); if (derivedKey.toString('hex') === pw) { req.session.name = id; req.session.save(function () { return res.redirect('/main'); }); } else { return res.render('login', { message: 'please check your password.' }); } });//pbkdf2 }); // end of app.post }
1.375
1
studioactions/mobile/p2kwiet128893149516_button1927359800104647_onClick_seq0.js
r1pc0rd/KitchenSink
0
15992924
function p2kwiet128893149516_button1927359800104647_onClick_seq0(eventobject) { regAccEvent.call(this); frmRegisterAccelerometer.show(); }
0.421875
0
note/is.js
195286381/file
0
15992932
/*! * is.js V0.0.1 * Author: Xz_zzzz */ ; (function(root, factory) { // 实现多模块兼容 if (typeof define === 'function' && define.amd) { // AMD兼容 注册一个匿名模块 define(function() { // Also create a global in case some scripts // that are loaded still are looking for // a global even when an AMD loader is in use. return (root.is = factory()); }); } else if (typeof exports === 'object') { // Node. 不仅兼容严格的CommonJS模块, // 也支持像Node这种支持module.exports的CommonJS-like环境 module.exports = factory(); } else { // 浏览器全局变量 root.is = factory(); } })(this, function() { // Baseline /*-----------------------------------------------------------------------*/ // 定义is对象和当前的版本 var is = {}; is.Version = '0.0.1'; // 定义接口 is.not = {}; is.all = {}; is.any = {}; // 定义一些后面需要调用的方法 var toString = Object.property.toString; var slice = Object.proprtty.slice; var hasOwnProperty = Object.proprtty.hasOwnProperty; // 用来反转断言结果的帮助函数 function not(func) { return function() { return !func.apply(null, slice.call(arguments)); } } function all(func) { var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!func.call(null, arg)) { return false; } } return true; } function any(func) { var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments; if (func.call(null, arg)) { return true; } } return false; } // 绑定接口 function setInterfaces() { var interfaces = ['not', 'all', 'any'], interface; for (var i = 0; i < interfaces.length; i++) { interface = interfaces[i]; for (var method in is) { if (is.hasOwnProperty(method)) { switch (interface) { case 'not': { is[interface][method] = not[method]; } break; case 'all': { is[interface][method] = all[method]; } break; case 'any': { is[interface][method] = any[method]; } break; default: } } } } } }); (function(window) { var is = {}; is.Number = function(para) { // 判断是不是数字 return typeof para === 'number'; } is.String = function(para) { // 判断是不是字符串 return typeof para === 'string'; } is.Boolean = function(para) { // 判断是不是布尔值 return typeof para === 'boolean'; } is.Null = function(para) { // 判断是不是null return null === para; } is.Undefined = function(para) { // 判断是不是undefined return undefined === para; } is.NaN = function(para) { // 判断是不是NaN return window.isNaN(para); } is.Array = function(para) { // 判断是不是数组 return Object.prototype.toString.call(para) === '[object Array]'; } is.PlainObject = function(para) { // 判断是不是PlainObject return Object.prototype.toString.call(para) === '[object Object]'; } is.Function = function(para) { // 判断是不是函数 return Object.prototype.toString.call(para) === '[object Function]' } is.is = function(typeInfo, para) { // if (arguments.length < 2) { throw new Error('parameters is needed more than one'); } else if (typeof arguments[0] !== 'string') { throw new TypeError('the first parameter should be a string'); } // var isType = false; for (var prop in is) { if (is.hasOwnProperty(prop)) { if (prop.toLowerCase() === typeInfo.toLowerCase() && Object.prototype.toString.call(is[prop]) === '[object Function]') { return is[prop](para); } } } } window.is = is; })(window);
1.507813
2
scripts/utils/translations.js
mauriciovieira/mauriciovieira.net
0
15992940
import { resolveObjectByPath } from './util' var I18n = { translations: { }, locale: '', t: function translate(key){ let result = "not found" let translation = this.translations[this.locale] if(translation){ result = resolveObjectByPath(translation, key) } return result } } const en = { myself: { about: "Software Engineer", contact: { email: '<EMAIL>' } } } const es = { myself: { about: "Ingeniero de Software", contact: { email: '<EMAIL>' } } } const ptBR = { myself: { about: "Engenheiro de Software", contact: { email: '<EMAIL>' } } } I18n.translations["en"] = en I18n.translations["es"] = es I18n.translations["pt-BR"] = ptBR export default I18n
1.671875
2
wp-content/themes/customify/assets/js/theme.js
icebergsal/thetimesharefirm.com
2
15992948
/** * Customify theme javaScript. * * @since 0.2.6 * * Copyright 2017, PressMaximum */ "use strict"; // prevent global namespace pollution /** * matches() pollyfil * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill */ if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector; } /** * closest() pollyfil * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill */ if (!Element.prototype.closest) { Element.prototype.closest = function(s) { var el = this; if (!document.documentElement.contains(el)) { return null; } do { if (el.matches(s)) { return el; } el = el.parentElement || el.parentNode; } while (el !== null && el.nodeType === 1); return null; }; } /** * Main Customify Scripts */ (function() { var Customify = function() { this.options = { menuToggleDuration: 300 }; this.menuSidebarState = "closed"; this.isPreviewing = document.body.classList.contains( "customize-previewing" ); this.init(); }; /** * Add body class to check touch screen. */ Customify.prototype.checkTouchScreen = function() { if ("ontouchstart" in document.documentElement) { document.body.classList.add("ontouch-screen"); } else { document.body.classList.add("not-touch-screen"); } }; /** * Check if current mobile viewing. * * @return bool */ Customify.prototype.isMobile = function() { if ( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ) { return true; } else { return false; } }; /** * Init mobile sidebar. * * @todo Move menu sidebar to body. * @todo Add events to menu buttons. */ Customify.prototype.initMenuSidebar = function() { var themeMenuSidebar; if (document.body.classList.contains("menu_sidebar_dropdown")) { // $( '#header-menu-sidebar' ).insertAfter( "#masthead" ); } else { themeMenuSidebar = document.getElementById("header-menu-sidebar"); if (themeMenuSidebar) { document.body.append(themeMenuSidebar); } } document.addEventListener( "customize_section_opened", function(e) { if (e.detail === "header_sidebar") { this.toggleMenuSidebar(false); } }.bind(this) ); var menuMobileToggleButtons = document.querySelectorAll( ".menu-mobile-toggle" ); /** * When click to toggle buttons. */ this.addEvent( menuMobileToggleButtons, "click", function(e) { e.preventDefault(); this.toggleMenuSidebar(); }.bind(this) ); var closeButtons = document.querySelectorAll( "#header-menu-sidebar .close-panel, .close-sidebar-panel" ); /** * When click close buttons. */ this.addEvent( closeButtons, "click", function(e) { e.preventDefault(); this.closeMenuSidebar(); }.bind(this) ); /** * When click to ouside of menu sidebar. */ this.addEvent( document, "click", function(e) { if (document.body.classList.contains("is-menu-sidebar")) { var menuSidebar = document.getElementById( "header-menu-sidebar" ); var buttons = document.querySelectorAll( ".menu-mobile-toggle" ); var outside = false; // If the click happened inside the the container, bail if ( !e.target.closest("#header-menu-sidebar") && e.target !== menuSidebar ) { // Outside menu sidebar. outside = true; } // Check if not click to menu toggle buttons. var onButton = false; if (buttons.length) { for (var i = 0; i < buttons.length; i++) { // If click on toggle button. if ( e.target.closest(".menu-mobile-toggle") || e.target === buttons[i] ) { onButton = true; } } } if (outside && !onButton) { this.closeMenuSidebar(); } } }.bind(this) ); this.addEvent( document, "keyup", function(e) { if (e.keyCode === 27) { this.closeMenuSidebar(); } }.bind(this) ); }; /** * Init mobile search form * * @todo Need check */ Customify.prototype.initMobieSearchForm = function() { var mobileSearchForm = document.querySelector(".search-form--mobile"); if (mobileSearchForm) { mobileSearchForm.classList.add( "mobile-search-form-sidebar menu-sidebar-panel" ); mobileSearchForm.classList.remove("hide-on-mobile hide-on-tablet"); document.body.prepend(mobileSearchForm); } }; Customify.prototype.toggleMobileSubmenu = function(e) { e.preventDefault(); var that = this; var li = e.target.closest("li"); var firstSubmenu = li.querySelectorAll( ":scope > .sub-menu, .sub-lv-0" ); if (!li.classList.contains("open-sub")) { // Show the sub menu. li.classList.add("open-sub"); if (firstSubmenu.length) { for (var i = 0; i < firstSubmenu.length; i++) { that.slideDown( firstSubmenu[i], this.options.menuToggleDuration, function() { li.classList.add("open-sub"); } ); } } } else { // Hide the sub menu. if (firstSubmenu.length) { for (var i = 0; i < firstSubmenu.length; i++) { that.slideUp( firstSubmenu[i], this.options.menuToggleDuration, function() { li.classList.remove("open-sub"); } ); } } } }; /** * Add events listener for mobile toggle button. * * @param Element toggleIcon */ Customify.prototype.toggleMobileSubmenuEvents = function(toggleIcon) { toggleIcon.addEventListener( "click", this.toggleMobileSubmenu.bind(this) ); }; /** * Inital mobile submenu. */ Customify.prototype.initMobileSubMenu = function() { var menuChildren = document.querySelectorAll( "#header-menu-sidebar .nav-menu-mobile .menu-item-has-children" ); if (menuChildren.length) { for (var i = 0; i < menuChildren.length; i++) { var child = menuChildren[i]; if (!child.classList.contains("toggle--added")) { child.classList.add("toggle--added"); var fistLink = child.querySelector(":scope > a"); var d = fistLink.cloneNode(true); if (this.isPreviewing) { } var toggleButton = document.createElement("span"); toggleButton.classList.add("nav-toggle-icon"); toggleButton.innerHTML = '<i class="nav-icon-angle"></i>'; fistLink.parentNode.insertBefore(toggleButton, fistLink); var submenu = child.querySelector(":scope > .sub-menu"); if( '1' !== Customify_JS.sidebar_menu_no_duplicator ){ submenu.prepend(d); } var firstSubmenu = child.querySelectorAll( ":scope > .sub-menu, .sub-lv-0" ); if (firstSubmenu.length) { for (var j = 0; j < firstSubmenu.length; j++) { this.slideUp(firstSubmenu[j], 0); } } if( '1' !== Customify_JS.sidebar_menu_no_duplicator ){ var dWrapper = document.createElement("li"); d.parentNode.prepend(dWrapper); dWrapper.appendChild(d); } this.toggleMobileSubmenuEvents(toggleButton); } } } }; /** * SideUp * * @param Element element * @param number duration * @param function callBack */ Customify.prototype.slideUp = function(element, duration, callBack) { if (typeof duration !== "number") { duration = 0; } // if ( element._sideUpTimeOut ) { // clearTimeout( element._sideUpTimeOut ); // element._sideUpTimeOut = false; // } if (element._slideDownTimeOut) { clearTimeout(element._slideDownTimeOut); element._slideDownTimeOut = false; } // Get orignal height. var offset = element.getBoundingClientRect(); // Back to default. element.style.overflow = "hidden"; element.style.height = offset.height + "px"; element.style.transition = "height " + duration + "ms linear"; setTimeout(function() { element.style.height = "0px"; }, 20); element._sideUpTimeOut = setTimeout(function() { element.style.transition = ""; if (typeof callBack === "function") { callBack.call(this); } }, duration + 20); }; /** * * @param Element element * @param number duration * @param function callBack */ Customify.prototype.slideDown = function(element, duration, callBack) { if (typeof duration !== "number") { duration = 0; } if (element._sideUpTimeOut) { clearTimeout(element._sideUpTimeOut); element._sideUpTimeOut = false; } // if ( element._slideDownTimeOut ) { // clearTimeout( element._slideDownTimeOut ); // element._slideDownTimeOut = false; // } // Reset element styling to get orignal height. element.style.height = "initial"; element.style.overflow = "initial"; element.style.transition = ""; // Get orignal height. var offset = element.getBoundingClientRect(); // Back to default. element.style.height = "0px"; element.style.overflow = "hidden"; element.style.transition = "height " + duration + "ms linear"; setTimeout(function() { element.style.height = offset.height + "px"; }, 50); element._sideUpTimeOut = setTimeout(function() { element.style.height = ""; element.style.overflow = ""; element.style.transition = ""; if (typeof callBack === "function") { callBack.call(this); } }, duration); }; Customify.prototype.insertMenuOverlayClass = function() { var navMobile = document.querySelector(".nav-menu-mobile"); if (navMobile) { if ( document.body.classList.contains("menu_sidebar_slide_overlay") ) { navMobile.classList.add("nav-menu-overlay"); } else { navMobile.classList.remove("nav-menu-overlay"); } } }; Customify.prototype.setupMobileItemAnimations = function(element) { var h = window.height; if (typeof element === "undefined") { element = document.getElementById("header-menu-sidebar"); } var t = 0.2; var index = 0; var itemsInner = element.querySelectorAll(".item--inner"); if (itemsInner.length) { for (var i = 0; i < itemsInner.length; i++) { index++; itemsInner[i].style.transitionDelay = index * t + "s"; } } }; /** * Toogle Element class name. * * @param Element element * @param string className */ Customify.prototype.toggleClass = function(element, className) { if (element instanceof NodeList) { for (var i = 0; i < element.length; i++) { if (element[i].classList.contains(className)) { element[i].classList.remove(className); } else { element[i].classList.add(className); } } } else if (element instanceof Node || element instanceof Element) { if (element.classList.contains(className)) { element.classList.remove(className); } else { element.classList.add(className); } } }; /** * Add class to element. * * @param Element element * @param string className */ Customify.prototype.addClass = function(element, className) { if (element instanceof NodeList) { for (var i = 0; i < element.length; i++) { element[i].classList.add(className); } } else if (element instanceof Node || element instanceof Element) { element.classList.add(className); } }; /** * Remove class name from element. * * @param Element element * @param string className */ Customify.prototype.removeClass = function(element, className) { // Split each class by space. var classes = className.split(" "); if (element instanceof NodeList) { for (var i = 0; i < element.length; i++) { for (var j = 0; j < classes.length; j++) { element[i].classList.remove(classes[j]); } } } else if (element instanceof Node || element instanceof Element) { for (var j = 0; j < classes.length; j++) { element.classList.remove(classes[j]); } } }; /** * Add event handle to elements. * * @param Element element * @param string event * @param function callBack */ Customify.prototype.addEvent = function(element, event, callBack) { if (element instanceof NodeList) { for (var i = 0; i < element.length; i++) { element[i].addEventListener(event, callBack); } } else if (element instanceof Node || element instanceof Element) { element.addEventListener(event, callBack); } }; /** * Close menu sidebar. */ Customify.prototype.closeMenuSidebar = function() { document.body.classList.add("hiding-header-menu-sidebar"); document.body.classList.remove("is-menu-sidebar"); var toggleButtons = document.querySelectorAll( ".menu-mobile-toggle, .menu-mobile-toggle .hamburger" ); this.removeClass(toggleButtons, "is-active"); /** * For dropdown sidebar. */ if (document.body.classList.contains("menu_sidebar_dropdown")) { this.removeClass(document.body, "hiding-header-menu-sidebar"); var menuSidebar = document.getElementById("header-menu-sidebar"); var menuSidebarInner = document.getElementById( "header-menu-sidebar-inner" ); var offset = menuSidebarInner.getBoundingClientRect(); var h = offset.height; this.slideUp( menuSidebar, 300, function() { menuSidebar.style.height = 0; menuSidebar.style.display = "block"; }.bind(this) ); } else { // Else slide sidebar. setTimeout( function() { this.removeClass( document.body, "hiding-header-menu-sidebar" ); }.bind(this), 1000 ); } }; /** * Toggle menu sidebar. * * @param bool open use animation or not. */ Customify.prototype.toggleMenuSidebar = function(toggle) { if (typeof toggle === "undefined") { toggle = true; } document.body.classList.remove("hiding-header-menu-sidebar"); if (!toggle) { document.body.classList.add("is-menu-sidebar"); } else { this.toggleClass(document.body, "is-menu-sidebar"); } if (document.body.classList.contains("menu_sidebar_dropdown")) { var buttons = document.querySelectorAll( ".menu-mobile-toggle, .menu-mobile-toggle .hamburger" ); if (toggle) { this.toggleClass(buttons, "is-active"); } else { this.addClass(buttons, "is-active"); } if (document.body.classList.contains("is-menu-sidebar")) { var menuSidebar = document.getElementById( "header-menu-sidebar" ); var menuSidebarInner = document.getElementById( "header-menu-sidebar-inner" ); var offset = menuSidebarInner.getBoundingClientRect(); var h = offset.height; this.slideDown(menuSidebar, 300, function() { menuSidebar.style.height = h + "px"; }); } else { if (toggle) { this.closeMenuSidebar(); } } } }; /** * Auto align search form. */ Customify.prototype.searchFormAutoAlign = function() { var searchItems = document.querySelectorAll(".header-search_icon-item"); var w = window.innerWidth; for (var i = 0; i < searchItems.length; i++) { var container = searchItems[i]; var button = container.querySelector(".search-icon"); var buttonOffset = button.getBoundingClientRect(); this.removeClass(container, "search-right search-left"); if (buttonOffset.left > w / 2) { this.removeClass(container, "search-right"); this.addClass(container, "search-left"); } else { this.removeClass(container, "search-left"); this.addClass(container, "search-right"); } } }; /** * Search form. */ Customify.prototype.initSearchForm = function() { var searchItems = document.querySelectorAll(".header-search_icon-item"); var that = this; searchItems.forEach( function( container ){ //let container = searchItems[i]; that.removeClass(container, "active"); var icon = container.querySelector(".search-icon"); /** * Add event handle when click to icon. */ that.addEvent( icon, "click", function(e) { e.preventDefault(); this.toggleClass( container, "active"); var inputField = container.querySelector(".search-field"); if (!container.classList.contains("active")) { inputField.blur(); } else { inputField.focus(); } }.bind(that) ); /** * When click outside search form. */ that.addEvent( document, "click", function(e) { // if the target of the click isn't the container nor a descendant of the container if ( !(container === e.target) && !container.contains(e.target) ) { that.removeClass(container, "active"); } }.bind(that) ); } ); that.searchFormAutoAlign(); }; /** * Wrapper element * * @param Element element * @param strig tag Tag name. * * @return Element */ Customify.prototype.wrapper = function(element, tag) { if (typeof tag === "undefined") { tag = "div"; } var wrapper = document.createElement(tag); element.parentNode.replaceChild(wrapper, element); wrapper.appendChild(element); return wrapper; }; /** * Responsive table. */ Customify.prototype.responsiveTable = function() { var tables = document.querySelectorAll(".entry-content table"); for (var i = 0; i < tables.length; i++) { if (!tables[i].parentNode.classList.contains("table-wrapper")) { // Wrap table by each div.table-wrapper var dWrapper = document.createElement("div"); dWrapper.classList.add("table-wrapper"); tables[i].parentNode.replaceChild(dWrapper, tables[i]); dWrapper.appendChild(tables[i]); } } }; /** * Reponsive video style. */ Customify.prototype.responsiveVideos = function() { }; /** * Inittial */ Customify.prototype.init = function() { this.checkTouchScreen(); this.initMobieSearchForm(); this.initMobileSubMenu(); this.insertMenuOverlayClass(); this.setupMobileItemAnimations(); this.initMenuSidebar(); this.initSearchForm(); this.responsiveTable(); this.responsiveVideos(); /** * Add action when Header Panel rendered by customizer. */ document.addEventListener( "header_builder_panel_changed", function() { this.initMobileSubMenu(); this.insertMenuOverlayClass(); }.bind(this) ); // Add actions when window resize. var tf; window.addEventListener( "resize", function() { // Resetup mobile animations this.setupMobileItemAnimations(); // Resetup search form alignmenet. this.removeClass( document.querySelectorAll(".header-search_icon-item"), "active" ); if (tf) { clearTimeout(tf); } tf = setTimeout(this.searchFormAutoAlign.bind(this), 100); }.bind(this) ); document.addEventListener( "selective-refresh-content-rendered", function(e) { if (e.detail === "customify_customize_render_header") { this.initSearchForm(); } }.bind(this) ); }; /** * Check is mobile. * This may use in plugins. * * @deprecated 0.2.6 */ function customify_is_mobile() { return Customify.isMobile(); } window.customify_is_mobile = customify_is_mobile; window.Customify = new Customify(); /** * Fix viewport units on Mobile. */ (function() { if ( window.Customify.isMobile() ) { /** * https://css-tricks.com/the-trick-to-viewport-units-on-mobile/ */ // First we get the viewport height and we multiple it by 1% to get a value for a vh unit var vh = window.innerHeight * 0.01; var vw = window.innerWidth * 0.01; // Then we set the value in the --vh, --vw custom property to the root of the document document.documentElement.style.setProperty("--vh", vh+'px'); document.documentElement.style.setProperty("--vw", vw+'px'); window.addEventListener("resize", function() { var vh = window.innerHeight * 0.01; var vw = window.innerWidth * 0.01; document.documentElement.style.setProperty("--vh", vh+'px'); document.documentElement.style.setProperty("--vw", vw+'px'); }); } })(); })(); /** * * Handles toggling the navigation menu for small screens and enables TAB key * navigation support for dropdown menus. */ (function() { var container, button, menu, links, i, len; container = document.getElementById("site-navigation-main-desktop"); if (!container) { return; } menu = container.getElementsByTagName("ul")[0]; // Hide menu toggle button if menu is empty and return early. if ("undefined" === typeof menu) { return; } menu.setAttribute("aria-expanded", "false"); if (-1 === menu.className.indexOf("nav-menu")) { menu.className += " nav-menu"; } // Get all the link elements within the menu. links = menu.getElementsByTagName("a"); // Each time a menu link is focused or blurred, toggle focus. for (i = 0, len = links.length; i < len; i++) { links[i].addEventListener("focus", toggleFocus, true); links[i].addEventListener("blur", toggleFocus, true); } /** * Sets or removes .focus class on an element. */ function toggleFocus() { var self = this; // Move up through the ancestors of the current link until we hit .nav-menu. while (-1 === self.className.indexOf("nav-menu")) { // On li elements toggle the class .focus. if ("li" === self.tagName.toLowerCase()) { if (-1 !== self.className.indexOf("focus")) { self.className = self.className.replace(" focus", ""); } else { self.className += " focus"; } } self = self.parentElement; } } /** * Toggles `focus` class to allow submenu access on tablets. */ (function(container) { var touchStartFn, i, parentLink = container.querySelectorAll( ".menu-item-has-children > a, .page_item_has_children > a" ); if ("ontouchstart" in window) { touchStartFn = function(e) { var menuItem = this.parentNode, i; if (!menuItem.classList.contains("focus")) { e.preventDefault(); for (i = 0; i < menuItem.parentNode.children.length; ++i) { if (menuItem === menuItem.parentNode.children[i]) { continue; } menuItem.parentNode.children[i].classList.remove( "focus" ); } menuItem.classList.add("focus"); } else { menuItem.classList.remove("focus"); } }; for (i = 0; i < parentLink.length; ++i) { parentLink[i].addEventListener( "touchstart", touchStartFn, false ); } } })(container); })(); /** * * Helps with accessibility for keyboard only users. * * Learn more: https://git.io/vWdr2 */ (function() { var isIe = /(trident|msie)/i.test(navigator.userAgent); if (isIe && document.getElementById && window.addEventListener) { window.addEventListener( "hashchange", function() { var id = location.hash.substring(1), element; if (!/^[A-z0-9_-]+$/.test(id)) { return; } element = document.getElementById(id); if (element) { if ( !/^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) { element.tabIndex = -1; } element.focus(); } }, false ); } })();
1.0625
1
src/plugin.js
saffari-m/videojs-controls-badge
7
15992956
import videojs from "video.js"; import { version as VERSION } from "../package.json"; import Badge from "./components/index"; const Plugin = videojs.getPlugin("plugin"); // Default options for the plugin. const defaults = {}; /** * An advanced Video.js plugin. For more information on the API * * See: https://blog.videojs.com/feature-spotlight-advanced-plugins/ */ class ControlsBadge extends Plugin { /** * Create a ControlsBadge plugin instance. * * @param {Player} player * A Video.js Player instance. * * @param {Object} [options] * An optional options object. * * While not a core part of the Video.js plugin architecture, a * second argument of options is a convenient way to accept inputs * from your plugin's caller. */ constructor(player, options) { // the parent class will add player under this.player super(player); this.options = videojs.mergeOptions(defaults, options); this.player.ready(() => { this.player.addClass("vjs-controls-badge"); this.initial(); }); } /** * Initial `controls-badge` logic * */ initial() { const badge = new Badge(this.player, this.options); badge.createBadges(); } } // Define default values for the plugin's `state` object here. ControlsBadge.defaultState = {}; // Include the version number. ControlsBadge.VERSION = VERSION; // Register the plugin with video.js. videojs.registerPlugin("controlsBadge", ControlsBadge); export default ControlsBadge;
1.710938
2
src/views/umc/datasource/index.js
wl4g/super-cloudops-view
2
15992964
import DataSource from './DataSource.vue' export default DataSource
0.351563
0
webpack.config.js
tuberrabbit/demo-webpack
0
15992972
'use strict'; module.exports = { entry: { app: './src/app', a: './src/aa', b: './src/bb', c: ['./src/cc', './src/dd'] }, output: { path: './dist', filename: '[name].entry.js' }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.scss$/, loader: 'style!css!sass' }] } };
0.769531
1
webpack/webpack.config.dev.js
acmilank22/react-app
0
15992980
/* cspell: disable-next-line */ const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin'); const config = require('config'); const { merge } = require('webpack-merge'); const paths = require('../scripts/utils/paths'); const baseConfig = require('./webpack.config.base'); const serverPort = config?.server?.port; const serverProxy = config?.server?.proxy; const devConfig = { output: { filename: 'js/[name].js', chunkFilename: 'js/[name].chunk.js', }, devtool: 'cheap-module-source-map', devServer: { port: serverPort, proxy: serverProxy, historyApiFallback: true, hot: true, static: { directory: paths.dist, }, devMiddleware: { stats: 'errors-warnings', }, }, plugins: [new ReactRefreshWebpackPlugin()], }; module.exports = merge(baseConfig, devConfig);
1.140625
1
docs/code/html/search/classes_6.js
carl-221b/gen_planete
0
15992988
var searchData= [ ['random_5feditor',['Random_Editor',['../class_random___editor.html',1,'']]], ['rendering',['Rendering',['../class_rendering.html',1,'']]], ['rendering_5fopengl',['Rendering_OpenGL',['../class_rendering___open_g_l.html',1,'']]] ];
0.035156
0
node_modules/discord/classes/Command.js
norbi617/1337bot
2
15992996
/** * Command classes are bound to the player. */ Command = new Class({ Implements: CommandParser, //Command is filled in by the object that instantiates this object, since it //knows the file name and we don't. command: '', initialize: function(command) { this.command = command; this.init(); if (!this.getPatterns(this.command)) { this.add_command(this.command, this.syntax || '*', this.execute); } }, //Should be defined by the child class. init: function() { this.add_command(this.command, '*', this.execute); }, execute: function() { }, /** * This method will be run before calling execute. If this method fails, * the game will act as if the command does not exist. * * This will enable us to easily create administrator and class-specific * commands. */ can_execute: function() { return true; } });
2.640625
3
website/pages/index.js
durksteed13/next-rapid-docs
2
15993004
import Head from 'next/head' import Link from 'next/link' import nextRapidDocs from 'next-rapid-docs' import MainMenu from '../components/MainMenu' const fitContent = 'fit-content' function copyNPXCommandToClipboard() { navigator.clipboard.writeText('npx create-next-rapid-docs <project-name>') } export default function Home({ nextRapidDocsTable }) { return ( <> <Head> <title> next-rapid-docs – Effortlessly Write Comprehensive Documentation </title> <meta name="description" content="next-rapid-docs makes it easy to quickly turn markdown text into complete documentation on responsive Next.js web applications" ></meta> </Head> <MainMenu nextRapidDocsTable={nextRapidDocsTable} /> <section className="pt-24 md:pt-30 lg:pt-36 mx-auto px-6 max-w-6xl"> <h1 className="font-extrabold text-4xl sm:text-5xl md:text-6xl lg:text-7xl text-gray-800"> Effortlessly Write <br /> Comprehensive Documentation </h1> <h3 className="mt-10 md:mt-8 mb-8 md:mb-10 text-xl md:text-2xl text-gray-700 max-w-3xl"> next-rapid-docs makes it easy to quickly turn{' '} <span className="font-bold text-indigo-600 dark:text-indigo-500 border-b-2 border-indigo-600 dark:border-indigo-500"> markdown text </span>{' '} into complete documentation on{' '} <span className="font-bold text-indigo-600 dark:text-indigo-500 border-b-2 border-indigo-600 dark:border-indigo-500"> responsive Next.js web applications </span> </h3> <div className="mb-12 flex flex-col md:flex-row items-center md:space-x-8 space-y-6 md:space-y-0"> <Link href="/docs/getting-started"> <a className="mr-auto md:mr-0 px-4 md:px-6 py-2 bg-indigo-600 dark:bg-indigo-500 hover:bg-indigo-700 dark:hover:bg-indigo-400 text-gray-50 dark:text-black hover:text-white text-xl md:text-2xl rounded"> Get Started </a> </Link> <button className="mr-auto md:mr-0 flex items-center space-x-4 px-2 sm:px-4 md:px-8 py-3 bg-blueGray-50 hover:bg-blueGray-100 dark:bg-gray-800 dark:hover:bg-blueGray-700 text-sm md:text-base text-gray-800 border dark:border-blueGray-600 rounded" onClick={copyNPXCommandToClipboard} > <code> npx create-next-rapid-docs{' '} <span className="text-indigo-500">{'<project-name>'}</span> </code> <svg xmlns="http://www.w3.org/2000/svg" className="hidden sm:block h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" /> </svg> </button> </div> <Link href="/docs"> <a className="flex items-center font-bold text-indigo-600 dark:text-indigo-500 text-lg md:text-xl border-b-2 border-transparent hover:border-indigo-600 dark:hover:border-indigo-500" style={{ width: fitContent }} > Read the Official Documentation <svg xmlns="http://www.w3.org/2000/svg" className="ml-2 h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" /> </svg> </a> </Link> </section> <section className="relative py-14 md:py-20 mx-auto px-4 max-w-6xl"> <div className="ml-auto rounded-lg w-100 md:w-4/5" style={{ height: 'auto' }} > <img alt="Example Project" src="svg/example-project.svg" /> </div> <div className="md:absolute -mt-32 mx-auto md:m-0 w-4/5 md:w-2/5 md:left-4 top-4/5 md:top-1/2 transform md:-translate-y-1/3 lg:-translate-y-1/2 bg-indigo-600 dark:bg-indigo-500 rounded md:rounded-lg shadow-xl" style={{ fontSize: '0.75rem' }} > <div className="px-6 py-2 bg-black bg-opacity-80 text-gray-300 rounded-t md:rounded-t-lg" /> <div className="p-6 bg-black bg-opacity-70 text-gray-100 rounded-b md:rounded-b-lg"> --- <br /> title: Videt Post Agris <br /> index: 0<br /> tags: next-rapid-docs welcome <br /> --- <br /> <br /> <span className="font-bold text-blue-300"># Videt post agris</span> <br /> <br /> <span className="font-bold text-blue-300"> ## Tua sine per concidit quaerens imago munere </span> <br /> <br /> Lorem markdownum Idaeis potenti, appellant Caune, repetitaque crimine opportuna et. Interdum in perdere stagnum placent candida arte est, <span className="italic text-yellow-200"> *facie* </span>{' '} minus.{' '} <span className="hidden md:block"> Dum portas regna: saepe tibi regna sanguine erat fontes fila aurum. <br /> <br /> <span className="font-bold text-blue-300"> ## Sed per tegitur senecta </span> </span> <br /> <br /> ... </div> <img alt="arrow-up" className="absolute md:hidden top-0 left-12 -mt-12 h-20 w-28" src="/svg/arrow-up.svg" /> <img alt="arrow-right" className="hidden md:block absolute -right-12 lg:-right-16 top-1/4 lg:top-1/3 h-20 lg:h-24 w-28 lg:w-32" src="/svg/arrow-right.svg" /> </div> </section> <section className="py-6 md:pb-6 md:pt-24 lg:py-10 mx-auto px-6 max-w-6xl"> <div className="flex items-center justify-center space-x-4 md:space-x-8 font-bold text-xs sm:text-base lg:text-xl text-gray-700"> <div className="px-3 md:px-6 py-4 flex items-center bg-indigo-50 dark:bg-indigo-400 bg-opacity-40 dark:bg-opacity-10 border border-gray-100 dark:border-transparent rounded"> <svg xmlns="http://www.w3.org/2000/svg" className="mr-2 md:mr-4 h-6 w-6 text-green-400 dark:text-green-300" viewBox="0 0 20 20" fill="currentColor" > <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" /> </svg> <span className="hidden md:inline-block mr-1">Automatic</span>Static Generation </div> <div className="px-3 md:px-6 py-4 flex items-center bg-indigo-50 dark:bg-indigo-400 bg-opacity-40 dark:bg-opacity-10 border border-gray-100 dark:border-transparent rounded"> <svg xmlns="http://www.w3.org/2000/svg" className="mr-2 md:mr-4 h-6 w-6 text-green-400 dark:text-green-300" viewBox="0 0 20 20" fill="currentColor" > <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" /> </svg> <span className="hidden md:inline-block mr-1">Built-in</span> Search Algorithm </div> </div> <div className="mt-8 flex items-center justify-center space-x-4 md:space-x-8 font-bold text-xs sm:text-base lg:text-xl text-gray-700"> <div className="px-3 md:px-6 py-4 flex items-center bg-indigo-50 dark:bg-indigo-400 bg-opacity-40 dark:bg-opacity-10 border border-gray-100 dark:border-transparent rounded"> <svg xmlns="http://www.w3.org/2000/svg" className="mr-2 md:mr-4 h-6 w-6 text-green-400 dark:text-green-300" viewBox="0 0 20 20" fill="currentColor" > <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" /> </svg> <span className="hidden lg:inline-block mr-1">Ordered</span> Sidebar <span className="hidden sm:inline-block ml-1">and Menu</span> </div> <div className="px-3 md:px-6 py-4 flex items-center bg-indigo-50 dark:bg-indigo-400 bg-opacity-40 dark:bg-opacity-10 border border-gray-100 dark:border-transparent rounded"> <svg xmlns="http://www.w3.org/2000/svg" className="mr-2 md:mr-4 h-6 w-6 text-green-400 dark:text-green-300" viewBox="0 0 20 20" fill="currentColor" > <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" /> </svg> MDX<span className="hidden md:inline-block ml-1">Support</span> </div> <div className="px-3 md:px-6 py-4 flex items-center bg-indigo-50 dark:bg-indigo-400 bg-opacity-40 dark:bg-opacity-10 border border-gray-100 dark:border-transparent rounded"> <svg xmlns="http://www.w3.org/2000/svg" className="mr-2 md:mr-4 h-6 w-6 text-green-400 dark:text-green-300" viewBox="0 0 20 20" fill="currentColor" > <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" /> </svg> <span className="hidden lg:inline-block mr-1">Highly</span>{' '} Customizable </div> </div> </section> <section className="py-8 md:py-12 mx-auto px-8 md:px-6 max-w-6xl"> <h2 className="mt-8 font-extrabold text-center text-4xl md:text-5xl lg:text-6xl text-gray-800"> Focus on Writing Documentation </h2> <h3 className="mx-auto mt-6 md:mt-10 py-2 font-bold text-center text-xl md:text-2xl lg:text-3xl text-gray-600 max-w-4xl"> Start a next-rapid-docs Project With{' '} <span className="border-b-2 border-gray-700">One Simple Command</span> </h3> <button className="mx-auto mt-8 mb-10 flex items-center space-x-4 px-2 sm:px-4 md:px-8 py-3 bg-blueGray-50 hover:bg-blueGray-100 dark:bg-gray-800 dark:hover:bg-blueGray-700 text-sm md:text-base text-gray-800 border dark:border-blueGray-600 rounded" onClick={copyNPXCommandToClipboard} > <code> npx create-next-rapid-docs{' '} <span className="text-indigo-500">{'<project-name>'}</span> </code> <svg xmlns="http://www.w3.org/2000/svg" className="hidden sm:block h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" /> </svg> </button> <div className="mx-auto p-2 md:p-4 px:p-6 rounded shadow-xl" style={{ backgroundColor: '#8851FC', width: fitContent }} > <img alt="create-next-rapid-docs" src="/create-next-rapid-docs.gif" /> </div> <h3 className="mx-auto mt-8 md:mt-12 py-2 font-bold text-center text-lg md:text-xl lg:text-2xl text-gray-600 max-w-4xl"> Want to Add next-rapid-docs to an{' '} <span className="border-b-2 border-gray-700">Existing Project</span>? </h3> <Link href="/docs"> <a className="mt-6 mx-auto flex items-center font-bold text-indigo-600 dark:text-indigo-500 text-lg md:text-xl border-b-2 border-transparent hover:border-indigo-600 dark:hover:border-indigo-500" style={{ width: fitContent }} > <span className="hidden sm:inline-block mr-1">How to</span>Add next-rapid-docs to{' '} <span className="hidden sm:inline-block mx-1">a</span> Project <svg xmlns="http://www.w3.org/2000/svg" className="ml-2 h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" /> </svg> </a> </Link> </section> <section className="py-6 mx-auto px-6 max-w-6xl"> <h2 className="my-8 font-extrabold text-center text-2xl md:text-3xl lg:text-4xl text-gray-800"> Built With </h2> <div className="flex flex-wrap items-center justify-center md:space-x-8"> <a className="px-4 flex items-center h-14 bg-indigo-600 bg-opacity-0 hover:bg-opacity-5 dark:bg-opacity-20 dark:hover:bg-opacity-30 rounded" href="https://nextjs.org/" rel="noopener noreferrer" target="_blank" > <img alt="Next.js" className="h-8" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/Nextjs-logo.svg/800px-Nextjs-logo.svg.png" /> </a> <a className="mx-4 md:mx-0 px-4 flex items-center h-14 bg-indigo-600 bg-opacity-0 hover:bg-opacity-5 dark:bg-opacity-20 dark:hover:bg-opacity-30 rounded" href="https://reactjs.org/" rel="noopener noreferrer" target="_blank" > <img alt="React.js" className="h-8" src="https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg" /> </a> <a className="px-4 flex items-center h-14 bg-indigo-600 bg-opacity-0 hover:bg-opacity-5 dark:bg-opacity-20 dark:hover:bg-opacity-30 rounded" href="https://mdxjs.com/" rel="noopener noreferrer" target="_blank" > <img alt="MDX.js" className="h-10" src="https://avatars.githubusercontent.com/u/37453691?s=280&v=4" /> </a> <div className="md:hidden w-full flex-shrink-0 h-4" /> <a className="px-4 flex items-center h-14 bg-indigo-600 bg-opacity-0 hover:bg-opacity-5 dark:bg-opacity-20 dark:hover:bg-opacity-30 rounded" href="https://fusejs.io/" rel="noopener noreferrer" target="_blank" > <img alt="fuse.js" className="h-8" src="https://fusejs.io/icons/android-icon-192x192.png" /> </a> <a className="ml-4 md:ml-0 px-4 flex items-center h-14 bg-indigo-600 bg-opacity-0 hover:bg-opacity-5 dark:bg-opacity-20 dark:hover:bg-opacity-30 rounded" href="https://tailwindcss.com" rel="noopener noreferrer" target="_blank" > <img alt="TailwindCSS" className="h-4" src="https://tailwindcss.com/_next/static/media/tailwindcss-logotype.128b6e12eb85d013bc9f80a917f57efe.svg" /> </a> </div> </section> </> ) } export async function getStaticProps() { const nextRapidDocsProps = new nextRapidDocs('docs', 'props') return { props: { nextRapidDocsTable: nextRapidDocsProps.getTable() } } }
1.476563
1
packages/ts-doc/src/context/modules.js
Romakita/docsify-ts-api
1
15993012
const context = require("./context"); module.exports = { /** * * @returns {any[]} */ modules() { return Object.keys(context.modules).reduce((acc, key) => { const mods = context.modules[key]; if (typeof mods === "string") { acc.push(mods); } else { Object.keys(mods).forEach((subKey) => { acc.push(mods[subKey]); }); } return acc; }, []); } };
1.382813
1
lib/selectors/element_selector.js
BentoBrowser/SiphonTools
3
15993020
var defaultTrigger = function ({ currentKey }) { return currentKey && currentKey.key == "Shift" // @ts-ignore && (!currentKey.target || (["INPUT", "TEXTAREA"].indexOf(currentKey.target.nodeName) < 0 && !currentKey.target.isContentEditable)); }; //@ts-ignore export default function ElementSelector({ trigger = defaultTrigger, onComplete = (elems, boxes, e) => { }, onUpdate = (elems, boxes) => { }, ignoreElements } = {}) { var saveElements = []; var highlightBoxes = []; var highlightedElement = null; var highlightBox = null; return { conditions: trigger, onSelectionChange: function ({ causingEvent, mouseUp, mousePosition, mouseDown, click }) { if (mouseDown) { mouseDown.preventDefault(); mouseDown.stopPropagation(); } if (mouseUp) { mouseUp.preventDefault(); mouseUp.stopPropagation(); } if (click) { click.preventDefault(); click.stopPropagation(); } if (causingEvent == "mouseup" && highlightedElement && highlightBox) { //Determine if any of the children are in our list -- if they are remove them for (let i = saveElements.length - 1; i >= 0; i--) { if (highlightedElement.contains(saveElements[i])) { saveElements.splice(i, 1); highlightBoxes.splice(i, 1)[0].remove(); } } saveElements.push(highlightedElement); highlightBoxes.push(highlightBox); highlightBox.style.pointerEvents = 'auto'; highlightBox.style.backgroundColor = '#9af58999'; highlightBox = null; highlightedElement = null; //mouseUp.target.style.border = '2px solid blue' if (onUpdate && saveElements.length) { onUpdate(saveElements, highlightBoxes); } } else if (causingEvent == "mouseup" && mouseUp && mouseUp.target && mouseUp.target.className.includes("siphon-element-selector")) { let boxIdx = highlightBoxes.indexOf(mouseUp.target); if (boxIdx >= 0) { highlightBoxes.splice(boxIdx, 1); saveElements.splice(boxIdx, 1); //@ts-ignore mouseUp.target.remove(); if (onUpdate && saveElements.length) { onUpdate(saveElements, highlightBoxes); } } } else if (mousePosition && highlightedElement != mousePosition.target) { if (mousePosition && mousePosition.target && !mousePosition.target.matches(ignoreElements) && !mousePosition.target.className.includes("siphon-element-selector")) { if (!highlightedElement) { highlightBox = document.body.appendChild(document.createElement('div')); highlightBox.style.position = "absolute"; highlightBox.style.backgroundColor = '#84e2f199'; highlightBox.style.zIndex = "889944"; highlightBox.style.pointerEvents = 'none'; //@ts-ignore highlightBox.style.pointer = 'pointer'; highlightBox.className = "siphon-element-selector"; } if (highlightBox) { let rect = mousePosition.target.getBoundingClientRect(); let x = rect.left + window.scrollX, y = rect.top + window.scrollY; highlightBox.style.left = `${x}px`; highlightBox.style.top = `${y}px`; highlightBox.style.height = `${rect.height}px`; highlightBox.style.width = `${rect.width}px`; highlightedElement = mousePosition.target; } } else if (highlightBox) { highlightBox.remove(); highlightedElement = null; } } }, onSelectionEnd: function (e) { //either cancel the selection highlightedElement = null; if (highlightBox) { highlightBox.remove(); } if (onComplete && saveElements.length) onComplete(saveElements, highlightBoxes, e); } }; } //# sourceMappingURL=element_selector.js.map
1.664063
2
templates/client/utils/girdle.js
trainiac/slush-react-webpack
0
15993028
/** @module express-jsonschema @author <NAME> */ import { css, StyleSheet } from 'aphrodite' import _ from 'lodash/fp' const mapValues = _.mapValues.convert({ cap: false }) const reduce = _.reduce.convert({ cap: false }) const getStateClassName = (className, state) => `g-${className}-${state}` const helperClassNameToStyleSheetStyles = (className, context) => helperClassName => { const styleSheetStyles = context.otherStylesStyleSheet[helperClassName] || context.contextStylesStyleSheet[helperClassName] if (!styleSheetStyles) { throw new Error( `Under the class name: ${className} you referenced a class name: ${helperClassName} in the helpers or states keys that could not be found.` ) } return styleSheetStyles } const stateClassNameToStyleSheetStyles = (className, context) => stateClassName => context.styleSheet[getStateClassName(className, stateClassName)] || helperClassNameToStyleSheetStyles(className, context)(stateClassName) const toStateClassName = className => state => getStateClassName(className, state) const wrapGetStateFunc = (context, className, getStateFunc) => (...args) => { const computedClassNames = _.compact(getStateFunc(...args)) const classNameStyleSheets = _.map( stateClassNameToStyleSheetStyles(className, context) )(computedClassNames) return { className: css(context.styleSheet[className], ...classNameStyleSheets) } } const findSpecialStyleKeys = context => (next, classNameStyles, className) => { const { helpers, getState, states, ...cssStyles } = classNameStyles next.cssStyles[className] = cssStyles if (helpers) { next.helpers[className] = _.map( helperClassNameToStyleSheetStyles(className, context) )(helpers) } if (states) { const stateClassNames = _.mapKeys(toStateClassName(className))(states) next.cssStyles = _.assign(stateClassNames)(next.cssStyles) } if (getState) { next.getStateFuncs[className] = getState } return next } const getClassNameFunc = context => (classNameStyles, className) => { const getStateFunc = context.getStateFuncs[className] if (getStateFunc) { return wrapGetStateFunc( context, className, context.getStateFuncs[className] ) } let stylesToApply = [context.styleSheet[className]] const helperStyleSheetStyles = context.helpers[className] if (helperStyleSheetStyles) { stylesToApply = [...stylesToApply, ...helperStyleSheetStyles] } return () => ({ className: css(...stylesToApply) }) } const addResultToContext = func => context => ({ ...context, ...func(context) }) const createOtherStylesStyleSheet = context => { let otherStylesStyleSheet = {} let contextStylesStyleSheet = {} if (context.otherStyles) { otherStylesStyleSheet = StyleSheet.create(context.otherStyles) } if (context.contextStyles) { contextStylesStyleSheet = StyleSheet.create(context.contextStyles) } return { otherStylesStyleSheet, contextStylesStyleSheet } } const gatherAllSpecialStyleKeys = context => reduce(findSpecialStyleKeys(context))({ helpers: {}, states: {}, getStateFuncs: {}, cssStyles: {} })(context.styles) const createStyleSheet = context => ({ styleSheet: StyleSheet.create(context.cssStyles) }) const getClassNameFuncs = context => mapValues(getClassNameFunc(context))(context.cssStyles) const stylesToClassNameFunc = _.flow( addResultToContext(createOtherStylesStyleSheet), addResultToContext(gatherAllSpecialStyleKeys), addResultToContext(createStyleSheet), getClassNameFuncs ) const girdle = (styles, otherStyles, contextStyles) => stylesToClassNameFunc({ styles, otherStyles, contextStyles }) export const girdleGlobals = contextStyles => (styles, otherStyles) => girdle(styles, otherStyles, contextStyles) export default girdle
1.382813
1
Widgets/TVGuide/TVGuide.js
0507spc/ScriptStore
30
15993036
let show = args.widgetParameter if (show == null) { show = "sports" } // add refresh of the earliest stop time + 10seconds let params = args.queryParameters // log("here") // log(args.queryParameters) if ( params.alert == 1 ) { log("here") log(params.type) log(params.desc) let a = new Alert(); a.title = params.type a.message = params.desc a.addCancelAction("OK"); await(a.presentAlert()); } theKey = "zrT6834Gydreeed" Version = 1.6 autoUpdate = true checkVersion(Version) // this is a param // this should empty cache folder forceRefresh = false // show = "sports" // show = "general" // The url below is WIP let vURL="https://scriptablefun.000webhostapp.com/getShow.php?key=" + theKey + "&id=@id@&date=@yyyymmdd@" let vLogoURLGeneric = "https://d2n0069hmnqmmx.cloudfront.net/epgdata/1.0/newchanlogos/320/320/skychb@[email protected]" //let vLogoURL="https://e3.365dm.com/tvlogos/channels/@[email protected]" let highlightMe = new RegExp(/live .*Eng|live snooker|live mosconi|Live.*Eng.*ODI|Live.*F1.*GP|live.*darts|chess |poker |the simpsons|red dwarf/, "i") // Choose from: SkyTV, SkyMobile, TVGuide, RadioTimes, VirginTVGo Theme = getTheme("SkyMobile") // hight a multiple of 26 max 26*13 = 338 // length is 2 * 153 = 306 // font sizes should increase too vBaseCellLength = 153 vBaseCellHeight = 26 // calculate the sizes here vCellLength = vBaseCellLength vCellHeight = vBaseCellHeight // iPhone 11 Pro Max sizes cellSize = new Size(vCellLength, vCellHeight) logoCellSize = new Size(45, vCellHeight) let mainText = new Font("ArialRoundedMT", 9) // this is the number of characters based on // font and width vStackLimit = 50 vCornerRadius = 4 vBorderWidth = 0.5 // just show an example rows = 3 switch (config.widgetFamily) { case "medium": rows = 5 break; case "large": rows = 13 break; } vBackground = rC(Theme.vBackground) vLogoBackground = rC(Theme.vLogoBackground) vNowBackgroundEven = rC(Theme.vNowBackgroundEven) vNextBackgroundEven = rC(Theme.vNextBackgroundEven) vNowBackgroundOdd = rC(Theme.vNowBackgroundOdd) vNextBackgroundOdd = rC(Theme.vNextBackgroundOdd) vTitleBackground = rC(Theme.vTitleBackground) vTitleTextColor = rC(Theme.vTitleTextColor) vTextColor = rC(Theme.vTextColor) vHightlightBkGnd = rC(Theme.vHightlightBkGnd) vHightlightText = rC(Theme.vHightlightText) vHightlightProg = rC(Theme.vHightlightProg) vProgressLine = rC(Theme.vProgressLine) vBorder = rC(Theme.vBorder) colourWhite = rC(Theme.colourWhite) vDebugTime = 0 updateTime = getNow(vDebugTime, "jhm") theDateTime = getNow(vDebugTime, "h") theDate = getNow(vDebugTime, "ymd") theDateOne = getNow(24, "ymd") theDateYest = getNow(-24, "ymd") vNowEpoch = Epoch(Date.now()) general = [ { "id": "2074", "name": "BBC One HD" }, { "id": "2075", "name": "BBC Two HD" }, { "id": "1402", "name": "Sky One" }, { "id": "3809", "name": "<NAME>" }, { "id": "4075", "name": "Channel 4 HD" }, { "id": "2320", "name": "<NAME>" }, { "id": "4061", "name": "Sky One HD" }, { "id": "6533", "name": "ITV3 HD" }, { "id": "6534", "name": "ITV4 HD" }, { "id": "4076", "name": "E4 HD" }, { "id": "4043", "name": "More4 HD" }, { "id": "4044", "name": "Film4 HD" }, { "id": "4074", "name": "SYFY HD" }, { "id": "2104", "name": "BBC One Yorks" } ] sports = [ { "id": "1301", "name": "Sky Sports Main Event" }, { "id": "1302", "name": "Sky Sports Cricket" }, { "id": "1306", "name": "Sky Sports F1" }, { "id": "1333", "name": "Sky Sports Action" }, { "id": "4091", "name": "Sky Sports Mix" }, { "id": "1303", "name": "Sky Sports Premier League" }, { "id": "3838", "name": "Sky Sports Football" }, { "id": "1322", "name": "Sky Sports Golf" }, { "id": "1354", "name": "Sky Sports Racing" }, { "id": "3839", "name": "Sky Sports Arena" }, { "id": "1314", "name": "Sky Sports News" }, { "id": "4004", "name": "Eurosport 1 HD" }, { "id": "4009", "name": "Eurosport 2 HD" } ] // sports = [ // { "id": "1314", "name": "Sky Sports News" }, // { "id": "4004", "name": "Eurosport 1 HD" }, // { "id": "4009", "name": "Eurosport 2 HD" } // ] if ( show == "sports" ) { showsToShow = sports vLogoURL = vLogoURLGeneric } else { showsToShow = general vLogoURL = vLogoURLGeneric } let widget = new ListWidget() widget.backgroundColor = vBackground //let titleLogo = await getImage("Sky-Sports-Logo.png", "https://e1.365dm.com/tvlogos/channels/Sky-Sports-Logo.png") let titleLogo = await getImage("Sky-Logo.png", "https://images.squarespace-cdn.com/content/v1/5305718de4b0e8a52d75a8cc/1502331535810-WDRY753TY9YN67EAPFKU/ke17ZwdGBToddI8pDm48kLXCf88_9uNTKXkq27cF4sB7gQa3H78H3Y0txjaiv_0fDoOvxcdMmMKkDsyUqMSsMWxHk725yiiHCCLfrh8O1z5QHyNOqBUUEtDDsRWrJLTmwbA6upbL5Bu97tJociXJklKprRMdH2Tl4F1PjaoPT3YUs5wkl5ojCV1O900UJ7ME/image-asset.png") let titleStack = widget.addStack() titleStack.size = new Size(350, vCellHeight / 2) theLogo = titleStack.addImage(titleLogo) theLogo.imageSize = new Size(50, vCellHeight) titleStack.centerAlignContent() let title = titleStack.addText(" - Sky TV Guide - @" + updateTime) title.font = Font.boldSystemFont(10) title.textColor = vTitleTextColor widget.addSpacer(10) vShowCount = 1 for (var key in showsToShow) { earlyEnd = 0 if ( vShowCount > rows ) { break } else { vShowCount++ } if (showsToShow.hasOwnProperty(key)) { var mainStack = widget.addStack() mainStack.layoutHorizontally() var columnOneStack = mainStack.addStack() columnOneStack.layoutVertically() columnOneStack.size = logoCellSize var columnTwoStack = mainStack.addStack() columnTwoStack.layoutHorizontally() var nowStack = columnTwoStack.addStack() nowStack.layoutVertically() nowStack.size = cellSize var nextStack = columnTwoStack.addStack() nextStack.layoutVertically() nextStack.size = cellSize theID = showsToShow[key].id vEPGURL = vURL.replace(/@yyyymmdd@/, theDate).replace(/@id@/, theID) vEPGURLONE = vURL.replace(/@yyyymmdd@/, theDateOne).replace(/@id@/, theID) tvGuide = await getString(vEPGURL, theID, theDate) tvGuideOne = await getString(vEPGURLONE, theID, theDateOne) vLogoImageURL = vLogoURL.replace(/@id@/, showsToShow[key].id) theLogo = await getImage(showsToShow[key].id + ".png", vLogoImageURL) image = columnOneStack.addImage(theLogo) columnOneStack.centerAlignContent() image.centerAlignImage() image.imageSize = new Size(40, vCellHeight) columnOneStack.setPadding(0, 2, 0, 2) columnOneStack.backgroundColor = vBackground columnOneStack.borderColor = vBorder columnOneStack.borderWidth = vBorderWidth columnOneStack.cornerRadius = vCornerRadius vCount = 1 columnOneStack.backgroundColor = vLogoBackground vComplete = "" for ( k in tvGuide.schedule[0].events ) { finishTime = tvGuide.schedule[0].events[k].st + tvGuide.schedule[0].events[k].d checkTime = getNow(0, "h", finishTime ) if ( (parseInt(checkTime) >= parseInt(theDateTime) ) && ( vCount <= 2 ) ) { startTime = getNow(0, "jhm",tvGuide.schedule[0].events[k].st) vTitle = await shortenMe(tvGuide.schedule[0].events[k].t) vTitle = startTime + " " + vTitle vTitle = vTitle.substring(0, vStackLimit) if ( (key % 2) == 0 ) { vNowBackground = vNowBackgroundEven vNextBackground = vNextBackgroundEven } else { vNowBackground = vNowBackgroundOdd vNextBackground = vNextBackgroundOdd } if ( vCount == 1 ) { if (earlyEnd < finishTime) { earlyEnd = finishTime } theDescription = tvGuide.schedule[0].events[k].sy vShowUrl = "scriptable:///run?scriptName=TVGuide&alert=1&type=desc&desc=" + encodeURI(theDescription) vLineLength = vCellLength * ((vNowEpoch - tvGuide.schedule[0].events[k].st) / tvGuide.schedule[0].events[k].d) createEntry(vTitle, nowStack, vNowBackground, vShowUrl, vLineLength) vComplete = "Now" } if ( vCount == 2 ) { if (earlyEnd > finishTime) { let earlyEnd = finishTime } theDescription = tvGuide.schedule[0].events[k].sy vShowUrl = "scriptable:///run?scriptName=TVGuide&alert=1&type=desc&desc=" + encodeURI(theDescription) vLineLength = vCellLength * ((vNowEpoch - tvGuide.schedule[0].events[k].st) / tvGuide.schedule[0].events[k].d) createEntry(vTitle, nextStack, vNextBackground, vShowUrl, vLineLength) vComplete = "Next" } vCount++ } if ( vComplete == "Next" ) { break } } } // I think this fixes it all?????? if ( vComplete == "Now" ) { for ( eventID in tvGuideOne.schedule[0].events ) { if ( parseInt(tvGuideOne.schedule[0].events[eventID].st = earlyEnd ) ) { startTime = getNow(0, "jhm",tvGuideOne.schedule[0].events[eventID].st) vTitle = await shortenMe(tvGuideOne.schedule[0].events[eventID].t) vTitle = startTime + " " + vTitle vTitle = vTitle.substring(0, vStackLimit) if ( (key % 2) == 0 ) { vNextBackground = vNextBackgroundEven } else { vNextBackground = vNextBackgroundOdd } theDescription = tvGuideOne.schedule[0].events[eventID].sy vShowUrl = "scriptable:///run?scriptName=TVGuide&alert=1&type=desc&desc=" + encodeURI(theDescription) createEntry(vTitle, nextStack, vNextBackground, vShowUrl, 0) } break } } // this is the earliest finish time // yyyy-mm-dd // let formatter = new DateFormatter() // formatter.dateFormat = "yyyy-MM-dd'T'HH:mmZ" // end = formatter.date(earlyEnd + "T05:00Z") end = getNow(0, "h", earlyEnd) widgetrefreshAfterDate = end } if ( config.runsInWidget == true) { Script.setWidget(widget) } // Debug: if ( params.alert != 1 ) { widget.presentMedium() } // ------------------------------------------------ // ------------------------------------------------ // --------- FUNCTIONS only here ----------------- // ------------------------------------------------ // ------------------------------------------------ function rC(hex) { return new Color(hex) } function createEntry(theText, theStack, vBackgroundCol, addURL, lineLength) { theStack.setPadding(1, 2, 1, 2) // lineLength = Math.abs(lineLength) overlay = theStack.addStack() overlay.size = new Size(lineLength, 1) overlay.backgroundColor = checkHighlight(theText, vBackgroundCol, "progress") theNow = theStack.addText(theText) theNow.font = mainText theNow.textColor = checkHighlight(theText, vBackgroundCol, "text") theStack.backgroundColor = checkHighlight(theText, vBackgroundCol, "cell") theStack.borderColor = vBorder theStack.borderWidth = vBorderWidth theStack.cornerRadius = vCornerRadius theStack.url = addURL } function checkHighlight(theText, defaultColour, textOrCell) { if ( theText.match(highlightMe) ) { theColourCell = vHightlightBkGnd theColourText = vHightlightText theColourProgress = vHightlightProg } else { theColourCell = defaultColour theColourText = vTextColor theColourProgress = vProgressLine } if ( textOrCell == "cell" ) { return theColourCell } if ( textOrCell == "text" ) { return theColourText } if ( textOrCell == "progress" ) { return theColourProgress } } async function shortenMe(text) { text = text.replace("England", "Eng").replace("S Africa", "SA").replace("Formula One", "F1").replace(/highlights/gi, "hlts") //.replace("The Home Of ", "Home Of ").replace(" - ", ": ") return text } async function getLocalFile(fileName) { let fm = FileManager.iCloud() let path = fm.documentsDirectory() + "/xmltv/cache/" if ( fm.isDirectory(path) == false) { fm.createDirectory(path) } let pathToFile = path + fileName // let pathToFile = fm.joinPath(dir, fileName) if ( fm.fileExists(pathToFile) ) { await fm.downloadFileFromiCloud(pathToFile) theOutput = fm.readString(pathToFile) theOutput = JSON.parse(theOutput.toString()); return theOutput } } async function checkVersion(Version) { // check if allowed to update then run if ( autoUpdate == false ) { return } vVersionUrl = "https://raw.githubusercontent.com/0507spc/ScriptStore/main/Widgets/TVGuide/version.json" let fReq = new Request(vVersionUrl) output = await fReq.loadJSON() //log(output.Version) if ( parseFloat(output.Version) > parseFloat(Version) ) { // log("There is a new version: " + output.Version) thisScript = Script.name() + ".js" let fm = FileManager.iCloud() let toUpdate = fm.documentsDirectory() + "/" + thisScript if (fm.fileExists(toUpdate) == true) { //log("Let's update") updateLink = "https://raw.githubusercontent.com/0507spc/ScriptStore/main/Widgets/TVGuide/TVGuide.js" let fReq = new Request(updateLink) updateString = await fReq.loadString() fm.writeString(toUpdate, updateString) } //if ( } } async function getString(urlName, theID, whatDate) { theFileName = whatDate + "_" + theID + ".json" theFileNameYest = theDateYest + "_" + theID + ".json" let fm = FileManager.iCloud() let dir = fm.documentsDirectory() + "/xmltv/cache/" if ( fm.isDirectory(dir) == false) { fm.createDirectory(dir, true) } let path = fm.joinPath(dir, theFileName) let pathYest = fm.joinPath(dir, theFileNameYest) if (fm.fileExists(pathYest) == true) { fm.remove(pathYest) } if ( fm.fileExists(path) == false || forceRefresh == true) { let fReq = new Request(urlName) output = await fReq.loadJSON() fm.writeString(path, JSON.stringify(output, null, 4)) } else { output = getLocalFile(theFileName) } return output } // get images from local filestore or download them once async function getImage(image, vImageURL) { let fm = FileManager.iCloud() let dir = fm.documentsDirectory() + "/xmltv/icons/" if ( fm.isDirectory(dir) == false) { fm.createDirectory(dir, true) } let path = fm.joinPath(dir, image) if(fm.fileExists(path)) { await fm.downloadFileFromiCloud(path) return fm.readImage(path) } else { // download once let iconImage = await loadImage(vImageURL) fm.writeImage(path, iconImage) return iconImage } } // helper function to download an image from a given url async function loadImage(imgUrl) { const req = new Request(imgUrl) return await req.loadImage() } function getNow(addHours, fmt, epoch) { // could have a format passed in if ( epoch != null ) { nowDate = EpochToDate(epoch) } else { nowDate = new Date() } nowDate.setHours(nowDate.getHours() + addHours) nowHour = ("0" + nowDate.getHours().toString()).slice(-2) // Get the hour (0-23) nowMin = ("0" + nowDate.getMinutes().toString()).slice(-2) // Get the minutes (0-59) nowMon = ("0" + (nowDate.getMonth() + 1).toString()).slice(-2) // Get the month (0-11) nowDay = ("0" + nowDate.getDate().toString()).slice(-2) // Get the day as a number (1-31) nowYear = nowDate.getFullYear().toString() // Get the four digit year (yyyy) nowSec = ("0" + nowDate.getSeconds().toString()).slice(-2) // Get the seconds (0-59) if ( fmt == "d" ) { theFormat = nowYear + nowMon + nowDay //+ nowHour //+ nowMin + nowSec } if ( fmt == "h" ) { theFormat = nowYear + nowMon + nowDay + nowHour + nowMin + nowSec } if ( fmt == "jhm" ) { theFormat = nowHour + ":" + nowMin } if ( fmt == "ymd" ) { theFormat = nowYear + nowMon + nowDay } return theFormat } //Epoch function Epoch(date) { return Math.round(new Date(date).getTime() / 1000.0); } //Epoch To Date function EpochToDate(epoch) { if (epoch < 10000000000) epoch *= 1000; // convert to milliseconds (Epoch is usually expressed in seconds, but Javascript uses Milliseconds) var epoch = epoch + (new Date().getTimezoneOffset() * -1); //for timeZone return new Date(epoch); } function getTheme(themeName) { // themes= { "SkyTV": { "vBackground" : "#0065C9" , "vLogoBackground" : "#0065C9" , "vNowBackgroundEven" : "#1277D0" , "vNextBackgroundEven" : "#0057AF" , "vNowBackgroundOdd" : "#1277D0" , "vNextBackgroundOdd" : "#0057AF" , "vTitleBackground" : "#005CB7" , "vTitleTextColor" : "#FFFFFF" , "vTextColor" : "#FEFFFE" , "vHightlightBkGnd" : "#FFFC2D" , "vHightlightText" : "#856A00" , "vBorder" : "#3381CF" , "colourWhite" : "#FFFFFF" , "vHightlightProg" : "#2F4F4F" , "vProgressLine" : "#A9A9A9" }, "SkyMobile": { "vBackground" : "#152966" , "vLogoBackground" : "#013F86" , "vNowBackgroundEven" : "#003E84" , "vNextBackgroundEven" : "#003E84" , "vNowBackgroundOdd" : "#0F2F72" , "vNextBackgroundOdd" : "#0F2F72" , "vTitleBackground" : "#005CB7" , "vTitleTextColor" : "#FFFFFF" , "vTextColor" : "#FEFFFE" , "vHightlightBkGnd" : "#FFFC2D" , "vHightlightText" : "#856A00" , "vBorder" : "#000022" , "colourWhite" : "#FFFFFF" , "vHightlightProg" : "#2F4F4F" , "vProgressLine" : "#A9A9A9" }, "TVGuide": { "vBackground" : "#F7F8FA" , "vLogoBackground" : "#FDFEFD" , "vNowBackgroundEven" : "#FDFEFD" , "vNextBackgroundEven" : "#FDFEFD" , "vNowBackgroundOdd" : "#FDFEFD" , "vNextBackgroundOdd" : "#FDFEFD" , "vTitleBackground" : "#F7F8FA" , "vTitleTextColor" : "#FFFFFF" , "vTextColor" : "#000000" , "vHightlightBkGnd" : "#EEEEF6" , "vHightlightText" : "#856A00" , "vBorder" : "#C4C5E2" , "colourWhite" : "#FFFFFF" , "vHightlightProg" : "#2F4F4F" , "vProgressLine" : "#A9A9A9" }, "RadioTimes": { "vBackground" : "#2D2E30" , "vLogoBackground" : "#999999" , "vNowBackgroundEven" : "#FEFFFE" , "vNextBackgroundEven" : "#FEFFFE" , "vNowBackgroundOdd" : "#EEF1F2" , "vNextBackgroundOdd" : "#EEF1F2" , "vTitleBackground" : "#2D2E30" , "vTitleTextColor" : "#FFFFFF" , "vTextColor" : "#343434" , "vHightlightBkGnd" : "#0ABDCD" , "vHightlightText" : "#856A00" , "vBorder" : "#DBDCDB" , "colourWhite" : "#FFFFFF" , "vHightlightProg" : "#2F4F4F" , "vProgressLine" : "#A9A9A9" }, "VirginTVGo": { "vBackground" : "#322332" , "vLogoBackground" : "#261926" , "vNowBackgroundEven" : "#4B354C" , "vNextBackgroundEven" : "#4B354C" , "vNowBackgroundOdd" : "#4B354C" , "vNextBackgroundOdd" : "#4B354C" , "vTitleBackground" : "#322332" , "vTitleTextColor" : "#FFFFFF" , "vTextColor" : "#FEFFFE" , "vHightlightBkGnd" : "#261926" , "vHightlightText" : "#E9E9EA" , "vBorder" : "#322332" , "colourWhite" : "#FFFFFF" , "vHightlightProg" : "#2F4F4F" , "vProgressLine" : "#A9A9A9" } } return themes[themeName] }
1.546875
2
packages/dynapi-plugin-ignore-paths/test/fixtures/routes/>handle.js
shirohana/dynapi
7
15993044
export default (req, res, next) => { res.write(`${req.method} ${req.path}`) res.end() }
0.546875
1
static/js/controllers/tasks.js
estellecomment/medic-webapp
0
15993052
var _ = require('underscore'); (function () { 'use strict'; var inboxControllers = angular.module('inboxControllers'); inboxControllers.controller('TasksCtrl', ['$scope', '$state', '$log', '$timeout', 'TranslateFrom', 'TaskGenerator', function ($scope, $state, $log, $timeout, TranslateFrom, TaskGenerator) { var setSelectedTask = function(task) { $scope.selected = task; $scope.setTitle(TranslateFrom(task.title, task)); $scope.setShowContent(true); }; $scope.setSelected = function(id) { var refreshing = ($scope.selected && $scope.selected._id) === id, task = _.findWhere($scope.tasks, { _id: id }); if (task) { $scope.settingSelected(refreshing); setSelectedTask(task); } else { $scope.clearSelected(); } }; $scope.refreshTaskList = function() { window.location.reload(); }; var mergeTasks = function(tasks) { $timeout(function() { tasks.forEach(function(task) { if ($scope.selected && task._id === $scope.selected._id || (!$scope.selected && task._id === $state.params.id)) { setSelectedTask(task); } for (var i = 0; i < $scope.tasks.length; i++) { if ($scope.tasks[i]._id === task._id) { if (task.resolved) { $scope.tasks.splice(i, 1); } else { $scope.tasks[i] = task; } return; } } $scope.tasks.push(task); }); }) .then(function() { $scope.loading = false; }); }; $scope.$on('ClearSelected', function() { $scope.selected = null; }); $scope.filterModel.type = 'tasks'; $scope.tasks = []; $scope.selected = null; $scope.loading = true; $scope.error = false; TaskGenerator('TasksCtrl', function(err, tasks) { if (err) { $log.error('Error getting tasks', err); $scope.loading = false; $scope.error = true; $scope.tasks = []; $scope.clearSelected(); return; } mergeTasks(tasks); }); } ]); }());
1.320313
1
tailwind.config.js
coopstories/frontend
1
15993060
module.exports = { content: ['./src/**/*.{js,jsx,ts,tsx}'], theme: { fontFamily: { sans: ['Lusitana', 'sans'], serif: ['Open Sans', 'serif'], }, extend: { colors: { 'green-mid': '#83c5beff', 'light-blue': '#edf6f9ff', primary: '#e29578ff', 'light-primary': '#ffddd2ff', secondary: '#006d77ff', }, }, }, plugins: [require('@tailwindcss/forms')], }
0.5
0
Scripts/LakeGeneration.js
pirosveta/utp2019-2-2d-game
0
15993068
// Генерация земли let seed = 1000000; const random = () => { /*let x = Math.sin(seed++) * 10000; return x - Math.floor(x);*/ return Math.random(); }; // Генерация массива уровней поверхности const landGen = (minHeight, maxHeight, widthWorld, heightWorld) => { let heights = [Math.floor((maxHeight + minHeight) / 2)]; let waterArrStartX = [], waterArrEndX = []; let waterArrStartY = [], waterArrEndY = []; let waterStartX = 0, waterEndX = 0; let waterStartY = 0, waterEndY = 0; let i = 1; let lastSign = 0; while (i < widthWorld) { let sectionLength = Math.round(random() * 9) + 1; // Длина сектора возрастания или убывания let sign = Math.floor(random() * 2); if (sign === 0) sign = -1; let lastDelta = 1; if (lastSign !== sign) { lastDelta = 0; } if (sign === -1 && lastDelta !== 0) { waterStartX = i; waterStartY = heights[i - 1]; } lastSign = sign; i += sectionLength; while (sectionLength > 0) { let delta = 0; if (lastDelta === 0 && random() > 0.07) { delta = 0; } else { delta = Math.ceil(random() * 3); // Максимальная разница в уровнях = 2 } lastDelta = delta; let nextHeight = heights[heights.length - 1] + delta * sign; if ((nextHeight >= maxHeight) || (nextHeight <= minHeight)) { i -= sectionLength; break; } else heights.push(nextHeight); sectionLength--; } if (sign === 1 && lastDelta !== 0 && waterStartX !== 1 && lastSign !== 0) { if (i - 1 >= widthWorld) { i = widthWorld; } waterEndX = i - 1; if (heights[i - 1] > waterStartY) { waterEndY = waterStartY; } else if (random() < 0.07) { waterEndY = heights[i - 1]; waterStartY = heights[i - 1]; } if (waterEndY !== 0) { waterArrStartX.push(waterStartX); waterArrStartY.push(waterStartY); waterArrEndX.push(waterEndX); waterArrEndY.push(waterEndY); waterStartX = 1; waterEndY = 0; } } } // Преобразование карты высот в матрицу let arr = []; for (let x = 0; x < widthWorld; x++) { arr[x] = []; for (let y = 0; y < heightWorld; y++) { arr[x][y] = (y <= heights[x]) ? 1 : -1; } } for (let i = 0; i < waterArrStartX.length; i++) { let x; let y; for (x = waterArrStartX[i]; x < waterArrEndX[i]; x++) { for (y = waterArrStartY[i]; arr[x][y] === -1; y--) { arr[x][y] = 3; if (arr[x - 1][y] === 1) { arr[x - 1][y] = 2; } if (arr[x + 1][y] === 1) { arr[x + 1][y] = 2; } } if (arr[x - 1][y + 1] === 3 && arr[x][y] === 1) { arr[x][y] = 2; } } } return arr; };
1.945313
2
apps/editor/src/js/indexEditorOnlyStyle.js
juicepharma/tui.editor
4
15993076
/** * @fileoverview entry point to create editor-only.css files * @author NHN FE Development Lab <<EMAIL>> */ import '../css/editor.css'; import '../css/preview-highlighting.css'; import '../css/md-syntax-highlighting.css';
0.030029
0
shop/shop.js
OlgaPacula/jodisklient.github.io
0
15993084
window.onload = function(){ let cart= {}; let goods = {}; function loadCartFromStorage(){ if (localStorage.getItem('cart') != undefined) cart = JSON.parse( localStorage.getItem('cart')); console.log(cart); } loadCartFromStorage(); let getJSON = function(url, callback){ let xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'json'; xhr.onload = function (){ let status = xhr.status; if (status === 200){ callback(null, xhr.response) } else { callback(status, xhr.response); } }; xhr.send(); } getJSON('https://spreadsheets.google.com/feeds/list/1SmXPbRoUvufGdAsl5fTgUclBsjuBCoPc_P68oi9JQX0/od6/public/values?alt=json', function(err, data){ console.log(data); if (err !== null){ alert('Error:'+err); } else { data = data['feed'] ['entry']; console.log(data); goods = arrayHelper(data); console.log(goods); document.querySelector('.shop-field').innerHTML = showGoods(data); showCart(); } }); function showGoods(data){ let out = ''; for (var i=0; i<data.length; i++){ if (data[i] ['gsx$show'] ['$t'] !=0){ out +=`<div class="col-lg-3 col-md-3 col-sm-2 text-center">`; out +=`<div class="goods">`; out +=`<h5>${data[i] ['gsx$name'] ['$t']}</h5>`; out +=`<img src="${data[i] ['gsx$image'] ['$t']}">`; out +=`<p class="cena">Ціна:${data[i] ['gsx$cena'] ['$t']}грн.</p>`; out +=`<p class="cost">В наявності: ${data[i] ['gsx$have'] ['$t']}</p>`; out +=`<p class="cost"><button type="button" class="btn btn-outline-success" name="add-to-cart" data="${data[i] ['gsx$id'] ['$t']}">Купити</button>`; out +=`</div>`; out +=`</div>`; } } return out; } document.onclick = function(e){ if(e.target.attributes.name !=undefined){ if (e.target.attributes.name.nodeValue == 'add-to-cart'){ addToCart(e.target.attributes.data.nodeValue); } else if (e.target.attributes.name.nodeValue == "delete-goods"){ delete cart[e.target.attributes.data.nodeValue]; showCart(); localStorage.setItem('cart', JSON.stringify(cart)); console.log(cart); } else if (e.target.attributes.name.nodeValue == "plus-goods"){ cart[e.target.attributes.data.nodeValue]++; showCart(); localStorage.setItem('cart', JSON.stringify(cart)); console.log(cart); } else if (e.target.attributes.name.nodeValue == "minus-goods"){ if (cart[e.target.attributes.data.nodeValue] - 1 == 0){ delete cart[e.target.attributes.data.nodeValue]; } else{ cart[e.target.attributes.data.nodeValue]--; } showCart(); localStorage.setItem('cart', JSON.stringify(cart)); console.log(cart); } } return false; } function addToCart(elem){ if (cart[elem]!==undefined){ cart[elem]++; } else{ cart[elem]= 1; } console.log(cart); showCart(); localStorage.setItem('cart', JSON.stringify (cart)); } function arrayHelper(arr){ let out = {}; for (let i =0; i<arr.length; i++){ let temp = {}; temp['articul'] = arr[i]['gsx$articul']['$t']; temp['name'] = arr[i]['gsx$name']['$t']; temp['category'] = arr[i]['gsx$category']['$t']; temp['cena'] = arr[i]['gsx$cena']['$t']; temp['image'] = arr[i]['gsx$image']['$t']; out[arr[i]['gsx$id']['$t']] = temp; } return out; } function showCart(){ let ul = document.querySelector('.cart'); ul.innerHTML = ' '; let sum = 0; for (let key in cart){ let li = '<li>'; li += goods[key]['name'] + ' '; li +=` <button name="minus-goods" class="btn btn-outline-success" data="${key}">-</button>`; li += cart[key]+"шт."; li +=` <button name="plus-goods" class="btn btn-outline-success" data="${key}">+</button>`; li += goods[key]['cena']*cart[key] + 'грн.'; li +=` <button name="delete-goods" class="btn btn-outline-success" data="${key}">X</button>`; li +='</li>'; sum += goods[key]['cena']*cart[key]; ul.innerHTML += li; } ul.innerHTML += 'Всього: '+sum +"грн." } }
1.671875
2
public/template/assets/js/function.js
ENVYUS1/E-Learning
0
15993092
function loader(attr) { $(attr).waitMe({ effect : 'ios', text : 'sedang memuat...', bg :' rgba(0,0,0,0.5)', color : '#e8eaf1', maxSize : '', waitTime : -1, textPos : 'vertical', fontSize : '', source : '', onClose : function() {} }); } function errorHandling(jqXHR, exception) { if (jqXHR===0) { Swal.fire('Oopps','Tidak ada koneksi','info') }else if(jqXHR===404){ Swal.fire('Oppss','request not found','info') }else if(jqXHR===500){ Swal.fire('Oppss','internal server Error','info') }else if(exception==='parseerror'){ alert('Request Json Parse failed') }else if(exception==='timeout'){ alert('Timeout Error') }else if(exception==='abort'){ alert('Ajax Request Aborted') }else{ alert('error '+jqXHR.responseText) } $('#load').waitMe('hide') $('button').prop('disabled', false) } function reset(form){ $(form)[0].reset() $('.form-group').removeClass('has-success has-error') $('.error').remove() } function clear(){ $('.form-group').removeClass('has-success has-error') $('.error').remove() } function validasi(form){ $(form).validate({ validClass: "success", rules: { }, highlight: function(element) { $(element).closest('.form-group').removeClass('has-success').addClass('has-error'); }, success: function(element) { $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); $(element).closest('.error').remove(); }, }); } function summernote(){ $('#summernote').summernote({ placeholder: 'Jawaban anda ...', toolbar: [ ['style', ['bold', 'italic', 'underline', 'clear']], ['fontsize', ['fontsize']], ['para', ['ul', 'ol', 'paragraph']], ['height', ['height']] ], tabsize: 2, height: 250 }); } dropzone() function dropzone(){ Dropzone.options.dropzoneFrom = { autoProcessQueue: false, acceptedFiles:".png,.jpg,.gif,.bmp,.jpeg", addRemoveLinks: true, init: function(){ var submitButton = document.querySelector('#submit-all'); myDropzone = this; submitButton.addEventListener("click", function(){ myDropzone.processQueue(); }); this.on("complete", function(){ if(this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0) { var _this = this; _this.removeAllFiles(); } }); }, }; } $('#datetimepicker3').datetimepicker({ format: 'HH:mm' });
1.164063
1
lib/checks/httpValueResponse.js
adriancbo/statusdashboard
80
15993100
var checkRange = require('./range').execute, checkHttpStatusCode = require('./httpStatusCode').execute; exports.execute = function(response, serviceDefinition, service, callback) { checkHttpStatusCode(response, service, function (serviceStatus, service) { if (response.statusCode == 200 && (serviceDefinition.checkFixedValueResponse || serviceDefinition.checkRangeValuesResponse)) { response.on('data', function (chunk) { var value = ('' + chunk).substring(0, chunk.length - 1); if (serviceDefinition.checkFixedValueResponse) { if (serviceDefinition.checkFixedValueResponse[value]) { service.status = serviceDefinition.checkFixedValueResponse[value]; } else { service.status = "critical"; service.message = "Unexpected value " + value; } } else { if (serviceDefinition.checkRangeValuesResponse) { if (serviceDefinition.checkRangeValuesResponse.length === 0) { service.status = "critical"; service.message = "No range defined!"; } else { var found = false; for(var i = 0; i < serviceDefinition.checkRangeValuesResponse.length; i++) { var range = serviceDefinition.checkRangeValuesResponse[i]; if (checkRange(range.min, range.max, parseInt(value, 10))) { service.status = range.status; found = true; break; } } if (!found) { service.status = "critical"; service.message = "No range matches"; } } } } callback(service.status, service); }); } else { callback(service.status, service); } }); };
1.59375
2
dist/MakeSetListTool.js
jlyonsmith/make-set-list
0
15993108
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MakeSetListTool = void 0; var _minimist = _interopRequireDefault(require("minimist")); var _autobindDecorator = _interopRequireDefault(require("autobind-decorator")); var version = _interopRequireWildcard(require("./version")); var _fsExtra = _interopRequireDefault(require("fs-extra")); var _readdirp = _interopRequireDefault(require("readdirp")); var _promisifyChildProcess = require("promisify-child-process"); var _path = _interopRequireDefault(require("path")); var _class; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const pipeToPromise = (readable, writeable) => { const promise = new Promise((resolve, reject) => { readable.on("error", error => { reject(error); }); writeable.on("error", error => { reject(error); }); writeable.on("finish", file => { resolve(file); }); }); readable.pipe(writeable); return promise; }; let MakeSetListTool = (0, _autobindDecorator.default)(_class = class MakeSetListTool { constructor(container) { this.toolName = container.toolName; this.log = container.log; this.debug = !!container.debug; } async run(argv) { const options = { boolean: ["debug", "help", "version"], string: ["output"], alias: { o: "output" } }; const args = (0, _minimist.default)(argv, options); this.debug = !!args.debug; if (args.version) { this.log.info(version.fullVersion); return 0; } if (args.help) { this.log.info(` Usage: ${this.toolName} [options] <song-list-file> <pdf-root-dir> Description: Creates a set list from a collection of PDF files storeh in sub-directories. Options: --help Shows this help. --version Shows the tool version. --debug Output debug information. --output, -o <file> Output file name. `); return 0; } const songListPath = args._[0]; if (!songListPath) { throw new Error("A song list file must be given"); } let pdfRootPath = args._[1]; if (!pdfRootPath) { throw new Error("A PDF root directory must be given"); } const songList = await _fsExtra.default.readFile(songListPath, { encoding: "utf8" }); const songMap = new Map(); for (const title of songList.split("\n")) { songMap.set(title + ".pdf", []); } const entries = await _readdirp.default.promise(pdfRootPath, { fileFilter: Array.from(songMap.keys()) }); const outputPath = args.output || _path.default.basename(songListPath, _path.default.extname(songListPath)) + ".pdf"; for (const entry of entries) { const files = songMap.get(entry.basename); if (files) { files.push(entry.fullPath); } } for (const [name, files] of songMap.entries()) { const title = name.slice(0, -4); if (files.length === 0) { this.log.warning(`Song '${title}' was not found`); } else if (files.length > 1) { this.log.warning(`Song '${title}' has ${files.length} copies: ${files.map(file => '"' + file + '"').join(", ")}`); } } const command = `pdf-o-rama concat -o ${outputPath} ${Array.from(songMap.values()).filter(files => files.length > 0).map(files => `"${files[0]}"`).join(" ")}`; if (this.debug) { this.log.info(command); } this.log.info(`Combining PDF's into ${outputPath}...`); try { await (0, _promisifyChildProcess.exec)(command); } catch (e) { throw new Error(`Unable to create PDF. ${result.stderr.trim()}`); } this.log.info("Done"); return 0; } }) || _class; exports.MakeSetListTool = MakeSetListTool; //# sourceMappingURL=MakeSetListTool.js.map
1.109375
1