text
stringlengths
7
3.69M
import * as actionTypes from './actionTypes'; export const getAllAssetHandler = allAsset => { return { type: actionTypes.GET_ALL_ASSET, payload: allAsset }; };
export default { resourceServer: { port: 8000, oidc: { issuer: "https://dev-170933.okta.com/oauth2/default" }, assertClaims: { aud: "api://default", cid: "0oadw3zeo3phZEALM356" } } };
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import className from 'classnames'; const propTypes = { countdown: PropTypes.number.isRequired }; const defaultProps = {}; class Timer extends Component { constructor(props) { super(props); this.state = { timer: '', isExpired: false }; this.end = null; this.interval = null; } componentDidMount() { this.startTimer(); } componentWillUnmount() { this.clearTimer(); } getTime() { if (!this.end) { this.end = performance.now() + (this.props.countdown * 60 * 1000); } const remainingTime = this.end - performance.now(); return { remainingTime, seconds: Math.floor((remainingTime / 1000) % 60), minutes: Math.floor((remainingTime / 1000 / 60) % 60), hours: Math.floor((remainingTime / (1000 * 60 * 60)) % 24), days: Math.floor(remainingTime / (1000 * 60 * 60 * 24)) }; } tick() { const { seconds, minutes } = this.getTime(); const isExpired = minutes + seconds <= 0; const timer = `${`0${minutes}`.slice(-2)}:${`0${seconds}`.slice(-2)}`; if (isExpired) { this.clearTimer(); } this.setState({ timer, isExpired }); } startTimer() { if (!this.interval) { this.tick(); this.interval = setInterval(() => this.tick(), 1000); } } clearTimer() { if (this.interval) { clearInterval(this.interval); this.interval = null; } } render() { const timerColor = className({ 'text--blue': this.state.isExpired }); return ( <span className={timerColor}>{this.state.timer}</span> ); } } Timer.propTypes = propTypes; Timer.defaultProps = defaultProps; export default Timer;
function tile(xTiles, yTiles, z, width, height, sprite){ this.rect = new rect(xTiles, yTiles, ancho, alto); this.zIndex = z; this.sprite = sprite; this.idHtml = "x" + xTiles + "y" + yTiles + "z" + z; this.html='<div id="'+this.idHtml+'"></div>'; } tile.prototype.aplicarEstilos = function(){ if(!document.getElementById(this.idHtml)){ throw("El ID "+this.idHtml+" No existe en la hoja"); } document.getElementById(this.idHtml).style.position = absolute; document.getElementById(this.idHtml).style.left = (this.rect.x * this.rect.width)+"px"; document.getElementById(this.idHtml).style.top = (this.rect.y * this.rect.height) + "px"; document.getElementById(this.idHtml).style.width = this.rect.width+"px"; document.getElementById(this.idHtml).style.height = this.rect.height+"px"; document.getElementById(this.idHtml).style.zIndex = ""+this.zIndex; document.getElementById(this.idHtml).style.background = "url('"+this.sprite.originRoute+"')"; var x = this.sprite.startPos.x; var y = this.sprite.startPos.y; document.getElementById(this.idHtml).style.backgroundPosition = "-"+x +"px -"+y+"px"; document.getElementById(this.idHtml).style.backgroundClip = "border-box"; document.getElementById(this.idHtml).style.outline = "1px solid ransparent"; }
import React from 'react' import Totals from '../Containers/Totals' import States from '../Containers/States' import Graph from '../Containers/Graph' import Logs from '../Containers/Logs' const Home = (props) => { return ( <div className='dashboard'> <h2>Dashboard</h2> <Totals /> <States /> <Graph /> <Logs /> </div> ) } export default Home
/** * @fileoverview Entity collects a group of Components that define a game object and its behaviors * * @author Tony Parisi */ goog.provide('SB.Entity'); goog.require('SB.PubSub'); /** * Creates a new Entity. * @constructor * @extends {SB.PubSub} */ SB.Entity = function() { SB.PubSub.call(this); /** * @type {number} * @private */ this._id = SB.Entity.nextId++; /** * @type {SB.Entity} * @private */ this._parent = null; /** * @type {Array.<SB.Entity>} * @private */ this._children = []; /** * @type {Array} * @private */ this._components = []; /** * @type {Boolean} * @private */ this._realized = false; } goog.inherits(SB.Entity, SB.PubSub); /** * The next identifier to hand out. * @type {number} * @private */ SB.Entity.nextId = 0; SB.Entity.prototype.getID = function() { return this._id; } //--------------------------------------------------------------------- // Hierarchy methods //--------------------------------------------------------------------- /** * Sets the parent of the Entity. * @param {SB.Entity} parent The parent of the Entity. * @private */ SB.Entity.prototype.setParent = function(parent) { this._parent = parent; } /** * Adds a child to the Entity. * @param {SB.Entity} child The child to add. */ SB.Entity.prototype.addChild = function(child) { if (!child) { throw new Error('Cannot add a null child'); } if (child._parent) { throw new Error('Child is already attached to an Entity'); } child.setParent(this); this._children.push(child); if (this._realized && !child._realized) { child.realize(); } } /** * Removes a child from the Entity * @param {SB.Entity} child The child to remove. */ SB.Entity.prototype.removeChild = function(child) { var i = this._children.indexOf(child); if (i != -1) { this._children.splice(i, 1); child.setParent(null); } } /** * Removes a child from the Entity * @param {SB.Entity} child The child to remove. */ SB.Entity.prototype.getChild = function(index) { if (index >= this._children.length) return null; return this._children[index]; } //--------------------------------------------------------------------- // Component methods //--------------------------------------------------------------------- /** * Adds a Component to the Entity. * @param {SB.Component} component. */ SB.Entity.prototype.addComponent = function(component) { if (!component) { throw new Error('Cannot add a null component'); } if (component._entity) { throw new Error('Component is already attached to an Entity') } if (component instanceof SB.Transform) { if (this.transform != null && component != this.transform) { throw new Error('Entity already has a Transform component') } this.transform = component; } this._components.push(component); component.setEntity(this); if (this._realized && !component._realized) { component.realize(); } } /** * Removes a Component from the Entity. * @param {SB.Component} component. */ SB.Entity.prototype.removeComponent = function(component) { var i = this._components.indexOf(component); if (i != -1) { if (component.removeFromScene) { component.removeFromScene(); } this._components.splice(i, 1); component.setEntity(null); } } /** * Retrieves a Component of a given type in the Entity. * @param {Object} type. */ SB.Entity.prototype.getComponent = function(type) { var i, len = this._components.length; for (i = 0; i < len; i++) { var component = this._components[i]; if (component instanceof type) { return component; } } return null; } /** * Retrieves a Component of a given type in the Entity. * @param {Object} type. */ SB.Entity.prototype.getComponents = function(type) { var i, len = this._components.length; var components = []; for (i = 0; i < len; i++) { var component = this._components[i]; if (component instanceof type) { components.push(component); } } return components; } //--------------------------------------------------------------------- //Initialize methods //--------------------------------------------------------------------- SB.Entity.prototype.realize = function() { this.realizeComponents(); this.realizeChildren(); this._realized = true; } /** * @private */ SB.Entity.prototype.realizeComponents = function() { var component; var count = this._components.length; var i = 0; for (; i < count; ++i) { this._components[i].realize(); } } /** * @private */ SB.Entity.prototype.realizeChildren = function() { var child; var count = this._children.length; var i = 0; for (; i < count; ++i) { this._children[i].realize(); } } //--------------------------------------------------------------------- // Update methods //--------------------------------------------------------------------- SB.Entity.prototype.update = function() { this.handleMessages(); this.updateComponents(); this.updateChildren(); } /** * @private */ SB.Entity.prototype.updateComponents = function() { var component; var count = this._components.length; var i = 0; for (; i < count; ++i) { this._components[i].update(); } } /** * @private */ SB.Entity.prototype.updateChildren = function() { var child; var count = this._children.length; var i = 0; for (; i < count; ++i) { this._children[i].update(); } }
// Generated by CoffeeScript 1.9.2 (function() { var async, cheerio, moment, request; async = require('async'); moment = require('moment'); request = require('request'); cheerio = require('cheerio'); module.exports = { crawl: function(hut, cbExports) { var capacity, capacityStatus, ddlLocation, parser, selectorRemaining, urlAfterDraw, urlBeforeDraw; capacityStatus = []; capacity = hut.capacity; urlAfterDraw = ''; urlBeforeDraw = ''; selectorRemaining = ''; ddlLocation = 0; switch (hut.nameZh) { case '排雲山莊': urlAfterDraw = 'https://mountain.ysnp.gov.tw/chinese/Location_Detail.aspx?pg=01&w=1&n=1005&s=1'; urlBeforeDraw = 'https://mountain.ysnp.gov.tw/chinese/LocationAppIndex.aspx?pg=01&w=1&n=1003'; selectorRemaining = 'span.style11 font'; ddlLocation = 1; break; case '圓峰山屋': urlAfterDraw = 'https://mountain.ysnp.gov.tw/chinese/Location_Detail.aspx?pg=01&w=1&n=1005&s=136'; urlBeforeDraw = 'https://mountain.ysnp.gov.tw/chinese/LocationAppIndex.aspx?pg=01&w=1&n=1003'; selectorRemaining = 'span.style11 font'; ddlLocation = 136; break; case '圓峰營地': urlAfterDraw = 'https://mountain.ysnp.gov.tw/chinese/Location_Detail.aspx?pg=01&w=1&n=1005&s=136'; urlBeforeDraw = 'https://mountain.ysnp.gov.tw/chinese/LocationAppIndex.aspx?pg=01&w=1&n=1003'; selectorRemaining = 'span.style12 font'; ddlLocation = 136; } async.waterfall([ function(cb) { return request(urlAfterDraw, function(err, res, body) { var $; $ = cheerio.load(body); return parser($, function() { return cb(null, $); }); }); }, function($, cb) { return request({ 'method': 'POST', 'url': urlAfterDraw, 'form': { '__EVENTTARGET': 'ctl00$ContentPlaceHolder1$CalendarReport', '__EVENTARGUMENT': $('table#ctl00_ContentPlaceHolder1_CalendarReport table tr td:nth-child(3) a').attr('href').substring(68, 68 + 5), '__VIEWSTATE': $('#__VIEWSTATE').val(), '__VIEWSTATEGENERATOR': $('#__VIEWSTATEGENERATOR').val(), '__EVENTVALIDATION': $('#__EVENTVALIDATION').val() } }, function(err, res, body) { return parser(cheerio.load(body), function() { return cb(null); }); }); }, function(cb) { return async.eachSeries([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], function(itmes, eachSerialFinished) { return request(urlBeforeDraw, function(err, res, body) { var $, date; $ = cheerio.load(body); date = moment().add(7 + capacityStatus.length, 'd'); return request({ 'method': 'POST', 'url': urlBeforeDraw, 'form': { 'ctl00_ContentPlaceHolder1_ToolkitScriptManager1_HiddenField': '', '__EVENTTARGET': '', '__EVENTARGUMENT': '', '__VIEWSTATE': $('#__VIEWSTATE').val(), '__VIEWSTATEGENERATOR': $('#__VIEWSTATEGENERATOR').val(), '__VIEWSTATEENCRYPTED': $('#__VIEWSTATEENCRYPTED').val(), '__EVENTVALIDATION': $('#__EVENTVALIDATION').val(), 'ctl00$ContentPlaceHolder1$txtSDate': date.format('YYYY/MM/DD'), 'ctl00$ContentPlaceHolder1$ddlLocation': ddlLocation, 'ctl00$ContentPlaceHolder1$btnSearch.x': 6, 'ctl00$ContentPlaceHolder1$btnSearch.y': 19, 'ctl00$ContentPlaceHolder1$gvIndex$ctl13$ddlPager': 1 } }, function(err, res, body) { var applying; $ = cheerio.load(body); applying = $('#ctl00_ContentPlaceHolder1_lblPeople').text(); capacityStatus.push({ 'date': date.format(), 'remaining': capacity, 'applying': applying, 'isDrawn': false }); return eachSerialFinished(); }); }); }, function(err) { if (err) { return console.log(err); } else { return cb(null); } }); } ], function(err, result) { return cbExports(null, capacityStatus); }); return parser = function($, done) { var month, year, yearMonth; yearMonth = $('#ctl00_ContentPlaceHolder1_CalendarReport tr:first-child td:nth-child(2)').text(); year = yearMonth.split('年')[0]; month = yearMonth.split('年')[1].split('月')[0]; $('#ctl00_ContentPlaceHolder1_CalendarReport tr').each(function(i) { if (i >= 3 && i <= 7) { return $(this).find('td > a').each(function(i) { var applying, dateDiff, registered, today; today = moment().year(year).month(month - 1).date($(this).text()); dateDiff = today.diff(moment(), 'd'); if (dateDiff >= 7 && dateDiff <= 31) { registered = $(this).parent('td').find(selectorRemaining).text(); if (dateDiff === 31 && registered === '') { return; } applying = $(this).parent('td').find('span.style14 font').text(); return capacityStatus.push({ 'date': moment().add(7 + capacityStatus.length, 'day').format(), 'remaining': registered === '' ? 0 : capacity - registered, 'applying': applying === '' ? 0 : applying, 'isDrawn': true }); } }); } }); return done(); }; } }; }).call(this);
#!/usr/bin/env node /** * Skrypt tworzący szkice stron o ulicach */ var fs = require('fs'), bot = require('nodemw'), client = new bot('config.js'); var SUMMARY = 'Szkic strony', YEAR = '2017', ULICA = process.argv[2] || ''; if (ULICA === '') { console.log('Podaj nazwę ulicy'); process.exit(1); } function osmSearch(query, callback) { client.log('osmSearch: query', query); query = query.replace(/^Ulica\s/, ''); // @see http://wiki.openstreetmap.org/wiki/Nominatim#Alternatives_.2F_Third-party_providers // e.g. https://nominatim.openstreetmap.org/search.php?q=Tony+Halika%2C+Pozna%C5%84&format=json&addressdetails=1 //const url = 'https://nominatim.openstreetmap.org/search.php?format=json&q=' + encodeURIComponent(query); // e.g. http://locationiq.org/v1/search.php?q=Tony+Halika%2C+Pozna%C5%84&format=json&addressdetails=1&key=XXX const key = client.getConfig('locationiqKey'), url = 'https://locationiq.org/v1/search.php?format=json&addressdetails=1&q=' + encodeURIComponent(query) + '&key=' + key; client.fetchUrl(url, (err, res) => { if (err) { callback(err, res); } try { const data = JSON.parse(res); callback(null, data); } catch (e) { callback(e, null); } }); } client.logIn((err, data) => { client.getArticle(ULICA, (err, content) => { // strona istnieje if (typeof content !== 'undefined') { throw 'Artykuł juz istnieje'; } // Geo data const query = `${ULICA}, Poznań`; osmSearch(query, (err, data) => { if (err) { console.log(data); throw err; } if (!data || !data[0]) { throw 'Address not found'; } var place = data[0]; client.log(place); place.address.postcode = place.address.postcode || ''; place.address.suburb = place.address.suburb || ''; place.address.neighbourhood = place.address.neighbourhood || ''; /** { place_id: '196302900', licence: 'Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright', osm_type: 'way', osm_id: '441844276', boundingbox: [ '52.3933304', '52.3936783', '16.9577746', '16.9580225' ], lat: '52.3934741', lon: '16.9578421', display_name: 'Anny Jantar, Łacina, Rataje, Poznań, wielkopolskie, 61-206, Polska', class: 'highway', type: 'residential', importance: 0.41, address: { road: 'Anny Jantar', neighbourhood: 'Łacina', suburb: 'Rataje', city: 'Poznań', county: 'Poznań', state: 'wielkopolskie', postcode: '61-206', country: 'Polska', country_code: 'pl' } } **/ var content = `{{Ulica infobox |nazwa_ulicy=${ULICA} |mapa_ulica=<place lat="${place.lat}" lon="${place.lon}" width="300" zoom=14 /> |patron= |patron_wikipedia= |długość= |dzielnice=${place.address.neighbourhood}, ${place.address.suburb} |rok=[[${YEAR}]] |numery= |najwyższy_budynek= |kody=${place.address.postcode} |przystanki_autobusowe= |przystanki_tramwajowe= }} '''${ULICA}''' == Historia == {{Rozwiń Sekcję}} {{Przy ulicy}} == Źródła == <references />`; content = content.replace(/=\s?,\s?/g, '='); //content = content.replace(/, ?\n*/g, '\n'); client.log(content); // edytuj client.edit(ULICA, content, SUMMARY, (err) => { if (err) { throw err; } console.log(ULICA + ' założona'); }); }); }); });
var isPc; function loadState(game){ this.init = function () { game.scale.pageAlignHorizontally=true;//水平居中 function goPC() { var userAgentInfo = navigator.userAgent; var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"); isPc = true; for (var v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { isPc = false; break; } } return isPc; } goPC(); } this.preload = function () { if(!isPc){ game.load.image('iBox','assets/img/IBox.png'); game.load.image('lBox','assets/img/LBox.png'); game.load.image('oBox','assets/img/OBox.png'); game.load.image('tBox','assets/img/TBox.png'); game.load.image('xBox','assets/img/XBox.png'); game.load.image('xBox_','assets/img/XBox_.png'); game.load.image('lBox_','assets/img/LBox_.png'); game.load.physics('physicsData',null,Bbox); game.load.image('change','assets/img/change.png'); game.load.image('fxj','assets/img/fxj.png'); }else{ game.load.image('line','assets/img/i.png'); game.load.image('iBox','assets/img/pc/IBox.png'); game.load.image('lBox','assets/img/pc/LBox.png'); game.load.image('oBox','assets/img/pc/OBox.png'); game.load.image('tBox','assets/img/pc/TBox.png'); game.load.image('xBox','assets/img/pc/XBox.png'); game.load.image('xBox_','assets/img/pc/XBox_.png'); game.load.image('lBox_','assets/img/pc/LBox_.png'); game.load.physics('physicsData',null,pcBox); game.load.tilemap('map_2',null,mapTwoJson,Phaser.Tilemap.EAST); game.load.tilemap('map_1',null,mapJson,Phaser.Tilemap.EAST); } game.load.image('startButton_1','assets/img/start-button.png'); game.load.image('oneButton','assets/img/one.png'); game.load.image('twoButton','assets/img/two.png'); game.load.image('mario','assets/img/mario.png'); game.load.image('down','assets/img/down.png'); game.load.audio('btn_sound','assets/music/flap.wav'); game.load.audio('ground_sound','assets/music/ground-hit.wav'); game.load.audio('score_sound','assets/music/score.wav'); game.load.spritesheet('bird','assets/img/bird.png',34,24,3); } this.create = function(){ game.state.start('menu'); } }
// pages/personal/personal.js var app = getApp(); var url = require('../../utils/url.js'); var constant = require('../../utils/constant.js'); Page({ /** * 页面的初始数据 */ data: { userInfo: {}, hasUserInfo: false, canIUse: wx.canIUse('button.open-type.getUserInfo'), isLogin: 1, isViewDisabled: true, userPro: {}, memberInformation: {}, wxNick:'', wxnickImg:'', wxnickview:false, appBalance:'', appPoint:'', appLevelName:'', appview: false, activeId: '',isShareImg1:false, }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; that.getActivity() console.log(app.globalData.JSESSIONID) console.log(app.globalData.wxnick) that.getIsLogin(app.globalData.JSESSIONID); if (app.globalData.wxnick != '' & app.globalData.wxnick != undefined){ console.log(app.globalData.wxnick) that.setData({ wxNick:app.globalData.wxnick, wxnickview:true, wxnickImg: app.globalData.wxnickimg }) } console.log(that.data.wxNick, that.data.wxnickview) wx.setNavigationBarTitle({ title: '我的', }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { var that = this; that.getUserInfoData(app.globalData.JSESSIONID); that.getActivity() that.setData({ isViewDisabled: true, }) // console.log(app.globalData.balance) // if (app.globalData.balance != '' & app.globalData.balance != undefined) { // appview = true // that.setData({ // appBalance: app.globalData.balance, // appPoint: app.globalData.point, // appLevelName: app.globalData.levelName // }) // console.log(12323) // console.log(that.data.appBalance, that.data.appPoint, that.data.appLevelName) // } }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, // getInfo: function () { // var that = this; // if (app.globalData.userInfo) { // this.setData({ // userInfo: app.globalData.userInfo, // hasUserInfo: true // }) // } else if (this.data.canIUse) { // // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // // 所以此处加入 callback 以防止这种情况 // app.userInfoReadyCallback = res => { // that.setData({ // userInfo: res.userInfo, // hasUserInfo: true // }) // } // } else { // // 在没有 open-type=getUserInfo 版本的兼容处理 // wx.getUserInfo({ // success: res => { // app.globalData.userInfo = res.userInfo // that.setData({ // userInfo: res.userInfo, // hasUserInfo: true // }) // } // }) // } // }, // getUserInfo: function (e) { // console.log(e) // app.globalData.userInfo = e.detail.userInfo // this.setData({ // userInfo: e.detail.userInfo, // hasUserInfo: true // }) // }, btn_login:function(){ var isLogin = this.data.isLogin; this.setData({ isViewDisabled: false, }) if (isLogin == 2){ wx.navigateTo({ url: '../login/login', }) }else{ wx.navigateTo({ url: '../userInfromation/userInfromation', }) } }, getUserInfoData: function (JSESSIONID){ var that = this; console.log(url.getUserInformation) wx.request({ url: url.getUserInformation, data:{ }, method: 'POST', header: JSESSIONID ? { 'Cookie': 'JSESSIONID=' + JSESSIONID } : {}, success:function(res){ console.log(res); if(res.data.status == 9){ that.setData({ isLogin: 2, isViewDisabled: true, memberInformation: {} }) }else if(res.data.status == 1){ // res.data.data.nickName = res.data.data.nickName.replace(/(.{3}).*(.{4})/, "$1****$2"); console.log('---------------------'); app.globalData.phone = res.data.data.phone; app.globalData.personName = res.data.data.compellation; that.getMemberInformation(res.data.data.phone); that.setData({ isLogin: 1, userPro: res.data.data, isViewDisabled: true, }) } else if (res.data.status == 11) { that.setCacheData(app.globalData.openId, app.globalData.cityName, app.globalData.JSESSIONID,1); } } }) }, btn_address:function(){ var that = this; that.setData({ isViewDisabled: false }) if (that.data.isLogin == 2) { wx.navigateTo({ url: '../login/login', }) } else { wx.navigateTo({ url: '../address/address', }) } }, getIsLogin: function (JSESSIONID){ var that = this; wx.request({ url: url.getIsLogin, data:{}, method:'POST', header: JSESSIONID ? { 'Cookie': 'JSESSIONID=' + JSESSIONID } : {}, success:function(res){ console.log(res); } }) }, btn_exit:function(){ var that = this; var JSESSIONID = app.globalData.JSESSIONID; that.setData({ isViewDisabled: false, }) wx.request({ url: url.exitLogin, method: 'POST', header: JSESSIONID ? { 'Cookie': 'JSESSIONID=' + JSESSIONID } : {}, success:function(res){ console.log(res); if(res.data.status == 1){ that.getUserInfoData(app.globalData.JSESSIONID); that.getIsLogin(app.globalData.JSESSIONID); // app.globalData.JSESSIONID='' } else if (res.data.status == 11) { that.setCacheData1(app.globalData.openId, app.globalData.cityName, app.globalData.JSESSIONID); } } }) }, setCacheData: function (openId, city, JSESSIONID, num = 0) { //that.setCacheData1(app.globalData.openId, app.globalData.cityName, app.globalData.JSESSIONID); /**else if(res.data.status == 9){ wx.navigateTo({ url: '../login/login', }) }else if(res.data.status == 11){ that.setCacheData1(app.globalData.openId, app.globalData.cityName, app.globalData.JSESSIONID); } */ var that = this; wx.request({ url: url.setCache, data: { cityName: city, openId: openId }, method: 'POST', header: JSESSIONID ? { 'Cookie': 'JSESSIONID=' + JSESSIONID } : {}, success: function (res) { if(num == 1){ that.getUserInfoData(app.globalData.JSESSIONID); } } }) }, getMemberInformation:function(phone){ var that = this; console.log(phone); wx.request({ url: url.getMemberInformation + phone, data:{ }, header:{ clientId: constant.clientId, brandId: constant.brandId, // openId: app.globalData.openId }, success:function(res){ console.log(res); if(res.data.code == 200){ app.globalData.memberId = res.data.data[0].id; that.setData({ memberInformation: res.data.data[0] }) } } }) }, btn_coupon:function(){ console.log(this.data.longitude, this.data.latitude, this.data.jump, this.data.address, this.data.typeNum, this.data.shopId) this.setData({ isViewDisabled: false }) if (this.data.isLogin == 2){ wx.navigateTo({ url: '../login/login', }) }else{ wx.navigateTo({ url: '../myCoupon/myCoupon', }) } }, btn_revise:function(){ var that = this; that.setData({ isViewDisabled: false }) if (this.data.isLogin == 2) { wx.navigateTo({ url: '../login/login', }) } else { wx.navigateTo({ url: '../revisePwd/revisePwd', }) } }, btn_contact:function(){ var that = this; that.setData({ isViewDisabled: false }) wx.navigateTo({ url: '../contactUs/contactUs', }) }, btn_share:function(){ var that = this; wx.navigateTo({ url: '../share/share?activityId=' + this.data.activeId }) }, getActivity: function () { var that = this console.log(url.getActivity + constant.brandId + '/123') wx.request({ url: url.getActivity + constant.brandId + '/123', method: 'GET', success: function (res) { console.log(res); if (res.data.code == 200) { console.log('chenggong') that.setData({ activeId: res.data.data.id, isShareImg1: true, }) } } }) }, })
const pig = require('pigcolor'); const Category = require("../models/Category"); const Sub = require("../models/SubCategory"); // ** User exports.getAllcategory = (req, res) => { pig.box("ALL CATEGORIES"); Category.find({}, (err, allCategory) => { if (err) { return res.status(400).json({ error: "Couldn't fetch all Category" }) } else { return res.json({ msg: "Categories", data: allCategory }) } }); } exports.getAcategory = (req, res) => { pig.box("GET A CATEGORY"); Category.findById({ _id: req.params.categoryId }, (err, category) => { if (err) { return res.status(400).json({ error: "Couldn't get a category", error_msg: err }) } else { return res.json({ msg: category }) } }); } // ** Admin // *? Sub-Category exports.addSubCategory = (req, res) => { pig.box("ADD SUB-CATEGORY"); const sub = new Sub(req.body); sub.save((err, saved) => { if (err) { return res.status(400).json({ error: "Couldn't save the Sub-Category", error_msg: err }) } else { Category.findById(req.params.categoryId, (err, category) => { if (err) { return res.status(400).json({ error: "Couldn't get the category" }) } else { category.sub.push(saved._id); category.save((err, savedsub) => { if (err) { return res.status(400).json({ error: "Couldn't puch sub-category" }) } else { return res.json({ msg: "Sub-Category Saved", data: saved }) } }); } }) } }); } exports.deleteSubCategory = (req, res) => { pig.box("DELETE SUB-CATEGORY & REMOVE SUB FROM CATEGORY"); Category.findById(req.params.categoryId, (err, category) => { if (err) { return res.status(400).json({ error: "Couldn't find the Category", error_msg: err }) } for (var i = 0; i < category.sub.length; i++) { if (String(category.sub[i]) === String(req.params.subcategoryId)) { category.sub.remove(req.params.subcategoryId); break; } } category.save((err, done) => { if (err) { return res.status(400).json({ error: "Couldn't save removed Category", error_msg: err }) } Sub.findByIdAndDelete(req.params.subcategoryId, (err, subDeleted) => { if (err) { return res.status(400).json({ error: "Coudln't Delete the Sub-Category", error_msg: err }) } return res.json({ msg: "Deleted Sub-Category Sucessful" }) }); }) }); } // *? Category exports.addCategory = (req, res) => { console.log(req.body); const newCategory = Category(req.body); newCategory.save((err, category) => { if (err) { return res.status(400).json({ error: "Couldn't Create Category", error_msg: err }); } else { return res.json({ msg: "Category Created Successfully" }) } }); pig.box("Add Category"); } exports.editCategory = (req, res) => { console.log(req.params.categoryId); // console.log(req.body); if (req.params.categoryId == undefined) return res.json({ error: "Your are not autherised" }); pig.box("Edit Category"); Category.findByIdAndUpdate(req.params.categoryId, req.body, { new: true }, (err, edited) => { if (err) { console.log(edited); return res.status(400).json({ error: "Couldn't Edit Category" }); } else { return res.json({ msg: "Category Edited Successfully" }) } }); } exports.deleteCategory = (req, res) => { pig.box("Delete Category"); Category.findByIdAndDelete(req.params.categoryId, (err, deleted) => { if (err) { return res.status(400).json({ error: "Couldn't Delete Category" }); } else { return res.json({ msg: "Category Deleted Successfully" }) } }); }
import { createStore } from "redux"; import reducer from "./reducer"; import middleware from "./middleware"; /** * Configure the store. * @param {Object} initialState Initial state object (typically empty: {}). */ const configureStore = (initialState) => { return createStore(reducer, initialState, middleware); }; export default configureStore;
$(function() { $("#root-view") .modelsView("/", "<li><a data-toggle='tab' href='#{{id}}-tab'>{{id}}</a></li>"); $("#main-content") .modelsView( "/", ["<div id='{{id}}-tab' class='container tab-pane'/>", ["<div class='row'/>", ["<div class='span12'/>", ["<a href='#add-{{id}}-modal' role='button' class='close pull-left' data-toggle='modal'/>", "<h2>&plus;</h2>"]]], ["<div class='row'/>", ["<div class='span2'/>", function(model) { return $() .renderView( model, "<ul class='nav nav-tabs nav-stacked' id='{{id}}-objects'></ul>") .objectsView( "/" + model.id, "<li><a data-toggle='tab' href='#" + model.id + "-{{id}}-tab'>{{name}}</a></li>"); }], [function(model) { return $() .renderView(model,"<div id='main-{{id}}-view' class='tab-content span10'/>") .objectsView( "/" + model.id, function (object) { if (model.id == "system") { var view = $().renderView( object, ["<div id='" + model.id + "-{{id}}-tab' class='tab-pane'/>", function(object) { var view = $() .renderView( object, "<ul id='" + model.id + "-toolbar-{{id}}' class='system-toolbar nav nav-tabs'/>") .modelsView( model.id, "<li><img data-model='{{id}}' class='system-icon' src='img/{{id}}.png'/></li>", {but: "connection"}); view.find("img") .draggable({ helper: "clone"}); return view; }]); $().renderView( object, "<div id='" + model.id + "-{{id}}-desktop' class='desktop' />") .desktopView("/" + model.id + "/" + object.id) .appendTo(view); return view; } else { return $() .renderView(object, "<form id='"+ model.id + "-{{id}}-tab' class='tab-pane'/>") .objectPropertiesView( "/" + model.id + "/" + object.id, ["<div/>", "<label>{{description}}</label>", "<input data-w-property='{{id}}' placeholder='{{type}}'/>"]) .append($().renderView( object, ["<div class='btn-toolbar'/>", "<button class='btn btn-primary' type='submit'>Save</button>", "<button class='btn' type='reset'>Reset</button>"])) .submit(function () { // avoid autoreload on form submit return false; }); }}, {but: ["web-server", "internet", "user", "connection"]})}]]]); $("#modals"). modelsView( "/", ["<div id='add-{{id}}-modal' class='modal hide fade' tabindex='-1' role='dialog' aria-labelledby=add-{{id}}-label' aria-hidden='true'/>", ["<div id=add-{{id}}-header' class='modal-header'/>", "<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>", "<h3 id='add-{{id}}-label'> Add {{id}}</h3>"], renderModelProperties]); $("#session-selector").propertyView("session", ["<form class='nav navbar-form form-inline'/>", "<input type='text' placeholder='session name' value='{{session}}'/>"]); client.events.connect("http://localhost:8080"); }); renderModelProperties = function (model) { return $().renderView(model, "<form id='add-{{id}}-body' class='modal-body'/>") .modelPropertiesView("/" + model.id, ["<div/>", "<label>{{description}}</label>", "<input data-w-property='{{id}}' placeholder='{{type}}'/>"]) .submit(function () { $("#add-" + model.id + "-modal").modal('hide'); return false; }) .append($().renderView(model, ["<div class='btn-toolbar'/>", "<button class='btn btn-primary' type='submit'>Save</button>", "<button class='btn' type='button' data-dismiss='modal'>Cancel</button>", "<button class='btn' type='reset'>Clear Form</button>"])); }
export default class NewRecord { constructor( serviceOperationNumber, date, mileage, serviceWorks, changableParts ) { this.serviceOperationNumber = serviceOperationNumber; this.date = date; this.mileage = mileage; this.serviceWorks = serviceWorks; this.changableParts = changableParts; } }
// app.js const { createStore } = require('redux'); // Define the store's reducer. const fruitReducer = (state = [], action) => { switch (action.type) { case 'ADD_FRUIT': return [...state, action.fruit]; default: return state; } }; // Create the store. const store = createStore(fruitReducer); // Define an 'ADD_FRUIT' action for adding an orange to the store. const addOrange = { type: 'ADD_FRUIT', fruit: 'orange', }; // Log to the console the store's state before and after // dispatching the 'ADD_FRUIT' action. console.log(store.getState()); // [] store.dispatch(addOrange); console.log(store.getState()); // [ 'orange' ] // Define and register a callback to listen for store updates // and console log the store's state. const display = () => { console.log(store.getState()); }; const unsubscribeDisplay = store.subscribe(display); // Dispatch the 'ADD_FRUIT' action. This time the `display` callback // will be called by the store when its state is updated. store.dispatch(addOrange); // [ 'orange', 'orange' ] // Unsubscribe the `display` callback to stop listening for store updates. unsubscribeDisplay(); // Dispatch the 'ADD_FRUIT' action one more time // to confirm that the `display` method won't be called // when the store state is updated. store.dispatch(addOrange); // no output
import Vue from 'vue' import Vuetify from 'vuetify' import Logout from '../components/App/Logout.vue' import DepartmentCreate from '../components/Department/Create.vue' import DepartmentUpdate from '../components/Department/Update.vue' import DepartmentRemove from '../components/Department/Remove.vue' import DepartmentItem from '../components/Department/Item.vue' import DepartmentList from '../components/Department/List.vue' import UserCreate from '../components/User/Create.vue' import UserUpdate from '../components/User/Update.vue' import UserUpdatePassword from '../components/User/UpdatePassword.vue' import UserRemove from '../components/User/Remove.vue' import UserList from '../components/User/List.vue' import UserItem from '../components/User/Item.vue' import TestCreate from '../components/Test/Create.vue' import TestUpdate from '../components/Test/Update.vue' import TestRemove from '../components/Test/Remove.vue' import TestList from '../components/Test/List.vue' import TestItem from '../components/Test/Item.vue' import TestingList from '../components/Testing/List.vue' import TestingItem from '../components/Testing/Item.vue' import TestingQuestion from '../components/Testing/Question.vue' import QuestionCreate from '../components/Question/Create.vue' import QuestionUpdate from '../components/Question/Update.vue' import QuestionRemove from '../components/Question/Remove.vue' import QuestionList from '../components/Question/List.vue' import QuestionItem from '../components/Question/Item.vue' import ResultItem from '../components/Result/Item.vue' import ResultList from '../components/Result/List.vue' import ResultRemove from '../components/Result/Remove.vue' import AnswerItem from '../components/Answer/Item.vue' import AnswerList from '../components/Answer/List.vue' import OptionCreate from '../components/Option/Create.vue' import OptionUpdate from '../components/Option/Update.vue' import OptionRemove from '../components/Option/Remove.vue' import OptionList from '../components/Option/List.vue' import OptionItem from '../components/Option/Item.vue' Vue.use(Vuetify) Vue.component('Logout', Logout) Vue.component('DepartmentCreate', DepartmentCreate) Vue.component('DepartmentUpdate', DepartmentUpdate) Vue.component('DepartmentRemove', DepartmentRemove) Vue.component('DepartmentItem', DepartmentItem) Vue.component('DepartmentList', DepartmentList) Vue.component('UserCreate', UserCreate) Vue.component('UserUpdate', UserUpdate) Vue.component('UserUpdatePassword', UserUpdatePassword) Vue.component('UserRemove', UserRemove) Vue.component('UserList', UserList) Vue.component('UserItem', UserItem) Vue.component('TestCreate', TestCreate) Vue.component('TestUpdate', TestUpdate) Vue.component('TestRemove', TestRemove) Vue.component('TestList', TestList) Vue.component('TestItem', TestItem) Vue.component('TestingList', TestingList) Vue.component('TestingItem', TestingItem) Vue.component('TestingQuestion', TestingQuestion) Vue.component('QuestionCreate', QuestionCreate) Vue.component('QuestionUpdate', QuestionUpdate) Vue.component('QuestionRemove', QuestionRemove) Vue.component('QuestionList', QuestionList) Vue.component('QuestionItem', QuestionItem) Vue.component('ResultItem', ResultItem) Vue.component('ResultList', ResultList) Vue.component('ResultRemove', ResultRemove) Vue.component('AnswerItem', AnswerItem) Vue.component('AnswerList', AnswerList) Vue.component('OptionCreate', OptionCreate) Vue.component('OptionUpdate', OptionUpdate) Vue.component('OptionRemove', OptionRemove) Vue.component('OptionList', OptionList) Vue.component('OptionItem', OptionItem)
import { Navigation, EVENTS } from '../../src/Navigation'; describe('navigation', () => { it('should has a navigators as an empty object', () => { const navigation = new Navigation(); expect(navigation.navigators).toEqual({}); }); it('should has EVENTS list', () => { expect(EVENTS).toEqual({ LOCK: 'lock', UNLOCK: 'unlock', ID: 'id', }); }); });
import React, { useState, useEffect, useContext } from 'react' import PropTypes from 'prop-types' import { Helmet } from 'react-helmet' import { Link, StaticQuery, graphql } from 'gatsby' import { Navigation } from '.' import SiteLogo from '../SiteLogo' // import config from '../../utils/siteConfig' import Prism from 'prismjs' import { ThemeContext } from '../../context/themeContext' /** * Main layout component * * The Layout component wraps around each page and template. * It also provides the header, footer as well as the main * styles, and meta data for each page. * */ const DefaultLayout = ({ data, children, bodyClass, isHome }) => { const site = data.allGhostSettings.edges[0].node const { theme, setTheme } = useContext(ThemeContext) const [menuState, setMenuState] = useState(`page nav-is-closed`) const toggleMenu = () => { setMenuState(state => (state === `page nav-is-closed` ? `page nav-is-active` : `page nav-is-closed`)) } const handleThemeToggle = () => { if (theme === `light`) { setTheme(`dark`) } else { setTheme(`light`) } } useEffect(() => { // call the highlightAll() function to style our code blocks Prism.highlightAll() }) return ( <> <Helmet> <html lang={site.lang} className={`${theme === `light` ? `light` : `dark`}`} /> <link rel="preload" href="/fonts/Mona-Sans.woff2" as="font" crossOrigin="anonymous" type="font/woff2" /> <style type="text/css">{`${site.codeinjection_styles}`}</style> <body className={bodyClass} /> </Helmet> <div className={`${menuState}`}> <div className="viewport"> <div className="viewport-top"> {/* The main header section on top of the screen */} <header className="site-head mx-auto"> <div className="toggle-wrapper container mx-auto text-right pt-5 pr-5 flex gap-8 justify-end"> <label className="relative inline-flex items-center cursor-pointer"> <input type="checkbox" className="sr-only peer" checked={theme === `light` ? true : false} onChange={handleThemeToggle} /> <div className="w-11 h-6 bg-slate peer-focus:outline-none peer-focus:ring-0 rounded-full peer dark:bg-purple-slate peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[6px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-slate peer-checked:bg-blue"></div> <span className="ml-3 text-lg font-medium"> {theme === `light` ? ( <> ☀️ <span className="sr-only">Light Mode</span> </> ) : ( <> 🌙 <span className="sr-only">Dark Mode</span> </> )} </span> </label> <button type="button" className="btn navbar-toggler focus:outline-none relative z-50" onClick={toggleMenu}> <span className={`icon-bar block top-bar`} /> <span className={`icon-bar block middle-bar`} /> <span className={`icon-bar block bottom-bar ml-auto`} /> <span className={`sr-only`}>Toggle navigation</span> </button> </div> {isHome && ( <div className="site-banner sr-only"> <h1 className="site-banner-title">{site.title}</h1> <p className="site-banner-desc">{site.description}</p> </div> )} <div className="gh-header gh-canvas lg:pb-5 pt-5"> <SiteLogo /> </div> <div className="site-menu fixed inset-0"> <div className="max-w-6xl mx-auto pt-8"> <Navigation data={site.navigation} navClass="site-nav-item py-2" /> </div> </div> </header> <main className="site-main mx-auto pb-5"> {/* All the main content gets inserted here, index.js, post.js */} {children} </main> </div> <div className="viewport-bottom"> {/* The footer at the very bottom of the screen */} <footer className="site-footer uppercase"> <div className="site-footer-nav container px-0 pb-1 mx-auto"> <Navigation data={site.navigation} navClass="site-footer-nav-item" /> </div> <div className="site-copyright text-center text-xs pb-8"> <Link to="/">{site.title}</Link> Copyright © Tyler Rilling 2001 - 2023. <br /> Site last updated:{` `} <a href="https://github.com/underlost/underlost.net/">{data.site.buildTime}</a>. ❤️ </div> </footer> </div> </div> <div className="page-bottom"></div> </div> </> ) } DefaultLayout.propTypes = { children: PropTypes.node.isRequired, bodyClass: PropTypes.string, isHome: PropTypes.bool, data: PropTypes.shape({ file: PropTypes.object, site: PropTypes.object, allGhostSettings: PropTypes.object.isRequired, }).isRequired, } const DefaultLayoutSettingsQuery = props => ( <StaticQuery query={graphql` query GhostSettings { allGhostSettings { edges { node { ...GhostSettingsFields } } } file(relativePath: { eq: "ghost-icon.png" }) { childImageSharp { gatsbyImageData(layout: FIXED) } } site { buildTime(formatString: "DD/MM/YYYY") } } `} render={data => <DefaultLayout data={data} {...props} />} /> ) export default DefaultLayoutSettingsQuery
window.onload = function() { var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), width = canvas.width = window.innerWidth, height = canvas.height = window.innerHeight; var weave = Weave.create(30, 20), model = { x: 0, y: 0, w: width, h: height, drawBG: false, shadowBlur: 5, autoBlur: true }, bg = document.createElement("img"); bg.src = "chocorua.jpg"; var rect = QuickSettings.create(10, 10, "Rect"); rect.setGlobalChangeHandler(draw); rect.bindRange("x", 0, 500, model.x, 1, model); rect.bindRange("y", 0, 500, model.y, 1, model); rect.bindRange("w", 100, width, model.w, 1, model); rect.bindRange("h", 100, height, model.h, 1, model); rect.bindBoolean("drawBG", false, model); var size = QuickSettings.create(10, 220, "Size"); size.setGlobalChangeHandler(draw); size.bindRange("tileSize", 20, 100, 30, 1, weave); size.bindRange("bandSize", 10, 90, 20, 1, weave); var style = QuickSettings.create(10, 340, "Style"); style.setGlobalChangeHandler(draw); style.bindColor("fillStyle", "#eeeeee", weave); style.bindColor("strokeStyle", "#999999", weave); style.bindRange("lineWidth", 1, 10, 1, 1, weave); style.bindBoolean("drawStroke", false, weave); var shadows = QuickSettings.create(700, 10, "Shadows"); shadows.setGlobalChangeHandler(draw); shadows.bindRange("shadowOffsetX", -10, 10, 0, 1, weave); shadows.bindRange("shadowOffsetY", -10, 10, 0, 1, weave); shadows.bindRange("shadowBlur", 0, 40, model.shadowBlur, 1, model); shadows.bindBoolean("autoBlur", model.autoBlur, model); draw(); function draw() { context.clearRect(0, 0, width, height); if(model.drawBG) { context.drawImage(bg, 0, 0); } if(model.autoBlur) { weave.shadowBlur = "auto"; } else { weave.shadowBlur = model.shadowBlur; } weave.render(context, model.x, model.y, model.w, model.h); } };
import React, {Component} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import Login from '../components/login'; import Header from '../components/header'; import Sidebar from '../components/sidebar'; class Main extends Component{ constructor(props, context){ super(props, context); this.state={ toggleSearch:false } } render(){ let userLocalStorage = JSON.parse(sessionStorage.getItem('userDetails')); return( <div>{((location.pathname!="/" && location.pathname!='/register' && location.pathname!="/enterEmail" && location.pathname!='/enterOTP' && location.pathname!='/enterNewPassword' && location.pathname!='/invite') && (this.props.activeUser!=null || userLocalStorage!=null))? (<div><Sidebar /> <Header /> </div>):(<div></div>)} <div>{this.props.children}</div></div>); } } Main.contextTypes = { router: React.PropTypes.object }; function mapStateToProps(state) { return { activeUser: state.activeUser }; } function matchDispatchToProps(dispatch){ return bindActionCreators({}, dispatch); } export default connect(mapStateToProps, matchDispatchToProps)(Main);
const initialState = { stocks: [], prices: [], totalEarnings: null, errors: [] } const stockReducer = (state = initialState, action) => { switch (action.type) { case 'LOAD_PORTFOLIO': return {...state, stocks: action.stocks} case 'ADD_STOCK': return {...state, stocks: [...state.stocks, action.stock]} case 'ADD_PRICE': let prices = state.prices.filter(price => price.symbol !== action.price.symbol) prices.push(action.price) return {...state, prices: prices} case 'INCREASE_SHARES': let stocks = state.stocks.filter(stock => stock.id !== action.stock.id) stocks.push(action.stock) return {...state, stocks: stocks} case 'SET_TOTAL_EARNINGS': // this was an attempt to solve a datatype issue when loading prices, still working // let total // if (action.total.includes(NaN)) { // total = null // } else if (action.total.length === 1) { // total = action.total[0] // } else if (action.total.length === 0) { // total = 0 // } else { // total = action.total.reduce((t, n) => t + n) // } return {...state, totalEarnings: action.total} case 'RESET_STOCKS': return initialState case 'STOCK_ERRORS': return {...state, errors: action.errors} case 'CLEAR_STOCK_ERRORS': return {...state, errors: []} default: return state } } export default stockReducer
import React, { useState, useEffect } from "react"; import axios from "axios"; import TextField from '@material-ui/core/TextField'; import Button from '@material-ui/core/Button'; import MenuItem from '@material-ui/core/MenuItem'; import Snackbar from '@material-ui/core/Snackbar'; import MuiAlert from '@material-ui/lab/Alert'; function Alert(props) { return <MuiAlert elevation={6} variant="filled" {...props} />; } const AssignCourses = (props) => { const [user, setUser] = useState(""); const [course, setCourse] = useState(""); const [allUsers, setAllUsers] = useState([]); const [allCourses, setAllCourses] = useState([]); const token = localStorage.getItem('token') const userID = localStorage.getItem('userID') const role = localStorage.getItem('role') const auth = { headers: { token } } const [open, setOpen] = React.useState(false); const handleClose = (event, reason) => { if (reason === 'clickaway') { return; } setOpen(false); }; useEffect(() => { if (props.role === "student") { axios.get("http://localhost:8080/users/allStudents", auth) .then(res => setAllUsers(res.data)) .catch(err => console.log(err.response.data)) } if (props.role === "staff") { axios.get("http://localhost:8080/users/allStaff", auth) .then(res => setAllUsers(res.data)) .catch(err => console.log(err.response.data)) } axios.get("http://localhost:8080/courses/find/all", auth) .then(res => setAllCourses(res.data)) .catch(err => console.log(err.response.data)) }, []) const handelSubmit = async (e) => { e.preventDefault(); try { const data = { user, course, role: props.role }; const res = await axios.post("http://localhost:8080/courses/assignCoursesForAll", data, auth) console.log(res.data); setOpen(true) setUser("") setCourse("") } catch (error) { console.log(error.response.data) } }; return ( <div className="container" style={{ margin: "auto 200px", alignItems: 'center' }}> <form onSubmit={handelSubmit}> <TextField id="standard-select-currency" select fullWidth // variant="outlined" label="select user" className="mt-3" value={user} onChange={(event) => setUser(event.target.value)} // helperText="Please select your course" > {allUsers && allUsers.map(user => ( <MenuItem key={user._id} value={user._id}> {user.firstName} {user.lastName} {user._id} </MenuItem> ))} </TextField> {/* <div> <label className="form-label" htmlFor="user"> user </label> <select className="form-select" id="user" value={user} onChange={(event) => setUser(event.target.value)} > <option value="">--select user--</option> {allUsers.map(user => { return <option key={user._id} value={user._id}> {user.name} </option> })} </select> </div> */} <TextField id="standard-select-currency" select fullWidth // variant="outlined" label="select course" className="mt-3" value={course} onChange={(event) => setCourse(event.target.value)} // helperText="Please select your course" > {allCourses && allCourses.map(course => ( <MenuItem key={course._id} value={course._id}> {course.name} - {course.code} </MenuItem> ))} </TextField> {/* <div> <label className="form-label" htmlFor="course"> course </label> <select className="form-select" id="course" value={course} onChange={(event) => setCourse(event.target.value)} > <option value="">--select course--</option> {allCourses.map(course => { return <option key={course._id} value={course._id}> {course.season} - {course.year} </option> })} </select> </div> */} <Button size="medium" className="mt-5" variant="contained" color="primary" onClick={handelSubmit}> Submit </Button> <Snackbar open={open} autoHideDuration={3000} onClose={handleClose}> <Alert onClose={handleClose} severity="success"> Course assigned successfully ! </Alert> </Snackbar> {/* <button type="submit" className="btn btn-primary mt-3"> Submit </button> */} </form> </div> ); }; export default AssignCourses;
import Vue from 'vue' import App from './App' import './assets/iconfont/iconfont.css' import router from './router' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import Validator from 'vue-validator' // 导入全局样式 import '@/assets/css/global.css' import less from 'less' import VueCookies from 'vue-cookies' import store from '@/store' // 引入xss import VueXss from 'vue-xss' // 引入Echarts import echarts from 'echarts' // 导出日志 import JsonExcel from 'vue-json-excel' // 日期转换 import Moment from 'moment' // 引入axios import axios from 'axios' Vue.use(VueXss) Vue.prototype.$echarts = echarts Vue.component('downloadExcel', JsonExcel) Vue.prototype.moment = Moment Vue.prototype.$http = axios Vue.config.productionTip = false Vue.use(less) Vue.use(VueCookies) Vue.prototype.$http = axios Vue.config.productionTip = false axios.defaults.baseURL = '/api' // axios.defaults.baseURL="http://39.97.102.209:80/api/"; Vue.use(Validator) Vue.use(ElementUI) // 注册一个全局自定义指令 v-focus Vue.directive('focus', { // 当绑定元素插入到 DOM 中。 inserted: function (el) { // 聚焦元素 el.focus() } }) // 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题 // const originalPush = router.prototype.push // router.prototype.push = function push(location) { // return originalPush.call(this, location).catch(err => err) // } // eslint-disable-next-line no-new new Vue({ el: '#app', router, store, components: { App }, template: ` <App/> ` })
const { checkRole } = require('../framework/middleware'); const { USER_ROLES } = require('./constants'); // NOTE: JWT token is checked at top level const userAuth = () => checkRole([USER_ROLES.ROLE_STANDARD, USER_ROLES.ROLE_ADMIN]); const adminAuth = () => checkRole(USER_ROLES.ROLE_ADMIN); module.exports = { userAuth, adminAuth, };
import styled from 'styled-components'; // notice: react native flex vs css flex is DIFFERENT for flex-grow, // flex-shrink default value // refer to: // https://github.com/styled-components/styled-components/issues/465 export const Flex = styled.View` flex: 1 0; `; export const RowFlex = styled.View` flex: 1 0; flex-direction: row; `; export const ColumnFlex = styled.View` flex: 1 0; flex-direction: column; `; export const ThemeFlex = styled(Flex)` background-color: ${props => props.theme.backgroundColor}; `;
const express = require('express'); const router = express.Router(); const index = require('../models/index'); // There are a few more actions defined for routes in the index model. router.get('/', (req, res, next) => { index.all((err, beers) => { res.render('index', { beers, title: 'Liftopia' }); }); }); module.exports = router;
describe('P.views.calendar.Workouts', function() { var View = P.views.calendar.Workouts, region = P.views.calendar.Cal.prototype; beforeEach(function() { spyOn(region, 'initialize'); spyOn(region, 'render'); var promise = new Promise(function() {}); spyOn(P.Collection.prototype, 'pFetch') .and.returnValue(promise); }); it('displays P.views.calendar.Layout on render', function() { var view = new View(); view.render(); expect(region.render.calls.count()).toBe(1); }); it('should set this.date to the first day of the month of year and month supplied', function() { // expect string values because of url route source var view = new View({ year: '2014', month: '2' }); expect(view.moment.format('YYYY-MM-DD')).toBe('2014-03-01'); }); describe('loadWorkouts', function() { it('loads the workouts from the first day of the month if it is a Sunday for all timezones', function() { var view = new View({ year: '2015', month: '10' }); var start = P.Collection.prototype.pFetch.calls.argsFor(0)[0].data.start; var expected = 1446336000; // UTC November 1, 2015 00:00:00 expect(parseInt(start, 10)).toBeLessThan(expected); }); }); it('sets the title to the month and year', function() { var view = new View({ year: '2014', month: '3' }); view.render(); expect(document.title).toBe('April 2014 | WorkoutFeed'); }); });
function asideDisplay (state=[], action) { // console.log('action', action); // console.log("modal reducer has been triggered!"); switch (action.type) { case 'OPEN_ASIDE': let popupId = action.id.match(/\d+/g).join(); return { ...state, showAside: true, asideText: popupId }; case 'CLOSE_ASIDE': return { ...state, showAside: false, // asideText: '', // clearing this too quick, causes glitch on close }; default: return state; } // console.log(state, action) // return state; } export default asideDisplay;
const breakPoint = 0; let countDrops = 0; function drop(floor) { countDrops++; return floor >= breakPoint } function findBreakingPoint(floors) { let interval = 14; let previousFloor = 0; let egg1 = interval; /**Drop egg1 at decreasing intervals */ while (!drop(egg) && egg1 <= floors) { interval--; previousFloor = egg1; egg += interval; } /**Drop egg2 at 1 unit increment */ while (egg2 < egg1 && egg2 <= floors && !drops(egg)) { egg2++; } return egg2 < floors ? egg2 : -1 }
import Link from 'next/link'; import styled from 'styled-components'; import Title from '../Title'; const Container = styled.section` display: flex; width: 100%; padding: 96px 20%; align-items: center; justify-content: space-between; background: ${({ theme }) => theme.colors.grayBackground}; border-top: 1px solid #e8e8e8; `; const Img = styled.img``; function Refund({ fontSize, fontColor, children }) { return ( <Container> <img alt="emoji" src="https://d233wbzwz46uqm.cloudfront.net/assets/smartmei/img-press-1-cc544924e8cda8eed5890cfb6105f9af900f98c6adcd03b4318dee631b363e82.svg" /> <img alt="emoji" src="https://d233wbzwz46uqm.cloudfront.net/assets/smartmei/img-press-2-ed6ebd2960602c80a444f857458d84d4b7fe0739ad51a040be1a90e495f7af79.svg" /> <img src="https://d233wbzwz46uqm.cloudfront.net/assets/smartmei/img-press-3-ed53e454191be33fd124b56973e37f7d9c281d9b7879acb3a36783c12a18b721.svg" alt="emoji" data-original="https://d233wbzwz46uqm.cloudfront.net/assets/smartmei/img-press-3-ed53e454191be33fd124b56973e37f7d9c281d9b7879acb3a36783c12a18b721.svg" /> <img src="https://d233wbzwz46uqm.cloudfront.net/assets/smartmei/img-press-4-86c7e6fb6a9b41c9dbce0c39dd5dc43c4109c4af786bdb97ee1545177282919e.svg" alt="emoji" data-original="https://d233wbzwz46uqm.cloudfront.net/assets/smartmei/img-press-4-86c7e6fb6a9b41c9dbce0c39dd5dc43c4109c4af786bdb97ee1545177282919e.svg" /> </Container> ); } export default Refund;
var gulp = require('gulp'); var mainBowerFiles = require('main-bower-files'); module.exports = function () { var setup = this.opts.setup; var asserts = setup.asserts; return gulp.src(mainBowerFiles(), {base: asserts.base.bower}) .pipe(gulp.dest(asserts.vendor, {cwd: asserts.base.src})); };
;!function(win){ var gy= win.gy; return gy = { /* * * */ isContain:function(parentOjb,targetObj){ return $(targetObj).closest(parentOjb).length ? true : false; } } }(window);
import express from "express"; import cors from "cors"; import AlienRouter from "./Router/alien.js"; import PartyRouter from "./Router/party.js"; import RegisterRouter from "./Router/register.js"; const app = express(); app.use(express.json()); app.use(cors()); app.use("/alien", AlienRouter); app.use("/party", PartyRouter); app.use("/register", RegisterRouter); app.use((err, req, res, _) => { console.log(`${req.method} ${req.baseUrl} - ${err.message}`); res.status(400).send({ error: err.message }); }); export default app;
import React, { Component } from 'react'; import { Text, StyleSheet } from 'react-native'; export default class MyComponent extends Component { render() { return <Text style={styles.welcome}>My Component</Text>; } } const styles = StyleSheet.create({ welcome: { fontSize: 20, textAlign: 'center', margin: 10 } });
import React from 'react'; import PropTypes from 'prop-types'; import {Redirect} from 'react-router-dom'; import classes from './index.module.css'; import {languageHelper} from '../../tool/language-helper'; import {removeUrlSlashSuffix} from '../../tool/remove-url-slash-suffix'; import './space.jpg'; class PageNoFoundReact extends React.Component { constructor(props) { super(props); // i18n this.text = PageNoFoundReact.i18n[languageHelper()]; } render() { const pathname = removeUrlSlashSuffix(this.props.location.pathname); if (pathname) { return (<Redirect to={pathname} />); } return ( <div className="cell-wall" style={{ background:'url("https://images2.alphacoders.com/644/644457.jpg") no-repeat', height:'62.5vw', width:'100%', backgroundSize:'100% 100%' }} > <div className="cell-membrane"> <div className="d-flex" style={{height:'250px',marginLeft:'100px',marginTop:'100px'}} > <div> <img src="https://weareblend.la/wp-content/themes/blend-wp-theme/images/404/astronaut.png" className={classes.astronaut} /> </div> <div style={{marginLeft:'200px'}} className="justify-content-center"> <p style={{textAlign:'center'}}className={classes.font404}>404</p> <p className={classes.text}>We told you not to stray too far from the ship!</p> </div> </div> <div className="d-flex justify-content-center"> <div className={classes.button} style={{marginRight:'60px'}}>返回</div> <div className={classes.button}>刷新</div> </div> </div> </div> ); } } PageNoFoundReact.i18n = [ {}, {} ]; PageNoFoundReact.propTypes = { // self // React Router match: PropTypes.object.isRequired, history: PropTypes.object.isRequired, location: PropTypes.object.isRequired }; export const PageNoFound = PageNoFoundReact;
import React from 'react' import LoginForm from '../components/Form/LoginForm' import {Box} from '@chakra-ui/react' function Login(){ return( <Box > <LoginForm/> </Box> ) } export default Login
/** * Created by xuwusheng on 15/12/18. */ define(['../../../app','../../../services/platform/integral-mall/ordeImportService','../../../services/uploadFileService'], function (app) { var app = angular.module('app'); app.controller('ordeImportCtrl', ['$rootScope', '$scope','$timeout', '$state', '$sce', '$filter', 'HOST', '$window','ordeImport','uploadFileService', function ($rootScope, $scope,$timeout, $state, $sce, $filter, HOST, $window,ordeImport,uploadFileService) { //table头 $scope.thHeader = ordeImport.getThead(); /*var pmsSearch = ordeImport.getSearch(); pmsSearch.then(function (data) { $scope.searchModel = data.query; //设置当前作用域的查询对象 //获取table数据 get(); }, function (error) { console.log(error) });*/ //查询 //$scope.searchClick = function () { // $scope.paging = { // totalPage: 1, // currentPage: 1, // showRows: $scope.paging.showRows // }; // get(); //} $scope.exParams = ''; function get() { //获取选中 设置对象参数 var opts = angular.extend({}, $scope.searchModel, {}); //克隆出新的对象,防止影响scope中的对象 $scope.exParams = $filter('json')({query: opts}); var promise = ordeImport.getDataTable( '/giftOrder /searchData', { param: { query: opts } } ); promise.then(function (data) { if(data.code==-1){ alert(data.message); $scope.result = []; return false; } $scope.result = data.grid; // $scope.paging.totalPage = data.total; }, function (error) { console.log(error); }); } //导入 $scope.isShow=true; $scope.impUploadFiles= function (files) { if(files.length==0) return false; //多文件上传 var count=0; function upFiles(){ uploadFileService.upload('/giftOrder/importExcel',files[count],function(evt){ //进度回调 var progressPercentage = parseInt(100.0 * evt.loaded / evt.total); $scope.impUploadFilesProgress=evt.config.data.file.name+'的进度:'+progressPercentage+'%'; }).then(function (resp) { //上传成功 $scope.impUploadFilesProgress='上传完成!'; //get(); alert( resp.data.status.msg); $timeout(function(){ $scope.isShow = false; },3000); if(resp.data.status.code=="0000"){ $scope.result = resp.data.grid; $scope.query =resp.data.query; } count++; if(files.length>count) upFiles(); }); } upFiles(); } //确认导入 $scope.confirmImpor=function(){ if($scope.result) { var opts = { grid: {grid: $scope.result} } ordeImport.getDataTable('/giftOrder/addOrderAndDetail', {param: opts}) .then(function (data) { if(data.code==-1){ alert(data.message); }else if(data.status.code=="0000") { alert(data.status.msg, function () { $state.go('main.giftOrders'); }); }else alert(data.status.msg); }); }else{ alert('请导入数据!'); } } //取消导入 $scope.cancel=function(){ var like=window.confirm("确认取消导入订单信息?"); if(like){ $state.go('main.giftOrders'); } } }]) });
describe("P.views.workouts.view.Layout", function() { var View = P.views.workouts.view.Layout, Model = P.models.workouts.Template, $fetchDefer; PTest.routing(View, 'workouts/template/view/mock-123', false); beforeEach(function() { if (!Sisse.getUser.and) { spyOn(Sisse, 'getUser') .and.returnValue(new Backbone.Model({ id: 'me' })); } $fetchDefer = $.Deferred(); spyOn(Model.prototype, 'fetch') .and.returnValue($fetchDefer); }); describe('deleting workouts', function() { var view, resolve, reject; beforeEach(function() { var promise = new Promise(function() { resolve = arguments[0]; reject = arguments[1]; }); var model = new Model({ id: 'mock-123', who: 'me' }); view = new View({ model: model }); view.model.$loading = false; view.render(); spyOn(view.model, 'pDestroy') .and.returnValue(promise); spyOn(window, 'confirm'); }); it('requires window.confirm to continue', function() { window.confirm.and.returnValue(false); view.$('.js-workout-delete') .click(); expect(view.model.pDestroy.calls.count()) .toBe(0); }); describe('confirmed', function() { beforeEach(function() { window.confirm.and.returnValue(true); }); it('destroys the workout', function() { view.$('.js-workout-delete:eq(0)') .click(); expect(view.model.pDestroy.calls.count()) .toBe(1); }); it('disables the delete button', function() { view.$('.js-workout-delete:eq(0)') .click(); expect(view.$('.js-workout-delete') .is('.disabled')) .toBe(true); }); it('redirects to the workout library when the promise is resolved', function(done) { spyOn(P.common.PubSub, 'navigate'); var fn = P.behaviors.WorkoutDestroy.prototype.onDelete; spyOn(P.behaviors.WorkoutDestroy.prototype, 'onDelete') .and.callFake(function() { fn.apply(this, arguments); expect(P.common.PubSub.navigate) .toHaveBeenCalledWith('/library/workouts'); done(); }); view.$('.js-workout-delete:eq(0)') .click(); resolve(); }); it('resets the button if delete fails', function(done) { var fn = P.behaviors.WorkoutDestroy.prototype.onDeleteFail; spyOn(P.behaviors.WorkoutDestroy.prototype, 'onDeleteFail') .and.callFake(function() { fn.apply(this, arguments); expect(view.$('.js-workout-delete') .is('.disabled')) .toBe(false); done(); }); view.$('.js-workout-delete:eq(0)') .click(); reject({ resp: null }); }); }); }); });
var array=['javascript','jquery','html','css']; var newarray=array.map(capitalise).toString(); function capitalise(word){ return word.toUpperCase(); } console.log(newarray);
const testResultXML2JSON = require("../testResultXML2JSON"); describe("testResultXML2JSON middleware", () => { const mockReq = { body: "" }; const mockResObj = () => { const res = {}; res.status = jest.fn().mockReturnValue(res); res.send = jest.fn(/*function(s){console.log('######',s);return res;}*/); return res; }; const mockRes = mockResObj(); const mockNext = jest.fn(); afterEach(() => { mockRes.status.mockClear(); mockRes.send.mockClear(); mockNext.mockClear(); }); it("should send 400 if the does not have mcq-test-results", () => { mockReq.body = ""; //invokeCase(false); testResultXML2JSON(mockReq, mockRes, mockNext); //expect(mockRes.send.mock.calls.length).toBe(1); }); invokeCase = isSuccessful => { testResultXML2JSON(mockReq, mockRes, mockNext); if (isSuccessful) { expect(mockRes.status.mock.calls.length).toBe(0); expect(mockRes.send.mock.calls.length).toBe(0); expect(mockNext.mock.calls.length).toBe(1); } else { expect(mockRes.status.mock.calls.length).toBe(1); expect(mockRes.status.mock.calls[0][0]).toBe(400); expect(mockRes.send.mock.calls.length).toBe(1); expect(mockRes.send.mock.calls[0][0]).toBe( "The structure of the request does not comply with expected structure" ); expect(mockNext.mock.calls.length).toBe(0); } }; });
const mongoose = require('mongoose'); const httpStatus = require('http-status'); const { omitBy, isNil } = require('lodash'); const bcrypt = require('bcryptjs'); const moment = require('moment-timezone'); const jwt = require('jwt-simple'); const uuidv4 = require('uuid/v4'); const APIError = require('../utils/APIError'); const { env, jwtSecret, jwtExpirationInterval } = require('../../config/vars'); const dataexplorerSchema = new mongoose.Schema({ connString: String, payload: { timePeriod : String, startTime : String, endTime : String, tag:[], skip: Number, take: Number, maxReductionPoints:Number, userID: String, sessionID: String, resource: String } }); dataexplorerSchema.method({ transform() { const transformed = {}; const fields = ['connString','payload']; fields.forEach((field) => { transformed[field] = this[field]; }); return transformed; }, }); module.exports = mongoose.model('DataExplorerSchema', dataexplorerSchema);
var searchData= [ ['parameters_5f',['parameters_',['../classopen3d_1_1camera_1_1_pinhole_camera_trajectory.html#a97289c86dbb9c354c592cd741ecf4eea',1,'open3d::camera::PinholeCameraTrajectory']]] ];
import React, { useEffect, useState } from 'react'; import { NavBar, Icon } from 'antd-mobile'; import { useHistory } from 'react-router-dom' import { Contain } from './Ticket.styled.js' import { get } from "@u/http"; const AboutUs = (props) => { const [coll, setColl] = useState(); useEffect(() => { (async () => { let ru = await get("/api/collection") setColl(ru) })() }, []) const history = useHistory(); return ( <Contain> <NavBar mode="light" icon={<Icon type="left" />} onLeftClick={() => history.push('/') } >优惠券</NavBar> <main> <ul> <li> <div className='top'> <span className="span1">店铺优惠券</span> <span className="span2">新用户注册优惠券</span> <span className="span3">¥</span> <span className="span4">10</span> <div className='full'><span className="span7">满100-10元</span></div> </div> <div className="second"> <span className="span5">不可与其他优惠共同使用</span> <span className="span6">在线支付专享</span> <div className='use' onClick={() => history.push('/Home')}><span className="span8">立即使用</span></div> </div> </li> <li> <div className='top'> <span className="span1">店铺优惠券</span> <span className="span2">新用户注册优惠券</span> <span className="span3">¥</span> <span className="span4">5</span> <div className='full'><span className="span7">满80-5元</span></div> </div> <div className="second"> <span className="span5">不可与其他优惠共同使用</span> <span className="span6">在线支付专享</span> <div className='use' onClick={() => history.push('/Home')}><span className="span8">立即使用</span></div> </div> </li> </ul> </main> </Contain> ); } export default AboutUs;
//var MAX_TOTAL_BYTES = 2097152; var MAX_TOTAL_BYTES = 104857600; var filesSize = new Array(); function OnFileSelected(sender, args) { var fileName = args.get_fileName(); var temp = fileName.split("."); var ext = temp[temp.length - 1]; if (!(ext == "pdf" || ext == "xls" || ext == "xlsx")) { alert(ext + " file type is invalid. System only allows PDF or EXCEL."); sender.deleteFileInputAt(0); sender.updateClientState(); return; } if (fileName.indexOf("&") > 1) { alert(fileName + " is invalid file name, can't contain ampersand (&)"); sender.deleteFileInputAt(0); sender.updateClientState(); return; } if (fileName.indexOf("#") > 1) { alert(fileName + " is invalid file name, can't contain hash (#)"); sender.deleteFileInputAt(0); sender.updateClientState(); return; } } function OnProgressUpdating(sender, args) { filesSize = new Array(); filesSize[args.get_data().fileName] = args.get_data().fileSize; } function OnFileUploaded(sender, args) { var totalBytes = 0; for (var index in filesSize) { totalBytes += filesSize[index]; } //if (totalBytes > MAX_TOTAL_BYTES) { // alert("File size is over the limit. System only allows 2MB per attach file size."); // sender.deleteFileInputAt(0); // sender.updateClientState(); //} }
/* Copyright 2016-2018 Stratumn SAS. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ export default { init(a, b, c) { this.state = { a, b, c }; this.append(); }, action(d) { this.state.d = d; this.append(); }, testLoadSegments() { if (this.meta.refs != null) { const segmentPromises = this.meta.refs.map(ref => this.loadSegment(ref) .then(seg => (seg ? 1 : 0)) .catch(() => -1) ); Promise.all(segmentPromises).then(segs => { this.state.nbSeg = segs.reduce((a, b) => a + (b > 0 ? 1 : 0), 0); this.state.nbErr = segs.reduce((a, b) => a + (b < 0 ? 1 : 0), 0); this.state.nbNull = segs.reduce((a, b) => a + (b === 0 ? 1 : 0), 0); this.append(); }); } } };
function getByClass(oParent , name){ var aElem = oParent.getElementsByTagName('*'); var aResult = []; for(var i=0;i<aElem.length;i++){ if(aElem[i].className==name){ aResult.push(aElem[i]); } } return aResult; }
"use strict"; let $ = require("jquery"); let controller = require("./controller"); let userFactory = require("./userFactory"); let db = require('./movieFactory'); let $container = $('.container'); let templates = require('./templateBuilder'); //When the user clicks the log in link, this calls the function to log them in with firebase $("#log-on").click( function() { $("#log-out").addClass("hideIt"); $(".messagePreLogin").addClass("hideIt"); userFactory.logInGoogle() .then( (result) => { $("#search-bar").prop("disabled", false); let user = result.user.uid; console.log("user", user); $("#log-out").removeClass("hideIt"); $(".messagePostLogin").removeClass("hideIt"); }); }); //When the user clicks the log out link, this calls the function to log them out //it also refreshes the page so that the user returns to the default website $("#log-out").click( function() { $("#log-out").addClass("hideIt"); userFactory.logOutGoogle(); location.reload(); }); $(document).on("click", ".card-link", function() { let movieId = $(this).data("add-watch"); $(`#${movieId}-add-watchlist`).addClass("hideIt"); $(`#${movieId}-stars-container`).removeClass("hideIt"); let title = $(`#${movieId}-title`).text(); controller.addToWatchList(movieId, title); }); $(document).on("click", ".star", function() { let thisStarIndex = $(this).attr("id").split("-"); let starMovieId = thisStarIndex[0]; console.log(thisStarIndex); for (let i = 1; i <= thisStarIndex[2]; i++) { document.getElementById(`${thisStarIndex[0]}-star-${i}`).classList.add("rated"); } }); $(document).keypress(function(e) { var key = e.which; if(key == 13) { $container.html(""); let searchValue = $("#search-bar").val(); db.getMovies(searchValue); db.printUserMovies(); } }); $("#unwatched").click(function() { $container.html(""); db.printUserMovies() .then((movieData) => { console.log("movieData", movieData); console.log("object key?", Object.keys(movieData)); $.each(movieData, (index, movie) => { if(movie.watched === false) { console.log("movie", movie.cast); let completedCard = templates.buildMovieCard(movie[index]); $container.append(completedCard); } }); }); });
import React from 'react'; import Course from './course.component.jsx'; import CourseService from './../services/courseService.js'; class CourseSales extends React.Component { constructor(props) { super(props); this.state = { total: 0, arrCourses: [] } } async testAsyncToGetAPI() { var arrTest = []; try { var res = await new CourseService().getAllCoursesAsync(); arrTest = res.data; console.log(arrTest); } catch (err) { console.log(err); } } componentDidMount() { CourseService.getAllCourses().then(res => { this.setState({ arrCourses: res.data }); }).catch(function (err) { console.log(err); }); } sumPrice(price) { this.setState({ total: this.state.total + price }); } render() { var courseList = this.state.arrCourses.map((item, i) => { return <Course name={item.name} price={item.price} key={i} sumPriceHandle={this.sumPrice.bind(this)} active={item.active} /> }); var totalRender = this.state.total <= 0 ? 0 : parseFloat(this.state.total).toFixed(2); return ( <div> <h1>You can buy courses:</h1> <div id="courses"> {courseList} <p id="total">Total: <b>${totalRender}</b></p> </div> <br /><br /> <button onClick={this.testAsyncToGetAPI.bind(this)}>Test Async</button> </div> ); } } export default CourseSales;
// Import React import React from "react"; import mapValues from "lodash/mapValues"; // Import Spectacle Core tags import { Appear, //BlockQuote, //Cite, CodePane, Deck, //Fill, Heading, Image, //Layout, Link, List, ListItem, //Markdown, //Quote, Slide, //Table, //TableRow, //TableHeaderItem, //TableItem, //Text } from "spectacle"; // Import image preloader util import preloader from "spectacle/lib/utils/preloader"; // Import theme import createTheme from "spectacle/lib/themes/default"; // Require CSS require("normalize.css"); require("./custom.css"); const slideTransition = ["slide"]; const images = mapValues( { bundler: require("../images/bundler.png"), danger: require("../images/danger.png"), flow: require("../images/flow.png"), moduleCounts: require("../images/module-counts.png"), survivejs: require("../images/survivejs.png"), testTower: require("../images/test-tower.png"), typeScript: require("../images/typescript.png"), }, v => v.replace("/", "") ); preloader(images); const theme = createTheme({ primary: "white", secondary: "black", tertiary: "#09b5c4", quarternary: "rgba(255, 219, 169, 0.43)", }); theme.screen.components.codePane.fontSize = "60%"; export default class Presentation extends React.Component { render() { return ( <Deck transition={slideTransition} transitionDuration={500} theme={theme}> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={1} fit caps lineHeight={1} textColor="tertiary"> JavaScript Maintenance </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={1}>Agenda</Heading> <List> <Appear> <ListItem>Packaging</ListItem> </Appear> <Appear> <ListItem>Code Quality</ListItem> </Appear> <Appear> <ListItem>Infrastructure</ListItem> </Appear> <Appear> <ListItem>Documentation</ListItem> </Appear> <Appear> <ListItem>Future</ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/packaging/" textColor="white" > Packaging </Link> </Heading> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/packaging/where-to-start/" textColor="white" > Where to Start Packaging </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>The Growth of npm</Heading> <Image src={images.moduleCounts} margin="40px auto" height="364px" /> </Slide> <Slide transition={slideTransition}> <Heading size={2}>To Consume or to Develop?</Heading> <List> <Appear> <ListItem>Ideal - what we need already exists</ListItem> </Appear> <Appear> <ListItem> Reality - only a part of what we need already exists </ListItem> </Appear> <Appear> <ListItem>Problem - how can we find what we need?</ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition}> <Heading size={2} fit> Technical Problem - What to Do? </Heading> <List> <Appear> <ListItem>Use an existing package</ListItem> </Appear> <Appear> <ListItem>Enhance an existing package</ListItem> </Appear> <Appear> <ListItem>Take over an existing package</ListItem> </Appear> <Appear> <ListItem>Fork an existing package</ListItem> </Appear> <Appear> <ListItem>Develop your own package</ListItem> </Appear> <Appear> <ListItem> <b>Note:</b> "you do" vs. "they do". Accountability! </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition}> <Heading size={2}>More to Consider</Heading> <List> <Appear> <ListItem> Package consumption - during development, in production </ListItem> </Appear> <Appear> <ListItem>Public or private packages?</ListItem> </Appear> <Appear> <ListItem> Leverage npm package lookup algorithm, possible to intercept and modify (be careful!) </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/packaging/anatomy/" textColor="white" > Anatomy of a Package </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What Files Are Included</Heading> <List> <Appear> <ListItem> Code, metadata (package.json), documentation (README.md), license </ListItem> </Appear> <Appear> <ListItem> Larger projects have contribution instructions, changelog, CI/git/npm/lint/build configuration </ListItem> </Appear> <Appear> <ListItem> <b>package.json</b> - Only JSON (no comments :(), understand this well </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition}> <Heading size={2}>package.json</Heading> <List> <Appear> <ListItem> <i>scripts</i> - <code>npm run {`<name>`}</code>,{" "} <code>pre</code>, <code>post</code>, shortcuts (<code> npm start </code>, <code>npm t</code>) </ListItem> </Appear> <Appear> <ListItem> <i>bin</i>, <i>main</i>, <i>module</i> - Entry points </ListItem> </Appear> <Appear> <ListItem> <i>dependencies</i>, <i>devDependencies</i>,{" "} <i>peerDependencies</i> - Depends on the context! Also more types. </ListItem> </Appear> <Appear> <ListItem> <i>repository</i>, <i>homepage</i>, <i>bugs</i> - Links </ListItem> </Appear> <Appear> <ListItem>Even more fields, sometimes tooling metadata</ListItem> </Appear> <Appear> <ListItem>At minimum, publish files needed to run</ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/packaging/publishing/" textColor="white" > Publishing Packages </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>SemVer Explained</Heading> <List> <Appear> <ListItem>SemVer === {`<major>.<minor>.<patch>`}</ListItem> </Appear> <Appear> <ListItem>ComVer === {`<not compatible>.<compatible>`}</ListItem> </Appear> <Appear> <ListItem>EmoVer === {`<emotional>.<major>.<minor>`}</ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition}> <Heading size={2}>Publishing a Version</Heading> <List> <Appear> <ListItem> <code> npm version{" "} {`<x.y.z|(pre)major|(pre)minor|(pre)patch|prerelease>`} </code> </ListItem> </Appear> <Appear> <ListItem> Publish pre-release versions to gather feedback </ListItem> </Appear> <Appear> <ListItem> Version ranges - ^, ~, * (dangerous!), also {`>=`}, {`<`} and combinations, … </ListItem> </Appear> <Appear> <ListItem> Use <b>lockfiles</b> (<i>package-lock.json</i>, <i>yarn.lock</i>) to manage (npm5+, yarn) </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition}> <Heading size={2}>More to Consider</Heading> <List> <Appear> <ListItem> Deprecating - <code>npm deprecate</code> </ListItem> </Appear> <Appear> <ListItem> Unpublishing - Possible only first 24h (hello <b>leftpad</b>) </ListItem> </Appear> <Appear> <ListItem>Renaming - See deprecation</ListItem> </Appear> <Appear> <ListItem> Sharing authorship - Consider namespaces and teams </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/packaging/building/" textColor="white" > Building Packages </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Consider?</Heading> <List> <Appear> <ListItem>Which browsers and Node versions to support?</ListItem> </Appear> <Appear> <ListItem> What if we want to use custom language features? </ListItem> </Appear> <Appear> <ListItem>What if we want to use some other language?</ListItem> </Appear> <Appear> <ListItem> How to support tree shaking of modern bundlers? </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition}> <Heading size={2} fit> Communicating Where Code Should Work </Heading> <List> <Appear> <ListItem> Simple answer for Node - the <i>engines</i> field </ListItem> </Appear> <Appear> <ListItem>This doesn't work with the browsers, though!</ListItem> </Appear> <Appear> <ListItem> If you use JavaScript, then the client can use{" "} <Link href="https://www.npmjs.com/package/babel-preset-env"> babel-preset-env </Link>{" "} and{" "} <Link href="https://www.npmjs.com/package/browserslist"> browserslist </Link>{" "} to compile to the needed targets </ListItem> </Appear> <Appear> <ListItem> Set up a <i>postinstall</i> script to compile during development </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/packaging/standalone-builds/" textColor="white" > Standalone Builds </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>How Bundlers Work</Heading> <Image src={images.bundler} margin="40px auto" height="364px" /> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Consider?</Heading> <List> <Appear> <ListItem>Is a standalone build needed?</ListItem> </Appear> <Appear> <ListItem> If generated, enables bundler optimizations (Example: skip compilation in webpack) </ListItem> </Appear> <Appear> <ListItem> Use UMD for legacy support (likely disappears eventually) </ListItem> </Appear> <Appear> <ListItem> A standalone bundle can be pushed to a Content Delivery Network (CDN) </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/code-quality/" textColor="white" > Code Quality </Link> </Heading> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/code-quality/linting/" textColor="white" > Linting </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>Can You See the Problem?</Heading> <CodePane lang="javascript" source={require("raw-loader!../examples/bad-code.js")} margin="20px auto" overflow="overflow" /> <Appear> <div>Eat croissants anyway! This should be</div> </Appear> <Appear> <CodePane lang="javascript" source={require("raw-loader!../examples/good-code.js")} margin="20px auto" overflow="overflow" /> </Appear> <Appear> <div>to avoid eating too many croissants.</div> </Appear> </Slide> <Slide transition={slideTransition}> <Heading size={2}>Lint to Spot Problems</Heading> <List> <Appear> <ListItem> <Link href="https://eslint.org/">ESLint</Link> to rescue </ListItem> </Appear> <Appear> <ListItem> Ready-made presets (Airbnb, Standard, ...) and specific plugins (best practices for React, security etc.) </ListItem> </Appear> <Appear> <ListItem> <Link href="https://palantir.github.io/tslint/">TSLint</Link>{" "} for TypeScript,{" "} <Link href="https://stylelint.io/">Stylelint</Link> for CSS </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/code-quality/code-formatting/" textColor="white" > Code Formatting </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>Linting !== Formatting</Heading> <List> <Appear> <ListItem> A linter can capture <i>some</i> formatting related problems </ListItem> </Appear> <Appear> <ListItem> Specific tools -{" "} <Link href="http://editorconfig.org/">EditorConfig</Link>,{" "} <Link href="https://prettier.io/">Prettier</Link> </ListItem> </Appear> <Appear> <ListItem> Code (JavaScript, CSS) and configuration (JSON) can be automatically formatted. One less worry. </ListItem> </Appear> <Appear> <ListItem>The tooling doesn't capture all concerns</ListItem> </Appear> <Appear> <ListItem> Consider higher level aspects such as patterns, naming separately. Automate when possible. </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/code-quality/typing/" textColor="white" > Typing </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>The Value of Typing</Heading> <List> <Appear> <ListItem> Improved communication - if you know a type, communicate it </ListItem> </Appear> <Appear> <ListItem>Better auto-completion and refactoring</ListItem> </Appear> <Appear> <ListItem> New techniques - <b>property based testing</b> </ListItem> </Appear> <Appear> <ListItem>More information for interpreter</ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition}> <Image src={images.flow} margin="40px auto" height="100px" /> <List> <Appear> <ListItem> <Link href="https://flow.org/">Flow</Link> is a type checker, a separate tool to run </ListItem> </Appear> <Appear> <ListItem>Type as you go</ListItem> </Appear> <Appear> <ListItem> See also{" "} <Link href="https://www.npmjs.com/package/flow-coverage-report"> flow-coverage-report </Link>{" "} and{" "} <Link href="https://www.npmjs.com/package/flow-runtime"> flow-runtime </Link> </ListItem> </Appear> </List> <Appear> <CodePane lang="javascript" source={require("raw-loader!../examples/flow.js")} margin="20px auto" overflow="overflow" /> </Appear> </Slide> <Slide transition={slideTransition}> <Image src={images.typeScript} margin="40px auto" height="200px" /> <List> <Appear> <ListItem> <Link href="https://www.typescriptlang.org/">TypeScript</Link>{" "} is a language that compiles to JavaScript </ListItem> </Appear> <Appear> <ListItem> Some commonalities with Flow but also custom features (interfaces, classes) </ListItem> </Appear> <Appear> <ListItem> <Link href="https://github.com/niieani/typescript-vs-flowtype"> See the comparison by Bazyli Brzóska </Link> </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition}> <Heading size={2}>Type Definitions</Heading> <List> <Appear> <ListItem> Third party packages require <b>type definitions</b> to capture type errors related to them </ListItem> </Appear> <Appear> <ListItem>Easy to generate especially with TypeScript</ListItem> </Appear> <Appear> <ListItem> <Link href="http://definitelytyped.org/">DefinitelyTyped</Link>{" "} and{" "} <Link href="https://github.com/flowtype/flow-typed"> flow-typed </Link>{" "} host the definitions </ListItem> </Appear> <Appear> <ListItem> Problems: keeping up with package versions, something to maintain </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition}> <Heading size={2}>Challenges of Typing</Heading> <List> <Appear> <ListItem> Versioning - what if language definition changes? </ListItem> </Appear> <Appear> <ListItem> Package versions - how to manage conflicting dependencies? </ListItem> </Appear> <Appear> <ListItem> Better solution? -{" "} <Link href="https://reasonml.github.io/">Reason</Link> provides programmable type definitions </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/code-quality/testing/" textColor="white" > Testing </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Verify with Testing?</Heading> <List> <Appear> <ListItem> Do parts of the system work in isolation/together? </ListItem> </Appear> <Appear> <ListItem>Does the system perform well enough?</ListItem> </Appear> <Appear> <ListItem>Does the old API of the system still work?</ListItem> </Appear> <Appear> <ListItem>Do the tests cover the system well?</ListItem> </Appear> <Appear> <ListItem>What's the quality of the tests?</ListItem> </Appear> <Appear> <ListItem>Does the system solve user problems?</ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition}> <Heading size={2}>Types of Testing</Heading> <Image src={images.testTower} margin="40px auto" height="464px" /> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/code-quality/dependencies/" textColor="white" > Dependency Management </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2} fit> Keeping Dependencies Up to Date </Heading> <List> <Appear> <ListItem> A single broken dependency can bring down a project </ListItem> </Appear> <Appear> <ListItem> Constant progress - a challenge to keep up with the updates </ListItem> </Appear> <Appear> <ListItem> Bigger projects may provide <b>codemods</b> and migration paths </ListItem> </Appear> <Appear> <ListItem> Specific tooling exists to help with the problem. Examples:{" "} <code>yarn upgrade-interactive</code>,{" "} <Link href="https://www.npmjs.com/package/npm-upgrade"> npm-upgrade </Link>,{" "} <Link href="https://www.npmjs.com/package/updtr">updtr</Link> </ListItem> </Appear> <Appear> <ListItem>Good tests help a lot</ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/infrastructure/" textColor="white" > Infrastructure </Link> </Heading> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/infrastructure/processes/" textColor="white" > Processes </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Consider?</Heading> <List> <Appear> <ListItem> How to track issues (what data, how to capture) </ListItem> </Appear> <Appear> <ListItem>How to manage changes (pull requests)</ListItem> </Appear> <Appear> <ListItem> How to develop (branching model, coordination) </ListItem> </Appear> <Appear> <ListItem>How to maintain project focus</ListItem> </Appear> <Appear> <ListItem>How to support users</ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/infrastructure/continuous-integration/" textColor="white" > Continuous Integration </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Consider?</Heading> <List> <Appear> <ListItem>How to test against different environments?</ListItem> </Appear> <Appear> <ListItem>How to deploy to staging/production?</ListItem> </Appear> <Appear> <ListItem>How to prevent deploying something broken?</ListItem> </Appear> <Appear> <ListItem> Answer: Continuous Integration (CI) and Continuous Deployment (CD) systems </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/infrastructure/automation/" textColor="white" > Automation </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Automate?</Heading> <List> <Appear> <ListItem> Change logs (semi-automation) - Requires commit message convention but helps with communication </ListItem> </Appear> <Appear> <ListItem> Releases - Release after each commit to the <code>master</code>{" "} branch and determine type of release automatically based on the changes </ListItem> </Appear> <Appear> <ListItem> Testing - Git hooks help here. Consider{" "} <Link href="https://www.npmjs.com/package/husky">husky</Link>,{" "} <Link href="https://www.npmjs.com/package/lint-staged"> lint-staged </Link> </ListItem> </Appear> <Appear> <ListItem> GitHub meta validation -{" "} <Link href="https://www.npmjs.com/package/gh-lint"> gh-lint </Link> </ListItem> </Appear> <Appear> <ListItem> Project validation -{" "} <Link href="https://github.com/danger/danger-js">Danger</Link> </ListItem> </Appear> <Appear> <ListItem> Issue management -{" "} <Link href="https://github.com/open-bot/open-bot"> open-bot </Link>{" "} and more </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/documentation/" textColor="white" > Documentation </Link> </Heading> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/documentation/readme/" textColor="white" > README </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Consider?</Heading> <List> <Appear> <ListItem>Who is going to use the README?</ListItem> </Appear> <Appear> <ListItem> Conversion - Explain clearly what the project is about. </ListItem> </Appear> <Appear> <ListItem> Developer eXperience (DX) - Make it easy to get started and use the project. </ListItem> </Appear> <Appear> <ListItem>Licensing - Make license terms clear.</ListItem> </Appear> <Appear> <ListItem> Testing - Make sure README examples are executed as tests so they work. </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/documentation/change-log/" textColor="white" > Change Logs </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Consider?</Heading> <List> <Appear> <ListItem>Change Log !== Commit Log</ListItem> </Appear> <Appear> <ListItem> Document intent of the changes - what's new, what broke, how to migrate </ListItem> </Appear> <Appear> <ListItem> A part of DX - saves time of developers when done well </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/documentation/site/" textColor="white" > Site </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Consider?</Heading> <List> <Appear> <ListItem>Conversion - first chance to convert.</ListItem> </Appear> <Appear> <ListItem> Documentation - communicate how to use the project and how to develop it. </ListItem> </Appear> <Appear> <ListItem> Showcase - show how the project is being used to inspire developers. </ListItem> </Appear> <Appear> <ListItem>Testing - test the site as any software.</ListItem> </Appear> <Appear> <ListItem>Hosting - free options for static sites.</ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/documentation/api/" textColor="white" > API Documentation </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Consider?</Heading> <List> <Appear> <ListItem> Philosophy - explain high-level ideas of the solution. </ListItem> </Appear> <Appear> <ListItem> Typing - can you extract type information to documentation? </ListItem> </Appear> <Appear> <ListItem> Specific details - how something specific works and how parts fit together, typical use cases. </ListItem> </Appear> <Appear> <ListItem> User experience - different users need different kind of documentation. </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/documentation/misc/" textColor="white" > Other Types of Documentation </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2} fit> What Documentation to Provide? </Heading> <List> <Appear> <ListItem> Contribution guidelines - how to set up the project, how to develop, what kind of contributions do you expect? </ListItem> </Appear> <Appear> <ListItem> Code of Conduct - how to collaborate together, what's acceptable and what's not? </ListItem> </Appear> <Appear> <ListItem> Issue and Pull Request templates - how to write an issue or a pull request? </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/documentation/linting/" textColor="white" > Linting and Formatting </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2} fit> Lint and Format Documentation </Heading> <List> <Appear> <ListItem> Why - link validation, consistent terminology, improved language and grammar </ListItem> </Appear> <Appear> <ListItem> Starting points -{" "} <Link href="https://textlint.github.io/">textlint</Link>,{" "} <Link href="http://proselint.com/">proselint</Link> </ListItem> </Appear> <Appear> <ListItem> <Link href="https://www.npmjs.com/package/prettier"> Prettier </Link>{" "} can format Markdown too </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/future/" textColor="white" > Future </Link> </Heading> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/future/longevity/" textColor="white" > Longevity </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Consider?</Heading> <List> <Appear> <ListItem>Who is going to develop/fund/manage?</ListItem> </Appear> <Appear> <ListItem>What happens if developers disappear?</ListItem> </Appear> <Appear> <ListItem>How to attract new contributors?</ListItem> </Appear> <Appear> <ListItem> How to keep track of everything that's going on? </ListItem> </Appear> <Appear> <ListItem>How to maintain a popular project?</ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition} bgColor="secondary"> <Heading size={2} textColor="tertiary"> <Link href="https://survivejs.com/maintenance/future/marketing/" textColor="white" > Marketing </Link> </Heading> </Slide> <Slide transition={slideTransition}> <Heading size={2}>What to Consider?</Heading> <List> <Appear> <ListItem> To market or not? Is popularity a goal? Might happen anyway if you connect with a market. </ListItem> </Appear> <Appear> <ListItem> Approaches - technical marketing, content marketing, word of mouth </ListItem> </Appear> <Appear> <ListItem>The point of marketing - serving people</ListItem> </Appear> <Appear> <ListItem> Marketing isn't about getting everyone to use your project, it's about getting the <b>right</b> people to use your project </ListItem> </Appear> </List> </Slide> <Slide transition={slideTransition}> <Link href="https://www.survivejs.com/maintenance/"> <Heading size={1}>SurviveJS - Maintenance</Heading> </Link> <Image src={images.survivejs} margin="0px auto 40px" height="324px" /> <Link href="https://twitter.com/bebraw"> <Heading size={2} textColor="secondary" fit> by Juho Vepsäläinen and Artem Sapegin </Heading> </Link> </Slide> </Deck> ); } }
import { Template } from 'meteor/templating'; import { ReactiveVar } from 'meteor/reactive-var'; import './main.html'; //Tasks = new Mongo.Collection('tasks'); Meteor.subscribe('tasks'); Template.tasks.helpers({ tasks() { return Tasks.find({}, {sort: {createdAdd: -1}}); }, }); Template.tasks.events({ 'submit .add-task'(event) { var name = event.target.name.value; console.log(name); Meteor.call('addTask', name); event.target.name.value = ''; return false; }, 'click .delete-task'(event) { if (confirm('Delete Task?')) { Meteor.call('deleteTask', this._id); } return false; }, }); // Template.hello.onCreated(function helloOnCreated() { // // counter starts at 0 // this.counter = new ReactiveVar(0); // }); // Template.hello.helpers({ // counter() { // return Template.instance().counter.get(); // }, // }); // Template.hello.events({ // 'click button'(event, instance) { // // increment the counter when button is clicked // instance.counter.set(instance.counter.get() + 1); // }, // });
import React from 'react' import ReactDOM from 'react-dom' import {Router, Route, IndexRoute, browserHistory} from 'react-router' import './index.css' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap/dist/css/bootstrap-theme.css' import GalleryPage from './pages/GalleryPage/GalleryPage' import ArtistsPage from './pages/ArtistsPage/ArtistsPage' import NewArtPage from './pages/NewArtPage/NewArtPage' import NewArtistPage from './pages/NewArtistPage/NewArtistPage' import UserProfilePage from './pages/UserProfilePage/UserProfilePage' import PlaygroundPage from './pages/PlaygroundPage/PlaygroundPage' import ForgotPasswordPage from './pages/ForgotPasswordPage/ForgotPasswordPage' import ResetPasswordPage from './pages/ResetPasswordPage/ResetPasswordPage' import ExportConfigurationPage from './pages/ExportConfigurationPage/ExportConfigurationPage' import AboutPage from './pages/AboutPage/AboutPage' import LoginLayout from './components/layouts/login-layout/LoginLayout' import BaseLayout from './components/layouts/base/BaseLayout' import SimpleLayout from './components/layouts/simple/SimpleLayout' import CreateTemplatePage from './pages/CreateTemplatePage/CreateTemplatePage' import Login from './Login' import RegisterPage from './pages/RegisterPage/RegisterPage' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import { Provider } from 'react-redux' import { createStore, applyMiddleware, compose } from 'redux' import thunk from 'redux-thunk' import reducers from './redux/reducers' import * as constants from "./redux/constants" import injectTapEventPlugin from 'react-tap-event-plugin' injectTapEventPlugin() let store = createStore( reducers, {}, compose( applyMiddleware(thunk), window.devToolsExtension ? window.devToolsExtension() : f => f )) export let clearNotifications = (store) => { store.dispatch({type: constants.CLEAR_ALL_NOTIFICATIONS}) } export let clearCheckCards = (store) => { store.dispatch({type: constants.CLEAR_CHECK_CARDS}) } export let receiveCurrentUser = (store, currentUser) => { store.dispatch({type: constants.CURRENT_USER_RECIEVED, user: currentUser}) } export let hideLoader = (store) => { store.dispatch({type: constants.SHOW_LOADER, showLoader: false}) } export let clearSourceImage = (store) => { store.dispatch({type: constants.SOURCE_IMAGE_RECEIVED, sourceImage: ""}) } export let everyPageNavigation = store => { clearNotifications(store) clearCheckCards(store) let currentUser = JSON.parse(localStorage.getItem('currentUser')) || {} receiveCurrentUser(store, currentUser) hideLoader(store) clearSourceImage(store) } function requireAuth(store, checkLogin) { return (nextState, replace) => { everyPageNavigation(store) if(!localStorage.getItem('currentUser') || !localStorage.getItem('token')) { if(nextState.location.pathname !== "/" && checkLogin) { replace('/') } } else { if(nextState.location.pathname === "/") replace('/home') } }; } const router = ( <Provider store={store}> <MuiThemeProvider> <Router history={browserHistory}> <Route path="/" component={LoginLayout}> <IndexRoute component={Login} onEnter={requireAuth(store, false)}/> <Route path="/register" component={RegisterPage} onEnter={requireAuth(store, false)} /> <Route path="/forgotPassword" component={ForgotPasswordPage} onEnter={requireAuth(store, false)} /> <Route path="/resetPassword/:accessToken" component={ResetPasswordPage} onEnter={requireAuth(store, false)} /> <Route path="/about" component={AboutPage} onEnter={requireAuth(store, false)}/> </Route> <Route path="/home" component={BaseLayout} onEnter={requireAuth(store, true)}> <IndexRoute component={GalleryPage} onEnter={requireAuth(store, true)}/> <Route path="/artists" component={ArtistsPage} onEnter={requireAuth(store, true)}/> </Route> <Route component={SimpleLayout}> <Route path="/newArt" component={NewArtPage} onEnter={requireAuth(store, true)}/> <Route path="/newArtist" component={NewArtistPage} onEnter={requireAuth(store, true)}/> <Route path="/myUserProfile" component={UserProfilePage} onEnter={requireAuth(store, true)}/> <Route path="/createTemplate" component={CreateTemplatePage} onEnter={requireAuth(store, true)}/> <Route path="/exportConfiguration" component={ExportConfigurationPage} onEnter={requireAuth(store, true)}/> </Route> <Route path="/play" component={PlaygroundPage} /> </Router> </MuiThemeProvider> </Provider> ); ReactDOM.render(router, document.getElementById('root'));
const db = require('../models'); const jwt = require('jsonwebtoken'); const cookieParser = require('cookie-parser'); // for the auth token // Defining methods for the todosController module.exports = { create: function(req, res) { const decoded = jwt.decode(req.cookies.token); const todo = req.body; todo.UserId = decoded.id; db.Todo.create(req.body) .then(result => { res.json(result); }) .catch(err => { res.json(err); }); }, getById: function(req, res) { const decoded = jwt.decode(req.cookies.token); db.Todo.findAll({ where: { UserId: decoded.id } }).then((dbTodos, err) => { if (err) { res.status(500).send(err); } dbTodos.filter(todo => todo.id == req.params.id); res.json(dbTodos[0]); }); }, getAllForUser: function(req, res) { const decoded = jwt.decode(req.cookies.token); db.Todo.findAll({ where: { UserId: decoded.id } }).then((dbTodos, err) => { if (err) { res.status(500).send(err); } res.json(dbTodos); }); }, updateById: function(req, res) { const decoded = jwt.decode(req.cookies.token); db.Todo.findAll({ where: { UserId: decoded.id } }).then((dbTodos, err) => { if (err) { res.status(500).send(err); } dbTodos.filter(todo => todo.id == req.params.id); if (dbTodos[0]) { db.Todo.update(req.body, { where: { id: req.params.id } }) .then(newDbTodo => { if (newDbTodo) { res.json(newDbTodo); } }) .catch(err => res.json(err)); } }); }, deleteById: async function(req, res) { const decoded = jwt.decode(req.cookies.token); db.Sprint.findAll({ where: { UserId: decoded.id } }).then((dbSprints, err) => { if (err) { res.status(500).send(err); } dbSprints.filter(sprint => sprint.id == req.params.id); if (dbSprints[0]) { db.Sprint.destroy({ where: { id: req.params.id } }).then(destroyed => { res.sendStatus(200); }); } }); } };
import React from 'react'; import PropTypes from 'prop-types'; import { observable, computed } from 'mobx'; import { observer, inject } from 'mobx-react'; import { withRouter } from 'react-router'; import { withStyles } from '@material-ui/core/styles'; import Auth from '../modules/Auth'; import empty from 'is-empty'; import { menuStyles } from '../styles'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import ExpandLessIcon from '@material-ui/icons/ExpandLess'; import PersonIcon from '@material-ui/icons/Person'; import ExitToAppIcon from '@material-ui/icons/ExitToApp'; import Drawer from '@material-ui/core/Drawer'; import { Scrollbars } from 'react-custom-scrollbars'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemText from '@material-ui/core/ListItemText'; import Collapse from '@material-ui/core/Collapse'; import Divider from '@material-ui/core/Divider'; import Avatar from '@material-ui/core/Avatar'; import Icon from '@material-ui/core/Icon'; const UserProfile = observer(({ classes, user }) => ( <List className="text-center"> <ListItem> <Avatar> <PersonIcon /> </Avatar> <ListItemText classes={{ primary: classes.textColor }} primary={ user.name || 'No Name' } /> </ListItem> </List> )); const MenuList = observer(({ classes, menuList, logOut }) => ( <List> { menuList } <Divider className={classes.divider} /> <ListItem onClick={logOut} button > <ListItemIcon> <ExitToAppIcon classes={{ root: classes.iconColor }} /> </ListItemIcon> <ListItemText classes={{ primary: classes.textColor }} primary="Salir" /> </ListItem> </List> )); @observer class NestedListItem extends React.Component { @observable pageState = {}; /** * Class constructor. */ constructor (props) { super(props) // Set the initial component state. this.pageState = { open: this.props.initiallyOpen }; } /** * Change the nested list open state to open/close the Collapse component. */ handleNestedListToggle = () => { this.pageState.open = !this.pageState.open; }; /** * Render the component. */ render () { const { id, classes, icon, text, nestedItemList } = this.props; const { open } = this.pageState; return [ <ListItem key={id} onClick={this.handleNestedListToggle} button > <ListItemText classes={{ primary: classes.textColor }} primary={text} /> { open ? <ExpandLessIcon classes={{ root: classes.iconColor }} /> : <ExpandMoreIcon classes={{ root: classes.iconColor }} /> } </ListItem>, <Collapse key={`${id}_collapse`} in={open} timeout="auto" unmountOnExit > <List component="div" disablePadding> {nestedItemList} </List> </Collapse> ]; } }; // Define received props types for validation. NestedListItem.propTypes = { id: PropTypes.string.isRequired, nestedItemList: PropTypes.array.isRequired, text: PropTypes.string, icon: PropTypes.string, initiallyOpen: PropTypes.bool }; // Define default props values. NestedListItem.defaultProps = { text: '', icon: '', initiallyOpen: false }; @inject('parentState') @observer class MenuContainer extends React.Component { @observable pageState = {}; @computed get menuList () { const { menu } = this.props.parentState; return this.generateMenu(menu); } /** * Class constructor. */ constructor (props) { super(props); // Set the initial component state. this.pageState = { link: '', dialog: { open: false, title: '¿Realmente desea abandonar la página actual?', message: 'Se perderán TODOS los datos sin guardar del formulario.', } }; } /** * Execute before component first render. */ componentWillMount () { this.pageState.dialog.onClick = this.handleDialogChangePage; } /** * Generate the system menu. * * @param {oject} pages - object with the menu structure. * @return {object} the menu in JSX. */ generateMenu = (pageList, id) => { if (empty(pageList)) return null; const { classes } = this.props; const { pathname } = this.props.parentState; return pageList.map(page => { let key = id ? `${id}_${page.text}` : page.text; if (!page.link) { return ( <ListItem key={key} classes={{ primary: classes.textColor }} button > <ListItemText classes={{ primary: classes.textColor }} primary={page.text} /> </ListItem> ); } switch (typeof page.link) { case 'string': return ( <ListItem key={key} className={pathname == page.link ? classes.selectedOption : null} onClick={this.handleChangePage(page.link)} button > <ListItemIcon> <Icon classes={{ root: classes.iconColor }}>{page.icon}</Icon> </ListItemIcon> <ListItemText classes={{ primary: classes.textColor }} primary={page.text} /> </ListItem> ); case 'function': return ( <ListItem key={key} onClick={page.link} button > <ListItemText classes={{ primary: classes.textColor }} primary={page.text} /> </ListItem> ); case 'object': const nestedMenu = page.link; const open = nestedMenu.findIndex(row => row.link == pathname) != -1; return ( <NestedListItem key={key} id={key} classes={classes} text={page.text} icon={page.icon} initiallyOpen={open} nestedItemList={this.generateMenu(page.link, key)} /> ); default: return null; } }); }; /** * Go to the received page. */ handleChangePage = link => () => { document.activeElement.blur(); if (empty(link)) return; this.props.history.push(link); }; /** * Go to the spedified page on dialog accept. */ handleDialogChangePage = () => { this.pageState.dialog.open = false; this.props.history.push(this.pageState.link); }; /** * Log out the current user. */ handleLogOut = () => { Auth.deauthenticateUser(this.props.history); }; /** * Render the component. */ render () { const { open, classes, parentState } = this.props; return ( <Drawer classes={{ paper: classes.menu }} open={open} variant="persistent"> <Scrollbars> <UserProfile classes={classes} user={parentState.user} /> <Divider className={classes.divider} /> <MenuList classes={classes} menuList={this.menuList} logOut={this.handleLogOut} /> </Scrollbars> </Drawer> ); } } // Define received props types for validation. MenuContainer.propTypes = { open: PropTypes.bool.isRequired, history: PropTypes.object.isRequired, }; export default withStyles(menuStyles)(withRouter(MenuContainer));
angular.module('socially').directive('locationList', function () { return { restrict: 'E', templateUrl: 'client/orders/location-list/location-list.html', controllerAs: 'locationList', controller: function ($scope, $reactive) { $reactive(this).attach($scope); $scope.subscribe('locations'); $scope.subscribe('orderAbles'); $scope.helpers({ locations: function() { return Locations.find({}); }, orderAbles: function() { return OrderAbles.find({}); } }); $scope.orderAbleCount = function(locationId) { return OrderAbles.find({locationId: locationId}).count(); }; $scope.newLocation = {}; $scope.addLocation = function() { $scope.newLocation.owner = Meteor.user()._id; $scope.newLocation.createdAt = new Date(); Locations.insert($scope.newLocation); $scope.newLocation = {}; }; $scope.updateLocation = function(location) { Locations.update(location._id, { $set: { description: location.description, enabled: location.enabled } }); } $scope.removeLocation = function(location) { Locations.remove({_id: location._id}); }; } } });
const Lootable = require('../Lootable'); const craft = require('../../../craft/craftItem'); function Production(id, mapItemId, typeId, location, characterId, durability, inventoryId, invenorySize, preparingTime) { Lootable.apply(this, arguments); this.preparingTime=preparingTime; this.currentPreparingTime=null; this.currentFuelTime = null; this.isInAction = false; this.fuelTime = [new Array(1, 2500)]; } Production.prototype = Object.create(Lootable.prototype); Production.prototype.onOff = function (inventory, stacks) { let beforeAction = this.isInAction; let result = []; if (this.isInAction === true){ this.isInAction = false; }else if (this.currentFuelTime===null){ let isAddedFuel = false; for(let i=0; i<inventory.stacks.length; i++){ for (let j = 0; j<this.fuelTime.length; j++){ if (stacks[inventory.stacks[i]].item!==null&&stacks[inventory.stacks[i]].item.typeId === this.fuelTime[j][0]){ this.isInAction = true; result = inventory.removeItem(stacks, stacks[inventory.stacks[i]].item.typeId, 1); isAddedFuel = true; this.currentFuelTime=this.fuelTime[j][1]; } } if (isAddedFuel)break; } }else{ this.isInAction = true; } let isActionChange=false; if (beforeAction!==this.isInAction) isActionChange = true; return new Array(isActionChange, result); } Production.prototype.tick = function (inventory, stacks, recipeList, items) { let beforeAction = this.isInAction; let result = []; this.currentFuelTime--; if (this.currentFuelTime<=0){ ////////Get fuel let isAddedFuel = false; for (let i=0; i<inventory.stacks.length; i++){ if (stacks[inventory.stacks[i]].item!==null){ for (let j=0; j<this.fuelTime.length; j++){ if (stacks[inventory.stacks[i]].item.typeId === this.fuelTime[j][0]){ result = inventory.removeItem(stacks, stacks[inventory.stacks[i]].item.typeId, 1); this.currentFuelTime = this.fuelTime[j][1]; isAddedFuel = true; break } } } if (isAddedFuel) break; } if (!isAddedFuel){ this.currentFuelTime = null; this.onOff(); } } // let isAllIngredients; this.currentPreparingTime++; if (this.preparingTime<=this.currentPreparingTime){ this.currentPreparingTime = 0; //////Craft item for (let key in recipeList){ if (recipeList[key].instrumentId === this.id){ let craftResult = craft(inventory, stacks, recipeList[key], items); if (craftResult!==1 && craftResult!==2 && craftResult.length>0){ result = result.concat(craftResult); let craftedItem = inventory.addItem(stacks, recipeList[key].craftedTypeId, recipeList[key].outputAmount); result = result.concat(craftedItem); } // isAllIngredients = true; // for (let j=0; j<recipeList[i].ingredients.length; j++){ // let amount = recipeList[i].ingredients[j].amount; // for (let k=0; k<inventory.stacks.length; k++){ // if (stacks[inventory.stacks[k]].item!==null){ // if (stacks[inventory.stacks[k]].item.typeId === recipeList[i].ingredients[j].typeId){ // amount -=stacks[inventory.stacks[k]].size; // } // if (amount<=0) break; // if (k===inventory.stacks.length-1)isAllIngredients=false // } // } // if (!isAllIngredients) break; // } // if (isAllIngredients) { // craftedItemId = recipeList[i].craftedTypeId; // amount = recipeList[i].outputAmount; // break; // } } } } let isActionChange=false; if (beforeAction!==this.isInAction) isActionChange = true; return new Array(isActionChange, result); } module.exports = Production;
var n = parseInt(process.argv[2]); var a1 = 1; var a2 = 1; var a3 = 0; console.log(a1); console.log(a2); for(var i = 2; i <= n; i++){ a3 = a1 + a2; a1 = a2; a2 = a3; console.log(a3); }
function Renderer(canvas, gl) { this.canvas = canvas; this.gl = gl; this.aspectRatio = 0; this.fieldOfView = 70; this.screenSize = new vec2(); this.reshape(canvas.width, canvas.height); gl.clearColor(0,0,0,1); gl.enable(gl.DEPTH_TEST); this.initColorShader(gl); this.initTriangle(gl); this.bindObjectToColorShader(gl); this.objectRotation = 0; } // Load shaders, get attribute locations, and get uniform locations Renderer.prototype.initColorShader = function(gl) { // Shaders defined in index.html this.shaderProgramID = getShaderProgram(gl, "color_v", "color_f"); gl.useProgram(this.shaderProgramID); this.vertexAttributeID = gl.getAttribLocation(this.shaderProgramID, "vertex"); this.colorAttributeID = gl.getAttribLocation(this.shaderProgramID, "color"); this.mvpID = gl.getUniformLocation(this.shaderProgramID, "mvp"); gl.enableVertexAttribArray(0); gl.enableVertexAttribArray(1); }; Renderer.prototype.initTriangle = function(gl) { var vertices = [ -.5, -.5, 0, .5, -.5, 0, 0, .5, 0 ]; var colors = [ 1,0,0,1, 0,1,0,1, 0,0,1,1 ]; this.vbo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); this.numVertices = vertices.length / 3; this.cbo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.cbo); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW); }; Renderer.prototype.bindObjectToColorShader = function(gl) { gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo); gl.vertexAttribPointer(this.vertexAttributeID, 3, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, this.cbo); gl.vertexAttribPointer(this.colorAttributeID, 4, gl.FLOAT, false, 0, 0); }; Renderer.prototype.reshape = function(w, h) { this.screenSize.x = w; this.screenSize.y = h; this.aspectRatio = w / h; this.gl.viewport(0, 0, w, h); this.perspectiveMatrix = perspectiveAspect(this.aspectRatio, this.fieldOfView, 0.1, 5000.0); }; Renderer.prototype.update = function() { this.objectRotation += .25; if (this.objectRotation > 360) this.objectRotation -= 360; }; Renderer.prototype.draw = function(gl) { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); var viewMatrix = translate(0,0,-100); var mvp = mat4_x_mat4_chain( this.perspectiveMatrix, viewMatrix, scale(50,50,50), rotateX(this.objectRotation), rotateZ(this.objectRotation)); var mvpTranspose = mat4Transpose(mvp); gl.uniformMatrix4fv(this.mvpID, false, new Float32Array(mvpTranspose)); gl.drawArrays(gl.TRIANGLES, 0, this.numVertices); gl.flush(); };
import React, { Component } from 'react'; export class WordRender extends Component { constructor(props){ super(props); this.state ={ madLibOptions: 0 } this.wordMenu = this.wordMenu.bind(this); }; wordMenu(e){ e.preventDefault(); let madLibOption = [ this.props.original, "_Noun_", "_Adjective_", "_Verb_", "_BodyPart_", "_PersonInRoom_" ]; let i = Number(e.target.value)+1; if (i < madLibOption.length){ e.target.innerText = madLibOption[i]; e.target.value = i; } else if (i >= 6){ e.target.value = this.state.madLibOptions e.target.innerText = this.props.original } else { alert("Uh oh") } }; render(){ return( <button className="WordRender" onClick={this.wordMenu} value={this.state.madLibOptions} >{this.props.original}</button> ); } };
/* CC3206 Programming Project Lecture Class: 203 Lecturer: Dr Simon WONG Group Member: CHAN You Zhi Eugene (11036677A) Group Member: FONG Chi Fai (11058147A) Group Member: SO Chun Kit (11048455A) Group Member: SO Tik Hang (111030753A) Group Member: WONG Ka Wai (11038591A) Group Member: YEUNG Chi Shing (11062622A) */ // User Interface var ui = (function() { // Point to current table var currentTable; // Number of player var playerCount; // Player position in array var playerPosition; // Map the <div>/<ul> player IDs to the player IDs in JS var playerMap = new Array(); playerMap[1] = [1]; playerMap[2] = [1, 2]; playerMap[3] = [1, 2, 3]; playerMap[4] = [1, 2, 3, 4]; playerMap[5] = [1, 2, 3, 4, 5]; playerMap[6] = [1, 2, 3, 4, 5, 6]; // Count number of card clicked var holderClickCounter = 0; // End turn button var pass = false; // Music control of the game var playBGM = document.createElement('audio'); playBGM.src = 'music/bgm.mp3'; playBGM.loop = true; playBGM.controls = true; var mutedMusic = false; // Add play cards to all the stacks to the UI function initGameBoard() { playerCount = game.getPlayerCount(); currentTable = game.getCurrentTable(); playerPosition = game.getPlayerPosition(); // Hidden gameboard item and then fade in $('.rubblish').hide(); $('.rubblishBin').hide(); for(var i = 1; i < playerCount; i++) { $('#player'+ (i+1) +'-holder').hide(); $('#player'+ (i+1) +'-cardNumber').hide(); $('#player'+ (i+1) +'-CrystalArea').hide(); } $('#player1-holder').hide(); $('#player1-CrystalArea').hide(); $('#Pass').hide(); $('.rubblishBin').fadeIn(1200); // Empty card holder clearCardHolders(); var map = playerMap[playerCount]; // Add cards to stock addCardToStockPile(); // Add cards for player var cardArray = game.getPlayerCards(playerPosition); var cardNumber = cardArray.length; for(var i = 0; i < cardNumber; i++) { ui.addCardToPlayerTray(cardArray[i]); } // Add cards for other players var pointer = parseInt(playerPosition) + 1; for(var i = 1; i < playerCount; i++) { if (pointer == parseInt(playerCount)) { pointer = 0; } ui.initCardToOtherPlayerTray(i, game.getPlayerCardNumber(pointer++)); var holder = document.getElementById('player' + map[i] + '-cardNumber'); holder.innerHTML="X " + game.getPlayerCardNumber(i); var j = i - 1; $('#player'+ (i+1) +'-holder').delay(((i*1200)+(j*1200))).fadeIn(1200); $('#player'+ (i+1) +'-cardNumber').delay(((i*1200)+(j*1200))).fadeIn(1200); $('#player'+ (i+1) +'-CrystalArea').delay((((i*1200)+1200)+(j*1200))).fadeIn(1200); } $('#player1-holder').fadeIn(1200); $('#player1-CrystalArea').delay(1200).fadeIn(1200); $('#Pass').delay(1200).fadeIn(1200); if (game.getPlayerCardsClickEnabled()) ui.showToast('This is your trun. Please play card(s).'); else { for (i = 0; i < playerCount; i++) { if (game.getPlayerEnable(i) == 1) ui.showToast('This is ' + game.getPlayerName(i) + ' trun. Please wait.'); } } $('#toast').hide(); $('#toast').delay(6400).fadeIn('fast'); } // Empty all the <ul> tags for holding the cards when a new game starts function clearCardHolders() { $('#player1-holder, #player2-holder, #player3-holder, #player4-holder, #player5-holder, #player6-holder').empty(); $('#stockpile-holder, #discardpile-holder').empty(); } // Add cards to the stockpile when the game starts function addCardToStockPile() { var cardArray = game.getStockCards(); var cardNumber = cardArray.length; var holder = document.getElementById('stockpile-holder'); for(var i = 0; i < cardNumber; i++) { var node = document.createElement('li'); node.setAttribute('id', 'card-' + cardArray[i].id); node.setAttribute('class', 'card-back card'); node.setAttribute('style', uiUtil.getRandomRotateStyle() + uiUtil.getRandomCoordStyle()); node.innerHTML = '&nbsp;'; holder.appendChild(node); } } return { init : function() { game.init(); playBGM.play(); initGameBoard(); ui.updateCrystalArea(); ui.bindCardClickListener(); // Bind the event listeners and handlers for the buttons in the control $('#home, #profile, #chatroom, #game-rules, #about, #credit, #music, #logout').bind('click', function(event) { var id = event.target.id; if(id === 'home') { // Ask player confirm to back home page var homeConfirm = confirm("Back to home page?"); if (homeConfirm) { document.myform.submit(); } } else if(id === 'profile') { server.get_profile(); ui.showPopup('profile'); var popup = $('#popup-background, #profile-close'); popup.click(function() { ui.hidePopup('profile'); popup.unbind('click'); }); $('body').keyup(function(event) { // Esc key if(event.keyCode === 27) { ui.hidePopup('profile'); $('body').unbind('keyup'); } }); } else if(id === 'chatroom') { document.myform3.submit(); } else if(id === 'game-rules') { ui.showPopup('rule'); var popup = $('#popup-background, #rule-close'); popup.click(function() { ui.hidePopup('rule'); popup.unbind('click'); }); $('body').keyup(function(event) { // Esc key if(event.keyCode === 27) { ui.hidePopup('rule'); $('body').unbind('keyup'); } }); } else if(id === 'about') { ui.showPopup('about'); var popup = $('#popup-background, #about-close'); popup.click(function() { ui.hidePopup('about'); popup.unbind('click'); }); $('body').keyup(function(event) { // Esc key if(event.keyCode === 27) { ui.hidePopup('about'); $('body').unbind('keyup'); } }); } else if(id === 'credit') { ui.showPopup('credit'); var popup = $('#popup-background, #credit-close'); popup.click(function() { ui.hidePopup('credit'); popup.unbind('click'); }); $('body').keyup(function(event) { // Esc key if(event.keyCode === 27) { ui.hidePopup('credit'); $('body').unbind('keyup'); } }); } else if(id === 'music') { if(mutedMusic){ playBGM.muted = false; mutedMusic = false; $('#music').html('Music On'); } else { playBGM.muted = true; mutedMusic = true; $('#music').html('Music Off'); } } else if(id === 'logout') { // Ask player confirm to logout var logoutConfirm = confirm("Logout?"); if (logoutConfirm) { location.href="index.html"; } } }); }, // Bind the event listeners for #stockpile-holder and #player1-holder at every new game bindCardClickListener : function() { // Bind the event listeners and handlers for the stockpile $('#stockpile-holder').bind('click', function(event) { var target = event.target; if(target.nodeName.toLowerCase() === 'li') { if(game.getPlayerCardsClickEnabled() && game.getStockpileClickEnabled()) { var cardArray = game.getPlayerCards(playerPosition); var cardNumber = cardArray.length; for(var i = 0; i < cardNumber; i++) { ui.addCardToWindowsTray(cardArray[i]); } ui.unbindCardClickListener(); ui.clearToast(); var windows = $('#card-windows'); var background = $('#popup-background'); windows.fadeIn('fast'); background.fadeIn('fast'); windows.bind('click', function(event) { var target = event.target; var Iid; if(target.nodeName.toLowerCase() === 'li') { // Get the card objcet behind that the user clicked var cardId = parseInt(target.id.split('-', 2)[1]); var cardObject = game.getPlayerCard(playerPosition, cardId); game.removePlayerCard(playerPosition, cardId); Iid = target.id; ui.addCardToDiscardPile(cardObject); game.addCardToDiscardPile(cardObject); windows.unbind('click'); windows.fadeOut(); background.fadeOut(); } document.getElementById('player1-holder').removeChild(document.getElementById(Iid)); $('card-holder').empty(); }); for( var i = 0; i < 2; i++) { // Get the card var cardObject = game.getStockPileCardToPlayer(); // Update the UI ui.removeCardFromStockPile(); ui.addCardToPlayerTray(cardObject); } ui.bindCardClickListener(); } else if (!game.getPlayerCardsClickEnabled()) { for (i = 0; i < playerCount; i++) { if (game.getPlayerEnable(i) == 1) ui.showToast('This is ' + game.getPlayerName(i) + ' trun. Please wait.'); } } else { ui.showToast("You still have card to play."); } } }); // Bind the event listeners and handlers for the cards of player $('#player1-holder').bind('mouseover mouseout', function(event) { var target = event.target; if(target.nodeName.toLowerCase() === 'li') { var cardId = parseInt(target.id.split('-', 2)[1]); var cardObject = game.getPlayerCard(playerPosition, cardId); ui.showToast(card.getCardDescription(cardObject)); $('#context-windows').fadeIn('fast'); document.getElementById('card-context').innerHTML = card.getCardContent(cardObject); } }); $('#player1-holder').bind('click', function(event) { var target = event.target; if(target.nodeName.toLowerCase() === 'li') { // If player clicks a card if(game.getPlayerCardsClickEnabled()) { // If it is player's turn // Get the card objcet behind that the user clicked var cardId = parseInt(target.id.split('-', 2)[1]); var cardObject = game.getPlayerCard(playerPosition, cardId); if(game.isLegalPlay(cardObject)) { ui.unbindCardClickListener(); ui.clearToast(); var holder = document.getElementById('player1-holder'); if(card.isFunctionalCard(cardObject)) { // If this card is a legal play, then remove it and add to discard pile game.removePlayerCard(playerPosition, cardId); ui.addCardToDiscardPile(cardObject); game.addCardToDiscardPile(cardObject); // Update the UI holder.removeChild(document.getElementById(target.id)); } else { game.removePlayerCard(playerPosition, cardId); // Update the UI holder.removeChild(document.getElementById(target.id)); } // set the width so that the cards can align center holder.style.width = 720 + 'px'; ui.incrementHolderClick(); game.playCardProcessor(cardObject); ui.bindCardClickListener(); } else { ui.showToast("Card already existed in gameboard. Please choose another card to play."); } } else { for (i = 0; i < playerCount; i++) { if (game.getPlayerEnable(i) == 1) ui.showToast('This is ' + game.getPlayerName(i) + ' trun. Please wait.'); } } } }); $('#Pass').bind('click', function(event) { if (game.getPlayerCardsClickEnabled() && ui.getHolderClick() >= 1) { ui.showToast('Moving to next player.'); pass = true; game.checkNextTurn(); } else if (!game.getPlayerCardsClickEnabled()) { for (i = 0; i < playerCount; i++) { if (game.getPlayerEnable(i) == 1) ui.showToast('This is ' + game.getPlayerName(i) + ' trun. Please wait.'); } } else if (ui.getHolderClick() < 1) { ui.showToast('Please play at least one card.'); } }); }, // Unbind the event listeners for #stockpile-holder and #player1-holder at every new game unbindCardClickListener : function() { $('#player1-holder').unbind('click'); $('#stockpile-holder').unbind('click'); $('#Pass').unbind('click'); }, bindCheatClickListener : function() { $('#Cheat').bind('click', function(event) { for (var i = 0; i < playerCount; i++) { if (game.getPlayerEnable(i) == 1 && i == playerPosition) { var cardObject = new Object(); cardObject.id = 999; cardObject.typeId = 32; game.pushCheat(cardObject); ui.addCardToPlayerTray(cardObject); $('#Cheat').unbind; $('#Cheat').hide(); } } }); }, addCardToWindowsTray : function(cardObject) { var holder = document.getElementById('card-holder'); var node = document.createElement('li'); node.id = 'card-' + cardObject.id; node.title = card.getTypeChar(cardObject.typeId); node.className = 'card-hoverable card'; node.setAttribute('style', uiUtil.getCardBackgroundShiftStyle(cardObject)); node.innerHTML = card.getTypeChar(cardObject.typeId); holder.appendChild(node); }, // Append a card to player addCardToPlayerTray : function(cardObject) { var holder = document.getElementById('player1-holder'); var node = document.createElement('li'); node.id = 'card-' + cardObject.id; node.title = card.getTypeChar(cardObject.typeId); node.className = 'card-hoverable card'; node.setAttribute('style', uiUtil.getCardBackgroundShiftStyle(cardObject)); node.innerHTML = card.getTypeChar(cardObject.typeId); holder.appendChild(node); holder.style.width = 720 + 'px'; }, // Append card to other player initCardToOtherPlayerTray : function(playerId, cardNumber) { var map = playerMap[playerCount]; var holder = document.getElementById('player' + map[playerId] + '-holder'); for(var i = 0; i < cardNumber; i++) { var node = document.createElement('li'); node.className = 'card-back-upside-down card'; node.innerHTML = '&nbsp;'; holder.appendChild(node); } }, // Append a card to player addCardToOtherPlayerTray : function(playerId) { var currentPlayerPosition = playerPosition - 1; if (playerId > currentPlayerPosition) currentPlayerPosition = playerId - currentPlayerPosition; else currentPlayerPosition = playerId - currentPlayerPosition + parseInt(playerCount); var holder = document.getElementById('player' + currentPlayerPosition + '-cardNumber'); $('#player' + currentPlayerPosition + '-cardNumber').slideUp('fast', function(){holder.innerHTML="X " + game.getPlayerCardNumber(playerId);}) .slideDown('fast'); }, // Remove a card from player removeCardFromOtherPlayerTray : function(playerId) { var currentPlayerPosition = playerPosition - 1; if (playerId > currentPlayerPosition) currentPlayerPosition = playerId - currentPlayerPosition; else currentPlayerPosition = playerId - currentPlayerPosition + parseInt(playerCount); var holder = document.getElementById('player' + currentPlayerPosition + '-cardNumber'); holder.innerHTML="X " + game.getPlayerCardNumber(playerId); }, // Add a card to discard pile addCardToDiscardPile : function(cardObject) { var node = document.createElement('li'); node.id = 'card-' + cardObject.id; node.title = card.getTypeChar(cardObject.typeId); node.className = 'card'; node.setAttribute('style', uiUtil.getRandomRotateStyle() + uiUtil.getRandomCoordStyle() + uiUtil.getCardBackgroundShiftStyle(cardObject)); node.innerHTML = card.getTypeChar(cardObject.typeId); document.getElementById('discardpile-holder').appendChild(node); }, // Remove a card from stock pile removeCardFromStockPile : function() { var node = document.getElementById('stockpile-holder'); node.removeChild(node.lastChild); }, incrementHolderClick : function() { holderClickCounter++; }, getHolderClick : function() { return holderClickCounter; }, resetHolderClick : function() { holderClickCounter = 0; }, getPass : function() { return pass; }, setPassFalse : function() { pass = false; }, addCardToPlayedCard : function(cardObject) { $('#player'+ 1 +'-playedCardHolder').empty(); var holder = document.getElementById('player' + 1 + '-playedCardHolder'); var node = document.createElement('li'); node.id = 'card-' + cardObject.id; node.title = card.getTypeChar(cardObject.typeId); node.className = 'card-hoverable card'; node.setAttribute('style', uiUtil.getCardBackgroundShiftStyle(cardObject)); node.innerHTML = card.getTypeChar(cardObject.typeId); holder.appendChild(node); }, addCardToPlayedCard2 : function(cardObject, currentPlayer) { $('#player'+ currentPlayer +'-playedCardHolder').empty(); var holder = document.getElementById('player' + currentPlayer + '-playedCardHolder'); var node = document.createElement('li'); node.id = 'card-' + cardObject.id; node.title = card.getTypeChar(cardObject.typeId); node.className = 'card-hoverable card'; node.setAttribute('style', uiUtil.getCardBackgroundShiftStyle(cardObject)); node.innerHTML = card.getTypeChar(cardObject.typeId); holder.appendChild(node); }, addCardToFunctionalArea : function(cardObject) { var currentPlayer; if (parseInt(playerPosition) + 1 == parseInt(playerCount)) currentPlayer = 1; else currentPlayer = parseInt(playerPosition) + 1; var theCard = $('#player' + currentPlayer + '-playedCard'); ui.addCardToPlayedCard(cardObject); if (currentPlayer == 1 ) { game.checkRubblishCollect(currentPlayer); } else { theCard.fadeIn('slow') .fadeOut('slow', function(){game.checkRubblishCollect(currentPlayer);}); } }, addCardToRubblishArea : function(cardObject) { var currentPlayer; for (var i = 0; i < playerCount; i++) { if (game.getPlayerEnable(i) == 1) { var currentPlayer = i; break; } } var theCard = $('#player' + 1 + '-playedCard'); ui.addCardToPlayedCard(cardObject); switch(cardObject.typeId) { case 0: var rubblish = $('#battery-1'); break; case 1: var rubblish = $('#battery-2'); break; case 2: var rubblish = $('#battery-3'); break; case 3: var rubblish = $('#oldStuff-1'); break; case 4: var rubblish = $('#oldStuff-2'); break; case 5: var rubblish = $('#oldStuff-3'); break; case 6: var rubblish = $('#surplus-1'); break; case 7: var rubblish = $('#surplus-2'); break; case 8: var rubblish = $('#surplus-3'); break; case 9: var rubblish = $('#metal-1'); break; case 10: var rubblish = $('#metal-2'); break; case 11: var rubblish = $('#metal-3'); break; case 12: var rubblish = $('#metal-4'); break; case 13: var rubblish = $('#metal-5'); break; case 14: var rubblish = $('#paper-1'); break; case 15: var rubblish = $('#paper-2'); break; case 16: var rubblish = $('#paper-3'); break; case 17: var rubblish = $('#paper-4'); break; case 18: var rubblish = $('#paper-5'); break; case 19: var rubblish = $('#plastics-1'); break; case 20: var rubblish = $('#plastics-2'); break; case 21: var rubblish = $('#plastics-3'); break; case 22: var rubblish = $('#plastics-4'); break; case 23: var rubblish = $('#plastics-5'); break; } rubblish.fadeIn('fast', function(){game.checkRubblishCollect(playerPosition);}); theCard.fadeIn(1000).fadeOut(1000, function(){rubblish.fadeIn('fast', function(){game.checkRubblishCollect(currentPlayer);});}); }, addCardToRubblishArea2 : function(cardObject) { var currentPlayer; for (var i = 0; i < playerCount; i++) { if (game.getPlayerEnable(i) == 1) { var currentPlayer = i; break; } } var currentPlayerPosition = playerPosition - 1; if (currentPlayer > currentPlayerPosition) currentPlayerPosition = currentPlayer - currentPlayerPosition; else currentPlayerPosition = currentPlayer - currentPlayerPosition + parseInt(playerCount); var theCard = $('#player' + currentPlayerPosition + '-playedCard'); ui.addCardToPlayedCard2(cardObject, currentPlayerPosition); switch(cardObject.typeId) { case 0: var rubblish = $('#battery-1'); break; case 1: var rubblish = $('#battery-2'); break; case 2: var rubblish = $('#battery-3'); break; case 3: var rubblish = $('#oldStuff-1'); break; case 4: var rubblish = $('#oldStuff-2'); break; case 5: var rubblish = $('#oldStuff-3'); break; case 6: var rubblish = $('#surplus-1'); break; case 7: var rubblish = $('#surplus-2'); break; case 8: var rubblish = $('#surplus-3'); break; case 9: var rubblish = $('#metal-1'); break; case 10: var rubblish = $('#metal-2'); break; case 11: var rubblish = $('#metal-3'); break; case 12: var rubblish = $('#metal-4'); break; case 13: var rubblish = $('#metal-5'); break; case 14: var rubblish = $('#paper-1'); break; case 15: var rubblish = $('#paper-2'); break; case 16: var rubblish = $('#paper-3'); break; case 17: var rubblish = $('#paper-4'); break; case 18: var rubblish = $('#paper-5'); break; case 19: var rubblish = $('#plastics-1'); break; case 20: var rubblish = $('#plastics-2'); break; case 21: var rubblish = $('#plastics-3'); break; case 22: var rubblish = $('#plastics-4'); break; case 23: var rubblish = $('#plastics-5'); break; } rubblish.fadeIn('fast', function(){game.checkRubblishCollect(currentPlayer);}); theCard.fadeIn(1000).fadeOut(1000, function(){rubblish.fadeIn('fast', function(){game.checkRubblishCollect(currentPlayer);});}); }, // Update crystal information updateCrystalArea : function () { var crystalNum; var landfillNum; pointer = parseInt(playerPosition); for (var i = 0; i < playerCount; i++) { if (pointer == parseInt(playerCount)) { pointer = 0; } crystalNum = game.getPlayerCrystal(pointer); landfillNum = game.getPlayerLandfill(pointer++); document.getElementById('player' + (i+1) + '-CrystalNum').innerHTML="x " + crystalNum; document.getElementById('player' + (i+1) + '-LandfillNum').innerHTML="x " + landfillNum; } }, // Show the game result window showResult : function() { ui.showToast('Game ended. Press Home to back to main page.'); // Unbind the card event listeners ui.unbindCardClickListener(); // Remove the card hover effect $('#player1-holder li').each(function() { $(this).removeClass('card-hoverable'); }); // Get the game results var results = game.calculateScore(); // Output the winner var bodyText = $('#result-body'); bodyText.empty(); var winnerNumber = results.winner.length; if (winnerNumber === 1) { // Only one winner bodyText.append($('<p>').text('The winner is ' + (game.getPlayerName(results.winner[0])) + '.')); } else { // More than one winners var winnerMsg = 'The winners are '; for(var i = 0; i < winnerNumber; i++) { if (i !== (winnerNumber - 1) && i !== (winnerNumber - 2)) { winnerMsg += (game.getPlayerName(results.winner[i])) + ', '; } else if (i === (winnerNumber - 2)) { winnerMsg += (game.getPlayerName(results.winner[i])) + ' and '; } else { winnerMsg += (game.getPlayerName(results.winner[i])) + '.'; } } bodyText.append($('<p>').text(winnerMsg)); } // Output a table listing number of crystals, landfill level and scores that player got var tableNode = $('<table>'); tableNode.append($('<tr>').append($('<th>').text('Players'), $('<th>').text('Number of Crystals / Landfill level'), $('<th>').text('Scores'))); for (var i = 0; i < playerCount; i++) { tableNode.append($('<tr>').append($('<td>').addClass('player').text(results.player[i]), $('<td>').addClass('player').text(results.crystal[i] + " / " + results.landfill[i]), $('<td>').addClass('player').text(results.scores[i]))); } bodyText.append(tableNode); // Set winners name var winnerName = new Array(); for (var i = 0; i < winnerNumber; i++) { winnerName[i] = game.getPlayerName(results.winner[i]); } // Update player win and lose record server.setWinLose(currentTable, winnerName, results.player); server.releaseTable(currentTable); // Show the popup ui.showPopup('result'); var popup = $('#result-close'); popup.click(function() { // Ask player confirm to close result windows or not var closeConfirm = confirm("If you close this windows, you cannot read the result again. Are you sure?"); if (!closeConfirm) { return; } ui.hidePopup('result'); popup.unbind('click'); bodyText.empty(); var node = document.getElementById("home"); node.disabled = false; node = document.getElementById("logout"); node.disabled = false; }); $('body').keyup(function(event) { // Esc key if(event.keyCode === 27) { ui.hidePopup('result'); $('body').unbind('keyup'); bodyText.empty(); var node = document.getElementById("home"); node.disabled = false; node = document.getElementById("logout"); node.disabled = false; } }); }, // Show the popup window showPopup : function(name) { var background = $('#popup-background'); background.fadeIn('slow'); $('#' + name + '-window').fadeIn('slow'); }, // Hide the popup window hidePopup : function(name) { $('#popup-background').fadeOut('slow'); $('#' + name + '-window').fadeOut('slow'); }, // Show the toast message showToast : function(message) { var toast = $('#toast'); toast.html(message); toast.hide().fadeIn('fast'); }, // Clear the toast message and hide the bar clearToast : function() { $('#toast').clearQueue().fadeOut('fast').html('&nbsp;'); } }; })(); // UI Utilities var uiUtil = (function() { return { // Return the style string for random rotation for cards in stockpile and discard pile getRandomRotateStyle : function() { var rotateAngle = (Math.random() > 0.5 ? 1 : -1) * Math.floor(Math.random() * 20); return '-moz-transform: rotate(' + rotateAngle + 'deg); -webkit-transform: rotate(' + rotateAngle + 'deg); -o-transform: rotate(' + rotateAngle + 'deg); -ms-transform: rotate(' + rotateAngle + 'deg); transform: rotate(' + rotateAngle + 'deg);'; }, // Return the style string for random position for cards in stockpile and discard pile getRandomCoordStyle : function() { return 'top: ' + ((Math.random() > 0.5 ? 1 : -1) * Math.floor(Math.random() * 5) + card.getCentralZoneYOffset()) + 'px; left: ' + ((Math.random() > 0.5 ? 1 : -1) * Math.floor(Math.random() * 5) + card.getCentralZoneXOffset()) + 'px;'; }, // Return the style string for background shift of cards getCardBackgroundShiftStyle : function(cardObject) { var shiftX = -1 * card.getWidth() * cardObject.typeId; return 'background-position: ' + shiftX + 'px '; }, // Return the width/height of the card holder based on the number of cards the player have getCardHolderWidth : function(playerId) { return (game.getPlayerCardNumber(playerId) - 1) * card.getShiftValue() + card.getWidth(); } }; })();
var isIsomorphic = function(s, t) { let hashMap = {}; for (let i = 0; i < s.length; i++) { if (hashMap[s[i]] === undefined) { for (let key in hashMap) { if (hashMap[key] === t[i]) { return false; } } hashMap[s[i]] = t[i]; } else { if (hashMap[s[i]] != t[i]) { return false; } } } return true; }; console.log(isIsomorphic("ab", "aa"));
const uri = "ytdl"; document.addEventListener('DOMContentLoaded', () => { for (const a of document.getElementsByTagName('a')) a.onclick = () => { if (a.href && a.href.length > 0) chrome.tabs.create({ active: true, url: a.href }); } document.getElementById("downloadMp3").onclick = async () => download("mp3"); document.getElementById("downloadMp4").onclick = async () => download("mp4"); }); const download = async (type) => { let [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); chrome.tabs.create({ active: true, url: uri + ":" + tab.url + ";" + type }); }
import createNode from "../common/createNode"; const cancelButton = createNode( "button", { class: "c-Form__button js-Form__button--cancel" }, "Cancel" ); cancelButton.addEventListener("click", (e) => { e.preventDefault(); console.log(e); // @ts-ignore e.target.offsetParent.remove(); }); const addButton = createNode( "button", { class: "c-Form__button js-Form__button--add" }, "Add" ); addButton.addEventListener("click", (e) => e.preventDefault()); const projectForm = createNode( "form", { class: "c-Form" }, createNode("h2", { class: "c-Form__header" }, "Add project"), createNode("label", { class: "c-Form__label", for: "projectName" }, "Name"), createNode("input", { type: "text", id: "projectName" }), createNode( "label", { class: "c-Form__label", for: "projectColor" }, "Colour" ), createNode("input", { type: "color", id: "projectColor" }), createNode( "div", { class: "c-Form__favourite" }, createNode("input", { type: "checkbox", id: "projectIsFavourite" }), createNode( "label", { class: "c-Form__label", for: "projectIsFavourite" }, "Add to favourites" ) ), createNode("div", { class: "c-Form__buttons" }, cancelButton, addButton) ); export default projectForm;
/** * 住房补贴查询初始化 */ var HousingSubsidyManage = { id: "HousingSubsidyTable", //表格id seItem: null, //选中的条目 table: null, layerIndex: -1, url:"", secondLayerIndex:-1 }; /** * 初始化表格的列 */ HousingSubsidyManage.initColumn = function () { return [ {field: '', radio: false,formatter:function(value,row,index){ return '<input type="hidden" value="'+row.id+'">'; } }, {title: '申请人姓名', field: 'name', align: 'center', valign: 'middle'}, {title: '身份证号码', field: 'idCard', align: 'center', valign: 'middle'}, {title: '电话号码', field: 'telphone', align: 'center', valign: 'middle'}, {title: 'OPTYPENUM', field: 'optypenum', align: 'center', valign: 'middle',visible: false}, {title: 'RECYEAR', field: 'recyear', align: 'center', valign: 'middle',visible: false}, {title: 'RECNUM', field: 'recnum', align: 'center', valign: 'middle',visible: false}, {title: '操作', align: 'center', valign: 'middle', formatter:function(value,row,index){ var str = '<a onclick="HousingSubsidyManage.lookPersonInfo('+'\'' + row.optypenum + '\',\'' +row.recyear + '\',\''+ row.recnum +'\')">查看</a>'; return str; } } ]; }; /** * 查看,个人可能会有多条数据 * @param OPTYPENUM * @param RECYEAR * @param RECNUM */ HousingSubsidyManage.lookPersonInfo = function (optypenum,recyear,recnum) { var index = layer.open({ type: 2, title: '个人住房补贴详情', area: ['80%', '95%'], //宽高 fix: false, //不固定 maxmin: true, content: Feng.ctxPath + '/housingSubsidy/look_person?optypenum=' + optypenum +'&recyear=' + recyear +'&recnum=' + recnum }); HousingSubsidyManage.layerIndex = index; } HousingSubsidyManage.query = function(){ var param = { "name":$("#condition").val() }; HousingSubsidyManage.table.refresh({query: param}); }; /** * 关闭此对话框 */ HousingSubsidyManage.close = function () { parent.layer.close(window.parent.contractManage.layerIndex); }; $(function () { HousingSubsidyManage.url = "/housingSubsidy/list"; var defaultColunms = HousingSubsidyManage.initColumn(); var table = new BSTable(HousingSubsidyManage.id, HousingSubsidyManage.url, defaultColunms); HousingSubsidyManage.table = table.init(); });
define(function(require){ var React = require('react'); var ReactDom = require('react-dom'); var mat = require('materialize'); var Header = require('jsx!app/components/header'); var Footer = require('jsx!app/components/footer'); var Home = React.createClass({ getInitialState: function() { return { posts: [ { post_title: "", post_content: "" } ] }; }, componentDidMount: function(){ $('.parallax').parallax(); $.ajax(rootDir + "/ajax-listener.php", { method: 'POST', data: {request: "pages"}, dataType: 'json', success: function(s){ var results = this.sortByKey(s, "menu_order"); this.setState({ posts: results }); }.bind(this) }); }, sortByKey: function(array, key) { return array.sort(function(a, b) { var x = a[key]; var y = b[key]; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }); }, renderHome: function(){ return ( <div className="parallax-body"> <div className="parallax-container"> <div className="parallax"><img src={rootDir + "/images/parallax1.jpg"} /></div> </div> <div className="section white"> <div className="row container"> <h2 className="header">{this.state.posts[0].post_title}</h2> <p className="grey-text text-darken-3 lighten-3"><div dangerouslySetInnerHTML={{__html: this.state.posts[0].post_content}} /></p> </div> </div> <div className="parallax-container"> <div className="parallax"><img src={rootDir + "/images/parallax2.jpg"} /></div> </div> </div> ); }, renderPage: function(){ for(var i = 0; i < this.props.posts.length; ++i){ var title = locationEnd.replace("%20", " "); if(this.props.posts[i].post_title == title){ this.setState({ title: this.props.posts[i].post_title, content: this.props.posts[i].post_content, loaded: true }); } } return ( <div className="container" key={locationEnd}> <div className="row"> <div className="col s12 m6"> <div className="card blue-grey darken-1"> <div className="card-content white-text"> <span className="card-title">{this.state.title}</span> <p>{this.state.content}</p> </div> <div className="card-action"> <a href="#">This is a link</a> <a href="#">This is a link</a> </div> </div> </div> </div> </div> ) }, render: function(){ if(this.state.route == "Home"){ return ( {renderHome} ); } else { return ( {renderPage} ) } } }); return Home; });
const util = require('../modules/util'); const statusCode = require('../modules/statusCode'); const resMessage = require('../modules/responseMessage'); const crypto = require('crypto'); const jwt = require('../modules/jwt'); const Post = require('../models/post'); const User = require('../models/user'); const user = { signup:async(req,res)=>{ var data=''; if(req.file !== undefined){ data = req.file.location; } const { id, password, name } = req.body; if(!id||!password||!name){ return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST,resMessage.BAD_REQUEST)); } // user id duplicated check const salt = crypto.randomBytes(32).toString() const hashedPw = crypto.pbkdf2Sync(password, salt, 1, 32, 'sha512').toString('hex') await User.signup(id,hashedPw,salt,name,data); return res.status(statusCode.OK).send(util.success(statusCode.OK,resMessage.CREATE_USER_SUCCESS)) }, signin:async(req,res)=>{ const { id,password } = req.body; if (!id || !password) { return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST, responseMsg.NULL_VALUE)) } if (await User.checkUser(id) === false) { return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.INTERNAL_SERVER_ERROR, responseMsg.DB_ERROR)) } const result = await User.signin(id, password) if (result === false) { return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.INTERNAL_SERVER_ERROR, responseMsg.DB_ERROR)) } const userData = await User.getUserById(id) const jwtToken = await jwt.sign(userData[0]) return res.status(statusCode.OK).send(util.success(statusCode.OK, resMessage.LOGIN_SUCCESS, { token: jwtToken.token })) }, getPostLikes:async(req,res)=>{ const userIdx = req.idx; const result = await Post.getUserLikePosts(userIdx) return res.status(statusCode.OK).send(util.success(statusCode.OK, resMessage.GET_USER_LIKE_POST_SUCCESS, { post_list: result })) }, getPostCommentsLikes:async(req,res)=>{ const userIdx = req.idx; const result = await Post.getUserLikePostComments(userIdx) return res.status(statusCode.OK).send(util.success(statusCode.OK, resMessage.GET_USER_LIKE_POST_SUCCESS, { result: result })) }, getPostOfUser:async(req,res)=>{ const userIdx = req.idx; const result = await Post.getUserPosts(userIdx) return res.status(statusCode.OK).send(util.success(statusCode.OK, resMessage.GET_USER_POST_SUCCESS, { post_list: result })) }, test:async(req,res)=>{ const result = await User.test(); return res.status(statusCode.OK).send(util.success(statusCode.OK,resMessage.ALREADY_ID,{ post_list:result })) }, getJwtAuth: async(req, res)=>{ const userIdx = req.idx; if(!userIdx){ return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST,resMessage.REQUIRE_AUTH,{ is_auth:false })) }else{ return res.status(statusCode.OK).send(util.success(statusCode.OK,resMessage.DONE_AUTH,{ is_auth:true })) } } } module.exports=user;
var httpController = function (http){ console.log('httpController loaded'); http.get('/', function (req, res){ res.render('index'); }); } module.exports = httpController;
(function() { 'use strict'; angular .module('unpsipApp') .controller('CursoDetailController', CursoDetailController); CursoDetailController.$inject = ['$scope', '$rootScope', '$stateParams', 'previousState', 'entity', 'Curso', 'Professor', 'Turma', 'Aluno']; function CursoDetailController($scope, $rootScope, $stateParams, previousState, entity, Curso, Professor, Turma, Aluno) { var vm = this; vm.curso = entity; vm.previousState = previousState.name; var unsubscribe = $rootScope.$on('unpsipApp:cursoUpdate', function(event, result) { vm.curso = result; }); $scope.$on('$destroy', unsubscribe); } })();
const graphql = require('graphql'); const GraphQLDate = require('graphql-date'); const validator = require('validator'); const _ = require('lodash'); const Admin = require('../models/admin'); const Staff = require('../models/staff'); const Student = require('../models/student'); const { GraphQLObjectType, GraphQLString, GraphQLID, GraphQLSchema, GraphQLNonNull } = graphql; const now = new Date(); const AdminType = new GraphQLObjectType({ name: 'Admin', fields: () => ({ id: { type: GraphQLID }, fname: { type: GraphQLString }, lname: { type: GraphQLString }, phone: { type: GraphQLString }, email: { type: GraphQLString }, password: { type: GraphQLString }, created_at: { type: GraphQLDate }, updated_at: { type: GraphQLDate } }) }); const StaffType = new GraphQLObjectType({ name: 'Staff', fields: () => ({ id: { type: GraphQLID }, fname: { type: GraphQLString }, lname: { type: GraphQLString }, phone: { type: GraphQLString }, email: { type: GraphQLString }, password: { type: GraphQLString }, created_at: { type: GraphQLDate }, updated_at: { type: GraphQLDate } }) }); const StudentType = new GraphQLObjectType({ name: 'Student', fields: () => ({ id: { type: GraphQLID }, fname: { type: GraphQLString }, lname: { type: GraphQLString }, phone: { type: GraphQLString }, email: { type: GraphQLString }, password: { type: GraphQLString }, created_at: { type: GraphQLDate }, updated_at: { type: GraphQLDate } }) }); const ContractorType = new GraphQLObjectType({ name: 'Contractor', fields: () => ({ id: { type: GraphQLID }, fname: { type: GraphQLString }, lname: { type: GraphQLString }, phone: { type: GraphQLString }, email: { type: GraphQLString }, password: { type: GraphQLString }, created_at: { type: GraphQLDate }, updated_at: { type: GraphQLDate } }) }); const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { staff: { type: StaffType, args: {id: { type: GraphQLID } }, resolve(parent, args){ //return _.find(users, { id: args.id }) } } } }); const Mutation = new GraphQLObjectType({ name: 'Mutation', fields: { addAdmin: { type: AdminType, args: { fname: { type: new GraphQLNonNull(GraphQLString) }, lname: { type: new GraphQLNonNull(GraphQLString) }, phone: { type: new GraphQLNonNull(GraphQLString) }, email: { type: new GraphQLNonNull(GraphQLString) }, password: { type: new GraphQLNonNull(GraphQLString) } }, resolve(parent, args){ //return _.find(users, { id: args.id }); let admin = new Admin({ fname: args.fname, lname: args.lname, phone: args.phone, email: args.email, password: args.password }); return admin.save(); } }, addStudent: { type: StudentType, args: { fname: { type: new GraphQLNonNull(GraphQLString) }, lname: { type: new GraphQLNonNull(GraphQLString) }, phone: { type: new GraphQLNonNull(GraphQLString) }, email: { type: new GraphQLNonNull(GraphQLString) }, password: { type: new GraphQLNonNull(GraphQLString) } }, resolve(parent, args){ //return _.find(users, { id: args.id }); let student = new Student({ fname: args.fname, lname: args.lname, phone: args.phone, email: args.email, password: args.password }); return student.save(); } }, addStaff: { type: StaffType, args: { fname: { type: new GraphQLNonNull(GraphQLString) }, lname: { type: new GraphQLNonNull(GraphQLString) }, phone: { type: new GraphQLNonNull(GraphQLString) }, email: { type: new GraphQLNonNull(GraphQLString) }, password: { type: new GraphQLNonNull(GraphQLString) } }, resolve(parent, args){ //return _.find(users, { id: args.id }); let staff = new Staff({ fname: args.fname, lname: args.lname, phone: args.phone, email: args.email, password: args.password }); return staff.save(); } } } }); module.exports = new GraphQLSchema({ query: RootQuery, mutation: Mutation });
// 构造函数 var now = new Date(); //获取当前时间 // Date.parse()方法 接受一个表示日期的字符串参数,可以是以下格式 /** "月/日/年" 如 6/13/2004 * "英文月名 日,年" 如 January 12,2004 * 其他格式省略 */ var someDate = new Date(Date.parse('May 25,2004')); //如果将表示日期字符串直接传给Date构造函数,在后头调用Date.parse方法 //以上代码等价于 var someDate = new Date('May 25,2004'); // Date.UTC方法参数 年份,基于0的月份(1月是0),月中的哪一天(1-31),小时数(0-23),分钟,秒以及毫秒 // 只有前两个参数必须 //以下两个是GMT时间 var y2k = new Date(Date.UTC(2000,0)); var allFives = new Date(Date.UTC(2005,4,5,17,55,55)); //以下两个是本地时间,不同 var y2k = new Date(2000,0); var allFives = new Date(2005,4,5,17,55,55); // es5新增Date.now方法,表示调用方法时的毫秒数 var start = Date.now(); console.log(start); //1567832113759
import { RECEIVE_USER } from '../actions/session' const initialState = { all: null, } const doctors = (state = initialState, action) => { switch (action.type) { case RECEIVE_USER: return Object.assign({}, state, { all: action.doctors }) default: return state } } export default doctors
const postcss = require("cssnano/node_modules/postcss"); module.exports = { syntax: "postcss-scss", plugins: [ require("postcss-preset-env")({ stage: 1, }), require("autoprefixer"), ], };
import { useState, useEffect } from "react"; import dayjs from 'dayjs'; import styles from "../styles/History.module.css"; export default function History({ workoutHistory }) { const [ monYrList, setMonYrList ] = useState([]); const [ haveLoaded, setHaveLoaded ] = useState(false); // import workoutHistory from localStorage, if available // if not, display error message // filter/parse dates with dayJS // console.log( dayjs("May2021").isBefore(dayjs("Jun2021")) ); useEffect(() => { function getMonths(){ let monthsArray = []; for (let monthYearKey in workoutHistory) { let empty = workoutHistory[monthYearKey].every(elem => elem === ""); // make sure array at this key in workoutHistory isn't empty if (!empty) monthsArray.push(monthYearKey); // generate array from all month/year keys in workoutHistory }; monthsArray.sort((mon1, mon2) => { // if compareFunction(a, b) returns a value > than 0, sort b before a if ( dayjs(mon1).isBefore(dayjs(mon2)) ) { // sort the array we created (since it may be out of order) return -1; } else { return 1; } }); setMonYrList(monthsArray); setHaveLoaded(true); // necessary to get this useEffect call to run twice...on first run, monYrList is empty }; getMonths(); // console.log(monYrList); }, [workoutHistory, haveLoaded]); function mapHistory() { let histMap = monYrList.map(monYr => { // map over the sorted keys in monYrList let monthMap = workoutHistory[monYr].map((elem, idx) => { // then for each key, map over values in workoutHistory at that key if (elem.length > 0) { // if the element in this array is not empty... let date = `${monYr.slice(0, 3)}-${idx}-${monYr.slice(3)}`; // set a date string + return a div with workout name(s) and date string return (<div className={styles.dateEntry} key={date}> <span className={styles.greenBold}>{date}{' '}~</span><span>{' '}{elem}</span> </div>) }; }); // return all mapped workouts for the month+year, below a title like 'Jun 2021' return (<div className={styles.monthYear} key={monYr}> <h3 className={styles.monthYearTitle}>{monYr.slice(0, 3)} {monYr.slice(3)}</h3> {monthMap} <br/> <hr/> </div>); }); return histMap; // return all mapped workouts for all months/years } return ( <> <div> { mapHistory() } </div> </> ); };
//Map through each day, and in each day run a loop(forEach) on the intervals for the day to determine max/min value of a property (example temp_min). A conditional is used to compare the previous interval min/max value to the current min/max value and value is updated based on the conditional //EXAMPLE: property1='main', property2='temp_min' maxmin='min' export const getMinMaxValue = (days,property1,property2,maxmin='min') => { return days.map((day)=>{ var value = day[0][property1][property2]; //temp_min of first element day.forEach((interval)=>{ if (maxmin==='min'){ if (interval[property1][property2] < value) { value = interval[property1][property2]; } } else if (maxmin==='max'){ if (interval[property1][property2] > value) { value = interval[property1][property2]; } } }); return value; }); }
for(var i = 0; i < 34; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); } $axure.eventManager.pageLoad( function (e) { }); gv_vAlignTable['u27'] = 'top'; u28.style.cursor = 'pointer'; $axure.eventManager.click('u28', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('Algorithm_Manager.html'); } }); u29.style.cursor = 'pointer'; $axure.eventManager.click('u29', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('Source_Manager.html'); } }); gv_vAlignTable['u8'] = 'top'; u30.style.cursor = 'pointer'; $axure.eventManager.click('u30', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('Interface_Manager.html'); } }); u32.style.cursor = 'pointer'; $axure.eventManager.click('u32', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('User_Manager.html'); } }); gv_vAlignTable['u13'] = 'top';gv_vAlignTable['u15'] = 'top';gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u9'] = 'top';gv_vAlignTable['u3'] = 'center';gv_vAlignTable['u23'] = 'center';gv_vAlignTable['u25'] = 'center';gv_vAlignTable['u20'] = 'center';gv_vAlignTable['u5'] = 'center';gv_vAlignTable['u21'] = 'top'; u33.style.cursor = 'pointer'; $axure.eventManager.click('u33', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('Config_Manager.html'); } }); u31.style.cursor = 'pointer'; $axure.eventManager.click('u31', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('ScheduleManager.html'); } });
var expect = require('expect.js'); var userCtrl = require('../routes/controller/userCtrl.js'); var userModel = require('../models/UserModel.js'); var db_init = require('../models/DB_InitTest.js'); if (typeof(suite) === "undefined") suite = describe; if (typeof(test) === "undefined") test = it; suite('User Ctrl', function(){ var updateInfo = { lastLoginAt: '2015-11-10', createdAt: '2015-11-08' }; test('updateValidateLastLoginAt', function(done){ updateInfo.lastLoginAt = "20141220"; updateInfo.createdAt = '2014-12-20'; userCtrl.update('username', updateInfo, true, function(result){ expect(result.statusCode).to.eql(400); expect(result.desc).to.eql('Error: date and time must be in ISO format!'); done(); }); }); test('updateValidateCreatedAt', function(done){ updateInfo.lastLoginAt = "2014-12-20"; updateInfo.createdAt = "20141220"; userCtrl.update('username', updateInfo, true, function(result){ expect(result.statusCode).to.eql(400); expect(result.desc).to.eql('Error: date and time must be in ISO format!'); done(); }); }); test('updateNotExistsUser', function(done){ updateInfo.lastLoginAt = "2014-12-20"; updateInfo.createdAt = "2014-12-20"; userCtrl.update('someUserNotExists', updateInfo, true, function(result){ expect(result.statusCode).to.eql(404); expect(result.desc).to.eql('user not exists!'); done(); }); }); test('updateExistsUser', function(done){ updateInfo.firstname = "Ming-Yuan"; updateInfo.lastname = "Jian"; updateInfo.location = "CMU-SV B19"; updateInfo.coordinate = "37.412353, -122.058460"; updateInfo.peopleiknow = "myjian"; userModel.addNewUser('myjian1', 'password', function(result){ userCtrl.update('myjian1', updateInfo, true, function(result){ expect(result.statusCode).to.eql(200); expect(result.desc).to.eql("update user success!"); done(); }); }); }); test('getUsersWithUserAdded', function(done){ userModel.addNewUser('someUserForGetUsers', 'password', function(result){ userCtrl.getUsers(function(result){ expect(result.statusCode).to.eql(200); expect(result.users.length).to.be.greaterThan(0); done(); }); }); }); test('getUserWithUserAdded', function(done){ userModel.addNewUser('someUserForGetUser', 'password', function(result){ userCtrl.getUser('someUserForGetUser', function(result){ expect(result.statusCode).to.eql(200); expect(result.user.username).to.eql('someUserForGetUser'); done(); }); }); }); var updateStatusRequest = { updatedAt: '2014-12-20', statusType: 'OK', location: 'SFO' }; test('updateStatusWithUserNotExists', function(done){ userCtrl.updateStatus('someUserForUpdateStatusWithUserNotExists', updateStatusRequest, function(result){ expect(result.statusCode).to.eql(404); expect(result.desc).to.eql("user not exists"); done(); }); }); test('updateStatusWithInvalidStatusType', function(done){ userModel.addNewUser('someUser', 'password', function(result){ updateStatusRequest.statusType = "unknownType"; userCtrl.updateStatus('someUser', updateStatusRequest, function(result){ expect(result.statusCode).to.eql(400); expect(result.desc).to.eql("Invalide status code"); done(); }); }); }); test('updateStatus', function(done){ userModel.addNewUser('someUserForUpdateStatus', 'password', function(result){ updateStatusRequest.statusType = "OK"; userCtrl.updateStatus('someUserForUpdateStatus', updateStatusRequest, function(result){ expect(result.statusCode).to.eql(200); expect(result.desc).to.eql('add status successfully.'); done(); }); }); }); test('getUserStatusHistoryWithUserNotExists', function(done){ userCtrl.getUserStatusHistory('someUserForGetUserStatusHistoryWithUserNotExists', function(result){ expect(result.statusCode).to.eql(400); expect(result.desc).to.eql("user not exists!"); done(); }); }); test('getUserStatusHistory', function(done){ userModel.addNewUser('someUserForGetUserStatusHistory', 'password', function(result){ userCtrl.updateStatus('someUserForGetUserStatusHistory', updateStatusRequest, function(result){ userCtrl.getUserStatusHistory('someUserForGetUserStatusHistory', function(result){ expect(result.statusCode).to.eql(200); expect(result.desc).to.eql("get user status history successfully"); done(); }); }); }); }); test('updateLastLogoutTimeWithUserNotExists', function(done){ userCtrl.updateLastLogoutTime('someUserNotExists', null, function(result){ expect(result.statusCode).to.eql(400); expect(result.desc).to.eql('user not exists'); done(); }); }); test('updateLastLogoutTimeWithUserAdded', function(done){ userModel.addNewUser('someUserForUpdateLastLogoutTime', 'password', function(result){ var updateInfo = {lastLogoutAt: "2014-12-20T08:20:30.000Z"}; userCtrl.update('someUserForUpdateLastLogoutTime', updateInfo, true, function(result){ expect(result.statusCode).to.eql(200); expect(result.desc).to.eql("update user success!"); done(); }); }); }); test('getUsersByUserNameMatch', function(done){ userModel.addNewUser('someUserForGetUserByUserNameMatch', 'password', function(result){ updateInfo.lastLoginAt = "2014-12-10"; updateInfo.lastLogoutAt = "2014-12-11"; userCtrl.update('someUserForGetUserByUserNameMatch', updateInfo, true, function(result){ userCtrl.getUsersByUserNameMatch('someUserForGetUserByUserNameMatch', function(result){ expect(result.statusCode).to.eql(200); expect(result.desc).to.eql('get matched users successfully.'); expect(result.users.length).to.above(0); done(); }); }); }); }); test('getUserByWrongStatusName', function(done){ userCtrl.getusersByStatusNameMatch('status', function(result){ expect(result.statusCode).to.eql(400); expect(result.users).to.eql(null); expect(result.desc).to.eql('invalide status name'); done(); }); }); test('getusersByStatusNameMatch', function(done){ userModel.addNewUser('someUserForGetUserByStatusNameMatch', 'password', function(result){ userCtrl.updateStatus('someUserForGetUserByStatusNameMatch', updateStatusRequest, function(result){ userCtrl.getusersByStatusNameMatch('ok', function(result){ expect(result.statusCode).to.eql(200); expect(result.desc).to.eql('get users by status success'); expect(result.users.length).to.above(0); done(); }); }); }); }); test('deleteOneUser', function(done){ userCtrl.deleteUser('someUser', function(result){ expect(result.statusCode).to.eql(200); done(); }); }); test('deleteAllUsers', function(done){ userModel.deleteAllUsers(function(result){ expect(result.status).to.be.ok(); done(); }); }); });
import React from "react"; import Button from "../Button/index"; export default function LocalStorageBlock({ saveTodoLocalStorage, deleteTodoLocalStorage, }) { return ( <div className="localStorage-block"> <Button className="btn-save" title="Save Todo" onClick={saveTodoLocalStorage}/> <Button className="btn-delete"title="Delete Todo" onClick={deleteTodoLocalStorage}/> </div> ); }
$(document).ready(function() { $("#providers").dynamiclist({ jsonrpc: { method: "ddns.providers" }, ejs: { url: "tpl/conn_ddns_provider_status.ejs", data: function(a) { return { provider: a } } }, filter: function(a) { return a.cfg.enabled == true }, interval: 1000, key: "name", jsonfield: function(b) { return b }, ejs_update_if_present: true }) });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const randomNumber = arr => arr[Math.floor(Math.random() * arr.length)]; exports.default = randomNumber;
var im = require('../lib/im/im'); im.startReciver('imReciver', function(content) { console.log(content); });
var API_URL = "/api/v1/"; $(function(){ $("#submit_login").on("click", function(e) { var arr = $("#login_form").serializeArray(), data = {}; for (var i = 0; i < arr.length; i++) { data[arr[i].name] = arr[i].value; } $.ajax({ type: "POST", url: API_URL+"login", data: JSON.stringify(data), contentType: "application/json", processData: false }).done(function(d) { $("#login-modal").hide(); $("#workplace").show(); Cookies.set('token', d.token); getHistory(); setInterval(getHistory, 60000); }).fail(function (x) { }); return false; }); $("#send_link").on("click", function(e){ var link = $("#link_value").val(); $.ajax({ type: "GET", url: API_URL+"audio", data: "link="+link, processData: false, headers: {"Authorization": " BEARER " + Cookies.get('token')} }).done(function(d) { $('<div id="job_alert" class="alert alert-success" role="alert">'+ d.jobID +'</div>').insertBefore("#link_container"); $("#job_alert").delay(3000).slideUp('slow', function(){ $(this).remove(); } ) }).fail(function (x) { }); }); $("#rss_link").on("click", function(e){ getRssLink(); return false; }) }); function getHistory() { $.ajax({ type: "GET", url: API_URL+"history", processData: false, headers: {"Authorization": " BEARER " + Cookies.get('token')} }).done(function(d) { var html = ""; for (var i = 0; i < d.history.length; i++) { var item = d.history[i]; html += '<tr id="'+item.id+'"><th scope="row">' + (i + 1) +'</th>' html += '<td>'+ item.time +'</td>' html += '<td>'+ item.title +'</td>' html += '<td><a href='+item.audio_link+'>ссылка</a></td>' html += '<td>'+ item.status +'</td>' html += '<td><button onClick="deleteHistoryItem("'+item.id+'");" class="btn btn-outline-secondary" type="button">Уалить</button></td>' html += '</tr>' } $("#history_body").html(html); $('#history_container').show(); }).fail(function (x) { }); } function deleteHistoryItem(id) { $.ajax({ type: "DELETE", url: API_URL+"delete_from_history/" + id, processData: false, headers: {"Authorization": " BEARER " + Cookies.get('token')} }).done(function(d) { $("#" + id).remove(); }).fail(function (x) { }); } function getRssLink() { $.ajax({ type: "GET", url: API_URL+"generate_rss_link", processData: false, headers: {"Authorization": " BEARER " + Cookies.get('token')} }).done(function(d) { var uri = window.location.origin + API_URL + d.rss_link; window.open(uri, '_blank'); }).fail(function (x) { }); }
// write me a function stringy that takes a size and returns a string of alternating '1s' and '0s'. // the string should start with a 1. // a string with size 6 should return :'101010'. // with size 4 should return : '1010'. // with size 12 should return : '101010101010'. // The size will always be positive and will only use whole numbers. // function stringy(size) { // // your code here // } //parameters //a string //returns //a string of 1 and 0s //examples //console.log(stringy("hello")) // "10101" //pseudocode //need to determine the length of size and populate the 1 at even indexs and 0 at odds // const stringy = size => { // let strArr = []; // for (i =0; i < size.length; i++){ // console.log(i) // if (i % 2 === 0) { // strArr.push("1"); // } // else if (i %2 !== 0){ // strArr.push("0") // } // } // return strArr.join(""); // } // console.log(stringy("hello")) //refactored const stringy = size => { let strArr = []; for (i =0; i < size; i++){ i % 2 === 0 ? strArr.push("1") : strArr.push("0"); } return strArr.join(""); }; console.log(stringy(5))
//mongoose const mongoose = require('mongoose') mongoose.Promise = global.Promise mongoose.connect('mongodb://localhost/csj',{ useMongoClient: true }); //schema const accountSchema = mongoose.Schema({ openid:String,//wechat id tel:Number, psw:String, business: Boolean, }) const shopSchema = mongoose.Schema({ info : { name : String, logo : String, label : Array, discount : String, intro : String, address : String, }, owner : { account : String, password : String, subAccount : Array }, items : Array, categories : [], }) const Account = mongoose.model('account', accountSchema) const Shop = mongoose.model('shop', shopSchema) module.exports={ Account, Shop }
import React, {Component} from 'react' import Post from './Post'; import {Row, Col} from 'react-bootstrap'; import BlogStore from '../../stores/BlogStore'; class Blog extends Component { constructor(props){ super(props); let date = new Date(); this.state = {BlogStore: BlogStore.getState()}; } render(){ let posts = this.state.BlogStore.posts; let postNodes = posts.map(function(post, i){ return( <Post key={i} date={post.date} messages={post.messages}/> ); }); return( <Row className="blog"> <Col lg={6} lgOffset={3}> {postNodes} </Col> </Row> ) } } export default Blog;
import getNeighborCells from "../helpers/getNeighborCells"; import initState from "../initState"; const generateBoard = (width, height, mines, click) => { const getRandLoc = () => { return { x: Math.floor(Math.random() * width), y: Math.floor(Math.random() * height), } } const isValidMineLoc = (l = { x: 0, y: 0 }, click = { x: 0, y: 0 }) => { let notMine = board[l.y][l.x].mine === false let notNearClick = (Math.abs(l.x - click.x) > 1) || (Math.abs(l.y - click.y) > 1); return notMine && notNearClick; } const createCell = () => { return { mine: false, nearMineCount: 0, checked: false, mark: '' }; } const board = []; for (let i = 0; i < height; i++) { board.push([]); for (let j = 0; j < width; j++) { board[board.length - 1].push(createCell()); } } for (; mines > 0; mines--) { let l = getRandLoc(); while (!isValidMineLoc(l, click)) { l = getRandLoc() } board[l.y][l.x].mine = true; getNeighborCells(l, width, height).forEach((n) => { board[n.y][n.x].nearMineCount++ }); } return board; }; const clickHandle = (board, cl) => { const cascade = (l) => { getNeighborCells(l, board[0].length, board.length).forEach(p => { let c = board[p.y][p.x]; if (c.checked || c.mark !== '') { return; } //Stops endless cascades and revealing marked tiles c.checked = true; if (c.nearMineCount === 0) { cascade(p); } board[p.y][p.x] = { ...c }; }) } let t = board[cl.y][cl.x]; if (t.mark === 'm') { return board } //Dissallows checking marked tiles t.checked = true; if (t.nearMineCount === 0) { cascade(cl); } board[cl.y][cl.x] = { ...t }; return [...board]; }; export default (pState = initState, action) => { if (action.type !== 'checkCell' || pState.gameOver || pState.victory) { return pState; } let cl = action.payload; //click location let newState = { ...pState }; if (pState.mode === 'c') { if (newState.freshBoard) { newState.board = generateBoard(pState.width, pState.height, pState.mines, cl); newState.freshBoard = false; } newState.board = clickHandle(newState.board, cl); } if (pState.mode === 'm') { var t = newState.board[cl.y][cl.x]; if (t.mark !== 'm') { newState.rMines--; t.mark = 'm'; } else { newState.rMines++; t.mark = ''; } newState.board[cl.y][cl.x] = { ...t }; newState.board = [...newState.board]; } if (pState.mode === '?') { console.log('toggle ?'); var t = newState.board[cl.y][cl.x]; if (t.mark !== '?') { if (t.mark === 'm') { newState.rMines++; } t.mark = '?'; } else { t.mark = ''; } newState.board[cl.y][cl.x] = { ...t }; newState.board = [...newState.board]; } return newState; }
(function(){ var settings = { channel: 'pi-house', publish_key: 'pub-c-8b8e3386-51eb-4dbc-92b8-281fb225cca1', subscribe_key: 'sub-c-0a63540c-0045-11e6-9086-02ee2ddab7fe' }; var pubnub = PUBNUB(settings); var door = document.getElementById('door'); var lightLiving = document.getElementById('lightLiving'); var lightPorch = document.getElementById('lightPorch'); var fireplace = document.getElementById('fireplace'); pubnub.subscribe({ channel: settings.channel, callback: function(m) { if(m.temperature) { document.querySelector('[data-temperature]').dataset.temperature = m.temperature; } if(m.humidity) { document.querySelector('[data-humidity]').dataset.humidity = m.humidity; } } }) /* Data settings: Servo item: 'door' open: true | false LED item: 'light-*' brightness: 0 - 10 */ function publishUpdate(data) { pubnub.publish({ channel: settings.channel, message: data }); } // UI EVENTS door.addEventListener('change', function(e){ publishUpdate({item: 'door', open: this.checked}); }, false); lightLiving.addEventListener('change', function(e){ publishUpdate({item: 'light-living', brightness: +this.value}); }, false); lightPorch.addEventListener('change', function(e){ publishUpdate({item: 'light-porch', brightness: +this.value}); }, false); fireplace.addEventListener('change', function(e){ publishUpdate({item: 'fireplace', brightness: +this.value}); }, false); })();
Meteor.publish("zona",function(params){ return Zona.find(params); });
function managerCard(manager) { return `<div class="col"> <div class='card bg-info mb-3 text-center border border-3 border-warning' style="padding: 1rem; margin: 2rem"> <div class='card-header fw-bold'> <h1>${manager.getRole()}</h1> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-binoculars" viewBox="0 0 16 16"> <path d="M3 2.5A1.5 1.5 0 0 1 4.5 1h1A1.5 1.5 0 0 1 7 2.5V5h2V2.5A1.5 1.5 0 0 1 10.5 1h1A1.5 1.5 0 0 1 13 2.5v2.382a.5.5 0 0 0 .276.447l.895.447A1.5 1.5 0 0 1 15 7.118V14.5a1.5 1.5 0 0 1-1.5 1.5h-3A1.5 1.5 0 0 1 9 14.5v-3a.5.5 0 0 1 .146-.354l.854-.853V9.5a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5v.793l.854.853A.5.5 0 0 1 7 11.5v3A1.5 1.5 0 0 1 5.5 16h-3A1.5 1.5 0 0 1 1 14.5V7.118a1.5 1.5 0 0 1 .83-1.342l.894-.447A.5.5 0 0 0 3 4.882V2.5zM4.5 2a.5.5 0 0 0-.5.5V3h2v-.5a.5.5 0 0 0-.5-.5h-1zM6 4H4v.882a1.5 1.5 0 0 1-.83 1.342l-.894.447A.5.5 0 0 0 2 7.118V13h4v-1.293l-.854-.853A.5.5 0 0 1 5 10.5v-1A1.5 1.5 0 0 1 6.5 8h3A1.5 1.5 0 0 1 11 9.5v1a.5.5 0 0 1-.146.354l-.854.853V13h4V7.118a.5.5 0 0 0-.276-.447l-.895-.447A1.5 1.5 0 0 1 12 4.882V4h-2v1.5a.5.5 0 0 1-.5.5h-3a.5.5 0 0 1-.5-.5V4zm4-1h2v-.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5V3zm4 11h-4v.5a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5V14zm-8 0H2v.5a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5V14z"/> </svg> </div> <div class='card-body p-3 mb-2 text-white bg-secondary border-3 border-warning' > <h3 class="card-title">${manager.getName()}</h3> <p class="card-text">ID: ${manager.getId()}</p> <p><a href="mailto:${manager.getEmail()}" class="card-text">${manager.getEmail()}</a></p> <p class="card-text">Office Number: ${manager.getOfficeNumber()}</p> </div> </div> </div>`; } function engineerCard(engineer) { return `<div class="col"> <div class='card bg-info mb-3 text-center border border-3 border-warning' style="padding: 1rem; margin: 2rem"> <div class='card-header fw-bold'> <h1>${engineer.getRole()}</h1> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-emoji-sunglasses" viewBox="0 0 16 16"> <path d="M4.968 9.75a.5.5 0 1 0-.866.5A4.498 4.498 0 0 0 8 12.5a4.5 4.5 0 0 0 3.898-2.25.5.5 0 1 0-.866-.5A3.498 3.498 0 0 1 8 11.5a3.498 3.498 0 0 1-3.032-1.75zM7 5.116V5a1 1 0 0 0-1-1H3.28a1 1 0 0 0-.97 1.243l.311 1.242A2 2 0 0 0 4.561 8H5a2 2 0 0 0 1.994-1.839A2.99 2.99 0 0 1 8 6c.393 0 .74.064 1.006.161A2 2 0 0 0 11 8h.438a2 2 0 0 0 1.94-1.515l.311-1.242A1 1 0 0 0 12.72 4H10a1 1 0 0 0-1 1v.116A4.22 4.22 0 0 0 8 5c-.35 0-.69.04-1 .116z"/> <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-1 0A7 7 0 1 0 1 8a7 7 0 0 0 14 0z"/> </svg> </div> <div class='card-body p-3 mb-2 text-white bg-secondary border-3 border-warning'> <h3 class="card-title">${engineer.getName()}</h3> <p class="card-text">ID: ${engineer.getId()}</p> <p><a href="mailto:${engineer.getEmail()}" class="card-text">${engineer.getEmail()}</a></p> <p><a href="https://github.com/${engineer.getGithub()}" class="card-text">${engineer.getGithub()}</a></p> </div> </div> </div>`; } function internCard(intern) { return `<div class="col"> <div class='card bg-info mb-3 text-center border border-3 border-warning' style="padding: 1rem; margin: 2rem"> <div class='card-header fw-bold'> <h1>${intern.getRole()}</h1> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil" viewBox="0 0 16 16"> <path d="M12.146.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.468-.325z"/> </svg> </div> <div class='card-body p-3 mb-2 text-white bg-secondary border-3 border-warning'> <h3 class="card-title">${intern.getName()}</h3> <p class="card-text">ID: ${intern.getId()}</p> <p><a href="mailto:${intern.getEmail()}" class="card-text">${intern.getEmail()}</a></p> <p class="card-text">School:${intern.getSchool()}</p> </div> </div> </div>`; } function renderHtml(teamMembers) { let employees = ``; for (let i = 0; i < teamMembers.length; i++) { if (teamMembers[i].getRole() === "Manager") { employees += managerCard(teamMembers[i]); } else if (teamMembers[i].getRole() === "Engineer") { employees += engineerCard(teamMembers[i]); } else { employees += internCard(teamMembers[i]); } } return `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Employee Page</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script> </head> <body> <div class='container-fluid'> <div class='row'> <div class="col-12 jumbotron mb-3 text-center bg-secondary text-white"> <h1>My Team</h1> </div> </div> <div class='container'> <div class='row'> ${employees} </div> </div> </body> </html>`; } module.exports = renderHtml;
d.rebase (function () { var e = document.getElementById ('examples'); var examples = {square: 'r4i {m100 t90}', circle: 'r360i {m1 t1}', spiral: 'r120i {\nmove(i);t60}', dome: 'p60 r120i {\nmove(i);t60 p-2}', torus: 'r40i {p90 j100 r30j {m12 p12} j-100 p-90 t90 j5 t-90 b9}', squares: 'r100i {m100 t89 p2}', sphere: 'p60 r20i {p4.5 r40j {m10 p9} p-4.5 t9}', corkscrew: 'p-30 r50i {b5 r2j {m10 t90 m100 t90} j10}', original: 'j-80 r100i {m160 t161 p1}'}; d.keys (examples) * (k >$> ( (document.createElement ('li'), document.createElement ('a'), document.createTextNode (k)) |$> ((li, a, t) >$> ( e.appendChild (li), li.appendChild (a), a.appendChild (t), a.href = '#', a.onclick = (_ >$> ( document.getElementById ('commands').value = examples[k].replace (/r(\d+)(\w+)/g, (_, n, i) >$> '\nfor (var #{i} = 0; #{i} < #{n}; ++#{i})'). replace (/m([\d-\.]+)/g, (_, n) >$> '\nmove(#{n});'). replace (/j([\d-\.]+)/g, (_, n) >$> '\njump(#{n});'). replace (/t([\d-\.]+)/g, (_, n) >$> '\nturn(#{n});'). replace (/b([\d-\.]+)/g, (_, n) >$> '\nbank(#{n});'). replace (/p([\d-\.]+)/g, (_, n) >$> '\npitch(#{n});'). replace (/}/g, '\n}'), false))))))}) (); var run_script = d.rebase (function (s) { var c = document.getElementById ('screen'); var t = cheloniidae.turtle ({pen: new cheloniidae.pen ({color: '#444', opacity: 0.6, size: 1})}); var v = new cheloniidae.viewport ({pov: cheloniidae.vector(0, 0, -350), context: c.getContext ('2d'), forward: cheloniidae.vector(0, 0, 1), up: cheloniidae.vector (0, 1, 0), width: 600, height: 350, batch: 10, delay: 0}); var commands = []; var move = d >$> commands << (t >$> t.move (d)), jump = d >$> commands << (t >$> t.jump (d)), turn = a >$> commands << (t >$> t.turn (a.degrees())), bank = a >$> commands << (t >$> t.bank (a.degrees())), pitch = a >$> commands << (t >$> t.pitch(a.degrees())); document.getElementById ('error-area').innerHTML = ''; try {eval ('(function() {' + s.toString() + '})') (); t = commands.fold ('$1($0)', t); v.context.clearRect (0, 0, v.width, v.height), v.queue = t.queue; v.render()} catch (e) {document.getElementById ('error-area').innerHTML = e.toString()} c.onmousedown = '@x_down = $0.clientX, @y_down = $0.clientY'.bind (c); document.onmousemove = e >$> ((c.x_down || c.y_down) && (e.shiftKey ? v.turn ((c.x_down - (c.x_down = e.clientX)).degrees()).pitch (-(c.y_down - (c.y_down = e.clientY)).degrees()) : e.ctrlKey ? v.zoom (c.y_down - (c.y_down = e.clientY)) : v.slide (c.x_down - (c.x_down = e.clientX), c.y_down - (c.y_down = e.clientY)), v.context.clearRect (0, 0, v.width, v.height), v.cancel ().render (false))); document.onmouseup = e >$> ((c.x_down || c.y_down) && (v.context.clearRect (0, 0, v.width, v.height), v.cancel().render(true)), c.x_down = c.y_down = null); });
let options = [ { id : 'circleWhite', src : './images/products/twelveRound/twelveRoundWhite.jpg', caption : 'Here is the caption for desk image', color: 'White' }, { id : 'circleDarkGray', src : './images/products/twelveRound/twelveRoundMetal.jpg', caption : 'Here is the caption for image 2', color: "Gun Metal" }, { id : 'circleSilver' , src : './images/products/twelveRound/twelveRoundSilver.jpg', caption : 'Here is the caption for image 3', color: 'Silver' }, { id : 'circleGold', src : './images/products/twelveRound/twelveRoundGold.jpg', caption : 'Here is the caption for image 4', color: 'Gold' }, { id : 'circleOrange' , src : './images/products/twelveRound/twelveRoundOrange.jpg', caption : 'Here is the caption for image 3', color: 'Orange' }, { id : 'circleTeal' , src : './images/products/twelveRound/twelveRoundTeal.jpg', caption : 'Here is the caption for image 3', color: 'Teal' }, { id : 'circleCarbon' , src : './images/products/twelveRound/twelveRoundCarbon.jpg', caption : 'Here is the caption for image 3', color: 'Carbon' }, { id : 'circleBlue' , src : './images/products/twelveRound/twelveRoundBlue.jpg', caption : 'Here is the caption for image 3', color: 'Classic Blue' }, //Start Nine Circle objects { id : 'circleWhiteNine', src : './images/products/nineRound/nineRoundWhite.jpg', caption : 'Here is the caption for desk image', color: 'White' }, { id : 'circleDarkGrayNine', src : './images/products/nineRound/nineRoundMetal.jpg', caption : 'Here is the caption for image 2', color: "Gun Metal" }, { id : 'circleSilverNine' , src : './images/products/nineRound/nineRoundSilver.jpg', caption : 'Here is the caption for image 3', color: 'Silver' }, { id : 'circleGoldNine', src : './images/products/nineRound/nineRoundGold.jpg', caption : 'Here is the caption for image 4', color: 'Gold' }, { id : 'circleOrangeNine' , src : './images/products/nineRound/nineRoundOrange.jpg', caption : 'Here is the caption for image 3', color: 'Orange' }, { id : 'circleTealNine' , src : './images/products/nineRound/nineRoundTeal.jpg', caption : 'Here is the caption for image 3', color: 'Teal' }, { id : 'circleCarbonNine' , src : './images/products/nineRound/nineRoundCarbon.jpg', caption : 'Here is the caption for image 3', color: 'Carbon' }, { id : 'circleBlueNine' , src : './images/products/nineRound/nineRoundCarbon.jpg', caption : 'Here is the caption for image 3', color: 'Classic Blue' }, //Start of Square objects //For square planters { id : 'squareWhite' , src : './images/products/twelveSquare/twelveSquareWhite.jpg', caption : 'Here is the caption for image 3', color: 'White' }, { id : 'squareDarkGray', src : './images/products/twelveSquare/twelveSquareMetal.jpg', caption : 'Here is the caption for desk image', color: 'Gun Metal' }, { id : 'squareSilver', src : './images/products/twelveSquare/twelveSquareSilver.jpg', caption : 'Here is the caption for desk image', color: 'Silver' }, { id : 'squareGold', src : './images/products/twelveSquare/twelveSquareGold.jpg', caption : 'Here is the caption for desk image', color: 'Gold' }, { id : 'squareOrange', src : './images/products/twelveSquare/twelveSquareOrange.jpg', caption : 'Here is the caption for desk image', color: 'Orange' }, { id : 'squareTeal', src : './images/products/twelveSquare/twelveSquareTeal.jpg', caption : 'Here is the caption for desk image', color: 'Teal' }, { id : 'squareCarbon' , src : './images/products/twelveSquare/twelveSquareCarbon.jpg', caption : 'Here is the caption for image 3', color: 'Carbon' }, { id : 'squareBlue' , src : './images/products/twelveSquare/twelveSquareBlue.jpg', caption : 'Here is the caption for image 3', color: 'Classic Blue' }, //Start Nine Square objects { id : 'squareWhiteNine' , src : './images/products/nineSquare/nineSquareWhite.jpg', caption : 'Here is the caption for image 3', color: 'White' }, { id : 'squareDarkGrayNine', src : './images/products/nineSquare/nineSquareMetal.jpg', caption : 'Here is the caption for desk image', color: 'Gun Metal' }, { id : 'squareSilverNine', src : './images/products/nineSquare/nineSquareSilver.jpg', caption : 'Here is the caption for desk image', color: 'Silver' }, { id : 'squareGoldNine', src : './images/products/nineSquare/nineSquareGold.jpg', caption : 'Here is the caption for desk image', color: 'Gold' }, { id : 'squareOrangeNine', src : './images/products/nineSquare/nineSquareOrange.jpg', caption : 'Here is the caption for desk image', color: 'Orange' }, { id : 'squareTealNine', src : './images/products/nineSquare/nineSquareTeal.jpg', caption : 'Here is the caption for desk image', color: 'Teal' }, { id : 'squareCarbonNine', src : './images/products/nineSquare/nineSquareCarbon.jpg', color: 'Carbon' }, { id : 'squareBlueNine', src : './images/products/nineSquare/nineSquareBlue.jpg', color: 'Classic Blue' }, //Start Rectangle objects //For Rectangle Content { id : 'rectangleWhite', src : '', caption : 'Here is the caption for desk image', color: 'White' }, { id : 'rectangleDarkGray', src : './images/products/rectangle/rectangleMetal.jpg', caption : 'Here is the caption for desk image', color: 'Gun Metal' }, { id : 'rectangleSilver', src : './images/products/rectangle/rectangleSilver.jpg', caption : 'Here is the caption for desk image', color: 'Silver' }, { id : 'rectangleGold', src : '', caption : 'Here is the caption for desk image', color: 'Gold' }, { id : 'rectangleOrange', src : './images/products/rectangle/rectangleOrange.jpg', caption : 'Here is the caption for desk image', color: 'Orange' }, { id : 'rectangleTeal', src : '', caption : 'Here is the caption for desk image', color: 'Teal' }, { id : 'rectangleCarbon' , src : '', caption : 'Here is the caption for image 3', color: 'Carbon' }, { id : 'rectangleBlue' , src : '', caption : 'Here is the caption for image 3', color: 'Classic Blue' }, //Start SoftSqaure section //SoftSquare Products { id : 'softSquareWhite', src : './images/products/twelveSoft/twelveSoftWhite.jpg', caption : 'Here is the caption for desk image', color: 'White' }, { id : 'softSquareDarkGray', src : './images/products/twelveSoft/twelveSoftMetal.jpg', caption : 'Here is the caption for desk image', color: 'Gun Metal' }, { id : 'softSquareSilver', src : './images/products/twelveSoft/twelveSoftSilver.jpg', caption : 'Here is the caption for desk image', color: 'Silver' }, { id : 'softSquareGold', src : './images/products/twelveSoft/twelveSoftGold.jpg', caption : 'Here is the caption for desk image', color: 'Gold' }, { id : 'softSquareOrange', src : './images/products/twelveSoft/twelveSoftOrange.jpg', caption : 'Here is the caption for desk image', color: 'Orange' }, { id : 'softSquareTeal', src : './images/products/twelveSoft/twelveSoftTeal.jpg', caption : 'Here is the caption for desk image', color: 'Teal' }, { id : 'softSquareCarbon' , src : './images/products/twelveSoft/twelveSoftCarbon.jpg', caption : 'Here is the caption for image 3', color: 'Carbon' }, { id : 'softSquareBlue' , src : './images/products/twelveSoft/twelveSoftBlue.jpg', caption : 'Here is the caption for image 3', color: 'Classic Blue' }, //Start Nine Inch Soft Square { id : 'softSquareNineWhite', src : './images/products/nineSoft/nineSoftWhite.jpg', caption : 'Here is the caption for desk image', color: 'White' }, { id : 'softSquareNineDarkGray', src : './images/products/nineSoft/nineSoftMetal.jpg', caption : 'Here is the caption for desk image', color: 'Gun Metal' }, { id : 'softSquareNineSilver', src : './images/products/nineSoft/nineSoftSilver.jpg', caption : 'Here is the caption for desk image', color: 'Silver' }, { id : 'softSquareNineGold', src : '', caption : 'Here is the caption for desk image', color: 'Gold' }, { id : 'softSquareNineOrange', src : './images/products/nineSoft/nineSoftOrange.jpg', caption : 'Here is the caption for desk image', color: 'Orange' }, { id : 'softSquareNineTeal', src : '', caption : 'Here is the caption for desk image', color: 'Teal' }, { id : 'softSquareNineCarbon' , src : './images/products/nineSoft/nineSoftCarbon.jpg', caption : 'Here is the caption for image 3', color: 'Carbon' }, { id : 'softSquareNineBlue' , src : '', caption : 'Here is the caption for image 3', color: 'Classic Blue' }, //Start Triangle section //Triangle Products { id : 'triangleWhite', src : './images/products/nineTriangle/nineTriangleWhite.jpg', caption : 'Here is the caption for desk image', color: 'White' }, { id : 'triangleDarkGray', src : './images/products/nineTriangle/nineTriangleMetal.jpg', caption : 'Here is the caption for desk image', color: 'Gun Metal' }, { id : 'triangleSilver', src : './images/products/nineTriangle/nineTriangleSilver.jpg', caption : 'Here is the caption for desk image', color: 'Silver' }, { id : 'triangleGold', src : './images/products/nineTriangle/nineTriangleGold.jpg', caption : 'Here is the caption for desk image', color: 'Gold' }, { id : 'triangleOrange', src : './images/products/nineTriangle/nineTriangleOrange.jpg', caption : 'Here is the caption for desk image', color: 'Orange' }, { id : 'triangleTeal', src : './images/products/nineTriangle/nineTriangleTeal.jpg', caption : 'Here is the caption for desk image', color: 'Teal' }, { id : 'triangleCarbon' , src : './images/products/nineTriangle/nineTriangleCarbon.jpg', caption : 'Here is the caption for image 3', color: 'Carbon' }, { id : 'triangleBlue' , src : './images/products/nineTriangle/nineTriangleBlue.jpg', caption : 'Here is the caption for image 3', color: 'Classic Blue' }, //Start Hexagon Products { id : 'hexWhite', src : './images/products/twelveHex/twelveHexWhite.jpg', caption : 'Here is the caption for desk image', color: 'White' }, { id : 'hexDarkGray', src : './images/products/twelveHex/twelveHexMetal.jpg', caption : 'Here is the caption for desk image', color: 'Gun Metal' }, { id : 'hexSilver', src : './images/products/twelveHex/twelveHexSilver.jpg', caption : 'Here is the caption for desk image', color: 'Silver' }, { id : 'hexGold', src : './images/products/twelveHex/twelveHexGold.jpg', caption : 'Here is the caption for desk image', color: 'Gold' }, { id : 'hexOrange', src : './images/products/twelveHex/twelveHexOrange.jpg', caption : 'Here is the caption for desk image', color: 'Orange' }, { id : 'hexTeal', src : './images/products/twelveHex/twelveHexTeal.jpg', caption : 'Here is the caption for desk image', color: 'Teal' }, { id : 'hexCarbon', src : './images/products/twelveHex/twelveHexCarbon.jpg', caption : 'Here is the caption for desk image', color: 'Carbon' }, { id : 'hexBlue', src : '', caption : 'Here is the caption for desk image', color: 'Classic Blue' }, ]; function imageChange(choice, container) { // console.log('choice: ', choice); // console.log(container); let obj = options.find(o => o.id === choice.id); $("#noImage").removeClass('silverBorder whiteBorder goldBorder orangeBorder darkGrayBorder tealBorder blueBorder carbonBorder'); $('#productImage').attr('src',obj.src); $("#captionColor").html(obj.color); $('#' + container.id + '>.infoContainer>.colors>.options>span.currentColor').removeClass('currentColor'); $(choice).addClass('currentColor'); // if(container.id === 'triangle'){ // $(".options .choice").removeClass('border'); // $(choice).addClass('border'); // } // else{ // $(choice).addClass('currentColor'); // } if(obj.src === ''){ let border = $("#" + choice.id).attr('class').split(' ')[1] + 'Border'; $('#noImage').addClass(border); // $("#" + container.id).find('.noImage').css('border-color', obj.color.replace(' ', '')); // if (obj.color === 'Gun Metal'){ // $("#" + container.id).find('.noImage').css('border-color', 'RGB(52,53,58)'); // } // $('#' + container.id + '>.imageSection>.noImage').css('background', obj.color); $('#noImage').removeClass('hide'); $('#productImage').addClass('hide'); // if (container.id === 'triangle'){ // $('#' + container.id).find('.noImage').css('border-color', 'transparent'); // console.log("is triangle! changing color:", obj.color); // $('#triangle >.imageContainer>.imageSection>.noImage').css("border-bottom-color", obj.color.replace(' ', '')); // $('#' + container.id + '>.imageContainer>.imageSection>.noImage').css('background', 'none'); // } } else{ $('#noImage').addClass('hide'); $('#productImage').removeClass('hide'); } }; $('.choice').on('mouseover', function(){ // let color = $(this).attr('class').split(' ')[1]; let obj = options.find(o => o.id === this.id) let color = obj.color; let triangle = document.getElementById('triangle'); if(triangle !== null){ console.log(color); console.log($(this)); $(this).html(color); } else{ console.log(color); console.log($(this)); $(this).html(color); } }).on('mouseleave', function(){ let triangle = document.getElementById('triangle'); if(triangle !== null){ console.log(this); $(this).html(''); } else{ $(this).html(''); } // $(this).html(''); }) // $('.choice').on('mouseover', function(){ // let color = $(this).attr('class').split(' ')[1]; // let triangle = document.getElementById('triangle'); // $(this).html(color); // if(triangle !== null){ // console.log(color); // $("#" + this.id + ">p").html(color); // } // else{ // console.log(color); // $(this).html(color); // } // }).on('mouseleave', function(){ // $(this).html(''); // let triangle = document.getElementById('triangle'); // if(triangle !== null){ // console.log(this); // console.log($(this.id + '>p')); // $("#" + this.id + ">p").html(''); // } // else{ // $(this).html(''); // } // $(this).html(''); // }) //------------------Shop Updates-------------// $('.imageChoice').on('click', function(){ console.log('imageReel'); $(this).addClass('selectedImage').siblings().removeClass('selectedImage'); })
import React from 'react'; import styles from './styles/blog.scss'; import { Link } from 'react-router-dom'; const Blog = () => { return ( <div id='Lessons' className={`row ${styles.container}`}> <div className={`${styles.semitransparent} col-lg-4 col-md-6 col-sm-8 col-xs-10 col-lg-offset-4 col-md-offset-3 col-sm-offset-2 col-xs-offset-1`}> <h1>Lessons</h1> <ul className={styles.list}> <li> <Link to='/lesson_1'><h3>Let&#39;s Start from the Beginning</h3></Link> <p> Dust off those critical reading skills and join me in taking an in-depth dive into the white paper that inspired the crypto-currency movement: <b> Bitcoin: A Peer-To-Peer Electronic Cash System</b>. Read the primary source, my/other&#39;s annotations, then make your own. </p> </li> </ul> </div> </div> ); }; export default Blog;
$(function () { layui.config({ version: '1545041465480' //为了更新 js 缓存,可忽略 }); //注意:这里是数据表格的加载数据,必须写 layui.use(['table', 'layer', 'form', 'laypage', 'laydate'], function () { var table = layui.table //表格 ,layer = layui.layer //弹层 ,form = layui.form //form表单 ,laypage = layui.laypage //分页 ,laydate = layui.laydate;//日期 //执行一个laydate实例 laydate.render({ elem: '#start' //指定元素 }); //执行一个laydate实例 laydate.render({ elem: '#end' //指定元素 }); //执行一个 table 实例 table.render({ elem: '#zq_table' ,id: 'tableReload'//重载数据表格 ,url: '/menu/page' //数据接口 ,toolbar: '#zq_toolbar' //开启头工具栏,此处default:显示默认图标,可以自定义模板,详见文档 ,title: 'xx表' ,page: true //开启分页 // ,totalRow: true //开启合计行 ,cols: [[ //表头 {type: 'checkbox', fixed: 'left'} ,{field: 'id', title: 'ID', width:80, sort: true, fixed: 'left', totalRowText: '合计:'} //totalRow:true则代表这列数据要合计 ,{field: 'name', title: '菜单名称',edit: 'text'} ,{field: 'url', title: '菜单路径', sort: true, totalRow: true,edit: 'text'} ,{field: 'icon', title: '菜单图标', sort: true,edit: 'text'} ,{field: 'parent', title: '菜单', sort: true, totalRow: true,edit: 'text',templet: '#zq_formatter'} ,{field: 'children', title: '子菜单',edit: 'text'} ,{fixed: 'right',title:'操作', width: 150, align:'center', toolbar: '#zq_bar'} ]] }); //监听头工具栏事件 table.on('toolbar(zq_table)', function(obj){ var checkStatus = table.checkStatus(obj.config.id) ,data = checkStatus.data; //获取选中的数据 //json字符串转换成Json数据 eval("("+jsonStr+")") /JSON.parse(jsonStr) data = eval("("+JSON.stringify(data)+")"); switch(obj.event){ case 'delAll': if(data.length === 0){ layer.msg('请至少选择1行', { icon: 2, time: 1500 }); }else { layer.alert('您确认要删除'+data.length+'条数据吗?', { skin: 'layui-layer-molv' //样式类名layui-layer-lan或layui-layer-molv 自定义样式 ,closeBtn: 1 // 是否显示关闭按钮 ,anim: 1 //动画类型 ,btn: ['确定','取消'] //按钮 ,icon: 2 // icon ,yes:function(){ // layer.msg('确定', { icon: 1, time: 1500 }); for (var i=0;i<data.length;i++){ console.debug("id:======"+data[i].id) //发送请求到后台 $.post("menu/delete", { id: data[i].id }, function (result) { if (result.code == "1") {//删除成功,刷新当前页表格 // obj.del(); //删除对应行(tr)的DOM结构,并更新缓存 layer.msg(result.msg, { icon: 1, time: 1500 }); // layer.close(index); $(".layui-laypage-btn").click();//点击分页刷新当前页 }else if(result.code == "-1"){ //删除失败 layer.alert(result.msg, { icon: 2},function () { $(".layui-laypage-btn").click(); window.location.reload(); }); } }); } /* //捉到所有被选中的,发异步进行删除 layer.msg('删除成功', {icon: 1}); $(".layui-form-checked").not('.header').parents('tr').remove();*/ } ,btn2:function(){ layer.msg('好的,暂时不给您删除。',{ icon: 1, time: 1500 }); } }); } break; case 'add': zq_form('添加菜单','url这个值不管','',''); //数据回显 // $("#zq_form").setForm({id:data.id,name: data.name, url: data.url,icon:data.icon,parent:data.parent,children:data.children}); $("#zq_form").setForm({id:''}); break; } }); //监听行工具事件 table.on('tool(zq_table)', function(obj){ //注:tool 是工具条事件名,zq_table 是 table 原始容器的属性 lay-filter="对应的值" var data = obj.data //获得当前行数据 ,layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值) var tr = obj.tr; //获得当前行 tr 的DOM对象 switch(layEvent){ case 'detail': //json字符串转换成Json数据 eval("("+jsonStr+")") /JSON.parse(jsonStr) var jsonstr = JSON.stringify(data);//json数据转字符串 JSON.stringify(obj) layer.alert(jsonstr); break; case 'del': layer.confirm('您确定删除id:'+data.id+'的数据吗?', function(index){ //向服务端发送删除指令,在这里可以使用Ajax异步 $.post("menu/delete", { id: data.id }, function (ret) { if (ret.code == "1") {//删除成功,刷新当前页表格 layer.msg(ret.msg, { icon: 1, time: 1500 }, function () { obj.del(); //删除对应行(tr)的DOM结构,并更新缓存 layer.close(index); // $(".layui-laypage-btn").click();//点击分页刷新当前页 }); }else if(ret.code == "-1"){ //删除失败 layer.alert(ret.msg, { icon: 2},function () { layer.close(index); // $(".layui-laypage-btn").click(); window.location.reload(); }); } }); }); break; case 'edit': console.debug(data); zq_form('编辑菜单','url这个值不管',500,400); //数据回显 $("#zq_form").setForm({id:data.id,name: data.name, url: data.url,icon:data.icon,parent:data.parent,children:data.children}); break; } }); //监听单元格编辑 zq_table 对应 <table> 中的 lay-filter="zq_table" 做可编辑表格使用 table.on('edit(zq_table)', function(obj){ var value = obj.value //得到修改后的值 ,data = obj.data //得到所在行所有键值 ,field = obj.field; //得到字段 layer.msg('[ID: '+ data.id +'] ' + field + ' 字段更改为:'+ value); }); /* //监听显示操作 form.on('switch(isShow)', function(obj) { var t = this; layer.tips(t.value + ' ' + t.name + ':' + obj.elem.checked, obj.othis); });*/ //监听提交 lay-filter="zq_submit" form.on('submit(zq_submit)', function(data){ // console.log(data.elem) //被执行事件的元素DOM对象,一般为button对象 // console.log(data.form) //被执行提交的form对象,一般在存在form标签时才会返回 console.log(data.field) //当前from表单所提交的所有字段, 名值对形式:{name: value} layer.msg(JSON.stringify(data.field));//表格数据序列化 var formData = data.field; var id = formData.id, name = formData.name, url=formData.url, icon=formData.icon, parent_id=formData.parent_id; $.ajax({ type: "post", //数据提交方式(post/get) url: "/menu/save", //提交到的url data: {"id":id,"name":name,"url":url,"icon":icon,"parent_id":parent_id},//提交的数据 dataType: "json",//返回的数据类型格式 success: function(msg){ if (msg.success){ //成功 layer.msg(msg.msg, { icon: 1, time: 1500 }); table.reload('tableReload');//数据表格重载 layer.close(index);//关闭弹出层 }else { //失败 layer.alert(msg.msg, { icon: 2},function () { // $(".layui-laypage-btn").click();//执行分页刷新当前页 layer.close(index); // window.location.reload(); }); } } }); return false;//false:阻止表单跳转 true:表单跳转 }); //监听提交 lay-filter="search" form.on('submit(search)', function(data){ layer.msg(JSON.stringify(data.field));//表格数据序列化 var formData = data.field; console.debug(formData); var name = formData.name, url=formData.url, icon=formData.icon, parent_id=formData.parent_id; //数据表格重载 table.reload('tableReload', { page: { curr: 1 //重新从第 1 页开始 } , where: {//这里传参 向后台 name: name, url:url } , url: '/menu/page'//后台做模糊搜索接口路径 , method: 'post' }); return false;//false:阻止表单跳转 true:表单跳转 }); }); }); var index;//layer.open 打开窗口后的索引,通过layer.close(index)的方法可关闭 //表单弹出层 function zq_form(title,url,w,h){ if (title == null || title == '') { title=false; }; if (url == null || url == '') { };// url="404.html"; if (w == null || w == '') { w=($(window).width()*0.9); }; if (h == null || h == '') { h=($(window).height() - 50); }; index = layer.open({ //layer提供了5种层类型。可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层) type:1, title:title, area: ['25%','55%'],//类型:String/Array,默认:'auto' 只有在宽高都定义的时候才不会自适应 // area: [w+'px', h +'px'], fix: false, //不固定 maxmin: true,//开启最大化最小化按钮 shadeClose: true,//点击阴影处可关闭 shade:0.4,//背景灰度 skin: 'layui-layer-rim', //加上边框 content:$("#zq_formpopbox").html() }); } //表单提交 onclick 普通的jquery实现 /*function zq_submit () { var formData = $("#zq_form").serializeFormToJson(); console.debug("============="+formData); var name = formData.name, url=formData.url, icon=formData.icon, parent_id=formData.parent_id; $.ajax({ type: "post", //数据提交方式(post/get) url: "/menu/save", //提交到的url data: {"name":name,"url":url,"icon":icon,"parent_id":parent_id},//提交的数据 dataType: "json",//返回的数据类型格式 success: function(msg){ if (msg.success){ //成功 //添加成功处理代码... layer.msg(msg.msg, { icon: 1, time: 1500 }); }else { //失败 //添加失败处理代码... layer.alert(msg.msg, { icon: 2},function () { $(".layui-laypage-btn").click();//执行分页刷新当前页 }); return false; } } }); }*/ //表单提交 onclick 普通的jquery实现 高级查询 /*function search () { var formData = $("#zq_search").serializeFormToJson(); console.debug(formData); var name = formData.name, url=formData.url, icon=formData.icon, parent_id=formData.parent_id; $.ajax({ type: "post", //数据提交方式(post/get) url: "/menu/page", //提交到的url data: {"name":name,"url":url,"icon":icon,"parent_id":parent_id},//提交的数据 dataType: "json",//返回的数据类型格式 success: function(msg){ if (msg.success){ //成功 //添加成功处理代码... layer.msg(msg.msg, { icon: 1, time: 1500 }); }else { //失败 //添加失败处理代码... layer.alert(msg.msg, { icon: 2},function () { // $(".layui-laypage-btn").click();//执行分页刷新当前页 }); return false; } } }); }*/ //下面忽略...=================================================================================================== /* var table = layui.table ,form = layui.form; layui.use('table', function () { // 引入 table模块 table.render({ id:"zq_table",// elem: '#layui_table_id',//指定表格元素 url: '/menu/page', //请求路径 cellMinWidth: 20 //全局定义常规单元格的最小宽度,layui 2.2.1 新增 ,skin: 'line ' //表格风格 line (行边框风格)row (列边框风格)nob (无边框风格) //,even: true //隔行换色 ,page: true //开启分页 ,limits: [10,20,50] //每页条数的选择项,默认:[10,20,30,40,50,60,70,80,90]。 ,limit: 10 //每页默认显示的数量 ,method:'post' //提交方式 ,cols: [[ {type:'checkbox'}, //开启多选框 { field: 'id', //json对应的key title: 'ID', //列名 sort: true // 默认为 false,true为开启排序 }, { field: 'name', //json对应的key title: '菜单名称', //列名 sort: true // 默认为 false,true为开启排序 }, { field: 'url', //json对应的key title: '菜单路径', //列名 sort: true // 默认为 false,true为开启排序 }, { field: 'icon', //json对应的key title: '菜单图标', //列名 sort: true // 默认为 false,true为开启排序 }, { field: 'parent', //json对应的key title: '菜单', //列名 sort: true // 默认为 false,true为开启排序 }, { field: 'children', //json对应的key title: '子菜单', //列名 sort: true // 默认为 false,true为开启排序 } ]] }); }); */ /* $(function () { var table = layui.table ,form = layui.form; layui.use('table', function () { // 引入 table模块 table.render({ id:"zq_table",// elem: '#layui_table_id',//指定表格元素 url: '/menu/page', //请求路径 cellMinWidth: 20 //全局定义常规单元格的最小宽度,layui 2.2.1 新增 ,skin: 'line ' //表格风格 line (行边框风格)row (列边框风格)nob (无边框风格) //,even: true //隔行换色 ,page: true //开启分页 ,limits: [10,20,50] //每页条数的选择项,默认:[10,20,30,40,50,60,70,80,90]。 ,limit: 10 //每页默认显示的数量 ,method:'post' //提交方式 ,cols: [[ {type:'checkbox'}, //开启多选框 { field: 'id', //json对应的key title: 'ID', //列名 sort: true // 默认为 false,true为开启排序 } ]] }); }); }); */ /*$(function(){ //声明变量来缓存组件 var menuDatagrid,menuDialog,menuDialogForm; //将组件缓存到变量中 menuDatagrid = $("#menuDatagrid"); menuDialog = $("#menuDialog"); menuDialogForm = $("#menuDialogForm"); //封装一个命令对象,存放按钮的响应函数 var cmdObj = { add : function(){ //打开模态框 menuDialog.dialog("open").dialog("setTitle","添加").dialog("center"); //清空form表单 menuDialogForm.form("clear"); }, edit:function(){ //获取选中行 var row = menuDatagrid.datagrid("getSelected"); //判断是否选中 if(!row){ $.messager.alert("温馨提示","亲,请选择一行进行修改","info"); return; } //打开模态框 menuDialog.dialog("open").dialog("setTitle","添加").dialog("center"); //回显form表单 menuDialogForm.form("load",row); }, delete:function(){ //获取选中行 var row = menuDatagrid.datagrid("getSelected"); //判断是否选中 if(!row){ $.messager.alert("温馨提示","亲,请选择一行进行删除","info"); return; } //询问是否删除 $.messager.confirm("温馨提示","亲,你确定要删除吗?",function(r){ if(r){ //发送ajax请求删除操作 $.get("menu/delete",{id:row.id},function (result) { if(result.success){ $.messager.alert("温馨提示",result.message,"info",function(){ //刷新 menuDatagrid.datagrid("reload"); }); }else{ $.messager.alert("温馨提示",result.errorCode+"-"+result.message,"info"); } },"json"); } }); }, refresh:function(){ // load reload loadData menuDatagrid.datagrid("reload"); }, //取消保存 cancelSave:function(){ menuDialog.dialog("close"); }, //保存 menuSave:function(){ //调用easyui form组件的submit方法 ajax方式提交 //注意不要调用jquery的submit menuDialogForm.form('submit', { url:'menu/save', onSubmit: function(){ return menuDialogForm.form("validate"); }, success:function(data){ //这里的data是一个json字符串 var result = $.parseJSON(data); if(result.success){ $.messager.alert("温馨提示",result.message,"info",function(){ //关掉dialog menuDialog.dialog("close"); //刷新 menuDatagrid.datagrid("reload"); }); }else{ $.messager.alert("温馨提示",result.errorCode+"-"+result.message,"info"); } } }); } } //初始化组件 menuDatagrid.datagrid({ url:'menu/list', title:"", fit:true, fitColumns:true, singleSelect:true, pagination:true,//分页 rownumbers:true, toolbar:"#menuDatagridToolbar", columns:[[ {field:'id',title:'编号',width:100}, {field:'name',title:'菜单名称',width:100}, {field:'url',title:'菜单路径',width:100}, {field:'icon',title:'菜单图标',width:100}, {field:'parent',title:'菜单',width:100}, ]] }); //初始化添加修改模态框 menuDialog.dialog({ width: 400, height: 300, closed: true,//默认关闭 modal: true, buttons:"#menuDialogButtons" }); //为页面的所有的按钮注册点击事件 //1 只想为我们自己定义的按钮注册事件 //2 事件的处理函数如何调用 $("a").on("click",function(){ //区分不同的按钮,调用指定的function //获取到data-cmd的值 var cmd = $(this).data("cmd"); //获取disabled属性值 var options = $(this).linkbutton("options"); if(cmd&&!options.disabled){ //调用对应的function cmdObj[cmd](); } }); });*/
import React, { useState, useEffect } from 'react'; import './WatchPage.css'; import DetailsCard from '../DetailsCard/DetailsCard'; import Header from '../Header/Header'; const WatchPage = () => { const [toWatch, setToWatch] = useState([]) useEffect(() => { retrieveSaved() }, []) const retrieveSaved = () => { const keys = Object.keys(localStorage) const saved = keys.map(key => { return JSON.parse(localStorage.getItem(key)); }) setToWatch(saved) } const saved = toWatch.map(anime => { return (<DetailsCard details={anime} noSave={true} retrieveSaved={retrieveSaved} key={anime.mal_id} canSave={true}/>) }) return ( <div> <Header title="Your Watch List" hasSearch={false} /> <section className="to-watch-container"> {saved} </section> </div> ) } export default WatchPage;
const express = require('express') const bodyParser = require('body-parser') var randomstring = require("randomstring"); var cors = require('cors') const app = express() app.use(cors()); app.use(bodyParser.json()) const credentials = require('../../utils/Credentials') const {storage_databaseCurr} = require("./Scripts/Storage_DB") const {datafactoryCurr} = require("./Scripts/Datafactory") const {sapCurr} = require("./Scripts/dataFacSAP") const {dataWarehouseCurr} = require("./Scripts/Storage_DW") const {sqlserverCurr} = require("./Scripts/SqlServer") const {storage_elasticpoolCurr} = require("./Scripts/ElasticPool") const {oracleCurr} = require("./Scripts/oracle") const {dynamic365Curr} = require("./Scripts/Dynamic365") const {datalakeCurr} = require("./Scripts/DataLake") const {datalakeSAPCurr} = require("./Scripts/datalakeSAP") const {datalakeOracleCurr} = require("./Scripts/datalakeOracle") const {dynamic365_DLCurr} = require("./Scripts/datalaked365") const {sqlserver_DLCurr} = require("./Scripts/datalakeserver") const {sap_SynapseCurr} = require("./Scripts/synapse_SAP") const {oracle_SynapseCurr} = require("./Scripts/synapse_Oracle") const {dynamic365_SynapseCurr} = require("./Scripts/synapse_d365") const {sqlserverSynapseCurr} = require("./Scripts/synapse_server"); //const { Output } = require('terraform-generator'); exports.dataETLHandler = async(req,res)=>{ data = req.body const cred = await credentials.getcredentials(req.headers.id) if(data.Name === "Storage_DB"){ console.log('storage account & DAtabase request') await storage_databaseCurr(data,cred,'Storage_DB'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "Datafactory"){ console.log('DataFactory request') await datafactoryCurr(data,cred,'Datafactory'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "SAP"){ console.log('SAP request') await sapCurr(data,cred,'SAP'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "Storage_DW"){ console.log('storage account & Datawarehouse request') await dataWarehouseCurr(data,cred,'Storage_DW'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "SQL"){ console.log('SQL request') await sqlserverCurr(data,cred,'SQL_Server'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "Storage_EP"){ console.log('storage account & Elastic pool request') await storage_elasticpoolCurr(data,cred,'Storage_EP'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if (data.Name === "Oracle"){ console.log('Oracle request') await oracleCurr(data,cred,'Oracle'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "Dynamic365"){ console.log('Dynamic365request') await dynamic365Curr(data,cred,'Dynamic365'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "DataLake"){ console.log('DataLake request') await datalakeCurr(data,cred,'DataLake'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "DataLake_Oracle"){ console.log('DataLake_Oracle request') await datalakeOracleCurr(data,cred,'DataLake_Oracle'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "DataLake_SAP"){ console.log('DataLake_SAP request') await datalakeSAPCurr(data,cred,'DataLake_SAP'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "DataLake_Dynamic365"){ console.log('DataLake_Dynamic365 request') await dynamic365_DLCurr(data,cred,'DataLake_Dynamic365'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "DataLake_SQL"){ console.log('DataLake_SQL request') await sqlserver_DLCurr(data,cred,'DataLake_SQL'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "Oracle_Synapse"){ console.log('Oracle_Synapse request') await oracle_SynapseCurr(data,cred,'Oracle_Synapse'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "Dynamic365_Synapse"){ console.log('Dynamic365_Synapse request') await dynamic365_SynapseCurr(data,cred,'Dynamic365_Synapse'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "SAP_Synapse"){ console.log('SAP_Synapse request') await sap_SynapseCurr(data,cred,'SAP_Synapse'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) }else if(data.Name === "SQL_Synapse"){ console.log('SQL_SynapseL request') await sqlserverSynapseCurr(data,cred,'SQL_Synapse'+randomstring.generate(5)).then(Output=>{ res.send(Output) }).catch(err=>{ res.status(400).send({"Error":"Not Available"}) }) } }
import React from 'react'; import './listContact.css'; import axios from 'axios'; import Contact from './contact'; import Input from './input'; import { read } from 'fs'; import IconSearch from '../assets/iconSearch.png'; import socketIOClient from "socket.io-client"; var socket; export default class ListContact extends React.Component{ state = { list: [], listFilter: [], listUserAdd: [], listUser: [], mode: '', inputSearch: '', boardContentFriendsRequest: false, boardContentFriends: true, countFriendsRequest: 0, countFriends: 0, contactSelect: '' } componentDidMount() { this.requestContact(); socket = socketIOClient('http://localhost:4000'); socket.on('eventFriendsModify', (data) => { if(data !== this.props.tokenUser){ this.requestContact(); } }); } requestContact = () => { axios.get(`http://localhost:4000/user/users/${this.props.tokenUser}`).then(res => { this.setState({listUser: res.data !== 'No users found!!' ? res.data : []}); axios.get(`http://localhost:4000/user/friends/${this.props.tokenUser}`).then(res => { if(res.status === 200){ if(res.data !== 'No information found!!'){ var listUserAdd = res.data; var count = 0; var countFriends = 0; listUserAdd.map((user) => user.Active ? countFriends++ : count++); this.setState({listUserAdd: res.data, countFriendsRequest: count, countFriends }); var listUser = this.state.listUser; var list = []; listUser.map((user) => listUserAdd.findIndex(useradd => useradd.Id === user.Id) < 0 && list.push(user)); this.setState({list,listFilter:list}); } } }); }); } selectContact = (idContact,nameContact) => { this.props.selectContact(idContact,nameContact); this.setState({contactSelect: idContact}); } changeValueSearch = (input) => { var listFilter = []; var list = this.state.list; list.map(user => ((user.Username).toString()).toLowerCase().indexOf((input.target.value).toLowerCase()) >= 0 && listFilter.push(user)); this.setState({inputSearch: input.target.value,listFilter: listFilter}); } render(){ return( <div> {this.props.mode === 'chat' && <div className="searchContact"> <Input className="input square" type="text" value={this.state.inputSearch} onChange={(input) => this.changeValueSearch(input)} /> <img className="iconSearch" src={IconSearch} /> </div> } {this.props.mode === 'chat' && this.state.listFilter.map((user, i) => <Contact key={i} nameContact={user.Username} tokenUser={this.props.tokenUser} idContact={user.Id} nameIcon="add" active={false} invited={false} add={true} inviteContact={() => this.requestContact()} /> ) } {this.props.mode === 'find' && <div> <div className="boardBrand" onClick={() => this.setState({boardContentFriendsRequest: !this.state.boardContentFriendsRequest})}><span>{this.state.boardContentFriendsRequest ? 'v' : '>' }</span><span>Friend requests:</span><span>{this.state.countFriendsRequest}</span></div> <div className="boardContent" style={!this.state.boardContentFriendsRequest ? {display: 'none'} : {}}> {this.state.countFriendsRequest === 0 && <p className="notFound">No pending friend requests</p>} {this.state.listUserAdd.map((user, i) => !user.Active && <Contact key={i} nameContact={user.Username} tokenUser={this.props.tokenUser} idContact={user.Id} nameIcon="" invited={user.Invited} active={user.Active} inviteContact={() => this.requestContact()} /> )} </div> <div className="boardBrand" onClick={() => this.setState({boardContentFriends: !this.state.boardContentFriends})}><span>{this.state.boardContentFriends ? 'v' : '>' }</span><span>Friends:</span></div> <div className="boardContent" style={!this.state.boardContentFriends ? {display: 'none'} : {}}> {this.state.countFriends === 0 && <p className="notFound">No friends found</p>} {this.state.listUserAdd.map((user, i) => user.Active && <span onClick={() => this.selectContact(user.Id,user.Username)}><Contact key={i} nameContact={user.Username} tokenUser={this.props.tokenUser} idContact={user.Id} nameIcon="" contactSelect={this.state.contactSelect === user.Id} invited={user.Invited} active={user.Active} inviteContact={() => this.requestContact()} /></span> )} </div> </div> } </div> ); } }
import axios from 'axios'; const TOKEN_KEY = '1863b96e04c24d408b28106d51afc728'; export const get = (url) => { return axios.get(url, { headers: { 'X-Auth-Token': TOKEN_KEY } }) .then((res) => { return res; }) .catch((error) => { console.log(error) }); };
var stream = require('stream'); module.exports = {connect: function(credentials, readyCallback, messageCallback){ var login = require('facebook-chat-api'); login(credentials, function callback(err, api){ if(err) return console.error(err); // Workaround to make a needlessly required argument optional again var native_sendTypingIndicator = api.sendTypingIndicator; api.sendTypingIndicator = function(thread_id, callback){ if(!callback) callback = function(){}; native_sendTypingIndicator(thread_id, callback); }; var native_sendMessage = api.sendMessage; api.sendMessage = function(message, threadID, callback){ try{ native_sendMessage(message, threadID, function(err, messageInfo){ if(err && err.errorDescription === "Please try closing and re-opening your browser window."){ console.log("Re-logging..."); api.logout(function(err){ console.log("Logged out", err); module.exports.connect(credentials, function(api){ console.log("Done re-logging."); api.sendMessage(text, message.thread_id, callback); }, messageCallback); }); } if(typeof callback === 'function') callback.apply(api, arguments); }); }catch(e){ if(typeof callback === 'function') callback(e); } }; api.type = "messenger"; api.userid = api.getCurrentUserID(); readyCallback(api); api.listen(function(err, message){ if(err) return console.error(err); message.body = message.body || ""; message.thread_id = message.threadID; console.log(message); if(message.isGroup === false) message.isAddressed = 2; // This is a PM if(message.mentions[api.userid]) message.isAddressed = 2; // This is a direct mention var reply = function(text, options, callback){ if(typeof options === "function"){ callback = options; options = {}; }else if(typeof options !== "object") options = {}; if(typeof text === "string") console.log("Responding to", message.thread_id, text); else{ console.log("Responding to", message.thread_id, "with an attachment"); // facebook-chat-api has the weirdest way of testing streams if(text.attachment && text.attachment instanceof stream.Stream && (typeof text.attachment._read !== 'Function' || typeof text.attachment._readableState !== 'Object')){ text.attachment._read = function(){}; text.attachment._readableState = {}; } } var delay = options.delay || 0; if(options.delay === undefined && typeof text === "string"){ delay = text.length * 100; // Subtract time since the original message was sent delay -= Date.now() - message.timestamp; // Ensure delay is non-negative and no more than 2 seconds delay = Math.min(Math.max(delay, 0), 2000); } if(delay > 0){ api.sendTypingIndicator(message.thread_id); console.log("Delaying response by " + delay + "ms"); } setTimeout(api.sendMessage.bind(api, text, message.thread_id, callback), delay); }; messageCallback(reply, message, api); }); }); }};
var TreeNode = function(value, left, right) { this.value = value; this.left = left; this.right = right; } var tree = new TreeNode(30, new TreeNode(8, new TreeNode(3), new TreeNode(20, new TreeNode(10), new TreeNode(29) ) ), new TreeNode(52) ); var fs = require("fs"); fs.readFileSync("input.txt").toString().split("\n").forEach(function (line) { if (line !== "") { lowestCommonAncestor(line); } }); function lowestCommonAncestor(line) { var temp = line.trim().split(" "), path1 = pathToNodeWithValue(tree, parseInt(temp[0]), []), path2 = pathToNodeWithValue(tree, parseInt(temp[1]), []), common = undefined; for (var i = 0, count = Math.min(path1.length, path2.length); i < count; i++) { if (path1[i] === path2[i]) { common = path1[i]; } else { break; } } console.log(common); } function pathToNodeWithValue(tree, value, path) { if (tree.value === value) { path.push(tree.value); return path; } else if (value < tree.value) { if (tree.left) { path.push(tree.value); return pathToNodeWithValue(tree.left, value, path); } else { throw Error("node with value " + value + " doesn't find"); } } else { if (tree.right) { path.push(tree.value); return pathToNodeWithValue(tree.right, value, path); } else { throw Error("node with value " + value + " doesn't find"); } } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ErrorHandler = (function () { function ErrorHandler(key, params) { this.key = key; this.params = params; this.errorMessages = { invalidSelector: "Can't find HTMLFormElement or HTMLInputElement on %selector% selector", invalidTarget: "Can't find HTMLFormElement or HTMLInputElement on %target% target", invalidErrorKey: "Invalid error key '%errorKey%'" }; } ErrorHandler.throw = function (key, params) { if (key === void 0) { key = ''; } if (params === void 0) { params = {}; } new ErrorHandler(key, params); }; ErrorHandler.prototype.getMessage = function () { if (!(this.key in this.errorMessages)) { ErrorHandler.throw("invalidErrorKey"); return ''; } var currentMessage = this.errorMessages[this.key]; for (var paramKey in this.params) { currentMessage = currentMessage.replace('%' + paramKey + '%', this.params[paramKey]); } return currentMessage; }; return ErrorHandler; }()); exports.ErrorHandler = ErrorHandler;
import React, { Component } from 'react'; import './Education.css'; import SocialSchool from 'material-ui/svg-icons/social/school'; import Paper from 'material-ui/Paper'; export default class Education extends Component { render() { return ( <Paper className="Education"> <div className="Education_TitleWrapper" > <SocialSchool/> <div className="Education_Title">Educations</div> </div> { this.props.schools.map((d, index) => <div className='Education_School' key={index}> <div className='Education_SchoolHeader'> <div className='Education_SchoolNameProgramWrapper'> <div className='Education_SchoolName'> {d.name} </div> <div className='Education_SchoolProgram'> {d.program} </div> </div> <div className='Education_SchoolDate'> {d.begin} - {d.end} </div> </div> { d.awards !== null ? (<div className='Education_Awards'> {d.awards.map((award, aid) => <div className='Education_AwardItem' key={aid}> - {award} </div> )} </div> ) : '' } </div> ) } </Paper> ); } }
///Counting Sort Algorithm's code here.. function count_sort(arr, min, max){ let i; let Y = 0; let count = []; for(i = min; i <= max; i++){ count[i] = 0; } for(i = 0; i <= arr.length; i++){ count[arr[i]]++ } for(i = min; i <= max; i++){ while(count[i]-- > 0){ arr[Y++] = i; } } return arr; } ///Default items... let min = 0; let max = 5; let arr = [3, 0, 2, 5, 4, 1]; console.log('Before Sort.......', arr); //After Sorting... let letUsSort = count_sort(arr, min, max); console.log('After Sort--------', letUsSort);