text
stringlengths
7
3.69M
// const MongoClient = require('mongodb').MongoClient; const { MongoClient, ObjectID } = require('mongodb'); const host_url = 'mongodb://localhost:27017/test'; MongoClient.connect(host_url, (err, db) => { if (err) { console.log('Unable to connect to mongodb server'); } else { console.log('Connected to mongodb server'); } db.collection('Users').insertOne( { name: 'lunan', 'usr_id': '????' }, (err, result) => { if (err) { return console.log('Uable to insert.', err); } else { console.log('insertion succeed'); } } ) db.collection('Users').findOneAndUpdate( { name: 'lunan' }, { // the following is the mongodb update operator, $ $set: { name: 'hongshen' } }, { returnOriginal: false }).then((result) => { console.log(result); }); db.close(); });
const UploadDress = require('../models/uploadDress'); const _ = require("underscore"); exports.uploaddress = function(req,res,next){ const dressupload = req.body; //console.log(dressupload); if(!dressupload){ return res.status(422).send({error:'you must provide data to save'}) } //if a user with email does not exit, create and save user if(dressupload._id == ''){ const postDressData = new UploadDress({ productName:dressupload.productName, detailName:dressupload.detailName, description:dressupload.description, priceDay:dressupload.priceDay, details:dressupload.details, fileList:dressupload.fileList, sizes:dressupload.sizes, tags:dressupload.tags, from:dressupload.from, to:dressupload.to, weather:dressupload.weather, background:dressupload.background, bodyType:dressupload.bodyType, userId:dressupload.userId, userName: dressupload.userName, userEmail: dressupload.userEmail, postedOn: dressupload.postedOn }); postDressData.save(function(err){ if(err){ return next(err); } }); //Respond to request indicating user was created res.send({ code:200, data:'data saved successfully' }); } else if(dressupload._id != ''){ console.log(Object.keys(dressupload).length,'LLLeeeennngggttthhhfirst'); if(Object.keys(dressupload).length > 2){ UploadDress.updateMany( {"_id":dressupload._id}, {$set: _.omit(dressupload, '_id')}, {multi:true} ).then(() => { res.send({ code:200, data:'data updated successfully' }); }).catch(() => res.status(422).send({msg:'okay'})); } else if(Object.keys(dressupload).length == 2){ console.log(dressupload.length,'LLLeeeennngggttthhhsecond'); UploadDress.updateOne( {"_id":dressupload._id}, {$set: _.omit(dressupload, '_id')} ).then(() => { res.send({ code:200, data:'data updated successfully' }); }).catch(() => res.status(422).send({msg:'okay'})); } } } // UploadDress.findOne({"_id":dressupload._id},function(err,existingDress){ // console.log(existingDress); // existingDress.productName=dressupload.productName; // existingDress.detailName=dressupload.detailName; // existingDress.description=dressupload.description; // existingDress.priceDay=dressupload.priceDay; // existingDress.details=dressupload.details; // existingDress.fileList=dressupload.fileList; // existingDress.sizes=dressupload.sizes; // existingDress.tags=dressupload.tags; // existingDress.from=dressupload.from; // existingDress.to=dressupload.to; // existingDress.weather=dressupload.weather; // existingDress.background=dressupload.background; // existingDress.bodyType=dressupload.bodyType; // existingDress.userId=dressupload.userId; // existingDress.save(function(err){ // if(err){ // return res.status(422).send({error:'Not updated'}) // } // //Respond to request indicating user was created // return res.send({ // code:200, // data:'data updated successfully' // }); // }) // })
(function(){ 'use strict'; angular .module('everycent.common') .directive('ecAsDollars', ecAsDollars); ecAsDollars.$inject = ['ecToDollarsFilter']; function ecAsDollars(ecToDollarsFilter){ var directive = { restrict:'A', require:'ngModel', link: link }; return directive; function link(scope, element, attrs, ngModel){ // add decimal places back to number when field loses focus element.on('blur', function(e){ var value = element.val(); element.val(Number(value).toFixed(2)); }); // convert cents in model to dollar amount with 2 dp for display ngModel.$formatters.push(function(modelValue){ return (modelValue / 100).toFixed(2); }); // update the model with the text input value, converted from dollars to cents ngModel.$parsers.push(function(viewValue){ var number = Number(viewValue); return number * 100; }); } } })();
function change_inc(x) { var y // x ir pierakstīts pie katra .navbar <a>. Piemērs: onclick="change_inc(1)" switch (x) { case 1: y = document.getElementById('stack'); y.setAttribute("src", "inc/1.php"); break; case 2: y = document.getElementById('stack'); y.setAttribute("src", "inc/2.php"); break; case 3: y = document.getElementById('stack'); y.setAttribute("src", "inc/3.php"); break; case 4: y = document.getElementById('stack'); y.setAttribute("src", "inc/4.php"); break; case 5: y = document.getElementById('stack'); y.setAttribute("src", "inc/5.php"); break; case 6: y = document.getElementById('stack'); y.setAttribute("src", "inc/6.php"); break; case 7: y = document.getElementById('stack'); y.setAttribute("src", "inc/7.php"); break; case 8: y = document.getElementById('stack'); y.setAttribute("src", "inc/8.php"); break; case 9: y = document.getElementById('stack'); y.setAttribute("src", "inc/9.php"); break; case 10: y = document.getElementById('stack'); y.setAttribute("src", "inc/10.php"); break; case 11: y = document.getElementById('stack'); y.setAttribute("src", "inc/11.php"); break; case 12: y = document.getElementById('stack'); y.setAttribute("src", "inc/12.php"); break; case 13: y = document.getElementById('stack'); y.setAttribute("src", "inc/13.php"); break; } }
/////////////////////////////////////////// // INITIALIZE APPLICATION // /////////////////////////////////////////// 'use strict'; // Requires var _ = require('lodash'), $ = require('jquery'), Backbone = require('backbone'); Backbone.$ = $; var Models = require('./models')(Backbone), Views = require('./views')(_, Backbone, Models); // Start the router require('./router')(Backbone, Views); Backbone.history.start();
export const SongUpdated = (updatedList, currentSong) => { return updatedList.filter((song) => song.id === currentSong.id); };
var charts = []; var maps; var dataLoaded = false; var chartqs = [[["pie", ["V028", "V054"]], ["bar", ["V085_3", "V084_3"]], ["bar", "V086_4"], ["bar", "V086_3"], ["bar", "V086_2"], ["bar", "V087_2"], ["bar", "V087_3"], ["pie", "V075"], ["bar", "V023_3"]], [["bar", ["V122", "V082"]], ["bar", ["V025_4", "V052_4"]], ["bar", ["V025_1", "V052_1"]], ["pie", ["V024_1", "V051_1"]], ["pie", ["V024_2", "V051_2"]]], [["bar", "V053_3"], ["pie", "V053_1"], ["bar", "V053_2"], ["bar", ["V013_1", "V048_1"]], ["bar", ["V013_2", "V048_2"]], ["bar", "V027_5"], ["bar", "V027_4"], ["bar", "V027_1"], ["bar", "V027_2"]] ]; function loadData() { API.loadData("data/data.csv", "data/postcodes.csv", "data/antwoorden.csv", function(){ dataLoaded = true; createCharts(); }); } function getFilterData(chart){ if ((chart.side == "left" && chart.g != filters_gemeente.left) || (chart.side == "right" && chart.g != filters_gemeente.right)){ chart.sourceData = getSourceData(chart.q, chart.side); chart.g = (chart.side == "left")? filters_gemeente.left : filters_gemeente.right; } var fdata = chart.sourceData; for (var i in filters){ if (filters.hasOwnProperty(i)) { fdata = fdata.filter(i, filters[i]); } } return fdata.countobj(); } function getSourceData(q, side){ var sdata = API.getData(q); if (filters_gemeente[side] != -1 && filters_gemeente[side] < gem_name.length){ sdata = sdata.filter("gemeente", filters_gemeente[side]); } return sdata; } function createCharts(){ $(".container_page").each(function(i){ if (i>0){ var color; switch(i){ case 1: color = "#F21933"; break; case 2: color = "#FFAA00"; break; case 3: color = "#19C0D1"; break; default: color = "#F21933"; break; }; $(this).find(".chartcontainer").each(function(j){ $left = $(this).find(".chart_left").find(".chart_chart"); $right = $(this).find(".chart_right").find(".chart_chart"); if (chartqs[i-1][j][0] == "pie"){ charts.push(new PieChart(getSourceData(chartqs[i-1][j][1], "left"), chartqs[i-1][j][1], filters_gemeente.left, "left", $left, color)); charts.push(new PieChart(getSourceData(chartqs[i-1][j][1], "right"), chartqs[i-1][j][1], filters_gemeente.right, "right", $right, color)); } else { charts.push(new BarChart(getSourceData(chartqs[i-1][j][1], "left"), chartqs[i-1][j][1], filters_gemeente.left, "left", $left, color)); charts.push(new BarChart(getSourceData(chartqs[i-1][j][1], "right"), chartqs[i-1][j][1], filters_gemeente.right, "right", $right, color)); } }); } }); var content = $(".container_dropdown"); var gemeentes = API.getData("V003").getGemeentesWithData(); var test_dat = API.getData("V028").countObjGemeenteLatLong(); maps = new mapChart(test_dat, $(".contentHeader").eq(1), "#F21933"); maps = new mapChart(test_dat, $(".contentHeader").eq(2), "#FFAA00"); maps = new mapChart(test_dat, $(".contentHeader").eq(3), "#19C0D1"); /*var dd = $("<select></select"); var noption = $("<option value='-1'>Nederland</option>"); noption.appendTo(dd); gemeentes.forEach(function(n){ var noption = $("<option value='"+n+"'>"+API.getGemeenteFromID(n)+"</option>"); noption.appendTo(dd); }); dd.appendTo(content); dd.change(function(){ var selected = $(this).find("option:selected"); //filter_gem1 = parseInt(selected.attr("value")); //console.log(filter_gem1); //update(); filterGemeente(parseInt(selected.attr("value"))); });*/ update(); } function resize(){ charts.forEach(function(e){ e.resize(); }); } function update(){ charts.forEach(function(e){ e.update(getFilterData(e)); }); }
import React from 'react'; import './Header.css'; import { Divider } from 'semantic-ui-react'; import Teasers from './Teasers'; const Header = () => ( <> <div className="headerBlock"> <div className="headerName"> <p>SST Translations</p> </div> <div className="headerContent"> <p>Ongoing</p> <Teasers placeholder="Search Teasers" fluid search selection options={['a', 'b']} /> <p>Contact</p> </div> </div> <Divider /> </> ); export default Header;
const defaultState = { list:["吃饭","睡觉"], val:'' } export default (state=defaultState)=>{ }
import React from 'react'; const CharacterCard = props => ( <div className="CharacterCard" style={{ backgroundImage: `url(${props.character.image})` }} > <div className="CharacterCard__name-container text-truncate"> {props.character.name} </div> </div> ); export default CharacterCard;
import React from 'react'; class Input extends React.Component { constructor(props) { super(props); this._onchange = this.onchange.bind(this); } componentWillMount() { this.setState({ data: {}, validation: { name: [] } }); } render() { console.log(this.state); return ( <input className={`${this.state.validation.name.length > 0 ? 'error' : ''}`} type="text" onChange={this._onchange}/> ); } /** * * @param {Event} event javascript onChange event object */ onchange(event){ this._update(this._validateName(event.target.value)); } /** * * @param newValue event to generate new state from * @returns {String} copy of an updated next state * @private */ _validateName(newValue){ if(newValue.length < 3){ return Object.assign({}, this.state, {validation : {name: this.state.validation.name.concat('MIN') }}); } return Object.assign({},this.state,{validation: {name:[]}}); } /** * * @param state the state to be used to update component * @private */ _update(state){ this.setState(Object.assign({}, state)); } } export default Input;
import React, {useLayoutEffect, useState} from "react"; import { View, Text, TextInput, StyleSheet, TouchableOpacity, Image } from 'react-native'; export const Feedback = () => { const [mailInput, setMailInput] = useState('') const [commentInput, setCommentInput] = useState('') const onSubmit = () => { alert('Вы молодец!') } return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}> <View style={styles.header}> <View style={styles.headerOne}> <Image source={require('../../assets/news/Logo.jpg')} style={styles.logoHeader}/> </View> <View style={styles.headerTwo}> <Text style={styles.textHeader}>Обратная связь</Text> </View> </View> <Image source={require('../../assets/avatar.png')} style={{ width: 80, height: 80, borderRadius:50, marginBottom: 5 }} /> <Text style={{ fontSize: 26}}>Ефимов И. А.</Text> <TextInput style={styles.mailInput} text={mailInput} onChange={setMailInput} placeholder='Введите почту' /> <TextInput style={styles.commentInput} text={commentInput} onChange={setCommentInput} placeholder='Введите комментарий' /> <TouchableOpacity style={styles.button} onPress={onSubmit}> <Text style={styles.buttonText}>Отправить</Text> </TouchableOpacity> <Text style={styles.appealText}> Мы прислушиваемся к каждому отзыву. Ваше мнение очень важно для нас. Опишите ваше впечатление от поездки </Text> </View> ) } const styles = StyleSheet.create({ mailInput: { width: '90%', padding: 10, borderColor: '#000', borderWidth: 1, marginTop: 35 }, commentInput: { width: '90%', height: '25%', padding: 10, borderColor: '#000', borderWidth: 1, marginVertical: 10 }, button: { backgroundColor: '#EA2A2A', paddingHorizontal: 40, paddingVertical: 10, marginBottom: 30 }, buttonText: { fontSize: 18 }, appealText: { fontSize: 18, textAlign: 'center', width: '80%' }, header: { display: 'flex', position: 'absolute', top: 0, start: 0, flexDirection: "row" }, headerOne: { flex: 1, alignItems: 'center', }, headerTwo: { flex: 5, alignItems: 'flex-start' }, logoHeader: { width: 30, height: 30, marginTop: '74%', }, textHeader: { fontFamily: 'GothamPro-Medium', fontSize: 19, marginTop: '16%', } })
(function( $, app, visor ){ var height = $( window ).height(); function preInit ( ) { // adjust app window height $( document.body ).height( height ); //if ( window.matchMedia('handheld, (max-width: 750px)').matches ){ console.log( 'current height: ', height ); var letterH = height/4; $( '.item, .item-off' ).height( letterH ); $( '.item, .item-off' ).css( 'font-size', letterH ); $( '.item, .item-off' ).css( 'line-height', 1 ); init(); }; function init (){ // init all the modules app.initialize(); visor.start(); postInit(); }; function postInit(){ // postInit() if ( window.matchMedia('handheld, (max-width: 750px)').matches ){ var forms = document.querySelectorAll( '.draggable' ); for ( var i = forms.length - 1; i >= 0; i-- ) { forms[ i ].classList.remove( 'draggable' ); } } }; function start( ) { preInit(); } start(); }( jQuery, ShapesApp, Visor ));
import styled from 'styled-components'; const DarkBox = styled.div` max-width: 960px; display: flex; flex-flow: row wrap; background-color: rgb(245, 246, 247); border-radius: 8px; overflow: hidden; padding: 8px;`; export default DarkBox;
function largestPanDigitalPrime(){ for(let nDigits = 7; nDigits >= 1; nDigits --) { for(const panDigital of sortedPandigitals(nDigits)) { if(isPrime(panDigital)) { return panDigital; } } } function* sortedPandigitals(nDigits) { let digits = new Array(nDigits).fill().map((_, i) => nDigits - i); yield* formOptions(digits, 10 ** (nDigits - 1), 0); function* formOptions(available, factor, current) { if(available.length === 1) yield current + available[0]; for(let pos = 0; pos < available.length; pos ++) { const rest = [...available.slice(0, pos), ...available.slice(pos + 1)]; yield* formOptions(rest, factor / 10, current + available[pos] * factor); } } } function isPrime(num) { const upperBound = Math.floor(Math.sqrt(num)); if(num % 2 === 0 || num % 3 === 0) return false; for(let test = 6; test <= upperBound; test += 6) { if((num % (test + 1) === 0) || (num % (test - 1) === 0)) { return false; } } return true; } } (function() { const start = performance.now(); console.log(largestPanDigitalPrime()); const end = performance.now(); console.log(`Elapsed time: ${(end - start)} ms`) })()
const express=require('express') const path=require('path') const app=express() const port=process.env.PORT||3000 app.use(express.static(__dirname+'/dist/ngproject')); app.get('/',(req,res)=>res.sendFile(path.join(__dirname + 'dist/ngproject/index.html'))); app.listen(port,()=>console.log('app on port ${port}!'))
import test from "tape" import { clone } from "./clone" test("clone", t => { /* * Primitives */ t.equal(clone(null), null, "Clone null") t.equal(clone(undefined), undefined, "Clone undefined") t.equal(clone(2), 2, "Clone number") t.equal(clone("3"), "3", "Clone number") t.equal(clone(true), true, "Clone boolean") /* * Date */ const date = new Date(86400000) t.notEqual(clone(date), date, "Imutable date") t.equal(clone(date).getTime(), 86400000, "Clone date") /* * Array */ const array = [1, 2, 3] t.notEqual(clone(array), array, "Imutable array") t.deepEqual(clone(array), [1, 2, 3], "Clone array") /* * Object */ const object = { a: 1, b: 2, c: 3 } t.notEqual(clone(object), object, "Imutable array") t.deepEqual(clone(object), { a: 1, b: 2, c: 3 }, "Clone array") t.end() })
import uuid4 from 'uuid/v4' import uuid5 from 'uuid/v5' import { cloneDeep } from 'lodash' import store from '@/store' const toString = Object.prototype.toString const Utils = { types: ['String', 'Function', 'Object'], isType(type) { return o => toString.call(o) === `[object ${type}]` }, isPlainObject(o) { return Utils.isObject(o) && Object.keys(o).length === 0 }, guid() { return 'fd' + uuid4().split('-')[0] }, namespace(str) { return 'fd' + uuid5(str, uuid5.DNS).split('-')[0] }, forIn(o, cb) { const length = o.length const isArray = Array.isArray(o) let value let k = 0 if (isArray) { for (; k < length; k++) { value = cb.call(o[k], o[k], k) if (value === false) { break } } } else { for (k in o) { value = cb.call(o[k], o[k], k) if (value === false) { break } } } }, traverse(source, target) { let result = null for (const item of source) { if (item.id === target) { result = item break } else { const { children } = item if (children) { result = Utils.traverse(children, target) } } } return result }, getVNodeProps(schema, readonly = store.state.mode === 'edit') { const { props, configs, attrs, events, className, style, id } = schema let { on, nativeOn } = events || {} let formatProps = props let formatOn = {} for (let key in configs) { formatProps[key] = configs[key].value } formatProps['id'] = id for (let key in on) { formatOn[key] = this.createFunc(on[key]) } let result = { class: className, props: formatProps, attrs, style } if (readonly === false) { result = Object.assign({}, result, { on: formatOn, nativeOn }) } return result }, createFunc(funcBody = '') { return typeof funcBody === 'string' ? new Function('event', funcBody) : funcBody }, addClass(elem, name) { const classList = elem.className.split(' ') if (!classList.includes(name)) { classList.push(name) elem.className = classList.join(' ') } }, removeClass(elem, name) { const classList = elem.className.split(' ') const index = classList.findIndex(val => val === name) if (index > -1) { classList.splice(index, 1) elem.className = classList.join(' ') } }, deepClone(o) { if (!Utils.isObject(o) && !Array.isArray(o)) return o // return JSON.parse(JSON.stringify(o)) return cloneDeep(o) } } Utils.forIn(Utils.types, type => { Utils[`is${type}`] = Utils.isType(type) }) export default Utils
import React from 'react'; import ContextNestedItemLast from './context_nested_item_last'; import {Context} from './context_main_container'; export default class ContextNestedItem extends React.Component { render() { return ( <Context.Consumer> {(context) => { return ( <div style={{backgroundColor: 'green'}}> I am a first-nested item in context example <button onClick={context.addProduct}>Add a product</button> <ContextNestedItemLast/> </div> ) }} </Context.Consumer> ); } }
import React, { Component } from 'react'; const steveImg = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAAgCAYAAACinX6EAAAGuklEQVRoQ+WYa2wUVRTH/7OP2d1u293i0uVRKMgbi7QBQyKGxwdFJVEbkfggMVGMBj9pNCYQMcaoEEhUxAYVDZpISECRGB81EQmmfLGkCCjlobRCKq3A9rXb7ttz7uzdnZlOtxQIi3CSdnbuvXNnzu/8z7l3RsEQNnNcSZqHxOJxqE6nGM2/2eL9diyfNznvDBvqf1OGukch+4d8OAbADntdLs3pVCoLgM9rZ09DOKqg4hYHzl5IiCNbqFeDdEMAcNpswpk+AuGw2y0B1J/pMQRyybgSgpb+/wOYPMqd5ujLyMs0YCjctnTmrUIBNywATgHpbCKZFFH2ZGrBTQOAnTY7L+vBYAqY7bRjUqXn/58CrAB2nqMeo2OSZB+NKPD7HIYUsKrkN0QNYABkwnG9cTFkYwXks+t+FZg+tkis8yn6rygKbPTncVF0tXSHDUkkyHeHYkM0mUAikYSNCqDTYQdxgT0DghSPvmiC5klTe5rmyVxv00ANto9o7QwPuRTnJXyFnYoeAM+lOhwi2jbywK060B9LZG/B5z5VISR2XOiNEpgkvG5VjEkRQTuBiSW08XoA+fYRp871FxZA1fjSdCxG4bZpDnB0k5TriWSaosznCjY8/yRcThUedyn6wt0UdhtC59qwbvcPCPfFECeJOOyKUEOK4Il0SSlQVTonNeTbRxQcgFBA2g4nOZCmWCRI5mkodG6HnWS+5olHUET7gEg0Sg66EOoOoTJYjtaWEyLS79c3IElpESdoNAOBcECh1IgTQCgMMiV2kYPtI/4401NYBcgU0OqAFv2Vi2sw0uvFpw1NWL3iMSxdswmz5m/H+sX7oZZ68cKeOTjS8Dh2rn0W7+78Ck/Nr8G/4TC2/twkVGBTcgXTRjUg3z7i+gFAKmD5qqqKR+dOwIgSP7rj/Qh4ShAcVQGHy49v9u4VUV927104+/dJ/NV+AW6XE6VONy72dGJHYwtisZhII46+qAWZIjjYPqLgALgGsOydNgfumDoR86dNQDIaxvnOTvFCMzYYgErOtJ4JG+rtqAoPusNx9PZGUFbsRMDvh93lRcPxFvx64jRJPiHSgWtAvn1EwQG89fBcsQyyA+x0eSCAWH8UvRTJjlCvyG1WRsDvEwCi8Rgtk27xuy/aTxFPoLysGCN9pUiSs6kkFU57CilaDXg+Nga558hJA8AHZ00R4FZ/2VjYGmBeRpff1yiASDt8eoVhSHNzc/4HbmxMv7zmafO04nzDm58Amzdb9mUbt23LP/+OHWlMznyDOHUKq7aswz9dYYz2ecVxd9PJYQEdMPhqAFj10kpLJ+s2br1yAARYPznf6+YFQAqoXf9qNvqsgrp9hwqvgGuZAlcMoHr6i0JSkWg7bXiCKB8xxyDfjosHs33coe/v7TuLAw9EcuMpIliwAKA3x9e//dgwz2tLn9HOW1uN6VFZCRQV5doyn95AGy9hx45Zj+dxPMbcX11tHF9bm1cRCgNg59mGC4Cv+fFu2hG2a9cjGARmzNB+RyJZCML5sjKt/dCh3Hg+X7QIkE7rH10C2Lcv18rzs4Pcx9eEQhpQ/f0vFwA7zzYcBQgAt/8y8AG5hR+SIIC/IPtoCZVO1tcbI7RkifHcDIEjbAasB6YHKgHp57hUBVw2gInfASUl2i176MPosmW523OEGEB5ea5t1y7r8R0d2jgG19WV+20GwCkj1XStFCAUnakRRR5NKdIOzDutOS6Na4CQUsZp6Rgf2fbvN0acgZmdlgBoZN3Xm7LjuyIxTJp+m+H6P5t/h69IzbYFxk8x9C9/46NLqwF6BXBxYyv2VEAWQT7nMQMAzDycuyEroaYmB8DKsaamHDAezykg4egVkEkbKwDnu8MI0EsZ23l6J2EwEsJVAaBHmG8V4HGiBkgFSAD66Mv8lzAkAJk2DED2ybE6IG9v35h1TipAAuAjOtsGABDtZAzpkhSgd3jYRdC8CowZY5S/GUBbm3EVkEWQnR4CgHBKJ3EzAKsUuSoA8gEasAzqlyG9UzwJn+sBWFVtY4WAVICUuRUAecllAVi4cKHYCHW1axsgKwVwuy94UPRXVVUZHvEDensUyxQ7w8YKkKaPPi9dVgD04zl1TPWg7vsPxWxWALida4DeGJA+RVa990X+IigByEnMDh49etRwA3N/w0/8uUzbRfJxwuj7TTEExI5x7dQsgKmf046RTG68ZNE98AotcbwCkN25pVMU4Yem0AuUBQDppFwF9IAKBoAf1KwgSUNAeM6P6neO599a05h7PivOQpQAsg3+MaK4yULX1dYyYBkcDoD/ACyhLV1sP+9TAAAAAElFTkSuQmCC'; export default class McSkinViewer extends Component { state = { ref: { canvas: null, canvasSketch: null } } //Scales using nearest neighbour scaleImage(imageData, context, dx, dy, scale) { var width = imageData.width , height = imageData.height context.clearRect(0, 0, width, height) //Clear the spot where it originated from for (var y = 0; y < height; y++) { // Height original for (var x = 0; x < width; x++) { // Width original // Gets original colour, then makes a scaled square of the same colour var index = (x + y * width) * 4 , fill = imageData.data[index] fill += ',' + imageData.data[index + 1] + ',' + imageData.data[index + 2] + ',' + imageData.data[index + 3] context.fillStyle = 'rgba(' + fill + ')' context.fillRect(dx + x * scale, dy + y * scale, scale, scale) } } } getDataUri(url) { return new Promise((resolve, reject) => { const image = new Image(); image.onload = function () { const canvas = document.createElement('canvas'); canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size canvas.getContext('2d').drawImage(this, 0, 0); resolve(canvas.toDataURL('image/png')); }; image.onerror = function () { reject(new Error(`Error loading image.`)); } image.src = url; }) } async loadImage() { let imageUri = steveImg; try { imageUri = await getDataUri(this.props.uri); } catch(e) { } drawImage(); } componentDidMount() { this.loadImage(); } async drawImage(imgData) { const canvas = this.state.ref.canvasSketch , scratchCanv = canvasSketch.getContext('2d') , model = canvas.getContext('2d') , scratch = scratchCanv.getContext('2d') , skin = new Image() , heightMultiplier = this.props.head ? 17.6 : 44.8 , scale = parseFloat(this.props.scale || '1'); canvas.setAttribute('class', 'model') // Resize Scratch scratchCanv.setAttribute('width', 64 * scale); scratchCanv.setAttribute('height', 32 * scale) scratchCanv.setAttribute('class', 'scratch') // Resize Isometric Area (Found by trial and error) canvas.setAttribute('width', 20 * scale) canvas.setAttribute('height', heightMultiplier * scale) skin.onload = function () { scratch.drawImage(skin, 0, 0, 64, 32, 0, 0, 64, 32) // Scale it _this.scaleImage(scratch.getImageData(0, 0, 64, 32), scratch, 0, 0, scale) // Draw the skin if (_this.props.head) { _this.drawHead(model, scratchCanv, scratch, this.props.hat, scale); } else { _this.drawModel(model, scratchCanv, scratch, this.props.hat, scale); } } skin.src = imgData } drawHead(model, scratchCanv, scratch, showHat, scale) { var scaleEight = 8 * scale // Head - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , scaleEight , scaleEight , scaleEight , scaleEight , 10 * scale , 13 / 1.2 * scale , scaleEight , scaleEight ) // Head - Right model.setTransform(1, 0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 0 , scaleEight , scaleEight , scaleEight , 2 * scale , 3 / 1.2 * scale , scaleEight , scaleEight ) // Head - Top model.setTransform(-1, 0.5, 1, 0.5, 0, 0) model.scale(-1, 1) model.drawImage (scratchCanv , scaleEight , 0 , scaleEight , scaleEight , -3 * scale , 5 * scale , scaleEight , scaleEight ) if (!showHat) return // Hat - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 40 * scale , scaleEight , scaleEight , scaleEight , 10 * scale , 13 / 1.2 * scale , scaleEight , scaleEight ) // Hat - Right model.setTransform(1, 0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 32 * scale , scaleEight , scaleEight , scaleEight , 2 * scale , 3 / 1.2 * scale , scaleEight , scaleEight ) // Hat - Top model.setTransform(-1, 0.5, 1, 0.5, 0, 0) model.scale(-1, 1) model.drawImage (scratchCanv , 40 * scale , 0 , scaleEight , scaleEight , -3 * scale , 5 * scale , scaleEight , scaleEight ) } drawModel(model, scratchCanv, scratch, showHat, scale) { var scaleEight = 8 * scale // Left Leg // Left Leg - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.scale(-1, 1) model.drawImage (scratchCanv , 4 * scale , 20 * scale , 4 * scale , 12 * scale , -16 * scale , 34.4 / 1.2 * scale , 4 * scale , 12 * scale ) // Right Leg // Right Leg - Right model.setTransform(1, 0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 0 * scale , 20 * scale , 4 * scale , 12 * scale , 4 * scale , 26.4 / 1.2 * scale , 4 * scale , 12 * scale ) // Right Leg - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 4 * scale , 20 * scale , 4 * scale , 12 * scale , 8 * scale , 34.4 / 1.2 * scale , 4 * scale , 12 * scale ) // Arm Left // Arm Left - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.scale(-1, 1) model.drawImage (scratchCanv , 44 * scale , 20 * scale , 4 * scale , 12 * scale , -20 * scale , 20 / 1.2 * scale , 4 * scale , 12 * scale ) // Arm Left - Top model.setTransform(-1, 0.5, 1, 0.5, 0, 0) model.drawImage (scratchCanv , 44 * scale , 16 * scale , 4 * scale , 4 * scale , 0 , 16 * scale , 4 * scale , 4 * scale ) // Body // Body - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 20 * scale , 20 * scale , 8 * scale , 12 * scale , 8 * scale , 20 / 1.2 * scale , scaleEight , 12 * scale ) // Arm Right // Arm Right - Right model.setTransform(1, 0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 40 * scale , 20 * scale , 4 * scale , 12 * scale , 0 , 16 / 1.2 * scale , 4 * scale , 12 * scale ) // Arm Right - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 44 * scale , 20 * scale , 4 * scale , 12 * scale , 4 * scale , 20 / 1.2 * scale , 4 * scale , 12 * scale ) // Arm Right - Top model.setTransform(-1, 0.5, 1, 0.5, 0, 0) model.scale(-1, 1) model.drawImage (scratchCanv , 44 * scale , 16 * scale , 4 * scale , 4 * scale , -16 * scale , 16 * scale , 4 * scale , 4 * scale ) this.drawHead(model, scratchCanv, scratch, showHat, scale) } render() { if (state.imageUri === null) { return ( <div>Loading...</div> ); } this.drawImage(); return ( <div> <canvas ref={r => { this.ref.canvas = r }} /> <canvas ref={r => { this.ref.canvasSketch = r }} /> </div> ) } } var pluginName = 'minecraftSkin' /* jslint maxlen: 2414 */ , steveImg = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAAgCAYAAACinX6EAAAGuklEQVRoQ+WYa2wUVRTH/7OP2d1u293i0uVRKMgbi7QBQyKGxwdFJVEbkfggMVGMBj9pNCYQMcaoEEhUxAYVDZpISECRGB81EQmmfLGkCCjlobRCKq3A9rXb7ttz7uzdnZlOtxQIi3CSdnbuvXNnzu/8z7l3RsEQNnNcSZqHxOJxqE6nGM2/2eL9diyfNznvDBvqf1OGukch+4d8OAbADntdLs3pVCoLgM9rZ09DOKqg4hYHzl5IiCNbqFeDdEMAcNpswpk+AuGw2y0B1J/pMQRyybgSgpb+/wOYPMqd5ujLyMs0YCjctnTmrUIBNywATgHpbCKZFFH2ZGrBTQOAnTY7L+vBYAqY7bRjUqXn/58CrAB2nqMeo2OSZB+NKPD7HIYUsKrkN0QNYABkwnG9cTFkYwXks+t+FZg+tkis8yn6rygKbPTncVF0tXSHDUkkyHeHYkM0mUAikYSNCqDTYQdxgT0DghSPvmiC5klTe5rmyVxv00ANto9o7QwPuRTnJXyFnYoeAM+lOhwi2jbywK060B9LZG/B5z5VISR2XOiNEpgkvG5VjEkRQTuBiSW08XoA+fYRp871FxZA1fjSdCxG4bZpDnB0k5TriWSaosznCjY8/yRcThUedyn6wt0UdhtC59qwbvcPCPfFECeJOOyKUEOK4Il0SSlQVTonNeTbRxQcgFBA2g4nOZCmWCRI5mkodG6HnWS+5olHUET7gEg0Sg66EOoOoTJYjtaWEyLS79c3IElpESdoNAOBcECh1IgTQCgMMiV2kYPtI/4401NYBcgU0OqAFv2Vi2sw0uvFpw1NWL3iMSxdswmz5m/H+sX7oZZ68cKeOTjS8Dh2rn0W7+78Ck/Nr8G/4TC2/twkVGBTcgXTRjUg3z7i+gFAKmD5qqqKR+dOwIgSP7rj/Qh4ShAcVQGHy49v9u4VUV927104+/dJ/NV+AW6XE6VONy72dGJHYwtisZhII46+qAWZIjjYPqLgALgGsOydNgfumDoR86dNQDIaxvnOTvFCMzYYgErOtJ4JG+rtqAoPusNx9PZGUFbsRMDvh93lRcPxFvx64jRJPiHSgWtAvn1EwQG89fBcsQyyA+x0eSCAWH8UvRTJjlCvyG1WRsDvEwCi8Rgtk27xuy/aTxFPoLysGCN9pUiSs6kkFU57CilaDXg+Nga558hJA8AHZ00R4FZ/2VjYGmBeRpff1yiASDt8eoVhSHNzc/4HbmxMv7zmafO04nzDm58Amzdb9mUbt23LP/+OHWlMznyDOHUKq7aswz9dYYz2ecVxd9PJYQEdMPhqAFj10kpLJ+s2br1yAARYPznf6+YFQAqoXf9qNvqsgrp9hwqvgGuZAlcMoHr6i0JSkWg7bXiCKB8xxyDfjosHs33coe/v7TuLAw9EcuMpIliwAKA3x9e//dgwz2tLn9HOW1uN6VFZCRQV5doyn95AGy9hx45Zj+dxPMbcX11tHF9bm1cRCgNg59mGC4Cv+fFu2hG2a9cjGARmzNB+RyJZCML5sjKt/dCh3Hg+X7QIkE7rH10C2Lcv18rzs4Pcx9eEQhpQ/f0vFwA7zzYcBQgAt/8y8AG5hR+SIIC/IPtoCZVO1tcbI7RkifHcDIEjbAasB6YHKgHp57hUBVw2gInfASUl2i176MPosmW523OEGEB5ea5t1y7r8R0d2jgG19WV+20GwCkj1XStFCAUnakRRR5NKdIOzDutOS6Na4CQUsZp6Rgf2fbvN0acgZmdlgBoZN3Xm7LjuyIxTJp+m+H6P5t/h69IzbYFxk8x9C9/46NLqwF6BXBxYyv2VEAWQT7nMQMAzDycuyEroaYmB8DKsaamHDAezykg4egVkEkbKwDnu8MI0EsZ23l6J2EwEsJVAaBHmG8V4HGiBkgFSAD66Mv8lzAkAJk2DED2ybE6IG9v35h1TipAAuAjOtsGABDtZAzpkhSgd3jYRdC8CowZY5S/GUBbm3EVkEWQnR4CgHBKJ3EzAKsUuSoA8gEasAzqlyG9UzwJn+sBWFVtY4WAVICUuRUAecllAVi4cKHYCHW1axsgKwVwuy94UPRXVVUZHvEDensUyxQ7w8YKkKaPPi9dVgD04zl1TPWg7vsPxWxWALida4DeGJA+RVa990X+IigByEnMDh49etRwA3N/w0/8uUzbRfJxwuj7TTEExI5x7dQsgKmf046RTG68ZNE98AotcbwCkN25pVMU4Yem0AuUBQDppFwF9IAKBoAf1KwgSUNAeM6P6neO599a05h7PivOQpQAsg3+MaK4yULX1dYyYBkcDoD/ACyhLV1sP+9TAAAAAElFTkSuQmCC' var methods = { init: function (options) { return this.each(function () { var $this = $(this) , data = $this.data(pluginName) , settings = {} // If the plugin hasn't been initialized yet if (!data) { settings = { scale: 6 , hat: true , draw: 'model' } if (options) $.extend(true, settings, options) } settings.username = $this.data('minecraft-username') if ($this.data('minecraft-scale')) settings.scale = $this.data('minecraft-scale') if ($this.data('minecraft-draw')) settings.draw = $this.data('minecraft-draw') // Check if valid drawing set if (settings.draw !== 'head' && settings.draw !== 'model') settings.draw = 'model' // Request the data methods.requestData('http://s3.amazonaws.com/MinecraftSkins/' + settings.username + '.png', $this, settings) }) } , buildImage: function (imgData, $this, settings) { // Failed to respond if (!imgData) return // Create the canvas var canvas = document.createElement('canvas') , scratchCanv = document.createElement('canvas') , model = canvas.getContext('2d') , scratch = scratchCanv.getContext('2d') , skin = new Image() , heightMultiplier = settings.draw === 'head' ? 17.6 : 44.8 canvas.setAttribute('class', 'model') // Resize Scratch scratchCanv.setAttribute('width', 64 * settings.scale) scratchCanv.setAttribute('height', 32 * settings.scale) scratchCanv.setAttribute('class', 'scratch') // Resize Isometric Area (Found by trial and error) canvas.setAttribute('width', 20 * settings.scale) canvas.setAttribute('height', heightMultiplier * settings.scale) $this.append(canvas) $this.append(scratchCanv) skin.onload = function () { scratch.drawImage(skin, 0, 0, 64, 32, 0, 0, 64, 32) // Scale it scaleImage(scratch.getImageData(0, 0, 64, 32), scratch, 0, 0, settings.scale) // Draw the skin if (settings.draw === 'model') { methods.drawModel(model, scratchCanv, scratch, settings.hat, settings.scale) } else { methods.drawHead(model, scratchCanv, scratch, settings.hat, settings.scale) } } skin.src = imgData } , requestData: function (username, $this, settings) { var query = encodeURIComponent('SELECT * FROM data.uri WHERE url = "' + username + '"') , yql = 'https://query.yahooapis.com/v1/public/yql?q=' + query + '&format=json&callback=?' $.getJSON(yql, function (data) { if (data.query.results.url) { var imgData = data.query.results.url // Convert MIME imgData = imgData.replace('application/octet-stream', 'image/png') methods.buildImage(imgData, $this, settings) } else { methods.buildImage(steveImg, $this, settings) } }).fail(function () { methods.buildImage(steveImg, $this, settings) }) } , drawHead: function (model, scratchCanv, scratch, showHat, scale) { var scaleEight = 8 * scale // Head - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , scaleEight , scaleEight , scaleEight , scaleEight , 10 * scale , 13 / 1.2 * scale , scaleEight , scaleEight ) // Head - Right model.setTransform(1, 0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 0 , scaleEight , scaleEight , scaleEight , 2 * scale , 3 / 1.2 * scale , scaleEight , scaleEight ) // Head - Top model.setTransform(-1, 0.5, 1, 0.5, 0, 0) model.scale(-1, 1) model.drawImage (scratchCanv , scaleEight , 0 , scaleEight , scaleEight , -3 * scale , 5 * scale , scaleEight , scaleEight ) if (!showHat) return // Hat - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 40 * scale , scaleEight , scaleEight , scaleEight , 10 * scale , 13 / 1.2 * scale , scaleEight , scaleEight ) // Hat - Right model.setTransform(1, 0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 32 * scale , scaleEight , scaleEight , scaleEight , 2 * scale , 3 / 1.2 * scale , scaleEight , scaleEight ) // Hat - Top model.setTransform(-1, 0.5, 1, 0.5, 0, 0) model.scale(-1, 1) model.drawImage (scratchCanv , 40 * scale , 0 , scaleEight , scaleEight , -3 * scale , 5 * scale , scaleEight , scaleEight ) } , drawModel: function (model, scratchCanv, scratch, showHat, scale) { var scaleEight = 8 * scale // Left Leg // Left Leg - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.scale(-1, 1) model.drawImage (scratchCanv , 4 * scale , 20 * scale , 4 * scale , 12 * scale , -16 * scale , 34.4 / 1.2 * scale , 4 * scale , 12 * scale ) // Right Leg // Right Leg - Right model.setTransform(1, 0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 0 * scale , 20 * scale , 4 * scale , 12 * scale , 4 * scale , 26.4 / 1.2 * scale , 4 * scale , 12 * scale ) // Right Leg - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 4 * scale , 20 * scale , 4 * scale , 12 * scale , 8 * scale , 34.4 / 1.2 * scale , 4 * scale , 12 * scale ) // Arm Left // Arm Left - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.scale(-1, 1) model.drawImage (scratchCanv , 44 * scale , 20 * scale , 4 * scale , 12 * scale , -20 * scale , 20 / 1.2 * scale , 4 * scale , 12 * scale ) // Arm Left - Top model.setTransform(-1, 0.5, 1, 0.5, 0, 0) model.drawImage (scratchCanv , 44 * scale , 16 * scale , 4 * scale , 4 * scale , 0 , 16 * scale , 4 * scale , 4 * scale ) // Body // Body - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 20 * scale , 20 * scale , 8 * scale , 12 * scale , 8 * scale , 20 / 1.2 * scale , scaleEight , 12 * scale ) // Arm Right // Arm Right - Right model.setTransform(1, 0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 40 * scale , 20 * scale , 4 * scale , 12 * scale , 0 , 16 / 1.2 * scale , 4 * scale , 12 * scale ) // Arm Right - Front model.setTransform(1, -0.5, 0, 1.2, 0, 0) model.drawImage (scratchCanv , 44 * scale , 20 * scale , 4 * scale , 12 * scale , 4 * scale , 20 / 1.2 * scale , 4 * scale , 12 * scale ) // Arm Right - Top model.setTransform(-1, 0.5, 1, 0.5, 0, 0) model.scale(-1, 1) model.drawImage (scratchCanv , 44 * scale , 16 * scale , 4 * scale , 4 * scale , -16 * scale , 16 * scale , 4 * scale , 4 * scale ) methods.drawHead(model, scratchCanv, scratch, showHat, scale) } }
export default [ { label: 'Users', state: 'main.users' }, { label: 'Albums', state: 'main.albums' } ];
var IB = { color: '0,0,0,1', lineWidth: 1, width: 480, height: 320, end: false, pagenum: document.getElementById('pagenum').innerHTML, dragFlag: false, oldX: 0, oldY: 0, hozon: {oldX: 0, oldY: 0} }; var socket = io.connect('http://tetsuone.rackbox.net:8080'); IB.setStatus = function() { var can = document.getElementById('setting'); var ctx = can.getContext('2d'); ctx.clearRect(0, 0, 100, 100); ctx.strokeStyle = 'rgba(' + IB.color + ')'; ctx.fillStyle = 'rgba(' + IB.color + ')'; ctx.beginPath(); ctx.arc(50, 50, IB.lineWidth / 2, 0, Math.PI*2, false); ctx.stroke(); ctx.fill(); } window.addEventListener('load', function() { var can = document.getElementById('myCanvas'); can.addEventListener('mousemove', IB.draw, true); can.addEventListener('mousedown', function(e) { IB.drawFlag = true; IB.oldX = e.clientX - can.getBoundingClientRect().left; IB.oldY = e.clientY - can.getBoundingClientRect().top; socket.emit('draw', { act: 'start', x: IB.oldX, y: IB.oldY, pagenum: IB.pagenum }); }, false); can.addEventListener('mouseup', function() { IB.drawFlag = false; }, false) }, true); IB.draw = function(e) { if (!IB.drawFlag) { return; } var can = document.getElementById('myCanvas'); var x = e.clientX - can.getBoundingClientRect().left; var y = e.clientY - can.getBoundingClientRect().top; var context = can.getContext('2d'); context.strokeStyle = 'rgba(' + IB.color + ')'; context.lineWidth = IB.lineWidth; context.lineCap = "round"; context.beginPath(); context.moveTo(IB.oldX, IB.oldY); context.lineTo(x, y); context.stroke(); context.closePath(); IB.oldX = x; IB.oldY = y; socket.emit('draw', { act: 'draw', x: x, y: y, color: IB.color, lineWidth: IB.lineWidth }); } socket.on('draw', function(data) { switch (data.act) { case "draw": var can = document.getElementById('myCanvas'); var context = can.getContext('2d'); context.strokeStyle = 'rgba(' + data.color + ')'; context.lineWidth = data.lineWidth; context.lineCap = "round"; context.beginPath(); context.moveTo(IB.hozon.oldX, IB.hozon.oldY); context.lineTo(data.x, data.y); context.stroke(); context.closePath(); IB.hozon.oldX = data.x; IB.hozon.oldY = data.y; break; case "start": IB.hozon.oldX = data.x; IB.hozon.oldY = data.y; break; case "eraze": IB.erase(1); break; case "move": IB.moveTop(); break; } }); socket.on('chat', function(data) { IB.inputComment(data.comment, data.name); }); document.getElementById('color').addEventListener('change', function() { var r = document.getElementById('r').value; var g = document.getElementById('g').value; var b = document.getElementById('b').value; var a = document.getElementById('a').value; IB.changeColor(r + ',' + g + ',' + b + ',' + a); }, true); IB.setColorStatus = function() { var colors = IB.color.split(','); document.getElementById('r').value = colors[0]; document.getElementById('g').value = colors[1]; document.getElementById('b').value = colors[2]; document.getElementById('a').value = colors[3]; }; IB.changeColor = function(color) { IB.color = color; IB.setStatus(); IB.setColorStatus(); } IB.changeLineWidth = function() { var dom = document.getElementsByName('lineWidth'); IB.lineWidth = dom[0].value; IB.setStatus(); } IB.erase = function(flag) { var can = document.getElementById('myCanvas'); var context = can.getContext('2d'); context.clearRect(0, 0, IB.width, IB.height); if(flag !== 1) { socket.emit('draw', { act: 'eraze' }); } } IB.save = function() { var can = document.getElementById('myCanvas'); var d = can.toDataURL('image/png'); var ele = document.getElementsByName('image'); ele[0].value = d; } IB.move = function() { var can = document.getElementById('myCanvas'); var d = can.toDataURL('image/png'); socket.emit('draw', { act: 'move', image: d }); } // Topに移動 IB.moveTop = function() { location.href = 'index.php'; } IB.inputComment = function(comment, name) { var div = document.createElement('div'); div.className = 'cell'; var spanName = document.createElement('span'); spanName.className = 'name'; spanName.innerHTML = name; var spanComment = document.createElement('span'); spanComment.className = 'comment'; spanComment.innerHTML = comment; div.appendChild(spanComment); div.appendChild(spanName); var inner = document.getElementById('chatinner') inner.appendChild(div); document.getElementById('chatcontainer').scrollTop = inner.scrollHeight; } IB.sendChat = function() { var name = document.getElementById('hname').value; var comment = document.getElementById('comment').value; if (comment === '') { return; } IB.inputComment(comment, name); socket.emit('chat', { name: name, comment: comment }); document.getElementById('comment').value = ''; } IB.blink = function() { if (document.all('message').style.visibility == 'visible') { document.all.message.style.visibility = 'hidden'; } else { document.all.message.style.visibility = 'visible'; } if (IB.end) { document.all.message.style.visibility = 'visible'; document.all.complete.style.color = 'blue'; return; } else { setTimeout("IB.blink()", 800); } } IB.hidden = function() { document.all.message.style.visibility = 'hidden'; document.all.complete.style.visibility = 'hidden'; } IB.submit = function() { IB.move(); IB.save(); document.getElementById('submit').submit(); } socket.on('complete', function(data) { document.getElementById('message').innerHTML = '接続完了'; IB.end = true; setTimeout("IB.hidden()", 2000); }); socket.on('image', function(data) { var can = document.getElementById('myCanvas'); var ctx = can.getContext('2d'); var img = new Image(); img.src = data.image; img.onload = function() { ctx.drawImage(img, 0, 0, 480, 320, 0, 0, 480, 320); } }); IB.setColorStatus(); IB.setStatus(); IB.blink();
import React, { PropTypes } from 'react'; import { Link } from 'react-router'; import { FormattedMessage } from 'react-intl'; import styles from './Nav.css'; const Nav = (props, context) => { return( <div className={styles['nav-list']}> <ul> <li><Link to="/home">Home</Link></li> <li><Link to="/">Posts</Link></li> <li><Link to="/about">About</Link></li> </ul> </div> ) } Nav.contextTypes = { router: React.PropTypes.object, }; Nav.propTypes = { }; export default Nav;
/* globals ActiveXObject:false */ 'use strict' module.exports = { load: load } function load (location, callback) { const xhr = getXHR() xhr.open('GET', location, true) xhr.onreadystatechange = createStateChangeListener(xhr, callback) xhr.send() } function createStateChangeListener (xhr, callback) { return function () { if (xhr.readyState === 4 && xhr.status === 200) { try { callback(null, JSON.parse(xhr.responseText)) } catch (err) { callback(err, null) } } } } function getXHR () { return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP') }
class Change { constructor(listLi, optionLi, arrow, wrap) { this.listLi = listLi; this.optionLi = optionLi; this.arrow = arrow; this.wrap = wrap; this.len = optionLi.length; this.index = 0; } init(canTouch) { this.optionSwitch(); this.arrowSwitch(); if(canTouch) { this.touchSwitch(); } } optionSwitch() { $("#option").on("click", (event) => { if(event.target.nodeName=="LI") { let i = parseInt(event.target.id); this.optionLi[this.index].className = ""; this.optionLi[i].className = "active"; this.listLi[this.index].className = ""; this.listLi[i].className = "block"; this.index = i; } }); } arrowSwitch() { $("#arrow").on("click", (event) => { if(event.target.nodeName=="BUTTON"){ this.optionLi[this.index].className = ""; this.listLi[this.index].className = ""; if (event.target.id=="right") { this.index++; if (this.index == this.len) { this.index = 0; } } else { this.index--; if (this.index == -1) { this.index = this.len - 1; } } this.optionLi[this.index].className = "active"; this.listLi[this.index].className = "block"; } }); } touchSwitch() { let startX,endX,moveX; this.wrap.addEventListener("touchstart", (event) => { let touch = event.touches[0]; startX = touch.pageX; }); this.wrap.addEventListener("touchmove", (event) => { event.preventDefault(); let touch = event.touches[0]; endX = touch.pageX; }); this.wrap.addEventListener("touchend", (event) => { event.preventDefault(); moveX = startX - endX; if(moveX>50) { this.optionLi[this.index].className = ""; this.listLi[this.index].className = ""; this.index++; if (this.index == this.len) { this.index = 0; } this.optionLi[this.index].className = "active"; this.listLi[this.index].className = "block"; } else if(moveX<-50) { this.optionLi[this.index].className = ""; this.listLi[this.index].className = ""; this.index--; if (this.index == -1) { this.index = this.len - 1; } this.optionLi[this.index].className = "active"; this.listLi[this.index].className = "block"; } }); } } class ChangeAuto extends Change { constructor(listLi, optionLi, arrow, wrap) { super(listLi, optionLi, arrow, wrap); this.timer = null; } init(canTouch) { this.play(); this.pause(); this.optionSwitch(); this.arrowSwitch(); if(canTouch) { this.touchSwitch(); } } play() { clearInterval(this.timer); this.timer = setInterval(() => { this.optionLi[this.index].className = ""; this.listLi[this.index].className = ""; this.index++; if (this.index == this.len) { this.index = 0; } this.optionLi[this.index].className = "active"; this.listLi[this.index].className = "block"; }, 2000); } pause() { this.wrap.addEventListener("mouseover",() => { clearInterval(this.timer); }); this.wrap.addEventListener("mouseout",() => { this.play(); }); this.wrap.addEventListener("touchstart",() => { clearInterval(this.timer); }); this.wrap.addEventListener("touchend",() => { this.play(); }); } } function adjustSize() { if($(window).width()<768){ document.querySelector("#wrap").className = "visible-xs"; } else{ document.querySelector("#wrap").className = "hidden-xs"; } $(window).resize(() => { adjustSize(); }); } function carousel_init(options) { let defaults = { isAuto : true, canTouch : true } let opts = $.extend(defaults, options); let listLi = document.querySelectorAll("#list li"); let optionLi = document.querySelectorAll("#option li"); let arrow = document.querySelectorAll("#arrow button"); let wrap = document.querySelector("#wrap"); adjustSize(); if(opts.isAuto){ let changeAuto = new ChangeAuto(listLi, optionLi, arrow, wrap); changeAuto.init(opts.canTouch); } else{ let change = new Change(listLi, optionLi, arrow, wrap); change.init(opts.canTouch); } } carousel_init();
import React from 'react'; import PropTypes from 'prop-types'; import { makeStyles, withStyles, useTheme } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Tabs from '@material-ui/core/Tabs'; import Tab from '@material-ui/core/Tab'; import Typography from '@material-ui/core/Typography'; import Box from '@material-ui/core/Box'; import Dashboard from './index'; import Leaderboard from '../AnalystLeaderboardBrowser'; import * as actions from '../../redux/actions/index'; import { connect } from 'react-redux'; const StyledTabs = withStyles({ indicator: { display: 'flex', justifyContent: 'center', backgroundColor: 'transparent', '& > span': { width: '100%', backgroundColor: '#565EBF' } } })(props => <Tabs {...props} TabIndicatorProps={{ children: <span /> }} />); const StyledTab = withStyles(theme => ({ root: { textTransform: 'none', color: '#fff', fontWeight: theme.typography.fontWeightRegular, fontSize: theme.typography.pxToRem(15), marginRight: theme.spacing(1), '&:focus': { opacity: 1 } } }))(props => <Tab disableRipple {...props} />); function TabPanel(props) { const { children, value, index, ...other } = props; return ( <div role='tabpanel' hidden={value !== index} id={`simple-tabpanel-${index}`} aria-labelledby={`simple-tab-${index}`} {...other} > {value === index && ( <Box p={3}> <>{children}</> </Box> )} </div> ); } TabPanel.propTypes = { children: PropTypes.node, index: PropTypes.any.isRequired, value: PropTypes.any.isRequired }; function a11yProps(index) { return { id: `simple-tab-${index}`, 'aria-controls': `simple-tabpanel-${index}` }; } const useStyles = makeStyles(theme => ({ root: { flexGrow: 1, backgroundColor: theme.palette.background.paper } })); const BrowserDashboard = props => { const classes = useStyles(); const [value, setValue] = React.useState(0); React.useEffect(() => { props.getAnalystLeaderboard(); }, []); const handleChange = (event, newValue) => { setValue(newValue); }; return ( <div className={classes.root} style={{ paddingLeft: '5rem', paddingRight: '5rem' }}> <AppBar style={{ backgroundColor: 'transparent', boxShadow: '0px 0px 0px #A9A9A8' }} position='static'> <StyledTabs style={{ backgroundColor: 'transparent', color: '#2B2B2B', borderBottom: '0.5px solid #B1AEC1' }} value={value} onChange={handleChange} aria-label='simple tabs example' > <StyledTab disableTouchRipple={true} aria-label='simple tabs example' style={{ color: value === 0 ? '#565EBF' : '#2B2B2B', textTransform: 'none' }} label='Summary' {...a11yProps(0)} /> <StyledTab disableTouchRipple={true} aria-label='simple tabs example' style={{ color: value === 1 ? '#565EBF' : '#2B2B2B', textTransform: 'none' }} label='Leaderboard' {...a11yProps(1)} /> </StyledTabs> </AppBar> <TabPanel value={value} index={0}> <Dashboard /> </TabPanel> <TabPanel value={value} index={1}> <Leaderboard analyst_leaderboard={props.analyst_leaderboard} /> </TabPanel> </div> ); }; const mapStateToProps = state => ({ message: state.auth.message, analyst_leaderboard: state.analyst.analyst_leaderboard }); const mapDispatchToProps = dispatch => ({ setMessage: message => dispatch(actions.setMessage(message)), getAnalystLeaderboard: () => dispatch(actions.getAnalystLeaderboard()) }); export default connect(mapStateToProps, mapDispatchToProps)(BrowserDashboard);
// Header $(window).on("scroll", function () { let scrollPosition = $(window).scrollTop(); let headerActiveEdge = $(".main__sidebar-btn").offset().top + $(".main__sidebar-btn").outerHeight(); if (scrollPosition >= headerActiveEdge) { $(".header").addClass("--active"); } else { $(".header").removeClass("--active"); } }); // Slider let carousel = $(".slider__wrapper"); // let dots = $(".slider__bottom-paging .dots li"); carousel.flickity({ // option cellAlign: "left", contain: true, wrapAround: true, prevNextButtons: false, pageDots: false, on: { // change: (index) => { // /*--------------*/ // let number = $(".number span"); // number.text((index + 1).toString().padStart(2, 0)); // /*--------------*/ // dots.removeClass("--active"); // dots.eq(index).addClass("--active"); // }, }, }); // flickity control $(".slider__bottom-control #prev").on("click", () => { carousel.flickity("previous"); }); $(".slider__bottom-control #next").on("click", () => { carousel.flickity("next"); }); // $(".slider__bottom-paging .dots").on("click", "li", function () { // let clickedIndex = $(this).index(); // carousel.flickity("select", clickedIndex); // }); // Sidebar $(".main__sidebar-btn").on("click", function () { $("body, html").scrollTop(0); $(".sidebar").addClass("--active"); $(".main__backdrop").addClass("--active"); $("body, html").addClass("--active"); }); $( ".main__backdrop, .sidebar .sidebar__middle .sidebar__middle-logo .-close" ).on("click", function () { $(".sidebar").removeClass("--active"); $(".main__backdrop").removeClass("--active"); $("body, html").removeClass("--active"); }); // Back to top $(".footer__scroll-top").on("click", function () { $("body, html").scrollTop(0); });
import SafeAreaView from 'react-native-safe-area-view'; import { DrawerItems } from 'react-navigation-drawer'; import { Text,View,StyleSheet,ScrollView } from 'react-native' import React from 'react' import { THEME } from '../theme'; export const CustomDrawerContentComponent = (props) => ( <ScrollView> <SafeAreaView style={styles.container} forceInset={{ top: 'always', horizontal: 'never' }} > <View style={styles.title}> <Text style={styles.text}>TachRent</Text> </View> <DrawerItems {...props} /> </SafeAreaView> </ScrollView> ); const styles = StyleSheet.create({ container: { flex: 1, }, title:{ width:'100%', height:'25%', backgroundColor:THEME.MAIN_COLOR }, text:{ fontSize:26, color:'white', paddingLeft:15, paddingTop:10 } });
module.exports = { deleteDog: (req, res) => { const db = req.app.get('db'); const {id} = req.params; // console.log(id) db.delete_dog(+id) .then(data => res.status(200).send(data)) .catch(err => { res.sendStatus(500) }) } }
"use strict"; var expect = require('chai').expect; const stop = require('../src/index'); describe('Enumerations', function() { describe('instance', function() { it('should create a stop instance based on an input string', function() { let stopTestContent = ` enum Type { ONE TWO THREE } start Hello { string test -> Say } stop Say { string words } `; expect(function(){ new stop.Stop(stopTestContent); }).to.not.throw(); }); }); describe('inner', function() { it('should create a stop instance based on an input string', function() { let stopTestContent = ` start Hello { enum Type { ONE TWO THREE } Type type string test -> Say } stop Say { string words } `; expect(function(){ let s = new stop.Stop(stopTestContent); expect(s.enumerations.length, 1, 'enumerations should be 1'); expect(s.enumerations['Hello.Type']).to.exist; expect(s.enumerations['Hello.Type'].name).to.equal('Hello.Type'); }).to.not.throw(); }); }); });
/* eslint-disable no-param-reassign */ import { createSlice } from '@reduxjs/toolkit'; import { NUMBER_OF_QUESTIONS } from 'constants/numbers'; const initialState = { gameState: {}, currentLevel: 1, pastRooms: [], currentRoom: 1, correctStreak: [], gameCompleted: false }; // const samplePayload = { // option: 'right', // isCorrect: true, // question: 'This is the question.', // optionSelected: 'Option selected' // }; const game = createSlice({ name: 'game', initialState, reducers: { updateGameState: (state, { payload }) => { state.gameState[`level-${state.currentLevel}`] = payload; state.pastRooms.push(state.currentRoom); if (payload.option === 'right') { state.currentRoom = state.currentRoom * 2 + 1; } else if (payload.option === 'left') { state.currentRoom *= 2; } state.correctStreak.push(payload.isCorrect); if (state.currentLevel === NUMBER_OF_QUESTIONS) { state.gameCompleted = true; } state.currentLevel += 1; }, resetGameState: state => { state.gameState = initialState.gameState; state.currentLevel = initialState.currentLevel; state.pastRooms = initialState.pastRooms; state.currentRoom = initialState.currentLevel; state.correctStreak = initialState.correctStreak; state.gameCompleted = false; } } }); export const { updateGameState, resetGameState } = game.actions; export default game.reducer;
var mongoose = require('mongoose'), Schema = mongoose.Schema; var seikyoSchema = new Schema({ date: {type: Date, required: true, unique: true}, year: {type: String, required: true}, advertising: [{type: Schema.Types.ObjectId, ref: 'Advertising'}], article: [{type: Schema.Types.ObjectId, ref: 'Article'}], basicTerm: [{type: Schema.Types.ObjectId, ref: 'BasicTerm'}], editorial: [{type: Schema.Types.ObjectId, ref: 'Editorial'}], experience: [{type: Schema.Types.ObjectId, ref: 'Experience'}], femenineDivision: [{type: Schema.Types.ObjectId, ref: 'FemenineDivision'}], futureGroup: [{type: Schema.Types.ObjectId, ref: 'FutureGroup'}], masculineDivision: [{type: Schema.Types.ObjectId, ref: 'MasculineDivision'}], message: [{type: Schema.Types.ObjectId, ref: 'Message'}], monthlyPhrase: [{type: Schema.Types.ObjectId, ref: 'MonthlyPhrase'}], orientation: [{type: Schema.Types.ObjectId, ref: 'Orientation'}], review: [{type: Schema.Types.ObjectId, ref: 'Review'}], sokaAdvance: [{type: Schema.Types.ObjectId, ref: 'SokaAdvance'}], studentGroup: [{type: Schema.Types.ObjectId, ref: 'StudentGroup'}] }); seikyoSchema.virtual('created').get(function () { return this._id.getTimestamp(); }); mongoose.model('Seikyo', seikyoSchema);
import React from "react"; import { useSelector } from "react-redux"; function UserManagementGuard({ children }) { const { user, userPermissions } = useSelector((state) => { return { user: state.user, userToken: state.userPermissions }; }); const isAdmin = user.roles[0].title === "Admin"; return userPermissions?.includes("vendor_access") && isAdmin ? ( children ) : ( <h1>Unauthorized</h1> ); } export default UserManagementGuard;
import basefunction from '../reusable/orgBaseFunctions'; describe('Customer user operations ', () => { const email = Cypress.env('existingEmail'); const password = Cypress.env('existingEmailPwd'); beforeEach(function () { basefunction.login(email, password); }); it('Org Admin can create a service', () => { // Visit services page cy.visit('/admin/servicetype'); // Add new service // Click add button cy.get('.v-btn__content > .router-link-exact-active').click(); // Enter name cy.get('#input-92').clear().type('Automated Test Service'); // Enter price cy.get('#input-96').clear().type('100'); // Enter time cy.get('#input-100').clear().type('60'); // Enter description cy.get('#input-108') .clear() .type('This is a service added automatically by a test'); // Check bookable checkbox cy.get('.v-input--selection-controls__ripple').click(); // Click submit button cy.get('.btn-shadow-primary > .v-btn__content').click(); // Search for new service cy.get('#input-128').clear().type('Automated Test Service'); // Check text shows in service table cy.get('tbody > tr').should('contain', 'Automated Test Service'); // Delete newly added service cy.get(':nth-child(1) > .justify-center > .v-icon--link').click(); }); });
import Home from 'components/Home'; import Blog from 'containers/BlogContainer'; import CommentList from 'components/CommentList'; import UserList from 'containers/UserListContainer'; import User from 'containers/UserContainer'; import { v4 } from 'uuid'; export default [{ id: v4(), path: '/', exact: true, component: Home }, { id: v4(), path: '/blog', exact: true, component: Blog }, { id: v4(), path: '/comments', exact: true, component: CommentList }, { id: v4(), path: '/users', exact: true, component: UserList }, { id: v4(), path: '/users/:id', exact: true, component: User }, ]
// https://bugs.chromium.org/p/chromium/issues/detail?id=564559 let store = new WeakMap(); const _ = (function () { return function (inst) { let obj = store.get(inst); if (!obj) { obj = {}; store.set(inst, obj); }; return obj; }; })(); const Keys = { UP: 38, DOWN: 40, ENTER: 13, ESC: 27, TAB: 9 }; /** * Public methods for DropdownInterface * are available through this class. * * @class DropdownInterface */ class DropdownInterface { constructor (options) { if (!options.parent || !(options.parent instanceof HTMLElement)) { throw new Error('"parent" option must be specified and assigned to a HTMLElement.'); } this.setItems(options.items || []); _(this).onItemSelected = options.onItemSelected; _(this).onItemRender = options.onItemRender; _(this).onListShow = options.onListShow; _(this).onListHide = options.onListHide; _(this).focusIndex = 0; _(this).isShowing = false; _(this).element = document.createElement('div'); _(this).element.setAttribute('class', 'DropdownInterface'); _(this).parent = options.parent; } toggle () { if (!_(this).isShowing) { this.showList(); } else { this.hideList(); } } setFocusedItem (index) { setFocusedItem.call(this, index); } setItems (items) { _(this).items = items.slice(0); _(this).focusIndex = 0; if (_(this).isShowing) { hideList.call(this); showList.call(this); } } isShowing () { return _(this).isShowing; } showList () { showList.call(this); } hideList () { hideList.call(this); } handleKeyDown (e) { handleKeyDown.call(this, e); } destroy () { this.hideList(); // Shouldn't need to do this, but better safe than sorry to prevent memory leaks. store.delete(this); } } /** * Wrapper around native addEventListener so that * events can be easily subscribed to and unsubscribed * despite passing a bound function. * * @method addEventListener * @param {HTMLElement} el * @param {String} name * @param {Function} callback * @return {Object} */ function addEventListener(el, name, callback, capture) { el.addEventListener(name, callback, capture); return { stop: function () { el.removeEventListener(name, callback, capture); } }; } function preventWindowScrollOnArrowKey (e) { if (getFocusableElement.call(this) === document.activeElement && (e.keyCode === Keys.UP || e.keyCode === Keys.DOWN)) { e.preventDefault(); } } /** * Finds the nearest focusable element in the parent. * * @method getFocusableElement * @return {HTMLElement} */ function getFocusableElement () { let selector = '[tabindex], input, button, textarea'; if (_(this).parent.matches(selector)) { return _(this).parent; } return _(this).parent.querySelector(selector); } /** * Gets the item and triggers onItemSelected. * * @method onItemClick */ function onItemClick (e) { e.stopPropagation(); let index = parseInt(e.currentTarget.getAttribute('data-index')); setFocusedItem.call(this, index); triggerItemSelected.call(this); let focusable = getFocusableElement.call(this); if (focusable) { focusable.focus(); } } /** * Focuses on the item the user hovers over. * * @method onItemHover */ function onItemHover (e) { let index = parseInt(e.target.getAttribute('data-index')); setFocusedItem.call(this, index); } /** * Calls the onItemSelected option passed into the constructor * passing the selected item. * * @method triggerItemSelected */ function triggerItemSelected () { let item = _(this).items[_(this).focusIndex]; if (!item.disabled) { hideList.call(this); _(this).onItemSelected.call(undefined, item); } } /** * Key events for when the parent is focused. * * @method handleKeyDown */ function handleKeyDown (e) { // We don't want to stop propagation all of the time, only if we // actually respond to the event ourselves. This is useful to ensure // that components like dialogs will still function correctly. if (!_(this).isShowing) { if (e.keyCode === Keys.DOWN) { e.stopPropagation(); if (e.preventDefault) { e.preventDefault(); // stops scrolling of page } showList.call(this); } return; } switch (e.keyCode) { case Keys.ENTER: e.stopPropagation(); triggerItemSelected.call(this); break; case Keys.TAB: e.stopPropagation(); triggerItemSelected.call(this); break; case Keys.ESC: e.stopPropagation(); hideList.call(this); break; case Keys.DOWN: e.stopPropagation(); focusNextItem.call(this); break; case Keys.UP: e.stopPropagation(); focusPrevItem.call(this); break; } } /** * Renders the list and displays it * inline with the parent. * * @method showList */ function showList () { if (_(this).isShowing) { return; } _(this).isShowing = true; // Render the list items render.call(this); document.body.appendChild(_(this).element); _(this).wheelEvent = addEventListener(_(this).element, 'mousewheel', (e) => { let scrollTop = _(this).element.scrollTop; let scrollHeight = _(this).element.scrollHeight - _(this).element.offsetHeight; let dir = e.wheelDelta > 0? 1 : -1; if ( (scrollTop === 0 && dir === 1) || (scrollTop >= scrollHeight && dir === -1) ) { e.preventDefault(); } }); _(this).preventScrollEvent = addEventListener(document, 'keydown', preventWindowScrollOnArrowKey.bind(this), true); // Add Event Listeners to list items. let itemEls = _(this).element.querySelectorAll('.item'); [].forEach.call(itemEls, el => { el.addEventListener('click', onItemClick.bind(this)); el.addEventListener('mouseenter', onItemHover.bind(this)); // Make sure we remain focused on the current parent. el.addEventListener('mousedown', () => { // Skipping a frame so that it goes to body and then we can take the focus back. requestAnimationFrame(() => { getFocusableElement.call(this).focus(); }); }); }); // Position the element let rect = _(this).parent.getBoundingClientRect(); _(this).element.style.top = rect.bottom + 'px'; _(this).element.style.left = rect.left + 'px'; _(this).element.style.width = rect.width + 'px'; // Flip the list if it's getting cropped below the window. let listHeight = _(this).element.offsetHeight; if (rect.bottom + listHeight >= window.innerHeight) { _(this).element.style.top = rect.top - listHeight + 'px'; } if (!_(this).bodyListener) { _(this).bodyListener = addEventListener(document.body, 'click', (e) => { // If we don't check if we're clicking on the input itself, // we could end up with a scenario where both the input and the body respond // calling the hideList and showList functions at the same time causing // nothing to happen. if (!_(this).parent !== e.target && !_(this).parent.contains(e.target)) { this.hideList(); } }); } if (!_(this).scrollListener) { let scrollListener = () => { // If the parent moves, close the list. let newPos = _(this).parent.getBoundingClientRect(); if (newPos.top !== rect.top || newPos.left !== rect.left) { this.hideList(); } else { _(this).scrollListener = requestAnimationFrame(scrollListener); } }; _(this).scrollListener = requestAnimationFrame(scrollListener); } setFocusedItem.call(this, _(this).focusIndex); if (_(this).onListShow) { _(this).onListShow(); } } /** * Removes the list and cleans up events. * * @method hideList */ function hideList () { if (_(this).isShowing) { _(this).isShowing = false; _(this).bodyListener.stop(); _(this).bodyListener = undefined; cancelAnimationFrame(_(this).scrollListener); _(this).scrollListener = undefined; _(this).wheelEvent.stop(); _(this).preventScrollEvent.stop(); document.body.removeChild(_(this).element); if (_(this).onListHide) { _(this).onListHide(); } } } /** * Focuses on the next item below the current focused item. * * @method focusNextItem */ function focusNextItem () { let focusIndex = _(this).focusIndex + 1; if (focusIndex === _(this).items.length) { focusIndex = 0; } setFocusedItem.call(this, focusIndex); } /** * Focuses on the previous item above the current focused item. * * @method focusPrevItem */ function focusPrevItem () { let focusIndex = _(this).focusIndex - 1; if (focusIndex < 0) { focusIndex = _(this).items.length - 1; } setFocusedItem.call(this, focusIndex); } /** * Sets the focus index and updates the visuals. * * @method setFocusedItem * @param {Number} newIndex */ function setFocusedItem (newIndex) { _(this).focusIndex = newIndex; let els = _(this).element.querySelectorAll('.item'); [].forEach.call(els, (el, index) => { if (index === _(this).focusIndex) { el.classList.add('focused'); } else { el.classList.remove('focused'); } }); // Need to scroll the element into view. let el = _(this).element.querySelector('.item.focused'); if (_(this).isShowing && el) { let parent = el.offsetParent.getBoundingClientRect(); let rect = el.getBoundingClientRect(); if (rect.bottom < parent.top || rect.top < parent.top) { el.offsetParent.scrollTop = el.offsetTop; } else if (rect.bottom > parent.bottom || rect.top > parent.bottom) { el.offsetParent.scrollTop = el.offsetTop - (parent.height - el.offsetHeight); } } } /** * Wipes out and renders the latest items. * * @method render */ function render () { _(this).element.innerHTML = ''; _(this).items.forEach((item, index) => { let el = document.createElement('div'); el.setAttribute('class', 'item'); el.setAttribute('data-index', index); if (item.disabled) { el.classList.add('disabled'); } if (_(this).onItemRender) { _(this).onItemRender.call(undefined, el, item); } else { el.textContent = item.label; } _(this).element.appendChild(el); }); } export default DropdownInterface;
const test = require('tape'); const merge = require('./merge.js'); test('Testing merge', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof merge === 'function', 'merge is a Function'); const object = { a: [{ x: 2 }, { y: 4 }], b: 1 }; const other = { a: { z: 3 }, b: [2, 3], c: 'foo' }; t.deepEqual(merge(object, other), { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }, 'Merges two objects'); //t.deepEqual(merge(args..), 'Expected'); //t.equal(merge(args..), 'Expected'); //t.false(merge(args..), 'Expected'); //t.throws(merge(args..), 'Expected'); t.end(); });
import React from 'react'; import {View, Text, StyleSheet, Image, TouchableOpacity, TextInput, ScrollView} from 'react-native'; import {LinearGradient} from "expo-linear-gradient"; export function LocationComments(props) { return ( <View> <View style={styles.commentsContainer}> <View style={styles.comment}> <TouchableOpacity style={[styles.userAvatar, styles.userAvatarDirectionToRight]}> <Image style={styles.avatarImage} source={require('./../assets/mapAssets/user.png')}></Image> <Text style={styles.avatarTxt}>username</Text> </TouchableOpacity> <View style={styles.userComment}> {getDecorationImage(0)} <View style={styles.commentContent}> <Text> Lorem ipsum costam costam and so on... Lorem ipsum costam costam and so on... Lorem ipsum costam costam and so on... Lorem ipsum costam costam and so on... </Text> <View style={styles.likes}> </View> </View> </View> </View> <View style={styles.comment}> <TouchableOpacity style={[styles.userAvatar, styles.userAvatarDirectionToLeft]}> <Image style={styles.avatarImage} source={require('./../assets/mapAssets/user.png')}></Image> <Text style={styles.avatarTxt}>username</Text> </TouchableOpacity> <View style={styles.userComment}> {getDecorationImage(1)} <View style={styles.commentContent}> <Text> Lorem ipsum costam costam and so on... Lorem ipsum costam costam and so on... Lorem ipsum costam costam and so on... Lorem ipsum costam costam and so on... </Text> <View style={styles.likes}> </View> </View> </View> </View> <View style={styles.comment}> <TouchableOpacity style={[styles.userAvatar, styles.userAvatarDirectionToRight]}> <Image style={styles.avatarImage} source={require('./../assets/mapAssets/user.png')}></Image> <Text style={styles.avatarTxt}>username</Text> <View style={styles.likes}> </View> </TouchableOpacity> <View style={styles.userComment}> {getDecorationImage(0)} <View style={styles.commentContent}> <Text> Lorem ipsum costam costam and so on... Lorem ipsum costam costam and so on... Lorem ipsum costam costam and so on... Lorem ipsum costam costam and so on... </Text> </View> </View> </View> </View> <View> <TextInput placeholder="Add comment" style={styles.textInputStyle} numberOfLines={5}></TextInput> <TouchableOpacity> <LinearGradient colors={['#FF633B', '#FD9668']} style={styles.buttonStyle} start={{x: 0, y: 0.5}} end={{x: 1, y: 0.5}}> <Text style={{color: 'white', textAlign: 'center', fontWeight: "bold"}}>Add comment</Text> </LinearGradient> </TouchableOpacity> </View> </View> ) } function getDecorationImage(number) { if (number % 2 === 0) { return (<Image style={[styles.commentDecoration, styles.commentDecorationLeft]} source={require('./../assets/mapAssets/tail.png')}></Image>) } return ( <Image style={[styles.commentDecoration, styles.commentDecorationRight]} source={require('./../assets/mapAssets/tail-l.png')}></Image> ) } const styles = StyleSheet.create({ likes: {}, textInputStyle: { borderWidth: 1, borderColor: 'gray', borderRadius: 10, paddingVertical: 10, paddingHorizontal: 15, fontSize: 15, backgroundColor: 'white', marginVertical: 5 }, comment: { backgroundColor: 'whitesmoke', paddingVertical: 20, paddingHorizontal: 10, borderRadius: 10, marginVertical: 5, marginHorizontal: 2, elevation: 1 }, userAvatar: { alignItems: 'center' }, avatarImage: { marginHorizontal: 5, width: 35, height: 35 }, avatarTxt: { color: '#FF633B' }, userAvatarDirectionToRight: { flexDirection: 'row' }, userAvatarDirectionToLeft: { flexDirection: 'row-reverse' }, commentsContainer: { paddingVertical: 20 }, userComment: { position: 'relative', paddingTop: 9 }, commentDecoration: { width: 10, height: 9, position: 'absolute', top: 5 }, commentDecorationLeft: { left: 20 }, commentDecorationRight: { right: 20 }, commentContent: { borderRadius: 5, backgroundColor: 'white', padding: 20, elevation: 1 }, buttonStyle: { paddingVertical: 20, //paddingHorizontal: 10, marginVertical: 5, elevation: 3, borderRadius: 10 } })
const mongoose = require('mongoose'); const NoteSchema = mongoose.Schema({ name: String, birth: String, nik: Number, email: String, }, { timestamps: true }); module.exports = mongoose.model('Mahasiswa', NoteSchema);
import {userConstants} from "./constants"; import axios from "../helpers/axios"; export const signup = (user) => { return async (dispatch) => { dispatch({ type: userConstants.USER_REGISTER_REQUEST }); try { const res = await axios.post(`/wp/v2/users/register`, { ...user }, { "headers": { "content-type": "application/json", } } ); if (res.status === 200){ const { message } = res.data; dispatch({ type: userConstants.USER_REGISTER_SUCCESS, payload: { message, user: {...user} } }); } } catch (error) { if (error.response.status === 400) { dispatch({ type: userConstants.USER_REGISTER_FAILURE, payload: { error: error.response.data.message } }); } } } }
import React from "react"; import Input from "../common/Input"; const Login = ({ username, password, handleSubmit, handleChange, errors, validate }) => { return ( <div className='loginForm d-flex h-100'> <div className='col-lg-5 col-xl-3 col-md-6 mx-auto my-auto'> <h3 className='display-4 text-light text-center mb-4'>WELCOME</h3> <p className='text-muted mb-4 text-center'> Key in your credentials to login </p> <form onSubmit={handleSubmit}> <Input type='text' name='username' value={username} placeholder='Username' error={errors.username} handleSubmit={handleSubmit} handleChange={handleChange} /> <Input type='password' name='password' value={password} placeholder='Password' error={errors.password} handleSubmit={handleSubmit} handleChange={handleChange} /> <button disabled={validate()} // type='submit' className='btn btn-primary btn-block text-uppercase mb-2 rounded-pill shadow-sm' > LogIn </button> </form> <p className="text-center" style={{color:"white"}}> Username: <span style={{color:"red"}}><i><u>root</u></i></span> Password: <span style={{color:"red"}}><i><u>rootAdmin</u></i></span> </p> </div> </div> ); }; export default Login;
const request = require("postman-request"); const forecast = (latitude, longitude, cb) => { const url = `http://api.weatherstack.com/current?access_key=3a111df34fb03bd85a8b669440f5c08a&query=${latitude},${longitude}`; request({ url, json: true }, (error, response) => { if (error) { cb(error.info); } else if (response.body.error) { cb(response.body.error); } else { const { temperature, feelslike } = response.body.current; cb(undefined, { temperature, feelslike, }); } }); }; module.exports = forecast;
import { connect } from 'react-redux'; import { push } from 'connected-react-router'; import { actions as historyActions } from '../modules/history/action'; import { actions as bookmarkActions } from '../modules/bookmark/action'; import Movie from '../components/movie/index.jsx'; import File from '../models/file'; import { getUrlFromFile } from '../utils/consts'; function mapStateToProps(state) { return { current: new File(state.common.current_file), is_playing_bookmark: !!state.bookmark.playing, }; } function mapDispatchToProps(dispatch) { return { timeupdate: (id, sec) => { dispatch(historyActions.update(id, sec)); } }; } export default connect( mapStateToProps, mapDispatchToProps )(Movie);
var imagesSRC = "static/images/"; function processJSON(data) { // now tab putNowTabValues(data); // day tab var dayTab = ""; for (var i = 1; i < 26; i++) { try { dayTab += createHourRow(data['hourly']['data'][i], i, data['thisCity']); } catch (e) { } } if (dayTab == "") { dayTab += "<tr><td colspan='5'>" + "<div class='alert alert-warning'>" + "There is no daily data for this location." + "</div>" + "</td></tr>"; } $(".table.days-table tbody").html(dayTab); // week tab var weekTab = ""; for (var j = 1; j < 8; j++) { try { weekTab += createDayCard(data['daily']['data'][j], j, data['thisCity']); } catch (e) { } } if (weekTab == "") { weekTab += "<div class='alert alert-warning'>" + "There is no week data for this location." + "</div>"; } $(".day-cards").html(weekTab); correctUnits(data['thisUnit']); } function getIcon(name) { switch (name) { case "clear-day": return "clear.png"; case "clear-night": return "clear_night.png"; case "rain": return "rain.png"; case "snow": return "snow.png"; case "sleet": return "sleet.png"; case "wind": return "wind.png"; case "fog": return "fog.png"; case "cloudy": return "cloudy.png"; case "partly-cloudy-day": return "cloud_day.png"; case "partly-cloudy-night": return "cloud_night.png"; default: return "clear.png"; } } function correctUnits(unit) { if (unit == "us") { $(".temp-unit").html("&#8457"); $(".speed-unit").html("mph"); $(".distance-unit").html("mi"); $(".pressure-unit").html("mb"); } else { $(".temp-unit").html("&#8451"); $(".speed-unit").html("m/s"); $(".distance-unit").html("km"); $(".pressure-unit").html("hPa"); } } function findPrecipitation(pre, unit) { if (unit == "si") { pre *= 0.0393701; } if (pre < 0.002) { return "None"; } else if (pre < 0.017) { return "Very Light"; } else if (pre < 0.1) { return "Light"; } else if (pre < 0.4) { return "Moderate"; } else { return "Heavy"; } } function putNowTabValues(data) { $(".now-current .image img").attr('src', imagesSRC + getIcon(data['currently']['icon'])) .attr('alt', data['currently']['summary']) .attr('title', data['currently']['summary']); $(".now-current .summary").html(data['currently']['summary']); $(".now-current .city-name").html(data['thisCity'] + ", " + data['thisState']); $(".now-current h1 .weather").html(parseInt(data['currently']['temperature'])); $(".now-current .low-temp").html(parseInt(data['daily']['data'][0]['temperatureMin'])); $(".now-current .high-temp").html(parseInt(data['daily']['data'][0]['temperatureMax'])); // fb params: fbOk = true; fbParams['name'] = "Current Weather in " + data['thisCity'] + ", " + data['thisState']; fbParams["description"] = data['currently']['summary'] + ", " + parseInt(data['currently']['temperature']) + "\xB0" + (data['thisUnit'] == "us" ? "F" : "C"); fbParams['picture'] = "http://forecast.arefsh.me/static/images/" + getIcon(data['currently']["icon"]); $(".now-current .now-precipitation").html(findPrecipitation(parseFloat(data['currently']['precipIntensity']), data['thisUnit'])); $(".now-current .now-rainchance span").html(parseInt(data["currently"]["precipProbability"]) * 100); $(".now-current .now-wind .num").html(parseFloat(data["currently"]["windSpeed"])); $(".now-current .now-dew .num").html(parseFloat(data["currently"]["dewPoint"])); $(".now-current .now-visibility .num").html(parseFloat(data["currently"]["visibility"])); $(".now-current .now-humidity span").html(parseInt(data["currently"]["humidity"])); $(".now-current .now-sunrise").html(moment.tz(new Date(data['daily']['data'][0]['sunriseTime'] * 1000), data["timezone"]).format("hh:mm A")); $(".now-current .now-sunset").html(moment.tz(new Date(data['daily']['data'][0]['sunsetTime'] * 1000), data["timezone"]).format("hh:mm A")); } function createHourRow(data, index) { var row = "<tr>"; row += "<td>" + (data['time'] != undefined ? moment.tz(new Date(data['time'] * 1000), data["timezone"]).format("hh:mm A") : "N/A") + "</td>"; if (data['icon']) { row += "<td><img width='40' height='40' src='" + imagesSRC + getIcon(data['icon']) + "'"; row += " alt='" + (data['summary'] ? data['summary'] : "") + "'"; row += " title='" + (data['summary'] ? data['summary'] : "") + "'"; row += "/></td>"; } else { row += "<td>N/A</td>"; } row += "<td>" + (data['cloudCover'] != undefined ? parseInt(parseFloat(data['cloudCover']) * 100) : "N/A") + "%</td>"; row += "<td>" + (data['temperature'] != undefined ? parseFloat(data['temperature']) : "N/A") + "</td>"; row += '<td><a role="button" data-toggle="collapse" href="#tab-day-details-' + index + '">'; row += '<i class="glyphicon glyphicon-plus"></i></td></tr>'; row += '<tr class="tab-day-row-collapse"><td colspan="5">'; row += '<div id="tab-day-details-' + index + '" class="collapse well"><div class="table-responsive">'; row += '<table class="table details-table"><thead><tr><th>Wind</th><th>Humidity</th>'; row += '<th>Visibility</th><th>Pressure</th></tr></thead><tbody><tr>'; row += '<td>' + (data['windSpeed'] != undefined ? data['windSpeed'] : "N/A") + "<span class='speed-unit'></span></td>"; row += '<td>' + (data['humidity'] != undefined ? parseInt(parseFloat(data['humidity']) * 100) : "N/A") + "%</td>"; row += '<td>' + (data['visibility'] != undefined ? data['visibility'] : "N/A") + "<span class='distance-unit'></span></td>"; row += '<td>' + (data['pressure'] != undefined ? data['pressure'] : "N/A") + "<span class='pressure-unit'></span></td>"; row += "</tr></tbody></table></div></div></td></tr>"; return row; } function createDayCard(data, index, city) { var date = (data['time'] ? moment.tz(new Date(data['time'] * 1000), data["timezone"]).format("MMM D") : "N/A"); var day = (data['time'] ? moment.tz(new Date(data['time'] * 1000), data["timezone"]).format("dddd") : "N/A"); var card = '<div class="col-lg-1 col-md-1 col-xs-11 col-sm-11 day-card day-card-' + index + '" data-toggle="modal" '; card += 'data-target="#show-details-modal-' + index + '" >'; card += "<h4 class='day'>" + day + "</h4>"; card += "<h4 class='date'>" + date + "</h4>"; if (data['icon']) { card += "<img width='70' height='70' src='" + imagesSRC + getIcon(data['icon']) + "'"; card += " alt='" + (data['summary'] ? data['summary'] : "") + "'"; card += " title='" + (data['summary'] ? data['summary'] : "") + "'"; card += "/>"; } else { } card += '<h5>Min</h5><h5>Temp</h5>'; card += '<h2>' + (data['temperatureMin'] != undefined ? parseInt(data['temperatureMin']) : "N/A") + '&deg;</h2>'; card += '<h5>Max</h5><h5>Temp</h5>'; card += '<h2>' + (data['temperatureMax'] != undefined ? parseInt(data['temperatureMax']) : "N/A") + '&deg;</h2>'; card += "</div>"; card += "<div id='show-details-modal-" + index + "' class='modal fade' role='dialog'>"; card += '<div class="modal-dialog"><div class="modal-content"><div class="modal-header">'; card += '<button type="button" class="close" data-dismiss="modal">&times;</button>'; card += '<h4 class="modal-title">Weather in ' + city + ' on ' + date + '</h4>'; card += '</div><div class="modal-body">'; if (data['icon']) { card += "<img width='250' height='220' src='" + imagesSRC + getIcon(data['icon']) + "'"; card += " alt='" + (data['summary'] ? data['summary'] : "") + "'"; card += " title='" + (data['summary'] ? data['summary'] : "") + "'"; card += "/>"; } card += '<div><h3>' + day + ': <span class="orange">' + (data['summary'] ? data['summary'] : "N/A") + '</span></h3></div>'; card += '<div class="row"><div class="col-md-4 col-xs-12 col-sm-12">'; card += '<h4>Sunrise Time</h4>'; card += '<div>' + (data['sunriseTime'] != undefined ? moment.tz(new Date(data['sunriseTime'] * 1000), data["timezone"]).format("hh:mm A") : "N/A") + '</div>'; card += '<h4>Wind Speed</h4>'; card += '<div>' + (data['windSpeed'] != undefined ? data['windSpeed'] : "N/A") + '<span class="speed-unit"></span></div></div>'; card += '<div class="col-md-4 col-xs-12 col-sm-12"><h4>Sunset Time</h4>'; card += '<div>' + (data['sunsetTime'] != undefined ? moment.tz(new Date(data['sunsetTime'] * 1000), data["timezone"]).format("hh:mm A") : "N/A") + '</div>'; card += '<h4>Visibility</h4>'; card += '<div>' + (data['visibility'] != undefined ? data['visibility'] + "<span class='distance-unit'></span>" : "N/A") + "</div></div>"; card += '<div class="col-md-4 col-xs-12 col-sm-12"><h4>Humidity</h4>'; card += '<div>' + (data['humidity'] != undefined ? parseInt(parseFloat(data['humidity']) * 100) : "N/A") + '%</div>'; card += '<h4>Pressure</h4>'; card += '<div>' + (data['pressure'] != undefined ? data['pressure'] + '<span class="pressure-unit"></span>' : "N/A") + '</div></div></div></div>'; card += '<div class="modal-footer">'; card += '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'; card += '</div></div></div></div>'; return card; }
/** * Created by wen on 2016/8/16. */ import React, { PropTypes,Component } from 'react'; import ClassName from 'classnames'; import {IconText,Button,Toast} from "../../../components"; import s from './memberAccount.css'; import {clientFetch} from "../../../utils/clientFetch"; import history from "../../../core/history"; class MemberAccount extends Component { constructor(props) { super(props); this.state = { code: "", isToast: false, ToastMsg: "", isBtn: true, mobileCode: "", }; } static contextTypes = { insertCss: PropTypes.func.isRequired, setTitle: PropTypes.func.isRequired, setState: PropTypes.func, showLoad: PropTypes.func, clearLoad: PropTypes.func, }; componentWillMount() { const { insertCss,setTitle } = this.context; this.removeCss = insertCss(s); setTitle("注册精选者会员"); } componentDidMount() { this.context.clearLoad(); this.imgCode(); } componentWillUnmount() { this.removeCss() } getValue(dom) { return this.refs[dom].getValue(); } btnCB() { let getInputval = this.getInputval(); if (this.matchValue(getInputval)) { if (getInputval.code.val == this.state.mobileCode) { clientFetch("/member/register", { account_name: getInputval.phone.val, password: getInputval.password.val, }).then(res=> { if (res.code === 200) { localStorage.setItem("account_name",getInputval.phone.val); window.location.href="/boutiquerMember/renew_get?type=register"; } else { this.showToast({msg: res.message}); } }) } else { this.showToast({msg: "验证码不正确"}); } } } imgCode() { clientFetch("/code", {}).then(result=> { this.setState({ code: 'data:image/jpeg;base64,' + result.img, }) }); } getSendCode() { let val = this.getInputval(); if (val.phone.state && val.figureCode.state) { clientFetch("/code", {code: val.figureCode.val}).then(res=> { if (res.code === 200 && res.success === "成功") { return clientFetch("/member/getMobileCode", {mobile: val.phone.val}) } else { this.showToast({msg: "验证码输入错误"}); this.imgCode(); } }).then((res)=> { console.log(res); if (res.code == 0) { this.countdown(); this.state.mobileCode = res.data.code; } else { this.showToast({msg: res.msg}); } }) } else { this.matchValue(val); } } matchValue(opt) { for (var o in opt) { if (!opt[o].state) { return this.showToast(opt[o]); } } return true; } getInputval() { return { phone: this.getValue("mobile"), figureCode: this.getValue("figureCode"), code: this.getValue("valiCode"), password: this.getValue("password"), } } countdown() { let code = this.refs.code, s = 60; let clear = setInterval(()=> { if (!s--) { code.removeAttribute("disabled"); code.style.background = "#1E9EF7"; code.innerHTML = "获取验证码"; clearInterval(clear); return; } code.setAttribute("disabled", "disabled"); code.style.background = "#ccc"; code.innerHTML = "(" + (s) + ")" + " 重新获取"; }, 1000); } showToast(opt) { this.setState({ isToast: false, }) setTimeout(()=> { this.setState({ isToast: true, ToastMsg: opt.msg }) }, 10) } filterVlalue(current) { let result; switch (current) { case 'mobile': result = this.getValue("mobile") !result.state && this.showToast(result); break; case 'figureCode': result = this.getValue("figureCode"); !result.state && this.showToast(result); break; case 'valiCode': result = this.getValue("valiCode"); !result.state && this.showToast(result); break; case 'password': result = this.getValue("password"); !result.state && this.showToast(result); break; } } onBlur() { let val = this.getInputval(); if (val.phone.type !== "required" && val.figureCode.type !== "required") { this.setState({ isBtn: false, }) } } render() { let dis = this.state.isBtn ? <button ref="code" disabled onClick={this.getSendCode.bind(this)}>获取验证码</button> : <button ref="code" className={ClassName(s.getCode)} onClick={this.getSendCode.bind(this)}>获取验证码</button> return ( <div id="box"> {this.state.isToast && <Toast showText={this.state.ToastMsg}/>} <div className={s.wrapper}> <h4>会员账号</h4> <IconText ref="mobile" onBlur={this.onBlur.bind(this,"mobile")} type="phone" validaType={['required',"mobile"]} placeholder="请填写您的手机号" /> <div className={s.sendCode}> <IconText ref="figureCode" type="safetycode" validaType={['required',"figureCode"]} onBlur={this.onBlur.bind(this,"figureCode")} btnStyle={["bg1","radius","fz5","color1","w5"]} placeholder="请填写图形验证码"/> <img src={this.state.code} onClick={this.imgCode.bind(this)} alt=""/> </div> <div className={s.sendCode}> <IconText ref="valiCode" type="safetycode" validaType={['required',"valiCode"]} btnStyle={["bg1","radius","fz5","color1","w5"]} placeholder="请填写手机验证码"/> {dis} </div> <IconText id="password" ref="password" type="password" validaType={['required',"pwd"]} placeholder="请填写你的账号密码"/> </div> <Button btnStyle={["bg1","fz5","color1","w10"]} className={s.ttt} btnText="去支付" btnCB={this.btnCB.bind(this)}/> </div> ); } } export default MemberAccount;
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import fs from 'fs'; import beautify from 'js-beautify'; import { CardEditor } from './CardEditor.js'; describe("Card Edition", () => { it('should edit a card from scratch', () => { const card = { "name": "Nouvelle carte", "content": [] }; const rendered = printCardEditor(card); expect(rendered) .toBe(expectedFile('edit_card_from_scratch.html')); }); it('should edit card title', () => { const card = { "name": "Ma Carte", "content": [ { "type": "title", "content": "Titre de ma carte" } ] }; const rendered = printCardEditor(card); expect(rendered) .toBe(expectedFile('edit_card_with_a_title.html')); }); it('should edit card field', () => { const card = { "name": "Ma Carte", "content": [ { "type": "field", "header" : "Type de carte", "content": "MJ" } ] }; const rendered = printCardEditor(card); expect(rendered) .toBe(expectedFile('edit_card_with_a_field.html')); }); it('should edit card text', () => { const card = { "name": "Ma Carte", "content": [ { "type": "text", "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam dui magna, tristique ac volutpat sed, sollicitudin molestie magna. Cras sed purus at metus viverra venenatis a et dolor. Pellentesque egestas nisi in mollis aliquam. Sed fermentum tincidunt. Nulla interdum venenatis sapien, sit amet condimentum lectus. Phasellus malesuada semper quam, ut pulvinar dolor iaculis vitae. Praesent eu lorem quis nisl lobortis venenatis non id massa. Curabitur non ex sodales, mollis tellus in, dapibus purus. Maecenas eget odio commodo, posuere sapien eget, congue arcu. Donec id facilisis lectus. Proin vitae ipsum libero. Quisque vitae tellus dui. Nulla tincidunt est ac quam faucibus, a lobortis elit venenatis. Sed quis neque sit amet leo finibus cursus. Aenean gravida consectetur erat, sit amet lobortis magna volutpat iaculis." } ] }; const rendered = printCardEditor(card); expect(rendered) .toBe(expectedFile('edit_card_with_a_text.html')); }); }); function printCardEditor(card) { const renderRoot = document.createElement('div'); ReactDOM.render( <CardEditor card={card} />, renderRoot ); return beautify.html(renderRoot.innerHTML); } function expectedFile(filename){ return fs.readFileSync('./src/codex/expects/'+ filename, 'utf-8').trim(); }
import React from 'react' import PropTypes from 'prop-types' import {browserHistory} from 'react-router' // redux import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import {validate} from 'sapin' import { reduxForm } from 'redux-form' // actions and selectors import config from '../../modules/clients/config' import { ActionCreators as AppActions } from '../../modules/app/actions' import { ActionCreators as ClientActions } from '../../modules/clients/actions' import { ActionCreators as FormActions } from '../../modules/form-templates/actions' import ClientSelectors from '../../modules/clients/selectors' import ClientFormSelectors from '../../modules/clients/client-form-selectors' import { getLocale } from '../../modules/app/selectors' // sections tabs components import { FormError } from '../components/forms/FormError' import {Form} from '../components/controls/SemanticControls' import {createTranslate} from '../../locales/translate' import StandardEditToolbar from '../components/behavioral/StandardEditToolbar' import DocumentDynamicForm from './components/DocumentDynamicForm' const labelNamespace = 'clients' const baseUrl = '/clients/' const mapDispatchToProps = (dispatch) => { return { actions: bindActionCreators(ClientActions, dispatch), appActions: bindActionCreators(AppActions, dispatch), formActions: bindActionCreators(FormActions, dispatch) } } class EditClientPage extends React.PureComponent { constructor (props) { super(props) this.handleSubmit = this.handleSubmit.bind(this) this.message = createTranslate(labelNamespace, this) this.handlers = {} } componentWillMount () { const id = this.props.params.id || null this.props.formActions.fetchList({limit: 1000, includeArchived: true}) this.props.actions.fetchClientForm() if (id !== null) { this.props.actions.clearEditedEntity() this.props.actions.fetchEditedEntity(id) } else { this.props.actions.setEditedEntity(ClientSelectors.buildNewEntity()) } } handleSubmit () { const isNew = this.props.isNew const notify = this.props.appActions.notify this.props.actions.saveEntity(this.props.client, (entity) => { if (isNew) { browserHistory.replace(baseUrl + entity.id) } browserHistory.goBack() notify('common.save', 'common.saved') }) } render () { const {canSave, error, locale, isNew, isLoading} = this.props const titleLabelKey = isNew ? 'create-title' : 'edit-title' if (isLoading) return null return ( <div> <StandardEditToolbar location={this.props.location} title={this.message(titleLabelKey)} backTo={baseUrl} onSaveClicked={this.handleSubmit} locale={locale} canSave={canSave} /> <FormError error={error} locale={locale} /> <Form> <DocumentDynamicForm controlsById={this.props.formControlsById} controlIdsByParentId={this.props.formControlIdsByParentId} locale={locale} handlers={this.handlers} /> </Form> </div> ) } } const mapStateToProps = (state) => { const props = { isNew: ClientSelectors.isNewEntity(state), canSave: ClientSelectors.canSaveEditedEntity(state), error: ClientSelectors.getSubmitError(state), isLoading: ClientFormSelectors.isFetchingClientForm(state) || ClientSelectors.isFetchingEntity(state), client: ClientSelectors.getEditedEntity(state), formTemplate: ClientFormSelectors.getClientForm(state), formSchema: ClientFormSelectors.getClientSchema(state), formControlsById: ClientFormSelectors.getControls(state), formControlIdsByParentId: ClientFormSelectors.getControlIdsByParentId(state), locale: getLocale(state) } return props } EditClientPage.propTypes = { isNew: PropTypes.bool.isRequired, canSave: PropTypes.bool.isRequired, error: PropTypes.object, client: PropTypes.object, formTemplate: PropTypes.object, formSchema: PropTypes.object.isRequired, formControlsById: PropTypes.object.isRequired, formControlIdsByParentId: PropTypes.object.isRequired, locale: PropTypes.string.isRequired, params: PropTypes.object.isRequired } const validateForm = (data, props) => { return validate(data, props.formSchema) } const EditClientFormPage = reduxForm({ form: config.entityName, validate: validateForm })(EditClientPage) const ConnectedEditClientPage = connect(mapStateToProps, mapDispatchToProps)(EditClientFormPage) export default ConnectedEditClientPage
const chai = require('chai'); const chaiHttp = require('chai-http'); const app = require('../src/app'); chai.use(chaiHttp); chai.should(); describe("People", () =>{ describe("GET /", () => { it("should get all students records", done => { chai.request(app).get('/people').end((err, res) => { res.should.have.status(200); res.body.should.be.a('object'); done(); }); }); it("should get a person record", done => { const id = 1; chai.request(app).get(`/people/${id}`).end((err, res) => { res.should.have.status(200); res.body.should.be.a('object'); done(); }); }); it("should not get a person record", done => { const id = 5; chai.request(app).get(`/people/${id}`).end((err, res) => { res.should.have.status(404); res.text.should.be.equal("Invalid id."); done(); }); }); }); describe("POST /", () => { it("should post a person", done => { chai.request(app).post('/people').send({ name:'a', age:2 }) .end((err, res) => { res.should.have.status(201); res.body.should.be.a('object'); done(); }); }); it("should not post a person", done => { chai.request(app).post('/people').send({ name:"", age:1 }) .end((err, res) => { res.should.have.status(400); res.text.should.be.equal("Fields can't be empty."); done(); }); }); it("should not post a person", done =>{ chai.request(app).post('/people').send({ name:"a", age:"" }) .end((err, res) =>{ res.should.have.status(400); res.text.should.be.equal("Fields can't be empty."); done(); }); }); }); describe("PUT /", () => { it("should update a person", done => { const id = 1; chai.request(app).put(`/people/${id}`).send({ name:"a", age:3 }) .end((err, res) => { res.should.have.status(200); res.body.should.be.a('object'); done(); }); }); it("should not update a person", done => { const id = 333; chai.request(app).put(`/people/${id}`).send({ name:"a", age:2 }) .end((err, res) => { res.should.have.status(404); res.text.should.be.equal("Invalid id."); done(); }); }); it("should not update a person", done => { const id = 1; chai.request(app).put(`/people/${id}`).send({ name:"", age:2 }) .end((err, res) => { res.should.have.status(400); res.text.should.be.equal("Fields can't be empty.") done(); }); }); it("should not update a person", done => { const id = 1; chai.request(app).put(`/people/${id}`).send({ name:"a", age:"" }) .end((err, res) => { res.should.have.status(400); res.text.should.be.equal("Fields can't be empty."); done(); }); }); }); describe("DELETE /", () => { it("should delete a person", done => { const id = 2; chai.request(app).delete(`/people/${id}`).end((err, res) => { res.should.have.status(200); res.body.should.be.a('object'); done(); }); }); it("should not delete a person", done => { const id = 333; chai.request(app).delete(`/people/${id}`).end((err, res) => { res.should.have.status(404); res.text.should.be.equal("Invalid id."); done(); }); }); }); });
const User = require("../models/userModel"); const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); // signup controller const signup = async (req, res) => { try { const { email, username, password, verifyPassword } = req.body; if (!email || !username || !password || !verifyPassword) { return res.status(400).json({ errorMessage: "please enter all fields" }); } if (password.length < 6) { return res .status(400) .json({ errorMessage: "password should be at least 6 characters" }); } if (password !== verifyPassword) { return res.status(400).json({ errorMessage: "passwords don't match" }); } const userExists = await User.findOne({ email }); if (userExists) { return res .status(400) .json({ errorMessage: "user already exists with this email" }); } // hash password const salt = await bcrypt.genSalt(12); const passwordHash = await bcrypt.hash(password, salt); // save new user to db const newUser = new User({ email, username, password: passwordHash, }); const savedUser = await newUser.save(); // sign the token const token = jwt.sign( { user_id: savedUser._id, }, process.env.JWT_SECRET ); // send the token in http-only cookie res.cookie("token", token, { httpOnly: true, }); return res .json({ user_id: savedUser._id, user_name: savedUser.username }) .send(); } catch (error) { console.log(error); } }; // login controller const login = async (req, res) => { try { const { email, password } = req.body; console.log("email => " + email); console.log("password => " + password); if (!email || !password) { return res.status(400).json({ errorMessage: "please enter all fields" }); } const existingUser = await User.findOne({ email }); if (!existingUser) { return res.status(401).json({ errorMessage: "wrong email or password" }); } const passwordCorrect = bcrypt.compare(password, existingUser.password); if (!passwordCorrect) { return res.status(401).json({ errorMessage: "wrong email or password" }); } console.log("password match"); // sign the token const token = jwt.sign( { user_id: existingUser._id, }, process.env.JWT_SECRET ); // send the token in a HTTP-only cookie res.cookie("token", token, { httpOnly: true, }); return res .json({ user_id: existingUser._id, user_name: existingUser.username }) .send(); } catch (error) { console.log(error); } }; module.exports = { signup, login, };
var chai = require( 'chai' ); var should = chai.should(); module.exports = should;
import React from "react"; import SEO from "../components/seo"; import Img from "gatsby-image"; import Layout from "../components/layout"; import { Link, graphql } from "gatsby"; const BlogPost = ({ data }) => { const { wordpressPost } = data; return ( <Layout> <div> <SEO title={wordpressPost.title} description={wordpressPost.excerpt} /> <h1>{wordpressPost.title}</h1> </div> <div> {wordpressPost.featured_media === null ? ( <h1>No featured media</h1> ) : ( <Img fluid={wordpressPost.featured_media.localFile.childImageSharp.fluid} /> )} Content: <br /> <div> <div dangerouslySetInnerHTML={{ __html: wordpressPost.content }} /> </div> <div> <Link to="/blog">Go back</Link> </div> </div> </Layout> ); }; export default BlogPost; export const pageQuery = graphql` query BlogPostByID($id: String!) { wordpressPost(id: { eq: $id }) { id title slug content date(formatString: "/YYYY/MM/DD/") featured_media { localFile { childImageSharp { fluid(maxWidth: 5000) { ...GatsbyImageSharpFluid_withWebp } } } } } } `;
const labels = document.querySelectorAll('.create__label'); const formInput = document.querySelector('.create__input'); const formTextarea = document.querySelector('.create__textarea'); function addLabelTransform(i){ labels[i].classList.add('label-transform'); }; function removeLabelTransform(i){ labels[i].classList.remove('label-transform'); }; formTextarea.addEventListener('change', function(){ if (formTextarea.value !== '') { addLabelTransform(1); } else { removeLabelTransform(1); }; }); // const casesList = document.querySelector('.cases__list'); const emptyList = document.querySelector('.cases__empty'); const casesBtns = document.querySelector('.cases__buttons'); function initialState() { if (localStorage.getItem('cases') == null) { emptyList.classList.remove('hidden'); casesBtns.classList.add('hidden'); } else { casesList.innerHTML = localStorage.getItem('cases'); emptyList.classList.add('hidden'); casesBtns.remove('hidden'); }; }; initialState(); function addToStorage() { let content = casesList.innerHTML; localStorage.setItem('cases', content); }; function addCase() { let title = formInput.value; let descr = formTextarea.value; if (title.length !== 0) { emptyList.classList.add('hidden'); casesBtns.classList.remove('hidden'); casesList.insertAdjacentHTML('beforeend', ` <article class="cases__item"> <h3 class="cases__subtitle subtitle"> ${title} </h3> <p class="cases__descr"> ${descr} </p> <span class="cases__item-buttons"> <button class="cases__item-btn start-btn"></button> <button class="cases__item-btn complete-btn"></button> <button class="cases__item-btn delete-btn"></button> </span> </article> `); formInput.value = ''; formTextarea.value = ''; labels.forEach(label => label.classList.remove('label-transform')); addToStorage(); }; }; const addCaseBtn = document.querySelector('.create__btn'); addCaseBtn.addEventListener('click', addCase); // функции кнопок - начать выполнение, завершить, удалить const startBtn = document.querySelectorAll('.start-btn'); const completeBtn = document.querySelectorAll('.complete-btn'); const deleteBtn = document.querySelectorAll('.delete-btn'); function startCase(elem){ let item = elem.closest('.cases__item'); item.classList.add('start-case'); addToStorage(); }; function completeCase(elem){ let item = elem.closest('.cases__item'); item.classList.add('start-case'); item.classList.toggle('complete-case'); addToStorage(); }; function deleteCase(elem){ let item = elem.closest('.cases__item'); item.remove(); addToStorage(); const casesItems = document.querySelectorAll('.cases__item'); if (casesItems.length === 0) { emptyList.classList.remove('hidden'); casesBtns.classList.add('hidden'); localStorage.removeItem('cases'); }; }; document.body.addEventListener('click', function(event){ let item = event.target; if (item.classList.contains('start-btn')) { startCase(item); }; if (item.classList.contains('complete-btn')) { completeCase(item); }; if (item.classList.contains('delete-btn')) { deleteCase(item); }; }); const casesStartAll = document.querySelector('.start-all'); const casesCompleteAll = document.querySelector('.complete-all'); const casesDeleteAll = document.querySelector('.delete-all'); casesStartAll.addEventListener('click', function(){ const casesItems = document.querySelectorAll('.cases__item'); casesItems.forEach(item => item.classList.add('start-case')); addToStorage(); }); casesCompleteAll.addEventListener('click', function(){ const casesItems = document.querySelectorAll('.cases__item'); for (i = 0; i < casesItems.length; i++) { casesItems[i].classList.add('complete-case'); casesItems[i].classList.add('start-case'); }; addToStorage(); }); casesDeleteAll.addEventListener('click', function(){ const casesItems = document.querySelectorAll('.cases__item'); casesItems.forEach(item => item.remove()); emptyList.classList.remove('hidden'); casesBtns.classList.add('hidden'); localStorage.removeItem('cases'); });
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "effe591f16c94de7852cdd079b3a6605", "url": "/index.html" }, { "revision": "0b1740ffd1012d725baa", "url": "/static/css/2.8d06fd47.chunk.css" }, { "revision": "fcd73da055345985f9f0", "url": "/static/css/main.dda74d2f.chunk.css" }, { "revision": "0b1740ffd1012d725baa", "url": "/static/js/2.0086c69e.chunk.js" }, { "revision": "56729d980da09961afe8d497a21eec12", "url": "/static/js/2.0086c69e.chunk.js.LICENSE.txt" }, { "revision": "fcd73da055345985f9f0", "url": "/static/js/main.d17b3868.chunk.js" }, { "revision": "1fddd770e8743a3f21e8", "url": "/static/js/runtime-main.e25bea79.js" } ]);
//1 Prompt for number, and display absolute version in console window /* var chooseNumber = prompt("Please enter a number"); window.console.log(Math.abs(chooseNumber));*/ //2 Prompt for decimal, round, and display in console window /*var decimalNum = prompt("Please choose a decimal number"); window.console.log(Math.round(decimalNum));*/ //3 Prompt for decimal, round down, and display in console window /*var decimalNum = prompt("Please choose a decimal number"); window.console.log(Math.floor(decimalNum));*/ //4 Prompt for 5 numbers, with comma in between. Store variable. Then find and display largest and smallest number in console window. /* var listOfNum = prompt("Please provide 5 numbers seperated by commas"); var a = +(listOfNum.charAt(0)); var b = +(listOfNum.charAt(2)); var c = +(listOfNum.charAt(4)); var d = +(listOfNum.charAt(6)); var e = +(listOfNum.charAt(8)); window.console.log(Math.max(a,b,c,d,e)); window.console.log(Math.min(a,b,c,d,e)); */ //5 Prompt for number; display square root in console window /* var numForRoot = prompt("Please provide a number"); window.console.log(Math.sqrt(numForRoot)); */ /*-----------------Part 2-2------------------*/ //6 Display the current date in console window /* var d= new Date(); window.console.log(d.toDateString()); */ //7 Display day of Month /* var d = new Date(); window.console.log(d.getDate()); */ //8 Get month name and display in console window /* var monthByName = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var d = new Date(); window.console.log(monthByName[d.getMonth()]); */ //9 test whether it'a a weekend /* var isWeekend = [true, false, false, false, false, false, true]; var d = new Date(); window.console.log(isWeekend[d.getDay()]); */ //10 Display yesterday's day of the week /* var dayByName = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var d = new Date(); window.console.log(dayByName[d.getDay()-1]); */ //11 Display first letter from the current day of the week /* var dayByName = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var d = new Date(); var firstLetter = dayByName[d.getDay()]; window.console.log(firstLetter.charAt(0)); */ /*-----------------Part 2-3------------------*/ //12 Prompt twice for number and compare for largest /* var firstNum = prompt("Please provide a number"); var secondNum = prompt("Please provide another number"); function largestNum() { if (firstNum > secondNum) { window.console.log(firstNum); } else { window.console.log(secondNum); } } largestNum(); */ //13 Store student marks and display student with letter grade /* var stuUrsula = 80; var stuPaul = 77; var stuHenry = 88; var stuTabitha = 95; var stuLucy = 68; function gradeUrsula() { if (stuUrsula <=59){ window.console.log("Ursula F"); } else if (stuUrsula <=69) { window.console.log("Ursula D"); } else if (stuUrsula <= 79) { window.console.log("Ursula C"); } else if (stuUrsula <= 89){ window.console.log("Ursula B"); } else { window.console.log("Ursula A"); } } function gradePaul() { if (stuPaul <=59){ window.console.log("Paul F"); } else if (stuPaul <=69) { window.console.log("Paul D"); } else if (stuPaul <= 79) { window.console.log("Paul C"); } else if (stuPaul <= 89){ window.console.log("Paul B"); } else { window.console.log("Paul A"); } } function gradeHenry() { if (stuHenry <=59){ window.console.log("Henry F"); } else if (stuHenry <=69) { window.console.log("Henry D"); } else if (stuHenry <= 79) { window.console.log("Henry C"); } else if (stuHenry <= 89){ window.console.log("Henry B"); } else { window.console.log("Henry A"); } } function gradeTabitha() { if (stuTabitha <=59){ window.console.log("Tabitha F"); } else if (stuTabitha <=69) { window.console.log("Tabitha D"); } else if (stuTabitha <= 79) { window.console.log("Tabitha C"); } else if (stuTabitha <= 89){ window.console.log("Tabitha B"); } else { window.console.log("Tabitha A"); } } function gradeLucy() { if (stuLucy <=59){ window.console.log("Lucy F"); } else if (stuLucy <=69) { window.console.log("Lucy D"); } else if (stuLucy <= 79) { window.console.log("Lucy C"); } else if (stuLucy <= 89){ window.console.log("Lucy B"); } else { window.console.log("Lucy A"); } } gradeUrsula(); gradePaul(); gradeHenry(); gradeTabitha(); gradeLucy(); */ //14 Create a JavaScript for loop that iterates from 1 to 15. Each iteration should check if the current number is odd or even, and display a message within the console window. var listForLoop = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; for (var x in listForLoop) { window.console.log(listForLoop[x]); } Number.isFinite(parseFloat(x)); function evenOrOdd() { if (x % 2 == 0) { window.console.log("even"); } else if (Math.abs(x % 2) == 1) { window.console.log("odd"); } } //window.console.log(evenOrOdd(6));
--- --- define(function() { return { apikey: { google: '{{ site.apikey.google }}', typekit: '{{ site.apikey.typekit }}', aws: { access: '{{ site.apikey.aws.access }}', secret: '{{ site.apikey.aws.secret }}' } } }; });
import Api from '@/services/Api' export default { schedulejob(currentAssess, auth) { return Api().post(`schedulejob/`,currentAssess, auth) }, testcenters(auth) { return Api().get(`servermanagement/test_centers`, auth) }, selectcenter(test, auth) { return Api().post(`servermanagement/manual_test/`, test, auth) }, }
function onBenchStart(){ var name = "args" cordova.exec(initSuccess, initFailure, "CtrExec", "init", [name]); } function onBenchEnd(){ var name = "args" cordova.exec(endSuccess, endFailure, "CtrExec", "end", [name]); } function onSuiteCycle(event){ console.log(event.target.toString()); } function onSuiteComplete(){ console.log('Fastest is ' + this.filter('fastest').map('name').join(', ')); } const cepjsOp = cepjs.operators; const cepjsMostOp = cepjsMost.operators; const cepjsMostCoreOp = cepjsMostCore.operators; //don't change it const commonOptions = { defer: true, onStart: onBenchStart, onComplete: onBenchComplete }; /* https://benchmarkjs.com/docs#options custom options examples: initCount minSamples maxTime minTime */ const customOptions = { } //don't change it const benchOpts = {...commonOptions, ...customOptions};
'use strict'; const chai = require('chai'); const assert = chai.assert; const errors = require('../../lib/errors'); const Requirement = require('../../lib/utils').Requirement; const testUtils = require('../../lib/test_utils'); const assertEqualError = testUtils.assertEqualError; describe('errors', function() { describe('createAccessDeniedError()', function() { it('creates an access denied error', function(done) { var promise = errors.createAccessDeniedError('TYPE'); promise.catch(function(err) { assertEqualError(err, 'AccessDenied', 403, 'Access denied: this account type (TYPE) does not have permission for this action'); done(); }); }); }); describe('createInvalidArgumentError(id, field, message)', function() { it('creates an invalid argument error with the default error message', function(done) { var promise = errors.createInvalidArgumentError('id', 'field', undefined); promise.catch(function(err) { assertEqualError(err, 'InvalidArgumentError', 400, 'Given field is of invalid format (e.g. not an integer or negative)'); assert.equal(err.propertyName, 'field'); assert.equal(err.propertyValue, 'id'); done(); }); }); it('creates an invalid argument error with a custom error message', function(done) { var promise = errors.createInvalidArgumentError('value', 'name', 'ERROR!'); promise.catch(function(err) { assertEqualError(err, 'InvalidArgumentError', 400, 'ERROR!'); assert.equal(err.propertyName, 'name'); assert.equal(err.propertyValue, 'value'); done(); }); }); }); describe('createUnsupportedRequestError()', function() { it('creates an unsupported request error', function(done) { var promise = errors.createUnsupportedRequestError(); promise.catch(function(err) { assertEqualError(err, 'UnsupportedRequest', 501, 'The API does not support a request of this format. ' + ' See the documentation for a list of options.'); done(); }); }); }); describe('createArgumentNotFoundError(id, field)', function() { it('creates an argument not found error', function(done) { var promise = errors.createArgumentNotFoundError('id', 'field'); promise.catch(function(err) { assertEqualError(err, 'ArgumentNotFoundError', 404, 'Invalid request: The given field does not exist in the database'); assert.equal(err.propertyName, 'field'); assert.equal(err.propertyValue, 'id'); done(); }); }); }); describe('createMissingFieldError(missingFields)', function() { var req1 = new Requirement('query', 'last_name'); var req2 = new Requirement('body', null); it('creates a missing field error for a single missing field', function(done) { errors.createMissingFieldError([req1]).catch(function(err) { assertEqualError(err, 'Missing Field', 400, 'Request must have the following component(s): ' + 'last_name (query)'); done(); }); }); it('creates a missing field error for multiple missing fields', function(done) { errors.createMissingFieldError([req1, req2]).catch(function(err) { assertEqualError(err, 'Missing Field', 400, 'Request must have the following component(s): ' + 'last_name (query), ' + 'body'); done(); }); }); }); describe('createEmptyFieldError(missingFields)', function() { var req1 = new Requirement('query', 'last_name'); var req2 = new Requirement('body', 'first_name'); it('creates an empty field error for a single empty field', function(done) { errors.createEmptyFieldError([req1]).catch(function(err) { assertEqualError(err, 'Empty Field', 400, 'Request must have the following non-empty component(s): ' + 'last_name (query)'); done(); }); }); it('creates an empty field error for multiple missing fields', function(done) { errors.createEmptyFieldError([req1, req2]).catch(function(err) { assertEqualError(err, 'Empty Field', 400, 'Request must have the following non-empty component(s): ' + 'last_name (query), ' + 'first_name (body)'); done(); }); }); }); describe('createMissingAuthError()', function() { it('creates a 400 error when the request is missing an auth0 id', function(done) { errors.createMissingAuthError().catch(function(err) { assertEqualError(err, 'Missing Field', 400, 'Request must have the following component(s): ' + 'auth0_id (auth)'); done(); }); }); }); describe('create500()', function() { it('creates a generic internal server error', function(done) { errors.create500().catch(function(err) { assertEqualError(err, 'Internal Server Error', 500, 'The server encountered an unexpected condition which prevented it from fulfilling the request'); done(); }); }); it('creates an internal server error with a specific message', function(done) { var custom = 'There was an error'; errors.create500({message: custom}).catch(function(err) { assertEqualError(err, 'Internal Server Error', 500, custom); done(); }); }); }); describe('create404(errorFields)', function() { it('creates a generic 404 error', function(done) { errors.create404().catch(function(err) { assertEqualError(err, 'Not Found', 404, 'The requested resource could not be found'); done(); }); }); it('creates a 404 error with a specific message', function(done) { var custom = 'There was an error'; errors.create404({message: custom}).catch(function(err) { assertEqualError(err, 'Not Found', 404, custom); done(); }); }); }); describe('create400(errorFields)', function() { it('creates a generic 400 error', function(done) { errors.create400().catch(function(err) { assertEqualError(err, 'Bad Request', 400, 'The request cannot be fulfilled due to bad syntax'); done(); }); }); it('creates a 400 error with a specific message', function(done) { var custom = 'There was an error'; errors.create400({message: custom}).catch(function(err) { assertEqualError(err, 'Bad Request', 400, custom); done(); }); }); }); describe('InvalidKeyError(key)', function() { it('creates an InvalidKeyError', function() { var invalidKeyError = new errors.InvalidKeyError('myKey'); assert.equal(invalidKeyError.name, 'InvalidKeyError'); assert.equal(invalidKeyError.message, 'Tried to access invalid key: myKey'); }); }); describe('AuthError()', function() { it('creates an AuthError', function() { var authError = new errors.AuthError(); assert.equal(authError.name, 'AuthError'); assert.equal(authError.message, 'This endpoint requires an auth0_id in the auth portion of the request'); }); }); });
var katzDeliLine = []; var takeANumber = (arr,name) =>{ let pos = arr.length+1 arr.push(name) return `Welcome, ${name}. You are number ${pos} in line.` } var nowServing = arr =>{ let name = arr.shift() if(arr.length === 0){ return "There is nobody waiting to be served!" }else{ return `Currently serving ${name}.` } } var currentLine = arr =>{ let j; let myString = "The line is currently: "; if(arr.length ===0){ return "The line is currently empty." }else{ for(let i =0; i<arr.length;i++){ j = i+1 if(i === 2){ myString+= `${j}. ${arr[i]}` }else{ myString+= `${j}. ${arr[i]}, ` } } return myString; } }
import React from 'react'; import {ListItemText, ListItem} from '@material-ui/core/'; // Links for Menu const ListItemLink = (props) => { return <ListItem button component="a" {...props} />; } const MenuHelper = (props) => { const { href, style, text, flag} = props return ( <ListItemLink href={href} target="_blank" style={style}> <img src={flag} alt="flag" style={{width:"10%"}}></img> <ListItemText primary={text} /> </ListItemLink> ); } export default MenuHelper;
import React from 'react'; import PropTypes from 'prop-types'; import Issue from '../Issue/Issue'; class Issues extends React.Component { constructor() { super(); this.state = { filter: 'SHOW_ALL', }; this.filterIssues = this.filterIssues.bind(this); } componentDidMount() { const { getIssues } = this.props.actions; getIssues(); } changeFilter(e, filter) { e.preventDefault(); this.setState({ filter, }); } filterIssues() { const { issues } = this.props.issues; return issues .filter((issue) => { return this.state.filter === 'SHOW_ALL' ? issue.archived === false : issue.archived; }) .map((issue) => { return ( <Issue key={issue._id} issue={issue} delete={this.props.actions.removeIssue} archive={this.props.actions.archiveIssue} /> ); }); } render() { return ( <div className="mainContent issues-container"> <header> <h1>Issues</h1> <nav className="issues-nav"> <a href="" onClick={(e) => { this.changeFilter(e, 'SHOW_ARCHIVED'); }} aria-label="show archived issues" > <i className={this.state.filter === 'SHOW_ARCHIVED' ? 'fa fa-archive redLight' : 'fa fa-archive'} /> </a> <a href="" onClick={(e) => { this.changeFilter(e, 'SHOW_ALL'); }} aria-label="show active issues" > <i className={this.state.filter === 'SHOW_ALL' ? 'fa fa-th-large redLight' : 'fa fa-th-large'} /> </a> </nav> </header> <section className="dashWrap"> {this.filterIssues()} </section> </div> ); } } Issues.propTypes = { issues: PropTypes.shape({ issues: PropTypes.array.isRequired, }).isRequired, actions: PropTypes.shape({ getIssues: PropTypes.func.isRequired, removeIssue: PropTypes.func.isRequired, archiveIssue: PropTypes.func.isRequired, }).isRequired, }; export default Issues;
define([ "underscore", "base/declare", "base/_WidgetBase" ], function (_, declare, _WidgetBase) { return declare(_WidgetBase, { baseClass: "u-linkbtn", templateString: '<a href="<%=href%>" class="<%=baseClass%>" data-kb-attach-event="click:_onClick"><i class="u-linkbtn-icon"></i><%=title%></a>', type: "linkButton", href: "javascript:;", title: null, _onClick: function () { this.onClick && this.onClick(); this.emit("click", this); } }); });
import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' import Router from '../router/index' Vue.use(Vuex) export default new Vuex.Store({ state: { totalCart: 0, count: 0, name: 'Hamdani Hamdan', todos: [], user: {}, token: localStorage.getItem('token') || null, products: [], register: [], message: '', search: '', tmpSearch: [], page: 1, limit: 12, totalProducts: 0, lastPage: 0, activ: false, activeAddUpdate: false, activeHumMenu: false, ActivBtnCancel: false, ActivBtnOk: false, isActiveCart: false, navTitle: '', isActiveCartNavbar: false }, mutations: { mutNavTitle (state, payload) { state.navTitle = payload }, kirimEmail (state) { // var nodemailer = require('nodemailer') // var fs = require('fs') // var transporter = nodemailer.createTransport({ // service: 'gmail', // auth: { // user: 'mychat709@gmail.com', // pass: 'Konsisten1!' // } // }) // var template = fs.readFileSync('index.html', 'utf-8') // var mailOptions = { // from: 'mychat709', // to: state.user.email, // subject: 'Selamat Datang di MyChat', // html: template // } // console.log(mailOptions.html) // transporter.sendMail(mailOptions, (err, info) => { // if (err) throw err // console.log('Email sent: ' + info.response) // }) }, settotalCart (state, payload) { state.totalCart = payload }, setCount (state, payload) { state.count = payload }, plus (state) { state.count++ }, minus (state) { state.count-- }, setTodosu (state, payload) { state.todos = payload }, setUser (state, payload) { state.user = payload state.token = payload.token }, setRegister (state, payload) { }, setAddProduct (state, payload) { state.products = payload }, setProduct (state, payload) { state.products = payload state.totalProducts = payload[0].totalData const lastPage = Math.ceil(this.state.totalProducts / this.state.limit) state.lastPage = lastPage }, setToken (state, payload) { state.token = payload }, setMessage (state, payload) { state.message = payload }, setSearch (state, payload) { state.products = payload }, mutActive (state, payload) { state.activ = payload }, mutActiveAddUpdate (state, payload) { state.activeAddUpdate = payload }, mutHumMenu (state, payload) { state.activeHumMenu = payload }, mutIsActiveCart (state, payload) { state.isActiveCart = payload }, mutIsActiveCartNavbar (state, payload) { state.isActiveCartNavbar = payload }, mutMsgAdd (state, payload) { state.message = payload }, mutActivBtnCancel (state, payload) { state.ActivBtnCancel = payload }, mutActivBtnOk (state, payload) { state.ActivBtnOk = payload } }, actions: { actAllProducts (setex) { return new Promise((resolve, reject) => { axios.get('https://api-inicafe.fwdev.online/api/v1/products/?page=' + this.state.page + '&limit=' + this.state.limit) .then(res => { setex.commit('setProduct', res.data.result) resolve(res.data.result) }) .catch(err => { console.log(err) reject(err) }) }) }, actAddProduct (setex, payload) { return new Promise((resolve, reject) => { axios.post('https://api-inicafe.fwdev.online/api/v1/products/', payload) .then(async res => { resolve(res.data.result) return await new Promise((resolve, reject) => { axios.get('https://api-inicafe.fwdev.online/api/v1/products/?page=' + this.state.page + '&limit=' + this.state.limit) .then(res => { setex.commit('setProduct', res.data.result) resolve(res.data.result) }) .catch(err => { console.log(err) reject(err) }) }) }) .catch(err => { console.log(err) reject(err) }) }) }, actNextPage (setex, payload) { console.log(payload) return new Promise((resolve, reject) => { axios.get('https://api-inicafe.fwdev.online/api/v1/products/?page=' + payload + '&limit=' + this.state.limit) .then((res) => { setex.commit('setProduct', res.data.result) resolve(res.data.result) }) .catch(err => { console.log(err) reject(err) }) }) }, getTodos (setex, payload) { }, actMessage (setex, payload) { setex.commit('setMessage', payload) }, actSearch (setex, payload) { return new Promise((resolve, reject) => { axios.get('https://api-inicafe.fwdev.online/api/v1/products/?search=' + payload) .then(res => { console.log('res') console.log(res) setex.commit('setSearch', res.data.result) resolve(res.data.result) }) .catch(err => { console.log(err) reject(err) }) }) }, login (setex, payload) { console.log(payload) return new Promise((resolve, reject) => { axios.post('https://api-inicafe.fwdev.online/api/v1/users/login', payload) .then(res => { console.log('res') console.log(res) setex.commit('setUser', res.data.result) localStorage.setItem('token', res.data.result.token) resolve(res.data.result) }) .catch(err => { console.log(err) reject(err) }) }) }, send (setex, payload) { return new Promise((resolve, reject) => { axios.post('https://api-inicafe.fwdev.online/api/v1/users/register', payload) .then(res => { resolve(res.data.result) }) .catch(err => { reject(err) }) }) }, getProducts (setex) { return new Promise((resolve, reject) => { axios.get('https://api-inicafe.fwdev.online/api/v1/products/?page=1&limit=3') .then(res => { setex.commit('setProduct', res.data.result) resolve(res.data.result) }) .catch(err => { console.log(err) reject(err) }) }) }, getRegister (setex) { return new Promise((resolve, reject) => { }) }, interceptorsRequest (setex, payload) { axios.interceptors.request.use(function (config) { // Do something before request is sent console.log(payload) config.headers.Authorization = `Bearer ${setex.state.token}` return config }, function (error) { console.log(payload) console.log('ini error request') console.log(error) // Do something with request error return Promise.reject(error) }) }, // Add a response interceptor interceptorsResponse (setex, payload) { axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data console.log(response) console.log(payload, 'response') return response }, function (error) { console.log(payload) console.log('ini error response') console.log(error.response) if (error.response.status === 401 && error.response.data.result.message === 'token invalid') { localStorage.removeItem('token') setex.commit('setToken', null) Router.push('/login') } else if (error.response.status === 401 && error.response.data.result.message === 'token expired') { alert('Token expired silahkan login') localStorage.removeItem('token') setex.commit('setToken', null) Router.push('/login') } else if (error.response.status === 401 && error.response.data.result.message === 'data sudah ada') { setex.commit('setMessage', error.response.data.result.message) } else if (error.response.status === 401 && error.response.data.result.message === 'Email Or Password Wrong') { setex.commit('setMessage', error.response.data.result.message) } // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error) }) } }, getters: { getNavTitle (state) { return state.navTitle }, getisActiveCart (state) { return state.isActiveCart }, getisActiveCartNavbar (state) { return state.isActiveCartNavbar }, gettotalCart (state) { return state.totalCart }, getCount (state) { return state.count * 2 }, getTodos (state) { return state.todos }, isLogin (state) { return state.token !== null }, Products (state) { return state.products }, getMessage (state) { return state.message }, getSearch (state) { return state.search }, gettmpSearch (state) { return state.tmpSearch }, getProductsAll (state) { return state.products }, getTotalProducts (state) { return state.totalProducts }, getlastpage (state) { return state.lastPage }, getActiv (state) { return state.activ }, getActivAddUpdate (state) { return state.activeAddUpdate }, getActiveHumMenu (state) { return state.activeHumMenu }, getActivBtnCancel (state) { return state.ActivBtnCancel }, getActivBtnOK (state) { return state.ActivBtnOk }, getPage (state) { return state.page }, getLimit (state) { return state.limit }, getUser (state) { return state.user.email } } })
import React, { Component } from 'react'; import Gallery from '../home/heading4'; import { Filter, ButtonComponent, RadioInput } from '../_components/myInput'; import { HttpUtils } from '../../Service/HttpUtils'; import './filterpanel.css'; import { Slider } from 'antd'; import _ from "underscore"; class Filterpanel extends Component { constructor(props) { super(props); this.state = { data : [], arr: [], filtered: [], loading: true, mainFilter: '', weather: '', size: '', label: 'Dresses available', mainFilterArr: ["Casual", "Semi Formal", "Formal", "Heavy Formal", "Bridal"], weatherArr: ["ColdWeather", "WarmWeather"], weatherArrM: ["Cold Weather", "Warm Weather"], sizesArr: ["XS", "S", "M", "XL", "L", "XXL"], sizesArrM: ["XSM", "SM", "MM", "XLM", "LM", "XXLM"] } } async componentDidMount(){ let filter = this.props.location.state; window.scrollTo(0,0) let data = await HttpUtils.get('getdresses'); console.log(data, 'dataaaaaaaaaaaaaaaa') if(data.code && data.code === 200){ this.setState({ data: data.allDress, arr: data.allDress, loading: false }); if(filter && filter !== undefined){ this.handleMainItems(null, filter); } } this.props.changingHeader('calling true'); } handleMainItems = (e, item , checkDevice) => { if(e !== null){ e.preventDefault(); } let { filtered, mainFilter, size, weather, weatherArr, sizesArr, weatherArrM, sizesArrM } = this.state; if(item == ''){ this.uncheckRadio(weatherArr); this.uncheckRadio(sizesArr); this.uncheckRadio(weatherArrM); this.uncheckRadio(sizesArrM); } this.setState({ mainFilter: item, weather: mainFilter.length > 0 ? weather : '', size: mainFilter.length > 0 ? size : '' }); this.handleConditions(filtered, mainFilter, item); // console.log(checkDevice) if(checkDevice == 'forMbl'){ if(item == 'Casual'){ document.getElementById('casual2').click(); } else if(item == 'Semi Formal'){ document.getElementById('semi Formal2').click(); } else if(item == 'Formal'){ document.getElementById('formal2').click(); } else if(item == 'Heavy Formal'){ document.getElementById('heavy2').click(); } else if(item == 'Bridal'){ document.getElementById('bridal2').click(); } } else if(checkDevice == 'forDektop'){ if(item == 'Casual'){ document.getElementById('casual1').click(); } else if(item == 'Semi Formal'){ document.getElementById('semi Formal1').click(); } else if(item == 'Formal'){ document.getElementById('formal1').click(); } else if(item == 'Heavy Formal'){ document.getElementById('heavy1').click(); } else if(item == 'Bridal'){ document.getElementById('bridal1').click(); } } } uncheckRadio(arr){ arr.map((elem) => { document.getElementById(elem).checked = false; }); } handleWeather = (item) => { let { filtered, weather } = this.state; this.setState({ weather: item }); this.handleConditions(filtered, weather, item); } handleSize = (item) => { let { filtered, size } = this.state; this.setState({ size: item }); this.handleConditions(filtered, size, item); } handleConditions(filtered, filter, item){ if(filtered.includes(filter)){ filtered = filtered.filter((elem) => elem !== filter); } filtered.push(item); this.setState({ filtered }, () => { this.filteringData(); }); } filteringData(){ const { arr, mainFilter, weather, size, filtered } = this.state; if(filtered.length === 0){ this.setState({ data: arr }); }else { let data = arr; data = !!mainFilter.length ? arr.filter((elem) => filtered.includes(elem.bodyType)) : data; data = !!weather.length ? data.filter((elem) => filtered.includes(elem.weather)) : data; data = !!size.length ? data.filter((elem) => filtered.some(r => elem.sizes.includes(r))): data; this.setState({ data }); } } handleSort = e => { let { data } = this.state, target = e.target.id; if(target === 'newest' || target === 'newestM'){ data = _.sortBy(data, 'postedOn') }else if(target === 'highAndLow' || target === 'highAndLowM'){ // data = _.sortBy(data, 'priceDay') data = this.orderByDate(data, 'priceDay') }else{ // data = (_.sortBy(data, 'priceDay')).reverse(); data = (this.orderByDate(data, 'priceDay')).reverse() } this.setState({ data }) } orderByDate(arr, dateProp) { return arr.slice().sort(function (a, b) { return a[dateProp] < b[dateProp] ? -1 : 1; }); } render() { const { size, weather, mainFilter, filtered, label } = this.state; return ( <div className="App "> {this.state.loading && <div className="loading">Loading&#8230;</div>} <div className="container-fluid" > <div className="col-md-12 col-sm-12 hidden-xs"> <div className="col-md-3 col-sm-4"> <div className="more"> <div className="row" style={{paddingLeft:'60px'}}> <h3 className="filter_H">Filters</h3> <h3 className="filter_H1">Categories</h3><br/> <label className="container1"><h5 id="Casual" onClick={(e) => this.handleMainItems(e, "Casual" , 'forDektop')} className="lH_filter"> <a href="" className="C_P">Casual</a></h5> <input type="checkbox"></input> <span className="checkmark1" id='casual1' ></span> </label><br/> <label className="container1"><h5 id="Semi Formal" onClick={(e) => this.handleMainItems(e, "Semi Formal", 'forDektop')} className="lH_filter"><a href="" className="C_P">Semi Formal</a></h5> <input type="checkbox"></input> <span className="checkmark1" id='semi Formal1'></span> </label><br/> <label className="container1"><h5 id="Formal" onClick={(e) => this.handleMainItems(e, "Formal", 'forDektop')} className="lH_filter"><a href="" className="C_P">Formal</a></h5> <input type="checkbox"></input> <span className="checkmark1" id='formal1'></span> </label><br/> <label className="container1"><h5 id="Heavy Formal" onClick={(e) => this.handleMainItems(e, "Heavy Formal", 'forDektop')} className="lH_filter" ><a href="" className="C_P">Heavy Formal</a></h5> <input type="checkbox"></input> <span className="checkmark1" id='heavy1'></span> </label><br/> <label className="container1"><h5 id="Bridal" onClick={(e) => this.handleMainItems(e, "Bridal", 'forDektop')} className="lH_filter"><a href="" className="C_P">Bridal</a></h5> <input type="checkbox"></input> <span className="checkmark1" id='bridal1'></span> </label><br/> {/*<h5 id="" onClick={(e) => this.handleMainItems(e, "")} className="lH_filter"><a href="" className="C_P">All Products</a></h5><br/> <h5 id="Wedding" onClick={(e) => this.handleMainItems(e, "Wedding")} className="lH_filter"><a href="" className="C_P">Casual</a></h5><br/> <h5 id="Party" onClick={(e) => this.handleMainItems(e, "Party")} className="lH_filter"><a href="" className="C_P">Semi Formal</a></h5><br/> <h5 id="Corporate" onClick={(e) => this.handleMainItems(e, "Corporate")} className="lH_filter"><a href="" className="C_P">Formal</a></h5><br/> <h5 id="Special Ocasion" onClick={(e) => this.handleMainItems(e, "Special Ocasion")} className="lH_filter" ><a href="" className="C_P">Heavy Formal</a></h5><br/> <h5 id="Family Dinner" onClick={(e) => this.handleMainItems(e, "Family Dinner")} className="lH_filter"><a href="" className="C_P">Bridal</a></h5> <div className="col-md-9 col-sm-12" style={{paddingBottom: '15px', margin: '40px 0 20px',borderBottom: '1px solid black'}}></div>*/} <div className="col-md-12" style={{padding: '0px'}}> <h3 className="filter_H1">Sort By&emsp;&nbsp;-</h3><br/> <RadioInput label="Newest" value="Newest" for="newest" name="sortBy" onChange={this.handleSort} /> <RadioInput label="High and Low" value="highAndLow" for="highAndLow" name="sortBy" onChange={this.handleSort}/> <RadioInput label="Low and High" value="lowAndHigh" for="lowAndHigh" name="sortBy" onChange={this.handleSort}/> {/*<Filter id="newest" heading="Newest" onChange={this.handleClick}/> <Filter id="high and low" heading="High and Low" onChange={this.handleClick}/> <Filter id="low and high" heading="Low and High" onChange={this.handleClick}/>*/} <Slider range min={500} max={500} step={500} defaultValue={[1000, 3000]} onChange={this.onChange} /> {/*<div className="col-md-10 col-sm-10" style={{paddingBottom: '15px', margin: '40px 0 20px',borderBottom: '1px solid black'}}></div>*/} </div> </div> {/*<div className="row"> <h3 style={{fontFamily: 'crimsontext'}}>Colors&emsp;&emsp;&nbsp;-</h3><br/> <div className="circle"> <a href=""><div className="circle1"></div></a>&nbsp; <a href=""><div className="circle2"></div></a>&nbsp; <a href=""><div className="circle3"></div></a> </div> <div className="circle"> <a href=""><div className="circle4"></div></a>&nbsp; <a href=""><div className="circle5"></div></a>&nbsp; <a href=""><div className="circle6"></div></a> </div> <div className="col-md-7 col-sm-7" style={{paddingBottom: '15px', margin: '40px 0 20px',borderBottom: '1px solid black'}}></div> </div>*/} <div className="row"> <div className="col-md-12 col-sm-12" style={{paddingLeft: '60px'}}> <h3 className="filter_H1">Weather&nbsp;&nbsp;&nbsp;-</h3><br/> <RadioInput label="Cold Weather" for="ColdWeather" name="weather" onChange={(e) => this.handleWeather('Cold Weather')} /> <RadioInput label="Warm Weather" for="WarmWeather" name="weather" onChange={(e) => this.handleWeather('Warm Weather')} /> {/*<div className="col-md-10 col-sm-10" style={{paddingBottom: '15px', margin: '40px 0 20px',borderBottom: '1px solid black'}}></div>*/} </div> </div> <div className="row"> <div className="col-md-12 col-sm-12" style={{paddingLeft: '60px'}}> <h3 className="filter_H1">Sizes&emsp;&nbsp;-</h3><br/> <RadioInput label="X Small" for="XS" name="sizes" onChange={(e) => this.handleSize(e.target.id)}/> <RadioInput label="Small" for="S" name="sizes" onChange={(e) => this.handleSize(e.target.id)}/> <RadioInput label="Medium" for="M" name="sizes" onChange={(e) => this.handleSize(e.target.id)}/> <RadioInput label="X Large" for="XL" name="sizes" onChange={(e) => this.handleSize(e.target.id)}/> <RadioInput label="Large" for="L" name="sizes" onChange={(e) => this.handleSize(e.target.id)}/> <RadioInput label="XX Large" for="XXL" name="sizes" onChange={(e) => this.handleSize(e.target.id)}/> {/*<div className="col-md-10 col-sm-10" style={{paddingBottom: '15px', margin: '40px 0 20px',borderBottom: '1px solid black'}}></div>*/} </div> </div> </div> </div> <div className="col-md-8 col-sm-8"> <Gallery label={mainFilter.length > 0 ? mainFilter : label} hrLine='false' data={this.state.data} colLg='col-md-3' imgtextstyle='absoulFilter' imgheadtext='pinktextFilter' imgSmalltext='pinksmaltext_filter' margBotom='margbootom' featureFilter='featuresub_dresses' featureArrow='featFilterarrow' featText='filterarrowtext' headLable='filterheadlable' tpmrgin='divTopmargin' rowmainmargin='row_Marg' // data={data} /> <div className="form-group row"> <label className="col-md-12 col-sm-12 col-xs-12 control-label" style={{textAlign: 'center'}}></label> <div className="col-lg-12 col-md-12 col-sm-12 col-xs-12 " style={{textAlign: 'center', paddingLeft: '0px'}}><br/> <div className="col-md-2 col-sm-3"></div> {this.state.data.length === 0 && <div className="col-md-8 col-sm-6"> <h1 style={{textAlign: 'center', fontFamily: 'Playfair Display'}}>Your filters did not return any result:'(</h1> <p style={{textAlign: 'center', fontFamily: 'Tajawal', color: 'gray', opacity: '1'}}>But dont worry, you can change your filters from the filters panel on the Left.</p> <h4 style={{textAlign: 'center', fontFamily: 'Playfair Display', color: '#cb9d6c'}}>Show all dresses</h4> </div> } <div className="col-md-2 col-sm-3"></div> </div> <div className="col-md-5 col-sm-5 col-xs-5 row"></div> <div className="col-md-5"></div> </div> </div> </div> </div> <div className="col-xs-12 visible-xs"> <div className="col-xs-1"></div> <div className="col-xs-11"> <div className="more"> <div className="row"> <div className=" row col-xs-12"> <div className="panel panel-default"> <div className="panel-heading" role="tab" id="headingTwo"> <h3 className="panel-title" style={{fontFamily: 'crimsontext'}}> <a className="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" aria-controls="collapseTwo"> Filters<br/>Categories </a> </h3> </div> <div id="collapseOne" className="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo"> <div className="panel-body" style={{fontFamily: 'crimsontext'}}> <label className="container1"><h5 id="Casual" onClick={(e) => this.handleMainItems(e, "Casual" ,'forMbl')} className="lH_filter"><a href="" className="C_P">Casual</a></h5> <input type="checkbox"></input> <span className="checkmark1" id='casual2'></span> </label><br/> <label className="container1"><h5 id="Semi Formal" onClick={(e) => this.handleMainItems(e, "Semi Formal" , 'forMbl')} className="lH_filter"><a href="" className="C_P">Semi Formal</a></h5> <input type="checkbox"></input> <span className="checkmark1" id='semi Formal2'></span> </label><br/> <label className="container1"><h5 id="Formal" onClick={(e) => this.handleMainItems(e, "Formal" ,'forMbl')} className="lH_filter"><a href="" className="C_P">Formal</a></h5> <input type="checkbox"></input> <span className="checkmark1" id='formal2'></span> </label><br/> <label className="container1"><h5 id="Heavy Formal" onClick={(e) => this.handleMainItems(e, "Heavy Formal" , 'forMbl')} className="lH_filter" ><a href="" className="C_P">Heavy Formal</a></h5> <input type="checkbox"></input> <span className="checkmark1" id='heavy2'></span> </label><br/> <label className="container1"><h5 id="Bridal" onClick={(e) => this.handleMainItems(e, "Bridal" , 'forMbl')} className="lH_filter"><a href="" className="C_P">Bridal</a></h5> <input type="checkbox"></input> <span className="checkmark1" id='bridal2'></span> </label><br/> {/*<h4 id="" onClick={(e) => this.handleMainItems(e, "")} style={{fontFamily: 'crimsontext'}}>Categories</h4><br/> <h4 id="Casual" onClick={(e) => this.handleMainItems(e, "Wedding")} style={{fontFamily: 'Tajawal'}}>Casual</h4><br/> <h4 id="Semi Formal" onClick={(e) => this.handleMainItems(e, "Party")} style={{fontFamily: 'Tajawal'}}>Semi Formal</h4><br/> <h4 id="Formal" onClick={(e) => this.handleMainItems(e, "Corporate")} style={{fontFamily: 'Tajawal'}}>Formal</h4><br/> <h4 id="Heavy Formal" onClick={(e) => this.handleMainItems(e, "Special Ocasion")} style={{fontFamily: 'Tajawal'}}>Heavy Formal</h4><br/> <h4 id="Bridal" onClick={(e) => this.handleMainItems(e, "Family Dinner")} style={{fontFamily: 'Tajawal'}}>Bridal</h4>*/} </div> </div> </div> </div> <div className="row"> <div className="col-xs-10" style={{paddingBottom: '15px', margin: '40px 15px 20px',borderBottom: '1px solid black'}}></div> </div> <div className="row col-xs-12"> <div className="panel panel-default"> <div className="panel-heading" role="tab" id="headingTwo"> <h3 className="panel-title" style={{fontFamily: 'crimsontext'}}> <a className="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Sort By </a> </h3> </div> <div id="collapseTwo" className="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo"> <div className="panel-body" style={{fontFamily: 'crimsontext'}}> <RadioInput label="Newest" value="Newest" for="newestM" name="sortBy" onChange={this.handleSort} /> <RadioInput label="High and Low" value="highAndLow" for="highAndLowM" name="sortBy" onChange={this.handleSort}/> <RadioInput label="Low and High" value="lowAndHigh" for="lowAndHighM" name="sortBy" onChange={this.handleSort}/> {/*<Slider range min={500} max={500} step={500} defaultValue={[1000, 3000]} onChange={this.onChange} />*/} </div> </div> </div> <div className="col-xs-12" style={{paddingBottom: '15px', margin: '40px 0 20px',borderBottom: '1px solid black'}}></div> </div> </div> {/*<div className="row"> <h3>Colors&emsp;&emsp;&nbsp;-</h3><br/> <div className="circle"> <a href=""><div className="circle1"></div></a>&nbsp; <a href=""><div className="circle2"></div></a>&nbsp; <a href=""><div className="circle3"></div></a> </div> <div className="circle"> <a href=""><div className="circle4"></div></a>&nbsp; <a href=""><div className="circle5"></div></a>&nbsp; <a href=""><div className="circle6"></div></a> </div> <div className="col-xs-12" style={{paddingBottom: '15px', margin: '40px 0 20px',borderBottom: '1px solid black'}}></div> </div>*/} <div className="row"> <div className="row col-xs-12"> <div className="panel panel-default"> <div className="panel-heading" role="tab" id="headingTwo"> <h3 className="panel-title" style={{fontFamily: 'crimsontext'}}> <a className="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseTwo"> Weather </a> </h3> </div> <div id="collapseThree" className="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo"> <div className="panel-body" style={{fontFamily: 'crimsontext'}}> <RadioInput label="Cold Weather" for="Cold Weather" name="weather" onChange={(e) => this.handleWeather(e.target.id)} /> <RadioInput label="Warm Weather" for="Warm Weather" name="weather" onChange={(e) => this.handleWeather(e.target.id)} /> </div> </div> </div> <div className="col-xs-12" style={{paddingBottom: '15px', margin: '40px 0 20px',borderBottom: '1px solid black'}}></div> </div> </div> <div className="row"> <div className="row col-xs-12"> <div className="panel panel-default"> <div className="panel-heading" role="tab" id="headingTwo"> <h3 className="panel-title" style={{fontFamily: 'crimsontext'}}> <a className="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseFour" aria-expanded="false" aria-controls="collapseTwo"> Sizes </a> </h3> </div> <div id="collapseFour" className="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo"> <div className="panel-body" style={{fontFamily: 'crimsontext'}}> <RadioInput label="X Small" for="XSM" name="sizes" onChange={(e) => this.handleSize('XS')}/> <RadioInput label="Small" for="SM" name="sizes" onChange={(e) => this.handleSize('S')}/> <RadioInput label="Medium" for="MM" name="sizes" onChange={(e) => this.handleSize('M')}/> <RadioInput label="X Large" for="XLM" name="sizes" onChange={(e) => this.handleSize('XL')}/> <RadioInput label="Large" for="LM" name="sizes" onChange={(e) => this.handleSize('L')}/> <RadioInput label="XX Large" for="XXLM" name="sizes" onChange={(e) => this.handleSize('XXL')}/> </div> </div> </div> <div className="col-xs-12" style={{paddingBottom: '15px', margin: '40px 0 20px',borderBottom: '1px solid black'}}></div> </div> </div> </div> </div> <div className="col-xs-12"> <Gallery label={mainFilter.length > 0 ? mainFilter : label} hrLine='false' data={this.state.data} colLg='col-xs-6' imgtextstyle='absoulFilter' imgheadtext='pinktextFilter' imgSmalltext='pinksmaltext_filter' margBotom='margbootom' featureFilter='featuresub_dresses' featureArrow='featFilterarrow' featText='filterarrowtext' headLable='filterheadlable' tpmrgin='divTopmargin' rowmainmargin='row_Marg' hoVerUp='' /> <div className="form-group row"> <label className="col-xs-12 control-label" style={{textAlign: 'center'}}></label> <div className="col-xs-12 row"></div> {/*{this.state.arr.length > 8 && <ButtonComponent label="More"/>}*/} {/*{this.state.data.length === 0 && <span> <ButtonComponent className="col-xs-12" label="Find More" onClick={() => this.setState({ data: this.state.arr })} /> </span>}*/} <div className="col-xs-12" style={{textAlign: 'center'}}><br/> {this.state.data.length === 0 && <div> <h1 style={{textAlign: 'center', fontFamily: 'Playfair Display'}}>Your filters did not return any result:'(</h1> <p style={{textAlign: 'center', fontFamily: 'Tajawal', color: 'gray', opacity: '1'}}>But dont worry, you can change your filters from the filters panel on the Left.</p> <h4 style={{textAlign: 'center', fontFamily: 'Playfair Display', color: '#cb9d6c'}}>Show all dresses</h4> </div> } </div> </div> </div> </div> </div> ); } } export default Filterpanel;
import tw from 'tailwind-styled-components' /** Div which contains Logo svg */ export const UserDropdownItem = tw.a` flex items-center px-4 py-1 hover:bg-gray-100 ` export const UserDropdownSystemItem = tw(UserDropdownItem)` text-blue-700 text-xs py-2 `
import styled from 'styled-components'; export const CollectionPreviewContainer = styled.div` display: flex; flex-direction: column; margin-bottom: 30px; padding: 20px; @media screen and (max-width: 800px) { padding: 10px; } `; export const TitleContainer = styled.h1` font-size: 28px; margin-bottom: 25px; cursor: pointer; padding: 0px 20px; &:hover { color: grey; } `; export const PreviewContainer = styled.div` display: flex; justify-content: space-between; @media screen and (max-width: 800px) { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 15px; & .collectionItem { width: auto; } } @media screen and (max-width: 576px) { grid-template-columns: 1fr; & .collectionItem { max-width: 100%; margin-bottom: 35px; } } `;
import { StyleSheet, Dimensions } from 'react-native'; const { height, width } = Dimensions.get('window'); export default StyleSheet.create({ avatarBlock: { width: '40%', alignItems: 'center', justifyContent: 'center' }, avatarContainer: { flexDirection: 'row', width: '100%', height: '100%', paddingRight: '14%', paddingLeft: '7%', paddingVertical: '7%' }, avatar: { flex: 1, alignSelf: 'stretch', height: undefined, width: undefined, borderRadius: 300 }, summaryContainer: { width: '100%', flexDirection: 'row', justifyContent: 'space-between' }, summaryBox: { width: '33.3%', flexDirection: 'column', alignItems: 'center' }, summaryValue: { width: '100%', fontSize: 28, fontWeight: 'bold', textAlign: 'center', color: '#222' }, summaryText: { fontSize: 17, textTransform: 'capitalize', textAlign: 'center', color: '#aaa', width: '85%' }, summaryAction: { width: '100%', flexDirection: 'row', justifyContent: 'space-between' }, descriptionContainer: { height: height * 0.2, marginTop: height * 0.03 }, username: { fontSize: 20, fontWeight: 'bold', color: '#111' }, about: { fontSize: 20, color: '#555' }, postsContainer: { width: width }, buttonGroupContainer: { height: height * 0.07, marginLeft: 0, marginRight: 0, marginBottom: 0 } });
import express from 'express' import User from '../models/user.js' import bcrypt from 'bcryptjs' import { auth } from '../middleware/auth.js' import upload from '../middleware/multer.js' const router = express.Router() router.post('/register', async (req, res) => { const { name, email, password, isAdmin } = req.body try { let user = await User.findOne({ email }) if (user) { return res.status(400).json({ msg: 'email already exists' }) } user = new User({ name, email, password, isAdmin }) await user.save() const token = user.signedWithToken() res.json({ user, token }) } catch (error) { res.status(500).json({ msg: 'Server Erro' }) } }) router.post('/login', async (req, res) => { const { email, password } = req.body try { const user = await User.findOne({ email }) if (!user) { return res.status(400).json({ msg: 'email not exists' }) } const isMatch = await bcrypt.compare(password, user.password) if (!isMatch) { return res.status(400).json({ msg: 'Incorrect Password' }) } const token = user.signedWithToken() res.json({ user, token }) } catch (error) { res.status(500).json({ msg: 'Server Error' }) } }) router.get('/profile', auth, async (req, res) => { try { const user = await User.findById(req.user.id).select('-password') if (!user) { return res.status(400).json({ msg: 'User not found' }) } res.json(user) } catch (error) { res.status(500).json({ msg: 'Server Error' }) } }) router.put('/', auth, async (req, res) => { const { email, password } = req.body try { const user = await User.findById(req.user.id) if (!user) { return res.status(400).json({ msg: 'User Not Found' }) } const isMatch = await bcrypt.compare(password, user.password) if (!isMatch) { return res.status(400).json({ msg: 'Your password is wrong' }) } user.email = email await user.save() res.json(user) } catch (error) { res.status(500).json({ msg: 'Server Error' }) } }) router.put('/website', auth, async (req, res) => { try { const user = await User.findById(req.user.id) if (!user) { return res.status(400).json({ msg: 'No User found' }) } user.name = req.body.name await user.save() const token = user.signedWithToken() res.json({user, token}) } catch (error) { res.status(500).json({ msg: 'Server Error' }) } }) router.put('/photoupload', upload.single('avatar'), auth, async (req, res) => { try { const user = await User.findById(req.user.id) if (!user) { return res.status(400).json({ msg: 'No Uswr Found' }) } user.avatar = req.file.path await user.save() res.json(user) } catch (error) { res.status(500).json({ msg: 'Server Error' }) } }) router.put('/changepassword', auth, async (req, res) => { const { currentPassword, newPassword } = req.body try { const user = await User.findById(req.user.id) if (!user) { return res.status(400).json({ msg: 'No User found' }) } const isMatch = await bcrypt.compare(currentPassword, user.password) if (!isMatch) { return res.status(400).json({ msg: 'Your Password was incorrect' }) } user.password = newPassword await user.save() res.json({ msg: 'Passsword Changed' }) } catch (error) { res.status(500).json({ msg: 'Server Error' }) } }) router.delete('/', auth, async (req, res) => { try { const user = await User.findById(req.user.id) await user.remove() res.json({ msg: 'Account Closed' }) } catch (error) { res.status(500).json({ msg: 'Server Error' }) } }) export default router
var myApp = angular.module("myApp", ["firebase"]); myApp.controller("MyController", ["$scope", "$firebaseArray", function($scope, $firebaseArray) { var ref = new Firebase("https://au3kez6j8sq.firebaseio-demo.com/"); $scope.messages = $firebaseArray(ref); $scope.addMessage = function() { var from = $scope.from || 'anonymous'; $scope.messages.$add({ from: from, body: $scope.body }); $scope.body = "" } }]);
const keystone = require('keystone'); const jwt = require("jsonwebtoken"); const moment = require("moment"); const _=require("lodash"); const bcrypt = require("bcryptjs"); const Types = keystone.Field.Types; const mongoose = keystone.mongoose; /** * User Model * ========== */ var User = new keystone.List('User',{ autokey:{path:'slug', from:'username',uniqe:true} }); // var myStorage = new keystone.Storage({ // adapter: keystone.Storage.Adapters.FS, // schema:{ // size: true, // mimetype: true, // path: true, // originalname: false, // url: true, // }, // fs: { // path: keystone.expandPath('./public/uploads/images'), // required; path where the files should be stored // publicPath: '/public/uploads/images', // path where files will be served // } // }); User.add({ // userImage:{ // type: Types.File, // storage:myStorage // }, userImage:{type:String}, username: { type: String, required: true, initial:true,uniqe:true, index: true }, name:{type:Types.Name,required:true,index:true}, email: { type: Types.Email, initial: true, required: true, unique: true, index: true }, password: { type: Types.Password, initial: true, required: true }, loggedOutAt:{type:Types.Datetime, hidden: true,default:null}, isOnline:{type:Types.Boolean, hidden: true ,default:true}, resetPasswordKey: { type: String, hidden: true }, }, 'Permissions', { isAdmin: { type: Boolean, label: 'Can access Keystone', index: true }, }); // // add tokens field to the database . asly var tokens = new mongoose.Schema([{ token: { type: String}, access: { type: String} }]); console.log('tokens ---+++>>>>#',typeof(tokens)); User.schema.add({ tokens :tokens }); // Provide access to Keystone User.schema.virtual('canAccessKeystone').get(function () { return this.isAdmin; }); //ignore certain fields from mongoose schema when return object to client . [when user.toJSON() called] User.schema.methods.toJSON=function(){ var user = this; var userObject = user.toObject(); return _.pick(userObject,['_id','email','username','isAdmin','name','tokens','resetPasswordKey','isOnline','loggedOutAt','userImage']); } //Generate user token for authentication and authorization . User.schema.methods.generateAuthToken = function () { var user = this; var access = 'auth'; var token = jwt.sign({_id: user._id.toHexString(), access},'abc123').toString(); user.tokens=[{access, token}]; console.log('type from generate token +>:',typeof(user.tokens)); return user.save().then(() => { return token; }); }; // User.schema.statics.findByToken = function(token){ // console.log('from user',token); // var User = this; // var decoded; // try{ // decoded = jwt.verify(token,'abc123'); // console.log('token id',decoded._id); // }catch(err){ // console.log('find by token error'); // return Promise.reject(); // } // return User.findOne({ // '_id':decoded._id, // 'tokens.token':token, // 'tokens.access':'auth' // }); // } //UserModel.findOne({_id: id}, function (err, user) { ... }); User.schema.statics.findByToken = function(token){ console.log('from user',token); var User = this; var decoded; try{ decoded = jwt.verify(token,'abc123'); console.log('token id',decoded._id); }catch(err){ console.log('find by token error'); return Promise.reject(); } return User.findOne( { _id:decoded._id, 'tokens.0.token':token, 'tokens.0.access':'auth' } ,function(err,user){ if(!user){ console.log('not found by id'); }else{ console.log('user found :---->',user); } }); } // // logout the user by removing his token. // User.schema.methods.removeToken = function(token){ // var user = this; // console.log('remove user :',user); // console.log('user.tokens:',user.tokens,typeof(user.tokens)); // return user.update({ // $pull:{ // tokens:{'0.token':token} // } // }); // } //db.test.update({"city":"Palo Alto"},{"$pull":{"friends":{"name":"Frank"}}}); // logout the user by removing his token. User.schema.methods.removeToken = function(token){ var user = this; console.log('remove user :',user); console.log('user.tokens:',user.tokens,typeof(user.tokens)); // return user.update({$unset:{tokens:""}}); return user.update({$set: {'tokens.0.token': "",'isOnline':false,'loggedOutAt':moment().format()}}) } //db.books.update( { _id: 1 }, { $unset: { tags: "" } } ) // find user by credentials [e-mail , password]. User.schema.statics.findByCredentials= function(email,password){ console.log(email,password); var User = this; return User.findOne({email}).then((user)=>{ if(!user){ console.log('user not found'); return Promise.reject(); } return new Promise((resolve,reject)=>{ bcrypt.compare(password,user.password,(err,res)=>{ console.log('hash',user.password); if(res){ console.log('resolve',res); resolve(user); }else{ console.log('reject',err); reject(); } }); }); }); } // before saving the password to the database we want to hashing it . [keystone Types.Password handle this task] // User.schema.pre('save',function(next){ // var user = this; // if(user.isModified('password')){ // bcrypt.genSalt(10,(err,salt)=>{ // bcrypt.hash(user.password,salt,(err,hash)=>{ // user.password = hash; // console.log(hash); // next(); // }); // }); // }else{ // next(); // } // }); /** * Registration */ User.defaultColumns = 'name, email, isAdmin'; User.register();
18 gid=1329781531 17 uid=183816338 20 ctime=1441138963 20 atime=1441138970 23 SCHILY.dev=16777221 23 SCHILY.ino=32545840 18 SCHILY.nlink=1
"use strict"; var express = require("express"); var router = express.Router(); var category_1 = require("../models/category"); var place_1 = require("../models/place"); router.post('/', function (req, res) { if (req.body._id) { place_1.default.findByIdAndUpdate(req.body._id, { "$set": { "name": req.body.name, "address": req.body.address } }, { "new": true, "upsert": true }, function (err, updatedCategory) { if (err) { res.send(err); } else { res.send(updatedCategory); } }); } else { var place = new place_1.default(); place.name = req.body.name; place.address = req.body.address; place.save(function (err, newPlace) { category_1.default.findOne({ name: req.body.category }).exec(function (err, result) { if (err) { res.send(err); } else { category_1.default.findByIdAndUpdate(result._id, { "$push": { "places": newPlace._id } }, { "new": true, "upsert": true }, function (err, updatedCategory) { if (err) { res.send(err); } else { res.send(updatedCategory); } }); } }); }); } }); router.get('/:tag', function (req, res) { category_1.default.findOne({ name: req.params['tag'] }).populate('places').exec(function (err, results) { if (err) { res.send(err); } else { res.json(results.places); } }); }); router.delete('/:tag', function (req, res) { place_1.default.remove({ _id: req.params['tag'] }, function (err) { if (err) { res.send(err); } else { res.send('success'); } }); }); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = router;
const input = require("fs").readFileSync("/dev/stdin", "utf8") let cin = input.split(/ |\n/), cid = 0 const next = () => cin[cid++] const nexts = (n) => cin.slice(cid, cid+=n).map(i=>parseInt(i)) const [N, M] = nexts(2) console.log(N, M) let routes = [] for (let i = 0; i < M; i++) { routes.push(nexts(2)) } let memo = new Array(M) memo.fill('No') memo[0] = 'Yes' const array = [] routes.forEach((route, index) => { if (route.includes(index + 1)) { if (route[0] === 1) { array.push(route[1]) } else { array.push(route[0]) } } })
var servicenow = require('servicenow'); var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until; var fs = require('fs'); // webdriver will not be accessible from outside this module var browser = new webdriver.Builder().usingServer().withCapabilities({ 'browserName': 'firefox' }).build(); var timeout = 20000; var delay = 1000; exports.deploy = function(server, username, password, path) { var config = { instance: server, username: username, password: password }; //login page browser.get(server + 'welcome.do').then(function() { console.log("login page loaded"); // throw new Error('my silly error'); }); browser.findElement(webdriver.By.id('user_name')).sendKeys(username); browser.findElement(webdriver.By.id('user_password')).sendKeys(password); browser.findElement(webdriver.By.id('sysverb_login')).click(); //get update set browser.wait(function() { console.log("home page loaded"); return browser.isElementPresent(webdriver.By.id('gsft_full_name')); }, timeout); //remote instance browser.get(server + 'sys_update_set_source_list.do'); browser.wait(function() { console.log("remote instance loaded"); return browser.isElementPresent(webdriver.By.id('sysverb_new')); }); //select all instance browser.executeScript("document.getElementById('allcheck_sys_update_set_source').click()"); var element = browser.findElement(webdriver.By.xpath("//select[@class='list_action_option form-control ']")); element.click().then(function() { element.findElement(webdriver.By.id("c2ca3de40a0a0b5000795879b46a69b5")).click().then(function() { var isPageRefresh = false; browser.wait(function() { browser.executeScript("return document.getElementById('allcheck_sys_update_set_source').checked").then(function(checked) { isPageRefresh = !checked; }); return isPageRefresh; }, timeout); }) }); browser.get(server + 'sys_remote_update_set_list.do?sysparm_query=sys_class_name%3Dsys_remote_update_set%5Estate%3Dloaded'); browser.wait(function() { console.log("updated sets list loaded"); return browser.isElementPresent(webdriver.By.id('0583c6760a0a0b8000d06ad9224a81a2')); }, timeout).then(function() { var client = new servicenow.Client(config); client.getRecords("sys_remote_update_set", "state=loaded", function(error, result) { if (!error) { // call succeded result.records.forEach(function(item) { var sys_id = item.sys_id; var name = item.name; var fileName = path + sys_id + "_" + name.replace(' ', '_') + ".txt"; var content = 'Update set committed at ' + new Date(); console.log(sys_id); browser.get(server + 'sys_remote_update_set.do?sys_id=' + sys_id); //preview update set browser.executeScript("document.getElementById('preview_update_set').click()"); browser.sleep(timeout); //preview has error browser.isElementPresent(webdriver.By.id("hierarchical_progress_viewer")).then(function(result) { if (result) { client.getRecords("sys_update_preview_problem", "remote_update_set=" + sys_id, function(error, result) { if (!error) { var data = result.records; var problems = "Update set " + name + " has error: "; data.forEach(function(element) { problems += element.description; }, this); fs.writeFile(fileName, problems, function(err) { if (err) return console.log(err); console.log(fileName); }); } }); } else { //show commit button browser.isElementPresent(webdriver.By.id("c38b2cab0a0a0b5000470398d9e60c36")).then(function(result) { if (result) { //commit update set browser.executeScript("document.getElementsByClassName('form_action_button header action_context btn btn-default')[3].click()"); browser.wait(function() { return browser.isElementPresent(webdriver.By.id("sysparm_button_close")); }, timeout); browser.findElement(webdriver.By.id("sysparm_button_close")).click(); fs.writeFile(fileName, content, function(err) { if (err) return console.log(err); console.log(fileName); }); } }) } }); }, this); browser.quit(); } }); }); }
// let wait = ms=>new Promise((resolve,reject)=>{setTimeout(resolve,ms)}); // wait(1000).then(value=>{console.log(value);console.log("resolved");console.log(obj);}).catch(reject=>{console.log(reject);}); // console.log("after wait"); // // setTimeout(()=>{console.log(obj);},1000);//出现错误无法处理 // setTimeout(()=>{console.log("2second later");},2000); let p1 = Promise.resolve("p1:resolved"); let p2 = Promise.reject("p2:rejected"); let p3 = function (choice) { return new Promise((resolve,reject)=>choice=="resolved"?resolve("p3:"+choice):reject("p3"+choice)); } // p3("resolved").then(value=>{console.log(value);}); // Promise.all([p1,p3("resolved")]).then(value=>{console.log(value);},reason=>{console.log(reason);}); // [p1,p3("resolved")].reduce((p,f)=>p.then(()=>f),Promise.resolve("p0:resolved")); //在node中会报错:TypeError: Cannot read property 'reduce' of undefined。去html文件中测试把 // [()=>{console.log(1);},()=>{console.log(2);},()=>{console.log(3);}].reduce((acc,cur)=>acc.then(cur),Promise.resolve(0)).then(value=>{console.log(value);}) // console.log([1,2,3].reduce((acc,cur)=>acc+cur,4)); let arr = [1,2,3]; console.log(arr.push(4,5)); console.log(arr); for(let i = 0; i < 5; i++){ console.log(arr.shift(arr[0])); console.log(arr); // console.log(arr[0]); console.log("----------------------------"); } let pp1 = new Promise((resolve,reject)=>{ resolve("p1:resolved1"); }); let pp2 = new Promise((resolve,reject)=>{ reject("p2:rejected2"); }); Promise.race([pp2,pp1]).then( value=>{console.log(value);}, reason=>{console.log(reason);} )
import Vue from 'vue' import store from '@store' import { SET_SHULD_LOGIN_FORM_SHOW, SET_LOGIN_FORM_TYPE, } from '@store/modules/login/mutation-types' // 全局登陆或者注册自定义指令 Vue.directive('login-in', { inserted: (el, bind) => { el.addEventListener('click', () => { store.commit(`login/${SET_LOGIN_FORM_TYPE}`, bind.value) store.commit(`login/${SET_SHULD_LOGIN_FORM_SHOW}`, { shuldLoginFormShow: true, }) }) }, })
import * as actions from '../constants' export function load() { return async (dispatch, getState, { get }) => { const { result } = await get('price') dispatch({ type: actions.load, ...result, }) } } export function add(countries, price) { return async (dispatch, getState, { get }) => { const body = { country_code: countries.map(country => country.country_code), price: parseFloat(price).toFixed(2), } await get('price/change', { body }) dispatch(load()) } } export function remove(countries) { return async (dispatch, getState, { get }) => { const body = { country_code: countries.map(country => country.country_code), } await get('price/delete', { body }) dispatch(load()) } }
// Require packages // const cors = require('cors') const express = require('express') // Create instance for express app const app = express() // Set up middleware app.use(express.urlencoded({ extended: false })) // app.use(express.json({ limit: '50mb' })) // app.use(cors()) app.get('/', (req, res) => { res.status(200).send({ message: 'Welcome to the MIB: Mates in Beige'}) }) // Include the controllers app.use('/v1/bounties', require('./routes/v1/bounties')) // Catch all route (404: Not found) app.get('*', (req, res) => { res.status(404).send({ message: 'Not Found' }) }) app.listen(process.env.PORT || 3000, console.log(`☕️ You're listening to the smooth sounds of port ${process.env.PORT || 3000} ☕️`));
var imgSrc = "https://p.kindpng.com/picc/s/12-129142_exemplo-de-spritesheet-sprite-sheet-megaman-png-transparent.png"; var redSpriteSrc = "https://mr-easy.github.io/files/blog/spritesheet/red.png"; var canvas, context; //Game Object constructor function GameObject(spritesheet, x, y, width, height, timePerFrame, numberOfFrames) { this.spritesheet = spritesheet; this.x = x; this.y = y; this.width = width; this.height = height; this.timePerFrame = timePerFrame; this.numberOfFrames = numberOfFrames; //current index of frame this.frameIndex = 0 this.lastUpdate = Date.now(); this.update = function() { if(Date.now() - this.lastUpdate >= this.timePerFrame) { this.frameIndex++; if(this.frameIndex >= this.numberOfFrames) { this.frameIndex = 0; } this.lastUpdate = Date.now(); } } } //Characters var hero; var heroSpritesheet = new Image(); heroSpritesheet.src = imgSrc; var red; var redSprite = new Image(); redSprite.src = redSpriteSrc; window.onload = function () { var canvas = document.getElementById('canvas'); context = canvas.getContext('2d'); hero = new GameObject(heroSpritesheet, 0, 0, 500, 280, 50, 5); var j = canvas.width/5; var i = canvas.height/2; red = new GameObject(redSprite, j-i, 0, 100, 140, 50, 5); red.update = function(context) { if(Date.now()-this.lastUpdate >= this.timePerFrame && this.frameIndex != 0) { this.frameIndex++; if(this.frameIndex >= this.numberOfFrames) { this.frameIndex = 0; } this.lastUpdate = Date.now(); } } red.draw = function(context) { context.drawImage(this.spritesheet, this.frameIndex*this.width/this.numberOfFrames, 0, this.width/this.numberOfFrames, this.height, this.x, this.y, 2*this.width/this.numberOfFrames, 2*this.height); } canvas.onmouseup = mouseClick; loop(); } function mouseClick(event) { red.frameIndex = 1; red.lastUpdate = Date.now(); } function loop() { update(); draw(); requestAnimationFrame(loop); } function draw() { context.clearRect(0, 0, canvas.width, canvas.height); hero.draw(context); red.draw(context); context.font = '30px Arial'; context.fillStyle = "black"; context.textAlign = 'center'; context.fillText('Click', canvas.width/2, canvas.height/2 - 50); }
$(document).ready(function(){ console.log("ready!"); }); $('.ui.dropdown').dropdown(); var xd=""; $(document).on("click","#botonBuscar", function(){ console.log("click"); var valor = $('#codigo').val(); $("#estado").val(xd); $("#mun").val(xd); $('select option').remove(); console.log(valor); $.ajax({ url: 'http://requenadev.swi.mx/some/api/listado-cp/'+valor, type: 'GET', dataType: 'json', data:{ } }).done(function(data){ console.log(data); console.log(data.estado); console.log(data.municipio); $("#estado").val(data.estado); $("#mun").val(data.municipio); console.log(data.colonias); var ah = []; ah = data.colonias; console.log("Ah "+ah); console.log("d"); for(var i=0; i<ah.length; i++){ $('#mySelect').append($('<option>', { value: i, text: ah[i] })); } // // $('#mySelect').append($('<option>', { // value: 1, // text: 'My option' // })); }).fail(function(e){ console.log(e); }).always(function () { }); })
/*global describe, beforeEach, it */ 'use strict'; var _ = require('lodash'); var path = require('path'); var helpers = require('yeoman-generator').test; var assert = require('yeoman-generator').assert; var outputInTest = require( './mute' ); describe('axi-dtsi-gulp-angular generator', function () { var mockPrompts = require('../app/src/mock-prompts.js'); var mockOptions = require('../app/src/mock-options.js'); var prompts = _.cloneDeep(mockPrompts.prompts); var defaultPrompts = mockPrompts.defaults; var defaultOptions = mockOptions.defaults; var promptCase; var optionCase; var skipOptions = { 'skip-install': true, 'skip-welcome-message': true, 'skip-message': true }; var libRegexp = mockPrompts.libRegexp; var gulpAngular; var folderName = 'tempGulpAngular'; var expectedFile; var expectedGulpContent = [ ['gulpfile.js', /gulp\.task\('default'/], ['gulp/build.js', /gulp\.task\('partials'/], ['gulp/build.js', /gulp\.task\('html'/], ['gulp/build.js', /gulp\.task\('images'/], ['gulp/build.js', /gulp\.task\('fonts'/], ['gulp/build.js', /gulp\.task\('misc'/], ['gulp/build.js', /gulp\.task\('clean'/], ['gulp/build.js', /gulp\.task\('build'/], ['gulp/inject.js', /gulp\.task\('inject'/], ['gulp/watch.js', /gulp\.task\('watch'/], ['gulp/unit-tests.js', /gulp\.task\('test'/], ['gulp/unit-tests.js', /gulp\.task\('test:auto'/], ['gulp/e2e-tests.js', /gulp\.task\('webdriver-update'/], ['gulp/e2e-tests.js', /gulp\.task\('webdriver-standalone'/], ['gulp/e2e-tests.js', /gulp\.task\('protractor:src'/], ['gulp/e2e-tests.js', /gulp\.task\('protractor:dist'/], ['gulp/server.js', /gulp\.task\('serve'/], ['gulp/server.js', /gulp\.task\('serve:dist'/], ['gulp/server.js', /gulp\.task\('serve:e2e'/], ['gulp/server.js', /gulp\.task\('serve:e2e-dist'/] ]; beforeEach(function (done) { expectedFile = [ // gulp/ directory 'gulp/build.js', 'gulp/inject.js', 'gulp/watch.js', 'gulp/proxy.js', 'gulp/server.js', 'gulp/unit-tests.js', 'gulp/e2e-tests.js', // src/ directory 'src/favicon.ico', 'src/index.html', // src/components/navbar/ directory 'src/components/navbar/navbar.html', // root directory '.bowerrc', '.editorconfig', '.gitignore', '.jshintrc', '.yo-rc.json', 'bower.json', 'gulpfile.js', 'package.json' ]; helpers.testDirectory(path.join(__dirname, folderName), function (err) { if (err) { done(err); } gulpAngular = helpers.createGenerator( 'axi-dtsi-gulp-angular:app', [ '../../app', ], false, optionCase ); helpers.mockPrompt(gulpAngular, promptCase); gulpAngular.on('run', outputInTest.mute); gulpAngular.on('end', outputInTest.unmute); done(); }); }); describe('with default config: [src, dist, e2e, .tmp] [angular 1.3.x, ngAnimate, ngCookies, ngTouch, ngSanitize, jQuery 1.x.x, ngResource, ngRoute, bootstrap, ui-bootstrap, node-sass, Standard JS, No HTML preprocessor]', function () { // Default scenario: angular 1.3.x, ngAnimate, ngCookies, ngTouch, ngSanitize, jQuery 1.x.x, ngResource, ngRoute, bootstrap, node-sass, standard js, jade before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.cloneDeep(defaultPrompts); }); it('should generate the expected files and their content', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ // Option: Javascript 'src/app/index.js', 'src/app/main/main.controller.js', 'src/app/main/main.controller.spec.js', 'src/components/navbar/navbar.controller.js', 'karma.conf.js', 'protractor.conf.js', 'e2e/main.po.js', 'e2e/main.spec.js', // Option: ngRoute 'src/app/main/main.html', // Option: Sass (Node) 'src/app/index.scss', 'src/app/vendor.scss', ])); assert.noFile([ 'src/**/*.ts', 'src/**/*.coffee' ]); assert.fileContent([].concat(expectedGulpContent, [ // Check src/app/index.js ['src/app/index.js', /'ngAnimate'/], ['src/app/index.js', /'ngCookies'/], ['src/app/index.js', /'ngTouch'/], ['src/app/index.js', /'ngSanitize'/], ['src/app/index.js', /'ngResource'/], ['src/app/index.js', /'ngRoute'/], // Check src/app/vendor.scss ['src/app/vendor.scss', /\$icon-font-path: "\/bower_components\/bootstrap-sass-official\/assets\/fonts\/bootstrap\/";/], ['src/app/vendor.scss', /@import '\.\.\/\.\.\/bower_components\/bootstrap-sass-official\/assets\/stylesheets\/bootstrap';/], // Check bower.json ['bower.json', libRegexp('angular', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('angular-animate', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('angular-cookies', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('angular-touch', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('angular-sanitize', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('jquery', prompts.jQuery.values['jquery 2'].version)], ['bower.json', libRegexp('angular-resource', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('angular-route', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('bootstrap-sass-official', prompts.ui.values.bootstrap.version)], // Check package.json ['package.json', libRegexp('gulp-sass', prompts.cssPreprocessor.values['node-sass'].version)], // Check wiredep css exclusion. ['gulp/inject.js', /exclude:.*?\/bootstrap\\\.css\/.*?/], // Check font-path replace in html ['gulp/build.js', /\/bower_components\/bootstrap-sass-official\/assets\/fonts\/bootstrap\//] ])); assert.noFileContent([].concat([ // Check no markups ['gulp/build.js', /gulp\.task\('partials'.*?'markups'/] ])); done(); }); }); }); // Prompt #1: Which version of Angular ? describe('with prompt: [angular 1.3.x]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { 'angularVersion': prompts.angularVersion.values['1.3'] }); }); it('should add dependency for angular 1.3.x', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent([].concat(expectedGulpContent, [ ['bower.json', libRegexp('angular', prompts.angularVersion.values['1.3'])] ])); done(); }); }); }); // Prompt #2: Which Angular's modules ? describe('without ngModules option', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { angularModules: [] }); }); it('should NOT add dependency for ngModules', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent(expectedGulpContent); assert.noFileContent([ ['src/app/index.js', /'ngAnimate'/], ['src/app/index.js', /'ngCookies'/], ['src/app/index.js', /'ngTouch'/], ['src/app/index.js', /'ngSanitize'/], ['bower.json', /"angular-animate":/], ['bower.json', /"angular-cookies":/], ['bower.json', /"angular-touch":/], ['bower.json', /"angular-sanitize":/], ]); done(); }); }); }); // Prompt #3: Which JavaScript library ? describe('with prompt: [jQuery 2.x.x]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { jQuery: prompts.jQuery.values['jquery 2'] }); }); it('should add dependency for jQuery 2.x.x', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent([].concat(expectedGulpContent, [ ['bower.json', libRegexp('jquery', prompts.jQuery.values['jquery 2'].version)] ])); done(); }); }); }); describe('with prompt: [ZeptoJS 1.1.x]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { jQuery: prompts.jQuery.values['zeptojs 1.1'] }); }); it('should add dependency for ZeptoJS 1.1.x', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent([].concat(expectedGulpContent, [ ['bower.json', libRegexp('zeptojs', prompts.jQuery.values['zeptojs 1.1'].version)] ])); done(); }); }); }); describe('with prompt: [jqLite]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { jQuery: prompts.jQuery.values.none }); }); it('should NOT add dependency for jqLite', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent(expectedGulpContent); assert.noFileContent([ ['bower.json', /"jquery:"/], ['bower.json', /"zeptojs:"/] ]); done(); }); }); }); // Prompt #4: Which Angular's modules for RESTful resource interaction ? describe('with prompt: [Restangular]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { resource: prompts.resource.values.restangular }); }); it('should add dependency for Restangular', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent([].concat(expectedGulpContent, [ ['src/app/index.js', /'restangular'/], ['bower.json', libRegexp('restangular', prompts.resource.values.restangular.version)] ])); done(); }); }); }); describe('with prompt: [$http]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { resource: prompts.resource.values.none }); }); it('should NOT add dependency for $http', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent(expectedGulpContent); assert.noFileContent([ ['src/app/index.js', /'ngResource'/], ['src/app/index.js', /'restangular'/], ['bower.json', libRegexp('angular-resource', prompts.resource.values['angular-resource'].version)], ['bower.json', libRegexp('restangular', prompts.resource.values.restangular.version)] ]); done(); }); }); }); // Prompt #5: Which Angular's modules for routing ? describe('with prompt: [UI Router]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { router: prompts.router.values['angular-ui-router'] }); }); it('should add dependency for UI Router', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/main/main.html', ])); assert.fileContent([].concat(expectedGulpContent, [ ['src/app/index.js', /'ui.router'/], ['bower.json', libRegexp('angular-ui-router', prompts.router.values['angular-ui-router'].version)] ])); done(); }); }); }); describe('without router option', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { router: prompts.router.values.none }); }); it('should NOT add dependency', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.noFile('src/app/main/main.html'); assert.fileContent(expectedGulpContent); assert.noFileContent([ ['src/app/index.js', /'ngRoute'/], ['src/app/index.js', /'ui.router'/], ['bower.json', libRegexp('angular-route', prompts.router.values['angular-route'].version)], ['bower.json', libRegexp('angular-ui-router', prompts.router.values['angular-ui-router'].version)] ]); done(); }); }); }); // Prompt #6: Which UI framework ? describe('with prompt: [Foundation, angular-foundation, Node SASS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.foundation, foundationComponents: prompts.foundationComponents.values['angular-foundation'] }); }); it('should add dependency for Foundation with SASS', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'gulp/styles.js', ])); assert.fileContent([].concat(expectedGulpContent, [ ['src/app/vendor.scss', /@import '..\/..\/bower_components\/foundation\/scss\/foundation';/], ['bower.json', libRegexp('angular-foundation', prompts.foundationComponents.values['angular-foundation'].version)], ['bower.json', libRegexp('foundation', prompts.ui.values.foundation.version)], ['package.json', libRegexp('gulp-sass', prompts.cssPreprocessor.values['node-sass'].version)], ['gulp/inject.js', /exclude:.*?\/foundation\\\.css\/.*?/] ])); done(); }); }); }); describe('with prompt: [Foundation, angular-foundation, Ruby SASS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.foundation, foundationComponents: prompts.foundationComponents.values['angular-foundation'], cssPreprocessor: prompts.cssPreprocessor.values['ruby-sass'] }); }); it('should add dependency for Foundation with SASS', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent([].concat(expectedGulpContent, [ ['src/app/vendor.scss', /@import '..\/..\/bower_components\/foundation\/scss\/foundation';/], ['bower.json', libRegexp('angular-foundation', prompts.foundationComponents.values['angular-foundation'].version)], ['bower.json', libRegexp('foundation', prompts.ui.values.foundation.version)], ['package.json', libRegexp('gulp-ruby-sass', prompts.cssPreprocessor.values['ruby-sass'].version)], ['gulp/inject.js', /exclude:.*?\/foundation\\\.css\/.*?/] ])); done(); }); }); }); describe('with prompt: [Foundation, angular-foundation, LESS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.foundation, foundationComponents: prompts.foundationComponents.values['angular-foundation'], cssPreprocessor: prompts.cssPreprocessor.values.less }); }); it('should add dependency for Foundation with LESS', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/index.less' ])); assert.fileContent([].concat(expectedGulpContent, [ ['bower.json', libRegexp('foundation', prompts.ui.values.foundation.version)], ['bower.json', libRegexp('angular-foundation', prompts.foundationComponents.values['angular-foundation'].version)], ['package.json', libRegexp('gulp-less', prompts.cssPreprocessor.values.less.version)], ['gulp/inject.js', /exclude:.*?\/foundation\\\.css\/.*?/] ])); done(); }); }); }); describe('with prompt: [Foundation, angular-foundation, Stylus]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.foundation, foundationComponents: prompts.foundationComponents.values['angular-foundation'], cssPreprocessor: prompts.cssPreprocessor.values.stylus }); }); it('should add dependency for Foundation with Stylus', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/index.styl' ])); assert.fileContent([].concat(expectedGulpContent, [ ['bower.json', libRegexp('foundation', prompts.ui.values.foundation.version)], ['bower.json', libRegexp('angular-foundation', prompts.foundationComponents.values['angular-foundation'].version)], ['package.json', libRegexp('gulp-stylus', prompts.cssPreprocessor.values.stylus.version)], ['gulp/inject.js', /exclude:.*?\/foundation\\\.css\/.*?/] ])); done(); }); }); }); describe('with prompt: [Foundation, angular-foundation, CSS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.foundation, foundationComponents: prompts.foundationComponents.values['angular-foundation'], cssPreprocessor: prompts.cssPreprocessor.values.none }); }); it('should add dependency for Foundation with CSS', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/index.css', ])); assert.noFile('src/app/vendor.*'); // No Gulp task for style assert.fileContent([ ['bower.json', libRegexp('foundation', prompts.ui.values.foundation.version)], ['bower.json', libRegexp('angular-foundation', prompts.foundationComponents.values['angular-foundation'].version)] ]); // No Gulp task for style assert.noFileContent([ ['gulp/inject.js', /exclude:.*?\/foundation\\\.css\/.*?/] ]); done(); }); }); }); describe('with prompt: [Foundation, Official, CSS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.foundation, cssPreprocessor: prompts.cssPreprocessor.values.none, foundationComponents: prompts.foundationComponents.values.official }); }); it('should not add angular-foundation', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/index.css', ])); assert.noFile('src/app/vendor.*'); // No Gulp task for style assert.fileContent([ ['bower.json', libRegexp('foundation', prompts.ui.values.foundation.version)], ]); // No Gulp task for style assert.noFileContent([ ['bower.json', libRegexp('angular-foundation', prompts.foundationComponents.values['angular-foundation'].version)], ['gulp/inject.js', /exclude:.*?\/foundation\\\.css\/.*?/] ]); done(); }); }); }); describe('with prompt: [Bootstrap, Ruby SASS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.bootstrap, cssPreprocessor: prompts.cssPreprocessor.values['ruby-sass'] }); }); it('should add dependency for Bootstrap with SASS', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/index.scss', 'src/app/vendor.scss', ])); assert.fileContent([].concat(expectedGulpContent, [ ['src/app/vendor.scss', /\$icon-font-path: "\/bower_components\/bootstrap-sass-official\/assets\/fonts\/bootstrap\/";/], ['src/app/vendor.scss', /@import '\.\.\/\.\.\/bower_components\/bootstrap-sass-official\/assets\/stylesheets\/bootstrap';/], ['bower.json', libRegexp('bootstrap-sass-official', prompts.ui.values.bootstrap.version)], ['package.json', libRegexp('gulp-ruby-sass', prompts.cssPreprocessor.values['ruby-sass'].version)], ['gulp/inject.js', /exclude:.*?\/bootstrap\\\.css\/.*?/] ])); done(); }); }); }); describe('with prompt: [Bootstrap, LESS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.bootstrap, cssPreprocessor: prompts.cssPreprocessor.values.less }); }); it('should add dependency for Bootstrap with LESS', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/index.less', 'src/app/vendor.less', ])); assert.fileContent([].concat(expectedGulpContent, [ ['src/app/vendor.less', /@import '\.\.\/\.\.\/bower_components\/bootstrap\/less\/bootstrap\.less';/], ['src/app/vendor.less', /@icon-font-path: '\/bower_components\/bootstrap\/fonts\/';/], ['bower.json', libRegexp('bootstrap', prompts.ui.values.bootstrap.version)], ['package.json', libRegexp('gulp-less', prompts.cssPreprocessor.values.less.version)], ['gulp/inject.js', /exclude:.*?\/bootstrap\\\.css\/.*?/] ])); done(); }); }); }); describe('with prompt: [Bootstrap, Stylus]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.bootstrap, cssPreprocessor: prompts.cssPreprocessor.values.stylus }); }); it('should add dependency for Bootstrap with Stylus', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/index.styl', ])); assert.noFile('src/app/vendor.*'); assert.fileContent([].concat(expectedGulpContent, [ ['src/index.html', /<link rel="stylesheet" href="..\/bower_components\/bootstrap\/dist\/css\/bootstrap.css">/], ['bower.json', libRegexp('bootstrap', prompts.ui.values.bootstrap.version)], ['package.json', libRegexp('gulp-stylus', prompts.cssPreprocessor.values.stylus.version)], ['gulp/inject.js', /exclude:.*?\/bootstrap\\\.css\/.*?/] ])); done(); }); }); }); describe('with prompt: [Bootstrap, CSS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.bootstrap, cssPreprocessor: prompts.cssPreprocessor.values.none }); }); it('should add dependency for Bootstrap with CSS', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/index.css', ])); assert.noFile('src/app/vendor.*'); // No Gulp task for style assert.fileContent([ ['bower.json', libRegexp('bootstrap', prompts.ui.values.bootstrap.version)] ]); assert.noFileContent([ ['package.json', libRegexp('gulp-less', prompts.cssPreprocessor.values.less.version)], ['package.json', libRegexp('gulp-sass', prompts.cssPreprocessor.values['node-sass'].version)], ['package.json', libRegexp('gulp-ruby-sass', prompts.cssPreprocessor.values['ruby-sass'].version)], ['gulp/inject.js', /exclude:.*\/bootstrap\\\.css\/.*/] ]); done(); }); }); }); describe('with prompt: [Bootstrap, UI Boostrap]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { bootstrapComponents: prompts.bootstrapComponents.values['ui-bootstrap'] }); }); it('should add UI Bootstrap Bower and Angular module', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent([ ['bower.json', libRegexp('angular-bootstrap', prompts.bootstrapComponents.values['ui-bootstrap'].version)], ['src/app/index.js', /'ui.bootstrap'/] ]); done(); }); }); }); describe('with prompt: [Bootstrap, Standard Boostrap JS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { bootstrapComponents: prompts.bootstrapComponents.values.official }); }); it('should add Bootstrap JS files', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.noFileContent([ ['gulp/inject.js', /\/bootstrap\\\.js\//] ]); done(); }); }); }); describe('with prompt: [Angular Material]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values['angular-material'] }); }); it('should add Angular Material Bower and Angular modules', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.noFile('src/app/vendor.*'); assert.fileContent([ ['bower.json', libRegexp('angular-material', prompts.ui.values['angular-material'].version)], ['src/app/index.js', /'ngMaterial'/] ]); done(); }); }); }); describe('with prompt: [None UI Framework, Node SASS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.none, cssPreprocessor: prompts.cssPreprocessor.values['node-sass'] }); }); it('should add index style', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent([].concat(expectedGulpContent, [ // Check package.json ['package.json', libRegexp('gulp-sass', prompts.cssPreprocessor.values['node-sass'].version)] ])); assert.noFile('src/app/vendor.*'); done(); }); }); }); describe('with prompt: [None UI Framework, Ruby SASS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.none, cssPreprocessor: prompts.cssPreprocessor.values['ruby-sass'] }); }); it('should add index style', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent([].concat(expectedGulpContent, [ // Check package.json ['package.json', libRegexp('gulp-ruby-sass', prompts.cssPreprocessor.values['ruby-sass'].version)] ])); assert.noFile('src/app/vendor.*'); done(); }); }); }); describe('with prompt: [None UI Framework, LESS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.none, cssPreprocessor: prompts.cssPreprocessor.values.less }); }); it('should add index style', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent([].concat(expectedGulpContent, [ // Check package.json ['package.json', libRegexp('gulp-less', prompts.cssPreprocessor.values.less.version)] ])); assert.noFile('src/app/vendor.*'); done(); }); }); }); describe('with prompt: [None UI Framework, Stylus]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.none, cssPreprocessor: prompts.cssPreprocessor.values.stylus }); }); it('should add index style', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent([].concat(expectedGulpContent, [ // Check package.json ['package.json', libRegexp('gulp-stylus', prompts.cssPreprocessor.values.stylus.version)] ])); assert.noFile('src/app/vendor.*'); done(); }); }); }); describe('with prompt: [None UI Framework, CSS]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { ui: prompts.ui.values.none, cssPreprocessor: prompts.cssPreprocessor.values.none }); }); it('should add index style', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.noFile('src/app/vendor.*'); done(); }); }); }); describe('with prompt: [None JS Preprocessor]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { jsPreprocessor: prompts.jsPreprocessor.values.none }); }); it('should not add browerify and inject js files from src', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.noFile([ 'src/**/*.ts', 'src/**/*.coffee' ]); assert.fileContent([].concat(expectedGulpContent, [ ['gulp/inject.js', /gulp\.task\(\'inject\', \[\'styles\'\]/], ['gulp/inject.js', /paths\.src \+ '\/{app,components}\/\*\*\/\*\.js'/] ])); assert.noFileContent([ ['gulp/build.js', /gulp\.task\(\'browserify\'/], ['package.json', /gulp-browserify/] ]); done(); }); }); }); describe('with prompt: [CoffeeScript]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { jsPreprocessor: prompts.jsPreprocessor.values.coffee }); }); it('should not add browerify and add gulp-coffee', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/index.coffee', 'src/app/main/main.controller.coffee', 'src/components/navbar/navbar.controller.coffee', 'coffeelint.json' ])); assert.noFile([ 'src/app/index.js', 'src/app/main/main.controller.js', 'src/components/navbar/navbar.controller.js', 'src/**/*.ts' ]); assert.fileContent([].concat(expectedGulpContent, [ ['gulp/inject.js', /gulp\.task\('inject', \['styles', 'scripts'\]/], ['gulp/inject.js', /'{' \+ paths\.src \+ ',' \+ paths\.tmp \+ '\/serve}\/{app,components}\/\*\*\/\*\.js',/], ['package.json', /gulp-coffee/], ['package.json', /gulp-coffeelint/] ])); assert.noFileContent([ ['gulp/build.js', /gulp\.task\(\'browserify\'/], ['package.json', /gulp-browserify/] ]); done(); }); }); }); describe('with prompt: [6to5]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { jsPreprocessor: prompts.jsPreprocessor.values['6to5'] }); }); it('should add browerify and gulp-6to5', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/index.js', 'src/app/main/main.controller.js', 'src/components/navbar/navbar.controller.js' ])); assert.noFile([ 'src/**/*.coffee', 'src/**/*.ts' ]); assert.fileContent([].concat(expectedGulpContent, [ ['gulp/scripts.js', /gulp\.task\(\'scripts\'/], ['gulp/inject.js', /gulp\.task\('inject', \['styles', 'scripts'\]/], ['gulp/inject.js', /paths\.tmp \+ '\/serve\/{app,components}\/\*\*\/\*\.js',/], ['package.json', /browserify/], ['package.json', /6to5ify/], ['package.json', /vinyl-buffer/], ['package.json', /vinyl-source-stream/] ])); done(); }); }); }); describe('with prompt: [Traceur]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { jsPreprocessor: prompts.jsPreprocessor.values.traceur }); }); it('should add browerify and gulp-traceur and traceur-runtime', function (done) { gulpAngular.run(function () { assert.file(expectedFile); assert.file([].concat(expectedFile, [ 'src/app/index.js', 'src/app/main/main.controller.js', 'src/components/navbar/navbar.controller.js' ])); assert.noFile([ 'src/**/*.coffee', 'src/**/*.ts' ]); assert.fileContent([].concat(expectedGulpContent, [ ['gulp/scripts.js', /gulp\.task\(\'browserify\'/], ['gulp/inject.js', /gulp\.task\('inject', \['styles', 'browserify'\]/], ['gulp/inject.js', /paths\.tmp \+ '\/serve\/{app,components}\/\*\*\/\*\.js',/], ['package.json', /browserify/], ['package.json', /vinyl-buffer/], ['package.json', /vinyl-source-stream/], ['bower.json', /traceur-runtime/] ])); done(); }); }); }); describe('with prompt: [TypeScript]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { jsPreprocessor: prompts.jsPreprocessor.values.typescript }); }); it('should not add browserify, but gulp-typescript and tsd gulpfile', function (done) { gulpAngular.run(function () { assert.file([].concat(expectedFile, [ 'src/app/index.ts', 'src/app/main/main.controller.ts', 'src/components/navbar/navbar.controller.ts', 'gulp/tsd.js', 'tslint.json' ])); assert.noFile([ 'src/app/index.js', 'src/app/main/main.controller.js', 'src/components/navbar/navbar.controller.js', 'src/**/*.coffee' ]); assert.fileContent([].concat(expectedGulpContent, [ ['gulp/inject.js', /gulp\.task\('inject', \['styles', 'scripts'\]/], ['gulp/inject.js', /'{' \+ paths\.src \+ ',' \+ paths\.tmp \+ '\/serve}\/{app,components}\/\*\*\/\*\.js',/], ['package.json', /gulp-typescript/], ['gulp/build.js', /gulp\.task\('clean', \['tsd:purge']/], ['gulp/scripts.js', /gulp\.task\('scripts', \['tsd:install']/] ])); assert.noFileContent([ ['gulp/build.js', /gulp\.task\(\'browserify\'/], ['package.json', /gulp-browserify/] ]); done(); }); }); }); describe('with prompt: [Jade HTML Preprocessor]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), skipOptions); promptCase = _.assign(_.cloneDeep(defaultPrompts), { htmlPreprocessor: prompts.htmlPreprocessor.values.jade }); }); it('should not have consolidate gulp task', function (done) { gulpAngular.run(function () { assert.file([].concat(_.clone(expectedFile), [ 'gulp/markups.js' ])); assert.fileContent([ ['gulp/build.js', /gulp\.task\('partials', \['markups'\]/], ['gulp/markups.js', /gulp\.task\('markups'/], ['gulp/markups.js', /return gulp\.src\(paths\.src \+ '\/{app,components}\/\*\*\/\*\.jade'\)/], ['gulp/markups.js', /\.pipe\(\$\.consolidate\('jade'/], ['gulp/watch.js', /gulp\.watch\(paths\.src \+ '\/{app,components}\/\*\*\/\*\.jade', \['markups'\]\);/] ]); done(); }); }); }); describe('with paths: [src:path/to/public e2e:path/to/e2e/test dist:path/to/dist tmp:.tmp/folder]', function () { before(function () { optionCase = _.assign(_.cloneDeep(defaultOptions), _.merge({ 'app-path': 'path/to/public', 'dist-path': 'path/to/dist', 'e2e-path': 'path/to/test', 'tmp': '.tmp/folder' }, skipOptions)); promptCase = _.cloneDeep(defaultPrompts); }); it('should generate the expected files and their content', function (done) { expectedFile = _.map(expectedFile, function(file) { if (file.indexOf('src') === 0) { return file.replace('src', optionCase['app-path']); } return file; }); gulpAngular.run(function () { assert.file([].concat(expectedFile, [ // Option: Javascript optionCase['app-path'] + '/app/index.js', optionCase['app-path'] + '/app/main/main.controller.js', optionCase['app-path'] + '/app/main/main.controller.spec.js', optionCase['app-path'] + '/components/navbar/navbar.controller.js', 'karma.conf.js', 'protractor.conf.js', optionCase['e2e-path'] + '/main.po.js', optionCase['e2e-path'] + '/main.spec.js', // Option: ngRoute optionCase['app-path'] + '/app/main/main.html', // Option: Sass (Node) optionCase['app-path'] + '/app/index.scss', optionCase['app-path'] + '/app/vendor.scss', ])); assert.noFile([ optionCase['app-path'] + '/**/*.ts', optionCase['app-path'] + '/**/*.coffee' ]); assert.fileContent([].concat(expectedGulpContent, [ // Check src/app/index.js [optionCase['app-path'] + '/app/index.js', /'ngAnimate'/], [optionCase['app-path'] + '/app/index.js', /'ngCookies'/], [optionCase['app-path'] + '/app/index.js', /'ngTouch'/], [optionCase['app-path'] + '/app/index.js', /'ngSanitize'/], [optionCase['app-path'] + '/app/index.js', /'ngResource'/], [optionCase['app-path'] + '/app/index.js', /'ngRoute'/], // Check src/app/vendor.scss [optionCase['app-path'] + '/app/vendor.scss', /\$icon-font-path: "\/bower_components\/bootstrap-sass-official\/assets\/fonts\/bootstrap\/";/], [optionCase['app-path'] + '/app/vendor.scss', /@import '\.\.\/\.\.\/\.\.\/\.\.\/bower_components\/bootstrap-sass-official\/assets\/stylesheets\/bootstrap';/], // Check bower.json ['bower.json', libRegexp('angular', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('angular-animate', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('angular-cookies', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('angular-touch', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('angular-sanitize', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('jquery', prompts.jQuery.values['jquery 2'].version)], ['bower.json', libRegexp('angular-resource', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('angular-route', prompts.angularVersion.values['1.3'])], ['bower.json', libRegexp('bootstrap-sass-official', prompts.ui.values.bootstrap.version)], // Check package.json ['package.json', libRegexp('gulp-sass', prompts.cssPreprocessor.values['node-sass'].version)], // Check wiredep css exclusion. ['gulp/inject.js', /exclude:.*?\/bootstrap\\\.css\/.*?/] ])); done(); }); }); }); // For future case /* describe('with prompt: []', function () { it('should', function (done) { var _ = gulpAngular._; helpers.mockPrompt(gulpAngular, _.assign(prompt, { // jQuery: { // "name": null, // "version": "1.1.x" // } })); gulpAngular.run(function () { assert.file(expectedFile); assert.fileContent(expectedGulpContent); done(); }); }); }); */ });
var sylvester = require('sylvester'), ols = require('./ols.js'); function randomreg(n,k){ var Y = sylvester.Matrix.Random(n,1); Y = Y.x(10); Y = Y.round(); var X = sylvester.Matrix.Random(n,k); X = X.x(10); X = X.round(); console.log('Y: ' + Y.elements); console.log('X: ' + JSON.stringify(X.transpose().elements)); var reg = ols.reg(Y,X); return reg; } function staticreg() { var Y = $M([10,4,3,5,9,3,3,2,6,7]); var X = $M([[6,4,9,1,4,6,4,0,9,10],[1,4,2,5,7,3,2,9,6,1],[6,0,2,3,6,2,8,8,5,7],[2,6,8,10,1,2,8,2,6,1]]); X = X.transpose(); var reg = ols.reg(Y, X); return reg; } console.log('Random: ' + JSON.stringify(randomreg(10, 4), null, 2)); //console.log('Known: ' + JSON.stringify(staticreg(), null, 2));
import "@testing-library/jest-dom/extend-expect"; import { cleanup, render } from "@testing-library/react"; import { MemoryRouter as Router } from "react-router-dom"; import Header from "./Header"; import React from "react"; describe("Header", () => { afterEach(cleanup); it("should render Header", () => { const { getByText } = render( <Router> <Header /> </Router> ); expect(getByText("Black Stories Matter")).toBeInTheDocument(); }); });
(function () { 'use strict'; angular.module('routerApp').directive('modelEdit', ["$compile", function ($compile) { return { scope: { title: '@', model: '=', id: '@', arrayHints: '=' }, transclude: true, templateUrl: 'views/modal/edit-model.html', link: function (scope, element, attrs) { scope.isObject = _.isObject(scope.model) && !_.isArray(scope.model); scope.isArray = _.isArray(scope.model) scope.temp = angular.copy(scope.model); scope.openModal = function (id) { $('#modal' + scope.id).openModal(); }; scope.save = function () { Object.assign(scope.model, scope.temp); } scope.cancel = function () { scope.temp = angular.copy(scope.model); } } } }]); })();
var Async = require('async'), Fs = require('fs'), Fse = require('fs-extra'), Deepmerge = require("deepmerge"); Path = require('path'), _ = require('lodash'), localeDirectory = 'lang', localeTmpDirectory = 'lang_tmp'; module.exports.assemble = assemble; module.exports.restoreLangFolder = restoreLangFolder; module.exports.localeDirectory = localeDirectory; /** * Assembles together all of the lang files. * This simply loads the files from the lang directory and puts them in an object where * locale name is the key and locale data is the value * * @param callback * @param localeSetting */ function assemble(callback, localeSetting) { if( localeSetting ) { console.log('ok'.green + ' -- Locale setting has been found in config file'); Async.waterfall([ function(aCbck) { Fse.copy(localeDirectory, localeTmpDirectory, aCbck); }, function(aCbck) { Fse.emptyDir(localeDirectory, aCbck); }, function(aCbck) { var fileName = localeSetting; if( localeSetting.indexOf( '-' ) !== -1 ) { fileName = localeSetting.split('-')[0]; } fileName += '.json' Fse.copy(localeTmpDirectory + '/' + fileName, localeDirectory + '/en.json', aCbck); }, function(aCbck) { if( localeSetting.indexOf( '-' ) !== -1 ) { var src = JSON.parse(Fse.readFileSync(localeTmpDirectory + '/' + localeSetting + '.json', 'utf8')); var dst = JSON.parse(Fse.readFileSync(localeDirectory + '/en.json', 'utf8')); Fse.writeJson(localeDirectory + '/en.json', Deepmerge(dst, src), aCbck); } else { aCbck(); } } ], function(err) { if( err ) { console.error(err); } console.log('ok'.green + ' -- en.json file was generated using locale config setting'); assembleConcat(callback); }); } else { assembleConcat(callback); } } function restoreLangFolder(callback, localeSetting) { if( localeSetting ) { Async.waterfall([ function(aCbck) { Fse.copy(localeTmpDirectory, localeDirectory, aCbck); }, function(aCbck) { Fse.remove(localeTmpDirectory, aCbck); }, ], function( err ) { if( err ) { console.log( err ); } console.log('ok'.green + ' -- Lang folder restored'); callback(); }); } else { callback(); } } function assembleConcat(callback) { Fs.readdir(localeDirectory, function (err, localeFiles) { var localesToLoad = {}; // Ignore hidden files // @example: MAC generates .DS_STORE localeFiles = _.filter(localeFiles, function(fileName) { return fileName[0] !== '.'; }); if (err) { return callback(err); } _.each(localeFiles, function (localeFile) { var localeName = Path.basename(localeFile, '.json'); localesToLoad[localeName] = function (callback) { var localeFilePath = localeDirectory + '/' + localeFile; Fs.readFile(localeFilePath, 'utf-8', callback); }; }); Async.parallel(localesToLoad, callback); }); }
import React from "react" import { Link } from "react-router-dom" function Card({ content, from }) { return ( <> <Link to={`${from}/${content._id}`}> <img style={{ width: "200px" }} src={content.poster_path} alt={content._id} /> </Link> </> ) } export default Card
// @flow import type { StandardTx, SwapFuncParams } from './checkSwapService.js' const bns = require('biggystring') const { checkSwapService } = require('./checkSwapService.js') const js = require('jsonfile') const fetch = require('node-fetch') const confFileName = './config.json' const config = js.readFileSync(confFileName) const BITY_CACHE = './cache/bityRaw.json' const BITY_TOKEN_URL = 'https://connect.bity.com/oauth2/token' const BITY_API_URL = 'https://reporting.api.bity.com/exchange/v1/summary/monthly/' const PAGE_SIZE = 100 async function doBity (swapFuncParams: SwapFuncParams) { return checkSwapService(fetchBity, BITY_CACHE, 'BITY', swapFuncParams ) } let queryYear = '2020' let queryMonth = '1' const todayMonth = bns.add(new Date().getMonth().toString(), '1') const todayYear = new Date().getFullYear().toString() async function fetchBity (swapFuncParams: SwapFuncParams) { if (!swapFuncParams.useCache) { console.log('Fetching Bity from JSON...') } let diskCache = { txs: [], offset: {lastCheckedMonth: queryMonth, lastCheckedYear: queryYear} } try { const diskCacheOnDisk = js.readFileSync(BITY_CACHE) diskCache = {...diskCache, ...diskCacheOnDisk} // Get most recent query from cache and subtract a month queryMonth = diskCache.offset.lastCheckedMonth queryYear = diskCache.offset.lastCheckedYear } catch (e) {} // Get auth token const credentials = { 'grant_type': 'client_credentials', scope: 'https://auth.bity.com/scopes/reporting.exchange', client_id: config.bity.clientId, client_secret: config.bity.clientSecret } const tokenParams = Object.keys(credentials).map((key) => { return encodeURIComponent(key) + '=' + encodeURIComponent(credentials[key]) }).join('&') const newTransactions = [] try { const tokenResponse = await fetch(BITY_TOKEN_URL, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: tokenParams }) const tokenReply = await tokenResponse.json() const authToken = tokenReply.access_token // Query monthly orders let keepQuerying = true let page = 1 while (keepQuerying) { const monthlyResponse = await fetch(`${BITY_API_URL}${queryYear}-${queryMonth}/orders?page=${page}`, { method: 'GET', headers: { Authorization: `Bearer ${authToken}` } } ) let monthlyTxs = [] if (monthlyResponse.ok) { monthlyTxs = await monthlyResponse.json().catch(e => []) } for (const tx of monthlyTxs) { const ssTx: StandardTx = { status: 'complete', inputTXID: tx.id, inputAddress: '', inputCurrency: tx.input.currency.toUpperCase(), inputAmount: parseFloat(tx.input.amount), outputAddress: '', outputCurrency: tx.output.currency.toUpperCase(), outputAmount: tx.output.amount.toString(), timestamp: Date.parse(tx.timestamp_executed.concat('Z')) / 1000 } newTransactions.push(ssTx) } if (monthlyTxs.length < PAGE_SIZE && queryMonth === todayMonth && queryYear === todayYear) { if (queryMonth === '1') { diskCache.offset.lastCheckedMonth = '12' diskCache.offset.lastCheckedYear = bns.sub(queryYear, '1') } else { diskCache.offset.lastCheckedMonth = bns.sub(queryMonth, '1') diskCache.offset.lastCheckedYear = queryYear } keepQuerying = false } else if (monthlyTxs.length === PAGE_SIZE) { page += 1 } else { page = 1 if (bns.lt(queryMonth, '12')) { queryMonth = bns.add(queryMonth, '1') } else { queryMonth = '1' queryYear = bns.add(queryYear, '1') } } } } catch (e) { console.log(e) } const out = { diskCache, newTransactions } return out } module.exports = { doBity }
var React = require('react/addons'); var UserItem = require('./UserItem.jsx'); var UserListAddItem = require('./UserListAddItem.jsx'); module.exports = React.createClass({ render: function() { return ( <div> <h1>Users List</h1> <ul> {this.props.items.map(function(item, index) { return ( <UserItem item={item} key={"item"+index} /> ) })} </ul> <UserListAddItem /> </div> ) } });
import augmentChessBoard from '/chess/wasm_load.js' async function main() { await augmentChessBoard() /** * @type {import('chessboard-element').ChessBoardElement} */ const board = $('chess-board') board.init() } main()
const io = require('./lib/io'); const is = require('./lib/types'); const settings = require('./lib/constants'); const parse = require('./lib/parse').parse; (function main() { const config = io.readJSON(settings.CONFIGFILEPATH); const configFolders = Object.keys(config).filter(x => is.array(config[x])); const parsedConfig = parse(configFolders, config); io.write(`${settings.OUTPUTPATH}data.json`, JSON.stringify(parsedConfig)); }());
import React from "react"; import PropTypes from "prop-types"; import { List } from "react-virtualized"; import "./Posts.scss"; const Posts = (props) => { const rowRenderer = ({ key, index, isScrolling, isVisible, style }) => { return ( <div key={key} style={style} className="posts__item"> <i onClick={() => props.handleLikeClick(index)} className={`fa fa-heart ${ props.posts[index].like ? "red-heart" : "" }`} ></i> <i onClick={() => props.handleDelete(index)} className="fa fa-trash" ></i> <a href={props.posts[index].postObj.data.url}>{props.posts[index].postObj.data.title}</a> </div> ); }; return ( <div className="posts"> <List rowCount={props.posts.length} width={1200} height={350} rowHeight={50} rowRenderer={rowRenderer} /> </div> ); }; Posts.propTypes = { posts: PropTypes.array, handleDelete: PropTypes.func, handleLikeClick: PropTypes.func, }; export default Posts;
/* console.log("hello again!"); var num = 8; var num = 10; console.log(num); // output obviously 10 //change the var to let, and youll get an undefined. function numbers() { for (let i = 0; i < 5; i += 1) { console.log(i); } console.log(i); } numbers(); */ var accountMoney = 500; var vat = .20; var transactions = 2100; var afterVat = transactions + transactions*vat; var sum = ""; if (transactions < 0) { sum = accountMoney + afterVat; } else{ sum = accountMoney + transactions; } console.log(sum);
"use strict" var Promise = require('./util').Promise, Callbacks = require('./callbacks'), MongoError = require('./mongo_error'), Long = require('./bson/long'), ObjectId = require('./bson/objectid'), co = require('co'), serialize = require('./util').serialize, deserializeFast = require('./bson/bson_parser').deserializeFast, Db = require('./db'); var deserialize = function(obj) { if(obj != null && typeof obj === 'object') { for(var name in obj) { if(obj[name] != null && obj[name]['$numberLong']) { obj[name] = Long.fromString(obj[name]['$numberLong']); } else if(obj[name] != null && obj[name]['$oid']) { obj[name] = new ObjectId(obj[name]['$oid']); } else if(obj[name] != null && obj[name]['$date']) { obj[name] = new Date(obj[name]['$date']); } else if(obj[name] != null && typeof obj[name] === 'object') { obj[name] = deserialize(obj[name]); } } } return obj; } class MongoClient { constructor(transportFactory) { this.transportFactory = transportFactory; this.store = new Callbacks(); } isConnected() { return this.transportFactory && this.transportFactory.isConnected(); } connect(url, channel, options) { var self = this; // Set the options this.options = options || {} // Use a custom channel or the default one this.channel = channel || 'mongodb'; // Return the promise to allow for the connection return new Promise(function(resolve, reject) { co(function*() { // Save the socket self.transport = yield self.transportFactory.connect(url, options); // Listen to all mongodb socket information self.transport.onChannel(self.channel, function(data) { if(data.ok != null && !data.ok) { self.store.call(data._id, new MongoError(data), undefined); } else if(data.ok != null && data.ok && typeof data.type == 'string') { self.store.update(deserialize(data)); } else if(data.ok != null && data.ok) { if(data.result.length) { data.result = deserializeFast(data.result); } else { data.result = deserialize(data.result); } // Result from a command self.store.call(data._id, null, data); } }); self.transport.on('connect', function() { co(function*() { // Execute ismaster against server to determine abilites available self.abilities = yield self.db('admin').command({ismaster:true}); // Resolve resolve(self); }).catch(function(err) { reject(err); }); }); self.transport.on('close', function() { reject(); }); self.transport.on('error', function(e) { reject(e); }); }).catch(function(err) { reject(err); }); }); } db(name) { return new Db(name, this.channel, this.transport, this.store); } // // Supports one or more operations, allowing for batching up // of command to save on round-trips to the server command(op, options = {}) { var self = this; // Return the promise return new Promise(function(resolve, reject) { // Final batch op sent to the server var cmd = { _id: self.store.id(), op: serialize(op) }; // Add a listener to the store self.store.add(cmd._id, function(err, result) { if(err) return reject(err); resolve(options.fullResult ? result : result.result); }); // Write the operation out on the transport (with a group id) self.transport.write(self.channel, cmd); }); } // // Send a command that includes a stream // async commandStream(op, stream, options = {}) { var self = this; // if(typeof XMLHttpRequest === 'undefined') { // throw new Error('XMLHttpRequest not found in the windows or global namespace'); // } // Return the promise return new Promise(function(resolve, reject) { // Final batch op sent to the server var cmd = { _id: self.store.id(), op: serialize(op) }; // Add a listener to the store self.store.add(cmd._id, function(err, result) { if(err) return reject(err); resolve(options.fullResult ? result : result.result); }); // Write the operation out on the transport (with a group id) self.transport.writeStream(self.channel, cmd, stream); }); } } module.exports = MongoClient;
export * from './BaristaPage'
const Stored_procedure_helper = require('./sprocs_class/sproc_helper') const run_sp = (name,arg,res = null)=>{ const sp_helper = new Stored_procedure_helper(name,arg) return sp_helper.get_data_by_sp(name,arg,res); } const get_sp_def = (routine_schema,sproc_name,res = null)=>{ const sp_helper = new Stored_procedure_helper(sproc_name) return sp_helper.get_sp_defination(routine_schema,sproc_name,res); } const drop_sp = (sproc_name,res = null)=>{ const sp_helper = new Stored_procedure_helper(sproc_name) return sp_helper.drop_procedure(sproc_name,res); } module.exports = {run_sp,get_sp_def,drop_sp}; /* Note: Currently store procedure middleware only expects number,string,array in para convert them in string only Read log if needed You can only achieve some fast performance with stored procedure just because it is cached in sql server in binary form and only function call with para goes to sql every time Real performance you can achieve with efficient query 1. Sql partitioning of searching huge data ** 2. Instead of update use case 3. Use temperory table for joins and delete them after use 4. Avoid joins instead use sub query if possible ** 5. Avoid cursor,triggers 6. Select exact amount of data needed 7. Use stored procedures ** 8. Avoid distinct instead use group by self join ** 9. Use EXISTS instead of where IN 10. Avoid subquery use CTE */
const express = require("express"); const router = express.Router(); const infoController = require("../controllers/infoController"); const socialController = require("../controllers/socialController"); const policyController = require("../controllers/policyController"); const imagesController = require("../controllers/imagesController"); const heroController = require("../controllers/heroController"); const subController = require("../controllers/subController"); // isValidID Middleware router.param("token", infoController.validateID); router.route(`/social/`).get(socialController.getAll); router.route(`/policies/`).get(policyController.getAll); router.route(`/images/`).get(imagesController.getAll); router.route(`/hero/`).get(heroController.getAll); router.route(`/subs/`).post(subController.addOne); router.route(`/subs/:token`).get(subController.getAll); router.route(`/social/:token`).patch(socialController.patchAll); router.route(`/policies/:token`).patch(policyController.patchAll); router.route(`/images/:token`).patch(imagesController.patchAll); router.route(`/hero/:token`).patch(heroController.patchAll); module.exports = router;
'use strict'; var username = null; var stompClient = null; var textMessage = document.querySelector("#textMessage"); var messageArea = document.querySelector("#messageArea"); var listUser = document.querySelector("#list"); function connect(){ username = document.querySelector("#username").innerText.trim(); var socket = new SockJS("/ws"); stompClient = Stomp.over(socket); stompClient.connect({}, onConnected, onError); } connect(); function onError(){ document.querySelector("#errorMessage").innerText = 'Can not connect to server!'; } function onConnected(){ stompClient.subscribe('/topic/userOnlineList', userListReceived); stompClient.subscribe('/topic/publicChatRoom', onMessageReceived); stompClient.send('/app/chat.AddUser', {}, JSON.stringify({sender:username,type:'JOIN'})); } function disconnect(){ stompClient.send('/app/chat.deleteUser', {}, JSON.stringify({sender:username,type:'LEAVE'})) } function sendMessage(){ if(textMessage.value.trim() && stompClient){ var chatMessage = { sender: username, type: 'CHAT', content: textMessage.value } stompClient.send("/app/chat.SendMessage",{},JSON.stringify(chatMessage)); textMessage.value = ''; } } function userListReceived(payload){ var userList = JSON.parse(payload.body); var user; listUser.textContent = ''; for(user in userList){ var li = document.createElement('LI'); var username = document.createTextNode(userList[user]); li.appendChild(username); listUser.appendChild(li); } } function onMessageReceived(payload){ var message = JSON.parse(payload.body); var messageContent = null; if(message.type==='JOIN'){ messageContent = message.sender + " joined\n"; } else if(message.type==='LEAVE'){ messageContent = message.sender + " leave\n"; } else{ messageContent= message.sender + ": " + message.content + "\n"; } messageArea.value = messageArea.value + messageContent; }
var StaticClass = /** @class */ (function () { function StaticClass() { } StaticClass.disp = function () { console.log("Print the value of num " + StaticClass.num); }; return StaticClass; }()); StaticClass.num = 25; StaticClass.disp();
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import './style.less'; export default class DragBar extends Component { constructor(props) { super(props); window.addEventListener('mouseup', this.handleDragEnd); window.addEventListener('touchend', this.handleDragEnd); window.addEventListener('mousemove', this.handleDragging); window.addEventListener('touchmove', this.handleDragging); } static propTypes = { onDragStart: PropTypes.func, onDragging: PropTypes.func, onDragEnd: PropTypes.func, }; state = { isDragging: false, original: { x: 0, y: 0, }, moved: { x: 0, y: 0, }, }; componentWillUnmount() { window.removeEventListener('mouseup', this.handleDragEnd); window.removeEventListener('touchend', this.handleDragEnd); window.removeEventListener('mousemove', this.handleDragging); window.removeEventListener('touchmove', this.handleDragging); } handleDragStart = (event) => { let clientX = 0; let clientY = 0; if (event.nativeEvent instanceof MouseEvent) { clientX = event.nativeEvent.clientX; clientY = event.nativeEvent.clientY; // When user click with right button the resize is stuck in resizing mode // until users clicks again, dont continue if right click is used. if (event.nativeEvent.which === 3) { return; } } else if (event.nativeEvent instanceof TouchEvent) { clientX = event.nativeEvent.touches[0].clientX; clientY = event.nativeEvent.touches[0].clientY; } const original = {x: clientX, y: clientY}; this.setState({isDragging: true, original}); if (this.props.onDragStart) { this.props.onDragStart(); } }; handleDragging = (event) => { const {isDragging, original} = this.state; if (isDragging) { event.preventDefault(); const clientX = event instanceof MouseEvent ? event.clientX : event.touches[0].clientX; const clientY = event instanceof MouseEvent ? event.clientY : event.touches[0].clientY; const {x: originalX, y: originalY} = original; const moved = { x: clientX - originalX, y: clientY - originalY, }; this.setState({moved}); if (this.props.onDragging) { this.props.onDragging({...moved, clientX, clientY}); } } return false; }; handleDragEnd = () => { const {isDragging, moved} = this.state; if (isDragging) { this.setState({isDragging: false}); if (this.props.onDragEnd) { this.props.onDragEnd(moved); } } }; render() { const {onDragStart, onDragging, onDragEnd, ...others} = this.props; return ( <div {...others} onMouseDown={this.handleDragStart} onTouchStart={this.handleDragStart} > <div styleName="drag-bar-icon" className="drag-bar-icon"> <span/> <span/> <span/> <span/> <span/> <span/> <span/> </div> </div> ); } }
const jwt = require('jsonwebtoken'); const secret = process.env.SECRET; /** * Authentication middleware */ function authorization(request, response, next) { const { authorization } = request.headers; const error = { message: 'Unauthorized', }; if (!authorization) { next(); return; } if (authorization.indexOf(' ') === -1) { error.message = 'Invalid token'; return response.status(401).send(error); } const token = authorization.split(" ")[1]; jwt.verify(token, secret, function(err, decoded) { if (!err) { request.user = decoded.user; } else { return response.status(401).send(error); } }); next(); } module.exports = authorization;