text
stringlengths
7
3.69M
// Implements the localization logic for the application // Can be used for direct resource string fetching and // to update the view automatically where possible. function Localizer(resources) { var dataAttrb = "data-localize"; if (resources == null) throw "No resource object passed to Localizer!"; var res = resources; // Returns a resource with name localizationKey and this.get = function (localizationKey) { return res[localizationKey]; }; // Date/Time formatting methods this.longDateFormat = function (dateItem) { if (res.longDateFormat) { return res.longDateFormat(dateItem); } else { return $.ig.formatter(dateItem, "date", $.ig.regional.defaults.dateLongPattern + ' ' + $.ig.regional.defaults.timeLongPattern); } } this.onlyMonthDayFormat = function (dateItem) { if (dateItem !== null) { return $.ig.regional.defaults.monthNamesShort[dateItem.getMonth()] + "/" + parseInt(dateItem.getDate()); } } this.shortDateFormat = function (dateItem) { if (res.shortDateFormat) { return res.shortDateFormat(dateItem); } else { return $.ig.formatter(dateItem, "date", $.ig.regional.defaults.datePattern); } } // Finds all DOM elements with attribute data-localize set and // applies the corresponding localization item to the element this.localizeView = function (view) { var viewResources = res[view]; // Get all HTML elements that have a resource key. $('[' + dataAttrb + ']').each(function () { // Get the resource key from the element. var resKey = $(this).attr(dataAttrb); if (resKey) { // Get all the resources that start with the key. var resValue = viewResources[resKey]; if (resKey.indexOf('.') == -1) { // No dot notation in resource key, // assign the resource value to the element's // innerHTML. $(this).html(resValue); } else { // Dot notation in resource key, assign the // resource value to the element's property // whose name corresponds to the substring // after the dot. var attrKey = resKey.substring(resKey.indexOf('.') + 1); $(this).attr(attrKey) = resValue; } } }); }; }
// import configuration of enviroment require('dotenv').config(); // React imports const react = require('react'); const reactDOM = require('react-dom'); const reactEngine = require('express-react-views').createEngine(); // Express imports const express = require('express'); const app = express(); const path = require('path'); const cors = require('cors'); // Express router imports const root_router = require('./routes/root'); const register_router = require('./routes/register'); const login_router = require('./routes/login'); const courses_router = require('./routes/courses'); const api_router = require('./routes/usersAPI'); // Express app configuration app.use(express.static(path.join(__dirname, 'public'))); app.use(express.urlencoded({ extended: false })); app.use(cors()); // Set up view engine app.set('views', __dirname + '/views'); app.set('view engine', 'jsx'); app.engine('jsx', reactEngine); // Routes redirects app.use(express.json()); app.use('/public', express.static(path.join(__dirname, 'public'))); app.use('/register', register_router); app.use('/login', login_router); app.use('/courses', courses_router); app.use('/api', api_router); app.use('/', root_router); const port = process.env.PORT || 4000; app.listen(port, () => console.log(`Escuchando en puerto ${port}...`));
var Title = { add: function(title, content) { var result = myVar.lists.filter(function(obj) { return obj.title === title; }); if (result.length === 0 && title !== "" && content !== "") { myVar.lists.push({ "title": title, "content": content }); localStorage["list"] = JSON.stringify(myVar.lists); return true; } else { return false; } }, delete: function(title) { myVar.lists = myVar.lists.filter(function(obj) { return obj.title !== title; }); localStorage["list"] = JSON.stringify(myVar.lists); }, update: function(prevtitle, currenttitle, content) { for (var count = 0; count < myVar.lists.length; count++) { if (myVar.lists[count].title == prevtitle) { myVar.lists[count].title = currenttitle; myVar.lists[count].content = content; } } localStorage["list"] = JSON.stringify(myVar.lists); }, ele: function(str, identifier) { if(str == 'name') { return document.getElementsByName(identifier); } else if(str == 'id') { return document.getElementById(identifier); } }, bindUIActions: function() { form.onsubmit = function() { return false; } submit.addEventListener('click', function() { title = Title.ele('name', 'title')[0].value; content = Title.ele('name', 'text')[0].value; var status = Title.add(title, content); if (status) { Title.ele('id', 'container').innerHTML += myVar.template.replace('{title}', title).replace('{content}', content); } }); container.addEventListener('click', function(e) { if (e.target && e.target.className == "delete") { title = e.target.parentNode.parentNode.querySelector('h3').innerHTML; Title.delete(title); e.target.parentNode.parentNode.parentNode.remove(); } if (e.target && e.target.className == "edit") { title = e.target.parentNode.parentNode.querySelector('h3').innerHTML; content = e.target.parentNode.parentNode.querySelector('p').innerHTML; Title.ele('name', 'title')[0].dataset.value = title; e.target.parentNode.parentNode.querySelector('h3').setAttribute('id', 'active'); window.scrollTo(0, 0); Title.ele('name', 'title')[0].value = title; Title.ele('name', 'text')[0].value = content; Title.ele('id', 'submit').className = 'hidden'; Title.ele('id', 'update').className = 'visible'; Title.ele('id', 'cancel').className = 'visible'; } }); update.addEventListener('click', function() { Title.update(Title.ele('name', 'title')[0].dataset.value, Title.ele('name', 'title')[0].value, Title.ele('name', 'text')[0].value); Title.ele('id', 'active').innerHTML = Title.ele('name', 'title')[0].value; Title.ele('id', 'active').nextSibling.innerHTML = Title.ele('name', 'text')[0].value; Title.ele('id', 'active').removeAttribute('id'); Title.ele('id', 'submit').className = 'visible'; Title.ele('id', 'update').className = 'hidden'; Title.ele('id', 'cancel').className = 'hidden'; }); cancel.addEventListener('click', function() { Title.ele('id', 'submit').className = 'visible'; Title.ele('id', 'update').className = 'hidden'; Title.ele('id', 'cancel').className = 'hidden'; }); search.addEventListener('keyup', function() { Title.ele('id', 'container').innerHTML = ''; var searchField = Title.ele('id', 'search').value; var myExp = new RegExp(searchField, "i"); for (var count = 0; count < myVar.lists.length; count++) { if (myVar.lists[count].title.search(myExp) != -1 || myVar.lists[count].content.search(myExp) != -1) { Title.ele('id', 'container').innerHTML += myVar.template.replace('{title}', myVar.lists[count].title).replace('{content}', myVar.lists[count].content); } } }); }, setLocalStorage: function() { if (localStorage["list"]) { var title = '', content = ''; myVar.lists = JSON.parse(localStorage["list"]); for (var i = 0; i < myVar.lists.length; i++) { title = myVar.lists[i].title; content = myVar.lists[i].content; Title.ele('id', 'container').innerHTML += myVar.template.replace('{title}', title).replace('{content}', content); }; } }, settings: { template: '<div class="mainContent"><div class="content"><div class="divImage">&nbsp;</div><div class="divContent"><h3>{title}</h3><p>{content}</p></div><div class="buttons"><button class="edit">Edit</button><button class="delete">Delete</button></div></div></div>', lists: [], title: '', content: '', form: document.getElementById('form'), submit: document.getElementById('submit'), container: document.getElementById('container'), search: document.getElementById('search'), update: document.getElementById('update'), cancel: document.getElementById('cancel') }, init: function() { window.myVar = this.settings; this.bindUIActions(); this.setLocalStorage(); } }; Title.init();
const axios = require('axios'); const moment = require('moment'); const turf = require('@turf/turf'); const settings = require('./appsettings.json'); async function getBirdInfo(settings) { const limit = 500; let offset = 0; let trips = []; let res = {}; const url = `${settings.BaseUrl}trips`; do { res = await axios.get(url, { params: { limit, offset, }, headers: settings.Headers }); trips = trips.concat(res.data.trips); offset += res.data.trips.length; } while (res.data.trips.length != 0); return trips; } async function getLimeInfo(settings) { let page = 0; let res = {}; let trips = []; const url = `${settings.BaseUrl}trips`; do { res = await axios.get(url, { params: { page, }, headers: settings.Headers }); trips = trips.concat(res.data.data); page += 1; } while (res.data.data.length != 0); return trips; } async function getSkipInfo(settings) { let trips = []; const url = `${settings.BaseUrl}trips.json`; let res = await axios.get(url, { headers: settings.Headers }); trips = trips.concat(res.data.reduce( (accu, curr) => { accu.push(curr); return accu; }, []) ); return trips; } const bird = getBirdInfo(settings.CompanySettings.Bird); const lime = getLimeInfo(settings.CompanySettings.Lime); const skip = getSkipInfo(settings.CompanySettings.Skip); let totalTrips = []; var fs = require('fs'); var fileStream = fs.createWriteStream('trips.json'); let returns = 0; function callback() { returns += 1; if (returns == 3) { fileStream.write(JSON.stringify(totalTrips)); fileStream.close(); } } bird.then((trips) => { totalTrips = totalTrips.concat(trips); console.log('Done reading Bird.'); callback(); }) .catch((err) => { console.error(JSON.stringify(err)); }); lime.then((trips) => { totalTrips = totalTrips.concat(trips); console.log('Done reading Lime.'); callback(); }) .catch((err) => { console.error(JSON.stringify(err)); }); skip.then((trips) => { totalTrips = totalTrips.concat(trips); console.log('Done reading Skip.'); callback(); }) .catch((err) => { console.error(JSON.stringify(err)); });
import React from 'react' import Center from './Center'; import {BsExclamationTriangleFill} from 'react-icons/bs'; import { IconContext } from 'react-icons/lib' function FetchCenters(props) { const scrollToTop = () =>{ window.scrollTo({ top: 0, behavior: 'smooth' }); }; return ( <div> { !props.items ? <></> : props.items.length ? ( <div> <IconContext.Provider value={{color:'#00ffb9',size:'25px'}}> <div className='accordionSection'> {props.items.map(item => (<Center key={item.session_id} item={item} index={item.session_id} />))} <div style={{textAlign:'center'}}><button className='topbtn' onClick={scrollToTop}>Back to Top</button></div> </div> </IconContext.Provider> </div> ) : (<div className='occupyFull'><div><BsExclamationTriangleFill /></div><div><h3>Sorry! No slots available.</h3></div></div>)} </div> ) } export default FetchCenters
// 插件 let KVue; class Store { constructor(options) { // options 是传入的State,actions这些数据 this._mutations = options.mutations; this._actions = options.actions; this._wrappedGetters = options.getters; const computed = {}; this.getters = {}; const store = this; Object.keys(this._wrappedGetters).forEach((key) => { // 获取用户定义的getter const fn = store._wrappedGetters[key]; // 转换为computed的可以使用无参形式 computed[key] = function() { return fn(store.state); }; Object.defineProperty(store.getters, key, { get: () => store._vm[key], }); }); this._vm = new KVue({ data: { $$state: options.state, }, computed, }); // 绑定this this.commit = this.commit.bind(store); this.dispatch = this.dispatch.bind(store); // 源码这样写的 // const store = this; // const {commit, action} =store // this.commit = function boundCommit(type, payload) { // commit.call(store, type, payload) // } // this.dispatch = function boundDispatch(type, payload) { // return dispatch.call(store, type, payload) // } // this.action = function boundAction(type, payload) { // return action.call(store, type, payload) // } } get state() { return this._vm._data.$$state; } set state(v) { console.error("please use replaceState too reset state"); } commit(type, payload) { const entry = this._mutations[type]; if (!entry) { console.error("unKown"); } entry(this.state, payload); } dispatch(type, payload) { const entry = this._actions[type]; if (!entry) { console.error("unKown"); } return entry(this, payload); } } function install(Vue) { KVue = Vue; // 混入 Vue.mixin({ beforeCreate() { if (this.$options.store) { Vue.prototype.$store = this.$options.store; } }, }); } export default { Store, install, };
import React from 'react'; import {render} from 'react-dom'; import "../../css/entry/modules/register.css"; import register from "../../data/register.json"; import { connect } from 'react-redux'; import {Link} from 'react-router'; var UserActions=require('../../entry/action/UserActions'); var ProxyQ = require('../../components/proxy/ProxyQ'); var Register = React.createClass({ repaintImage: function () { var img = document.getElementById("validateImage"); img.src = "/supnuevo/validatecode.jpg?rnd=" + Math.random(); }, register: function () { var field_values = { merchantType: '', nickName: '', password: '', email: '', qq: '', verify: '' }; $('#first_step input').removeClass('error').removeClass('valid'); var error = 0; //检查昵称不能为空 var fields2 = $('#nickName'); fields2.each(function () { //前端校验 var value2 = $(this).val(); if (value2.length < 1) { $(this).addClass('error'); $(this).effect("shake", {times: 3}, 50); document.getElementById("nickNameMsg").innerHTML = "昵称不能为空 "; error++; } else { var nickName = document.getElementById("nickName").value;// 获取输入框信息 field_values.nickName = nickName; var merchantType = document.getElementById("merchantType").value; field_values.merchantType = merchantType; if (nickName != null && nickName != "" && nickName.indexOf(" ") == -1) { document.getElementById("nickNameMsg").innerHTML = ""; $('#nickName').addClass('valid'); } else if (nickName.indexOf(" ") >= 0) { $('#nickName').addClass('error'); $('#nickName').effect("shake", {times: 3}, 50); document.getElementById("nickNameMsg").innerHTML = "不允许有空格 " error++; } } }); //检查密码不能为空 var fields = $('#password'); fields.each(function () { var value = $(this).val(); var passWord = document.getElementById("password").value;// 获取输入框信息 field_values.password = passWord; var reg = /^[0-9a-zA-Z]+$/; if (value.length < 1) { $(this).addClass('error'); $(this).effect("shake", {times: 3}, 50); document.getElementById("passwordMsg").innerHTML = "密码不能为空 "; error++; } else if (passWord.indexOf(" ") >= 0) { $('#password').addClass('error'); $('#password').effect("shake", {times: 3}, 50); document.getElementById("passwordMsg").innerHTML = "不允许有空格" error++; } else if (!reg.test(passWord)) { $('#password').addClass('error'); $('#password').effect("shake", {times: 3}, 50); document.getElementById("passwordMsg").innerHTML = "您输入的字符不是数字或者字母 " error++; } else { $(this).addClass('valid'); document.getElementById("passwordMsg").innerHTML = ""; } }); //验证两次输入的密码是否一致 var fields3 = $('#cpassword'); fields3.each(function () { var value3 = $(this).val(); if ($('#password').val() != $('#cpassword').val() || $('#cpassword').val().length < 1) { $(this).removeClass('valid').addClass('error'); $(this).effect("shake", {times: 3}, 50); document.getElementById("cpasswordMsg").innerHTML = "两次输入的密码不一致"; error++; } else { $(this).addClass('valid'); document.getElementById("cpasswordMsg").innerHTML = ""; } }); //检查是否同意服务条款 agreeMsg var fields4 = $('#agree'); fields4.each(function () { var ck = document.getElementById("agree"); if (ck.checked) {//选中 ck.value = 1; } else { ck.value = 0; } var value4 = ck.value; if (value4 != 1) { $(this).addClass('error'); $(this).effect("shake", {times: 3}, 50); document.getElementById("agreeMsg").innerHTML = "请接受supnuevo服务条款 "; error++; } else { /* $(this).addClass('valid'); */ document.getElementById("agreeMsg").innerHTML = ""; } }); //检查是否填写验证码 var fields6 = $('#verify'); fields6.each(function () { if (($('#verify').val() == null || $('#verify').val() == "")) { $(this).addClass('error'); $(this).effect("shake", {times: 3}, 50); document.getElementById("verifyMsg").innerHTML = "验证码不能为空 "; error++; } else { //$(this).addClass('valid'); document.getElementById("verifyMsg").innerHTML = ""; } var verify = document.getElementById("verify").value;// 获取输入框信息 field_values.verify = verify; }); //检查是否填写email或者qq var fields5 = $('#email'); fields5.each(function () { if (($('#email').val() == null || $('#email').val() == "") && ($('#qq').val() == null || $('#qq').val() == "")) { document.getElementById("emailMsg").innerHTML = "“email”和“网上社交工具及注册号”请至少填写一种"; $(this).addClass('error'); $(this).effect("shake", {times: 3}, 50); error++; } else { if ($('#email').val() != null && $('#email').val() != "") { var reMail = /^(?:[a-zA-Z0-9]+[_\-\+\.]?)*[a-zA-Z0-9]+@(?:([a-zA-Z0-9]+[_\-]?)*[a-zA-Z0-9]+\.)+([a-zA-Z]{2,})+$/; var s = new RegExp(reMail); if (!s.test($(this).val())) { document.getElementById("emailMsg").innerHTML = "邮箱不正确!"; error++; } } if ($('#qq').val() != null && $('#qq').val() != "") { document.getElementById("emailMsg").innerHTML = ""; } } //email是否已经注册 var email = document.getElementById("email").value;// 获取输入框信息 field_values.email = email; //qq 是否已经注册 var qq = document.getElementById("qq").value;// 获取输入框信息 field_values.qq = qq; }); if (error == 0) { //提交菜单 var params = field_values; var url = "/func/merchant/registerNewMerchantInfo"; var ref = this; ProxyQ.query( 'POST', url, params, null, function (req) { if(req.re==1){ alert("注册成功!"); ref.props.dispatch(UserActions.loginAction(params.nickName,params.password,null)); } }, function (xhr, status, err) { console.error(this.props.url, status, err.toString()); } ); return true; } else { return false; } }, showTip: function () { var oDiv = document.getElementById("divTip1"); oDiv.style.visibility = "visible"; }, hideTip: function () { var oDiv = document.getElementById("divTip1"); oDiv.style.visibility = "hidden"; }, getInitialState: function () { var data = null; var language = this.props.language; if (language == "Chinese") { data = register[1]; } else { data = register[0]; } return ({ data: data, language: language, }) }, render: function () { var contains = null; if (this.state.data != null && this.state.data != undefined) { var data = this.state.data; contains = <div style={{padding: '70px'}}> <div id="register"> <input type="hidden" id="error" value="${systemPrompt}"/> <div id="formasdf"> <div id="first_step"> {this.state.language == "Chinese" ? <h1><span style={{color: 'black'}}>{data.title1}</span><span>{data.title2}</span> </h1> : <h1>{data.title}</h1> } <input type="hidden" id="merchantType" name="merchantType" value="1"/> <table cellPadding="0" cellSpacing="0" border="0"> <tr> <td className="info" align='right'>{data.type} &nbsp;</td> <td> <select name="userType" id="userType" className="input-text" onChange="justWe()"> <option value="1">{data.typeOpt1}</option> <option value="2">{data.typeOpt2}</option> </select> </td> </tr> <tr> <td className="info" align='right'>{data.nikename} &nbsp;</td> <td> <input type="text" name="nickName" id="nickName" className="input-text"/> <span id="nickNameMsg" className="errorMessage"> </span></td> </tr> <tr> <td className="info" align='right'>{data.email} &nbsp;</td> <td><input type="text" name="email" id="email" className="input-text"/> <span id="emailMsg" className="errorMessage"> </span></td> </tr> {this.state.language == "Chinese" ? <tr> <td className="info" align='right'>网上社交工具及注册号: &nbsp;</td> <td><input type="text" name="qq" id="qq" className="input-text"/> <span id="qqMsg" className="errorMessage"> </span></td> </tr> : null } <tr> <td className="info" align='right'>{data.password} &nbsp;</td> <td><input type="password" name="password" id="password" className="input-text" onMouseOver={this.showTip} onMouseOut={this.hideTip}/> <span id="passwordMsg" className="errorMessage"> </span> <span id="divTip1" style={{visibility: 'hidden'}}>{data.pswprompt}</span> </td> </tr> <tr> <td className="info" align='right'>{data.checkpsw} &nbsp;</td> <td><input type="password" name="cpassword" id="cpassword" className="input-text"/> <span id="cpasswordMsg" className="errorMessage"> </span></td> </tr> <tr> <td className="info" align='right'>{data.verification} &nbsp;</td> <td> <table id="tableVerify"> <tr valign="bottom"> <td><input type="text" name="verify" id="verify" className="input-text"/></td> <td><img id="validateImage" src="/supnuevo/validatecode.jpg"/></td> <td><a href="#" onClick={this.repaintImage} style={{color: '#7e231b'}}>{data.changevcode}</a> </td> <span id="verifyMsg" className="errorMessage"> </span> </tr> </table> </td> </tr> <tr> <td className="info" align='right'></td> <td> <table style={{width: '330px', margin: 'auto'}}> <tr valign="bottom"> <td><input type="checkbox" name="agree" id="agree"/></td> <td className="agree2">{data.agree}</td> <td className="clause"> <Link to={window.App.getAppRoute()+"/agreement"} className="clause2" target="_blank">{data.clause} </Link> </td> <td><span id="agreeMsg" className="errorMessage" style={{margin: '1px'}}> </span></td> </tr> </table> </td> </tr> <tr> <td colSpan="2"> <table style={{width: '85px', margin: 'auto'}}> <tr> <td> <input onClick={this.register} className={data.regBut} type="button" id="submit_first"> </input> <Link to={window.App.getAppRoute() + '/news?register=1'} id="goToOther"></Link> </td> </tr> </table> </td> </tr> </table> </div> <div className="clear"></div> </div> </div> </div> } else { contains = <div> {this.state.language == "Chinese" ? <div> 数据加载出错! </div> : <div> Date load error! </div> } </div> } return contains; }, componentWillMount: function () { $(document).ready(function () { document.body.style.backgroundColor = "#e6e0d0"; }) } }) const mapStateToProps = (state, ownProps) => { const props = { token: state.userInfo.accessToken, name: state.userInfo.loginName, personId:state.userInfo.personId } return props } export default connect(mapStateToProps)(Register);
import React, { useState, useEffect} from "react"; import useKey from '@accessible/use-key' import Link from 'next/link' import { useUser } from '../utils/auth/useUser' import initFirebase from '../utils/auth/initFirebase' import { throttle } from 'throttle-debounce'; import { Character } from '../components' const stc = require('string-to-color'); const setData = async (content) => { try { await initFirebase.database().ref(`realtimeData`).set(content); } catch (error) { console.error("error push ", error); } } const Index = () => { const { user, logout } = useUser() const [positions, setPositions] = useState({}) const setPosition = async (direction) => { // throttle(1000, false, (num) => { let _positions = positions if(!positions[user.id]) { return } let { x, y } = positions[user.id] if(direction == 'ArrowUp') { _positions[user.id].y = y-10 } else if(direction == 'ArrowDown') { _positions[user.id].y = y+10 } else if(direction == 'ArrowLeft') { _positions[user.id].x = x-10 } else if(direction == 'ArrowRight') { _positions[user.id].x = x+10 } console.log('setPosition',_positions) setData(_positions) // }); } if (typeof window === 'undefined') { return false } useKey(window, { // Logs event when the Escape key is pressed ArrowUp: (e) => setPosition(e.code), ArrowDown: (e) => setPosition(e.code), ArrowLeft: (e) => setPosition(e.code), ArrowRight: (e) => setPosition(e.code), Escape: console.log, // Logs "Key was pressed: Enter" to the console when Enter is pressed Enter: (event) => console.log('Key was pressed:', event.key), }) useEffect(() => { let socket if(user) { try { socket = initFirebase.database() .ref(`realtimeData`) .on("value", (snapshot) => { let data = snapshot.val() if(typeof data != 'object' || !data) { data = {} } console.log(data) //check if theres not a last position if(!data[user.id]) { data[user.id] = { x:50, y:50, n:user.displayName, // o:true, c:stc(user.id) } } setPositions(data) setData(data) }); } catch (error) { console.error("error push ", error); } } return () => { if(user) { //set user offline // let _positions = { ...positions[user.id], o:false } // _positions = {[user.id]:_positions} // setData({ ...positions, ..._positions}) } // setData() // unsusbcribe to socket connection when user closes the page initFirebase.database().ref(`realtimeData`).off("value", socket); } },[user]) if (!user) { return ( <> <p>Hi there!</p> <p> You are not signed in.{' '} <Link href={'/auth'}> <a>Sign in</a> </Link> </p> </> ) } // debugger; // console.log("userData",userData); return ( <div className="world" onKeyDown={(e) => { console.log('onKeyDown',e) }} > { Object.keys(positions).map(key => { const char = positions[key] return ( <Character key={key} char={char} /> ) }) } </div> ) } export default Index
//We need socket.io to enable connection with server require(['socket.io/socket.io.js']); var socket = io.connect('localhost:8080'); var salon = false; toastr.options = { "closeButton": false, "debug": false, "newestOnTop": false, "progressBar": true, "positionClass": "toast-top-full-width", "preventDuplicates": false, "onclick": null, "showDuration": "300", "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }; inGameToastOptions = { "closeButton": false, "debug": false, "newestOnTop": false, "progressBar": true, "positionClass": "toast-bottom-full-width", "preventDuplicates": false, "onclick": null, "showDuration": "300", "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }; //palette : http://www.palettable.io/99C2E1-FCF9F0-FEF88E-FFAB60-FFA07A var couleurFin = "black"; var couleurCaseVide = "#99C2E1"; var couleurCaseBateau = "#FCF9F0"; var couleurRate = "#FEF88E"; var couleurTouche = "#FFAB60"; var couleurCoule = "#D45938"; //TOATSR : how to use :------------------------ /* //INFO TOAST toastr.info("title","message"); // Display a warning toast, with no title toastr.warning('My name is Inigo Montoya. You killed my father, prepare to die!'); // Display a success toast, with a title toastr.success('Have fun storming the castle!', 'Miracle Max Says'); // Display an error toast, with a title toastr.error('I do not think that word means what you think it means.', 'Inconceivable!'); // Immediately remove current toasts without using animation toastr.remove(); // Remove current toasts using animation toastr.clear(); */ //END TOASTR TUTO------------------------------ //OUTILS------------------------------------- function switch_page(tohide, togo){ document.getElementById(tohide).style.display = "none"; document.getElementById(togo).style.display = "block"; toastr.clear(); } //MMR------------------------------------- function annuler_recherche(){ socket.emit('cancel_search',{sal_state:salon}); salon = false; switch_page("mmr_search","home"); } function demarrer_mmr(){ switch_page("home","mmr_search"); switch_page("attente","rech"); socket.emit("mmr_search"); socket.on('not_found', function(){ //OUVERTURE D'UN SALON salon = true; switch_page("rech","attente"); socket.removeListener("not_found"); }); socket.on('found', function(){ switch_page("mmr_search", "ready"); menu_pret(); socket.removeListener("not_found"); socket.removeListener("found"); }); } //SALON PRIVE------------------------------------- function annuler_salon_prive(){ //PREVENIR LE SERVEUR DE LA FERMETURE DU SALON PRIVE socket.emit("cancel_private"); switch_page("private_room_waiting","home"); } function demarrer_salon(){ socket.emit('private_init'); socket.on('key_code', function(data){ document.getElementById("key").innerHTML = data["kc"]; console.log(data.kc); switch_page("home","private_room_waiting"); //ATTENTE DE JOUEUR socket.on('found_rival', function(){ switch_page("private_room_waiting","ready"); menu_pret(); socket.removeListener("found_rival"); }); socket.removeListener('key_code'); }); } //RECHERCHE SALON PRIVE------------------------------------- function rejoindre_prive(){ //RECUPERER LES DONNEES DU CHAMPS DE CLE socket.emit("private_search", {'sal_key' : document.getElementById("room_key_input").value}); socket.on("key_response", function(data){ if(data.found){ //PARTIE TROUVEE, FAIRE QUELQUE CHOSE switch_page("home","ready"); menu_pret(); } else{ document.getElementById("room_key_input").value = ""; toastr.error("Clé invalide !","Impossible de rejoindre une partie avec cette clé"); } socket.removeListener("key_response"); }); } //READY------------------------------------- function menu_pret(){ socket.removeListener("player_left"); socket.on("player_left", function(){ console.log("other player left the game"); switch_page("ready","home"); document.getElementById("ready_bt").disabled = false; document.getElementById("other_ready_text").innerHTML = "Adversaire pas encore prêt..."; socket.removeListener("other_cancel"); socket.removeListener("other_ready"); socket.removeListener("player_left"); }); socket.on("other_ready",function(){ document.getElementById("other_ready_text").innerHTML = "Adversaire prêt !"; socket.removeListener("other_ready"); }); socket.on("other_cancel",function(){ document.getElementById("ready_bt").disabled = false; document.getElementById("other_ready_text").innerHTML = "Adversaire pas encore prêt..."; switch_page("ready","home"); socket.removeListener("other_cancel"); toastr.info("L'adversaire a quitté la partie..."); }); } function annuler_pret(){ document.getElementById("ready_bt").disabled = false; document.getElementById("other_ready_text").innerHTML = "Adversaire pas encore prêt..."; socket.emit("cancel_ready"); socket.removeListener("other_ready"); socket.removeListener("other_cancel"); socket.removeListener("go_party"); switch_page("ready","home"); } function declarer_pret(){ document.getElementById("ready_bt").disabled = true; //AFFICHER QUELQUE CHOSE A L'ECRAN DU JOUEUR socket.emit("ready"); //ATTENDRE LA REPONSE DU SERVEUR, si l'autre est pret, go en jeu socket.on("go_party",function(){ document.getElementById("ready_bt").disabled = false; document.getElementById("other_ready_text").innerHTML = "Adversaire pas encore prêt..."; switch_page("ready","ingame"); start_game(); socket.removeListener("go_party"); }); } //INGAME------------------------------------- function explode(x, y) { var particles = 30, // explosion container and its reference to be able to delete it on animation end explosion = $('<div class="explosion"></div>'); // put the explosion container into the body to be able to get it's size $('body').append(explosion); // position the container to be centered on click explosion.css('left', x - explosion.width() / 2); explosion.css('top', y - explosion.height() / 2); for (var i = 0; i < particles; i++) { // positioning x,y of the particle on the circle (little randomized radius) var x = (explosion.width() / 2) + rand(80, 150) * Math.cos(2 * Math.PI * i / rand(particles - 10, particles + 10)), y = (explosion.height() / 2) + rand(80, 150) * Math.sin(2 * Math.PI * i / rand(particles - 10, particles + 10)), color = 252 + ', ' + 101 + ', ' + 26, // randomize the color rgb // particle element creation (could be anything other than div) elm = $('<div class="particle" style="' + 'background-color: rgb(' + color + ') ;' + 'top: ' + y + 'px; ' + 'left: ' + x + 'px"></div>'); if (i == 0) { // no need to add the listener on all generated elements // css3 animation end detection elm.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) { explosion.remove(); // remove this explosion container when animation ended }); } explosion.append(elm); } } // get random number between min and max value function rand(min, max) { return Math.floor(Math.random() * (max + 1)) + min; } function hide_boat_placement(){ document.getElementsByClassName("boats")[0].classList.add("hide_by_default"); document.getElementById("show_bt").classList.remove("hide_by_default"); } function show_boat_placement(){ document.getElementsByClassName("boats")[0].classList.remove("hide_by_default"); document.getElementById("show_bt").classList.add("hide_by_default"); } function start_game(){ createGrid(); socket.on("player_left", function(){ quitter_partie(); socket.removeListener("player_left"); toastr.info("L'adversaire a quitté la partie..."); }); socket.on("boat_placed", function(){ toastr.info("L'adversaire a placé ses bateaux !"); socket.removeListener("boat_placed"); }); } function quitter_partie(){ switch_page("ingame","home"); socket.emit("quit_game"); reset(); } var taille = 10; var isdrag = false; //si un element est selectionner pour drag. var valide = false; //si le bateau peut etre placé a la case. var ajouer; //si le jouer a jouer. var elem; var div; var gamefinie = false; //c'eation de la grille de div function createGrid() { var gridDivj = document.querySelectorAll('.grid-j'); var gridDivb = document.querySelectorAll('.grid-b'); for (var grid = 0; grid < gridDivj.length; grid++) { for (var i = 0; i < taille; i++) { for (var j = 0; j < taille ; j++) { gridj(gridDivj, grid, i, j); gridb(gridDivb, grid, i, j); } } } rotateimg(); } //creation et ajout des attributs pour la grille cote joueur function gridj(gridDiv, pos, i, j){ var el = document.createElement('div'); el.setAttribute('data-x', i); el.setAttribute('data-y', j); el.setAttribute('class', 'grid-cell player'); el.setAttribute('vide', true); el.setAttribute('id', i + "" + j); el.self = this; el.addEventListener('click', eventclic, false); el.addEventListener('mouseover', placementMouseover, false); el.addEventListener('mouseout', placementMouseout, false); gridDiv[pos].appendChild(el); } //creation et ajout des attributs pour la grille cote "bot"/adversaire function gridb(gridDiv, pos, i, j){ var el = document.createElement('div'); el.setAttribute('data-x', i); el.setAttribute('data-y', j); el.setAttribute('class', 'grid-cell bot'); el.setAttribute('vide', true); el.setAttribute('id', i + "b" + j); el.self = this; gridDiv[pos].appendChild(el); } //ajout des listener sur les images de bateaux function rotateimg() { var img = document.querySelectorAll('.boat'); for (var i = 0; i < img.length; i++) { img[i].addEventListener('click', selection, false); } } // action effectuer lors du clic sur une image de bateau function selection(j){ if (isdrag && (elem.target.getAttribute('id') == j.target.getAttribute('id'))){ isdrag = false; elem = null; j.target.classList.remove("boat_selected"); } else { var img = document.querySelectorAll('.boat'); for (var i = 0; i < img.length; i++) { img[i].classList.remove("boat_selected"); } j.target.classList.add("boat_selected"); isdrag = true; elem = j; } } // action effectuer lors du clic sur une div de la grille cote joueur function eventclic(j){ if (isdrag && valide) { if (verouiller(j.target)) { elem.target.classList.add("hide_by_default"); elem = null; isdrag = false; } } if (document.querySelectorAll('.boat').length == 0) { iddrag = false; } } // action quand la souris passe sur une div de la grille joueur function placementMouseover(j){ if (isdrag == true) { div = j; coloriage(j.target, couleurCaseBateau); } } // action quand la souris sort du'une div de la grille function placementMouseout(j){ if (isdrag == true) { div = null; coloriage(j.target, couleurCaseVide); } } //calcul de la position d'une div function point(j, x, y) { return (document.getElementById('' + (parseInt(Math.floor(j.getAttribute('data-x')) + parseInt(Math.floor(x)))) + '' + (parseInt(Math.floor(j.getAttribute('data-y')) + parseInt(Math.floor(y)))))); } //fait la liste des cases correspondant a une div function listecase(j) { var tailleboat = elem.target.getAttribute('taille'); var liste = []; valide = true; if (elem.target.getAttribute('pos') == 'h' && ((-1 <= j.getAttribute('data-y')-tailleboat/2) && (j.getAttribute('data-y') < taille) && (-1 < (parseInt(j.getAttribute('data-y'))+tailleboat/2)) && (parseInt(j.getAttribute('data-y'))+tailleboat/2) < taille)) { for (var i = 0; i < tailleboat; i++) { liste[i] = point(j, 0, tailleboat/2 - i); } } else if (elem.target.getAttribute('pos') == 'v' && ((-1 <= j.getAttribute('data-x')-tailleboat/2) && (j.getAttribute('data-x') < taille) && (-1 < (parseInt(j.getAttribute('data-x'))+tailleboat/2)) && (parseInt(j.getAttribute('data-x'))+tailleboat/2) < taille)) { for (var i = 0; i < tailleboat; i++) { liste[i] = point(j, tailleboat/2 - i, 0); } } if (liste.length==0) { valide = false; } return liste; } //colore une div suivant une couleur passer dans les parametre function coloriage(j, couleur) { if (elem == null) { j.style.backgroundColor = couleur; } else { var liste = listecase(j); if (estVerouiller(liste) == false) { for (var i = 0; i < liste.length; i++) { liste[i].style.backgroundColor = couleur; } } } } //si une liste comprend un element non vide alors elle est verouiller. la fonction renvoi alors true, false sinon function estVerouiller(liste){ var res = false; for (var i = 0; i < liste.length; i++) { if (liste[i].getAttribute('vide') != 'true'){ res = true; } } return res; } //verrouille une case et confirme son verrouillage function verouiller(j) { var res = true; var liste = listecase(j); if (estVerouiller(liste)) { res = false; } else { for (var i = 0; i < liste.length; i++) { coloriage(j, couleurCaseBateau); liste[i].setAttribute('vide', false); liste[i].setAttribute('boat', elem.target.getAttribute('id')); } } return res; } //permet la rotation d'un bateau lors de l'appui sur la touche "r" document.onkeydown = function (e) { e=e || window.event; var code=e.keyCode || e.wihch; if (code == 82 && isdrag == true && div != null) { coloriage(div.target, couleurCaseVide); if (elem.target.getAttribute('pos') == "h"){ elem.target.setAttribute('pos', 'v'); } else { elem.target.setAttribute('pos', 'h'); } coloriage(div.target, couleurCaseBateau); } } // verifi si tout les batteau sont placé pui lance le jeu function jouer(){ var bool = true; var img = document.getElementsByClassName("boat"); for (var el = 0; el < img.length; el++) { if (!img[el].classList.contains("hide_by_default")) { bool = false; } } if(bool == false) { toastr.error("Vous n'avez pas placé tous vos bateaux..."); } else { document.getElementById("gamestate").innerHTML = "Fin de phase de préparation"; supprimg(); socket.on("jouer", function() { debutaction(); }); socket.on("attendre", function() { debutattente(); }) socket.emit("boat_placed"); } } //debut dun tour pour un joueur si la partie n'est pas finie et que c'est a lui de jouer function debutaction() { if (!gamefinie) { document.getElementById("gamestate").innerHTML = "C'est à vous de jouer"; } ajouer = false; initlistener(); } //place le joueur en mode attente si la partie n'est pas finie function debutattente() { removelistener(); if (!gamefinie) { document.getElementById("gamestate").innerHTML = "C'est au tour de l'adversaire"; } socket.on("player_attack", function(data) { socket.emit("result_attack", isVide(data)); socket.removeListener("player_attack"); debutaction(); }); } //retourne l'id des cellules d'un bateau function getboat(j) { var listeb = []; var bateau = j.getAttribute("boat"); var gridDiv = document.querySelectorAll('.player'); for (var grid = 0; grid < gridDiv.length; grid++) { if (gridDiv[grid].getAttribute("boat") == bateau) { listeb.push(gridDiv[grid].getAttribute("data-x") + "b" + gridDiv[grid].getAttribute("data-y")) } } return listeb; } //appelée en fin de partie, animation de destruction du plateau du perdant, et départ sur l'écran de revanche / pret function destroy(cells, ind, max) { coloriage(cells[ind], couleurFin); var rect = cells[ind].getBoundingClientRect(); explode(rect.left + (Math.abs(rect.left - rect.right) / 2), rect.top + (Math.abs(rect.top - rect.bottom) / 2)); if((ind + 1) < max) { setTimeout(destroy, 75, cells, ind+1, max); } else { $("body").effect("shake"); setTimeout(function() { reset(); switch_page("ingame","ready"); toastr.info("Une revanche ?"); menu_pret(); }, 5000); } } //fonction d'attente du joueur. attend les informations d'attaque de l'adversaire et agit en fonction function isVide(j) { var part1 = document.getElementById(j).getAttribute("vide"); var res = [part1]; if (part1 == "false") { part1 = 1; document.getElementById(j).setAttribute('toucher', true); coloriage(document.getElementById(j), couleurTouche); res = [part1]; if (iscouler(document.getElementById(j))) { part1 = 2; var part2 = getboat(document.getElementById(j)); if (isFin()) { toastr.error("Vous avez perdu...", "Dommage !", inGameToastOptions); part1 = 3; var gridDiv = document.querySelectorAll('.bot'); for (var grid = 0; grid < gridDiv.length; grid++) { coloriage(gridDiv[grid], couleurFin); } fingame(".player"); } else { toastr.error("Un de vos bateaux a coulé...", "Attaque ennemie !", inGameToastOptions); } res = [part1, part2]; } else { var rect = document.getElementById(j).getBoundingClientRect(); explode(rect.left + (Math.abs(rect.left - rect.right) / 2), rect.top + (Math.abs(rect.top - rect.bottom) / 2)); toastr.warning("Un de vos bateaux a été touché...", "Attaque ennemie !", inGameToastOptions); } } else { toastr.success("L'ennemi a raté son tir !", "Attaque ennemie !", inGameToastOptions); part1 = 0; res = [part1]; coloriage(document.getElementById(j), couleurRate); } return res; } // dit si la partie est finie ou non function isFin() { var gridDiv = document.querySelectorAll('.player'); var taillecoul = 0; for (var grid = 0; grid < gridDiv.length; grid++) { if (gridDiv[grid].getAttribute("couler") == "true") { taillecoul++; } } if (taillecoul == 17) { return true; } return false; } //verifi si un bateau est couler et le colore si c'est le cas function iscouler(j) { var gridDiv = document.querySelectorAll('.player'); var bateau = j.getAttribute("boat"); var tailletouch = 0; for (var grid = 0; grid < gridDiv.length; grid++) { if (gridDiv[grid].getAttribute("boat") == bateau && gridDiv[grid].getAttribute("toucher") == "true") { tailletouch++; } } if (tailletouch == document.getElementById(bateau).getAttribute("taille")) { for (var grid = 0; grid < gridDiv.length; grid++) { if (gridDiv[grid].getAttribute("boat") == bateau && gridDiv[grid].getAttribute("toucher") == "true") { coloriage(gridDiv[grid], couleurCoule); gridDiv[grid].setAttribute("couler", "true"); tailletouch++; var rect = gridDiv[grid].getBoundingClientRect(); explode(rect.left + (Math.abs(rect.left - rect.right) / 2), rect.top + (Math.abs(rect.top - rect.bottom) / 2)); } } $("body").effect("shake"); return true; } return false; } // fonction d'action du joueur. envoi a l'adversaire un id de div et agit en fonction du retour de celui-ci function fire(j){ var pos = "" + j.target.getAttribute("data-x") + j.target.getAttribute("data-y"); document.getElementById(j.target.getAttribute("data-x") + "b" + j.target.getAttribute("data-y")).setAttribute("toucher", true); socket.emit("player_attack", pos); socket.on("result_attack", function(data) { if (data[0] == 1) { toastr.success("Touché !", "Résultat de votre attaque", inGameToastOptions); coloriage(j.target, couleurTouche); var rect = j.target.getBoundingClientRect(); explode(rect.left + (Math.abs(rect.left - rect.right) / 2), rect.top + (Math.abs(rect.top - rect.bottom) / 2)); } else if (data[0] == 2) { toastr.success("Coulé !", "Résultat de votre attaque", inGameToastOptions); coloriage(j.target, couleurTouche); for (var i = 0; i < data[1].length; i++) { coloriage(document.getElementById(data[1][i]), couleurCoule); document.getElementById(data[1][i]).setAttribute("couler","true"); var rect = document.getElementById(data[1][i]).getBoundingClientRect(); explode(rect.left + (Math.abs(rect.left - rect.right) / 2), rect.top + (Math.abs(rect.top - rect.bottom) / 2)); } $("body").effect("shake"); } else if (data[0] == 3) { toastr.success("Victoire !", "Félicitations !", inGameToastOptions); coloriage(j.target, couleurTouche); for (var i = 0; i < data[1].length; i++) { coloriage(document.getElementById(data[1][i]), couleurCoule); document.getElementById(data[1][i]).setAttribute("couler","true"); } var gridDiv = document.querySelectorAll('.player'); for (var grid = 0; grid < gridDiv.length; grid++) { coloriage(gridDiv[grid], couleurFin); } socket.emit("revenge"); fingame(".bot"); } else { toastr.info("Raté !", "Résultat de votre attaque", inGameToastOptions); coloriage(j.target, couleurRate); } socket.removeListener("result_attack"); debutattente(); }); } // creer les listener sur les div de la grille "bot"/adversaire function initlistener() { if (!gamefinie) { var gridDiv = document.querySelectorAll('.bot'); for (var grid = 0; grid < gridDiv.length; grid++) { if ( gridDiv[grid].getAttribute('toucher') != "true" ) { gridDiv[grid].addEventListener('click', fire, false); } } } } //enleve les listener sur la grille "bot"/adversaire function removelistener() { var gridDiv = document.querySelectorAll('.bot'); for (var grid = 0; grid < gridDiv.length; grid++) { gridDiv[grid].removeEventListener('click', fire, false); } } //cache les images de bateaux et leur enleve les listener function supprimg() { document.getElementById("show_bt").classList.add("hide_by_default"); document.querySelector('.boats').classList.add("hide_by_default"); elem = null; var gridDiv = document.querySelectorAll('.player'); for (var grid = 0; grid < gridDiv.length; grid++) { gridDiv[grid].removeEventListener('click', eventclic, false); gridDiv[grid].removeEventListener('mouseover', placementMouseover, false); gridDiv[grid].removeEventListener('mouseout', placementMouseout, false); } } //fini la partie function fingame(destroy_selector) { if (!gamefinie) { gamefinie = true; removelistener(); document.getElementById("gamestate").innerHTML = "Partie terminée !"; var gridDiv = document.querySelectorAll(destroy_selector); destroy(gridDiv, 0, gridDiv.length); } } // detruit toutes les cellules de la page et les recrée function reset() { gamefinie = false; var gridDiv = document.querySelectorAll('.grid-cell'); for (var grid = 0; grid < gridDiv.length; grid++) { gridDiv[grid].remove(); } document.getElementsByClassName("boats")[0].classList.remove("hide_by_default"); var img = document.getElementsByClassName("boat"); for (var el = 0; el < img.length; el++) { img[el].classList.remove("hide_by_default"); img[el].classList.remove("boat_selected"); } document.getElementById("show_bt").classList.add("hide_by_default"); document.getElementById("gamestate").innerHTML = "Phase de préparation"; socket.removeListener("player_left"); socket.removeListener("boat_placed"); socket.removeListener("player_attack"); socket.removeListener("result_attack"); }
// -- Step 1 const yargs = require('yargs'); const metalsmith = require('metalsmith'); const livereload = require('livereload'); const connect = require('connect'); const static = require('serve-static'); const chokidar = require('chokidar'); const metadata = require('metalsmith-filemetadata'); // --- Step 2 const markdown = require('metalsmith-markdown'); const handlebars = require('handlebars'); const layouts = require('metalsmith-layouts'); // -- Step 2a const partials = require("metalsmith-discover-partials"); // -- Step 3 const assets = require('metalsmith-assets'); // -- Step 4 const sass = require('metalsmith-sass'); // -- Step 5 const collections = require('metalsmith-collections'); const build = (destination, liveReloadPort) => { // Step 1: this is our metalsmith build! metalsmith(__dirname) .source('src') .destination(destination) .use(metadata([{ pattern: '**/*.md', metadata: { liveReloadPort } }])) // --- Step 2: HTML .use(markdown()) // -- Step 5: Collections .use(collections({ blog: { sortBy: 'title' } })) // --- Step 2: HTML .use(partials({ directory: 'src/partials' })) .use(layouts({ directory: 'src/layouts', default: 'layout.hbs', pattern: '**/*.html' })) // -- Step 3: Assets .use(assets({ source: 'src/assets', destination: 'assets' })) // -- Step 4: Styles .use(sass()) .build((err, files) => { console.log(err ?? 'build complete!'); }); }; // --- // Don't worry too much about the code beyond this point, it's just // some helpful tooling to make working on our website a little nicer // this is just a utility for parsing command-line arguments to a node script. const argv = yargs(process.argv.slice(2)) .options({ dev: { type: 'boolean', default: false }, port: { type: 'number', default: 8080 }, 'live-reload-port': { type: 'number', default: 35729 } }) .argv; if (argv.dev) { // if we're in development mode, watch the source directory and re-build // whenever anything changes build('./build', argv['live-reload-port']); chokidar .watch(__dirname + '/src', { ignored: /(^|[\/\\])\../, persistent: true }) .on('change', () => build('./build', argv['live-reload-port'])); // run a 'live reload' server to tell the client to refresh when there // are updates livereload .createServer({ delay: 1000, debug: true, port: argv['live-reload-port'] }) .watch(__dirname + '/build'); // run a static file server of our built website connect() .use(static(__dirname + '/build')) .listen(argv.port); } else { // if we're not in development mode, just build the site so we can publish it build('./dist'); }
import { Bitski, AuthenticationStatus } from 'bitski'; import Web3 from 'web3'; import Game from './Game.js'; import { LoggedInView } from '../views/LoggedIn.js'; import { LoggedOutView } from '../views/LoggedOut.js'; const LOGGED_OUT_SELECTOR = "#signed-out"; const LOGGED_IN_SELECTOR = "#game"; export class Index { constructor() { this.bitski = new Bitski(BITSKI_CLIENT_ID, BITSKI_REDIRECT_URL); this.loggedInView = new LoggedInView(LOGGED_IN_SELECTOR); this.loggedOutView = new LoggedOutView(LOGGED_OUT_SELECTOR, this.bitski, (provider) => { this.startGame(provider); }); } start() { this.checkAuthStatus(); } checkAuthStatus() { if (this.bitski.authStatus !== AuthenticationStatus.NotConnected) { this.startGame(this.bitski.getProvider(BITSKI_PROVIDER_ID)); } else { this.showLogin(); } } showLogin() { this.loggedInView.hide(); this.loggedOutView.show(); } showApp() { this.loggedOutView.hide(); this.loggedInView.show(); } logOut() { this.bitski.signOut().then(() => { this.showLogin(); }).catch((error) => { this.showLogin(); console.error(error); }); } verifyNetwork() { return this.web3.eth.net.getId().then(netId => { if (netId !== EXPECTED_NETWORK_ID) { throw new Error(`Please set your network to ${EXPECTED_NETWORK_NAME}`); } return true; }); } startGame(provider) { this.web3 = new Web3(provider); this.verifyNetwork().then(() => { this.showApp(); this.game = new Game(this, provider); }).catch(error => { console.error(error); alert(error.message); }); } }
let express = require("express") let router = express.Router() let mongoose = require("mongoose") var Essay= require("../models/essay") var mongodbUri = "mongodb+srv://leon:liang369369@wit-donation-cluster-lovf9.mongodb.net/foodhub?retryWrites=true&w=majority" mongoose.connect(mongodbUri,{useNewUrlParser:true}) let db = mongoose.connection db.on("error", function (err) { console.log("Unable to Connect to [ " + db.name + " ]", err) }) db.once("open", function () { console.log("Successfully Connected to [ " + db.name + " ]") }) router.findAll = (req, res) => { // Return a JSON representation of our list res.setHeader("Content-Type", "application/json") Essay.find(function(err, essay) { if (err) res.send(err) res.send(JSON.stringify(essay,null,5)) }) } router.findOne = (req, res) => { res.setHeader("Content-Type", "application/json") Essay.find({ "_id" : req.params.id },function(err,essay) { if (err) res.json({ message: "Essay NOT Found!", errmsg : err } ) else res.send(JSON.stringify(essay,null,5)) }) } router.addEssay = (req, res) => { res.setHeader("Content-Type", "application/json") var essay = new Essay() essay.author = req.body.author essay.content= req.body.content essay.comment=req.body.comment essay.date=new Date() essay.likes=req.body.likes essay.save(function(err) { if (err) res.json({ message: "New essay NOT Added!", errmsg : err } ) else res.json({ message: "Essay Successfully Added!", data: essay }) }) } router.incrementLikes = (req, res) => { Essay.findById(req.params.id, function(err,essay) { if (err) res.json({ message: "Fail to submit!", errmsg : err } ) else { essay.likes += 1 essay.save(function (err) { if (err) res.json({ message: "Fail to submit!", errmsg : err } ) else res.json({ message: "Submit your like Successfully!", data: essay}) }) } }) } router.deleteEssay = (req, res) => { Essay.findByIdAndRemove(req.params.id, function(err) { if (err) res.json({ message: "Essay NOT DELETED!", errmsg : err } ) else res.json({ message: "Essay Successfully Deleted!"}) }) } module.exports = router
$(document).ready(function () { var windowHeight = $(window).height() - 180; var table = $('#example').DataTable({ // "dom": 'Rlfrtip', "ordering": false, "info": false, responsive: true, fixedHeader: true, paging: false, scrollY: windowHeight + 'px', scrollX: '100%', searching: false, // 这三句是到处按钮 "dom": 'T<"toolbar"><"clear">lfrtip', tableTools: { "aButtons": [{ "sExtends": "copy", "sButtonText": "复制" }, { "sExtends": "xls", "sButtonText": "导出" }], "sSwfPath": "../DataTables-1.10.7/extensions/TableTools/swf/copy_csv_xls.swf" } }); new $.fn.dataTable.ColReorder(table); new $.fn.dataTable.FixedColumns(table); $('#hiddenToolbar').removeClass('hide'); })
import React, {useEffect, useMemo, useState} from 'react'; import {Routes, Route} from "react-router-dom"; import './App.css'; import Login from "./pages/Login/Login"; import Registration from "./pages/Registration/Registration"; import Navbar from "./components/Navbar/Navbar"; import Posts from "./pages/Posts/Posts"; import CreatePost from "./CreatePost/CreatePost"; import Post from "./pages/Posts/Post/Post"; import PageNotFound from "./pages/PageNotFound/PageNotFound"; import EditPost from "./pages/EditPost/EditPost"; import {UserContext} from "./pages/UserAuth/UserAuth"; const App = () => { const token = localStorage.getItem('token'); const [tokenData, setTokenData] = useState(token) const [userAuth, setUserAuth] = useState(false) const [userData, setUserData] = useState() useEffect(() => { if (token) { setUserAuth(true) } }) const providerValue = useMemo(() => ( { tokenData, setTokenData, userAuth, setUserAuth, userData, setUserData }), [tokenData, setTokenData, userAuth, setUserAuth, userData, setUserData]) const logout = () => { setUserAuth(false) setTokenData(null) setUserData([]) localStorage.removeItem("token"); } //изменить на протектед роуты return ( <div className='App'> <UserContext.Provider value={providerValue}> <Navbar logout={logout}/> <div className='app-wrapper-content'> <Routes> <Route path="/login" element={<Login/>}/> <Route path="/create" element={<CreatePost/>}/> <Route path="/posts" element={<Posts/>}/> <Route path="/post/:id" element={<Post/>}/> <Route path="/registration" element={<Registration/>}/> <Route path="/:pageName" element={<PageNotFound/>}/> <Route path="/editPost/:id" element={<EditPost/>}/> </Routes> </div> </UserContext.Provider> </div> ); } export default App;
import React, { useState, useEffect} from 'react' import ImageGallery from '../Components/imageGallery/ImageGallery'; import Searchbar from '../Components/searchbar/Searchbar'; import Button from '../Components/button/Button'; import Loader from '../Components/loader/Loader'; import Modal from '../Components/modal/Modal' import getData from '../utils/api' const _INITIAL_STATE_={ images:[], page:0, query:"", maxPages:0, isLoadButton:false, isLoading:false, modal:null, afterScroll:false } const App=()=>{ const [state, setState] = useState(_INITIAL_STATE_) const closeModal=()=>{ setState(state=>({...state, modal:null})) } const handelSubmit=(e)=>{ e.preventDefault() setState(state=>({..._INITIAL_STATE_, query:e.target[1].value.trim().replaceAll(" ","+"),isLoading:true})) } const handelCicks=({target:{dataset:{bigimage:bigImage,alt}}})=>{ setState(state=>({...state, modal:{bigImage,alt}})) } const downImages=async()=>{ if(state.query===""){ setState(state=>({...state, isLoading:false})) return } const PER_PAGE=12 let page=state.page if(state.maxPages===0 || page<state.maxPages){ page=state.page+1 }else{ setState(state=>({...state, isLoading:false,isLoadButton:false})) return } try{ const {data}=await getData(state.query,page,PER_PAGE) let maxPages=0 let images=[] if(data.total!==0) { maxPages=Math.ceil(data.totalHits/PER_PAGE) images=data.hits.map(srcImg=>({ smallImage:srcImg.webformatURL, bigImage:srcImg.largeImageURL, alt:srcImg.tags, id:srcImg.id.toString(), })) } setState(state=>({...state, images:[...state.images,...images],maxPages,page,isLoading:false,isLoadButton:page<maxPages})) }catch(error){ setState(state=>({...state, isLoading:false,isLoadButton:false})) } } useEffect(() => { const scrollUp=()=>{ window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'smooth', }); } if(state.isLoading) downImages() else if(state.afterScroll) { scrollUp() setState(state=>({...state,afterScroll:false})) } }, [state]) const moreImages=()=> setState(state=>({...state,isLoading:true,afterScroll:true})) return ( <div className="App"> {state.modal && <Modal image={state.modal} onClose={closeModal} />} <Searchbar onSubmit={handelSubmit}/> <ImageGallery images={state.images} onClick={handelCicks}/> {state.isLoading && <Loader/>} {state.isLoadButton && <Button onMore={moreImages}/>} </div> ) } export default App
const Webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const webpackConfig = require('./webpack.config'); const devServerOptions = Object.assign({}, webpackConfig.devServer, { stats: { colors: true } }); const server = new WebpackDevServer(Webpack(webpackConfig), devServerOptions); const port = devServerOptions.port || '8080'; server.listen(port, '0.0.0.0', () => { console.log(`Starting server on http://localhost:${port}`); });
export const request = (state, payload, initialState) => { return { ...state, producers: [], isLoadingProducers: true, error: { ...initialState.error }, }; }; export const success = (state, payload, initialState) => { return { ...state, isLoadingProducers: false, producers: payload, error: { ...initialState.error }, }; }; export const failure = (state) => ({ ...state, isLoadingProducers: false, error: { msg: "Ops! Não conseguimos carregar os produtores.", hasError: true, }, });
const filesServices = require("./filesServices"); const uuid = require("uuid"); let users = require("../models/users"); console.log(users); const usersServices = { getAllUsers(){ return filesServices.readFile();; }, getUserByID(id){ const found = users.some(user => user.id === id); if (found){ return users.filter(user=>user.id === id); } }, addUser(body){ const newUser = { name: body.name, gmail:body.gmail, id : uuid.v4() } if( !newUser.name || !newUser.gmail){ throw Error("Mail or gmail not included.") } users.push(newUser); filesServices.writeFile( users); return users; }, updateUser(id, body){ const found = users.some(user => user.id === id); if (found){ const updUser = body; users.forEach(user => { if(user.id === id){ user.name = updUser.name ? updUser.name : user.name; user.gmail = updUser.gmail ? updUser.gmail : user.gmail; } }); filesServices.writeFile(users); return users; }else{ return null; } }, deleteUser(id){ const found = users.some(user => user.id === id); if (found){ users = users.filter(user=>user.id !== id ); filesServices.writeFile( users); return users; }else{ return null; } } } module.exports = usersServices;
OC.L10N.register( "updatenotification", { "Update notifications" : "Paziņojumi par atjauninājumiem", "{version} is available. Get more information on how to update." : "{version} ir pieejams. Uzziniet vairāk kā atjaunināt.", "ownCloud core" : "ownCloud kodols", "Update for %1$s to version %2$s is available." : "Ir pieejams atjauninājums no %1$s uz %2$s ", "A new version is available: %s" : "Pieejama jauna versija: %s", "Open updater" : "Atvērt atjauninātāju", "Your version is up to date." : "Jūsu versija ir atjaunināta", "Checked on %s" : "Pārbaudīts %s" }, "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2);");
import React from "react"; import "./Header.css"; import MenuIcon from "@mui/icons-material/Menu"; import SearchIcon from "@mui/icons-material/Search"; import { Avatar, IconButton } from "@mui/material"; import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown"; import AppsIcon from "@mui/icons-material/Apps"; import NotificationsIcon from "@mui/icons-material/Notifications"; import { useDispatch, useSelector } from "react-redux"; import { logout, selectUser } from "../../features/userSlice"; import { auth } from "../../firebase"; const Header = () => { const user = useSelector(selectUser); const dispatch = useDispatch(); const signOut = () => { dispatch(logout()); auth.signOut(); }; return ( <div className="header"> <div className="header__left"> <IconButton> <MenuIcon /> </IconButton> <img src="https://i.pinimg.com/originals/ae/47/fa/ae47fa9a8fd263aa364018517020552d.png" alt="" className="logo192" /> </div> <div className="header__middle"> <SearchIcon /> <input type="search" placeholder="Search Mail" /> <ArrowDropDownIcon className="header__inputCaret" /> </div> <div className="header__right"> <IconButton> <AppsIcon /> </IconButton> <IconButton> <NotificationsIcon /> </IconButton> <Avatar onClick={signOut} src={user?.photoUrl} className="header__avatar" > {user?.displayName[0].toUpperCase()} </Avatar> </div> </div> ); }; export default Header;
export const formatter = (foreignbook) => { const book = {}; (book._id = foreignbook.id), (book.category = foreignbook.volumeInfo.categories ? foreignbook.volumeInfo.categories[0] : ""), (book.cover = foreignbook.volumeInfo.imageLinks ? foreignbook.volumeInfo.imageLinks.thumbnail : "https://books.google.mn/googlebooks/images/no_cover_thumb.gif"), (book.description = foreignbook.volumeInfo.description), (book.isbn = foreignbook.volumeInfo.industryIdentifiers ? foreignbook.volumeInfo.industryIdentifiers[0].identifier : "ISBN:"), (book.publisher = { cover: "", description: "", name: foreignbook.volumeInfo.authors, }), (book.rating = foreignbook.volumeInfo.averageRating), (book.release_date = foreignbook.volumeInfo.publishedDate), (book.title = foreignbook.volumeInfo.title), (book.comments = []); return book; };
// Numeriai let n1 = 1; // [number] let n2 = 5; let result = n1 + n2; //console.log(result); result = result * 2; //console.log(result); // Strings (Zodziai) let w1 = "Apple"; let w2 = "Banana"; let w3 = "Pie"; let pie1 = w1 + " " + w3; // Apple Pie let pie2 = w2 + " " + w3; // Banana Pie //console.log(pie1); //console.log(pie2);
function applyExtraSetup(sequelize) { const { book, author, directory } = sequelize.models; const { language } = sequelize.models; language.hasOne(book, { foreignKey: { allowNull: false, name: 'l_code' } }) author.belongsToMany(book, { through: 'author_book', foreignKey: 'a_i' }); book.belongsToMany(author, { through: 'author_book', foreignKey: 'b_i' }); directory.hasOne(directory, { foreignKey: { allowNull: true, name: 'p_name', } }) directory.belongsToMany(book, { through: 'directory_book', foreignKey: 'd_n' }); book.belongsToMany(directory, { through: 'directory_book', foreignKey: 'b_i' }); } module.exports = {applyExtraSetup};
import React, {useState, useEffect} from "react"; import API from "../../utils/API"; import MyContext from "../../utils/MyContext"; import TableHeaderData from "../TableHeaderData"; function EmployeeData() { const [developerState, setDeveloperState] = useState({ users: [], headings: [ {name: "First Name"}, {name: "Last Name"}, {name: "Email"}, {name: "Age"}, {name: "Phone"}, {name: "Image"} ] }); useEffect(() => { API.getUsers().then(results => { console.log(results.data.results); setDeveloperState({ ...developerState, users: results.data.results, }); }); }, []); return ( <MyContext.Provider value={developerState}> <div className="table-header-data"> <TableHeaderData/> </div> </MyContext.Provider> ); }; export default EmployeeData;
(function(angular) { 'use strict'; angular.module('<%= appname %>') .constant('<%= _.camelize(name) %>', { errorLogin: 'Bad username or password' }); })(window.angular);
import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api', ajaxError: function(jqXHR) { var error = this._super(jqXHR); var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; if (jqXHR && jqXHR.status === 422) { return new DS.InvalidError(jsonErrors); } else { return new DS.Errors(jsonErrors); } } });
/*----------------------------------------------------------------------------- This template demonstrates how to use an IntentDialog with a LuisRecognizer to add natural language support to a bot. For a complete walkthrough of creating this type of bot see the article at http://docs.botframework.com/builder/node/guides/understanding-natural-language/ -----------------------------------------------------------------------------*/ "use strict"; var request; var userid; var score; var builder = require("botbuilder"); var botbuilder_azure = require("botbuilder-azure"); var analyticsService = require('./models/text-analytics'); var path = require('path'); var sql = require('mssql'); var config = { user: 'gmi', // update me password: 'sa@12345', // update me server: 'gmidatabase.database.windows.net', database: 'GMI', options: { encrypt : true //update me } } sql.connect(config, function (err) { if (err != null) {session.send(" err " + err)} ; request = new sql.Request(); }); var useEmulator = (process.env.NODE_ENV == 'development'); var connector = useEmulator ? new builder.ChatConnector() : new botbuilder_azure.BotServiceConnector({ appId: process.env['MicrosoftAppId'], appPassword: process.env['MicrosoftAppPassword'], stateEndpoint: process.env['BotStateEndpoint'], openIdMetadata: process.env['BotOpenIdMetadata'] }); var bot = new builder.UniversalBot(connector); //bot.localePath(path.join(__dirname, './locale')); var count = 1; var candscore = 30; var candiatescore = 0; // Make sure you add code to validate these fields var luisAppId = process.env.LuisAppId; var luisAPIKey = process.env.LuisAPIKey; var luisAPIHostName = process.env.LuisAPIHostName || 'westus.api.cognitive.microsoft.com'; const LuisModelUrl = 'https://' + luisAPIHostName + '/luis/v1/application?id=' + luisAppId + '&subscription-key=' + luisAPIKey; // Main dialog with LUIS var recognizer = new builder.LuisRecognizer(LuisModelUrl); var intents = new builder.IntentDialog({ recognizers: [recognizer] }) /* .matches('<yourIntent>')... See details at http://docs.botframework.com/builder/node/guides/understanding-natural-language/ */ .matches('aboutcomp', (session, args) => { saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); session.send('The company is Global Mantra Innovations (GMI), located in Siruseri SIPCOT IT Park, Chennai. Our mantra is "Free Thinking". GMI is a full life cycle Research and Innovation company focused on providing repeatable, reusable and scalable widgets.'); }) .matches('address', (session, args) => { saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); session.send('Global Mantra Innovations, the company, is located in Siruseri SIPCOT IT Park, Chennai.'); }) .matches('affir', (session, args) => { saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); session.send('Are there anything else you wish to know about the company? If yes, please continue. If not, type "menu"'); }) .matches('compcult', (session, args) => { session.send('Fun at work! Mantraians, our employees, are high-spirited people, who thirst for innovation and love to work as a team. Sky is the limit and we are driven by the phrase "Why not?".This is our culture.'); if (count < 5) { candscore += 10 score = 10; count += 1 }; saveusersubinput(session,'1','1','AboutGMI',session.message.text,score); }) .matches('compdom', (session, args) => { session.send('Our primary domain is Healthcare. We also do a number of US federal defense projects.'); if (count < 5) { candscore += 10 score = 10; count += 1 }; saveusersubinput(session,'1','1','AboutGMI',session.message.text,score); }) .matches('compgoal', (session, args) => { session.send('We are a products company! We aspire to develop a handful of globally competing tech products in cutting edge domains such as artificial intelligence, augmented reality, and block-chain technologies, by 2020.'); if (count < 5) { candscore += 10 score = 10; count += 1 }; saveusersubinput(session,'1','1','AboutGMI',session.message.text,score); }) .matches('compprod', (session, args) => { session.send('Some of the products developed in our very own "Widget Factory" serve in fast-tracking the code, as security wrapper, and for transformation of data into various formats.'); if (count < 5) { candscore += 10 score = 10; count += 1 }; saveusersubinput(session,'1','1','AboutGMI',session.message.text,score); }) .matches('compprof', (session, args) => { session.send('We are a profitable company. Our revenue in 2016 was USD 150 million.'); saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); }) .matches('compsize', (session, args) => { saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); session.send('At present, we employ about 50 professionals. We are looking to expand to about 150 techies by the end of 2017.'); }) .matches('compvalue', (session, args) => { session.send('Free thinking and Innovation are our core values. Our Dream is “Super BIG” Innovations and be “the industry standard”.'); if (count < 5) { candscore += 10; count += 1; score = 10; }; saveusersubinput(session,'1','1','AboutGMI',session.message.text,score); }) .matches('compweb', (session, args) => { saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); session.send('The company website is http://globalmantrai.com/index.html.'); }) .matches('currtech', (session, args) => { session.send('We are working in cutting-edge technologies like Artificial Intelligence, Blockchain, Virtual Reality, Data Science, etc.'); if (count < 5) { candscore += 10 score =10; count += 1 }; saveusersubinput(session,'1','1','AboutGMI',session.message.text,score); }) .matches('dresscode', (session, args) => { session.send('We do not have any strict dress codes. Casual office dressing is encouraged.'); saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); }) .matches('founder', (session, args) => { session.send('Ravi Kunduru is the founder and CEO of Global Mantra Innovations.'); saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); }) .matches('geog', (session, args) => { saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); session.send('Our headquarters is in Columbus, Ohio. We are also present in Maryland, Virginia, Iowa, New Mexico, Louisiana and Chennai. Soon we’ll extend to Singapore and Ireland.'); }) .matches('headop', (session, args) => { saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); session.send('Naresh Nagarajan is the SVP and head of operations of Global Mantra Innovations.'); }) .matches('howapp', (session, args) => { saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); session.send('For current openings and the procedure to apply, please visit http://globalmantrai.com/Careers.html.'); }) .matches('idealemp', (session, args) => { session.send('An ideal employee is one who is brave to think "Super BIG" and open to face challenges.'); if (count < 5) { candscore += 10; score = 10; count += 1; }; saveusersubinput(session,'1','1','AboutGMI',session.message.text,score); }) .matches('pubpriv', (session, args) => { session.send('Global Mantra Innovations is a privately-owned company!'); saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); }) .matches('services', (session, args) => { saveusersubinput(session,'1','1','AboutGMI',session.message.text,'0'); session.send('We do services. Center for Medicare and Medicaid is one of the clients for whom we do services.'); }) .matches('scope', (session, args) => { session.send('We have a vibrant atmosphere and we provide a great landscape for you to be creative and explore cutting-edge technologies.'); if (count < 5) { candscore += 10; score = 10; count += 1; }; saveusersubinput(session,'1','1','AboutGMI',session.message.text,score); }) .matches('whenfound', (session, args) => { session.send('The company was founded in 1996 in Chennai.'); candscore += 5; score = 5; saveusersubinput(session,'1','1','AboutGMI',session.message.text,score); }) .matches('worktime', (session, args) => { session.send('We encourage Mantraians to be present between 10 am to 7 pm, when majority of team discussions and meetings take place. Work-from-home is allowed when the need arises.'); if (count < 5) { candscore -= 10 count += 1; score = -10; }; saveusersubinput(session,'1','1','AboutGMI',session.message.text,score); }) .onDefault((session) => { session.send('Sorry, I did not understand \'%s\'.', session.message.text); }); //bot.dialog('/', intents); //========================================================= // Bots Global Actions //========================================================= bot.endConversationAction('goodbye', 'Goodbye :)', { matches: /^goodbye/i }); bot.beginDialogAction('help', '/help', { matches: /^help/i }); //========================================================= // Bots Dialogs //========================================================= bot.dialog('/', [ function (session) { // Send a greeting and show help. var card = new builder.HeroCard(session) .title("Global Mantra Innovations") .text("Free Thinking for Global Innovations") .images([ builder.CardImage.create(session, "http://globalmantrai.com/assets/img/images/logo_new.png") ]); var msg = new builder.Message(session).attachments([card]); session.send(msg); session.send("Hi... I am the GMI_Bot. Thanks for installing me. "); request = new sql.Request(); request.query("Select Max(UserID) as UserID from SalesLT.Log") .then(function (recordSet) { userid = recordSet.recordsets[0][0].UserID + 1; }).catch(function (err) { session.send("Insert err " + err); }); session.beginDialog('/menu'); }, // function (session, results) { // // Display menu // session.beginDialog('/menu'); // }, function (session, results) { // Always say goodbye session.send("Ok... See you later!"); } ]); bot.dialog('/menu', [ function (session) { var style = builder.ListStyle["button"]; builder.Prompts.choice(session, "When you are ready to play, choose one of the options below:", "About GMI|About You|Clickn Play|(quit)", { listStyle: style }); }, function (session, results) { saveuserinput(session,results.response,results.response.entity); if (results.response && results.response.entity != '(quit)') { // Launch demo dialog // session.send("The results '%s'", JSON.stringify(results.response.entity)); session.beginDialog('/' + results.response.entity); } else { // Exit the menu session.endDialog(); } }, function (session, results) { // The menu runs a loop until the user chooses to (quit). session.replaceDialog('/menu'); } ]).reloadAction('reloadMenu', null, { matches: /^menu|show menu/i }); function saveuserinput(session,result,resultentity){ switch(resultentity) { case "About GMI": insertuserdata(session,'1',resultentity); break; case "About You": insertuserdata(session,'2',resultentity); break; case "Clickn Play": insertuserdata(session,'3',resultentity); break; } } function saveusersubinput(session,InputID,SubInput,Input,SubInputvalue,candscore){ request = new sql.Request(); request.query("Insert into [SalesLT].[Log] (InputID,Input,SubInput,SubInputvalue,Score,UserID) values ('"+ parseInt(InputID) +"','"+Input+"','"+ parseInt(SubInput) +"','"+SubInputvalue+"','"+parseFloat(candscore)+"','"+parseInt(userid)+"')") .then(function () { }).catch(function (err) { session.send("Insert err " + err); }); } function insertuserdata(session,InputID,Input){ request = new sql.Request(); request.query("Insert into [SalesLT].[Log] (InputID,Input,SubInput,SubInputvalue,UserID) values ('"+ parseInt(InputID) +"','"+Input+"',0,'','"+parseInt(userid)+"')") .then(function () { }).catch(function (err) { session.send("Insert err " + err); }); } bot.dialog('/help', [ function (session) { session.endDialog("Global commands that are available anytime:\n\n* menu - Exits a play session and returns to the menu.\n* goodbye - End this conversation.\n* help - Displays these commands."); } ]); bot.dialog('/About\ GMI', [ function (session) { session.send("Feel free to ask questions about the company! When you are done with questions, type 'menu' to go to the main menu."); session.beginDialog('/intt'); } // function (session, results) { // // Display menu // session.send("You entered '%s'", results.response); // } ]); bot.dialog('/intt', intents); // bot.dialog('/About_GMI/intt', intents, [ // function (session, results) { // .matches('compsize', (session, args) => { // session.send('At present, the company size is about 50 employees. We are looking to expand to about 150 techies by the end of 2017.'); // }) // .onDefault((session) => { // session.send('Sorry, I did not understand \'%s\'.', session.message.text); // }); // } // ]); bot.dialog('/About\ You', [ function (session) { session.send("Okay, let's chat!"); builder.Prompts.text(session, "Could you please tell me about yourself in two sentences?"); }, function (session, results) { analyticsService.getScore(results.response).then(score => { saveusersubinput(session,'2','1','About_You',results.response,score); //session.send("Your score is %s", score); }) .catch((error) => { console.error(error); next(); }); builder.Prompts.text(session, "Thanks! Could you define success?"); }, function (session, results) { session.send("Got it!"); var style = builder.ListStyle["button"]; saveusersubinput(session,'2','2','About You',results.response,'0'); builder.Prompts.choice(session, "Who is the most inspirational personality to you among these 4?", "Narayana Murthi|Steve Jobs|Bill Gates|Elon Musk", { listStyle: style }); }, function (session, results) { if (results.response.entity === 'Elon Musk') { candscore += 20; score = 20; } else if (results.response.entity === 'Narayana Murthi') { candscore += 15; score = 15; } else { candscore += 10; score = 10; } saveusersubinput(session,'2','3','About You',results.response.entity,score); builder.Prompts.text(session, "What is the single quality in " + results.response.entity + " that inspires you the most?"); }, function (session, results) { var style = builder.ListStyle["button"]; session.send("Ok! noted! '%s'", results.response); saveusersubinput(session,'2','4','About You',results.response,'0'); builder.Prompts.choice(session, "How comfortable would you be to work in an R&I environment?", "Very comfortable|Okay|Not comfortable", { listStyle: style }); }, function (session, results) { if (results.response.entity === 'Very comfortable') { candscore += 20; score = 20; } else if (results.response.entity === 'Okay') { candscore += 5; score = 5; } else { candscore -= 10; score = -10; } saveusersubinput(session,'2','4','About You',results.response.entity,score); var style = builder.ListStyle["button"]; // session.send("Ok! noted! '%s'", results.response); builder.Prompts.choice(session, "If the job is offered, will you be willing to relocate closer to Siruseri?", "Yes|No", { listStyle: style }); }, function (session, results) { if (results.response.entity === 'Yes') { candscore += 20; score = 20; } else { candscore -= 20; score = -20; } saveusersubinput(session,'2','5','About\ You',results.response.entity,score); if (candscore > 50) { session.send("Based on our conversation, we assess a fit. Our HR representative will contact you to schedule for the next round of interview.", candscore); } else { session.send("Our HR team will review and let you know of their decision.") } }, function (session, results) { // session.send("You said:", JSON.stringify(LuiModelUrl + results.response)); session.send("Thanks for the resonses! Type 'menu' to go to the main menu."); } ]); bot.dialog('/Clickn_Play', [ function (session) { var style = builder.ListStyle["button"]; session.send("Let's Play!"); builder.Prompts.choice(session, "Who is the most inspirational personality to you among these 4?", "Narayana Murthi|Steve Jobs|Bill Gates|Elon Musk", { listStyle: style }); }, function (session, results) { if (results.response.entity === 'Elon Musk') { candscore += 20; } else if (results.response.entity === 'Narayana Murthi') { candscore += 15; } else { candscore += 10; } builder.Prompts.text(session, "What is the single quality in " + results.response.entity + " that inspires you the most?"); }, function (session, results) { var style = builder.ListStyle["button"]; session.send("Ok! noted! '%s'", results.response); builder.Prompts.choice(session, "How comfortable would you be to work in an R&I environment?", "Very comfortable|Okay|Not comfortable", { listStyle: style }); }, function (session, results) { if (results.response.entity === 'Very comfortable') { candscore += 20; } else if (results.response.entity === 'Okay') { candscore += 5; } else { candscore -= 10 } var style = builder.ListStyle["button"]; // session.send("Ok! noted! '%s'", results.response); builder.Prompts.choice(session, "If the job is offered, will you be willing to relocate closer to Siruseri?", "Yes|No", { listStyle: style }); }, function (session, results) { if (results.response.entity === 'Yes') { candscore += 20; } else { candscore -= 20; } session.send("Thanks for your responses."); if (candscore > 50) { session.send("Based on our conversation, we assess a fit (%s/100). Our HR representative will contact you to schedule for the next round of interview.", candscore); } else { session.send("We do not see a fit here. Our HR team will review and let you know of their decision.") } } ]); if (useEmulator) { var restify = require('restify'); var server = restify.createServer(); server.listen(3978, function() { console.log('test bot endpont at http://localhost:3978/api/messages'); }); server.post('/api/messages', connector.listen()); } else { module.exports = { default: connector.listen() } }
/** * @Author: cyzeng * @DateTime: 2017-06-16 22:07:55 * @Description: main.js */ // 引入相关依赖 import Vue from 'vue'; import VueRouter from 'vue-router'; import routes from '@Src/routers'; import App from '@Src/App'; Vue.use(VueRouter); const router = new VueRouter({ routes }); const app = new Vue({ el: '#app', router, components:{ App: App }, template: '<App/>', });
import React, { Fragment } from "react"; import "../../App.css"; import classesCont from "./Contacts.module.css"; import classesAbout from "../AboutPage/About.module.css"; import Container from "@material-ui/core/Container"; import SidebarMenu from "../AboutPage/SidebarMenu"; import Consulting from "../Consulting/Consulting"; import Footer from "../Footer/Footer"; import Typography from '@material-ui/core/Typography'; const ContactsPage = () => { return ( <Fragment> <section className={classesAbout.sectionAbout}> <Container> <div className={classesAbout.layoutAbout}> <div className={classesAbout.layoutItem}> <div className={classesAbout.sidebar}> <SidebarMenu /> </div> </div> <div className={classesAbout.layoutItem}> <div className="headingSecondary"> <Typography variant="h2"> Контакты </Typography> </div> <div className={classesCont.contacts}> <p className={classesCont.title}>Отдел продаж:</p> <p>+380(50)302-55-22</p> <p>+380(57)717-61-17</p> <p>+380(57)717-50-27</p> </div> <div className={classesCont.contacts}> <p className={classesCont.title}>Бухгалтерия:</p> <p>+380(57)717-50-27</p> </div> <div className={classesCont.contacts}> <p className={classesCont.title}>e-mail: </p> <div className={classesCont.email}> <a href="#">sales@tara.kh.ua </a> <p>&nbsp;- отдел продаж</p> </div> </div> <p className={classesAbout.description}> График работы: Пн. – Пт. с 9:00 до 17:00 </p> <p className={classesAbout.description}> Харьков, проспект Московский, д. 257Б </p> <div className={classesCont.map}> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2568.0359782612354!2d36.42624011571278!3d49.93566617940772!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x41270c1544ee7823%3A0xdf8e0cc0a742b458!2sMoskovs&#39;kyi%20Ave%2C%202576%2C%20Kharkiv%2C%20Kharkivs&#39;ka%20oblast%2C%2061000!5e0!3m2!1sen!2sua!4v1590509422462!5m2!1sen!2sua" width="100%" height="100%" frameborder="0" style={{ border: 0 }} allowfullscreen="" aria-hidden="false" tabindex="0" ></iframe> </div> </div> </div> </Container> </section> <Consulting /> <Footer /> </Fragment> ); }; export default ContactsPage;
import API from 'src/util/api'; import fileSaver from 'file-saver'; export async function twigToDoc(moduleID, options = {}) { const { filename = 'report.html' } = options; const module = API.getModule(moduleID); let div = module.domContent[0]; let canvases = div.querySelectorAll('canvas'); // clone the original dom, we also need to copy the canvas let domCopy = div.firstChild.cloneNode(true); let canvasesCopy = domCopy.querySelectorAll('canvas'); for (let i = 0; i < canvases.length; i++) { const png = canvases[i].toDataURL('image/png'); canvasesCopy[i].parentElement.innerHTML = '<img src="' + png + '" />'; } let svgs = div.querySelectorAll('svg'); let svgsCopy = domCopy.querySelectorAll('svg'); const promises = []; for (let i = 0; i < svgs.length; i++) { const svgDOM = svgs[i]; const svgDOMCopy = svgsCopy[i]; const width = svgDOM.clientWidth; const height = svgDOM.clientHeight; const svgString = svgDOM.outerHTML; const canvas = document.createElement('canvas'); canvas.setAttribute('width', width); canvas.setAttribute('height', height); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'white'; ctx.fillRect(0, 0, canvas.width, canvas.height); const image = new Image(); const svg = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' }); const url = URL.createObjectURL(svg); const promise = new Promise((resolve, reject) => { image.onload = () => { ctx.drawImage(image, 0, 0); const png = canvas.toDataURL('image/png'); const img = document.createElement('img'); img.src = png; svgDOMCopy.replaceWith(img); URL.revokeObjectURL(url); resolve(); }; }); promises.push(promise); image.src = url; } await Promise.all(promises); const blob = new Blob(['<html>' + domCopy.innerHTML + '</html>'], { type: 'text/html' }); fileSaver(blob, filename); }
import { Link } from 'react-router-dom'; function Nav(props) { if (props.loggedIn) { return ( <nav> <Link to="/"> <h2>Home</h2> </Link> <Link to="/map"> <h2>My Map</h2> </Link> <Link to="/profile"> <h2>My Profile</h2> </Link> <button onClick={props.logOut}>Logout {props.name}</button> </nav> ) } else { return ( <nav> <Link to="/"> <h2>Home</h2> </Link> <Link to="/register"> <h2>Sign up</h2> </Link> <Link to="/login"> <h2>Login</h2> </Link> </nav> ) } } export default Nav;
//TODO add comment support //NMLElement window.NMLElement = function(doc,name,space){ if(!this instanceof NMLElement){ return new NMLElement(doc,name,space); }; this.tag = {name:name,space:space}; this.children = []; this.ownerDocument = doc; this.parent = null; this.nthChild = null; this.getNamespace = function(){ return doc.namespaces[this.tag.space] || '/nml'; }; this.appendChild = function(node){ if(!node instanceof NMLElement){ throw Error("Argument 1 does not implement NMLElement"); } node.parent = this; node.nthChild = this.children.length; this.children.push(node); doc.trigObserver('add',{ target: node, parent: this }); }; this.remove = function(){ doc.trigObserver('rm',{ target: this, parent: this.parent }); this.parent.children[this.nthChild] = null; this.parent = null; }; }; //NMLDocument window.NMLDocument = function(){ this.failonerr = false; this.namespaces = { 'html': "http://www.w3.org/1999/xhtml" }; this.sandbox = []; this.children = []; this.createElement = function(name,space){ return new NMLElement(this,name,space); }; this.appendChild = function(node){ if(!node instanceof NMLElement){ throw Error("Argument 1 does not implement Node"); } node.parent = this; node.nthChild = this.children.length; this.children.push(node); this.trigObserver('add',{ target: node, parent: this }); }; this.observe = function(what,listener){ if(!what in this.observers){throw Error('No such event');} this.observers[what].push(listener); }; this.unobserve = function(what,listener){ if(!what in this.observers){throw Error('No such event');} var arr = this.observers[what]; var i = arr.indexOf(listener); ( i > -1 )&&( arr.slice(i,i+1) ); }; this.trigObserver = function(what,props){ if(!what in this.observers){throw Error('No such event');} var self = this; setTimeout(function(){ var arr = self.observers[what]; var i=-1, l=arr.length; while(++i<l){ arr[i](props); } },0); }; this.observers = { 'add':[], 'rm':[], 'attr':[] }; this.parse = function(str,async){ if(async){ setTimeout(this.parse,0); return; } //Preparation str = str.trim(); var i = {n:0};//The major cursor var x = 0; //The minor cursor var line = 1; var col = 1; var run = true; var structure = [this]; var node; i.add = function(n){//i++ with line counter if(!n){n=1;} while(n-->0&&str.length>i.n){ if(str.length<=i.n&&this.failonerr){throw {line:line,collumn:col,message:"Unexpected end of the document."};} if(str[i.n]=="\n"){line++;col=1;} i.n++;col++; } } var skipEmpty = function(){//Skip to the first non-empty character while(" \n\t".indexOf(str[i.n])+1&&str.length>i.n) {i.add();} }; var getAttrs = function(){//Parse tag's attributes skipEmpty(); var attrs = {}; var attr = {};//Buffer var x = i.n; //Redefine the minor cursor while(str[i.n]!=">"&&str.substr(i.n,2)!="/>"&&str.length>i.n){//Until the end of the tag x=i.n; while(!(" =>".indexOf(str[x])+1)){x++;} attr.name=str.substring(i.n,x);//Save attribute name i.add(x-i.n); skipEmpty(); x=i.n; if(str[x]=="="){ //String attribute i.add(); skipEmpty(); x=i.n; if(str[x]=="'"){ //For single quotes i.add();x++;//Skip the quote while(str[x]!="'"&&str.length>x){x++;} attr.value=str.substring(i.n,x);//Save attribute value x++;//Skip the quoto i.add(x-i.n);//Move i to x }else if(str[x]=='"'){ //For double quotes i.add();x++;//Skip the quote while(str[x]!='"'&&str.length>x){x++;} attr.value=str.substring(i.n,x);//Save attribute value x++;//Skip the quote i.add(x-i.n);//Move i to x }else{ //For value without quotes while(!(" \n\t>".indexOf(str[x])+1)&&str.length>x){x++;} attr.value=str.substring(i.n,x);//Save attribute value i.add(x-i.n);//Move i to x } }else{ //Boolean attribute attr.value=true;//Save attribute value } attrs[attr.name]=attr.value;//Write to the array attr = {};//Clean buffer skipEmpty(); } skipEmpty(); return attrs; }; //Parsing while(run){ if(str[i.n]=="<"){ //If the document begins with "<" run = false; //Do not repeat the cycle i.add(); x = i.n; while(!(" \n\t/>".indexOf(str[x])+1)&&str.length>x) {x++;} if(str.substring(i.n,x).toLowerCase()=="!doctype"){ //If the first tag is doctype i.add(x-i.n+1); while(str[i.n]!=">"){ //Get the namespaces skipEmpty(); x=i.n; while(!(" \n\t,>".indexOf(str[x])+1)){x++;} if( str.substring(i.n,x) && !this.namespaces[str.substring(i.n,x)] ){ this.namespaces[str.substring(i.n,x)]='/nml/'+str.substring(i.n,x); } i.add(x-i.n);//Move i to x } }else{ i.add(); if(str.substring(i.n,x).indexOf(":")+1){//With namespace node = this.createElement( str.substring(i.n,x).split(":")[0], str.substring(i.n,x).split(":")[1] ); }else{//Without namespace node = this.createElement(str.substring(i.n,x)); } this.appendChild(node); i.add(x-i.n);//Move i to x this.children[0].attrs = getAttrs(); if(str[i.n]){ if(str.substring(i.n,i.n+2)=="/>"){ return; }else{ i.add(); } }else if(this.failonerr){ throw {line:line,collumn:col,message:"Unexpected end of the document."}; }else{ return; } } i.add(); //BEGIN Main cycle while(str.length>i.n){ //Add text node while(str[x]!="<"&&str.length>x){x++;} if(x!=i.n){ structure.lenght-1 && //if active node != document structure[structure.length-1] .children.push( str.substring(i.n,x) ); this.trigObserver('add',{ target: str.substring(i.n,x), parent: structure[structure.length-1] }); i.add(x-i.n); } if(str.length<=i.n){ if(this.failonerr){ throw {line:line,collumn:col,message:"Unexpected end of the document, document does not end with the ending tag of the root."}; }else{ return; } } //Parse tag i.add(); if(str[i.n]=="/"){//Ending tag i.add(); x = i.n; while((!(">".indexOf(str[x])+1))&&str.length>x) {x++;} node = {}; node.tag = {}; if(str.substring(i.n,x).indexOf(":")+1){//With namespace node.tag.name = str.substring(i.n,x).split(":")[1]; node.tag.space = str.substring(i.n,x).split(":")[0]; }else{//Without namespace node.tag.name = str.substring(i.n,x); } i.add(x-i.n); if( structure[structure.length-1].tag.name == node.tag.name && structure[structure.length-1].tag.space == node.tag.space ){ structure.length--; }else{ //begin TODO if(this.failonerr){ throw {line:line,collumn:col,message:"Bazinga!"}; }else{ return; } //end TODO } skipEmpty(); if(str[i.n]==">"){ i.add(); }else{ if(this.failonerr){ throw {line:line,collumn:col,message:"Unknown error"}; } } }else{ x = i.n; while((!(" \n\t/>".indexOf(str[x])+1))&&str.length>x) {x++;} if(str.substring(i.n,x).indexOf(":")+1){//With namespace node = this.createElement( str.substring(i.n,x).split(":")[1], str.substring(i.n,x).split(":")[0] ); }else{//Without namespace node = this.createElement(str.substring(i.n,x)); } structure[structure.length-1].children[structure[structure.length-1].children.length] = node; skipEmpty(); //Parse attributes i.add(x-i.n);//Move i to x node.attrs = getAttrs(); structure[structure.length-1].appendChild(node); //End the tag if(str.substr(i.n,2)=="/>"){ i.add(2); }else if(str[i.n]){ if(str[i.n]==">"){ structure.push(node); i.add(); }else if(this.failonerr){ throw {line:line,collumn:col,message:"Unknown error"}; } }else{ if(!structure.length){ return; }else{ if(this.failonerr){ throw {line:line,collumn:col,message:"Unexpected end of the document"}; }else{ return; } } } } } //END Main cycle }else{ //If the document begins with an invalid character if(this.failonerr){ throw {line:line,collumn:col,message:"Expected '<' at the beginning of the document."}; } while(str[x]!="<"&&str.length>x){x++;}//Get the position of a)the "<" char or b)the end of the document this.children[0].children[this.children[0].children.length] = str.substring(i.n,x-i.n);//Insert the text into root element i.add(x-i.n);//Move i to x if(str.length==x){ run = false; //If x is the end of the document, do not repeat the cycle } } } var q = 0; while(this.parse.events.length>q){ this.parse.events[q++](); } this.events = []; }; this.parse.events = []; this.parse.on = function(){ //TODO }; this.parse.addEventListener = this.parse.on; this.parse.rmon = function(){ //TODO }; this.parse.removeEventListener = this.parse.rmon; this.toDOM = function(doc){ var ns = "/nml/"+this.children[0].getNamespace(); var doc = (new Document()).implementation.createDocument( ns, //Namespace identifier this.children[0].tag.name, //Set root element's tag name (new Document()).implementation.createDocumentType( this.namespaces[0], //Add a simple doctype "", //No DTD, the same way as in HTML5 "" ) ); //BEGIN Main cycle var f = function(f,e,d,x){ var node; if(typeof e == "string"){ node = d.createTextNode(e); x.appendChild(node); }else{ if(e.tag.space){ if(e.tag.space = 'html'){ node = d.createElementNS(this.htmlns,e.tag.name); }else{ node = d.createElementNS("/nml/"+e.tag.space,e.tag.name); } }else{ node = d.createElementNS('/nml',e.tag.name); } var i = 0; for(attr in e.attrs){ node.setAttribute(attr,e.attrs[attr]); } x.appendChild(node); var i = 0; while(e.children.length>i){ f(f,e.children[i],d,node); i++; } } } var i = 0; while(this.children[0].children.length>i){ f(f,this.children[0].children[i],doc,doc.lastChild); i++; } //END Main cycle return doc; }; this.toDOM.events = []; this.toDOM.on = function(){ //TODO }; this.toDOM.addEventListener = this.toDOM.on; this.toDOM.rmon = function(){ //TODO }; this.toDOM.removeEventListener = this.toDOM.rmon; };
//constant var REMOTE_DOMAIN="http://app-ads.hoangweb.com/"; //"http://localhost:81/";// //data var tab; var external_scripts; var count=0; /** * init */ //send message chrome.runtime.sendMessage({text:"contentScript_enabled_onpage"}); /*load jquery addJs(REMOTE_DOMAIN+"test/ksn-crx/assets/jquery-1.10.2.min.js",function(){ }); //load my js addJs(REMOTE_DOMAIN+"test/ksn-crx/assets/ksn-crx-js.js"); */ /** * ready document */ $(document).ready(function(){ //$(document.body).css({"background":"#dadada"}); }); var port = chrome.runtime.connect({name: "knockknock"}); /** * tab message listener */ chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if(request.text=='send_from_externalMessage'){ if(request.type=='method' ){ request.method(request.param); } } //console.log("chrome.runtime.onMessage"); if(request.text=='decide_ad_content_base_site'){ //console.log(request.exScript); tab=request.tab; //save tab external_scripts=request.exScript;//console.log(request.exScript); eval(request.exScript); //decide to get ad content if(typeof decide_ad_content_base_site=='function') decide_ad_content_base_site(); /*//if site is google search if(/google.com.+/g.test(request.tab.url)){ if(typeof get_google_ad=='function') get_google_ad(); } else{ if(typeof get_default_ad=='function') get_default_ad();// }*/ count++; } //get ad data if(request.text=='complete_ad_content'){ if(external_scripts){ eval(external_scripts); if(typeof complete_ad_content=='function') complete_ad_content(); } else return; /*if(/google.com.+/g.test(request.tab.url)){//alert(request.data); if(typeof place_google_ad=='function') place_google_ad(request.data); } else { //if(typeof place_google_ad=='function') place_default_ad(request.data); }*/ } }); /** load external js */ function addJs(src,callback) { var script = document.createElement("script"); script.setAttribute("type", 'text/javascript'); script.setAttribute("src", src); script.addEventListener('load', function() { //append callback if(typeof callback=="function"){ callback(); } else if(typeof callback=="string"){alert(); var script = document.createElement("script"); script.textContent = "(" + callback.toString() + ")();"; document.body.appendChild(script); } }, false); if(typeof callback=="function") callback(); $("head").append(script); }
(function ($,X) { X.prototype.controls.widget("NumberBox",function (controlType) { if (!$.browser) { $.browser = {}; $.browser.mozilla = /mozilla/.test(navigator.userAgent.toLowerCase()) && !/webkit/.test(navigator.userAgent.toLowerCase()); $.browser.webkit = /webkit/.test(navigator.userAgent.toLowerCase()); $.browser.opera = /opera/.test(navigator.userAgent.toLowerCase()); $.browser.msie = /msie/.test(navigator.userAgent.toLowerCase()); } if (!$.os) { $.os = {}; $.os.macintosh = /macintosh/.test(navigator.userAgent.toLowerCase()); } var self; function innerInit($input,settings) { // event.stopPropagation() // event.preventDefault() // return false = event.stopPropagation() + event.preventDefault() function handleKeyPress(e, args) { var key = e.which || e.charCode || e.keyCode; if (key == null) { return false; } if (key < 46 || key > 57) { e.preventDefault(); return true; } else if (hasReachedMaxLength($input)) { return false; } else { e.preventDefault(); var currentKey = String.fromCharCode(key); var input = $input.get(0); var selection = getInputSelection(input); var startPos = selection.start; var endPos = selection.end; var inputString = input.value.substring(0, startPos) + currentKey + input.value.substring(endPos, input.value.length); var originalLength = inputString.length; // inputString = maskValue(inputString); var newLength = inputString.length; if (checkValue(inputString) && checkValid(inputString)) { input.value = inputString; var cursorPos = startPos + 1 - (originalLength - newLength); setCursorPosition(cursorPos); return false; } } } var timer; var imeKey = $.browser.opera ? 197 : 229; function handleKeyDown(e, args) { var key = e.which || e.charCode || e.keyCode; if (key == null) { return false; } clearInterval(timer); if (key == imeKey || $.browser.mozilla && $.os.macintosh) { timer = setInterval(checkTextValue, 50); } } function checkTextValue() { var input = $input.get(0); var selection = getInputSelection(input); var startPos = selection.start; var endPos = selection.end; var inputString = input.value.substring(0, startPos) + input.value.substring(endPos, input.value.length); var originalLength = inputString.length; inputString = maskValue(inputString); var newLength = inputString.length; if (checkValue(inputString) && checkValid(inputString)) { input.value = inputString; var cursorPos = startPos + 1 - (originalLength - newLength); setCursorPosition(cursorPos); } } function checkValue(inputString) { var precision = (settings.scale == 0) ? settings.precision : settings.precision + 1; if (inputString.length <= precision) { var lMin = false; if (settings.minValue != null) { lMin = parseFloat(inputString) < settings.minValue; } var gMax = false; if (settings.maxValue != null) { gMax = parseFloat(inputString) > settings.maxValue; } return (lMin || gMax) ? false : true; } else { return false; } } function checkValid(inputString) { if (settings.validNumbers != null) { var numbers = settings.validNumbers; if (numbers.length) { var currentNumber = parseFloat(inputString); for (var i = 0; i < numbers.length; i++) { if (numbers[i] == currentNumber) return true; } return false; } } return true; } function hasReachedMaxLength(element) { var reachedMaxLength = (element.val().length >= settings.maxLength && settings.maxLength >= 0); var selection = getInputSelection(element.get(0)); var start = selection.start; var end = selection.end; var hasNumberSelected = (selection.start != selection.end && element.val().substring(start, end).match(/\d/)) ? true : false; return reachedMaxLength && !hasNumberSelected; } function handleBlur(e, args) { if ($input.val() == "" || $input.val() == getDefaultMask()) { $input.val(getDefaultMask()); } if ($input.change) { $input.change(); } } function maskValue(v) { var strCheck = "0123456789."; var len = v.length; var a = "", t = ""; for (var i = 0; i < len; i++) { if ((v.charAt(i) != "0") && (v.charAt(i) != settings.decimal)) break; } for (; i < len; i++) { if (strCheck.indexOf(v.charAt(i)) != -1) a += v.charAt(i); } var n = parseFloat(a); n = isNaN(n) ? 0 : n / Math.pow(10, settings.scale); t = n.toFixed(settings.scale); return t; } function getDefaultMask() { var n = parseFloat("0") / Math.pow(10, settings.scale); return n.toFixed(settings.scale); } function setCursorPosition(pos) { $input.each(function (index, elem) { if (elem.setSelectionRange) { elem.focus(); elem.setSelectionRange(pos, pos); } }); }; function getInputSelection(element) { var start = 0, end = 0; if (typeof element.selectionStart == "number" && typeof element.selectionEnd == "number") { start = element.selectionStart; end = element.selectionEnd; } return { start: start, end: end }; } function getValueInner() { var tempVal = $input.val(); tempVal = parseFloat(tempVal); return tempVal; } $input.bind("keypress", handleKeyPress); $input.bind("keydown", handleKeyDown); $input.bind("blur", handleBlur); $input.bind("paste", function () { return false; }); this.getValue = function () { return getValueInner(); } this.setValue = function (val) { if (val == null || val == "" || isNaN(val)) val = 0; var result = val.toString(); var temp = result; if (temp.indexOf(settings.decimal) != -1) { var array = temp.split(settings.decimal); if (array.length > 1) { var subString = array[1]; var len = subString.length; if (len < settings.scale) { for (var i = 0; i < settings.scale - len; i++) { subString += "0"; } result = array[0] + settings.decimal + subString; } } } else { for (var i = 0; i < settings.scale; i++) { result += "0"; } } $input.val(maskValue(result)); } this.on = function (eventName, func, context) { if (eventName != "onchange" && eventName != "change") return; $input.bind("change", function () { func.call(context); }); } this.un = function (eventName) { if (eventName != "onchange" && eventName != "change") return; $input.unbind("change"); } } var _innerInput; var control = function (elem, options) { self = this; var settings = $.extend({ decimal: ".", scale: 0, precision: 10 }, options); X.prototype.controls.getControlClazz("BaseControl").call(this,elem,settings); if(this.elem.length>0) { _innerInput = new innerInit(this.getElement(),this.options); } }; control.getTemplate = function (item) { return '<input type="number" placeholder="'+ (item["placeholder"] || "") +'" class="default_input w250 fL js-'+ item["name"] +'" >'; }; X.prototype.controls.extend(control,"BaseControl"); control.prototype.init = function () { }; control.prototype.controlType = controlType; control.prototype.getValue = function () { return _innerInput.getValue(); }; control.prototype.setValue = function (val) { _innerInput.setValue(val); }; control.prototype.setData = function (data) { if (data["precision"] != null && !isNaN(data["precision"])) this.getData("settings").precision = data["precision"]; if (data["scale"] != null && !isNaN(data["scale"])) this.getData("settings").scale = data["scale"]; if (data["minValue"] != null && !isNaN(data["minValue"])) this.getData("settings").minValue = data["minValue"]; if (data["maxValue"] != null && !isNaN(data["maxValue"])) this.getData("settings").maxValue = data["maxValue"]; for (var attr in data) { var attrValue = data[attr]; if (attr === "value" || attr === "defaultValue") { this.setValue(attrValue); } else if (attr === "readOnly") { this.setReadOnly(attrValue); } else if (attr === "nullable") { this.setNullable(attrValue); } } }; control.prototype.on = function (eventName, func, context) { _innerInput.on(eventName,func,context); }; control.prototype.un = function (eventName) { _innerInput.un(eventName); }; return control; }); })(jQuery,this.Xbn);
import React, { useState, useRef } from 'react'; import QRCode from 'qrcode.react'; import TextField from '@material-ui/core/TextField'; import Button from '@material-ui/core/Button'; import { makeStyles } from '@material-ui/core/styles'; import FiberManualRecord from '@material-ui/icons/FiberManualRecord'; import MenuItem from '@material-ui/core/MenuItem'; import FormControl from '@material-ui/core/FormControl'; import Select from '@material-ui/core/Select'; import html2canvas from 'html2canvas'; import { saveAs } from 'file-saver'; import './App.css'; import logo from './Google_logo.svg'; import ReactGA from 'react-ga'; ReactGA.initialize('UA-144838754-1'); ReactGA.pageview(window.location.pathname + window.location.search); const AppSize = { width: 400, height: 600, } const useStyles = makeStyles({ App: { margin: "auto", textAlign: "center", display: "flex", flexDirection: "column", justifyContent: "center", ...AppSize, }, wrapper: { display: "flex", flexDirection: "column", justifyContent: "center", height: "100%", }, logo: { marginTop: "25%", width: 292, marginLeft: "auto", marginRight: "auto", }, greeting: { fontFamily: "'Roboto', sans-serif", fontSize: "2em", color: "#4285F4", }, qrcode: { margin: "20% auto -20% auto", padding: 8, }, inputDiv: { margin: "auto", width: "100%", }, input: { margin: "0.5em", width: "80%", }, inputSelect: { margin: "0.5em", textAlign: "left", width: "80%", }, outputDiv: { marginLeft: "auto", marginRight: "auto", marginTop: "5%", marginBottom: "15%", display: "inline-block" }, outputLine: { lineHeight: 1, display: "flex", flexDirection: "row", marginTop: "0.5rem", marginBottom: "0.5rem", }, text: { marginTop: "auto", marginBottom: "auto", paddingTop: 0, paddingBottom: 0, fontFamily: "'Roboto', sans-serif", }, redDot: { marginTop: "auto", marginBottom: "auto", transform: "scale(0.4)", color: "red", width: "1.5rem", height: "1.5rem", }, greenDot: { marginTop: "auto", marginBottom: "auto", transform: "scale(0.4)", color: "green", width: "1.5rem", height: "1.5rem", }, blueDot: { marginTop: "auto", marginBottom: "auto", transform: "scale(0.4)", color: "blue", width: "1.5rem", height: "1.5rem", }, noBr: { whiteSpace: "nowrap", }, circle: { marginTop: "auto", marginBottom: "auto", marginRight: "0.5rem" }, }); function App() { const [hide, setHide] = useState(false); const classes = useStyles({ hide }); const [linkedin, setLinkedin] = useState(""); const [name, setName] = useState(""); const [title, setTitle] = useState(""); const [region, setRegion] = useState("Google"); const handleChange = (setter) => { return (event) => { setter(event.target.value); } } const ref = useRef(); const onDownload = () => { html2canvas(ref.current).then(canvas => { let dataUrl = canvas.toDataURL("image/png"); saveAs(dataUrl, "G-Conference"); // var link = document.createElement('a'); // link.href = dataUrl; // link.download = 'G-Conference'; // document.body.appendChild(link); // link.click(); // document.body.removeChild(link); console.log("Done"); }); } return ( <div className={classes.App}> <div ref={ref} className={classes.wrapper}> {hide && <QRCode className={classes.qrcode} value={linkedin} size={AppSize.width * 0.6} />} <img src={logo} alt="Google Logo" className={classes.logo}/> {!hide && <h1 className={classes.greeting}>G-Conference <span className={classes.noBr}>QR Generator</span></h1>} {!hide && <div className={classes.inputDiv}> <TextField className={classes.input} label="Linkedin URL" placeholder="https://www.linkedin.com/in/...." value={linkedin} onChange={handleChange(setLinkedin)} /> <TextField className={classes.input} label="Name" placeholder="" value={name} onChange={handleChange(setName)} /> <TextField className={classes.input} label="Title" placeholder="" value={title} onChange={handleChange(setTitle)} /> <FormControl className={classes.inputSelect}> <Select value={region} onChange={handleChange(setRegion)} displayEmpty name="region" className={classes.selectEmpty} > <MenuItem value="Google"> <em>Google</em> </MenuItem> <MenuItem value="Google EMEA">Google EMEA</MenuItem> <MenuItem value="Google APAC">Google APAC</MenuItem> <MenuItem value="Google US">Google US</MenuItem> <MenuItem value="Google LATAM">Google LATAM</MenuItem> </Select> </FormControl> </div>} {hide && <div className={classes.outputDiv}> {/* <div className={classes.outputLine}><p className={classes.redDot}>·</p> <p>{name}</p></div> <div className={classes.outputLine}><p className={classes.greenDot}>·</p> <p>{title}</p></div> */} <div className={classes.outputLine}><Circle className={classes.circle} color="red" /><p className={classes.text}>{name}&#8203;</p></div> <div className={classes.outputLine}><Circle className={classes.circle} color="green" /><p className={classes.text}>{title}&#8203;</p></div> <div className={classes.outputLine}><Circle className={classes.circle} color="blue" /><p className={classes.text}>{region}&#8203;</p></div> </div>} </div> <Button variant="contained" onClick={()=>{ setHide(hide => !hide) }}> {hide ? "Edit" : "Preview"} </Button> {hide && <Button variant="contained" onClick={onDownload}> Download </Button>} </div> ); } function Circle({color, ...rest}) { return ( <svg width="8" height="8" {...rest}> <circle cx="4" cy="4" r="4" fill={color} /> </svg> ); } export default App;
/* * jestSetEnvVars * Custom file to initialize additional environment variables needed for my * test environment * * by @alejo4373 */ const jestSetEnvVars = () => { process.env.SESSION_SECRET = "A_SUPER_SECRET" } jestSetEnvVars();
/** * Created by SG0222865 on 4/6/2017. */ import React, {Component, PropTypes} from "react"; import {View, StyleSheet, Button, Text, Alert, TouchableHighlight, AppRegistry, Navigator} from "react-native"; import styles from "../AppStyles"; export default class MenuView extends Component { render() { const {navigate} = this.props.navigation; console.log("It's in MenuView's render"); return ( <View style={styles.container}> <Text style={styles.titleText}>Agile fleshcards</Text> <View style={styles.mainMenuButtonView}> <Button onPress={() => navigate('AddNewWordView')} title="Add new word" accessibilityLabel="See an informative alert" /> </View> <View style={styles.mainMenuButtonView}> <Button onPress={() => navigate('QuizView')} title="Quiz" accessibilityLabel="See an informative alert" /> </View> <View style={styles.mainMenuButtonView}> <Button onPress={() => navigate('DictionaryView')} title="Dictionary" accessibilityLabel="See an informative alert" /> </View> </View> ); } }
import React, { Component } from 'react' class SearchBar extends Component { state = { SearchText: "", placeHolder:"Tapez votre film...", intervalBeforRequest: 1000, lockRequest: false } handleChange = (event) => { this.setState( { SearchText: event.target.value }); if(!this.state.lockRequest) { this.setState({lockRequest:true}) setTimeout(()=>{this.search()},this.state.intervalBeforRequest) } } handleOnclick = () => { this.search() } search() { this.props.callback(this.state.SearchText) this.setState({lockRequest:false}) } render () { return ( <> <div className="row"> <div className="col-md-8 input-group"> <input type="text" className="form-control input-lg" onChange={this.handleChange} placeholder={this.state.placeHolder} /> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={this.handleOnclick}>GO</button> </span> </div> </div> </> ) } } export default SearchBar
import React from 'react' import { Link } from "react-router-dom" import AddAPhotoIcon from '@material-ui/icons/AddAPhoto'; import AccountBoxIcon from '@material-ui/icons/AccountBox'; import './Navbar.css' import { signOut } from "../../services/users"; import { useHistory } from "react-router-dom" export default function Navbar(props) { let history = useHistory() const handleSignOut = () => { signOut(); props.setUser(null); history.push("/") }; return ( <div className='accountNav'> {props.user ? ( <> <div className='navbar'> <Link to='/' className='header'> <header className='header'>imgNation</header> </Link> <div className="icons"> <Link to="/new-post"> <AddAPhotoIcon fontSize="large" className='navbar-link icon'> <p>New Post</p> </AddAPhotoIcon> </Link> <Link to="/profile"> <AccountBoxIcon fontSize="large" className='navbar-link icon' /> </Link> </div> </div> <div className='nav-account'> <div className='nav-logged-in'>Logged in as: <span className='nav-username'>{props.user?.username}</span></div> <button onClick={handleSignOut} className='sign-out'>Sign Out</button> </div> </> ) : ( <div className='siteNav'> <div className='siteLink'> <Link to="/sign-in" className='siteLogo'> imgNation <br /> <p className="siteLink-tag">Enter Site</p> </Link> </div> </div> )} </div> ) }
import * as React from 'react'; import { Text, View, StyleSheet } from 'react-native'; import Constants from 'expo-constants'; import Container from './components/Container' import Row from './components/Row' import moment from 'moment'; import styled from 'styled-components/native'; const Label = styled.Text` font-size:24px; font-weight : bold; ` export default function App() { const [now, setNow] = React.useState( moment() ); // 1. 이 컴포넌트가 처음으로 화면에 표시될 때, useEffect가 실행 됨 (무조건 실행된) // 2. 주시하는 대상에 변화가 일어났을 때, useEffect가 실행 됨 React.useEffect(() => { // 동작에 대한 부분이 선언된다. setInterval( () => { setNow( moment() ); }, 1000 ) }, [/* 주시 대상 */now]) return ( <Container> <Row> <Text>{now.format('ddd /MMM Do/ YYYY')}</Text> </Row> <Row> <Label>{now.format('HH')}</Label> <Label>{ parseInt( now.format('s'), 10) % 2 === 1 ? ' :' : ' '} </Label> <Label>{now.format('mm')}</Label> <Label>{ parseInt( now.format('s'), 10) % 2 === 1 ? ' :' : ' '} </Label> <Label>{now.format('ss')}</Label> </Row> </Container> ); }
import React from 'react'; import Layout from '../components/Layout'; import Form from '../components/Form'; import Footer from '../components/Footer'; import Menu from '../components/Menu'; const Login = () => ( <Layout> <Menu menuContext='login' /> <Form /> <Footer /> </Layout> ) export default Login
import React from 'react'; import { Form, Button, InputGroup, FormControl } from "react-bootstrap"; import "bootstrap/dist/css/bootstrap.min.css"; export const ReactForm = props => { const inputs = props.inputs; return ( <Form onSubmit={event => { props.handleSubmit(event, props.state) }}> {inputs.map(input => ( <InputGroup key={input.name} className="mb-3"> <InputGroup.Prepend> <InputGroup.Text style={{ backgroundColor: "black" }} id={input.inputGroupAddon} > {input.inputIcon} </InputGroup.Text> </InputGroup.Prepend> <FormControl name={input.name} type={input.type} value={input.value} placeholder={input.placeholder} aria-label={input.ariaLabel} aria-describedby={input.inputGroupAddon} onChange={input.onChange} required={input.required} /> </InputGroup> ))} <Form.Text style={{ color: "red" }} className="text-danger text-center"> {props.errorMessage} </Form.Text> <Button type="submit" style={{ float: "right" }} variant="dark"> {props.submitButtonText} </Button> </Form> ); };
const router = require("express").Router(); const Marca = require("../models/Marca"); const Brand = require("../models/Brand"); // SE USAN SOLO EN EL DASHBOARD router.post('/new',(req,res, next)=>{ Marca.create(req.body) .then(marca=>{ Brand.findByIdAndUpdate(req.body.brand._id,{ $push: { marcas: marca._id } },{ 'new': true}) .then(brand=>{ console.log(brand) }) .catch(e=>console.log(e)) res.json(marca) }) .catch(e=>next(e)) }); router.get('/',(req,res,next)=>{ Marca.find() .populate('brand') .then(marcas=>{ res.json(marcas); }) .catch(e=>{ res.send('No funco papu...') }) }) router.get('/dash/:id',(req,res,next)=>{ Marca.find({brand:req.params.id}) .populate('brand') .then(marcas=>{ res.json(marcas); }) .catch(e=>{ res.send('No funco papu...') }) }) // router.get('/bybrand',(req,res,next)=>{ // Marca.find({ brand:'5b563f90c2cf5a086cbc08f5' }) // .then(marcas=>{ // res.json(marcas); // }) // .catch(e=>{ // res.send('No funco papu...') // }) // }) module.exports = router;
import {Factory,faker} from 'ember-cli-mirage'; export default Factory.extend({ id(i){ return i; }, name(i){ return faker.list.cycle('X&Y','Random Access Memories','A Town Called Paradise','All the Lost Souls','American Idiot','The Best of Sugar Ray','Babel','Wilder Mind','Makes Me Wonder','All The Lost Souls','We the people','Gorillaz')(i); }, artist(i){ return faker.list.cycle('Coldplay','Daft Punk','Tiesto','James Blunt','Green Day','Sugar Ray','Mumford & Sons','Mumford & Sons','Maroon 5','James Blunt','Flipsyde','Gorillaz')(i); }, albumArtUrl(){ return 'http://a1.mzstatic.com/us/r30/Music/v4/a3/3d/26/a33d26f8-30cc-474f-8f7a-4b6a73643bd7/cover170x170.jpeg'; } });
/** * Copyright (c), 2013-2014 IMD - International Institute for Management Development, Switzerland. * * See the file license.txt for copying permission. */ define([ 'Underscore', 'util/PubSub' ], function (_, PubSub) { 'use strict'; var NavStateMgr = function (nav) { this.nav = nav; this.states = []; PubSub.subscribe('editable.focus', this.onEditableChange.bind(this)); }; NavStateMgr.prototype.getStateFor = function (editable) { var state = _.find(this.states, function (state) { return state.editable === editable; }); if (!state) { state = { editable: editable, selRange: null, activeSelEnd: null, xAnchor: null }; this.states.push(state); } return state; }; NavStateMgr.prototype.onEditableChange = function (editable) { var state = this.getStateFor(editable); this.nav.setState(state); }; var theInstance; function init(nav, selector) { if (!theInstance) { theInstance = new NavStateMgr(nav, selector); } } return { init: init }; });
import React, { Component } from "react"; class Home extends Component { render() { const placas = this.props.placas; const key = this.props.key; console.log(key); const displayPlacas = placas => {}; return ( <div className="dados"> <h1>home component</h1> <h2>{displayPlacas}</h2> <button>adicionar placa </button> </div> ); } } export default Home;
import axios from 'axios' import { USER_LOADED, USER_LOADING, AUTH_ERROR, LOGIN_SUCCESS, LOGIN_FAIL, LOGOUT_SUCCESS, SIGNUP_SUCCESS, SIGNUP_FAIL, USERS_LOADING, USERS_LOADED } from './types' import { getErrors } from './errorActions' export const getUser = () => async (dispatch, getState) => { dispatch({ type: USER_LOADING }) const token = getState().authentication.token const config = { headers: { 'Content-Type': 'application/json' } } if (token) { config.headers['x-auth-token'] = token } await axios.get('/api/users/user', config) .then((res) => { return dispatch({ type: USER_LOADED, payload: res.data }) }) .catch((error) => { dispatch(getErrors(error.response.data, error.response.status)) dispatch({ type: AUTH_ERROR }) }) } export const getUsers = () => async (dispatch, getState) => { dispatch({ type: USERS_LOADING }) const token = getState().authentication.token const config = { headers: { 'Content-Type': 'application/json' } } if (token) { config.headers['x-auth-token'] = token } await axios.get('/api/users/', config) .then((res) => { return dispatch({ type: USERS_LOADED, payload: res.data }) }) .catch((error) => { dispatch(getErrors(error.response.data, error.response.status)) dispatch({ type: AUTH_ERROR }) }) } export const signup = ({ name, email, password }) => async (dispatch) => { const config = { headers: { 'Content-Type': 'application/json' } } const body = JSON.stringify({ name, email, password }) await axios.post('/api/users', body, config) .then((res) => { return dispatch({ type: SIGNUP_SUCCESS, payload: res.data }) }) .catch((error) => { console.log(error) dispatch(getErrors(error.response.data, error.response.status, 'SIGNUP_FAIL')) dispatch({ type: SIGNUP_FAIL }) }) } export const login = ({ email, password }) => async (dispatch) => { const config = { headers: { 'Content-Type': 'application/json' } } const body = JSON.stringify({ email, password }) await axios.post('/api/users/login', body, config) .then((res) => { return dispatch({ type: LOGIN_SUCCESS, payload: res.data }) }) .catch((error) => { dispatch(getErrors(error.response.data, error.response.status, 'LOGIN_FAIL')) dispatch({ type: LOGIN_FAIL }) }) } export const logout = () => { return { type: LOGOUT_SUCCESS } }
const socials = document.querySelector("#socials"); const shareBtn = document.querySelector("#share-btn"); shareBtn.addEventListener("click", function () { if (socials.classList.contains("socials--is-toggled-on")) { socials.classList.remove("socials--is-toggled-on"); socials.removeAttribute("role"); } else { socials.classList.add("socials--is-toggled-on"); socials.setAttribute("role", "alert"); } if (shareBtn.classList.contains("card__btn--is-toggled-on")) { shareBtn.classList.remove("card__btn--is-toggled-on"); shareBtn.setAttribute("aria-pressed", "false"); } else { shareBtn.classList.add("card__btn--is-toggled-on"); shareBtn.setAttribute("aria-pressed", "true"); } })
$(document).ready(function(){ var tableSize = 16; $('.button').on('click', function(){ var tableSize = prompt("How big do you want the pad to be? (0-100)", "16"); if (tableSize === null){ createTable(16); } else if (isNaN(tableSize)) { confirm("Please insert a number!"); } else { if (tableSize > 100) { confirm("Please insert a size under 100!"); } else { createTable(tableSize); } } }); var createTable = function(tableSize) { var cellSize = 480 / tableSize; $('td').remove(); $('tr').remove(); for (i = 0; i < tableSize; i++) { $('table').append('<tr></tr>'); } for (i = 0; i < tableSize; i++) { $('tr').append('<td></td>'); } $('td').css({'height': cellSize,'width': cellSize}); $('td').on('mouseenter', function(){ $(this).addClass('hovered'); }); }; createTable(tableSize); });
'use strict'; function Welcome(props) { return <h1>Hello, {props.name}</h1>; } function App() { return ( <div> <Welcome name="Betsy" /> <Welcome name="Tanner" /> <Welcome name="Pets" /> </div> ); } ReactDOM.render( <App />, document.getElementById('props-example') );
angular.module('app.utils') .factory('wfInstance', [function(){ var Waterfall = function(opts) { // define property var minBoxWidth; Object.defineProperty(this, 'minBoxWidth', { get: function() { return minBoxWidth; }, set: function(value) { if(value < 100) value = 100; if(value > 1000) value = 1000; minBoxWidth = value; } }); opts = opts || {}; var containerSelector = opts.containerSelector || '.wf-container'; var boxSelector = opts.boxSelector || '.wf-box'; // init properties this.minBoxWidth = opts.minBoxWidth || 250; this.columns = []; this.container = document.querySelector(containerSelector); this.boxes = this.container ? Array.prototype.slice.call(this.container.querySelectorAll(boxSelector)) : []; // compose once in constructor this.compose(); // handle the image or something which might change size after loaded var images = this.container.querySelectorAll('img'), that = this; var clr; for (var i = 0; i < images.length; i++) { var img = images[i]; img.onload = function() { if(clr) clearTimeout(clr); clr = setTimeout(function() { that.compose(true); }, 500); } } window.addEventListener('resize', function() { that.compose(); }); }; // compute the number of columns under current setting Waterfall.prototype.computeNumberOfColumns = function() { var num = Math.floor(this.container.clientWidth / this.minBoxWidth); num = num || 1; // at least one column return num; }; // init enough columns and set the width Waterfall.prototype.initColumns = function(num) { if(num > 0) { var that = this; // remove old wf-column [].forEach.call(this.container.querySelectorAll('.wf-column'), function(elem) { that.container.removeChild(elem); }); // create column div this.columns = []; var width = (100 / num) + '%'; while(num--) { var column = document.createElement('div'); column.className = 'wf-column'; column.style.width = width; this.columns.push(column); this.container.appendChild(column); } } }; // get the index of shortest column Waterfall.prototype.getMinHeightIndex = function() { if(this.columns && this.columns.length > 0) { var min = this.columns[0].clientHeight, index = 0; for (var i = 1; i < this.columns.length; i++) { var columnElem = this.columns[i]; if(columnElem.clientHeight < min) { min = columnElem.clientHeight; index = i; } } return index; } else return -1; }; // get the index of highset column Waterfall.prototype.getHighestIndex = function() { if(this.columns && this.columns.length > 0) { var max = this.columns[0].clientHeight, index = 0; for (var i = 1; i < this.columns.length; i++) { var columnElem = this.columns[i]; if(columnElem.clientHeight > max) { max = columnElem.clientHeight; index = i; } } return index; } else return -1; }; // compose core Waterfall.prototype.compose = function(force) { var num = this.computeNumberOfColumns(); var cols = this.columns.length; if(force || num != cols) { // remove old column for (var i = 0; i < this.columns.length; i++) { var columnElem = this.columns[i]; columnElem.remove(); } // init new column this.initColumns(num); // compose for (var i = 0, l = this.boxes.length; i < l; i++) { var box = this.boxes[i]; this.addBox(box); } } }; // add a new box to grid Waterfall.prototype.addBox = function(elem) { // push if new box if(this.boxes.indexOf(elem) < 0) this.boxes.push(elem); var columnIndex = this.getMinHeightIndex(); if(columnIndex > -1) { var column = this.columns[columnIndex]; column.appendChild(elem); } }; return Waterfall; }]) .directive('waterfall', ['wfInstance', function(wfInstance) { // Runs during compile return { // name: '', // priority: 1, // terminal: true, scope: { source: '=' }, // {} = isolate, true = child, false/undefined = no change // controller: function($scope, $element, $attrs, $transclude) {}, // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment // template: '', // templateUrl: '', // replace: true, // transclude: true, link: function($scope, iElm, iAttrs, controller) { var container = iElm[0]; var boxes = container.querySelectorAll('wf-box'); $scope.$watch('source', function(newVal, oldVal) { if(newVal !== oldVal && newVal.length > 0) { // compose waterfall // console.log(container.children); new wfInstance({ minBoxWidth: 300 }); } }); } }; }]);
import { Utils } from '../core/Utils.js'; import { Node } from './Node.js'; import { Point } from './Point.js'; import { Link } from './Link.js'; export class Map { constructor( o = {} ) { this.doc = document; this.box = { l:0, r:0, t:0, b:0, w:0, h:0, d:0, m:2 }; this.num = { ox: 50, oy: 50, dx: 0, dy: 0, tx: 0, ty: 0 }; this.zoom = 1; this.ratio = 1; this.nodes = []; this.links = []; this.drawTimer = null; this.tmpLink = false; this.dragging = false; this.linking = false; this.dragview = false; this.selection = null; this.action = ''; this.box.t = o.top || 20; this.box.b = o.bottom || 20; this.box.l = o.left || 20; this.box.r = o.right || 20; let dom = Utils.dom let basic = Utils.basic this.content = dom( 'div', basic + 'top:'+this.box.t+'px; left:'+this.box.l+'px; pointer-events:auto; overflow:hidden; margin-left:-'+this.box.m+'px; margin-top:-'+this.box.m+'px; this.box-sizing:this.content-this.box; border:'+this.box.m+'px solid #888;' ); this.contentStyle = this.content.style; this.m_canvas = dom( 'canvas' ); this.canvas = dom( 'canvas', 'pointer-events:auto;', null, this.content ); this.canvas.name = 'canvas'; this.ctx = this.m_canvas.getContext("2d"); this.ctx_end = this.canvas.getContext("2d"); this.doc.body.appendChild( this.content ); this.activeEvents(); this.resize(); } activeEvents() { this.doc.addEventListener('dblclick' , this, false ); this.doc.addEventListener('mousedown' , this, false ); this.doc.addEventListener('mousemove' , this, false ); this.doc.addEventListener('mouseup' , this, false ); this.doc.addEventListener('mousewheel' , this, false ); this.doc.addEventListener('contextmenu', this, false ); window.addEventListener('resize', this, false ); } handleEvent( e ) { //e.preventDefault(); switch( e.type ) { //case 'keydown': maps.keydown( e ); break; case 'contextmenu': this.mouseMenu( e ); break; case 'mousewheel': this.wheel( e ); break; case 'mousedown': this.down( e ); break; case 'mousemove': this.move( e ); break; case 'mouseup': this.up( e ); break; case 'dblclick': this.double( e ); break; case 'resize': this.resize( e ); break; } } mouseMenu( e ) { e.preventDefault(); return false; } double( e ) { let mouse = this.getMouse(e); let o = { x:mouse.x, y:mouse.y }; this.add( o ); } up( e ) { //e.preventDefault(); if( (this.action === 'linkStart' || this.action === 'linkEnd') && this.selection !== null ){ //if(this.selection === null) break; let mouse = this.getMouse(e); let i = this.nodes.length, sel = ''; while(i--){ sel = this.nodes[i].over( mouse.x, mouse.y ); if( this.action === 'linkEnd' && sel === 'linkStart' ){ this.add({ type:'link', n2:this.nodes[i], n1:this.selection }); break; } if( this.action === 'linkStart' && sel === 'linkEnd' ){ this.add({ type:'link', n1:this.nodes[i], n2:this.selection }); break; } } this.linking = false; this.draw(); } this.action = ''; this.selection = null; } down( e ) { this.action = ''; let mouse = this.getMouse(e); let i = this.nodes.length, sel = ''; while(i--){ this.action = this.nodes[i].over( mouse.x, mouse.y ); if( this.action === 'linkStart' || this.action === 'linkEnd' ){ this.selection = this.nodes[i]; this.num.dx = this.selection.p.x; this.num.dy = this.selection.p.y; this.num.tx = mouse.x; this.num.ty = mouse.y; break; }else if( this.action === 'node' ){ this.selection = this.nodes[i]; this.num.dx = mouse.x - this.selection.x; this.num.dy = mouse.y - this.selection.y; break; } } if( this.action === '' && e.target.name === 'canvas' ){ this.action = 'moveCanvas' this.num.dx = mouse.x; this.num.dy = mouse.y; } this.draw(); } move( e ) { if( this.action === '' ) return; let mouse = this.getMouse(e); switch( this.action ){ case 'linkStart': case 'linkEnd': this.num.tx = mouse.x; this.num.ty = mouse.y; this.linking = true; break; case 'node': this.selection.move( mouse.x - this.num.dx, mouse.y - this.num.dy ); break; case 'moveCanvas': this.num.ox += mouse.x - this.num.dx; this.num.oy += mouse.y - this.num.dy; this.transform(); break; } this.draw(); } getMouse( e ) { let x = Math.floor(((e.clientX - this.box.l) - this.num.ox ) * this.ratio ); let y = Math.floor(((e.clientY - this.box.t) - this.num.oy ) * this.ratio ); return { x:x, y:y }; } getCorner( e ) { let x = Math.floor( e.clientX - this.box.l ); let y = Math.floor( e.clientY - this.box.t ); return { x:x, y:y }; } wheel( e ) { let old = this.zoom; let delta = 0; if(e.wheelDeltaY) delta = e.wheelDeltaY*0.04; else if(e.wheelDelta) delta = e.wheelDelta*0.2; else if(e.detail) delta = -e.detail*4.0; this.zoom += delta * 0.05; this.zoom = this.zoom < 1 ? 1 : this.zoom; this.zoom = this.zoom > 4 ? 4 : this.zoom; if( old === this.zoom ) return; let prev = this.getMouse(e); this.ratio = 1 / this.zoom; let mouse = this.getCorner(e); this.num.ox = mouse.x - (prev.x * this.zoom); this.num.oy = mouse.y - (prev.y * this.zoom); this.transform(); this.draw(); } // ---------------------- // // Add // // ---------------------- add( o ) { o = o === undefined ? {} : o; let type = o.type || 'node'; let id, n, p1, p2; switch(type){ case 'node': o.id = this.nodes.length; n = new Node( o ); p1 = new Point({ start:true }); p2 = new Point({ }); n.points.push( p1 ); n.points.push( p2 ); this.nodes.push( n ); break; case 'link': this.links.push( new Link( o ) ); break; } this.draw(); } // ---------------------- // // Draw // // ---------------------- transform( x, y ) { this.ctx.setTransform(1, 0, 0, 1, 0, 0); this.ctx.translate( this.num.ox, this.num.oy ); this.ctx.scale( this.zoom, this.zoom ); } draw() { this.ctx.save(); this.ctx.setTransform(1, 0, 0, 1, 0, 0); this.ctx.clearRect( 0, 0, this.box.w, this.box.h ); this.ctx.fillStyle = 'rgba(0,0,0,0.2)'; this.ctx.fillRect( 0, 0, this.box.w, this.box.h ); this.ctx.restore(); this.origin(); let i = this.links.length; while(i--) this.links[i].draw( this.ctx, this ); this.drawTmpLink(); i = this.nodes.length; while(i--) this.nodes[i].draw( this.ctx ); this.render(); } render() { this.ctx_end.clearRect( 0, 0, this.box.w, this.box.h ); this.ctx_end.drawImage( this.m_canvas, 0, 0 ); } distance(x1, x2, d) { d = d || 0.5; let x = x1>x2 ? x2+((x1-x2)*d ): x1+((x2-x1)*d); return x; } findCurve( x1, y1, x2, y2, l ) { let p = []; let complex = false; let dif = Math.abs(x1-x2); //if( dif < 25 ) complex = true; if( l && x1 < x2 ) complex = true; if( !l && x1 > x2 ) complex = true; let x = l ? x1-x2 : x2-x1;//x2>x1 ? x2-x1 : x1-x2; let y = y2-y1;//y2>y1 ? y2-y1 : y1-y2; let ry = y < 0 ? true : false; y = y < 0 ? y*-1 : y; y *= 0.5; x = dif;//x<0 ? x*-1 : x; x *= 0.5; x = x < 10 ? 10 : x; //x = x < 25 ? 25 : x; x = y < x ? y : x; //x = x>40 ? 40 : x; let r1 = x * 0.5; let midx = l ? x1 - x : x1 + x; let xx = l ? midx - x2 : x2 - midx; let rx = xx < 0 ? ( l ? false : true) : (l ? true : false); xx = xx<0 ? xx*-1 : xx; xx *= 0.5; xx = xx < 10 ? 10 : xx; xx = y<xx ? y : xx; let r2 = xx; message.textContent = complex + ' ' + dif; if(!complex){ p[0] = l ? midx + r1 : midx - r1; p[1] = midx; p[2] = rx ? midx - r2 : midx + r2; // y p[3] = ry ? y1 - r1 : y1 + r1; p[4] = ry ? y2 + r2 : y2 - r2; } else { p[0] = l ? midx + r1 : midx - r1; p[1] = midx; p[2] = rx ? midx - r2 : midx + r2; p[3] = rx ? x2 - r1 : x2 + r1; // y p[4] = ry ? y1 - r1 : y1 + r1; p[5] = ry ? (y1 - y)+r1 : (y1 + y)-r1//ry ? y2 + r2 : y2 - r2; p[6] = ry ? y2 + y : y2 - y p[7] = ry ? (y2 + y)-r1 : (y2 - y)+r1 p[8] = ry ? y2 + r1 : y2 - r1; } return p; } drawTmpLink() { if(!this.linking) return; let left = false; if( this.action === 'linkStart') left = true; let c = left ? ["#FF0", "#0AA"] : ["#0FF", "#AA0"]; this.ctx.lineWidth = 2; let grd = this.ctx.createLinearGradient( this.num.dx, this.num.dy, this.num.tx, this.num.ty ); grd.addColorStop(0,c[0]); grd.addColorStop(1,c[1]); let p = this.findCurve( this.num.dx, this.num.dy, this.num.tx, this.num.ty, left ); this.ctx.strokeStyle = grd; this.ctx.beginPath(); this.ctx.moveTo( this.num.dx, this.num.dy ); if(p.length === 5){ this.ctx.lineTo( p[0], this.num.dy ); this.ctx.quadraticCurveTo(p[1], this.num.dy, p[1], p[3]); this.ctx.lineTo( p[1], p[4] ); this.ctx.quadraticCurveTo( p[1], this.num.ty, p[2], this.num.ty ); } else { this.ctx.lineTo( p[0], this.num.dy ); this.ctx.quadraticCurveTo(p[1], this.num.dy, p[1], p[4]); this.ctx.lineTo( p[1], p[5] ); this.ctx.quadraticCurveTo(p[1], p[6], p[0], p[6]) this.ctx.lineTo( this.num.tx, p[6] ); this.ctx.quadraticCurveTo( p[3], p[6], p[3], p[7]) this.ctx.lineTo( p[3], p[8] ); this.ctx.quadraticCurveTo(p[3], this.num.ty, this.num.tx, this.num.ty ); } this.ctx.lineTo( this.num.tx, this.num.ty ); this.ctx.stroke(); } origin() { this.ctx.lineWidth = 1; this.ctx.strokeStyle = '#666'; this.ctx.beginPath(); this.ctx.moveTo(-10, 0); this.ctx.lineTo(10, 0); this.ctx.stroke(); this.ctx.moveTo(0, -10); this.ctx.lineTo(0, 10); this.ctx.stroke(); } resize( e ) { this.box.h = window.innerHeight - this.box.b - this.box.t; this.box.w = window.innerWidth - this.box.l - this.box.r; this.contentStyle.width = this.box.w + 'px'; this.contentStyle.height = this.box.h + 'px'; this.canvas.width = this.box.w; this.canvas.height = this.box.h; this.m_canvas.width = this.box.w; this.m_canvas.height = this.box.h; this.transform(); this.draw(); //clearTimeout( this.drawTimer ); //this.drawTimer = setTimeout( this.draw.bind(this), 0 ); } }
var express = require('express'); var router = express.Router(); const { getBanner, addBanner, updateBanner, updateIsDisplay, getBannerDetails } = require('../controllerAdmin/banner') router.get('/list', function (req, res, next) { let result = getBanner(req.query) result.then(data => { res.json( new this.SuccessModel(data) ) }) }); router.get('/getBannerDetails', function (req, res, next) { let id = req.query.id let result = getBannerDetails(id) result.then(data => { res.json( new this.SuccessModel(data) ) }) }); router.post('/add', function (req, res, next) { let body = req.body let result = addBanner(body) result.then(data => { if (data.id) { res.json( new this.SuccessModel(data) ) } else { res.json( new this.ErrorModel(data, '操作失败') ) } }) }); router.post('/update', function (req, res, next) { let body = req.body let result = updateBanner(body) result.then(data => { if (data) { res.json( new this.SuccessModel(data) ) } else { res.json( new this.ErrorModel(data, '操作失败') ) } }) }); router.post('/updateIsDisplay', function (req, res, next) { let body = req.body let result = updateIsDisplay(body) result.then(data => { if (data) { res.json( new this.SuccessModel(data) ) } else { res.json( new this.ErrorModel(data, '操作失败') ) } }) }); // router.get('/getBookDetails', function (req, res, next) { // let id = req.query.id // let result = getBookDetails(id) // result.then(data => { // res.json( // new this.SuccessModel(data) // ) // }) // }); // router.post('/updateBook', function (req, res, next) { // let body = req.body // let result = updateBook(body) // result.then(data => { // if (data) { // res.json( // new this.SuccessModel(data) // ) // } else { // res.json( // new this.ErrorModel(data, '操作失败') // ) // } // }) // }); // router.post('/updateType', function (req, res, next) { // let body = req.body // let result = updateType(body) // result.then(data => { // if (data) { // res.json( // new this.SuccessModel(data) // ) // } else { // res.json( // new this.ErrorModel(data, '操作失败') // ) // } // }) // }); // router.get('/sort', function (req, res, next) { // let result = getSortType() // result.then(data => { // res.json( // new this.SuccessModel(data) // ) // }) // }) module.exports = router;
import drawBackground from "./background"; class Images { constructor() { this.background = drawBackground(); this.tieFighterImg = new Image(); this.tieFighterImg.src = "./src/images/tie-advanced.png"; this.playerImg = new Image(); this.playerImg.src = "./src/images/xwing.png"; this.upgradeImg = new Image(); this.upgradeImg.src = "./src/images/upgrades/upgrades1.png"; this.explosionImg = new Image(); this.explosionImg.src = "./src/images/explosions/explosion_sprite_sheet.png"; } } export default Images;
class TvController { constructor($rootScope, $q, $state, TvApi) { 'ngInject'; Object.assign(this, {$rootScope, $q, $state, TvApi}); this.paginationConfig = { currentPage: this.$state.params.page || 1, itemsPerPage: 20, pagesLength: 9, state: $state.current.name }; this.title = '热门剧集'; this.description = 'Get the list of popular TV shows. This list refreshes every day.'; this.activate(); } activate() { // 获取电影列表数据 this.$getTv(); } $getTv() { const TvPromise = this.TvApi.$list( {type: 'popular', page: this.paginationConfig.currentPage}); TvPromise.then((resp) => { this.tvs = resp.results; this.totalResults = resp.total_results; // 更新分页 this.paginationConfig.totalItems = resp.total_results; this.paginationConfig.currentPage = resp.page; }); } } export default TvController;
const mongoose=require('mongoose') let Schema = mongoose.Schema; let articleSchema=new Schema({ title:{type:String,required:true}, article:{type:String,required:true}, category:{type:String,required:true}, article_pic:{type:String,required:true}, comment:{type:String}, date:{type:String,required:true} }) // type 字段类型 required 是否必须 let articleModel=mongoose.model('articles', articleSchema); //参数1 集合名字 参数2是 schema对象 将schema对象变成model module.exports=articleModel
(function(core) { if(typeof define === 'function' && define.amd) { define('clique', function() { var clique; clique = window.Clique || core(window, window.jQuery, window.document); clique.load = function(res, req, onload, config) { var base, i, load, resource, resources; resources = res.split(','); load = []; base = (config.config && config.config.clique && config.config.clique.base ? config.config.clique.base : '').replace(/\/+$/g, ''); if(!base) { throw new Error('Please define base path to Clique in the requirejs config.'); } i = 0; while(i < resources.length) { resource = resources[i].replace(/\./g, '/'); load.push(base + '/components/' + resource); i += 1; } req(load, function() { onload(clique); }); }; return clique; }); } if(!window.jQuery) { throw new Error('Clique requires jQuery'); } if(window && window.jQuery) { core(window, window.jQuery, window.document); } })(function(global, $, doc) { var hovercls, hoverset, selector, _c, _cTEMP; _c = {}; _cTEMP = window.Clique; _c.version = '1.0.4'; _c.noConflict = function() { if(_cTEMP) { window.Clique = _cTEMP; $.Clique = _cTEMP; $.fn.clique = _cTEMP.fn; } return _c; }; _c.prefix = function(str) { return str; }; _c.$ = $; _c.$doc = $(document); _c.$win = $(window); _c.$html = $('html'); _c.fn = function(command, options) { var args, cmd, component, method; args = arguments; cmd = command.match(/^([a-z\-]+)(?:\.([a-z]+))?/i); component = cmd[1]; method = cmd[2]; if(!method && typeof options === 'string') { method = options; } if(!_c[component]) { $.error('Clique component [' + component + '] does not exist.'); return this; } return this.each(function() { var $this, data; $this = $(this); data = $this.data(component); if(!data) { $this.data(component, data = _c[component](this, (method ? void 0 : options))); } if(method) { data[method].apply(data, Array.prototype.slice.call(args, 1)); } }); }; _c.support = { requestAnimationFrame: window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(callback) { setTimeout(callback, 1e3 / 60); }, touch: 'ontouchstart' in window && navigator.userAgent.toLowerCase().match(/mobile|tablet/) || global.DocumentTouch && document instanceof global.DocumentTouch || global.navigator.msPointerEnabled && global.navigator.msMaxTouchPoints > 0 || global.navigator.pointerEnabled && global.navigator.maxTouchPoints > 0 || false, mutationobserver: global.MutationObserver || global.WebKitMutationObserver || null }; _c.support.transition = (function() { var transitionEnd; transitionEnd = (function() { var element, name, transEndEventNames; element = doc.body || doc.documentElement; transEndEventNames = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' }; for(name in transEndEventNames) { if(element.style[name] !== undefined) { return transEndEventNames[name]; } } })(); return transitionEnd && { end: transitionEnd }; })(); _c.support.animation = (function() { var animationEnd; animationEnd = (function() { var animEndEventNames, element, name; element = doc.body || doc.documentElement; animEndEventNames = { WebkitAnimation: 'webkitAnimationEnd', MozAnimation: 'animationend', OAnimation: 'oAnimationEnd oanimationend', animation: 'animationend' }; for(name in animEndEventNames) { if(element.style[name] !== undefined) { return animEndEventNames[name]; } } })(); return animationEnd && { end: animationEnd }; })(); _c.utils = { now: Date.now || function() { return new Date().getTime(); }, isString: function(obj) { return Object.prototype.toString.call(obj) === '[object String]'; }, isNumber: function(obj) { return !isNaN(parseFloat(obj)) && isFinite(obj); }, isDate: function(obj) { var d; d = new Date(obj); return d !== "Invalid Date" && d.toString() !== "Invalid Date" && !isNaN(d); }, str2json: function(str, notevil) { var e, newFN; try { if(notevil) { return JSON.parse(str.replace(/([\$\w]+)\s* :/g, function(_, $1) { return '"' + $1 + '" :'; }).replace(/'([^']+)'/g, function(_, $1) { return '"' + $1 + '"'; })); } else { newFN = Function; return new newFN('', 'var json = ' + str + '; return JSON.parse(JSON.stringify(json));')(); } } catch(_error) { e = _error; return false; } }, debounce: function(func, wait, immediate) { return function() { var args, callNow, context, later, timeout; context = this; args = arguments; later = function() { var timeout; timeout = null; if(!immediate) { func.apply(context, args); } }; callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if(callNow) { func.apply(context, args); } }; }, removeCssRules: function(selectorRegEx) { if(!selectorRegEx) { return; } setTimeout(function() { var idx, idxs, stylesheet, _i, _j, _k, _len, _len1, _len2, _ref; try { _ref = document.styleSheets; _i = 0; _len = _ref.length; while(_i < _len) { stylesheet = _ref[_i]; idxs = []; stylesheet.cssRules = stylesheet.cssRules; idx = _j = 0; _len1 = stylesheet.cssRules.length; while(_j < _len1) { if(stylesheet.cssRules[idx].type === CSSRule.STYLE_RULE && selectorRegEx.test(stylesheet.cssRules[idx].selectorText)) { idxs.unshift(idx); } idx = ++_j; } _k = 0; _len2 = idxs.length; while(_k < _len2) { stylesheet.deleteRule(idxs[_k]); _k++; } _i++; } } catch(_error) {} }, 0); }, isInView: function(element, options) { var $element, left, offset, top, window_left, window_top; $element = $(element); if(!$element.is(':visible')) { return false; } window_left = _c.$win.scrollLeft(); window_top = _c.$win.scrollTop(); offset = $element.offset(); left = offset.left; top = offset.top; options = $.extend({ topoffset: 0, leftoffset: 0 }, options); if(top + $element.height() >= window_top && top - options.topoffset <= window_top + _c.$win.height() && left + $element.width() >= window_left && left - options.leftoffset <= window_left + _c.$win.width()) { return true; } else { return false; } }, checkDisplay: function(context, initanimation) { var elements; elements = $('[data-margin], [data-row-match], [data-row-margin], [data-check-display]', context || document); if(context && !elements.length) { elements = $(context); } elements.trigger('display.clique.check'); if(initanimation) { if(typeof initanimation !== 'string') { initanimation = '[class*="animation-"]'; } elements.find(initanimation).each(function() { var anim, cls, ele; ele = $(this); cls = ele.attr('class'); anim = cls.match(/animation\-(.+)/); ele.removeClass(anim[0]).width(); ele.addClass(anim[0]); }); } return elements; }, options: function(string) { var options, start; if($.isPlainObject(string)) { return string; } start = string ? string.indexOf('{') : -1; options = {}; if(start !== -1) { try { options = _c.utils.str2json(string.substr(start)); } catch(_error) {} } return options; }, animate: function(element, cls) { var d; d = $.Deferred(); element = $(element); cls = cls; element.css('display', 'none').addClass(cls).one(_c.support.animation.end, function() { element.removeClass(cls); d.resolve(); }).width(); element.css({ display: '' }); return d.promise(); }, uid: function(prefix) { return(prefix || 'id') + _c.utils.now() + 'RAND' + Math.ceil(Math.random() * 1e5); }, template: function(str, data) { var cmd, fn, i, newFN, openblocks, output, prop, toc, tokens; tokens = str.replace(/\n/g, "\\n").replace(/\{\{\{\s*(.+?)\s*\}\}\}/g, "{{!$1}}").split(/(\{\{\s*(.+?)\s*\}\})/g); i = 0; output = []; openblocks = 0; while(i < tokens.length) { toc = tokens[i]; if(toc.match(/\{\{\s*(.+?)\s*\}\}/)) { i = i + 1; toc = tokens[i]; cmd = toc[0]; prop = toc.substring((toc.match(/^(\^|\#|\!|\~|\:)/) ? 1 : 0)); switch(cmd) { case '~': output.push('for(var $i = 0; $i < ' + prop + '.length; $i++) { var $item = ' + prop + '[$i];'); openblocks++; break; case ':': output.push('for(var $key in ' + prop + ') { var $val = ' + prop + '[$key];'); openblocks++; break; case '#': output.push('if(' + prop + ') {'); openblocks++; break; case '^': output.push('if(!' + prop + ') {'); openblocks++; break; case '/': output.push('}'); openblocks--; break; case '!': output.push('__ret.push(' + prop + ');'); break; default: output.push('__ret.push(escape(' + prop + '));'); } } else { output.push('__ret.push(\'' + toc.replace(/\'/g, '\\\'') + '\');'); } i = i + 1; } newFN = Function; fn = new newFN("$data", ["var __ret = [];", "try {", "with($data){", !openblocks ? output.join("") : '__ret = ["Not all blocks are closed correctly."]', "};", "}catch(e){__ret = [e.message];}", 'return __ret.join("").replace(/\\n\\n/g, "\\n");', "function escape(html) { return String(html).replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');}"].join("\n")); if(data) { return fn(data); } else { return fn; } }, events: { click: _c.support.touch ? 'tap' : 'click' } }; window.Clique = _c; $.Clique = _c; $.fn.clique = _c.fn; _c.langdirection = _c.$html.attr('dir') === 'rtl' ? 'right' : 'left'; _c.components = {}; _c.component = function(name, def) { var fn; fn = function(element, options) { var $this; $this = this; this.Clique = _c; this.element = element ? $(element) : null; this.options = $.extend(true, {}, this.defaults, options); this.plugins = {}; if(this.element) { this.element.data('clique.data.' + name, this); } this.init(); (this.options.plugins.length ? this.options.plugins : Object.keys(fn.plugins)).forEach(function(plugin) { if(fn.plugins[plugin].init) { fn.plugins[plugin].init($this); $this.plugins[plugin] = true; } }); this.trigger('init.clique.component', [name, this]); return this; }; fn.plugins = {}; $.extend(true, fn.prototype, { defaults: { plugins: [] }, boot: function() {}, init: function() {}, on: function(a1, a2, a3) { return $(this.element || this).on(a1, a2, a3); }, one: function(a1, a2, a3) { return $(this.element || this).one(a1, a2, a3); }, off: function(evt) { return $(this.element || this).off(evt); }, trigger: function(evt, params) { return $(this.element || this).trigger(evt, params); }, find: function(selector) { return $((this.element ? this.element : [])).find(selector); }, proxy: function(obj, methods) { var $this; $this = this; methods.split(' ').forEach(function(method) { if(!$this[method]) { $this[method] = function() { return obj[method].apply(obj, arguments); }; } }); }, mixin: function(obj, methods) { var $this; $this = this; methods.split(' ').forEach(function(method) { if(!$this[method]) { $this[method] = obj[method].bind($this); } }); }, option: function() { if(arguments.length === 1) { return this.options[arguments[0]] || undefined; } else { if(arguments.length === 2) { this.options[arguments[0]] = arguments[1]; } } } }, def); this.components[name] = fn; this[name] = function() { var element, options; if(arguments.length) { switch(arguments.length) { case 1: if(typeof arguments[0] === 'string' || arguments[0].nodeType || arguments[0] instanceof jQuery) { element = $(arguments[0]); } else { options = arguments[0]; } break; case 2: element = $(arguments[0]); options = arguments[1]; } } if(element && element.data('clique.data.' + name)) { return element.data('clique.data.' + name); } return new _c.components[name](element, options); }; if(_c.domready) { _c.component.boot(name); } return fn; }; _c.plugin = function(component, name, def) { this.components[component].plugins[name] = def; }; _c.component.boot = function(name) { if(_c.components[name].prototype && _c.components[name].prototype.boot && !_c.components[name].booted) { _c.components[name].prototype.boot.apply(_c, []); _c.components[name].booted = true; } }; _c.component.bootComponents = function() { var component; for(component in _c.components) { _c.component.boot(component); } }; _c.domObservers = []; _c.domready = false; _c.ready = function(fn) { _c.domObservers.push(fn); if(_c.domready) { fn(document); } }; _c.on = function(a1, a2, a3) { if(a1 && a1.indexOf('ready.clique.dom') > -1 && _c.domready) { a2.apply(_c.$doc); } return _c.$doc.on(a1, a2, a3); }; _c.one = function(a1, a2, a3) { if(a1 && a1.indexOf('ready.clique.dom') > -1 && _c.domready) { a2.apply(_c.$doc); return _c.$doc; } return _c.$doc.one(a1, a2, a3); }; _c.trigger = function(evt, params) { return _c.$doc.trigger(evt, params); }; _c.domObserve = function(selector, fn) { if(!_c.support.mutationobserver) { return; } fn = fn || function() {}; $(selector).each(function() { var $element, element, observer; element = this; $element = $(element); if($element.data('observer')) { return; } try { observer = new _c.support.mutationobserver(_c.utils.debounce(function(mutations) { fn.apply(element, []); $element.trigger('changed.clique.dom'); }, 50)); observer.observe(element, { childList: true, subtree: true }); $element.data('observer', observer); } catch(_error) {} }); }; _c.delay = function(fn, timeout, args) { if(timeout == null) { timeout = 0; } fn = fn || function() {}; return setTimeout(function() { return fn.apply(null, args); }, timeout); }; _c.on('domready.clique.dom', function() { _c.domObservers.forEach(function(fn) { fn(document); }); if(_c.domready) { _c.utils.checkDisplay(document); } }); $(function() { _c.$body = $('body'); _c.ready(function(context) { _c.domObserve('[data-observe]'); }); _c.on('changed.clique.dom', function(e) { var ele; ele = e.target; _c.domObservers.forEach(function(fn) { fn(ele); }); _c.utils.checkDisplay(ele); }); _c.trigger('beforeready.clique.dom'); _c.component.bootComponents(); setInterval((function() { var fn, memory; memory = { x: window.pageXOffset, y: window.pageYOffset }; fn = function() { var dir; if(memory.x !== window.pageXOffset || memory.y !== window.pageYOffset) { dir = { x: 0, y: 0 }; if(window.pageXOffset !== memory.x) { dir.x = (window.pageXOffset > memory.x ? 1 : -1); } if(window.pageYOffset !== memory.y) { dir.y = (window.pageYOffset > memory.y ? 1 : -1); } memory = { dir: dir, x: window.pageXOffset, y: window.pageYOffset }; _c.$doc.trigger('scrolling.clique.dom', [memory]); } }; if(_c.support.touch) { _c.$html.on('touchmove touchend MSPointerMove MSPointerUp pointermove pointerup', fn); } if(memory.x || memory.y) { fn(); } return fn; })(), 15); _c.trigger('domready.clique.dom'); if(_c.support.touch) { if(navigator.userAgent.match(/(iPad|iPhone|iPod)/g)) { _c.$win.on('load orientationchange resize', _c.utils.debounce((function() { var fn; fn = function() { $('.height-viewport').css('height', window.innerHeight); return fn; }; return fn(); })(), 100)); } } _c.trigger('afterready.clique.dom'); _c.domready = true; }); if(_c.support.touch) { hoverset = false; hovercls = 'hover'; selector = '.overlay, .overlay-hover, .overlay-toggle, .animation-hover, .has-hover'; _c.$html.on('touchstart MSPointerDown pointerdown', selector, function() { if(hoverset) { $('.' + hovercls).removeClass(hovercls); } hoverset = $(this).addClass(hovercls); }).on('touchend MSPointerUp pointerup', function(e) { var exclude; exclude = $(e.target).parents(selector); if(hoverset) { hoverset.not(exclude).removeClass(hovercls); } }); } $.expr[':'].on = function(obj) { return $(obj).prop('on'); }; return _c; });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const THREE = SupEngine.THREE; class SelectionBox extends SupEngine.ActorComponent { constructor(actor) { super(actor, "SelectionBox"); this.geometry = new THREE.Geometry(); for (let i = 0; i < 24; i++) this.geometry.vertices.push(new THREE.Vector3(0, 0, 0)); this.line = new THREE.LineSegments(this.geometry, new THREE.LineBasicMaterial({ color: 0x00ffff, opacity: 1, depthTest: false, depthWrite: false, transparent: true })); this.actor.threeObject.add(this.line); this.line.updateMatrixWorld(false); this.line.visible = false; } setIsLayerActive(active) { this.line.visible = active && this.target != null; } setTarget(target) { this.target = target; this.line.visible = this.target != null; if (this.target != null) { this.move(); this.resize(); } } move() { this.actor.threeObject.position.copy(this.target.getWorldPosition()); this.actor.threeObject.quaternion.copy(this.target.getWorldQuaternion()); this.actor.threeObject.updateMatrixWorld(false); } resize() { const vec = new THREE.Vector3(); const box = new THREE.Box3(); const inverseTargetMatrixWorld = new THREE.Matrix4().compose(this.target.getWorldPosition(), this.target.getWorldQuaternion(), { x: 1, y: 1, z: 1 }); inverseTargetMatrixWorld.getInverse(inverseTargetMatrixWorld); this.target.traverse((node) => { const geometry = node.geometry; if (geometry != null) { node.updateMatrixWorld(false); if (geometry instanceof THREE.Geometry) { const vertices = geometry.vertices; for (let i = 0, il = vertices.length; i < il; i++) { vec.copy(vertices[i]).applyMatrix4(node.matrixWorld).applyMatrix4(inverseTargetMatrixWorld); box.expandByPoint(vec); } } else if (geometry instanceof THREE.BufferGeometry && geometry.attributes["position"] != null) { const positions = geometry.attributes["position"].array; for (let i = 0, il = positions.length; i < il; i += 3) { vec.set(positions[i], positions[i + 1], positions[i + 2]); vec.applyMatrix4(node.matrixWorld).applyMatrix4(inverseTargetMatrixWorld); box.expandByPoint(vec); } } } }); const min = box.min; const max = box.max; // Front this.geometry.vertices[0].set(max.x, min.y, min.z); this.geometry.vertices[1].set(min.x, min.y, min.z); this.geometry.vertices[2].set(min.x, min.y, min.z); this.geometry.vertices[3].set(min.x, max.y, min.z); this.geometry.vertices[4].set(min.x, max.y, min.z); this.geometry.vertices[5].set(max.x, max.y, min.z); this.geometry.vertices[6].set(max.x, max.y, min.z); this.geometry.vertices[7].set(max.x, min.y, min.z); // Back this.geometry.vertices[8].set(min.x, max.y, max.z); this.geometry.vertices[9].set(max.x, max.y, max.z); this.geometry.vertices[10].set(max.x, max.y, max.z); this.geometry.vertices[11].set(max.x, min.y, max.z); this.geometry.vertices[12].set(max.x, min.y, max.z); this.geometry.vertices[13].set(min.x, min.y, max.z); this.geometry.vertices[14].set(min.x, min.y, max.z); this.geometry.vertices[15].set(min.x, max.y, max.z); // Lines this.geometry.vertices[16].set(max.x, min.y, min.z); this.geometry.vertices[17].set(max.x, min.y, max.z); this.geometry.vertices[18].set(max.x, max.y, min.z); this.geometry.vertices[19].set(max.x, max.y, max.z); this.geometry.vertices[20].set(min.x, max.y, min.z); this.geometry.vertices[21].set(min.x, max.y, max.z); this.geometry.vertices[22].set(min.x, min.y, min.z); this.geometry.vertices[23].set(min.x, min.y, max.z); this.geometry.verticesNeedUpdate = true; } _destroy() { this.actor.threeObject.remove(this.line); this.line.geometry.dispose(); this.line.material.dispose(); this.line = null; super._destroy(); } } exports.default = SelectionBox;
'use strict' const axios = require('axios') const apiUrl = '/api' function getUser (username) { return axios.get(apiUrl + `/users/${username}`) } function postUser (user = {}) { return axios.post(apiUrl + '/users', user) } function getCurrentUser () { return axios.get(apiUrl + '/me') } function putCurrentUser (user = {}) { var userData = {} for (var index in user) { if (user[index] !== '') userData[index] = user[index] } return axios.put(apiUrl + '/me', userData) } function postLog (user = {}) { return axios.post(apiUrl + '/auth/local', user) } function getAdorableAvatar (username = '') { return axios.get(`https://api.adorable.io/avatars/${username}.png`) } function logout () { return axios.get(apiUrl + '/auth/logout') } function recoverPassword (email) { return axios.post(apiUrl + '/auth/recover', { email: email }) } module.exports = { getUser, postUser, getCurrentUser, putCurrentUser, postLog, getAdorableAvatar, logout, recoverPassword }
/* * productSearchApi.js * * Copyright (c) 2016 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ 'use strict'; /** * API to support viewing and updating product discontinue rules. * * @author m594201 * @since 2.0.2 */ (function () { angular.module('productMaintenanceUiApp').factory('ProductSearchApi', productSearchApi); productSearchApi.$inject = ['urlBase', '$resource']; /** * Constructs the API to call the backend functions related to product searches. * * @param urlBase The Base URL for the back-end. * @param $resource Angular $resource factory used to create the API. * @returns {*} */ function productSearchApi(urlBase, $resource) { return $resource(null, null, { 'getClassesByRegularExpression': { method: 'GET', url: urlBase + '/pm/productHierarchy/itemClass/findByRegularExpression', isArray: false }, 'getCommoditiesByRegularExpression': { method: 'GET', url: urlBase + '/pm/productHierarchy/commodity/findByRegularExpression', isArray: false }, 'getSubDepartmentsByRegularExpression': { method: 'GET', url: urlBase + '/pm/subDepartment', isArray: false }, 'getSubCommoditiesByRegularExpression': { method: 'GET', url: urlBase + '/pm/productHierarchy/subCommodity/findByRegularExpression', isArray: false }, 'getBDMByRegularExpression': { method: 'GET', url: urlBase + '/pm/bdm', isArray: false }, 'queryVertexTaxCategories': { method: 'GET', url:urlBase + '/pm/vertex', isArray: true }, 'queryVertexQualifyingConditions': { method: 'GET', url:urlBase + '/pm/vertex/qualifyingConditions', isArray: true }, 'queryFulfilmentChannels': { method: 'GET', url:urlBase + '/pm/salesChannel/fulfilmentChannel', isArray: true }, 'findSubCommoditiesByCommodity': { method: 'GET', url: urlBase + '/pm/productHierarchy/subCommodity/findByCommodity', isArray: true } }); } })();
const webpack = require('webpack'); const path = require('path'); const nodeExternals = require('webpack-node-externals'); const SRC_DIR = path.join(__dirname, '/client/src'); const DIST_DIR = path.join(__dirname, '/client/dist'); module.exports = [{ entry: path.resolve(__dirname, '.', 'server/server.js'), output: { path: path.resolve(__dirname, '.', 'dist'), publicPath: '/dist/', filename: 'server.js', }, node: { __dirname: false, __filename: false, }, target: 'node', externals: nodeExternals(), module: { loaders: [ { test: /\.jsx?$/, loader: 'babel-loader', }, { test: /\.css$/, use: [ 'isomorphic-style-loader', { loader: 'css-loader', options: { importLoaders: 1, }, }, ], }, ], } }, { entry: `${SRC_DIR}/index.jsx`, node: { __dirname: false, __filename: false, }, output: { filename: 'bundle.js', path: DIST_DIR, }, module: { loaders: [ { test: /\.jsx?/, include: SRC_DIR, loader: 'babel-loader', query: { presets: ['react', 'env'], }, }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, resolve: { alias: { react: path.resolve(__dirname, 'node_modules', 'react'), }, }, }, ];
const Route = $.router; /** * All "/api" routes are defined here. */ Route.path('/api').middleware('Api'); Route.path('/api', () => { Route.post('@connect'); Route.get('@all'); Route.post('@add'); Route.delete('@delete'); Route.all('*', 'notFound'); }).controller('Api', true).as('api');
// https://www.hackerrank.com/challenges/the-birthday-bar/problem const solve = (chocNums, dayOfBirth, monthOfBirth) => { const targetLength = monthOfBirth; const targetSum = dayOfBirth; const validChocNumSeqs = chocNums.filter((chocNum, chocNumIdx) => { const sliceEnd = chocNumIdx + targetLength; const chocNumSeq = chocNums.slice(chocNumIdx, sliceEnd); const chocNumSeqSum = chocNumSeq.reduce((sum, chocNum) => sum + chocNum, 0); const isValidSum = chocNumSeqSum === targetSum; return isValidSum; }); return validChocNumSeqs.length; };
define([ 'angular' , '../module' , '../namespace' ], function (angular, module, namespace) { 'use strict'; var name = namespace + '.TopicController'; module.controller(name, TopicController); TopicController.$inject = ['$scope', '$timeout', '$ionicLoading', '$ionicPopover' , '$ionicModal', '$stateParams', namespace + '.topicService']; return TopicController; function TopicController($scope, $timeout, $ionicLoading, $ionicPopover , $ionicModal, $stateParams, topicService) { var vm = this; var attributes = { group: {name: 'Group Name' , slug: 'group-slug' } , topic: {} , replyTo: '' // for modal reply , replyContent: '' }; var methods = { openPopover: openPopover , closePopover: closePopover , openModal: openModal , closeModal: closeModal }; vm = angular.extend(vm, attributes, methods); $scope.vm = vm; $ionicLoading.show({noBackdrop: true}); topicService.getTopic($stateParams.id) .then(function(topic){ vm.topic = topic; vm.replyTo = topic.title; $ionicLoading.hide(); } , function(error){ $timeout(function(){ $ionicLoading.show({ template: 'Load Failed! Retry later', noBackdrop: true, duration: 2000 }); }, 500); }); /* vm.replies = []; vm.moreDataCanBeLoaded = moreDataCanBeLoaded; vm.loadMore = loadMore; */ $ionicPopover.fromTemplateUrl('app/group/templates/topic_popover.html', { scope: $scope }).then(function(popover) { $scope.popover = popover; }); $ionicModal.fromTemplateUrl('app/group/templates/reply_modal.html', { scope: $scope , animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal; }); function openPopover($event) { $scope.popover.show($event); }; function closePopover() { $scope.popover.hide(); }; function openModal($event) { $scope.modal.show($event); }; function closeModal() { $scope.modal.hide(); }; //Cleanup the popover when we're done with it! $scope.$on('$destroy', function() { $scope.popover.remove(); $scope.modal.remove(); }); /* // replies replyService.getTopicReplies($stateParams.id) .then(function(replies){ vm.replies = replies; } , function(error){ $timeout(function(){ $ionicLoading.show({ template: 'Load Failed! Retry later', noBackdrop: true, duration: 2000 }); }, 500); }); function moreDataCanBeLoaded(){ // return true will trigger loadMore function var result = vm.replies.length > 2 && vm.replies.length <= 30; return result; } function loadMore(){ replyService.getTopicReplies($stateParams.id) .then(function(replies){ for(var i=0; i<replies.length; i++){ vm.replies.push(replies[i]); } $scope.$broadcast('scroll.infiniteScrollComplete'); } , function(error){ $timeout(function(){ $ionicLoading.show({ template: 'Load Failed! Retry later', noBackdrop: true, duration: 2000 }); $scope.$broadcast('scroll.infiniteScrollComplete'); }, 500); }); } */ } });
'use strict'; angular.module('qul.env', []);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // EXPRESS const express_1 = require("express"); // MODELS const gruposModel_1 = require("../models/gruposModel"); var gruposRouter = express_1.Router(); // ================================================================= //-- Obtener todos los grupos // ================================================================= gruposRouter.get('/', (req, resp) => { gruposModel_1.gruposModel.find() // .populate('maestro', 'nombre correo img') .populate('usuarios', 'nombre') .exec((error, grupos) => { if (error) { return resp.status(400).json({ ok: false, message: 'Error al buscar grupos', errors: error }); } resp.status(200).json({ ok: true, grupos: grupos }); }); }); // ================================================================= //-- Crear nuevo grupo // ================================================================= gruposRouter.post('/', (req, resp) => { var body = req.body; var grupo = new gruposModel_1.gruposModel({ nombre: body.nombre, hora: body.hora, grupo: body.grupo, maestro: body.maestro }); grupo.save((error, grupoCreado) => { if (error) { return resp.status(400).json({ ok: false, message: 'Error al crear grupo', errors: error }); } resp.status(200).json({ ok: true, grupo: grupoCreado }); }); }); // ================================================================= //-- Agregar un usuario a un grupo en especifico // ================================================================= gruposRouter.put('/:id', (req, resp) => { var id = req.params.id; var body = req.body; // AGREGAR USUARIO AL GRUPO gruposModel_1.gruposModel.findById(id, (error, grupo) => { if (error) { return resp.status(400).json({ ok: false, mensaje: 'Error al encontrar grupo', errors: error }); } if (!grupo) { return resp.status(400).json({ ok: false, message: 'No existe un grupo con el id indicado' }); } for (let i = 0; i < grupo.usuarios.length; i++) { const element = grupo.usuarios[i]; if (element == body.usuario) { return resp.status(400).json({ ok: false, mensaje: 'El usuario ya esta registrado en el grupo' }); } } grupo.update({ $push: { usuarios: body.usuario } }, (error, grupoActualizado) => { if (error) { return resp.status(400).json({ ok: false, mensaje: 'Error al actualizar grupo' }); } resp.status(200).json({ ok: true, grupo: grupoActualizado, }); }); }); }); // ================================================================= //-- Guardar mensajes de los usuarios en el grupo // ================================================================= gruposRouter.put('/:id/mensaje', (req, resp) => { var id = req.params.id; var body = req.body; var date = new Date().toLocaleString(); if (body.mensaje == '' || body.mensaje == null || body.mensaje == ' ') { return resp.json({ ok: false, mensaje: 'El campo no puede ir vacio' }); } var mensaje = ({ usuario: body.usuario, mensaje: body.mensaje, fecha: date }); gruposModel_1.gruposModel.findById(id, (error, grupo) => { if (error) { return resp.status(400).json({ ok: false, mensaje: 'Error al buscar grupo', errors: error }); } if (!grupo) { return resp.status(400).json({ ok: false, mensaje: 'No existe un grupo con el id ingresado' }); } grupo.update({ $push: { mensajes: mensaje } }, (error, mensajeEnviado) => { if (error) { return resp.status(400).json({ ok: false, mensaje: 'Error al enviar el mensaje', errors: error }); } resp.status(200).json({ ok: true, mensaje: mensajeEnviado, fecha: date }); }); }); }); // ================================================================= //-- Guardar comentario de una publicacion de un grupo // ================================================================= gruposRouter.put('/:idGrupo/comentario/:idMensaje', (req, resp) => { var idGrupo = req.params.idGrupo; var idMensaje = req.params.idMensaje; var body = req.body; var date = new Date().toLocaleString(); if (body.comentario == '' || body.comentario == null || body.comentario == ' ') { return resp.json({ ok: false, falla: '02', mensaje: 'El campo no puede ir vacio' }); } var comentario = { usuario: body.usuario, comentario: body.comentario, fecha: date }; gruposModel_1.gruposModel.findById(idGrupo, (error, grupoBD) => { if (error) { return resp.json({ ok: false, mensaje: 'Error al buscar grupo', errors: error }); } if (!grupoBD) { return resp.json({ ok: false, mensaje: `No existe el grupo con el id: ${idGrupo}` }); } for (let i = 0; i < grupoBD.mensajes.length; i++) { const element = grupoBD.mensajes[i]; if (element._id == idMensaje) { element.comentarios.push(comentario); } } gruposModel_1.gruposModel.findByIdAndUpdate(idGrupo, grupoBD, (error, grupoActualizado) => { if (error) { return resp.json({ ok: false, mensaje: 'Error al actualizar comentario del grupo', errors: error }); } resp.json({ ok: true, grupoActualizado }); }); }); }); // ================================================================= //-- Eliminar Grupo por ID // ================================================================= gruposRouter.delete('/eliminar/:id', (req, resp) => { var id = req.params.id; gruposModel_1.gruposModel.findByIdAndRemove(id, (error, grupo) => { if (error) { return resp.status(400).json({ ok: false, mensaje: 'Error al encontrar grupo', errors: error }); } if (!grupo) { return resp.status(400).json({ ok: false, messages: { message: `No existe un grupo con el id ${id}` } }); } return resp.status(200).json({ ok: true, grupoEliminado: grupo }); }); }); // gruposRouter.delete('/usuario/:id', (req: Request, resp: Response) => { // var id = req.params.id; // resp.status(200).json({ // ok:true, // id // }) // }) gruposRouter.get('/info/:idGrupo', (req, res) => { var id = req.params.idGrupo; gruposModel_1.gruposModel.findById(id) .populate('usuarios', 'nombre correo img') .populate('maestro', 'nombre correo img') .exec((error, grupo) => { if (error) { return res.json({ ok: false, mensaje: 'Error al buscar grupo por id', errors: error }); } if (!grupo) { return res.json({ ok: true, mensaje: `No existe un grupo con el id: ${id}`, }); } res.json({ ok: true, grupo }); }); }); exports.default = gruposRouter;
var splitInteger = function(num, parts) { let result = []; if (parts === 1) { result = [num]; return result; } else if (num%parts === 0){ let element = num/parts ; for (let i =0 ; i < parts; i++) { result.push(element); } return result; } else if (num%parts !== 0) { let min = Math.floor(num/parts); let remainder = num - min * parts; let max = min + remainder/remainder; for (let y = 0; y < parts - remainder; y++) { result.push(min); } console.log(result); for (let z = 0; z < remainder; z++){ result.push(max); } return result; } }
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('fancy-album', 'Integration | Component | fancy album', { integration: true }); test('album renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.set('albumToPass', { name: 'We are the champions', artist: 'Queen', albumArtUrl: '' }); this.render(hbs`{{fancy-album album=albumToPass}}`); assert.equal(this.$('.album__desc__title').text().trim(), 'We are the champions', 'It shows the title'); assert.equal(this.$('.album__desc__artist').text().trim(), 'by Queen', 'it shows the artist'); });
webix.ui({ view: "window" , move: false , id: "deal_refund_window" , height: 480 , width: 640 , position: "center" , head: { view: "toolbar", cols: [ {view: "label", label: "Возврат займа"} , { view: "button", value: "Закрыть", width: 100, click: function () { deal_refund_clean_and_close(); } } ] }, body: { view: "form", id: "deal_refund_form", elements: [ { view: "text", labelWidth: 200, id: "refund_dealId", name: "refund_dealId", label: "ID Сделки", hidden: true } , { view: "text", labelWidth: 200, id: "refund_dealGivenSum", name: "refund_dealGivenSum", label: "Сумма инвестирования", readonly: true } , { view: "text", labelWidth: 200, id: "refund_dealRefundSum", name: "refund_dealRefundSum", label: "Сумма возврата", readonly: true } , { view: "text", labelWidth: 200, id: "refund_dealCommission", name: "refund_dealCommission", label: "Комиссия агента", readonly: true } , { view: "text", labelWidth: 200, id: "refund_result", name: "refund_result", label: "Итого к возврату", readonly: true } , { cols: [ {}, { view: "button", value: "Подтвердить", type: "form", click: function () { deals_refund($$("refund_dealId").getValue()); deal_refund_clean_and_close(); } } ] } ] } }); function deal_refund_clean_and_close() { $$("refund_dealGivenSum").setValue(""); $$("refund_dealRefundSum").setValue(""); $$("refund_dealCommission").setValue(""); $$("refund_result").setValue(""); $$("deal_refund_window").hide(); $$("index_page").enable(); }
'use strict' var gProjects = []; var gCurrProject = {}; function createProjects() { gProjects.push(createProject(getRandomID(), "minesweeper", "minesweeper-master", "try not to get blown up in this classic arcade game", "img/portfolio/minesweeper.jpg", 1575292950179, "excercise for coding academy", ["life simulation", "js"])); gProjects.push(createProject(getRandomID(), "Who Is?", "who-is", "let me guess who you're thinking about", "img/portfolio/who-is.jpg", 1575292950179, "excercise for coding academy", ["life simulation", "js"])); gProjects.push(createProject(getRandomID(), "Game Of Life", "game-of-life", "watch them grow", "img/portfolio/game-of-life.jpg", 1575292950179, "excercise for coding academy", ["life simulation", "js"])); gProjects.push(createProject(getRandomID(), "Touch the Nums", "touch-nums", "touch numbers in order", "img/portfolio/touch.jpg", 1575292950179, "excercise for coding academy", ["life simulation", "js"])); saveToStorage("projects", gProjects) return gProjects; } function createProject(id, name, title, desc, url, publishedAt, labels) { return { id, name, title, desc, url, publishedAt, labels } } function getProjectsToRender() { return gProjects } function getProjectById(id) { for (var i = 0; i < gProjects.length; i++) { if (gProjects[i].id === id) return gProjects[i]; } return null }
import "./Login.css"; import axios from 'axios' import React, { PropTypes, Component } from "react"; import { Link } from 'react-router-dom' import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; class Login extends Component { constructor(props) { super(props); this.state = { username: '', password: '', errors: '' }; } handleChange = (event) => { const {name, value} = event.target this.setState({ [name]: value }) }; handleSubmit = (event) => { event.preventDefault() const {username, password} = this.state let user = { username: username, password: password } axios.post('/login', {user}, {withCredentials: true}) .then(response => { if (response.data.logged_in) { this.props.handleLogin(response.data) this.redirect(); } else { this.setState({ errors: response.data.errors }) } }) .catch(error => { this.handleErrors(); console.log('api errors:', error) }) }; redirect = () => { this.props.history.push('/') } handleErrors = () => { }; render() { const {username, password} = this.state return ( <div className="Login"> <Form onSubmit={this.handleSubmit}> <Form.Group size="lg" controlId="username"> <Form.Label>Username</Form.Label> <Form.Control autoFocus type="text" name="username" onChange={this.handleChange} /> </Form.Group> <Form.Group size="lg" controlId="password"> <Form.Label>Password</Form.Label> <Form.Control type="password" name="password" onChange={this.handleChange} /> </Form.Group> <Button block size="lg" type="submit"> Login </Button> <div> or <Link to='/signup'>sign up</Link> </div> </Form> </div> ); } } export default Login;
'use strict'; import request from 'supertest'; import bootstrap from '../db-bootstrap'; describe('PUT /api/names', () => { let server; before(done => { bootstrap('name-test-database', (err, body) => { delete require.cache[require.resolve('../../build/server/server')]; server = require('../../build/server/server'); done(); }); }) after(done => { server.close(done); }) it('should respond with 200 ok when a unique name is checked', done => { request(server) .put('/api/names') .send({name: 'A really cool test'}) .set('Accept', 'application/json') .expect(200, {status: 'ok'}) .end(err => done(err)); }) it('should respond with 409 NOT_UNIQUE when a name is already in the db', done => { let agent = request.agent(server); agent .put('/api/names') .send({name: 'not unique'}) .set('Accept', 'application/json') .expect(409, {status: 'NOT_UNIQUE'}) .end(err => done(err)) }) it('should respond with 400 VALIDATION_ERROR when the name is formatted incorrectly', done => { request(server) .put('/api/names') .send({name: 'a name that (may) contain some _extra_ characters?'}) .expect(400, {status: 'VALIDATION_ERROR', invalid: ['(', ')', '_', '_', '?']}) .end(err => done(err)); }) })
// Array data structure user = [ { UserId: "123", username: null, password: null, isOnline: "offline", }, { UserId: "123", username: null, password: null, isOnline: "offline", }, ]; rooms = [ { roomId: 456, roomName: "test", messages: [ { userId: "123", messageContent: [], }, ], }, { roomId: 456, roomName: "test", messages: [ { userId: "123", messageContent: [], }, ], }, ]; user = { "12341234": { UserId: "123", username: 'Euge', password: null, isOnline: "offline", }, }; // hash table / dictionary
/** * @license * Copyright (C) 2013 Andrew Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview * Registers a language handler for Erlang. * * Derived from https://raw.github.com/erlang/otp/dev/lib/compiler/src/core_parse.yrl * Modified from Mike Samuel's Haskell plugin for google-code-prettify * * @author achew22@gmail.com */ PR['registerLangHandler']( PR['createSimpleLexer']( [ // Whitespace // whitechar -> newline | vertab | space | tab | uniWhite // newline -> return linefeed | return | linefeed | formfeed [PR['PR_PLAIN'], /^[\t\n\x0B\x0C\r ]+/, null, '\t\n\x0B\x0C\r '], // Single line double-quoted strings. [PR['PR_STRING'], /^\"(?:[^\"\\\n\x0C\r]|\\[\s\S])*(?:\"|$)/, null, '"'], // Handle atoms [PR['PR_LITERAL'], /^[a-z][a-zA-Z0-9_]*/], // Handle single quoted atoms [PR['PR_LITERAL'], /^\'(?:[^\'\\\n\x0C\r]|\\[^&])+\'?/, null, "'"], // Handle macros. Just to be extra clear on this one, it detects the ? // then uses the regexp to end it so be very careful about matching // all the terminal elements [PR['PR_LITERAL'], /^\?[^ \t\n({]+/, null, "?"], // decimal -> digit{digit} // octal -> octit{octit} // hexadecimal -> hexit{hexit} // integer -> decimal // | 0o octal | 0O octal // | 0x hexadecimal | 0X hexadecimal // float -> decimal . decimal [exponent] // | decimal exponent // exponent -> (e | E) [+ | -] decimal [PR['PR_LITERAL'], /^(?:0o[0-7]+|0x[\da-f]+|\d+(?:\.\d+)?(?:e[+\-]?\d+)?)/i, null, '0123456789'] ], [ // TODO: catch @declarations inside comments // Comments in erlang are started with % and go till a newline [PR['PR_COMMENT'], /^%[^\n]*/], // Catch macros //[PR['PR_TAG'], /?[^( \n)]+/], /** * %% Keywords (atoms are assumed to always be single-quoted). * 'module' 'attributes' 'do' 'let' 'in' 'letrec' * 'apply' 'call' 'primop' * 'case' 'of' 'end' 'when' 'fun' 'try' 'catch' 'receive' 'after' */ [PR['PR_KEYWORD'], /^(?:module|attributes|do|let|in|letrec|apply|call|primop|case|of|end|when|fun|try|catch|receive|after|char|integer|float,atom,string,var)\b/], /** * Catch definitions (usually defined at the top of the file) * Anything that starts -something */ [PR['PR_KEYWORD'], /^-[a-z_]+/], // Catch variables [PR['PR_TYPE'], /^[A-Z_][a-zA-Z0-9_]*/], // matches the symbol production [PR['PR_PUNCTUATION'], /^[.,;]/] ]), ['erlang', 'erl']);
const queries = require('../database/queries') var expect = require('chai').expect describe('#provisionSim', () => { it('should provision a simcard', async function () { const simcard = { iccid: 5465476465405465656, imsi: 54654664654854656546, ki: '46641321164654654654', pin1: 3243, puc: 4664956, } const result = await queries.provisionSim(simcard) expect(result).to.include(simcard); }); }) describe('#activateSim', () => { it('should activate a simcard', async function () { const simcard = { iccid: 5465476465405465656, imsi: 54654664654854656546, msisdn: 254705031577, } const result = await queries.activateSim(simcard) expect(result).to.include(simcard); }); }) describe('#querySubscriberInfo', () => { it('should return simcard info', async function () { const simcard = { msisdn: 254705031577, } const result = await queries.querySubscriberInfo(simcard) expect(result).to.include(simcard); }); }) describe('#adjustAccountBalance', () => { it('should increment accountBalance', async function () { const simcard = { msisdn: 254705031577, amount: 40, } const result = await queries.adjustAccountBalance(simcard) expect(result.accountBalance).to.equal(simcard.amount); }); it('should decrement accountBalance', async function () { const simcard = { msisdn: 254705031577, amount: -4, } const result = await queries.adjustAccountBalance(simcard) expect(result.accountBalance).to.equal(36); }); })
export {default as BoardInput} from 'features/view/component/Board/BoardInput' export {default as FindPassword} from 'features/view/component/FindPassword' export {default as Boardlist} from 'features/view/component/Board/Boardlist'
import React from "react"; import { Link } from "react-router-dom"; export default function Home() { return ( <> <div className="homepage"> <Link to="/people" className="homepage__link"> <div className="homepage__link--title"> Browse all Brastlewark&apos;s People &rarr; </div> </Link> </div> </> ); }
X.define("common.layer",function () { var popLayer = { successMsg : function(title,callback){ layer.msg('<span style="margin-left:20px;">'+title+'</span>', { icon: 1, time: 2000 },function(){ callback(); }); }, failMsg : function(title,callback){ layer.msg('<span style="margin-left:20px;">'+title+'</span>', { icon: 2, time: 2000 },function(){ callback(); }); }, sMsg : function(title,callback,area,time,btn,closeBtn){ layer.alert('<div style="padding:40px 15px 20px;;"><i class="iconfont icon-bgcDuiguo" style="color: #00b904;margin-right: 10px"></i>'+title+'</div>', { title:"提示", area: area || ["300px","250px"], time: time, btn: btn || ["确定"], closeBtn: closeBtn, yes : function(index){ callback(index); } }); }, sMsgSucc : function(title,callback,area){ layer.alert('<div class="tac"><i class="iconfont icon-bgcDuiguo" style="color: #00b904;"></i>'+title+'</div>', { title:"提示", area: area || ["200px","200px"], yes : function(index){ callback(index); } }); }, sChange : function(content ,title,callback,area){ layer.open({ type : 1, content:content, title :title, area: area || ["500px","535px"], btn:["保存"], yes : function(index){ callback(index); } }); }, successConfirm : function(content ,callback,title){ layer.confirm(content ,{title:title || "提示"}, function(index){ callback(); }); }, closeIt : function(index){ layer.close(index); }, successChange : function(content ,title, callback){ layer.confirm(content ,{title:title}, function(index){ callback(index); }); }, layerImg:function(content){ layer.open({ type: 1, title: false, area: function(){ var imgarea = [$(content).width(), $(content).height()]; var winarea = [$(window).width() - 50, $(window).height() - 50]; if(imgarea[0] > winarea[0]){ imgarea[0] = winarea[0]; imgarea[1] = imgarea[0]*img.height/img.width; } return [imgarea[0]+'px', imgarea[1]+'px']; }(), content: content }); }, layerOpen:function(opt){ layer.open({ type: opt.type || 1, title: opt.title ||false, closeBtn: opt.closeBtn || 0, area: opt.area || false, skin: opt.skin || false, //没有背景色 shadeClose: opt.shadeClose || false, btn: opt.btn || false, time: opt.time, content: opt.content || "", success:function(){ opt.callback && opt.callback(); }, yes:function(){ opt.yes && opt.yes(); } }); }, layerAlert : function(content){ layer.alert(content); }, layerBigImg : function(img){ var index = layer.open({ type: 1, content: img, maxmin: true }); layer.full(index); }, layerPrompt : function(content,callback){ layer.alert(content,function(index){ callback(index); }); }, alert: function(msg) { layer.alert(msg) }, closeAll: function (type) { layer.closeAll(type); } }; return popLayer; });
const express=require('express'); const common=require('../../libs/common'); const mysql=require('mysql'); var db=mysql.createPool({host: 'localhost', user: 'root', password: 'lp1435075638', database: 'learn'}); module.exports=function (){ var router=express.Router(); router.get('/', (req, res)=>{ res.render('admin/login.ejs', {}); }); router.post('/', (req, res)=>{ var username=req.body.username; var password=common.md5(req.body.password+common.MD5_SUFFIX); db.query(`SELECT * FROM admin_table WHERE username='${username}'`, (err, data)=>{ if(err){ console.error(err); res.status(500).send('database error').end(); }else{ if(data.length==0){ res.status(400).send('no this admin').end(); }else{ if(data[0].password==password){ //成功 req.session['admin_id']=data[0].ID; res.redirect('/admin/'); }else{ res.status(400).send('this password is incorrect').end(); } } } }); }); return router; };
angular.module('ddysys.controllers') //--------- 预约列表controller ---------// .controller('AppointmentsCtrl', function($scope, $rootScope, Appointments, $localStorage) { $scope.Appointments = $localStorage.getObject('appointments') || []; $scope.setType = function(type) { $scope.type = type; $rootScope.consultType = $scope.type; Appointments.all(type).then(function(data) { if (!data) return; $scope.appointments = data.list; if (type === '') $localStorage.setObject('appointments', $scope.appointments || []); $scope.$broadcast('scroll.refreshComplete'); }) } $scope.setType(''); $rootScope.setAppointmentType = $scope.setType; $scope.formatDate = Appointments.formatDate; $scope.formatPStatus = Appointments.formatPStatus; }) //--------- 预约详情controller ---------// .controller('AppointmentsDetailCtrl', function($scope, $rootScope, Appointments, $stateParams, $ionicHistory, $system, $ionicPopup) { $scope.appointment = {}; function init() { Appointments.get($stateParams.appointmentId).then(function(data) { if (!data) return; $scope.appointment = data.info; }) } init() $scope.handle = function(id, pStatus, reason) { var confirmPopup = $ionicPopup.confirm({ title: '提示', template: '您确定' + (pStatus === 'Y' ? '同意' : '拒绝') + '该预约请求?' }); confirmPopup.then(function(res) { if(res) { Appointments.handle(id, pStatus, reason).then(function(data) { $system.toast('已处理!') $ionicHistory.goBack(); $rootScope.setAppointmentType(pStatus); }) } else { console.log('You are not sure'); } }); } $scope.formatDate = Appointments.formatDate; $scope.formatPStatus = Appointments.formatPStatus; })
export default { label: 'Antonyms Collection - 1', id: 'antonyms-1', defs: { data: [ `yes, no I, you yesterday, tomorrow young, old early, late cry, laugh`, `fail, pass many, few poor, rich speed, slow cruel, kind above, below`, `left, right always, never bottom, top careful, careless warm, cool east, west`, `bad, good after, before boy, girl near, far dark, light empty, full`, `against,for question, answer brave, coward closed, open day, night found, lost`, `all,none black, white dull, bright cold, hot down, up give, take`, `begin, end lend, borrow broad, narrow come, go dry, wet hate, love`, `out, in heaven, hell here, there large, small loss, win low, high`, `north, south push, pull smooth, rough slim, fat soft, hard them, us`, `true, false tall, short truth, lie loud, quiet loose, tight on, off` ] }, list: [ { id: 'reading', type: 'passage', label: 'Words List', data: { title: 'Antonyms', text: [ `Two words are said to be antonyms, if they have opposite meaning.`, { type: 'hilight', text: `yes × no you × I yesterday × tomorrow young × old early × late cry × laugh` }, { type: 'hilight', text: `fail × pass many × few poor × rich speed × slow cruel × kind above × below` }, { type: 'hilight', text: `left × right always × never bottom × top careful × careless warm × cool east × west` }, { type: 'hilight', text: `bad × good after × before boy × girl close × far dark × light empty × full` }, { type: 'hilight', text: `against × for question × answer brave × coward closed × open day × night found × lost` }, { type: 'hilight', text: `all × none black × white dull × bright cold × hot down × up give × take` }, { type: 'hilight', text: `begin × end lend × borrow broad × narrow come × go dry × wet hate × love` }, { type: 'hilight', text: `out × in heaven × hell here × there large × small loss × win low × high` }, { type: 'hilight', text: `north × south push × pull smooth × rough slim × fat soft × hard them × us` }, { type: 'hilight', text: `true × false tall × short truth × lie loud × quiet loose × tight on × off` } ] } }, { type: 'match', label: 'Match Antonyms', id: 'match', commonData: { title: 'Match Antonyms' }, data: [ { refs: 'data~0' }, { refs: 'data~1' }, { refs: 'data~2' }, { refs: 'data~3' }, { refs: 'data~4' }, { refs: 'data~5' }, { refs: 'data~6' }, { refs: 'data~7' }, { refs: 'data~8' }, { refs: 'data~9' } ] }, { type: 'completeWord', label: 'Write the Antonym', id: 'complete-word', commonData: { lang: 'en', title: 'Type the antonym of the given word.' }, data: [ { refs: 'data~0' }, { refs: 'data~1' }, { refs: 'data~2' }, { refs: 'data~3' }, { refs: 'data~4' }, { refs: 'data~5' }, { refs: 'data~6' }, { refs: 'data~7' }, { refs: 'data~8' }, { refs: 'data~9' } ] }, { type: 'connectLetters', label: 'Pick the word', id: 'connect-letters', commonData: { title: 'Connect the letters from left to right to form the antonym for the below word.', clueFont: 'big' }, data: [ { refs: 'data~0' }, { refs: 'data~1' }, { refs: 'data~2' }, { refs: 'data~3' }, { refs: 'data~4' }, { refs: 'data~5' }, { refs: 'data~6' }, { refs: 'data~7' }, { refs: 'data~8' }, { refs: 'data~9' } ] } ] };
const express = require("express"); const router = new express.Router(); const Book = require("../models/book"); const { validate } = require('jsonschema'); const bookSchema = require(`../schema/bookSchema.json`) const editBookSchema = require(`../schema/editBookSchema.json`) router.get("/", async function (req, res, next) { try { const books = await Book.findAll(req.query); return res.json({ books }); } catch (err) { return next(err); } }); router.get("/:id", async function (req, res, next) { try { const book = await Book.findOne(req.params.id); return res.json({ book }); } catch (err) { return next(err); } }); router.post("/", async function (req, res, next) { try { const result = validate(req.body, bookSchema); if(!result.valid){ return next(result.errors.map(error => error.stack)); } else{ const book = await Book.create(req.body); return res.status(201).json({ book }); } } catch (err) { return next(err); } }); router.patch("/:isbn", async function (req, res, next) { try { const result = validate(req.body, editBookSchema); if(!result.valid){ return next(result.errors.map(error => error.stack)); } else{ const book = await Book.update(req.params.isbn, req.body); return res.json({ book }); } } catch (err) { return next(err); } }); router.delete("/:isbn", async function (req, res, next) { try { await Book.remove(req.params.isbn); return res.json({ message: "Book deleted" }); } catch (err) { return next(err); } }); module.exports = router;
var React = require('react'); var IndexItem = require('./IndexItem'); var Index = React.createClass({ handleItemClick: function (band) { this.props.history.pushState(null, "band/" + band.id); }, render: function(){ var handleItemClick = this.handleItemClick; var bands; if (this.props.bands.length > 0) {bands = this.props.bands.map(function (band, key) { return ( <IndexItem key={key} band={band} clicked={handleItemClick.bind(null, band)}/> ); }); } console.log(bands); return ( <div> <h1>Index</h1> <ul> {bands} </ul> </div> ); } }); module.exports = Index;
import React from 'react' // 测试引用类型的数据的改变对数据的影响 // 因为react采取的是浅比较,所以如果引用类型只是改变了值,引用地址并没有改变,这时候 // 不管是hooks里的依赖项还是作为props的参数,都会被认为值没有改变,因此也不会产生渲染 // 往往这样都与我们的意识违背 function HooksRender() { const [list, setList] = React.useState([]) const [map, setMap] = React.useState({}) React.useEffect(() => { console.log("list state is changed") }, [list]) const onPushData = React.useCallback(() => { setList(prevList => { prevList.push(1) console.log("prevList.....", prevList) return prevList }) }, []) React.useEffect(() => { console.log("map is changes") }, [map]) const onChangeMap = React.useCallback(() => { setMap(prevMap => { prevMap.name = 'tanqq1' return prevMap }) }, []) console.log("parent list", list) console.log("map.......", map) return ( <div> <button style={{ backgroundColor: 'pink' }} onClick={onPushData}>push</button> <button style={{ backgroundColor: 'orange' }} onClick={onChangeMap}>add</button> <HooksRenderChild list={list} /> </div> ) } export default HooksRender export function HooksRenderChild({ list }) { console.log("child list", list) React.useEffect(() => { console.log("child list props is changed") }, [list]) return <div> this is child</div> }
import HSLData from './modules/hsl-data'; const switchLanguage = () => { loadAllMenuData(); }; const loadAllMenuData = async () => { for (const restaurant of restaurants) { try { const parsedMenu = await restaurant.type.getDailyMenu(restaurant.id, languageSetting, today); renderMenu(parsedMenu, restaurant.name); } catch (error) { console.error(error); // notify user if errors with data renderNoDataNotification('No data available..', restaurant.name); } } }; const loadHSLData = async () => { const result = await HSLData.getRidesByStopId(2132208); const stop = result.data.stop; console.log('loadHSLData', stop); const stopElement = document.createElement('div'); stopElement.innerHTML = `<h3>Seuraavat vuorot pysäkiltä ${stop.name}</h3><ul>`; for (const ride of stop.stoptimesWithoutPatterns) { stopElement.innerHTML += `<li>${ride.trip.routeShortName}, ${ride.trip.tripHeadsign}, ${HSLData.formatTime(ride.scheduledDeparture)}</li>`; } stopElement.innerHTML += `</ul>`; document.querySelector('.hsl-data').appendChild(stopElement); }; window.onhashchange = function(){ // render function is called every hash change. render(window.location.hash); }; function render(hashKey) { //first hide all divs let pages = document.querySelectorAll(".page"); for (let i = 0; i < pages.length; ++i) { pages[i].style.display = 'none'; } //...now do same with lis let lis_nav = document.querySelectorAll(".box"); for (let i = 0; i < lis_nav.length; ++i) { lis_nav[i].classList.remove("active"); } //then unhide the one that user selected //console.log(hashKey); switch(hashKey){ case "": pages[0].style.display = 'block'; document.getElementsByClassName("logo").classList.add("active"); break; case "#menu": pages[1].style.display = 'block'; document.getElementById("box1").classList.add("active"); break; case "#time": pages[2].style.display = 'block'; document.getElementById("box2").classList.add("active"); break; case "#weather": pages[3].style.display = 'block'; document.getElementById("box3").classList.add("active"); break; case "#event": pages[4].style.display = 'block'; document.getElementById("box4").classList.add("active"); break; default: pages[0].style.display = 'block'; document.getElementsByClassName("logo").classList.add("active"); }// end switch };//end fn //MENUS -------------------------------------------- const menu = {}; function getMenu () { const today = new Date().toISOString().split('T')[0]; console.log(today); const api = `https://www.sodexo.fi/ruokalistat/output/daily_json/152/${today}`; fetch(api) .then(function(response){ let data = response.json(); console.log(data); return data; }) .then(function(data) { menu.place = data.meta.ref_title; console.log(menu.place); menu.menus = data.courses; var text = ""; var x; var mainContainer = document.getElementById("menus"); var priceContainer = document.getElementById("price"); var dietContainer = document.getElementById("diet"); function addText() { for (x in data.courses){ var text = data.courses[x].title_fi; var prices = data.courses[x].price; var diets = data.courses[x].dietcodes; var price = document.createElement("li"); var dish = document.createElement("li"); var diet = document.createElement("li"); price.textContent = prices; dish.textContent = text; diet.textContent = diets; priceContainer.appendChild(price); mainContainer.appendChild(dish); dietContainer.appendChild(diet); } } addText(text); console.log(menu.menus); }) .then(function(){ displayMenu(); }) function displayMenu() { const place = document.querySelector(".place"); place.innerHTML = menu.place; } }; //WEATHERS --------------------------- const weather = {}; // weather.temperature = { // unit : "celsius" // } // if('geolocation' in navigator){ // navigator.geolocation.getCurrentPosition(setPosition, showError); // }else{ // NotificationElement.style.display = "block"; // NotificationElement.innerHTML = "<p>Browser doesn't support</p>"; // } // function setPosition(position){ // let latitude = position.coords.latitude; // let longitude = position.coords.longitude; // getWeather(latitude, longitude); // } // function showError(error){ // notificationElement.style.display = "block"; // notificationElement.innerHTML = '<p> ${error.message} </p>'; // } function getWeather () { let api = 'http://api.openweathermap.org/data/2.5/forecast?q=Vantaa&appid=86f94b479af9041fc281c8e0829cbe47'; fetch(api) .then(function(response){ let data = response.json(); return data; }) .then(function(data){ weather.tila = data.list[0].main.temp-273.15; weather.iconId = data.list[0].weather[0].icon; weather.list = data.list; const mainContainer = document.querySelector(".day"); const iconContainer = document.querySelector(".icon"); var text = ""; function addList() { for(var i=0; i<weather.list.length; i++){ var everyNinth = (i+1) % 8 === 0; if (everyNinth) { var saa = document.createElement("div"); var icon = document.createElement("div"); weather.tila1 = data.list[i].main.temp-273.15; weather.icon1 = data.list[i].weather[0].icon; saa.innerHTML = weather.tila1.toFixed(0)+"°C"; icon.innerHTML = "<img src='http://openweathermap.org/img/wn/"+weather.icon1+"@2x.png'>"; mainContainer.appendChild(saa); saa.appendChild(icon); console.log(weather.tila1); console.log(data.list[i].weather[0].icon); } }} addList(); }) .then(function(){ displayWeather(); }) function displayWeather() { const place = document.querySelector(".degree"); place.innerHTML = weather.tila.toFixed(0) + "°C"; const iconElement = document.querySelector(".description"); iconElement.innerHTML = "<img src='http://openweathermap.org/img/wn/"+weather.iconId+"@2x.png'/>"; } } // function getWeather () { // const today = "2021-03-03"; /* new Date().toISOString().split('T')[0]; */ // console.log(today); // const api = `https://www.sodexo.fi/ruokalistat/output/daily_json/152/${today}`; // fetch(api) // .then(function(response){ // let data = response.json(); // console.log(data); // return data; // }) // .then(function(data) { // menu.place = data.meta.ref_title; // console.log(menu.place); // menu.menus = data.courses; // var text = ""; // var x; // var mainContainer = document.getElementById("menus"); // for (x in data.courses){ // var dish = document.createElement("li"); // text += data.courses[x].title_fi + data.courses[x].price + // data.courses[x].dietcodes+"<br>"; // dish.innerHTML = text; // } // mainContainer.appendChild(dish); // console.log(menu.menus); // }) // .then(function(){ // displayMenu(); // }) // function displayMenu() { // const place = document.querySelector(".place"); // place.innerHTML = menu.place; // } // } function getDay() { var d = new Date(); var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; var container = document.getElementById("demo"); function addText() { for(i=0; i<5; i++){ var n = d.getDay(); var weekdays = [d.getDay()+n+i]; var day = document.createElement("li"); day.textContent = weekdays; container.appendChild(day); } } addText(d.getDay()); } function init() { getMenu(); getWeather(); loadAllMenuData(); loadHSLData(); } init();
import {AvatarListItemSVG} from "./avatarListItemSVG"; export const MoneyTransfersSVG = () => <AvatarListItemSVG xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z"/> </AvatarListItemSVG>
const mongoose = require("mongoose"); const validator = require("validator"); const productSchema = mongoose.Schema({ name: { type: String, required: true, unique: true }, category: { type: String, required: true }, isActive: { type: Boolean }, details: { description: { type: String, required: true, minLength: 10 }, price: { type: Number, required: true, validate(value) { if (value < 0) { throw new Error("price number has to be a positive value"); } }, }, discount: { type: Number, required: false, default: 0 }, images: { type: [ { type: String, }, ], validate(value) { if (value.length < 2) { throw new Error("array of images must include at least two images"); } }, }, phone: { type: String, minLength: 10, required: true, validate(value) { if (!validator.isMobilePhone(value, "he-IL")) { throw new Error("Not A valid israeli Number"); } }, }, date: { type: Date, required: false, unique: false, default: Date.now(), }, }, }); const productModel = mongoose.model("Product", productSchema); module.exports = productModel;
const rl = require('readline') /** Ask user a question on the commandline and pass received answer to a handler. If the handler does not return true, re-ask until a valid answer was given. @param {string} question - To bee or not to bee? @param {function} [onAnswer] - Handle received answer. If passed, it must return true, to signal an answer is valid, otherwise question is re-asked until handler returns true. Gets "answer" and "io" passed. @param {object} [io] - In- and output-interface from readline-package. @example let question = 'What is the answer to life, the universe and everything?' let onAnswer = (answer) => { if(answer == '42') return true else console.log('Nope, try again.') } askQuestion(question, onAnswer) */ function askQuestion(question, onAnswer, io) { if( ! io) io = rl.createInterface({input:process.stdin,output:process.stdin}) io.resume() io.question(question, answer => { io.pause() // If onAnswer was passed and does not return true, // consider answer as invalid and ask question again: if(onAnswer && onAnswer(answer, question, io) !== true) { askQuestion(question, onAnswer, io) } }) } /** Perform askQuestion() over an array of questions. @param {array} questions - A list of questions to ask. @param {function} [onAnswer] - See description of same param in askQuestion(). @param {function} [onAnswers] - Handle all answers received. Gets "answers" and "io" passed. @param {object} [io] - In- and output-interface from readline-package. @example let questions = ['What can you know?', 'What should you do?', 'What may you hope?'] let onAnswers = answers => console.log('Thanks! Your answers are:', answers) askQuestions(questions, onAnswers) @example // As example above, adding validation for each answer. let onAnswer = (answer, question) { if(question == 'What can you know?' && answer != 'Nothing') return false return true } askQuestions(questions, onAnswers, onAnswer) */ function askQuestions(questions, onAnswers, onAnswer, io) { if(! onAnswers && ! onAnswer) { console.log(` Info: No answer-handlers were specified, all input is lost in space. `) } let answers = [] let i = 0 let onAnswerXt = (answer, question, io) => { if( ! onAnswer || onAnswer(answer, question, io) === true) { answers.push(answer) if(i < questions.length-1) { i += 1 askQuestion(questions[i], onAnswerXt, io) } else { if(onAnswers) onAnswers(answers, io) io.close() return true // end loop } return true } return false } askQuestion(questions[i], onAnswerXt, io) // start loop } module.exports = { askQuestion: askQuestion, askQuestions: askQuestions }
const tipsForCare =[ { topic: "Water Salination", text: "no salty water", temp: "75-80 farenheit" } ] export const careTips = () => { return tipsForCare.slice() }
import React from "react"; import PropTypes from "prop-types"; import Carousel from "./carousel"; import CarouselItem from "./carouselItem"; import { Scrollbars } from "react-custom-scrollbars"; class GreedyCarousel extends React.Component { chunk(myArray, chunk_size) { var i = 0; var chunk; var tempArray = []; for (i = 0; i < myArray.length; i += chunk_size) { chunk = myArray.slice(i, i + chunk_size); tempArray.push(chunk); } return tempArray; } render() { const { children, layout, perTile, squareStackVertical, ...rest } = this.props; const { w, h } = layout; let perCarouselItem = Math.max(1, Math.floor(w / h), Math.floor(h / w)) * perTile; let chunks = this.chunk(children, perCarouselItem); return ( <Carousel hideControls={Boolean(chunks.length == 1)} {...rest}> {chunks.map((chunk, i) => { return ( <CarouselItem key={i}> {chunk.map((child, j) => { var size = 100 / chunk.length + "%"; return ( <Scrollbars autoHide key={j} style={ (squareStackVertical && w > h) || (!squareStackVertical && w >= h) ? { float: "left", position: "relative", height: "100%", width: size } : { position: "relative", width: "100%", height: size } } > {child} </Scrollbars> ); })} </CarouselItem> ); })} </Carousel> ); } } Carousel.PropTypes = { /** Optional: show more items per tile. */ perTile: PropTypes.number, /** The parent layout */ layout: PropTypes.object, /** If Tile is square but has more than one item showing, use squareStackVertical if you want items to stack vertically. */ squareStackVertical: PropTypes.bool }; GreedyCarousel.defaultProps = { rows: 1, columns: 1, perTile: 1, layout: { w: 1, h: 1 }, squareStackVertical: false }; export default GreedyCarousel;
import React from "react"; import { connect } from "react-redux"; import { createStructuredSelector } from "reselect"; import { selectFilteredOrders, selectActiveOrder, selectActiveFilter, selectIsFetching, selectIsLoaded, selectQuery, } from "../../../redux/orders/orders.selectors"; import { selectOrder, removeQuery } from "../../../redux/orders/orders.actions"; import { BriefOrdersContainer, BriefOrder } from "./brief-orders.styles"; import Spinner from "../../spinner/spinner.component"; import Badge from "../../badge/badge.component"; const BriefOrders = ({ orders, activeOrder, activeFilter, setActiveOrder, isFetching, isLoaded, query, removeQuery, }) => ( <BriefOrdersContainer length={!!orders && orders.length}> {isFetching && !isLoaded ? ( <Spinner /> ) : ( !!orders && orders.map(({ data: { formattedDate, name, phone, status } }, idx) => ( <BriefOrder key={idx} active={idx === activeOrder} onClick={() => { setActiveOrder(idx); if (query.length !== 0) removeQuery(); }} > <span>{formattedDate}</span> <span> <b>{name}</b> </span> <span>{phone}</span> {activeFilter === "all" ? ( <Badge status={status} text={status} /> ) : null} </BriefOrder> )) )} </BriefOrdersContainer> ); const mapStateToProps = createStructuredSelector({ orders: selectFilteredOrders, activeOrder: selectActiveOrder, activeFilter: selectActiveFilter, isFetching: selectIsFetching, isLoaded: selectIsLoaded, query: selectQuery, }); const mapDispatchToProps = (dispatch) => ({ setActiveOrder: (order) => dispatch(selectOrder(order)), removeQuery: () => dispatch(removeQuery()), }); export default connect(mapStateToProps, mapDispatchToProps)(BriefOrders);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { handleChange, handleDelete } from '../actions' class UnpackedItem extends Component { render(){ return ( <div className="unpacked__item"> <div class="todo-content"> <input type = "checkbox" onChange = {()=> this.props.dispatch(handleChange(this.props.id))} checked = {this.props.data.done}></input> <p>{this.props.data.value}</p> </div> <button onClick = {()=> this.props.dispatch(handleDelete(this.props.id))}>delete</button> </div> ) } } export default connect()(UnpackedItem);
(function() { 'use strict'; angular .module('iconlabApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider .state('commentaire', { parent: 'entity', url: '/commentaire?page&sort&search', data: { authorities: ['ROLE_ADMIN'], pageTitle: 'Commentaires' }, views: { 'content@': { templateUrl: 'app/entities/commentaire/commentaires.html', controller: 'CommentaireController', controllerAs: 'vm' } }, params: { page: { value: '1', squash: true }, sort: { value: 'id,asc', squash: true }, search: null }, resolve: { pagingParams: ['$stateParams', 'PaginationUtil', function ($stateParams, PaginationUtil) { return { page: PaginationUtil.parsePage($stateParams.page), sort: $stateParams.sort, predicate: PaginationUtil.parsePredicate($stateParams.sort), ascending: PaginationUtil.parseAscending($stateParams.sort), search: $stateParams.search }; }], } }) .state('commentaire-detail', { parent: 'entity', url: '/commentaire/{id}', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'], pageTitle: 'Commentaire' }, views: { 'content@': { templateUrl: 'app/entities/commentaire/commentaire-detail.html', controller: 'CommentaireDetailController', controllerAs: 'vm' } }, resolve: { entity: ['$stateParams', 'Commentaire', function($stateParams, Commentaire) { return Commentaire.get({id : $stateParams.id}).$promise; }] } }) .state('commentaire.new', { parent: 'commentaire', url: '/new', data: { authorities: ['ROLE_ADMIN'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/commentaire/commentaire-dialog.html', controller: 'CommentaireDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { contenu: null, auteur: null, datePost: null, actif: null, id: null }; } } }).result.then(function() { $state.go('commentaire', null, { reload: true }); }, function() { $state.go('commentaire'); }); }] }) .state('app.tacheprojet.newusercomment', { parent: 'app.tacheprojet', url: '/commentaire/new', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/commentaire/commentaire-dialog.html', controller: 'CommentaireDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { contenu: null, datePost: null, actif: null, id: null }; } } }).result.then(function() { $state.go('app.tacheprojet', null, { reload: true }); }, function() { $state.go('app.tacheprojet'); }); }] }) .state('commentaire.edit', { parent: 'commentaire', url: '/{id}/edit', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/commentaire/commentaire-dialog.html', controller: 'CommentaireDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: ['Commentaire', function(Commentaire) { return Commentaire.get({id : $stateParams.id}).$promise; }] } }).result.then(function() { $state.go('commentaire', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('commentaire.delete', { parent: 'commentaire', url: '/{id}/delete', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/commentaire/commentaire-delete-dialog.html', controller: 'CommentaireDeleteController', windowClass:'center-modal', controllerAs: 'vm', size: 'md', resolve: { entity: ['Commentaire', function(Commentaire) { return Commentaire.get({id : $stateParams.id}).$promise; }] } }).result.then(function() { $state.go('commentaire', null, { reload: true }); }, function() { $state.go('^'); }); }] }); } })();
import React from 'react' import firebase from '../firebase' const NavPanel = ({ screen, updateScreen, productsFilter, setProductsFilter }) => { const logout = async () => { await firebase.logout() updateScreen('Login') } return ( <div> <button disabled={screen === 'Main'} onClick={() => updateScreen('Main')} >Главная</button> <button disabled={screen === 'ListSells'} onClick={() => updateScreen('ListSells')} >Продажи</button> <button disabled={screen === 'AddSell'} onClick={() => updateScreen('AddSell')} >Сделка</button> <button disabled={screen === 'PurschareProduct'} onClick={() => updateScreen('PurschareProduct')} >Приход товара</button> <button disabled={screen === 'AddProduct'} onClick={() => updateScreen('AddProduct')} >Добавить товар</button> <button disabled={screen === 'EditProduct' && productsFilter.includes('available')} onClick={() => { setProductsFilter('available') updateScreen('EditProduct') }} >Наличие</button> <button disabled={screen === 'EditProduct' && productsFilter.length === 0} onClick={() => { setProductsFilter('all') updateScreen('EditProduct') }} >Склад</button> <button onClick={logout} >Logout</button> </div> ) } export default NavPanel
import React, {Component} from 'react'; import classy from '../../utils/classy'; import style from './HouseCupHero.module.scss'; import slackLogo from './images/slack-logo-icon.png'; import {Col, Row, Container } from 'react-bootstrap'; import {Link} from 'react-router-dom'; import { Section, Modal, DownloadModal, Button, Crest } from '../../components'; import lake from './images/black-lake.svg'; import frontTreeline from './images/front-treeline.png'; import backTreeline from './images/back-treeline.png'; import castle from './images/castle.png'; import mainDarkHill from './images/main-ground.png'; import tree from './images/tree.svg'; import trees from './images/trees.svg'; import cloudLeft from './images/cloud-1.svg'; import cloudRight from './images/cloud-2.svg'; export default class HouseCupHero extends Component { render() { return( <div className={style.HouseCupHero}> <Row className={style.scenery}> <div className={style.background}> <img src={lake} className={style.lake}/> </div> <div className={style.middleground}> <img src={frontTreeline} className={style.frontTreeline}/> <img src={backTreeline} className={style.backTreeline}/> </div> <div className={style.foreground}> <img src={tree} className={style.tree}/> <img src={castle} className={style.castle}/> <img src={mainDarkHill} className={style.mainDarkHill}/> </div> <div className={style.clouds}> <img src={cloudRight} className={style.cloudOne}/> <img src={cloudLeft} className={style.cloudTwo}/> <img src={cloudRight} className={style.cloudThree}/> </div> </Row> <Container> <Row className={style.row}> <Col xs="12" sm="6" className={style.content}> <div className={style.header}> Team up & award house points. </div> <div className={style.body}> <p>In gravida ligula facilisis odio convallis, quis mollis nibh dignissim. In vehicula placerat malesuada. Praesent pharetra tincidunt est feugiat pharetra.</p> </div> <div className={style.footer}> <Modal className={style.modal} trigger={ <Button className={style.slackButton}> <img src={slackLogo} className={style.slackLogo}/>Add to Slack </Button>} > <DownloadModal /> </Modal> <Button className={style.appWorks}> <a href="#google"> How it works </a> </Button> </div> </Col> <Col xs="12" sm="6" className={style.crest}> <Crest /> </Col> </Row> </Container> </div> ); } }
const express = require('express'); const helmet = require('helmet'); const {addAsync} = require('@awaitjs/express'); const jwtMiddleware = require('./middleware/jwt-middleware'); const register = require('./auth/register'); const signin = require('./auth/signin'); const getProfile = require('./auth/get-profile'); module.exports = function() { const app = addAsync(express()); app.use(helmet()); app.use(express.json()); app.use(jwtMiddleware); app.use(register); app.use(signin); app.use(getProfile); /* istanbul ignore next */ app.get('/hi', (req, res) => { res.status(200).send('Hi there this is just a test on the new feature branch!'); }); return app; };
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { modeEnum } from 'utils/properties'; import { pathExtraction, pathTransmissionCampagne } from '../../utils/properties'; import DownloadFile from '../utils/downloadFile'; export default class LigneCampagne extends Component { constructor(props) { super(props); this.state = {}; } appelEdition() { const { idCampagne, labelCampagne, dateDebutCollecte, dateFinCollecte, onOpenModalFormCampagne, setMode, selectCampagne, } = this.props; setMode(modeEnum.UPDATE); selectCampagne({ idCampagneSelect: idCampagne, labelCampagneSelect: labelCampagne, dateDebutCollecteSelect: dateDebutCollecte, dateFinCollecteSelect: dateFinCollecte, }); onOpenModalFormCampagne(); } appelSuppression() { const { idCampagne, labelCampagne, dateDebutCollecte, dateFinCollecte, openValidationPanel, setMode, selectCampagne, } = this.props; setMode(modeEnum.DELETE); selectCampagne({ idCampagneSelect: idCampagne, labelCampagneSelect: labelCampagne, dateDebutCollecteSelect: dateDebutCollecte, dateFinCollecteSelect: dateFinCollecte, }); openValidationPanel(); } render() { const { idCampagne, labelCampagne, dateDebutCollecte, dateFinCollecte } = this.props; const localDateOptions = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', }; const { setLoading } = this.props; return ( <tr id={idCampagne}> <td>{idCampagne}</td> <td>{labelCampagne}</td> <td>{new Date(dateDebutCollecte).toLocaleDateString('fr-FR', localDateOptions)}</td> <td>{new Date(dateFinCollecte).toLocaleDateString('fr-FR', localDateOptions)}</td> <td> <button type="button" className="btn btn-secondary btn-sm glyphicon glyphicon-pencil" title="Modifier" onClick={() => this.appelEdition()} /> <DownloadFile fileName={`extraction-${idCampagne}-${new Date().toLocaleDateString()}.csv`} url={pathTransmissionCampagne + idCampagne + pathExtraction} setLoading={setLoading} /> <button type="button" className="btn btn-secondary btn-sm glyphicon glyphicon-trash" title="Supprimer" onClick={() => this.appelSuppression()} /> </td> </tr> ); } } LigneCampagne.propTypes = { idCampagne: PropTypes.string.isRequired, labelCampagne: PropTypes.string.isRequired, dateDebutCollecte: PropTypes.number.isRequired, dateFinCollecte: PropTypes.number.isRequired, onOpenModalFormCampagne: PropTypes.func.isRequired, openValidationPanel: PropTypes.func.isRequired, selectCampagne: PropTypes.func.isRequired, setMode: PropTypes.func.isRequired, setLoading: PropTypes.func.isRequired, };
const { authenticate } = require('@feathersjs/authentication/lib').hooks const { disallow } = require('feathers-hooks-common/lib') const populateFromGoogle = require('../../hooks/populateFromGoogle') const createSellerAndCustomer = require('../../hooks/createSellerAndCustomer') const onlyGetLoggedInUser = require('../../hooks/onlyGetLoggedInUser') module.exports = { before: { all: [], find: [authenticate('jwt'), disallow('external')], get: [authenticate('jwt'), onlyGetLoggedInUser()], create: [populateFromGoogle()], update: [disallow('external'), authenticate('jwt')], patch: [authenticate('jwt'), onlyGetLoggedInUser()], remove: [authenticate('jwt'), disallow('external')] }, after: { all: [], find: [], get: [], create: [createSellerAndCustomer()], update: [], patch: [], remove: [] }, error: { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [] } }
/** * */ function loginCheck() { console.log("formCheck().......") var formData = $("#npelogin").serialize(); var user_id = document.getElementById('user_id'); var password = document.getElementById('password'); var user_id_check; if (user_id.value == '' || user_id.value == null) { alert('아이디를 입력하세요'); focus.user_id; return; } if (password.value == '' || password.value == null) { alert('비밀번호를 입력하세요'); focus.password; return; } if(user_id.value != '' && user_id.value != null && password.value != '' && password.value != null ) { console.log('ajax실행................'); $.ajax({ url : "/user/membercheck", type : "post", data : formData, success : function(response) { console.log("response : " + response); if (response == '0') { alert('아이디가 없거나 비밀번호가 틀렸습니다.') focus.user_id; return; } // if(response == 'logined') { // alert("어디선가 로그인이 했다!!") // return false; // } else { login(); return; } } }); } } function login() { console.log("login().......") document.npelogin.method = "POST"; document.npelogin.action = "/user/login"; document.npelogin.submit(); } //$(".btn btn-default btn-flat").on("click", function() { // // console.log("login().......") // document.npelogin.method = "post"; // document.npelogin.action = "/user/login"; // document.npelogin.submit(); // //});
module.exports={ //配置地址 dizi : "192.168.1.241", // dizi : "192.168.1.5", port : 5000, //配置mysql host : "localhost", user : "root", password : "", database : "xiyuan" };