text
stringlengths
7
3.69M
$(document).ready(function () { //为每个时间控制添加事件 $("#blminus").on("click", function () { setBreakTime("-"); }); $("#blplus").on("click", function () { setBreakTime("+"); }); $("#slminus").on("click", function () { setSessionTime("-"); }); $("#slplus").on("click", function () { setSessionTime("+"); }); //执行倒计时 $("#toggle").on("click", function () { toggleTime(); }); }); //设置中断时间 function setBreakTime(symbol) { var breaktime = parseInt($("#blTime").text()); if (symbol === "-") { if (breaktime === 1) { return; } breaktime--; } else { breaktime++; } $("#blTime").text(breaktime); } //设置倒计时长 function setSessionTime(symbol) { var sessiontime = parseInt($("#slTime").text()); if (symbol === "-") { if (sessiontime === 1) { return; } sessiontime--; } else { sessiontime++; } $("#slTime").text(sessiontime); } //倒计时函数 function toggleTime() { var breaktime = parseInt($("#blTime").text()); var sessiontime = parseInt($("#slTime").text()); var nowtime=parseInt($("#countdown").text()); }
$(document).ready(function(){ $('#clear').bind('click', function () { $('#email').val("") $('#password').val("") $('#wrong').text("") }); $('#email').bind('keyup', function () { $('#wrong').text("") }); $('#password').bind('keyup', function () { $('#wrong').text("") }); }); $("#frmlogin").submit(function (e) { e.preventDefault(); $.ajax({ url: "/login/Login", cache: false, method: 'post', data: $('#frmlogin').serialize(), success: function (response) { if (response.status === "success") { window.location = response.url } else if (response.status === "wrong") { $('#wrong').text("Invalid Email or Password").css("color", "red"); } }, error: function (xhr, ajaxOptions, thrownError) { } }); //alert("ok") });
'use strict'; $(document).ready(function () { console.log('START'); var totalLength = 1500, count = 15, workers = [], allData = [], workersDone = 0; for (var i = 0; i < count; i++) { workers.push(new Worker('js/worker.js')); workers[i].onmessage = function (e) { allData[e.data.id] = e.data.data; workersDone++; }; workers[i].postMessage({ id: i, totalLength: totalLength, partialLength: totalLength / count }); } var interval = setInterval(function () { if (workersDone === count) { $('body').append(allData.join('')); console.log('END'); clearInterval(interval); } }, 200); });
'use strict'; /** Append the selected text to the end of the URL and redirect to the new address. */ function appendSuffixToUrl(tabUrl, TabId, suffixToAdd) { var newUrl = tabUrl + suffixToAdd; chrome.tabs.update(TabId, {url: newUrl}); } /** Verify that the URL and the selected text are strings */ function checkUrlAndSelectedTextAreValid(item) { console.assert(typeof item == 'string', 'url/selected text should be a string'); } /** Run verifications on the selected text and the URL. Add '/' in case it is missing and will cause to invalid address, or remove '/' in case of duplication. */ function checkSelectetTextValid(tabUrl, selectedText) { [tabUrl, selectedText].forEach(checkUrlAndSelectedTextAreValid); if(!selectedText.startsWith('/') && !tabUrl.endsWith('/')) { selectedText = '/' + selectedText; } else if (selectedText.startsWith('/') && tabUrl.endsWith('/')) { selectedText = selectedText.substr(1); } return selectedText; } /** Redirect to the new address that composed from the URL and the selected text */ function redirectUrlToPasteSuffixContent(selectedText) { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { selectedText = checkSelectetTextValid(tabs[0].url, selectedText); appendSuffixToUrl(tabs[0].url, tabs[0].id, selectedText); }); } /** Send message to the content script to fetch the marked text and redirect to the new address */ function sendCopySelectedTextMessage(callback) { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { var message = 'get_selected_text'; chrome.tabs.sendMessage(tabs[0].id, {data: message}, function(data) { callback(data.selectedText); }); }); } function commandSelector(command) { if (command == "add-marked-text-to-url") { sendCopySelectedTextMessage(redirectUrlToPasteSuffixContent); } } chrome.commands.onCommand.addListener(commandSelector);
import { fetchActivities } from "./activityActions"; describe("ActivityActions", () => { it("should get ok response", () => { fetchActivities(); }); });
$(function() { $("#btnNovoSistema").click(function(){ $("#codSistema").val(''); $("#nmeSistema").val(''); $("#nmeBanco").val(''); $("#indAtivo").attr('checked', false); $("#updateSistemaTitle").html("Incluir Sistema"); $("#updateSistema").modal("show"); }); }); function carregaGridSistemas(){ ExecutaDispatch('Sistemas', 'ListarSistemas', undefined, montaGridSistemas); } function montaGridSistemas(dados){ if(dados[0]){ var tabela = '<table id="tbSistemas" class="table table-striped">'; tabela += '<thead>'; tabela += '<tr>'; tabela += '<th><b>Sistema</b></th>'; tabela += '<th><b>Banco</b></th>'; tabela += '<th><b>Ativo?</b></th>'; tabela += '<th><b>Ações</b></th>'; tabela += '</tr>'; tabela += '</thead><tbody>'; if(dados[1]!=null) { dados = dados[1]; for (i=0;i<dados.length;i++){ tabela += '<tr>'; tabela += '<td>'+dados[i].NME_SISTEMA+'</td>'; tabela += '<td>'+dados[i].NME_BANCO+'</td>'; tabela += '<td>'+dados[i].IND_ATIVO+'</td>'; tabela += ' <td>'; tabela += ' <button class="btn btn-link" title="Editar" onClick="javascript:carregaCamposSistema('+dados[i].COD_SISTEMA+', `'+dados[i].NME_SISTEMA+'`, `'+dados[i].NME_BANCO+'`, `'+dados[i].IND_ATIVO+'`);">'; tabela += ' <i class="fa-solid fa-pencil"></i>'; tabela += ' </button>'; tabela += ' </td>'; tabela += '</tr>'; } } tabela += '</tbody>'; tabela += '</table>'; $("#tabelaSistemas").html(tabela); criarDataTable("tbSistemas"); } } $(document).ready(function(){ carregaGridSistemas(); });
/** * Created by Liu.Jun on 2020/11/5 11:24. */ import './style.css'; import { genId, getRealCurrentTarget, groupByLetter, querySelectorList, throttle, handleEvents } from './utils'; import genTemplateHtml, { groupItemsHtml, navItemsHtml } from './template'; // const hideClass = 'xx-disHide'; export default class Contacts { events = [] options = { target: '', // 需要放置的容器 hotLetter: '#', hotName: 'Hot.xxx', hotList: [], allList: [], groupedList: [], // 处理为分组数据 containerHeight: '60vh', showSearch: true, // 是否显示搜索 searchPlaceholder: '输入搜索词', // 是否显示搜索 showNavBar: true, // 显示导航条 navModel: 'scroll', // scrollBar / touchmove searchVal: '', // 搜索框的关键词同步 curSelect: '', // 当前选中的值 indicatorDuration: 1500, // 指示器弹窗显示时间 isDestroy: false, shouldObserveScroll: true, // 是否需要监听滚动事件 shouldObserveTouchMove: false, // 是否需要监听touchmove touchmoveX: 0, // 兼容移除区域继续move activeClassName: 'xx-active' } constructor(options) { this.resolveData(options); // 初始化options this.grouping(); // 分组 this.render(); // 渲染dom 已经绑定事件 this.updatePosition(); // 计算每个session position } callHook(name, ...args) { if (this.options[name]) { this.options[name].apply(null, args); } } throwError(msg) { // 抛出异常 throw new Error(msg.message || msg); } // 转换Option NodeList 到 dataList optionNodeList2DataList(optionNodeList) { return Array.from(optionNodeList).reduce((previousValue, curVal) => { if (curVal.value !== '') { const label = curVal.innerText || curVal.textContent || curVal.text; const groupKey = curVal.dataset.groupKey || label; previousValue.push({ value: curVal.value, label, groupKey, }); } return previousValue; }, []); } // 根据select标签解析数据 resolveSelectNodeData(selector, curSelect) { const selectDom = querySelectorList(selector)[0]; // selectDom.classList.add(hideClass); this.options.selectDom = selectDom; const hotNode = selectDom.querySelector('[data-type=hot]'); const dataOptions = Object.create(null); if (curSelect === undefined) dataOptions.curSelect = selectDom.value; if (hotNode) { // hotList dataOptions.hotList = this.optionNodeList2DataList(hotNode.querySelectorAll('option')); // allList const allNode = selectDom.querySelector('[data-type=all]'); if (allNode) dataOptions.allList = this.optionNodeList2DataList(allNode.querySelectorAll('option')); } else { dataOptions.allList = this.optionNodeList2DataList(selectDom.querySelectorAll('option')); } return dataOptions; } resolveData(options) { // 处理参数 const { data, ...args } = options; if (!data) this.throwError('构造函数参数必须包含 [data] 属性'); if (data.selectDom) { const dataOptions = this.resolveSelectNodeData(data.selectDom, args.curSelect); Object.assign(this.options, args, dataOptions); } else { if (!data.allList) { this.throwError('构造函数参数data属性必须包含 [selectDom] 或者 [allList]'); } Object.assign(this.options, args, data); } } // 对数据按首字母分组 grouping(isSearch = false) { // 合并hot 和所有两组数据 const hasHot = this.options.hotList && this.options.hotList.length > 0; this.options.groupedList = [ ...(hasHot && (!isSearch || this.options.searchVal === '') ? [{ isHot: true, name: this.options.hotName, letter: this.options.hotLetter, value: this.options.hotList, anchorPoint: genId() }] : []), ...groupByLetter(this.options.allList, this.options.searchVal) ]; } render() { const html = genTemplateHtml(this.options); const targetDom = querySelectorList(this.options.target)[0]; targetDom.insertAdjacentHTML('afterbegin', html); this.options.targetDom = targetDom; this.options.scrollDom = targetDom.querySelector('.js_contactsBoxListBox'); this.options.navBarDom = targetDom.querySelector('.js_contactsBoxKeyBar'); this.options.indicatorDom = targetDom.querySelector('.js_indicator'); this.bindEvent(targetDom); } toggleObserving(value) { this.options.shouldObserveScroll = value; } setNavBarSelect(target) { if (!this.options.showNavBar) return; const currentActiveDom = this.options.targetDom.querySelector(`.js_keyBarItem.${this.options.activeClassName}`); if (currentActiveDom) { currentActiveDom.classList.remove(this.options.activeClassName); } target.classList.add(this.options.activeClassName); } // 设置指示器弹窗 showNavBar(target) { this.options.indicatorDom.innerText = target.innerText; this.options.indicatorDom.style.display = 'block'; clearTimeout(this.$$indicatorTimer); this.$$indicatorTimer = setTimeout(() => { this.options.indicatorDom.style.display = 'none'; this.$$indicatorTimer = null; }, this.options.indicatorDuration); } // 计算每个 section position top updatePosition() { if (!this.options.allList.length > 0) return; // 如果滚动容器高度没发生变化 不重新计算 const curScrollHeight = this.options.scrollDom.scrollHeight; if (this.options.scrollHeight === curScrollHeight) return; this.options.scrollHeight = this.options.targetDom.scrollHeight; // 计算各个节点高度 const groupDomList = querySelectorList('.js_contactsBoxGroup', this.options.targetDom); groupDomList.forEach((item, index) => { this.options.groupedList[index].positionTop = item.offsetTop; }); // 计算 touchmoveX if (this.options.showNavBar && this.options.navModel === 'touchmove') { const barClientRect = this.options.navBarDom.getBoundingClientRect(); this.options.touchmoveX = barClientRect.left + (barClientRect.width || 6) / 2; } } getCurrentSection(scrollTop) { for (let i = this.options.groupedList.length - 1; i >= 0; i -= 1) { const cur = this.options.groupedList[i]; if (cur.positionTop <= scrollTop) { return cur; } } return this.options.groupedList[this.options.groupedList.length - 1]; } // 快捷导航点击事件 handleAnchorPoint(target) { // 停止滚动监听 // 优化性能,以及可能产生滚动定位计算和当前选中点的偏差 this.toggleObserving(false); this.setNavBarSelect(target); this.showNavBar(target); // 通过dom 计算对应高度 // this.options.scrollDom.scrollTop = document.getElementById(target.dataset.target).offsetTop; // 通过缓存的高度做计算 const anchorPoint = target.dataset.target; const curSectionPosition = this.options.groupedList.find(item => item.anchorPoint === anchorPoint); this.options.scrollDom.scrollTop = curSectionPosition.positionTop; setTimeout(() => { this.toggleObserving(true); }, 16); this.callHook('onScrollToAnchorPoint', target); } // 列表选中事件 handleSelect(target) { // 移除已选中 const currentActiveList = querySelectorList(`.js_contactsBoxGroupItem.${this.options.activeClassName}`, this.options.targetDom); currentActiveList.forEach(item => item.classList.remove(this.options.activeClassName)); // 选中新的值,可能多选 const curSelect = target.dataset.value; const selectList = querySelectorList(`.js_contactsBoxGroupItem[data-value='${target.dataset.value}']`, this.options.targetDom); selectList.forEach(item => item.classList.add(this.options.activeClassName)); this.options.curSelect = curSelect; this.callHook('onSelect', curSelect, target); } // 滚动条滚动事件 handleScrollChange(event) { if (this.isDestroy || !this.options.shouldObserveScroll) return; const scrollTarget = (event && event.target) || this.options.scrollDom; const scrollTop = Math.round(scrollTarget.scrollTop); // 有些浏览器可能不四舍五入 const currentSection = this.getCurrentSection(scrollTop); if (currentSection) { this.setNavBarSelect(this.options.targetDom.querySelector(`.js_keyBarItem[data-target=${currentSection.anchorPoint}]`)); } } // 搜索框change handleSearch(event) { // 更新值. this.options.searchVal = String(event.target.value).replace(/^\s+|\s+$/gm, ''); this.grouping(true); // 分组 this.options.scrollDom.innerHTML = groupItemsHtml(this.options); if (this.options.showNavBar) { this.options.navBarDom.innerHTML = navItemsHtml(this.options); } this.updatePosition(); this.options.scrollDom.scrollTop = 0; } bindEvent(targetDom) { // 点击选中事件 this.events.push({ target: targetDom, eventName: 'click', handler: (event) => { getRealCurrentTarget(event.currentTarget, event.target, (t) => { // 选中数据 if (t.className && ~t.className.indexOf('contactsBox_groupItem')) { this.handleSelect(t); return true; } return false; }); } }); // 容器滚动右侧定位事件 // 不操作dom不做节流了 this.events.push({ target: this.options.scrollDom, eventName: 'scroll', handler: this.handleScrollChange.bind(this) }); // 搜索框 input if (this.options.showSearch) { this.events.push({ target: this.options.targetDom.querySelector('.js_contactsBoxSearchInput'), eventName: 'input', handler: throttle(this.handleSearch.bind(this), 350) }); } // resize 判断是否需要重新计算position this.events.push({ target: window, eventName: 'resize', handler: throttle(() => { if (this.isDestroy) return; this.updatePosition(); this.handleScrollChange(); }, 250) }); // 快捷选择条事件 if (this.options.showNavBar) { // 点击跳转当前锚点 this.events.push({ target: targetDom, eventName: 'touchstart', handler: (event) => { getRealCurrentTarget(event.currentTarget, event.target, (t) => { // 点击右边栏关键词 if (t.className && ~t.className.indexOf('js_keyBarItem')) { this.handleAnchorPoint(t); return true; } return false; }); } }); if (this.options.navModel === 'touchmove') { // touchmove 模式,支持区域外滑动 this.events.push({ target: this.options.navBarDom, eventName: ['touchstart', 'touchend'], handler: (event) => { if (this.isDestroy) return; event.preventDefault(); this.options.shouldObserveTouchMove = event.type === 'touchstart'; } }); this.events.push({ target: document, eventName: 'touchmove', handler: throttle((event) => { if (this.isDestroy || !this.options.shouldObserveTouchMove) return; const target = document.elementFromPoint(this.options.touchmoveX, event.changedTouches[0].clientY); if (target && target.classList && target.classList.contains('js_keyBarItem')) { this.handleAnchorPoint(target); } }, 80) }); } } // 注册事件 handleEvents(this.events); } // 销毁 destroy() { this.isDestroy = true; // 释放计时器 clearTimeout(this.$$indicatorTimer); // 释放事件 handleEvents(this.events, 'removeEventListener'); // 还原dom节点 // if (this.options.selectDom) this.options.selectDom.classList.remove(hideClass); this.options.targetDom.removeChild(this.options.targetDom.firstElementChild); // 释放dom等引用 this.options = null; this.events.length = 0; } }
import { xianRequest } from '../../utils/xianRequest' import { HOST } from '../config' const getAdvertise = (params = {}) => { return xianRequest(params, `${HOST}/advertise/getAdvertises`) } const loginIn = (params = {}) => { return xianRequest(params, `${HOST}/userInfo/loginIn`) } const getHomeConfig = () => { return xianRequest({}, `${HOST}/config/getHome`) } const getHomeProduct = (params = {}) => { return xianRequest(params, `${HOST}/product/getByPage`) } const userExpected = (params = {}) => { return xianRequest(params, `${HOST}/expected/add`) } // 首页模块相关的接口 export default { getAdvertise, loginIn, getHomeConfig, getHomeProduct, userExpected }
import React, { PropTypes } from 'react'; import {Button, Select, Checkbox, Input, Form} from 'antd'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import {showError} from '../../../../../common/common'; import s from './Setting.less'; const SelectOption = Select.Option; class Setting extends React.Component { static propTypes = { setting: PropTypes.array, baseInfo: PropTypes.object, onClick: PropTypes.func, // 按钮事件 onBaseInfo: PropTypes.func, // setting数据改变事件 }; componentWillMount() { this.reportName = this.props.baseInfo.reportName; } onClick = (key) => { if (this.props.onClick && typeof this.props.onClick === 'function') { if(key === 'save' && this.props.baseInfo.tenantId) { this.props.onClick(key); } else if(key === 'add' && this.props.baseInfo.reportTypeConfigId) { this.props.onClick(key); } else if(key === 'del' && this.props.baseInfo.tenantId) { this.props.onClick(key); } else if(key === 'preview' && this.props.baseInfo.tenantId) { this.props.onClick(key); } else { showError('请选择一个设计模板'); } } }; onChange = (e, key) => { if (this.props.onBaseInfo && typeof this.props.onBaseInfo === 'function') { this.props.onBaseInfo(e.target.value, key); } } onSelect = (value, key) => { if (this.props.onBaseInfo && typeof this.props.onBaseInfo === 'function') { this.props.onBaseInfo(value, key); } } onCheckBoxChange = (e, key) => { if (this.props.onBaseInfo && typeof this.props.onBaseInfo === 'function') { this.props.onBaseInfo(e.target.checked ? 0 : 1, key); } } toOptions(options) { return options.map((options, index) => { return <SelectOption value={options.value} key={index}>{options.title}</SelectOption> }) } renderButton(set, index) { return <div key={index} style={{verticalAlign: 'bottom'}} > <Button onClick={() => this.onClick(set.key)} size="small" style={{ margin: '0 0 0 10px' }} >{set.title}</Button> </div> } renderSelect(set, index) { return <div key={index}> <span>{set.title}</span> <Select value={this.props.baseInfo[set.key]} size="small" mode="single" allowClear={true} showSearch={true} style={{ width: 100 }} onSelect={(value) => this.onSelect(value, set.key)} onChange={(value) => this.onSelect(value, set.key)} > {this.toOptions(set.options)} </Select> </div> } renderCheckbox(set, index) { return <div key={index} > <Checkbox onChange={(e) => this.onCheckBoxChange(e, set.key)} checked={this.props.baseInfo[set.key] === 0} > {set.title} </Checkbox> </div> } renderInput(set, index) { return <div key={index}> <span>{set.title}</span> <Input readOnly={set.readOnly} value={this.props.baseInfo[set.key]} size="small" style={{ width: 100 }} onChange={(e) => this.onChange(e, set.key)} /> </div> } renderComponents () { return this.props.setting.map((set, index) => { switch(set.type) { case 'select': return this.renderSelect(set, index); break; case 'text': return this.renderInput(set, index); break; case 'button': return this.renderButton(set, index); break; case 'checkbox': return this.renderCheckbox(set, index); break; default: break; } }); } renderPage = () => { return ( <div className={s.root}> <Form> {this.renderComponents()} </Form> </div> ); } render() { return this.renderPage(); } } export default withStyles(s)(Setting);
import './env'; import express from 'express'; import 'zone.js/dist/zone-node.js'; import bodyParser from 'body-parser'; import * as dbStuffs from './dbStuffs'; import * as dbware from './middlewares/dbware'; import * as todoService from './services/todos'; const PORT = process.env.PORT; let app = express(); app.set('port', PORT); app.use(bodyParser.json()); dbStuffs.connectAllDb(); //API Routes app.get('/', dbware.resolveConnection, async (req, res, next) => { let response; if (req.query.db === 'db1') { setTimeout(async () => { try { response = await todoService.getAllTodos(); } catch (e) { console.log('error', e); return; } res.json({ body: response[0].name }); }, 1000); } else { try { response = await todoService.getAllTodos(); } catch (e) { console.log('error', e); return; } res.json({ body: response[0].name }); } }); app.listen(app.get('port'), () => { console.log(`Server started at port: ${PORT}`); });
'use strict'; const mongoose = require('mongoose'); const Config = require('./env'); const mongoDBUrl = Config.db.url; const Console = console; module.exports.connect = () => { mongoose.Promise = Promise; mongoose.connect(mongoDBUrl, { useMongoClient: true }).then(() => { Console.log('Connected to MongoDB'); }, (err) => { Console.log(err); }); };
import BlockFactory from "./BlockFactory.js"; class BlockManager{ constructor(){ this.blocks = BlockFactory.getBlocks(); this.blockPreviews = BlockFactory.getPreviews(); this.offsets = BlockFactory.getKickOffsets(); this.rotation = 0; this.initQueue(); } initQueue(){ this.queue = [this.getRandomBlock(), this.getRandomBlock()]; } getCurrentBlock(){ return this.blocks[this.queue[0]][this.rotation]; } getNextBlock(){ return this.blockPreviews[this.queue[1]]; } rotateLeft(){ let from = this.rotation; this.rotation -= 1; if (this.rotation < 0){ this.rotation = 3; } return this.calculateKickOffset(from, this.rotation); } rotateRight(){ let from = this.rotation; this.rotation = (this.rotation + 1) % 4; return this.calculateKickOffset(from, this.rotation); } calculateKickOffset(from, to){ let fromOffsets = this.offsets[this.queue[0]][from]; let toOffsets = this.offsets[this.queue[0]][to]; let offsets = []; for(let i=0; i<fromOffsets.length; i++){ let o1 = fromOffsets[i]; let o2 = toOffsets[i]; offsets.push([o1[0] - o2[0], o1[1] - o2[1]]); } return offsets; } nextBlock(){ this.queue.shift(); this.queue.push(this.getRandomBlock()); this.rotation = 0; } getRandomBlock(){ return Math.floor(Math.random()*this.blocks.length); } } export default BlockManager
var uid_element = document.getElementById("uid"); var gid_element = document.getElementById("gid"); var uid = uid_element.innerHTML; var gid = gid_element.innerHTML; var myInterval = 0; var old_djson = null var new_djson = null var right_letters = []; var wrong_letters = []; var wrong_phrases = []; var new_right_letters = []; var new_wrong_letters = []; var new_wrong_phrases = []; resizeDiv(); $.ajax({ type : 'GET', url : '/game/'+ gid + '/no_ai', contentType: 'application/json', }).done(function(data) { old_djson = JSON.parse(data); var win_uid = old_djson.win; var guess_uid = old_djson.guesser_uid; var creator_uid = old_djson.creator_uid; var message = ""; var redirect_location = "/lobby/" + uid; if(uid.charAt(0) == 'g') { var redirect_location = "/guestlobby/"+uid; } if(win_uid == uid){ if(uid == guess_uid){ message = "You correctly guessed the phrase!"; } else{ message = "Your opponent failed to guess your word!"; } window.alert(message); window.location.href = redirect_location; } else if(win_uid == guess_uid){ message = "Your opponent got loose from noose. You lose!"; window.alert(message); window.location.href = redirect_location; } else if(win_uid == creator_uid){ message = "Oh no! You died. The word was " + answer; console.log(word); window.alert(message); window.location.href = redirect_location; } else{ myInterval = setInterval(function(){ poll_updates(); }, 3000); } }); window.onresize = function(event) { resizeDiv(); } function resizeDiv() { vpw = $(window).width(); vph = $(window).height()/2; $('#gallows-img').css({'height': vph + 'px'}); } function poll_updates(){ $.ajax({ type : 'GET', url : '/game/'+ gid, contentType: 'application/json', }).done(function(data) { console.log("in done"); new_djson = JSON.parse(data); console.log(new_djson.correct_letters) console.log(old_djson.correct_letters) console.log(new_djson.incorrect_letters) console.log(old_djson.incorrect_letters) console.log(new_djson.incorrect_words) console.log(old_djson.incorrect_words) if(new_djson.correct_letters.length != old_djson.correct_letters.length){ console.log('correct_letters\n') window.location.href="/gameplay/" + uid + "/" + gid; } if(new_djson.incorrect_letters.length != old_djson.incorrect_letters.length){ console.log('incorrect_letters\n') window.location.href="/gameplay/" + uid + "/" + gid; } if(new_djson.incorrect_words.length != old_djson.incorrect_words.length){ console.log('incorrect_words\n') window.location.href="/gameplay/" + uid + "/" + gid; } }); }
const data = require('./database.json'); const GetCumbiaAPIHandler = { canHandle(handlerInput) { const request = handlerInput.requestEnvelope; return Alexa.getRequestType(request) === 'Dialog.API.Invoked' && request.request.apiRequest.name === 'getCumbia'; }, handle(handlerInput) { const apiRequest = handlerInput.requestEnvelope.request.apiRequest; } }; // ***************************************************************************** // Resolves slot value using Entity Resolution const resolveEntity = function(resolvedEntity, slotName) { //This is built in functionality with SDK Using Alexa's ER let erAuthorityResolution = resolvedEntity[slotName].resolutions.resolutionsPerAuthority[0]; let value = null; if (erAuthorityResolution.status.code === 'ER_SUCCESS_MATCH') { value = erAuthorityResolution.values[0].value.name; } return value; } const buildSuccessApiResponse = (returnEntity, endSession = false) => { return { apiResponse: returnEntity, shouldEndSession: endSession}; };
import baseConfig from './webpack.base.config' export default { ...baseConfig, entry: '../src/index.js', output: { ...baseConfig.output, filename: 'client.js' } }
// *********************************************** // This example commands.js shows you how to // create various custom commands and overwrite // existing commands. // // For more comprehensive examples of custom // commands please read more here: // https://on.cypress.io/custom-commands // *********************************************** // Test Data가 필요함.. //username, paswword를 가져와서 넣어주도록 구현 필요 //url도 환경 설정에 따라 설정되도록 해야함.. //token을 받아오는 방법 확인해 보아야함. /* Cypress.Commands.add('login', ({ username = 'jw3@jw.com', password = '12341234' }) => { cy.request({ method: 'post', url: `https://api.qa.fastcampus.co.kr/auth/tokens`, body: { grant_type: 'password', client_id: 'fc:client:www', client_secret: undefined, scope: 'www', state: 'www:password', username, password, }, }).as('token'); cy.get('@token').then((res) => { const accessToken = res.body.access_token; console.info(accessToken); cy.visit(`/#access_token=${accessToken}`); }); }); */
var initstate={ list2:[] } function reducer(state=initstate,action){ switch(action.type){ case 'HOTPRO': //console.log(action);//{payload:{},type:{}} return {...state,list2:action.payload}; default: return state } } export default reducer;
const express=require("express"); const mysql=require("mysql"); const sqlMsg=require("../CONFIG/DATA_BASE.js") const link=mysql.createPool(sqlMsg) module.exports=function(){ const server=express.Router() server.use("/",function(request,response,next){ const {userMSG}=Object.assign({},request.session); const cid=request.query.cid||""; const sql=`select * from customer where uid='${userMSG.uid}' ORDER BY time DESC` link.query(sql,function(err,res){ if(!err){ response.send(res) }else{ response.send(false) } }) }) return server }
import React, {Component} from 'react'; import {Button} from '@material-ui/core'; import Checkout from './Checkout'; import FlashMessage from 'react-flash-message'; import './Home.css'; class Home extends Component{ state={ foodList:[], cart:[], total:0 } componentDidMount(){ let uri="http://localhost:9000/getFoodItem"; fetch(uri).then(res=>res.json()).then(res=>{ this.setState({foodList:res}); } ).catch(er=>alert(er)); } onCart=u=>{ let cart=this.state.cart; cart.push(u); let total=this.state.total; total+=u.price; this.setState({cart:cart,total:total}); } show=()=>{ const cart=this.state.cart; const total=this.state.total; this.props.history.push({ pathname:'/checkout', state:{cart:cart,total:total} }); } render(){ return( <div> <h1>Welcome to Simple Restaurant App</h1> <div className='row'> {this.state.foodList.map((u)=> <div className='column' key={u._id}> <h3>{u.title}</h3> <img src={u.Imgurl} style={{width:'300px',height:'300px'}} alt=''/> <p>Price: {u.price}</p> <Button variant='contained' color='primary' onClick={()=>this.onCart(u)}>Add to cart</Button> </div> )} </div> <Button variant='contained' onClick={this.show}>Go to checkout page</Button> </div> ) } } export default Home;
/* global jasmine, describe, beforeAll, afterAll, it, expect */ import { join, resolve } from 'path' import { existsSync } from 'fs' import { nextServer, renderViaHTTP, startApp, stopApp, waitFor } from 'next-test-utils' const context = {} context.app = nextServer({ dir: join(__dirname, '../'), dev: true, quiet: true }) jasmine.DEFAULT_TIMEOUT_INTERVAL = 40000 describe('On Demand Entries', () => { beforeAll(async () => { context.server = await startApp(context.app) context.appPort = context.server.address().port }) afterAll(() => stopApp(context.server)) it('should compile pages for SSR', async () => { const pageContent = await renderViaHTTP(context.appPort, '/') expect(pageContent.includes('Index Page')).toBeTruthy() }) it('should compile pages for JSON page requests', async () => { const pageContent = await renderViaHTTP(context.appPort, '/_next/-/page/about') expect(pageContent.includes('About Page')).toBeTruthy() }) it('should dispose inactive pages', async () => { await renderViaHTTP(context.appPort, '/_next/-/pages/about') const aboutPagePath = resolve(__dirname, '../.next/bundles/pages/about.js') expect(existsSync(aboutPagePath)).toBeTruthy() // Wait maximum of jasmine.DEFAULT_TIMEOUT_INTERVAL checking // for disposing /about while (true) { await waitFor(1000 * 1) if (!existsSync(aboutPagePath)) return } }) })
/* eslint-disable no-undef */ import LikeButtonInitiator from '../src/scripts/utils/like-button-initiator'; import FavoriteRestoIdb from '../src/scripts/data/favoriterestaurant-idb'; describe('Liking Restaurant', () => { const resto = { id: 'abc', name: 'Resto a', }; const addLikeButton = async () => { await LikeButtonInitiator.init({ likeButtonContainer, favoriteResto: FavoriteRestoIdb, resto, }); }; const clickLikeButton = () => { const likeButton = document.querySelector('#likeButton'); likeButton.dispatchEvent(new Event('click')); }; beforeEach(async () => { await FavoriteRestoIdb.deleteResto(resto.id); document.body.innerHTML = '<div id="likeButtonContainer"></div>'; // eslint-disable-next-line no-unused-vars const likeButtonContainer = document.getElementById('likeButtonContainer'); }); afterEach(async () => { await FavoriteRestoIdb.deleteResto(resto.id); }); it('should show the like button when no resto liked', async () => { await addLikeButton(); expect(document.querySelector('[aria-label="like this resto"]')) .toBeTruthy(); expect(document.querySelector('[aria-label="unlike this resto"]')) .toBeFalsy(); }); it('should add the resto if the like button is clicked', async () => { await addLikeButton(); clickLikeButton(); expect(await FavoriteRestoIdb.getResto(resto.id)) .toEqual(resto); }); it('should not add the resto if it already exists', async () => { await addLikeButton(); await FavoriteRestoIdb.putResto(resto); clickLikeButton(); expect(await FavoriteRestoIdb.getAllRestos()) .toEqual([resto]); }); it('should not add the resto if it has no id', async () => { await LikeButtonInitiator.init({ likeButtonContainer, favoriteResto: FavoriteRestoIdb, resto: {}, }); clickLikeButton(); expect(await FavoriteRestoIdb.getAllRestos()) .toEqual([]); expect(document.querySelector('[aria-label="like this resto"]')) .toBeTruthy(); expect(document.querySelector('[aria-label="unlike this resto"]')) .toBeFalsy(); }); });
import React, { Component } from 'react'; import './App.css'; import Home from './Page/home' import Brand from './Page/brand' import Loginpage from './Page/Loginpage'; import Registerpage from './Page/Registerpage' import Shoppingcart from './Page/Shoppingcart' import { Link, Route } from 'react-router-dom'; import { createStore, applyMiddleware } from 'redux'; import reducer from './reducer'; import ReduxThunk from 'redux-thunk'; import {Provider} from 'react-redux' import Invoice from './komponen/invoice'; import Admin from './komponen/admin'; import Categories from './komponen/Categories'; import adminDetails from './komponen/adminDetails' import adminProd from './komponen/adminProd'; import adminCategory from './komponen/adminCategory'; import adminInvoice from './komponen/adminInvoice'; // import product1 from './komponen/product1'; class App extends Component { render() { const store = createStore(reducer,{},applyMiddleware(ReduxThunk)) return( <Provider store = {store}> <div> <Route exact path="/" component={Home}/> <Route path="/brands" component={Brand}/> <Route path="/Loginpage" component={Loginpage}/> <Route path="/Registerpage" component={Registerpage}/> <Route path="/Shoppingcart" component={Shoppingcart}/> <Route path="/invoice" component={Invoice}/> <Route path="/admin" component={Admin}/> <Route path="/Categories" component={Categories}/> <Route path="/adminDetails" component={adminDetails}/> <Route path="/adminProduct" component={adminProd}/> <Route path="/adminCategory" component={adminCategory}/> <Route path="/adminInvoice" component={adminInvoice}/> </div> </Provider> ); } } export default App;
module.exports = { "development": { "username": "onboard", "database": "onboard", "host": "0.0.0.0", "dialect": "mysql" }, "c9": { "username": "arnoldtan", "database": "c9", "host": process.env.IP, "dialect": "mysql" } };
//負責路由 //模塊任務單一且清晰 var fs = require('fs') var Student = require('./student') var express = require('express') var router = express.Router() router.get('/students', function (req, res) { Student.find(function (err, students) { if (err) { return res.status(500).send('server error') } res.render('index.html', { fruits: [ '蘋果', '香蕉', '葡萄' ], students: students }) }) }) router.get('/students/new', function (req, res) { res.render('new.html') }) router.post('/students/new', function (req, res) { //先獲取表單數據 //處理 //發出響應 //先讀取然後轉成對象 //往對象push數據 //把對象轉成字串 //把對象再次寫入 new Student(req.body).save(function (err) { if (err) { return res.status(500).send('server error') } res.redirect('/students') }) }) router.get('/students/edit', function (req, res) { //在客戶端獲取處理鏈結<需要id參數> //獲取編輯學生id //渲染 // res.render('edit.html',{ // }) //replace用正則表達式把全部" "換掉 Student.findById(req.query.id.replace(/"/g, ''), function (err, student) { if (err) { return res.status(500).send('Server error.') } res.render('edit.html', { student: student }) }) }) router.post('/students/edit', function (req, res) { var id = req.body.id.replace(/"/g, '') Student.findByIdAndUpdate(id,req.body, function (err) { if (err) { return res.status(500).send('Server error.') } res.redirect('/students') }) }) router.get('/students/delete', function (req, res) { var id = req.query.id.replace(/"/g, '') Student.findByIdAndRemove(id, function (err) { if (err) { return res.status(500).send('Server error.') } res.redirect('/students') }) }) module.exports = router // module.exports = function(router){ // router.get('/', function (req, res) { // fs.readFile('./db.json','utf8',function(err,data){ // if(err){ // return res.status(500).send('server error.') // } // var students = JSON.parse(data).students // //從文件出來一定是字串 // //一定要手動轉乘對象 // res.render('index.html', { // fruits: [ // '蘋果', // '香蕉', // '葡萄' // ], // students:students // }) // }) // }) // router.get('/', function (req, res) { // }) // router.get('/', function (req, res) { // }) // router.get('/', function (req, res) { // }) // router.get('/', function (req, res) { // }) // }
url_regex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/ tech_urls = ['http://feeds.feedburner.com/blogspot/MKuf?format=xml', 'http://jcla1.com/rss.xml']; human_urls = ['http://geographyblog.eu/wp/feed/']; science_urls = ['http://blogs.nature.com/feed/']; sources = [tech_urls, human_urls, science_urls]; subscribed_urls = []; $(function() { $('#addbuttonrss').click(function(e){ var input = $('#rssinput').val() if (url_regex.test(input) & subscribed_urls.indexOf(input) === -1) { subscribed_urls.push(input); $('#rssurls').append('<p>' + input + '</p>') } else { alert('wrong input or already submitted!'); } }); $('#submitrss').click(function(e){ $('input[type="checkbox"]').each(function(key, value){ if ($(value).is(':checked')) { for(var i = 0; i < sources[key].length; i++){ if (subscribed_urls.indexOf(sources[key][i]) === -1) { subscribed_urls.push(sources[key][i]); } } } }); // AJAX Stuff $.ajax({ url: '/recrss', type: 'POST', data: {feeds: subscribed_urls}, completed: function(request){ window.location = "/" } }) }); });
function initTabs() { const tabsWrapper = document.querySelectorAll('[data-tabs-wrapper]'); const _tabs = '[data-tab]'; const _buttons = '[data-button]'; function buttonsListener(buttons, tabs, tabsWrapper) { let activeTabNumber = +tabsWrapper.dataset.tabsWrapper; function removeActive(buttons, tabs) { for (let i = 0; i < buttons.length; i++){ tabs[activeTabNumber].classList.remove('active-tab'); } }; for (let i = 0; i < buttons.length; i++){ buttons[i].addEventListener('click', ()=> { removeActive(buttons, tabs); if(i === 1){ activeTabNumber += 1; if (activeTabNumber === tabs.length){ activeTabNumber = 0 } }else{ activeTabNumber -= 1; if (activeTabNumber < 0){ activeTabNumber = --tabs.length } } let abc = tabs[activeTabNumber]; abc.classList.add('active-tab'); }) } }; for (let i= 0; i < tabsWrapper.length; i++){ const buttons = tabsWrapper[i].querySelectorAll(_buttons); const tabs = tabsWrapper[i].querySelectorAll(_tabs); buttonsListener(buttons, tabs, tabsWrapper[i]); } }; initTabs();
// This import loads the firebase namespace along with all its type information. import * as firebase from 'firebase/app'; // These imports load individual services into the firebase namespace. import 'firebase/auth'; import 'firebase/firestore'; import "firebase/storage"; const firebaseConfig = { apiKey: process.env.REACT_APP_FIREBASE_API_KEY, authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN, databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL, projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID, storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID, appId: process.env.REACT_APP_FIREBASE_APP_ID, measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID }; // react-redux-firebase config const rrfConfig = { userProfile: 'users', useFirestoreForProfile: true, // Firestore for Profile instead of Realtime DB enableClaims: true // Get custom claims along with the profile } const initFirebase = () => { firebase.initializeApp(firebaseConfig); firebase.storage() } export { initFirebase, firebase, rrfConfig }
//function parseFiled(field){ // return field.split(/\[|\]/).filter(function (s) { // return s; // }) //} function getFiled(req,field){ var val=req.body; //field.forEach(function (prop) { // val=val[prop]; //}); return val[field]; } exports.required= function (field) { //field=parseFiled(field); return function (req,res,next) { if(getFiled(req,field)){ next(); } else{ res.err(field + 'is required'); //因为不是数组,所以不能用join res.redirect('back'); } } }; exports.lengthAbove= function (field,len) { //field=parseFiled(field); return function (req,res,next) { if(getFiled(req,field).length>len){ next(); } else{ res.err(field+'must have more than'+len +'charactes'); res.redirect('back'); } } };
const consign = require('consign') const fs = require('fs'); // const http = require('http'); const https = require('https'); let app = require('./config/server') const credentials = { key: fs.readFileSync('/etc/letsencrypt/live/azcrew.ddns.net/privkey.pem', 'utf8'), cert: fs.readFileSync('/etc/letsencrypt/live/azcrew.ddns.net/fullchain.pem', 'utf8') } // const httpServer = http.createServer(app).listen(80, () => { // console.log('HTTP Express Server running') // }) const httpsServer = https.createServer(credentials, app).listen(443, () => { console.log('HTTPS Express Server running') }) let io = require('socket.io').listen(httpsServer) consign().include('./app/socket').into(io)
import React, { Component } from 'react'; import { Nav, NavItem, Navbar, NavbarToggler, NavbarBrand, Collapse, Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap'; import { NavLink, Redirect, Link } from 'react-router-dom'; class NavBarC extends Component{ constructor(props) { super(props); this.state = { isNavOpen: false, isDropdownOpen: false }; this.toggleNav = this.toggleNav.bind(this); this.toggleDropdown = this.toggleDropdown.bind(this); } toggleNav(){ this.setState({ isNavOpen: !this.state.isNavOpen }); } toggleDropdown(){ this.setState({ isDropdownOpen: !this.state.isDropdownOpen }); } render(){ return ( <Navbar color='dark' expand="md" dark> <div className="container"> <NavbarToggler onClick={this.toggleNav} /> <NavbarBrand className="mr-auto logo-setting" href="/"><img height="30" width="41" alt='Blog Outlet' src={process.env.PUBLIC_URL + '/assets/images/logo.png'} /> BLOG OUTLET</NavbarBrand> <Collapse isOpen={this.state.isNavOpen} navbar> <Nav navbar className="ml-auto"> <NavItem> <NavLink className="nav-link" to='/home'><span className="fa fa-home fa-lg"></span> Home</NavLink> </NavItem> { !this.props.authUser.authenticated && ( <NavItem> <NavLink className="nav-link" to='/login'><span className="fa fa-user fa-lg"></span> Login</NavLink> </NavItem> ) } { this.props.authUser.authenticated && ( <React.Fragment> <Redirect to='/home'/> <NavItem> <NavLink className="nav-link" to='/contactus'><span className="fa fa-address-card fa-lg"></span> Contact Us</NavLink> </NavItem> <NavItem> <NavLink className="nav-link" to='/blog'><span className="fa fa-edit fa-lg"></span> Blog</NavLink> </NavItem> <NavItem className="ml-1"> <Dropdown isOpen={this.state.isDropdownOpen} toggle={this.toggleDropdown}> <DropdownToggle tag="span" caret> <img src= {this.props.authUser.user.credentials.imageUrl} className="user-icon" alt='Userimg' /> </DropdownToggle> <DropdownMenu className="link-setup"> <Link to="/user"><DropdownItem>{this.props.authUser.user.credentials.handle}</DropdownItem></Link> <DropdownItem onClick={this.props.logout}>Logout</DropdownItem> </DropdownMenu> </Dropdown> </NavItem> </React.Fragment> ) } </Nav> </Collapse> </div> </Navbar> ); } } export default NavBarC;
import React from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faUserLock } from "@fortawesome/free-solid-svg-icons"; export default function Forbbiden() { return ( <div className="container"> <div className="row"> <div className="col"> <div className="text-center"> <FontAwesomeIcon icon={faUserLock} size={"6x"} className="mt-5 text-primary" /> <p className="mt-2">Acceso denegado</p> </div> </div> </div> </div> ); }
import axios from 'axios'; import { LOGIN, CHECK_AUTH, loginSuccess, loginError, logoutSuccess } from '../action/user-actions'; export default (store) => (next) => (action) => { next(action); switch (action.type) { /* case CHECK_AUTH: { axios({ method: 'post', url: 'http://localhost:3001/isLogged', withCredentials: true // Je veux que le serveur sache qui je suis grace à la session }) .then((res) => { console.log(res.data); if (res.data.logged) { store.dispatch(loginSuccess(res.data.info)); } }) .catch((err) => { console.error(err); }) break; } */ // réagir au login case LOGIN: { const { user } = store.getState(); console.log(user); axios({ method: 'post', url: 'http://localhost:3000/api/user', data: user, withCredentials: true // Je veux que le serveur sache qui je suis grace à la session }) .then((res) => { console.log('login request') store.dispatch(loginSuccess(res.data)); }) .catch((err) => { store.dispatch(loginError("Impossible de connecter cet utilisateur")) }) break; } default: return; } }
/*jshint sub:true, evil:true */ (function () { "use strict"; var view = '', // data-view listFeeds = '', // data-list-feeds filter = '', // data-filter order = '', // data-order autoreadItem = '', // data-autoread-item autoreadPage = '', // data-autoread-page autohide = '', // data-autohide byPage = -1, // data-by-page shaarli = '', // data-shaarli redirector = '', // data-redirector currentHash = '', // data-current-hash currentPage = 1, // data-current-page currentNbItems = 0, // data-nb-items autoupdate = false, // data-autoupdate autofocus = false, // data-autofocus addFavicon = false, // data-add-favicon preload = false, // data-preload stars = false, // data-stars isLogged = false, // data-is-logged blank = false, // data-blank swipe = '', // data-swipe status = '', listUpdateFeeds = [], listItemsHash = [], currentItemHash = '', currentUnread = 0, title = '', cache = {}, intlTop = 'top', intlShare = 'share', intlRead = 'read', intlUnread = 'unread', intlStar = 'star', intlUnstar = 'unstar', intlFrom = 'from'; /** * trim function * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/Trim */ if(!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g,''); }; } /** * http://javascript.info/tutorial/bubbling-and-capturing */ function stopBubbling(event) { if(event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } } /** * JSON Object * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON */ if (!window.JSON) { window.JSON = { parse: function (sJSON) { return eval("(" + sJSON + ")"); }, stringify: function (vContent) { if (vContent instanceof Object) { var sOutput = ""; if (vContent.constructor === Array) { for (var nId = 0; nId < vContent.length; sOutput += this.stringify(vContent[nId]) + ",", nId++); return "[" + sOutput.substr(0, sOutput.length - 1) + "]"; } if (vContent.toString !== Object.prototype.toString) { return "\"" + vContent.toString().replace(/"/g, "\\$&") + "\""; } for (var sProp in vContent) { sOutput += "\"" + sProp.replace(/"/g, "\\$&") + "\":" + this.stringify(vContent[sProp]) + ","; } return "{" + sOutput.substr(0, sOutput.length - 1) + "}"; } return typeof vContent === "string" ? "\"" + vContent.replace(/"/g, "\\$&") + "\"" : String(vContent); } }; } /** * https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started */ function getXHR() { var httpRequest = false; if (window.XMLHttpRequest) { // Mozilla, Safari, ... httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) {} } } return httpRequest; } /** * http://www.sitepoint.com/xhrrequest-and-javascript-closures/ */ // Constructor for generic HTTP client function HTTPClient() {} HTTPClient.prototype = { url: null, xhr: null, callinprogress: false, userhandler: null, init: function(url, obj) { this.url = url; this.obj = obj; this.xhr = new getXHR(); }, asyncGET: function (handler) { // Prevent multiple calls if (this.callinprogress) { throw "Call in progress"; } this.callinprogress = true; this.userhandler = handler; // Open an async request - third argument makes it async this.xhr.open('GET', this.url, true); var self = this; // Assign a closure to the onreadystatechange callback this.xhr.onreadystatechange = function() { self.stateChangeCallback(self); }; this.xhr.send(null); }, stateChangeCallback: function(client) { switch (client.xhr.readyState) { // Request not yet made case 1: try { client.userhandler.onInit(); } catch (e) { /* Handler method not defined */ } break; // Contact established with server but nothing downloaded yet case 2: try { // Check for HTTP status 200 if ( client.xhr.status != 200 ) { client.userhandler.onError( client.xhr.status, client.xhr.statusText ); // Abort the request client.xhr.abort(); // Call no longer in progress client.callinprogress = false; } } catch (e) { /* Handler method not defined */ } break; // Called multiple while downloading in progress case 3: // Notify user handler of download progress try { // Get the total content length // -useful to work out how much has been downloaded var contentLength; try { contentLength = client.xhr.getResponseHeader("Content-Length"); } catch (e) { contentLength = NaN; } // Call the progress handler with what we've got client.userhandler.onProgress( client.xhr.responseText, contentLength ); } catch (e) { /* Handler method not defined */ } break; // Download complete case 4: try { client.userhandler.onSuccess(client.xhr.responseText, client.obj); } catch (e) { /* Handler method not defined */ } finally { client.callinprogress = false; } break; } } }; /** * Handler */ var ajaxHandler = { onInit: function() {}, onError: function(status, statusText) {}, onProgress: function(responseText, length) {}, onSuccess: function(responseText, noFocus) { var result = JSON.parse(responseText); if (result['logout'] && isLogged) { alert('You have been disconnected'); } if (result['item']) { cache['item-' + result['item']['itemHash']] = result['item']; loadDivItem(result['item']['itemHash'], noFocus); } if (result['page']) { updateListItems(result['page']); setCurrentItem(); if (preload) { preloadItems(); } } if (result['read']) { markAsRead(result['read']); } if (result['unread']) { markAsUnread(result['unread']); } if (result['update']) { updateNewItems(result['update']); } } }; /** * http://stackoverflow.com/questions/4652734/return-html-from-a-user-selection/4652824#4652824 */ function getSelectionHtml() { var html = ''; if (typeof window.getSelection != 'undefined') { var sel = window.getSelection(); if (sel.rangeCount) { var container = document.createElement('div'); for (var i = 0, len = sel.rangeCount; i < len; ++i) { container.appendChild(sel.getRangeAt(i).cloneContents()); } html = container.innerHTML; } } else if (typeof document.selection != 'undefined') { if (document.selection.type == 'Text') { html = document.selection.createRange().htmlText; } } return html; } /** * Some javascript snippets */ function removeChildren(elt) { while (elt.hasChildNodes()) { elt.removeChild(elt.firstChild); } } function removeElement(elt) { if (elt && elt.parentNode) { elt.parentNode.removeChild(elt); } } function addClass(elt, cls) { if (elt) { elt.className = (elt.className + ' ' + cls).trim(); } } function removeClass(elt, cls) { if (elt) { elt.className = (' ' + elt.className + ' ').replace(cls, ' ').trim(); } } function hasClass(elt, cls) { if (elt && (' ' + elt.className + ' ').indexOf(' ' + cls + ' ') > -1) { return true; } return false; } /** * Add redirector to link */ function anonymize(elt) { if (redirector !== '') { var domain, a_to_anon = elt.getElementsByTagName("a"); for (var i = 0; i < a_to_anon.length; i++) { domain = a_to_anon[i].href.replace('http://','').replace('https://','').split(/[/?#]/)[0]; if (domain !== window.location.host) { if (redirector !== 'noreferrer') { a_to_anon[i].href = redirector+a_to_anon[i].href; } else { a_to_anon[i].setAttribute('rel', 'noreferrer'); } } } } } function initAnonyme() { if (redirector !== '') { var i = 0, elements = document.getElementById('list-items'); elements = elements.getElementsByTagName('div'); for (i = 0; i < elements.length; i += 1) { if (hasClass(elements[i], 'item-content')) { anonymize(elements[i]); } } } } /** * Replace collapse bootstrap function */ function collapseElement(element) { if (element !== null) { var targetElement = document.getElementById( element.getAttribute('data-target').substring(1) ); if (hasClass(targetElement, 'in')) { removeClass(targetElement, 'in'); targetElement.style.height = 0; } else { addClass(targetElement, 'in'); targetElement.style.height = 'auto'; } } } function collapseClick(event) { event = event || window.event; stopBubbling(event); collapseElement(this); } function initCollapse(list) { var i = 0; for (i = 0; i < list.length; i += 1) { if (list[i].hasAttribute('data-toggle') && list[i].hasAttribute('data-target')) { addEvent(list[i], 'click', collapseClick); } } } /** * Shaarli functions */ function htmlspecialchars_decode(string) { return string .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&quot;/g, '"') .replace(/&amp;/g, '&') .replace(/&#0*39;/g, "'") .replace(/&nbsp;/g, " "); } function shaarliItem(itemHash) { var domainUrl, url, domainVia, via, title, sel, element; element = document.getElementById('item-div-'+itemHash); if (element.childNodes.length > 1) { title = getTitleItem(itemHash); url = getUrlItem(itemHash); via = getViaItem(itemHash); if (redirector != 'noreferrer') { url = url.replace(redirector,''); via = via.replace(redirector,''); } domainUrl = url.replace('http://','').replace('https://','').split(/[/?#]/)[0]; domainVia = via.replace('http://','').replace('https://','').split(/[/?#]/)[0]; if (domainUrl !== domainVia) { via = 'via ' + via; } else { via = ''; } sel = getSelectionHtml(); if (sel !== '') { sel = '«' + sel + '»'; } if (shaarli !== '') { window.open( shaarli .replace('${url}', encodeURIComponent(htmlspecialchars_decode(url))) .replace('${title}', encodeURIComponent(htmlspecialchars_decode(title))) .replace('${via}', encodeURIComponent(htmlspecialchars_decode(via))) .replace('${sel}', encodeURIComponent(htmlspecialchars_decode(sel))), '_blank', 'height=390, width=600, menubar=no, toolbar=no, scrollbars=yes, status=no, dialog=1' ); } else { alert('Please configure your share link first'); } } else { loadDivItem(itemHash); alert('Sorry ! This item is not loaded, try again !'); } } function shaarliCurrentItem() { shaarliItem(currentItemHash); } function shaarliClickItem(event) { event = event || window.event; stopBubbling(event); shaarliItem(getItemHash(this)); return false; } /** * Folder functions */ function getFolder(element) { var folder = null; while (folder === null && element !== null) { if (element.tagName === 'LI' && element.id.indexOf('folder-') === 0) { folder = element; } element = element.parentNode; } return folder; } function getLiParentByClassName(element, classname) { var li = null; while (li === null && element !== null) { if (element.tagName === 'LI' && hasClass(element, classname)) { li = element; } element = element.parentNode; } if (classname === 'folder' && li.id === 'all-subscriptions') { li = null; } return li; } function getFolderHash(element) { var folder = getFolder(element); if (folder !== null) { return folder.id.replace('folder-',''); } return null; } function toggleFolder(folderHash) { var i, listElements, url, client; listElements = document.getElementById('folder-' + folderHash); listElements = listElements.getElementsByTagName('h5'); if (listElements.length > 0) { listElements = listElements[0].getElementsByTagName('span'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'folder-toggle-open')) { removeClass(listElements[i], 'folder-toggle-open'); addClass(listElements[i], 'folder-toggle-close'); } else if (hasClass(listElements[i], 'folder-toggle-close')) { removeClass(listElements[i], 'folder-toggle-close'); addClass(listElements[i], 'folder-toggle-open'); } } } url = '?toggleFolder=' + folderHash + '&ajax'; client = new HTTPClient(); client.init(url); try { client.asyncGET(ajaxHandler); } catch (e) { alert(e); } } function toggleClickFolder(event) { event = event || window.event; stopBubbling(event); toggleFolder(getFolderHash(this)); return false; } function initLinkFolders(listFolders) { var i = 0; for (i = 0; i < listFolders.length; i += 1) { if (listFolders[i].hasAttribute('data-toggle') && listFolders[i].hasAttribute('data-target')) { listFolders[i].onclick = toggleClickFolder; } } } function getListLinkFolders() { var i = 0, listFolders = [], listElements = document.getElementById('list-feeds'); if (listElements) { listElements = listElements.getElementsByTagName('a'); for (i = 0; i < listElements.length; i += 1) { listFolders.push(listElements[i]); } } return listFolders; } /** * MarkAs functions */ function toggleMarkAsLinkItem(itemHash) { var i, item = getItem(itemHash), listLinks; if (item !== null) { listLinks = item.getElementsByTagName('a'); for (i = 0; i < listLinks.length; i += 1) { if (hasClass(listLinks[i], 'item-mark-as')) { if (listLinks[i].href.indexOf('unread=') > -1) { listLinks[i].href = listLinks[i].href.replace('unread=','read='); listLinks[i].firstChild.innerHTML = intlRead; } else { listLinks[i].href = listLinks[i].href.replace('read=','unread='); listLinks[i].firstChild.innerHTML = intlUnread; } } } } } function getUnreadLabelItems(itemHash) { var i, listLinks, regex = new RegExp('read=' + itemHash.substr(0,6)), items = []; listLinks = getListLinkFolders(); for (i = 0; i < listLinks.length; i += 1) { if (regex.test(listLinks[i].href)) { items.push(listLinks[i].children[0]); } } return items; } function addToUnreadLabel(unreadLabelItem, value) { var unreadLabel = -1; if (unreadLabelItem !== null) { unreadLabel = parseInt(unreadLabelItem.innerHTML, 10) + value; unreadLabelItem.innerHTML = unreadLabel; } return unreadLabel; } function getUnreadLabel(folder) { var element = null; if (folder !== null) { element = folder.getElementsByClassName('label')[0]; } return element; } function markAsItem(itemHash) { var item, url, client, indexItem, i, unreadLabelItems, nb, feed, folder, addRead = 1; item = getItem(itemHash); if (item !== null) { unreadLabelItems = getUnreadLabelItems(itemHash); if (!hasClass(item, 'read')) { addRead = -1; } for (i = 0; i < unreadLabelItems.length; i += 1) { nb = addToUnreadLabel(unreadLabelItems[i], addRead); if (nb === 0) { feed = getLiParentByClassName(unreadLabelItems[i], 'feed'); removeClass(feed, 'has-unread'); if (autohide) { addClass(feed, 'autohide-feed'); } } folder = getLiParentByClassName(unreadLabelItems[i], 'folder'); nb = addToUnreadLabel(getUnreadLabel(folder), addRead); if (nb === 0 && autohide) { addClass(folder, 'autohide-folder'); } } addToUnreadLabel(getUnreadLabel(document.getElementById('all-subscriptions')), addRead); if (hasClass(item, 'read')) { url = '?unread=' + itemHash; removeClass(item, 'read'); toggleMarkAsLinkItem(itemHash); } else { url = '?read=' + itemHash; addClass(item, 'read'); toggleMarkAsLinkItem(itemHash); if (filter === 'unread') { url += '&currentHash=' + currentHash + '&page=' + currentPage + '&last=' + listItemsHash[listItemsHash.length - 1]; removeElement(item); indexItem = listItemsHash.indexOf(itemHash); listItemsHash.splice(listItemsHash.indexOf(itemHash), 1); if (listItemsHash.length <= byPage) { appendItem(listItemsHash[listItemsHash.length - 1]); } setCurrentItem(listItemsHash[indexItem]); } } } else { url = '?currentHash=' + currentHash + '&page=' + currentPage; } client = new HTTPClient(); client.init(url + '&ajax'); try { client.asyncGET(ajaxHandler); } catch (e) { alert(e); } } function markAsCurrentItem() { markAsItem(currentItemHash); } function markAsClickItem(event) { event = event || window.event; stopBubbling(event); markAsItem(getItemHash(this)); return false; } function toggleMarkAsStarredLinkItem(itemHash) { var i, item = getItem(itemHash), listLinks, url = ''; if (item !== null) { listLinks = item.getElementsByTagName('a'); for (i = 0; i < listLinks.length; i += 1) { if (hasClass(listLinks[i], 'item-starred')) { url = listLinks[i].href; if (listLinks[i].href.indexOf('unstar=') > -1) { listLinks[i].href = listLinks[i].href.replace('unstar=','star='); listLinks[i].firstChild.innerHTML = intlStar; } else { listLinks[i].href = listLinks[i].href.replace('star=','unstar='); listLinks[i].firstChild.innerHTML = intlUnstar; } } } } return url; } function markAsStarredCurrentItem() { markAsStarredItem(currentItemHash); } function markAsStarredItem(itemHash) { var url, client, indexItem; url = toggleMarkAsStarredLinkItem(itemHash); if (url.indexOf('unstar=') > -1 && stars) { removeElement(getItem(itemHash)); indexItem = listItemsHash.indexOf(itemHash); listItemsHash.splice(listItemsHash.indexOf(itemHash), 1); if (listItemsHash.length <= byPage) { appendItem(listItemsHash[listItemsHash.length - 1]); } setCurrentItem(listItemsHash[indexItem]); url += '&page=' + currentPage; } if (url !== '') { client = new HTTPClient(); client.init(url + '&ajax'); try { client.asyncGET(ajaxHandler); } catch (e) { alert(e); } } } function markAsStarredClickItem(event) { event = event || window.event; stopBubbling(event); markAsStarredItem(getItemHash(this)); return false; } function markAsRead(itemHash) { setNbUnread(currentUnread - 1); } function markAsUnread(itemHash) { setNbUnread(currentUnread + 1); } /** * Div item functions */ function loadDivItem(itemHash, noFocus) { var element, url, client, cacheItem; element = document.getElementById('item-div-'+itemHash); if (element.childNodes.length <= 1) { cacheItem = getCacheItem(itemHash); if (cacheItem !== null) { setDivItem(element, cacheItem); if(!noFocus) { setItemFocus(element); } removeCacheItem(itemHash); } else { url = '?'+(stars?'stars&':'')+'currentHash=' + currentHash + '&current=' + itemHash + '&ajax'; client = new HTTPClient(); client.init(url, noFocus); try { client.asyncGET(ajaxHandler); } catch (e) { alert(e); } } } } function toggleItem(itemHash) { var i, listElements, element, targetElement; if (view === 'expanded') { return; } if (currentItemHash != itemHash) { closeCurrentItem(); } // looking for ico + or - listElements = document.getElementById('item-toggle-' + itemHash); listElements = listElements.getElementsByTagName('span'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'item-toggle-open')) { removeClass(listElements[i], 'item-toggle-open'); addClass(listElements[i], 'item-toggle-close'); } else if (hasClass(listElements[i], 'item-toggle-close')) { removeClass(listElements[i], 'item-toggle-close'); addClass(listElements[i], 'item-toggle-open'); } } element = document.getElementById('item-toggle-'+itemHash); targetElement = document.getElementById( element.getAttribute('data-target').substring(1) ); if (element.href.indexOf('&open') > -1) { element.href = element.href.replace('&open',''); addClass(targetElement, 'well'); setCurrentItem(itemHash); loadDivItem(itemHash); } else { element.href = element.href + '&open'; removeClass(targetElement, 'well'); } } function toggleCurrentItem() { toggleItem(currentItemHash); collapseElement(document.getElementById('item-toggle-' + currentItemHash)); } function toggleClickItem(event) { event = event || window.event; stopBubbling(event); toggleItem(getItemHash(this)); return false; } /** * Item management functions */ function getItem(itemHash) { return document.getElementById('item-' + itemHash); } function getTitleItem(itemHash) { var i = 0, element = document.getElementById('item-div-'+itemHash), listElements = element.getElementsByTagName('a'), title = ''; for (i = 0; title === '' && i < listElements.length; i += 1) { if (hasClass(listElements[i], 'item-link')) { title = listElements[i].innerHTML; } } return title; } function getUrlItem(itemHash) { var i = 0, element = document.getElementById('item-'+itemHash), listElements = element.getElementsByTagName('a'), url = ''; for (i = 0; url === '' && i < listElements.length; i += 1) { if (hasClass(listElements[i], 'item-link')) { url = listElements[i].href; } } return url; } function getViaItem(itemHash) { var i = 0, element = document.getElementById('item-div-'+itemHash), listElements = element.getElementsByTagName('a'), via = ''; for (i = 0; via === '' && i < listElements.length; i += 1) { if (hasClass(listElements[i], 'item-via')) { via = listElements[i].href; } } return via; } function getLiItem(element) { var item = null; while (item === null && element !== null) { if (element.tagName === 'LI' && element.id.indexOf('item-') === 0) { item = element; } element = element.parentNode; } return item; } function getItemHash(element) { var item = getLiItem(element); if (item !== null) { return item.id.replace('item-',''); } return null; } function getCacheItem(itemHash) { if (typeof cache['item-' + itemHash] !== 'undefined') { return cache['item-' + itemHash]; } return null; } function removeCacheItem(itemHash) { if (typeof cache['item-' + itemHash] !== 'undefined') { delete cache['item-' + itemHash]; } } function isCurrentUnread() { var item = getItem(currentItemHash); if (hasClass(item, 'read')) { return false; } return true; } function setDivItem(div, item) { var markAs = intlRead, starred = intlStar, target = ' target="_blank"', linkMarkAs = 'read', linkStarred = 'star'; if (item['read'] == 1) { markAs = intlUnread; linkMarkAs = 'unread'; } if (item['starred'] == 1) { starred = intlUnstar; linkStarred = 'unstar'; } if (!blank) { target = ''; } div.innerHTML = '<div class="item-title">' + '<a class="item-shaarli" href="' + '?'+(stars?'stars&':'')+'currentHash=' + currentHash + '&shaarli=' + item['itemHash'] + '"><span class="label">' + intlShare + '</span></a> ' + (stars?'': '<a class="item-mark-as" href="' + '?'+(stars?'stars&':'')+'currentHash=' + currentHash + '&' + linkMarkAs + '=' + item['itemHash'] + '"><span class="label item-label-mark-as">' + markAs + '</span></a> ') + '<a class="item-starred" href="' + '?'+(stars?'stars&':'')+'currentHash=' + currentHash + '&' + linkStarred + '=' + item['itemHash'] + '"><span class="label item-label-starred">' + starred + '</span></a> ' + '<a' + target + ' class="item-link" href="' + item['link'] + '">' + item['title'] + '</a>' + '</div>' + '<div class="clear"></div>' + '<div class="item-info-end item-info-time">' + item['time']['expanded'] + '</div>' + '<div class="item-info-end item-info-authors">' + intlFrom + ' <a class="item-via" href="' + item['via'] + '">' + item['author'] + '</a> ' + '<a class="item-xml" href="' + item['xmlUrl'] + '">' + '<span class="ico">' + '<span class="ico-feed-dot"></span>' + '<span class="ico-feed-circle-1"></span>' + '<span class="ico-feed-circle-2"></span>'+ '</span>' + '</a>' + '</div>' + '<div class="clear"></div>' + '<div class="item-content"><article>' + item['content'] + '</article></div>' + '<div class="clear"></div>' + '<div class="item-info-end">' + '<a class="item-top" href="#status"><span class="label label-expanded">' + intlTop + '</span></a> ' + '<a class="item-shaarli" href="' + '?'+(stars?'stars&':'')+'currentHash=' + currentHash + '&shaarli=' + item['itemHash'] + '"><span class="label label-expanded">' + intlShare + '</span></a> ' + (stars?'': '<a class="item-mark-as" href="' + '?'+(stars?'stars&':'')+'currentHash=' + currentHash + '&' + linkMarkAs + '=' + item['itemHash'] + '"><span class="label item-label-mark-as label-expanded">' + markAs + '</span></a> ') + '<a class="item-starred" href="' + '?'+(stars?'stars&':'')+'currentHash=' + currentHash + '&' + linkStarred + '=' + item['itemHash'] + '"><span class="label label-expanded">' + starred + '</span></a>' + (view=='list'? '<a id="item-toggle-'+ item['itemHash'] +'" class="item-toggle item-toggle-plus" href="' + '?'+(stars?'stars&':'')+'currentHash=' + currentHash + '&current=' + item['itemHash'] +'&open" data-toggle="collapse" data-target="#item-div-'+ item['itemHash'] + '"> ' + '<span class="ico ico-toggle-item">' + '<span class="ico-b-disc"></span>' + '<span class="ico-w-line-h"></span>' + '</span>' + '</a>':'') + '</div>' + '<div class="clear"></div>'; initLinkItems(div.getElementsByTagName('a')); initCollapse(div.getElementsByTagName('a')); anonymize(div); } function setLiItem(li, item) { var markAs = intlRead, target = ' target="_blank"'; if (item['read'] == 1) { markAs = intlUnread; } if (!blank) { target = ''; } li.innerHTML = '<a id="item-toggle-'+ item['itemHash'] +'" class="item-toggle item-toggle-plus" href="' + '?'+(stars?'stars&':'')+'currentHash=' + currentHash + '&current=' + item['itemHash'] +'&open" data-toggle="collapse" data-target="#item-div-'+ item['itemHash'] + '"> ' + '<span class="ico ico-toggle-item">' + '<span class="ico-b-disc"></span>' + '<span class="ico-w-line-h"></span>' + '<span class="ico-w-line-v item-toggle-close"></span>' + '</span>' + item['time']['list'] + '</a>' + '<dl class="dl-horizontal item">' + '<dt class="item-feed">' + (addFavicon? '<span class="item-favicon">' + '<img src="' + item['favicon'] + '" height="16" width="16" title="favicon" alt="favicon"/>' + '</span>':'' ) + '<span class="item-author">' + '<a class="item-feed" href="?'+(stars?'stars&':'')+'currentHash=' + item['itemHash'].substring(0, 6) + '">' + item['author'] + '</a>' + '</span>' + '</dt>' + '<dd class="item-info">' + '<span class="item-title">' + (stars?'':'<a class="item-mark-as" href="' + '?'+(stars?'stars&':'')+'currentHash=' + currentHash + '&' + markAs + '=' + item['itemHash'] + '"><span class="label">' + markAs + '</span></a> ') + '<a' + target + ' class="item-link" href="' + item['link'] + '">' + item['title'] + '</a> ' + '</span>' + '<span class="item-description">' + '<a class="item-toggle muted" href="' + '?'+(stars?'stars&':'')+'currentHash=' + currentHash + '&current=' + item['itemHash'] + '&open" data-toggle="collapse" data-target="#item-div-'+ item['itemHash'] + '">' + item['description'] + '</a> ' + '</span>' + '</dd>' + '</dl>' + '<div class="clear"></div>'; initCollapse(li.getElementsByTagName('a')); initLinkItems(li.getElementsByTagName('a')); anonymize(li); } function createLiItem(item) { var li = document.createElement('li'), div = document.createElement('div'); div.id = 'item-div-'+item['itemHash']; div.className= 'item collapse'+(view === 'expanded' ? ' in well' : ''); li.id = 'item-'+item['itemHash']; if (view === 'list') { li.className = 'item-list'; setLiItem(li, item); } else { li.className = 'item-expanded'; setDivItem(div, item); } li.className += (item['read'] === 1)?' read':''; li.appendChild(div); return li; } /** * List items management functions */ function getListItems() { return document.getElementById('list-items'); } function updateListItems(itemsList) { var i; for (i = 0; i < itemsList.length; i++) { if (listItemsHash.indexOf(itemsList[i]['itemHash']) === -1 && listItemsHash.length <= byPage) { cache['item-' + itemsList[i]['itemHash']] = itemsList[i]; listItemsHash.push(itemsList[i]['itemHash']); if (listItemsHash.length <= byPage) { appendItem(itemsList[i]['itemHash']); } } } } function appendItem(itemHash) { var listItems = getListItems(), item = getCacheItem(itemHash), li; if (item !== null) { li = createLiItem(item); listItems.appendChild(li); removeCacheItem(itemHash); } } function getListLinkItems() { var i = 0, listItems = [], listElements = document.getElementById('list-items'); listElements = listElements.getElementsByTagName('a'); for (i = 0; i < listElements.length; i += 1) { listItems.push(listElements[i]); } return listItems; } function initListItemsHash() { var i, listElements = document.getElementById('list-items'); listElements = listElements.getElementsByTagName('li'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'item-list') || hasClass(listElements[i], 'item-expanded')) { if (hasClass(listElements[i], 'current')) { currentItemHash = getItemHash(listElements[i]); } listItemsHash.push(listElements[i].id.replace('item-','')); } } } function initLinkItems(listItems) { var i = 0; for (i = 0; i < listItems.length; i += 1) { if (hasClass(listItems[i], 'item-toggle')) { listItems[i].onclick = toggleClickItem; } if (hasClass(listItems[i], 'item-mark-as')) { listItems[i].onclick = markAsClickItem; } if (hasClass(listItems[i], 'item-starred')) { listItems[i].onclick = markAsStarredClickItem; } if (hasClass(listItems[i], 'item-shaarli')) { listItems[i].onclick = shaarliClickItem; } } } function initListItems() { var url, client; url = '?currentHash=' + currentHash + '&page=' + currentPage + '&last=' + listItemsHash[listItemsHash.length -1] + '&ajax' + (stars?'&stars':''); client = new HTTPClient(); client.init(url); try { client.asyncGET(ajaxHandler); } catch (e) { alert(e); } } function preloadItems() { // Pre-fetch items from top to bottom for(var i = 0, len = listItemsHash.length; i < len; ++i) { loadDivItem(listItemsHash[i], true); } } /** * Update */ function setStatus(text) { if (text === '') { document.getElementById('status').innerHTML = status; } else { document.getElementById('status').innerHTML = text; } } function getTimeMin() { return Math.round((new Date().getTime()) / 1000 / 60); } function updateFeed(feedHashIndex) { var i = 0, url, client, feedHash = ''; if (feedHashIndex !== '') { setStatus('updating ' + listUpdateFeeds[feedHashIndex][1]); feedHash = listUpdateFeeds[feedHashIndex][0]; listUpdateFeeds[feedHashIndex][2] = getTimeMin(); } url = '?update'+(feedHash === ''?'':'='+feedHash)+'&ajax'; client = new HTTPClient(); client.init(url); try { client.asyncGET(ajaxHandler); } catch (e) { alert(e); } } function updateNextFeed() { var i = 0, nextTimeUpdate = 0, currentMin, diff, minDiff = -1, feedToUpdateIndex = '', minFeedToUpdateIndex = ''; if (listUpdateFeeds.length !== 0) { currentMin = getTimeMin(); for (i = 0; feedToUpdateIndex === '' && i < listUpdateFeeds.length; i++) { diff = currentMin - listUpdateFeeds[i][2]; if (diff >= listUpdateFeeds[i][3]) { //need update feedToUpdateIndex = i; } else { if (minDiff === -1 || diff < minDiff) { minDiff = diff; minFeedToUpdateIndex = i; } } } if (feedToUpdateIndex === '') { feedToUpdateIndex = minFeedToUpdateIndex; } updateFeed(feedToUpdateIndex); } else { updateFeed(''); } } function updateTimeout() { var i = 0, nextTimeUpdate = 0, currentMin, diff, minDiff = -1, feedToUpdateIndex = ''; if (listUpdateFeeds.length !== 0) { currentMin = getTimeMin(); for (i = 0; minDiff !== 0 && i < listUpdateFeeds.length; i++) { diff = currentMin - listUpdateFeeds[i][2]; if (diff >= listUpdateFeeds[i][3]) { //need update minDiff = 0; } else { if (minDiff === -1 || (listUpdateFeeds[i][3] - diff) < minDiff) { minDiff = listUpdateFeeds[i][3] - diff; } } } window.setTimeout(updateNextFeed, minDiff * 1000 * 60 + 200); } } function updateNewItems(result) { var i = 0, list, currentMin, folder, feed, unreadLabelItems, nbItems; setStatus(''); if (result !== false) { if (result['feeds']) { // init list of feeds information for update listUpdateFeeds = result['feeds']; currentMin = getTimeMin(); for (i = 0; i < listUpdateFeeds.length; i++) { listUpdateFeeds[i][2] = currentMin - listUpdateFeeds[i][2]; } } if (result.newItems && result.newItems.length > 0) { nbItems = result.newItems.length; currentNbItems += nbItems; setNbUnread(currentUnread + nbItems); addToUnreadLabel(getUnreadLabel(document.getElementById('all-subscriptions')), nbItems); unreadLabelItems = getUnreadLabelItems(result.newItems[0].substr(0,6)); for (i = 0; i < unreadLabelItems.length; i += 1) { feed = getLiParentByClassName(unreadLabelItems[i], 'feed'); folder = getLiParentByClassName(feed, 'folder'); addClass(feed, 'has-unread'); if (autohide) { removeClass(feed, 'autohide-feed'); removeClass(folder, 'autohide-folder'); } addToUnreadLabel(getUnreadLabel(feed), nbItems); addToUnreadLabel(getUnreadLabel(folder), nbItems); } } updateTimeout(); } } function initUpdate() { window.setTimeout(updateNextFeed, 1000); } /** * Navigation */ function setItemFocus(item) { if(autofocus) { // First, let the browser do some rendering // Indeed, the div might not be visible yet, so there is no scroll setTimeout(function() { // Dummy implementation var container = document.getElementById('main-container'), scrollPos = container.scrollTop, itemPos = item.offsetTop, temp = item; while(temp.offsetParent != document.body) { temp = temp.offsetParent; itemPos += temp.offsetTop; } var current = itemPos - scrollPos; // Scroll only if necessary // current < 0: Happens when asking for previous item and displayed item is filling the screen // Or check if item bottom is outside screen if(current < 0 || current + item.offsetHeight > container.clientHeight) { container.scrollTop = itemPos; } }, 0); window.location.hash = '#item-' + currentItemHash; } } function previousClickPage(event) { event = event || window.event; stopBubbling(event); previousPage(); return false; } function nextClickPage(event) { event = event || window.event; stopBubbling(event); nextPage(); return false; } function nextPage() { currentPage = currentPage + 1; if (currentPage > Math.ceil(currentNbItems / byPage)) { currentPage = Math.ceil(currentNbItems / byPage); } if (listItemsHash.length === 0) { currentPage = 1; } listItemsHash = []; initListItems(); removeChildren(getListItems()); } function previousPage() { currentPage = currentPage - 1; if (currentPage < 1) { currentPage = 1; } listItemsHash = []; initListItems(); removeChildren(getListItems()); } function previousClickItem(event) { event = event || window.event; stopBubbling(event); previousItem(); return false; } function nextClickItem(event) { event = event || window.event; stopBubbling(event); nextItem(); return false; } function nextItem() { var nextItemIndex = listItemsHash.indexOf(currentItemHash) + 1, nextCurrentItemHash; closeCurrentItem(); if (autoreadItem && isCurrentUnread()) { markAsCurrentItem(); if (filter == 'unread') { nextItemIndex -= 1; } } if (nextItemIndex < 0) { nextItemIndex = 0; } if (nextItemIndex < listItemsHash.length) { nextCurrentItemHash = listItemsHash[nextItemIndex]; } if (nextItemIndex >= byPage) { nextPage(); } else { setCurrentItem(nextCurrentItemHash); } } function previousItem() { var previousItemIndex = listItemsHash.indexOf(currentItemHash) - 1, previousCurrentItemHash; if (previousItemIndex < listItemsHash.length && previousItemIndex >= 0) { previousCurrentItemHash = listItemsHash[previousItemIndex]; } closeCurrentItem(); if (previousItemIndex < 0) { previousPage(); } else { setCurrentItem(previousCurrentItemHash); } } function closeCurrentItem() { var element = document.getElementById('item-toggle-' + currentItemHash); if (element && view === 'list') { var targetElement = document.getElementById( element.getAttribute('data-target').substring(1) ); if (element.href.indexOf('&open') < 0) { element.href = element.href + '&open'; removeClass(targetElement, 'well'); collapseElement(element); } var i = 0, listElements = element.getElementsByTagName('span'); // looking for ico + or - for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'item-toggle-open')) { removeClass(listElements[i], 'item-toggle-open'); addClass(listElements[i], 'item-toggle-close'); } } } } function setCurrentItem(itemHash) { var currentItemIndex; if (itemHash !== currentItemHash) { removeClass(document.getElementById('item-'+currentItemHash), 'current'); removeClass(document.getElementById('item-div-'+currentItemHash), 'current'); if (typeof itemHash !== 'undefined') { currentItemHash = itemHash; } currentItemIndex = listItemsHash.indexOf(currentItemHash); if (currentItemIndex === -1) { if (listItemsHash.length > 0) { currentItemHash = listItemsHash[0]; } else { currentItemHash = ''; } } else { if (currentItemIndex >= byPage) { currentItemHash = listItemsHash[byPage - 1]; } } if (currentItemHash !== '') { var item = document.getElementById('item-'+currentItemHash), itemDiv = document.getElementById('item-div-'+currentItemHash); addClass(item, 'current'); addClass(itemDiv, 'current'); setItemFocus(itemDiv); updateItemButton(); } } updatePageButton(); } function openCurrentItem(blank) { var url; url = getUrlItem(currentItemHash); if (blank) { window.location.href = url; } else { window.open(url); } } // http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.js (swipe) function checkMove(e) { // More than this horizontal displacement, and we will suppress scrolling. var scrollSupressionThreshold = 10, // More time than this, and it isn't a swipe. durationThreshold = 500, // Swipe horizontal displacement must be more than this. horizontalDistanceThreshold = 30, // Swipe vertical displacement must be less than this. verticalDistanceThreshold = 75; if (e.targetTouches.length == 1) { var touch = e.targetTouches[0], start = { time: ( new Date() ).getTime(), coords: [ touch.pageX, touch.pageY ] }, stop; var moveHandler = function ( e ) { if ( !start ) { return; } if (e.targetTouches.length == 1) { var touch = e.targetTouches[0]; stop = { time: ( new Date() ).getTime(), coords: [ touch.pageX, touch.pageY ] }; } }; if (swipe) { addEvent(window, 'touchmove', moveHandler); addEvent(window, 'touchend', function (e) { removeEvent(window, 'touchmove', moveHandler); if ( start && stop ) { if ( stop.time - start.time < durationThreshold && Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > horizontalDistanceThreshold && Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < verticalDistanceThreshold ) { if ( start.coords[0] > stop.coords[ 0 ] ) { nextItem(); } else { previousItem(); } } start = stop = undefined; } }); } } } function checkKey(e) { var code; if (!e) e = window.event; if (e.keyCode) code = e.keyCode; else if (e.which) code = e.which; if (!e.ctrlKey && !e.altKey) { switch(code) { case 32: // 'space' toggleCurrentItem(); break; case 65: // 'A' if (window.confirm('Mark all current as read ?')) { window.location.href = '?read=' + currentHash; } break; case 67: // 'C' window.location.href = '?config'; break; case 69: // 'E' window.location.href = (currentHash===''?'?edit':'?edit='+currentHash); break; case 70: // 'F' if (listFeeds =='show') { window.location.href = (currentHash===''?'?':'?currentHash='+currentHash+'&')+'listFeeds=hide'; } else { window.location.href = (currentHash===''?'?':'?currentHash='+currentHash+'&')+'listFeeds=show'; } break; case 72: // 'H' window.location.href = document.getElementById('nav-home').href; break; case 74: // 'J' nextItem(); toggleCurrentItem(); break; case 75: // 'K' previousItem(); toggleCurrentItem(); break; case 77: // 'M' if (e.shiftKey) { markAsCurrentItem(); toggleCurrentItem(); } else { markAsCurrentItem(); } break; case 39: // right arrow case 78: // 'N' if (e.shiftKey) { nextPage(); } else { nextItem(); } break; case 79: // 'O' if (e.shiftKey) { openCurrentItem(true); } else { openCurrentItem(false); } break; case 37: // left arrow case 80 : // 'P' if (e.shiftKey) { previousPage(); } else { previousItem(); } break; case 82: // 'R' window.location.reload(true); break; case 83: // 'S' shaarliCurrentItem(); break; case 84: // 'T' toggleCurrentItem(); break; case 85: // 'U' window.location.href = (currentHash===''?'?update':'?currentHash=' + currentHash + '&update='+currentHash); break; case 86: // 'V' if (view == 'list') { window.location.href = (currentHash===''?'?':'?currentHash='+currentHash+'&')+'view=expanded'; } else { window.location.href = (currentHash===''?'?':'?currentHash='+currentHash+'&')+'view=list'; } break; case 90: // 'z' for (var i=0;i<listItemsHash.length;i++){ if (!hasClass(getItem(listItemsHash[i]), 'read')){ window.open(getUrlItem(currentItemHash),'_blank'); markAsCurrentItem(); } nextItem(); } break; case 170: // '*' markAsStarredCurrentItem(); break; case 112: // 'F1' case 188: // '?' case 191: // '?' window.location.href = '?help'; break; default: break; } } // e.ctrlKey e.altKey e.shiftKey } function initPageButton() { var i = 0, paging, listElements; paging = document.getElementById('paging-up'); if (paging) { listElements = paging.getElementsByTagName('a'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'previous-page')) { listElements[i].onclick = previousClickPage; } if (hasClass(listElements[i], 'next-page')) { listElements[i].onclick = nextClickPage; } } } paging = document.getElementById('paging-down'); if (paging) { listElements = paging.getElementsByTagName('a'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'previous-page')) { listElements[i].onclick = previousClickPage; } if (hasClass(listElements[i], 'next-page')) { listElements[i].onclick = nextClickPage; } } } } function updatePageButton() { var i = 0, paging, listElements, maxPage; if (filter == 'unread') { currentNbItems = currentUnread; } if (currentNbItems < byPage) { maxPage = 1; } else { maxPage = Math.ceil(currentNbItems / byPage); } paging = document.getElementById('paging-up'); if (paging) { listElements = paging.getElementsByTagName('a'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'previous-page')) { listElements[i].href = '?currentHash=' + currentHash + '&previousPage=' + currentPage; if (currentPage === 1) { if (!hasClass(listElements[i], 'disabled')) { addClass(listElements[i], 'disabled'); } } else { if (hasClass(listElements[i], 'disabled')) { removeClass(listElements[i], 'disabled'); } } } if (hasClass(listElements[i], 'next-page')) { listElements[i].href = '?currentHash=' + currentHash + '&nextPage=' + currentPage; if (currentPage === maxPage) { if (!hasClass(listElements[i], 'disabled')) { addClass(listElements[i], 'disabled'); } } else { if (hasClass(listElements[i], 'disabled')) { removeClass(listElements[i], 'disabled'); } } } } listElements = paging.getElementsByTagName('button'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'current-max-page')) { listElements[i].innerHTML = currentPage + ' / ' + maxPage; } } } paging = document.getElementById('paging-down'); if (paging) { listElements = paging.getElementsByTagName('a'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'previous-page')) { listElements[i].href = '?currentHash=' + currentHash + '&previousPage=' + currentPage; if (currentPage === 1) { if (!hasClass(listElements[i], 'disabled')) { addClass(listElements[i], 'disabled'); } } else { if (hasClass(listElements[i], 'disabled')) { removeClass(listElements[i], 'disabled'); } } } if (hasClass(listElements[i], 'next-page')) { listElements[i].href = '?currentHash=' + currentHash + '&nextPage=' + currentPage; if (currentPage === maxPage) { if (!hasClass(listElements[i], 'disabled')) { addClass(listElements[i], 'disabled'); } } else { if (hasClass(listElements[i], 'disabled')) { removeClass(listElements[i], 'disabled'); } } } } listElements = paging.getElementsByTagName('button'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'current-max-page')) { listElements[i].innerHTML = currentPage + ' / ' + maxPage; } } } } function initItemButton() { var i = 0, paging, listElements; paging = document.getElementById('paging-up'); if (paging) { listElements = paging.getElementsByTagName('a'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'previous-item')) { listElements[i].onclick = previousClickItem; } if (hasClass(listElements[i], 'next-item')) { listElements[i].onclick = nextClickItem; } } } paging = document.getElementById('paging-down'); if (paging) { listElements = paging.getElementsByTagName('a'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'previous-item')) { listElements[i].onclick = previousClickItem; } if (hasClass(listElements[i], 'next-item')) { listElements[i].onclick = nextClickItem; } } } } function updateItemButton() { var i = 0, paging, listElements; paging = document.getElementById('paging-up'); if (paging) { listElements = paging.getElementsByTagName('a'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'previous-item')) { listElements[i].href = '?currentHash=' + currentHash + '&previous=' + currentItemHash; } if (hasClass(listElements[i], 'next-item')) { listElements[i].href = '?currentHash=' + currentHash + '&next=' + currentItemHash; } } } paging = document.getElementById('paging-down'); if (paging) { listElements = paging.getElementsByTagName('a'); for (i = 0; i < listElements.length; i += 1) { if (hasClass(listElements[i], 'previous-item')) { listElements[i].href = '?currentHash=' + currentHash + '&previous=' + currentItemHash; } if (hasClass(listElements[i], 'next-item')) { listElements[i].href = '?currentHash=' + currentHash + '&next=' + currentItemHash; } } } } /** * init KrISS feed javascript */ function initUnread() { var element = document.getElementById((stars?'nb-starred':'nb-unread')); currentUnread = parseInt(element.innerHTML, 10); title = document.title; setNbUnread(currentUnread); } function setNbUnread(nb) { var element = document.getElementById((stars?'nb-starred':'nb-unread')); if (nb < 0) { nb = 0; } currentUnread = nb; element.innerHTML = currentUnread; document.title = title + ' (' + currentUnread + ')'; } function initOptions() { var elementIndex = document.getElementById('index'); if (elementIndex.hasAttribute('data-view')) { view = elementIndex.getAttribute('data-view'); } if (elementIndex.hasAttribute('data-list-feeds')) { listFeeds = elementIndex.getAttribute('data-list-feeds'); } if (elementIndex.hasAttribute('data-filter')) { filter = elementIndex.getAttribute('data-filter'); } if (elementIndex.hasAttribute('data-order')) { order = elementIndex.getAttribute('data-order'); } if (elementIndex.hasAttribute('data-autoread-item')) { autoreadItem = parseInt(elementIndex.getAttribute('data-autoread-item'), 10); autoreadItem = (autoreadItem === 1)?true:false; } if (elementIndex.hasAttribute('data-autoread-page')) { autoreadPage = parseInt(elementIndex.getAttribute('data-autoread-page'), 10); autoreadPage = (autoreadPage === 1)?true:false; } if (elementIndex.hasAttribute('data-autohide')) { autohide = parseInt(elementIndex.getAttribute('data-autohide'), 10); autohide = (autohide === 1)?true:false; } if (elementIndex.hasAttribute('data-autofocus')) { autofocus = parseInt(elementIndex.getAttribute('data-autofocus'), 10); autofocus = (autofocus === 1)?true:false; } if (elementIndex.hasAttribute('data-autoupdate')) { autoupdate = parseInt(elementIndex.getAttribute('data-autoupdate'), 10); autoupdate = (autoupdate === 1)?true:false; } if (elementIndex.hasAttribute('data-by-page')) { byPage = parseInt(elementIndex.getAttribute('data-by-page'), 10); } if (elementIndex.hasAttribute('data-shaarli')) { shaarli = elementIndex.getAttribute('data-shaarli'); } if (elementIndex.hasAttribute('data-redirector')) { redirector = elementIndex.getAttribute('data-redirector'); } if (elementIndex.hasAttribute('data-current-hash')) { currentHash = elementIndex.getAttribute('data-current-hash'); } if (elementIndex.hasAttribute('data-current-page')) { currentPage = parseInt(elementIndex.getAttribute('data-current-page'), 10); } if (elementIndex.hasAttribute('data-nb-items')) { currentNbItems = parseInt(elementIndex.getAttribute('data-nb-items'), 10); } if (elementIndex.hasAttribute('data-add-favicon')) { addFavicon = parseInt(elementIndex.getAttribute('data-add-favicon'), 10); addFavicon = (addFavicon === 1)?true:false; } if (elementIndex.hasAttribute('data-preload')) { preload = parseInt(elementIndex.getAttribute('data-preload'), 10); preload = (preload === 1)?true:false; } if (elementIndex.hasAttribute('data-stars')) { stars = parseInt(elementIndex.getAttribute('data-stars'), 10); stars = (stars === 1)?true:false; } if (elementIndex.hasAttribute('data-blank')) { blank = parseInt(elementIndex.getAttribute('data-blank'), 10); blank = (blank === 1)?true:false; } if (elementIndex.hasAttribute('data-is-logged')) { isLogged = parseInt(elementIndex.getAttribute('data-is-logged'), 10); isLogged = (isLogged === 1)?true:false; } if (elementIndex.hasAttribute('data-intl-top')) { intlTop = elementIndex.getAttribute('data-intl-top'); } if (elementIndex.hasAttribute('data-intl-share')) { intlShare = elementIndex.getAttribute('data-intl-share'); } if (elementIndex.hasAttribute('data-intl-read')) { intlRead = elementIndex.getAttribute('data-intl-read'); } if (elementIndex.hasAttribute('data-intl-unread')) { intlUnread = elementIndex.getAttribute('data-intl-unread'); } if (elementIndex.hasAttribute('data-intl-star')) { intlStar = elementIndex.getAttribute('data-intl-star'); } if (elementIndex.hasAttribute('data-intl-unstar')) { intlUnstar = elementIndex.getAttribute('data-intl-unstar'); } if (elementIndex.hasAttribute('data-intl-from')) { intlFrom = elementIndex.getAttribute('data-intl-from'); } if (elementIndex.hasAttribute('data-swipe')) { swipe = parseInt(elementIndex.getAttribute('data-swipe'), 10); swipe = (swipe === 1)?true:false; } status = document.getElementById('status').innerHTML; } function initKF() { var listItems, listLinkFolders = [], listLinkItems = []; initOptions(); listLinkFolders = getListLinkFolders(); listLinkItems = getListLinkItems(); if (!window.jQuery || (window.jQuery && !window.jQuery().collapse)) { document.getElementById('menu-toggle'). onclick = collapseClick; initCollapse(listLinkFolders); initCollapse(listLinkItems); } initLinkFolders(listLinkFolders); initLinkItems(listLinkItems); initListItemsHash(); initListItems(); initUnread(); initItemButton(); initPageButton(); initAnonyme(); addEvent(window, 'keydown', checkKey); addEvent(window, 'touchstart', checkMove); if (autoupdate && !stars) { initUpdate(); } listItems = getListItems(); listItems.focus(); } //http://scottandrew.com/weblog/articles/cbs-events function addEvent(obj, evType, fn, useCapture) { if (obj.addEventListener) { obj.addEventListener(evType, fn, useCapture); } else { if (obj.attachEvent) { obj.attachEvent('on' + evType, fn); } else { window.alert('Handler could not be attached'); } } } function removeEvent(obj, evType, fn, useCapture) { if (obj.removeEventListener) { obj.removeEventListener(evType, fn, useCapture); } else if (obj.detachEvent) { obj.detachEvent("on"+evType, fn); } else { alert("Handler could not be removed"); } } // when document is loaded init KrISS feed if (document.getElementById && document.createTextNode) { addEvent(window, 'load', initKF); } window.checkKey = checkKey; window.removeEvent = removeEvent; window.addEvent = addEvent; })(); // unread count for favicon part if(typeof GM_getValue == 'undefined') { GM_getValue = function(name, fallback) { return fallback; }; } // Register GM Commands and Methods if(typeof GM_registerMenuCommand !== 'undefined') { var setOriginalFavicon = function(val) { GM_setValue('originalFavicon', val); }; GM_registerMenuCommand( 'GReader Favicon Alerts > Use Current Favicon', function() { setOriginalFavicon(false); } ); GM_registerMenuCommand( 'GReader Favicon Alerts > Use Original Favicon', function() { setOriginalFavicon(true); } ); } (function FaviconAlerts() { var self = this; this.construct = function() { this.head = document.getElementsByTagName('head')[0]; this.pixelMaps = {numbers: {0:[[1,1,1],[1,0,1],[1,0,1],[1,0,1],[1,1,1]],1:[[0,1,0],[1,1,0],[0,1,0],[0,1,0],[1,1,1]],2:[[1,1,1],[0,0,1],[1,1,1],[1,0,0],[1,1,1]],3:[[1,1,1],[0,0,1],[0,1,1],[0,0,1],[1,1,1]],4:[[0,0,1],[0,1,1],[1,0,1],[1,1,1],[0,0,1]],5:[[1,1,1],[1,0,0],[1,1,1],[0,0,1],[1,1,1]],6:[[0,1,1],[1,0,0],[1,1,1],[1,0,1],[1,1,1]],7:[[1,1,1],[0,0,1],[0,0,1],[0,1,0],[0,1,0]],8:[[1,1,1],[1,0,1],[1,1,1],[1,0,1],[1,1,1]],9:[[1,1,1],[1,0,1],[1,1,1],[0,0,1],[1,1,0]],'+':[[0,0,0],[0,1,0],[1,1,1],[0,1,0],[0,0,0]],'k':[[1,0,1],[1,1,0],[1,1,0],[1,0,1],[1,0,1]]}}; this.timer = setInterval(this.poll, 500); this.poll(); return true; }; this.drawUnreadCount = function(unread, callback) { if(!self.textedCanvas) { self.textedCanvas = []; } if(!self.textedCanvas[unread]) { self.getUnreadCanvas(function(iconCanvas) { var textedCanvas = document.createElement('canvas'); textedCanvas.height = textedCanvas.width = iconCanvas.width; var ctx = textedCanvas.getContext('2d'); ctx.drawImage(iconCanvas, 0, 0); ctx.fillStyle = '#b7bfc9'; ctx.strokeStyle = '#7792ba'; ctx.strokeWidth = 1; var count = unread.length; if(count > 4) { unread = '1k+'; count = unread.length; } var bgHeight = self.pixelMaps.numbers[0].length; var bgWidth = 0; var padding = count < 4 ? 1 : 0; var topMargin = 0; for(var index = 0; index < count; index++) { bgWidth += self.pixelMaps.numbers[unread[index]][0].length; if(index < count-1) { bgWidth += padding; } } bgWidth = bgWidth > textedCanvas.width-4 ? textedCanvas.width-4 : bgWidth; ctx.fillRect(textedCanvas.width-bgWidth-4,topMargin,bgWidth+4,bgHeight+4); var digit; var digitsWidth = bgWidth; for(index = 0; index < count; index++) { digit = unread[index]; if (self.pixelMaps.numbers[digit]) { var map = self.pixelMaps.numbers[digit]; var height = map.length; var width = map[0].length; ctx.fillStyle = '#2c3323'; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { if(map[y][x]) { ctx.fillRect(14- digitsWidth + x, y+topMargin+2, 1, 1); } } } digitsWidth -= width + padding; } } ctx.strokeRect(textedCanvas.width-bgWidth-3.5,topMargin+0.5,bgWidth+3,bgHeight+3); self.textedCanvas[unread] = textedCanvas; callback(self.textedCanvas[unread]); }); callback(self.textedCanvas[unread]); } }; this.getIcon = function(callback) { self.getUnreadCanvas(function(canvas) { callback(canvas.toDataURL('image/png')); }); }; this.getIconSrc = function() { var links = document.getElementsByTagName('link'); for (var i = 0; i < links.length; i++) { if (links[i].rel === 'icon') { return links[i].href; } } return false; }; this.getUnreadCanvas = function(callback) { if(!self.unreadCanvas) { self.unreadCanvas = document.createElement('canvas'); self.unreadCanvas.height = self.unreadCanvas.width = 16; var ctx = self.unreadCanvas.getContext('2d'); var img = new Image(); img.addEventListener('load', function() { ctx.drawImage(img, 0, 0); callback(self.unreadCanvas); }, true); // if(GM_getValue('originalFavicon', false)) { // img.src = self.icons.original; // } else { // img.src = self.icons.current; // } // img.src = 'inc/favicon.ico'; img.src = self.getIconSrc(); } else { callback(self.unreadCanvas); } }; this.getUnreadCount = function() { matches = self.getSearchText().match(/\((.*)\)/); return matches ? matches[1] : false; }; this.getUnreadCountIcon = function(callback) { var unread = self.getUnreadCount(); self.drawUnreadCount(unread, function(icon) { if(icon) { callback(icon.toDataURL('image/png')); } }); }; this.getSearchText = function() { var elt = document.getElementById('nb-unread'); if (!elt) { elt = document.getElementById('nb-starred'); } if (elt) { return 'Kriss feed (' + parseInt(elt.innerHTML, 10) + ')'; } return ''; }; this.poll = function() { if(self.getUnreadCount() != "0") { self.getUnreadCountIcon(function(icon) { self.setIcon(icon); }); } else { self.getIcon(function(icon) { self.setIcon(icon); }); } }; this.setIcon = function(icon) { var links = self.head.getElementsByTagName('link'); for (var i = 0; i < links.length; i++) if ((links[i].rel == 'shortcut icon' || links[i].rel=='icon') && links[i].href != icon) self.head.removeChild(links[i]); else if(links[i].href == icon) return; var newIcon = document.createElement('link'); newIcon.type = 'image/png'; newIcon.rel = 'shortcut icon'; newIcon.href = icon; self.head.appendChild(newIcon); // Chrome hack for updating the favicon //var shim = document.createElement('iframe'); //shim.width = shim.height = 0; //document.body.appendChild(shim); //shim.src = 'icon'; //document.body.removeChild(shim); }; this.toString = function() { return '[object FaviconAlerts]'; }; return this.construct(); }());
//gulpfile.js var gulp = require('gulp'); var sass = require('gulp-sass'); //style paths // var scssFiles = 'src/assets/scss/**/*.scss'; // var cssDest = 'src/assets/css/'; var scssFiles = 'src/assets/scss/*.scss'; var cssDest = 'src/assets/css/'; function defaultTask(cb) { gulp.src(scssFiles) .pipe(sass({ errorLogToConsole: true, outputStyle: 'compressed' })) .on('error', console.error.bind(console)) .pipe(gulp.dest(cssDest)); cb(); } exports.default = defaultTask
var BookView = Backbone.View.extend({ tagName: 'li', className: 'list-menu-item', events: { 'click': 'increment' }, initialize: function(options) { this.model.on('change', this.render, this); this.model.on('destroy', this.remove, this); }, render: function() { var html = "<div>" + this.model.get('title') + "</div><div>" + this.model.get('counter') + "</div>"; this.$el.html(html); return this; }, increment: function() { this.model.set('counter', this.model.get('counter')+1); this.render(); } });
import React from 'react'; const SuccessModal = () => ( <div id="success-box" className="success-modal">Song added to playlist</div> ); export default SuccessModal;
"use strict"; /*jslint nomen: true, white: true, plusplus: true*/ var entityManager = { _gameboard : [], _pacman : [], _ghost : [], _timer : [], _points : [], // "PRIVATE" METHODS _forEachOf : function(aCategory, fn) { for (var i = 0; i < aCategory.length; ++i) { fn.call(aCategory[i]); } }, // PUBLIC METHODS // Some things must be deferred until after initial construction // i.e. thing which need `this` to be defined. // deferredSetup : function () { this._categories = [this._gameboard, this._pacman, this._ghost, this._timer, this._points]; }, init: function() { this.generatePacman(); this.generateGameboard(); this.generateGhost(); this.generateTimer(); }, resetTimer : function() { this._timer[0].reset(); }, generateTimer : function(descr) { this._timer.push(new Timer(descr)); }, generateGameboard : function(descr) { this._gameboard.push(new Gameboard(descr)); }, generatePacman : function(descr) { this._pacman.push(new Pacman({ x : 24*10, y : 24*13, width : tile_width, height : tile_height, cx : 24+tile_width/2, cy : 24+tile_height/2, lives : 10, score : 0 })); }, generateGhost : function(descr) { var colors = ['orange', 'red', 'pink', 'blue']; var pos = [[240, 216], [216, 192], [240, 192], [264, 192]]; var targets = [[1, 1], [1, 17], [19, 17], [19, 1]]; var initialPos = [[10, 9], [9, 8], [10, 8], [9, 9]]; this._ghost.push(new Ghost({ x : pos[0][0], y : pos[0][1], cx : pos[0][0] + tile_width/2, cy : pos[0][1] + tile_width/2, color : colors[0], targetX : targets[0][0], targetY : targets[0][1], tilePosX : initialPos[0][0], tilePosY : initialPos[0][1], mode : 'scatter' })); for(var i = 1; i < colors.length; i++) { this._ghost.push(new Ghost({ x : pos[i][0], y : pos[i][1], cx : pos[i][0] + tile_width/2, cy : pos[i][1] + tile_width/2, color : colors[i], targetX : targets[i][0], targetY : targets[i][1], tilePosX : initialPos[i][0], tilePosY : initialPos[i][1], mode : 'chase' })); } }, update: function(du) { for (var c = 0; c < this._categories.length; ++c) { var aCategory = this._categories[c]; var i = 0; while (i < aCategory.length) { var status = aCategory[i].update(du); ++i; } } }, render: function(ctx) { for (var i = 0; i < this._categories.length; ++i) { var aCategory = this._categories[i]; for (var j = 0; j < aCategory.length; ++j) { aCategory[j].render(ctx); } } }, setMode : function(mode) { for (var i = 0; i < this._ghost.length; ++i) { if (mode === 'frightened' && this._ghost[i].mode === 'dead') { this._ghost[i].setMode('dead'); } else { this._ghost[i].setMode(mode); } } }, //set ghost modes to scatter/chase switchModes : function() { console.log('switch'); var modes = []; var scatter = 0; var chase = 0; var frightened = 0; var dead; for (var i = 0; i < this._ghost.length; i++) { var ghost = this._ghost[i]; modes.push(ghost.mode); if (ghost.mode === 'scatter') scatter++; if (ghost.mode === 'chase') chase++; if (ghost.mode === 'frightened') frightened++; if (ghost.mode === 'dead') dead++; } //at least one ghost has to be in scatter mode if (chase === 4) this._ghost[0].setMode('scatter'); //if all ghosts are in either scatter or chase mode we switch between chase and scatter else if (scatter === 1 && chase === 3) { var index = modes.indexOf('scatter'); this._ghost[index].setMode('chase'); if (index === 3) this._ghost[index].setMode('scatter'); else this._ghost[index+1].setMode('scatter'); } //if all ghosts are in frightened mode else if (frightened === 4) { this._ghost[0].setMode('scatter'); this._ghost[1].setMode('chase'); this._ghost[2].setMode('chase'); this._ghost[3].setMode('chase'); } //if at least one ghost is in frightened mode else if (frightened > 0 && frightened < 4) { for (var j = 0; j < modes.length; j++) { if (this._ghost[j].mode === 'frightened') this._ghost[j].setMode('chase'); } } }, //check if pacman has eaten ghost checkCollide : function() { var pacman = this._pacman[0]; for (var i = 0; i < this._ghost.length; i++) { var ghost = this._ghost[i]; if (this._ghost[i].mode === 'frightened' && (ghost.x <= pacman.cx && pacman.cx <= ghost.x+tile_width) && (ghost.y <= pacman.cy && pacman.cy <= ghost.y+tile_width)) { ghost.setMode('dead'); var snd = new Audio("views/pacman/pacman_eatghost.wav"); // buffers automatically when created if(g_sound) snd.play(); pacman.score = pacman.score + 200 this._points.push(new Points({ x : ghost.x, y : ghost.y, points : 200 })); } } }, restart : function() { console.log("pressing restart"); //g_isUpdatePaused = true; this.clearEverything(); this.init(); main._isGameOver = false; document.getElementById('gameOver').style.display = "none"; var gameboard = this._gameboard[0]; gameboard.reset(gameboard.level); main.init(); }, clearEverything : function(){ for (var i = 0; i < this._categories.length; ++i) { var aCategory = this._categories[i]; while(aCategory.length > 0){ aCategory.pop(); } } } } // Some deferred setup which needs the object to have been created first entityManager.deferredSetup(); entityManager.init();
alias_Bitmap_drawText = Bitmap.prototype.drawText; Bitmap.prototype.drawText = function (text, x, y, maxWidth, lineHeight, align) { y += -5; alias_Bitmap_drawText.call(this, text, x, y, maxWidth, lineHeight, align); };
'use strict'; // write a function called each that takes an array and a function as a paramter // and calls the function with each element of the array as parameter // so it should call the array 3 times if the array has 3 elements function each (arr, func) { for (var i = 0; i < arr.length; i++) { func(arr[i]); } } each([1,2,3], console.log);
// block scope let globalScope = 'hello global scope' if (true) { let blockScope = 'hello block scope'; // only inside the if is available console.log(blockScope); } else { console.log(globalScope); // console.log(myVar); // myVar is not defined } // console.log(myVar); // myVar is not defined console.log(globalScope); // variables // var is available globally even ig you have declared it inside a block { var hello = 'world'; var hello = 'hello'; // there is no check for existing variables } console.log(hello); let globally = 'i need this everywhere'; // the let statement declares a block-scoped local variable, let hello2 = 'world'; // let hello = 'hello' // error // const is like let in scopes { const MY_NAME = 'Peter'; console.log(MY_NAME); } // Console.log(MY_NAME); error // when should i ise if, when should i use ternary operator let date = 'wednesday'; if (date === 'wednesday') { console.log('it is 2 days until the weekend'); } console.log(date === 'wednesday' ? 'it is 2 days until the weekend' : 'it is not wednesday'); if (date === 'wednesday') { console.log('it is 2 days until the weekend'); } if (date === 'tuesday') { console.log('it is 3 days until the weekend'); } if (date === 'monday') { console.log('it is 4 days until the weekend'); } // math problems let number = 42; if (number % 2 === 0) { console.log(number/2); console.log(number/2/2); } console.log(number%2 === 0?` ${number/2} ${number/2/2} `: number);
import React from 'react' import "./card.scss" import { Link, useHistory } from "react-router-dom"; export default function Card({ item }) { const history = useHistory(); const handleProductRoute = (item) => { history.push({ pathname: `/product/${item.id}`, }); } return ( <div className="card" onClick={() => handleProductRoute(item)}> <div className="image-container"> <img src={item.image} /> </div> <div className="card-title-container"> <span>{item.title}</span> </div> <div className="card-price-container"> <span>${item.price}</span> </div> </div> ) }
import React from 'react' import { getListType } from '../Common/axios' import { random } from '../Common/commonfunc' import { Link } from 'react-router-dom' import Animation from './animation' import LazyLoad from 'react-lazyload'; function RenderItem(props) { return props.list.map((item, index) => ( <div key={index}> <div className="ListType_li" > <Link className="ListType_li_img" to={{ pathname: props.title == "推荐菜单" ? `/SongSheet/${item[0].content_id}` : `/SongSheet/${item[0].tid}`, state: { data: props.title == "推荐菜单" ? item[0].cover : item[0].cover_url_small } }} > {props.title == "推荐菜单" ? <img data-src={`${item[0].cover}`} /> : <img data-src={`${item[0].cover_url_small}`} />} </Link> </div > <p>{item[0].title}</p> </div> )) } class ListType extends React.Component { constructor(props) { super(props); this.state = { } } componentDidUpdate(nextprops) { if (this.props.title == nextprops.title) { return false } } componentDidMount() { getListType(this.props.title, this.props.id).then((res) => { this.setState({ list: [...random(res, 6)] }, function () { this.lazy() }) }) } lazy = () => { let img = document.getElementsByTagName("img"); let length = img.length; for (let i = 7; i < length; i++) { if (img[i].getBoundingClientRect().top < 50 + window.innerHeight) { img[i].classList.add("animation_opacity"); img[i].src = img[i].getAttribute("data-src"); } } } render() { return ( <> < div className="ListType" > <div className="ListType_title"> <p>{this.props.title}</p> <i className="iconfont icon-xiaojiantou"></i> </div> {this.state.list ? <div className="ListType_ul"> <RenderItem list={this.state.list} title={this.props.title}></RenderItem> </div> : <Animation></Animation> } </div > </> ) } } export default ListType
import React from 'react'; import HomePost from './HomePost'; const Home = props => { const { content, categoryFilter } = props; return ( <div className="container"> { content.filter(post => !categoryFilter || post.category === categoryFilter).map((item, key) => { return <HomePost key={key} post={item} />; }) } </div> ); }; export default Home;
"use strict"; var box0 = { value: 'test' }; var box1 = { value: 'test' }; var box2 = { value: 0 }; var box3 = { value: false };
const express = require('express') const app = express() var router = express.Router(); const port = 3000 let bodyParser = require('body-parser'); let cors = require('cors'); router.use(bodyParser.urlencoded({ extended: false })); // router.use(bodyParser.json()); app.use(bodyParser.json()); require('./routes/index')(app); let mongoose = require('./dbconnection'); mongoose.init('mongodb+srv://dbuser:dbuser@cluster0-kpe8t.mongodb.net/health_application?retryWrites=true&w=majority'); require('./models').init() app.use(cors({ maxAge: 3600, credentials: true, methods: 'GET, HEAD, OPTIONS, PUT, POST, DELETE', headers: 'Access-Control-Allow-Origin, Access-Control-Expose-Headers,auth_token,x-access-token,agent_auth,user_auth,Origin, X-Requested-With, Content-Type, Accept, Authorization,ConnectionType,AgentCode', expose: ['Access-Control-Allow-Origin', 'Access-Control-Expose-Headers'] })); app.use(bodyParser.urlencoded({ parameterLimit: 1000000, limit: '500mb', extended: true })); app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
import React from "react"; import { createStackNavigator } from "@react-navigation/stack"; import routes from "./routes"; import AccountScreen from "../screens/AccountScreen"; import MessagesScreen from "../screens/MessagesScreen"; const Stack = createStackNavigator(); const AccountNavigator = () => ( // mode="modal" allows for pulling down to remove view // You have to start pulling pretty high up, so I decided to use card (default) instead // which allows for swiping back. Should maybe add back the header with back button as well <Stack.Navigator mode="card"> <Stack.Screen name={routes.ACCOUNT} component={AccountScreen} /> <Stack.Screen name={routes.MESSAGES} component={MessagesScreen} /> </Stack.Navigator> ); export default AccountNavigator;
Orders = new Mongo.Collection("orders"); Orders.allow({ insert: function (userId, order) { return userId && order.owner === userId; }, update: function (userId, order, fields, modifier) { return userId && order.owner === userId; }, remove: function (userId, order) { return true; } });
function solve(){ return function(selector){ $.fn.dropdownList = function(selector) { var select = $(selector); var dropdownWrapper = $('<div>').addClass('dropdown-list'); var currentSelectedElement = $('<div>') .addClass('current') .attr('data-value', $(select.children()[0]).html()) .html($(select.children()[0]).html()); var optionsContainer = $('<div>').addClass('options-container').css({ 'position': 'absolute', 'display': 'none' }); for(var i = 0; i < select.children().length; i += 1){ var currentSelectItem = select.children()[i]; var option = $('<div>') .addClass('dropdown-item') .attr('data-value', $(currentSelectItem).val()) .attr('data-index', i) .html($(currentSelectItem).html()) .click(function(){ $('.current') .html($(this).html()) .attr('data-value', $(this).attr('data-value')); select.val($(this).attr('data-value')); }); optionsContainer.append(option); } dropdownWrapper.append(select.css('display', 'none')); dropdownWrapper.append(currentSelectedElement); dropdownWrapper.append(optionsContainer); $(this).append(dropdownWrapper); $('.current').click(function(){ $(this).html('Select a value'); if($('.options-container').css('display') === 'none'){ $('.options-container').css('display', ''); } else{ $('.options-container').css('display', 'none'); } }); $('.dropdown-item').click(function(){ $('.options-container').css('display', 'none'); }); }; $('body').dropdownList(selector); }; } module.exports = solve;
/** * Non-exhaustive set of tests that ensure that * the most important functions work. */ if (typeof module !== "undefined") { module.exports = { smokeTest: smokeTest } } function smokeTest(cornerstone) { describe("CornerStone", function() { it("should get a list of languages", (done) => { cornerstone.getLanguages() .then(function(data) { expect(data.length).toBeGreaterThan(0); done(); }) .catch(function(err) { done(err); }); }); it("should get a verse", (done) => { cornerstone.getVerse({book: "John", chapter: 3, verse: 16}) .then((data) => { expect(data.verses[0].text).toContain("For God so loved the world,"); done(); }) .catch((err) => { done(err); }); }); it("should get a chapter", (done) => { cornerstone.getChapter({book: "Matt", chapter: 28}) .then(function(data) { expect(data.verses.length).toEqual(20); done(); }) .catch(function(err) { done(err); }); }); /* it("should get a list of versions", function(done) { done(); });*/ }); }
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PostContainer from '../post/PostContainer'; import Paging from '../../components/paging/Paging'; import { fetchUsers } from '../../actions/userActions'; import { fetchPosts } from '../../actions/postActions'; import { getIsUserRequested, getIsPostsRequested, getPosts, getCurrentPage} from '../../reducers'; class App extends Component { constructor(props) { super(props); const { fetchUsers, fetchPosts } = this.props; fetchUsers(); fetchPosts(1); this.onPageClicked = this.onPageClicked.bind(this); } getPostsElements(){ const {posts, isUserRequested, isPostsRequested} = this.props; if(isUserRequested || isPostsRequested || !posts){ return ( <div className="loading-container"> Loading... </div> ); } return posts.map( (postId) => { const key = `post-${postId}`; return ( <PostContainer postId={postId} key={key} onCommentsClicked={this.onCommentsClicked} /> ); } ); } onPageClicked(index) { const { fetchPosts } = this.props; fetchPosts(index); } render() { const {currentPage} = this.props; return ( <div> <h1> TEST APPLICATION </h1> <Paging currentPage={currentPage} onPageClicked={this.onPageClicked} lastPageIndex={10} /> {this.getPostsElements()} </div> ); } } const mapStateToProps = (state) => ({ isUserRequested:getIsUserRequested(state), isPostsRequested:getIsPostsRequested(state), posts:getPosts(state), currentPage:getCurrentPage(state), }); const mapDispatchToProps = { fetchUsers, fetchPosts, }; export const AppBase = App; export default App = connect( mapStateToProps, mapDispatchToProps )(App);
import request from '@/utils/request' const uri = '/favorite/' export class favoriteApi { static websiteClick(id) { return request({ url: uri + 'website/click/' + id, method: 'get' }) } static websiteInfo(id) { return request({ url: uri + 'website/info/' + id, method: 'get' }) } static typeList() { return request({ url: uri + 'type/list', method: 'get' }) } static allTypeList() { return request({ url: uri + 'type/all/list', method: 'get' }) } static websiteFavorite(form) { return request({ url: uri + 'website/favorite', method: 'post', data: form }) } static websiteList(id) { return request({ url: uri + 'website/list/' + id, method: 'get' }) } static typeEdit(form) { return request({ url: uri + 'type/edit', method: 'post', data: form }) } static websiteEdit(form) { return request({ url: uri + 'website/edit', method: 'post', data: form }) } }
var num = -23; if(num == 0){ console.log("É zero"); } else if(num > 0){ console.log("É maior que zero"); } else{ console.log("É menor que zero"); }
import React from 'react'; import Button from './Button'; import Timer from './Timer'; export default class Layout extends React.Component { constructor() { super(); this.state = { firstName: "Marcin", lastName: "Kopanski", isTimerMounted: true }; } changeName() { this.setState({ firstName: "Agata", lastName: "Czarny" }) } toggleTimers() { this.setState((prevState) => ({ isTimerMounted: !prevState.isTimerMounted })) } render() { return ( <div> <h1>Welcome to my site!!!!!!!!!</h1> <h3>Happy to have you here</h3> <h1>{this.state.firstName} {this.state.lastName}</h1> <Button firstName={this.state.firstName} changeName={this.changeName.bind(this)} /> <p>Lorem ipsum lorem ipsum</p> {this.state.isTimerMounted ? <div> <Timer /> <Timer /> <Timer /> </div> : null } <button onClick={this.toggleTimers.bind(this)}>{this.state.isTimerMounted ? "Hide timers" : "Show timers"}</button> </div> ) } }
/** * Created by GG on 2018/07/19. */ const pkg = require('../package.json') const prod = require('./webpack.prod.conf') const fs = require('fs') const del = require('del') const path = require('path') const chalk = require('chalk') const webpack = require('webpack') const easeftp = require('easeftp/upload') const ftppass = JSON.parse(fs.readFileSync('.ftppass', 'utf-8')) console.log(chalk.cyan('building...')) webpack(prod, (err, stats) => { if (err) throw err console.log(stats.toString({ colors: true, modules: false, children: false })) console.log(chalk.cyan('uploading...')) easeftp.addFile(['**/*'], { ...ftppass.easeftp, path: 'activity/' + pkg.name + '/static', cwd: path.resolve('dist/static') }).then((data)=>{ console.log(data.urls) del(['dist/static']) }) })
var express=require('express'); var bodyParser=require('body-parser'); var api=require('./api.js'); var app=express(); app.use(bodyParser.json()); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); api(app); app.listen(3000,function(){ console.log('Listening to port '+3000); });
import React, { Component } from 'react'; import { Route, Switch } from 'react-router-dom'; import style from './index.module.scss'; import Bottom from '../bottom/index'; import About from '../about/About'; import Projects from '../projects/index'; import Detail from '../detail/detail'; class Home extends Component { constructor(props) { super(props); } render() { return ( <div> <Switch className={style.mainPage}> <Route path="/" exact component={Projects} /> <Route path="/about" component={About} /> <Route path="/detail" component={Detail} /> <Route component={Projects} /> </Switch> <Bottom /> </div> ); } } export default Home;
import { TagSEO } from '@/components/utils/SEO' import siteMetadata from '@/data/siteMetadata' import ListLayout from '@/layouts/ListLayout' import generateRss from '@/lib/generate-rss' import kebabCase from '@/lib/utils/kebabCase' import { getAllFilesFrontMatter } from '@/lib/mdx' import { getAllCategories } from '@/lib/categories' import fs from 'fs' import path from 'path' const root = process.cwd() export async function getStaticPaths() { const categories = await getAllCategories('blog') return { paths: Object.keys(categories).map((category) => ({ params: { category, }, })), fallback: false, } } export async function getStaticProps({ params }) { const allPosts = await getAllFilesFrontMatter('blog') const filteredPosts = allPosts.filter( (post) => post.draft !== true && kebabCase(post.category) == params.category ) // RSS if (filteredPosts.length > 0) { const rss = generateRss(filteredPosts, `blog/category/${params.category}/feed.xml`) const rssPath = path.join(root, 'public', 'category', params.category) fs.mkdirSync(rssPath, { recursive: true }) fs.writeFileSync(path.join(rssPath, 'feed.xml'), rss) } return { props: { posts: filteredPosts, category: params.category } } } export default function Category({ posts, category }) { const title = category.replace('-', ' ') return ( <> <TagSEO title={`${category} - ${siteMetadata.author}`} description={`${category} Category - ${siteMetadata.author}`} /> <ListLayout className="capitalize" posts={posts} title={title} /> </> ) }
var path = require('path'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { context: path.resolve(__dirname, './src'), entry: './main.jsx', output: { path: path.resolve(__dirname, './dist'), filename: 'bundle.js' }, plugins: [ new HtmlWebpackPlugin({ title: 'GoEuro Job Application', template: 'index.html' }) ], module: { loaders: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.s?css$/, exclude: /node_modules/, loaders: [ 'style', 'css', 'postcss' ] }, { test: /\.(otf|ttf|eot|svg|jpg|png)(\?[\s\S]+)?$/, loader: 'file' } ] }, postcss: function(webpack) { return [ require('postcss-import')({ addDependencyTo: webpack }), require('postcss-url')(), require('postcss-cssnext')({}), // add your 'plugins' here // ... // and if you want to compress, // just use css-loader option that already use cssnano under the hood require('postcss-browser-reporter')(), require('postcss-reporter')() ] }, devtool: 'source-map' }
import React from "react"; import styled from "styled-components"; import { Container } from "semantic-ui-react"; import Filter from "../FilterWrapper"; const FiltersList = ({ filters }) => ( <div> {filters.map(({ name, component }) => ( <Filter name={name}>{component}</Filter> ))} </div> ); export default FiltersList;
import { Reducer } from 'redux-testkit' import theReducer, { initialState } from '../reducer' import * as actionTypes from '../actionTypes' describe('ExportCategories Reducer', () => { it('should have initial state', () => { expect(theReducer()).toEqual(initialState) }) it('should not affect state', () => { Reducer(theReducer).expect({ type: 'NOT_EXISTING_TYPE' }).toReturnState(initialState) }) it('should handle reset', () => { Reducer(theReducer).expect({ type: actionTypes.EXPORT_CATEGORIES_RESET }).toReturnState(initialState) }) it('should load export pages', () => { const resultState = { "ID4000 ": { id: "ID4000", label: "Integrantes", value: "Lisa, Jisoo, Jenny, Rosé" }, "ID4001": { id: "ID4001", label: "Categoria Inventada", value: "Valores aleatorios" } } Reducer(theReducer).expect({ type: actionTypes.EXPORT_CATEGORIES_LOAD_CATEGORIES, payload: { "ID4000 ": { id: "ID4000", label: "Integrantes", value: "Lisa, Jisoo, Jenny, Rosé" }, "ID4001": { id: "ID4001", label: "Categoria Inventada", value: "Valores aleatorios" } } }).toReturnState(resultState) }) })
import React from 'react'; import { shallow } from 'enzyme'; import { BoardHeader } from './BoardHeader'; describe('BoardHeader', () => { let wrapper; let props; beforeEach(() => { props = { phase: 'diplomatic', season: 'spring', year: 1901, mode: 'normal', setMode: jest.fn(), toggleGameInfoModal: jest.fn(), } wrapper = shallow(<BoardHeader {...props} />); }) it('clicking on list icon calls toggleGameInfoModal', () => { wrapper.find('.list-icon').simulate('click'); expect(props.toggleGameInfoModal).toHaveBeenCalled(); }); it('clicking on one of the mode buttons calls setMode', () => { wrapper.find('#set-support-mode-button').simulate('click'); expect(props.setMode).toHaveBeenCalledWith('support'); }) })
const request = require('supertest') const expect = require('expect') const app = require('./server').app describe('Server', () => { describe('GET /', () => { it('should return hello response', (done) => { request(app) .get('/') .expect(200) .expect('Hello') .end(done) }) }) describe('GET /users', () => { it('should show me in the users response', (done) => { request(app) .get('/users') .expect(200) .expect((res) => { expect(res.body).toInclude({ name: 'Ivaylo', age: 90 }) }) .end(done) }) }) describe('GET unknown', () => { it('should return 404 for unknown urls', (done) => { request(app) .get('/random') .expect(404) .expect((res) => { expect(res.body).toInclude({ error: 'Page not found' }) }) .end(done) }) }) })
import { renderString } from '../../src/index'; describe(`Insert custom HTML module`, () => { it(`unnamed case 0`, () => { const html = renderString(`{% raw_html "raw_html" %}`); }); it(`unnamed case 1`, () => { const html = renderString(`{% raw_html "my_raw_html", label="Enter HTML here", value="<div>My HTML Block</div>" %}`); }); });
function init() { var code_mirror_source_editor = CodeMirror.fromTextArea(document.getElementById('source_editor'), { mode: "clike", theme: "dracula", lineNumbers: true, autoCloseBrackets: true }); var code_mirror_result_editor = CodeMirror.fromTextArea(document.getElementById('result_editor'), { mode: "clike", theme: "dracula", lineNumbers: true, autoCloseBrackets: true, readOnly: true }); var singleModNav = document.getElementById('singlemod'); singleModNav.style.color = "white"; singleModNav.style.fontWeight = "bold"; singleModNav.style.fontSize = "18px"; singleModNav.style.textDecoration = "underline" code_mirror_source_editor.on("change",function(cm,change){ source_editor.value = code_mirror_source_editor.getValue(); }); }
import main from '../../src' import map from 'ramda/src/map' import addIndex from 'ramda/src/addIndex' import lensIndex from 'ramda/src/lensIndex' import over from 'ramda/src/over' import add from 'ramda/src/add' const mapIndexed = addIndex(map) const counter = (count, index) => ( ['.counter', [ ['h1', count], ['button', {click: {add: {index, amount: 1}}}, 'Add 1'], ['button', {click: {add: {index, amount: -1}}}, 'Remove 1'] ]] ) const view = (counters) => ( ['main', [ ['button', {click: {addCounter: true}}, 'Add counter'], ['button', {click: {removeCounter: true}}, 'Remove counter'], ['ol', mapIndexed(counter, counters)] ]] ) const reducer = (state, {type, payload}) => { switch (type) { case 'addCounter': return [...state, 0] case 'removeCounter': const [, ...counters] = state return counters case 'add': return over(lensIndex(payload.index), add(payload.amount), state) } return state } const model = [] main(view, model, reducer)
import React from 'react' import styles from './header.module.css' import HomeOutlinedIcon from '@material-ui/icons/HomeOutlined'; import Link from 'next/link' const Header = () => { return ( <header className={styles.header}> <nav className={styles.container}> <Link href="/"><a><HomeOutlinedIcon style={{fontSize: "2.25rem"}} /></a></Link> <h1>Rick y Morty</h1> <Link href="/about"><a>Nosotros</a></Link> </nav> </header> ) } export default Header
import React, { Component } from 'react' import './App.css'; // import LightBulbApp from './components/LightBulbApp/LightBulbApp' // import InputsEventsApp from './components/InputsEventsApp/InputsEventsApp' // import MadlibApp from './components/MadlibApp/MadlibApp' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' import mockCats from './mockCats' import Home from './pages/Home' import CatIndex from './pages/CatIndex' import CatShow from './pages/CatShow' import CatNew from './pages/CatNew' import CatEdit from './pages/CatEdit' import NotFound from './pages/NotFound' class App extends Component { constructor(props) { super(props); this.state = { cats: mockCats }; } render() { return ( <Router> <Switch> {/* Home */} <Route exact path="/" component={ Home } /> {/* Index */} <Route path="/catindex" component={ CatIndex } /> {/* Show */} <Route path="/catshow/:id" component={ CatShow } /> {/* New */} <Route path="/catnew" component={ CatNew } /> {/* Edit */} <Route path="/catedit/:id" component={ CatEdit } /> <Route component={ NotFound }/> </Switch> </Router> ); } } export default App;
import React from 'react'; import {storiesOf} from '@storybook/react'; import Shows from '../src/app/containers/Shows'; import reducers from '../src/app/reducers/index.js'; import {combineReducers, createStore} from 'redux'; import {Provider} from 'react-redux'; import {BrowserRouter as Router} from 'react-router-dom'; const store = createStore( combineReducers(reducers), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ); storiesOf('Shows', module).add('Default', () => ( <Provider store={store}> <Router> <Shows /> </Router> </Provider> ));
let config = { type: 'carousel', perView: 1, //jumlah tampilan gambar autoplay: 1000, //waktu untuk mengganti gambar hoverpause: true, //saat kursor diarahkan ke gambar, maka autoplay berhenti }; let glide = new Glide('.glide', config).mount()
const express = require("express"); const router = express.Router(); // const getProjectSummary = require("../library/getProjectSummary"); const ifEnvExists = require("../library/ifEnvExists"); const showData = require("../library/showData"); const sqlite3 = require('sqlite3').verbose(); /** * Express.js router for /envlist * * Return array of all envelopes by given scan number and project code */ let envlist = router.get('/envlist', function(req, res) { console.log("Hello, envlist!"); let projectDir = req.query.projectDir; let scanid = req.query.scanID; let projectCode = req.query.projectCode; // console.log(scanid); // getProjectSummary(projectCode, function (err, row) { // }) let dbDir = projectDir.substr(0, projectDir.lastIndexOf(".")) + ".db"; let resultDb = new sqlite3.Database(dbDir, (err) => { if (err) { console.error(err.message); } // console.log('Connected to the result database.'); }); ifEnvExists(projectCode,(err, row)=> { // console.log("row:", row); if(row.EnvelopeStatus === 1) { showData(resultDb,scanid,res); }else { res.write('0'); res.end(); } }) }); module.exports = envlist;
var $ = require('jquery'); var chatMessageTpl = require('./chat-message.jade') function Chat() { this.messages = []; }; var p = Chat.prototype; p.run = function() { var errors = false; if (!this.inputEl) { console.error('Your chat app needs proper input element!'); console.warning('Use: setInputElement'); errors = true; } if (!this.outputEl) { console.error('Your chat app needs proper output element!'); console.warning('Use: setOutputElement'); errors = true; } if (!this.socket) { console.log('Your chat app needs a proper socket connection.'); console.log('Try to use: setSocket'); errors = true; } if (!errors) { console.log('Creating chat!') this.attachEvents(); } } p.loginUser = function(username) { this.socket = io(); this.socket.emit('set-username', username); } p.getSocket = function() { return this.socket; } p.setInputElement = function(element) { var el = $(element); this.inputEl = el.length && el; } p.setOutputElement = function(element) { var el = $(element); this.outputEl = el.length && el; } p.sendMessage = function() { var msg = this.inputEl.val(); this.socket.emit('message', msg); this.clearInput(); this.writeMessageToOutput(msg); } p.writeMessageToOutput = function(msg, author, date) { this.messages.push({ message: msg, author: author, date: date }); var messageTag = this.createMessageTag(msg); this.outputEl.append(messageTag); } p.createMessageTag = function(msg) { return $(chatMessageTpl({ message: msg })); } p.clearInput = function() { this.inputEl.val(''); } p.attachEvents = function() { var sendMessage = function(event) { switch (event.keyCode) { case 13: { this.sendMessage(); } } } this.inputEl.on('keydown', sendMessage.bind(this)); } module.exports = Chat;
const Router = require("express").Router(); const TestOrders = require("../models/test-orders"); Router.post("/add", (req, res) => { const {total, items, user_id} = req.body; let messages = []; // Null Validation if (!total || !items || !user_id){ messages.push({ msg: "Missing Credentials", msg_class: "alert-danger" }) } // Check errors if (messages.length > 0) { return res.json({ messages }); } new TestOrders({ total, items, user_id }).save() .then(createdOrder => { messages.push({ msg: "Successfully create a new order", msg_class: "alert-success" }) res.json({ messages, createdOrder }) }) .catch((err) => { messages.push({ msg: "Something went wrong when create a new product", msg_class: "alert-danger" }) res.json({ messages, err }) }) }) Router.get("/", (req, res) => { let messages = []; TestOrders.find({}) .then(products => { res.json({ products }) }) .catch(err => { messages.push({ msg: "Something went wrong when trying to get the data", msg_class: "alert-danger" }) res.json({ messages, err }) }) }); Router.get("/:id", (req, res) => { const id = req.params.id; let messages = []; TestOrders.findById(id) .then(order => { res.json({ order }) }) .catch(err => { messages.push({ msg: "Something went wrong when trying to get the data", msg_class: "alert-danger", }) res.json({ messages, err }) }) }); Router.get("/all/:user_id", (req, res) => { const id = req.params.user_id; let messages = []; TestOrders.find({user_id: id}) .then(orders => { res.json({ orders }) }) .catch(err => { messages.push({ msg: "Something went wrong when trying to get the data", msg_class: "alert-danger", }) res.json({ messages, err }) }) }); module.exports = Router;
import React from "react"; import fake_icon from "../../assets/fake_icon.png"; import { NavLink } from "react-router-dom"; const Footer = () => { return ( <footer className="footer-section"> <div className="container"> <div className="footer-cta pt-5 pb-5"> <div className="row"> <div className="col-xl-4 col-md-4 mb-30"> <div className="single-cta"> <i className="fas fa-map-marker-alt"></i> <div className="cta-text"> <h4>Find us</h4> <span>Wasa Raod, Maniknagor Dhaka-1203</span> </div> </div> </div> <div className="col-xl-4 col-md-4 mb-30"> <div className="single-cta"> <i className="fas fa-phone"></i> <div className="cta-text"> <h4>Call us</h4> <span>9876543210 0</span> </div> </div> </div> <div className="col-xl-4 col-md-4 mb-30"> <div className="single-cta"> <i className="far fa-envelope-open"></i> <div className="subscribe-form"> <h4>Mail us</h4> <span>mail@info.com</span> </div> </div> </div> </div> </div> <div className="footer-content pt-5 pb-5"> <div className="row"> <div className="col-xl-4 col-lg-4 mb-50"> <div className="footer-widget"> <div className="footer-logo"> <img src={fake_icon} className="img-fluid" alt="logo" /> </div> <div className="footer-text"> <p> Lorem ipsum dolor sit amet, consec tetur adipisicing elit, sed do eiusmod tempor incididuntut consec tetur adipisicing elit,Lorem ipsum dolor sit amet. </p> </div> <div className="footer-social-icon"> <span>Follow us</span> <a href="https://www.facebook.com/" target="_blank" rel="noreferrer" > <i className="fab fa-facebook-f facebook-bg"></i> </a> <a href="https://twitter.com/login?lang=en" target="_blank" rel="noreferrer" > <i className="fab fa-twitter twitter-bg"></i> </a> <a href="https://www.google.com/" target="_blank" rel="noreferrer" > <i className="fab fa-google-plus-g google-bg"></i> </a> </div> </div> </div> <div className="col-xl-4 col-lg-4 col-md-6 mb-30"> <div className="footer-widget"> <div className="footer-widget-heading"> <h3>Useful Links</h3> </div> <ul> <li> <NavLink to="/">Home</NavLink> </li> <li> <NavLink to="/users">Users</NavLink> </li> <li> <NavLink to="/posts">Posts</NavLink> </li> </ul> </div> </div> </div> </div> </div> <div className="copyright-area"> <div className="container"> <div className="row"> <div className="col-xl-6 col-lg-6 text-center text-lg-left"> <div className="copyright-text"> <p>Copyright &copy; 2021, All Right Reserved </p> </div> </div> </div> </div> </div> </footer> ); }; export default Footer;
var DAYS; (function (DAYS) { DAYS[DAYS["SunDay"] = 1] = "SunDay"; DAYS[DAYS["MonDay"] = 2] = "MonDay"; DAYS[DAYS["TuesDay"] = 3] = "TuesDay"; DAYS[DAYS["WendsDay"] = 4] = "WendsDay"; DAYS[DAYS["ThursDay"] = 5] = "ThursDay"; DAYS[DAYS["FriDay"] = 6] = "FriDay"; DAYS[DAYS["SaturDay"] = 7] = "SaturDay"; })(DAYS || (DAYS = {})); var printWeekEnd = function (weekEnd) { console.log(weekEnd); }; var printDay = function (day) { console.log(day); }; printWeekEnd(1 /* SunDay */); console.log('-----------------'); printDay(DAYS.SunDay); console.log('-----------------'); console.log(DAYS[DAYS.SunDay]);
export const FETCH_SEASON_SUCCESS = "FETCH_SEASON_SUCCESS"; export const FETCH_SEASON_FAILURE = "FETCH_SEASON_FAILURE";
import React from 'react/addons' import Parser from '../dist/parser' import Parsertools from '../dist/parsertools' var CalculatorError = React.createClass({ convertFound(found) { if (found == null) { return 'nichts'; } return '"' + found + '"'; }, connectList(list) { if (list.length == 1) { return this.stringifyItem(list[0]); } return list.slice(0, list.length - 1).map(this.stringifyItem).join(", ") + ' oder ' + this.stringifyItem(list[list.length - 1]) }, stringifyItem(item) { if (item.type == 'end') { return 'das Eingabeende'; } else { return item.description; } }, decodeError(err) { if (err === null) { return { title: '', info: '' } } if (err instanceof Parser.SyntaxError) { console.log(err); var desc = 'Es wurde ' + this.connectList(err.expected) + ' erwartet. Gefunden wurde aber ' + this.convertFound(err.found) + '.'; return { title: 'Der Ausdruck enthält einen syntaktische Fehler an Position ' + err.column + '!', info: desc } } else if (err instanceof Parsertools.UnknownIdentifierError) { return { title: 'Die Variable "' + err.identifier + '" wurde nicht definiert!', info: 'Bei der Berechnung wurde ein unbekannter Bezeichner gefunden. Die Berechnung wird abgebrochen.' }; } else if (err == 'Exponent must not have error') { return { title: 'Der absolute Fehler des Exponenten muss 0 sein!', info: 'Dies liegt an den Grenzen der zugrunde liegenden Fehlerfortpflanzung.' } } else { console.log(err); return { title: 'Ein unbekannter Fehler ist aufgetreten!', info: '' } } }, render() { var cx = React.addons.classSet; var classes = cx({ 'row': true, 'error_container': true, 'hide': this.props.error === null }); var e = this.decodeError(this.props.error); return ( <div className={classes}> <div className="col-md-12"> <h2 className="error">{e.title}</h2> <p className="infotext">{e.info}</p> </div> </div>) } }); export default CalculatorError;
const Order=require('../models/order.model'); const mongoose=require('mongoose'); const Art=require('../models/art.model'); exports.getOrders=(req,res,next)=>{ Order.find() .populate('art','name','gallery','artist') .then(results=>{ console.log(results) res.status(201).json(results) }) .catch(err=>{ res.status(500).json({ error:err }) }) } exports.newOrder=(req,res,next)=>{ Art.findById(req.body.id) .then(art=>{ if(!art){ return res.status(404).json( { message:"product not found" } ) } const order=new Order({ _id:mongoose.Types.ObjectId(), artid:req.body.artid }); return order.save() }) .then(result=>{ res.status(200).json({ message:"order successful", order }) }) .catch(err=>{ res.status(501).json({ error:err } ) }) } exports.getOrder=(req,res,next)=>{ const orderid=req.params.orderid; Order.finById(orderid) .populate('art') exec() .then(order=>{ if(!order){ return res.status(404).json({ message:"order not found" }) } res.status(200).json(order) }) .catch(err=>{ res.status(404).json({ message:"cannot order", error:err }) }) } exports.deleteOrder=(req,res,next)=>{ Order.remove({_id:req.params.orderid}) .exec() .then(result=>{ res.status(200).json({ message:"order succesfully deleted" }) }) .catch(err=>{ res.status(500).json({ }); }) }
$(document).ready( function () { reqFeedBack(resFeedBack); if(!sessionStorage.getItem('loginFlag')){ window.location.href = '../login.html'; } } ); //反馈信息回调 function resFeedBack(data){ console.log(data) $('#table_id_example').DataTable({ data:data.feedback, columns: [ { data: 'qid' }, { data: 'ques_con' }, { data: 'ques_from' }, { data: 'date' } ] }); } //退出 $('#exit').on('click',function(){ sessionStorage.removeItem('loginFlag'); sessionStorage.removeItem('level'); window.location.href = '../login.html'; });
let cells = document.querySelectorAll('.cell') let player = 'x' let restartBtn = document.querySelector('.start-button') let setPlayer = document.querySelector('#player-move') let data = [] let stepCounter = 0 let pause = false let winX = document.querySelector('#win-x') let winY = document.querySelector('#win-y') let draw = document.querySelector('#draw') let winIndex = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ]; let stat = { winX: 0, winY: 0, draw: 0, } setPlayer.innerHTML = player restartBtn.addEventListener('click', () => { for (let cell of cells) { cell.innerHTML = '' } data = [] stepCounter = 0 pause = false }) for (let cell of cells) { cell.addEventListener('click', () => { if (!cell.innerHTML && !pause) { cell.innerHTML = player id = cell.getAttribute('data-id') data[id] = player stepCounter++ console.log(data) if (checkWin()) { if (player === 'x') { stat.winX = ++stat.winX } else { stat.winY = ++stat.winY } pause = true updateStat() return alert('победил ' + player) } if (stepCounter >= 9) { alert('draw') stat.draw = ++stat.draw updateStat() } changePlayer() } else { alert('ячейка занята') } }) } function changePlayer() { if (player === 'x') { player = 'y' setPlayer.innerHTML = player } else { player = 'x' setPlayer.innerHTML = player } } function checkWin() { for (let i = 0;i < winIndex.length;i++) { if (data[winIndex[i][0]] === 'x' && data[winIndex[i][1]] === 'x' && data[winIndex[i][2]] === 'x') { return true; } if (data[winIndex[i][0]] == 'y' && data[winIndex[i][1]] == 'y' && data[winIndex[i][2]] == 'y') { return true; } } return false } function updateStat() { winX.innerHTML = stat.winX winY.innerHTML = stat.winY draw.innerHTML = stat.draw }
import YearPanel from './Panel'; export { YearPanel, };
const fs = require('fs'); const path = require('path'); const utility = require('./utility'); const startTime = Date.now(); const timestamp = utility.getTimestamp(startTime); let execId = `${timestamp}_supply_`; const info = { 'Base directory': null, 'Base file count': null, 'Base symbolic link count': null, 'Target directory': null, 'Target file count': null, 'Target symbolic link count': null, 'Forced': null, 'Extra directory': null, 'Records': [], 'Time': null }; const main = async () => { if (!fs.existsSync('./logs')) { fs.mkdirSync('./logs'); } if (!fs.existsSync('./extra')) { fs.mkdirSync('./extra'); } // node supply ${dir_path} ${dir_path} -s ${sign} ${-F} -dp ${dir_path} const [ , , testBaseDpath, testTargetDpath, ...options ] = process.argv; const baseDpath = path.resolve(testBaseDpath); if (!fs.existsSync(baseDpath) || !fs.lstatSync(baseDpath).isDirectory()) { throw new Error(`Not directory. "${baseDpath}"`); } const targetDpath = path.resolve(testTargetDpath); if (!fs.existsSync(targetDpath) || !fs.lstatSync(targetDpath).isDirectory()) { throw new Error(`Not directory. "${targetDpath}"`); } if (baseDpath === targetDpath) { throw new Error(`Same directories.`); } info['Base directory'] = baseDpath; info['Target directory'] = targetDpath; const isForced = options.includes('-F'); info['Forced'] = isForced; const sign = utility.getOptionValue('-s', options); execId += (sign !== undefined && sign !== null && sign !== '') ? sign : `${path.basename(baseDpath).toUpperCase()}_${path.basename(targetDpath).toUpperCase()}`; const testDestinationDpath = utility.getOptionValue('-dp', options); const extraDpath = ( testDestinationDpath === undefined || testDestinationDpath === null || testDestinationDpath.length === 0 ) ? path.resolve('./extra', `${execId}`) : path.resolve(testDestinationDpath); if (fs.existsSync(extraDpath)) { if (!fs.lstatSync(extraDpath).isDirectory() || 0 < fs.readdirSync(extraDpath).length) { throw new Error(`Can not create. "${extraDpath}"`); } } else { if (isForced) { fs.mkdirSync(extraDpath); } } info['Extra directory'] = isForced ? extraDpath : null; const digestSet = new Set(); const baseFpaths = utility.getFilePaths(baseDpath); info['Base file count'] = baseFpaths.length; for (let i = 0; i < baseFpaths.length; i++) { const testPath = baseFpaths[i]; const digest1 = await utility.getFileDigest(testPath, 'md5'); const digest2 = await utility.getFileDigest(testPath, 'sha1'); const digest = `${digest1}_${digest2}`; digestSet.add(digest); } const omittedFpaths = []; const targetFpaths = utility.getFilePaths(targetDpath); info['Target file count'] = targetFpaths.length; for (let i = 0; i < targetFpaths.length; i++) { const testPath = targetFpaths[i]; const digest1 = await utility.getFileDigest(testPath, 'md5'); const digest2 = await utility.getFileDigest(testPath, 'sha1'); const digest = `${digest1}_${digest2}`; if (!digestSet.has(digest)) { const omittedFpath = utility.omitPath(testPath, targetDpath); omittedFpaths.push(omittedFpath); } } for (let i = 0; i < omittedFpaths.length; i++) { const omittedFpath = omittedFpaths[i]; const oldFpath = path.resolve(targetDpath, omittedFpath); const newFpath = path.resolve(extraDpath, omittedFpath); if (isForced) { const parentDpath = path.dirname(newFpath); fs.mkdirSync(parentDpath, { recursive: true }); fs.copyFileSync(oldFpath, newFpath); } info['Records'].push(omittedFpath); } const baseSlpaths = utility.getSymbolicLinkPaths(baseDpath); info['Base symbolic link count'] = baseSlpaths.length; const targetSlpaths = utility.getSymbolicLinkPaths(targetDpath); info['Target symbolic link count'] = targetSlpaths.length; }; main(). catch(e => console.error(e.stack)). finally(() => { info['Time'] = Date.now() - startTime; const logFpath = path.resolve('./logs', `${execId}.json`); fs.writeFileSync(logFpath, JSON.stringify(info, null, 2)); console.log(`End. Time: ${Date.now() - startTime}`); });
define([ 'AppView', 'text!./Checklist.html', 'text!./ChecklistItem.html' ], function( AppView, template, checklistItem ) { var ChecklistView = AppView.extend({ start : function() { this.setReady(true); }, render : function() { this.applyTemplate(template); this.sectionTag = $(this.el)[0].children[0]; this.displayChecklist(this.checklistData); }, setData: function (data) { this.checklistData = data; }, getValues: function () { console.log('checklist values'); }, displayChecklist: function(checklistData) { var checklist = checklistData.checklist, checklistDataLength = checklist.length, checklistName = checklistData.checklistName, i; // Create title header var headerDiv = document.createElement('div'); $(headerDiv).html(checklistData.listTitle); $(headerDiv).addClass('checklist-header'); $(this.sectionTag).append(headerDiv); // Create info text var infoDiv = document.createElement('div'); $(infoDiv).html(checklistData.listDescription); $(infoDiv).addClass('checklist-info'); $(this.sectionTag).append(infoDiv); for (i = 0; i < checklistDataLength; i++) { checklist[i].itemNumber = i; checklist[i].checklistName = checklistName; var newChecklistItem = _.template(checklistItem, checklist[i]); $(this.sectionTag).append(newChecklistItem); } } }); return ChecklistView; });
#! /usr/bin/env node const { program } = require('commander') const list = require('./commands/list') const contacts = require('./commands/contacts') program .command('list') .description('List all the available modules to interact with') .action(list); program .command('contacts') .description('Output the test function from neighbor module.') .action(contacts); program.parse();
var helper = require(__dirname + '/../helper'); module.exports = { /** * GET - 競技名リストの取得 */ find: function (req, res) { helper.db().query('SELECT * FROM competitionName;', function(err, rows, fields) { if (err) { res.status(500).send(err.toString()); return; } res.send(rows); }); }, /** * GET - 競技名の取得 */ findById: function (req, res) { var id = req.params.id; if (id == null) { res.status(400).send('id parameter is required.'); return; } helper.db().query('SELECT * FROM competitionName, team WHERE competitionName.id = ? AND competitionName.teamId = team.id;', [id], function(err, rows, fields) { if (err) { res.status(500).send(err.toString()); return; } if (rows.length <= 0) { res.status(404).send('Could not find item.'); return; } res.send(rows[0]); }); }, /** * GET - 競技名の作成 */ create: function (req, res) { helper.db().query('INSERT INTO competitionName SET ?', req.body, function (err, result) { if (err) { res.status(500).send(err.toString()); return; } res.send({ id: result.insertId }); }); }, /** * GET - 競技名の作成 */ update: function (req, res) { var id = req.params.id; if (id == null) { res.status(400).send('id parameter is required.'); return; } helper.db().query('UPDATE competitionName SET ? WHERE id = ?', [req.body, id], function (err, result) { if (err) { res.status(500).send(err.toString()); return; } res.send('Updated ' + result.affectedRows + ' items.'); }); }, /** * DELETE - 競技名の削除 */ delete: function (req, res) { var id = req.params.id; if (id == null) { res.status(400).send('id parameter is required.'); } helper.db().query('DELETE FROM competitionName WHERE id = ?;', [id], function(err, result) { if (err) { res.status(500).send(err.toString()); return; } res.send('Deleted ' + result.affectedRows + ' items.'); }); } };
module.exports = { width: 1380, height: 1047, remap: false, CRTFade: true, background: "black", elements:{ "#bg":{ "src":"Pipboy3000_MarkIV.jpg", "style":"mix-blend-mode: screen" }, "#screen":{ style:` top: 26%; height: 22.92%; left: 22%; width: 35%; filter: sepia(100%) hue-rotate(12deg) saturate(100); ` }, "led.tx":{ style:{ top: "85%", left: "22%", width: "4%" } }, "led.rx":{ style:{ top: "85%", left: "19%", width: "4%" } }, "#ABM":{ style:{ width: "15%", height: "9%", top: "84%", left: "19%", display: "none" } }, "#DBG":{ style:{ width: "21%", height: "10%", bottom: 0, left: "41%" } } } };
import React from 'react' import { getNotes } from '../services/noteServices'; import Card from '@material-ui/core/Card'; import { MuiThemeProvider, createMuiTheme, InputBase } from '@material-ui/core'; // import AddAlertOutlinedIcon from '@material-ui/icons/AddAlertOutlined'; import ImageOutlinedIcon from '@material-ui/icons/ImageOutlined'; // import PersonAddOutlinedIcon from '@material-ui/icons/PersonAddOutlined'; // import UndoOutlinedIcon from '@material-ui/icons/UndoOutlined'; // import RedoOutlinedIcon from '@material-ui/icons/RedoOutlined'; import ColorComponent from '../components/colorComponent'; import { changeColorNotes } from '../services/noteServices'; import Dialog from '@material-ui/core/Dialog'; import DialogContent from '@material-ui/core/DialogContent'; import Button from '@material-ui/core/Button'; import DialogContentText from '@material-ui/core/DialogContentText'; import { updateNotes } from '../services/noteServices'; import MoreComponent from '../components/moreComponent'; import Tooltip from '@material-ui/core/Tooltip'; import ArchiveComponent from '../components/archiveComponent'; import Chip from '@material-ui/core/Chip'; import ReminderNoteComponent from '../components/reminderNotesComponent'; import { removeLabelToNotes } from '../services/noteServices'; import { withRouter } from 'react-router-dom'; import { removeReminderNotes } from '../services/noteServices'; import CollaboratorComponent from '../components/collaboratorComponent'; import AccountCircleIcon from '@material-ui/icons/AccountCircle'; import Avatar from '@material-ui/core/Avatar'; import ClearIcon from '@material-ui/icons/Clear'; import Divider from '@material-ui/core/Divider'; import { removeCollaboratorsNotes } from '../services/noteServices'; import MenuItem from '@material-ui/core/MenuItem'; const theme = createMuiTheme({ overrides: { MuiSvgIcon: { root: { color: "rgba(0, 0, 0, 0.54)", fontSize: "20px" } }, MuiCard: { root: { boxShadow: "3px 4px 11px 1px lightgrey" } }, MuiBackdrop: { root: { backgroundColor: "transparent" } }, MuiDialog: { paperWidthSm: { boxShadow: "3px 1px 4px 2px rgb(206, 206, 206)", width: "36%", '@media (min-width: 300px)': { width: " 80%", marginTop: " 53 %" } } }, MuiPaper: { rounded: { borderRadius: "11px" } } } }) function searchFunction(searchValue) { return function (x) { return x.title.includes(searchValue) || x.description.includes(searchValue) } } class GetNoteComponent extends React.Component { constructor(props) { super(props) this.state = { getNoteData: [], open: false, noteId: "", title: "", description: "", Id: [], lableId: "", noteIdList: "", color: "", dialogOpen: false, mail: "" } // this.handleUpdateCard = this.handleUpdateCard.bind(this) } componentWillMount() { this.getNotes() } getNotes = () => { getNotes() .then(response => { console.log("response in get note---->", response.data.data.data) //console.log("response in get note id ---->", response.data.data.data.id) this.setState({ getNoteData: response.data.data.data, // id: response.data.data.data.id }) }) } handleGetColor = (value, noteID) => { // console.log("response in getNotes for color and id--->", value) var data = { noteIdList: [noteID], color: value, } //console.log("response in getNotes for color and id--->",color) changeColorNotes(data) .then(response => { console.log("response in getNotes for color and id--->", response) this.getNotes() }) } handleClickOpen = () => { this.setState({ open: true }) // console.log("dialog details--->", this.state.open) } handleClose = () => { this.setState({ open: false }) } handleUpdateCard = (id, oldTitle, oldDescription, color) => { this.setState({ // open: false, noteId: id, title: oldTitle, description: oldDescription, color: color, }) console.log("data for updation", this.state.noteId, this.state.title, this.state.description, this.state.color); var data = { noteId: this.state.noteId, title: this.state.title, description: this.state.description, color: this.state.color } console.log("data in update note--->", data) updateNotes(data) .then(response => { console.log("response of update details--->", response) this.getNotes() }) .catch(err => { console.log("err while updating", err); }) } handleTitle = (e) => { this.setState({ title: e.target.value, }) console.log("title updation", this.state.title); } handledescription = (e) => { this.setState({ description: e.target.value, }) console.log("description updation", this.state.description); } displayNote = (cardDetails) => { console.log("data in carddetails", cardDetails) this.setState({ getNoteData: [...this.state.getNoteData, cardDetails] }) } presentData = (updateNote) => { if (updateNote) { this.getNotes() } } storeData = (updateNote) => { if (updateNote) { this.getNotes() } } labelData = (updateNote) => { if (updateNote) { this.getNotes() } } reminderData = (updateNote) => { if (updateNote) { this.getNotes() } } collaboratorData = (updateNote) => { if (updateNote) { this.getNotes() } } handeChipLabel = (noteId, lableId) => { var data = { noteId: noteId, lableId: lableId } removeLabelToNotes(data, noteId, lableId) .then(response => { console.log("label in note --->", response); this.getNotes() }) } handeChipReminder = (noteID) => { var data = { noteIdList: [noteID] } removeReminderNotes(data) .then(response => { console.log("response in removeing remainder Notes", response); this.getNotes() }) } handleOpen = (email) => { // console.log("colla62email); this.setState({ dialogOpen: true, mail: email }) console.log("collaborator state", this.state.mail); } handleClose = () => { this.setState({ dialogOpen: false }) } handleCancel = (noteId, userId) => { console.log("response in remove collaborator in getnotes", noteId, userId); removeCollaboratorsNotes(noteId, userId) .then(response => { console.log("response in remove collaborator getnotes", response); this.getNotes() }) } // handleQuestionPage = () => { // this.props.history.push('/draftEditorPage') // } handleQuestionAsked = async (title, description, noteId, question, parentId) => { await this.setState({ arr: [title, description, noteId, question, true, parentId] }) console.log("props in morecomponent", this.state.arr); this.props.history.push(`/draftEditorPage/${parentId}`, this.state.arr) } render() { console.log("dataaaaaaaaaaaaaaa", this.state.color); var list = this.props.gridViewProps ? "noteList" : null var getNoteDetails = this.state.getNoteData.map((key, index) => { //console.log("data in key-->", key) //console.log("data in indexfffffff-->", key.questionAndAnswerNotes.message) console.log("keyyyyyyyyyyyyyyy--->", key.questionAndAnswerNotes); return ( (((key.isArchived === false) && key.isDeleted === false) && <MuiThemeProvider theme={theme}> <div className="card-note" id={list} > <Card className="Cardscss" style={{ backgroundColor: key.color }} id={list} > <div className="getNotes-align" onClick={this.handleClickOpen}> <InputBase placeholder="title" value={key.title} multiline onClick={() => this.handleUpdateCard(key.id, key.title, key.description, key.color)} /> </div> <div className="getNotes-align" onClick={this.handleClickOpen}> <InputBase placeholder="take a note....." value={key.description} multiline onClick={() => this.handleUpdateCard(key.id, key.title, key.description, key.color)} /> </div> <div style={{ margin: "7px" }}> {key.noteLabels.map(LabelKey => { return ( <Chip label={LabelKey.label} onDelete={() => this.handeChipLabel(key.id, LabelKey.id)} /> ) }) } </div> <div style={{ margin: "7px" }}> {key.reminder.map(reminderKey => { //console.log("key in remainder", reminderKey); return ( <Chip className="reminder-chip" label={reminderKey.split(" ").splice(0, 5)} onDelete={() => this.handeChipReminder(key.id)} /> ) })} </div> <div style={{ margin: "7px", display: "flex" }}> {key.collaborators.map(collaboratorkey => { // console.log("key in collaborator", collaboratorkey); return ( <div> <div onClick={() => this.handleOpen(collaboratorkey.email)} > <AccountCircleIcon /> </div> <div> <Dialog open={this.state.dialogOpen} onClose={this.handleClose}> <h3 style={{ padding: "1px 1px 1px 10px" }}>Collaborators</h3> <Divider /> <div className="email-css"> <div><Avatar>R</Avatar></div> <div><h3 style={{ padding: "1px 1px 0px 16px" }}>{localStorage.getItem("Email")}</h3></div> </div> <MenuItem><div style={{ display: " flex" }}> <div> <AccountCircleIcon /></div> <div>{this.state.mail}</div> <div onClick={() => this.handleCancel(key.id, collaboratorkey.userId)} style={{ padding: "1px 1px 1px 143px" }}> <ClearIcon /></div> </div></MenuItem> <div onClick={this.handleClose}> <Button>Close</Button> </div> </Dialog> </div> </div> ) })} </div> <div className="align-icons"> <MuiThemeProvider theme={theme}> <ReminderNoteComponent reminderProps={this.reminderData} // getReminderProps={this.getReminder} noteID={key.id} /> <Tooltip title="Collabarator"> <CollaboratorComponent collaboratorProps={this.collaboratorData} noteID={key.id} collaboratorkey={key.userId} /> </Tooltip> <ColorComponent colorComponentProps={this.handleGetColor} noteID={key.id}></ColorComponent> <Tooltip title="Add image"> <ImageOutlinedIcon /> </Tooltip> <ArchiveComponent archiveData={this.storeData} noteID={key.id}></ArchiveComponent> <MoreComponent deletingData={this.presentData} propsValue={this.labelData} noteID={key.id} noteTitle={key.title} noteDescription={key.description} questionAndAnswerProps={key.questionAndAnswerNotes} ></MoreComponent> </MuiThemeProvider> </div> {key.questionAndAnswerNotes.length > 0 && //console.log("ujhhhhhhhh--------->", key.questionAndAnswerNotes[0].message) <div onClick={() => this.handleQuestionAsked(key.title, key.description, key.id, key.questionAndAnswerNotes[0].message, key.questionAndAnswerNotes[key.questionAndAnswerNotes.length - 1].id)} getlikeProps={key.questionAndAnswerNotes}> <Divider /> <h3>Question Asked</h3> <div dangerouslySetInnerHTML={{ __html: key.questionAndAnswerNotes[0].message }}></div> </div> } </Card> </div> {(this.state.noteId === key.id) && <div> <Dialog open={this.state.open} onClose={this.handleClose} > <DialogContent style={{ backgroundColor: key.color }} > <DialogContentText id="alert-dialog-description"> <div> <InputBase placeholder="title" value={this.state.title} onChange={this.handleTitle} className="titleDescInput" /> </div> <div> <InputBase placeholder="take a note....." value={this.state.description} onChange={this.handledescription} /> </div> </DialogContentText> </DialogContent> <div className="update-icons" style={{ backgroundColor: key.color }}> <MuiThemeProvider theme={theme}> <ReminderNoteComponent reminderProps={this.reminderData} noteID={key.id} /> <Tooltip title="Collabarator"> <CollaboratorComponent collaboratorProps={this.collaboratorData} noteID={key.id} collaboratorkey={key.userId} /> </Tooltip> <ColorComponent colorComponentProps={this.handleGetColor} noteID={key.id}></ColorComponent> <Tooltip title="Add image"> <ImageOutlinedIcon /> </Tooltip> <ArchiveComponent archiveData={this.storeData} noteID={key.id}></ArchiveComponent> <MoreComponent deletingData={this.presentData} labelNoteProps={this.labelData} noteID={key.id} noteTitle={key.title} noteDescription={key.description} ></MoreComponent> </MuiThemeProvider> </div> <div className="dialog-Button" style={{ backgroundColor: key.color }} > <Button onClick={this.handleUpdateCard} color="primary"> Close </Button></div> </Dialog> </div> } </MuiThemeProvider> ) ) }) return ( <div className="getnote-Card" > {getNoteDetails} </div> ) } } export default withRouter(GetNoteComponent) // <div dangerouslySetInnerHTML={{ __html: "<h1>Hi there!</h1>" }} /> //
import React from "react"; import { Link } from "react-router-dom"; function ArticlesNav({ backgroundPrev, titlePrev, linkPrev, noMorePrev, backgroundNext, titleNext, linkNext, noMoreNext, }) { return ( <> <section id="sectionArticlesNav"> <div className="row"> <Link to={noMorePrev === "done" ? "/" : `single-news-${linkPrev}`} onClick={(event) => { noMorePrev === "done" && event.preventDefault(); }} className={ noMorePrev === "done" ? `col-12 col-md-6 news-prev news-nav-box news-last anim-bot` : `col-12 col-md-6 news-prev news-nav-box anim-bot` } style={{ backgroundImage: `url(/assets/images/${backgroundPrev})` }} > <div className="news-nav-overlay"></div> {noMorePrev === "done" ? ( <div> <h1 className="big-title next-grey">No more articles</h1> <h3>This is the first article.</h3> </div> ) : ( <div> <h1 className="big-title">Previous article</h1> <h3>{titlePrev}</h3> </div> )} </Link> <Link to={noMoreNext === "done" ? "/" : `single-news-${linkNext}`} onClick={(event) => { noMoreNext === "done" && event.preventDefault(); }} className={ noMoreNext === "done" ? `col-12 col-md-6 news-next news-nav-box news-last anim-bot` : `col-12 col-md-6 news-next news-nav-box anim-bot` } style={{ backgroundImage: `url(/assets/images/${backgroundNext})` }} > <div className="news-nav-overlay"></div> {noMoreNext === "done" ? ( <div> <h1 className="big-title next-grey">No more articles</h1> <h3>This is the last article.</h3> </div> ) : ( <div> <h1 className="big-title">Next article</h1> <h3>{titleNext}</h3> </div> )} </Link> </div> </section> </> ); } export default ArticlesNav;
mapboxgl.accessToken = 'pk.eyJ1Ijoic2FyZXdlcyIsImEiOiJjamx2bzRubWkweXpiM3FwZXZ2ZWxxYTZkIn0.acBKDYn4ACmB6R0Fr5Mvjw'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11' });
import React from 'react'; import { Link } from 'react-router'; import {getPostDetails, searchPosts} from '../actions/postAction'; import {addComment, likePost, deletePostPhoto} from '../actions/groupListAction'; import {deletePost, deleteComment} from '../actions/eventDetailsAction'; import {connect} from 'react-redux'; import Spinner from 'react-spinner'; import {bindActionCreators} from 'redux'; import {isValidImage} from "../utils/Validation"; import {SERVICE_URLS} from '../constants/serviceUrl'; import {isExistObj} from '../utils/functions'; class FeedPage extends React.Component { constructor(props){ super(props); this.state={ posts: Object.assign([], props.postList), ajaxCallInProgress:false, cimgArray:'', imgId:'',pImgId:'', commentId:'', ajax:false, postId:'' }; } componentWillMount(){ this.setState({ajaxCallInProgress:true}); this.props.getPostDetails(this.props.activeUser.token).then(()=>{ this.setState({posts:this.props.postList.feedPosts, ajaxCallInProgress:false}); $(".imgSpinner").hide(); }).catch((error)=>{ if(error == "Error: Request failed with status code 401"){ this.context.router.push('/'); } this.setState({ajaxCallInProgress:false}); }); } Comment(postsId){ let commentTextBox=(postsId + "_txtComment"); let commentSection=(postsId+"_commentSection"); let innerDescValue = document.getElementById(commentTextBox).value.replace(new RegExp('\r?\n','g'), '<br />'); let body; _.set( body, innerDescValue); let imgArray={}; let imgId=[]; for(var i=0;i<_.size(this.state.cimgArray);i++){ imgArray=this.state.cimgArray[i]; imgId.push(imgArray.id); } if(innerDescValue == ""){ $("#"+commentTextBox).focus(); } else{ //$('#'+postsId).prop('disabled', true); $("#"+postsId+"_imgSpinner").show(); $("#"+postsId+"_commentSection").hide(); this.props.addComment(postsId, this.props.activeUser.token, innerDescValue, imgId).then(()=>{ $('textarea#'+ postsId + '_txtComment').val(''); //$('#'+ postsId + "_txtComment").innerText(); this.getPostsDetails(); $("#"+postsId+"_imgSpinner").hide(); $("#"+postsId+"_commentSection").show(); this.setState({cimgArray:''}); }).catch((error)=>{ }); } } getPostsDetails(){ this.props.getPostDetails(this.props.activeUser.token).then(()=>{ this.setState({posts:this.props.postList.feedPosts, ajaxCallInProgress:false}); }).catch((error)=>{ this.setState({ajaxCallInProgress:false}); }); } componentDidMount() { $(".imgSpinner").hide(); $('.menu').parent().removeClass('active'); $('#feed').parent().addClass('active'); } onPostSearch(e){ if(e.which==13) { this.props.searchPosts(this.props.activeUser.token, e.target.value).then(()=>{ this.setState({posts:this.props.postList.PostList}); }).catch((error)=>{ }); } } onPostSearchIcon(){ // let searchTxtValue = document.getElementById('searchCriteriaText').value; let searchTxtValue = this.refs.searchCriteriaText.value; this.props.searchPosts(this.props.activeUser.token, searchTxtValue).then(()=>{ this.setState({posts:this.props.postList.PostList}); }).catch((error)=>{ }); } onLikeClick(id){ this.props.likePost(this.props.activeUser.token, id).then(()=>{ this.getPostsDetails(); }).catch((error)=>{ }); } focusOnCommentBox(id){ /* $('#'+ id + "_commentSection").toggle(); // $('#'+ id + "_commentText").css("color", "green"); // $('#'+ id).toggle(); $('#'+id).prop('disabled', false);*/ $('#'+ id + "_txtComment").focus(); } postDelModal(id){ $("#modalPostDelet").modal('show'); this.setState({postId:id}); } deletePost(){ let id=this.state.postId; this.props.deletePost(id, this.props.activeUser.token).then(()=>{ this.getPostsDetails(); }).catch((error)=>{ }); } setCommentId(id){ $("#modalCommentDlt").modal('show'); this.setState({commentId:id}); } deleteComments(id){ let cId=this.state.commentId; this.props.deleteComment(id, cId, this.props.activeUser.token).then(()=>{ this.getPostsDetails(); }).catch((error)=>{ }); } getFileExtension(name){ var found = name.lastIndexOf('.') + 1; return (parseInt(found) > 0 ? name.substr(found) : ""); } commentImage(id){ $("#"+id+"_imgSpinner").addClass("display:none"); $("#"+id+"_imgSpinner").show(); $("#"+id+"_commentSection").hide(); var that = this; var imagesArray = new FormData(); $.each($('#commentFile')[0].files, function(i, file) { imagesArray.append('images', file); }); let fileExtention = this.getFileExtension(document.getElementById('commentFile').files[0].name); if(isValidImage(fileExtention)){ $.ajax({ url: SERVICE_URLS.URL_USED+'api/posts/comment-upload-images/', data: imagesArray, processData: false, contentType: false, type: 'POST', headers:{ 'Authorization':'Token '+ this.props.activeUser.token }, success: function(data){ that.setState({cimgArray:data}); $("#"+id+"_imgSpinner").hide(); $("#"+id+"_commentSection").show(); }, error: function(error){ console.log("err",error); //that.setState({selectedScoreId:null}); $("#"+id+"_imgSpinner").hide(); $("#"+id+"_commentSection").show(); } }); } else{ $("#"+id+"_imgSpinner").hide(); $("#"+id+"_commentSection").show(); toastr.error('Upload a valid Image'); } } /*deletePostImage(id){ this.props.deletePostPhoto(this.props.activeUser.token, id).then(()=>{ this.getPostsDetails(); }).catch((error)=>{ }); }*/ postImage(id){ var that = this; var imagesArray = new FormData(); $.each($('#postFile')[0].files, function(i, file) { imagesArray.append('images', file); }); let fileExtention = this.getFileExtension(document.getElementById('postFile').files[0].name); if(isValidImage(fileExtention)){ $.ajax({ url: SERVICE_URLS.URL_USED+'api/posts/'+id+'/gallery', data: imagesArray, processData: false, contentType: false, type: 'POST', headers:{ 'Authorization':'Token '+ this.props.activeUser.token }, success: function(data){ //that.setState({imgArray:data}); that.getPostsDetails(); }, error: function(){ //that.setState({selectedScoreId:null}); } }); } else{ toastr.error('Upload a valid Image'); } } deletePostImage(){ let id=this.state.pImgId; this.props.deletePostPhoto(this.props.activeUser.token, id).then(()=>{ $('#deletecImageModal').modal('hide'); this.getPostsDetails(); }).catch((error)=>{ }); } deleteCommtenImage(){ $('#deleteImageModal').modal('hide'); let id=this.state.imgId; this.props.deletePostPhoto(this.props.activeUser.token, id).then(()=>{ this.getPostsDetails(); }).catch((error)=>{ }); } checkId(id){ this.setState({imgId:id}); $('#deleteImageModal').modal('show'); } setpImgId(id){ this.setState({pImgId:id}); $("#deletecImageModal").modal('show'); } render() { return ( <div className="feedPage"> <div className="pageFeed col-sm-12 pdryt0px"> <div className="feedcntnt col-sm-12"> <div className="img-cntnt col-sm-12"> <div className="cover-img col-sm-12 zeroPad"><img src="/assets/img/feedImg (1).png" className="feedImg col-sm-12 zeroPad" /></div> <div className="img-feed col-sm-12"> <h3 className="col-sm-8">Feed</h3> <span className="search-feed col-sm-4 zeroPad"> <div className="col-sm-12 pdlft0px"> <input type="search" ref="searchCriteriaText" placeholder="Search Feed" className="searching col-sm-11" onKeyPress={this.onPostSearch.bind(this)}/> <button className="search-btn col-sm-1" onClick={this.onPostSearchIcon.bind(this)} > <span className="searchbtn-img"><img src="/assets/img/icons/Search_Icon.png"/></span> </button> </div> </span> </div> </div> <div className="col-sm-12 mt22px pdlftryt0px"> {(this.state.ajaxCallInProgress)?(<div className="col-sm-12 bgwhite"><Spinner /></div>):( <div> {isExistObj(this.state.posts) && _.size(this.state.posts)>0 ? this.state.posts.map((item,i)=>{ return(<div className="users col-sm-12" key={i}> <div className="user1 pdlft0px pdngryt0px col-xs-12 pdlftryt0px col-sm-12"> <div className="col-sm-12 zeroPad"> <div className="col-sm-1 col-xs-1 wd6pc dsplyInln"> <img className="Harvey-img" src={'http://'+item.author.profile_image_url} /></div> <div className="user1-header col-sm-6 col-xs-6"> <h3><Link to={item.author.id==this.props.activeUser.id?"/profile_0":"/profileDetail_"+item.author.id}>{item.author.first_name} {item.author.last_name}</Link></h3> <span> {item.object_name!=null?item.object_type=="Group"?<b>Posted on {item.object_type} <Link to={"groupMembers_" + item.object_id}><span className="txtUnderline text_overflow"> {item.object_name} </span></Link> </b>:item.object_type=="Course"?<b>Posted on {item.object_type} <Link to={"forumCourse_" + item.object_id}><span className="txtUnderline text_overflow"> {item.object_name} </span></Link> </b>:<b>Posted on {item.object_type} <Link to={"/events_"+item.object_id}><span className="txtUnderline text_overflow"> {item.object_name} </span></Link> </b>:''} </span> </div> <div className="col-sm-5 dsplyInln zeroPad feedRyt txtRyt"> <p className="ryt">{item.created} <br/>{item.created_since}</p> </div> </div> <div className="tglng"> <div className="user1-spl word-break"> {this.props.activeUser.id==item.author.id?<span className="glyphicon glyphicon-trash fr cursor-pointer mt1pc marTop10px" data-toggle="modal" onClick={this.postDelModal.bind(this,item.id)}></span>:''} <h3>{item.title}</h3> </div> <div className="modal fade" id="modalPostDelet" role="dialog" data-dropback="static"> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header modalHder"> <h4>Delete Post</h4> </div> <div className="modal-body"><p className="pdleft15px">Are you sure you want to delete?</p></div> <div className="modal-footer txtRight zeroPad"> <button type="button" className="cnfrmbtn checkng" data-dismiss="modal"onClick={this.deletePost.bind(this)} >Yes</button> <button type="button" className="cancelbtn checkng" data-dismiss="modal">No</button> </div> </div> </div> </div> {item.body!=null?<div> <h4 className="detil">Details</h4> <p className="xplin">{item.body}</p> </div>:<div></div>} </div> <div className="user-footer"> <div className="col-sm-12 rspnsng"> {/* <img src="/assets/img/Camera Icon.png" className="fr mr4_5pc" /> <input type="file" id="postFile" name="postFile" className="postCameraImg" onChange={this.postImage.bind(this,item.id)} multiple/>*/} <div className="col-sm-12"> {isExistObj(item) && isExistObj(item.images) && _.size(item.images)>0? item.images.map((imgItem,i)=>{ return( <div className="col-sm-2 postImgDiv"> <img src={"http://"+imgItem.image} className="img-thumbnail wd120px hgt120px"/> <i className="glyphicon glyphicon-remove top-55px cursor-pointer color-black" onClick={this.setpImgId.bind(this,imgItem.id)} data-toggle="modal" ></i> <div className="modal fade" id="deletecImageModal" role="dialog"> <div className="modal-dialog modal-sm"> <div className="modal-content"> <div className="modal-header modalHder"> <button type="button" className="close" data-dismiss="modal">&times;</button> <h4 className="modal-title">Delete Photo</h4> </div> <div className="modal-body"> <p className="pdleft15px">Are you sure you want to delete this photo?</p> </div> <div className="modal-footer"> <button type="button" className="checkng" data-dismiss="modal">No</button> <button type="button" className="checkng" onClick={this.deletePostImage.bind(this)}>Yes</button> </div> </div> </div> </div> </div> ); }):''} </div> <div className="col-sm-8"></div> <div className="col-sm-4 pdng"> <div className="col-sm-12 pdng"> <span onClick={this.onLikeClick.bind(this, item.id)} className={(item.has_like)?"like color-green":"like"}><span className={(item.has_like)?("rspnsImg glyphicon glyphicon-heart color-green"):("rspnsImg glyphicon glyphicon-heart ")}></span>Like (<span className="likingNumber">{item.likes_count}</span>)</span> <span className="cursor-pointer" id={item.id+"_commentText"} onClick={this.focusOnCommentBox.bind(this, item.id)} className="comment"><img src="/assets/img/icons/comment.png" className="rspnsImg"/>Comment</span> </div> </div> </div> <span className="footer4"> <span className="butn-err" data-toggle="modal" data-target=""> </span> </span> <div className="modal fade secondModal" id="myModal" role="dialog" data-backdrop="static"> <div className="modal-dialog modal-sm"> <div className="modal-content"> <div className="modal-body"> <div className="checkbox"> <input type="checkbox" value="1" id="checkboxInput" name="" />Hide/DeletePost </div> <div className="checkbox"> <input type="checkbox" value="1" id="checkboxInput" name="" />Block </div> <div className="checkbox"> <input type="checkbox" value="1" id="checkboxsInput" name="" />Report </div> <div className="reason">Reason for reporting</div> <textarea className="txtarea form-control" maxLength="200" name="txtArea"></textarea> </div> <div className="modal-footer"> <button type="button" className="butnPrimary" id="btnSubmit">Submit</button> <button type="button" className="butnSecondary" data-dismiss="modal">Cancel</button></div> </div> </div> </div> </div> {isExistObj(item) && isExistObj(item.comments) && _.size(item.comments)>0 && item.comments.map((childItem, childIndex)=>{ return(<div key={childIndex} className="col-sm-12 col-xs-12 mt-6pc" > <div className="modal fade" id="modalCommentDlt" role="dialog" data-dropback="static"> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header modalHder"> <button type="button" className="close" data-dismiss="modal">&times;</button> <h4 className="textMargin">Delete comment</h4> </div> <div className="modal-body"> <p className="pdleft15px">Are you sure you want to delete?</p> </div> <div className="modal-footer zeroPad"> <button type="button" className="cancelbtn checkng" data-dismiss="modal">No</button> <button type="button" className="cnfrmbtn checkng" data-dismiss="modal" onClick={this.deleteComments.bind(this,item.id)}>Yes</button> </div> </div> </div> </div> <div className="col-sm-12 col-xs-12 mt3pc pdryt0px"> {this.props.activeUser.id==childItem.author.id || this.props.activeUser.id==item.author.id?<span className="glyphicon glyphicon-trash fr cursor-pointer mt1pc top40px zIndex1" data-toggle="modal" onClick={this.setCommentId.bind(this,childItem.id)}></span>:''} <div className="col-sm-1 col-xs-2"> <div className=""><img src={'http://'+childItem.author.profile_image_url} className="rplyImg"/></div> </div> <div className="col-sm-9 col-xs-7 feedRply"> <div className="col-sm-12 prsnName"> <Link to={childItem.author.id==this.props.activeUser.id?"/profile_0":"/profileDetail_"+childItem.author.id}>{childItem.author.first_name} {childItem.author.last_name}</Link> </div> <div className="col-sm-12 prsnSent"> {childItem.created} </div> </div> <div className="col-sm-12 col-xs-12 mt1pc "> <div className="pstReply col-sm-12"> <p dangerouslySetInnerHTML={{__html: childItem.body}} ></p> </div> <div className="col-sm-12"> {isExistObj(childItem) && isExistObj(childItem.images) && _.size(childItem.images)>0? childItem.images.map((cimgItem,i)=>{ return( <div className="col-sm-2 postImgDiv"> <img src={"http://"+cimgItem.image} className="img-thumbnail wd120px hgt120px"/> {this.props.activeUser.id==childItem.author.id || this.props.activeUser.id==item.author.id?<i className="glyphicon glyphicon-remove top-55px cursor-pointer" data-toggle="modal" onClick={this.checkId.bind(this,cimgItem.id)} ></i>:''} <div className="modal fade" id="deleteImageModal" role="dialog"> <div className="modal-dialog modal-sm"> <div className="modal-content"> <div className="modal-header modalHder"> <button type="button" className="close" data-dismiss="modal">&times;</button> <h4 className="modal-title">Delete Photo</h4> </div> <div className="modal-body"> <p className="pdleft15px">Are you sure you want to delete this photo?</p> </div> <div className="modal-footer"> <button type="button" className="checkng" data-dismiss="modal">No</button> <button type="button" className="checkng" onClick={this.deleteCommtenImage.bind(this)}>Yes</button> </div> </div> </div> </div> </div> ); }):''} </div> </div> </div> </div>) })} <div className="col-sm-12 bgwhite imgSpinner" id={item.id+"_imgSpinner"} ><Spinner /></div> <div id={item.id+ "_commentSection"} className="" > <div className="cmnt-matter"> <textarea type="text" maxLength="250" className="txtarea form-control" placeholder="Write Something..." id={item.id+ "_txtComment"}></textarea> <img src="/assets/img/Camera Icon.png" className="fr cameraCommentImg" /> <input type="file" id="commentFile" name="commentFile" className="commentCameraImg" onChange={this.commentImage.bind(this,item.id)} /> </div> <div> <input type="button" id={item.id} value="Add Comment" className="btnAddComment" onClick={this.Comment.bind(this, item.id)}/> </div> </div> </div> </div>) }):<div className=" users col-sm-12">There are no posts to show.</div>} </div> )} </div> </div> </div> </div> ); } } FeedPage.contextTypes = { router: React.PropTypes.object }; function mapStateToProps(state) { return { activeUser: (state.activeUser!=null)?(state.activeUser):(JSON.parse(sessionStorage.getItem('userDetails'))), postList: state.savePost }; } function matchDispatchToProps(dispatch){ return bindActionCreators({getPostDetails, searchPosts, addComment, likePost, deletePost, deleteComment, deletePostPhoto}, dispatch); } export default connect(mapStateToProps,matchDispatchToProps) (FeedPage);
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('sw.js', {scope: './'}).then(function (registration) { console.log('Service Worker Registered Succesful'); }); navigator.serviceWorker.ready.then(function (registration) { registration.pushManager.subscribe({userVisibleOnly: true}).then(function (subscription) { var isPushEnabled = true; console.log("Push notification supported"); }) }) }
'use strict'; import '@babel/polyfill'; import 'nodelist-foreach-polyfill'; import elementClosest from 'element-closest'; elementClosest(window); import 'formdata-polyfill'; import 'fetch-polyfill'; import maskPhone from './modules/maskPhone'; import countTimer from './modules/countTimer'; import toggleMenu from './modules/toggleMenu'; import togglePopUp from './modules/togglePopUp'; import tabs from './modules/tabs'; import slider from './modules/slider'; import changeImage from './modules/changeImage'; import calc from './modules/calc'; import sendForm from './modules/sendForm'; maskPhone(".form-phone", "+7(___)_______"); countTimer("30 november 2020"); toggleMenu(); togglePopUp(); tabs(); slider(); changeImage(); calc(100); sendForm();
module.exports = function() { if (process.env.NODE === 'production') { throw new Error('Please do not use this in production.'); } };
import 'idempotent-babel-polyfill'; // import { typeCheck } from 'type-check'; import getClient from 'extended-ds-client'; import joi from 'joi'; import mapValues from 'lodash.mapvalues'; import fetch from 'node-fetch'; export const rpcSplitChar = '/'; export function typeAssert() { throw new Error('typeAssert deprecated. API spec should be joi schemas, that will be checked automatically'); } const defaultOptions = { // Reconnection procedure: R 1s R 2s R 3s ... R 8s R 8s ... reconnectIntervalIncrement: 1000, maxReconnectInterval: 8000, maxReconnectAttempts: Infinity, }; async function fetchCredentials(url) { if (this.state.closing) return undefined; try { const reply = await fetch(url); if (reply.status === 201) { return reply.json(); } } catch (err) { console.log('Will retry credentials fetch due to:', err); } return new Promise(r => setTimeout(r, 1000)).then(fetchCredentials.bind(this, url)); } async function updateCredentials() { if (this.config.credentialsUrl) { this.state.credentials = { ...this.state.credentials, ...(await this.fetchCredentials(this.config.credentialsUrl)), }; this.client._connection._authParams = this.state.credentials; } } function connectionStateChangedCallback(state) { if (state === 'RECONNECTING' && this.config.credentialsUrl && !this.state.closing) { console.log('Re-fetching credentials...'); this.updateCredentials(); } } let loopTimer; const idleLoop = () => { loopTimer = setTimeout(idleLoop, 100000); }; const createOnRpc = (spec, impl) => async (data = {}, response) => { try { const args = joi.validate(data, spec); if (args.error) { response.error(args.error.details[0].message); } else { const result = await impl(args.value); response.send(result); } } catch (err) { console.log('RPC ERROR:', err); response.error(err.message); } }; function loadApi(client, pathFunc, apiSpec, apiImpl) { Object.keys(apiSpec).forEach(f => { client.rpc.provide( pathFunc(f), createOnRpc(apiSpec[f].args.keys({ _id: joi.string() }), apiImpl[f]), ); }); } function getInterface() { return this.state.apiDesc; } function registerApi(apiSpec = {}, apiImpl) { // api: { name: spec }, impl: { name: func } const getInterfaceDescription = { description: 'Returns the interface of the service.', args: joi.object(), return: joi .object() .unknown() .pattern( joi.any(), joi.object().keys({ description: joi.string(), args: joi.object(), return: joi.object(), }), ), }; apiSpec = { ...apiSpec, getInterface: getInterfaceDescription }; apiImpl = { ...apiImpl, getInterface: this.getInterface }; const apiDesc = mapValues(apiSpec, v => ({ description: v.description, args: v.args && v.args.describe(), return: v.return && v.return.describe(), })); this.setState({ apiSpec, apiImpl, apiDesc }); } function rpcPath(name) { return `${this.name}${this.config.splitChar}${name}`; } async function start() { this.state.closing = false; this.client.on('connectionStateChanged', connectionStateChangedCallback.bind(this)); await this.updateCredentials(); await this.client.login(this.state.credentials, this.authCallback); // console.log('start:', this.state.apiSpec, this.state.apiImpl); loadApi(this.client, this.rpcPath.bind(this), this.state.apiSpec, this.state.apiImpl); // provideInterface(this.client, this.rpcPath.bind(this), this.api); if (this.config.runForever) idleLoop(); } function close() { this.state.closing = true; if (loopTimer) clearTimeout(loopTimer); return this.client.close(); } export function createRpcService({ name = 'service', address, options = {}, splitChar = rpcSplitChar, runForever = true, credentials = {}, credentialsUrl, clientErrorCallback = Function.prototype, }) { const service = Object.assign(Object.create({ constructor: createRpcService }), { name, state: { closing: false, apiSpec: {}, apiImpl: {}, credentials, }, config: { runForever, splitChar, credentialsUrl, }, client: getClient(address, { ...defaultOptions, ...options }), }); service.client.on('error', clientErrorCallback); service.setState = updates => { service.state = { ...service.state, ...updates }; }; service.close = close.bind(service); service.fetchCredentials = fetchCredentials.bind(service); service.getInterface = getInterface.bind(service); service.registerApi = registerApi.bind(service); service.rpcPath = rpcPath.bind(service); service.start = start.bind(service); service.updateCredentials = updateCredentials.bind(service); process.on('SIGTERM', service.close); return service; } createRpcService.of = createRpcService; // // Another pattern. For future? Better? Using closure instead of bind(this). Class not possible // // // const obj = Object.assign(Object.create({ constructor: createRpcService }), { // name, // state: { // closing: false, // apiSpec: {}, // apiImpl: {}, // credentials, // }, // client: getClient(address, { ...defaultOptions, ...options }), // }); // obj.client.on('error', clientErrorCallback); // obj.setState = updates => { // obj.state = { ...obj.state, ...updates }; // }; // obj.close = () => { // obj.state.closing = true; // if (loopTimer) clearTimeout(loopTimer); // return obj.client.close(); // }; // // obj.fetchCredentials = async (url) => { // if (obj.state.closing) return undefined; // try { // const reply = await fetch(url); // if (reply.status === 201) { // return reply.json(); // } // } catch (err) { // console.log('Will retry credentials fetch due to:', err); // } // return new Promise(r => setTimeout(r, 1000)).then(() => obj.fetchCredentials(url)); // }; // obj.rpcPath = id => `${obj.name}${obj.splitChar}${id}`; // // obj.registerApi = (apiSpec = {}, apiImpl) => obj.setState({ // apiSpec: { ...apiSpec, getInterface: joi.any() }, // apiImpl: { ...apiImpl, getInterface: () => mapValues(apiSpec, v => v.describe()) }, // }); // // obj.updateCredentials = async () => { // if (credentialsUrl) { // this.credentials = await this.fetchCredentials(credentialsUrl); // this.credentials.id = this.serviceName; // this.client._connection._authParams = this.credentials; // } // } // // function connectionStateChangedCallback(state) { // if (state === 'RECONNECTING' && credentialsUrl && !obj.state.closing) { // console.log('Re-fetching credentials...'); // this.updateCredentials(); // } // } // // obj.start = async () => { // obj.state.closing = false; // obj.client.on('connectionStateChanged', connectionStateChangedCallback.bind(this)); // await this.updateCredentials(); // await this.client.login(this.credentials, this.authCallback); // if (this.apiImpl) { // loadApi(this.client, this.rpcPath.bind(this), this.apiSpec, this.apiImpl); // } else { // provideInterface(this.client, this.rpcPath.bind(this), this.api); // } // if (this.runForever) idleLoop(); // }; // ================================================================================ // Class simulation for backward compatibility and cases where inheritance fit function Service(args) { const obj = createRpcService(args); Object.getOwnPropertyNames(obj).forEach(k => { if (typeof obj[k] !== 'function') { this[k] = obj[k]; } }); } Service.prototype.setState = function setState(updates) { this.state = { ...this.state, ...updates }; }; Service.prototype.close = close; Service.prototype.fetchCredentials = fetchCredentials; Service.prototype.getInterface = getInterface; Service.prototype.updateCredentials = updateCredentials; Service.prototype.start = start; Service.prototype.rpcPath = rpcPath; Service.prototype.registerApi = registerApi; export default Service; // let service; // if (require.main === module) { // service = createRpcService('deepstream:6020'); // service.start(); // }
import React, { Component } from 'react'; import { ErrorBoundaryComponent } from './ErrorBoundary.component'; class ErrorBoundaryContainer extends Component { constructor(props) { super(props); this.state = { error: false, } } componentDidCatch() { this.setState({ error: !this.state.error }); } render() { const { error } = this.state; return error ? <ErrorBoundaryComponent /> : this.props.children; } } export { ErrorBoundaryContainer as ErrorBoundary }
/* eslint-env jest */ import React from 'react'; import { shallow } from 'enzyme'; import Login from '..'; it('renders Login component without crashing', () => { shallow( <Login loginInputs={[]} visible renderMessage={() => 'span'} login={{}} />, ); });
import ColumnSetting from './ColumnSetting/ColumnSetting' import FilterItem from './FilterSetting/FilterItem' import FilterSetting from './FilterSetting/FilterSetting' export { ColumnSetting, FilterItem, FilterSetting, }
$( "#table_day1" ).wrap( "<div class='tab-pane active' id='m_day1'></div>" ); $( "#table_day2" ).wrap( "<div class='tab-pane' id='m_day2'></div>" );
import React , {Component} from 'react'; class Main extends Component{ render(){ return ( <div className=" col"> <div className="Main bg-danger p-5">{this.props.children}</div> </div> ); } } export default Main ;
import { Pie } from 'vue-chartjs' import chartBuilder from './chartBuilder' export default chartBuilder(Pie, { scales: {} })
import { Activity, dom } from "../exports.js" export default class Tracker { constructor({name, activities}){ this.name = name this.selected = "Daily" this.activities = Object.keys(activities).map(key => new Activity(key, activities[key], this)) } render(){ document.getElementById("name").innerText = this.name this.renderOptions() this.appendEventListener() } renderOptions(){ const options = [...dom.nav.children] options.forEach(item => item.innerText === this.selected ? item.classList.add("selected") : item.classList.remove("selected")) } appendEventListener(){ dom.nav.addEventListener("click", ({target}) => { if (target.classList.contains("option")){ this.selected = target.innerText this.renderOptions() this.activities.forEach(activity => activity.update()) } }) } }