text
stringlengths
7
3.69M
import axios from 'axios'; const instance = axios.create({ // baseURL: 'https://quiz-admin-api.priyoschool.com/admin/api' baseURL: 'http://68.183.186.191:8765', responseType: 'blob', }); instance.interceptors.request.use(function (config) { console.log('A request is made to Priyo quiz'); console.log('Injecting authorization header'); // config.headers.Authorization = 'Token b5ea0dd65c9fff4977bd4ec76a62d00e1ceddf44'; const token = localStorage.getItem('token'); const role = localStorage.getItem('role'); if (token) config.headers.Authorization = 'Token ' + token; if (role) config.headers.role = role; // if (!config.headers.Accept) // config.headers.Accept = "application/vnd.api+json"; // if(!config.headers['Content-Type']) // config.headers['Content-Type'] = "application/vnd.api+json"; return config; }); export default instance;
// pages/orderteacher/orderteacher.js Page({ /** * 页面的初始数据 */ data: { bgpic: null, tid: null, openid: '', teacherid: '', classsigns: null, userInfo:"", orderState: [0, 0, 0, 0], warming: false, orderArray: null, orderList: [] }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { wx.getStorage({ key: 'openid', fail: () => { wx.redirectTo({ url: '../index/index', }) }, }) //先获取必要数据 wx.getStorage({ key: 'openid', success: (res)=>{this.setData({openid: res.data}) console.log(res.data)}, }) wx.getStorage({ key: 'teacherid', success: (res)=>{ this.setData({ teacherid: res.data }) }, }) var that = this; wx.request({ url: 'https://www.qczyclub.com/Getime', header: { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' }, method: 'post', data: { 'openid': that.data.openid, 'tid': 1 }, success:(res)=> { console.log(res) this.setData({ orderList: res.data }) } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { // 这里生成时间,将这个时间传到服务器,来判别当前时间 var that = this; // var timestamp = Date.parse(new Date()); // console.log(timestamp); // console.log(that.data.tid); }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, //勾选框判定事件 checkBoxChange: function(e) { let data = this.data.orderState; let arrNumber = e.currentTarget.id; data[arrNumber] = !data[arrNumber]; }, confirm: function(e) { let that = this let result = 0 let orderState = this.data.orderState //将预约数据传入 wx.showLoading({ title: '预约中', }) for(let i=1; i<5; i++){ if(orderState[i-1]){ wx.request({ url: 'https://www.qczyclub.com/userappoint', method: 'post', data: { 'openid': that.data.openid, 'classid': i, 'tid': that.data.teacherid }, header: { 'Content-Type': "application/x-www-form-urlencoded;charset=UTF-8", }, success: function(res) { console.log(res) wx.hideLoading() if(res.data){ wx.showToast({ title: '预约成功!', icon: 'success', duration: 1500 }) }else{ wx.showToast({ title: '预约失败请稍后重试!', duration: 1000 }) } }, fail: function() { wx.hideLoading() wx.showToast({ title: '网络请求失败!', icon: 'none', duration: 1500 }) } }) } wx.hideLoading() this.setData({orderState:[0,0,0,0]}) } }, onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, })
module.exports = function (censusBase) { this.getMapOwnership = function (worldId, zoneId, callback) { var query = censusBase.createQuery('map'); query.setLanguage('en'); query.where('world_id').equals(worldId); query.where('zone_ids').equals(zoneId); censusBase.fetchData(query, false, callback); }; return this; };
const uuidV4 = require('uuid/v4') function RegisterASiteAction (APIService) { function run (siteData) { const method = 'registerASite' const id = uuidV4() const params = { siteData } const body = { method, params, id } return APIService.run(body) } return { run } } export default RegisterASiteAction
//ipc 管道通讯 var cp = require('child_process'); //只有使用fork才可以使用message事件和send()方法 var n = cp.fork('./child.js'); n.on('message',function(m){ //接收子进程消息 console.log(m); }) n.send({"message":"hello"}); //发送到子进程
import * as React from "react"; import { NavigationContainer } from "@react-navigation/native"; import { createStackNavigator } from "@react-navigation/stack"; import DashboardScreen from "../screens/DashboardScreen"; import AboutScreen from "../screens/AboutScreen"; import ProjectsScreen from "../screens/ProjectsScreen"; import ContactScreen from "../screens/ContactScreen"; import AddProjects from "../screens/AddProjectsScreen"; import AdminContact from "../screens/AdminContactScreen"; import ProjectDetails from "../screens/ProjectDetailsScreen"; import SignIn from "../screens/SignInScreen"; import * as Linking from "expo-linking"; export default function RootNavigator() { const Stack = createStackNavigator(); const linking = { prefixes: ["https://elite-terminal-services.firebaseapp.com", "elite://"], config: { screens: { DashboardScreen: "", AboutScreen: ":id/about", ContactScreen: ":id/contact", ProjectsScreen: ":id/projects", ProjectDetails: ":id/project-details", SignIn: ":id/admin" } } }; return ( <NavigationContainer linking={linking}> <Stack.Navigator headerMode="none" initialRouteName="DashboardScreen"> <Stack.Screen name="DashboardScreen" component={DashboardScreen} /> <Stack.Screen name="AboutScreen" component={AboutScreen} /> <Stack.Screen name="ProjectsScreen" component={ProjectsScreen} /> <Stack.Screen name="ProjectDetails" component={ProjectDetails} /> <Stack.Screen name="ContactScreen" component={ContactScreen} /> <Stack.Screen name="AddProjects" component={AddProjects} /> <Stack.Screen name="AdminContact" component={AdminContact} /> <Stack.Screen name="SignIn" component={SignIn} /> </Stack.Navigator> </NavigationContainer> ); }
const { Usuario } = require('../database/models') const userController = { index: async (req, res) => { const users = await Usuario.findAll(); console.log(users) } } module.exports = userController
/* You are given an initial 2-value array (x). You will use this to calculate a score. If both values in (x) are numbers, the score is the sum of the two. If only one is a number, the score is that number. If neither is a number, return 'Void!'. Once you have your score, you must return an array of arrays. Each sub array will be the same as (x) and the number of sub arrays should be equal to the score. For example: if (x) == ['a', 3] you should return [['a', 3], ['a', 3], ['a', 3]]. */ // We are given x, which is an array that contains two elements; // If x[0] && x[1] are of the Number data type, we can return the sum of those two values; // If only one of the two (x[0] or x[1]) are of the Number data type, we should return that value; // If neither of the two elements are of the Number data type, we should return "Void!"; // With the score (either the sum or the single numerical value), we must return a multidimensional array; // Each subarray will be an array containing the same values x originally held; // The amount of subarrays will reflect the score; function explode(x) { let arr = []; let score = 0; let primary = x[0]; let secondary = x[1]; if (Number.isInteger(primary) && Number.isInteger(secondary)) { score += primary; score += secondary; } else if (Number.isInteger(primary)) { score += primary; } else if (Number.isInteger(secondary)) { score += secondary; } else { return "Void!"; } while (score) { arr.push([primary, secondary]); score--; } return arr; }
const LEVEL = { LOG: 0, WARN: 1, ERROR: 2, }; let _level = 2; class Log { static setLevel(level) { _level = level; } constructor(name) { this.name = name; } log(message) { this._log(Log.LEVEL.LOG, message); } warn(message) { this._log(Log.LEVEL.WARN, message); } error(message) { this._log(Log.LEVEL.ERROR, message); } _log(level, message) { if(level >= _level) { let log = this.name + ': ' + message; switch(level) { case 0: log = '[log]' + log; break; case 1: log = '[warn]' + log; break; case 2: default: log = '[error]' + log; break; } console.log(log); } } } Log.LEVEL = LEVEL; module.exports = Log;
const path = require('path'); module.exports = { publicPath: '/static/src/vue/dist/', outputDir: path.resolve(__dirname, '../static/src/vue/dist/'), filenameHashing: false, runtimeCompiler: true, devServer: { writeToDisk: true, }, };
module.exports = (sequelize, DataTypes) => { const User = sequelize.define("user", { id : { type: DataTypes.INTEGER, // 구분용 primaryKey : true, autoIncrement: true }, name : { type: DataTypes.STRING, // 닉네임 allowNull: false }, pass : { type: DataTypes.STRING, // 비밀번호 allowNull: false } }); User.associate = function(models) { } return User; };
import React from "react"; import "./Nav.css"; function Nav({ goHome, route, goOut }) { return ( <nav className="Nav"> <h3 className="navText"> {route === "home" ? <p onClick={goOut}>Sign Out</p> : null} </h3> </nav> ); } export default Nav;
class Shape { constructor(canvas) { this.canvas = document.getElementById("canvas"); this.context = this.canvas.getContext('2d'); this.fontSize = 100;//字体大小 this.dotGap = 15;//点间隙 }; resize() { var canvas = this.canvas; var context = this.context; //canvas宽高样式 canvas.height = window.innerHeight; canvas.width = window.innerWidth; canvas.style.height = window.innerHeight; canvas.style.width = window.innerWidth; context.fillStyle = '#fff'; context.textBaseline = 'middle'; //设置当前文本基线--方框的正中。 context.textAlign = 'center'; //对齐方式 文本中心 }; genDotMap() { var canvas = this.canvas; var context = this.context; var data = context.getImageData(0, 0, canvas.width, canvas.height).data; var dotc = []; var dotGap = this.dotGap; for (var y = 0; y < canvas.height; y += dotGap) { for (var x = 0; x < canvas.width; x += dotGap) { if (data[y * canvas.width * 4 + x * 4] != 0) { dotc.push(new Point(x, y)); } } } return dotc; }; text(str) { var context = this.context; var canvas = this.canvas; var fontSize = this.fontSize; context.font = 'bold 30px sans-serif'; var size = Math.min(0.22 * fontSize / context.measureText(str).width * canvas.width, 0.6 * canvas.height); context.font = 'bold ' + Math.floor(size) + 'px sans-serif'; //设置或返回文本内容的当前字体属性 context.clearRect(0, 0, canvas.width, canvas.height);//清空矩形内容。 context.fillText(str,canvas.width / 2, canvas.height / 2);//字符串居中 }; } Shape.radius = 7; //半径 //绘制引擎 设置宽高 设置字体样式 class Engine extends Shape { constructor(canvas) { super(canvas) // canvas宽高 this.canvas.height = window.innerHeight; this.canvas.width = window.innerWidth; this.width = this.canvas.width; this.height = this.canvas.height; this.context = this.canvas.getContext("2d"); this.context.fillStyle = 'yellow'; this.shapeFactory = new Shape(); this.points = []; //存储像素数据 this.shapeFactory.resize(); //字体样式 window.addEventListener('resize', (e) => { this.canvas.height = window.innerHeight; this.canvas.width = window.innerWidth; this.width = this.canvas.width; this.height = this.canvas.height; // this.context.fillStyle = 'red'; this.shapeFactory.resize(); }); } genText(text) { this.shapeFactory.text(text);//设置字符串样式并显示 return this.shapeFactory.genDotMap(); //复制canvas像素进行处理 }; toText(text) { var points = this.genText(text); //获取canvas上的像素数据 return this._toShape(points); }; checkLife () { this.points = this.points.filter(function(point) { if (point.state === -1) { return false; } else { point.x = point.targetX; point.y = point.targetY; point.state = 0; return true; } }); }; shuffle () { var points = this.points; for (let i = points.length - 1; i > 0; i -= 1) { let j = Math.floor(Math.random() * (i + 1)) let temp = points[i]; points[i] = points[j]; points[j] = temp; } } shake (time) { var promise = new Promise((resolve, reject) => { time = time || 500; var context = this.context; var width = this.width; var height = this.height; var engine = this; var points = this.points; var totalProgress = 0.0; var step = 25 / time; var timer = setInterval(function(){ if (totalProgress >= 1.0) { clearInterval(timer); timer = null; totalProgress = 1.0; } context.clearRect(0, 0, width, height); points.forEach((point) => { point.shake();//抖动 point.render(context);//描绘渲染 }); if (timer === null) { engine.checkLife(); resolve(); } else { totalProgress += step; if (totalProgress > 1.0) { totalProgress = 1.0; } } }, 50); }); return promise; }; _toShape(targets) { var promise = new Promise((resolve, reject) => { var context = this.context; var width = this.width; var height = this.height; var engine = this; var points = this.points; var len = Math.min(targets.length, points.length); for (let i = 0; i < len; i++) { points[i].targetX = targets[i].x; points[i].targetY = targets[i].y; } if (points.length > targets.length) { for (let i = len; i < points.length; i++) { points[i].state = -1; points[i].targetX = Math.random() * width; points[i].targetY = Math.random() * height; } } else { for (let i = len; i < targets.length; i++) { points.push(targets[i]); targets[i].x = Math.random() * width; targets[i].y = Math.random() * height; points[i].state = 1; } } var totalProgress = 0.0; var timer = setInterval(function () { if (totalProgress >= 1.0) { clearInterval(timer); timer = null; totalProgress = 1.0; } context.clearRect(0, 0, width, height); var progress = (2 - totalProgress) * totalProgress; points.forEach((point) => { point.update(progress); point.render(context); }); if (timer === null) { engine.checkLife(); engine.shuffle(); resolve(); } else { totalProgress += 0.02; if (totalProgress > 1.0) { totalProgress = 1.0; } } }, 20); }); return promise; } }; //点 class Point extends Shape { constructor(x, y) { super(x, y) this.x = x; this.y = y; this.targetX = x;//目标 this.targetY = y; this.currentX = x; this.currentY = y; //当前 this.state = 0; this.r = Shape.radius; }; shake () { this.currentX = this.targetX + Math.random() * 2; this.currentY = this.targetY + Math.random() * 2; }; clear () { return new Engine()._toShape([]); }; update (ratio) { this.currentX = ratio * (this.targetX - this.x) + this.x; this.currentY = ratio * (this.targetY - this.y) + this.y; if (this.state === 0) { } else if (this.state === 1) { //逐渐显示 this.r = ratio * Shape.radius; } else { //逐渐消失 this.r = (1 - ratio) * Shape.radius; } }; render (context) { context.beginPath(); context.arc( this.currentX, this.currentY, this.r, 0, Math.PI * 0.5); context.closePath(); context.fill(); }; };
Ext.onReady(function () { Ext.define('gigade.EdmContentNewReport', { extend: 'Ext.data.Model', fields: [ { name: "trace_day", type: "string" }, { name: "openPerson", type: "int" }, { name: "openCount", type: "int" }, { name: "avgPerson", type: "string" }, { name: "avgCount", type: "string" }, ] }); EdmContentNewReportStore = Ext.create('Ext.data.Store', { autoLoad: 'true', pageSize: 25, model: 'gigade.EdmContentNewReport', proxy: { type: 'ajax', url: '/EdmNew/EdmContentNewReportList', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); Ext.define('gigade.CreatedateAndLogId', { extend: 'Ext.data.Model', fields: [ { name: "log_id", type: "int" }, { name: "createdate", type: "string" }, ] }); CreatedateAndLogIdStore = Ext.create('Ext.data.Store', { model: 'gigade.CreatedateAndLogId', autoLoad:true, proxy: { type: 'ajax', url: '/EdmNew/CreatedateAndLogId', reader: { type: 'json', root: 'data', } } }); CreatedateAndLogIdStore.on('beforeload', function () { Ext.apply(CreatedateAndLogIdStore.proxy.extraParams, { content_id: document.getElementById('content_id').value, }); }); EdmContentNewReportStore.on('beforeload', function () { Ext.apply(EdmContentNewReportStore.proxy.extraParams, { content_id: document.getElementById('content_id').value, log_id: Ext.getCmp('log_id').getValue(), }); }); var ReportForm = Ext.create('Ext.form.Panel', { id: 'ReportForm', layout: 'anchor', border: 0, bodyPadding: 10, width: document.documentElement.clientWidth, items: [ { xtype: 'combobox', store: CreatedateAndLogIdStore, displayField: 'createdate', valueField: 'log_id', id:'log_id', fieldLabel: '電子報統計報表', lastQuery:'', editable: false, listeners: { select: function () { var log_id = Ext.getCmp('log_id').getValue(); load(); EdmContentNewReportStore.load(); } } }, { xtype: 'displayfield', value: '<span style="color:white;color:green;font-size:20px;margin-left: 200px">開 信 狀 況 統 計 摘 要</span>' }, { xtype: 'fieldcontainer', layout: 'hbox', items: [ { xtype: 'displayfield', width: 100, value: '<span style="color:white;color:green;">郵件主旨</span>' }, { xtype: 'displayfield', width: 500, id: 'subject' }, { xtype: 'displayfield', width: 100, value: '<span style="color:white;color:green;">發送時間</span>' }, { xtype: 'displayfield', width: 200, id: 'date' }, ] }, { xtype: 'fieldcontainer', layout: 'hbox', items: [ { xtype: 'displayfield', width: 100, value: '<span style="color:white;color:green;">發信成功人數</span>' }, { xtype: 'displayfield', width: 500, id: 'successCount' }, { xtype: 'displayfield', width: 100, value: '<span style="color:white;color:green;">發信失敗人數</span>' }, { xtype: 'displayfield', width: 200, id: 'failCount' }, ] }, { xtype: 'fieldcontainer', layout: 'hbox', items: [ { xtype: 'displayfield', width: 100, value: '<span style="color:white;color:green;">總開信人數</span>' }, { xtype: 'displayfield', width: 500, id: 'totalPersonCount' }, { xtype: 'displayfield', width: 100, value: '<span style="color:white;color:green;">總開信次數</span>' }, { xtype: 'displayfield', width: 200, id: 'totalCount' }, ] }, { xtype: 'fieldcontainer', layout: 'hbox', items: [ { xtype: 'displayfield', width: 100, value: '<span style="color:white;color:green;">開信率</span>' }, { xtype: 'displayfield', width: 500, id: 'openAveragePrecent' }, { xtype: 'displayfield', width: 100, value: '<span style="color:white;color:green;">平均開信次數</span>' }, { xtype: 'displayfield', width: 200, id: 'openAverageCount' }, ] }, ] }); var EdmListGrid = Ext.create('Ext.grid.Panel', { id: 'EdmListGrid', store: EdmContentNewReportStore, width: document.documentElement.clientWidth, columnLines: true, frame: true, flex: 9.4, columns: [ { header: "開信時間", dataIndex: 'trace_day', width: 150, align: 'center' }, { header: "開信人數", dataIndex: 'openPerson', width: 150, align: 'center' }, { header: "開信次數", dataIndex: 'openCount', width: 150, align: 'center' }, { header: "人數比率", dataIndex: 'avgPerson', width: 80, align: 'center' }, { header: "次數比率", dataIndex: 'avgCount', width: 150, align: 'center' }, ], tbar: [ { xtype: 'button', text: "電子報統計報表", iconCls: '', id: 'edm_list', disabled: true, handler: onEdm_listClick }, { xtype: 'button', text: "發信名單統計", iconCls: '', id: 'edm_send', handler: onEdm_sendClick }, { xtype: 'button', text: "開信名單下載", iconCls: 'icon-excel', id: 'open_download', handler: onOpen_downloadClick }, { xtype: 'button', text: "未開信名單下載", iconCls: 'icon-excel', id: 'close_download', handler: onClose_downloadClick }, ], bbar: Ext.create('Ext.PagingToolbar', { store: EdmContentNewReportStore, pageSize: 25, displayInfo: true, displayMsg: "當前顯示記錄" + ': {0} - {1}' + "共計" + ': {2}', emptyMsg: "沒有記錄可以顯示" }), listeners: { scrollershow: function (scroller) { if (scroller && scroller.scrollEl) { scroller.clearManagedListeners(); scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller); } } } }); Ext.create('Ext.container.Viewport', { layout: 'vbox', items: [ReportForm, EdmListGrid], renderTo: Ext.getBody(), autoScroll: true, listeners: { resize: function () { EdmListGrid.width = document.documentElement.clientWidth; var log_id = document.getElementById('log_id').value; if (log_id != "" && log_id != 0) { Ext.getCmp('log_id').setValue(log_id) } else { CreatedateAndLogIdStore.on('load', function () { Ext.getCmp('log_id').select(CreatedateAndLogIdStore.getAt(0)); load(); EdmContentNewReportStore.load(); }); } load(); this.doLayout(); } } }); //QueryAuthorityByUrl('/EdmNew/EdmContentNewReport'); }); function load() { var content_id = document.getElementById('content_id').value; Ext.Ajax.request({ url: '/EdmNew/Load', params: { content_id: content_id, log_id: Ext.getCmp('log_id').getValue(), }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { Ext.getCmp('successCount').setValue(result.successCount); Ext.getCmp('failCount').setValue(result.failCount); Ext.getCmp('totalPersonCount').setValue(result.totalPersonCount); Ext.getCmp('totalCount').setValue(result.totalCount); Ext.getCmp('openAveragePrecent').setValue(result.openAveragePrecent); Ext.getCmp('openAverageCount').setValue(result.openAverageCount); Ext.getCmp('openAverageCount').setValue(result.openAverageCount); Ext.getCmp('subject').setValue(result.subject); if (result.date == "0001-01-01 00:00:00") { Ext.getCmp('date').setValue(""); } else { Ext.getCmp('date').setValue(result.date); } } else { Ext.Msg.alert("提示信息", "賦值出錯!"); } }, failure: function () { Ext.Msg.alert("提示信息", "獲取數據出現異常!"); } }); } function onOpen_downloadClick() { var content_id = document.getElementById('content_id').value; var log_id = Ext.getCmp('log_id').getValue(); window.open("/EdmNew/ImportKXMD?content_id=" + content_id + "&log_id=" + log_id); } function onClose_downloadClick() { var log_id = Ext.getCmp('log_id').getValue(); var content_id = document.getElementById('content_id').value; window.open("/EdmNew/ImportWKXMD?content_id=" + content_id + "&log_id=" + log_id); } function onEdm_sendClick() { var content_id = document.getElementById("content_id").value; var log_id = Ext.getCmp('log_id').getValue(); var urlTran = '/EdmNew/EdmSendListCountView?content_id=' + content_id + "&log_id=" + log_id;; var panel = window.parent.parent.Ext.getCmp('ContentPanel'); var copy = panel.down('#EdmSendListCount'); if (copy) { copy.close(); } copy = panel.add({ id: 'EdmSendListCount', title: '發信名單統計', html: window.top.rtnFrame(urlTran), closable: true }); panel.setActiveTab(copy); panel.doLayout(); } function onEdm_listClick() { var content_id = document.getElementById("content_id").value; var urlTran = '/EdmNew/EdmContentNewReport?content_id=' + content_id; var panel = window.parent.parent.Ext.getCmp('ContentPanel'); var copy = panel.down('#EdmListGrid'); if (copy) { copy.close(); } copy = panel.add({ id: 'EdmListGrid', title: '電子報統計報表', html: window.top.rtnFrame(urlTran), closable: true }); panel.setActiveTab(copy); panel.doLayout(); }
require('./env') require('should') const { db } = require('ben7th-fc-utils') const UserStore = require('../lib/UserStore') describe('UserStore', () => { before(async () => { await UserStore.__clear() await UserStore.createByLoginAndPassword({ login: 'ben7th1', password: '123456' }) await UserStore.createByLoginAndPassword({ login: 'ben7th2', password: '123456' }) await UserStore.createByLoginAndPassword({ login: 'ben7th3', password: '123456' }) await UserStore.createByLoginAndPassword({ login: 'ben7th4', password: '123456' }) }) it('UserStore', () => { should(UserStore).not.be.null }) it('getList', async () => { let users = await UserStore.getList() // console.log(users) should(users.length > 0).be.true() }) it('totalCount', async () => { let count = await UserStore.totalCount() should(count).equal(4) }) it('getOne', async () => { let user = await UserStore.createByLoginAndPassword({ login: 'slime', password: '123456' }) let id = user.store.id should(id).be.ok() let user1 = await UserStore.getOne(id) should(user1.id).be.ok() should(user1.id).be.equal(id) }) it('update', async () => { let user = await UserStore.createByLoginAndPassword({ login: 'duck', password: '123456' }) let id = user.store.id should(id).be.ok() should(UserStore.update).be.ok() should(user.store.description).be.not.ok() await UserStore.update(id, { description: '好的鸭' }) let user1 = await UserStore.getOne(id) should(user1.id).be.ok() should(user1.id).be.equal(id) should(user1.description).be.equal('好的鸭') }) })
var addFood,feed; var fedTime, lastFed; let food = []; var h; var milk,ml; var foods, foodStock; var dog,happyDog; var database; function preload(){ //Load images here happyDog=loadImage("images/dogImg.png"); sadDog=loadImage("images/dogImg1.png"); ml=loadImage("images/Milk.png") } function setup(){ database = firebase.database(); createCanvas(1000,500); lastFed = 1; var foodStock = database.ref('FoodS/food'); foodStock.on("value",function(data){ foods = data.val(); }) // foodObj = new Food(400,250) //console.log(reedStock); feed = createButton("Feed the dog"); feed.position(800,95); feed.mousePressed(feedDog); addFood = createButton("Add food for the dog"); addFood.position(900,95); addFood.mousePressed(addFoods); dog = createSprite(500,250,10,10); dog.addImage(sadDog); dog.scale=0.1; milk = createSprite(400,250); milk.addImage(ml); milk.scale=0.1 milk.visible=false; } function draw(){ background("green"); fedTime = database.ref('FeedTime') fedTime.on("value",function(data){ lastFed = data.val(); }) fill(0,0,0) textSize(25) text ("foods:"+foods,300,40); for ( var h = 0; h <food.length; h++) { food[h].display(); } fill(255,255,254); textSize(15); if(lastFed>=12){ text("Last Feed : " + lastFed%12 + "PM",50,30) } else if(lastFed==0){ text("Last Feed : 12 AM",50,30) } else{ text("Last Feed :"+ lastFed +"AM",50,30) } drawSprites(); } function feedDog (){ if(foods>0){ dog.addImage(happyDog) foods= foods-1; milk.visible=true; } database.ref('/').update({ FeedTime:hour() }) } function addFoods(){ if (foods<12){ dog.addImage(sadDog) foods++; milk.visible=false; } food.push(new Food) database.ref('/').update({ FoodS: foods }) }
var menuState = { create: function(){ //prevent page from moving around this.input.keyboard.addKeyCapture([Phaser.Keyboard.UP, Phaser.Keyboard.DOWN, Phaser.Keyboard.LEFT, Phaser.Keyboard.RIGHT, Phaser.Keyboard.SPACEBAR]); nowPlaying = false; resetNav(); drawPatternBG("#888800", "222277"); //buttonTint = 0xa3d0e5; buttonTint = 0xbce2f4; logo = game.add.sprite(game.world.width / 2, 80, 'logo', ); logo.anchor.setTo(0.5, 0.5); var titleLabel = game.add.text(game.world.width / 2, 180, getText("MainMenu", 0), getStyle("text_regular")); titleLabel.anchor.setTo(0.5, 0.5); titleLabel.align = "center"; //var enterKey = game.input.keyboard.addKey(Phaser.Keyboard.ENTER); var buttonStyle = getStyle("button_regular"); //enterKey.onDown.addOnce(this.start, this); btnNewGame = game.add.button(game.world.width / 2, game.world.height / 2, 'big_button', function(){show('singlePlayerPrep')}, this, 1, 2, 0); btnNewGame.anchor.setTo(0.5, 0.5); btnNewGame.tint = buttonTint; lblNewGame = game.add.text(game.world.width / 2, game.world.height / 2, getText("MainMenu", 1), buttonStyle); lblNewGame.anchor.setTo(0.5, 0.5); btnSettings = game.add.button(game.world.width / 2, (game.world.height / 2) + 60, 'big_button', function(){show('settings')}, this, 1, 2, 0); btnSettings.anchor.setTo(0.5, 0.5); btnSettings.tint = buttonTint; lblSettings = game.add.text(game.world.width / 2, (game.world.height / 2) + 60, getText("MainMenu", 2), buttonStyle); lblSettings.anchor.setTo(0.5, 0.5); btnLeaderboard = game.add.button(game.world.width / 2, (game.world.height / 2) + 120, 'big_button', function(){show('leaderboard')}, this, 1, 2, 0); btnLeaderboard.anchor.setTo(0.5, 0.5); btnLeaderboard.tint = buttonTint; lblLeaderboard = game.add.text(game.world.width / 2, (game.world.height / 2) + 120, getText("MainMenu", 3), buttonStyle); lblLeaderboard.anchor.setTo(0.5, 0.5); btnCredits = game.add.button(game.world.width / 2, (game.world.height / 2) + 180, 'big_button', function(){show('credits')}, this, 1, 2, 0); btnCredits.anchor.setTo(0.5, 0.5); btnCredits.tint = buttonTint; lblCredits = game.add.text(game.world.width / 2, (game.world.height / 2) + 180, getText("MainMenu", 4), buttonStyle); lblCredits.anchor.setTo(0.5, 0.5); createLanguageFlags(); }, start: function(){ game.state.start('singlePlayerPrep'); } };
//window.server = 'http://192.168.1.101:8080/MMS'; // window.server = 'http://192.168.43.244:9080/MMS'; // window.server='http://192.168.1.102:8080/MMS' // dist环境 // window.server="http://10.22.224.110:30011/MMS" window.xxx="china"
import React, { Component } from 'react'; import anime from 'animejs'; import './logo.scss'; const logoViewBox = '0 0 700 100'; const letterColors = { capitalT: '#6F146D', r: '#6F146D', e: '#6F146D', }; /** * A component to hold the animated logo for the website so that users can be * wowed as soon as they land. * Huge amounts of help/influence from Julian Garnier's anime js logo animation * @extends Component */ class Logo extends Component { static triggerAnimation() { console.log('ran'); const timeline = anime.timeline(); timeline.add({ targets: '.letter-cap-t', strokeDashoffset: [anime.setDashoffset, 0], duration: 2000, offset: 0, }); timeline.add({ targets: '.letter-r', strokeDashoffset: [anime.setDashoffset, 0], duration: 2000, offset: 250, }); timeline.add({ targets: '.letter-e', strokeDashoffset: [anime.setDashoffset, 0], duration: 2000, offset: 500, }); } render() { return ( <div className="logo-container"> <div className="letters"> <svg width="100%" height="100%" viewBox={logoViewBox}> <g fill="none" strokeWidth="15"> <path className="letter-cap-t" stroke={letterColors.capitalT} d="M0,20 H100 L50,20 V100" /> <path className="letter-r" stroke={letterColors.r} d="M100,100 V50 L100,60 Q125,40 145,60" /> <path className="letter-e" stroke={letterColors.e} d="M81 101h60V81c-1-33.14-26.86-60-60-60a60 60 0 1 0 0 120 h50" /> </g> </svg> </div> </div> ); } } export default Logo;
var Sceney = require('./index') var imageUrls = [ 'https://images.thetrumpet.com/51e9636a!h.300,id.9292,m.fill,w.540', 'https://c1.staticflickr.com/1/572/22607522004_1380a87e79_b.jpg' ]; var sceney = Sceney.init([process.env.CLARIFAI_CLIENT_ID, process.env.CLARIFAI_CLIENT_SECRET], function () { sceney.rateImage(imageUrls, function (ratings) { console.log(ratings); }); });
'use strict' const rand = require('../src/util.js') test('it should random array', () => { const array = ['666', '2', '123', '69'] expect(array).toContain(rand(array)) })
const mongoose = require('mongoose') mongoose.connection.on('open', () => console.log("db connected")) async function mongodbConn( host ){ try { await mongoose.connect( `${host}`, {useNewUrlParser: true, useUnifiedTopology: true} ) } catch( e ){ console.error(`Error in mongodbConn: ${e.message}`) } } module.exports = mongodbConn
var mongoose = require('mongoose'); var Schema = require('mongoose').Schema; var UserSchema = new Schema({ local: { username: {type : String, unique : true}, password: String }, info: { lastConnection: { type: Date, default: Date.now }, state: { type: String, enum: ['pending', 'active', 'baned', 'removed'], default: 'pending' } }, profile: { photo: String, creationDate: { type: Date, default: Date.now }, nickname: String }, updatedAt: { type: Date, default: Date.now }, rol: { type: String, enum: ['user', 'moderator', 'admin'], default: 'user' }, userGroups : [Schema.Types.ObjectId] }); UserSchema.pre('update', function() { this.update({},{ $set: { updatedAt: new Date() } }); }); module.exports = mongoose.model('User', UserSchema);
var port = process.env.PORT || 5000; var app = require('express')(); var server = require('http').Server(app); server.listen(port); app.get('/',function(req,res){ res.sendFile(__dirname + '/index.html'); }); // Chargement de socket.io var io = require('socket.io')(server); var connectedUsers = []; // Quand on client se connecte, on le note dans la console io.sockets.on('connection', function (socket) { socket.emit('connectedUsers',connectedUsers); socket.on('message',function(message){ socket.broadcast.emit('newMessage',message,socket.pseudo); }) socket.on('addUser',function(pseudo){ socket.pseudo = pseudo; socket.idUser = connectedUsers.length; connectedUsers.push(pseudo); socket.broadcast.emit('newUser',pseudo,connectedUsers); }); socket.on('geolocalisation',function(gmaps){ socket.broadcast.emit('addPosition',gmaps,socket.pseudo); }); socket.on('image',function(image){ socket.broadcast.emit('addImage',image,socket.pseudo); }); socket.on('disconnect', function() { connectedUsers.splice(socket.idUser,1); socket.broadcast.emit('removeUser',socket.pseudo,connectedUsers); }); });
#!/usr/bin/env node const path = require('path'); const childProcess = require('child_process'); try { childProcess.execFileSync( 'php', [path.join(__dirname, '../external/phpcs.phar'), ...process.argv.slice(2)], { stdio: 'inherit' } ); } catch (e) { process.exit(e.status); }
var redLetters = require('../assets/js/solve/redLetters.js') test('empty returns true', () => { expect(redLetters([])).toBeTruthy() }); test('finds right coordinate', () => { var coords = [0, 1, "5", "5"] expect(redLetters()).toBeTruthy() });
import React from 'react'; import { connect } from 'react-redux'; import { Redirect, Route } from 'react-router-dom'; const ProtectedRoute = ({ component: Component, ...protectedRouteProps }) => ( <Route {...protectedRouteProps} render={props => protectedRouteProps.isLogged ? <Component {...props} /> : <Redirect to="/auth/signin" /> } /> ); const mapStateToProps = ({ user }) => ({ isLogged: user.isLogged }); export default connect( mapStateToProps, null )(ProtectedRoute);
movieDBApp.controller('MovieListController', function MovieListController($scope, movieDataService, $log, $routeParams, $location) { $log.info($location); const params = { sort: $routeParams.sort || 'title', page: $routeParams.page || 0, size: $routeParams.size || 2, }; const onLoadingSuccessful = (res) => { $scope.movies = res; } const onLoadingFailure = (error) => { $scope.message = "Unable to load movies..."; } movieDataService.getMovies(params, onLoadingSuccessful, onLoadingFailure); $scope.prevPage = () => { $location.search({ page: $scope.movies.number - 1 }); }; $scope.nextPage = () => { $location.search({ page: $scope.movies.number + 1 }); }; $scope.selectMovie = (movieId) => { if (movieId) { $location.url(`/movies/${movieId}`); } }; });
'use strict' const helmet = require('helmet') const bodyParser = require('body-parser') const cors = require('cors') const expressDeliver = require('express-deliver') const customExceptions = requireRoot('services/customExceptions') const appManager = requireRoot('./appManager') const parameters = requireRoot('../parameters') module.exports = function (app) { expressDeliver(app, { exceptionPool: customExceptions, printErrorStack: parameters.expressDeliver.printErrorStack, printInternalErrorData: parameters.expressDeliver.printInternalErrorData }) // Disable express header app.set('x-powered-by', false) app.set('etag', false) // cors app.use(cors()) // Helmet security enabled app.use(helmet()) // Throw error if no db connection app.use(function (req, res, next) { if (!appManager.running) { throw new customExceptions.DatabaseError() } next() }) // Parses http body app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) // Check device app.use(function (req, res, next) { let device = req.get('X-device') if (!device) { throw new customExceptions.ValidationDeviceFailed() } req.device = device next() }) }
var dgram = require('dgram'); var http = require('http'); var sys = require('sys'); var fs = require('fs'); var url = require("url"); var path = require("path"); http.createServer(function(req, res) { //debugHeaders(req); if (req.headers.accept && req.headers.accept == 'text/event-stream') { if (req.url == '/events') { sendSSE(req, res); } else { res.writeHead(404); res.end(); } } else { var uri = url.parse(req.url).pathname, filename = path.join(process.cwd(), "public", uri); path.exists(filename, function(exists) { if(!exists) { res.writeHead(404, {"Content-Type": "text/plain"}); res.write("404 Not Found\n"); res.end(); return; } if (fs.statSync(filename).isDirectory()) filename += '/index.html'; fs.readFile(filename, "binary", function(err, file) { if(err) { res.writeHead(500, {"Content-Type": "text/plain"}); res.write(err + "\n"); res.end(); return; } res.writeHead(200); res.write(file, "binary"); res.end(); }); }); } }).listen(8000); function sendSSE(req, res) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); var server = dgram.createSocket("udp4"); server.on("error", function (err) { console.log("server error:\n" + err.stack); server.close(); }); var id = (new Date()).toLocaleTimeString(); server.on("message", function (msg, rinfo) { console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port); constructSSE(res, id, msg); }); server.bind(12345); var message = new Buffer("REGISTER_SPECTATOR;web_server"); server.send(message, 0, message.length, 9000, "localhost", function(err, bytes) { }); } function constructSSE(res, id, data) { res.write('id: ' + id + '\n'); res.write("data: " + data + '\n\n'); } function debugHeaders(req) { sys.puts('URL: ' + req.url); for (var key in req.headers) { sys.puts(key + ': ' + req.headers[key]); } sys.puts('\n\n'); }
define([ 'react', 'jquery','properties' ], function(React, $,properties) { var BootstrapButton = React.createClass({ render: function() { return ( <a {...this.props} href="javascript:;" role="button" className={(this.props.className || '')}> {this.props.data} </a> ); } }); var CreateFBComponent = React.createClass({ onChangeFunction: function(e) { this.setState({fbName: e.target.value}); }, getInitialState: function() { return {fbName: ""} }, keyPressFunction: function(event) { var keycode = (event.keyCode ? event.keyCode : event.which); if (keycode == '13') { this.handleConfirm(); } event.stopPropagation() }, handleCancel: function() { this.props.close(); if (this.props.onCancel) { this.props.onCancel(); } }, handleConfirm: function() { this.props.topologyModel.createNode(this.state.fbName, this.props.iconType, this.props.coordinates); console.log("iconType" + this.props.iconType) this.props.close(); properties.addNode(this.state.fbName,this.props.iconType) }, render: function() { return ( <div className={"modal-content "+this.props.className}> <div className="modal-header"> <button type="button" className="close" onClick={this.handleCancel}> &times;</button> <h3>{this.props.title}</h3> </div> <div className="modal-body"> <form id="add-node-form"> <div className="form-group"> <label for="fbname">Name:</label> <input onChange={this.onChangeFunction} onKeyDown={this.keyPressFunction} type="text" className="form-control" id="fb_name"></input> </div> </form> </div> <div className="modal-footer"> <div class="row"> <div class="col-md-12 section-divider-bottom"> <BootstrapButton onClick={this.handleConfirm} className="btn btn-sm btn-primary" data="Save"></BootstrapButton> <BootstrapButton onClick={this.handleCancel} className="btn btn-sm btn-default" data="Cancel"></BootstrapButton> </div> </div> </div> </div> ); } }); return CreateFBComponent; });
import React, { useState } from 'react'; import PropTypes from 'prop-types'; import { useFilmsContext } from '@/components/films-provider/films-provider'; import './list-item.scss'; const ListItem = ({ film }) => { const [statusClass, setStatusClass] = useState(''); const { checkAnswer } = useFilmsContext(); const clickHandler = () => { const status = checkAnswer(film, statusClass); setStatusClass((prev) => { if (!prev) { return status; } return prev; }); }; const { title } = film; return ( <button type="button" className="films_item" onClick={clickHandler}> <span className={`films_item_status ${statusClass}`} /> <div className="films_item_text">{title}</div> </button> ); }; ListItem.propTypes = { film: PropTypes.shape({ id: PropTypes.number, title: PropTypes.string, }).isRequired, }; export default ListItem;
import React, {Component} from 'react'; import { Table,Modal, Button,Input,Radio,message } from 'antd'; const Search = Input.Search; export default class Linknext extends Component{ constructor(props){ super(props) this.state={ dataSource:{}, // 列表数据 current:1 // 当前页数 } this.SupplyName=null; this.columns = [{ title: '供应商名称', dataIndex: 'COMPANY_NAME', key: 'COMPANY_NAME', }, { title: '主数据编码', dataIndex: 'MDM_CODE', key: 'MDM_CODE', }]; this.columns1 = [{ title: '物料品类', dataIndex: 'MAT_NAME', key: 'MAT_NAME', }, { title: '板块', dataIndex: 'USE_TYPE', key: 'USE_TYPE', }]; this.search = ''; this.SupplyName = null; } componentDidMount(){ this.handleSearchData() } //分页以及按查询条件查询数据 // url:`/txieasyui?taskFramePN=AlternativeSupplierDao&command=AlternativeSupplierDao.getAlternativeSupplierList&colname=json&colname1={"dataform":"eui_datagrid_data"}`, // data:{queryValue:this.search}, handleSearchData=()=>{ const that = this; let url = this.props.modalType=='material_category'?`/txieasyui?taskFramePN=CSupplierHandle&command=CSupplierHandle.getMaterialListBySupplier&colname=json_ajax&colname1={'dataform':'eui_datagrid_data','tablename':'detail0'}`:'/txieasyui?taskFramePN=supplierRectifyDao&command=supplierRectifyDao.initSupplierHandle&colname=json_ajax&colname1={%27dataform%27:%27eui_datagrid_data%27,%27tablename%27:%27detail0%27}'; let data = this.props.modalType=='material_category'?{queryParam:JSON.stringify({name:this.search,rows:10,page:this.state.current,id:this.props.id})}:{initparams:JSON.stringify({keywords:this.search,rows:10,page:this.state.current})}; ajax({ url:url, data:data, type:"GET", success:function(res){ if(res.EAF_ERROR) { message.error(res.EAF_ERROR); return; } that.setState({dataSource:res}); }, error:function(res){ message.error(res.EAF_ERROR) } }) } // 点击搜索查询数据 searchData = (value)=>{ this.search = value.replace(/\s/g,''); this.handleSearchData(); } // 点击行选中该供应商 clickLine = (record)=>{ this.SupplyName = JSON.parse(JSON.stringify(record)); this.props.showSupply(record); } // 分页查询数据 onChangePage = (page)=>{ console.log(page) this.setState({current:page},()=>{ this.handleSearchData('changepage'); }); } // 分页器初始化 handlePage = ()=>{ // const total = this.props.sellerData&&this.props.sellerData.total; return( { current:this.state.current, defaultCurrent:1, defaultPageSize:10, showQuickJumper:true, onChange: (pageNumber) => this.onChangePage(pageNumber), total:this.state.dataSource.total?Number(this.state.dataSource.total):0 } ) } handleCancel = ()=>{ this.props.showSupply(''); } render(){ let loading = this.state.dataSource; const title=()=>{ return( <div style={{height:30}}> <div style={{float:'left'}}>{this.props.modalType=='material_category'?'物料品类列表:':'供应商列表:'}</div> <div style={{float:'right'}}> <Search placeholder={this.props.modalType=='material_category'?'检索物料品类':'检索供应商名称或主数据编码'} onSearch={this.searchData} style={{ width: 300 }} maxLength={20} enterButton /> </div> </div> ) } console.log(this.state.dataSource) return( <div> <Modal title={title()} visible={this.props.visible} onOk={this.handleOk} onCancel={this.handleCancel} destroyOnClose = {true} footer={null} width={700} maskClosable = {true} wrapClassName='supplyName' > <Table dataSource={this.state.dataSource.rows} pagination={this.handlePage()} loading = {!loading} onRow={(record) => { return { onClick: ()=>this.clickLine(record), // 点击行 } } } columns={this.props.modalType=='material_category'?this.columns1:this.columns} /> </Modal> </div> ) } }
function judgeVegetable (vegetables, metric) { let currentWinnerIndex = 0; for (let veg in vegetables) { if (vegetables[veg][metric] > vegetables[currentWinnerIndex][metric]) { currentWinnerIndex = veg; } } return vegetables[currentWinnerIndex].submitter; } const vegetables = [ { submitter: 'Old Man Franklin', redness: 10, plumpness: 5 }, { submitter: 'Sally Tomato-Grower', redness: 2, plumpness: 8 }, { submitter: 'Hamid Hamidson', redness: 4, plumpness: 3 } ] const metric = 'plumpness' console.log(judgeVegetable(vegetables, metric));
'use strict' import React from 'react' import PropTypes from 'prop-types' import c from 'classnames' import ThePeerStyle from './ThePeerStyle' import { htmlAttributesFor, eventHandlersFor } from 'the-component-util' import { TheVideo } from 'the-video' import newPeer from './helpers/newPeer' import { get } from 'the-window' import asleep from 'asleep' import { TheCondition } from 'the-condition' import { textColorFor, colorWithText } from 'the-color' import { LABEL_HEIGHT, BASE_LABEL_COLOR, DEFAULT_BORDER_COLOR } from './helpers/constants' /** * Peer video chat component */ class ThePeerReceiver extends React.Component { constructor (props) { super(props) const s = this s.peer = null s.connection = null s.mounted = false s.videoElm = null s.state = { connecting: false } s.ready = false s.lost = false s._playRequesting = false s._retryTimer = -1 } render () { const s = this const {props, state} = s const { className, children, reloadable, style, width, height, labelBaseColor, label } = props const {connecting} = state const labelColor = label && colorWithText(label, {base: labelBaseColor}) const labelHeight = label ? LABEL_HEIGHT : 0 return ( <div {...htmlAttributesFor(props, {except: ['className', 'width', 'height']})} {...eventHandlersFor(props, {except: []})} className={c('the-peer-receiver', className)} style={Object.assign({borderColor: labelColor ? labelColor : DEFAULT_BORDER_COLOR}, style)} > {children} <TheVideo videoRef={(videoElm) => { s.videoElm = videoElm }} {...{width}} height={height - labelHeight} spinning={connecting} onClick={() => reloadable && s.reloadPeer()} /> <TheCondition if={!!label}> <div className='the-peer-label' style={{ height: labelHeight, color: labelColor && textColorFor(labelColor), backgroundColor: labelColor }} >{label}</div> </TheCondition> </div> ) } componentDidMount () { const s = this s.mounted = true const {props} = s ;(async () => { await s.preparePeer(props) s.forceUpdate() })().catch((err) => s.catchError(err)) s._retryTimer = setInterval(async () => { const {props} = s if (s.ready && s.lost) { console.log('Retry connection...') await s.reloadPeer() } }, 1000) } componentWillReceiveProps (nextProps) { const s = this const {props} = s ;(async () => { const shouldPreparePeer = ['peerId', 'peerOptions'].some((name) => nextProps[name] !== props[name]) if (shouldPreparePeer) { await s.preparePeer(nextProps) } })().catch((err) => s.catchError(err)) } componentDidUpdate () { const s = this const {videoElm} = s if (videoElm) { const needsPlay = videoElm.paused && !s._playRequesting if (needsPlay) { (async () => { await s.requestPlay() })() } } } componentWillUnmount () { const s = this s.destroyPeer() if (s.videoElm) { s.videoElm.pause() s.videoElm = null } s.mounted = false clearInterval(s._retryTimer) s._retryTimer = -1 } async preparePeer ({peerId, peerOptions}) { const s = this const {connection} = s if (connection) { const known = connection.peer === peerId if (known) { return false } connection.close() } if (peerId) { s.false = true if (!s.peer) { const URL = get('window.URL') s.peer = await newPeer(peerOptions) s.peer .on('call', (call) => { call.answer() call.on('stream', (stream) => { if (!s.mounted) { return } s.videoElm.srcObject = stream s.setState({connecting: false}) }) }) .on('disconnected', async () => { await asleep(100) const {peer} = s if (peer) { const needsReconnect = s.mounted && !peer.disconnected if (needsReconnect) { peer.reconnect() } } }) .on('error', (err) => s.catchError(err)) } await asleep(100) if (!s.peer) { s.lost = true s.ready = true return } s.connection = s.peer.connect(peerId) s.connection .on('open', () => { s.lost = false }) .on('close', () => { s.lost = true }) s.ready = true await s.requestPlay() } else { s.connection = null } return true } destroyPeer () { const s = this const {peer, connection, videoElm} = s connection && connection.close() peer && peer.destroy() s.peer = null s.connection = null videoElm && videoElm.pause() } async reloadPeer () { const s = this const {props} = s s.destroyPeer() await asleep(100) await s.preparePeer(props) } async requestPlay () { const s = this const {props, videoElm} = s if (!videoElm) { return } if (s._playRequesting) { return } if (!videoElm.paused) { return } const {volume} = props s._playRequesting = true try { await asleep(10) videoElm.volume = volume await videoElm.play() } finally { s._playRequesting = false } } catchError (err) { const s = this const {props} = s s.connection && s.connection.close() s.connection = null if (s.mounted) { s.setState({connecting: false}) } if (props.onError) { props.onError(err) } else { console.error(err) } } } ThePeerReceiver.Style = ThePeerStyle ThePeerReceiver.propTypes = { /** Id for peer */ peerId: PropTypes.string, /** Peer js options */ peerOptions: PropTypes.object, /** Volume */ volume: PropTypes.number, /** Component width */ width: PropTypes.number, /** Component height */ height: PropTypes.number, /** Reloadable on click */ reloadable: PropTypes.bool, /** Handler for error events */ onError: PropTypes.func, /** Label text */ label: PropTypes.string } ThePeerReceiver.defaultProps = { peerId: null, peerOptions: {}, volume: 0.9, width: 150, height: 150, reloadable: false, onError: null, labelBaseColor: BASE_LABEL_COLOR, label: null } ThePeerReceiver.displayName = 'ThePeerReceiver' export default ThePeerReceiver
import React from "react"; import { Link } from "react-router-dom"; export default ({ product }) => { return ( <div className="card"> <li> <div className="card-image"> <img src={require(`../assets/images/${product.image}`)} alt={product.title} /> </div> <div> <span className="card-title">{product.title}</span> <b>Price:</b> {product.price} </div> <div> <Link to={`/product/${product.id}`}>Details</Link> </div> </li> </div> ); };
import * as PUTbooks from '../requests/PUTBooks.request' import * as GETBooks from '../requests/GETBooks.request' import * as POSTBooks from '../requests/POSTBooks.request' describe('PUT Books', () => { it('Alterar o primeiro livro da lista', () => { GETBooks.allBooks().then((responseAllBooks) => { PUTbooks.updateBook(responseAllBooks.body[0].id).should((responseUpdateBook) => { expect(responseUpdateBook.status).to.eq(200); expect(responseUpdateBook.body).to.be.not.null; expect(responseUpdateBook.body.title).to.eq('Livro Alteraddo'); }) }) }); it('Criar e alterar um livro', () => { POSTBooks.addBook().then((responseAddBooks) => { PUTbooks.updateBook(responseAddBooks.body.id).should((responseUpdateBook) => { expect(responseUpdateBook.status).to.eq(200); expect(responseUpdateBook.body).to.be.not.null; expect(responseUpdateBook.body.title).to.eq('Livro Alteraddo'); }) }) }); });
var single=require("./somethingSingle"); single.hello(); single.hello(); single.hello(); single.hello(); var single1=require("./somethingSingle"); single1.hello(); single1.hello(); single1.hello(); single1.hello(); console.log(single===single1);//true //这里single1和single是同一个对象 module.exports=single;
import React from 'react'; const SkillComponent = (props)=>{ return( <div className='skill-component'> <h1>{props.skill}</h1> <div className='skill-loader'> <div></div> <div></div> </div> </div> ) } export default SkillComponent;
var characterService = require('./../services/character'); module.exports.lookupCharactersByName = function (query, limit, req, res, next) { characterService.lookupCharactersByName(query, limit, function (error, response) { if (error) { return res.json(new Error('Could not looking characters')); } res.json(response); }); }; module.exports.getCharacterById = function (characterId, req, res, next) { characterService.getCharacterById(characterId, function (error, response) { if (error) { return res.json(new Error('Could not retrieve character')); } res.json(response); }); }; module.exports.getCharacterFullById = function (characterId, req, res, next) { characterService.getCharacterFullById(characterId, function (error, response) { if (error) { return res.json(new Error('Could not retrieve character')); } res.json(response); }); }; module.exports.updateCharacterById = function (characterId, lastLoginDate, req, res, next) { characterService.updateCharacterById(characterId, lastLoginDate, function (error, response) { if (error) { return res.json(new Error('Could not update character')); } res.json(response); }); }; module.exports.findCharacters = function (characterIds, req, res, next) { characterService.findCharacters(characterIds, function (error, response) { if (error) { return res.json(new Error('Could not retrieve characters')); } res.json(response); }); }; module.exports.getCharactersOutfit = function (characterId, req, res, next) { characterService.getCharactersOutfit(characterId, function (error, response) { if (error) { return res.json(new Error('Could not retrieve characters outfit')); } res.json(response); }); };
import * as userReducer from '../../reducers/users-reducer'; describe('users reducer', () => { it('should return our initial state', () => { const expectation = {}; expect(userReducer.activeUser(undefined, {})).toEqual(expectation); }); it('should allow me to add active user to state', () => { const action = { type: 'LOGIN_USER', user: { email: 'gizmo_da_corgi@doggos.com', password: 'stumper4lyfe' } }; const expectation = action.user; expect(userReducer.activeUser(undefined, action)).toEqual(expectation); }); it('should allow me to log a user out', () => { const action = { type: 'SIGN_OUT_USER', user: {} }; const expectation = {}; expect(userReducer.activeUser(undefined, action)).toEqual(expectation); }); it('should fire an error when login does not function properly', () => { const action = { type: 'LOGIN_ERROR', loginError: true }; const expectation = true; expect(userReducer.userLoginError(undefined, action)).toEqual(expectation); }); it('should reset login status', () => { const action = { type: 'LOGIN_RESET', loginError: false }; const expectation = false; expect(userReducer.userLoginError(undefined, action)).toEqual(expectation); }); });
// FINCAD // React Assignment - Janurary 28, 2017 // Chedwick Montoril // License MIT // React-* dependencies. import React from 'react'; // Internal dependencies. import PostCard from './PostCard.component'; /** * Post List component. */ class PostList extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { if (this.props.posts[0].id === null) { return null; } const postCards = this.props.posts.map( post => ( <PostCard key={`post-idx-${post.id}`} post={post} /> ) ); return ( <div> {postCards} </div> ); } } export default PostList;
$(document).ready(function () { var leftBtn = $('#char-carousel').find('.left-arrow-wrapper'); var rightBtn = $('#char-carousel').find('.right-arrow-wrapper'); var gauls = $('.info-text .gauls'); var romans = $('.info-text .romans'); var teutons = $('.info-text .teutons'); var showDescription = function(){ if($('#char-foreground .char').hasClass("gaul")){ $('.info-text .info-wrap').hide(); $('.info-text .info-more').hide(); gauls.first().show(); } else if($('#char-foreground .char').hasClass("roman")){ $('.info-text .info-wrap').hide(); $('.info-text .info-more').hide(); romans.first().show() } else { $('.info-text .info-wrap').hide(); $('.info-text .info-more').hide(); teutons.first().show(); } }; showDescription(); $('#arrows').on('click', function () { $('.info-text').toggleClass("active"); if($('#char-foreground .char').hasClass("gaul")){ if($('.info-text').hasClass("active")){ gauls.first().hide(); gauls.last().show(); } else { gauls.first().show(); gauls.last().hide(); } } else if($('#char-foreground .char').hasClass("roman")){ if($('.info-text').hasClass("active")){ romans.first().hide(); romans.last().show(); } else { romans.first().show(); romans.last().hide(); } } else { if($('.info-text').hasClass("active")){ teutons.first().hide(); teutons.last().show(); } else { teutons.first().show(); teutons.last().hide(); } } }); rightBtn.on('click', function(){ var foreChar = $('#char-foreground .char').remove(); var backChar = $('#char-background .char').last().remove(); if($('.info-text').hasClass("active")){ $('.info-text').toggleClass("active") } $('#char-background').prepend(foreChar); $('#char-foreground').append(backChar); showDescription(); }); leftBtn.on('click', function(){ var foreChar = $('#char-foreground .char').remove(); var backChar = $('#char-background .char').first().remove(); if($('.info-text').hasClass("active")){ $('.info-text').toggleClass("active") } $('#char-background').append(foreChar); $('#char-foreground').append(backChar); showDescription(); }); });
const Discord = require('discord.js') const config = require('../config.json') const storage = require('../util/storage.js') const currentGuilds = storage.currentGuilds const overriddenGuilds = storage.overriddenGuilds const failedLinks = storage.failedLinks const pageControls = require('../util/pageControls.js') module.exports = function (bot, message, command) { const guildRss = currentGuilds.get(message.guild.id) if (!guildRss || !guildRss.sources || guildRss.sources.size() === 0) return message.channel.send('There are no existing feeds.').catch(err => console.log(`Promise Warning: chooseFeed 2: ${err}`)) const rssList = guildRss.sources const failLimit = (config.feedSettings.failLimit && !isNaN(parseInt(config.feedSettings.failLimit, 10))) ? parseInt(config.feedSettings.failLimit, 10) : 0 let failedFeedCount = 0 function getFeedStatus (link) { const failCount = failedLinks[link] if (!failCount || (typeof failCount === 'number' && failCount <= failLimit)) return `Status: OK ${failCount > Math.ceil(failLimit / 5) ? '(' + failCount + '/' + failLimit + ')' : ''}\n` else { failedFeedCount++ return 'Status: FAILED\n' } } const maxFeedsAllowed = overriddenGuilds[message.guild.id] != null ? overriddenGuilds[message.guild.id] === 0 ? 'Unlimited' : overriddenGuilds[message.guild.id] : (!config.feedSettings.maxFeeds || isNaN(parseInt(config.feedSettings.maxFeeds))) ? 'Unlimited' : config.feedSettings.maxFeeds let embedMsg = new Discord.RichEmbed().setColor(config.botSettings.menuColor) .setAuthor('Current Active Feeds') .setDescription(`**Server Limit:** ${rssList.size()}/${maxFeedsAllowed}\u200b\n\u200b\n`) // Generate the info for each feed as an array, and push into another array const currentRSSList = [] for (var rssName in rssList) { const feed = rssList[rssName] let o = { link: feed.link, title: feed.title, webhook: feed.webhook ? feed.webhook.id : undefined, channel: bot.channels.get(feed.channel) ? bot.channels.get(feed.channel).name : undefined, titleChecks: feed.titleChecks === true ? 'Title Checks: Enabled\n' : null } if (failLimit !== 0) o.status = getFeedStatus(feed.link) currentRSSList.push(o) } if (failedFeedCount) embedMsg.description += `**Attention!** Feeds that have reached ${failLimit} connection failure limit have been detected. They will no longer be retried until the bot instance is restarted. Please either remove, or use *${config.botSettings.prefix}rssrefresh* to try to reset its status.\u200b\n\u200b\n` const pages = [] for (var x in currentRSSList) { const count = parseInt(x, 10) + 1 const link = currentRSSList[x].link const title = currentRSSList[x].title const channelName = currentRSSList[x].channel const status = currentRSSList[x].status const titleChecks = currentRSSList[x].titleChecks const webhook = currentRSSList[x].webhook // 7 feeds per embed if ((count - 1) !== 0 && (count - 1) / 7 % 1 === 0) { pages.push(embedMsg) embedMsg = new Discord.RichEmbed().setColor(config.botSettings.menuColor).setDescription(`Page ${pages.length + 1}\n\u200b`) } embedMsg.addField(`${count}) ${title.length > 200 ? title.slice(0, 200) + '[...]' : title}`, `${titleChecks || ''}${status || ''}Channel: #${channelName}\n${webhook ? 'Webhook: ' + webhook + '\n' : ''}Link: ${link}`) } // Push the leftover results into the last embed pages.push(embedMsg) message.channel.send({embed: pages[0]}) .then(m => { if (pages.length === 1) return m.react('◀') .then(rct => m.react('▶').catch(err => console.log(`yep2`, err))) .catch(err => console.log(`yep`, err)) pageControls.add(m.id, pages) }) .catch(err => console.log(`Message Error: (${message.guild.id}, ${message.guild.name}) => Could not send message of embed feed list. Reason: ${err}`)) }
import { dateFormat } from "../../helpers/dateformat"; const Post = ({ title, date, content }) => { return ( <main className="post individual"> <h1>{title}</h1> <small className="date">{dateFormat(date)}</small> <section dangerouslySetInnerHTML={{ __html: content }}></section> <style jsx>{` main.post { margin: 60px auto 50px; max-width: 800px; padding: 0 30px 70px; } h1 { color: black; font-size: 40px; } section { color: #444; } .date { text-align: center; } `}</style> </main> ); }; Post.getInitialProps = async ctx => ctx.query; export default Post;
function runTest() { FBTest.openNewTab(basePath + "search/6454/issue6454.html", function() { FBTest.openFirebug(function() { FBTest.selectPanel("html"); var tasks = new FBTest.TaskList(); tasks.push(searchTest, "testing", false, 14); tasks.push(searchTest, "testing", true, 7); tasks.push(searchTest, "Testing", false, 8); tasks.push(searchTest, "#test div", false, 5); tasks.push(searchTest, "/html/body", true, 4); tasks.run(function() { FBTest.testDone(); }); }); }); } function searchTest(callback, text, caseSensitive, expectedMatches) { executeSearchTest(text, false, caseSensitive, function(counter) { FBTest.compare(expectedMatches, counter, "There must be " + expectedMatches + " matches when searching for \"" + text + "\""); callback(); }); } // xxxHonza: could be shared FBTest API // Execute one test. function executeSearchTest(text, reverse, caseSensitive, callback) { var counter = 0; var firstMatch = null; function searchNext() { var panel = FBTest.getPanel("html"); var sel = panel.document.defaultView.getSelection(); if (sel.rangeCount != 1) { FBTest.compare(1, sel.rangeCount, "There must be one range selected."); return callback(counter); } var match = sel.getRangeAt(0); // OK, we have found the first occurence again, so finish the test. FBTest.sysout("search.match; ", match); if (firstMatch && (firstMatch.compareBoundaryPoints(Range.START_TO_START, match) || firstMatch.compareBoundaryPoints(Range.END_TO_END, match)) == 0) return callback(counter); // Remember the first match. if (!firstMatch) { firstMatch = match; FBTest.sysout("search.firstMatch; ", firstMatch); } counter++; doSearch(text, reverse, caseSensitive, callback); setTimeout(searchNext, 300); }; doSearch(text, reverse, caseSensitive, callback); setTimeout(searchNext, 300); } // Set search box value and global search options. function doSearch(text, reverse, caseSensitive, callback) { FW.Firebug.chrome.$("fbSearchBox").value = text; FBTest.setPref("searchCaseSensitive", caseSensitive); // Press enter key within the search box. FBTest.focus(FW.Firebug.chrome.$("fbSearchBox")); FBTest.sendKey("RETURN", "fbSearchBox"); }
import { useEffect, useState } from "react"; import { useQuery, useSubscription } from '@apollo/react-hooks'; import { GET_SEASON } from '../../graphql'; import LoadScreen from "../LoadScreen/LoadScreen"; import { getUniqueRandoms } from "./GameLogic"; import PickCard from './PickCard/PickCard'; import './Game.css'; import { navigate } from "hookrouter"; const Game = (props) => { const { loading, error, data } = useQuery(GET_SEASON, { variables: { year: props.chosenSeason } }); const [allAnswered, setAllAnswered] = useState(false); useEffect(() => { console.log(allAnswered); }, [allAnswered]); useEffect(() => { if(data && props.newGame) { props.setEvents(data.season.events); props.setNewGame(!props.newGame); } }, [data]); useEffect(() => { if(props.events) { let picks = getUniqueRandoms(props.events, 4); props.setRandomPicks(picks); } }, [props.events]); useEffect(() => { if(props.events) { for(let x in props.picks) { if(!props.picks[x]) { return; } } setAllAnswered(true); // if(props.events.length >= 4) { // } else { // props.events.map((val, ind) => { // if(!props.picks[ind]) { // return; // } // }) // setAllAnswered(true); // } } }, [props.picks, props.events]); if(!props.randomPicks) return <LoadScreen /> else { return ( <div className='container-fluid'> <div className='row justify-content-around justify-content-center align-items-center pt-4 pick-card-row'> <div className='col-md-8'> <div className='row'> {props.randomPicks.map((val, ind) => { return <PickCard pickQuestion={val.strEvent} choiceA={val.strHomeTeam} choiceB={val.strAwayTeam} date={val.dateEvent} setPicks={props.setPicks} picks={props.picks} ind={ind}/> })} </div> </div> <button type='button' className={`btn-dark text-light submit-button ${allAnswered ? 'fixed-bottom d-flex justify-content-center align-items-center' : 'd-none'}`} onClick={() => navigate('/results')}>SUBMIT</button> </div> </div> ) } } export default Game;
import React, { Component } from 'react'; import Container from 'react-bootstrap/Container' import Form from 'react-bootstrap/Form' import Button from 'react-bootstrap/Button' class CreateBooking extends Component { // TODO // Fetch rooms and populate form fields with Names and IDs. constructor(props) { super(props); this.state = { bookingName: '' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { console.log(event.target.value); this.setState({bookingName: event.target.value}); } handleSubmit(event) { console.log("submitting"); event.preventDefault(); } render() { return ( <Container> <Form onSubmit={this.handleSubmit}> <Form.Group controlId="bookingForm.name"> <Form.Label>Booking Name</Form.Label> <Form.Control type="text" value={this.state.bookingName} onChange={this.handleChange} /> </Form.Group> <Form.Group controlId="exampleForm.ControlSelect1"> <Form.Label>Rooms</Form.Label> <Form.Control as="select"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </Form.Control> </Form.Group> <Form.Group controlId="exampleForm.ControlSelect2"> <Form.Label>Example multiple select</Form.Label> <Form.Control as="select" multiple> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </Form.Control> </Form.Group> <Form.Group controlId="exampleForm.ControlTextarea1"> <Form.Label>Example textarea</Form.Label> <Form.Control as="textarea" rows="3" /> </Form.Group> <Button as="input" type="submit" value="Submit" /> </Form> </Container> ); } } export default CreateBooking;
const jwt = require("jsonwebtoken"); const User = require("../models/User"); const key = process.env.SECRET; module.exports.createToken = ({ _id, email }) => jwt.sign({ id: _id, email }, key); module.exports.authCheck = (req, res, next) => { const { authorization } = req.headers; if (!authorization) return res.status(400).json({ message: "no token found" }); const tokenArr = authorization.split(" "); let token; if (tokenArr.length === 2) { token = tokenArr[1]; } else { return res.status(400).json({ message: "Your token is invalid" }); } jwt.verify(token, key, async (err, decodedToken) => { if (err) { return res.status(401).json({ message: "Invalid auth" }); } const { id } = decodedToken; const user = await User.findOne({ _id: id }); if (!user) return res.status(401).json({ message: "No user found :(" }); return next(); }); };
$(document ).ready(function() { var basepath = $("#basepath").val(); /* On change project change servier*/ $(document).on("change", "#project", function() { getTipper(basepath); }); $('#syncReportBtn').on('click',function(e){ e.preventDefault(); if (validate()) { $('#loader').show(); var formDataserialize = $("#syncReport").serialize(); var urlpath = basepath + 'syncreport/tipperWiseSyncreport'; $.ajax({ type: "POST", url: urlpath, data:formDataserialize, dataType: "html", success: function(result) { $('#loader').hide(); $("#sqncreportView").html(result); }, error: function(jqXHR, exception) { var msg = ''; if (jqXHR.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (jqXHR.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { msg = 'Time out error.'; } else if (exception === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\n' + jqXHR.responseText; } // alert(msg); } }); } }); $(document).on('click','#downloadxls',function(){ $('#SyncReportData').tableExport({type:'excel',escape:'false'}); }); });// end of document ready function getTipper(basepath){ var project=$('select[name=project]').val(); $.ajax({ type: "POST", url: basepath+'syncreport/getTipperByProject', data: {project:project}, success: function(data){ $("#tipper_dropdown").html(data); $('.selectpicker').selectpicker(); }, error: function (jqXHR, exception) { var msg = ''; if (jqXHR.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (jqXHR.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { msg = 'Time out error.'; } else if (exception === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\n' + jqXHR.responseText; } // alert(msg); } });/*end ajax call*/ } function validate() { $("#error_msg").text("").css("dispaly", "none").removeClass("form_error"); var projectid=$('#project').val(); if(projectid=='0') { $("#project").focus(); $("#error_msg") .text("Error : Select project") .addClass("form_error") .css("display", "block"); return false; } return true; }
class Event { constructor(sender) { this._sender = sender this._listeners = [] } attach (callback) { this._listeners.push(callback) } notify (args) { this._listeners.forEach( data => { data(this._sender,args) }) } } export default Event
import axios from 'axios' export default axios.create({ baseURL: 'https://watchtrade-api.herokuapp.com', // timeout: 1000, headers: { 'Content-Type' : 'application/x-www-form-urlencoded', 'Authorization' : 'Bearer '+localStorage.getItem("accessToken") } });
import {showContent} from './service/showContent'; import {addActiveClass} from './service/addActiveClass'; const showTabs = (elementSelectorCSS, tabsElemCSS) => { const tabs = document.querySelector(elementSelectorCSS); const tabElements = document.querySelectorAll(tabsElemCSS) showContent('.tabcontent', 'show',0); addActiveClass('.tabheader__item', 'tabheader__item_active', 0 ); tabs.addEventListener('click', (event) =>{ const target = event.target; if (!target.matches('.tabheader__item')) return; tabElements.forEach((item, index)=>{ if(target != item) return; showContent('.tabcontent', 'show',index); addActiveClass('.tabheader__item', 'tabheader__item_active', index ); }) }) }; // showTabs('.tabheader__items'); export {showTabs};
module.exports = { builder: new (require('./command-builder'))(), Runner: require('./runner') };
import * as React from 'react'; import DashboardIcon from '@material-ui/icons/Dashboard'; import AssignmentIcon from '@material-ui/icons/Assignment'; import StorageIcon from '@material-ui/icons/Storage'; import PeopleIcon from '@material-ui/icons/People'; import NotificationsIcon from '@material-ui/icons/Notifications'; import SettingsIcon from '@material-ui/icons/Settings'; export const sideMenuItems = [ { text: "Kanban Board", actionKey : 'kanban-board', id : 1, iconType : <DashboardIcon /> }, { text: "Tasks", actionKey : 'tasks', id : 2, iconType : <AssignmentIcon /> }, { text: "Documents", actionKey : 'documents', id : 3, iconType : <StorageIcon /> }, { text: "Team", actionKey : 'team', id : 4, iconType : <PeopleIcon /> }, { text: "Activities", actionKey : 'activities', id : 5, iconType : <NotificationsIcon /> }, { text: "Customize", actionKey : 'customize', id : 6, iconType : <SettingsIcon /> } ];
const Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('LoginAsCustomer', { secret: { type: DataTypes.STRING(64), allowNull: false, primaryKey: true, comment: "Login Secret" }, customer_id: { type: DataTypes.INTEGER, allowNull: false, comment: "Customer ID" }, admin_id: { type: DataTypes.INTEGER, allowNull: false, comment: "Admin ID" }, created_at: { type: DataTypes.DATE, allowNull: true, comment: "Creation Time" } }, { sequelize, tableName: 'login_as_customer', timestamps: false, indexes: [ { name: "PRIMARY", unique: true, using: "BTREE", fields: [ { name: "secret" }, ] }, { name: "LOGIN_AS_CUSTOMER_CREATED_AT", using: "BTREE", fields: [ { name: "created_at" }, ] }, ] }); };
/** * Created by Drew on 1/10/2015. */ var fs = require('fs'), path = require('path'), Plates = require('plates'), React = require('react'); var STATIC_BASE_HTML; fs.readFile( path.join(__dirname, '../', 'public', 'base.html'), { encoding: 'utf-8'}, function(err, template) { STATIC_BASE_HTML = template; } ); function renderHtml(res, appHtml, userData) { var html = Plates.bind( STATIC_BASE_HTML, { "APP": appHtml, "USER_DATA": 'USER_DATA = ' + JSON.stringify(userData) } ); res.set('Content-Type', 'text/html'); res.send(html); } module.exports = function (req, res, next) { console.log('!appRender: ' + req.originalUrl); /* Isomorphic server render... Not working well with authentication var html = React.renderToString( require('../app/roots/app')(req.originalUrl) );*/ var username = ''; if (req.user) { username = req.user.username; } var html = ''; renderHtml( res, html, { auth: req.isAuthenticated(), username: username } ) };
const express = require('express'); const router = express.Router(); const connection = require('../config/connectDB'); // DB 연결 및 쿼리작성 변수 /** * @swagger * tags: * name: scanKitchen * description: 사용자 위치 반경내의 급식소 검색 * definitions: * scanResults: * type: object * properties: * id: * type: integer * description: primary key * fcltyNm: * type: string * description: 급식소 이름 * rdnmadr: * type: string * description: 급식소 도로명주소 * phoneNumber: * type: string * description: 급식소 전화번호 * latitude: * type: number * format: double * description: 급식소 위도 * longitude: * type: number * format: double * description: 급식소 경도 * scanResult: * type: number * format: double * description: 사용자 위치로부터 급식소까지의 거리 */ /** * @swagger * /scankitchen: * post: * tags: [scanKitchen] * parameters: * - name: requestBody * in: body * description: 반경 내 급식소 검색에 필요한 요청 내용 * required: true * schema: * type: object * properties: * latitude: * type: number * format: double * description: 사용자의 위치 위도 값 * longitude: * type: number * format: double * description: 사용자의 위치 경도 값 * distance: * type: integer * description: 검색하고자 하는 반경 값 * responses: * 200: * description: 검색 성공 * schema: * $ref: '#/definitions/scanResults' * 400: * description: 요청 값이 올바르지 않음 * schema: * type: object * properties: * error: * type: object * properties: * code: * type: integer * example: 400 * description: 상태 코드 * contents: * type: string * example: Incorrect ??? * description: 에러 내용 * 404: * description: 검색된 급식소가 없음 * schema: * type: object * properties: * error: * type: object * properties: * code: * type: integer * example: 404 * description: 상태 코드 * contents: * type: string * example: No result found * description: 에러 내용 */ router.post('/', async (req, res) => { // console.log(req.body); res.send(req.body) const lat = parseFloat(req.body.latitude); // 사용자 위치 위도 const lot = parseFloat(req.body.longitude); // 사용자 위치 경도 const distance = Math.abs(parseInt(req.body.distance, 10)); // 검색 반경 거리 // console.log('scanKitchen : ', lat, lot, distance); if (!lat) { const resultJson = { "error": { "code": 400, "contents": "Incorrect latitude" } }; return res .status(400) .json(resultJson); } else if (!lot) { const resultJson = { "error": { "code": 400, "contents": "Incorrect longitude" } }; return res .status(400) .json(resultJson); } else if (!distance) { const resultJson = { "error": { "code": 400, "contents": "Incorrect distance" } }; return res .status(400) .json(resultJson); } // 각각의 요청 값이 없을 경우 400 에러 코드 및 관련 메시지를 응답 전송 let result = await(await connection).query( 'SELECT fcltyNm,rdnmadr,phoneNumber,latitude,longitude,(6371 * acos(cos(radians(?)) * cos(radians(latitude)) * cos(radians(l' + 'ongitude) - radians(?)) + sin(radians(?)) * sin(radians(latitude)))) AS scanRe' + 'sult FROM kitchen_table HAVING scanResult <= ? ORDER BY scanResult', [ lat, lot, lat, distance ], // 하버사인 공식을 통한 반경 내 급식소만을 조회 (err, results) => { if (err) { console.log('scanKitchen, Select query is now error by : ', err); throw err; // select 처리 실패 시 에러 전송 } console.log('Scan kitchen : ', results); } ); // console.log(result[0]); if (result[0].length == 0) { const resultJson = { "error": { "code": 404, "contents": "No result found" } }; return res .status(404) .json(resultJson); // 검색된 급식소가 없을 시 404 에러 코드 응답 전송 } const resultJson = { "header": { "resultCode": 201, "type": "json", "totalCount": result[0].length }, "body": { "items": result[0] } }; res .status(201) .json(resultJson); // 검색 성공 시 201 성공 코드 및 결과 값을 응답으로 전송 }); module.exports = router;
import create from '../src/js/utils/create.js'; describe('create method', () => { test('should create div element by default', () => { const config = {}; const expected = '<div></div>'; const result = create(config); expect(result).toMatchSnapshot(expected); }); test('should create specified type of element', () => { const config = { tagName: 'span', }; const expected = '<span></span>'; const result = create(config); expect(result).toMatchSnapshot(expected); }); test('should create element with specified css class', () => { const config = { classNames: 'class1', }; const expected = '<div class="class1"></div>'; const result = create(config); expect(result).toMatchSnapshot(expected); }); test('should create element with more than one css class', () => { const config = { classNames: 'class1 class2', }; const expected = '<div class="class1 class2"></div>'; const result = create(config); expect(result).toMatchSnapshot(expected); }); test('should create element with custom attributes', () => { const config = { attributes: ['id', 'id1'], }; const expected = '<div id="id1"></div>'; const result = create(config); expect(result).toMatchSnapshot(expected); }); test('should create element with child', () => { const config = { child: 'test' }; const expected = '<div>test</div>'; const result = create(config); expect(result).toMatchSnapshot(expected); }); test('should create children', () => { const config = { child: [ create({ child: '1' }), create({ child: '2' }), ], }; const expected = '<div><div>1</div><div>2</div></div>'; const result = create(config); expect(result).toMatchSnapshot(expected); }); });
var barsetNumber; try { $("#btnOpen").click(function (e) { // RULE: All Input validations must be met. var Form = document.getElementById("frmBarset"); if (Form.checkValidity()) { e.preventDefault(); ShowConfirmation(); } }); $("#btnConfirmBarsetNumber").click(function (e) { // *** Open the Barset *** bl.OpenBarset(barsetNumber); }); } catch (err) { ex.Log(err, "barset.open.Init()"); } function ShowConfirmation() { try { barsetNumber = $("#BarsetNumber").val(); // *** Get User Confirmation *** $("#spanBarsetNumber").html(barsetNumber); $("h3.ui-title span").html(barsetNumber); $("#popupDialog").popup("open"); } catch (err) { ex.Log(err, "catering.ShowConfirmation()"); } }
// NAVBAR ButterCake.plugin('navbar', function () { var $toggler = $('.navbar .toggler'); // NAVBAR RESPONSIVE BREAKING POINTS // $('.navbar').each(function () { if ($(this).hasClass('expand-sm')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.sm); } else if ($(this).hasClass('expand-md')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.md); } else if ($(this).hasClass('expand-lg')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.lg); } else if ($(this).hasClass('expand-xl')) { $(this).attr('data-toggle', ButterCake.settings.breakPoints.xl); } else if ($(this).hasClass('expanded')) { $(this).attr('data-toggle', 'null'); } else { $(this).attr('data-toggle', 'none'); } sideBar(); $(this).find('.container').append('<div class="shadow-fixed"></div>'); $(this).find('.container-fluid').append('<div class="shadow-fixed"></div>'); }); // SIDEBAR function sideBar() { var $width = $(window).width() + 15; $('.navbar').each(function () { var $toggleWidth = $(this).attr('data-toggle'); if ($toggleWidth !== undefined) { if ($toggleWidth !== 'null' || $toggleWidth === 'none') { if ($width >= $toggleWidth) { $(this).find('.menu-box').removeClass('sideNavbar toggled'); } else { $(this).find('.menu-box').addClass('sideNavbar'); } } } }); } // ON RESIZE $(window).on('resize', function () { sideBar(); }); // TOGGLER CLICK $toggler.on('click', function () { var $id = $(this).attr('data-nav'); ButterCake.settings.body.toggleClass('noScroll'); $($id).toggleClass('toggled'); }); // MENU CLOSE $('.menu-close').on('click', function () { ButterCake.settings.body.removeClass('noScroll'); $('.navbar .menu-box').removeClass('toggled'); }); // SHADOW CLICK $('.navbar .shadow-fixed').click(function (e) { $(this).parents('.navbar').find('.toggled').removeClass('toggled'); ButterCake.settings.body.removeClass('noScroll'); }); }, true);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _pluginBase = _interopRequireDefault(require("../core/plugin-base")); var _index = require("../utils/index"); var _index2 = _interopRequireDefault(require("../index")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } // function toMap(arr = []) { // return arr.reduce((obj, item) => { // obj[item] = true; // return obj; // }, {}) // } /** * 小程序业务渠道&参数处理(如果扩展可以支持业务之外的参数处理) * 支持业务参数配置 spm channel_id 等,可新增 * 支持参数的 parse stringify merge 操作 * * @class Plugin * @extends {PluginBase} */ var Plugin = /*#__PURE__*/ function (_PluginBase) { _inherits(Plugin, _PluginBase); function Plugin() { var _this; var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Plugin); _this = _possibleConstructorReturn(this, _getPrototypeOf(Plugin).call(this, config)); _defineProperty(_assertThisInitialized(_this), "name", 'route'); _defineProperty(_assertThisInitialized(_this), "events", {}); _defineProperty(_assertThisInitialized(_this), "methods", { getPages: 'getPages' // setChannel: 'setChannel', // getChannelFilter: 'getChannelFilter', }); _this.initPages(config.appConfig); return _this; } _createClass(Plugin, [{ key: "pagesMap", value: function pagesMap() { var pageArr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; return pageArr.reduce(function (obj, item) { var page = item.split('/').reverse()[0] || ''; /* eslint no-param-reassign: 0 */ obj[page] = "".concat(item); return obj; }, {}); } }, { key: "pagesObj", value: function pagesObj(allPages, tabPages) { return { allPages: this.pagesMap(allPages), tabPages: this.pagesMap(tabPages), defaultPage: allPages[0] && allPages[0].split('/').reverse()[0] || '' }; } }, { key: "getPages", value: function getPages() { return { allPages: _objectSpread({}, this.pages.allPages), tabPages: _objectSpread({}, this.pages.tabPages), default: this.pages.defaultPage }; } // const appConfig = typeof __wxConfig !== 'undefined' ? __wxConfig : require('/app.json'); }, { key: "initPages", value: function initPages() { var appConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _appConfig$pages = appConfig.pages, pages = _appConfig$pages === void 0 ? [] : _appConfig$pages, _appConfig$tabBar = appConfig.tabBar, tabBar = _appConfig$tabBar === void 0 ? {} : _appConfig$tabBar; var tabBarList = tabBar.items || tabBar.list || []; var tabPages = tabBarList.map(function (item) { return item.pagePath; }); this.pages = this.pagesObj(pages, tabPages); return this.pages; } }, { key: "urlParse", value: function urlParse() { var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var query = _objectSpread({}, params); var urlArr = url ? url.split('?') : []; var pageName = urlArr[0]; if (!pageName) return; var _this$getPages = this.getPages(), allPages = _this$getPages.allPages, tabPages = _this$getPages.tabPages; var pagePath; var urlType = ''; if (/^miniapp/.test(url)) { urlType = 'miniapp'; pagePath = pageName.replace('miniapp://', ''); } pagePath = allPages[pageName]; query = !urlArr[1] ? (0, _index.stringify)(query) : [(0, _index.stringify)(query), urlArr[1]].join('&'); if (!pagePath) { if (url === '/') { pagePath = ''; } } query = query ? "?".concat(query) : ''; return { isTabPage: !!tabPages[pageName], urlType: urlType, pageName: pageName, pageQuery: query, pagePath: "".concat(pagePath), pageUrl: "".concat(pagePath).concat(query) }; } }, { key: "goPage", value: function goPage(url) { var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (!url) return; var me = _index2.default.me; var replace = query.replace, back = query.back, appid = query.appid; // TODO: deal channel var page = url; var type = ''; var _ref = this.urlParse(url, query) || {}, pagePath = _ref.pagePath, pageUrl = _ref.pageUrl, isTabPage = _ref.isTabPage; type = replace ? 'replace' : back ? 'back' : ''; if (/^miniapp/.test(url)) { var urlArr = url ? url.split('?') : []; url = urlArr[0].replace('miniapp://', ''); // appid, 跳转到的小程序appId // path, 打开的页面路径,如果为空则打开首页 // extraData, 需要传递给目标小程序的数据 var miniParams = { appid: appid, extraData: query, success: function success(res) {}, fail: function fail(res) {}, complete: function complete(res) {} }; if (url) { miniParams.path = url; } this.goMiniUrl({ path: url.replace('miniapp://', '/') }); me.navigateToMiniProgram(miniParams); return; } if (!pagePath) return; page = { url: "/".concat(pageUrl) }; if (isTabPage) { type = 'switch'; page = { url: "/".concat(pagePath) }; } delete query.replace; delete query.back; // 上传formid事件没办法触发,需要一点时间延迟 // 不支持 async // await sleep(100); switch (type) { case 'replace': me.redirectTo(page); break; case 'back': me.navigateBack(page); break; case 'switch': // url 不支持 queryString me.switchTab(page); break; default: // navigateTo, redirectTo 只能打开非 tabBar 页面。 // switchTab 只能打开 tabBar 页面。 if (getCurrentPages().length === 10) { me.redirectTo(page); } else { me.navigateTo(page); } break; } } }, { key: "install", value: function install(xm) { var _this2 = this; xm.addMixin('page', { $forward: function $forward(url, query) { _this2.goPage(url, query); }, back: function back() {} }); } }]); return Plugin; }(_pluginBase.default); var _default = Plugin; exports.default = _default; module.exports = exports.default;
import React from 'react'; import IconHome from '@material-ui/icons/Home'; function SidebarData(){ return ( <div> title: "HOME" icon: <IconHome/> link: "/home" </div> ) } export default SidebarData;
'use strict'; angular.module('system').controller('IndexController', ['$scope', function($scope) { } ]);
const initialState = [ { id: '1', user: 'peter', body: '用 React 配合上 Meteor 来制作成一个单页面应用( SPA ) 架构的聊天室', course: '1' }, { id: '2', user: 'billie', body: '学完课程之后,可以自己搭建一个网站了', course: '1' }, { id: '3', user: 'Jay', body: 'React 框架的最佳入门课程', course: '1' }, { id: '4', user: 'jhon', body: '一个摩登 JS 开发者应该具备的知识大全', course: '2' }, { id: '5', user: 'jake', body: 'nice', course: '2' } ] const comments = (state = initialState, action) => { switch (action.type) { case 'ADD_COMMENT': return [ ...state, action.comment ] case 'DELETE_COMMENT': return state.filter(t => t.id !== action.id) default: return state } } export default comments
import React, { Component } from 'react'; import {Col,Row,Form, Icon} from 'antd'; import './footer.css'; export default class Footer extends Component { render(){ return( <footer className="footer"> <div className="overlay"></div> <Row> <Col span={24} className="footer-top">联系我们</Col> <Col span={6} offset={3} className="footer-bottom"><Icon type="phone" /> +123 456 789</Col> <Col span={6} className="footer-bottom"><Icon type="mail" /> SpanishDreamTeam@github.com</Col> <Col span={6} className="footer-bottom"><Icon type="message" /> 在线联系</Col> <Col span={24} className="footer-top">关注我们</Col> <Col span={1} offset={10} className="footer-bottom"><Icon type="github" /></Col> <Col span={1} className="footer-bottom"><Icon type="aliwangwang" /></Col> <Col span={1} className="footer-bottom"><Icon type="dingding" /></Col> <Col span={1} className="footer-bottom"><Icon type="chrome" /></Col> </Row> <Row> <Col span={24} className="footer-foot">2017 &copy; 版权归SpanishDreamTeam所有</Col> </Row> </footer> ); } }
import React, { Component } from 'react'; import { Container, Row, Col } from 'reactstrap'; import Layout from '../../../components/account/accountLayout'; import AccountCard from '../../../components/account/accountCard'; import AccountNav from '../../../components/account/accountNav'; import DashboardHeader from '../../../components/dashboardHeader'; import AccountGroup from '../../../components/account/accountGroup'; const change = 'CHANGE'; const message = 'MESSAGE'; export default class subscriptionChange extends Component { state = { type: change, } changeType = (type) => { this.setState(() => ({ type })); } save = () => { // save stuff then change type this.changeType(message); } render() { const { type } = this.state; return ( <Layout> <DashboardHeader /> <Container> <AccountCard className="card"> <Row> <Col> <h2 className="mb-md">Account/Alarm Info</h2> </Col> </Row> <Row> <Col md={4}> <AccountNav /> </Col> <Col> <AccountCard> {type === change ? <div> <h4 className="text-center mb-md">Change Membership Type</h4> <AccountGroup> <div> <div className="flex-col"> <div className="font-gotham-rounded"> November 10, 2017 </div> </div> <hr /> <div className="label"> Current Plan </div> <div className="font-gotham-rounded mb-md"> Basic Membership: $19.99/mo </div> <div className="label"> New Plan </div> <div className="mb-md"> <select className="form-control" name="" id=""> <option value="basic">Basic</option> </select> </div> <div className="text-right"> <a href="/account/subscriptions/details" className="btn btn--white"> Cancel </a> <button className="btn btn--primary ml-sm" onClick={this.save}> Change Plan Type </button> </div> </div> </AccountGroup> </div> : ''} {type === message ? <div> <h4 className="text-center mb-md">Plan Has Been Changed</h4> <AccountGroup> <div> <div className="flex-col"> <div className="font-gotham-rounded"> November 10, 2017 </div> </div> <hr /> <div className="label"> Current Plan </div> <div className="font-gotham-rounded mb-md"> Basic Membership: $29.99/mo </div> <div className="form-group"> <p> This change will reflect on your next billing cycle. </p> <div className="font-gotham-rounded"> February 22nd, 2018 </div> </div> <div className="text-right"> <a className="btn btn--primary" href="/account/subscriptions/details"> Done </a> </div> </div> </AccountGroup> </div> : ''} </AccountCard> </Col> </Row> </AccountCard> </Container> </Layout> ); } }
'use strict'; (function(){ document.addEventListener('DOMContentLoaded',function(){ var oBox=document.getElementById('box'); var oUl=oBox.children[0]; var aLi=oUl.children; var aBtn=document.querySelectorAll('#box ol li'); oUl.style.width=aLi[0].offsetWidth*aLi.length+'px'; var translateX=-aLi[0].offsetWidth; oUl.style.WebkitTransform='translateX('+translateX+'px)'; var iNow=1; var bOK = false; oUl.addEventListener('touchstart',function(ev){ if(bOK) return; bOK=true; var downX=ev.targetTouches[0].pageX; var disX=downX-translateX; oUl.style.WebkitTransition = 'none'; function fnMove(ev){ translateX=ev.targetTouches[0].pageX-disX; oUl.style.WebkitTransform='translateX('+translateX+'px)'; } function fnEnd(ev){ oUl.removeEventListener('touchmove',fnMove,false); oUl.removeEventListener('touchend',fnEnd,false); oUl.style.WebkitTransition = '.4s all ease'; if(Math.abs(ev.changedTouches[0].pageX-downX)>10){ if(downX>ev.changedTouches[0].pageX){ iNow++; translateX= -iNow*aLi[0].offsetWidth; oUl.style.WebkitTransform='translateX('+translateX+'px)'; tab(); }else{ iNow--; translateX= -iNow*aLi[0].offsetWidth; oUl.style.WebkitTransform='translateX('+translateX+'px)'; tab(); } }else{ translateX= -iNow*aLi[0].offsetWidth; oUl.style.WebkitTransform='translateX('+translateX+'px)'; } function tranEnd(){ oUl.removeEventListener('transitionend',tranEnd,false); oUl.style.WebkitTransition = 'none'; if(iNow==0){ iNow = aLi.length-2; translateX = -iNow*aLi[0].offsetWidth; oUl.style.WebkitTransform='translateX('+translateX+'px)'; } if(iNow==aLi.length-1){ iNow = 1; translateX = -iNow*aLi[0].offsetWidth; oUl.style.WebkitTransform='translateX('+translateX+'px)'; } bOK = false; }; oUl.addEventListener('transitionend',tranEnd,false); } oUl.addEventListener('touchmove',fnMove,false); oUl.addEventListener('touchend',fnEnd,false); ev.preventDefault(); },false); function tab(){ for(var i=0; i<aBtn.length; i++){ aBtn[i].className=''; } var index=iNow-1; if(index==-1){ index = aLi.length-3; } if(index==aLi.length-2){ index = 0; } aBtn[index].className='on'; } },false); })();
export default { getAllSendingInfo:{ url:'scm/logistic/getAllSendingInfo' } }
import React from 'react'; const ListItem = ({item}) => { return ( <li>{item}</li> ) } const RenderList = ({list}) => { return ( <ol> {list.map(({name, url}, i) => <ListItem item={name || list[i]} key={url || i}/>)} </ol> ) } export default RenderList; /* item = { name: bulbasaur, url: 'https....' } name = item.name {name} */
import React from 'react'; import Counter from 'components/Counter'; /** * React component implementation. * * @author dfilipovic * @namespace ReactApp * @class FactItem * @extends ReactApp */ const FactItem = (props) => ( <div className="fact"> <div className="fact-number timer"> <span className="factor color-light"> <Counter id={'counter-' + props.id} to={props.number} /> </span> </div> <span className="fact-title color-light alpha7"> {props.name} </span> </div> ); FactItem.propTypes = { id: React.PropTypes.number, number: React.PropTypes.number, name: React.PropTypes.string }; export default FactItem;
var renderer = new THREE.WebGLRenderer({canvas: document.getElementById("myCanvas"), antialias: true}); renderer.setClearColor(0xFFFFFF); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); var camera = new THREE.PerspectiveCamera(35,window.innerWidth / window.innerHeight, 0.1, 3000); var scene = new THREE.Scene(); camera.position.z = 1000 controls = new THREE.OrbitControls(camera, renderer.domElement) controls.minDistance = 1 controls.maxDistance = 2000 var light = new THREE.AmbientLight(0xFFFFFF, 0.5); scene.add(light); // var light1 = new THREE.PointLight(0xFFFFFF, 0.3); scene.add(light1); //cubes var geometry = new THREE.BoxGeometry(150, 200, 150); var material = new THREE.MeshLambertMaterial({color: 0x5290FF }); var mesh = new THREE.Mesh(geometry, material); mesh.position.set(500,0,-200); // var geometry1 = new THREE.CubeGeometry(100,100,100); // var material1 = new THREE.MeshLambertMaterial({color: 0xABE7FF}); // var mesh1 = new THREE.Mesh(geometry1, material1); // mesh1.position.set(500,200,-200); // // var geometry2 = new THREE.CubeGeometry(100,100,100); // var material2 = new THREE.MeshLambertMaterial({color: 0xFF9A00}); // var mesh2 = new THREE.Mesh(geometry2, material2); // mesh2.position.set(500,-200,-200); // // var geometry3 = new THREE.CubeGeometry(100,100,100); // var material3 = new THREE.MeshLambertMaterial({color: 0xF7FE00}); // var mesh3 = new THREE.Mesh(geometry3, material3); // mesh3.position.set(-500,-200,-200); // // //sphere var geometry4 = new THREE.SphereGeometry(100,32,32); var material4 = new THREE.MeshLambertMaterial({color: 0xFE0000}); var mesh1 = new THREE.Mesh(geometry4, material4); mesh1.position.set(-500,0,-200); // // //cone var geometry5 = new THREE.ConeGeometry(50,200,8); var material5 = new THREE.MeshLambertMaterial({color: 0x2CFE00 }); var mesh2 = new THREE.Mesh(geometry5, material5); mesh2.position.set(250,0,-200); // // //ring var geometry = new THREE.RingGeometry(40, 110, 32); var material = new THREE.MeshLambertMaterial({color: 0xF4FF00}); var mesh3 = new THREE.Mesh(geometry, material); mesh3.position.set(0,0,-200); // // //Cylinders var geometry7 = new THREE.CylinderGeometry(35,35,200,64,1,false); var material7 = new THREE.MeshLambertMaterial({color: 0xFF9BD1}); var mesh4 = new THREE.Mesh(geometry7, material7); mesh4.position.set(-250,0,-200); // // var geometry8 = new THREE.CylinderGeometry(35,35,150,64,1,false); // var material8 = new THREE.MeshLambertMaterial({color: 0x0029FE}); // var mesh8 = new THREE.Mesh(geometry8, material8); // mesh8.position.set(250,0,-200); // // //plane // var geometry9 = new THREE.PlaneGeometry(2000,2000); // var material9 = new THREE.MeshLambertMaterial({color: 0x0029FE}); // var mesh9 = new THREE.Mesh(geometry9, material9); // mesh9.rotation.set(-Math.PI/2, Math.PI/2000, Math.PI); // mesh9.position.set(0,-500,0); scene.add(mesh, mesh1, mesh2, mesh3, mesh4); var domEvents = new THREEx.DomEvents(camera,renderer.domElement) var sphereClicked var planeClicked domEvents.addEventListener(mesh1, 'click', event =>{ if (!sphereClicked){ mesh1.material.wireframe = false sphereClicked = true } else { mesh1.material.wireframe = true sphereClicked = false } }) // // //change cylinder scale on mouseover hover domEvents.addEventListener(mesh4, 'mouseover', event => { mesh4.scale.set(1.5,1.5,1.5) }) //change cylinder scale back to default on mouseout hover domEvents.addEventListener(mesh4, 'mouseout', event => { mesh4.scale.set(1,1,1) }) // // //change cylinder scale on mouseover hover // domEvents.addEventListener(mesh8, 'mouseover', event => { // mesh8.scale.set(1.5,1.5,1.5) // }) // //change cylinder scale back to default on mouseout hover // domEvents.addEventListener(mesh8, 'mouseout', event => { // mesh8.scale.set(1,1,1) // }) // // //change color of plane and revert to default color domEvents.addEventListener(mesh3, 'click', event =>{ if (!planeClicked){ mesh3.material.color.setHex(0xFFAD00 ); planeClicked = true } else { mesh3.material.color.setHex(0xF4FF00); planeClicked = false } }) // //change cube lt rotation speed on mouseover domEvents.addEventListener(mesh2, 'mouseover', event => { mesh2.rotation.y += 0.2; mesh2.rotation.x += 0.2; }) domEvents.addEventListener(mesh, 'dblclick', event => { scene.remove(mesh) }) domEvents.addEventListener(mesh1, 'dblclick', event => { scene.remove(mesh1) }) domEvents.addEventListener(mesh2, 'dblclick', event => { scene.remove(mesh2) }) domEvents.addEventListener(mesh3, 'dblclick', event => { scene.remove(mesh3) }) domEvents.addEventListener(mesh4, 'dblclick', event => { scene.remove(mesh4) }) // // //change cube rt rotation speed on mouseover // domEvents.addEventListener(mesh1, 'mouseover', event => { // mesh1.rotation.x += 0.1; // }) // // //change cube rb rotation speed on mouseover // domEvents.addEventListener(mesh2, 'mouseover', event => { // mesh2.rotation.x += 0.1; // }) // // //change cube lb rotation speed on mouseover // domEvents.addEventListener(mesh3, 'mouseover', event => { // mesh3.rotation.x += 0.1; // }) requestAnimationFrame(render); function render(){ // mesh.rotation.x += 0.01; mesh.rotation.y += 0.01; mesh.rotation.z += 0.01; mesh1.rotation.x += 0.01; mesh1.rotation.y += 0.01; // mesh2.rotation.x += 0.01; mesh2.rotation.y += 0.01; // mesh3.rotation.x += 0.01; mesh3.rotation.y += 0.01; // mesh4.rotation.x += 0.01; mesh4.rotation.y += 0.01; // // mesh5.rotation.x += 0.01; // mesh5.rotation.y += 0.01; // // mesh6.rotation.x += 0.0; // mesh6.rotation.y += 0.05; // // mesh7.rotation.x += 0.01; // mesh7.rotation.y += 0.0; // mesh7.rotation.z += 0.01; // // // mesh8.rotation.x += 0.01; // mesh8.rotation.y += 0.0; // mesh8.rotation.z += -0.01; controls.update() renderer.render(scene,camera); requestAnimationFrame(render); } renderer.render(scene, camera); //document.body.appendChild(renderer.domElement);
const jwt = require('jsonwebtoken'); const jwtSecret = require('../../config').jwtSecret; module.exports = { requiresLogin: (req, res, next) => { const token = req.body.token || req.cookies.token; if (token) { jwt.verify(token, jwtSecret, (err, decoded) => { if (err) { return next(new Error('Failed to authenticate token!')); } else { req.decoded = decoded; next(); } }) } else { return next(new Error('Please log in!')); } } };
//inherits from Base /** * Constructs the Species object * @constructor * @param options * @returns {Species} */ function Species(options){ //call to super constructor Base.call(this,options); //add species specific properties /* * bBoundaryCondition: false bIsConstant: false color: {iRed: 0, iGreen: 0, iBlue: 168, iAlfa: 255} dInitialQuantity: 0 iHeight: 40 -->base iWidth: 40 -->base position: {iX: 557, iY: 126} -->base sHasOnlySubtanceUnit: false sId: "S_1" -->base sModification: "" sName: "e-" -->base sParentCompartment: "C_1" -->base sParentComplex: "" sQuantityType: "Concentration" sSubstanceUnit: "" this.sNote = "" sType: "SIMPLECHEMICAL" */ this.bBoundaryCondition = options.bBoundaryCondition || false; this.bIsConstant = options.bIsConstant || false; this.color = options.color || {iRed: 0, iGreen: 0, iBlue: 168, iAlfa: 255}; this.dInitialQuantity = options.dInitialQuantity || 0; this.sHasOnlySubtanceUnit = options.sHasOnlySubtanceUnit || false; this.sModification = options.sModification || ""; this.sParentComplex = options.sParentComplex || null; this.sQuantityType = options.sQuantityType || "Concentration"; this.sSubstanceUnit = options.sSubstanceUnit || "mole (Pathway Map Default)"; //TODO : verify this assumption //also should this be alerted to user? this.sType = options.sType || "Gene"; this.sSpeciesGroup = options.sSpeciesGroup || "Group 2"; this.sNote = options.sNote || ""; // if Group 2 [{id:String,title:string,journal:string,volume:String,pages:String,dop:string,author:string}] this.sPubMedReferences = options.sPubMedReferences || (this.sSpeciesGroup ==='Group 1'? "":[]); /** hidden properties **/ //species will function as container only if it is of type COMPLEX if( this.sType === "Complex"){ var children = []; /** not a SBML property **/ this.getAllChildren = function(){return children;} this.addChild = function(sId){ //TODO add validation here to check that added is not compartment return children.indexOf(sId) === -1 ?children.push(sId):-1; } /** * removes child from a child list return array of deleted */ this.removeChild = function(sId){ if(children.indexOf(sId) !== -1) return children.splice(children.indexOf(sId), 1); return null; } } /** * Private variable stores overlayStatus of this Species * @type {String} valid values = UR,DR,UA,ND */ var overlayStatus = ''; /** * returns or sets the overlayStatus of this species * @return {[type]} [description] */ this.overlayStatus = function(_overlayStatus){ overlayStatus = _overlayStatus || overlayStatus; return overlayStatus; } //TODO: add edges to the speceis var edges = [] /** * store the edge refrence of edge this species is part of * @param {Edge} edge edge object of which this species is part of * @return {} adds this edge to the edge list */ this.addEdge = function(edge){ if(!edge || edge.constructor.name !=='Edge') throw new Error('Species addEdge failed. Invalid edge object added'); //var allEdgeSIds = edges.map(function(_edge){return _edge.sId}); //if(allEdgeSIds.indexOf(edge.sId) == -1){ edges.push(edge); //} //else{ //edge allredy exists ignore this for now //console.warn('Edge ' + edge.sId + " Edge allready exists"); //} } /** * remove edge from this species based on the edge sId * @param {Edge} sId edge id to be removed * @return {Edge} removed edge or undefined if not found */ this.removeEdge = function(edge){ var allEdgeSIds = edges.map(function(_edge){return _edge.sId}); var spliced; if(allEdgeSIds.indexOf(edge.sId) !== -1){ spliced = edges.splice(allEdgeSIds.indexOf(edge.sId),1); } return spliced; } /** * returns all the edges this species is part of. * @return {[Edge]} all the edges of this species */ this.getAllEdges = function(){ return edges; } } //setup inheritance ( prototype chain ) Species.prototype = Object.create(Base.prototype); Species.prototype.constructor = Species; // Reset the constructor from Base to Species
export { default } from '@upfluence/ember-upf-utils/types/user';
/** * Created by a on 2017/10/23. */ //Express的路由 const express = require("express"); const constroller = require("../controller/peoplecontroller"); //获取路由对象 const router = express.Router(); // router.route("/login.do") // .get(constroller.getUser) // .post(constroller.postUser); router.get("/roleMan.do",constroller.getRole); router.get("/xgrole.do",constroller.getxgrole); router.get("/deleterole.do",constroller.getscPeople); router.get("/addrole.do",constroller.getaddPeople); router.get("/seach.do",constroller.getseachrole); module.exports=router;
import axios from "axios"; const URL = "http://localhost:3333/smurfs"; //Action types: export const FETCHING = "FETCHING_SMURFS"; export const FETCHED = "FETCHED_SMURFS_SUCCESS"; export const ERROR = "SMURFS_ERROR"; export const ADDING = "ADDING_SMURF"; export const ADDED = "ADDED_SMURF"; export const DELETING = "DELETING_SMURF"; export const DELETED = "DELETED_SMURF"; //Action creator export const getSmurfsData = () => { return dispatch => { console.log("fetching"); dispatch({ type: FETCHING }); axios .get(URL) .then(response => dispatch({ type: FETCHED, payload: response.data })) .catch(err => dispatch({ type: ERROR })); }; }; export const addNewSmurf = smurf => { const newSmurfPromise = axios.post(URL, smurf); return dispatch => { dispatch({ type: ADDING }); newSmurfPromise .then(({ data }) => { dispatch({ type: ADDED, payload: data }); }) .catch(err => { dispatch({ type: ERROR, payload: err }); }); }; }; export const deleteSmurf = id => { const deleteSmurfPromise = axios.delete(`${URL}/${id}`); return dispatch => { dispatch({ type: DELETING }); deleteSmurfPromise .then(({ data }) => { dispatch({ type: DELETED, payload: data }); }) .catch(err => { dispatch({ type: ERROR, payload: err }); }); }; };
exports.run = function(client, message, args) { message.member.addRole('308783051826135041'); message.reply('your role as been updated!'); }
import { Widget } from "../widget.js"; import { UI } from "../ui.js"; import { importCss } from "../../utils.js"; class InputController extends Widget { /** * Input controller constructor * @param {UI} ui parent UI */ constructor(ui) { super(ui); /** * Widget title * @type {HTMLHeadingElement} */ this.$title = document.createElement("h3"); /** * Input of circuit * @type {HTMLUListElement} */ this.$inputs = document.createElement("ul"); /** * Input buttons of circuit * @type {HTMLButtonElement[]} */ this.inputs = []; this.setup(); } setup() { importCss("/css/widgets/inputController.css"); this.$title.innerText = "Input controller"; this.elm.classList.add("inputController"); this.elm.appendChild(this.$title); this.elm.appendChild(this.$inputs); } changeInput(index) { const circuit = this.ui.app.circuit; const targetInput = circuit.inputs[index]; circuit.calcCycle(); targetInput.setInput(~targetInput.getValue(0)); targetInput.forwardProp(); this.ui.updateWidgets(); this.ui.app.requestRender(); } update() { const circuit = this.ui.app.circuit; for (let i = 0; i < circuit.inputs.length; i++) { if (circuit.inputs[i].getState(0)) { this.inputs[i].classList.add("on"); this.inputs[i].classList.remove("off"); } else { this.inputs[i].classList.remove("on"); this.inputs[i].classList.add("off"); } } } updateStruct() { const circuit = this.ui.app.circuit; for (let i = 0; i < circuit.inputs.length; i++) { const input = document.createElement("li"); const button = document.createElement("button"); button.appendChild(document.createTextNode("input " + i.toString())); button.addEventListener("click", this.changeInput.bind(this, i)); input.appendChild(button); this.$inputs.appendChild(input); this.inputs[i] = button; } } } export { InputController };
import React, {Component} from "react"; import {ScrollView, StyleSheet, View} from 'react-native'; import {Button, Input, Text} from "react-native-elements"; import strings from "../strings"; import {boundMethod} from "autobind-decorator"; import {getAuthedAPI} from "../api"; import {ACTION_TYPES, createAction} from '../redux/actions'; import {connect} from 'react-redux'; const initialPasswordFieldsState = { oldPassword: null, newPassword: null, confirmPassword: null, oldPasswordValidationError: null, newPasswordValidationError: null, confirmPasswordValidationError: null } class Security extends Component { constructor(props) { super(props); this.state = { ...initialPasswordFieldsState, verificationStatus: false, emailSent: false } getAuthedAPI().getEmailVerificationStatus().then((status) => { this.setState({verificationStatus: status}); }) } @boundMethod handleOldPassword(text) { this.setState({oldPassword: text}); } @boundMethod handleNewPassword(text) { this.setState({newPassword: text}); } @boundMethod onNewPasswordBlur() { this.setState({ newPasswordValidationError: this.state.newPassword.length < 6 ? strings.pages.signUp.doesNotMeetPasswordRequirements : "" }); this.checkPasswordConfirm(); } @boundMethod handleConfirmPassword(text) { this.setState({confirmPassword: text}, this.checkPasswordConfirm); } @boundMethod checkPasswordConfirm() { this.setState({ confirmPasswordValidationError: this.state.newPassword !== this.state.confirmPassword && this.state.confirmPassword ? strings.pages.signUp.noPasswordMatch : null }); } @boundMethod doChangePassword() { getAuthedAPI() .changePassword(this.state.oldPassword, this.state.newPassword) .then(() => { this.setState({ ...initialPasswordFieldsState }); alert("Password was successfully changed."); }) .catch(() => { alert("Failed to update password. Check that you entered your old password correctly."); }) } changePasswordButtonEnabled() { return !this.state.newPasswordValidationError && !this.state.passwordConfirmValidationError && !this.state.oldPasswordValidationError && this.state.oldPassword && this.state.newPassword && this.state.confirmPassword; } @boundMethod logout() { this.props.resetStore(); } @boundMethod requestResendVerification() { getAuthedAPI().resendVerificationEmail().then(() => { this.setState({emailSent: true}); }) } render() { return ( <ScrollView style={{margin: 15}}> <View> <Text h4>Change Password</Text> <Input placeholder="Old Password" secureTextEntry={true} containerStyle={styles.smallMargin} disabled={this.state.loading} onChangeText={this.handleOldPassword} errorMessage={this.state.oldPasswordValidationError} autoCapitalize="none" value={this.state.oldPassword} /> <Input placeholder="New Password" secureTextEntry={true} containerStyle={styles.smallMargin} disabled={this.state.loading} onChangeText={this.handleNewPassword} errorMessage={this.state.newPasswordValidationError} autoCapitalize="none" onBlur={this.onNewPasswordBlur} value={this.state.newPassword} /> <Input placeholder="Confirm New Password" secureTextEntry={true} containerStyle={styles.smallMargin} disabled={this.state.loading} onChangeText={this.handleConfirmPassword} errorMessage={this.state.confirmPasswordValidationError} onBlur={this.checkPasswordConfirm} value={this.state.confirmPassword} autoCapitalize="none" /> <Button title="Update Password" containerStyle={styles.smallMargin} onPress={this.doChangePassword} disabled={!this.changePasswordButtonEnabled()} /> </View> <View style={{marginTop: 10}}> <Text h4>Logout</Text> <Button title="Logout" onPress={this.logout} /> </View> <View style={{marginTop: 10}}> <Text h4>Email Verification</Text> {this.state.verificationStatus ? <Text>Your email is verified!</Text> : <View> {this.state.emailSent ? <Text>Email sent! Please check your inbox.</Text> : <View> <Text>Please check your inbox for a verification email.</Text> <Button title="Resend" containerStyle={styles.smallMargin} onPress={this.requestResendVerification} /> </View> } </View> } </View> </ScrollView> ); } } const styles = StyleSheet.create({ smallMargin: { margin: 5 }, }); function mapDispatchToProps(dispatch) { return { resetStore: () => dispatch(createAction(ACTION_TYPES.RESET_STORE)) }; } export default connect(null, mapDispatchToProps)(Security);
import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import { loginUser } from '../actions/LoginActions.js' import HomeNavbar from '../components/HomeNavbar' import HomeFooter from '../components/HomeFooter' import { Link } from "react-router"; export default class About extends Component { render() { const { dispatch, isAuthenticated, history } = this.props return ( <div className="about" > <div className="homepage-container"> <div className="homepage-section homepage-section-title"> <div className="homepage-section homepage-section-title-bg"> </div> <div className="homepage-section-wrapper"> <HomeNavbar isAuthenticated={isAuthenticated} dispatch={dispatch} history={history} /> <div className="homepage-section-inner"> <h1 className="page-section-title-title">Envie de connaître <span className="c-second">la naissance</span> et <span className="c-second">les secrets</span> de My Dress’Up ?</h1> <div className="homepage-section-title-baseline page-section-title-baseline">Apprenez-tout de son histoire ! </div> </div> <div className="arrow-to-bottom"></div> </div> </div> <div className="page-section page-section-about"> <div className="homepage-section-wrapper"> <div className="page-section-about-text"> <h2 className="page-section-about-text-title">Lassée de ne jamais savoir quoi mettre le matin? Trouver la bonne tenue avec My Dress Up, en un coup de main !</h2> <p>My Dress’Up est une application web d’un dressing virtuel. Elle vous permettra de créer, classer, organiser votre propre dressing, de créer vos tenues favorites mais aussi des lookbooks avec l’ensemble de vos tenues préférées. Pluie, soleil, neige, My Dress’Up vous conseillera des tenues en fonction de la météo et de la température extérieure. Un dîner important vendredi soir, un footing le samedi après-midi, une soirée le samedi soir, le calendrier de My Dress’Up vous permettra d’organiser vos tenues pour chacune de vos sorties ! </p> <p>Un mois de réalisation professionnelle dans le cadre d’un M2 CIM, 2 DT et 2 DA, des passionnées de mode, voilà comment est né My Dress’Up ! Soutenez-nous et aidez-nous à développer ce projet jusqu’au bout ! Nous avons besoin de votre soutient ! </p> <video controls src="video.ogv" width="100%" className="page-section-about-video">Ici la description alternative</video> </div> </div> </div> <HomeFooter /> </div> </div> ) } }
import React, {Component} from 'react'; import { Table, Icon, Divider } from 'antd'; export default class AllMatt extends Component{ constructor(props){ super(props); this.state={ data:null, } } render(){ return ( <div> <ul id="supp-ul"> <li>供应商评价<span>(<i className="reds">10</i>)</span></li> <li>供应商评价<span>(<i className="reds">10</i>)</span></li> <li>临时外包项目申请<span>(<i className="reds">10</i>)</span></li> <li>临时外包项目申请<span>(<i>10</i>)</span></li> <li>临时外包项目申请<span>(<i>10</i>)</span></li> <li>临时外包项目申请<span>(<i className="reds">10</i>)</span></li> <li>临时外包项目申请<span>(<i>10</i>)</span></li> <li>临时外包项目申请<span>(<i>10</i>)</span></li> <li>临时外包项目申请<span>(<i>10</i>)</span></li> <li>临时外包项目申请<span>(<i>10</i>)</span></li> <li>临时外包项目申请<span>(<i>10</i>)</span></li> <li>临时外包项目申请<span>(<i>10</i>)</span></li> <li>临时外包项目申请<span>(<i>10</i>)</span></li> <li>临时外包项目申请<span>(<i>10</i>)</span></li> </ul> </div> ) } }
import React from "react" import styled, { createGlobalStyle } from "styled-components" import SEO from "./seo" import Navbar from "./navbar" import ScrollToTop from "./scrollToTop" /* Colour Pallette Main: #0074b8 Accent: #ECA400 Background: #202020 Alt Background: #191919 Footer Background: #131418 Text: #efefef Alt Text: #8f8f8f */ const GlobalStyle = createGlobalStyle` *, *::after, *::before{ margin: 0; padding: 0; box-sizing: inherit; } html{ font-size: 62.5%; @media (max-width: 75em){ font-size: 50%; } @media (max-width: 56.25em){ font-size: 56.25%; } @media (max-width: 41em){ font-size: 75%; } } body{ font-family: 'Lato', sans-serif; font-weight: 300; line-height: 1.7; color: #efefef; background-color: #202020; font-size: 1.6rem; box-sizing: border-box; } ` const Container = styled.div` position: relative; ` const Layout = ({ title, children }) => ( <Container> <GlobalStyle /> <SEO title={title} /> <Navbar /> <ScrollToTop /> {children} </Container> ) export default Layout
/*jslint es6 */ "use strict"; const {describe, it} = require("mocha"); describe("projectMembers", function () { const chai = require("chai"); const expect = chai.expect; const chaiAsPromised = require("chai-as-promised"); const sinon = require("sinon"); const factory = require("../../../lib/domain/projectMembers"); const credentials = require("../../credentials"); const config = Object.assign({resource: "ProjectMembers"}, credentials); chai.use(chaiAsPromised); describe("toIds", function () { function getHandlerWithFakeFunction(args, value, prop) { const stub = sinon.stub(); const handler = {resource: "Users"}; stub.rejects(); stub.withArgs(args).resolves(value); handler[prop] = stub; return handler; } it("should eventually return an empty array when value is omitted", function () { const sut = factory(config); return expect(sut.toIds(null, undefined)) .to.eventually.be.an("array") .that.is.empty; }); it("should eventually return an empty array when value is null", function () { const sut = factory(config); return expect(sut.toIds(null, null)) .to.eventually.be.an("array") .that.is.empty; }); it("should eventually return an empty array when value is a boolean (false)", function () { const sut = factory(config); return expect(sut.toIds(null, false)) .to.eventually.be.an("array") .that.is.empty; }); it("should eventually return an empty array when value is a boolean (true)", function () { const sut = factory(config); return expect(sut.toIds(null, true)) .to.eventually.be.an("array") .that.is.empty; }); it("should eventually return a one-item array when value is a number", function () { const sut = factory(config); const id = 1; return expect(sut.toIds(null, id)).to.eventually.be.an("array").and.to.deep.equal([id]); }); it("should convert value to string when it is neither undefined, null, boolean nor integer", function () { const sut = factory(config); const name = "ABC"; const handler = getHandlerWithFakeFunction(name, 42, "getByName"); return expect(sut.toIds(handler, [name])) .to.eventually.be.an("array") .and.to.deep.equal([42]); }); it("should eventually invoke the filter function when value is a string starting with 'where='", function () { const sut = factory(config); const condition = "(FirstName eq 'Adam')"; const expected = 42; const handler = getHandlerWithFakeFunction(condition, [{Id: expected}], "filter"); return expect(sut.toIds(handler, `where=${condition}`)) .to.eventually.deep.equal([expected]); }); it("should eventually be rejected when no item of the given name is found", function () { const sut = factory(config); const name = "x"; const handler = getHandlerWithFakeFunction(name, null, "getByName"); return expect(sut.toIds(handler, name)) .to.be.rejected; }); it("should eventually be rejected when the given name matches several items", function () { const sut = factory(config); const veryCommonLastName = "Smith"; const handler = getHandlerWithFakeFunction(veryCommonLastName, [1, 2], "getByName"); return expect(sut.toIds(handler, veryCommonLastName)) .to.be.rejected; }); it("should eventually return an array whose unique item is matching the given name", function () { const sut = factory(config); const name = "x"; const expected = 42; const handler = getHandlerWithFakeFunction(name, expected, "getByName"); return expect(sut.toIds(handler, name)) .to.eventually.be.an("array") .and.to.deep.equal([expected]); }); }); describe("getWhereClause", function () { it("should return an empty string when both projects and users are empty", function () { const sut = factory(config); return expect(sut.getWhereClause([], [])) .to.be.a("string") .that.is.empty; }); it("should use the 'eq' operator on users when only one user id is given", function () { const sut = factory(config); return expect(sut.getWhereClause([1], [])) .to.equal("(User.Id eq 1)"); }); it("should use the 'in' operator on users when several user ids are given", function () { const sut = factory(config); return expect(sut.getWhereClause([1, 2], [])) .to.equal("(User.Id in (1,2))"); }); it("should use the 'eq' operator on projects when only one project id is given", function () { const sut = factory(config); return expect(sut.getWhereClause([], [1])) .to.equal("(Project.Id eq 1)"); }); it("should use the 'in' operator on projects when several project ids are given", function () { const sut = factory(config); return expect(sut.getWhereClause([], [1, 2])) .to.equal("(Project.Id in (1,2))"); }); it("should use the 'and' operator when both user and project are given", function () { const sut = factory(config); return expect(sut.getWhereClause([1], [2])) .to.equal("(User.Id eq 1)and(Project.Id eq 2)"); }); }); describe("getItems", function () { it("should eventually reject the promise when both users and projects are empty", function () { const sut = factory(config); return expect(sut.getItems([[], []])) .to.eventually.be.rejected; }); it("should eventually return a 3-elements array whose first two are those given in input", function () { const users = [1]; const projects = [2]; const items = []; const sut = factory(config); const filter = sinon.stub(sut, "filter"); filter.resolves(items); return expect(sut.getItems([users, projects])) .to.eventually.be.an("array") .and.to.deep.equal([users, projects, items]); }); }); describe("show", function () { it("should eventually return an array of users ids, projects ids and existing assignments", function () { const items = [ { User: {Id: 1}, Project: {Id: 2}, Role: {Id: 3} } ]; const expected = [[1], [2], items]; const sut = factory(config); const getItems = sinon.stub(sut, "getItems"); getItems.withArgs([[1], [2]]).resolves(expected); return expect(sut.show(1, 2)) .to.eventually.be.an("array") .and.to.deep.equal(expected); }); }); describe("remove", function () { it("should eventually return a 4-elements array whose first three are those given in input", function () { const users = [1]; const projects = [2]; const items = [{}]; const result = {Deleted: [], NotDeleted: []}; const sut = factory(config); const batchRemove = sinon.stub(sut.remover, "batchRemove"); batchRemove.resolves(result); return expect(sut.remove([users, projects, items])) .to.eventually.be.an("array") .and.to.deep.equal([users, projects, items, result]); }); }); describe("noneIsAll", function () { it("should eventually return the input array when it is not empty", function () { const sut = factory(config); const arr = [1, 2, 3]; return expect(sut.noneIsAll(null, arr)) .to.eventually.equal(arr); }); it("should eventually return a new array when the input array is empty", function () { const sut = factory(config); const arr = []; const handler = { getActive: () => Promise.resolve([1, 2, 3]) }; return expect(sut.noneIsAll(handler, arr)) .to.eventually.be.an("array") .and.to.not.equal(arr); }); }); describe("makeItem", function () { it("should return an object with User, Project and Role properties set according to arguments", function () { const sut = factory(config); const expected = { User: {Id: 1}, Project: {Id: 2}, Role: {Id: 3} }; return expect(sut.makeItem(1, 2, 3)).to.deep.equal(expected); }); it("should return an object without Role property when the role is undefined", function () { const sut = factory(config); return expect(sut.makeItem(1, 2)).to.not.have.own.property("Role"); }); }); describe("makeBatch", function () { it("should throw an Error when multiple roles are given", function () { const sut = factory(config); const makeBatchWithMultipleRoles = function () { sut.makeBatch([null, null, [1, 2]]); }; return expect(makeBatchWithMultipleRoles).to.throw(Error); }); it("should make a batch whose length is the product of the number of users by the number of projects", function () { const sut = factory(config); const users = [1, 2, 3]; const projects = [4, 5]; const roles = []; return expect(sut.makeBatch([users, projects, roles])) .to.be.an("array") .and.to.have.lengthOf(users.length * projects.length); }); }); describe("assign", function () { it("should eventually remove prior assignments and create new ones", function () { const sut = factory(config); const unassign = sinon.stub(sut, "unassign"); const create = sinon.stub(sut, "create"); unassign.withArgs(1, 2).resolves([[1], [2], [], {}]); create.resolves({}); sut.assign(1, 2, 3); return expect(unassign.calledWith(1, 2) && create.calledWith(3, [[1], [2]])); }); }); });
// @flow import type { InEnv } from "./in-env"; import { Env, pure, liftA2, fetch, alias, run } from "./in-env"; export type Expr = Var | Let | Num | Plus | Times ; export class Var { name: string; constructor(name: string) { this.name = name; } } export class Let { name: string; value: number; scope: Expr; constructor(name: string, value: number, scope: Expr) { this.name = name; this.value = value; this.scope = scope; } } export class Num { value: number; constructor(value: number) { this.value = value; } } export class Plus { left: Expr; right: Expr; constructor(left: Expr, right: Expr) { this.left = left; this.right = right; } } export class Times { left: Expr; right: Expr; constructor(left: Expr, right: Expr) { this.left = left; this.right = right; } } const plus = liftA2(a => b => a + b), times = liftA2(a => b => a * b); function evaluate(expr: Expr) : InEnv<string, number, number> { return expr instanceof Var ? fetch(expr.name) : expr instanceof Let ? alias(expr.name, expr.value, evaluate(expr.scope)) : expr instanceof Num ? pure(expr.value) : expr instanceof Plus ? plus(evaluate(expr.left), evaluate(expr.right)) : /* we have a Times */ times(evaluate(expr.left), evaluate(expr.right)); } const env = new Env(new Map([ ["foo", 2], ["bar", 3] ])); const expr = new Plus( new Var("foo"), new Let( "bar", 5, new Plus( new Num(1), new Times( new Num(4), new Var("bar"))))); console.log(run(evaluate(expr), env));
const a = require('../../constants/action'); const initialState = { textinput: '', pulldown: '5', target_id: '', } export default function room_talk_detail(state = initialState, action) { switch (action.type) { case a.ROOM_DETAIL_INIT: return Object.assign({}, state, { textinput: '', target_id: '' }) case a.ROOM_DETAIL_SET_ROOMNAME: return Object.assign({}, state, { textinput: action.data, }) case a.ROOM_DETAIL_SET_PULLDOWN: return Object.assign({}, state, { pulldown: action.data, }) case a.ROOM_DETAIL_SET_TARGET_ID: return Object.assign({}, state, { target_id: action.data, }) default: return state; } }
import React, { useRef } from 'react'; import axios from 'axios'; import { useStore } from '../store/store'; import { setBlogs } from '../store/blogActions'; const AddPost = () => { const inputTitleRef = useRef(); const inputBodyRef = useRef(); const inputUserIdRef = useRef(); const { dispatch } = useStore(); const addPost = async (e) => { const data = await axios.post( `https://jsonplaceholder.typicode.com/posts`, { userId: Number(inputUserIdRef.current.value), title: inputTitleRef.current.value, body: inputBodyRef.current.value, }, { 'Content-type': 'application/json; charset=UTF-8', } ); dispatch(setBlogs([data.data])); e.target.reset(); }; const handleSubmit = (e) => { e.preventDefault(); addPost(e); }; return ( <> <form onSubmit={(e) => handleSubmit(e)} className="post-form"> <input required type="text" name="title" placeholder="Title" id="" ref={inputTitleRef} /> <textarea ref={inputBodyRef} required name="body" placeholder="Post" id="" /> <input ref={inputUserIdRef} required type="number" name="userId" placeholder="User ID" id="" /> <input required type="submit" value="Post" /> </form> </> ); }; export default AddPost;
const TelegramBot = require('node-telegram-bot-api') const mongoose = require('mongoose') const config = require('./config') const helper = require('./helper') const _ = require('lodash') const geolib = require('geolib') const keyboard = require('./keyboard') const kb = require('./keyboardButtons') const database = require('../database.json') helper.logStart() mongoose.Promise = global.Promise async function connectToDb() { try { await mongoose.connect(config.DB_URL, { useNewUrlParser: true, useUnifiedTopology: true }) console.log('Connected to Mongo DB') } catch (error) { console.log(error) } } connectToDb() require('./models/film.model') require('./models/cinema.model') require('./models/user.model') const Film = mongoose.model('films') // database.films.forEach(element => { // new Film(element).save() // }); const Cinema = mongoose.model('cinemas') // database.cinemas.forEach(element => { // new Cinema(element).save() // }) const User = mongoose.model('users') //============================================================ const ACTION_TYPE = { TOGGLE_FAV_FILM: 'TFF', SHOW_CINEMAS: 'SC', SHOW_CINEMAS_MAP: 'SCM', SHOW_FILMS: 'SF' } const bot = new TelegramBot(config.TOKEN, { polling: true }) bot.on('message', msg => { console.log('Working', msg.from.first_name) const chatId = helper.getChatId(msg) switch(msg.text) { case kb.home.favourite: showFavouriteFilms(chatId, msg.from.id) break case kb.home.films: bot.sendMessage(chatId, `Выберите жанр:`, { reply_markup: {keyboard: keyboard.film} }) break case kb.home.cinemas: bot.sendMessage(chatId, `Send your location`, { reply_markup: { keyboard: keyboard.cinemas } }) break case kb.film.action: sendFilmByQuery(chatId, {type: 'action'}) break case kb.film.comedy: sendFilmByQuery(chatId, {type: 'comedy'}) break case kb.film.random: sendFilmByQuery(chatId, {}) break case kb.back: bot.sendMessage(chatId, `Что хотите посмотреть?`,{ reply_markup: {keyboard: keyboard.home} }) break } if(msg.location){ getCinemaInCoord(chatId, msg.location) } }) bot.on('callback_query', query => { let data const userId = query.from.id try { data = JSON.parse(query.data) } catch (error) { throw new Error('Data parsing error') } switch (data.type) { case ACTION_TYPE.TOGGLE_FAV_FILM: toggleFavouriteFilm(userId, query.id, data) break; case ACTION_TYPE.SHOW_CINEMAS: showCinemas(userId, data.cinemaUuids) break; case ACTION_TYPE.SHOW_CINEMAS_MAP: bot.sendLocation(userId, data.lat, data.lon) break; case ACTION_TYPE.SHOW_FILMS: sendFilmByQuery(userId, {uuid: {'$in': data.filmUuids}}) break; default: console.log('unknown keyboard key') break; } }) bot.on('inline_query', query => { Film.find({}) .then((movies) => { const results = movies.map(f => { const caption = `Название: ${f.name}\nГод выпуска: ${f.year}\nРейтинг: ${f.rate}\nДлительность: ${f.length}\nСтрана: ${f.country}\n` return { id: f.uuid, type: 'photo', photo_url: f.picture, thumb_url: f.picture, caption: caption, reply_markup: { inline_keyboard: [ [ { text: `Кинопоиск: ${f.name}`, url: f.link } ] ] } } }) bot.answerInlineQuery(query.id, results, { cache_time: 0 }) }) }) bot.onText(/\/start/, msg => { const text = `HEllo, ${msg.from.first_name}\nВыбирите команду для начала работы` bot.sendMessage(helper.getChatId(msg), text, { reply_markup: { keyboard: keyboard.home } }) }) bot.onText(/\/f(.+)/, (msg, [source, match]) => { Promise.all([ Film.findOne({uuid: match}), User.findOne({telegramId: msg.from.id}) ]).then(([foundMovie, foundUser]) => { let isFav = false; if(foundUser){ isFav = foundUser.films.indexOf(foundMovie.uuid) !== -1 } let favText = isFav ? 'Удалить из избранного' : 'Добавить в избранное' const caption = `Название: ${foundMovie.name}\nГод выпуска: ${foundMovie.year}\nРейтинг: ${foundMovie.rate}\nДлительность: ${foundMovie.length}\nСтрана: ${foundMovie.country}\n` bot.sendPhoto(helper.getChatId(msg), foundMovie.picture, { caption: caption, reply_markup: { inline_keyboard: [ [ { text: favText, callback_data: JSON.stringify({ type: ACTION_TYPE.TOGGLE_FAV_FILM, filmUuid: foundMovie.uuid, isFav: isFav }) }, { text: 'Показать кинотеатры', callback_data: JSON.stringify({ type: ACTION_TYPE.SHOW_CINEMAS, cinemaUuids: foundMovie.cinemas }) } ], [ { text: `Кинопоиск ${foundMovie.name}`, url: foundMovie.link } ] ] } }) }) }) bot.onText(/\/c(.+)/, async (msg, [source, match]) => { const foundCinema = await Cinema.findOne({uuid: match}) bot.sendMessage(msg.chat.id, `Кинотеатр ${foundCinema.name}`, { reply_markup:{ inline_keyboard: [ [ { text: foundCinema.name, url: foundCinema.url }, { text: 'Показать на карте', callback_data: JSON.stringify({ type: ACTION_TYPE.SHOW_CINEMAS_MAP, lat: foundCinema.location.latitude, lon: foundCinema.location.longitude }) } ], [ { text: 'Фильмы в прокате', callback_data: JSON.stringify({ type: ACTION_TYPE.SHOW_FILMS, filmUuids: foundCinema.films }) } ] ] } }) }) //================================================================================= async function sendFilmByQuery(chatId, query) { const resultArr = await Film.find(query) const html = resultArr.map((item, index) => { return `<b>${index + 1}.</b> ${item.name} - /f${item.uuid}` }).join('\n') sendHtml(chatId, html, 'films') } async function getCinemaInCoord(chatId, location) { let cinemas = await Cinema.find({}) cinemas.forEach(c => { c.distance = geolib.getDistance(location, c.location)/1000 }) cinemas = _.sortBy(cinemas, 'distance') const html = cinemas.map((c,i) => { return `<b> ${i+1}. </b> ${c.name} <em>Расстояние</em> - <strong>${c.distance}</strong> км /c${c.uuid}` }).join('\n') sendHtml(chatId, html, 'home') } function sendHtml(chatId, html, kbName = null) { const objOptions = { parse_mode: 'HTML' } if(kbName) { objOptions.reply_markup = { keyboard: keyboard[kbName] } } bot.sendMessage(chatId, html, objOptions) } function toggleFavouriteFilm(userId, queryId, {filmUuid, isFav}) { let userWillSave User.findOne({telegramId: userId}) .then( user => { if(user) { if(isFav){ user.films = user.films.filter(fUuid => fUuid !== filmUuid) } else { user.films.push(filmUuid) } userWillSave = user } else { userWillSave = new User({telegramId: userId, films: [filmUuid]}) } const answerText = isFav ? 'Deleted' : 'Added' userWillSave.save().then(_ => { bot.answerCallbackQuery({ callback_query_id: queryId, text: answerText }) }) .catch(err => console.log(err)) }) .catch( err => console.log(err)) } function showFavouriteFilms(chatId, userId){ User.findOne({telegramId: userId}) .then((foundUser)=>{ if(foundUser){ Film.find({uuid: {'$in': foundUser.films}}) .then( foundMovies => { let html if(foundMovies.length){ html =`<strong>Ваши фильмы в категории избранное:\n</strong>` + foundMovies.map(( f, i ) => { return `<b>${ i + 1 }.</b> "${f.name}" <em>рейтинг - ${f.rate} </em> link - /f${f.uuid}` }).join('\n') }else{ html = "У Вас нет фильмов в категории избранное" } sendHtml(chatId, html, 'home') }) } else{ sendHtml(chatId, 'User has not been found', home) } }) } function showCinemas(userId, cinemasArray) { Cinema.find({uuid: {'$in': cinemasArray}}) .then(cinemas => { let html = `<strong>Фильм можете постотреть в кинотеатрах:\n</strong>` + cinemas.map(( c, i ) => { return `<b> ${i + 1}.</b> ${c.name} /c${c.uuid}` }).join('\n') sendHtml(userId, html, 'home') }) }
import { getQueryString } from './getQueryString'; describe('getQueryString', () => { it('should return the right string', () => { const actual = getQueryString({ test: 1, hello: 'hello', dontIncludeEmptyStrings: '', dontIncludeUndefined: undefined, include0: 0, includeFalse: false, }); expect(actual).toBe(`?test=1&hello=hello&include0=0&includeFalse=false`); }); });
$( document ).ready(function(){ var timeLeft = 15; // countdown start time var timerId = setInterval(countdown, 1000); // de-crementing one sec at a time var numRight = 0; // correct answer array var messages = ["Wow! Were you born in Cleveland?", // array for messages called based upon 'Meh, you did "OK"', // answers correct "Yikes! I'm sending you a ticket to Cleveland!"]; var analysis; // calls the message based on the index stated $("#countdown").text("seconds remaining: " + timeLeft) // puts the countdown function on the page function countdown() { if (timeLeft < 8) { $("#countdown").css("color", "red"); // at 3 sec numbers change from green to red } if (timeLeft == -1) { //runs the noTimeleft function at zero clearTimeout(timerId); noTimeLeft(); } else { $("#countdown").text("seconds remaining: " + timeLeft) //countdown if not at zero timeLeft--; } } function noTimeLeft() { $("#buttonSub").attr("disabled", true);// disables submit button when time runs out alert("We'll accept any answers before time ran out"); checkAnswers(); //checks any answers selected prior to timeout $('input[type=radio]').prop('checked',false); // clears radio button selection } function reset() { $("#countdown").css("color", "limegreen"); // color back to green timeLeft = 15; //time back to 7 seconds timerId = setInterval(countdown, 1000); //1 sec increments numRight = 0; // resets number correct $("#buttonSub").attr("disabled", false); //re-enables submit button $("#at-submit").css("visibility", "hidden"); // hides at-submit values $('input[type=radio]').prop('checked',false); // see above } function checkAnswers(){ var question1 = document.quiz.q1.value; //captures question selection var question2 = document.quiz.q2.value; var question3 = document.quiz.q3.value; if(question1=="Cuy"){ // compares to answer, if correct, adds to the array numRight++; } if(question2=="54"){ numRight++; } if(question3=="green"){ numRight++; } if (numRight < 1){ //determines messages array index selection with analysis variable analysis = 2; } if (numRight > 0 && numRight < 3 ){ analysis = 1; } if (numRight > 2){ analysis = 0; } $("#at-submit").css("visibility", "visible"); // number correct data becomes visible $("#amount-correct").text("You got " + numRight + " right."); // text adds number correct $("#message").text(messages[analysis]) // analysis variable is either 0, 1, or 2, selects index value from messages variable } $("#buttonSub").on("click", function(){ // on submit, checks answers, resets timer, disables submit button checkAnswers(); clearTimeout(timerId); $("#buttonSub").attr("disabled", true); }) $("#buttonReset").on("click", function(){ reset(); // runs reset }) });
// ------------ Global ---------------- var http = require('http'); var express = require('express'); var path = require('path'); var mongoose = require('mongoose'); var passport = require('passport'); var app = express(); var server = http.createServer(app); var socketIO = require('socket.io'); var io = socketIO.listen(server); var cors = require('cors'); //global variables app.locals = { // Super User.. Only used for demonstration // Should be removed on real implementation superClinician : [ { firstName : "Sainez", surname : "Amon", lastName : "Kimutai", username : "@sainez_sainez", userNo : "000002", nationalId : "00000000", gender : "male", phone : "+254 718 896 779", specialize : "SuperUser", profNo : "101010", mail : "sainez@kimsweb.co.ke", password : '573fcc62ae45988da88a492d0e15b5c01c53cc94f5a1d7aed95bb1208a8862f6e57164f42b98d7f8dbe8f989d24f7476e351b955a29d77af77a74cd677ce9bbc' } ], // Clinical Users superAdmin : [ { firstName : "Sainez", surname : "Amon", lastName : "Kimutai", username : "@sainez_sainez", userNo : "000001", nationalId : "00000000", gender : "male", phone : "+254 718 896 779", department : "SuperUser", officeNo : "101010", mail : "sainez@kimsweb.co.ke", password : '573fcc62ae45988da88a492d0e15b5c01c53cc94f5a1d7aed95bb1208a8862f6e57164f42b98d7f8dbe8f989d24f7476e351b955a29d77af77a74cd677ce9bbc' } ], // Admin Users // Active files variables activeONE : [], activeTWO : [], activeTHREE : [], activeFOUR : [],activeMED : [], activeUSER : [] }; // Database Config var db = require('./config/keys').MongoURI; // Connect to Mongo mongoose.connect(db, { useNewUrlParser: true } ) .then(() => console.log('MongoDB Connected...')) .catch(err => console.log("Cannot connect to MongoDB!!")); // Passport Config require('./config/passport')(passport); // Passport Middleware app.use(passport.initialize()); app.use(passport.session()); // Controlers var users = require('./controllers/users.js'); var files = require('./controllers/files.js'); var stats = require('./controllers/stats.js'); // controllers users(app); files(app, io); stats(app, io); //Static files app.use(express.static(path.join(__dirname, '/public'))); //cors app.use(cors({ credentials : true })); //Get all Routes app.get('/*', cors(), function(req, res){ res.sendFile(path.join(__dirname, '/public/index.html')); }); //Socket Connection io.on('connection', function(){}); //listen to port server.listen(process.env.PORT || 8090, () =>{ console.log('Running Port 8090....'); });
const UserData = [ {id: 1, name: 'Suparman', registered: '2018/01/01', role: 'Guest', status: 'Pending'}, {id: 2, name: 'Sapardi', registered: '2018/01/01', role: 'Member', status: 'Active'}, {id: 3, name: 'Suparjo', registered: '2018/02/01', role: 'Staff', status: 'Banned'}, {id: 4, name: 'Sujatmiko', registered: '2018/02/01', role: 'Admin', status: 'Inactive'}, {id: 5, name: 'Sunaryo', registered: '2018/03/01', role: 'Member', status: 'Pending'}, {id: 6, name: 'Sugiman', registered: '2018/01/21', role: 'Staff', status: 'Active'}, {id: 7, name: 'Subianto', registered: '2018/01/01', role: 'Member', status: 'Active'}, {id: 8, name: 'Sutrisno', registered: '2018/02/01', role: 'Staff', status: 'Banned'}, {id: 9, name: 'Sutejo', registered: '2018/02/01', role: 'Admin', status: 'Inactive'}, {id: 10, name: 'Superman', registered: '2018/03/01', role: 'Member', status: 'Pending'}, {id: 11, name: 'Supratman', registered: '2018/03/01', role: 'Owner', status: 'Active'} ] export default UserData;
$(document).ready(function(){ $('#btn-menu').click(function(){ if ( $ ('.btn-menu span').attr('class') == 'icon-menu') { $ ('.btn-menu span').removeClass('icon-menu').addClass('icon-cross'); $ ('.menu-link').css({'left': '0'}); } else { $ ('.btc-menu span').removeClass('icon-cross').addClass('icon-menu'); $ ('.menu-link').css({'left': '-100%'}); } }) })
export { post as postCallMeBack } from './post';
import name from '../../../api/dictionary/name'; import {pageSize, pageSizeType, description, searchConfig} from '../../globalConfig'; const filters = [ {key: 'supplierPriceCode', title: '系统编号', type: 'text'}, {key: 'supplierId', title: '供应商', type: 'search'}, {key: 'contractCode', title: '合同号', type: 'text'}, {key: 'balanceCompany', title: '结算单位', type: 'search'}, {key: 'enabledType', title: '是否启用', type: 'select', dictionary: name.ZERO_ONE_TYPE}, {key: 'statusType', title: '状态', type: 'select', dictionary: 'status_type'}, {key: 'insertUser', title: '创建用户', type: 'search'}, {key: 'startTimeFrom', title: '有效开始日期', type: 'date'}, {key: 'startTimeTo', title: '至', type: 'date'}, {key: 'endTimeFrom', title: '有效结束日期', type: 'date'}, {key: 'endTimeTo', title: '至', type: 'date'}, {key: 'insertTimeFrom', title: '创建日期', type: 'date'}, {key: 'insertTimeTo', title: '至', type: 'date'}, ]; const buttons = [ {key: 'add', title: '新增', bsStyle: 'primary', sign: 'supplierPrice_add'}, {key: 'copy', title: '复制新增', sign: 'supplierPrice_copy'}, {key: 'edit', title: '编辑', sign: 'supplierPrice_edit'}, {key: 'delete', title: '删除', sign: 'supplierPrice_delete', confirm: '是否确定删除所选数据?'}, {key: 'enable', title: '启用', sign: 'supplierPrice_enable'}, {key: 'disable', title: '禁用', sign: 'supplierPrice_disable'}, {key: 'import', title: '导入', sign: 'supplierPrice_import'}, {key: 'export', title: '导出', sign: 'supplierPrice_export'}, ]; const tableCols = [ {key: 'supplierPriceCode', title: '系统编号'}, {key: 'enabledType', title: '是否启用', dictionary: name.ENABLED_TYPE}, {key: 'supplierId', title: '供应商'}, {key: 'contractCode', title: '合同号'}, {key: 'balanceCompany', title: '结算单位'}, {key: 'startTime', title: '有效开始日期'}, {key: 'endTime', title: '有效结束日期'}, {key: 'fileList', title: '附件', link: 'list', linkTitleKey: 'fileName'}, {key: 'remark', title: '备注'}, {key: 'insertTime', title: '创建时间'}, {key: 'insertUser', title: '创建人员'}, {key: 'insertInstitution', title: '创建机构'}, {key: 'updateTime', title: '更新时间'}, {key: 'updateUser', title: '更新人员'}, // {key: 'lockStatus', title: '是否锁定', dictionary: name.ZERO_ONE_TYPE}, {key: 'statusType', title: '状态', dictionary: 'status_type'}, ]; const index = { filters, buttons, tableCols, searchConfig, searchData: {}, tableItems: [], currentPage: 1, returnTotalItems: 0, pageSize, pageSizeType, description }; const tabs2 = [ {key: 'contract', title: '合同信息', showIn: [0, 1, 2]}, {key: 'freight', title: '运费', showIn: [2]}, {key: 'extraCharge', title: '附加费', showIn: [2]}, ]; const contract = { controls: [ {key: 'supplierId', title: '供应商', type: 'search', required: true}, {key: 'contractCode', title: '合同号', type: 'text'}, {key: 'startTime', title: '有效开始日期', type: 'date', required: true, rule: {type: '<', key: 'endTime'}}, {key: 'endTime', title: '有效结束日期', type: 'date', required: true, rule: {type: '>', key: 'startTime'}}, {key: 'balanceCompany', title: '结算单位', type: 'search'}, {key: 'remark', title: '备注', type: 'textArea', props: {span: 2}}, ], uploadText: '上传文档:(单个文件大小限制在5M以内,上传个数不能超过10个,若大于10个请压缩后上传)', footerBtns: [ {key: 'save', title: '保存', showIn: [0, 1, 2]}, {key: 'commit', title: '提交', showIn: [2]}, ] }; const businessTypeOptions = [ {title: '始发地', value: '1'}, {title: '发货人', value: '2'}, ]; const destinationTypeOptions = [ {title: '目的地', value: '1'}, {title: '收货人', value: '2'}, ]; const priceTypeOptions = [ {title: '金额', value: '1'}, {title: '运费比例', value: '2'}, ]; const freight = { buttons: [ {key: 'add', title: '新增', bsStyle: 'primary'}, {key: 'copy', title: '复制新增'}, {key: 'edit', title: '编辑'}, {key: 'batchEdit', title: '批量修改'}, {key: 'delete', title: '删除', confirm: '是否确定删除所选数据?'}, {key: 'enable', title: '启用'}, {key: 'disable', title: '禁用'}, {key: 'import', title: '导入'}, {key: 'export', title: '导出'}, {key: 'refresh', title: '刷新'}, ], cols: [ {key: 'supplierPriceCode', title: '供应商报价标识'}, {key: 'enabledType', title: '是否启用', dictionary: name.ENABLED_TYPE}, {key: 'businessType', title: '运输类型', dictionary: name.BUSINESS_TYPE}, {key: 'departureType', title: '起发地类别', options: businessTypeOptions}, {key: 'departure', title: '起运地'}, {key: 'destinationType', title: '目的地类别', options: destinationTypeOptions}, {key: 'destination', title: '目的地'}, {key: 'isReturn', title: '是否返程', dictionary: name.ZERO_ONE_TYPE}, {key: 'carModeId', title: '车型'}, {key: 'fuelType', title: '燃油种类', dictionary: name.FUEL_TYPE}, {key: 'standardPrice', title: '基本运费'}, {key: 'returnPrice', title: '返空费'}, {key: 'currency', title: '币种'}, {key: 'chargeUnit', title: '计量单位', dictionary: name.CHARGE_UNIT}, {key: 'numberSource', title: '数量源', dictionary: name.NUMBER_SOURCE}, {key: 'hours', title: '时效(小时)'}, {key: 'kilometre', title: '公里数(KM)'}, {key: 'remark', title: '备注'}, {key: 'statusType', title: '状态', dictionary: 'status_type'}, {key: 'insertTime', title: '创建时间'}, {key: 'insertUser', title: '创建人员'}, {key: 'updateTime', title: '更新时间'}, {key: 'updateUser', title: '更新人员'}, ], controls: [ {key: 'supplierId', title: '供应商', type: 'readonly', required: true}, {key: 'contractNumber', title: '供应商合同号', type: 'readonly'}, {key: 'departureType', title: '起发地类别', type: 'select', required: true, options: businessTypeOptions}, {key: 'departure', title: '起运地', type: 'search', required: true}, {key: 'destinationType', title: '目的地类别', type: 'select', required: true, options: destinationTypeOptions}, {key: 'destination', title: '目的地', type: 'search', required: true}, {key: 'businessType', title: '运输类型', type: 'select', dictionary: name.BUSINESS_TYPE}, {key: 'isReturn', title: '是否返程', type: 'select', dictionary: name.ZERO_ONE_TYPE}, {key: 'carModeId', title: '车型', type: 'search'}, {key: 'fuelType', title: '燃油种类', type: 'select', dictionary: name.FUEL_TYPE}, {key: 'standardPrice', title: '基本运费', type: 'text', required: true}, {key: 'returnPrice', title: '返空费', type: 'text'}, {key: 'chargeUnit', title: '计量单位', type: 'select', dictionary: name.CHARGE_UNIT, required: true}, {key: 'numberSource', title: '数量源', type: 'select', dictionary: name.NUMBER_SOURCE, required: true}, {key: 'hours', title: '时效(小时)', type: 'number'}, {key: 'kilometre', title: '公里数(KM)', type: 'number', props: {real: true, precision: 2}}, {key: 'remark', title: '备注', type: 'text'}, ], batchEditControls: [ {key: 'standardPrice', title: '基本运费', type: 'text'}, {key: 'returnPrice', title: '返空费', type: 'text'}, {key: 'currency', title: '币种', type: 'search'}, {key: 'chargeUnit', title: '计量单位', type: 'select', dictionary: name.CHARGE_UNIT}, {key: 'numberSource', title: '数量源', type: 'select', dictionary: name.NUMBER_SOURCE}, ], currentPage: 1, pageSize, pageSizeType, description, names: [ name.ZERO_ONE_TYPE, name.BUSINESS_TYPE, name.FUEL_TYPE, name.CHARGE_UNIT, name.NUMBER_SOURCE ] }; const extraCharge = { buttons: [ {key: 'add', title: '新增', bsStyle: 'primary'}, {key: 'copy', title: '复制新增'}, {key: 'edit', title: '编辑'}, {key: 'batchEdit', title: '批量修改'}, {key: 'delete', title: '删除', confirm: '是否确定删除所选数据?'}, {key: 'enable', title: '启用'}, {key: 'disable', title: '禁用'}, {key: 'import', title: '导入'}, {key: 'export', title: '导出'}, {key: 'refresh', title: '刷新'}, ], cols: [ {key: 'supplierPriceCode', title: '供应商报价标识'}, {key: 'enabledType', title: '是否启用', dictionary: name.ENABLED_TYPE}, {key: 'businessType', title: '运输类型', dictionary: name.BUSINESS_TYPE}, {key: 'departureType', title: '起发地类别', options: businessTypeOptions}, {key: 'departure', title: '起运地'}, {key: 'destinationType', title: '目的地类别', options: destinationTypeOptions}, {key: 'destination', title: '目的地'}, {key: 'carModeId', title: '车型'}, {key: 'chargeItemId', title: '费用项', required: true}, {key: 'price', title: '价格', required: true}, {key: 'priceType', title: '价格类别', options: priceTypeOptions, required: true}, {key: 'currency', title: '币种'}, {key: 'chargeUnit', title: '计量单位', dictionary: name.CHARGE_UNIT}, {key: 'numberSource', title: '数量源', dictionary: name.NUMBER_SOURCE}, {key: 'remark', title: '备注'}, {key: 'statusType', title: '状态', dictionary: 'status_type'}, {key: 'insertTime', title: '创建时间'}, {key: 'insertUser', title: '创建人员'}, {key: 'updateTime', title: '更新时间'}, {key: 'updateUser', title: '更新人员'}, ], controls: [ {key: 'supplierId', title: '供应商', type: 'readonly', required: true}, {key: 'contractNumber', title: '供应商合同号', type: 'readonly'}, {key: 'departureType', title: '起发地类别', type: 'select', options: businessTypeOptions}, {key: 'departure', title: '起运地', type: 'search'}, {key: 'destinationType', title: '目的地类别', type: 'select', options: destinationTypeOptions}, {key: 'destination', title: '目的地', type: 'search'}, {key: 'businessType', title: '运输类型', type: 'select', dictionary: name.BUSINESS_TYPE}, {key: 'carModeId', title: '车型', type: 'search'}, {key: 'chargeItemId', title: '费用项', type: 'search', required: true}, {key: 'price', title: '价格', type: 'number', required: true}, {key: 'priceType', title: '价格类别', type: 'select', options: priceTypeOptions, required: true}, {key: 'chargeUnit', title: '计量单位', type: 'select', dictionary: name.CHARGE_UNIT, required: true}, {key: 'numberSource', title: '数量源', type: 'select', dictionary: name.NUMBER_SOURCE, required: true}, {key: 'remark', title: '备注', type: 'text'}, ], batchEditControls: [ // {key: 'standardPrice', title: '基本运费', type: 'text'}, // {key: 'returnPrice', title: '返空费', type: 'text'}, {key: 'price', title: '价格', type: 'number', props: {real: true, precision: 2}}, {key: 'currency', title: '币种', type: 'search'}, {key: 'chargeUnit', title: '计量单位', type: 'select', dictionary: name.CHARGE_UNIT}, {key: 'numberSource', title: '数量源', type: 'select', dictionary: name.NUMBER_SOURCE}, ], currentPage: 1, pageSize, pageSizeType, description, names: [ name.ZERO_ONE_TYPE, name.BUSINESS_TYPE, name.FUEL_TYPE, name.CHARGE_UNIT, name.NUMBER_SOURCE ] }; const editConfig = { activeKey: 'contract', tabs: tabs2, contract, freight, extraCharge }; const config = { activeKey: 'index', tabs: [{key: 'index', title: '供应商报价列表', close: false}], index, editConfig, names: [ name.ZERO_ONE_TYPE, name.BUSINESS_TYPE, name.FUEL_TYPE, name.CHARGE_UNIT, name.NUMBER_SOURCE, name.ENABLED_TYPE ] }; export default config;
/* Design a cash register drawer function checkCashRegister() that accepts purchase price as the first argument (price), payment as the second argument (cash), and cash-in-drawer (cid) as the third argument. cid is a 2D array listing available currency. The checkCashRegister() function should always return an object with a status key and a change key. Return {status: "INSUFFICIENT_FUNDS", change: []} if cash-in-drawer is less than the change due, or if you cannot return the exact change. Return {status: "CLOSED", change: [...]} with cash-in-drawer as the value for the key change if it is equal to the change due. Otherwise, return {status: "OPEN", change: [...]}, with the change due in coins and bills, sorted in highest to lowest order, as the value of the change key. */ function checkCashRegister(price, cash, cid) { var change = cash - price const money = { 'ONE HUNDRED': { value: 100, index: 8 }, TWENTY: { value: 20, index: 7 }, TEN: { value: 10, index: 6 }, FIVE: { value: 5, index: 5 }, ONE: { value: 1, index: 4 }, QUARTER: { value: 0.25, index: 3 }, DIME: { value: 0.1, index: 2 }, NICKEL: { value: 0.05, index: 1 }, PENNY: { value: 0.01, index: 0 }, } while (change > 0) { for (let denomination in money) { if (change >= money[denomination].value) { // update cid // console.log('change', change, 'CID', cid) cid[money[denomination].index][1] -= money[denomination].value // decrement change change -= money[denomination].value // console.log('change', change, 'CID', cid) break } } } return change } checkCashRegister(19.5, 20, [ ['PENNY', 1.01], ['NICKEL', 2.05], ['DIME', 3.1], ['QUARTER', 4.25], ['ONE', 90], ['FIVE', 55], ['TEN', 20], ['TWENTY', 60], ['ONE HUNDRED', 100], ])
import React, { Component } from 'react'; import {Form, FormGroup, Col, Row, Container, Button, Label, Input} from 'reactstrap' import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import * as userActions from '../actions/userActions' class UpdateAccountForm extends Component { constructor(props) { super(props) this.state = { info: { id: this.props.user.users.user.id, password: "", passwordConfirmation: "", username: "", email: "", } } } handleChange(event){ const field = event.target.name; const info = this.state.info; info[field] = event.target.value; return this.setState({info: info}) } handleSubmit(event) { event.preventDefault() this.props.actions.updateUser(this.state.info); } render() { const username = this.props.user.users.user.username const email = this.props.user.users.user.email const image = this.props.user.users.user.image return( <Container> <Row style={{paddingTop: "25px"}}> <Col className="col-4"></Col> <Col className="col-4"> <Form onChange={(event) => this.handleChange(event)} onSubmit={(event) => this.handleSubmit(event)}> <FormGroup> <Label for="username">Username</Label> <Input type="text" name="username" id="username" placeholder={username} /> </FormGroup> <FormGroup> <Label for="email">Email</Label> <Input type="email" name="email" id="email" placeholder={email} /> </FormGroup> <FormGroup> <Label for="image">Image</Label> <Input type="text" name="image" id="image" placeholder={image} /> </FormGroup> <FormGroup> <Label for="password">Enter New or Confirm Current Password</Label> <h6><em>This field cannot be blank</em></h6> <Input type="password" name="password" id="password" /> </FormGroup> <FormGroup> <Label for="passwordConfirmation">Confirm New Password</Label> <Input type="password" name="passwordConfirmation" id="passwordConfirmation" /> </FormGroup> <Button>Submit</Button> </Form> </Col> <Col className="col-4"></Col> </Row> </Container> ) } } const mapDispatchToProps = (dispatch) => { return { actions: bindActionCreators(userActions, dispatch) }; } const mapStateToProps = (state) => { return { user: state } } export default connect(mapStateToProps, mapDispatchToProps)(UpdateAccountForm);
const util = require('util') const log = (data) => console.log(util.inspect(data, {showHidden: false, depth: Infinity, colors: true})) // Returns UUIDV4 string const uuidv4 = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); const ItemTypes = { Consumable: 0, Resource: 1, Weapon: 2, Armor: 3, Unset: 4, } // Practica operador || // Usar operador || para tomar valores por defecto // Ej: { valor: someVariable || "valor por defecto"} const createItem = ({gid, name, description, type, uid} = {}) => { return { uid: uid || uuidv4(), // por defecto deberia ser uuidv4() gid: gid || 0, // por defecto deberia ser 0 name: name || "", // por defecto string vacio description: description || null, // por defecto null type: type || ItemTypes.Unset, // por defecto ItemTypes Unset } } const calculateStackSize = (item) => { switch(item?.type){ case ItemTypes.Consumable: return 16; case ItemTypes.Resource: return 999; case ItemTypes.Weapon: case ItemTypes.Armor: return 1; } return 0; } // Practica arrays // Practica method find in array // https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/find const findEmptySlot = (slots) => { //slots is an array that contains slot objects // {item, quantity, stackSize} // find first elements that matchs slot empty condition // an slot is empty if item is null return null; } // Practica method find in array const findStackableSlotForItem = (slots, item) => { //slots is an array that contains slot objects // {item, quantity, stackSize} // find first elements that matchs slot stackable condition // an slot is stackable if item is not null // and item.gid equals slot.item.gid // and slot is not full (slot.quantity < slot.stackSize) return null } // Necesitamos buscar items en los slots que contengan el gid // Hint: podemos usar array filter // https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/filter // slots puede o no tener item, se debe validar const findItemsByGID = (slots, gid) => { //slots is an array that contains slot objects // {item, quantity, stackSize} // item contains {gid: number} return [] } const calculateSlotQuantityAndRest = (slotQ, stackSize, quantity) => { const newQuantity = slotQ + quantity //sobrante si la cantidad total es mayor al stack size const rest = newQuantity - stackSize // Si sobran items (es decir no entran en el stack fijo) (rest > 0) // newQ es el stack size, caso contrario es la nueva cantidad // Practica operador ternario // https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Conditional_Operator // Resolver con una ternaria a ? b : c const newQ = 0 return { quantity: newQ, rest } } const addItem = (inventory, item, quantity) => { let slot = null; slot = findStackableSlotForItem(inventory.slots, item); if(!slot){ slot = findEmptySlot(inventory.slots) } // Inventory full if (!slot) return; // Practica optional chaining // https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Optional_chaining // Reemplazar expresion con operador optional chaining if(slot && slot.item && slot.item.gid === item.gid){ const res = calculateSlotQuantityAndRest(slot.quantity, slot.stackSize, quantity) slot.quantity = res.quantity if (res.rest > 0){ addItem(inventory, item, res.rest) }else{ slot.item.uid = item.uid; } }else{ slot.quantity = quantity slot.stackSize = calculateStackSize(item) slot.item = item; inventory.items.push(slot) } } // Nothing to do here :) const createInventory = () => { const slots = []; for(let i=0;i<12;i++){ const slot = { stackSize: 0, item: null, quantity: 0, } slots.push(slot); } const items = []; return { slots, items, } } module.exports = { createItem, ItemTypes, createInventory, addItem, uuidv4, findEmptySlot, findStackableSlotForItem, findItemsByGID, calculateSlotQuantityAndRest }
// Declaring a Hashmap using the JS Map constructor let firstHashmap = new Map(); // Declaring and initializing a new hashmap object let secondHashmap = new Map([ [1, "first"], [2, "second"], [3, "third"], ]); console.log("firsthashmap:", firstHashmap); console.log("secondHashmap:", secondHashmap); console.log(secondHashmap.get(1));
let foo = "bar" const obj1 = { name: "JC", email: "id@server.com" } const arr = [1, 'blue', true, {ISBN: 145}] const arr2 = [5, 99, 200, 6, 32, 33] const add = (num1, num2)=>{ return (num1 + num2) } const doMath = (...args) => { if (args.length == 1) { return args[0] * args[0] } else { switch (args[0]) { case 'mult': return args[1] * args[2] case "add": return args[1] + args[2] case "sub": return args[1] - args[2] case "div": return args[1] / args[2] case "mod": return args[1] % args[2] case "exp": return args[1] ** args[2] default: return false } } } module.exports = { foo, obj1, arr, add, arr2, doMath }