text
stringlengths
7
3.69M
ProductPanel=Ext.extend(Disco.Ext.CrudListPanel,{ id:"productPanel", baseUrl:"product.ejf", viewWin:function(){ var size = this.getDefaultWinSize(); return { width : size.width , height : size.height, title : '产品详情' } }, createForm:function(){ var formPanel=new Ext.form.FormPanel({ frame:true, labelWidth:70, fileUpload:true, labelAlign:'right', items:[ {xtype:"hidden",name:"id"}, Disco.Ext.Util.twoColumnPanelBuild( {fieldLabel:'产品名称',name:'title',allowBlank:false}, {fieldLabel:'产品编号',name:'sn',allowBlank:false}, ConfigConst.BASE.getDictionaryCombo("dir","分类","ProductDir",null,false), ConfigConst.BASE.getDictionaryCombo("brand","品牌","ProductBrand"), ConfigConst.BASE.getDictionaryCombo("unit","计量单","ProductUnit"), {fieldLabel:'规格',name:'spec'}, {fieldLabel:'型号',name:'model'}, {fieldLabel:'等级',name:'lev'}, {fieldLabel:'进价',name:'buyPrice',xtype:"numberfield"}, {fieldLabel:'销售价',name:'salePrice',xtype:"numberfield"} ), {fieldLabel:'产品描述',xtype:"textarea",name:'content',anchor:"-20",height:80} ] }); return formPanel; }, searchFormPanel : function(){ var form = new Ext.FormPanel({ items : [ {} ] }); return form; }, createWin:function(callback, autoClose){ var size = this.getDefaultWinSize(); return this.initWin(size.width,size.heigth,"产品信息录入",callback, autoClose); }, getDefaultWinSize : function(){ return { width : 538, heigth : 300 } }, storeMapping:["id","title","sn","spec","model","lev","buyPrice","salePrice","content","dir","brand","unit"], initComponent : function(){ this.cm=new Ext.grid.ColumnModel([ {header: "产品名称", sortable:true,width: 100, dataIndex:"title"}, {header: "产品编号", sortable:true,width: 100, dataIndex:"sn"}, {header: "分类", sortable:true,width: 100, dataIndex:"dir",renderer:this.objectRender("title")}, {header: "品牌", sortable:true,width: 100, dataIndex:"brand",renderer:this.objectRender("title")}, {header: "单位", sortable:true,width: 100, dataIndex:"unit",renderer:this.objectRender("title")}, {header: "规格", sortable:true,width: 100, dataIndex:"spec"}, {header: "型号", sortable:true,width: 100, dataIndex:"model"}, {header: "等级", sortable:true,width: 100, dataIndex:"lev"}, {header: "进价", sortable:true,width: 100, dataIndex:"buyPrice"}, {header: "销售价", sortable:true,width: 100, dataIndex:"salePrice"}, {header: "简介", sortable:true,width: 300, dataIndex:"content"} ]); ProductPanel.superclass.initComponent.call(this); } });
var mongoose = require('mongoose'), Schema = mongoose.Schema; var basicTermSchema = new Schema({ name: {type: String, required: true}, seikyo: {type: Schema.Types.ObjectId, ref: 'Seikyo', required: true} }); basicTermSchema.virtual('created').get(function () { return this._id.getTimestamp(); }); mongoose.model('BasicTerm', basicTermSchema);
import { Vue, $ } from 'js/base' import homeHeader from '../../components/home/home-header.vue' require('./scss/home.scss') import homeIndex from './index.vue' var homeVue = new Vue({ el: '#home', template: '<div class="pageview"><home-header></home-header><home-index></home-index></div>', components: { 'home-index': homeIndex, 'home-header': homeHeader } })
const numbers = [1, 2, 3, 4]; const moreNumbers = [5, 6, 7, 8]; const allNumbers = numbers.concat(moreNumbers); console.log(numbers); console.log(moreNumbers); console.log(allNumbers);
({ handleRecordUpdated: function (component, event, helper) { var eventParams = event.getParams(); if (eventParams.changeType === "LOADED") { // record is loaded (render other component which needs record data value) } else if (eventParams.changeType === "CHANGED") { // record is changed helper.getRegionalVariantHelper(component, event, helper); } else if (eventParams.changeType === "REMOVED") { // record is deleted } else if (eventParams.changeType === "ERROR") { // there’s an error while loading, saving, or deleting the record } }, handleEvent: function (component, event, helper) { let eventSource = event.getParam("source"); if (eventSource === 'variant added' || 'variant removed') { $A.get('e.force:refreshView').fire(); component.find("recordLoader").reloadRecord(); } } });
const puppeteer = require('puppeteer'); const { expect } = require('chai'); const epext = require('chai').expect describe('My First Pippeteer Test',()=>{ it('Launch the Browser',async()=>{ const browser = await puppeteer.launch({headless:false ,slowMo:10,devtools:false}); const page = await browser.newPage() await page.setDefaultTimeout('10000') await page.setDefaultNavigationTimeout('20000') await page.goto('http://zero.webappsecurity.com/') await page.waitForXPath('//*[@id="searchTerm"]') await page.type('#searchTerm','Hello World',{delay: 200}) await page.keyboard.press('Enter',{delay: 10}) await page.waitFor(5000) await page.goBack(); await page.waitForSelector('#signin_button') await page.click('#signin_button'); await page.waitFor(()=> !document.querySelector('#signin_button')) //await page.waitForSelector('#signin_button', {hidden:true,timeout:5000}) await browser.close() }) })
'use strict'; window.onload = function() { const bat = new Audio("金属バットで打つ1.mp3"); document.querySelectorAll("a").forEach(function(a){ a.addEventListener('click',()=>{ bat.play(); }); }); }
import './modules/parts/viz';
(function() { 'use strict'; angular.module('app') .controller('IdeaCtrl', IdeaCtrl); function IdeaCtrl($state, $ionicHistory, $stateParams, Ideas, $scope, IdeasService) { var ideaId = $stateParams.id; $scope.idea = IdeasService.getIdea(ideaId); // $scope.event = Event; // console.log(Event); $scope.refresh = function() { $scope.idea = IdeasService.getIdea(ideaId); console.log($scope.idea); //Stop the ion-refresher from spinning $scope.$broadcast('scroll.refreshComplete'); }; } })();
import React, { PropTypes } from 'react'; import Square from './Square'; class BoardSquare extends React.Component { constructor() { super(); this.handleClick = this.handleClick.bind(this); this.getSquareStyle = this.getSquareStyle.bind(this); } handleClick() { this.props.handleClick(this.props.x, this.props.y); } getSquareStyle() { const sizeInPercentage = (1 / this.props.height) * 100; return { height: `${sizeInPercentage}%`, width: `${sizeInPercentage}%`, }; } render() { return ( <div className="boardSquare" onClick={this.handleClick} style={this.getSquareStyle()}> <Square alive={this.props.alive} /> </div> ); } } BoardSquare.propTypes = { x: PropTypes.number.isRequired, y: PropTypes.number.isRequired, height: PropTypes.number.isRequired, alive: PropTypes.bool.isRequired, handleClick: PropTypes.func.isRequired }; export default BoardSquare;
// this index.js is for index page // the animation to show/hide feed content & summary $(".list-title").click(function () { if($(this).siblings(".list-hidden").is(":hidden")){ $(this).siblings(".list-summary").hide("normal"); $(this).siblings(".list-hidden").show("normal"); }else{ $(this).siblings(".list-summary").show("normal"); $(this).siblings(".list-hidden").hide("normal"); } }); // the animation to show/hide feed details $(".feed-list-li-title").click(function () { if($(this).siblings(".feed-detail").is(":hidden")){ $(this).siblings(".feed-detail").show("normal"); }else{ $(this).siblings(".feed-detail").hide("normal"); } }); // the animation of right-top arrow, to show/hide logout $(".left-arrow").click(function () { if($(".logout").is(":hidden")){ $(".logout").css("display","inline"); $(this).css("transform","rotate(135deg)"); }else{ $(".logout").css("display","none"); $(this).css("transform","rotate(-45deg)"); } }); // use regex to check url function checkUrl(url){ let regex=/^(http(s?):\/\/)/; if(regex.test(url)){ // if true hide error hint $(".error-url").hide("normal"); console.log("url format true"); }else{// if false show hint $(".error-url").show("normal"); console.log("url format false"); } } // when click submit check url $("#submit").click(function () { checkUrl($("#link").val()); });
import React from "react"; import PropTypes from "prop-types"; import styled, { css } from "styled-components"; import { Grid } from "@material-ui/core"; const FlexGrid = styled(Grid)` display: flex; ${({ padd }) => padd && css` padding: ${padd}; `} ${({ margin }) => margin && css` margin: ${margin}; `} `; const FlexBox = ({ padd, margin, children, max, ...gridProps }) => { return ( <FlexGrid container max={max} padd={padd} margin={margin} {...gridProps}> {children} </FlexGrid> ); }; FlexBox.propTypes = {}; FlexBox.defaultProps = { max: "false" }; export default FlexBox;
'use strict'; module.exports = function(app) { const controller = require('../controllers/controller'); app.route('/') .get(controller.homepage) .post(controller.page404); app.route('/new_access_token/:userID/:account/:token') .get(controller.page404) .put(controller.newAccessTok); app.route('/schedule_post') .post(controller.schedulePost); app.use(function(req, res) { res.status(404) .send({ error: req.url + ' not found', cause: 'api call to invalid endpoint.', }); }); };
/** * Use different values in production and development mode * @param {any} originalValue * @param {any} developmentValue */ const useDevelopmentValue = (originalValue, developmentValue) => { const { NODE_ENV } = process.env; if (NODE_ENV === 'development') { return developmentValue; } return originalValue; }; module.exports = useDevelopmentValue;
const image = document.getElementById("image"); const citation = document.getElementById("citation"); const auteur = document.getElementById("auteur"); let getData = function () { fetch("https://thatsthespir.it/api") //fonction s'execute a la fin du fetch de l'url .then((res) => res.json()) //imbriqué :retourne en json .then((data) => { image.src = data.photo; citation.innerText = '"' + data.quote + '"'; auteur.innerText = '@' + data.author + '_'; }); //imbriqué :recupère les attributs et les inscrit dans le champ de texte }; getData();
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import reduxThunk from 'redux-thunk'; import SearchFlights from './views/SearchFlights'; import { Reducers } from './config/reducers'; import './App.css'; class App extends Component { constructor(props) { super(props); let createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore); this.Store = createStoreWithMiddleware(Reducers); } render() { return ( <Provider store={this.Store}> <SearchFlights /> </Provider> ); } } export default App;
(function($,w){ var asyncbox = {}; /** * confirm */ asyncbox.confirm = function(options){ var defaults = { text:'', //提示内容 oktext:'确定', //确认按钮文案 call:null //回调函数(ok:代表点击确定按钮,cancel:代表点击取消按钮) } var options = $.extend(defaults,options); $("body").append('<div class="asyncbox_cover"></div><div class="asyncbox"><div class="text"><h1>'+options.text+'</h1></div><div class="btn"><a href="javascript:void(0);" class="cancel">取消</a><a href="javascript:void(0);" class="ok">'+options.oktext+'</a></div></div>'); $(".ok",'.asyncbox').click(function(){ $('.asyncbox,.asyncbox_cover').remove(); if(options.call instanceof Function){ options.call('ok'); } }); $('.cancel','.asyncbox').click(function(){ $('.asyncbox,.asyncbox_cover').remove(); if(options.call instanceof Function){ options.call('cancel'); } }); }; /** * alert */ asyncbox.alert = function(text){ $("body").append('<div class="asyncbox_cover"></div><div class="asyncbox"><div class="text"><h1>'+text+'</h1></div><div class="btn"><a href="javascript:void(0);" class="ok single_btn">确定</a></div></div>'); $(".ok",'.asyncbox').click(function(){ $('.asyncbox,.asyncbox_cover').remove(); }); }; w.asyncbox = asyncbox; /** * 自定义弹窗 * 关闭弹窗:$.modal.close(); */ $.fn.modal = function(options){ var defaults = { overlayClose : true, //点击遮罩层是否关闭弹出窗体 onOpen:null, //弹出窗体打开时候的回调函数 onShow:null, //弹出窗体显示时候的回调函数 onClose:null //弹出窗体关闭时候的回调函数 } var options = $.extend(defaults,options); if(options.onOpen instanceof Function){ options.onOpen();0 } $.modal = $(this); var modal_width = $.modal.width()/2; var style = 'margin-left:-'+modal_width+'px'; var content = $(this).prop("outerHTML"); $("body").append('<div class="asyncbox_cover"></div><div class="modal" style="'+style+'">'+content+'</div>'); if(options.onShow instanceof Function){ options.onShow(); } var box_close = function(){ $('.modal,.asyncbox_cover').remove(); if(options.onClose instanceof Function){ options.onClose(); } } $('.close_btn','.modal').click(function(){ box_close(); }); $.modal.close = function(){ box_close(); }; if(options.overlayClose){ $('.asyncbox_cover').click(function(){ box_close(); }); } }; })(jQuery,window);
/** * @author Adrian Chmielewski-Anders */ // "main" document.addEventListener("DOMContentLoaded", function() { });
var audioCache = {};//音频缓存 var bgmCache = {}//背景缓存 var gameType = require('../data/gametype') var Aduio = { musicOn: true, init: function () { var local = cc.sys.localStorage.getItem("music"); this.musicOn = ("" === local || null === local || local == 1); if (!WECHATGAME && !QQPLAY) this.musicOn = false }, on() { this.musicOn = !this.musicOn; if (this.musicOn == false) this.stopBgm() else this.playBgm(gameType.BgmType.start) cc.sys.localStorage.setItem("music", this.musicOn ? 1 : 0); }, playEffect(name) { if (!this.musicOn) return; if (audioCache[name] == undefined) { if (name == "") return cc.loader.loadRes("audios/" + name, function (err, audio) { audioCache[name] = audio; cc.audioEngine.playEffect(audio, false); }) } else { cc.audioEngine.playEffect(audioCache[name], false); } }, playBgm(name) { return if (!this.musicOn) return; if (bgmCache[name] == undefined) { cc.loader.loadRes("audios/" + name, function (err, audio) { if (err) console.log(err) bgmCache[name] = audio cc.audioEngine.playMusic(audio, true); }) } else { cc.audioEngine.playMusic(bgmCache[name], true); } }, stopBgm() { cc.audioEngine.stopAll(); } } module.exports = Aduio;
import $ from 'jquery'; import _ from 'lodash' import Backgrid from 'backgrid'; import Epoxy from 'igui_root/node_modules/backbone.epoxy/backbone.epoxy'; import Utils from 'igui_root/src/scripts/utils'; var TableBooleanCellView = Backgrid.Cell.extend(Epoxy.View.mixin()); TableBooleanCellView = Utils.extend.call(TableBooleanCellView, { className: 'radio-cell', render: function() { this.$el.empty(); var name = this.column.get('name'); var disabled = this.column.get('disabled') var $elem = $(`<label class="black-checkbox" ><input type="checkbox" data-bind="checked:${name}" ${disabled ? 'disabled' : ''}/><span></span></label>`); this.$el.append($elem); this.delegateEvents(); this.applyBindings(); return this; } }, { _optionsToAttach: ['rowViewCid'] }); export default TableBooleanCellView;
import React, { useState, useEffect } from "react"; import "./weatherinfo.css"; function WeatherInfo({ weatherInfo }) { const data = weatherInfo; const [info, setInfo] = useState(); const [hide, setHide] = useState("block"); const handelClick = () => { setHide("none"); }; useEffect(() => { setInfo(data); }, [data]); return ( <div className="weather-info" style={{ display: hide }}> <span className="close" onClick={handelClick}> x </span> <div className="weather-card"> {info && info["daily"].map((item, index) => { return index > 0 ? ( <div className="forecast-day" key={index}> <h5> {new Date(item.dt * 1000).toLocaleDateString("en", { weekday: "long", })} </h5> <div> <div className="weather-mood"> <img src={`${process.env.REACT_APP_IMAGE_URL}${item.weather[0].icon}.png`} /> <small> {item.weather[0].description} </small> </div> </div> <div className="forecast-day--temp"> <b> {item.temp.day.toFixed(0).toString().slice(0, 2)}</b> <sup>°C</sup> </div> </div> ) : null; })} </div> </div> ); } export default WeatherInfo;
// 全局变量,回头存到utils/config.js中 const ddBIKey = 'a62c8307891df356' // 接口秘钥 const DD_BI_API = 'http://testdataback.dangdang.com/miniprogram.php' // 测试环境 // const DD_BI_API = 'https://databack.dangdang.com/miniprogram.php' // 正式环境 !function (envObj, func) { if ("object" == typeof exports && "undefined" != typeof module) { module.exports = func() } else { if ("function" == typeof define && define.amd) { define(func) } else { envObj.DdBI = func() } } } (this, function () { // 初始化执行队列及队列方法 function queueFunc () { this.concurrency = 4 // 当前执行promise对象的数量 this.queue = [] // 等待队列 this.tasks = [] // 任务队列 this.activeCount = 0 // promise计数 var that = this // 当前对象 // 压入任务队列方法 this.push = function (promise) { this.tasks.push(new Promise(function (resolve, reject) { var ajax = function () { that.activeCount++ promise().then(function (n) { resolve(n) }).then(function () { that.next() }) } // 如果小于4个的请求,直接请求接口,否则加入到执行队列中 if (that.activeCount < that.concurrency) { ajax() } else { that.queue.push(ajax) } })) } // 执行全部任务方法 this.all = function () { return Promise.all(this.tasks) } // 将执行完的任务清除出等待队列并执行 this.next = function () { that.activeCount-- // 如果队列中的请求多于1个,则pull出第一个并执行 if (that.queue.length > 0) { that.queue.shift()() } } } // 大数据埋点队列 function ddBIQueueFunc () { this.request = [] // 请求队列,临时破放请求 this.updata = false // this.push = function (promisen) { // 当请求队列中有大于8个的请求时,去执行一次自动生成openid的操作,不知是为什么! if (this.request.length >= 8 && !this.updata) { this.updata = true } // 当请求队列大于10个的时候,则把第一个丢弃,可能是因为小程序规定只能有10个并发的原因 if (this.request.length >= 10) { this.request.shift() this.request.push(promise) } else { this.request.push(promise) } } // 合并执行队列 this.concat = function () { this.request.map(function (promise) { wx.Queue.push(promise) }) this.request = [] // 合并完后清空请求队列 } } // 大数据对象 function ddBIStat (obj) { this.app = obj } // pages的onLoad触发事件 function pageLoadEvent (params) { addDdBIQueue(params) } // page的onShow触发事件 function pageShowEvent() { sn = this.route lifeMD("page", "show") rn = false } // page的onShareAppMessage触发事件 function pageShareAppMessgeEvent (shareParams) { isClickShare = true var t = urlParams2Obj(shareParams.path), e = {} // 保存阿拉丁的ald_share_src参数 for (var o in wsr.query) { if ("ald_share_src" === o) { e[o] = wsr.query[o] } } var r = "" if (shareParams.path.indexOf("?") == -1) { r = shareParams.path + "?" } else { shareParams.path.substr(0, shareParams.path.indexOf("?")) + "?" } if ("" !== t) { for (var o in t) { e[o] = t[o] } } if (e.ald_share_src) { if (e.ald_share_src.indexOf(getAldUuid) == -1 && e.ald_share_src.length < 200) { e.ald_share_src = e.ald_share_src + "," + getAldUuid } else { e.ald_share_src = getAldUuid } } for (var i in e) { if (i.indexOf("ald") == -1) { r += i + "=" + e[i] + "&" } } shareParams.path = r + "ald_share_src=" + e.ald_share_src eventMD("event", "ald_share_status", shareParams) return shareParams } // 生成随机udid function getRandomUuid () { function randomPart () { return Math.floor(65536 * (1 + Math.random())).toString(16).substring(1) } return randomPart() + randomPart() + randomPart() + randomPart() + randomPart() + randomPart() + randomPart() + randomPart() } // 将埋点请求压入执行队列 const md5 = require('./md5') function addDdBIQueue (params) { let ajax = () => { return new Promise(function(reslove, reject) { params.time = new Date().getTime() // 收集时间 毫秒级13位时间戳(new Date().getTime()) params.permanentid = wx.getStorageSync('permanent_id') || '' // 个人用户标识 params.udid = wx.getStorageSync('udid') || '' // 设备标识 params.unionid = wx.getStorageSync('my_unionid') || '' // 渠道ID 推广或广告 params.code = md5(params.time + ddBIKey + params.permanentid) // token验证 生成规则:code=md5(收集时间戳 + 密钥 + permanentid) params.wechat_user = '' // 微信用户信息 wx.getSystemInfo({ success: res => { if (wx.getSetting) { wx.getSetting({ success: res => { if (res && res.authSetting && res.authSetting['scope.userInfo']) { wx.getUserInfo({ success: res => { params.wechat_user = res.userInfo.nickName }, }) } }, }) } }, }) params.url = '' // 当前页面url const pages = getCurrentPages() // 获取加载的页面 const currentPage = pages[pages.length-1] // 获取当前页面的对象 const options = currentPage.options // 如果要获取url中所带的参数可以查看options params.url = currentPage.route // 当前页面url let urlParams = '' let andFlag = false for (let i in options) { if (andFlag) { urlParams += '&' } else { urlParams = true } urlParams += i + '=' + options[i] } if (urlParams) { params.url += '?' + urlParams } // 请求 wx.request({ url: DD_BI_API, data: params, method: "POST", success: res => reslove(res), fail: err => reslove(err), }) }) } wx.Queue.push(ajax) // 加入任务队列 } // 拷贝传参对象 function copyParams () { var temp = {} for (var i in params) { temp[i] = params[i] } return temp } // 得到用户头像文件名 function getAvatarFileName (avatarArr) { for (var t = "", e = 0; e < avatarArr.length; e++) { avatarArr[e].length > t.length && (t = avatarArr[e]) } return t } // 生成当前大于现在的随机时间戳 function getRandomTimeStamp() { return "" + Date.now() + Math.floor(1e7 * Math.random()) } // 过滤参数为rawData及errMsg字段 function filterObject (obj) { var t = {} for (var e in obj) { if ("rawData" != e && "errMsg" != e) { t[e] = obj[e] } } return t } // 路径参数生成对象 function urlParams2Obj (url) { if (url.indexOf("?") == -1) { return "" } var obj = {} url.split("?")[1].split("&").forEach(function (v) { var paramsArr = v.split("=") obj[paramsArr[0]] = paramsArr[i] }) return obj } // 判断传入参数的二级是否还为对象 function isDeepObject (obj) { for (var t in obj) { if ("object" == typeof obj[t] && null !== obj[t]) { return true } } return false } // 自定义埋点 function customEvent (ev, evName) { var e = copyParams() e.ev = ev e.life = evName e.ec = errorCount e.dr = Date.now() - currentRandomTimeStamp if (X) { e.qr = X e.sr = X } if (F) { e.usr = F } addDdBIQueue(e) } // 生命周期函数埋点 function lifeMD (ev, life) { var e = copyParams() // 拷贝传参 e.ev = ev // 发起事件 e.life = life // 触发的生命周期事件 e.pp = sn e.pc = an e.dr = Date.now() - currentRandomTimeStamp if (isClickShare) { e.so = 1 isClickShare = false } if (pageLoadParams && "{}" != JSON.stringify(pageLoadParams)) { e.ag = pageLoadParams } if (X) { e.qr = X e.sr = X } if (F) { e.usr = F } if (rn) { e.ps = 1 } if (!on) { cn = sn on = true e.ifp = on e.fp = sn } addDdBIQueue(e) } // 事件埋点 function eventMD (ev, evName, params) { var obj = copyParams() obj.ev = ev // 事件名称 obj.tp = evName // 事件说明 obj.dr = Date.now() - currentRandomTimeStamp if (params) { obj.ct = params } addDdBIQueue(obj) } // 劫持小程序原生事件(重要) function hijackEvent (that, evName, func) { if (that[evName]) { // 如果有原生事件,则在之前插入埋点事件 var originalFunc = that[evName] that[evName] = function (params) { func.call(this, params, evName) originalFunc.call(this, params) } } else { // 没有原生事件,则直接执行埋点事件 that[evName] = function (params) { func.call(this, params, evName) } } } // 劫持page级事件 function hijackPageEvent (that) { var t = {} for (var e in that) { if ("onLoad" !== e) { t[e] = that[e] } } t.onLoad = function (params) { pageLoadEvent.call(this, params) if ("function" == typeof that.onLoad) { that.onLoad.call(this, params) } } return t } if (void 0 === wx.Queue) { wx.Queue = new queueFunc wx.Queue.all() } var client = "7.3.0", // 阿拉丁版本 domain = "https://log.aldwx.com/", // 埋点请求的域名 b = "wx", // 获取当前小程序的appId getMiniAppId = function() { // void 0 返回 undefined // return void 0 === wx.getAccountInfoSync ? "" : wx.getAccountInfoSync().miniProgram.appId.split("").map(function (n) { // return n.charCodeAt(0) + 9 // }).join("-") return "" } (), timeStamp = getRandomTimeStamp(), appLaunchRandomTimeStamp = "", // onLaunch时生成的大于当前的随机时间戳 currentRandomTimeStamp = 0, // 大于当前的随机时间戳 currentTimeStamp = 0, // 当前时间戳 sessionId = "", // 获取openid getOpenId = function () { var openId = "" try { openId = wx.getStorageSync("ddBIstat_op") } catch (e) {} return openId } (), userAvatar = "", // 用户头像 sort = 0, // 事件序号,从0开始递增 wsr = "", // 进入页面时的页面信息,例:{"scene":1001,"path":"pages/index/index","query":{},"referrerInfo":{}} ifo = "", // 参数ifo到值,不知道是什么意思 // 获取阿拉丁uuid getAldUuid = function () { var uuid = "" try { uuid = wx.getStorageSync("ddBIstat_uuid") } catch(e) { uuid = "uuid_getstoragesync" } if (uuid) { ifo = false } else { uuid = getRandomUuid() // 生成uuid try { wx.setStorageSync("ddBIstat_uuid", uuid) ifo = true } catch (e) { wx.setStorageSync("ddBIstat_uuid", "uuid_getstoragesync") } } return uuid } (), F = "", // 阿拉丁相关参数,无用 X = "", // 阿拉丁相关参数,无用 Y = "", // 阿拉丁相关参数,无用 errorCount = 0, // app onError错误计数 nn = "", tn = "", params = {}, // 给接口传的参数对象 on = false, rn = false, // 阿拉丁相关参数,无用 sn = "", an = "", pageLoadParams = "", // 页面的onLoad参数 cn = "", fn = true, isClickShare = false, // 是否点击过分享标识 ln = "", // 场景值 ddBIQueue = new ddBIQueueFunc, openId = "" wx.ddBIstat = new ddBIStat("") try { var systemInfo = wx.getSystemInfoSync() params.br = systemInfo.brand params.pm = systemInfo.model params.pr = systemInfo.pixelRatio params.ww = systemInfo.windowWidth params.wh = systemInfo.windowHeight params.lang = systemInfo.language params.wv = systemInfo.version params.wvv = systemInfo.platform params.wsdk = systemInfo.SDKVersion params.sv = systemInfo.system } catch (e) {} wx.getNetworkType({ success: function (res) { params.nt = res.networkType } }) wx.getSetting({ success: function (res) { if (res.authSetting["scope.userLocation"]) { wx.getLocation({ type: "wgs84", success: function (r) { params.lat = r.latitude params.lng = r.longitude params.spd = r.speed }, }) } } }) // 自定义埋点发送事件 ddBIStat.prototype.sendEvent = function (evName, params) { if ("" !== evName && "string" == typeof evName && evName.length <= 255) { if ("string" == typeof params && params.length <= 255) { eventMD("event", evName, params) } else if ("object" == typeof params) { if (JSON.stringify(params).length >= 255) { return void console.error("自定义事件参数不能超过255个字符") } if (isDeepObject(params)) { return void console.error("事件参数,参数内部只支持Number,String等类型,请参考接入文档") } for (var e in params) { "number" == typeof params[e] && (params[e] = params[e] + "s##") } eventMD("event", evName, JSON.stringify(params)) } else { void 0 === params ? eventMD("event", evName, false) : console.error("事件参数必须为String,Object类型,且参数长度不能超过255个字符") } } else { console.error("事件名称必须为String类型且不能超过255个字符") } } // 发送session方法 ddBIStat.prototype.sendSession = function (sessionid) { if ("" === sessionid || !sessionid) { return void console.error("请传入从后台获取的session_key") } sessionId = sessionid var t = copyParams() t.tp = "session" t.ct = "session" t.ev = "event" if ("" === tn) { wx.getSetting({ success: function (res) { if (res.authSetting["scope.userInfo"]) { wx.getUserInfo({ success: function (r) { t.ufo = filterObject(r) userAvatar = getAvatarFileName(r.userInfo.avatarUrl.split("/")) if ("" !== nn) { t.gid = nn } addDdBIQueue(t) } }) } else { if ("" !== nn) { t.gid = nn addDdBIQueue(t) } } } }) } else { t.ufo = tn if ("" !== nn) { t.gid = nn addDdBIQueue(t) } } } // 发送openid方法 ddBIStat.prototype.sendOpenid = function (openId) { if ("" === openId || !openId || 28 !== openId.length) { return void console.error("openID不能为空") } getOpenId = n wx.setStorageSync("ddBIstat_op", openId) var params = copyParams() params.tp = "openid" params.ev = "event" params.ct = "openid" addDdBIQueue(params) } // 设置openid方法 ddBIStat.prototype.setOpenid = function (openIdFunc) { if ("function" == typeof openIdFunc) { openId = openIdFunc } } // 将阿拉丁埋点事件注入页面对象 return function () { var appObj = App, pageObj = Page, componentObj = Component // 小程序事件 App = function (app) { // hijackEvent(app, "onLaunch", appLaunchEvent) // hijackEvent(app, "onShow", appShowEvent) // hijackEvent(app, "onHide", appHideEvent) // hijackEvent(app, "onError", appErrorEvent) appObj(app) } // 页面事件 Page = function (page) { var e = page.onShareAppMessage hijackEvent(page, "onLoad", pageLoadEvent) // hijackEvent(page, "onUnload", pageUnloadEvent) // hijackEvent(page, "onShow", pageShowEvent) // hijackEvent(page, "onHide", pageHideEvent) // hijackEvent(page, "onReachBottom", pageReachBottomEvent) // hijackEvent(page, "onPullDownRefresh", pagePullDownRefreshEvent) // 分享事件劫持 // if (void 0 !== e && null !== e) { // page.onShareAppMessage = function (params) { // if (void 0 !== e) { // var t = e.call(this, params) // if (void 0 === t) { // t = {} // t.path = sn // } else { // if (void 0 === t.path) { // t.path = sn // } // } // return pageShareAppMessgeEvent(t) // } // } // } pageObj(page) } // 组件事件 Component = function (component) { try { // var t = component.methods.onShareAppMessage // hijackEvent(component.methods, "onLoad", pageLoadEvent) // hijackEvent(component.methods, "onUnload", pageUnloadEvent) // hijackEvent(component.methods, "onShow", pageShowEvent) // hijackEvent(component.methods, "onHide", pageHideEvent) // hijackEvent(component.methods, "onReachBottom", pageReachBottomEvent) // hijackEvent(component.methods, "onPullDownRefresh", pagePullDownRefreshEvent) // if (void 0 !== t && null !== t) { // component.methods.onShareAppMessage = function (params) { // if (void 0 !== t) { // var e = t.call(this, params) // if (void 0 === e) { // e = {} // e.path = sn // } else { // if (void 0 === e.path) { // e.path = sn // } // } // return pageShareAppMessgeEvent(e) // } // } // } componentObj(component) } catch (err) { componentObj(component) } } } () })
import { getSheet } from '../get-sheet'; describe('getSheet', () => { it('regression', () => { const target = getSheet(); expect(target.nodeType).toEqual(3); }); it('custom target', () => { const custom = document.createElement('div'); const sheet = getSheet(custom); expect(sheet.nodeType).toEqual(3); expect(sheet.parentElement.nodeType).toEqual(1); expect(sheet.parentElement.getAttribute('id')).toEqual('_goober'); }); it('reuse sheet', () => { const custom = document.createElement('div'); const sheet = getSheet(custom); const second = getSheet(custom); expect(sheet === second).toBeTruthy(); }); it('server side', () => { const bkp = global.document; delete global.document; expect(() => getSheet()).not.toThrow(); global.document = bkp; }); it('server side with custom collector', () => { const bkp = global.document; const win = global.window; delete global.document; delete global.window; const collector = { data: '' }; expect(collector === getSheet(collector)).toBeTruthy(); global.document = bkp; global.window = win; }); });
import { action, computed, thunk } from 'easy-peasy' import _get from 'lodash/get' import _set from 'lodash/set' import HmacSHA256 from 'crypto-js/hmac-sha256' import CryptoJS from 'crypto-js' import { postOrder } from 'Services/order' import Axios from 'axios' import { updateUser, deleteCart } from 'Services/auth' const cart = { cart: [], loading: false, count: computed((state) => state.cart.length), subTotal: computed((state) => { const data = state.cart return data .reduce((acc, cur) => acc + cur.price * cur.quantity, 0) .toFixed(2) }), total: computed((state) => { return state.subTotal }), setLoading: action((state, payload) => { state.loading = payload }), setCart: action((state, payload) => { state.cart = payload state.loading = false }), // getCart: action((state) => { // state.cart = [ // ...state.cart, // { ...JSON.parse(localStorage.getItem('cartItem')) }, // ] // console.log('state.cart :>> ', state.cart) // }), addCart: thunk(async (actions, payload, { getState }) => { const data = getState().cart actions.setLoading(true) try { for (let i = 0; i < data.length; i += 1) { if (payload.id === data[i].id && payload.color === data[i].color) { let count = _get(data, `[${i}].quantity`, 0) count += payload.quantity const dataAddQuantity = _set(data, `[${i}].quantity`, count) // getState().cart = dataAddQuantity actions.setCart(dataAddQuantity) // localStorage.setItem('cartItem', JSON.stringify(payload)) return } } getState().cart = [...data, payload] // console.log('payload :>> ', payload); await updateUser(payload, payload.id) // localStorage.setItem('cartItem', JSON.stringify(payload)) } catch (error) { actions.setCart([]) } }), setAddQuantity: thunk(async (actions, payload, { getState }) => { const data = getState().cart for (let i = 0; i < data.length; i += 1) { if (payload.id === data[i].id && payload.color === data[i].color) { let count = _get(data, `[${i}].quantity`, 0) // if (state.cart[i].quantity < payload.quantity) { if (payload.quantity > data[i].quantity) { const quantity = payload.quantity - data[i].quantity count += quantity } else { const quantity = data[i].quantity - payload.quantity count -= quantity } const dataAddQuantity = _set(data, `[${i}].quantity`, count) actions.setCart(dataAddQuantity) // localStorage.setItem('cartItem', JSON.stringify(payload)) return } } getState().cart = [...data, payload] await updateUser(payload, payload.userId) // localStorage.setItem('cartItem', JSON.stringify(payload)) }), removeProduct: thunk(async (actions, id) => { await deleteCart(id) // state.cart = state.cart.filter((item) => item.id !== payload.id) // localStorage.removeItem('cartItem') }), checkoutCart: thunk( async ( actions, { reciver, payment, total, fnCallback }, { getState, getStoreState } ) => { const user = _get(getStoreState(), 'auth.user', {}) const products = _get(getState(), 'cart', {}) const data = { products, user, reciver, payment, total, status: 'Processing', create_at: Date.now(), code: Date.now(), } try { // actions.setLoading(true) if (payment === 'momo') { const requestId = data.create_at const orderId = data.code const totalCart = 100000 const returnUrl = 'http://localhost:8000/' const secretkey = '9JHO4c3lgPjkgibhAtM8wV8tvlxPAzp0' const datatest = `partnerCode=MOMOAWIY20200512&accessKey=j786WfkBxCqtZzOz&requestId=${requestId}&amount=${totalCart}&orderId=MM${orderId}&orderInfo=Thanh Toán Qua Momo&returnUrl=${returnUrl}&notifyUrl=https://momo.vn&extraData=merchantName=FaceMask Payment Momo` const dataTest256 = HmacSHA256(datatest, secretkey).toString( CryptoJS.enc.Hex ) const dataRequestMomo = { partnerCode: 'MOMOAWIY20200512', accessKey: 'j786WfkBxCqtZzOz', requestType: 'captureMoMoWallet', requestId: `${requestId}`, amount: `${totalCart}`, orderId: `MM${requestId}`, orderInfo: 'Thanh Toán Qua Momo', returnUrl: `${returnUrl}`, notifyUrl: 'https://momo.vn', extraData: 'merchantName=FaceMask Payment Momo', signature: dataTest256, } const myBodyJsonString = JSON.stringify(dataRequestMomo) const dataResponseMoMo = await Axios.post( 'https://test-payment.momo.vn/gw_payment/transactionProcessor', myBodyJsonString ) if (dataResponseMoMo.data.message === 'Success') { const url = _get(dataResponseMoMo, 'data.payUrl', '') window.open(url) } } await postOrder(data) if (fnCallback) { fnCallback(true) // actions.setLoading(false) } } catch (error) { console.log(error) fnCallback(false) } } ), } export default cart
const animals = [{ image: '/images/owl1.jpg', type: 'owl', name: 'Mr. Beige', description: 'The eastern barn owl (Tyto javanica) is usually considered a subspecies group and together with the American barn owl group, the western barn owl group, and sometimes the Andaman masked owl make up the barn owl. The cosmopolitan barn owl is recognized by most taxonomic authorities. A few (including the International Ornithologists\' Union) separate them into distinct species, as is done here. The eastern barn owl is native to southeastern Asia and Australasia.', animalId: 'owl1' }, { image: '/images/owl2.jpg', type: 'owl', name: 'Mr. Burrow', description: 'The burrowing owl (Athene cunicularia) is a small, long-legged owl found throughout open landscapes of North and South America. Burrowing owls can be found in grasslands, rangelands, agricultural areas, deserts, or any other open dry area with low vegetation.[2] They nest and roost in burrows, such as those excavated by prairie dogs (Cynomys spp.). Unlike most owls, burrowing owls are often active during the day, although they tend to avoid the midday heat. Like many other kinds of owls, though, burrowing owls do most of their hunting from dusk until dawn, when they can use their night vision and hearing to their advantage. Living in open grasslands as opposed to forests, the burrowing owl has developed longer legs that enable it to sprint, as well as fly, when hunting.', animalId: 'owl2' }, { image: '/images/owl3.jpg', type: 'owl', name: 'Mr. Short-Ears', description: 'The short-eared owl (Asio flammeus) is a species of typical owl (family Strigidae). Owls belonging to genus Asio are known as the eared owls, as they have tufts of feathers resembling mammalian ears. These "ear" tufts may or may not be visible. Asio flammeus will display its tufts when in a defensive pose, although its very short tufts are usually not visible. The short-eared owl is found in open country and grasslands. The genus name Asio is a type of eared owl, and flammeus means "flame-coloured"', animalId: 'owl3' }, { image: '/images/owl4.jpg', type: 'owl', name: 'Mr. Horns', description: 'The great horned owl (Bubo virginianus), also known as the tiger owl (originally derived from early naturalists description as the winged tiger or tiger of the air) or the hoot owl, is a large owl native to the Americas. It is an extremely adaptable bird with a vast range and is the most widely distributed true owl in the Americas. Its primary diet is rabbits and hares, rats and mice, and voles, although it freely hunts any animal it can overtake, including rodents and other small mammals, larger mid-sized mammals, birds, reptiles, amphibians, and invertebrates.', animalId: 'owl4' }, { image: '/images/turtle1.jpg', type: 'turtle', name: 'Chelonia Mydas', description: 'The green sea turtle (Chelonia mydas), also known as the green turtle, black (sea) turtle or Pacific green turtle,[3] is a species of large sea turtle of the family Cheloniidae. It is the only species in the genus Chelonia.[4] Its range extends throughout tropical and subtropical seas around the world, with two distinct populations in the Atlantic and Pacific Oceans, but it is also found in the Indian Ocean.[5][6] The common name refers to the usually green fat found beneath its carapace, not to the color of its carapace, which is olive to black.', animalId: 'turtle1' }, { image: '/images/turtle2.jpg', type: 'turtle', name: 'Sulcata Tortoise', description: 'The African spurred tortoise (Centrochelys sulcata), also called the sulcata tortoise, is a species of tortoise inhabiting the southern edge of the Sahara desert in Africa. It is the third-largest species of tortoise in the world, the largest species of mainland tortoise, and the only extant species in the genus Centrochelys.', animalId: 'turtle2' }, { image: '/images/turtle3.jpg', type: 'turtle', name: 'Red-Eared Slider', description: 'The red-eared slider (Trachemys scripta elegans), also known as the red-eared terrapin, red-eared slider turtle, red-eared turtle, slider turtle, and water slider turtle, is a semiaquatic turtle belonging to the family Emydidae. It is a subspecies of the pond slider. It is the most popular pet turtle in the United States and is also popular as a pet across the rest of the world.[2] Because of this, they are the most commonly traded turtle in the world.[3] Red-eared sliders are native to the southern United States and northern Mexico, but have become established in other places because of pet releases, and have become an invasive species in many areas where they outcompete native species. The red-eared slider is included in the list of the world\'s 100 most invasive species[4] published by the IUCN.', animalId: 'turtle3' }, { image: '/images/turtle4.jpg', type: 'turtle', name: 'Pleurodira', description: 'The red-eared slider (Trachemys scripta elegans), also known as the red-eared terrapin, red-eared slider turtle, red-eared turtle, slider turtle, and water slider turtle, is a semiaquatic turtle belonging to the family Emydidae. It is a subspecies of the pond slider. It is the most popular pet turtle in the United States and is also popular as a pet across the rest of the world.[2] Because of this, they are the most commonly traded turtle in the world.[3] Red-eared sliders are native to the southern United States and northern Mexico, but have become established in other places because of pet releases, and have become an invasive species in many areas where they outcompete native species. The red-eared slider is included in the list of the world\'s 100 most invasive species[4] published by the IUCN.', animalId: 'turtle4' }, { image: '/images/cat1.jpg', type: 'felidae', name: 'Ocelot', description: 'The ocelot (/ˈɒsəlɒt/; Leopardus pardalis) is a small wild cat native to the southwestern United States, Mexico, and Central and South America. This medium-sized cat is characterized by solid black spots and streaks on its coat, round ears, and white neck and undersides. It weighs between 8 and 15.5 kg (18 and 34 lb) and reaches 40–50 cm (15 1⁄2–19 1⁄2 in) at the shoulders. It was first described by Carl Linnaeus in 1758. Two subspecies are recognized: L. p. pardalis and L. p. mitis. Typically active during twilight and at night, the ocelot tends to be solitary and territorial. It is efficient at climbing, leaping and swimming.', animalId: 'cat1' }, { image: '/images/cat2.jpg', type: 'felidae', name: 'Canada Lynx', description: 'The Canada lynx (Lynx canadensis) is a medium-sized North American cat that ranges across Alaska, Canada and many of the contiguous United States. It is characterized by its long, dense fur, triangular ears with black tufts at the tips, and broad, snowshoe-like paws. Similar to the bobcat (L. rufus), the hindlimbs are longer than the forelimbs, so that the back slopes downward to the front. The Canada lynx stands 48–56 cm (19–22 in) tall at the shoulder and weighs between 5 and 17 kg (11 and 37 lb). The lynx is a good swimmer and an agile climber. The Canada lynx was first described by Robert Kerr in 1792. Three subspecies have been proposed, but their validity is doubted.', animalId: 'cat2' }, { image: '/images/cat3.jpg', type: 'felidae', name: 'Fishing Cat', description: 'The fishing cat (Prionailurus viverrinus) is a medium-sized wild cat of South and Southeast Asia. Since 2016, it is listed as Vulnerable on the IUCN Red List. Fishing cat populations are threatened by destruction of wetlands and have declined severely over the last decade. The fishing cat lives foremost in the vicinity of wetlands, along rivers, streams, oxbow lakes, in swamps, and mangroves. The fishing cat is the state animal of West Bengal.', animalId: 'cat3' }, { image: '/images/cat4.jpg', type: 'felidae', name: 'Black Panther', description: 'A black panther is the melanistic colour variant of any Panthera, particularly of the leopard (P. pardus) in Asia and Africa, and the jaguar (P. onca) in the Americas. Black panthers of both species have excess black pigments, but their typical spotted markings are also present. Melanism in the leopard is caused by a recessive allele, and in the jaguar by a dominant allele.', animalId: 'cat4' } ] export default animals
var svgLogo = document.querySelector('.svgLogo path.st0'); var svgLogo1 = document.querySelector('.svgLogo path.st1'); var svgLogo2 = document.querySelector('.svgLogo path.st2'); var svgLogo3 = document.querySelector('.svgLogo path.st3'); var svgLogo4 = document.querySelector('.svgLogo path.st4'); var svgLogo5 = document.querySelector('.svgLogo path.st5'); var svgLogo6 = document.querySelector('.svgLogo polygon.p0'); var svgLogo7 = document.querySelector('.svgLogo text.t1'); var svgLogo5 = document.querySelector('.svgLogo path.st5'); var svgLogoAnimation = anime.timeline(); svgLogoAnimation.add({ targets: svgLogo, strokeDashoffset:[anime.setDashoffset, 0], duration: 2000, easing: 'easeOutSine', direction: 'alternate', loop: true, delay: 1000 }); svgLogoAnimation.add({ targets: svgLogo1, strokeDashoffset:[anime.setDashoffset, 0], duration: 2000, easing: 'easeOutSine', direction: 'alternate', loop: true });svgLogoAnimation.add({ targets: svgLogo2, strokeDashoffset:[anime.setDashoffset, 0], duration: 2000, easing: 'easeOutSine' });svgLogoAnimation.add({ targets: svgLogo3, strokeDashoffset:[anime.setDashoffset, 0], duration: 2000, easing: 'easeOutSine', direction: 'alternate', loop: true });svgLogoAnimation.add({ targets: svgLogo4, strokeDashoffset:[anime.setDashoffset, 0], duration: 2000, easing: 'easeOutSine', direction: 'alternate', loop: true }); svgLogoAnimation.add({ targets: svgLogo5, strokeDashoffset:[anime.setDashoffset, 0], duration: 2000, easing: 'easeOutSine', direction: 'alternate', loop: true }); svgLogoAnimation.add({ targets: svgLogo6, opacity: [0,1], direction: 'alternate', loop: true }); svgLogoAnimation.add({ targets: svgLogo7, opacity: [0,1], duration: 2000, easing: 'easeOutSine', direction: 'alternate', loop: true }); //Open-Close Snow Effect var snow = document.querySelector('.snowClick'); var snowDisplay = document.querySelectorAll('.snow'); snow.onclick = function(){ snowDisplay[0].classList.toggle('snow1'); }; //Mute Sound var speaker = document.querySelector('.speaker'); var audio = document.querySelector('.audio'); speaker.onclick = function(){ if(audio.muted == false){ audio.muted = true; } else{ audio.muted = false; } }; // Feb 5, 2019 00:00:00 //DAQ Counntdown web 2019 var countDownDate = new Date("Jan 1, 2020 00:00:00").getTime(); var x = setInterval(function(){ var now = new Date().getTime(); var distance = countDownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); document.getElementById("day").innerHTML = days; document.getElementById("hours").innerHTML = hours; document.getElementById("minutes").innerHTML = minutes; document.getElementById("senconds").innerHTML = seconds; document.getElementById("day1").innerHTML = "Days"; document.getElementById("hours1").innerHTML = "Hours"; document.getElementById("minutes1").innerHTML = "Minutes"; document.getElementById("senconds1").innerHTML = "Seconds"; if (distance < 0) { clearInterval(x); document.getElementById("day").innerHTML = "2"; document.getElementById("hours").innerHTML = "0"; document.getElementById("minutes").innerHTML = "1"; document.getElementById("senconds").innerHTML = "9"; //Clear info document.getElementById("day1").innerHTML = ""; document.getElementById("hours1").innerHTML = ""; document.getElementById("minutes1").innerHTML = ""; document.getElementById("senconds1").innerHTML = ""; } }); //Animejs Click var c = document.getElementById("c"); var ctx = c.getContext("2d"); var cH; var cW; var bgColor = "#FF6138"; var animations = []; var circles = []; var colorPicker = (function() { var colors = ["#FF6138", "#FFBE53", "#2980B9", "#282741"]; var index = 0; function next() { index = index++ < colors.length-1 ? index : 0; return colors[index]; } function current() { return colors[index] } return { next: next, current: current } })(); function removeAnimation(animation) { var index = animations.indexOf(animation); if (index > -1) animations.splice(index, 1); } function calcPageFillRadius(x, y) { var l = Math.max(x - 0, cW - x); var h = Math.max(y - 0, cH - y); return Math.sqrt(Math.pow(l, 2) + Math.pow(h, 2)); } function addClickListeners() { document.addEventListener("touchstart", handleEvent); document.addEventListener("mousedown", handleEvent); }; function handleEvent(e) { if (e.touches) { e.preventDefault(); e = e.touches[0]; } var currentColor = colorPicker.current(); var nextColor = colorPicker.next(); var targetR = calcPageFillRadius(e.pageX, e.pageY); var rippleSize = Math.min(200, (cW * .4)); var minCoverDuration = 750; var pageFill = new Circle({ x: e.pageX, y: e.pageY, r: 0, fill: nextColor }); var fillAnimation = anime({ targets: pageFill, r: targetR, duration: Math.max(targetR / 2 , minCoverDuration ), easing: "easeOutQuart", complete: function(){ bgColor = pageFill.fill; removeAnimation(fillAnimation); } }); var ripple = new Circle({ x: e.pageX, y: e.pageY, r: 0, fill: currentColor, stroke: { width: 3, color: currentColor }, opacity: 1 }); var rippleAnimation = anime({ targets: ripple, r: rippleSize, opacity: 0, easing: "easeOutExpo", duration: 900, complete: removeAnimation }); var particles = []; for (var i=0; i<32; i++) { var particle = new Circle({ x: e.pageX, y: e.pageY, fill: currentColor, r: anime.random(24, 48) }) particles.push(particle); } var particlesAnimation = anime({ targets: particles, x: function(particle){ return particle.x + anime.random(rippleSize, -rippleSize); }, y: function(particle){ return particle.y + anime.random(rippleSize * 1.15, -rippleSize * 1.15); }, r: 0, easing: "easeOutExpo", duration: anime.random(1000,1300), complete: removeAnimation }); animations.push(fillAnimation, rippleAnimation, particlesAnimation); } function extend(a, b){ for(var key in b) { if(b.hasOwnProperty(key)) { a[key] = b[key]; } } return a; } var Circle = function(opts) { extend(this, opts); } Circle.prototype.draw = function() { ctx.globalAlpha = this.opacity || 1; ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false); if (this.stroke) { ctx.strokeStyle = this.stroke.color; ctx.lineWidth = this.stroke.width; ctx.stroke(); } if (this.fill) { ctx.fillStyle = this.fill; ctx.fill(); } ctx.closePath(); ctx.globalAlpha = 1; } var animate = anime({ duration: Infinity, update: function() { ctx.fillStyle = bgColor; ctx.fillRect(0, 0, cW, cH); animations.forEach(function(anim) { anim.animatables.forEach(function(animatable) { animatable.target.draw(); }); }); } }); var resizeCanvas = function() { cW = window.innerWidth; cH = window.innerHeight; c.width = cW * devicePixelRatio; c.height = cH * devicePixelRatio; ctx.scale(devicePixelRatio, devicePixelRatio); }; (function init() { resizeCanvas(); if (window.CP) { // CodePen's loop detection was causin' problems // and I have no idea why, so... window.CP.PenTimer.MAX_TIME_IN_LOOP_WO_EXIT = 6000; } window.addEventListener("resize", resizeCanvas); addClickListeners(); if (!!window.location.pathname.match(/fullcpgrid/)) { startFauxClicking(); } handleInactiveUser(); })(); function handleInactiveUser() { var inactive = setTimeout(function(){ fauxClick(cW/2, cH/2); }, 2000); function clearInactiveTimeout() { clearTimeout(inactive); document.removeEventListener("mousedown", clearInactiveTimeout); document.removeEventListener("touchstart", clearInactiveTimeout); } document.addEventListener("mousedown", clearInactiveTimeout); document.addEventListener("touchstart", clearInactiveTimeout); } function startFauxClicking() { setTimeout(function(){ fauxClick(anime.random( cW * .2, cW * .8), anime.random(cH * .2, cH * .8)); startFauxClicking(); }, anime.random(200, 900)); } function fauxClick(x, y) { var fauxClick = new Event("mousedown"); fauxClick.pageX = x; fauxClick.pageY = y; document.dispatchEvent(fauxClick); } //firework // window.human = false; // var canvasEl = document.querySelector('.fireworks'); // var ctx = canvasEl.getContext('2d'); // var numberOfParticules = 30; // var pointerX = 0; // var pointerY = 0; // var tap = ('ontouchstart' in window || navigator.msMaxTouchPoints) ? 'touchstart' : 'mousedown'; // var colors = ['#FF1461', '#18FF92', '#5A87FF', '#FBF38C']; // function setCanvasSize() { // canvasEl.width = window.innerWidth * 2; // canvasEl.height = window.innerHeight * 2; // canvasEl.style.width = window.innerWidth + 'px'; // canvasEl.style.height = window.innerHeight + 'px'; // canvasEl.getContext('2d').scale(2, 2); // } // function updateCoords(e) { // pointerX = e.clientX || e.touches[0].clientX; // pointerY = e.clientY || e.touches[0].clientY; // } // function setParticuleDirection(p) { // var angle = anime.random(0, 360) * Math.PI / 180; // var value = anime.random(50, 180); // var radius = [-1, 1][anime.random(0, 1)] * value; // return { // x: p.x + radius * Math.cos(angle), // y: p.y + radius * Math.sin(angle) // } // } // function createParticule(x,y) { // var p = {}; // p.x = x; // p.y = y; // p.color = colors[anime.random(0, colors.length - 1)]; // p.radius = anime.random(16, 32); // p.endPos = setParticuleDirection(p); // p.draw = function() { // ctx.beginPath(); // ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, true); // ctx.fillStyle = p.color; // ctx.fill(); // } // return p; // } // function createCircle(x,y) { // var p = {}; // p.x = x; // p.y = y; // p.color = '#FFF'; // p.radius = 0.1; // p.alpha = .5; // p.lineWidth = 6; // p.draw = function() { // ctx.globalAlpha = p.alpha; // ctx.beginPath(); // ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, true); // ctx.lineWidth = p.lineWidth; // ctx.strokeStyle = p.color; // ctx.stroke(); // ctx.globalAlpha = 1; // } // return p; // } // function renderParticule(anim) { // for (var i = 0; i < anim.animatables.length; i++) { // anim.animatables[i].target.draw(); // } // } // function animateParticules(x, y) { // var circle = createCircle(x, y); // var particules = []; // for (var i = 0; i < numberOfParticules; i++) { // particules.push(createParticule(x, y)); // } // anime.timeline().add({ // targets: particules, // x: function(p) { return p.endPos.x; }, // y: function(p) { return p.endPos.y; }, // radius: 0.1, // duration: anime.random(1200, 1800), // easing: 'easeOutExpo', // update: renderParticule // }) // .add({ // targets: circle, // radius: anime.random(80, 160), // lineWidth: 0, // alpha: { // value: 0, // easing: 'linear', // duration: anime.random(600, 800), // }, // duration: anime.random(1200, 1800), // easing: 'easeOutExpo', // update: renderParticule, // offset: 0 // }); // } // var render = anime({ // duration: Infinity, // update: function() { // ctx.clearRect(0, 0, canvasEl.width, canvasEl.height); // } // }); // document.addEventListener(tap, function(e) { // window.human = true; // render.play(); // updateCoords(e); // animateParticules(pointerX, pointerY); // }, false); // var centerX = window.innerWidth / 2; // var centerY = window.innerHeight / 2; // // function autoClick() { // // if (window.human) return; // // animateParticules( // // anime.random(centerX-50, centerX+50), // // anime.random(centerY-50, centerY+50) // // ); // // anime({duration: 200}).finished.then(autoClick); // // } // // autoClick(); // setCanvasSize(); // window.addEventListener('resize', setCanvasSize, false);
// gulp default const gulp = require("gulp"); const babel = require("gulp-babel"); gulp.task("default", () => gulp .src("jsx-javascript/*.jsx") .pipe( babel({ presets: ["@babel/preset-env", "@babel/preset-react"], }) ) .pipe(gulp.dest("compiled-javascript")) );
const Sequelize = require('sequelize'); const databaseConfig = require('../config/database'); const env = process.env.ENV || 'development'; const config = { ...databaseConfig[env], define: { timestamps: false, underscored: true, }, logging: false, }; module.exports = new Sequelize(config);
export const USER_LOGIN = "USER_LOGIN"; export const USER_LOGOUT = "USER_LOGOUT"; export const SAVE_SUBMITTED_INFO = "SAVE_SUBMITTED_INFO"; export const SAVE_SELECTED_ROOM_INFO = "SAVE_SELECTED_ROOM_INFO"; export const SAVE_RESERVATION_INFO = "SAVE_RESERVATION_INFO"; export const SAVE_AGREEMENT_INFO = "SAVE_AGREEMENT_INFO"; export const SAVE_TRAVEL_PURPOSE_INFO = "SAVE_TRAVEL_PURPOSE_INFO"; export const CLEAR_INFO = "CLEAR_INFO"; export const userLogIn = () => { return { type: USER_LOGIN, }; }; export const userLogOut = () => { return { type: USER_LOGOUT, }; }; export const saveSubmittedInfo = (info) => { // Total Stay Calculation const arrivalDate = new Date(info.arrival); const departureDate = new Date(info.departure); const timeDifference = Math.abs(departureDate - arrivalDate); const dateDifference = Math.ceil(timeDifference / (1000 * 60 * 60 * 24)); const totalStay = dateDifference + 1; return { type: SAVE_SUBMITTED_INFO, payload: { ...info, totalStay: totalStay }, }; }; export const saveSelectedRoomInfo = ( bookingInfo, RoomInfo, roomsNeeded, totalGuests, subTotal ) => { return { type: SAVE_SELECTED_ROOM_INFO, payload: { ...bookingInfo, ...RoomInfo, roomsNeeded: roomsNeeded, totalGuests: totalGuests, subTotal: subTotal, }, }; }; export const saveReservationInfo = (bookingInfo, total) => { return { type: SAVE_SELECTED_ROOM_INFO, payload: { ...bookingInfo, total: total, }, }; }; export const saveAgreementInfo = (bookingInfo) => { return { type: SAVE_SELECTED_ROOM_INFO, payload: { ...bookingInfo, rulesAgreed: true, }, }; }; export const saveTravelPurposeInfo = (bookingInfo, travelPurpose) => { return { type: SAVE_SELECTED_ROOM_INFO, payload: { ...bookingInfo, travelPurpose: travelPurpose, }, }; }; export const clearInfo = () => { return { type: CLEAR_INFO, }; };
import { List } from 'immutable' import SessionRecord from './SessionRecord' import EventRecord from './EventRecord' import Template from './Template' import logger from'../debug' const log = logger('model') class MissingAttributesError extends Error { constructor(record, attributes) { super(`Missing attributes for record ${record}: ${attributes}`) } } class NoMatchingTypeError extends Error { constructor(iterable) { super(`No matching type for ${JSON.stringify(iterable.toJSON())}`) } } function selectType(iterable) { const Type = List.of(SessionRecord, EventRecord, Template).find(Type => { return Type.isType(iterable) }) if (!Type) throw new NoMatchingTypeError(iterable) return Type } export function recordFromIterable(iterable) { const Type = selectType(iterable) return Type.fromIterable(iterable) } export function requireAttributes(record, kwargs, ...attributes) { for (let attr of attributes) { if (!kwargs[attr]) throw new MissingAttributesError(record, attr) } return kwargs }
var config = require('./config'); var prompt = require('./prompt'); module.exports = { getJson: function(url, data, callback) { var self = arguments.callee; // console.log('getting!'); // return; $.ajax({ url: url, dataType: 'json', data: data, crossDomain: true, success: callback, error: function(jqXHR, textStatus, error){ if(textStatus == 'timeout'&&(!document.querySelector('body .shade'))){ prompt({content:'<span style=\'background-image:url("../images/jyhemaiicon09.png");\'></span>请求超时, 点击确定重试!', okCallback: function(){ self(url, data, callback); }, cancelCallback: function(){void(0); } }); }; }, timeout: 30000 }); }, forceRefresh: function(){ var $body = $('body'); var $iframe = $('<iframe src="/favicon.ico"></iframe>'); $iframe.on('load',function() { setTimeout(function() { $iframe.off('load').remove(); }, 0); }).appendTo($body); }, togglePopup: function(options){ var popup = document.querySelector('body .transcationPopup'); var infoWrapper = popup.querySelector('.infoWrapper'); // var shade = document.querySelector('body .ntfShade'); // shade.style.display = 'initial'; if(!options){ popup.style.top = '-4rem'; // shade.style.display = 'none'; setTimeout(function(){ infoWrapper.innerHTML = ''; }, 2000); return; }else{ if(options.type === 'create'){ infoWrapper.innerHTML = ''; popup.firstElementChild.innerHTML = options.title; var $infoElem = $('<div><p></p><p></p></div><div><p></p></div>'); $infoElem.appendTo($(infoWrapper)); popup.querySelector('.infoWrapper div:first-of-type p:first-child').innerHTML = '方向: <span style="color:' + (options.direction?'green':'red') + ';">' + (options.direction?'做空</span>':'做多</span>'); popup.querySelector('.infoWrapper div:first-of-type p:nth-child(2)').innerHTML = '建仓点位: <span style="color:red;">' + (options.openPrice).toFixed(3) + '</span>'; // debugger; popup.querySelector('.infoWrapper div:nth-of-type(2) p:first-child').innerHTML = '建仓时间: ' + (new Date(options.createTime).toLocaleTimeString().replace('GMT+8', '')); }else if (options.type === 'close') { popup.firstElementChild.innerHTML = '&nbsp;'; infoWrapper.innerHTML = '<p>您关注的达人' + ((options.title).toString().trim()) + '刚刚平仓了 快去看看吧!</p>'; } popup.style.top = '1.5rem'; } }, watchPrice: function(elem){ var mo = new MutationObserver(function(MutationRecord){ // console.log(MutationRecord[0], MutationRecord[0]['oldValue']); var newVal = MutationRecord[0]['target']['nodeValue']; var oldVal = MutationRecord[0]['oldValue']; var parent = MutationRecord[0]['target']['parentNode']; parent.style.transition = ''; if (newVal>oldVal){ parent['className'] = 'red'; parent.style.backgroundColor = 'rgba(228, 39, 39, 0.3)'; }else{ parent['className'] = 'green'; parent.style.backgroundColor = 'rgba(18, 188, 101, 0.3)'; } setTimeout(function(){ parent.style.transition = 'all .5s linear'; parent.style.backgroundColor = ''; }, 200); // debugger; }) mo.observe(elem, { 'characterData': true, 'subtree':true, 'characterDataOldValue':true }); }, myRouter: function(view){ location.hash = view; // setTimeout(function(){ // window.App.currentView = view; // }, 0) } }
const input = require('./day6-input.js') let arr = input.split('\t').map(x => parseInt(x, 10)) const [steps, duplicate] = countUntilAnyDuplicate(arr) console.log(steps, duplicate) function countUntilAnyDuplicate (arr) { const arrs = [] let lastArrString = '' let steps = 0 while (!arrs.includes(lastArrString, 1)) { const max = findMax(arr) const index = arr.indexOf(max) arr[index] = 0 distribute(arr, index + 1, max) lastArrString = arr.join(',') arrs.unshift(lastArrString) steps++ } return [steps, arrs[0].split(',').map(x=> parseInt(x, 10))] } function findMax(arr) { return arr.reduce(function(a, b) { return Math.max(a, b); }); } function distribute(arr, index, val) { for (let i = 0; i < val; i++) { arr[(index + i) % arr.length] += 1 } } // find max // empty max val // distribute that val // store array // check doubles // find max
/* * A style is expected to take one parameter, the player's playback object. * The playback object has all of the functionality a style needs to get chord * data from the current measure, and play notes. * * A style should have a requireInstruments array, which can include * "General MIDI" instrument names as well as the string 'percussion'. * A style should return 1-2 functions: onBeat or onMeasure. */ export default function style_basic(playback) { var style = {}; /* * The load function could be no-op if you really wanted, but it has to * exist. You can use it to load instruments required by the style. */ style.requireInstruments = [ 'percussion', 'acoustic_grand_piano', 'acoustic_bass' ]; /* * Style should have either an onBeat function or an onMeasure function. * Here we have both. */ style.onMeasure = function() { // Play metronome. playback.drum('Bass Drum'); // This isn't the best way to do this, but for the sake of example, // here's how the scheduler works: playback.schedule(() => playback.drum('Hi Wood Block'), [2, 3, 4]); }; style.onBeat = function() { var chord = playback.beats[playback.beat]; // If there's no chord returned by getBeat, there's no chord on this beat. if(chord) { // This turns a beat object into an array of note names. // the second argument decides whether to go up or down the octave. var notes = playback.octave(chord, 4, true); playback.playNotes({ notes: notes, // Note name or array of note names. instrument: 'acoustic_grand_piano', dur: playback.restsAfter // Number of beats to play the note. // Optionally: 'velocity' which is a number 0-127 representing volume. // Well, technically it represents how hard you play an instrument // but it corresponds to volume so. }); playback.playNotes({ notes: chord[0] + 2, instrument: 'acoustic_bass', dur: playback.restsAfter }); } }; return style; }
const weakness_db = require('../db/weakness'); module.exports = (args, msg) => { if (!args || args.length <= 0) { return; } const fullName = args.join(' '); weakness_db(fullName, weaknesses => { if (!weaknesses) { return msg.channel.send(`Sorry partner, I don't have any notes on that monster.`) } const reply = buildMessage(weaknesses); msg.channel.send(reply); }); }; const buildMessage = weaknesses => { return ` \`\`\` 🔥 : ${weaknesses.weakness_fire} 💧 : ${weaknesses.weakness_water} ❄ : ${weaknesses.weakness_ice} ⚡ : ${weaknesses.weakness_thunder} 🐲 : ${weaknesses.weakness_dragon} ☣️ : ${weaknesses.weakness_poison} 💤 : ${weaknesses.weakness_sleep} ♿ : ${weaknesses.weakness_paralysis} 💥 : ${weaknesses.weakness_blast} 💫 : ${weaknesses.weakness_blast} \`\`\` `; };
import React, { useState } from 'react'; const ThreadInputSearch = (props) => { const [query, setQuery] = useState(''); function evaluateTerm(event) { const { value } = event.target; setQuery(value); if(value.length > 4) { props.search({ showResult: true, value }) } else { props.search({ showResult: false, value: '' }) } } function clearInput (event){ const { value } = event.target; setQuery(value); let threadLink = event.relatedTarget; if(threadLink !== null && threadLink.classList.contains('search-result')) { props.redirect(threadLink.dataset.url); removeResults(); } else { props.search({ showResult: false, value }); } } const removeResults = () => { setQuery(''); props.search({ showResult: false, value:'' }) }; return ( <form className="form-inline my-2 my-lg-0"> <input className="form-control mr-sm-2" type="text" placeholder="Search" onChange={ (event) => evaluateTerm(event) } value={ query } onBlur={(event) => clearInput(event)} onFocus={(event) => evaluateTerm(event) } /> </form> ); }; export default ThreadInputSearch;
const { Client, Message, MessageEmbed } = require("discord.js"); const config = require("../../config.json"); const BoltyInfo = require("../../classes/BoltyInfo"); /** * * @param {Client} client * @param {Message} message * @param {String[]} args */ module.exports.run = async (client, message, args) => { message.channel.send({ embeds: [ BoltyInfo.BoltyInfoEmbed(client, message) .setTitle(`Invite me to your server!`) .setDescription( `Thank you for being interested in inviting me to your server! To do so, please\n[click here](https://discord.com/api/oauth2/authorize?client_id=856104744396259378&permissions=8&scope=bot%20applications.commands).\nThank you!` ) .setColor(config.colors.boltyEmbedColor) .setThumbnail(client.user.displayAvatarURL()), ], }); }; module.exports.help = { name: "invite", description: "Invite me to your server.", aliases: ["inv"], usage: "", category: "Info", cooldown: 7, };
import React from "react"; import { useSelector, useDispatch } from "react-redux"; import { increment, decrement } from "./actions"; const App = () => { const { counter, isLogged } = useSelector(state => state); const dispatch = useDispatch(); return ( <div> <h1>Welcome to Redux! :)</h1> <p>{isLogged ? "The user is logged in" : "The user is not log in"}</p> <button onClick={() => dispatch(increment(5))}>+</button> <button onClick={() => dispatch(decrement())}>-</button> <p>this is the counter: {counter}</p> </div> ); }; export default App;
const styles = require('../styles') //Documentation for Phaser's (2.6.2) text:: phaser.io/docs/2.6.2/Phaser.Text.html class SlideTimer extends Phaser.Text { //initialization code in the constructor constructor(game, event) { super(game, game.world.centerX, game.height, JSON.parse(localStorage.getItem(game.global.key_totalSlides)) + ' seconds remaining', styles.fonts.medium(game)); this.timer = event.timer; this.anchor.set(0.5, 1); game.add.existing(this); } //Code ran on each frame of game update() { this.text = Math.ceil(this.timer.duration / 1000) + ' seconds remaining'; } } module.exports = SlideTimer;
import React from 'react'; import {useSelector} from 'react-redux'; import {createStackNavigator} from '@react-navigation/stack'; import {PublicNavigation} from './PublicNavigation'; import {PrivateNavigation} from './PrivateNavigation'; const Stack = createStackNavigator(); export const Navigation = () => { const {isLoggedIn} = useSelector(({auth}) => auth); return ( <Stack.Navigator> {isLoggedIn ? ( <Stack.Screen name="App" component={PrivateNavigation} options={{headerShown: false}} /> ) : ( <Stack.Screen name="Auth" component={PublicNavigation} options={{headerShown: false}} /> )} </Stack.Navigator> ); };
import React from 'react' import { Navbar, Footer, UserSettings } from '../components' const User=()=>{ return( <div className="MenuDiv"> <Navbar/> <UserSettings/> <Footer/> </div> ) } export default User
const Admin = require("../model/Admin") const jwt = require('jsonwebtoken'); const bcrypt = require('bcrypt'); require('../config/envConfig'); //const data = require('../data/data') const key = process.env.SECRET_KEY; const salt = process.env.ENCRYPT_SALT; module.exports = { async Store(req, res) { const { nome, email, password } = req.body let admin = await Admin.findOne({ email, password }) if (!admin) { admin = await Admin.create({ nome, email, password: bcrypt.hashSync(password, salt) }) } return res.json(admin) }, async Find(req, res) { const { email, senha } = req.body; let response = await Admin.findOne({ email }); if (!response) { return res.send("Email inválido!") } if (response.password == senha) { return res.send(response); } return res.send("Senha inválida!"); }, //Função retorna um token para autenicação async Sign(req, res) { const { email, senha } = req.body; const token = req.headers['authorization']; Admin.where({ email: email }).findOne((e, data) => { //Casos de erro ao procurar usuário if (e) return res.send({ error: e }); if (!data) return res.send("Email inválido!") // Caso de reautenticação, retornando dados sem necessidade de login e senha if(token) return res.send({ token: token, user: data }); const senha_criptografada = bcrypt.compareSync(senha,data.password) if(!senha_criptografada){ return res.send("Senha inválida!") } //Gerando token com dados do usuário encontrado jwt.sign(data.toJSON(), key, { expiresIn: '1d' }, (err, token) => { if (err) { console.log(err) return res.send({ error: "Erro inesperado..." }) } return res.send({ token: token, user: data }); }) }); }, //Função para autenticação de tokens Auth(req, res, next) { const token = req.headers['authorization']; //Decodificando token jwt.verify(token, key, (err, decode) => { if (err) { //Caso em que token se expirou ou houve algum erro interno return res.send({ error: err }) } //Buscando dados do usuário Admin.where({ email: decode.email }).findOne((e, data) => { if (e) { console.log('erro ao buscar usuário'); return res.status(401).send({ error: e }); } else if (!data) { return res.send("Usuário não encontrado"); } else { req.body.email = data.email; req.body.senha = data.password; next(); } }) }) }, }
/* * dom operate */ /** * @function getStyle * @description **getStyle(el, property)** get DOM style * @param {DOM Object} el element * @param {String} property css property */ export function getStyle(el, property) { let value = el.currentStyle ? el.currentStyle[property] : document.defaultView.getComputedStyle(el, null).getPropertyValue(property); let matches = value && value.match(/^(\d+)(\.\d+)?px$/); return matches ? Number(matches[1]) : undefined; }
var whyHireChang = whyHireChang || {}; whyHireChang.model = (function(){ var object = {}; return object; })();
import React from 'react' import { StyleSheet } from 'quantum' import Filter from './Filter' import Selection from './Selection' const styles = StyleSheet.create({ self: { background: '#d3e0e5', padding: '5px 10px 10px 10px', display: 'flex', flexDirection: 'row', alignItems: 'baseline', justifyContent: 'center', flexWrap: 'wrap', }, }) const Toolbar = ({ filter, onFilter, onSelect, onUnselect }) => ( <div className={styles()}> <Filter value={filter} onChange={onFilter} /> <Selection onSelect={onSelect} onUnselect={onUnselect} /> </div> ) export default Toolbar
const mongoose = require('mongoose'); const Schema = mongoose.Schema; mongoose.Promise = global.Promise; const reviewSchema = new Schema({ username: { type: String, required: true, trim: true }, comment: { type: String }, post_id: { type: mongoose.Schema.Types.ObjectId, required:true }, score: {type: Number, required:true }, date: { type: Date, default: Date.now }, }, { timestamps: true, }); const postSchema = new Schema({ title: { type: String, required: true, unique: true, trim: true }, creator: { type: String, required: true, trim: true }, description: { type: String, required: true }, score: {type: Number, required:true }, date: { type: Date, default: new Date() }, reviews: [{}], }, { timestamps: true, }); const Post = mongoose.model('Post', postSchema); const Review = mongoose.model('Review', reviewSchema); exports.Post = Post; exports.Review = Review;
import { getClasses } from "../../api/getClasses" import { GET_CLASSES, GET_MARKAS, GET_MODELS } from "../types" import { getMarkas } from "../../api/getMarkas" import { getModels } from "../../api/getModels" export const getAllClasses = () =>{ return async dispatch =>{ const classes = await getClasses() dispatch({ type: GET_CLASSES, payload: classes }) } } export const getAllMarkas = () =>{ return async dispatch =>{ const markas = await getMarkas() dispatch({ type: GET_MARKAS, payload: markas }) } } export const getModelsForMarka = (markaId) =>{ return async dispatch =>{ const models = await getModels(markaId) dispatch({ type: GET_MODELS, payload: models }) } }
import React, { useState, useEffect } from 'react'; import Details from './Details.js' const Character = ({ name, gender, birthYear, height, films }) => { const [showDetails, setShowDetails] = useState(false); const toggleDetails = ({ films }) => { showDetails ? setShowDetails(false) : setShowDetails(true); } return ( <div className="character"> <div className="wrapper"> <div className="box"> <p>{name}</p> </div> <div className="box"> <p>{gender}</p> </div> <div className="box"> <p>{birthYear}</p> </div> <div className="box"> { showDetails ? ( <div className="details-icon details-icon-after" onClick={toggleDetails}> <i className="fa fa-info fa-lg" ></i> <p>Details</p> </div> ) : ( <i className="fa fa-info fa-lg" onClick={toggleDetails}></i> ) } </div> </div> { showDetails ? <Details height={height} films={films}/> : null } </div> ) } export default Character;
function power(base, expo) { if (base == 0) return 0 if (expo === 0) return 1 return base * power(base, expo - 1) } console.log(power(3, 3)) // 27 < == power(3, 3) // 9 < == power(3, 2) // 3 < == power(3, 1) // 1 < == power(3, 0) function factorial(n) { if (n == 0) return 0 if (n == 1) return 1 return n * factorial(n - 1) } console.log(factorial(5)) // 120 < == fac(5) // 24 < == fac(4) // 6 < == fac(3) // 2 < == fac(2) // 1 < == fac(1) function productOfArray(arr) { if (arr.length == 0) return 0 if (arr.length == 1) return arr[0] return arr.pop() * productOfArray(arr.slice(0, arr.length)) } console.log(productOfArray([])) function recursiveRange(n) { if (n === 0) return 0 return n + recursiveRange(n - 1) } console.log(recursiveRange(3)) // I did't understand following problem function fib(n) { if (n <= 2) return 1 return fib(n - 1) + fib(n - 2) }
import Switch from "../../../../utils/functors/Switch"; import INITIAL_STATE from "../state"; import Types from "../actions/actionTypes"; import * as loadProducers from "./operations/loadProducers"; import * as loadProducerDetails from "./operations/loadProducerDetails"; import * as createProducer from "./operations/createProducer"; import * as updateProducer from "./operations/updateProducer"; import * as deleteProducer from "./operations/deleteProducer"; const reducer = (state = INITIAL_STATE, { type, payload }) => { return Switch.on(type, state, payload, INITIAL_STATE) .case(Types.LOAD_PRODUCERS_REQUEST, loadProducers.request) .case(Types.LOAD_PRODUCERS_SUCCESS, loadProducers.success) .case(Types.LOAD_PRODUCERS_FAILURE, loadProducers.failure) .case(Types.LOAD_PRODUCER_DETAILS_REQUEST, loadProducerDetails.request) .case(Types.LOAD_PRODUCER_DETAILS_SUCCESS, loadProducerDetails.success) .case(Types.LOAD_PRODUCER_DETAILS_FAILURE, loadProducerDetails.failure) .case(Types.CREATE_PRODUCER_REQUEST, createProducer.request) .case(Types.CREATE_PRODUCER_SUCCESS, createProducer.success) .case(Types.CREATE_PRODUCER_FAILURE, createProducer.failure) .case(Types.UPDATE_PRODUCER_REQUEST, updateProducer.request) .case(Types.UPDATE_PRODUCER_SUCCESS, updateProducer.success) .case(Types.UPDATE_PRODUCER_FAILURE, updateProducer.failure) .case(Types.DELETE_PRODUCER_REQUEST, deleteProducer.request) .case(Types.DELETE_PRODUCER_SUCCESS, deleteProducer.success) .case(Types.DELETE_PRODUCER_FAILURE, deleteProducer.failure) .default(state); }; export default reducer;
import http from './public' /*获取jwt令牌*/ export const getjwt = () => { return http.requestQuickGet('/openapi/auth/userjwt') } /*同步获取jwt令牌*/ export const getjwtSync = () => { return new Promise((resolve, reject) => { jQuery.ajax({ type: 'Get', url: '/openapi/auth/userjwt', async: false, success: function (data) { resolve(data) }, error: function (error) { reject(error) } }) }) } /*同步获取退出登录令牌*/ export const userlogout = () => { return new Promise((resolve, reject) => { jQuery.ajax({ type: 'Get', url: '/openapi/auth/userlogout', async: false, success: function (data) { resolve(data) }, error: function (error) { reject(error) } }) }) }
var cantidadSolicitada = 25; var deseaImprimir = true; debugger; if (deseaImprimir) { console.log('Esta imprimiendo'); if (cantidadSolicitada > 10) { console.log('Tienes un descuento'); } } deseaImprimir = false; deseaImprimir = true; deseaImprimir = false; deseaImprimir = false && false; deseaImprimir = true && true;
const jwt = require("jsonwebtoken"); const { Book } = require("../models"); // create a new book const newBook = (req, res) => { const { title, authors, pages, year, plot, rating } = req.body; Book.create({ title, authors, pages, year, plot, rating }) .then(dbBookData => res.json(dbBookData)) .catch(err => { console.log(err); res.json(err); }); }; // get back all books const getAllBooks = async (req, res) => { Book.findAll({ }) .then(dbBookData => res.json(dbBookData)) .catch(err => res.json(err)); } // delete book const deletePostBook = async (req, res) => { Book.destroy({ where: { id: req.body.id } }) .then(dbBookData => res.json(dbBookData)) .catch(err => res.json(err)); } module.exports = { newBook, getAllBooks, deletePostBook };
/* * Copyright (c) 2012,2013 DeNA Co., Ltd. et al. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ import "./analysis.jsx"; import "./parser.jsx"; import "./classdef.jsx"; import "./type.jsx"; import "./emitter.jsx"; import "./platform.jsx"; import "./util.jsx"; import "./optimizer.jsx"; import "./completion.jsx"; import "./instruments.jsx"; import "./statement.jsx"; import "./transformer.jsx"; class Compiler { static const MODE_COMPILE = 0; static const MODE_PARSE = 1; static const MODE_COMPLETE = 2; static const MODE_DOC = 3; var _platform : Platform; var _mode : number; var _transformCommands : TransformCommand[]; var _optimizer : Optimizer; var _warningFilters : Array.<function(:CompileWarning):Nullable.<boolean>>; var _warningAsError : boolean; var _parsers : Parser[]; var _fileCache : Map.<string>; var _searchPaths : string[]; var _builtinParsers : Parser[]; var _userEnvironment : Map.<string>; var _emitter : Emitter; function constructor (platform : Platform) { this._platform = platform; this._mode = Compiler.MODE_COMPILE; this._transformCommands = [] : Array.<TransformCommand>; this._optimizer = null; this._warningFilters = [] : Array.<function(:CompileWarning):Nullable.<boolean>>; this._warningAsError = false; this._parsers = new Parser[]; this._fileCache = new Map.<string>; this._searchPaths = [ this._platform.getRoot() + "/lib/common" ]; // load the built-in classes this.addSourceFile(null, this._platform.getRoot() + "/lib/built-in.jsx"); this._builtinParsers = this._parsers.concat(new Parser[]); // shallow clone this._userEnvironment = new Map.<string>; } function addSearchPath (path : string) : void { this._searchPaths.unshift(path); } function getPlatform () : Platform { return this._platform; } function getMode () : number { return this._mode; } function setMode (mode : number) : Compiler { this._mode = mode; return this; } function getEmitter () : Emitter { return this._emitter; } function setEmitter (emitter : Emitter) : void { this._emitter = emitter; } function setTransformCommands(cmds : string[]) : Nullable.<string> { for (var i = 0; i < cmds.length; ++i) { var cmd = cmds[i]; switch (cmd) { case "generator": this._transformCommands.push(new GeneratorTransformCommand(this)); break; case "cps": this._transformCommands.push(new CPSTransformCommand(this)); break; default: return "unknown transformation command: " + cmd; } } return null; } function setOptimizer (optimizer : Optimizer) : void { this._optimizer = optimizer; } function getWarningFilters () : Array.<function(:CompileWarning):Nullable.<boolean>> { return this._warningFilters; } function setWarningAsError(f : boolean) : void { this._warningAsError = f; } function getParsers () : Parser[] { return this._parsers; } function getBuiltinParsers () : Parser[] { return this._builtinParsers; } function getUserEnvironment() : Map.<string> { return this._userEnvironment; } function addSourceFile (token : Token, path : string) : Parser { return this.addSourceFile(token, path, null); } function addSourceFile (token : Token, path : string, completionRequest : CompletionRequest) : Parser { var parser; if ((parser = this.findParser(path)) == null) { parser = new Parser(token, path, completionRequest); this._parsers.push(parser); } return parser; } function findParser (path : string) : Parser { for (var i = 0; i < this._parsers.length; ++i) if (this._parsers[i].getPath() == path) return this._parsers[i]; return null; } function compile () : boolean { var errors = new CompileError[]; // parse all files for (var i = 0; i < this._parsers.length; ++i) { if (! this._parseFile(errors, i)) { if (! this._handleErrors(errors)) return false; } } switch (this._mode) { case Compiler.MODE_PARSE: return true; } // fix-up classdefs to start semantic analysis this.normalizeClassDefs(errors); if (! this._handleErrors(errors)) return false; // resolve imports this._resolveImports(errors); if (! this._handleErrors(errors)) return false; // register backing class for primitives var builtins = this._builtinParsers[0]; BooleanType._classDef = builtins.lookup(errors, null, "Boolean"); NumberType._classDef = builtins.lookup(errors, null, "Number"); StringType._classDef = builtins.lookup(errors, null, "String"); FunctionType._classDef = builtins.lookup(errors, null, "Function"); if (! this._handleErrors(errors)) return false; // semantic analysis this._resolveTypes(errors); if (! this._handleErrors(errors)) return false; this._exportEntryPoints(); this._analyze(errors); if (! this._handleErrors(errors)) return false; switch (this._mode) { case Compiler.MODE_COMPLETE: return true; case Compiler.MODE_DOC: return true; } // transformation this._transform(errors); if (! this._handleErrors(errors)) return false; // optimization this._optimize(); // TODO peep-hole and dead store optimizations, etc. this._generateCode(errors); if (! this._handleErrors(errors)) return false; return true; } /** * Returns a JSON data structure of parsed class definitions */ function getAST () : variant { var classDefs = new ClassDefinition[]; for (var i = 0; i < this._parsers.length; ++i) { classDefs = classDefs.concat(this._parsers[i].getClassDefs()); classDefs = classDefs.concat(this._parsers[i].getTemplateClassDefs().map.<ClassDefinition>((classDef) -> classDef)); } return ClassDefinition.serialize(classDefs); } function getFileContent (errors : CompileError[], sourceToken : Token, path : string) : Nullable.<string> { assert path != ""; if(this._fileCache[path] == null) { try { this._fileCache[path] = this._platform.load(path); } catch (e : Error) { errors.push(new CompileError(sourceToken, "could not open file: " + path + ", " + e.toString())); this._fileCache[path] = null; } } return this._fileCache[path]; } function _parseFile (errors : CompileError[], parserIndex : number) : boolean { var parser = this._parsers[parserIndex]; // read file var content = this.getFileContent(errors, parser.getSourceToken(), parser.getPath()); if (content == null) { // call parse() to initialize parser's state // because some compilation mode continues to run after errors. parser.parse("", new CompileError[]); return false; } // check conflicts var conflictWarning = this._checkConflictOfNpmModulesParsed(parserIndex) ?: this._checkConflictOfIdenticalFiles(parserIndex, content); if (conflictWarning != null) { errors.push(conflictWarning); } // parse parser.parse(content, errors); // register imported files if (this._mode != Compiler.MODE_PARSE) { var imports = parser.getImports(); for (var i = 0; i < imports.length; ++i) { if (! this._handleImport(errors, parser, imports[i])) return false; } } return true; } var _npmModulesParsed = new Map.<number>; // map of module_name => parser index function _checkConflictOfNpmModulesParsed(parserIndex : number) : CompileWarning { function getModuleNameAndPath(path : string) : string[] { var match = path.match(/^(?:.*\/|)node_modules\/([^\/]+)\//); if (match == null) { return null; } return [ match[1], match[0].substring(0, match[0].length - 1), // strip trailing "/" ]; } var parser = this._parsers[parserIndex]; var moduleNameAndPath = getModuleNameAndPath(parser.getPath()); // return if the source file is not part of a npm module if (moduleNameAndPath == null) { return null; } // register and return if the source file is a npm module that is loaded for the first time if (! this._npmModulesParsed.hasOwnProperty(moduleNameAndPath[0])) { this._npmModulesParsed[moduleNameAndPath[0]] = parserIndex; return null; } // check conflict var offendingParser = this._parsers[this._npmModulesParsed[moduleNameAndPath[0]]]; var offendingModulePath = getModuleNameAndPath(offendingParser.getPath())[1]; if (offendingModulePath == moduleNameAndPath[1]) { return null; } // found conflict return new CompileWarning(parser.getSourceToken(), "please consider running \"npm dedupe\"; the NPM module has already been read from a different location:") .addCompileNote(new CompileNote(offendingParser.getSourceToken(), "at first from here as: " + offendingParser.getPath())) .addCompileNote(new CompileNote(parser.getSourceToken(), "and now from here as: " + parser.getPath())) as CompileWarning; } function _checkConflictOfIdenticalFiles(parserIndex : number, content : string) : CompileWarning { var parser = this._parsers[parserIndex]; for (var i = 0; i != parserIndex; ++i) { if (this._parsers[i].getContent() == content && Util.basename(this._parsers[i].getPath()) == Util.basename(parser.getPath())) { return new CompileWarning(parser.getSourceToken(), "the file (with identical content) has been read from different locations:") .addCompileNote(new CompileNote(parser.getSourceToken(), "from here as: " + parser.getPath())) .addCompileNote(new CompileNote(this._parsers[i].getSourceToken(), "from here as: " + this._parsers[i].getPath())) as CompileWarning; } } return null; } function _handleImport (errors : CompileError[], parser : Parser, imprt : Import) : boolean { if (imprt instanceof WildcardImport) { var wildImprt = imprt as WildcardImport; // read the files from a directory var resolvedDir = this._resolvePath(wildImprt.getFilenameToken().getFilename(), wildImprt.getDirectory(), true); var files = new string[]; try { files = this._platform.getFilesInDirectory(resolvedDir); } catch (e : Error) { errors.push(new CompileError(wildImprt.getFilenameToken(), "could not read files in directory: " + resolvedDir + ", " + e.toString())); return false; } var found = false; for (var i = 0; i < files.length; ++i) { if (files[i].length >= wildImprt.getSuffix().length && files[i].charAt(0) != "." && files[i].substring(files[i].length - wildImprt.getSuffix().length) == wildImprt.getSuffix()) { var path = resolvedDir + "/" + files[i]; if (path != parser.getPath()) { var newParser = this.addSourceFile(wildImprt.getFilenameToken(), resolvedDir + "/" + files[i], null); wildImprt.addSource(newParser); found = true; } } } if (! found) { errors.push(new CompileError(wildImprt.getFilenameToken(), "no matching files found in directory: " + resolvedDir)); return false; } } else { // read one file var path = this._resolvePath(imprt.getFilenameToken().getFilename(), Util.decodeStringLiteral(imprt.getFilenameToken().getValue()), false); if (path == parser.getPath()) { errors.push(new CompileError(imprt.getFilenameToken(), "cannot import itself")); return false; } var newParser = this.addSourceFile(imprt.getFilenameToken(), path, null); imprt.addSource(newParser); } return true; } function forEachClassDef (f : function(:Parser, :ClassDefinition):boolean) : boolean { function onClassDef (parser : Parser, classDef : ClassDefinition) : boolean { if (! f(parser, classDef)) return false; var inners = classDef.getInnerClasses(); for (var i = 0; i < inners.length; ++i) { if (! onClassDef(parser, inners[i])) return false; } return true; } for (var i = 0; i < this._parsers.length; ++i) { var parser = this._parsers[i]; var classDefs = parser.getClassDefs(); for (var j = 0; j < classDefs.length; ++j) { if (! onClassDef(parser, classDefs[j])) return false; } } return true; } function normalizeClassDefs (errors : CompileError[]) : void { this.forEachClassDef((parser, classDef) -> { classDef.normalizeClassDefs(errors); return true; }); } function _resolveImports (errors : CompileError[]) : void { for (var i = 0; i < this._parsers.length; ++i) { // built-in classes become implicit imports this._parsers[i].registerBuiltinImports(this._builtinParsers); // set source of every import var imports = this._parsers[i].getImports(); for (var j = 0; j < imports.length; ++j) { imports[j].assertExistenceOfNamedClasses(errors); } } } function _resolveTypes (errors : CompileError[]) : void { this.forEachClassDef(function (parser : Parser, classDef : ClassDefinition) : boolean { classDef.resolveTypes(new AnalysisContext(errors, parser, null)); return true; }); } function _analyze (errors : CompileError[]) : void { var createContext = function (parser : Parser) : AnalysisContext { return new AnalysisContext( errors, parser, function (parser : Parser, classDef : ClassDefinition) : ClassDefinition { classDef.setAnalysisContextOfVariables(createContext(parser)); classDef.analyze(createContext(parser)); return classDef; }); }; // set analyzation context of every member variable this.forEachClassDef(function (parser : Parser, classDef : ClassDefinition) { classDef.setAnalysisContextOfVariables(createContext(parser)); return true; }); // analyze every classdef this.forEachClassDef(function (parser : Parser, classDef : ClassDefinition) { classDef.analyze(createContext(parser)); return true; }); // NOTE: template inner classes might not be analyzed in first time, // so the second time we analyze such a class // see t/run/322 this.forEachClassDef(function (parser : Parser, classDef : ClassDefinition) { classDef.analyze(createContext(parser)); return true; }); // analyze unused member variables in every classdef this.forEachClassDef(function (parser : Parser, classDef : ClassDefinition) { classDef.analyzeUnusedVariables(); return true; }); } function _transform (errors : CompileError[]) : void { function doit(cmd : TransformCommand) : boolean { cmd.setup(errors); cmd.performTransformation(); return errors.length == 0; } // apply the registered transformations for (var i = 0; i < this._transformCommands.length; ++i) { if (! doit(this._transformCommands[i])) return; } // apply the fixed transformations if (! doit(new FixedExpressionTransformCommand(this))) return; } function _optimize () : void { if (this._optimizer != null) this._optimizer.setCompiler(this).performOptimization(); } function _generateCode (errors : CompileError[]) : void { // build list of all classDefs var classDefs = new ClassDefinition[]; for (var i = 0; i < this._parsers.length; ++i) { classDefs = classDefs.concat(this._parsers[i].getClassDefs()); // to emit native classes with in-line native definitions this._parsers[i].getTemplateClassDefs().forEach((templateClassDef) -> { if ((templateClassDef.flags() & ClassDefinition.IS_NATIVE) != 0 && templateClassDef.getNativeSource() != null) { classDefs.push(templateClassDef); } }); } for (var i = 0; i < classDefs.length; ++i) { if (classDefs[i].getInnerClasses().length != 0) classDefs = classDefs.concat(classDefs[i].getInnerClasses()); } // check that there are no conflict of names bet. native classes var nativeClassNames = new Map.<ClassDefinition>; var foundConflict = false; classDefs.forEach(function (classDef) { if ((classDef.flags() & ClassDefinition.IS_NATIVE) == 0) { return; } if (nativeClassNames.hasOwnProperty(classDef.className()) && ! (classDef instanceof InstantiatedClassDefinition && nativeClassNames[classDef.className()] instanceof InstantiatedClassDefinition && (classDef as InstantiatedClassDefinition).getTemplateClass() == (nativeClassNames[classDef.className()] as InstantiatedClassDefinition).getTemplateClass()) && classDef.getNativeSource() == null && classDef.getOuterClassDef() == null ) { errors.push( new CompileError(classDef.getToken(), "native class with same name is already defined") .addCompileNote(new CompileNote(nativeClassNames[classDef.className()].getToken(), "here"))); foundConflict = true; return; } nativeClassNames[classDef.className()] = classDef; }); if (foundConflict) { return; } // reorder the classDefs so that base classes would come before their children var getMaxIndexOfClasses = function (deps : ClassDefinition[]) : number { deps = deps.concat([]); // clone the array if (deps.length == 0) return -1; for (var i = 0; i < classDefs.length; ++i) { for (var j = 0; j < deps.length; ++j) { if (classDefs[i] == deps[j]) { deps.splice(j, 1); if (deps.length == 0) return i; } } } throw new Error("logic flaw, could not find class definition of '" + deps[0].className() + "'"); }; for (var i = 0; i < classDefs.length;) { if ((classDefs[i].flags() & ClassDefinition.IS_NATIVE) != 0) { var maxIndexOfClasses = -1; } else { var deps = classDefs[i].implementTypes().map.<ClassDefinition>(function (t) { return t.getClassDef(); }).concat([]); if (classDefs[i].extendType() != null) deps.unshift(classDefs[i].extendType().getClassDef()); if (classDefs[i].getOuterClassDef() != null && deps.indexOf(classDefs[i].getOuterClassDef()) == -1) deps.unshift(classDefs[i].getOuterClassDef()); maxIndexOfClasses = getMaxIndexOfClasses(deps); } if (maxIndexOfClasses > i) { classDefs.splice(maxIndexOfClasses + 1, 0, classDefs[i]); classDefs.splice(i, 1); } else { ++i; } } // emit this._emitter.emit(classDefs); } function _exportEntryPoints() : void { this.forEachClassDef(function (parser, classDef) { switch (classDef.classFullName()) { case "_Main": classDef.setFlags(classDef.flags() | ClassDefinition.IS_EXPORT); classDef.forEachMemberFunction(function (funcDef) { if ((funcDef.flags() & ClassDefinition.IS_STATIC) != 0 && funcDef.name() == "main" && funcDef.getArguments().length == 1 && Util.isArrayOf(funcDef.getArgumentTypes()[0].getClassDef(), Type.stringType)) { funcDef.setFlags(funcDef.flags() | ClassDefinition.IS_EXPORT); } return true; }); break; case "_Test": classDef.setFlags(classDef.flags() | ClassDefinition.IS_EXPORT); classDef.forEachMemberFunction(function (funcDef) { if ((funcDef.flags() & ClassDefinition.IS_STATIC) == 0 && (funcDef.name().match(/^test/) || funcDef.name() == "constructor") && funcDef.getArguments().length == 0) { funcDef.setFlags(funcDef.flags() | ClassDefinition.IS_EXPORT); } return true; }); break; } return true; }); } function _handleErrors (errors : CompileError[]) : boolean { // ignore all messages on completion mode if (this._mode == Compiler.MODE_COMPLETE) { errors.splice(0, errors.length); return true; } // print issues var isFatal = false; errors.forEach(function (error) { if (error instanceof CompileWarning) { var warning = error as CompileWarning; var doWarn; for (var i = 0; i < this._warningFilters.length; ++i) { if ((doWarn = this._warningFilters[i](warning)) != null) break; } if (doWarn != false) { this._platform.warn(warning.format(this.getPlatform())); warning.getCompileNotes().forEach(function (note) { this._platform.warn(note.format(this.getPlatform())); }); if (this._warningAsError) { isFatal = true; } } } else { this._platform.error(error.format(this.getPlatform())); error.getCompileNotes().forEach(function (note) { this._platform.error(note.format(this.getPlatform())); }); isFatal = true; } }); // clear all errors errors.splice(0, errors.length); return ! isFatal; } var _packageJsonCache = new Map.<Map.<variant>>; function _readPackageJson(moduleDir : string) : Map.<variant> { if (this._packageJsonCache.hasOwnProperty(moduleDir)) { return this._packageJsonCache[moduleDir]; } var json = null : Map.<variant>; if (this._platform.fileExists(moduleDir + "/package.json")) { try { var contents = this._platform.load(moduleDir + "/package.json"); json = JSON.parse(contents) as Map.<variant>; } catch (e : variant) { this._platform.warn("could not parse file:" + moduleDir + "/package.json"); } } this._packageJsonCache[moduleDir] = json; return json; } function _resolvePathFromNodeModules (srcDir : string, givenPath : string, isWildcard : boolean) : string { var firstSlashAtGivenPath = givenPath.indexOf("/"); var moduleName = firstSlashAtGivenPath != -1 ? givenPath.substring(0, firstSlashAtGivenPath) : givenPath; // search for givenPath in given "node_modules" dir function lookupInNodeModules(nodeModulesDir : string) : string { var moduleDir = nodeModulesDir + "/" + moduleName; // return if module does not exist if (! this._platform.fileExists(moduleDir)) { return ""; } // found the package, read package.json var packageJson = this._readPackageJson(moduleDir); if (packageJson == null) { packageJson = {}; } if (isWildcard || firstSlashAtGivenPath != -1) { // if given path is package/filename, then return a filename relative to package.json/[directories]/[lib] (or default to "lib") var libDir = packageJson["directories"] && packageJson["directories"]["lib"] ? packageJson["directories"]["lib"] as string : "lib"; var subPathWithLeadingSlash = firstSlashAtGivenPath != -1 ? givenPath.substring(firstSlashAtGivenPath): ""; return Util.resolvePath(moduleDir + "/" + libDir + subPathWithLeadingSlash); } else { // given path did not contain "/", so return package.json/[main] or "index.jsx" var main = packageJson["main"] ? packageJson["main"] as string : "index.jsx"; return Util.resolvePath(moduleDir + "/" + main); } } // lookup dependencies (from "srcDir/node_modules", "srcDir/../../node_modules", ...) while (true) { var path = lookupInNodeModules(srcDir + "/node_modules"); if (path != "") { return path; } // lookup parent dependencies var match = srcDir.match(/^(.*)\/node_modules\/[^\/]+$/); if (match == null) { break; } srcDir = match[1]; } return ""; } function _resolvePath (srcPath : string, givenPath : string, isWildcard : boolean) : string { /* the search order is: 1) --add-search-path, 2) node_modules/, 3) relative to src file This is defined as such to provide freedom to users: - users may use ```import "./foo.jsx"``` to explicitly specify 3 - users may use --add-search-path explicitly to avoid diamond dependency problem of NPM */ if (givenPath.match(/^\.{1,2}\//) == null) { // search the file from [one-of-the-search-paths]/givenPath var searchPaths = this._searchPaths.concat(this._emitter.getSearchPaths()); for (var i = 0; i < searchPaths.length; ++i) { var path = Util.resolvePath(searchPaths[i] + "/" + givenPath); // check the existence of the file, at the same time filling the cache if (this._platform.fileExists(path)) return path; } // search srcDir/node_modules var srcDir = Util.dirname(srcPath); var path = this._resolvePathFromNodeModules(srcDir, givenPath, isWildcard); if (path != "") return path; // search from [cwd]/node_modules if (srcDir != ".") { path = this._resolvePathFromNodeModules(".", givenPath, isWildcard); if (path != "") return path; } } // return path relative to srcPath var lastSlashAt = srcPath.lastIndexOf("/"); path = Util.resolvePath((lastSlashAt != -1 ? srcPath.substring(0, lastSlashAt + 1) : "") + givenPath); return path; } } // vim: set noexpandtab:
import styled from "styled-components"; const DeviceInfo = styled.div` grid-area: device-info; height: 100%; width: 100%; font-family: 'Roboto', sans-serif; ` export default DeviceInfo;
/* HOMEPAGE CONTENT - Function to fetch past or future events depending on user selection - Displays title & body content - Sets page image as background of the <main> element */ import firebase from '../../db/firebase' import { Switch, EventList, Overlay } from '../Events' import { useState, useEffect } from 'react' import styles from '../Events/styles/events.module.css' const Content = ({ content, upcomingEvents }) => { const { title, body, image } = content const [ eventList, setEventListTo ] = useState(upcomingEvents) const [ viewingFuture, setViewingFutureTo ] = useState(true) const [ currentEvent, setCurrentEventTo ] = useState({}) /* Set the background image */ useEffect(() => { const main = document.querySelector('main') // main.style.marginTop = 0 // main.style.paddingTop = '95px' main.style.backgroundImage = `url(${process.env.NEXT_PUBLIC_BUCKET}/media/images/${image})` }, []) /* Function for fetching events from db */ const fetchEvents = async future => { // dependent variables const now = new Date() const queryBase = firebase.firestore().collection('schedule') // function to transform snapshot into an array of objects // each object is a distinct event (possible with multiple performances) const handleSnapshot = snapshot => { const events = [] snapshot.forEach(doc => {events.push(doc.data())}) return events } // fetch events from db if(!future){ // fetch past events setEventListTo([]) setViewingFutureTo(false) const pastEvents = await queryBase .orderBy('startDate', 'desc') .where('startDate', '<', now) .limit(20) .get() .then(snap => handleSnapshot(snap)) setEventListTo(pastEvents) }else{ // fetch future events setEventListTo([]) setViewingFutureTo(true) const futureEvents = await queryBase .orderBy('endDate', 'asc') .where('endDate', '>=', now) .limit(20) .get() .then(snap => handleSnapshot(snap)) setEventListTo(futureEvents) } } /* Function to open a full-screen overlay - displays selected event's details - slides in from the bottom of the screen */ const openOverlay = details => { document.getElementById('eventOverlay').style.top = 0 setCurrentEventTo(details) } /* Component */ return ( <> <div className={`normal-page-wrapper ${styles.pageWrapper}`} > <h1>{title}</h1> <p>{body}</p> <Switch fetchEvents={fetchEvents} /> { eventList.length ? <EventList events={eventList} future={viewingFuture} openOverlay={openOverlay} /> : "Loading Johann's schedule..." } </div> <Overlay details={currentEvent} /> </> ) } export default Content
import { createRouter, } from '@exponent/ex-navigation' import SettingsScreen from '../screens/SettingsScreen' import RootNavigation from './RootNavigation' import GuestNavigation from './GuestNavigation' import CuponsScreen from '../screens/CuponsScreen' import RestaurantesScreen from '../screens/RestaurantesScreen' import EscanearScreen from '../screens/EscanearScreen' import VouchersScreen from '../screens/VouchersScreen' import PromocoesScreen from '../screens/PromocoesScreen' import RestauranteDetailScreen from '../screens/RestauranteDetail' import CupomDetailScreen from '../screens/CupomDetail' import WelcomeScreen from '../screens/WelcomeScreen' import SignInScreen from '../screens/SignInScreen' import SignUpScreen from '../screens/SignUpScreen' export default createRouter(() => ({ restaurantes: () => RestaurantesScreen, restauranteDetail: () => RestauranteDetailScreen, cupomDetail: () => CupomDetailScreen, cupons: () => CuponsScreen, escanear: () => EscanearScreen, promocoes: () => PromocoesScreen, vouchers: () => VouchersScreen, settings: () => SettingsScreen, rootNavigation: () => RootNavigation, guestNavigation: () => GuestNavigation, signIn: () => SignInScreen, signUp: () => SignUpScreen, welcome: () => WelcomeScreen }))
import "./index.scss"; import $ from "jquery"; import muu from "muu"; function getFileIcon( mimeType, fileName ) { let icon, type; mimeType = mimeType.split("/"); type = mimeType[0]; if ( type === "image" ) { icon = "file-image-o"; } else if ( type === "text" ) { icon = /\.(js|css|scss)$/.test(fileName) ? "file-code-o" : "file-text-o"; } else { icon = "file-o"; } return icon ? `fa-${icon}` : ""; } function resolveFileType( mime, data ) { let type; if ( data.isFile ) { let fileExt = data.name.match(/\.([a-z0-9]+)$/)[1]; let extName = fileExt.toUpperCase(); switch( mime.split("/")[0] ) { case "image": type = `图片文件`; break; case "text": type = `${(["css", "scss", "less"].includes(fileExt) ? "样式表" : ["js", "coffee"].includes(fileExt) ? "脚本" : "纯文本")}文件`; break; default: type = ["woff", "woff2", "ttf", "eot"].includes(fileExt) ? "字体文件" : mime; } } else { type = "文件夹"; } return type; } function copyAssetUrl( url ) { const ipt = document.createElement("input"); ipt.setAttribute("value", url); document.body.appendChild(ipt); ipt.select(); document.execCommand("copy"); document.body.removeChild(ipt); } function initDataTable() { let $sel = $(".Area--query form [name='mode']"); muu.table.init({ url: "/api/assets", queryParams: function() { return muu.form.jsonify($(".Area--query form").serializeArray().concat({ name: "pageSize", value: this.pageSize }, { name: "pageNo", value: this.pageNumber }, { name: "dir", value: window.currentDir }), function (jsonified) { $.each(jsonified, function( k, v ) { jsonified[k] = jsonified[k].toString(); }); return jsonified; }); }, columns: [{ title: "名称", field: "name", formatter: function( val, row ) { let text = `<i class="fa ${row.isFile ? getFileIcon(row.mimeType, val) : "fa-folder"}"></i>${val}`; if ( row.isFile ) { return `<div class="Cell--path">${text}</div>`; } else { return `<a class="Cell--path" href="/assets${row.path}?mode=${window.currentDir === "/" ? "file" : $sel.val()}">${text}</a>` } } }, { title: "类型", field: "mimeType", formatter: resolveFileType, width: 100 }, { title: "大小(KB)", field: "size", formatter: function( val ) { return val ? `${(val / 1000).toFixed(2)}` : "-"; }, width: 100 }, { title: "修改时间", field: "modifiedAt", width: 150 }, { title: "七牛", field: "qiniu", formatter: function( val, row ) { return row.isFile ? `<div class="u-textCenter"><i class="fa fa-circle" style="color: ${val.code === 200 ? "green" : "red"};" data-toggle="tooltip" title="${val.code === 200 ? "正常" : "不存在此文件或发生异常"}" ></i></div>` : "-"; }, width: 60 }, { title: "操作", field: "operation", width: 100, formatter: function( val, row ) { let btns = []; if ( row.url ) { let copyActions = [[{ text: "复制顽兔外链", action: "copyWantuUrl" }]]; let deleteActions = [{ text: "删除顽兔文件", action: "deleteWantuFile" }]; if ( row.qiniu && row.qiniu.code === 200 ) { copyActions[0].push({ text: "复制七牛外链", action: "copyQiniuUrl" }); deleteActions.push({ text: "删除七牛文件", action: "deleteQiniuFile" }); } copyActions.push([{ text: "复制相对路径", action: "copyRelativePath" }]); btns.push({ text: "复制链接", action: "copyLink", icon: "link", actions: copyActions }); // btns.push({ // text: "删除文件", // action: "deleteFile", // icon: "trash", // isDelete: true // }); } return muu.generate.action(btns, true); }, events: { "click .js-copyRelativePath": function( evt, val, row ) { copyAssetUrl(row.path); }, "click .js-copyWantuUrl": function( evt, val, row ) { copyAssetUrl(row.url); }, "click .js-copyQiniuUrl": function( evt, val, row ) { copyAssetUrl(row.qiniu.data.url); }/*, "click .js-deleteFile": function( evt, val, row ) { if ( confirm(`确定要删除存储在 CDN 上的「${row.path}」?`) ) { muu.ajax.delete("/api/assets", {dir: row.dir, name: row.name}, function( res ) { muu.table.refresh(); }); } }*/ } }] }); } function addFilesInfo( files ) { let $list = $("#targetFiles > ul"); if ( !$list.size() ) { $("#targetFiles").prepend(`<ul class="FileList" />`); $list = $("#targetFiles > ul"); } $list.append(files.map(function( f ) { return ` <li class="FileList-item" id="${f.id}"> <button class="FileList-button btn btn-danger btn-xs js-removeFile">删除</button> <div class="FileList-text">${f.name}</div> </li> `; })); } function initNewDataDialog() { let $dlg = $(".js-addNewData"); let $form = $("form", $dlg); let $btn = $(".js-chooseFiles"); let $box = $btn.closest(".FileBox"); let $result = $btn.siblings(".FileBox-result"); if ( $dlg.size() ) { $(".Header-operations").prepend(` <div class="Header-action Action"> <button class="Action-trigger fa fa-plus js-add--header" type="button" data-toggle="modal" data-target=".js-addNewData" title="新增"><span class="sr-only">新增</span></button> </div> `); } let uploader = new plupload.Uploader({ browse_button: $btn.get(0), url: "/api/assets" }); uploader.init(); uploader.bind("FilesAdded", function (up, files) { addFilesInfo(files); }); uploader.bind("FileUploaded", function (up, file, result) { $(`#${file.id} .FileList-text`).text(`文件「${file.name}」上传${result.status === 200 ? "成功" : "失败"}`); }); uploader.bind("UploadComplete", function( up, files ) { muu.table.refresh(); $dlg.modal("hide"); }); uploader.bind("Error", function (up, err) { console.log(err); }); uploader.bind("FilesRemoved", function( up, files ) { files.forEach(function( file ) { $(`#${file.id}`).remove(); }); }); $form.on({ "reset": function() { let $list = $("#targetFiles > ul"); [].map.call($("li", $list), function( li ) { uploader.removeFile(li.id); }); $list.remove(); $("button", $(".modal-header, .modal-footer", $dlg)).prop("disabled", false); $(".js-waitForResult", $dlg).remove(); }, "H5F:submit": function( evt, ins, submitEvt ) { let params = muu.form.jsonify($form); muu.ajax.waiting($form); uploader.setOption("multipart_params", {dir: params.dir || "/"}); uploader.start(); submitEvt.preventDefault(); return false; } }); $dlg.on("hidden.bs.modal", function () { $form.trigger("reset"); }); $("body").on("click", ".js-removeFile", function() { uploader.removeFile($(this).closest(".FileList-item").attr("id")); return false; }); } $(document).ready(function() { initDataTable(); initNewDataDialog(); });
import React, { useState } from "react"; const Login = props => { const setUser = props.setUser; const setLocalStorage = props.setLocalStorage // const setLocalStorage = props.setLocalStorage; const [credentials, setCredentials] = useState({email: "", password: ""}); const [isChecked, setIsChecked] = useState(false) //update state whenever input field is edited const handleFieldChange = event => { const stateToChange = {...credentials }; stateToChange[event.target.id] = event.target.value; //change state based on what the user types (ie change values of properties that coincide with the id of the input field, name and password) setCredentials(stateToChange) }; // localStorage.setItem("credentials", JSON.stringify(credentials)) const handleLogin = event => { event.preventDefault(); //if checkbox is checked, set user login info into localStorage, if checkbox not checked, only set in sessionStorage isChecked ? setLocalStorage(credentials) : setUser(credentials); props.history.push("/") }; return ( <form onSubmit={handleLogin}> <fieldset> <h3> Please Sign In</h3> <div className="formgrid"> <input onChange={handleFieldChange} type="email" id="email" placeholder="Email address" required="" autoFocus="" /> <label htmlFor="inputEmail"> Email address </label> <input onChange={handleFieldChange} type="password" id="password" placeholder="Password" required="" /> <label htmlFor="inputPassword">Password</label> <input onChange={() => setIsChecked(true)} type="checkbox" checked={isChecked} /> <label htmlFor="checkbox">Remember Me</label> </div> <button type="submit">Sign in</button> </fieldset> </form> ); }; export default Login
import { GET_SENSOR_STATUS_SUCCESS, GET_SENSOR_STATUS_LOADING, UPDATE_SENSOR_STATUS, DISABLE_ALL_SENSORS, ENABLE_ALL_SENSORS } from './sensor.actionType' import firebase from 'firebase' import { database } from '../../firebase/firebase' import { homeUnlock, homePinAccessSuccess } from '../housePin/housePin.actions' export const getSensorStatus = () => { /* istanbul ignore next */ return dispatch => { /* istanbul ignore next */ dispatch(getSensorStatusLoading()) /* istanbul ignore next */ database().ref('/smarthome/sensors').on('value', (snap) => { let data = snap.val() /* istanbul ignore next */ dispatch(getSensorStatusSuccess(data)) }, (err) => { console.log(err) }) } } export const updateSensorStatus = (payload) => { /* istanbul ignore next */ return dispatch => { /* istanbul ignore next */ let val = (payload.value) ? 1 : 0 /* istanbul ignore next */ database().ref(`/smarthome/sensors/${payload.type}`).set(val) .then(() => { /* istanbul ignore next */ checkSensorStatus() /* istanbul ignore next */ dispatch(updateSensorStatusSuccess()) }) } } export const disableSensors = () => { return dispatch => { /* istanbul ignore next */ database().ref('/smarthome/sensors/door').set(0) /* istanbul ignore next */ database().ref('/smarthome/sensors/garage').set(0) /* istanbul ignore next */ database().ref('/smarthome/sensors/gas').set(0) .then(() => { /* istanbul ignore next */ dispatch(disableAllSensors()) }) } } export const enableSensors = () => { return dispatch => { database().ref('/smarthome/sensors/door').set(1) database().ref('/smarthome/sensors/garage').set(1) database().ref('/smarthome/sensors/gas').set(1) .then(() => { /* istanbul ignore next */ dispatch(enableAllSensors()) }) } } const getSensorStatusSuccess = (payload) => ({ type: GET_SENSOR_STATUS_SUCCESS, payload: payload }) const getSensorStatusLoading = () => ({ type: GET_SENSOR_STATUS_LOADING }) const updateSensorStatusSuccess = () => ({ type: UPDATE_SENSOR_STATUS }) const disableAllSensors = () => ({ type: DISABLE_ALL_SENSORS }) const enableAllSensors = () => ({ type: ENABLE_ALL_SENSORS })
Ext.define('extjs5.view.content.ContentController', { extend : 'Ext.app.ViewController', alias : 'controller.content' });
$(function(){ // logout $("#logoutBtn").click(function(){ layer.confirm( I18n.logout_confirm , { icon: 3, title: I18n.system_tips , btn: [ I18n.system_ok, I18n.system_cancel ] }, function(index){ layer.close(index); $.post(base_url + "/logout", function(data, status) { if (data.code == "200") { layer.msg( I18n.logout_success ); setTimeout(function(){ window.location.href = base_url + "/"; }, 500); } else { layer.open({ title: I18n.system_tips , btn: [ I18n.system_ok ], content: (data.msg || I18n.logout_fail), icon: '2' }); } }); }); }); // slideToTop var slideToTop = $("<div />"); slideToTop.html('<i class="fa fa-chevron-up"></i>'); slideToTop.css({ position: 'fixed', bottom: '20px', right: '25px', width: '40px', height: '40px', color: '#eee', 'font-size': '', 'line-height': '40px', 'text-align': 'center', 'background-color': '#222d32', cursor: 'pointer', 'border-radius': '5px', 'z-index': '99999', opacity: '.7', 'display': 'none' }); slideToTop.on('mouseenter', function () { $(this).css('opacity', '1'); }); slideToTop.on('mouseout', function () { $(this).css('opacity', '.7'); }); $('.wrapper').append(slideToTop); $(window).scroll(function () { if ($(window).scrollTop() >= 150) { if (!$(slideToTop).is(':visible')) { $(slideToTop).fadeIn(500); } } else { $(slideToTop).fadeOut(500); } }); $(slideToTop).click(function () { $("html,body").animate({ // firefox ie not support body, chrome support body. but found that new version chrome not support body too. scrollTop: 0 }, 100); }); // left menu status v: js + server + cookie $('.sidebar-toggle').click(function(){ var xxljob_adminlte_settings = $.cookie('xxljob_adminlte_settings'); // on=open,off=close if ('off' == xxljob_adminlte_settings) { xxljob_adminlte_settings = 'on'; } else { xxljob_adminlte_settings = 'off'; } $.cookie('xxljob_adminlte_settings', xxljob_adminlte_settings, { expires: 7 }); //$.cookie('the_cookie', '', { expires: -1 }); }); // left menu status v1: js + cookie /* var xxljob_adminlte_settings = $.cookie('xxljob_adminlte_settings'); if (xxljob_adminlte_settings == 'off') { $('body').addClass('sidebar-collapse'); } */ // update pwd $('#updatePwd').on('click', function(){ $('#updatePwdModal').modal({backdrop: false, keyboard: false}).modal('show'); }); var updatePwdModalValidate = $("#updatePwdModal .form").validate({ errorElement : 'span', errorClass : 'help-block', focusInvalid : true, rules : { password : { required : true , rangelength:[4,50] } }, messages : { password : { required : '请输入密码' , rangelength : "密码长度限制为4~50" } }, highlight : function(element) { $(element).closest('.form-group').addClass('has-error'); }, success : function(label) { label.closest('.form-group').removeClass('has-error'); label.remove(); }, errorPlacement : function(error, element) { element.parent('div').append(error); }, submitHandler : function(form) { $.post(base_url + "/user/updatePwd", $("#updatePwdModal .form").serialize(), function(data, status) { if (data.code == 200) { $('#updatePwdModal').modal('hide'); layer.msg( I18n.change_pwd_suc_to_logout ); setTimeout(function(){ $.post(base_url + "/logout", function(data, status) { if (data.code == 200) { window.location.href = base_url + "/"; } else { layer.open({ icon: '2', content: (data.msg|| I18n.logout_fail) }); } }); }, 500); } else { layer.open({ icon: '2', content: (data.msg|| I18n.change_pwd + I18n.system_fail ) }); } }); } }); $("#updatePwdModal").on('hide.bs.modal', function () { $("#updatePwdModal .form")[0].reset(); updatePwdModalValidate.resetForm(); $("#updatePwdModal .form .form-group").removeClass("has-error"); }); });
'use strict' const NotificationAppType = Object.freeze({WEB:1, API:2, ANDROID:3, IOS:4}); module.exports = NotificationAppType;
import io from 'socket.io-client'; export const JOIN_ROOM = 'JOIN_ROOM'; export const LEAVE_ROOM = 'LEAVE_ROOM'; export const ATTEMPT_JOIN = 'ATTEMPT_JOIN'; export const ATTEMPT_FAILED = 'ATTEMPT_FAILED'; export function setSocket(socket) { return { type: JOIN_ROOM, socket }; } export function disconnect() { return { type: LEAVE_ROOM }; } export function validating() { return { type: ATTEMPT_JOIN }; } export function failed() { return { type: ATTEMPT_FAILED }; }
const Users = require('./handler/userHandling'); const API = require('./handler/stockApi'); module.exports = { name: 'buy', description: 'Buying functionality', async execute(message, args, Discord, client) { console.log("@buy: "+message.author.username + " " + args) //const channel = '830936886473261066'; /* if(message.channel!=channel) { message.channel.send("Please move to the correct channel to Buy and Sell."); return }*/ if (args[0]==null||args[1]==null) { message.channel.send("Please enter a valid command."); return } if(args[0]=="all") var buyingAll = true; else { var amount = parseInt(args[0]) if(amount < 0) { message.channel.send("Please enter a valid amount."); return; } } var symbol = args[1].toUpperCase() var user = message.author.username const checkmark = '✅'; const xmark = '❌'; const icon = '🟦'; Users.getUser(user).then( (data)=>{ var subject = data; API.getQuote(symbol).then( async (response)=>{ var tempBalance = subject.balance var max = 0; var value = parseFloat(response.close) while(tempBalance>value) { tempBalance-=value; max++; } if(max==0) { } if(buyingAll) amount = max; var clicked = false; if(response.name==undefined) { message.channel.send("That stock is unavailable."); return } var price = amount * value; var remBalance = subject.balance - price // Calculating the most a person can buy. let embed = new Discord.MessageEmbed() .setColor("#2ab0ff") .setTitle("**"+subject.name+"**:\nBuying "+amount+" of "+response.name) .setDescription(symbol +" Market Values:") .addFields( {name:"Valued at:", value:currencyFormatDE(parseFloat(response.close)), inline:true}, {name:"Recent change:", value:volumeFormatDE(parseFloat(response.change)), inline:true}, {name:"_", value:"**Price:** " + currencyFormatDE(price) +"\n\n**Current Balance:** " + currencyFormatDE(subject.balance) +"\n**Remaining Balance:** "+currencyFormatDE(remBalance) }, {name:"Most you can buy:", value:max}, ) let messageEmbed = await message.channel.send(embed); messageEmbed.react(checkmark); messageEmbed.react(xmark); if(amount==0) { message.channel.send("You just can't afford any . . ."); return; } client.on('messageReactionAdd', async (reaction, user)=>{ if(reaction.message.partial) await reaction.message.fetch(); if(reaction.partial) await reaction.fetch(); if(user.bot) return; if(!reaction.message.guild) return; if(true) { if(!clicked) { if(reaction.emoji.name===checkmark && user.id==message.author.id) { if(remBalance>0) { subject.balance = remBalance if(subject[symbol]==null) { subject[symbol]={ amount: amount, purchasedValue: parseFloat(response.close) } } else { subject[symbol].amount+=amount; subject[symbol].purchasedValue=parseFloat(response.close); } message.channel.send("**PURCHASED:** `"+amount+" "+symbol+'`'); Users.setUser(subject); clicked = true; return; } else { message.channel.send("You do not have that money . . ."); Users.setUser(subject); clicked = true; return } } if(reaction.emoji.name===xmark && user.id==message.author.id) { clicked = true; message.channel.send("**CANCELLED ORDER**"); return; } } else { return } } else return; }) }) }).catch((error)=>{ message.channel.send("You don't seem to have a portfolio."); }) function currencyFormatDE(num) { return ( num .toFixed(2) // always two decimal digits .replace('.', '.') // replace decimal point character with , .replace('$1.') + ' $' ) // use . as a separator } function volumeFormatDE(num) { return ( num .toFixed(2) // always two decimal digits .replace('.', '.') // replace decimal point character with , .replace('$1.') ) // use . as a separator } } }
import $ from '../../core/renderer'; import { extend } from '../../core/utils/extend'; import { isFunction } from '../../core/utils/type'; import { getWindow, hasWindow } from '../../core/utils/window'; import Widget from '../widget/ui.widget'; import Drawer from '../drawer/ui.drawer'; import SplitterControl from '../splitter'; var window = getWindow(); var ADAPTIVE_STATE_SCREEN_WIDTH = 573; var FILE_MANAGER_ADAPTIVITY_DRAWER_PANEL_CLASS = 'dx-filemanager-adaptivity-drawer-panel'; var DRAWER_PANEL_CONTENT_INITIAL = 'dx-drawer-panel-content-initial'; var DRAWER_PANEL_CONTENT_ADAPTIVE = 'dx-drawer-panel-content-adaptive'; class FileManagerAdaptivityControl extends Widget { _initMarkup() { super._initMarkup(); this._initActions(); this._isInAdaptiveState = false; var $drawer = $('<div>').appendTo(this.$element()); $('<div>').addClass(FILE_MANAGER_ADAPTIVITY_DRAWER_PANEL_CLASS).appendTo($drawer); this._drawer = this._createComponent($drawer, Drawer); this._drawer.option({ opened: true, template: this._createDrawerTemplate.bind(this) }); $(this._drawer.content()).addClass(DRAWER_PANEL_CONTENT_INITIAL); var $drawerContent = $drawer.find(".".concat(FILE_MANAGER_ADAPTIVITY_DRAWER_PANEL_CLASS)).first(); var contentRenderer = this.option('contentTemplate'); if (isFunction(contentRenderer)) { contentRenderer($drawerContent); } this._updateDrawerMaxSize(); } _createDrawerTemplate(container) { this.option('drawerTemplate')(container); this._splitter = this._createComponent('<div>', SplitterControl, { container: this.$element(), leftElement: $(this._drawer.content()), rightElement: $(this._drawer.viewContent()), onApplyPanelSize: this._onApplyPanelSize.bind(this), onActiveStateChanged: this._onActiveStateChanged.bind(this) }); this._splitter.$element().appendTo(container); this._splitter.disableSplitterCalculation(true); } _render() { super._render(); this._checkAdaptiveState(); } _onApplyPanelSize(e) { if (!hasWindow()) { return; } if (!this._splitter.isSplitterMoved()) { this._setDrawerWidth(''); return; } $(this._drawer.content()).removeClass(DRAWER_PANEL_CONTENT_INITIAL); this._setDrawerWidth(e.leftPanelWidth); } _onActiveStateChanged(_ref) { var { isActive } = _ref; this._splitter.disableSplitterCalculation(!isActive); !isActive && this._splitter.$element().css('left', 'auto'); } _setDrawerWidth(width) { $(this._drawer.content()).css('width', width); this._updateDrawerMaxSize(); this._drawer.resizeViewContent(); } _updateDrawerMaxSize() { this._drawer.option('maxSize', this._drawer.getRealPanelWidth()); } _dimensionChanged(dimension) { if (!dimension || dimension !== 'height') { this._checkAdaptiveState(); } } _checkAdaptiveState() { var oldState = this._isInAdaptiveState; this._isInAdaptiveState = this._isSmallScreen(); if (oldState !== this._isInAdaptiveState) { this.toggleDrawer(!this._isInAdaptiveState, true); $(this._drawer.content()).toggleClass(DRAWER_PANEL_CONTENT_ADAPTIVE, this._isInAdaptiveState); this._raiseAdaptiveStateChanged(this._isInAdaptiveState); } if (this._isInAdaptiveState && this._isDrawerOpened()) { this._updateDrawerMaxSize(); } } _isSmallScreen() { return $(window).width() <= ADAPTIVE_STATE_SCREEN_WIDTH; } _isDrawerOpened() { return this._drawer.option('opened'); } _initActions() { this._actions = { onAdaptiveStateChanged: this._createActionByOption('onAdaptiveStateChanged') }; } _raiseAdaptiveStateChanged(enabled) { this._actions.onAdaptiveStateChanged({ enabled }); } _getDefaultOptions() { return extend(super._getDefaultOptions(), { drawerTemplate: null, contentTemplate: null, onAdaptiveStateChanged: null }); } _optionChanged(args) { var name = args.name; switch (name) { case 'drawerTemplate': case 'contentTemplate': this.repaint(); break; case 'onAdaptiveStateChanged': this._actions[name] = this._createActionByOption(name); break; default: super._optionChanged(args); } } isInAdaptiveState() { return this._isInAdaptiveState; } toggleDrawer(showing, skipAnimation) { this._updateDrawerMaxSize(); this._drawer.option('animationEnabled', !skipAnimation); this._drawer.toggle(showing); var isSplitterActive = this._isDrawerOpened() && !this.isInAdaptiveState(); this._splitter.toggleDisabled(!isSplitterActive); } } export default FileManagerAdaptivityControl;
import assert from 'assert'; import {roundToBase as rounder} from '../src/round'; describe('rounder', () => { let expected = new Map([ [11, 10], [16, 10], [22, 20], [97, 90], [127, 100], [179, 100], ]); expected.forEach((rounded, input) => { it(`converts "${input}" to "${rounded}"`, () => { assert.strictEqual(rounded, rounder(input)); }); }); });
const middlewares = require("./middlewares"); const multer = require("multer"); const path = require("path"); // //set storage engine (multer) const storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, "public/uploads"); }, filename: function (req, file, callback) { callback( null, file.fieldname + "-" + Date.now() + "-" + req.session.userData.pseudonyme + path.extname(file.originalname) ); }, }); const upload = multer({ storage: storage, onError: function (err, next) { console.log("error", err); next(err); }, }); // creator of a unique id; const { v4: uuidv4 } = require("uuid"); // handling of the environnement require("dotenv").config(); const express = require("express"); const route = express.Router(); const MongoClient = require("mongodb").MongoClient; // link to the database. const uri = "mongodb+srv://frudent:toLi62tL7wdlali3@cluster0-3woch.mongodb.net/test?retryWrites=true&w=majority"; // gestion of nodemailer to send an email with the new password const nodemailer = require("nodemailer"); let transporter = nodemailer.createTransport({ service: "gmail", auth: { user: process.env.EMAIL, pass: process.env.PASSWORD, // generated ethereal password }, }); let mailOptions = function (receiver, newPassword) { return { from: "assistance@socialjoke.fr", to: receiver, subject: "Your new password", text: "your new password to connect is : " + newPassword, html: "<p> your new password to connect is : " + newPassword + " </p>", }; }; const response = { userData: {}, isLogged: false, message: "", error: false, errorMessage: "", }; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, }); // Une route post login route.post("/login", (req, res) => { response.userData = { pseudonyme: req.body.pseudonyme, password: req.body.password, }; //////////////// CONNEXION TO DATABASE : client.connect((err, client) => { let DB = client.db("social_jokes"); let collection = DB.collection("users"); // first I check to see if a matching pseudonyme exists in the DB : collection .find({ pseudonyme: response.userData.pseudonyme }) .toArray(function (err, result) { if (err) { console.log(err); } if (!result.length) { response.errorMessage = "user name incorrect"; response.error = true; res.json(response); } else { const informationsUser = result[0]; if (response.userData.password === informationsUser.password) { response.message = " You are logged!"; response.error = false; response.isLogged = true; response.userData = { pseudonyme: informationsUser.pseudonyme, password: informationsUser.password, favs: informationsUser.favs, description: informationsUser.description, name: informationsUser.name, firstname: informationsUser.firstname, gender: informationsUser.gender, age: informationsUser.age, email: informationsUser.email, avatar: informationsUser.avatar, isAdministrator: informationsUser.administrator, isLogged: true, }; if (informationsUser.avatar) { response.userData.avatar = informationsUser.avatar; } req.session.userData = response.userData; res.json(response); } else { response.errorMessage = "password incorrect"; response.error = true; response.isLogged = false; res.json(response); } } }); }); }); route.post("/register", (req, res) => { response.userData = { pseudonyme: req.body.pseudonyme, password: req.body.password, email: req.body.email, name: req.body.name, firstname: req.body.firstname, isLogged: true, isAdmin: false, }; client.connect((err) => { if (err) { console.log(err); } let db = client.db("social_jokes"); let collection = db.collection("users"); collection .find({ pseudonyme: req.body.pseudonyme }) .toArray(function (err, result) { if (err) { console.log(err); } if (!result.length) { req.session.userData = response.userData; let insertion = {}; insertion.pseudonyme = req.body.pseudonyme; insertion.password = req.body.password; insertion.email = req.body.email; insertion.name = req.body.name; insertion.firstname = req.body.firstname; collection.insertOne(insertion, (err, result) => { response.message = " You are logged!"; response.error = false; response.isLogged = true; res.json(response); }); } else { response.errorMessage = "the username is already used"; response.error = true; response.isLogged = false; res.json(response); } }); }); }); route.post("/update/userdetails", (req, res) => { let userDataAdding = { pseudonyme: req.body.pseudonyme, }; if (req.body.age) { userDataAdding.age = parseInt(req.body.age); } if (req.body.description) { userDataAdding.description = req.body.description; } if (req.body.favs) { userDataAdding.favs = req.body.favs; } if (req.body.gender) { userDataAdding.gender = req.body.gender; } response.userDataAdding = userDataAdding; client.connect((err) => { if (err) { console.log(err); } let db = client.db("social_jokes"); let collection = db.collection("users"); collection .findOneAndUpdate( { pseudonyme: req.body.pseudonyme }, { $set: { age: userDataAdding.age, gender: userDataAdding.gender, description: userDataAdding.description, favs: userDataAdding.favs, }, } ) .then((result) => { if (!result.value) { response.errorMessage = "something went wrong"; response.error = true; res.json(response); } else { response.error = false; response.message = true; response.messageToShow = " Your profile has been updated ! "; res.json(response); } }) .catch((err) => { console.log(err); }); }); }); route.post("/passwordforgotten", (req, res) => { response.userData = { email: req.body.email, }; client.connect((err) => { let newPassword = uuidv4(); if (err) { console.log(err); } let db = client.db("social_jokes"); let collection = db.collection("users"); collection .findOneAndUpdate( { email: req.body.email }, { $set: { password: newPassword, }, } ) .then((result) => { if (!result.value) { response.errorMessage = "email adress incorrect"; response.error = true; res.json(response); } else { response.messageToShow = "An email has been send to your email adress with your new password."; response.error = false; response.message = true; response.mailSent = true; res.json(response); transporter.sendMail( mailOptions(req.body.email, newPassword), function (err, data) { if (err) { console.log(err); } else { console.log("email sent"); } } ); } }); }); }); route.delete( "/delete/:pseudonyme", middlewares.isThisUserAdmin, (req, res, next) => { let pseudonyme = req.params.pseudonyme; client.connect((err) => { let response = {}; if (err) { console.log(err); } let db = client.db("social_jokes"); let collection = db.collection("users"); collection.deleteOne({ pseudonyme: pseudonyme }).catch((err) => { console.log(err); }); response.message = `the user ${pseudonyme} has been deleted`; res.json(response); }); } ); route.post("/upload", upload.single("avatar"), (req, res, next) => { let avatar = req.file.filename; client.connect((err) => { if (err) { console.log(err); } let db = client.db("social_jokes"); let collection = db.collection("users"); collection .findOneAndUpdate( { pseudonyme: req.session.userData.pseudonyme }, { $set: { avatar: "uploads/" + avatar, }, } ) .then((result) => { if (!result.value) { response.errorMessage = "something went wrong"; response.error = true; res.json(response); } else { response.error = false; response.message = true; response.messageToShow = " Your profile has been updated ! "; res.json(response); } }) .catch((err) => { console.log(err); }); }); }); module.exports = route;
const axios = require('axios'); const getYelp = async ({ category, latitude, longitude }) => { const baseUrl = 'https://api.yelp.com/v3/businesses/search?'; const apiKey = process.env.YELP_APIKEY; const query = `term=restaurants&categories=${category}&latitude=${latitude}&longitude=${longitude}&sort_by=distance`; const url = baseUrl + query; const options = { headers: { Authorization: `Bearer ${apiKey}` } }; try { const response = await axios.get(url, options); return response; } catch (error) { console.log('Error when requesting to Yelp:'); console.error(error); } }; module.exports = getYelp;
const PATTERNS = { en: { 'patterns.all': 'All', 'patterns.large-spike': 'Large spike', 'patterns.small-spike': 'Small spike', 'patterns.fluctuating': 'Fluctuating', 'patterns.decreasing': 'Decreasing' }, zhCNS: { 'patterns.all': '综合', 'patterns.large-spike': '大涨型', 'patterns.small-spike': '小涨型', 'patterns.fluctuating': '波动型', 'patterns.decreasing': '递减型' } } let patterns = PATTERNS.zhCNS try { const lang = $('html').attr('lang') const pat = PATTERNS[lang] if (pat) patterns = pat } catch (err) {} window.i18next = { t: function (val) { return patterns[val] } }
function openChat(latency, expires, callback) { if (parseCookie('loaded') !== '') { callback(true); } else { var date = new Date(); date.setTime(date.getTime() + expires * 24*60*60*1000); setTimeout(function(){ document.cookie += 'loaded=true;expires=' + date.toUTCString() + ';'; callback(false); }, latency); } } function parseCookie(key){ key += '='; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(key) == 0) return c.substring(key.length,c.length); } return ''; }
'use strict' const exec = require('child_process').execSync const split = Buffer.from('0D1B', 'hex') // Buffer.from('0D1B5B3964', 'hex') let out = exec("htop << f\nq\nf").toString() // run htop for a sec out = out.substr(80).split(String(split))[0].split(' PID USER ')[0] console.log(out.substr(0, out.length - 3)) // console.log("\n\n\n\n\n\n") //add line breaks (because reset)
import { StyleSheet } from 'react-native'; export default StyleSheet.create({ 'li': { 'listStyle': 'none' }, 'a': { 'textDecoration': 'none' }, 'h2': { 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }] }, 'li': { 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }] }, 'p': { 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }] }, 'ul': { 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }] }, 'em': { 'fontWeight': '400', 'fontStyle': 'normal' }, 'title': { 'display': 'inline-block', 'marginTop': [{ 'unit': 'px', 'value': 12 }], 'padding': [{ 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 10 }], 'width': [{ 'unit': 'px', 'value': 860 }], 'height': [{ 'unit': 'px', 'value': 230 }], 'borderRadius': '2px', 'color': '#fff', 'textAlign': 'center', 'fontFamily': 'Open Sans,sans-serif', 'lineHeight': [{ 'unit': 'em', 'value': 1.5 }] }, 'title h2': { 'marginTop': [{ 'unit': 'px', 'value': 10 }], 'marginLeft': [{ 'unit': 'px', 'value': 10 }], 'color': '#007160', 'textTransform': 'uppercase', 'fontWeight': 'bold', 'fontSize': [{ 'unit': 'px', 'value': 42 }], 'lineHeight': [{ 'unit': 'em', 'value': 1.4 }], 'letterSpacing': [{ 'unit': 'px', 'value': 6 }] }, 'box': { 'position': 'relative' }, 'nav': { 'position': 'absolute', 'bottom': [{ 'unit': 'px', 'value': 44 }], 'left': [{ 'unit': '%H', 'value': 0.5 }], 'marginLeft': [{ 'unit': 'px', 'value': -50 }], 'width': [{ 'unit': 'px', 'value': 100 }], 'height': [{ 'unit': 'px', 'value': 14 }] }, 'nav ul li': { 'float': 'left', 'display': 'inline', 'marginRight': [{ 'unit': 'px', 'value': 6 }], 'width': [{ 'unit': 'px', 'value': 10 }], 'height': [{ 'unit': 'px', 'value': 10 }], 'border': [{ 'unit': 'string', 'value': 'none' }], 'border': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#8BC34A' }], 'borderRadius': '50%', 'background': '#fff' }, 'nav ul bg': { 'width': [{ 'unit': 'px', 'value': 10 }], 'height': [{ 'unit': 'px', 'value': 10 }], 'border': [{ 'unit': 'string', 'value': 'none' }], 'background': '#8bc34a' }, 'nav ul bg': { 'width': [{ 'unit': 'px', 'value': 10 }], 'height': [{ 'unit': 'px', 'value': 10 }], 'border': [{ 'unit': 'string', 'value': 'none' }], 'background': '#8bc34a' }, 'nav ul': { 'width': [{ 'unit': '%H', 'value': 1 }], 'height': [{ 'unit': 'px', 'value': 14 }] }, 'pic ul li': { 'position': 'relative', 'overflow': 'hidden', 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }], 'width': [{ 'unit': '%H', 'value': 1 }], 'height': [{ 'unit': 'px', 'value': 400 }], 'backgroundSize': 'contain', 'listStyle': 'none', 'textAlign': 'center' }, 'pic': { 'position': 'relative', 'overflow': 'hidden', 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }], 'width': [{ 'unit': '%H', 'value': 1 }], 'height': [{ 'unit': 'string', 'value': 'auto' }], 'maxHeight': [{ 'unit': 'px', 'value': 400 }] }, 'pic ul': { 'maxHeight': [{ 'unit': 'px', 'value': 400 }] }, '#picShow li img': { 'width': [{ 'unit': '%H', 'value': 1 }], 'maxWidth': [{ 'unit': '%H', 'value': 1 }], 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'display': 'inline-block', 'verticalAlign': 'middle', 'maxWidth': [{ 'unit': '%H', 'value': 1 }], 'height': [{ 'unit': 'string', 'value': 'auto' }] }, 'wrap': { 'position': 'absolute', 'top': [{ 'unit': 'px', 'value': 0 }], 'left': [{ 'unit': 'px', 'value': 0 }], 'width': [{ 'unit': '%H', 'value': 1 }], 'height': [{ 'unit': '%V', 'value': 1 }] }, 'boxBtn': { 'position': 'absolute', 'top': [{ 'unit': '%V', 'value': 0.5 }], 'display': 'inline-block', 'marginTop': [{ 'unit': 'px', 'value': -40 }], 'width': [{ 'unit': 'px', 'value': 60 }], 'height': [{ 'unit': 'px', 'value': 80 }], 'WebkitBorderRadius': '2px', 'borderRadius': '2px', 'background': 'url(../images/bt-next.png) #000 no-repeat center center', 'opacity': '.5' }, 'boxBtn:hover': { 'opacity': '1' }, 'moreDetail pictext2': { 'display': 'block', 'color': '#007160', 'textTransform': 'uppercase', 'fontSize': [{ 'unit': 'px', 'value': 20 }], 'padding': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'px', 'value': 1 }, { 'unit': 'px', 'value': 1 }, { 'unit': 'px', 'value': 1 }] }, 'moreDetail picArrow': { 'position': 'relative', 'display': 'inline-block', 'marginTop': [{ 'unit': 'px', 'value': 20 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 16 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 16 }], 'height': [{ 'unit': 'px', 'value': 36 }], 'border': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#fff' }], 'borderRadius': '2px', 'background': '#007160', 'color': '#fff', 'verticalAlign': 'middle', 'textAlign': 'center', 'textTransform': 'uppercase', 'letterSpacing': [{ 'unit': 'em', 'value': 0.1 }], 'fontWeight': '700', 'fontSize': [{ 'unit': 'px', 'value': 14 }], 'lineHeight': [{ 'unit': 'em', 'value': 1 }], 'lineHeight': [{ 'unit': 'px', 'value': 36 }] }, 'moreDetail picArrow svg': { 'marginTop': [{ 'unit': 'px', 'value': -3 }], 'marginLeft': [{ 'unit': 'px', 'value': 6 }], 'width': [{ 'unit': 'px', 'value': 16 }], 'height': [{ 'unit': 'px', 'value': 16 }], 'border': [{ 'unit': 'string', 'value': 'none' }], 'fill': '#fff' }, 'line': { 'display': 'inline-block', 'width': [{ 'unit': 'px', 'value': 200 }], 'border': [{ 'unit': 'string', 'value': 'none' }] }, '#boxPrev': { 'left': [{ 'unit': 'px', 'value': 80 }], 'background': 'url(../images/bt-prev.png) #000 no-repeat center center', 'backgroundSize': '20px' }, '#boxNext': { 'right': [{ 'unit': 'px', 'value': 80 }], 'backgroundSize': '20px' }, '#pic0 h2': { 'marginLeft': [{ 'unit': 'px', 'value': 0 }], 'textAlign': 'center' }, '#pic0 pictext2': { 'fontSize': [{ 'unit': 'px', 'value': 20 }] }, '#pic0 title': { 'width': [{ 'unit': 'px', 'value': 740 }], 'textAlign': 'center', 'background': 'rgba(255,255,255,0.82)', 'borderRadius': '5', 'marginTop': [{ 'unit': 'px', 'value': 50 }] }, '#pic0 svg': { 'fill': '#fff' }, '#pic2 h2': { 'color': '#fdfdfd' }, '#pic1 title': { 'marginTop': [{ 'unit': 'px', 'value': 40 }], 'height': [{ 'unit': 'px', 'value': 180 }], 'width': [{ 'unit': 'px', 'value': 900 }], 'background': 'rgba(255,255,255,0.88)', 'borderRadius': '8px' }, '#pic1 h2': { 'color': '#4CAF50' }, '#pic1 pictext2': { 'color': '#444', 'fontSize': [{ 'unit': 'px', 'value': 20 }], 'marginLeft': [{ 'unit': 'px', 'value': 10 }], 'textTransform': 'uppercase', 'fontWeight': 'bold' }, '#pic1 picArrow': { 'borderColor': '#4CAF50', 'background': '#4CAF50', 'color': '#fff', 'marginLeft': [{ 'unit': 'px', 'value': 10 }] }, '#pic1 em': { 'fontWeight': '700' }, '#pic1 svg': { 'marginTop': [{ 'unit': 'px', 'value': -3 }], 'fill': '#fff' }, '#pic1 title': { 'marginTop': [{ 'unit': 'px', 'value': 70 }], 'height': [{ 'unit': 'px', 'value': 178 }] }, '#pic0 title': { 'marginTop': [{ 'unit': 'px', 'value': 54 }] }, // **************services.css ******************************** 'h2': { 'marginBottom': [{ 'unit': 'px', 'value': 0 }] }, 'em': { 'fontWeight': 'normal', 'fontStyle': 'normal' }, 'Top svg': { 'height': [{ 'unit': 'px', 'value': 30 }], 'fill': '#77C855', 'display': 'block', 'textAlign': 'center', 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'px', 'value': 10 }, { 'unit': 'string', 'value': 'auto' }] }, 'Service-module': { 'width': [{ 'unit': 'px', 'value': 1000 }], 'textAlign': 'center', 'position': 'relative', 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }], 'height': [{ 'unit': 'px', 'value': 110 }], 'position': 'relative', 'zIndex': '99', 'marginTop': [{ 'unit': 'px', 'value': -30 }] }, 'Service-module Top': { 'padding': [{ 'unit': 'px', 'value': 5 }, { 'unit': 'px', 'value': 5 }, { 'unit': 'px', 'value': 5 }, { 'unit': 'px', 'value': 5 }], 'verticalAlign': 'middle', 'height': [{ 'unit': 'px', 'value': 80 }], 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }], 'display': 'inline-block', 'borderRadius': '4px', 'width': [{ 'unit': 'px', 'value': 280 }], 'paddingTop': [{ 'unit': 'px', 'value': 10 }], 'background': '#fff', 'boxShadow': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 2 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'rgba(0, 0, 0, 0.15)' }] }, '#pic2 h2': { 'fontWeight': 'bolder', 'fontSize': [{ 'unit': 'px', 'value': 54 }], 'letterSpacing': [{ 'unit': 'px', 'value': 3 }], 'lineHeight': [{ 'unit': 'em', 'value': 1.1 }], 'textAlign': 'right' }, '#pic2 h2 span': { 'fontWeight': '300', 'fontSize': [{ 'unit': 'px', 'value': 40 }], 'letterSpacing': [{ 'unit': 'px', 'value': 3 }], 'textAlign': 'right' }, '#pic2 smalltext': { 'textAlign': 'right', 'color': '#fff', 'marginTop': [{ 'unit': 'px', 'value': 20 }] }, '#pic2 pictext2': { 'color': '#fff', 'fontWeight': '100' }, '#pic2 picArrow': { 'borderColor': '#ea3e39', 'background': '#ea3e39', 'color': '#fff' }, '#pic2 em': { 'fontWeight': '700' }, '#pic2 svg': { 'marginTop': [{ 'unit': 'px', 'value': -3 }], 'fill': '#fff' }, '#pic2 title': { 'marginTop': [{ 'unit': 'px', 'value': 50 }], 'marginRight': [{ 'unit': 'px', 'value': 290 }] }, '#pic2 wrap': { 'textAlign': 'right' }, '#pic3 wrap': { 'top': [{ 'unit': 'px', 'value': 20 }], 'right': [{ 'unit': 'px', 'value': 20 }], 'left': [{ 'unit': 'px', 'value': 20 }], 'bottom': [{ 'unit': 'px', 'value': 20 }], 'width': [{ 'unit': 'string', 'value': 'auto' }], 'height': [{ 'unit': 'string', 'value': 'auto' }], 'border': [{ 'unit': 'px', 'value': 2 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#fff' }] }, '#pic3 title': { 'marginTop': [{ 'unit': 'px', 'value': 22 }], 'width': [{ 'unit': 'px', 'value': 698 }], 'height': [{ 'unit': 'px', 'value': 240 }], 'textAlign': 'center' }, '#pic3 title h2': { 'marginTop': [{ 'unit': 'px', 'value': 0 }], 'color': '#fff', 'fontSize': [{ 'unit': 'px', 'value': 50 }], 'textAlign': 'center', 'lineHeight': [{ 'unit': 'em', 'value': 1.2 }] }, '#pic3 title svg': { 'fill': '#fff' }, '#pic3 pictext2': { 'color': '#fff', 'fontSize': [{ 'unit': 'px', 'value': 20 }], 'paddingLeft': [{ 'unit': 'px', 'value': 10 }], 'lineHeight': [{ 'unit': 'em', 'value': 1.5 }], 'textAlign': 'center', 'letterSpacing': [{ 'unit': 'px', 'value': 1 }], 'marginTop': [{ 'unit': 'px', 'value': 20 }] }, '#pic3 picArrow': { 'color': '#fff', 'marginLeft': [{ 'unit': 'px', 'value': 10 }] }, '#pic3 moreDetail picArrow': { 'background': '#fff', 'color': '#670001' }, '#pic3 moreDetail svg': { 'fill': '#670001' }, '#pic4 title': { 'marginTop': [{ 'unit': 'px', 'value': 56 }], 'marginLeft': [{ 'unit': 'px', 'value': 290 }], 'width': [{ 'unit': 'px', 'value': 586 }], 'height': [{ 'unit': 'px', 'value': 260 }], 'textAlign': 'left', 'float': 'left', 'background': '#fafff0', 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'borderRadius': '2px' }, '#pic4 title h2': { 'fontWeight': 'bold', 'fontSize': [{ 'unit': 'px', 'value': 32 }], 'textAlign': 'right', 'color': '#fafff0', 'background': '#32b4c7', 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 20 }, { 'unit': 'px', 'value': 30 }, { 'unit': 'px', 'value': 20 }, { 'unit': 'px', 'value': 30 }], 'lineHeight': [{ 'unit': 'em', 'value': 1.2 }], 'letterSpacing': [{ 'unit': 'px', 'value': 2 }] }, '#pic4 hr': { 'display': 'none' }, '#pic4 title #pic4 picArrow': { 'color': '#c76655', 'textAlign': 'right' }, '#pic4 pictext2': { 'color': '#c76655', 'textAlign': 'right' }, '#pic4 em': { 'fontWeight': '700' }, '#pic4 svg': { 'marginTop': [{ 'unit': 'px', 'value': -3 }], 'fill': '#c76655' }, '#pic4 smalltext': { 'marginTop': [{ 'unit': 'px', 'value': 14 }], 'paddingRight': [{ 'unit': 'px', 'value': 34 }], 'fontWeight': 'bold', 'textAlign': 'right' }, '#pic4 moreDetail picArrow': { 'background': 'transparent', 'color': '#333', 'fill': '#333', 'textAlign': 'right', 'border': [{ 'unit': 'string', 'value': 'none' }], 'marginTop': [{ 'unit': 'px', 'value': 6 }], 'fontSize': [{ 'unit': 'px', 'value': 18 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }] }, '#pic4 svg': { 'fill': '#333' }, 'Service-module Top Title': { 'fontSize': [{ 'unit': 'px', 'value': 16 }], 'color': '#444', 'margin': [{ 'unit': 'px', 'value': 4 }, { 'unit': 'px', 'value': 4 }, { 'unit': 'px', 'value': 4 }, { 'unit': 'px', 'value': 4 }], 'lineHeight': [{ 'unit': 'em', 'value': 1.2 }], 'letterSpacing': [{ 'unit': 'px', 'value': 1 }], 'marginTop': [{ 'unit': 'px', 'value': 12 }], 'height': [{ 'unit': 'px', 'value': 44 }], 'cursor': 'pointer' }, 'Service-module Top title2': { 'height': [{ 'unit': 'px', 'value': 44 }], 'marginTop': [{ 'unit': 'px', 'value': 14 }], 'cursor': 'pointer' }, 'Service-module last': { 'borderRight': [{ 'unit': 'string', 'value': 'none' }] }, 'Service-module Top Title h3': { 'margin': [{ 'unit': 'px', 'value': 3 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'fontSize': [{ 'unit': 'px', 'value': 13 }], 'lineHeight': [{ 'unit': 'em', 'value': 1.2 }], 'fontWeight': '400', 'textTransform': 'uppercase' }, 'Service-module Top Title p': { 'margin': [{ 'unit': 'px', 'value': 3 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'fontSize': [{ 'unit': 'px', 'value': 13 }], 'lineHeight': [{ 'unit': 'em', 'value': 1.2 }], 'fontWeight': '400', 'textTransform': 'uppercase' }, // ***************content************ 'sidebar_box': { 'width': [{ 'unit': 'px', 'value': 530 }] }, 'content2_bottom_left': { 'position': 'relative' }, 'content2_bottom_left': { 'textAlign': 'center' }, 'content2_bottom_right': { 'textAlign': 'center' }, 'content2_bottom_center': { 'textAlign': 'center' }, 'blue': { 'backgroundColor': 'rgba(16, 165, 205, 0.7)' }, 'svg': { 'fontSize': [{ 'unit': 'px', 'value': 68 }], 'verticalAlign': 'middle', 'overflow': 'hidden', 'display': 'inline-block', 'textAlign': 'center' }, 'content2_bottom_left strong': { 'fontSize': [{ 'unit': 'px', 'value': 14 }], 'verticalAlign': 'middle', 'display': 'block', 'overflow': 'hidden', 'marginTop': [{ 'unit': 'px', 'value': 20 }] }, 'content2_bottom_right strong': { 'fontSize': [{ 'unit': 'px', 'value': 14 }], 'verticalAlign': 'middle', 'display': 'block', 'overflow': 'hidden', 'marginTop': [{ 'unit': 'px', 'value': 20 }] }, 'content2_bottom_center strong': { 'fontSize': [{ 'unit': 'px', 'value': 14 }], 'verticalAlign': 'middle', 'display': 'block', 'overflow': 'hidden', 'marginTop': [{ 'unit': 'px', 'value': 20 }] }, 'p': { 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }] }, 'sidebar_box': { 'position': 'absolute', 'left': [{ 'unit': 'px', 'value': 0 }], 'border': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#eee' }], 'top': [{ 'unit': 'px', 'value': 0 }], 'background': 'url(../images/left1.jpg) left bottom', 'backgroundSize': 'cover', 'height': [{ 'unit': '%V', 'value': 1 }] }, 'news-wrapper': { 'height': [{ 'unit': 'px', 'value': 322 }], 'overflow': 'hidden' }, 'news-wrapper news-contents-wrapper': { 'width': [{ 'unit': 'px', 'value': 500 }], 'margin': [{ 'unit': 'string', 'value': 'auto' }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'string', 'value': 'auto' }], 'borderRight': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'dashed' }, { 'unit': 'string', 'value': '#F1F6FA' }], 'borderLeft': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'dashed' }, { 'unit': 'string', 'value': '#F1F6FA' }], 'height': [{ 'unit': 'px', 'value': 400 }] }, 'news-wrapper news-contents': { 'overflow': 'hidden', 'position': 'relative', 'zIndex': '998', 'height': [{ 'unit': 'px', 'value': 308 }] }, 'news-wrapper news': { 'overflow': 'hidden', 'margin': [{ 'unit': 'px', 'value': 6 }, { 'unit': 'string', 'value': '' }, { 'unit': 'px', 'value': 32 }, { 'unit': 'string', 'value': '' }], 'position': 'relative', 'height': [{ 'unit': 'string', 'value': 'auto' }], 'marginBottom': [{ 'unit': 'px', 'value': 4 }], 'borderBottom': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'dashed' }, { 'unit': 'string', 'value': '#8fa8bd' }], 'clear': 'both' }, 'description htext': { 'fontSize': [{ 'unit': 'px', 'value': 14 }], 'color': '#777', 'verticalAlign': 'top', 'lineHeight': [{ 'unit': 'px', 'value': 28 }], 'display': 'inline-block', 'fontWeight': '400', 'color': '#666' }, 'news-header': { 'padding': [{ 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }], 'color': '#8BC34A', 'height': [{ 'unit': 'px', 'value': 42 }], 'fontWeight': 'bold', 'fontSize': [{ 'unit': 'px', 'value': 20 }], 'lineHeight': [{ 'unit': 'px', 'value': 42 }], 'paddingLeft': [{ 'unit': 'px', 'value': 32 }], 'borderTop': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#eee' }] }, 'time': { 'position': 'absolute', 'left': [{ 'unit': 'px', 'value': 0 }], 'top': [{ 'unit': 'px', 'value': 10 }], 'fontSize': [{ 'unit': 'px', 'value': 12 }], 'color': '#888', 'display': 'inline-block', 'borderRadius': '12px', 'height': [{ 'unit': 'px', 'value': 28 }], 'lineHeight': [{ 'unit': 'px', 'value': 28 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }], 'color': '#fff', 'fontWeight': '400', 'opacity': '0.9', 'filter': 'alpha(opacity=90)' }, 'description': { 'display': 'block', 'position': 'relative', 'cursor': 'pointer', 'padding': [{ 'unit': 'px', 'value': 8 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 12 }, { 'unit': 'px', 'value': 100 }], 'borderBottom': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'dotted' }, { 'unit': 'string', 'value': '#d7e1e4' }], 'marginLeft': [{ 'unit': 'px', 'value': 32 }], 'marginRight': [{ 'unit': 'px', 'value': 32 }] }, 'redTab': { 'background': '-webkit-gradient(linear, left top, left bottom, from(#E95F5F), to(#C64444))', 'backgroundImage': '-moz-linear-gradient(#E95F5F, #C64444)', 'backgroundImage': '-webkit-linear-gradient(#E95F5F, #C64444)', 'backgroundImage': '-o-linear-gradient(#E95F5F, #C64444)', 'filter': 'progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#E95F5F, endColorstr=#C64444)', 'MsFilter': '"progid:DXImageTransform.Microsoft.gradient (GradientType=0, startColorstr=#E95F5F, endColorstr=#C64444)"' }, 'yellowTab': { 'backgroundColor': '#fee140', 'backgroundImage': 'linear-gradient(to bottom, #ffe88e 0%, #fee140 100%)' }, 'greenTab': { 'background': '-webkit-gradient(linear, left top, left bottom, from(#C4D8A6), to(#C4D8A6))', 'backgroundImage': '-moz-linear-gradient(#C4D8A6, #C4D8A6)', 'backgroundImage': '-webkit-linear-gradient(#C4D8A6, #C4D8A6)', 'backgroundImage': '-o-linear-gradient(#C4D8A6, #C4D8A6)', 'filter': 'progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#C4D8A6, endColorstr=#C4D8A6)', 'MsFilter': '"progid:DXImageTransform.Microsoft.gradient (GradientType=0, startColorstr=#C4D8A6, endColorstr=#C4D8A6)"' }, 'blueTab': { 'background': '-webkit-gradient(linear, left top, left bottom, from(#A3CCD8), to(#5E9EB7))', 'backgroundImage': '-moz-linear-gradient(#A3CCD8, #5E9EB7)', 'backgroundImage': '-webkit-linear-gradient(#A3CCD8, #5E9EB7)', 'backgroundImage': '-o-linear-gradient(#A3CCD8, #5E9EB7)', 'filter': 'progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#A3CCD8, endColorstr=#5E9EB7)', 'MsFilter': '"progid:DXImageTransform.Microsoft.gradient (GradientType=0, startColorstr=#A3CCD8, endColorstr=#5E9EB7)"' }, 'tab': { 'height': [{ 'unit': 'px', 'value': 37 }], 'fontSize': [{ 'unit': 'px', 'value': 14 }], 'borderBottom': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': '#e1e1e1' }, { 'unit': 'string', 'value': 'solid' }], 'paddingLeft': [{ 'unit': 'px', 'value': 32 }] }, 'tab li': { 'height': [{ 'unit': 'px', 'value': 36 }], 'lineHeight': [{ 'unit': 'px', 'value': 36 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 25 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 25 }], 'marginRight': [{ 'unit': 'px', 'value': 10 }], 'color': '#888', 'cursor': 'pointer', 'letterSpacing': [{ 'unit': 'px', 'value': 2 }], 'display': 'inline-block' } });
import RBAC from './rbac' export default RBAC;
import AccessibilityModule from '../../index'; describe('TreeData', () => { describe('register role', () => { let cjsTree; let ulEl; beforeEach(() => { cjsTree = new createjs.Shape(); AccessibilityModule.register({ displayObject: cjsTree, parent: container, role: AccessibilityModule.ROLES.TREE, }); stage.accessibilityTranslator.update(); ulEl = parentEl.querySelector('ul[role=tree]'); }); describe('rendering', () => { it('creates ul[role=tree] element', () => { expect(ulEl).not.toBeNull(); }); }); describe('"addChild" and "addChildAt"', () => { let childObj; const errorMsg = /Children of tree must have a role of treeitem/; beforeEach(() => { childObj = new createjs.Shape(); }); describe('child is not Accessible and not a TreeItem', () => { it('"addChild" throws error if the child is not accessible object or not a treeItem', () => { expect(() => { cjsTree.accessible.addChild(childObj); }).toThrowError(errorMsg); }); it('"addChildAt" throws error if the child is not accessible object or not a treeItem', () => { expect(() => { cjsTree.accessible.addChildAt(childObj, 0); }).toThrowError(errorMsg); }); }); describe('child is Accessible and has role TREEITEM', () => { beforeEach(() => { AccessibilityModule.register({ displayObject: childObj, role: AccessibilityModule.ROLES.TREEITEM, }); }); it('"addChild" does not throws error if the child accessible object and a treeItem', () => { expect(() => { cjsTree.accessible.addChild(childObj); }).not.toThrowError(errorMsg); }); it('"addChildAt" does not throws error if the child accessible object and a treeItem', () => { expect(() => { cjsTree.accessible.addChildAt(childObj, 0); }).not.toThrowError(errorMsg); }); }); }); describe('Accessible getters and setters', () => { it('can set and get "multiselectable" property', () => { expect(cjsTree.accessible.multiselectable).toBe(undefined); cjsTree.accessible.multiselectable = true; stage.accessibilityTranslator.update(); expect(cjsTree.accessible.multiselectable).toBe(true); expect(ulEl.getAttribute('aria-multiselectable')).toBe('true'); }); it('can set and get "required" property', () => { expect(cjsTree.accessible.required).toBe(undefined); cjsTree.accessible.required = true; stage.accessibilityTranslator.update(); expect(cjsTree.accessible.required).toBe(true); expect(ulEl.getAttribute('aria-required')).toBe('true'); }); }); }); });
import React, { useEffect, useState } from 'react'; import { ApexChart } from 'views/charts'; import { ApexTimeSeriesData } from 'utils/charts'; import { isEmpty } from 'underscore'; const DeviceVoltageChart = ({ deviceUptimeData, controllerChildren, controllerChildrenOpen }) => { const [series, setSeries] = useState([]); useEffect(() => { if (!isEmpty(deviceUptimeData)) { const updatedData = deviceUptimeData.map((object) => { return { ...object, created_at: object.timestamp }; }); const label = []; const values = []; updatedData.forEach((status) => { label.push(status.created_at); values.push(status['voltage']); }); const deviceVoltage = { line: { label, data: values } }; const batteryVoltageSeries = [ { name: 'voltage', data: ApexTimeSeriesData(deviceVoltage.line.label, deviceVoltage.line.data) } ]; setSeries(batteryVoltageSeries); } }, [deviceUptimeData]); const todaysDate = new Date().getTime(); const minDate = new Date(); minDate.setDate(minDate.getDate() - 1); const ChartOptions = { chart: { id: 'realtime', type: 'line', zoom: { enabled: true, autoScaleYaxis: true } }, stroke: { curve: 'straight', width: 1.5, breaks: { style: 'null' } }, dataLabels: { enabled: false }, xaxis: { type: 'datetime', min: minDate.getTime(), max: todaysDate, labels: { dateTimeUTC: false }, tickAmount: 4 }, yaxis: { min: 2.5, max: 4.5, decimalsInFloat: 2, tickAmount: 5 }, grid: { row: { colors: ['#f3f3f3', 'transparent'], opacity: 0.5 } }, tooltip: { x: { format: 'dd MMM yyyy hh:mm:ss' } } }; return ( <> <ApexChart title={'battery voltage'} options={ChartOptions} series={series} type="line" blue controllerChildren={controllerChildren} /> </> ); }; export default DeviceVoltageChart;
var events = require('events'), eventEmitter = new events.EventEmitter(), fs = require('fs'), path = require('path'); var modules = []; module.exports = eventEmitter; module.exports.initialize = function() { eventEmitter.emit('initialize'); var directories = fs.readdirSync('./lib').filter(f => fs.statSync(path.join('./lib', f)).isDirectory()); for (var m = 0; m < directories.length; m++) { module.exports.load(directories[m], function(err, result) { if (err) { eventEmitter.emit('fail', err, directories[m]); } }); if (m == directories.length - 1) { setTimeout(function() { eventEmitter.emit('ready', modules); module.exports.modules = modules; }, 5000); } } }; module.exports.load = function(module, callback) { try { var m = require('./' + module); modules.push(m); eventEmitter.emit('load', m); return callback(null, m); } catch (exception) { return callback(exception, null); } }; module.exports.reload = function(moduleName, callback) { module.exports.unload(moduleName, function(err, result) { if (err) { return callback(err, null); } module.exports.load(moduleName, function(err, result) { if (err) { return callback(err, null); } module.exports.modules = modules; eventEmitter.emit('reload', result); return callback(null, result); }) }); return callback(new Error("Cannot reload module " + moduleName), null); }; module.exports.unload = function(moduleName, callback) { if (containsModule(moduleName, modules)) { try { delete require.cache[require.resolve('./' + moduleName)]; var directories = fs.readdirSync('./lib').filter(f => fs.statSync(path.join('./lib', f)).isDirectory()); for (var m = 0; m < directories.length; m++) { if (modules[m].name.toLowerCase() == moduleName.toLowerCase()) { eventEmitter.emit('unload', modules[m]); modules.splice(m, 1); module.exports.modules = modules; return callback(null, modules); } } } catch (exception) { return callback(exception, null); } return callback(new Error("Cannot unload module " + moduleName), null); } else { return callback(new Error("Cannot find module " + moduleName), null); } }; var containsModule = function(module, array) { for (var i = 0; i < array.length; i++) { if (array[i].name.toLowerCase() === module.toLowerCase()) { return true; } } return false; }
const client = require('mongodb').MongoClient; const UserConstants = require('./util.service').UserConstants; const jwt = require('jsonwebtoken'); class Service { // authorize authorize (request,response,next){ const _token =request.headers.token; if(!_token){ // stop access response.redirect('/auth/unauthorize'); }else{ if(this.verifyToken(_token)){ // continue the flow next(); }else{ // stop access response.redirect('/auth/unauthorize'); } } } // verify token verifyToken(_token){ let validToken = false; try{ const isValid = jwt.verify(_token,UserConstants.jwt.key); if(isValid){ validToken = isValid; } }catch(error){ } return validToken; } // create jwt token generateToken(email,type){ const _token = jwt.sign({ email : email, type:type }, UserConstants.jwt.key,{ expiresIn : '1hr' }); return _token; } saveToken(_user,callback){ const _url = UserConstants.mongo.url + UserConstants.mongo.port; client.connect(_url,(err,connection)=>{ const id = _user.id; delete _user.id; connection .db(UserConstants.mongo.db) .collection(UserConstants.mongo.collections.security) .update( {_id: id }, {$set: _user}, {upsert: true}, (error,response)=>{ callback(error,response); }); }); } // end of save Token // refresh an existing token if valid refreshToken(_token,callback){ const _user = this.verifyToken(_token); if(_user){ this.fetchTokenDetails(_token,_user.email,(err,data)=>{ callback(err,data); }); } else{ callback("err",{data:"noting"}); } } // end of refresh Token fetchTokenDetails(_token,_email,callback){ client.connect(UserConstants.mongo.url+UserConstants.mongo.port,(err,conn)=>{ conn .db(UserConstants.mongo.db) .collection(UserConstants.mongo.collections.security) .find({_token : _token, email: _email}) .toArray((error,data)=>{ callback(error,data); }); }); } } module.exports={ SecurityService : Service }
firebase.auth().onAuthStateChanged(function(user) { winLoc = String(window.location).split("/") winLoc = winLoc[winLoc.length-1] if (user) { // User signed in if(winLoc=="index.html"){ window.location = "form.html"; } var userEmail = user.email; $("#account").html(userEmail) } else { if(winLoc!="index.html"){ window.location = "index.html"; } } }) function signOut(){ firebase.auth().signOut().then(function() { // Sign-out successful. }).catch(function(error) { // An error happened. }); }
const Pilotos = ['Vettel', 'Alonso', 'Raikkonen','Massa'] Pilotos.pop() console.log(Pilotos) Pilotos.push('Verstappen') Pilotos.shift() // Remove primeiro elemento Pilotos.unshift('Hamilton') // Insere na primeira posição console.log(Pilotos) // Splice pode adicionar e remover // Adicionar Pilotos.splice(2, 0, 'Bottas', 'Massa') // Remover Pilotos.splice(3, 1) const algunsPilotos = Pilotos.slice(2) // Retorna um novo Array const algunsPilotos2 = Pilotos.slice(1, 4)
export const paginate = (datas, chunk_size, current) => { let results = []; let items = [] datas.forEach((item,index) => { item.no = index+1 items.push(item) }) items = [].concat(...items) while (items.length) { results.push(items.splice(0, (chunk_size !== 'all' ? chunk_size : items.length))); } return { current: results[current], total: datas.length, page_length: results.length } // return results[page] } export default { paginate }
import uuid from "uuid"; import * as dynamoDbLib from '../../libs/dynamodb'; import { success, failure } from '../../libs/response'; export async function main(event, context, callback) { const data = JSON.parse(event.body); const params = { TableName: "unsplashed", Item: { userId: event.requestContext.identity.cognitoIdentityId, photoId: uuid.v1(), unsplashId: data.unsplashId, thumbUrl: data.thumbUrl, regularUrl: data.regularUrl, createdAt: Date.now() } }; try { await dynamoDbLib.call("put", params); callback(null, success(params.Item)); } catch (e) { callback(null, failure({ status: false })); } }
goog.provide('animatejs.ease'); goog.require('goog.math.Bezier'); /** * Easing functions * @name animatejs.ease * @namespace */ /** * Linear ease * @param {number} p * @return {number} * @export */ animatejs.ease.linear = function(p) { 'use strict'; return p; }; /** * Ease in quadratic * @param {number} p * @return {number} * @export */ animatejs.ease.easeinquad = function(p) { 'use strict'; return p * p; }; /** * Ease in quadratic * @param {number} p * @return {number} * @export */ animatejs.ease.easeoutquad = function(p) { 'use strict'; return -p * (p - 2); }; /** * Ease in out quintic * @param {number} p * @return {number} * @export */ animatejs.ease.easeinoutquint = function(p) { 'use strict'; p = 2 * p; if (p < 1) { return p * p * p * p * p / 2; } p -= 2; return p * p * p * p * p / 2 + 1; }; /** * Ease out circ * @param {number} p * @return {number} * @export */ animatejs.ease.easeoutcirc = function(p) { 'use strict'; return Math.sqrt(2 * p - p * p); }; /** * Creates cubic bezier ease function * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * * @export * @return {Function} */ animatejs.ease.createBezier = function(x1, y1, x2, y2) { 'use strict'; if (!goog.isNumber(x1) || !goog.isNumber(y1) || !goog.isNumber(x2) || !goog.isNumber(y2)) { throw new TypeError('all coords must be numbers'); } x1 = (x1 < 0) ? 0 : (x1 > 1) ? 1 : x1; x2 = (x2 < 0) ? 0 : (x2 > 1) ? 1 : x2; var bezier = new goog.math.Bezier(0, 0, x1, y1, x2, y2, 1, 1); return function(p) { return bezier.solveYValueFromXValue(p); }; };
import React from 'react'; import {LaunchPage, PromiseNotUntil} from 'react-hymn'; import {Router, Route} from 'react-router-dom'; import history from './history'; import appStore from './appStore'; //路由页面管理 import {routes_start} from './routes'; // 路由页面管理 import Index from './pages/Index'; // exact首页,默认指定首页 import {listen403} from './networking/FetchManager'; import 'antd/dist/antd.css'; // or 'antd/dist/antd.less' import 'ant-design-pro/dist/ant-design-pro.css'; import './App.css'; import {Layout, LocaleProvider, DatePicker, message} from 'antd'; import GlobalUtilsWrapper from './components/global-utils-wrapper/GlobalUtilsWrapper'; import Login from '../src/pages/Login.js' import {FormattedMessage, IntlProvider, injectIntl} from 'react-intl'; // import {injectIntl} from 'react-intl'; // 由于 antd 组件的默认文案是英文,所以需要修改为中文 import zhCN from 'antd/lib/locale-provider/zh_CN'; import zh_CN from './resources/i18n/zh_CN'; import en_US from './resources/i18n/en_US'; import moment from 'moment'; import 'moment/locale/zh-cn'; import './RewriteMethods.js' moment.locale('zh-cn'); const {Sider, Footer, Content} = Layout; // var heightTop = document.documentElement.scrollTop || document.body.scrollTop; class App extends LaunchPage { constructor(props) { super(props); this.state = { showInitialError: false, language:null }; this.startTime = Date.now(); } atVeryBeginning() { } cacheLoaded() { return void 0; } checkCache(cache) { //console.log('try main checkCache'); } tryMainServer() { //console.log('try main server'); return Promise.resolve(); } tryBackServer() { return Promise.resolve(); } updateCriticalData() { // 默认启动缓存的数据 //return [symbol, banner, tradeTime, getAppId]; } _getRouter() { //console.log(document.querySelector('body')) return ( <Router history={history}> <div style={{display: 'flex', flexDirection: 'row', width: '100%', height: '100%'}}> <switch> <Route exact path='/' component={Login}/> { routes_start.map((item) => { //console.log(item.path) return <Route path={item.path} component={item.component}/> }) } </switch> </div> </Router> ); } chooseLocale(language) { let JsSrc if (language) { JsSrc = language } else { JsSrc = (navigator.language || navigator.browserLanguage).toLowerCase(); window.localStorage.setItem('language',JsSrc) } switch (JsSrc.split('-')[0]) { case 'en': //console.log('111') return en_US; break; case 'zh': //console.log('222') return zh_CN; break; default: //console.log('333') return zh_CN; break; } } _getRouterNew() { return ( <IntlProvider locale={'en'} messages={this.chooseLocale(window.localStorage.getItem('language'))}> <GlobalUtilsWrapper history={history} routes={routes_start} InitPage={Index}/> </IntlProvider> ); } _getLaunchView() { // 启动页 return null; } async criticalDataDidLoad() { //this._renderPage(); } _detectViewportSize() { let w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], width = w.innerWidth || e.clientWidth || g.clientWidth, height = w.innerHeight || e.clientHeight || g.clientHeight; appStore.set('viewport', {width: width, height: height}); } componentDidMount() { this._detectViewportSize(); window.addEventListener('resize', () => { this._detectViewportSize(); }); listen403(); // this.launch(appStore); } render() { return ( <div className="App" style={{display: 'flex', flexDirection: 'row'}}> {/*{this._getRouter()}*/} {this._getRouterNew()} </div> ); } } export default App;
/** * Excalibur - A Material Design Admin Template * Copyright 2018 All Rights Reserved * Made Wih Love * Created By The Iron Network, LLC */ import React from 'react'; import ReactDOM from 'react-dom'; // Save a reference to the root element for reuse const rootEl = document.getElementById("root"); // Create a reusable render method that we can call more than once let render = () => { // Dynamically import our main App component, and render it const MainApp = require('./App').default; ReactDOM.render( <MainApp />, rootEl ); }; if (module.hot) { module.hot.accept('./App', () => { const NextApp = require('./App').default; render( <NextApp />, rootEl ); }); } render();
import React from 'react'; import { Card ,Button } from 'react-bootstrap'; import { useHistory } from 'react-router'; export default function Riders({rider}){ const history = useHistory(); const handleRider = (name) => { history.push(`/destination/${name}`) } return ( <div> <Card style={{ backgroundColor: 'grey'}}> <Card.Img variant="top" src={rider.imgUrl} /> <Card.Body> <Card.Title>{rider.name}</Card.Title> </Card.Body> <Card.Footer> <Button onClick={() => handleRider(rider.name)} variant="warning">Going to {rider.name}</Button> </Card.Footer> </Card> </div> ); };
import express from 'express'; import { TodoService } from './controller'; var app = express() const TodosRoute = express.Router() TodosRoute.route('/').get((req, res) => { console.log("GET all todos"); // res.status(200).send(TodoService.getTodos()) res.send(TodoService.getTodos()); }) TodosRoute.route('/:id').get((req, res) => { console.log('GET todo by id'); res.status(200).send(TodoService.getTodo(req.params.id)); }) TodosRoute.route('/').post((req, res) => { console.log('POST create new todo') res.status(200).send(TodoService.addTodo(req.body.name, req.body.id)) }) TodosRoute.route('/update/:id').put((req, res) => { console.log("PUT update todo") // console.log(req.body) res.status(200).send(TodoService.updateTodo(req.params.id, req.body.todo)) }) TodosRoute.route('/completed').delete((req, res) => { console.log("DELETE completed todo"); res.status(200).send(TodoService.clearCompletedTodo()) }) TodosRoute.route('/:id').delete((req, res) => { console.log("DELETE todo"); res.status(200).send(TodoService.deleteTodo(req.params.id)) }) TodosRoute.route('/toggleAll').put((req, res) => { console.log("PUT toggle all todos") // console.log(req.body) res.status(200).send(TodoService.toggleAllTodo(req.body.toggleStatus)) }) export default TodosRoute
// @flow import { ASYNC_SCENE_INIT, INITIALIZE_SCENE, HANDLE_NOTIFICATION, GET_ALL_SCENES_SUCCESS, ON_CHANGE_SCENE_FIELD, ON_ADD_NEW_LAYER, ON_SELECT_SINGLE_SCENE, ON_ADD_NEW_STORY, ON_CHANGE_STORY_FIELD, } from "actionTypes/scene"; import Alert from "components/Alert"; export function initializeScene() { return (dispatch) => { dispatch({ type: INITIALIZE_SCENE }); }; } function asyncSceneInit() { return { type: ASYNC_SCENE_INIT, }; } export function notificationHandler(isSuccess, message) { return { type: HANDLE_NOTIFICATION, payload: { isSuccess, notification: { type: isSuccess ? Alert.TYPE.SUCCESS : Alert.TYPE.ERROR, message, }, }, }; } export function getAllScenes(scriptId: string) { return (dispatch, getState, serviceManager) => { dispatch(asyncSceneInit()); let sceneService = serviceManager.get("SceneService"); sceneService .getAllScenes(scriptId) .then(({ success, data }) => { if (success) { dispatch({ type: GET_ALL_SCENES_SUCCESS, payload: data }); } else { dispatch( notificationHandler( success, "Something went wrong. Please try again" ) ); } }) .catch(() => { dispatch( notificationHandler(false, "Something went wrong. Please try again") ); }); }; } export function updateScene(payload: object) { return (dispatch, getState, serviceManager) => { dispatch(asyncSceneInit()); let sceneService = serviceManager.get("SceneService"); sceneService .saveScene(payload) .then(({ success }) => { if (success) { sceneService .getAllScenes(payload.scriptId) .then(({ success, data }) => { if (success) { dispatch({ type: GET_ALL_SCENES_SUCCESS, payload: data }); } else { dispatch( notificationHandler( success, "Something went wrong. Please try again" ) ); } }) .catch(() => { dispatch( notificationHandler( false, "Something went wrong. Please try again" ) ); }); } dispatch( notificationHandler( success, success ? "Scene saved successfully." : "Failed to save scene." ) ); }) .catch(() => { dispatch( notificationHandler(false, "Something went wrong. Please try again") ); }); }; } export function onChangeSceneField(payload: Object) { return (dispatch) => { dispatch({ type: ON_CHANGE_SCENE_FIELD, payload }); }; } export function onAddNewLayer(payload: Object) { return (dispatch) => { dispatch({ type: ON_ADD_NEW_LAYER, payload }); }; } export function onSelectSingleScene(sceneId: string) { return (dispatch) => { dispatch({ type: ON_SELECT_SINGLE_SCENE, payload: sceneId }); }; } export function onAddNewStory(payload: Object) { return (dispatch) => { dispatch({ type: ON_ADD_NEW_STORY, payload }); }; } export function onChangeStoryField(payload: Object) { return (dispatch) => { dispatch({ type: ON_CHANGE_STORY_FIELD, payload }); }; }
import React from "react"; import { FaPlus, FaTag } from "react-icons/fa"; import Coffee from "../assets/images/portfolio/coffee.jpg"; import Console from "../assets/images/portfolio/console.jpg"; import Judah from "../assets/images/portfolio/judah.jpg"; import IntoTheLight from "../assets/images/portfolio/into-the-light.jpg"; import Farmerboy from "../assets/images/portfolio/farmerboy.jpg"; import Girl from "../assets/images/portfolio/girl.jpg"; import Origami from "../assets/images/portfolio/origami.jpg"; import Retrocam from "../assets/images/portfolio/retrocam.jpg"; import CoffeeModal from "../assets/images/portfolio/modals/m-coffee.jpg"; import ConsoleModal from "../assets/images/portfolio/modals/m-console.jpg"; import JudahModal from "../assets/images/portfolio/modals/m-judah.jpg"; import IntoTheLightModal from "../assets/images/portfolio/modals/m-intothelight.jpg"; import FarmerboyModal from "../assets/images/portfolio/modals/m-farmerboy.jpg"; import GirlModal from "../assets/images/portfolio/modals/m-girl.jpg"; import OrigamiModal from "../assets/images/portfolio/modals/m-origami.jpg"; import RetrocamModal from "../assets/images/portfolio/modals/m-retrocam.jpg"; const Portfolio = () => ( <section id="portfolio"> <div className="row"> <div className="twelve columns collapsed"> <h1>Check Out Some of My Works</h1> <div id="portfolio-wrapper" className="bgrid-quarters s-bgrid-thirds cf" > {/* FlexLog */} <div className="columns portfolio-item"> <div className="item-wrap"> <a href="#modal-02" title=""> <img alt="" src={Console} /> <div className="overlay"> <div className="portfolio-item-meta"> <h5>FlexLog </h5> <p>Full-Stack Workout Tracker</p> </div> </div> <div className="link-icon"> <FaPlus /> </div> </a> </div> </div> {/* Notes */} <div className="columns portfolio-item"> <div className="item-wrap"> <a href="#modal-01" title=""> <img alt="" src={Coffee} /> <div className="overlay"> <div className="portfolio-item-meta"> <h5>DiFulvio Notes</h5> <p>Full-Stack Notes Application </p> </div> </div> <div className="link-icon"> <FaPlus /> </div> </a> </div> </div> {/* Mox Draft */} <div className="columns portfolio-item"> <div className="item-wrap"> <a href="#modal-03" title=""> <img alt="" src={Judah} /> <div className="overlay"> <div className="portfolio-item-meta"> <h5>Mox</h5> <p>Mock Drafting Application</p> <p>Lambda Winter Hackathon 2019</p> </div> </div> <div className="link-icon"> <FaPlus /> </div> </a> </div> </div> <div className="columns portfolio-item"> <div className="item-wrap"> <a href="#modal-04" title=""> <img alt="" src={IntoTheLight} /> <div className="overlay"> <div className="portfolio-item-meta"> <h5>FlexBlog</h5> <p>Weekly Blog for my workout-tracker app, FlexLog</p> </div> </div> <div className="link-icon"> <FaPlus /> </div> </a> </div> </div> {/* <div className="columns portfolio-item"> <div className="item-wrap"> <a href="#modal-05" title=""> <img alt="" src={Farmerboy} /> <div className="overlay"> <div className="portfolio-item-meta"> <h5>Farmer Boy</h5> <p>Branding</p> </div> </div> <div className="link-icon"> <FaPlus /> </div> </a> </div> </div> */} {/* <div className="columns portfolio-item"> <div className="item-wrap"> <a href="#modal-06" title=""> <img alt="" src={Girl} /> <div className="overlay"> <div className="portfolio-item-meta"> <h5>Girl</h5> <p>Photography</p> </div> </div> <div className="link-icon"> <FaPlus /> </div> </a> </div> </div> */} {/* <div className="columns portfolio-item"> <div className="item-wrap"> <a href="#modal-07" title=""> <img alt="" src={Origami} /> <div className="overlay"> <div className="portfolio-item-meta"> <h5>Origami</h5> <p>Illustrration</p> </div> </div> <div className="link-icon"> <FaPlus /> </div> </a> </div> </div> */} {/* <div className="columns portfolio-item"> <div className="item-wrap"> <a href="#modal-08" title=""> <img alt="" src={Retrocam} /> <div className="overlay"> <div className="portfolio-item-meta"> <h5>Retrocam</h5> <p>Web Development</p> </div> </div> <div className="link-icon"> <FaPlus /> </div> </a> </div> </div> */} </div> </div> {/* POPUPS */} {/* FlexLog Popup */} <div id="modal-02" className="popup-modal mfp-hide"> <img className="scale-with-grid" src={ConsoleModal} alt="" /> <div className="description-box"> <h4>FlexLog</h4> <p> Workout-Tracking Application where users can create and schedule custom workouts as well as track their progress. </p> <span className="categories"> <FaTag /> Full-Stack, Team-Project, React, Hooks, Node.js </span> </div> <div className="link-box"> <a href="https://flexlog.netlify.com/" target="_blank">Visit</a> <a href="#portfolio" className="popup-modal-dismiss"> Close </a> </div> </div> {/* Notes App Popup */} <div id="modal-01" className="popup-modal mfp-hide"> <img className="scale-with-grid" src={CoffeeModal} alt="" /> <div className="description-box"> <h4>Full-Stack</h4> <p> Full-Stack Notes Application using React front-end and fully-functional backend database. </p> <span className="categories"> <FaTag /> Full-Stack, React, Front-End, Back-End </span> </div> <div className="link-box"> <a href="https://difulvionotes.netlify.com" target="_blank"> visit </a> <a href="#portfolio" className="popup-modal-dismiss"> Close </a> </div> </div> {/* Mox Popup */} <div id="modal-03" className="popup-modal mfp-hide"> <img className="scale-with-grid" src={JudahModal} alt="" /> <div className="description-box"> <h4>Mox Demo</h4> <p> Demo of a Fantasy Football Mock Drafting Application built over two days for the Lambda School Winter Hackathon </p> <span className="categories"> <FaTag /> React, Front-End, Hackathon, Team-Project </span> </div> <div className="link-box"> <a href="https://youtu.be/t-AfcaYolxY" target="_blank" >Watch</a> <a href="#portfolio" className="popup-modal-dismiss"> Close </a> </div> </div> {/* FlexBlog Popup */} <div id="modal-04" className="popup-modal mfp-hide"> <img className="scale-with-grid" src={IntoTheLightModal} alt="" /> <div className="description-box"> <h4>FlexBlog</h4> <p> Weekly Blog as I built my workout-tracker app, FlexLog. From day 1 decisions like data structure, through design and presentation. </p> <span className="categories"> <FaTag /> Blog </span> </div> <div className="link-box"> <a href="https://billd-labs-blog.netlify.com/">Details</a> <a href="#portfolio" className="popup-modal-dismiss"> Close </a> </div> </div> {/* <div id="modal-05" className="popup-modal mfp-hide"> <img className="scale-with-grid" src={FarmerboyModal} alt="" /> <div className="description-box"> <h4>Farmer Boy</h4> <p> Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. </p> <span className="categories"> <FaTag /> Branding, Webdesign </span> </div> <div className="link-box"> <a href="http://www.behance.net">Details</a> <a href="#portfolio" className="popup-modal-dismiss"> Close </a> </div> </div> */} {/* <div id="modal-06" className="popup-modal mfp-hide"> <img className="scale-with-grid" src={GirlModal} alt="" /> <div className="description-box"> <h4>Girl</h4> <p> Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. </p> <span className="categories"> <FaTag /> Photography </span> </div> <div className="link-box"> <a href="http://www.behance.net">Details</a> <a href="#portfolio" className="popup-modal-dismiss"> Close </a> </div> </div> */} {/* <div id="modal-07" className="popup-modal mfp-hide"> <img className="scale-with-grid" src={OrigamiModal} alt="" /> <div className="description-box"> <h4>Origami</h4> <p> Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. </p> <span className="categories"> <FaTag /> Branding, Illustration </span> </div> <div className="link-box"> <a href="http://www.behance.net">Details</a> <a href="#portfolio" className="popup-modal-dismiss"> Close </a> </div> </div> */} {/* <div id="modal-08" className="popup-modal mfp-hide"> <img className="scale-with-grid" src={RetrocamModal} alt="" /> <div className="description-box"> <h4>Retrocam</h4> <p> Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. </p> <span className="categories"> <i className="fa fa-tag" /> Webdesign, Photography </span> </div> <div className="link-box"> <a href="http://www.behance.net">Details</a> <a href="#portfolio" className="popup-modal-dismiss"> Close </a> </div> </div> */} </div> </section> ); export default Portfolio;
import React, { useEffect } from 'react' import LoginPrompt from '../components/login/LoginPrompt' export default function Login() { return ( <div id="login-section"> <LoginPrompt /> </div> ) }
import styled from 'styled-components'; import { SmallCaps } from '../../../theme/typography'; export const Breadcrumbs = styled.div` align-items: center; display: flex; `; export const Crumb = styled.span` ${SmallCaps}; color: ${({ theme }) => theme.colors.primary.denim}; `; export const Arrow = styled.div` height: 1.6rem; width: 1.6rem; margin: 0 0.8rem; & svg { fill: ${({ theme }) => theme.colors.primary.denim}; height: 100%; width: 100%; } `;
const removeFromArray = function(valuesList, ...values) { values.forEach(function(value) { for (let i = 0; i < valuesList.length; i++) { if (valuesList[i] === value) { valuesList.splice(i, 1); }; }; }); return valuesList; }; module.exports = removeFromArray; /* run: jasmine removeFromArray.spec.js */ // console.log('valuesList B4 splice: ', valuesList, // 'valuesList[i]: ', valuesList[i],) //console.log('valuesList AFT splice: ', valuesList);
$(document).ready(() => { $("#movie-title-btn").on("click", function (event) { event.preventDefault() const title = $("#movie-title").val().trim() $.ajax({ url: '/api/search/movie?title=' + title, method: 'get' }) .then((response) => { console.log(response.Poster) const moviePoster = $("<img>") .attr("src", response.Poster) .addClass("card-img-top"); const movieBody = $("<div>") .addClass("card-body") const moviePtag = $("<p>") .addClass("card-text") .html(`${response.Title} - ${response.Released}<br>Rated: ${response.Rated}<hr>Plot Summary: ${response.Plot}<br>Cast: ${response.Actors}<hr>RT Score: ${response.Ratings[1].Value}`); const movieContent = $("<div>") .addClass("card") .attr("movie-title", response.Title) .attr("release-year", moment(response.Released, 'DD MMM YYYY').format('MM-DD-YYYY')) .append(moviePoster, movieBody, moviePtag); $("#movie-card").append(movieContent); // get access token const token = localStorage.getItem("accessToken"); var movieData = { poster: response.Poster, title: response.Title, year: response.Year, plot: response.Plot, cast: response.Actors, rated: response.Rated, rating: response.Ratings[1].Value } console.log(movieData); $.ajax({ url: "/api/movie", method: "POST", data: movieData, headers: { authorization: `Bearer ${token}` } }).then(function (movieData) { console.log(movieData) }); }) .catch((err) => { console.log(err); }); }) })
require('dotenv').config(); const jwt = require('jsonwebtoken'); // quickly see what this file exports module.exports = { authenticate, generateToken, }; // Custom Function for token generation const jwtKey = process.env.JWT_KEY || 'add a secret to your .env file with this key'; function generateToken(user) { const jwtPayload = { ...user, funtimes: 'for laughs', role: 'admin', }; const jwtOptions = { expiresIn: '3m', } return jwt.sign(jwtPayload, jwtKey, jwtOptions) } // implementation details // CUSTOM MIDDLEWARE function authenticate(req, res, next) { //authentication tokens are normally sent as a header instead of the body const token = req.get('Authorization'); if (token) { jwt.verify(token, jwtKey, (err, decodedToken) => { if (err) { // token verification failed res.status(401).json({ message: 'invalid token'}); } else { // token is valid req.decodedToken = decodedToken; // sub-agent middleware of route handler have access to this next(); } }); } else { res.status(401).json({ error: 'No token provided, must be set on the Authorization Header'}); } }
(function ($, ko, $p) { $p.models = $p.models || {}; $p.models.BookingCategorySelection = function (stepData) { var self = this; self.categoryId = ko.observable(stepData.categoryId); self.subCategoryId = ko.observable(stepData.subCategoryId); self.publications = ko.observableArray(stepData.publications); self.shouldShowSubCategory = ko.computed(function () { return self.categoryId() !== ""; }); self.togglePublication = function (pub) { if (!pub) { return; } if (pub.isSelected === 'undefined') { return; } pub.isSelected = !pub.isSelected; }; self.errorMsg = ko.observable(""); } $p.booking = $p.booking || {}; $p.booking.stepOne = function (contract) { var adDesignService = new $p.AdDesignService(); var categorySelection = new $p.models.BookingCategorySelection(contract); ko.applyBindings(categorySelection); $('#parentCategoryId').on('change', function () { var me = $(this); categorySelection.subCategoryId = ko.observable(null); // clear if (me.val() === '') { return; } $('#subCategoryId').loadSubCategories(me.val(), false); }); $('#btnSubmit').on('click', function () { var $btn = $(this); $btn.loadBtn(); var modelToPost = ko.toJS(categorySelection); // Validate if (isNaN(categorySelection.subCategoryId()) || categorySelection.subCategoryId() === null) { categorySelection.errorMsg('You must select a sub category for your ad'); $(this).button('reset'); $btn.resetBtn(); return; } adDesignService.setCategoryAndPublications(modelToPost); }); }; })(jQuery, ko, $paramount);
#!/usr/bin/gjs const Lang = imports.lang; const vmath = imports.gi.vmath; function test_cross_product() { var v1 = vmath.Vector.three_d(1, 0, 0) var v2 = vmath.Vector.three_d(0, 1, 0) var v = vmath.Vector.three_d(0, 0, 1) var v3 = v1.cross(v2) if(v.compare(v3, 0.0001)) return true; return false; } function test_sub_vector() { var v = vmath.Vector.three_d(3, 2, 1) var d = v.sub_vector(2) var v2 = vmath.Vector.two_d(3, 2) if(v2.compare(d, 0.00001)) return true; return false; } function test_scale_vector() { var v = vmath.Vector.three_d(1, 2, 3) v.scale(5.0) var v2 = vmath.Vector.three_d(5, 10, 15) if(v2.compare(v, 0.001)) return true; return false; } function run_tests() { var test_name = "Vector\t\t\t\t" if(!test_cross_product()) { print(test_name + "failed cross product") return; } if(!test_sub_vector()) { print(test_name + "failed sub vector") return; } if(!test_scale_vector()) { print(test_name + "failed scale vector") return; } print(test_name + "passed") } run_tests()
// Google Blog Descriptions. For use in the PartnerBar var googleBlogs = [ // Product Blogs { title: "Google Enterprise Blog", subtitle: "Information, search, and users", feed : "http://googleenterprise.blogspot.com/atom.xml", link : "http://googleenterprise.blogspot.com/", classSuffix : "product", tags : ["all", "product"] }, { title: "Google Checkout Blog", subtitle: "News for sellers", feed : "http://googlecheckout.blogspot.com/atom.xml", link : "http://googlecheckout.blogspot.com/", classSuffix : "product", tags : ["all", "developer", "product"] }, { title: "The Official Gmail Blog", subtitle: "News, tips, and tricks from the team", feed : "http://feeds.feedburner.com/OfficialGmailBlog", link : "http://gmailblog.blogspot.com/", classSuffix : "product", tags : ["all", "product"] }, { title: "Blogger Buzz", subtitle: "The official buzz from blogger", feed : "http://feeds.feedburner.com/BloggerBuzz", link : "http://buzz.blogger.com/", classSuffix : "product", tags : ["all", "developer", "product"] }, { title: "The official YouTube Blog", subtitle: "See what's happening on YouTube", feed : "http://youtube.com/rss/global/our_blog.rss", link : "http://www.youtube.com/blog", classSuffix : "product", tags : ["all", "product"] }, { title: "Inside Google Booksearch", subtitle: "The inside scoop", feed : "http://booksearch.blogspot.com/atom.xml", link : "http://booksearch.blogspot.com/", classSuffix : "product", tags : ["all", "product"] }, { title: "Google News Blog", subtitle: "News from the Google News team", feed : "http://feeds.feedburner.com/GoogleNewsBlog", link : "http://googlenewsblog.blogspot.com/", classSuffix : "product", tags : ["all", "product"] }, { title: "Orkut Blog", subtitle: "Staying beatuiful on orkut", feed : "http://en.blog.orkut.com/atom.xml", link : "http://en.blog.orkut.com", classSuffix : "product", tags : ["all", "product"] }, { title: "Orkut Blog", subtitle: "o blog oficial do orkut", feed : "http://blog.orkut.com/atom.xml", link : "http://blog.orkut.com", classSuffix : "product", tags : ["all", "product"] }, { title: "Google Desktop Blog", subtitle: "Official info on Google Desktop", feed : "http://googledesktop.blogspot.com/atom.xml", link : "http://googledesktop.blogspot.com/", classSuffix : "product", tags : ["all", "product"] }, { title: "The Official Google Reader Blog", subtitle: "News, tips, and tricks", feed : "http://googlereader.blogspot.com/atom.xml", link : "http://googlereader.blogspot.com/", classSuffix : "product", tags : ["all", "product"] }, { title: "Google Docs", subtitle: "News and notes from the team", feed : "http://googledocs.blogspot.com/atom.xml", link : "http://googledocs.blogspot.com/", classSuffix : "product", tags : ["all", "product"] }, { title: "Google Talk", subtitle: "On voice, IM, and open communications", feed : "http://googletalk.blogspot.com/atom.xml", link : "http://googletalk.blogspot.com/", classSuffix : "product", tags : ["all", "product"] }, { title: "Google Lat Long Blog", subtitle: "News from the Earth and Maps teams", feed : "http://feeds.feedburner.com/blogspot/SbSV", link : "http://google-latlong.blogspot.com/", classSuffix : "product", tags : ["all", "developer", "product"] }, { title: "Custom Search Engine Blog", subtitle: "News and tips from the team", feed : "http://googlecustomsearch.blogspot.com/atom.xml", link : "http://googlecustomsearch.blogspot.com/", classSuffix : "product", tags : ["all", "developer", "product"] }, { title: "Google Notebook Blog", subtitle: "News and tips from the team", feed : "http://googlenotebookblog.blogspot.com/atom.xml", link : "http://googlenotebookblog.blogspot.com/", classSuffix : "product", tags : ["all", "product"] }, { title: "SketchUp Blog", subtitle: "News and noted from the SketchUp folks", feed : "http://sketchupdate.blogspot.com/atom.xml", link : "http://sketchupdate.blogspot.com/", classSuffix : "product", tags : ["all", "developer", "product"] }, { title: "Google Finance Blog", subtitle: "News and views from the team", feed : "http://feeds.feedburner.com/GoogleFinanceBlog", link : "http://googlefinanceblog.blogspot.com/", classSuffix : "product", tags : ["all", "product"] }, { title: "Google Photo Blog", subtitle: "Tips from the Picasa team", feed : "http://googlephotos.blogspot.com/atom.xml", link : "http://googlephotos.blogspot.com/", classSuffix : "product", tags : ["all", "product"] }, { title: "Google Mobile Blog", subtitle: "News and views from the team", feed : "http://googlemobile.blogspot.com/atom.xml", link : "http://googlemobile.blogspot.com/", classSuffix : "product", tags : ["all", "developer", "product"] }, // Advertising Blogs { title: "Inside AdSense", subtitle: "A look inside Google AdSense", feed : "http://feeds.feedburner.com/blogspot/tuAm", link : "http://adsense.blogspot.com/", classSuffix : "advertising", tags : ["all", "ads"] }, { title: "Google Analytics", subtitle: "Stright fro the Analytics Team", feed : "http://analytics.blogspot.com/feeds/posts/default", link : "http://analytics.blogspot.com/", classSuffix : "advertising", tags : ["all", "ads"] }, { title: "Inside AdWords", subtitle: "Google's official AdWords blog", feed : "http://feeds.feedburner.com/blogspot/ATHs", link : "http://adwords.blogspot.com/", classSuffix : "advertising", tags : ["all", "ads"] }, { title: "Health Advertising Blog", subtitle: "News and Notes", feed : "http://google-health-ads.blogspot.com/atom.xml", link : "http://google-health-ads.blogspot.com/", classSuffix : "advertising", tags : ["all", "ads"] }, { title: "Google CPG Blog", subtitle: "News and Notes, straight from the team", feed : "http://google-cpg.blogspot.com/atom.xml", link : "http://google-cpg.blogspot.com/", classSuffix : "advertising", tags : ["all", "ads"] }, { title: "Entertainment Italia Blog", subtitle: "Entertainment Advertising Italia", feed : "http://google-entertainment-it.blogspot.com/atom.xml", link : "http://google-entertainment-it.blogspot.com/", classSuffix : "advertising", tags : ["all", "ads"] }, { title: "Google AdWords Retail Blog", subtitle: "AdWords Retail Tips", feed : "http://adwordsretail.blogspot.com/atom.xml", link : "http://adwordsretail.blogspot.com/", classSuffix : "advertising", tags : ["all", "ads"] }, // Developer Blogs { title: "Open Source at Google", subtitle: "News on projects and programs", feed : "http://google-opensource.blogspot.com/atom.xml", link : "http://www.google-opensource.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "Google Testing Blog", subtitle: "If it ain't broke...", feed : "http://googletesting.blogspot.com/atom.xml", link : "http://googletesting.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "Google Code Blog", subtitle: "Tips and tricks for developers", feed : "http://google-code-updates.blogspot.com/atom.xml", link : "http://google-code-updates.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "The AJAX API Blog", subtitle: "What's happening with the AJAX APIs", feed : "http://googleajaxsearchapi.blogspot.com/atom.xml", link : "http://googleajaxsearchapi.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "Google Web Toolkit Blog", subtitle: "Musings on GWT", feed : "http://googlewebtoolkit.blogspot.com/atom.xml", link : "http://googlewebtoolkit.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "Google Maps API Blog", subtitle: "tips and tricks from the team", feed : "http://feeds.feedburner.com/OfficialGoogleMapsApiBlog", link : "http://googlemapsapi.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "YouTube API Blog", subtitle: "Tips, tricks, and news tidbits", feed : "http://youtubeapi.blogspot.com/atom.xml", link : "http://apiblog.youtube.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "GData API Blog", subtitle: "Tips, tricks, and news tidbits", feed : "http://googledataapis.blogspot.com/atom.xml", link : "http://googledataapis.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "AdWords API Blog", subtitle: "Information about the AdWords API", feed : "http://adwordsapi.blogspot.com/atom.xml", link : "http://adwordsapi.blogspot.com", classSuffix : "developer", tags : ["all", "developer"] }, { title: "Google Checkout API Blog", subtitle: "News, tips, and tricks", feed : "http://googlecheckoutapi.blogspot.com/atom.xml", link : "http://googlecheckoutapi.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "Google Mashup Editor Blog", subtitle: "Information about the Mashup Editor", feed : "http://googlemashupeditor.blogspot.com/atom.xml", link : "http://googlemashupeditor.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "Google Summer of Code", subtitle: "Students and Open Source", feed : "http://googlesummerofcode.blogspot.com/atom.xml", link : "http://googlesummerofcode.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "Gears API Blog", subtitle: "What's happeining with Gears", feed : "http://gearsblog.blogspot.com/atom.xml", link : "http://gearsblog.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "Google Desktop API Blog", subtitle: "News, tips, and tricks", feed : "http://googledesktopapis.blogspot.com/atom.xml", link : "http://googledesktopapis.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "Google Gadgets API Blog", subtitle: "News, tips, and tricks", feed : "http://googlegadgetsapi.blogspot.com/atom.xml", link : "http://googlegadgetsapi.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "The OpenSocial API Blog", subtitle: "The current buzz on OpenSocial", feed : "http://opensocialapis.blogspot.com/atom.xml", link : "http://opensocialapis.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "android", subtitle: "An Open Handset Alliance Project", feed : "http://feeds.feedburner.com/blogspot/hsDu", link : "http://android-developers.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, { title: "Programa con Google", subtitle: "Programa con Google", feed : "http://programa-con-google.blogspot.com/atom.xml", link : "http://programa-con-google.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, /* * jcooper: only 2 entries in this blog. Don't use it. { title: "SketchUp API Blog", subtitle: "News, tips, and tricks", feed : "http://sketchupapi.blogspot.com/atom.xml", link : "http://sketchupapi.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, */ { title: "Google Testing Blog-de", subtitle: "Testet nicht gut genug", feed : "http://googletesting-de.blogspot.com/atom.xml", link : "http://googletesting-de.blogspot.com/", classSuffix : "developer", tags : ["all", "developer"] }, // Country Blogs { title: "The Official Google Blog", subtitle: "Googlers thoughts on our products and culture", feed : "http://googleblog.blogspot.com/atom.xml", link : "http://googleblog.blogspot.com/", classSuffix : "country", tags : ["all"] }, // Vertical Blogs { title: "Librarian Central", subtitle: "Google tips, news, and updates", feed : "http://librariancentral.blogspot.com/atom.xml", link : "http://librariancentral.blogspot.com/", classSuffix : "vertical", tags : ["all"] }, { title: "Public Policy Blog", subtitle: "Views on government, policy and politics", feed : "http://googlepublicpolicy.blogspot.com/atom.xml", link : "http://googlepublicpolicy.blogspot.com/", classSuffix : "vertical", tags : ["all"] }, { title: "Google Research Blog", subtitle: "Whats happeing inside Google Research", feed : "http://googleresearch.blogspot.com/atom.xml", link : "http://googleresearch.blogspot.com/", classSuffix : "vertical", tags : ["all"] }, { title: "Online Security Blog", subtitle: "Security and Safety on the Internet", feed : "http://googleonlinesecurity.blogspot.com/atom.xml", link : "http://googleonlinesecurity.blogspot.com/", classSuffix : "vertical", tags : ["all"] }, { title: ".org Blog", subtitle: "News from our philanthropic arm", feed : "http://blog.google.org/atom.xml", link : "http://blog.google.org", classSuffix : "vertical", tags : ["all"] }, { title: "Webmaster Central Blog", subtitle: "Notes on crawling and indexing", feed : "http://googlewebmastercentral.blogspot.com/atom.xml", link : "http://googlewebmastercentral.blogspot.com/", classSuffix : "vertical", tags : ["all"] }, { title: "Webmaster Central China", subtitle: "Notes on crawling and indexing", feed : "http://www.googlechinawebmaster.com/atom.xml", link : "http://www.googlechinawebmaster.com/", classSuffix : "vertical", tags : ["all"] }, { title: "Webmaster Zentrale", subtitle: "Zom crawling und zur Indexierung", feed : "http://googlewebmastercentral-de.blogspot.com/atom.xml", link : "http://googlewebmastercentral-de.blogspot.com/", classSuffix : "vertical", tags : ["all"] }, { title: "The Official Google Mac Blog", subtitle: "Macs inside Google", feed : "http://googlemac.blogspot.com/atom.xml", link : "http://googlemac.blogspot.com/", classSuffix : "vertical", tags : ["all"] } ]; function getBlogsByTag(tag) { var blogs = new Array(); for (var i=0; i<googleBlogs.length; i++) { var pbe = googleBlogs[i]; if (pbe.tags && pbe.tags.length > 0) { for (var t=0; t<pbe.tags.length; t++) { if (pbe.tags[t].toLowerCase() == tag.toLowerCase() ) { blogs.push(pbe); break; } } } } return blogs; }
if (Cus_analyticsId!=='') { (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create',Cus_analyticsId, 'auto', 'blogger'); ga('blogger.send', 'pageview'); window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config',Cus_analyticsId); }; (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create','UA-98674484-3', 'auto', 'blogger'); ga('blogger.send', 'pageview'); window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config','UA-98674484-3'); var head = document.getElementsByTagName('head')[0], link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = 'https://rawcdn.githack.com/prakashincovai/ShowAds/c5f5323b51acd028a3e09fe1aa39d0f3c65227ae/Basic Ads/css/Res.css'; head.appendChild(link); if (ads_size=='728x90') { $(function(){ var adBanners = [ "cars24728x214.jpg", "icici728x90.jpg", "bigbasket728x90.png", "hostgator728x90.gif", "GoDaddy728x90.gif", "flipkart728x90.jpg", "samsung728x90.jpg", "GoDaddy728x901.gif" ]; var bannerLinks = [ "https://clnk.in/gXQB", "https://clnk.in/gXIT", "https://clnk.in/gXJi", "https://clnk.in/gXfD", "https://clnk.in/gXeG", "http://www.flipkart.com/offers/electronics?affid=prakashincovai", "https://goo.gl/y4tS3k", "https://clnk.in/gXeG" ]; var imgPrefix = "https://raw.githack.com/prakashincovai/ShowAds/master/Basic Ads/images/"; var randNum = Math.floor(Math.random() * (7 - 0 + 1)) + 0; var topAdBanner = $('#topad > a > img'); var newBannerImg = imgPrefix + adBanners[randNum]; var newBannerLink = bannerLinks[randNum]; // update new img src and link HREF value $(topAdBanner).attr('src',newBannerImg); $('#topad > a').attr('href',newBannerLink); }); };
import { lazy } from 'react' const HomePage = lazy(() => import('./HomePage')) const AuthPage = lazy(() => import('./AuthPage')) const DetailPost = lazy(() => import('./DetailPost')) export { HomePage, AuthPage, DetailPost }
var c = require('../common/config'); var gameConfig = require("../common/gameConfig") var request = require('../manager/request'); var time = require("../manager/time"); var launch = require("../platform/launch"); var audio = require("../manager/audio") var ui = require("../manager/ui"); var userdata = require("../data/userdata"); var gamedata = require("../data/gamedata"); var gametype = require("../data/gametype"); var util = require("../common/util"); var event = require("../manager/event") var ui = require("../manager/ui") const localSave = false const data_key = "191211_8" var gameMgr = { login: function (callback, showLoading = true) { console.log("login"); if (showLoading) ui.showLoading({ title: "登录中" }); var self = this; if (WECHATGAME || QQPLAY) { var res = platform.getLaunchOptionsSync(); var channel = res.query.channel if (channel == undefined) channel = "" platform.login({ success: (res) => { console.log("res.code:" + res.code) var params = { Code: res.code } if (QQPLAY) params = { QQCode: res.code, } request.post(c.configUrl.url, params, function (data) { if (data.Result == 0) { console.log("Get OpenID:" + data.Member.OpenID) userdata.openid = data.Member.OpenID gamedata.drawNum = parseInt(data.Member.LuckDrawCount)//抽奖次数 //签到数据 var strArray = data.Member.SignStr.split(',') for (var i = 0; i < strArray.length; i++) { gamedata.signArray[i] = parseInt(strArray[i]) == 1 } gamedata.getGuideData() platform.getUserInfo({ lang: "zh_CN", success: (res) => { console.log(res) userdata.isGetUserData = true userdata.nickname = res.userInfo.nickName userdata.icon = res.userInfo.avatarUrl self.updateUserInfo() }, fail: (res) => { console.log("授权失败") userdata.isGetUserData = false userdata.userInfoBtn = wx.createUserInfoButton({ type: 'image', image: '', style: { left: 0, top: 0, width: gamedata.screenWidth, height: gamedata.screenHeight } }) userdata.userInfoBtn.onTap((res) => { userdata.userInfoBtn.hide() userdata.isGetUserData = true userdata.nickname = res.userInfo.nickName userdata.icon = res.userInfo.avatarUrl self.updateUserInfo() }) }, }) } }) }, fail: (res) => { ui.showFloatTip("登录失败,请稍后重试") }, complete: () => { ui.hideLoading() } }) } }, //获取游戏控制数据 getGameControl() { var params = { AppID: c.appID, } request.post(c.configUrl.control, params, (data) => { console.log(data) var info = data.GameControlInfo gamedata.control.showGamelist = parseInt(info.ShowGameList) == 1 gamedata.control.bannerRefreshTime = parseInt(info.RefreshTime) gamedata.control.homeBannerRatio = parseInt(info.Banner) gamedata.control.showMore = parseInt(info.Recharge) == 1 gamedata.control.uglyShare = parseInt(info.Share) == 1 c.netversion = parseInt(info.Edition) if (info.Edition > c.localversion) { gamedata.control.uglyShare = true } }) }, //获取分享文案 getShareContent() { var params = { AppID: c.appID, } request.post(c.configUrl.share, params, (data) => { gamedata.shareData = new Array() for (var i = 0; i < data.Copywriting.length; i++) { var item = { text: data.Copywriting[i].Text, img: data.Copywriting[i].Img } gamedata.shareData.push(item) } console.log(gamedata.shareData) }) }, //抽奖 draw: function (func) { if (WECHATGAME || QQPLAY) { if (gamedata.drawNum <= 0) { ui.showFloatTip("抽奖次数已用完~") return } var params = { LuckDraw: userdata.openid } request.post(c.configUrl.url, params, function (data) { if (data.Result == 0) { var type = parseInt(data.LuckDrawType) gamedata.drawNum = parseInt(data.LuckDrawCount) if (func) func(type) } }) } }, addDrawNum: function () { if (WECHATGAME || QQPLAY) { var params = { AddLuckDrawCount: userdata.openid } request.post(c.configUrl.url, params, function (data) { if (data.Result == 0) { gamedata.drawNum = parseInt(data.LuckDrawCount) event.emit(gametype.eventType.UpdateDrawNum) event.emit(gametype.eventType.RedTip) } }) } }, //清除用户数据 Delete: function () { gamedata.resetDataKey() var params = { ClearUser: userdata.openid } request.post(c.configUrl.url, params, function () { this.clearChestData() ui.showFloatTip("重启后生效") }.bind(this)) }, //签到 sign(idx) { var self = this if (gamedata.signArray[idx]) return var params = { RepairSign: userdata.openid + "|" + idx } request.post(c.configUrl.url, params, function (data) { if (data.Result == 0) { var signStr = data.SignStr.split(',') gamedata.signArray = new Array() for (var i = 0; i < signStr.length; i++) { gamedata.signArray.push(parseInt(signStr[i]) == 1) } var gold = gameConfig.sign[idx].reward.split('|')[0] var diamond = gameConfig.sign[idx].reward.split('|')[1] var gift = gameConfig.sign[idx].reward.split('|')[2] if (gold > 0) { self.AddGold(gold) } if (diamond > 0) { self.addDiamond(diamond) } event.emit(gametype.eventType.RedTip) if (gift > 0) { //礼包模块待做 } event.emit(gametype.eventType.Sign) event.emit(gametype.eventType.RedTip) } }) }, //领主加金币接口 AddGold(num) { gamedata.masterData.gold += parseInt(num) if (num > 0) { ui.showFloatTip("获得"+num+"金币") } gamedata.saveMasterData() event.emit(gametype.eventType.GOLD) event.emit(gametype.eventType.RedTip) }, //领主加钻石接口 addDiamond(num) { gamedata.masterData.gem += parseInt(num) if (num > 0) { ui.showFloatTip("获得"+num+"钻石") } gamedata.saveMasterData() event.emit(gametype.eventType.Diamond) event.emit(gametype.eventType.RedTip) }, //更新玩家信息 updateUserInfo() { var self = this var params = { UpdateUserInfo: userdata.openid + "|" + userdata.nickname + "|" + userdata.icon } request.post(c.configUrl.url, params, function (data) { if (data.Result == 0) { console.log("更新玩家数据成功") if (gamedata.battleValue == 0) { self.updateBattleValue() } } }) }, //获取排行数据 getRankingData(func) { if (!WECHATGAME) { //本地测试数据 var data = JSON.parse("{\"Result\":\"0\",\"Ranking\":[{\"OpenID\":\"obBqq5Z1Lrq3Sy1ahGiYIme4Ax2M\",\"Head\":\"https://wx4.sinaimg.cn/mw690/006ys9Gfgy1fxto237bq2j302a02a743.jpg\",\"Name\":\"殇        \",\"Score\":45000056,\"CreateTime\":\"2019-12-08T01:59:44.9870929+08:00\",\"Index\":1},{\"OpenID\":\"obBqq5ZB56Ot7g5OA5KFNt8wg_R4\",\"Head\":\"https://wx3.sinaimg.cn/mw690/006ys9Gfgy1fxto4jdpibj302a02aa9u.jpg\",\"Name\":\"拾贰\",\"Score\":387,\"CreateTime\":\"2019-11-16T18:38:26.813\",\"Index\":2},{\"OpenID\":\"obBqq5RqfxY4mkbbt2i9Ii1gWdgs\",\"Head\":\"https://wx4.sinaimg.cn/mw690/006ys9Gfgy1fxto27b5pqj302a02aa9u.jpg\",\"Name\":\"Ken\",\"Score\":50,\"CreateTime\":\"2019-12-27T12:43:21.9363307+08:00\",\"Index\":72},{\"OpenID\":\"obBqq5bxifjYfa-Po7ER8ELx5oYo\",\"Head\":\"https://wx3.sinaimg.cn/mw690/006ys9Gfgy1fxto0oqthuj302a02aa9u.jpg\",\"Name\":\"不礼不才\",\"Score\":46,\"CreateTime\":\"2019-11-22T09:59:30.237\",\"Index\":100}]}") if (data.Result == 0) { gamedata.rankData = new Array() for (var i = 0; i < data.Ranking.length; i++) { gamedata.rankData.push(data.Ranking[i]) } if (func) func() } return } var params = { GetRanking: "" } request.post(c.configUrl.url, params, function (data) { console.log(data) if (data.Result == 0) { gamedata.rankData = new Array() for (var i = 0; i < data.Ranking.length; i++) { gamedata.rankData.push(data.Ranking[i]) } if (func) func() } }) }, //领取好友助力奖励~ getInviteReward() { for (var i = 0; i < gamedata.masterData.inviteReward.length; i++) { if (gamedata.masterData.inviteReward[i] == 0) { if (gamedata.masterData.friendList.length >= parseInt(gameConfig.friend[i].num)) { this.addDiamond(parseInt(gameConfig.friend[i].reward)) gamedata.masterData.inviteReward[i] = 1 this.saveMaster() event.emit(gametype.eventType.Friend) return } } } }, } module.exports = gameMgr;
import React from 'react'; import { connect } from 'react-redux'; import CreateableSelect from 'react-select/lib/Creatable'; import PropTypes from 'prop-types'; import withStyles from '@material-ui/styles/withStyles'; import Dialog from '@material-ui/core/Dialog'; import DialogTitle from '@material-ui/core/DialogTitle'; import DialogContent from '@material-ui/core/DialogContent'; import Button from '@material-ui/core/Button'; import Loader from './Loader'; import { styles } from '../theme'; import { joinChannel, fetchChannelList, createChannel } from '../store/channels/actions'; class JoinChannelDialog extends React.Component { state = { channels: [], loaded: false }; async componentDidUpdate(prevProps) { const prevOpen = prevProps.open; const currOpen = this.props.open; if (!prevOpen && currOpen) { const channels = await this.props.fetchAvailChannels(); const options = channels.map(ch => ({ label: ch.name, value: ch.id })); this.setState({ channels: options, loaded: true }); } } static getDerviedStateFromProps(nextProps, prevState) { if (prevState.loaded && nextProps.open) return { loaded: false }; } render() { const { open, onClose, attemptJoinChannel, createAndJoinChannel, classes } = this.props; const { channels, loaded } = this.state; const submit = async evt => { evt.preventDefault(); const channelId = evt.target.channelId.value; if (channels.find(ch => ch.value === Number(channelId))) { await attemptJoinChannel(evt.target.channelId.value); } else { await createAndJoinChannel(channelId); } onClose(); }; return ( <Dialog open={open} onClose={onClose} fullWidth maxWidth="sm" classes={{ paper: classes.dialogPaper }} > <DialogTitle>Join New Channel</DialogTitle> <DialogContent className={classes.dialogPaper}> <form onSubmit={submit}> <Loader isLoading={!loaded}> <CreateableSelect options={channels} name="channelId" placeholder="Type channel name here" /> <Button type="submit" variant="contained" color="primary"> Join </Button> </Loader> </form> </DialogContent> </Dialog> ); } } const mapState = state => ({ user: state.user }); const mapDispatch = dispatch => ({ attemptJoinChannel: channelId => dispatch(joinChannel(channelId)), fetchAvailChannels: () => dispatch(fetchChannelList(false)), createAndJoinChannel: name => dispatch(createChannel(name)) }); export default connect( mapState, mapDispatch )(withStyles(styles)(JoinChannelDialog)); JoinChannelDialog.propTypes = { /** Whether or not to display diaglog */ open: PropTypes.bool, /** Callback called when a close is triggered */ onClose: PropTypes.func.isRequired }; JoinChannelDialog.defaultProps = { open: false };