text
stringlengths
7
3.69M
function CreateBadge(icon,header,content,url){ var Badge = '<li class="list-item game-card">'+ '<div class="game-card-container">'+ '<a href='+url+' class="game-card-link">'+ '<div class="game-card-thumb-container">'+ '<img class="game-card-thumb" src='+icon+' alt="Catalog Notifier" image-retry="">'+ '</div>'+ '<div class="text-overflow game-card-name" title="Catalog Notifier" ng-non-bindable="">'+header+'</div>'+ '<div class="game-card-name-secondary">'+content+'</div>'+ '</a>'+ '<span class="game-card-footer">'+ '<span class="text-label xsmall">By </span>'+ '<a class="text-link xsmall text-overflow" href="https://chrome.google.com/webstore/detail/roblox-enhancer/gmnpgjlgjedlhfnphihaimmimdmmgiim">Roblox Enhancer</a>'+ '</span>'+ '</div>'+ '</li>' var NewBadge = '<li class="list-item game-card">'+ '<div class="game-card-container">'+ '<a href='+url+' class="game-card-link">'+ '<div class="game-card-thumb-container">'+ '<img class="game-card-thumb" src='+icon+' alt="Catalog Notifier" image-retry="">'+ '<img src="https://images.rbxcdn.com/8a25ded7fa07d098dac7f234e7b34cfd.png" id="ctl00_cphRoblox_ItemNewOverlay" class="thumbnail-overlay" alt="New" style="width:70px;height:70px;position: absolute; top: 0px; right: 0px;">'+ '</div>'+ '<div class="text-overflow game-card-name" title="Catalog Notifier" ng-non-bindable="">'+header+'</div>'+ '<div class="game-card-name-secondary">'+content+'</div>'+ '</a>'+ '<span class="game-card-footer">'+ '<span class="text-label xsmall">By </span>'+ '<a class="text-link xsmall text-overflow" href="https://chrome.google.com/webstore/detail/roblox-enhancer/gmnpgjlgjedlhfnphihaimmimdmmgiim">Roblox Enhancer</a>'+ '</span>'+ '</div>'+ '</li>' if($('#loading')){$('#loading').remove();} if(header.match(/New/)){ $('#GamesPageLeftColumn > .hlist').append(NewBadge); $('.hlist').css({'white-space':'pre-line'}); }else{ $('#GamesPageLeftColumn > .hlist').append(Badge); $('.hlist').css({'white-space':'pre-line'}); } } $(function(){ if(window.location.href.match(/https:\/\/www.roblox.com\/games\/\?Keyword=CatalogNotification/)){ //chrome.storage.sync.set({'Items':''}) $('#ResponsiveWrapper').css({'display':'none'}) $('#ResponsiveWrapper').after('<div id="ResponsiveWrapper" class="games-responsive-wrapper ads-in-game-search games-lists-single" data-gamessearchonpage="true" data-adsingamesearchresultsenabled="true"><div id="GamesPageLeftColumn" class="games-page-left " data-searchstate="off"><ul class="hlist games game-cards"><center id="loading"><h1>Loading....</h1></center></ul></div></div>') chrome.extension.sendRequest({action: 'GetBadges'}) chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) { CreateBadge(msg.action[0],msg.action[1],msg.action[2],msg.action[3]) }); } })
const { GraphQLClient } = require("graphql-request"); const GRAPHQL_URI = "http://mazzad.herokuapp.com/v1alpha1/graphql"; module.exports = new GraphQLClient(GRAPHQL_URI, { headers: { "x-hasura-admin-secret": "mazzadapi" } });
import { rhythm, colors, transitions } from '../../lib/traits' export default { base: { display: 'inline-block', lineHeight: 1, color: colors.light, padding: `${rhythm(0.5, 'em')} ${rhythm(0.75, 'em')}`, transition: `box-shadow ${transitions.easeOut}`, ':hover': { boxShadow: `inset 0 0 0 ${rhythm(10)} rgba(0,0,0,0.2)` } }, type: { basic: { backgroundColor: colors.dark }, maroon: { backgroundColor: colors.maroon, fontSize: '12px', '@media screen and (min-width:40em)': { fontSize: '18px' } }, orange: { backgroundColor: colors.orange, fontSize: '12px', lineHeight: 2.5, '@media screen and (min-width:40em)': { fontSize: '18px', lineHeight: 1 } }, maroonGrow: { backgroundColor: colors.maroon, flexGrow: '1' }, orangeGrow: { backgroundColor: colors.orange, flexGrow: '1' } } }
var io = require('socket.io-client'); var socket = io('http://localhost:8000'); socket.emit('join_room', 'foobar'); socket.emit('foo', {bar: 'bar', room: 'foobar'}); socket.on('foo', function(args) { console.log(args); // -> ['bar'] });
Ext.namespace('Ext.Syis.lib'); Ext.Syis.lib.SyisModifyVeWin = Ext.extend(Ext.Window, { type : null, record : null, modifyVeUrl : null, constructor : function(_cfg) { if (_cfg == null) { _cfg = {}; }; Ext.apply(this, _cfg); Ext.QuickTips.init(); var me = this; var fieldPlugins = [new Ext.ux.FieldStylePlugin()]; var items = null; if(me.type == 'inbill'){ items = [ {xtype : 'textfield', fieldLabel : '入库单号', name : 'billNo', width : 150, value : me.record.data.billNo, readOnly : true, plugins: fieldPlugins}, {xtype : 'textfield', fieldLabel : '原车辆编号', name : 'veNo', width : 150, value : me.record.data.veNo, readOnly : true, plugins: fieldPlugins}, {xtype : 'textfield', fieldLabel : '新车辆编号', name : 'veNo2', width : 150} ] } else { items = [ {xtype : 'textfield', fieldLabel : '出库单号', name : 'outBillNo', width : 150, value : me.record.data.outBillNo, readOnly : true, plugins: fieldPlugins}, {xtype : 'textfield', fieldLabel : '原车辆编号', name : 'veNo', width : 150, value : me.record.data.veNo, readOnly : true, plugins: fieldPlugins}, {xtype : 'textfield', fieldLabel : '新车辆编号', name : 'veNo2', width : 150} ] } me.syisModifyVePanel = new Ext.form.FormPanel({ labelAlign : 'right', buttonAlign : 'center', labelWidth : 120, labelSeparator : ':', border : false, frame : true, defaults : { baseCls : 'x-plain' }, items : items, buttons : [ {text : '确定', iconCls : 'btn-ok', handler : function(){ me.modifyVe(); }}, {text : '取消', iconCls : 'btn-cancel', handler : function(){ me.closeWin(); }} ] }); Ext.Syis.lib.SyisModifyVeWin.superclass.constructor.call(this, { id : 'syisModifyVeWin', title : '修改车辆编号', iconCls : 'btn-form', width : 350, modal : true, closable : true, resizable : false, items : me.syisModifyVePanel }); }, modifyVe : function(){ var me = this; var params = null; if(me.type == 'inbill'){ params = { 'id' : me.record.data.id, 'billNo' : me.syisModifyVePanel.find('name','billNo')[0].getValue(), 'veNo' : me.syisModifyVePanel.find('name','veNo2')[0].getValue() } } else { params = { 'id' : me.record.data.id, 'outBillNo' : me.syisModifyVePanel.find('name','outBillNo')[0].getValue(), 'veNo' : me.syisModifyVePanel.find('name','veNo2')[0].getValue() } } Ext.Ajax.request({ url : me.modifyVeUrl, params : params, success : function(response, opts){ me.closeWin(); Ext.getCmp('syisbillQuery').query_grid.getStore().reload(); }, failure : function(response, opts){ } }); }, closeWin : function(){ Ext.getCmp('syisModifyVeWin').close(); } });
$(function () { $("#more-concert").css({borderBottom:"3px solid #C81623", color:"#C81623"}); $(".phone-show li").hover(function(){ var i = $(this).index(); $(".phone-show li .desc").eq(i).hide() $(".phone-show .ph_buy").eq(i).css("opacity","1") $(".phone-show .ph_buy").eq(i).stop().animate({ bottom:"10" },300) }, function () { $(".phone-show li .desc").show() $(".phone-show .ph_buy").css("opacity","0") $(".phone-show .ph_buy").stop().animate({ bottom:"-75" },300) }) //选择手机类型 $(".phone-banner-list a").eq(2).css({backgroundColor:"#E80000", color:"white"}) $(".phone-banner-list a:gt(0)").click(function () { $(".phone-banner-list a").css({backgroundColor:"#ffffff", color:"#666666"}) $(this).css({backgroundColor:"#E80000", color:"white"}) }) $(".phone-banner-list1 a").eq(1).css({backgroundColor:"#E80000", color:"white"}) $(".phone-banner-list1 a:gt(0)").click(function () { $(".phone-banner-list1 a").css({backgroundColor:"#ffffff", color:"#666666"}) $(this).css({backgroundColor:"#E80000", color:"white"}) }) $(".phone-banner-list2 a").eq(2).css({backgroundColor:"#E80000", color:"white"}) $(".phone-banner-list2 a:gt(0)").click(function () { $(".phone-banner-list2 a").css({backgroundColor:"#ffffff", color:"#666666"}) $(this).css({backgroundColor:"#E80000", color:"white"}) }) $(".phone-banner-list3 a").eq(1).css({backgroundColor:"#E80000", color:"white"}) $(".phone-banner-list3 a:gt(0)").click(function () { $(".phone-banner-list3 a").css({backgroundColor:"#ffffff", color:"#666666"}) $(this).css({backgroundColor:"#E80000", color:"white"}) }) $(".phone-banner-list4 a").eq(1).css({backgroundColor:"#E80000", color:"white"}) $(".phone-banner-list4 a:gt(0)").click(function () { $(".phone-banner-list4 a").css({backgroundColor:"#ffffff", color:"#666666"}) $(this).css({backgroundColor:"#E80000", color:"white"}) }) })
import Ember from 'ember'; export function hot(params) { if (params[0] > 4) { return ("<img src='assets/shocked.png' alt='' />").htmlSafe(); } } export default Ember.Helper.helper(hot);
import {Grid} from "@material-ui/core"; import {useEffect} from "react"; import {useRecoilState} from "recoil"; import IconButton from "~/components/atoms/iconButton/IconButton"; import Select from "~/components/atoms/Select/Select"; import TextField from "~/components/atoms/textfield/Textfield"; import TextFieldWithTag from "~/components/atoms/textfield/TextFieldWithTag"; import useForm from "~/util/form"; import {segmentState, tagsState} from "../../../atoms"; const {StyledArrayConfigurator} = require("./ArrayConfigurator.style"); const ArrayConfigurator = function (props) { const [tags, setTags] = useRecoilState(tagsState); const [form, setForm, resetForm, replaceForm] = useForm({ prefixSingle: "", prefixMultiple: "", array: "", field: "", limit: 0, sortField: "", sortMethod: "", divider: "", lastDivider: "", suffixSingle: "", suffixMultiple: "", }); const [updateSegment, setUpdateSegment] = useRecoilState(segmentState); useEffect(() => { replaceForm({ prefixSingle: props.segment.data.prefixSingle, prefixMultiple: props.segment.data.prefixMultiple, array: props.segment.data.array ? props.segment.data.array.replace("{[", "").replace("]}", "") : "", field: props.segment.data.field ? props.segment.data.field.replace("{[", "").replace("]}", "") : "", limit: props.segment.data.limit, sortField: props.segment.data.sortField ? props.segment.data.sortField.replace("{[", "").replace("]}", "") : "", sortMethod: props.segment.data.sortMethod, divider: props.segment.data.divider, lastDivider: props.segment.data.lastDivider, suffixSingle: props.segment.data.suffixSingle, suffixMultiple: props.segment.data.suffixMultiple, }); }, []); useEffect(() => { if (form.array == "") return; let newSegment = JSON.parse(JSON.stringify(props.segment)); newSegment.data = { prefixSingle: form.prefixSingle, prefixMultiple: form.prefixMultiple, array: "{[" + form.array + "]}", field: "{[" + form.field + "]}", limit: form.limit, sortField: "{[" + form.sortField + "]}", sortMethod: form.sortMethod, divider: form.divider, lastDivider: form.lastDivider, suffixSingle: form.suffixSingle, suffixMultiple: form.suffixMultiple, }; setUpdateSegment(newSegment); }, [form]); return ( <StyledArrayConfigurator> <Grid container spacing={2}> <Grid item xs={form.array == "" ? 12 : 6}> <div className="input-wrapper"> <TextFieldWithTag mustSelectTag onChange={setForm} value={form.array} label="Variabele" name="array" tags={tags} allowed={["array"]} /> </div> </Grid> {form.array != "" && ( <> <Grid item xs={6}> <div className="input-wrapper"> <TextFieldWithTag mustSelectTag onChange={setForm} value={form.field} label="Veld" name="field" tags={[form.array.replace("{", "").replace("}", "") + "[]"]} allowed={["string", "number"]} /> </div> </Grid> <Grid item xs={4}> <div className="input-wrapper"> <TextFieldWithTag mustSelectTag onChange={setForm} value={form.sortField} label="Sorteren op veld" name="sortField" tags={[form.array.replace("{", "").replace("}", "") + "[]"]} allowed={["string", "number"]} /> </div> </Grid> <Grid item xs={4}> <div className="input-wrapper"> <Select label="Sorteer volgorde" onChange={setForm} value={form.sortMethod} name="sortMethod" items={[ {label: "Oplopend", value: "asc"}, {label: "Aflopend", value: "desc"}, ]} /> </div> </Grid> <Grid item xs={4}> <div className="input-wrapper"> <TextField onChange={setForm} value={form.limit} label="Limiet" name="limit" type="number" /> </div> </Grid> </> )} <Grid item xs={6}> <div className="input-wrapper"> <TextField onChange={setForm} value={form.prefixSingle} label="Voorvoegsel 1 item" name="prefixSingle" /> </div> </Grid> <Grid item xs={6}> <div className="input-wrapper"> <TextField onChange={setForm} value={form.prefixMultiple} label="Voorvoegsel meerdere items" name="prefixMultiple" /> </div> </Grid> </Grid> <Grid container spacing={2}> <Grid item xs={6}> <div className="input-wrapper"> <TextField onChange={setForm} value={form.divider} label="Scheidingsteken" name="divider" /> </div> </Grid> <Grid item xs={6}> <div className="input-wrapper"> <TextField onChange={setForm} value={form.lastDivider} label="Laatste scheidingsteken" name="lastDivider" /> </div> </Grid> </Grid> <Grid container spacing={2}> <Grid item xs={6}> <div className="input-wrapper"> <TextField onChange={setForm} value={form.suffixSingle} label="Achtervoegsel 1 item" name="suffixSingle" /> </div> </Grid> <Grid item xs={6}> <div className="input-wrapper"> <TextField onChange={setForm} value={form.suffixMultiple} label="Achtervoegsel meerdere items" name="suffixMultiple" /> </div> </Grid> </Grid> <div className="tools"> <div></div> <div> <IconButton className="configButton save" onClick={props.onClose} icon={["fal", "check"]} square small /> </div> </div> </StyledArrayConfigurator> ); }; export default ArrayConfigurator;
import isPlainObject from './.inside/isPlainObject'; import getType from './.inside/getType'; /** * 判断一个值是不是错误对象。 * `Error`, `EvalError`, `RangeError`, `ReferenceError`,`SyntaxError`, `TypeError`, or `URIError` * * @since V0.1.3 * @public * @param {*} value 需要判断类型的值 * @returns {boolean} 如果是错误对象返回true,否则返回false */ export default function (value) { if (value === null || typeof value !== 'object') { return false; } const type = getType(value); return type === '[object Error]' || type === '[object DOMException]' || (typeof value.message === 'string' && typeof value.name === 'string' && !isPlainObject(value)); };
import { fromJS } from 'immutable'; import * as actionType from './actionType.js'; const defaultState = fromJS({ topicList: [], articleList: [], writerList: [], articlePage: 1, showScroll: false }); const changeContent = (prevState,action)=>{ return prevState.merge({ topicList:fromJS(action.topicList), articleList:fromJS(action.articleList), writerList:fromJS(action.writerList) }) }; const updateList = (prevState,action)=>{ const newList = prevState.get('articleList').concat(action.articleList); return prevState.set('articleList',newList).set("articlePage",action.nextPage); } export default (prevState = defaultState,action)=>{ switch (action.type) { case actionType.CHANGE_CONTENT: return changeContent(prevState,action); case actionType.UPDATE_LIST: return updateList(prevState,action); case actionType.CHANGE_SHOW_SCROLL_TRUE: return prevState.set('showScroll',true); case actionType.CHANGE_SHOW_SCROLL_FALSE: return prevState.set('showScroll',false); default: return prevState; } }
import payment, {Creators as PaymentActions} from '../../store/ducks/payment' describe('Payment Duck', () => { const newPayment = { cardHolder: "Donald Martinez", cardNumber: "4764146564886488", cvv: "307", validity: "03/2023" } it('should be able to realize payment', () => { const state = payment({ data: {}}, PaymentActions.setPayment(newPayment)); expect(state.data).toBe(newPayment) }) })
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import {updateHistory} from '../../ducks/reducer.js'; import {connect} from 'react-redux'; class WizardEight extends Component { render(){ return( <div className="parent-div"> <div className="vert-align"> <p>Have you had a bankruptcy or foreclosure in the past seven years? </p><br /> <div className="row"> <Link to="/wNine"><button value="Has never been in bankruptcy" onClick={()=>this.props.updateHistory("Has never been in bankruptcy")}>No</button></Link> <Link to="/wNine"><button value="Has had bankruptcy before" onClick={()=>this.props.updateHistory("Has had bankruptcy before")}>Bankruptcy</button></Link> <Link to="/wNine"><button value="Has had a foreclosure before" onClick={()=>this.props.updateHistory("Has had a foreclosure before")}>Foreclosure</button></Link> <Link to="/wNine"><button value="Has had both a foreclosure and a bankruptcy" onClick={()=>this.props.updateHistory("Has had both a foreclosure and a bankruptcy")}>Both</button></Link> </div> </div> </div> ) } } function mapToState(state){ return{ history:state.history } } export default connect(mapToState, {updateHistory}) (WizardEight);
import dbConnection from '../../../middlewares/db'; import Post from '../../../models/Post'; import User from '../../../models/User'; import mongoose from 'mongoose'; import { getSession } from 'next-auth/client'; async function handler(req, res) { const { method } = req; const session = await getSession({ req }); if (method === 'PUT') { if (!session || !session.sub) return res.status(422).send(); const isValid = mongoose.Types.ObjectId.isValid(session.sub); if (isValid) { const mId = mongoose.Types.ObjectId(session.sub); const foundUser = await User.findById(mId); if (!foundUser) return res.status(404).send(); User.findByIdAndUpdate(session.sub, req.body, { new: true }) .then((updatedUser) => res.send(updatedUser._id)) .catch(() => res.status(500).send()); } else { return res.status(404).send(); } } } export default dbConnection(handler);
/** * Title: Initial file * Description: Project initial file to starts server and workers * Author: Samin Yasar * Date: 24/October/2021 */ // Dependencies const server = require("./src/helpers/server"); const worker = require("./src/helpers/worker"); // Module scaffolding const app = {}; // Definition of the initialize function of the app app.init = () => { // Start the server server.init(); // Start the workers worker.init(); }; // Initialize the app app.init();
var jsutil = jsutil || {}; /** can be used to copy a function's arguments into a real Array */ jsutil.Number = { range: function(from, to) { var out = []; for (var i=from; i<to; i++) out.push(i); return out; } };
// Seven Boom! // Create a function that takes an array of numbers and return "Boom!" if the number 7 appears in the array. Otherwise, return "there is no 7 in the array". // Examples sevenBoom([1, 2, 3, 4, 5, 6, 7])// ➞ "Boom!" sevenBoom([8, 6, 33, 100])// ➞ "there is no 7 in the array" sevenBoom([2, 55, 60, 97, 86])// ➞ "Boom!" function sevenBoom(arr) { var newStr = arr.join(); var boom; for (var i = 0; i < newStr.length; i++) { if (newStr.charAt(i) === '7') { boom = 'Boom!'; } } if (boom) { return boom; } else { return 'there is no 7 in the array'; } } // Make a container for the joined numbers // Join all the numbers together // Set a container for boom // Check if the joined number has a 7 in it // If so, add text to the container // If not, add nothing // Return the container if there is text // If there is no text, return error message
import React from "react"; import ReactDom from "react-dom"; import { Hangman } from "../Hangman"; import { resetButton, guessedWord, handleGuess, getMistake, getGameState, getDisplayText } from "../hangman-functions"; import { PROGRAMING_LANG } from "../words"; let mockState = { mistake: 100, guessed: new Set(), answer: "python" }; const setState = state => { mockState = state; }; it("renders without crashing", () => { const div = document.createElement("div"); ReactDom.render(<Hangman />, div); }); test("Reset state", () => { resetButton(setState)(); expect(mockState.mistake).toBe(0); expect(PROGRAMING_LANG).toContain(mockState.answer); }); test("Get current guessed word", () => { mockState.answer = "python"; mockState.guessed = new Set("p"); expect(guessedWord(mockState)).toEqual(["p", "_", "_", "_", "_", "_"]); mockState.answer = "python"; mockState.guessed = new Set("r"); expect(guessedWord(mockState)).toEqual(["_", "_", "_", "_", "_", "_"]); }); test("Get mistake", () => { mockState.answer = "python"; expect(getMistake(mockState, "p")).toBe(0); }); test("Handle guess", () => { let fakeEvt = { target: { value: "r" } }; mockState.guessed = new Set(); mockState.answer = "python"; mockState.mistake = 0; handleGuess(setState, mockState)(fakeEvt); expect(mockState.mistake).toEqual(1); fakeEvt = { target: { value: "p" } }; mockState.guessed = new Set(); mockState.answer = "python"; mockState.mistake = 0; handleGuess(setState, mockState)(fakeEvt); expect(mockState.mistake).toEqual(0); }); test("Get game state", () => { expect(getGameState(true, false, "state")).toBe("YOU WON"); expect(getGameState(false, true, "state")).toBe("YOU LOST"); expect(getGameState(false, false, "state")).toBe("state"); }); test("Get display text", () => { mockState.answer = "python" mockState.guessed = new Set("p"); expect(getDisplayText(true, mockState)).toBe("python"); expect(getDisplayText(false, mockState)).toEqual(["p", "_", "_", "_", "_", "_"]); });
/* EXERCISE 18: Write a small function called "randNum" that takes the parameters of "min" and "max" and returns a random integer from 0 to "max" (inclusive). For example: randNum(0,10) should only return integers between 0 and 10 (including 0 and 10) randNum(10,10) should only return 10 randNum(5,10) should only return integers between 5 and 10 (including 5 and 10) */ function randNum(min,max){ var val = 1; return val; }
(function() { 'use strict' angular .module('reward', [ 'ui.router', 'btford.socket-io', 'customer', 'prize', 'angular-svg-round-progressbar', 'ngToast' ]) })()
module.exports = { parseYaml: require('./yamlParser').parseYaml }
const express = require('express'); const path = require('path'); const routes = require('./routes.js'); const app = express(); const port = process.env.PORT || 8084; const router = express.Router(); const bodyParser = require('body-parser'); const passport = require('./auth/local.js'); var session = require('express-session'); app.set('view engine', 'html'); app.use([bodyParser.json(), bodyParser.urlencoded({ extended: true })]); app.use(express.static(path.join(__dirname, '../client'))); app.use((err, req, res, next) => { console.log(err); res.status(500).send('Server Error'); }); app.use(session({ secret: "this-is-a-secret-key", cookie: { maxAge: null }, resave: false, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); app.use('/api', routes); app.get('/signin/:uniqueorg/:uniquelist/:uniqueevent', (req, res, next) => { res.sendFile(path.join(__dirname, '..', 'client', 'signin.html')); }); router.get('/', (req, res, next) => { res.sendFile(path.join(__dirname, '..', 'client', 'index.html')); }); app.listen(port, (err) => { err ? console.log('Cannot connect...', err) : console.log(`Connected! Server is listening on port ${port}`); });
var pin = require('linchpin') var h = require('snabbdom/h') var { div } = require('hyperscript-helpers')(h) var most = require('most') var { tail } = require('ramda') var { CellStateEnum, CellFlagEnum } = require('minesweeper') module.exports = function (cell) { return div(`#c${cell.x}|${cell.y}.col-xs-1`, cellState(cell)) } most.fromEvent('click', document) .filter(ev => ev.target.classList.contains('col-xs-1')) .map(ev => tail(ev.target.id.split('')).join('').split('|')) .observe(cell => { pin.emit('openCell', cell[0], cell[1]) }) function cellState(cell) { if (cell.state === CellStateEnum.CLOSED) { if (cell.flag === CellFlagEnum.NONE) { return 'X' } else if (cell.flag === CellFlagEnum.EXCLAMATION) { return '!' } else if (cell.flag === CellFlagEnum.QUESTION) { return '?' } } else if (cell.state === CellStateEnum.OPEN) { if (cell.isMine) { return '*' } else { return cell.numAdjacentMines === 0 ? ' ' : cell.numAdjacentMines.toString() } } }
/** * Created by huamin on 2018/4/12. */ //money 类型为string 或 number, 调用:numFormat(10000)或numFormat('10000'); export let numFormat = value => { let m2 = parseFloat(value); if(isNaN(m2)) { return false; } let num = m2 + "" let re = /([0-9]+\.[0-9]{2})[0-9]*/; m2 = num.replace(re, "$1") let money = m2.toString(); let pos_decimal = money.indexOf('.'); if(pos_decimal < 0) { pos_decimal = money.length; money += '.'; } while(money.length <= pos_decimal + 2) { money += '0'; } if(typeof money == "number") money = money.toString(); return money.replace(/^(\d+)((\.\d+)?)$/, function(v1, v2, v3) { return v2.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,') + (v3 || '.00'); }); }
import React from 'react'; import Drawer from 'material-ui/Drawer'; import {List, ListItem} from 'material-ui/List'; import LogoWhite from '../../../static/aLogo.svg'; import PetroTitle from '../../../static/title.svg'; import RoundedLogo from '../../../static/rounded_logo.svg'; import CommentsIcon from 'material-ui/svg-icons/communication/comment'; import PetroIcon from 'material-ui/svg-icons/places/spa'; import IconRight from 'material-ui/svg-icons/hardware/keyboard-arrow-right'; import DashboardIcon from 'material-ui/svg-icons/action/dashboard'; import Classes from 'material-ui/svg-icons/hardware/toys'; import styles from './Sidebar.css.js'; import {Router, Route, browserHistory} from "react-router"; import DrawerStore from '../../stores/DrawerStore'; import actions from '../../actions/actions.js'; import {Link} from "react-router"; import localStorage from 'localStorage'; import Person from './Person'; class Sidebar extends React.Component{ constructor(props, context) { super(props, context); this.state = DrawerStore.getListItemsState(); } componentWillMount(){ DrawerStore.on('app.drawerchanged', this.updateState.bind(this)); DrawerStore.on('app.drawerhovered', this.updateState.bind(this)); DrawerStore.on('app.drawerdehovered', this.updateState.bind(this)); } componentDidMount(){ if(this.props.currentPath.pathname === '/'){ actions.selectMenuItem(0); }else if(this.props.currentPath.pathname === '/classes'){ actions.selectMenuItem(3); }else if(this.props.currentPath.pathname.startsWith('/petroglyphs') && this.props.currentPath.pathname.endsWith('/petroglyphs')){ actions.selectMenuItem(1); }else if(this.props.currentPath.pathname.startsWith('/petroglyphs') && !this.props.currentPath.pathname.endsWith('/petroglyphs')){ actions.selectMenuItem(1); }else{ actions.selectMenuItem(2); } } _onClick(index){ actions.selectMenuItem(index); localStorage.setItem('sidebarIndex', index); } _onMouseEnter(index){ actions.hoverMenuItem(index); } _onMouseLeave(index){ actions.dehoverMenuItem(index); } updateState(){ this.setState(DrawerStore.getListItemsState()); } render(){ return ( <div style={styles.drawer}> <Person /> <List ref = "menu" style={{marginTop:'0px', paddingTop:'0px'}}> <Link to="/" style={{color: 'white', textDecoration:'none'}} activeStyle={{color: 'white'}}> <ListItem primaryText="Dashboard" key={0} style={{backgroundColor:this.state.values[0]!=='' ? this.state.values[0] : '', fontSize:'15px', fontWeight:'500', height:'60px', color:'#FFFFFF'}} innerDivStyle = {{paddingLeft:'65px', paddingTop:'21px'}} leftIcon={<DashboardIcon style={{fill:'#FFFFFF', marginTop:'17px'}}/>} onClick={this._onClick.bind(this, 0)} onMouseEnter={this._onMouseEnter.bind(this,0)} onMouseLeave={this._onMouseLeave.bind(this,0)} /> </Link> <Link to="/petroglyphs" style={{color: 'white', textDecoration:'none'}} activeStyle={{color: 'white'}}> <ListItem primaryText="Petroglyphs" key={1} style={{backgroundColor:this.state.values[1]!=='' ? this.state.values[1] : '', fontSize:'15px', fontWeight:'500', height:'60px', color:'#FFFFFF'}} innerDivStyle = {{paddingLeft:'65px', paddingTop:'21px'}} leftIcon={<PetroIcon style={{fill:'#FFFFFF', marginTop:'17px'}}/>} onClick={this._onClick.bind(this, 1)} onMouseEnter={this._onMouseEnter.bind(this,1)} onMouseLeave={this._onMouseLeave.bind(this,1)} initiallyOpen={true} autoGenerateNestedIndicator={false} /> </Link> <Link to="/comments" style={{color: 'white', textDecoration:'none'}} activeStyle={{color: 'white'}}> <ListItem primaryText="Comments" key={2} style={{backgroundColor:this.state.values[2]!=='' ? this.state.values[2] : '', fontSize:'15px', fontWeight:'500', height:'60px', color:'#FFFFFF'}} innerDivStyle = {{paddingLeft:'65px', paddingTop:'21px'}} leftIcon={<CommentsIcon style={{fill:'#FFFFFF', marginTop:'17px'}}/>} onMouseEnter={this._onMouseEnter.bind(this,2)} onMouseLeave={this._onMouseLeave.bind(this,2)} onClick={this._onClick.bind(this, 2)} initiallyOpen={true} autoGenerateNestedIndicator={false} /> </Link> <Link to="/classes" style={{color: 'white', textDecoration:'none'}} activeStyle={{color: 'white'}}> <ListItem primaryText="Classes" key={3} style={{backgroundColor:this.state.values[3]!=='' ? this.state.values[3] : '', fontSize:'15px', fontWeight:'500', height:'60px', color:'#FFFFFF'}} innerDivStyle = {{paddingLeft:'65px', paddingTop:'21px'}} leftIcon={<Classes style={{fill:'#FFFFFF', marginTop:'17px'}}/>} onMouseEnter={this._onMouseEnter.bind(this,3)} onMouseLeave={this._onMouseLeave.bind(this,3)} onClick={this._onClick.bind(this, 3)} initiallyOpen={true} autoGenerateNestedIndicator={false} /> </Link> </List> </div> ) } } export default Sidebar;
const Singleton_queue = require("../queue_helpers/Singleton"); const Singleton_worker = require("../../worker/Singleton"); const EnqueueTask = require("../task_helpers/EnqueueTask"); const EmitEvent = require("./Emitters"); const invokeWorker = () => { const taskQueue = Singleton_queue.getQueue(); const workerPool = Singleton_worker.getPool(); const task = taskQueue.dequeue; workerPool.executeTask(task, (err, result, task) => { if (err) { if (task.halt < 2 && task.halt >= 0) { task.halt = task.halt++; task.priorityLevel = 10; EnqueueTask(task); } } else if (result) { //TODO: mark the task success in database } EmitEvent("invoke_worker"); }); }; module.exports = { invokeWorker, };
var React = require('react'); var Router = require('react-router'); var Quiz = React.createClass({ render: function(){ return( <div className="main-container"> <div className="row">Question 1</div> <div className="row"> <button type="button" className="btn btn-secondary btn-lg btn-block answer">Option1</button> </div> <div className="row"> <button type="button" className="btn btn-secondary btn-lg btn-block answer">Option2</button> </div> <div className="row"> <button type="button" className="btn btn-secondary btn-lg btn-block answer">Option3</button> </div> <div className="row"> <button type="button" className="btn btn-secondary btn-lg btn-block answer">Option4</button> </div> </div> ) } }); module.exports = Quiz;
let Events = function() { this.funcs = {}; }; Events.prototype = { on: function(name, func) { if (!this.funcs[name]) { this.funcs[name] = []; } this.funcs[name].push(func); }, fire: function(name, evt) { if (this.funcs[name]) { this.funcs[name].forEach(function(f) { f(evt); }); } } }; module.exports = Events;
import Analytics from 'analytics'; import googleAnalytics from '@analytics/google-analytics'; import { getApp } from ".."; let analytics; let isAnalyticsActive = false; if(typeof getApp().analytics != "undefined") { isAnalyticsActive = getApp().analytics.isActive; if(isAnalyticsActive === true) { const googleAnalyticsKey = isAnalyticsActive === true ? getApp().analytics.google_tracking_id : null; const appName = getApp().name; analytics = Analytics({ app: appName, plugins: [ googleAnalytics({ trackingId: googleAnalyticsKey }) ] }); window.Analytics = analytics; } } function analyticsIdentify(user) { if(isAnalyticsActive === true) { analytics.identify(user.id, { name: user.username }); } } function analyticsPage() { if(isAnalyticsActive === true) { analytics.page(); } } export { analyticsIdentify, analyticsPage }
// let a = 2 + 2; // switch (a) { // case 3: // alert( 'Too small' ); // break; // case 4: // alert( 'Exactly!' ); //Alerts 'Exactly' // break; // case 5: // alert( 'Too large' ); // break; // default: // alert( "I don't know such values" ); // } // // Without the breaks, it alerts 'Exactly, Too large and I don't know such values' // // Switch/case argument // let a = "1"; // let b = 0; // switch (+a) { // case b + 1: // alert("this runs, because +a is 1, exactly equals b+1"); // break; // default: // alert("this doesn't run"); // }; // // Grouping of case // let a = 3; // switch (a) { // case 4: // alert('Right!'); // break; // case 3: // (*) grouped two cases // case 5: // alert('Wrong!'); // alert("Why don't you take a math class?"); // break; // default: // alert('The result is strange. Really.'); // } // // Type matters // let arg = prompt("Enter a value?"); // switch (arg) { // case '0': // case '1': // alert( 'One or zero' ); //Runs // break; // case '2': // alert( 'Two' ); //Runs // break; // case 3: // alert( 'Never executes!' ); //Doesn't run because the prompt is a string "3", which is not strictly equal === to the number 3 // alert( 'Never executes!' ); // break; // default: // alert( 'An unknown value' ); // } // Task 1 let browser = prompt('Enter browser type'); if(browser === 'Edge'){ alert("You've got the edge!"); } else if(browser === 'Chrome' || browser === 'Firefox' || browser === 'Safari' || browser === 'Opera'){ alert('Okay we support these browsers too'); } else{ alert('We hope that this page looks ok!'); }; // Task 2 let a = +prompt('a ?', ''); switch(a){ case 0: alert(0); break; case 1: alert(1); break; case 2: case 3: alert('2, 3'); break; };
// @flow import React from 'react'; import { compose } from 'redux'; import SettingsHOC from '../../Settings/HOC'; import SettingsComponent from '../../Settings/components/currentFiatSettings'; const Settings = compose( SettingsHOC, )(SettingsComponent); class SettingsPage extends React.Component<{}>{ render(){ return ( <div> <Settings /> </div> ) } } export default SettingsPage;
import React, { useState, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { getProduct, updateProduct } from "../reducers/productAction"; import { useHistory } from "react-router-dom"; import { useParams } from "react-router-dom"; const EditProduct = () => { let history = useHistory(); const dispatch = useDispatch(); const product = useSelector((state) => state.product.product); const [name, setName] = useState(""); const [description , setdescription ] = useState(""); const [price, setPrice] = useState(""); const [quantity , setQuantity ] = useState(""); const [image , setImage ] = useState(""); useEffect(() => { debugger if (product != null) { setName(product.name); setPrice(product.price); setdescription(product.description); setQuantity(product.quantity); setImage(product.image); } dispatch(getProduct(id)); }, [product]); const onUpdateProduct = (e) => { e.preventDefault(); const update_product = Object.assign(product, { name: name, price : price , description: description, quantity: quantity, image:image, }); dispatch(updateProduct(update_product)); history.push("/product") }; const style = {backgroundColor: '#6200ea', color :" white", marginLeft : "95%",marginTop: "15px" } return ( <div className="card border-0 shadow"> <div className="card-header"> <button style ={style} onClick={() => history.push('/product')} >X</button><h5> Update Product</h5></div> <div className="card-body"> <form onSubmit={(e) => onUpdateProduct(e)}> <div className="form-group"> <input type="text" className="form-control" placeholder="Enter Your Name" value={name} onChange={(e) => setName(e.target.value)} required /> </div> <div className="form-group"> <input type="number" className="form-control" placeholder="Enter Your Price" value={price } onChange={(e) => setPrice(e.target.value)} step="any" required /> </div> <div className="form-group"> <input type="text" className="form-control" placeholder="Enter Description" value={description } onChange={(e) => setdescription (e.target.value)} /> </div> <div className="form-group"> <input type="number" className="form-control" placeholder="Enter Quantity " value={quantity } onChange={(e) => setQuantity(e.target.value)} required /> </div> <div className="form-group"> <input type="file" onChange={(e) => setImage(e.target.value)} /> <img src={image}/> </div> <button className="btn btn-primary" type="submit"> Update Product </button> </form> </div> </div> ); }; export default EditProduct;
// Membuat object // Object patrial const santri1 = { nama : "Bangkit Juang Raharjo", id : "081325507780", email : "juangraharjo03@gmail.com", divisi : "Backend Developer" } const santri2 = { nama : "Rahmat Bagus Latami", id : "088881222345", email : "latami28@gmail.com", divisi : "Backend De veloper" } //Membuat object dengan menggunakan function declaration function buatObjectSantri(nama, id, email, divisi){ const santri = {}; santri.nama = nama; santri.id = id; santri.email = email; santri.divisi = divisi; return santri; } const santri3 = buatObjectSantri('Muhammad Mujahid Muslim', '087776687395362', 'mujahidpondokprogrammer@gmail.com', 'mobile'); //Membuat object menggunakan constructor function Santri(nama, id, email, divisi) { //var this = {}; this.nama = nama; this.id = id; this.email = email; this.divisi = divisi; //return this; } const santri4 = new Santri("Muhammad David Ismail MS", "081225356213434", "davidpondokprogrammer@gmail.com", "Backend");
import axios from "axios"; const cardDiv = document.querySelector(".git-cards"); function getUserInfo(username) { // pulling userdata from the api axios .get(`https://api.github.com/users/${username}`) .then((res) => { // creating a variable to store the userdata recieved inside of const gitUserData = cardCreator(res.data); // appending the userdata inside of the container cardDiv.appendChild(gitUserData); // logging the data recieved to make sure that it is correct console.log(res.data); }) .catch((err) => { // this will catch any errors that occur during the instantiation of the code console.log("Container Doesnt Exist yet"); }); } getUserInfo("belak98"); function cardCreator(obj) { //create elements const userCard = document.createElement("div"); const userImg = document.createElement("div"); const cardInfo = document.createElement("div"); const usersName = document.createElement("h3"); const userName = document.createElement("p"); const location = document.createElement("p"); const userProfile = document.createElement("p"); const profileUrl = document.createElement("a"); const followers = document.createElement("p"); const following = document.createElement("p"); const userBio = document.createElement("p"); //append cardDiv.appendChild(userCard); userCard.appendChild(userImg); userCard.appendChild(cardInfo); userCard.appendChild(usersName); userCard.appendChild(userName); userCard.appendChild(location); userCard.appendChild(userProfile); userProfile.appendChild(profileUrl); userCard.appendChild(followers); userCard.appendChild(following); userCard.appendChild(userBio); //class userCard.classList.add("card"); cardInfo.classList.add("card-info"); usersName.classList.add("name"); userName.classList.add("username"); //content return userCard; } // now that the api client works I can get started on using this in the live webpage.. // make sure you take in everything that you need from git hub make the classes and the UI look good :)
// forms const signUpForm = document.querySelector('#sign-up-form'); const loginForm = document.querySelector('#login-form'); // Sign up inputs const signUpName = document.querySelector('#sign-up-name'); const signUpEmail = document.querySelector('#sign-up-email'); const signUpPassword = document.querySelector('#sign-up-password'); // Login inputs const loginEmail = document.querySelector('#email'); const loginPassword = document.querySelector('#password'); // error messages const errorMsg = document.querySelector('#error'); signUpForm.addEventListener('submit', e => { e.preventDefault(); const signUpDetails = { name: signUpName.value, email: signUpEmail.value, password: signUpPassword.value }; fetch('/api/user/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(signUpDetails) }) .then(res => res.json()) .then(response => { if(response.error) { errorMsg.innerHTML = response.error; } else { console.log(response); errorMsg.innerHTML = ''; localStorage.setItem('auth-token', response.token); location.href = response.redirect; } }); }); loginForm.addEventListener('submit', e => { e.preventDefault(); const loginDetails = { email: loginEmail.value, password: loginPassword.value }; fetch('/api/user/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(loginDetails) }) .then(res => res.json()) .then(response => { if(response.error) { errorMsg.innerHTML = response.error; } else { errorMsg.innerHTML = ''; localStorage.setItem('auth-token', response.token); location.href = response.redirect; } }); });
'use strict'; MetronicApp.controller('TodoController', function($rootScope, $scope, $http, $timeout) { $scope.$on('$viewContentLoaded', function() { Metronic.initAjax(); // initialize core components }); // set sidebar closed and body solid layout mode $rootScope.settings.layout.pageAutoScrollOnLoad = 1500; $rootScope.settings.layout.pageSidebarClosed = true; $rootScope.settings.layout.hasToolbar = true; $rootScope.settings.layout.toolbarHref = '/#/adicionar'; $rootScope.settings.layout.toolbarIcon = 'icon-plus'; });
var express = require('express'); var expressLayouts = require('cloud/express-layouts'); var smartshop = require('cloud/routes/smartshop'); var app = express(); // Configure the app app.set('views', 'cloud/views'); app.set('view engine', 'ejs'); app.use(expressLayouts); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); // Setup your keys here (TODO: replace with dummy values before publicizing) app.locals.parseApplicationId = 'z7QffxJLRKIucW67A7eGrALrp0aOU6i2nwcqC1hU'; app.locals.parseJavascriptKey = 'HRsVePrwUH5a0rTEIE1gbSRmoFtgffCOgjiWrHEP'; // Setup underscore to be available in all templates app.locals._ = require('underscore'); // Define all the endpoints app.get('/',smartshop.home); app.post('/sssignin',smartshop.signin); app.post('/sssignout',smartshop.signout); app.get('/prod', smartshop.listprods); app.get('/prod/new', smartshop.newProd); app.post('/prod/save', smartshop.saveNewProd); app.post('/prod/save/:objectId', smartshop.saveProd); app.get('/prod/:objectId', smartshop.updateProd); app.get('/prod/del/:objectId', smartshop.deleteProd); app.listen();
import DS from 'ember-data'; export default DS.RESTAdapter.extend({ //host: 'http://intuo-backend.herokuapp.com', host: Frontend.SERVICES_HOST, primaryKey: 'id', ajaxError: function(jqXHR) { var error, errors, jsonErrors, response; error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { response = Ember.$.parseJSON(jqXHR.responseText); errors = {}; if (response.errors !== null) { jsonErrors = response.errors; Ember.keys(jsonErrors).forEach(function(key) { errors[Ember.String.camelize(key)] = jsonErrors[key]; return errors[Ember.String.camelize(key)]; }); } return new DS.InvalidError(errors); } else { return error; } alert("AJAX ERROR"); } });
var express = require('express'); var multer = require('multer'); var path = require('path'); const http = require('http'); const url = require('url'); require('dotenv').config() const app = express(); var expressWs = require('express-ws')(app); var apiKey = process.env.API_KEY; app.use(express.static('public')); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'public/uploads') }, filename: function (req, file, cb) { var ext = path.extname(file.originalname); cb(null, Date.now() + ext); } }) var upload = multer({ storage: storage }); app.ws('/socket', function(ws, req) { ws.on('message', function(msg) { console.log(msg); }); console.log('socket', req.testing); }); app.post('/upload', upload.single('upload'), function (req, res, next) { console.log(req.body); if ( ! req.body.api_key || req.body.api_key !== apiKey ) { res.send('bad api key!'); } else { res.send(''); console.log(req.file); var dest = 'uploads/' + req.file.filename; var listeners = expressWs.getWss('/socket'); listeners.clients.forEach(function each(client) { client.send(JSON.stringify({file: dest})); }); } }); app.listen(8888, function () { console.log('Example app listening on port 8888!'); });
import React from 'react'; import Section from './Section'; import type { Education } from './types'; const Edu = ({ list }: { list: Education[] }) => ( <Section title="Education"> <ul className="list--unstyled"> {list.map(({ institution, qualification, yearStart, yearEnd }, i) => ( <li key={i}> <p> <strong>{`${institution} (${yearStart} - ${yearEnd})`}</strong> <br /> <span>{qualification}</span> </p> </li> ))} </ul> </Section> ); export default Edu;
const addActionToRequested = db => db.query( `ALTER TABLE requested ADD COLUMN action INTEGER NOT NULL REFERENCES action(id)` ).catch(e => { // ignore the error when we have already run the migration successfully if (e.message !== 'column "action" of relation "requested" already exists') { throw e } }) module.exports = { addActionToRequested }
//2520 is the smallest number that can be divided by //each of the numbers from 1 to 10 without any remainder. //What is the smallest positive number that is evenly divisible //by all of the numbers from 1 to 20? //function gcd(a, b) { var x = a; var y = b; var result; while (y != 0) { result = x % y; x = y; y = result; } return x; } function lcm(a,b) { return (a * b) / gcd(a, b); } var max = 20; var min = 11; var n = min; for(var i = min; i <= max; i++){ n = lcm(n, i); } console.log(n);
//Importar FS const fs = require('fs'); //constante que contiene la ruta en donde se almacenara el archivo const archivo = './db/data.json'; //Funcion para crear archivo JSON const guardarDB = ( data ) => { //grabar archivo recibiendo como argumento la constante de la URL fs.writeFileSync( archivo, JSON.stringify(data) ); } //Leer archivo JSON const leerDB = () => { if(!fs.existsSync(archivo)){ return null; } const info = fs.readFileSync( archivo, { encoding: 'utf-8' } ); const data = JSON.parse(info); //console.log(data); return data; } module.exports = { guardarDB, leerDB }
function monkeyTrouble(aSmile, bSmile){ if (aSmile && bSmile || !aSmile && !bSmile) { return true; } return false; }
/** * Created by dkroeske on 28/04/2017. */ // API - versie 3 const express = require('express'); const router = express.Router(); const db = require('../db/mssql-connector'); const assert = require('assert'); router.get('/actors/:id?', (req, res, next) => { const actorId = req.params.id || null; if (actorId === null) { var request = new db.Request(); request.query(`SELECT TOP 20 * FROM dbo.actor`, function (err, result) { if (err) { res.status(500).json("An error occured!") return next(err); } else { var data = {}; data["user"] = result.recordset; res.status(200).json(data) } }); } else { var request = new db.Request(); request.query(`SELECT * FROM dbo.actor WHERE actor_id = ${actorId}`, function (err, result) { if (err) { res.status(500).json("An error occured!") return next(err); } else { var data = {}; data["user"] = result.recordset; res.status(200).json(data) } }); } }); //werkt nog niet! -------------------- router.post('/actors', (req, res, next) => { let actor = req.body; assert.equal(typeof (req.body.first_name), 'string', "Argument 'first_name' must be a string."); assert.equal(typeof (req.body.last_name), 'string', "Argument 'last_name' must be a string."); const query = { sql: 'INSERT INTO `actor`(first_name, last_name) VALUES (?, ?)', values: [actor.first_name, actor.last_name ], timeout: 2000 }; console.log('QUERY: ' + query.sql); db.query( query, (error, rows, fields) => { if (error) { res.status(500).json(error.toString()) } else { res.status(200).json(rows) } }) //res.status(200).json('ok') }); module.exports = router;
/*** * * @param {string} text * @return {{}} */ export default function parseCookieString(text) { return text.split(/\s*;\s*/).reduce(function (ac, item) { var tokens = item.split('='); var name = (tokens.shift() || '').trim(); if (!name) return ac; var value = (tokens.shift() || '').trim(); if (!value) value = true; ac[name] = value; return ac; }, {}); }
import API from '@/api'; export const GET_HOSTGROUP = 'GET_HOSTGROUP'; export const GET_HOSTS = 'GET_HOSTS'; export const getHostgroup = data => ({ type: GET_HOSTGROUP, hostGroups: data }); export const getHosts = data => ({ type: GET_HOSTS, hosts: data }); export const fetchHostgroup = () => async (dispatch) => { const { data } = await API.get('/hostgroup'); dispatch(getHostgroup(data)); }; export const fetchHosts = id => async (dispatch) => { const { data } = await API.get(`/hostgroup/${id}`); dispatch(getHosts(data)); };
const express = require('express') const userRouter = require('./user') const app = express() app.use('/user', userRouter) app.get('/', (req, res) => { res.send('hello zhangyuhong3') }) app.listen(9093, function () { console.log('Node app start at port 9093') })
var x=50 console.log(x) /*to print the value of x*/ console.log(typeof x) /*to print the type of x*/ var j=100.45 console.log(j) console.log(typeof j) var str="welcome" /*for string and characters, can use both '' and "" */ console.log(typeof str) console.log("value of x=",x, "type :",typeof x) var b=true console.log(typeof b) var b=false x=100 console.log(x) /*over write the value of x, now x is 100*/ document.write("x=",x,"<p>"+"welcome"+"</p>") /*print the value in html page*/ var z console.log(typeof z) /*uninitialized varibale*/ var obj=null console.log(typeof obj) /*empty object*/ var k var sum=k+x console.log(sum) /*output=NaN means not a number coz k is undefined */ //operators - for adding and concatinating //arithmetic operators var x=10+20; console.log(x) str1="hello" str2="world" str3=str1+str2 console.log(str3) var a=10,b=20,c=30 var sub=b-a console.log(sub) var mul=a*b console.log(mul) var div=a/b console.log(div) var mod=b%a console.log(mod) var x=10**3 console.log(x) x=10 x+=2 console.log(x) //relational operators var a=10,b=20,c=10 console.log(a<=b) // if condition is true then result will be true console.log(a>=b) console.log(a==b) var s="10" ; var k=10 console.log(s==k) //it will check the value of s and k not its type console.log(s===k) //here it will check the type console.log(s!=k) //logical operators console.log(a<b && a==c) // if both side expression are true then the reslut will be true console.log(a>b || a==c) console.log(!(a>b)) //cinditional operators console.log(a<b ? str="hello" : str="world") //conditional stmnts var x=100,y=90.50,z="hi" if(typeof x=="number"){ x+=20 console.log(x) }else if(typeof z=="string"){ str=z+"hello" console.log(str) } else{ console.log(z) }
export const IconMap = { logout: 'fas fa-sign-out-alt', user: 'fas fa-user', manage: 'fas fa-th-list', edit: 'fas fa-edit' };
//global variables const colordivs = document.querySelectorAll(".color"); const generate = document.querySelector(".generate"); const sliders = document.querySelectorAll(".slider"); const currentHexes = document.querySelectorAll(".color h3"); const adjust = document.querySelectorAll(".adjust"); const closeSlider = document.querySelectorAll(".close-slider"); const locks = document.querySelectorAll(".lock"); const saveBtn = document.querySelector(".save"); const closeSavePopup = document.querySelector(".close-save"); const savePopup = document.querySelector(".save-container"); const savepopupBox = savePopup.querySelector(".save-popup"); const libraryBtn = document.querySelector(".library"); const closeLibraryPopup = document.querySelector(".close-library"); const libraryPopup = document.querySelector(".library-container"); const librarypopupBox = libraryPopup.querySelector(".library-popup"); const savePalette = document.querySelector(".submit-save"); const saveInput = document.querySelector(".save-input"); let initialcolor; let savedPalettes = []; //event listeners saveInput.value="" generate.addEventListener("click", () => { randomColor(); }); sliders.forEach((slider) => { slider.addEventListener("input", hslcontrol); }); sliders.forEach((slider, index) => { slider.addEventListener("change", () => { updateTextUi(index); }); // if(sliderinput.value==="hue-input") }); //copy color text currentHexes.forEach((hex) => { hex.addEventListener("click", () => { copyToClipboard(hex); }); }); //sliders adjust adjust.forEach((button, index) => { button.addEventListener("click", () => { sliders[index].classList.add("active"); }); }); //sliders close closeSlider.forEach((close, index) => { close.addEventListener("click", () => { sliders[index].classList.remove("active"); }); }); //lock and unlock locks.forEach((lock, index) => { lock.addEventListener("click", () => { const icon = lock.querySelector("i"); if (icon.classList.contains("fa-lock-open")) { icon.classList.remove("fa-lock-open"); icon.classList.add("fa-lock"); } else { icon.classList.remove("fa-lock"); icon.classList.add("fa-lock-open"); } colordivs[index].classList.toggle("locked"); }); }); //save-popup saveBtn.addEventListener("click", () => { savePopup.classList.add("active"); savepopupBox.classList.add("active"); }); //close-save-popup closeSavePopup.addEventListener("click", () => { savePopup.classList.remove("active"); savepopupBox.classList.remove("active"); }); //Save-Palette savePalette.addEventListener("click", (event) => { const name = saveInput.value; const colors = []; currentHexes.forEach((hex) => { colors.push(hex.innerText); }); //generate object let paletteNumber; const paletteObject =JSON.parse(localStorage.getItem('palettes')); if(paletteObject){ paletteNumber=paletteObject.length } else{ paletteNumber=savedPalettes.length } const paletteObj = { name, colors, nr: paletteNumber }; savedPalettes.push(paletteObj); //save to Local Storage savetoLocal(paletteObj) saveInput.value="" //generate palette for library const palette=document.createElement("div") palette.classList.add("custom-palette") const title=document.createElement("h4") title.innerText= paletteObj.name const preview= document.createElement('div') preview.classList.add("small-preview") paletteObj.colors.forEach(smallColor=>{ const smallDiv= document.createElement("div") smallDiv.style.backgroundColor= smallColor preview.appendChild(smallDiv) }) const paletteBtn= document.createElement("button") paletteBtn.classList.add("pick-palette-btn") paletteBtn.classList.add(paletteObj.nr) paletteBtn.innerText="Select" //attach event to btn paletteBtn.addEventListener("click",e=>{ closeLibrary(); const paletteIndex= e.target.classList[1]; console.log(paletteIndex); initialcolor=[] console.log(savedPalettes); savedPalettes[paletteIndex].colors.forEach((color,index)=>{ initialcolor.push(color) colordivs[index].style.backgroundColor=color; const text=colordivs[index].children[0] text.innerText=color; updateTextUi(index); }) reset(); }) //append to library palette.appendChild(title) palette.appendChild(preview) palette.appendChild(paletteBtn) librarypopupBox.appendChild(palette) }); //library-popup libraryBtn.addEventListener("click", (event) => { libraryPopup.classList.add("active"); librarypopupBox.classList.add("active"); }); //close-library-popup closeLibraryPopup.addEventListener("click",closeLibrary); //functions function generatehex() { const hash = chroma.random(); // const allvar= "0123456789ABCDEF"; // let hash="#"; // for (let i=0;i<6;i++){ // hash+=allvar[Math.floor(Math.random()*15)]; // } return hash; } //set colors function randomColor() { initialcolor = []; colordivs.forEach((div, index) => { const hexhead = div.children[0]; const adjust = div.querySelector(".adjust"); const lock = div.querySelector(".lock"); const randcol = generatehex(); if (div.classList.contains("locked")) { initialcolor.push(hexhead.innerText); return; } else { initialcolor.push(chroma(randcol).hex()); } div.style.background = randcol; hexhead.innerText = randcol; //hexhead color textColor(randcol, hexhead); textColor(randcol, adjust); textColor(randcol, lock); //slider color const slider = div.querySelectorAll(".slider input"); const hue = slider[0]; const brightness = slider[1]; const saturation = slider[2]; const col = chroma(randcol); sliderColor(col, hue, brightness, saturation); //sliderValue hue.value = Math.floor(chroma(randcol).hsl()[0]); brightness.value = Math.floor(chroma(randcol).hsl()[2] * 100) / 100; saturation.value = Math.floor(chroma(randcol).hsl()[1] * 100) / 100; }); } //textcontrast function textColor(color, hexhead) { const luminance = chroma(color).luminance(); if (luminance > 0.5) { hexhead.style.color = "black"; } else { hexhead.style.color = "white"; } } //slider color function sliderColor(color, hue, brightness, saturation) { const lowsat = color.set("hsl.s", 0); const highsat = color.set("hsl.s", 1); const midbright = color.set("hsl.l", 0.5); const scaleSat = chroma.scale([lowsat, color, highsat]); const scaleBright = chroma.scale(["black", midbright, "white"]); saturation.style.backgroundImage = `linear-gradient(to right,${scaleSat( 0 )},${scaleSat(1)})`; brightness.style.backgroundImage = `linear-gradient(to right,${scaleBright( 0 )},${scaleBright(0.5)},${scaleBright(1)})`; hue.style.backgroundImage = `linear-gradient(to right, rgb(255, 0, 0), rgb(255, 125, 0), rgb(255, 255, 0), rgb(125, 255, 0), rgb(0, 255, 0), rgb(0, 255, 125), rgb(0, 255, 255), rgb(0, 125, 255), rgb(0, 0, 255)) `; } function hslcontrol(event) { const index = event.target.getAttribute("data-bright") || event.target.getAttribute("data-sat") || event.target.getAttribute("data-hue"); let sliders = event.target.parentElement.querySelectorAll( 'input[type="range"]' ); const hue = sliders[0]; const brightness = sliders[1]; const saturation = sliders[2]; const bgcolor = initialcolor[index]; let colory = chroma(bgcolor) .set("hsl.s", saturation.value) .set("hsl.l", brightness.value) .set("hsl.h", hue.value); colordivs[index].style.backgroundColor = colory; sliderColor(colory, hue, brightness, saturation); } function updateTextUi(index) { const activeDiv = colordivs[index]; const color = chroma(activeDiv.style.backgroundColor); const headtext = activeDiv.querySelector("h3"); const adjust = activeDiv.querySelector(".adjust"); const lock = activeDiv.querySelector(".lock"); headtext.innerText = color.hex(); textColor(color, headtext); textColor(color, adjust); textColor(color, lock); } randomColor(); //copy color text function function copyToClipboard(hex) { const temp = document.createElement("textarea"); document.body.appendChild(temp); temp.innerText = hex.innerText; temp.select(); document.execCommand("copy"); document.body.removeChild(temp); //popup-animation const popup = document.querySelector(".copy-container"); const popupBox = popup.querySelector(".copy-popup"); popup.classList.add("active"); popupBox.classList.add("active"); popup.addEventListener("transitionend", () => { popup.classList.remove("active"); popupBox.classList.remove("active"); }); } //save to local storage function savetoLocal(paletteObj){ let localPalettes; if(localStorage.getItem("palettes")===null){ localPalettes=[]; } else{ localPalettes=JSON.parse(localStorage.getItem('palettes')) } localPalettes.push(paletteObj) localStorage.setItem("palettes",JSON.stringify(localPalettes)) } //get from local storage function getLocal(){ if(localStorage.getItem("palettes")===null){ localPalettes=[]; } else{ const paletteObject =JSON.parse(localStorage.getItem('palettes')); savedPalettes = [...paletteObject]; paletteObject.forEach(paletteObj=>{ const palette=document.createElement("div") palette.classList.add("custom-palette") const title=document.createElement("h4") title.innerText= paletteObj.name const preview= document.createElement('div') preview.classList.add("small-preview") paletteObj.colors.forEach(smallColor=>{ const smallDiv= document.createElement("div") smallDiv.style.backgroundColor= smallColor preview.appendChild(smallDiv) }) const paletteBtn= document.createElement("button") paletteBtn.classList.add("pick-palette-btn") paletteBtn.classList.add(paletteObj.nr) paletteBtn.innerText="Select" //attach event to btn paletteBtn.addEventListener("click",e=>{ closeLibrary(); const paletteIndex= e.target.classList[1]; initialcolor=[] paletteObj.colors.forEach((color,index)=>{ initialcolor.push(color) colordivs[index].style.backgroundColor=color; const text=colordivs[index].children[0] text.innerText=color; updateTextUi(index); }) reset(); }) //append to library palette.appendChild(title) palette.appendChild(preview) palette.appendChild(paletteBtn) librarypopupBox.appendChild(palette) }) } } function closeLibrary(){ libraryPopup.classList.remove("active"); librarypopupBox.classList.remove("active"); } function reset(){ colordivs.forEach((div, index) => { const slider = div.querySelectorAll(".slider input"); const hue = slider[0]; const brightness = slider[1]; const saturation = slider[2]; // console.log(initialcolor[index]); const col = chroma(initialcolor[index]); sliderColor(col, hue, brightness, saturation); // //sliderValue hue.value = Math.floor(chroma(initialcolor[index]).hsl()[0]); brightness.value = Math.floor(chroma(initialcolor[index]).hsl()[2] * 100) / 100; saturation.value = Math.floor(chroma(initialcolor[index]).hsl()[1] * 100) / 100; }) } getLocal(); // localStorage.clear();s
const Category = require('../controller/categoryController'); module.exports = { Query: { categories: async (parent, args, req) => { const categories = Category.find({}); if(categories !== undefined){ return categories; } return null; } }, Mutation: { addCategory: async (parent, args, req) => { return Category.addCategory(args); } } }
var React=require('react'); var DisplayEmp=require('./DisplayEmp'); var Display=React.createClass({ var msg= this.props.display.map(function(l){ render:function(){ //console.log(this.props.p2); var msg= this.props.adata.map(function(e){ return( <DisplayEmp wave={e.wave} name={e.name} email={e.email} phno={e.phno} giturl={e.giturl} empcode={e.empcode} empdesig={e.empdesig} edept={e.empdept} skills={e.skills} exp={e.exp} ></DisplayEmp> ); }); return( <div> {msg} </div> ); } }); module.exports=Display;
require('dotenv').config(); const mongoose = require('mongoose'); const { initApp } = require('./init-app.js'); const { MONGODB_URI } = process.env; async function connectDb(mongoUrl) { return mongoose.connect(mongoUrl, { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true }); } async function createApp() { const { connection: mongooseConnection } = await connectDb(MONGODB_URI); console.log(`... mongo connection established ...`); const app = await initApp({ mongooseConnection }); console.log('... app created ...'); return app; } module.exports = { createApp, };
import React from 'react'; import { connect } from 'react-redux'; import { Form, Input, Button, Select, InputNumber } from 'antd'; import { fetchMetrics } from '../../store/reducers/template/actions'; import API from '@/api'; const { Item } = Form; const { Option } = Select; class StrategyForm extends React.Component { componentDidMount() { const { metrics, dispatch } = this.props; if (!metrics) { dispatch(fetchMetrics()); } } saveStrategy = () => { this.props.form.validateFields(async (err, values) => { if (!err) { const { id } = this.props.strategy; const { max_step } = values; const method = id ? 'put' : 'post'; const tpl_id = id ? undefined : parseInt(this.props.tpl, 10); await API[method]('/strategy', { tpl_id, id, ...values, max_step }); this.props.getTemplate(); } }); } render() { const { strategy, metrics = [] } = this.props; const { getFieldDecorator } = this.props.form; return ( <> <Form layout="inline"> <Item label="metric"> { getFieldDecorator('metric', { initialValue: strategy.metric, rules: [{ required: true }] })( <Select showSearch style={{ width: 200 }} filterOption={(input, option) => ( option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 )} > { metrics.map(metric => <Option value={metric} key={metric}>{metric}</Option>) } </Select> ) } </Item> <Item label="tags"> { getFieldDecorator('tags', { initialValue: strategy.tags })( <Input /> ) } </Item> <Item label="Max"> { getFieldDecorator('max_step', { initialValue: strategy.max_step, rules: [{ required: true }] })( <InputNumber /> ) } </Item> <Item label="Priority"> { getFieldDecorator('priority', { initialValue: strategy.priority, rules: [{ required: true }] })( <InputNumber /> ) } </Item> <Item label="Note"> { getFieldDecorator('note', { initialValue: strategy.note })( <Input /> ) } </Item> <Item label="if"> { getFieldDecorator('func', { initialValue: strategy.func, rules: [{ required: true }] })( <Input /> ) } </Item> <Item> { getFieldDecorator('op', { initialValue: strategy.op, rules: [{ required: true }] })( <Select style={{ width: 50 }}> { ['==', '!=', '<', '<=', '>', '>='].map(op => <Option key={op} value={op}>{op}</Option>) } </Select> ) } </Item> <Item> { getFieldDecorator('right_value', { initialValue: strategy.right_value, rules: [{ required: true }] })( <Input /> ) } </Item> <Item label=": alarm(); callback();" /> <Item label="run begin(e.g. 00:00)"> { getFieldDecorator('run_begin', { initialValue: strategy.run_begin })( <Input /> ) } </Item> <Item label="run end(e.g. 24:00)"> { getFieldDecorator('run_end', { initialValue: strategy.run_end })( <Input /> ) } </Item> <Item> <Button type="primary" onClick={this.saveStrategy}>Save</Button> </Item> </Form> </> ); } } const mapStateToProps = ({ template }) => { const { metrics } = template; return { metrics }; }; export default Form.create()(connect(mapStateToProps)(StrategyForm));
var _viewer = this; var ctlgShare = _viewer.getItem("CTLG_SHARE"); //模块CTLG_MODULE赋值 if(_viewer.getItem("CTLG_MODULE").getValue() == "") { if(_viewer.getParHandler()){ _viewer.getItem("CTLG_MODULE").setValue(_viewer.getParHandler().getParams().CTLG_MODULE); } else { _viewer.getItem("CTLG_MODULE").setValue(_viewer.getParams().CTLG_MODULE); } } var pcode = _viewer.getItem("CTLG_PCODE").getValue(); var pcodeH = _viewer.getItem("CTLG_PCODE_H").getValue(); var module = _viewer.getItem("CTLG_MODULE").getValue(); if(pcode == '' && pcodeH.length > 0 && module.length > 0) { pcode = pcodeH.replace(module+"-",""); _viewer.getItem("CTLG_PCODE").setValue(pcode); } if(_viewer.getItem("CTLG_MODULE").getValue() == ""){ alert("目录所属模块为空,请重新打开!"); } else if(_viewer.getItem("CTLG_PCODE").getValue() == ""){ alert("上级目录为空,请重新打开!"); } //编辑时 目录编码只读 if (_viewer.getItem("CTLG_CODE").getValue().length > 0) { _viewer.getItem("CTLG_CODE").disabled(); } //选中当前模块 ctlgShare._obj.find(":checkbox").each(function() { var opt = jQuery(this); if (_viewer.getItem("CTLG_MODULE").getValue() == opt.val()) { opt.attr("checked","true"); } }); //已选中模块 只读 ctlgShare.getCheckedCheckbox().each(function() { $(this).attr("disabled","disabled"); }); //保存后刷新 _viewer.afterSave = function(){ // var where = " AND CTLG_MODULE = '"+ module +"'"; // _viewer.getParHandler().refreshTreeGrid(where,where); _viewer.refresh(); };
/******************** VARIABLE DECLARATION *********************/ // constants var LIST_LEFT; var USER_LANG = navigator.language || navigator.userLanguage; var ID_SCROLL_PREV = 'box_prev'; var ID_SCROLL_NEXT = 'box_next'; var ID_DAYLIST = 'box-daylist'; var ID_VIEWPORT = 'layer_viewport'; var ID_NEEDLE = 'obj_needle'; var FRAMERATE = 1000/50; var HOVERSPEED = 20; var ACC_T_INCREASE = 30; var ACC_T_ZERO = 20; var ACC_T_DECREASE = 10; // control variables var listSpeed; var v0 = 0; var acc = 0; var acc_t_count = 0; // object var daylist = document.createElement('div'); daylist.id = ID_DAYLIST; daylist.classList.add('container-daylist'); var viewport = document.createElement('div'); viewport.id = ID_VIEWPORT; viewport.classList.add('container-viewport'); var dayBox = []; var stitchBox = []; var stitch = []; // decorative objects var dimLeft = document.createElement('div'); dimLeft.classList.add('container-left'); var dimRight = document.createElement('div'); dimRight.classList.add('container-right'); var scrollBoxPrev = document.createElement('div'); scrollBoxPrev.setAttribute('id', ID_SCROLL_PREV); scrollBoxPrev.classList.add('container-scroll-prev'); var scrollBoxNext = document.createElement('div'); scrollBoxNext.setAttribute('id', ID_SCROLL_NEXT); scrollBoxNext.classList.add('container-scroll-next'); var needleBox = document.createElement('div'); needleBox.classList.add('container-needle'); var needleImage = document.createElement('object'); needleImage.setAttribute('id', ID_NEEDLE); needleImage.setAttribute('data', 'assets/needle.svg'); needleImage.setAttribute('type', 'image/svg+xml'); needleImage.classList.add('img-needle'); if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) { // some code.. alert('mobile browser!'); } /************** READ JSON FILE ***************/ localStorage.clear(); var sheetIndex = ["date", "day", "type", "instensity", "duration", "hue", "saturation", "level", "note", "redundant"]; var tempStr; var jsonData = []; var url_parameter = "https://spreadsheets.google.com/pub?key=1IqZWY3edz2fGNT8O3uciprX6oElkLu8Vm8-i33CMNyk&hl=kr&output=html"; var googleSpreadsheet = new GoogleSpreadsheet(); googleSpreadsheet.url(url_parameter); googleSpreadsheet.load(function(result) { for(i = 0; i < result.data.length; i++){ var x = Math.round((i/sheetIndex.length - Math.trunc(i/sheetIndex.length))*sheetIndex.length); if(x == 0){ tempStr = '{"'+sheetIndex[x]+'": "'+result.data[i]; } else if(x == sheetIndex.length - 1){ tempStr += '", "'+sheetIndex[x]+'": "'+result.data[i]+'"}'; jsonData.push(JSON.parse(tempStr)); } else{ tempStr += '", "'+sheetIndex[x]+'": "'+result.data[i]; } } putDynamicComps(); putStaticComps(); }); function putDynamicComps(){ var todayIndex = 0; for(i = 1; (i < jsonData.length)&&(Date.parse(jsonData[i].date) < Date.now()); i++){ todayIndex++; } for(i = 1; i < todayIndex+1; i++){ dayBox.push(document.createElement('div')); stitchBox.push(document.createElement('div')); stitch.push(document.createElement('div')); stitchBox[i-1].classList.add('container-stitch'); stitch[i-1].classList.add('fill-stitch'); stitch[i-1].style.background = 'hsl('+jsonData[i].hue+', '+jsonData[i].saturation+'%, '+jsonData[i].level+'%)'; stitchBox[i-1].appendChild(stitch[i-1]); dayBox[i-1].classList.add('container-day'); dayBox[i-1].appendChild(stitchBox[i-1]); daylist.appendChild(dayBox[i-1]); if(i == todayIndex){ dayBox.push(document.createElement('div')); needleBox.appendChild(needleImage); dayBox[i].appendChild(needleBox); dayBox[i].classList.add('container-day'); daylist.appendChild(dayBox[i]); } } viewport.appendChild(daylist); document.getElementsByClassName('container-body')[0].appendChild(viewport); LIST_LEFT = daylist.getBoundingClientRect().left; var eventRepeater = setInterval(function(){moveX(daylist)}, FRAMERATE); } function putStaticComps(){ document.getElementsByClassName('container-body')[0].appendChild(dimLeft); document.getElementsByClassName('container-body')[0].appendChild(dimRight); document.getElementsByClassName('container-body')[0].appendChild(scrollBoxPrev); document.getElementsByClassName('container-body')[0].appendChild(scrollBoxNext); } /****************** * DYNAMIC CONTROLS ******************/ document.getElementsByClassName('container-body')[0].onresize = function(){ LIST_LEFT = daylist.getBoundingClientRect().left; }; scrollBoxPrev.onmousemove = function(e){ var w = this.getBoundingClientRect().width; var mX = e.clientX; var d = w - mX; v0 = HOVERSPEED*d/w; }; scrollBoxPrev.onmouseout = function(e){ v0 = 0; }; scrollBoxNext.onmousemove = function(e){ var w = this.getBoundingClientRect().width; var mX = e.clientX; var d = window.innerWidth - w - mX; v0 = HOVERSPEED*d/w; }; scrollBoxNext.onmouseout = function(e){ v0 = 0; }; document.onwheel = function(e){ acc = (-0.2)*e.deltaY; acc_t_count = ACC_T_INCREASE; } //////////////////////////////////////////////////////////////////////////////// /*********** * FUNCTIONS ***********/ function moveX(obj){ var x0 = obj.getBoundingClientRect().left; var x = x0 + v0 + vAcc(); if(x > 0){ x = 0; } else if(x < LIST_LEFT){ x = LIST_LEFT; } else{ //do nothing } setX(obj, x); } function vAcc(){ var vA; if(acc_t_count > ACC_T_ZERO){ vA = acc*(ACC_T_INCREASE - acc_t_count)/(ACC_T_INCREASE - ACC_T_ZERO)/2; acc_t_count--; } else if(acc_t_count > ACC_T_DECREASE){ vA = acc; acc_t_count--; } else if(acc_t_count > 0){ vA = acc -acc*(ACC_T_DECREASE - acc_t_count)/(ACC_T_ZERO - ACC_T_DECREASE)/2; acc_t_count--; } else{ //do nothing vA = 0; acc = 0; } return vA; } function setX(obj, x){ obj.style.left = x + "px"; }
import React from 'react'; import { Button, View, Text, AsyncStorage } from 'react-native'; import { ListItem } from 'react-native-elements'; export default class Lista extends React.Component { constructor(props) { super(props); try { AsyncStorage.getItem('dados').then(value => { global.dados = JSON.parse(value) || []; }); } catch (e) { console.error('falha ao ler dados'); } } willFocus = this.props.navigation.addListener('willFocus', payload => { this.forceUpdate(); }); render() { return ( <View> <Text>Lista2</Text> {global.dados.map((l, i) => ( <Text> {l.nome} - {l.telefone} </Text> ))} <Button title="novo" onPress={() => this.props.navigation.navigate('Formulario')} /> </View> ); } }
window.onload = function(){ function accodianInit(accodianDiv){ var liElements = accodianDiv.querySelectorAll('.title_section'); function showPanel(titleItem){ (accodianDiv.querySelector('.is_active')) && accodianDiv.querySelector('.is_active').classList.remove('is_active'); titleItem.classList.add('is_active'); } function sendEvent(event){ showPanel(event.currentTarget); } for(var i=0,len=liElements.length; i<len; i++){ liElements[i].addEventListener('click', sendEvent); } showPanel(liElements[0]); } accodianInit(document.querySelector('.accordion')); }
var BTVPlatform = new function () { var callback_2; /** * 구매 비밀번호 체크 * @param {int} inputPwd 입력한 비밀 번호 * @param {function} callback 비밀번호 체크 결과를 리턴 받을 콜백 함수 * @returns {Boolean} */ this.checkPurchasePin = function (inputPwd, callback) { if (!callback) { HLog.err("checkPurchasePin Error - callback is undefined"); callback({isError : true}); return; } var checkPIN = function () { try { callback_2 = callback; android.getCheckPurchasePin(inputPwd); } catch (e) { console.error("checkPin Error 1 >> " + e); callback({isError:true, e:e}); } }; checkPIN(); }; this.getPurchaseCallback = function(response) { console.error("getPurchaseCallback parse >> " + JSON.parse(response)); console.error("getPurchaseCallback stringify >> " + JSON.stringify(response)); if (response == null || response == "undefined") { callback_2({isError:false}); } else { callback_2({isError:false, result:JSON.parse(response)}); } } };
/** * * @param {*} graph */ var shortestPathLength = function(graph) { const N = graph.length; // 动态规划 // 广搜 // 如果指定了起点结束点 直接广搜解决 // 初始化 const L = []; for (const i = 0; i < N; i++) { gI.foreach(j => { l[i][j] = 1; }); } for () { } }; const graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]; shortestPathLength(graph); if ( ((rect.bottom >= 0 - preload && rect.bottom <= window.screen.height + preload) || (rect.top >= 0 - preload && rect.top <= window.screen.height + preload)) && ((rect.right >=0 && rect.right <= window.screen.width) || (rect.left >=0 && rect.left <= window.screen.width)) ) { }
describe('Transformation', function() { it('can do an identity transform', function() { var t = new MM.Transformation(1, 0, 0, 0, 1, 0); var p = new MM.Point(1, 1); var p_ = t.transform(p); var p__ = t.untransform(p_); expect(p).toEqual(new MM.Point(1, 1)); expect(p_).toEqual(new MM.Point(1, 1)); expect(p__).toEqual(new MM.Point(1, 1)); }); it('can do an inverse transform', function() { var t = new MM.Transformation(0, 1, 0, 1, 0, 0); var p = new MM.Point(0, 1); var p_ = t.transform(p); var p__ = t.untransform(p_); expect(p).toEqual(new MM.Point(0, 1)); expect(p_).toEqual(new MM.Point(1, 0)); expect(p__).toEqual(new MM.Point(0, 1)); }); it('can do an addition transform', function() { var t = new MM.Transformation(1, 0, 1, 0, 1, 1); var p = new MM.Point(0, 0); var p_ = t.transform(p); var p__ = t.untransform(p_); expect(p).toEqual(new MM.Point(0, 0)); expect(p_).toEqual(new MM.Point(1, 1)); expect(p__).toEqual(new MM.Point(0, 0)); }); });
define(function (require) { var slider = require('slide'); var a = new slider('#box-outer',{ }); console.log(a); });
const conexionMysql = require("../../DB/conexionMysql"); /** * Cancela la reserva de cierta experiencia 👍 * @param {} req * @param {*} res * @param {*} next */ async function cancelarExperiencia(req, res, next) { let conexion; try { conexion = await conexionMysql(); const idExperiencia = req.params.id; const idUsuario = req.userAuth.id; await existeReserva(conexion, idUsuario, idExperiencia); await cancelarReserva(conexion, idUsuario, idExperiencia) res.send({ status: 'Ok', data: 'reserva cancelada' }); } catch (err) { next(err) } finally { if (conexion) conexion.release(); } } /** * Comprueba si ya existe la reserva. * @param {Object} conexion * @param {number} idUsuario * @param {number} idExperiencia */ async function existeReserva(conexion, idUsuario, idExperiencia) { const [data] = await conexion.query( ` SELECT id FROM reservas WHERE id_experiencia=? AND id_usuario=? AND cancelada=false `, [idExperiencia, idUsuario] ); if (data.length === 0) { const error = new Error('Reserva no encontrada'); error.httpStatus = 404; throw error; } } /** * Actualiza la el regitro pertinente de la tabla reservas. * @param {Object} conexion * @param {number} idUsuario * @param {number} idExperiencia */ async function cancelarReserva(conexion, idUsuario, idExperiencia) { await conexion.query( ` UPDATE reservas SET cancelada=true WHERE id_usuario=? AND id_experiencia=? `, [idUsuario, idExperiencia] ); } module.exports = cancelarExperiencia;
export const WitnessHTML = (witnessObj) => { return ` <section class="witness card"> <div class="witness__name"> Name: ${witnessObj.name}</div> <div class="witness__statement"> Statement ${witnessObj.statements}</div> </section> ` }
var txtintro = "Press enter!"; function intro() { document.getElementById('suite').style.display = 'none' display = document.getElementById('intro'); for(var i = 0, l = txtintro.length; i < l; i++) { (function(i) { setTimeout(function() { display.innerHTML += txtintro.charAt(i); }, i * 200); }(i)); } } document.querySelector('body').addEventListener('keypress', function (e) { var key = e.which || e.keyCode; if (key === 13) { var question = prompt("Checking humanity. Please answer this : \n 3+3 ="); if(question == 6){ document.getElementById('intro').style.display = 'none'; document.getElementById('suite').style.display = 'block'; } else alert('Intruders !!'); } });
import React, { Component } from 'react'; import Background from './Background' import Loading from './Loading' import LandingPage from './LandingPage' import Transition from './Transition' import Question1 from './question/Question_1' import Question2 from './question/Question_2' import Question3 from './question/Question_3' import Question4 from './question/Question_4' import Result from './Result' import axios from 'axios'; import qs from 'qs'; import wx from "weixin-jsapi"; // import Audio from '../components/Audio' import './Index.scss' class Index extends Component { state = { step: 0, answer: 1, scrren:false, userInfo: { // headimgurl: "http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eq4gq4FGJsRQg7u7KKf6aqzcLoNickuowTGcQr52z2jfTtnJQCyYibwNjLhoiaA1qUvPpHBmtI0xwJCg/132", // nickname: "PandaQ" } } componentDidMount() { let data = qs.parse(window.location.href.split('?')[1]); const { code } = data const self = this; console.log('code',code) if (code) { axios.get(`https://cocostar.com.cn/kaltendin/api/users?code=${code}`).then((res = {}) => { const { code, data } = res.data console.log('res',res) if (res.data.code === 0) { this.setState({ userInfo: data }) } else { window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4e31314f63c6e1be&redirect_uri=https%3A%2F%2Fcocostar.com.cn%2Fkaltendin%2Fexploratory_testing%2F&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect' } }); this.initWechat() } else { // 开发调试时可屏蔽 window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4e31314f63c6e1be&redirect_uri=https%3A%2F%2Fcocostar.com.cn%2Fkaltendin%2Fexploratory_testing%2F&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect' } window.addEventListener('orientationchange', function(event){ if ( window.orientation == 180 || window.orientation==0 ) { self.setState({scrren:false}) } if( window.orientation == 90 || window.orientation == -90 ) { self.setState({scrren:true}) } }); //事件上报 window.MtaH5 && window.MtaH5.clickStat('ceshi-10',{'page1':'true'}) } initWechat = () => { axios.post(`https://cocostar.com.cn/kaltendin/api/users/jsconfig`,{ jsApiList: ["updateAppMessageShareData","updateTimelineShareData","onMenuShareAppMessage","onMenuShareTimeline"], url: window.location.href.split("#")[0], debug: false }).then(({data})=>{ if(data.code === 0) { wx.config({ debug: false, appId: data.data.appId, timestamp: data.data.timestamp, nonceStr: data.data.nonceStr, signature: data.data.signature, jsApiList: ["updateAppMessageShareData","updateTimelineShareData","onMenuShareAppMessage","onMenuShareTimeline"] }); wx.ready(function () { //需在用户可能点击分享按钮前就先调用 // wx.updateAppMessageShareData({ // title: '探索你的潜能', // 分享标题 // desc: '探索你的潜能', // 分享描述 // link: 'https://cocostar.com.cn/kaltendin/exploratory_testing/', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 // imgUrl: 'https://cocostar.com.cn/kaltendin/exploratory_testing/share.jpg', // 分享图标 // success: function () { // // 设置成功 // } // }) // wx.updateTimelineShareData({ // title: '探索你的潜能', // 分享标题 // link: 'https://cocostar.com.cn/kaltendin/exploratory_testing/', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 // imgUrl: 'https://cocostar.com.cn/kaltendin/exploratory_testing/share.jpg', // 分享图标 // success: function () { // // 设置成功 // } // }) wx.onMenuShareAppMessage({ title: '这有一张票送你去宇宙外太空,探索你的潜能', // 分享标题 desc: '恭喜您正在登陆X星球,前方高能…', // 分享描述 link: 'https://cocostar.com.cn/kaltendin/exploratory_testing/', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: 'https://cocostar.com.cn/kaltendin/exploratory_testing/share.jpg', // 分享图标 success: function () { // 用户点击了分享后执行的回调函数 } }) wx.onMenuShareTimeline({ title: '这有一张票送你去宇宙外太空,探索你的潜能', // 分享标题 link: 'https://cocostar.com.cn/kaltendin/exploratory_testing/', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: 'https://cocostar.com.cn/kaltendin/exploratory_testing/share.jpg', // 分享图标 success: function () { // 用户点击了分享后执行的回调函数 } }) }); } }) } onPageChange = (data) => { const { step } = this.state switch (data.step) { case 0: this.setState({ step: step + 1 }) break; case 1: this.setState({ step: step + 1 }) break; case 2: this.setState({ step: step + 1 }) break; case 3: this.setState({ step: step + 1 }) break; case 4: this.setState({ step: step + 1 }) break; case 5: this.setState({ step: step + 1, answer: data.value }) break; case 6: this.setState({ step: step + 1 }) break; case 7: this.setState({ step: step + 1 }) break; default: break; } } render() { const { step, answer, userInfo,scrren } = this.state; return <div className='main'> <Background step={step} /> <div className='main-page' style={{ opacity: step === 0 ? 1 : 0 }}> <Loading step={0} currentStep={step} callback={this.onPageChange} /> </div> <div className='main-page' style={{ opacity: step === 1 ? 1 : 0 }}> <LandingPage step={1} currentStep={step} callback={this.onPageChange} /> </div> {step === 2 && <Transition step={2} callback={this.onPageChange} />} {/* <div className='main-page' style={{ opacity: step === 3 ? 1 : 0 }}> <Question1 step={3} callback={this.onPageChange} /> </div> */} {step === 3 && <Question1 step={3} callback={this.onPageChange} />} {step === 4 && <Question2 step={4} callback={this.onPageChange} />} {step === 5 && <Question3 step={5} callback={this.onPageChange} />} {step === 6 && <Question4 step={6} callback={this.onPageChange} />} {step === 7 && <Result step={7} answer={answer} userInfo={userInfo} callback={this.onPageChange} />} {/* {step === 8 && <Result step={8} callback={this.onPageChange} />} */} {/* {step !== 0 && <Audio/>} */} { scrren && <div className='tips'> <img src={require('../images/change.jpg')}/> </div> } </div> } } export default Index
import Artboard from './Artboard' import dndWrapper from './dndWrapper' import connector from './connector' import './styles.scss' export default connector(dndWrapper(Artboard))
import React from 'react' import { View, StyleSheet } from 'react-native' import { Text } from 'react-native-elements' import { BarIndicator as LoadingAnimation } from 'react-native-indicators' import { COLORS } from '../style/theme.style' import { getLoadingPhrase } from './lib/helper' import { commonStyles as common } from '../style/common.style' const Loading = props => ( <View style={styles.loadingContainer}> <View style={styles.loadingContainer}> <Text style={{ ...common.regularText }} > {getLoadingPhrase()} </Text> <LoadingAnimation color={props.color} /> </View> </View> ) const styles = StyleSheet.create({ loadingContainer: { flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', backgroundColor: COLORS.BLACK } }) export default Loading
/* FreeBSD License --------------- Copyright 2011 Maarten Mortier. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of <copyright holder>. */ MMUTest = TestCase("MMUTest"); /* Reset. */ MMUTest.prototype.setUp = function() { console.log("Setting up MMUTest."); this.mmu = new MMU(); } MMUTest.prototype.tearDown = function() { console.log("Tear down MMUTest."); } /* MMUTest.prototype.testReset = function() { this.mmu.reset(); test = function(region, expected_length) { assertNotNull(region); assertEquals(expected_length, region.length); for(i = 0; i < region.length; i++) assertEquals(region[i], 0); } test(this.mmu.kernel, 0x10000); test(this.mmu.user, 0x1f0000); test(this.mmu.port, 0x10000); test(this.mmu.scratch, 0x400); test(this.mmu.reg, 0x2000); test(this.mmu.mirror1, 0x200000); test(this.mmu.mirror2, 0x200000); test(this.mmu.bios, 0x80000); } */ MMUTest.prototype.testMappingUK8 = function() { this.mmu.reset(); var mmu = this.mmu; test = function(address, expected) { var actual = mmu.read8(address); assertEquals(expected, actual); } // data fixture for generated tests for(i = 0; i<0x20000; i++) { area = (i > 0xffff ? this.mmu.user : this.mmu.kernel); r_addr = (i > 0xffff ? i - 0xffff : i); area[r_addr] = (i%255 + i%17)%255; } /** Generated from C code **/ // Read mem 8 test(0x0,0); test(0x1555,110); test(0x2aaa,220); test(0x3fff,75); test(0x5554,185); test(0x6aa9,23); test(0x7ffe,133); test(0x9553,243); test(0xaaa8,98); test(0xbffd,191); test(0xd552,46); test(0xeaa7,156); test(0xfffc,11); test(0x11551,104); test(0x12aa6,214); test(0x13ffb,69); test(0x15550,179); test(0x16aa5,17); test(0x17ffa,127); test(0x1954f,237); test(0x1aaa4,92); test(0x1bff9,202); test(0x1d54e,40); test(0x1eaa3,150); test(0x1fff8,5); /** End generated code **/ }
import Person from "./Object-oriented"; class Student extends Person { constructor(name, age, job) { super(name); this.age = age; this.job = job; } getJob() { console.log(this.job); } getAge() { console.log(this.age); } } export default Student;
const err_names = { ServerError: [ "Internal Server Error", 500 ], TooFewArguments: [ "Too few Arguments", 400 ], PasswordInvalid: [ "Password invalid", 400 ], PasswordNotSecure: [ "Password does not match criteria", 400 ], UsernameInvalid: [ "Username invalid", 400 ], UserEmailInvalid: [ "Username/Email invalid", 400 ], UsernameTaken: [ "Username is already taken", 400 ], InvalidEmail: [ "Not a valid Email", 400 ], } mapped = {} Object.keys(err_names).forEach(error => { mapped[error] = { error: err_names[error][0], code: err_names[error][1] } }); module.exports = mapped;
import {request} from "../utils/request"; export function getCart(data) { return request({ url: '/api/Cart/getCart', method: 'post', data }) } export function saveCart(data) { return request({ url: '/api/Cart/saveCart', method: 'post', data }) } export function deleteCart(data) { return request({ url: '/api/Cart/deleteCart', method: 'post', data }) }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // import * as network from '../../utils/network.js'; import chai from 'chai'; const {expect} = chai; describe('utils/network.js', () => { describe('isCacheable', () => { const testCases = [ { resourceType: 'XHR', cacheControl: 'public, max-age=20000', expectation: false, }, { resourceType: 'Script', cacheControl: 'public, max-age=20000', expectation: true, }, { resourceType: 'Script', cacheControl: 'public, max-age=0', expectation: false, }, { resourceType: 'Script', cacheControl: 'no-cache', expectation: false, }, { resourceType: 'Script', cacheControl: 'no-store', expectation: false, }, { resourceType: 'Script', cacheControl: 'public', expectation: true, }, ]; for (const {resourceType, cacheControl, expectation} of testCases) { const headerNames = ['cache-control', 'cache-Control', 'CACHE-CONTROL']; for (const name of headerNames) { it(`should return ${expectation} for resource type ${resourceType} ` + `with cache-control=${cacheControl}`, () => { const record = { statusCode: 200, resourceType, responseHeaders: [{name, value: cacheControl}], protocol: 'https:', parsedURL: { scheme: 'https:', }, }; expect(network.isCacheable(record)).to.equal(expectation); }); } } it('should return false with no cache-control header', () => { const record = { statusCode: 200, resourceType: 'Script', protocol: 'https', parsedURL: { scheme: 'https:', }, }; expect(network.isCacheable(record)).to.equal(false); }); }); });
const timesDB = require("../myModel/timesCount.js"); module.exports = app => { class NewsController extends app.Controller { * list() { let list = []; for(let key in timesDB) { list.push({ type:`${key}`, times:`${timesDB[key]}` }) } list = this.mergeSort(list); const dataList = { list, } yield this.ctx.render('news/list.tpl', dataList); } mergeSort(arr) { let len = arr.length; if(len<2) { return arr; } let middle = Math.floor(len / 2); let left = arr.slice(0, middle); let right = arr.slice(middle); return this.merge(this.mergeSort(left), this.mergeSort(right)); } merge(left,right) { let result = []; while(left.length && right.length) { if(left[0].times >= right[0].times) { result.push(left.shift()); } else { result.push(right.shift()); } } while(left.length) { result.push(left.shift()); } while(right.length) { result.push(right.shift()); } return result; } } return NewsController; };
'use strict'; app.controller('JobCtrl', function ($scope, factJobs, factDomains, factAnalytics, $timeout, $q) { console.log ('JobCtrl'); $scope.newcrawljob = { depth : -1, numberpages : -1 } $scope.addCrawljob = function (newcrawljob) { console.log('addCrawljob: started "startJob"'); console.log('addCrawljob: newcrawljob: ' + JSON.stringify(newcrawljob)); factJobs.startCrawlJob(newcrawljob).then(function(status) { console.log('JobCtrl: addCrawljob. SUCCESS: status: ' + JSON.stringify(status)); }, function (error) { console.log('JobCtrl: addCrawljob. ERROR: error: ' + JSON.stringify(error)); }); console.log('JobCtrl: ended "addCrawljob"'); }; $scope.addScreenshotjob = function (newscreenshotjob) { console.log('addScreenshotjob: started "addScreenshotjob"'); console.log('addScreenshotjob: newscreenshotjob: ' + JSON.stringify(newscreenshotjob)); console.log('addScreenshotjob: newscreenshotjob.selectedWebsite: ' + JSON.stringify(newscreenshotjob.selectedWebsite)); factJobs.startScreenshotJob(newscreenshotjob).then(function(status) { console.log('JobCtrl: addScreenshotjob. SUCCESS: status: ' + JSON.stringify(status)); }, function (error) { console.log('JobCtrl: addScreenshotjob. ERROR: error: ' + JSON.stringify(error)); }); console.log('JobCtrl: ended "addScreenshotjob"'); }; function loadDomains() { var deferred = $q.defer(); // load existing domains and show them factDomains.getAll().then(function(data) { $scope.allDomains = data; console.log('JobCtrl: $scope.allDomains: ' + JSON.stringify(data)); $scope.showSuccess = true; $scope.alertSuccessMessage = "domains loaded successfully from the server!"; $timeout(function() { $scope.showSuccess = false; $scope.alertSuccessMessage = ''; }, 3000); deferred.resolve(true); }, function(error) { $scope.allDomains = []; $scope.showError = true; $scope.alertErrorMessage = "error while retrieving the domains from the server!"; $timeout(function() { $scope.showError = false; $scope.alertErrorMessage = ''; }, 3000); deferred.reject(false); }); return deferred.promise; } function loadJobs() { var deferred = $q.defer(); factJobs.getJobs().then(function(data) { $scope.allJobes = data; console.log('JobCtrl: $scope.allJobes: ' + JSON.stringify(data)); $scope.showSuccess = true; $scope.alertSuccessMessage = "jobs loaded successfully from the server!"; $timeout(function() { $scope.showSuccess = false; $scope.alertSuccessMessage = ''; }, 3000); deferred.resolve(true); }, function(error) { $scope.allDomains = []; $scope.showError = true; $scope.alertErrorMessage = "error while retrieving the jobs from the server!"; $timeout(function() { $scope.showError = false; $scope.alertErrorMessage = ''; }, 3000); deferred.reject(false); }); return deferred.promise; } function loadWebsites() { var deferred = $q.defer(); factAnalytics.getWebsites().then(function(data) { console.log('JobCtrl: getWebsites success : data returned: ' + JSON.stringify(data)); var s; // add a useful text for the user to select for (var i = 0; i < data.length; i++) { s = 'uid: ' + data[i].uid + ' | ' + data[i].name + ' | ' + data[i].description + ' | ' + data[i].status; data[i].text = s; } $scope.allWebsites = data; console.log('JobCtrl: $scope.allWebsites: ' + JSON.stringify(data)); $scope.showSuccess = true; $scope.alertSuccessMessage = "pages loaded successfully from the server!"; $timeout(function() { $scope.showSuccess = false; $scope.alertSuccessMessage = ''; }, 3000); deferred.resolve(true); }, function(error) { $scope.allDomains = []; $scope.showError = true; $scope.alertErrorMessage = "error while retrieving the pages from the server"; $timeout(function() { $scope.showError = false; $scope.alertErrorMessage = ''; }, 3000); deferred.reject(error); }); return deferred.promise; } loadDomains().then(function () { console.log('JobCtrl: loadDomains() success'); loadWebsites().then(function () { console.log('JobCtrl: loadWebsites() success'); loadJobs().then(function () { console.log('JobCtrl: loadJobs() success'); },function (error){ console.log('JobCtrl: loadJobs() ERROR: ' +error) }); },function (error){ console.log('JobCtrl: loadWebsites() ERROR: ' +error) }); },function (error){ console.log('JobCtrl: loadDomains() ERROR: ' +error) }); // newscreenshotcomparisonjob.selectedDomain.name $scope.$watch('compareJobSelectedDomain', function(newValue, oldValue) { if ((newValue !== undefined) && (newValue.uid !== undefined)) { console.log('JobCtrl: factAnalytics.getPages(uid) newValue.uid: ' + newValue.uid); factAnalytics.getWebsites(newValue.uid).then(function(data) { var s; // add a useful text for the user to select for (var i = 0; i < data.length; i++) { s = 'uid: ' + data[i].uid + ' | ' + data[i].name + ' | ' + data[i].description + ' | ' + data[i].status; data[i].text = s; } $scope.selectedDomainWebsites = data; }, function(error) { console.log('JobCtrl: factAnalytics.getPages(uid) returned an error: ' + JSON.stringify(error)); $scope.selectedDomainWebsites = []; }) }; }); $scope.newscreenshotjob = { height : 768, width : 1366 } $scope.addScreenshotcomparisonjob = function(newscreenshotcomparisonjob) { console.log('"addScreenshotcomparisonjob" newscreenshotcomparisonjob: '+ JSON.stringify(newscreenshotcomparisonjob, null, 4)); factJobs.addComparejob(newscreenshotcomparisonjob).then(function(status) { console.log('JobCtrl: addScreenshotcomparisonjob. SUCCESS: status: ' + JSON.stringify(status)); }, function (error) { console.log('JobCtrl: addScreenshotcomparisonjob. ERROR: error: ' + JSON.stringify(error)); }); console.log('JobCtrl: ended "addScreenshotcomparisonjob"'); }; })
const gulp = require('gulp'); const build = () => ( gulp.series('build') ); module.exports = { build, };
import { USER } from '../constants/actionTypes'; import authHeader from '../helpers/authHeader'; const { token, user } = authHeader(); const initialState = { isLoggedIn: token ? true : false, user: user ? user : false, } console.log(initialState); export default (state = initialState, action) => { switch(action.type) { case USER.LOGIN_REQUEST: return { isLogging: true, } case USER.LOGIN_SUCCESS: return { isLoggedIn: true, user: action.payload.user, } case USER.LOGIN_FAILURE: return { isLogging: false, loginFailure: true, status: action.payload.status, message: action.payload.message }; case USER.LOGOUT_REQUEST: return { isLoggingOut: true, }; case USER.LOGOUT_SUCCESS: return { isLoggedIn: false, }; case USER.VERIFICATION_SUCCESS: return { emailVerificationMessage: 'email_verified' }; case USER.VERIFICATION_ERROR: return { emailVerificationMessage: 'email_verification_failed', }; case USER.VERIFICATION_CLEAR: return { ...state, emailVerificationMessage: null, }; default: return state; } }
/* EXERCISE 16: Write a small function called "getLongest" that takes a parameter called "arr" and returns the longest string in "arr". If there is a tie, return the first of the longest strings. For example: getLongest(['sam','indubitably','jacob']) should return 'indubitably' getLongest(['sam','cam','bob']) should return 'sam' getLongest(['','','']) should return '' */ function getLongest(arr){ var val = 1; return val; }
function checkForInputErrors(regex, element, array, message){ if(!regex.test(element.val().trim())) { array.push(message); element.addClass("border-danger"); } else{ element.removeClass("border-danger"); $(".errors").empty(); } } function printErrors(array) { if (array.length > 0) { let error = ""; for (let item of array) { error += `<span class="h6 ">${item}</span> </br>`; } $(".errors").html(error); } } function sendCSRFToken(){ $.ajaxSetup({ headers: { "X-CSRF-TOKEN": $("meta[name='_token']").attr("content") }, accept: "application/json" }); } function checkIfDropDownListIsNotSelected(list, array, message){ if(list.val() === '0' || list.val() === ''){ array.push(message); list.addClass('border-danger') } else{ list.removeClass('border-danger'); } } function checkIfMultipleListIsNotSelected(list, array, message){ if($('.multiple :selected').length === 0){ array.push(message); list.addClass('border-danger'); } else{ list.removeClass('border-danger'); } } function validatePicture(image, array){ var file = null; if(image.val() === ""){ array.push("Picture is not chosen"); image.addClass('border-danger'); } else{ image.removeClass('border-danger'); file = image.prop('files')[0]; const fileName = file.name; const fileExtension = fileName.split(".").pop().toLowerCase(); var validExtension = true; if(!jQuery.inArray(fileExtension)) { let permittedExtensionsString = ""; validExtension = false; $.each(permittedExtensions, function(index, value){ permittedExtensionsString+= value + " "; }); array.push("Permitted extensions are: <span class='text-uppercase'> " + permittedExtensionsString + "</span>"); } if(file.size > 3000000 && validExtension === true ) { array.push("Picture can not be grater than 3 MB"); } } } function toggleCrewList(){ if($('#role').val() == 2){ $('.ranks').css('display','block'); } else{ $('.ranks').css('display','none'); } }
import express from 'express'; import mongoose from 'mongoose'; import User from '../models/user'; const router = express.Router(); // GET: / router.get('/', async (req, res) => { const users = await User.find().exec(); return res .status(200) .json({ data: users }); }); // GET: /:id router.get('/:id', async (req, res) => { const { id } = req.params; if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).json({ statusCode: 400, message: `Id is not valid`, }); } const user = await User.findById(id).exec(); if (!user) { return res.status(404).json(); } return res .status(200) .json(user); }); // POST: / router.post('/', async (req, res) => { const { name, email } = req.body; // TODO: Add validations // Generating a new User instance const newUser = new User({ name, email }); await newUser.save(); return res .status(201) .json(); }); // PATCH: /:id router.patch('/:id', async (req, res) => { const { id } = req.params; const body = req.body; // TODO: Add validations if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).json({ statusCode: 400, message: 'Id is not valid', }); } const user = await User.findByIdAndUpdate(id, { $set: { ...body } }, { new: true }).exec(); if (!user) { return res.status(404).json(); } return res .status(200) .json(user); }); router.delete('/:id', async (req, res) => { const { id } = req.params; if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).json({ statusCode: 400, message: 'Id is not valid', }); } await User.findByIdAndDelete(id).exec(); return res.status(200).json(); }); export default router;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var expect = require('chai').expect; var sinon = require('sinon'); var contextGetVariableMethod, contextSetVariableMethod, httpClientSendMethod, requestConstr; beforeEach(function() { global.context = { getVariable: function(s) {}, setVariable: function(a, b) {} }; global.httpClient = { send: function(s) {} }; global.Request = function(s) {}; contextGetVariableMethod = sinon.stub(global.context, 'getVariable'); contextSetVariableMethod = sinon.spy(global.context, 'setVariable'); httpClientSendMethod = sinon.stub(httpClient, 'send'); requestConstr = sinon.spy(global, 'Request'); }); afterEach(function() { contextGetVariableMethod.restore(); contextSetVariableMethod.restore(); httpClientSendMethod.restore(); requestConstr.restore(); }); exports.getMock = function() { return { contextGetVariableMethod: contextGetVariableMethod, contextSetVariableMethod: contextSetVariableMethod, httpClientSendMethod: httpClientSendMethod, requestConstr: requestConstr }; }
const form = document.querySelector("form"); const inputFields = document.querySelectorAll("input"); const textAreas = document.querySelectorAll("textarea"); const submitButton = document.querySelector(".submit-button"); const validate = () => { let inputArray = []; // If the form includes textareas textAreas.length > 0 ? // Combine textareas and regular inputs into one array inputArray = [...inputFields, ...textAreas]: // Or proceed with input fields only inputArray = [...inputFields]; // Filter out inputs/textareas that have content const filteredArray = inputArray.filter(field => field.value.trim().length > 0); // If the number of fields with content in the filtered array matches the total number of fields, enable the submit button filteredArray.length === inputArray.length ? submitButton.removeAttribute("disabled") : // Otherwise, keep disabled. Also allows function to reflexively disable button if field has content deleted submitButton.setAttribute("disabled", ""); } form.addEventListener("input", validate);
#!/usr/bin/env node require('../index.js')(process.argv[2], process.argv[3]);
const board = { asdf12j124j: { name: "Stuff to Try", cards: [ { id: "asdfj23j243", text: 'This is a card. Drag it on to "tried it" to show it\'s done.' }, { id: "asdfj23j244", text: 'This is a card. Drag it on to "tried it" to show it\'s done.' }, { id: "asdfj23j245", text: 'This is a card. Drag it on to "tried it" to show it\'s done.' }, { id: "asdfj23j246", text: 'This is a card. Drag it on to "tried it" to show it\'s done.' }, { id: "asdfj23j247", text: 'This is a card. Drag it on to "tried it" to show it\'s done.' }, { id: "asdfj23j248", text: 'This is a card. Drag it on to "tried it" to show it\'s done.' } ] }, rasdfea243s2: { name: "Stuff to Try", cards: [] }, wdfa43rwdafd34: { name: "Stuff to Try", cards: [] } }; export default board;
import authRouter from './authRouter'; import spotifyRouter from './spotifyRouter'; import trackRouter from './trackRouter'; import unknownRouter from './unknownRouter'; export { authRouter, spotifyRouter, trackRouter, unknownRouter };
//import actions import { GET_DATA } from '../actions/shared' export default function meta (state = {}, action){ switch(action.type){ case GET_DATA : return { ...state, page: action.metadata.meta.page, perPage: action.metadata.meta.perPage, totalPages: action.metadata.meta.totalPages } default : return state } }
var co = require('co'), path = require('path'), assert = require('assert'), f = require('util').format, SocketIOTransport = require('../../../server/transports/socketio'), Server = require('../../../server/server'), Long = require('../../../client/bson/long'), MongoClient = require('mongodb').MongoClient; // MongoDB Topology Manager var ServerManager = require('mongodb-topology-manager').Server, ReplSetManager = require('mongodb-topology-manager').ReplSet; // Get the client so we can simulate the Browser - Server connection var MongoBrowserClient = require('../../../client/mongo_client'), SocketIOClientTransport = require('../../../client/transports/socket_io_transport'), ioClient = require('socket.io-client'); var createServer = function(options) { return new Promise(function(resolve, reject) { co(function*() { var httpServer = require('http').createServer(function(req, res) { res.end("Hello World Page"); }); // Get the MongoClient var client = yield MongoClient.connect('mongodb://localhost:27017/test', { db: { promoteLongs: false } }); // Add to the server var mongoDBserver = new Server(client, options || {}); // Add a socket transport mongoDBserver.registerTransport(new SocketIOTransport(httpServer)); // Listen to the http server httpServer.listen(9091, function() { resolve({ httpServer: httpServer, client: client, mongoDBserver: mongoDBserver }); }); }).catch(function(err) { reject(err); }); }); } describe('Security', function() { describe('Reject', function() { it('reject command due to user not being authenticated single error', function(done) { co(function*() { // Start the server manager var manager = new ServerManager('mongod', { dbpath: path.join(path.resolve('db'), f("data-%d", 27017)), setParameter: ['enableTestCommands=1'] }); // Start a MongoDB instance yield manager.purge(); yield manager.start(); // // Server connection // var object = yield createServer({raw:true}); var mongoDBserver = object.mongoDBserver; var dbClient = object.client; var httpServer = object.httpServer; // Register channel handlers these are used to handle any data before it's passed through // to the mongodb handler var channel = yield mongoDBserver.createChannel('mongodb'); // Register before handler channel.before(function(conn, channel, data, callback) { callback(new Error('not authenticated')); }); // // Client connection // var client = new MongoBrowserClient(new SocketIOClientTransport(ioClient.connect, {})); // Create an instance try { // Attempt to connect var connectedClient = yield client.connect('http://localhost:9091'); } catch(e) { assert.equal('pre condition failed', e.message); assert.equal(false, e.ok); assert.equal(8, e.code); assert.deepEqual({ ismaster: true }, e.op); assert.deepEqual([ { message: 'not authenticated' } ], e.errors); // Destroy MongoDB browser server mongoDBserver.destroy(); // Shut down the httpServer.close(); // Shut down MongoDB connection dbClient.close(); // Shut down MongoDB instance yield manager.stop(9); done(); }; }).catch(function(e) { console.log(e.stack) }); }); it('reject command due to user not being authenticated multiple errors', function(done) { co(function*() { // Start the server manager var manager = new ServerManager('mongod', { dbpath: path.join(path.resolve('db'), f("data-%d", 27017)), setParameter: ['enableTestCommands=1'] }); // Start a MongoDB instance yield manager.purge(); yield manager.start(); // // Server connection // var object = yield createServer({raw:true}); var mongoDBserver = object.mongoDBserver; var dbClient = object.client; var httpServer = object.httpServer; // Register channel handlers these are used to handle any data before it's passed through // to the mongodb handler var channel = yield mongoDBserver.createChannel('mongodb'); // Register before handler channel.before(function(conn, channel, data, callback) { callback([new Error('not authenticated'), new Error('some other error')]); }); // // Client connection // var client = new MongoBrowserClient(new SocketIOClientTransport(ioClient.connect, {})); // Create an instance try { // Attempt to connect var connectedClient = yield client.connect('http://localhost:9091'); } catch(e) { assert.equal('pre condition failed', e.message); assert.equal(false, e.ok); assert.equal(8, e.code); assert.deepEqual({ ismaster: true }, e.op); assert.deepEqual([ { message: 'not authenticated' }, { message: 'some other error' } ], e.errors); // Destroy MongoDB browser server mongoDBserver.destroy(); // Shut down the httpServer.close(); // Shut down MongoDB connection dbClient.close(); // Shut down MongoDB instance yield manager.stop(9); done(); }; }).catch(function(e) { console.log(e.stack) }); }); }); });
var searchData= [ ['name',['name',['../interface_c1_connector_offer.html#a6c64624a2579f62538634568f7972525',1,'C1ConnectorOffer']]], ['nickname',['nickname',['../interface_c1_connector_user_master_data.html#a60223ec1e4216d015a063f4e272012d8',1,'C1ConnectorUserMasterData']]], ['nsdata_28base64_29',['NSData(Base64)',['../category_n_s_data_07_base64_08.html',1,'']]], ['nsdata_28kbhelper_29',['NSData(KBHelper)',['../category_n_s_data_07_k_b_helper_08.html',1,'']]], ['nsdata_28md5_29',['NSData(MD5)',['../category_n_s_data_07_m_d5_08.html',1,'']]], ['nsdate_28kbhelper_29',['NSDate(KBHelper)',['../category_n_s_date_07_k_b_helper_08.html',1,'']]], ['nsdictionary_28kbhelper_29',['NSDictionary(KBHelper)',['../category_n_s_dictionary_07_k_b_helper_08.html',1,'']]], ['nsstring_28hmac_5fsha256_29',['NSString(HMAC_SHA256)',['../category_n_s_string_07_h_m_a_c___s_h_a256_08.html',1,'']]], ['nsurl_28kbhelper_29',['NSURL(KBHelper)',['../category_n_s_u_r_l_07_k_b_helper_08.html',1,'']]] ];
'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _viewsTooltip = require('../views/tooltip'); var _post = require('./post'); var _cardsImage = require('../cards/image'); var _utilsKey = require('../utils/key'); var _utilsEventEmitter = require('../utils/event-emitter'); var _parsersMobiledoc = require('../parsers/mobiledoc'); var _parsersHtml = require('../parsers/html'); var _parsersDom = require('../parsers/dom'); var _renderersEditorDom = require('../renderers/editor-dom'); var _modelsRenderTree = require('../models/render-tree'); var _renderersMobiledoc = require('../renderers/mobiledoc'); var _utilsMerge = require('../utils/merge'); var _utilsDomUtils = require('../utils/dom-utils'); var _utilsArrayUtils = require('../utils/array-utils'); var _utilsElementUtils = require('../utils/element-utils'); var _utilsMixin = require('../utils/mixin'); var _utilsEventListener = require('../utils/event-listener'); var _utilsCursor = require('../utils/cursor'); var _utilsCursorRange = require('../utils/cursor/range'); var _modelsPostNodeBuilder = require('../models/post-node-builder'); var _textExpansions = require('./text-expansions'); var _keyCommands = require('./key-commands'); var _utilsStringUtils = require('../utils/string-utils'); var _utilsLifecycleCallbacks = require('../utils/lifecycle-callbacks'); var _modelsCard = require('../models/card'); var _utilsPasteUtils = require('../utils/paste-utils'); var _utilsCharacters = require('../utils/characters'); var _utilsAssert = require('../utils/assert'); var _editorMutationHandler = require('../editor/mutation-handler'); var _editorEditHistory = require('../editor/edit-history'); var EDITOR_ELEMENT_CLASS_NAME = '__mobiledoc-editor'; exports.EDITOR_ELEMENT_CLASS_NAME = EDITOR_ELEMENT_CLASS_NAME; var ELEMENT_EVENTS = ['keydown', 'keyup', 'cut', 'copy', 'paste']; var DOCUMENT_EVENTS = ['mouseup']; var defaults = { placeholder: 'Write here...', spellcheck: true, autofocus: true, undoDepth: 5, cards: [], atoms: [], cardOptions: {}, unknownCardHandler: function unknownCardHandler(_ref) { var env = _ref.env; throw new Error('Unknown card encountered: ' + env.name); }, unknownAtomHandler: function unknownAtomHandler(_ref2) { var env = _ref2.env; throw new Error('Unknown atom encountered: ' + env.name); }, mobiledoc: null, html: null }; var CALLBACK_QUEUES = { DID_UPDATE: 'didUpdate', WILL_RENDER: 'willRender', DID_RENDER: 'didRender', CURSOR_DID_CHANGE: 'cursorDidChange', DID_REPARSE: 'didReparse' }; /** * @class Editor * An individual Editor * @param element `Element` node * @param options hash of options */ var Editor = (function () { function Editor() { var _this = this; var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; _classCallCheck(this, Editor); (0, _utilsAssert['default'])('editor create accepts an options object. For legacy usage passing an element for the first argument, consider the `html` option for loading DOM or HTML posts. For other cases call `editor.render(domNode)` after editor creation', options && !options.nodeType); this._elementListeners = []; this._views = []; this.isEditable = null; this._parserPlugins = options.parserPlugins || []; // FIXME: This should merge onto this.options (0, _utilsMerge.mergeWithOptions)(this, defaults, options); this.cards.push(_cardsImage['default']); _textExpansions.DEFAULT_TEXT_EXPANSIONS.forEach(function (e) { return _this.registerExpansion(e); }); _keyCommands.DEFAULT_KEY_COMMANDS.forEach(function (kc) { return _this.registerKeyCommand(kc); }); this._parser = new _parsersDom['default'](this.builder); this._renderer = new _renderersEditorDom['default'](this, this.cards, this.atoms, this.unknownCardHandler, this.unknownAtomHandler, this.cardOptions); this.post = this.loadPost(); this._renderTree = new _modelsRenderTree['default'](this.post); this._editHistory = new _editorEditHistory['default'](this, this.undoDepth); } _createClass(Editor, [{ key: 'addView', value: function addView(view) { this._views.push(view); } }, { key: 'loadPost', value: function loadPost() { if (this.mobiledoc) { return _parsersMobiledoc['default'].parse(this.builder, this.mobiledoc); } else if (this.html) { if (typeof this.html === 'string') { var options = { plugins: this._parserPlugins }; return new _parsersHtml['default'](this.builder, options).parse(this.html); } else { var dom = this.html; return this._parser.parse(dom); } } else { return this.builder.createPost(); } } }, { key: 'rerender', value: function rerender() { var _this2 = this; var postRenderNode = this.post.renderNode; // if we haven't rendered this post's renderNode before, mark it dirty if (!postRenderNode.element) { (0, _utilsAssert['default'])('Must call `render` before `rerender` can be called', this.hasRendered); postRenderNode.element = this.element; postRenderNode.markDirty(); } this.runCallbacks(CALLBACK_QUEUES.WILL_RENDER); this._mutationHandler.suspendObservation(function () { _this2._renderer.render(_this2._renderTree); }); this.runCallbacks(CALLBACK_QUEUES.DID_RENDER); } }, { key: 'render', value: function render(element) { (0, _utilsAssert['default'])('Cannot render an editor twice. Use `rerender` to update the ' + 'rendering of an existing editor instance.', !this.hasRendered); (0, _utilsDomUtils.addClassName)(element, EDITOR_ELEMENT_CLASS_NAME); element.spellcheck = this.spellcheck; (0, _utilsDomUtils.clearChildNodes)(element); this.element = element; this._mutationHandler = new _editorMutationHandler['default'](this); this._mutationHandler.startObserving(); if (this.isEditable === null) { this.enableEditing(); } this._addTooltip(); // A call to `run` will trigger the didUpdatePostCallbacks hooks with a // postEditor. this.run(function () {}); this.rerender(); if (this.autofocus) { this.element.focus(); } this._setupListeners(); } }, { key: '_addTooltip', value: function _addTooltip() { this.addView(new _viewsTooltip['default']({ rootElement: this.element, showForTag: 'a' })); } }, { key: 'registerExpansion', /** * @method registerExpansion * @param {Object} expansion The text expansion to register. It must specify a * trigger character (e.g. the `<space>` character) and a text string that precedes * the trigger (e.g. "*"), and a `run` method that will be passed the * editor instance when the text expansion is invoked * @public */ value: function registerExpansion(expansion) { (0, _utilsAssert['default'])('Expansion is not valid', (0, _textExpansions.validateExpansion)(expansion)); this.expansions.push(expansion); } /** * @method registerKeyCommand * @param {Object} keyCommand The key command to register. It must specify a * modifier key (meta, ctrl, etc), a string representing the ascii key, and * a `run` method that will be passed the editor instance when the key command * is invoked * @public */ }, { key: 'registerKeyCommand', value: function registerKeyCommand(rawKeyCommand) { var keyCommand = (0, _keyCommands.buildKeyCommand)(rawKeyCommand); (0, _utilsAssert['default'])('Key Command is not valid', (0, _keyCommands.validateKeyCommand)(keyCommand)); this.keyCommands.unshift(keyCommand); } /** * @param {KeyEvent} event optional * @private */ }, { key: 'handleDeletion', value: function handleDeletion() { var _this3 = this; var event = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0]; var range = this.range; if (!range.isCollapsed) { this.run(function (postEditor) { var nextPosition = postEditor.deleteRange(range); postEditor.setRange(new _utilsCursorRange['default'](nextPosition)); }); } else if (event) { (function () { var key = _utilsKey['default'].fromEvent(event); _this3.run(function (postEditor) { var nextPosition = postEditor.deleteFrom(range.head, key.direction); var newRange = new _utilsCursorRange['default'](nextPosition); postEditor.setRange(newRange); }); })(); } } }, { key: 'handleNewline', value: function handleNewline(event) { if (!this.cursor.hasCursor()) { return; } event.preventDefault(); var range = this.range; this.run(function (postEditor) { var cursorSection = undefined; if (!range.isCollapsed) { var nextPosition = postEditor.deleteRange(range); cursorSection = nextPosition.section; if (cursorSection && cursorSection.isBlank) { postEditor.setRange(new _utilsCursorRange['default'](cursorSection.headPosition())); return; } } cursorSection = postEditor.splitSection(range.head)[1]; postEditor.setRange(new _utilsCursorRange['default'](cursorSection.headPosition())); }); } }, { key: 'showPrompt', value: function showPrompt(message, defaultValue, callback) { callback(window.prompt(message, defaultValue)); } }, { key: 'didUpdate', value: function didUpdate() { this.trigger('update'); } }, { key: 'selectSections', value: function selectSections() { var sections = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; if (sections.length) { var headSection = sections[0], tailSection = sections[sections.length - 1]; this.selectRange(new _utilsCursorRange['default'](headSection.headPosition(), tailSection.tailPosition())); } else { this.cursor.clearSelection(); } this._reportSelectionState(); } }, { key: 'selectRange', value: function selectRange(range) { this.range = range; this.renderRange(); } // @private }, { key: 'renderRange', value: function renderRange() { if (this.range.isBlank) { this.cursor.clearSelection(); } else { this.cursor.selectRange(this.range); } this._reportSelectionState(); // ensure that the range is "cleaned"/un-cached after // rendering a cursor range this.range = null; } }, { key: 'setPlaceholder', value: function setPlaceholder(placeholder) { (0, _utilsElementUtils.setData)(this.element, 'placeholder', placeholder); } }, { key: '_reparsePost', value: function _reparsePost() { var post = this._parser.parse(this.element); this.run(function (postEditor) { postEditor.removeAllSections(); postEditor.migrateSectionsFromPost(post); }); this.runCallbacks(CALLBACK_QUEUES.DID_REPARSE); this.didUpdate(); } }, { key: '_reparseSections', value: function _reparseSections() { var _this4 = this; var sections = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; var currentRange = undefined; sections.forEach(function (section) { _this4._parser.reparseSection(section, _this4._renderTree); }); this._removeDetachedSections(); if (this._renderTree.isDirty) { currentRange = this.range; } // force the current snapshot's range to remain the same rather than // rereading it from DOM after the new character is applied and the browser // updates the cursor position var range = this._editHistory._pendingSnapshot.range; this.run(function () { _this4._editHistory._pendingSnapshot.range = range; }); this.rerender(); if (currentRange) { this.selectRange(currentRange); } this.runCallbacks(CALLBACK_QUEUES.DID_REPARSE); this.didUpdate(); } // FIXME this should be able to be removed now -- if any sections are detached, // it's due to a bug in the code. }, { key: '_removeDetachedSections', value: function _removeDetachedSections() { (0, _utilsArrayUtils.forEach)((0, _utilsArrayUtils.filter)(this.post.sections, function (s) { return !s.renderNode.isAttached(); }), function (s) { return s.renderNode.scheduleForRemoval(); }); } /* * Returns the active sections. If the cursor selection is collapsed this will be * an array of 1 item. Else will return an array containing each section that is either * wholly or partly contained by the cursor selection. * * @return {array} The sections from the cursor's selection start to the selection end */ }, { key: 'detectMarkupInRange', value: function detectMarkupInRange(range, markupTagName) { var markups = this.post.markupsInRange(range); return (0, _utilsArrayUtils.detect)(markups, function (markup) { return markup.hasTag(markupTagName); }); } }, { key: 'serialize', value: function serialize() { var version = arguments.length <= 0 || arguments[0] === undefined ? _renderersMobiledoc.MOBILEDOC_VERSION : arguments[0]; return _renderersMobiledoc['default'].render(this.post, version); } }, { key: 'removeAllViews', value: function removeAllViews() { this._views.forEach(function (v) { return v.destroy(); }); this._views = []; } }, { key: 'destroy', value: function destroy() { this._isDestroyed = true; if (this.cursor.hasCursor()) { this.cursor.clearSelection(); this.element.blur(); } if (this._mutationHandler) { this._mutationHandler.destroy(); } this.removeAllEventListeners(); this.removeAllViews(); this._renderer.destroy(); } /** * Keep the user from directly editing the post. Modification via the * programmatic API is still permitted. * * @method disableEditing * @public */ }, { key: 'disableEditing', value: function disableEditing() { this.isEditable = false; if (this.element) { this.element.setAttribute('contentEditable', false); this.setPlaceholder(''); } } /** * Allow the user to directly interact with editing a post via a cursor. * * @method enableEditing * @return undefined * @public */ }, { key: 'enableEditing', value: function enableEditing() { this.isEditable = true; if (this.element) { this.element.setAttribute('contentEditable', true); this.setPlaceholder(this.placeholder); } } /** * Change a cardSection into edit mode * If called before the card has been rendered, it will be marked so that * it is rendered in edit mode when it gets rendered. * @param {CardSection} cardSection * @return undefined * @public */ }, { key: 'editCard', value: function editCard(cardSection) { this._setCardMode(cardSection, _modelsCard.CARD_MODES.EDIT); } /** * Change a cardSection into display mode * If called before the card has been rendered, it will be marked so that * it is rendered in display mode when it gets rendered. * @param {CardSection} cardSection * @return undefined * @public */ }, { key: 'displayCard', value: function displayCard(cardSection) { this._setCardMode(cardSection, _modelsCard.CARD_MODES.DISPLAY); } /** * Run a new post editing session. Yields a block with a new `postEditor` * instance. This instance can be used to interact with the post abstract, * and defers rendering until the end of all changes. * * Usage: * * let markerRange = this.range; * editor.run((postEditor) => { * postEditor.deleteRange(markerRange); * // editing surface not updated yet * postEditor.schedule(() => { * console.log('logs during rerender flush'); * }); * // logging not yet flushed * }); * // editing surface now updated. * // logging now flushed * * The return value of `run` is whatever was returned from the callback. * * @method run * @param {Function} callback Function to handle post editing with, provided the `postEditor` as an argument. * @return {} Whatever the return value of `callback` is. * @public */ }, { key: 'run', value: function run(callback) { var postEditor = new _post['default'](this); postEditor.begin(); this._editHistory.snapshot(); var result = callback(postEditor); this.runCallbacks(CALLBACK_QUEUES.DID_UPDATE, [postEditor]); postEditor.complete(); if (postEditor._shouldCancelSnapshot) { this._editHistory._pendingSnapshot = null; } this._editHistory.storeSnapshot(); return result; } /** * @method didUpdatePost * @param {Function} callback This callback will be called with `postEditor` * argument when the post is updated * @public */ }, { key: 'didUpdatePost', value: function didUpdatePost(callback) { this.addCallback(CALLBACK_QUEUES.DID_UPDATE, callback); } /** * @method willRender * @param {Function} callback This callback will be called before the editor * is rendered. * @public */ }, { key: 'willRender', value: function willRender(callback) { this.addCallback(CALLBACK_QUEUES.WILL_RENDER, callback); } /** * @method didRender * @param {Function} callback This callback will be called after the editor * is rendered. * @public */ }, { key: 'didRender', value: function didRender(callback) { this.addCallback(CALLBACK_QUEUES.DID_RENDER, callback); } /** * @method cursorDidChange * @param {Function} callback This callback will be called after the cursor * position (or selection) changes. * @public */ }, { key: 'cursorDidChange', value: function cursorDidChange(callback) { this.addCallback(CALLBACK_QUEUES.CURSOR_DID_CHANGE, callback); } }, { key: '_setupListeners', value: function _setupListeners() { var _this5 = this; ELEMENT_EVENTS.forEach(function (eventName) { _this5.addEventListener(_this5.element, eventName, function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _this5.handleEvent.apply(_this5, [eventName].concat(args)); }); }); DOCUMENT_EVENTS.forEach(function (eventName) { _this5.addEventListener(document, eventName, function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return _this5.handleEvent.apply(_this5, [eventName].concat(args)); }); }); } }, { key: 'handleEvent', value: function handleEvent(eventName) { for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } if ((0, _utilsArrayUtils.contains)(ELEMENT_EVENTS, eventName)) { var element = args[0].target; if (!this.cursor.isAddressable(element)) { // abort handling this event return true; } } var methodName = 'handle' + (0, _utilsStringUtils.capitalize)(eventName); (0, _utilsAssert['default'])('No handler "' + methodName + '" for ' + eventName, !!this[methodName]); this[methodName].apply(this, args); } }, { key: 'handleMouseup', value: function handleMouseup() { var _this6 = this; // mouseup does not correctly report a selection until the next tick setTimeout(function () { return _this6._reportSelectionState(); }, 0); } }, { key: 'handleKeyup', value: function handleKeyup() { this._reportSelectionState(); } /* The following events/sequences can create a selection and are handled: * mouseup -- can happen anywhere in document, must wait until next tick to read selection * keyup when key is a movement key and shift is pressed -- in editor element * keyup when key combo was cmd-A (alt-A) aka "select all" * keyup when key combo was cmd-Z (browser may restore selection) These cases can create a selection and are not handled: * ctrl-click -> context menu -> click "select all" */ }, { key: '_reportSelectionState', value: function _reportSelectionState() { this.runCallbacks(CALLBACK_QUEUES.CURSOR_DID_CHANGE); } }, { key: '_insertEmptyMarkupSectionAtCursor', value: function _insertEmptyMarkupSectionAtCursor() { var _this7 = this; this.run(function (postEditor) { var section = postEditor.builder.createMarkupSection('p'); postEditor.insertSectionBefore(_this7.post.sections, section); postEditor.setRange(_utilsCursorRange['default'].fromSection(section)); }); } }, { key: 'handleKeydown', value: function handleKeydown(event) { var _this8 = this; if (!this.isEditable || this.handleKeyCommand(event)) { return; } if (this.post.isBlank) { this._insertEmptyMarkupSectionAtCursor(); } var key = _utilsKey['default'].fromEvent(event); var range = undefined, nextPosition = undefined; switch (true) { case key.isHorizontalArrow(): range = this.cursor.offsets; var position = range.tail; if (range.direction === _utilsKey.DIRECTION.BACKWARD) { position = range.head; } nextPosition = position.move(key.direction); if (position.section.isCardSection || position.marker && position.marker.isAtom || nextPosition && nextPosition.marker && nextPosition.marker.isAtom) { if (nextPosition) { var newRange = undefined; if (key.isShift()) { newRange = range.moveFocusedPosition(key.direction); } else { newRange = new _utilsCursorRange['default'](nextPosition); } this.selectRange(newRange); event.preventDefault(); } } break; case key.isDelete(): this.handleDeletion(event); event.preventDefault(); break; case key.isEnter(): this.handleNewline(event); break; case key.isPrintable(): range = this.range; var _range = range, isCollapsed = _range.isCollapsed; nextPosition = range.head; if (this.handleExpansion(event)) { event.preventDefault(); break; } var shouldPreventDefault = isCollapsed && range.head.section.isCardSection; var didEdit = false; var isMarkerable = range.head.section.isMarkerable; var isVisibleWhitespace = isMarkerable && (key.isTab() || key.isSpace()); this.run(function (postEditor) { if (!isCollapsed) { nextPosition = postEditor.deleteRange(range); didEdit = true; } if (isVisibleWhitespace) { var toInsert = key.isTab() ? _utilsCharacters.TAB : _utilsCharacters.SPACE; shouldPreventDefault = true; didEdit = true; nextPosition = postEditor.insertText(nextPosition, toInsert); } if (nextPosition.marker && nextPosition.marker.isAtom) { didEdit = true; // ensure that the cursor is properly repositioned one character forward // after typing on either side of an atom _this8.addCallbackOnce(CALLBACK_QUEUES.DID_REPARSE, function () { var position = nextPosition.move(_utilsKey.DIRECTION.FORWARD); var nextRange = new _utilsCursorRange['default'](position); _this8.run(function (postEditor) { return postEditor.setRange(nextRange); }); }); } if (nextPosition && nextPosition !== range.head) { didEdit = true; postEditor.setRange(new _utilsCursorRange['default'](nextPosition)); } if (!didEdit) { // this ensures we don't push an empty snapshot onto the undo stack postEditor.cancelSnapshot(); } }); if (shouldPreventDefault) { event.preventDefault(); } break; } } /** * Finds and runs first matching text expansion for this event * @param {Event} event keyboard event * @return {Boolean} True when an expansion was found and run * @private */ }, { key: 'handleExpansion', value: function handleExpansion(keyEvent) { var expansion = (0, _textExpansions.findExpansion)(this.expansions, keyEvent, this); if (expansion) { expansion.run(this); return true; } return false; } /** * Finds and runs the first matching key command for the event * * If multiple commands are bound to a key combination, the * first matching one is run. * * If a command returns `false` then the next matching command * is run instead. * * @method handleKeyCommand * @param {Event} event The keyboard event triggered by the user * @return {Boolean} true when a command was successfully run * @private */ }, { key: 'handleKeyCommand', value: function handleKeyCommand(event) { var keyCommands = (0, _keyCommands.findKeyCommands)(this.keyCommands, event); for (var i = 0; i < keyCommands.length; i++) { var keyCommand = keyCommands[i]; if (keyCommand.run(this) !== false) { event.preventDefault(); return true; } } return false; } }, { key: 'handleCut', value: function handleCut(event) { event.preventDefault(); this.handleCopy(event); this.handleDeletion(); } }, { key: 'handleCopy', value: function handleCopy(event) { event.preventDefault(); (0, _utilsPasteUtils.setClipboardCopyData)(event, this); } }, { key: 'handlePaste', value: function handlePaste(event) { event.preventDefault(); var position = this.cursor.offsets.head; if (position.section.isCardSection) { return; } if (this.cursor.hasSelection()) { this.handleDeletion(); } var pastedPost = (0, _utilsPasteUtils.parsePostFromPaste)(event, this.builder, this._parserPlugins); this.run(function (postEditor) { var nextPosition = postEditor.insertPost(position, pastedPost); postEditor.setRange(new _utilsCursorRange['default'](nextPosition)); }); } // @private }, { key: '_setCardMode', value: function _setCardMode(cardSection, mode) { var renderNode = cardSection.renderNode; if (renderNode && renderNode.isRendered) { var cardNode = renderNode.cardNode; cardNode[mode](); } else { cardSection.setInitialMode(mode); } } }, { key: 'builder', get: function get() { if (!this._builder) { this._builder = new _modelsPostNodeBuilder['default'](); } return this._builder; } }, { key: 'expansions', get: function get() { if (!this._expansions) { this._expansions = []; } return this._expansions; } }, { key: 'keyCommands', get: function get() { if (!this._keyCommands) { this._keyCommands = []; } return this._keyCommands; } }, { key: 'cursor', get: function get() { return new _utilsCursor['default'](this); } // "read" the range from dom unless it has been set explicitly // Any method that sets the range explicitly should ensure that // the range is rendered and cleaned later }, { key: 'range', get: function get() { return this._range || this.cursor.offsets; }, set: function set(newRange) { this._range = newRange; } }, { key: 'activeSections', get: function get() { return this.cursor.activeSections; } }, { key: 'activeSection', get: function get() { var activeSections = this.activeSections; return activeSections[activeSections.length - 1]; } }, { key: 'markupsInSelection', get: function get() { if (this.cursor.hasCursor()) { var range = this.range; return this.post.markupsInRange(range); } else { return []; } } }, { key: 'hasRendered', get: function get() { return !!this.element; } }]); return Editor; })(); (0, _utilsMixin['default'])(Editor, _utilsEventEmitter['default']); (0, _utilsMixin['default'])(Editor, _utilsEventListener['default']); (0, _utilsMixin['default'])(Editor, _utilsLifecycleCallbacks['default']); exports['default'] = Editor;
import React, { Component } from "react"; import { connect } from "react-redux"; import { isUserSet } from "../../lib/helpers"; import DepositTable from "../DepositTable"; import _ from 'lodash'; import "./index.css"; class DepositTab extends Component { constructor(props){ super(props); this.state = {}; } componentDidMount(){ this.projectData(this.props); } componentWillReceiveProps(props){ this.projectData(props); } projectData = async (props) => { } render() { const { profile, isCurrentPath } = this.props; if(!isUserSet(profile)){return} return ( <DepositTable isCurrentPath={isCurrentPath} /> ); } } function mapStateToProps(state){ return { profile: state.profile, ln : state.language }; } export default connect(mapStateToProps)(DepositTab);
'use strict'; const webpack = require('webpack'); const utils = require('../webpack/utils'); const { NODE_ENV } = utils; const config = { output: { filename: '[name].js', chunkFilename: '[id].chunk.js' }, performance: { hints: NODE_ENV === 'production' ? 'warning' : false, assetFilter(assetFilename) { return assetFilename.endsWith('.js'); } }, resolve: { modulesDirectories: ['node_modules', 'public/bower-components'] }, module: { noParse: [ // 不解析某些模块 /node_modules\/jquery/ ], loaders: [{ test: /\.pug$/, loader: 'pug' }] }, //插件 plugins: [ // new webpack.ResolverPlugin([ // new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('package.json', ['main']), // new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main']) // ], ['normal', 'loader']) ], target: 'web' }; module.exports = config;
//====================================// //========== Express Server ==========// //====================================// // Require server modules const express = require('express'); const app = express(); const server = require('http').createServer(app); const port = process.env.PORT || 3000; // Serve the public directory app.use(express.static('source/public')); // Start listening on the server port server.listen(port, () => { console.log('[Server] Listening on port: ', port); }); //===================================// //========== Export Module ==========// //===================================// module.exports = server;
/* * Short description for file * * Long description for file (if any)... * * @package: Blueacorn AdminColorAttribute.js * @version: 1.0 * @Author: Blue Acorn, Inc. <code@blueacorn.com> * @Copyright: Copyright 2015-08-23 21:03:06 Blue Acorn, Inc. */ 'use strict'; function AdminColorAttribute() { var adminColorAttributeUrl = 'admin/catalog_product_attribute/edit/attribute_id/92/'; this.getAdminColorAttributeUrl = function() { return adminColorAttributeUrl; }; };
const test = require('tape'); const everyNth = require('./everyNth.js'); test('Testing everyNth', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof everyNth === 'function', 'everyNth is a Function'); t.deepEqual(everyNth([1, 2, 3, 4, 5, 6], 2), [ 2, 4, 6 ], "Returns every nth element in an array"); //t.deepEqual(everyNth(args..), 'Expected'); //t.equal(everyNth(args..), 'Expected'); //t.false(everyNth(args..), 'Expected'); //t.throws(everyNth(args..), 'Expected'); t.end(); });
import React from 'react'; import './Buildcontrol.css'; class Buildcontrol extends React.Component { render() { return ( <div className="buildcontrol"> <div className="label">{this.props.label}</div> <button onClick={this.props.removeItem} className="btn btn-secondary" disabled={this.props.isDisabled}>Less</button> <button className="btn btn-primary" onClick={this.props.addItem}>More</button> </div> ); } } export default Buildcontrol;
'use strict'; angular.module('newApp').controller('mdl.mobileweb.controller.postalvotesdeliveredstatement', ['$rootScope', '$scope', 'mdl.mobileweb.service.dashboard', 'mdl.mobileweb.service.recordprogress','mdl.mobileweb.service.login', 'toaster', 'mdl.mobileweb.service.json', '$http','modalService','$location','mdl.mobileweb.service.postalvotes', function ($rootScope, $scope, dashboardService, recordprogressService, loginService, toaster, jsonService, $http,modalService,$location, postalvotesService) { var vm = this; vm.pollingStationList = []; vm.electionlist = []; vm.electionId; vm.getProgressSummary=[]; vm.progressSummeryDetails = []; vm.stationstatuscheck = function(stationId){ dashboardService.getpollingstationclosedstatus(stationId, function(response) { var res = response; if(res.response=="success"){ if ((res.open_status==1)&&(res.closed_status==0)){ // toaster.pop("info","can do record progress"); vm.stationstatus = true; } else if(res.open_status==0) { vm.stationstatus = false; toaster.pop("info","Station Not Opened!",""); } else if(res.closed_status==1) { vm.stationstatus = false; toaster.pop("error","Station Closed!",""); } else{ vm.stationstatus = false; toaster.pop("error","Error!","Please try again later."); } } else{ toaster.pop("error","Error!","Try again later"); } }); } vm.getStationList = function (){ dashboardService.getPollingStations(function (response){ var resp = response; if(jsonService.whatIsIt(resp)=="Object"){ vm.pollingStationList[0] = resp; vm.getEList(vm.pollingStationList[0].id) } else if(jsonService.whatIsIt(resp)=="Array"){ vm.pollingStationList = resp; vm.getEList(vm.pollingStationList[0].id) } vm.stationstatuscheck(vm.pollingStationList[0].id); if (vm.pollingStationList[0]) { vm.stationcheck(vm.pollingStationList[0].id); } vm.selectedStation=vm.stationid; }) }; vm.getStationList(); vm.getEList = function (stationid){ dashboardService.getEllectionList(stationid,function (response){ var res = response; if(jsonService.whatIsIt(res)=="Object"){ vm.electionlist[0] = res; } else if(jsonService.whatIsIt(res)=="Array"){ vm.electionlist = res; } vm.getProgress(vm.electionlist[0].electionid,stationid); vm.checkElection(vm.electionlist[0].electionid,stationid); }) }; vm.checkElectionClosed = 0; vm.checkElection = function(eid,stationid){ $rootScope.cui_blocker(true);//UI blocker started dashboardService.getElectionStatus(eid,stationid,function(response){ vm.checkElectionClosed = response.electionstatus; vm.electionstatus = response; $rootScope.cui_blocker(false);//UI blocker close }); } vm.stationcheck = function(stationid,eid) { vm.stationid=stationid; vm.electionlist = []; vm.getEList(stationid); vm.stationstatuscheck(stationid); } vm.getProgress = function(electionid, stationId) { vm.electionId=electionid; //console.log(stationId); //console.log(electionid); vm.checkElection(electionid,stationId); recordprogressService.getPostalPackProgress(electionid, stationId, function (response) { var res = response; if(jsonService.whatIsIt(res)=="Object"){ vm.progressSummery = res; console.debug(vm.progressSummery); } else if(jsonService.whatIsIt(res)=="Array"){ vm.progressSummery = res; console.debug(vm.progressSummery.length); } }); } vm.cancel = function () { $location.path('/closestation'); } } ]);
function asyncAdd(a, b, callback) { setTimeout(function () { callback(null, a + b); }, 1000); } /** * 请在此方法中调用asyncAdd方法,完成数值计算 * @param {...any} rest 传入的参数 */ async function sum(...rest) { async function add(a, b) { return new Promise((resolve) => { asyncAdd(a, b, (err, result) => { resolve(result); }); }); } let sumResult = 0; for (let i of rest) { sumResult = await add(sumResult, i); } return sumResult; } // let start = window.performance.now(); sum(1, 2, 3, 4, 5, 6).then((res) => { // 请保证在调用sum方法之后,返回结果21 console.log(res); // console.log(`程序执行共耗时: ${window.performance.now() - start}`); });
'use strict'// Modo estricto para las variables. /** LOOPS */ let n=0; while(n<10){ console.log(`While ${n++}`); } for(var i = 0;i<10;i++){ console.log(`For ${i}`); } console.log(`i = ${i}`); // Var se mantiene fuera de los loops y los condicionales.
import React, { useState } from 'react' import { BrowserRouter as Router, Route, Switch } from "react-router-dom" import { useHistory } from "react-router-dom" import { useDispatch } from 'react-redux' import { SETUSER } from '../../Reducers/actionTypes' import { makeStyles } from '@material-ui/core/styles' import AppBar from '@material-ui/core/AppBar' import Toolbar from '@material-ui/core/Toolbar' import Typography from '@material-ui/core/Typography' import { TextField } from '@material-ui/core' import Button from '@material-ui/core/Button' import IconButton from '@material-ui/core/IconButton' import MeetingRoom from '@material-ui/icons/MeetingRoom' import LockOpen from '@material-ui/icons/LockOpen' import GitHubIcon from '@material-ui/icons/GitHub'; import LinkedIn from '@material-ui/icons/LinkedIn' // pages import Register from './Register' import NotFound from '../Static/NotFound' // compoenents import Notification from '../../Components/Notification/Notification' import LoadingScreen from '../../Components/LoadingScreen/LoadingScreenHook' import Illustration from '../Static/Illustration' // styling import { Form, Card } from 'react-bootstrap' import './CSS/common.css' // services import post from '../../Helpers/Request/post' import { setItem } from '../../Helpers/LocalStorage/LocalStorage' /** * @param _Login login form * @param loadingScreen loading scrren hook variable * @param email email entered by user in input field * @param password password entered by user in input field */ function _Login() { let history = useHistory() let moveToRegister = () => { history.push("/register") } const dispatch = useDispatch() const [loadingScreen, showLoadingScreen, hideLoadingScreen] = LoadingScreen() const [email, setEmail] = useState(null) const [password, setPassword] = useState(null) let handleFormSubmit = async (event) => { // login request event.preventDefault() showLoadingScreen() if (!email || !password) { Notification('Warning', 'Please type something to proceed!!', "danger") hideLoadingScreen() return } const response = await post('login', { email, password }) if (response.data) { let { data } = response let { uid, refreshToken } = data // set user in redux store dispatch({ type: SETUSER, token: refreshToken, email: email, user: uid }) setItem('usertoken', refreshToken) setItem('email', email) setItem('uid', uid) } else { // response is error message : string Notification('Error', 'Invalid Username/ Password', 'danger') } hideLoadingScreen() } return ( <> {loadingScreen} <div class="container"> <div class="row"> <div class="col-md-6 col-12 commontext"> <Illustration /> </div> <div class="col-md-6 col-12 input-position text-center"> <Form onSubmit={handleFormSubmit} id="commonform"> <h2 style={{ textAlign: "center" }}><LockOpen /> Login</h2> <Form.Group className="mb-3" controlId="formBasicEmail"> <TextField label="Email" type="email" fullWidth color="primary" onChange={(event) => setEmail(event.target.value)} /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicPassword"> <TextField label="Password" type="password" fullWidth color="primary" onChange={(event) => setPassword(event.target.value)} /> </Form.Group> <Button variant="contained" color="primary" type="submit"> Login </Button> <Button variant="link" onClick={moveToRegister}>New User? Register Here</Button> </Form> </div> </div> </div> </> ) } const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { flexGrow: 1, }, })); function Login() { const classes = useStyles(); return ( <div className={classes.root}> <AppBar position="static"> <Toolbar> <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu"> <MeetingRoom /> </IconButton> <Typography variant="h6" className={classes.title}> Meet - In - Room </Typography> </Toolbar> </AppBar> <Router> <Switch> <Route exact path="/"><_Login /></Route> <Route exact path="/register"><Register /></Route> {/* Not found */} <Route component={NotFound} /> </Switch> </Router> <div className="footer-common"> <div className="footer-common-heading"> <p>Buit with ❤️ by Shivansh Goel</p> </div> <div className="footer-common-icons"> <div className="footer-common-icons-item"><a target="_blank" href="https://github.com/ishivanshgoel"><GitHubIcon/></a></div> <div className="footer-common-icons-item"><a target="_blank" href="https://www.linkedin.com/in/shivansh-goel-260019a7/"><LinkedIn/></a></div> </div> </div> </div> ) } export default Login
import React from "react"; import "./Navbar.css"; function Navbar() { return ( <div className="nav"> <div className="container-fluid"> <nav className="navbar navbar-expand-md bg-dark navbar-dark"> <a href="#" className="navbar-brand"> MENU </a> <button datatype="button" className="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse" > <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse justify-content-between" id="navbarCollapse" > <div className="navbar-nav mr-auto"> <a href="/" className="nav-item nav-link active"> Home </a> <a href="/product" className="nav-item nav-link "> Products </a> <a href="/product-detail" className="nav-item nav-link "> Products Detail </a> <a href="/cart" className="nav-item nav-link "> Cart </a> <a href="/checkout" className="nav-item nav-link "> Checkout </a> <a href="/my-account" className="nav-item nav-link "> My Account </a> <div className="nav-item dropdown"> <a href="" className="nav-link dropdown-toggle" data-toggle="dropdown" > More Pages </a> <div className="dropdown-menu"> <a href="/wishlist" className="dropdown-item"> Wishlist </a> <a href="login-register" className="dropdown-item"> Login and Register </a> <a href="contact" className="dropdown-item"> Contact US </a> </div> </div> </div> <div className="navbar-nav ml-auto"> <div className="nav-item dropdown"> <a href="" className="nav-link dropdown-toggle" data-toggle="dropdown" > User Account </a> <div className="dropdown-menu"> <div className="dropdown-item">Login</div> <div className="dropdown-item">Register</div> </div> </div> </div> </div> </nav> </div> </div> ); } export default Navbar;