text
stringlengths
7
3.69M
// Object is not iterable only array and string is iteratable so how can i iterate object for loop // We can notdirectly iterate on object we need to firstly transform object in to array then we can iterate easily const weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']; const openingHours = { [weekdays[3]]: { open: 12, close: 22, }, [weekdays[4]]: { open: 11, close: 23, }, [weekdays[5]]: { open: 0, // Open 24 hours close: 24, }, }; const t1 = Object.entries(openingHours) console.log(t1); for (const [key, { open, close }] of t1) console.log(`So key ${key} and value is ${open} and ${close}`);
import React from 'react'; import moment from 'moment'; import { Session } from 'meteor/session'; import { withTracker } from 'meteor/react-meteor-data'; const FeatListItem = (props) => { const className = props.feat.selected ? 'item item--selected' : 'item'; return ( <div className={className} onClick={() => { props.Session.set('selectedFeatId', props.feat._id); props.history.replace(`/admin/${props.feat._id}`) }}> <h5 className="item__title" >{ props.feat.name || "Untitled Feat" }</h5> <p className="item__subtitle" >{ moment(props.feat.updatedAt).format('M/DD/YY') }</p> </div> ) } export default withTracker(() => { return {Session}; })(FeatListItem)
import { createTransport } from "nodemailer"; const MAIL_SENDING_E_MAIL = "chandankr.js.dev@gmail.com"; const MAIL_SENDING_MAIL_PASSWORD = "ckpassforgmail"; const transportOptions = { host: "smtp.gmail.com", port: 465, secure: true, auth: { user: MAIL_SENDING_E_MAIL, pass: MAIL_SENDING_MAIL_PASSWORD, }, }; const mailTransport = createTransport(transportOptions); export const SEND_EMAIL_WITH_OTP = (first_name, email, otp) => { // console.log("forgot pass for email sender called"); let html = null; html = ` <div style="background: #81ecec"> <center> <h1>Welcome to MY_WAY </h1> <h5>Hey <span style="color: blue">${first_name}</span> Here Is Your OTP To Move Ahead</h5> <h5> OTP for ${email} is <br/> <span style="color: red">${otp}</span> </h5> <br/> <h4>And This OTP Is Valid For Only 2 Minute So Hurry Up</h4> <h1> THANK YOU ONCE AGAIN FOR BEING WITH US </h1> </center> </div> `; try { var mailOptions = { from: MAIL_SENDING_E_MAIL, to: email, subject: "OTP request from you FOR Activating your Account ", html, }; mailTransport.sendMail(mailOptions, (error, info) => { if (error) { console.log(error); } else { console.log("Message sent to : ", info.envelope.to); } }); } catch (err) { console.log(err); } };
(function () { $.log('init sound') })
const ptr$ = (from, to) => { return { get v() { return from(); }, set v(i) { return to(i); } }; }; const refName = "ptr$("; const indName = "$"; document.body.querySelectorAll('script').forEach((tag) => { tag.getAttributeNames().forEach((name) => { if (name == 'use_refs') { const script = tag.textContent; if (script.includes(refName)) { for (let line of script.split('\n')) { if (line.includes(refName) && !line.startsWith('//') && !line.startsWith('/*')) { const change = tag.textContent.substring(tag.textContent.indexOf(line), tag.textContent.indexOf(line) + line.length).trim(); const toChangeName = change.split('=')[1].substring(change.split('=')[1].indexOf(refName) + refName.length, change.split('=')[1].indexOf(refName).length).replace(')', '').replace(';', '').trim(); const varName = change.split('=')[0]; tag.textContent = tag.textContent.replace(change, varName + `=${refName}()=>${toChangeName},(v)=>${toChangeName}=v)`); } /*if (line.includes(indName) && !line.includes(refName)) { const change = line.split('$')[0].trim(); tag.textContent = tag.textContent.replace(change+'$', change + `.v`); }*/ } // console.log(tag.textContent); eval(tag.textContent); } } }); });
const router = require('express').Router(); let Resto = require('../models/restaurant.model'); router.route('/').get((req, res) => { Resto.find() .then(restaurant => res.json(restaurant)) .catch(err => res.status(400).json('Error: ' + err)); }); router.route('/add').post((req, res) => { //add params here const newResto = new Resto({/*and here*/}); newResto.save() .then(() => res.json('Restaurant added into Database')) .catch(err => res.status(400).json('Error: ' + err)); });
import { GET_PROFILE_GITHUB_DATA_START, GET_PROFILE_GITHUB_REPOS_START } from '../../consts/actionTypes' export const getProfileData = payload => ({ type: GET_PROFILE_GITHUB_DATA_START, payload }) export const getProfileRepos = payload => ({ type: GET_PROFILE_GITHUB_REPOS_START, payload })
const fs = require('fs'); const handleError = require('./handle-error'); const VALID_COMMANDS = { CLEAR: 'CLEAR', FLAG: 'FLAG', UNFLAG: 'UNFLAG', END: 'END' }; const NUM_ROWS = 8; const NUM_COLS = 8; const commandsFile = fs.readFileSync('./commands.json'); const { commands } = JSON.parse(commandsFile) commands.forEach(command => { const [action, cellId] = command.toUpperCase().split(/\s+/g); if (!Object.values(VALID_COMMANDS).includes(action)) { handleError(`Invalid command "${command}"`); return; } if (action === VALID_COMMANDS.END) { return; } const posX = Number(cellId.charCodeAt(0) - "A".charCodeAt(0)); const posY = Number.parseInt(cellId.charAt(1), 10) - 1; if ( posX < 0 || posX >= NUM_COLS || posY < 0 || posY >= NUM_ROWS ) { handleError(`${command}: Field ${cellId} does not exist.`); return; } })
import cx from 'classnames' import React, { PureComponent } from 'react' import { findDOMNode } from 'react-dom' import PT from 'prop-types' import rAF from 'dom-helpers/util/requestAnimationFrame' import { noop } from '../utils/utils' import { UNMOUNTED, WILL_ENTER, DID_ENTER, WILL_LEAVE, DID_LEAVE, hasEntered, hasLeft, } from './utils' export class Transition extends PureComponent { state = { status: UNMOUNTED, } componentDidMount() { this.handleIn(this.state, this.props) } componentWillReceiveProps(nextProps) { if (this.props.in !== nextProps.in) { this.handleIn(this.state, nextProps) this.handleOut(this.state, nextProps) } } componentWillUnmount() { window.cancelAnimationFrame(this.requestAnimationId) } handleIn = (state, props) => { if (props.in && !hasEntered(state.status)) { const node = findDOMNode(this) const willEnter = () => this.willEnter(node, props, state) this.requestAnimationId = rAF(willEnter) } } handleOut = (state, props) => { if (!props.in && hasEntered(state.status)) { const node = findDOMNode(this) const willLeave = () => this.willLeave(node, props, state) this.requestAnimationId = rAF(willLeave) } } willEnter = (node, props, state) => { const didEnter = () => this.didEnter(node, props, this.state) const nextStep = () => { if (props.willEnter) { props.willEnter(node, didEnter) } else { this.requestAnimationId = rAF(didEnter) } } this.setState({ status: WILL_ENTER }, nextStep) } didEnter = (node, props, state) => { const nextStep = () => { if (props.didEnter) { props.didEnter(node, props, this.state) } else { this.requestAnimationId = 0 } } this.setState({ status: DID_ENTER }, nextStep) } willLeave = (node, props, state) => { const didLeave = () => this.didLeave(node, props, this.state) const nextStep = () => { if (props.willLeave) { props.willLeave(node, didLeave) } else { this.requestAnimationId = rAF(didLeave) } } this.setState({ status: WILL_LEAVE }, nextStep) } didLeave = (node, props, state) => { const didFinish = () => this.didFinish(props.didFinish) const nextStep = () => { if (props.didLeave) { props.didLeave(node, didFinish) } else { this.requestAnimationId = rAF(didFinish) } } this.setState({ status: DID_LEAVE }, nextStep) } didFinish = (cb) => { this.requestAnimationId = null this.setState({ status: UNMOUNTED }, cb) } render() { const { children, } = this.props return children } } Transition.propTypes = { didEnter: PT.func, didLeave: PT.func, willEnter: PT.func, willLeave: PT.func, } Transition.defaultProps = { didFinish: noop, }
/** * AIT - building an http server on top of the net module * this program displays a page that says hello if you go to * localhost:8080/hello... and goodbye if you go to localhost:8080/goodbye */ var net = require('net'); /** * Request object - takes http request string and parses out path * @param s - http request as string */ function Request(s) { // GET /foo/bar.baz HTTP/1.1\r\nX-Header:Qux\r\n\r\n // get the path ^ (which is 2nd element on 1st line) var requestParts = s.split(' '); var path = requestParts[1]; this.path = path; } /** * object that maps paths to functions that return an http response via * socket */ var routes = {}; routes['/hello'] = function(sock) { sock.write('HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<h2>hello!!!!!!</h2>'); }; routes['/goodbye'] = function(sock) { sock.write('HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<h1><em>goodbye :( :(</em></h1>'); }; var server = net.createServer(function(sock) { sock.on('data', function(data){ var reqString = data + ''; var req = new Request(reqString); // determine if our applications "knows" about this path if(routes.hasOwnProperty(req.path)) { // if it does, call the function that exists in the routes // object at the key, path ... pass in the socket as an // argument so that it can be used to send back a response routes[req.path](sock); } else { // uh-oh... didn't find a path, so send back a 404! sock.write('HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n\r\n NOT FOUND!!!!!!!'); } // remember to close the connection after response is sent sock.end(); }); sock.on('close', function(data){ console.log('closed'); }); console.log('got connection'); }); // use http://localhost:8080/hello in browser // or curl -i localhost:8080/hello in terminal server.listen(8080, '127.0.0.1');
let bt = document.querySelectorAll('.bt') /*con el foreach recorremos todos los elementos que esten en el bt*/ bt.forEach(e =>{ e.addEventListener('click', function(e){ const padre = e.target.parentNode; padre.children[1].classList.toggle('animation') padre.parentNode.children[1].classList.toggle('animation') }) })
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ function TreeNode(val) { this.val = val; this.left = this.right = null; } /** * @param {TreeNode} root * @return {number} */ var sumNumbers = function(root) { var result = {sum: 0}; if(!root) return 0; recurse(root, ''+root.val, result); return result.sum; }; function recurse(node, temp, result) { if (!node.left && !node.right) { result.sum += parseInt(temp); return; } if (node.left) { recurse(node.left, temp+node.left.val, result); } if (node.right) { recurse(node.right, temp+node.right.val, result); } } var a = new TreeNode(1); a.left = new TreeNode(2); a.right = new TreeNode(3); console.log(sumNumbers(a)); var b = new TreeNode(4); b.left = new TreeNode(9); b.right = new TreeNode(0); b.left.left = new TreeNode(5); b.left.right = new TreeNode(1); console.log(sumNumbers(b)); var c = new TreeNode(1); c.right = new TreeNode(5); console.log(sumNumbers(c));
chrome.runtime.onMessage.addListener(function (request) { if (request.name === "procedure") { switch (request.procedure) { case 1: var select = document.getElementById("p_kctsm"); select.value = 14; // 设为通识英语 document.getElementsByName("bt")[1].click(); // 点击查询 break; case 2: document.getElementsByTagName("a")[5].click(); document.getElementsByTagName("a")[5].click();// 按课余量排序 break; case 3: var array = document.getElementsByName("p_rx_id"); for (let i = 0; i < array.length; ++i) { array[i].click(); // 选中 } document.getElementsByName("submit1")[1].click(); break; default: break; } } });
angular.module('ngApp.preAlert').factory('PreAlertService', function ($http, config, SessionService) { var PreALertInitials = function (shipmentId) { return $http.get(config.SERVICE_URL + '/TradelaneShipments/PreALertInitials', { params: { shipmentId: shipmentId } }); }; var getTradelaneDocuments = function (shipmentId) { return $http.get(config.SERVICE_URL + '/TradelaneShipments/GetShipmentOtherDocuments', { params: { shipmentId: shipmentId } }); }; var SendPreAlertEmail = function (preAlerDetail) { return $http.post(config.SERVICE_URL + "/TradelaneShipments/SendPreAlertEmail", preAlerDetail); }; var removeOtherDoc = function (tradelaneShipmentDocument) { return $http.get(config.SERVICE_URL + '/TradelaneShipments/RemoveOtherDocument', { params: { tradelaneShipmentDocument: tradelaneShipmentDocument } }); }; return { removeOtherDoc: removeOtherDoc, SendPreAlertEmail: SendPreAlertEmail, PreALertInitials: PreALertInitials, getTradelaneDocuments: getTradelaneDocuments }; });
import isNumber from 'lodash/isNumber' export default class Execution { constructor() { this.op = null; this.left = null; this.right = null; this.parent = null; } setLeft(val) { if (val instanceof Execution) { val.parent = this; } this.left = val; } setRight(val) { if (val instanceof Execution) { val.parent = this; } this.right = val; } isLeaf() { return isNumber(this.left) && isNumber(this.right); } exec(leaves) { var calc = () => { return new Promise((resolve) => { setTimeout(() => { switch (this.op) { case '*': resolve(this.left * this.right); break; case '/': resolve(this.left / this.right); break; case '+': resolve(this.left + this.right); break; case '-': resolve(this.left - this.right); break; default: throw "Unknown operator " + this.op; } }, 10); }); } return calc() .then((val) => { if (this.parent) { if (this.parent.left === this) { this.parent.left = val; } else if (this.parent.right === this) { this.parent.right = val; } if (this.isLeaf()) { leaves.push(this); } } return Promise.resolve(val); }); } }
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const { VENUE_CATEGORIES, COUNTRIES, VENUE_DOORPOLICIES, VENUE_PAYMENT_METHODS, VENUE_MUSIC_TYPES, VENUE_VISITOR_TYPES, VENUE_DRESSCODES, VENUE_FACILITIES, } = require('../../shared/constants'); const { pointSchema, translatedSchema, weekSchema, } = require('../../shared/schemas'); const { deserialize } = require('./lib/serialization'); const VenueSchema = new Schema( { sourceId: Number, // Airtable ID name: { type: String, required: true, }, queryText: String, description: translatedSchema, categories: [ { type: String, enum: Object.values(VENUE_CATEGORIES), }, ], images: [{ type: String, ref: 'Image' }], location: { address1: { type: String, required: true, }, address2: String, postalCode: { type: String, required: true, }, city: { type: String, required: true, }, country: { type: String, required: true, enum: Object.values(COUNTRIES), }, coordinates: { type: pointSchema, required: true, }, googlePlaceId: String, }, phoneNumber: String, website: String, facebook: { id: String, pagesId: String, }, instagram: { id: String, explorePage: String, }, twitterHandle: String, musicTypes: [ { type: String, enum: Object.values(VENUE_MUSIC_TYPES), }, ], visitorTypes: [ { type: String, enum: Object.values(VENUE_VISITOR_TYPES), }, ], doorPolicy: { policy: { type: String, enum: Object.values(VENUE_DOORPOLICIES), }, description: translatedSchema, }, prices: Object, priceClass: { type: Number, min: 1, max: 4, }, timeSchedule: { open: weekSchema, kitchen: weekSchema, terrace: weekSchema, bitesUntil: weekSchema, drinksFrom: weekSchema, busyFrom: weekSchema, dancingFrom: weekSchema, }, capacity: Number, paymentMethods: [ { type: String, enum: Object.values(VENUE_PAYMENT_METHODS), }, ], fees: { entrance: Number, coatCheck: Number, }, dresscode: { type: String, enum: Object.values(VENUE_DRESSCODES), }, facilities: [ { type: String, enum: Object.values(VENUE_FACILITIES), }, ], tags: [{ type: String, ref: 'Tag' }], pageSlug: { type: String, required: true, }, tickets: { codes: [String], pdfUrl: String, qrCode: { version: String, text: String, }, guestListReference: String, }, admin: { hide: Boolean, }, }, { timestamps: true, } ); VenueSchema.index({ 'location.coordinates': '2dsphere' }); VenueSchema.index({ tags: 1 }); VenueSchema.method('deserialize', function(...args) { return deserialize(this, ...args); }); module.exports = mongoose.model('Venue', VenueSchema);
const state = { stops: [], isLoading: false, favorites: [], }; const getters = {}; let lastQuery; const actions = { findStops({ commit, rootGetters }, query) { if (!query) return commit('setStops', []); lastQuery = query; commit('setLoading', true); return rootGetters['api/api'] .findStops(query) .then((stops) => { console.log('stops', stops); if (lastQuery === query) { commit('setLoading', false); commit('setStops', stops); } else { console.log('skipping response'); } return stops; }) .catch((reason) => { console.error(reason); commit('setLoading', false); }); }, addFavorite({ commit, state }, favorite) { commit('setFavorites', [...state.favorites, favorite]); }, removeFavorite({ commit, state }, favorite) { const remainingFavorites = state.favorites.filter((fav) => { const toBeRemoved = fav.id === favorite.id && fav.name === favorite.name; return !toBeRemoved; }); commit('setFavorites', remainingFavorites); }, }; const mutations = { setStops(state, stops) { state.stops = stops; }, setLoading(state, value) { state.isLoading = value; }, setFavorites(state, favorites) { state.favorites = favorites; }, }; export default { namespaced: true, state, getters, actions, mutations, };
export const config = { api: { baseUrl: 'https://reels--video.herokuapp.com', baseVideoUrl: 'https://www.youtube.com/embed', imgURL: 'http://image.tmdb.org/t/p', // /{movieSize}/{movieIMGid} imgagesSizes: { backdrop_sizes: ['w300', 'w780', 'w1280', 'original'], logo_sizes: ['w45', 'w92', 'w154', 'w185', 'w300', 'w500', 'original'], poster_sizes: ['w92', 'w154', 'w185', 'w342', 'w500', 'w780', 'original'], profile_sizes: ['w45', 'w185', 'h632', 'original'], still_sizes: ['w92', 'w185', 'w300', 'original'], }, }, };
import React from 'react'; import Card from '../card'; import Grid from '@material-ui/core/Grid'; import PropTypes from 'prop-types'; const CardList = (props) => { if(!props.cardClickFunc || !props.listData) return null; return ( <Grid data-test="cardListContainer" container spacing={2}> {props.listData.map(item => { return ( <Grid key={item.id} item xs={12} sm={12} md={12} lg={12}> <Card onClick={() => props.cardClickFunc(item.id)} title={item.text} /> </Grid> ) })} </Grid> ); } CardList.propTypes = { cardClickFunc: PropTypes.func, listData: PropTypes.arrayOf(PropTypes.shape({ Title: PropTypes.string })) } export default CardList;
import React, { useState } from "react"; import ReminderIcon from "@material-ui/icons/NotificationsOutlined"; import AccessTimeIcon from "@material-ui/icons/AccessTime"; import ArrowBackIcon from "@material-ui/icons/ArrowBack"; import "./Reminder.css"; import { Button, Card, CardContent, ClickAwayListener, Divider, Grid, } from "@material-ui/core"; import { KeyboardDatePicker, KeyboardTimePicker, MuiPickersUtilsProvider, } from "@material-ui/pickers"; import DateFnsUtils from "@date-io/date-fns"; import "date-fns"; import moment from "moment"; const Reminder = ({ setDateTimeChip, setDisplayDateTime, item }) => { const [selectedDate, setSelectedDate] = useState(new Date()); const [showReminder, setShowReminder] = useState(false); const [showDateTime, setShowDateTime] = useState(false); const handleDateChange = (day) => { setShowDateTime(false); setShowReminder(false); let time = ""; let date = ""; if (day === "today") { date = moment(selectedDate).format("MMM Do YY"); time = "8:00PM"; } else if (day === "tomorrow") { date = moment(selectedDate).add(1, "day").format("MMM Do YY"); time = "8:00AM"; } else { date = moment(selectedDate).format("MMM Do YY"); time = moment(selectedDate).format("LT"); } if (item !== undefined) { setDateTimeChip(selectedDate); } else { setDateTimeChip(selectedDate); setDisplayDateTime(date + " " + time); } }; return ( <ClickAwayListener onClickAway={() => setShowReminder(false)}> <div> <div className="tools"> <ReminderIcon className="reminderContainer" onClick={() => setShowReminder(!showReminder)} /> </div> {showReminder ? ( <div className="dateTimeContainer"> <Card> <div className="dateTimeCardContainer"> <CardContent className="dateTimeCardContentReminder"> Reminder: </CardContent> <CardContent className="dateTimeCardContentStyle"> <div className="dateTimeSubCardcontentStyle" onClick={() => handleDateChange("today")} > Later Today <div>8:00PM</div> </div> <div className="dateTimeSubCardcontentStyle" onClick={() => handleDateChange("tomorrow")} > Tomorrow <div>8:00AM</div> </div> <div className="pickDateTimeLabel" onClick={() => setShowDateTime(!showDateTime)} > <AccessTimeIcon /> Pick date & time </div> </CardContent> </div> </Card> </div> ) : null} {showDateTime ? ( <div style={{ position: "absolute" }}> <Card> <CardContent className="dateTimePickerContainer" onClick={() => setShowDateTime(!showDateTime)} > <ArrowBackIcon /> <div>Pick date & time</div> </CardContent> <Divider /> <div> <MuiPickersUtilsProvider utils={DateFnsUtils}> <Grid container justify="space-around"> <KeyboardDatePicker disableToolbar={false} variant="inline" format="dd/MM/yyyy" margin="normal" id="date-picker-inline" label="Date picker" value={selectedDate} onChange={(date) => setSelectedDate(date)} KeyboardButtonProps={{ "aria-label": "change date", }} /> <KeyboardTimePicker margin="normal" id="time-picker" label="Time picker" value={selectedDate} onChange={(date) => setSelectedDate(date)} KeyboardButtonProps={{ "aria-label": "change time", }} /> </Grid> </MuiPickersUtilsProvider> <div className="saveButton"> <Button color="primary" variant="text" onClick={() => handleDateChange()} > save </Button> </div> </div> </Card> </div> ) : null} </div> </ClickAwayListener> ); }; export default Reminder;
// 分页器业务逻辑和代码 class Pagination { constructor (select, options = {}) { // options 是使用者传递进来的对象数据类型, 里面包含使用者需要的配置 // 构造函数体 // 你写的所有 this.xxx = yyy // 都是将来 Pagination 创建出来的实例对象身上的成员 this.ele = document.querySelector(select) // 需要一个表示当前是第几页的属性 // current: 当前 this.current = 1 // 需要一个表示一共多少条数据的属性 // total: 总数 // 如果使用者传递了, 使用人家传递的, 如果没有传递, 那么就用默认值 this.total = options.total || 90 // 需要一个表示一页显示多少条的属性 // pagesize: 一页显示多少条 this.pagesize = options.pagesize || 10 // 需要一个一共多少页的属性 // 根据总数据量 和 一页显示多少条 计算出来的 // totalPage: 总页数 this.totalPage = Math.ceil(this.total / this.pagesize) // 需要一个表示渲染下拉列表的属性 this.sizeList = options.sizeList || [10, 20, 30, 40] // 需要一个表示首页按钮文本的属性 // 如果使用者传递了内容, 那么我就用用户传递的 // 如果使用者没有传递, 那么我就用默认值 this.first = options.first || 'first' // 需要一个表示上一页按钮文本的属性 // prev: previous this.prev = options.prev || 'prev' // 需要一个表示下一页按钮文本的属性 this.next = options.next || 'next' // 需要一个表示最后一页按钮文本的属性 this.last = options.last || 'last' // 需要一个表示跳转按钮文本的属性 this.jump = options.jump || 'go' // 需要一个每次分页器改变当前页的时候, 触发的函数 this.change = options.change || function () {} // 利用 this 启动启动器 // this 就是当前实例 this.init() } // 直接开启启动器 // 直接写的所有内容都是原型上的方法 // 将来 Pagination 的实例都可以调用 init () { this.setHtml() this.setEvent() } // 1. 渲染页面 setHtml () { let str = ` <select class="sizeList"> ` // 根据 this.sizeList 来进行渲染 this.sizeList.forEach(item => { str += `<option value="${ item }">${ item }</option>` }) str += ` </select> <p class="first ${ this.current === 1 ? 'disable' : '' }">${ this.first }</p> <p class="prev ${ this.current === 1 ? 'disable' : '' }">${ this.prev }</p> <div class="list"> ` // 根据总页数去渲染多少个切换页按钮 // 要自己设置一个临界点: 9 // 只有 9 个及一下的时候, 才直接渲染 // 如果是 9 个以上, 那么就需要 ... 出现了 if (this.totalPage <= 9) { for (let i = 1; i <= this.totalPage; i++) { str += `<p class="item ${ this.current === i ? 'active' : '' }">${ i }</p>` } } else { // 根据当前页来判断 // 当前页 <= 3 if (this.current <= 3) { for (let i = 1; i <= 5; i++) { str += `<p class="item ${ this.current === i ? 'active' : '' }">${ i }</p>` } str += `<span>···</span><p class="item">${ this.totalPage }</p>` } else if (this.current <= this.totalPage - 2) { // 当前页 <= 倒数第三页 str += `<span>···</span>` for (let i = this.current - 2; i <= this.current + 2; i++) { str += `<p class="item ${ this.current === i ? 'active' : '' }">${ i }</p>` } str += `<span>···</span>` } else { // 当前页 > 倒数第三页 str += `<p class="item">1</p><span>···</span>` for (let i = this.totalPage - 4; i <= this.totalPage; i++) { str += `<p class="item ${ this.current === i ? 'active' : '' }">${ i }</p>` } } } str += ` </div> <p class="next ${ this.current === this.totalPage ? 'disable' : '' }">${ this.next }</p> <p class="last ${ this.current === this.totalPage ? 'disable' : '' }">${ this.last }</p> <input type="text" value="${ this.current }" class="jumpText"> <span>/ ${ this.totalPage }</span> <button class="jumpBtn">${ this.jump }</button> ` // 把准备好的结构插入到 this.ele 里面 // 所有内容都是放在范围元素内的 // this.ele 就是范围元素 this.ele.innerHTML = str // 设置 select 显示的内容是什么 const select = this.ele.querySelector('select') select.value = this.pagesize // 每一次当前页改变都要执行 这个 setHtml 函数 // 调用使用者传递进来的函数 // 把当前页和一页显示多少条, 给到使用者 this.change(this.current, this.pagesize) } // 2. 绑定事件 setEvent () { // 2-1. 点击事件 // 一大堆点击事件 // 都是动态渲染的 // 事件委托, 委托给范围元素 this.ele this.ele.onclick = e => { // 处理事件对象兼容 e = e || window.event // 处理事件目标兼容 const target = e.target || e.srcElement // 条件判断 // if (target.className.indexOf('disable') !== -1 || target.className.indexOf('active') !== -1) { // // 表示元素身上有 disable 类名 或者 active // // 就应该什么都不做 // return // } if (target.className.search(/(disable|active)/) !== -1) return // 判断按下的是哪一个按钮 if (target.className.indexOf('first') !== -1) { // 表示元素身上有 first 类名 // console.log('第一页') // 只要修改 this.current this.current = 1 this.setHtml() return } // 判断按下的是上一页 if (target.className.indexOf('prev') !== -1) { // console.log('上一页') this.current-- this.setHtml() return } // 判断按下的是下一页 if (target.className.indexOf('next') !== -1) { // console.log('下一页') this.current++ this.setHtml() return } // 判断按下的是最后一页 if (target.className.indexOf('last') !== -1) { // console.log('最后一页') this.current = this.totalPage this.setHtml() return } // 判断按下的是某一页 if (target.className.indexOf('item') !== -1) { // console.log('某一页') // 拿到我点击的这个元素身上写的是第几页 // 我点击的这个元素是什么 ? target this.current = target.innerText - 0 this.setHtml() return } // 判断按下的是跳转按钮 if (target.className.indexOf('jumpBtn') !== -1) { // 拿到文本框内部输入的内容 const text = this.ele.querySelector('.jumpText').value.trim() // 判断 text // 如果是一个 NaN 不跳转 if (isNaN(text)) return // 如果 text 小于第一页 if (text < 1) return // 如果 text 大于最后一页 if (text > this.totalPage) return // 代码能来到这里, 表示你输入的是一个合法的页数 this.current = text - 0 this.setHtml() return } } // 2-2. 一页显示多少条的切换 // 因为这个切换关系到一共多少页 // 还要关系到一共多少数据 this.ele.onchange = e => { // 处理事件对象兼容 e = e || window.event // 处理事件目标兼容 const target = e.target || e.srcElement // 判断发生改变的是 select 标签 if (target.nodeName === 'SELECT') { // 拿到你准备切换成一页显示多少条 this.pagesize = target.value - 0 // 一页显示多少条发生变化了, 那么总页数就得改变 this.totalPage = Math.ceil(this.total / this.pagesize) // 把当前页回到第一页 this.current = 1 // 从新渲染页面 this.setHtml() return } } } } /* for (let i = 1; i <= this.totalPage; i++) { str += `<p class="item ${ this.current === i ? 'active' : '' }">${ i }</p>` } */
"use strict"; exports.__esModule = true; function getCounter() { function counter(str) { } counter.title = '123'; counter.add = function (str) { }; return counter; } var counter = { title: '123', add: function (str1) { } }; var Sub = /** @class */ (function () { function Sub() { this.title = 'abc'; } Sub.prototype.add = function (str) { console.log(this.title + str); }; Sub.prototype.decerate = function (num) { return 1; }; return Sub; }()); exports["default"] = { run: function () { var sub = new Sub(); sub.add('-1234'); console.error(sub.decerate(1)); } };
import React from 'react' import {Form, Button} from 'semantic-ui-react'; import "../../index.css" class DogForm extends React.Component { constructor() { super() this.state = { name: '', age: '', breed: '' } } // keep state up-to-date as the form fills for any field handleChange = (event) => { this.setState({ [event.currentTarget.name]: event.currentTarget.value }) } // handle a form submission handleSubmit = (event) => { // prevent default form behavior of a screen refresh event.preventDefault() // call add dog in the main container to add the dog to state there // lift up state this.props.addDog(this.state) // reset state here to a blank form this.setState({ name: '', age: '', breed: '' }) } render() { // return HTML to render the edit form return( <div> <h3>Add your pet (or a friend's pet) to the list</h3> <Form className="dog-form" onSubmit={this.handleSubmit} > <Form.Field> <Form.Input type="text" name="name" placeholder="Enter name" value={this.state.name} onChange={this.handleChange} /> </Form.Field> <Form.Field> <Form.Input type="number" name="age" placeholder="Enter age" value={this.state.age} onChange={this.handleChange} /> </Form.Field> <Form.Field> <Form.Input type="text" name="breed" placeholder="Enter breed" value={this.state.breed} onChange={this.handleChange} /> </Form.Field> <Button>Add Pet</Button> </Form> </div> ) } } export default DogForm
import React from 'react' import { storiesOf } from '@storybook/react' import BlockHeading from './index' storiesOf('core|Components/Block Heading', module).add( 'with text content', () => <BlockHeading>Sample Content</BlockHeading>, { info: 'Demonstates basic usage with text content', } )
export function makeAbsoluteURL(url) { return url.startsWith('http://') ? url : 'http://theatrics.ru' + url; }
import React, { Component } from 'react'; //import { connect } from "react-redux" import Modal from 'react-responsive-modal'; import Datetime from 'react-datetime'; // import Select from 'react-select'; import Joi from 'joi-browser'; import Input from './helper/input'; import TextArea from './helper/textArea'; import SelectCustom from "./helper/select"; //import { getNotification } from './calendarAction'; import { saveChatNotificationDetails } from '../../../database/dal/firebase/chatNotificationDal'; import './calendar.css'; class CalendarModal extends Component { state = { data: { datetime: '', duration: '', message: '' }, errors: {} }; componentDidMount() { const loggedInUSer = JSON.parse(localStorage.getItem('user')); console.log(loggedInUSer); } schema = { datetime: Joi.allow('').allow(null) .label('Date Time'), duration: Joi.string() .required() .label('Duration'), message: Joi.string() .required() .label('Message') }; validate = () => { const options = { abortEarly: false }; const { error } = Joi.validate(this.state.data, this.schema, options); if (!error) return null; const errors = {}; for (let item of error.details) errors[item.path[0]] = item.message; return errors; }; validateProperty = ({ name, value }) => { const obj = { [name]: value }; const schema = { [name]: this.schema[name] }; const { error } = Joi.validate(obj, schema); return error ? error.details[0].message : null; }; randomString(length) { var text = ''; var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (var i = 0; i < length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } validateCalendar = () => { const errors = {}; const dateField = "datetime"; const { datetime } = { ...this.state.data }; if (!datetime) { delete errors[dateField]; errors[dateField] = "Date and Time can not be blank."; } else { if (datetime < Date.now()) { delete errors[dateField]; errors[dateField] = "Selected date should be of future date."; } } return errors; } handleSubmit = e => { const randomString = this.randomString(20); e.preventDefault(); const validateErrors = this.validate(); const calendarError = this.validateCalendar(); const errors = { ...validateErrors, ...calendarError } this.setState({ errors: errors || {} }); if (Object.keys(errors).length !== 0) { return } //if (errors) return; const { data } = this.state; //console.log(new Date(data.datetime).toUTCString()) //const scheduledDate = new Date(data.datetime).toUTCString(); //const myDate = new Date(1000 * data.datetime); //console.log(myDate.toUTCString()); const createdAt = new Date(); const loggedInUSer = JSON.parse(localStorage.getItem('user')); console.log("loggedInUSer => ", loggedInUSer); console.log("this.props.teacherData.userId => ", this.props.teacherData.userId) console.log("randomString", randomString) if (loggedInUSer) { const chatNotificationDetails = { nId: randomString, charge: '3$', createdAt, details: data.message, paymentStatus: false, reschedule: true, sId: loggedInUSer.user.uid, sStatus: true, tId: this.props.teacherData.userId, tStatus: true, status: -1, deleted: false, reqForReSchedule: false, // reschedule: false, comment: [ { by: loggedInUSer.user.uid, date: createdAt, details: data.message } ], scheduleDate: data.datetime, duration: data.duration }; saveChatNotificationDetails({ ...chatNotificationDetails }); //this.props.history.push('/dashboard'); //model close display message success or failure } this.props.closeCalendarModal(); }; handleChange = ({ currentTarget: input }) => { if (input) { const errors = { ...this.state.errors }; const errorMessage = this.validateProperty(input); if (errorMessage) errors[input.name] = errorMessage; else delete errors[input.name]; const data = { ...this.state.data }; data[input.name] = input.value; this.setState({ data, errors }); } }; handleChange1 = (obj) => { const dateField = "datetime"; const data = { ...this.state.data }; //data[dateField] = new Date(obj).toISOString(); console.log(obj._d); data[dateField] = Date.parse(obj._d); this.setState({ data }); }; onCloseModal = () => { this.props.closeCalendarModal(); }; render() { const { firstName, lastName } = this.props.teacherData; const openModal = this.props.modalState; return ( <div> <Modal open={openModal} onClose={this.onCloseModal} classNames={{ modal: this.props.classes }} > <form onSubmit={this.handleSubmit}> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal" aria-hidden="true" /> <h4 className="modal-title" id="myModalLabel"> Send Chat Notification to {firstName} {lastName}{' '} </h4> </div> <div className="modal-body"> <div className="row"> <div className="col-md-6 ">Pick Date and Time</div> <div className="col-md-6">Select a duration</div> </div> <div className="row"> <div className="col-md-6"> <Datetime value={this.state.datetime} onChange={this.handleChange1} inputProps={{ placeholder: 'Please choose date and time', name: 'datetime', id: 'datetime', className: 'form-control', readOnly: true }} /> <div className="c-error">{this.state.errors.datetime}</div> {/* <Input value={this.state.datetime} onChangeHandle={this.handleChange} name="datetime" className="form-control" errorMessage={this.state.errors.datetime} placeHolder="04/20/2019 12:00 AM" /> */} </div> <div className="col-md-6"> <SelectCustom value={this.state.duration} onChangeHandle={this.handleChange} name="duration" className="form-control" errorMessage={this.state.errors.duration} placeHolder="Duration"></SelectCustom> {/* <Input value={this.state.duration} onChangeHandle={this.handleChange} name="duration" className="form-control" errorMessage={this.state.errors.duration} placeHolder="Duration" /> */} </div> </div> <div className="row"> <div className="col-md-12">Message</div> <div className="col-md-12"> <TextArea value={this.state.message} onChangeHandle={this.handleChange} name="message" className="form-control" errorMessage={this.state.errors.message} placeHolder="Message" /> </div> </div> </div> <div className="modal-footer"> <button type="submit" className="btn btn-success" data-dismiss="modal" > Request </button> <input onClick={this.onCloseModal} type="button" className="btn btn-danger" value="Cancel" /> </div> </div> </form> </Modal> </div> ); } } export default CalendarModal;
import router from '../router' import store from '../store' const USERLOGIN = 'loginStatus' //获取登录状态 export function getStatus() { return localStorage.getItem(USERLOGIN) } //设置登录状态 export function setStatus(status) { localStorage.setItem(USERLOGIN, status) } //移除登录状态 export function removeStatus() { localStorage.removeItem('loginStatus') } //从本地缓存获取token export function getToken() { let token = JSON.parse(localStorage.getItem("TOKEN_KEY")) return token } //存入token export function setToken(token) { localStorage.setItem("TOKEN_KEY", JSON.stringify(token)) } //移除本地token export function removeToken() { localStorage.removeItem('TOKEN_KEY') } //判断登录状态 export function checkLogin() { if (store.state.loginStatus) { return true } else { router.push({path: '/login'}) return false } }
import { StyleSheet } from 'react-native' export default StyleSheet.create({ T1: { fontSize: 20, }, T2: { fontSize: 18, }, T3: { fontSize: 16, }, T4: { fontSize: 14, }, T5: { fontSize: 12, }, })
const mongoose = require('mongoose'); const Job = require('../models/job'); const Client = require('../models/client'); // post clients/add exports.addClient = async (req, res) => { const client = new Client({ name: req.body.name, email: req.body.email, phone: req.body.phone, jobs: [], }) await client.save(err => { if (err) console.log(err); }); res.setHeader('Content-Type', 'application/json'); res.json(''); } // get /clients/all-by-name exports.getAllClientNames = async (req, res) => { const clientNames = await Client.find({}).select('name'); res.setHeader('Content-Type', 'application/json'); res.json(clientNames); } // get /clients/:clientId exports.getClientById = async (req, res) => { const client = await Client.findOne({_id: req.params.clientId}).populate('jobs', 'job_no'); res.json(client); } exports.getClients = async (req, res) => { let query = Client.find({}).populate('jobs'); if (req.query.filter) { query.select(req.query.filter) } response = await query.exec(); res.setHeader('Content-Type', 'application/json'); res.json(response); }
import React from "react" class Card extends React.Component { constructor(props) { super(props) this.state = ({ image: this.props.src, faceUp: true }) } flip() { // use this form of setState since updates might be asynchronous // see: https://facebook.github.io/react/docs/state-and-lifecycle.html this.setState((prevState, props) => { this.props.registerFlip(props.index) return ({ image: (prevState.image === props.src) ? "x.svg" : props.src, faceUp: !prevState.faceUp }) }) } render() { return ( <div className="card"><img src={this.state.image} onClick={this.flip.bind(this)}/></div> ) } } export default Card
import React from 'react'; import { Link } from 'react-router'; /** * React component implementation. * * @author dfilipovic * @namespace ReactApp * @class TopRow * @extends ReactApp */ const TopRow = (props) => ( <header className="bg-grad-stellar mt70"> <div className="container"> <div className="row mt20 mb30"> <div className="col-md-6 text-left"> <h3 className="color-light text-uppercase" data-animation="fadeInUp" data-animation-delay="100"> Blog Post Read <small className="color-light alpha7">some notes.</small> </h3> </div> <div className="col-md-6 text-right pt35"> <ul className="breadcrumb"> <li> <Link to={'/'} > Home </Link> </li> <li> <Link to={'/blog'} > Blog </Link> </li> <li>{props.postTitle}</li> </ul> </div> </div> </div> </header> ); TopRow.propTypes = { postTitle: React.PropTypes.string }; TopRow.defaultProps = { postTitle: '' }; export default TopRow;
var questionCounter = 0; var selecterAnswer; var correctTally = 0; var incorrectTally = 0; var unansweredTally = 0; var questionArray = [ questions[0] = "What was Jason Voorhees' original mask?", questions[1] = "In what movie did Johnny Depp make his acting debut?", questions[2] = "Michael Myers received a roundhouse kick from which famous rapper?", questions[3] = "Which horror movie featured a member from pop-group New Kids on the Block?" ]; for (var i = 0; i < questions.length; i++) { $('#mainArea').text(questions[i]); } var answerArray = [ answers[0] = "Clown Mask", "Potato Sack", "Hockey Mask", "A Sheet with Holes for Eyes", answers[1] = "Hellraiser", "Gremlins", "The Lost Boys", "A Nightmare on Elm Street", answers[2] = "Vanilla Ice", "2Pac", "Busta Rhymes", "The Entire Wu-Tang Clan", answers[3] = "Saw 2", "I Know What You Did Last Summer", "Urban Legend", "Scream" ]; for (var i = 0; i < answers.length; i++) { var button = $('<button>'); button.text(answers[i]); button.appendTo('#buttons'); } var imageArray = [ imageArray[0] = "<img class='center-block' src='/TriviaGame/assets/images/FT13.gif'>", imageArray[1] = "<img class='center-block' src='/TriviaGame/assets/images/NES.gif'>", imageArray[2] = "<img class='center-block' src='/TriviaGame/assets/images/brroundhouse.gif'>", imageArray[3] = "<img class='center-block' src='/TriviaGame/assets/images/Saw2.gif'>" ]; for (var i = 0; i < imageArray.length; i++) { var button = $('<button>'); $('#result').text(imageArray[i]); button.appendTo('#result'); } var correctAnswers = [ correctAnswers[0] = "B. Potato Sack", correctAnswers[1] = "D. A Nightmare on Elm Street", correctAnswers[2] = "C. Busta Rhymes", correctAnswers[3] = "A. Saw 2" ]; for (var i = 0; i < correctAnswers.length; i++) { $('#result').text(correctAnswers[i]); } function openingPage() { openScreen = "<button>DO NOT ENTER</button>"; $("#start-button").append(openScreen); }; openingPage(); $("body").on("click", "#start-button", function (event) { event.preventDefault(); generateQuestions(); timerWrapper(); }); $("body").on("click", "#buttons", function (event) { selectedAnswer = $(this).text(); if (selectedAnswer === correctAnswers[questionCounter]) { clearInterval(theClock), generateWin() } else { clearInterval(theClock), generateLoss() }; $("body").on("click", ".reset-button", function (event) { clickSound.play(); resetGame(); }); function timeoutLoss() { unansweredTally++; gameHTML = "<p class='text-center timer-p'>Time Remaining: <span class='timer'>" + counter + "</span></p>" + "<p class='text-center'>You ran out of time! The correct answer was: " + correctAnswers[questionCounter] + "</p>" + "<img class='center-block img-wrong' src='/assets/images/x.gif'>"; $("#start-button").text(gameHTML); setTimeout(wait, 3000); }; function generateWin() { correctTally++; gameHTML = "<p class='text-center timer-p'>Time Remaining: <span class='timer'>" + counter + "</span></p>" + "<p class='text-center'>Correct! The answer is: " + correctAnswers[questionCounter] + "</p>" + imageArray[questionCounter]; $("#mainArea").text(gameHTML); setTimeout(wait, 3000); }; function generateLoss() { incorrectTally++; gameHTML = "<p class='text-center timer-p'>Time Remaining: <span class='timer'>" + counter + "</span></p>" + "<p class='text-center'>Wrong! The correct answer is: " + correctAnswers[questionCounter] + "</p>" + "<img class='center-block img-wrong' src='/assets/images/x.gif'>"; $("#mainArea").text(gameHTML); setTimeout(wait, 3000); }; function generateQuestions() { gameHTML = "<p class='text-center timer-p'>Time Remaining: <span class='timer'>30</span></p>" + questionArray[questionCounter] + "</p><p class='first-answer answer'>A. " + answerArray[questionCounter][0] + "</p><p class='answer'>B. " + answerArray[questionCounter][1] + "</p><p class='answer'>C. " + answerArray[questionCounter][2] + "</p><p class='answer'>D. " + answerArray[questionCounter][3] + "</p>"; $("#buttons").text(gameHTML); }; function wait() { questionCounter < 4 ? (questionCounter++ , generateQuestions(), counter = 30, timerWrapper()) : (finalScreen()) }; function timerWrapper() { theClock = setInterval(thirtySeconds, 1000); function thirtySeconds() { if (counter === 0) { clearInterval(theClock); timeoutLoss(); } if (counter > 0) { counter--; } $("#timer").text(counter); } }; function finalScreen() { gameHTML = "<p class='text-center timer-p'>Time Remaining: <span class='timer'>" + counter + "</span></p>" + "<p class='text-center'>All done, here's how you did!" + "</p>" + "<p class='summary-correct'>Correct Answers: " + correctTally + "</p>" + "<p>Wrong Answers: " + incorrectTally + "</p>" + "<p>Unanswered: " + unansweredTally + "</p>" + "<p class='text-center reset-button-container'><a class='btn btn-warning btn-md btn-block reset-button' href='#' role='button'>Reset The Quiz!</a></p>"; $("#mainArea").text(gameHTML); }; function resetGame() { questionCounter = 0; correctTally = 0; incorrectTally = 0; unansweredTally = 0; counter = 30; generateQuestions(); timerWrapper(); };
import React, { useState } from 'react'; import { Button, Form, Grid, ModalHeader, } from 'semantic-ui-react'; import { ChromePicker } from 'react-color'; import type Pillar from '../types/Pillar'; import { LOADING_TIME } from '../Constants'; import { deepCopyPillar } from '../logic/PillarHelper'; import { convertHexToHSL } from '../logic/ColorHelper'; type Props = { pillar: Pillar, closeView: () => void, editPillarRedux: (Pillar) => void, deletePillarRedux: () => void, }; const generateField = (label, placeholder, value, setValue, editing) => ( <Grid.Row> {!editing ? ( [ <ModalHeader as="h5">{label}</ModalHeader>, <ModalHeader as="h2">{value}</ModalHeader>, ] ) : ( <ModalHeader as="h4"> <Form.Input fluid value={value} type="text" label={label} name={label} placeholder={placeholder} onChange={(v) => setValue(v.target.value)} /> </ModalHeader> )} </Grid.Row> ); /** * Gets the color for the text identifying the Pillar. * * @param {string} color The hex string for the color of the Pillar. * @return {string} The color for the text of the pillar. */ const getTextColor = (color) => { const hsl = convertHexToHSL(color); if (hsl[2] > 50) { return 'black'; } return 'white'; }; /** * This view displays the actual details of the specified pillar. These details include both editable attributes and the * specific actions that one can take on the pillar. * * @param {Pillar} pillar The pillar to display the information with. * @param {Function} closeView Callback function to close the view with. * @param {Function} editPillarRedux The redux function to edit this pillar. * @param {Function} deletePillarRedux The redux function to delete this specific pillar. * @returns {*} The jsx to display the view. * @constructor */ const PillarDescriptionView = ({ pillar, closeView, editPillarRedux, deletePillarRedux, }: Props) => { const [currentPillar, setCurrentPillar] = useState(deepCopyPillar(pillar)); const [isEditing, setIsEditing] = useState(false); const [deleteIsLoading, setDeleteIsLoading] = useState(false); const setPillarValue = (n, v) => setCurrentPillar((p) => { const c = deepCopyPillar(p); c[n] = v; return c; }); return ( <Grid rows="equal" stretched> {generateField( 'Name', 'Name For The Pillar', currentPillar.name, (v) => setPillarValue('name', v), isEditing, )} {generateField( 'Description', 'Description For The Pillar', currentPillar.description, (v) => setPillarValue('description', v), isEditing, )} <Grid.Row> <label>Color:</label> {isEditing ? ( <ChromePicker color={currentPillar.color} onChangeComplete={(c) => setPillarValue('color', c.hex)} disableAlpha /> ) : ( <div style={{ background: pillar.color, textAlign: 'center', color: getTextColor(pillar.color), }} > {pillar.color} </div> )} </Grid.Row> <Grid.Row> <Button primary={!isEditing} icon={isEditing ? 'save' : 'pencil'} onClick={() => { isEditing && editPillarRedux(currentPillar); setIsEditing((p) => !p); }} /> </Grid.Row> <Grid.Row> <Button primary negative loading={deleteIsLoading} onClick={() => { setDeleteIsLoading(true); setTimeout(() => { deletePillarRedux(); closeView(); setDeleteIsLoading(false); }, LOADING_TIME); }} > Delete </Button> </Grid.Row> </Grid> ); }; export default PillarDescriptionView;
_.Error = { get: function(type) { var err; switch (type) { case "PRODUCER_MISSING": err = "Please fill the producer name"; break; } return err; } }; function error(type) { return _.Error.get(type); }
"use strict"; let money,time; function start() { money = +prompt("Ваш бюджет на месяц?", ""); time = prompt("Введите дату в формате YYYY-MM-DD", ""); while (isNaN(money) || money == "" || money == null ) { money = +prompt("Ваш бюджет на месяц?", ""); } } start(); let appData = { budget: money, expenses: {}, optionalExpenses: {}, income: [], timeData: time, savings: true, chooseExpenses: function() { for (let i = 0; i < 2; i++) { let a = prompt("Введите обязательную статью расходов?", ""), b = +prompt("Во сколько это обойдется?", ""); if ((typeof(a)) === 'string' && (typeof(a)) != null && (typeof(b)) != null && a !='' && b !='' && a.length < 50) { console.log("done"); appData.expenses[a] = b; } else { i--; } } }, detectDayBudget: function() { appData.moneyPerDay = (appData.budget / 30).toFixed(2); alert("Ежедневный бюджет: " + appData.moneyPerDay); }, detectLevel: function() { if(appData.moneyPerDay < 100) { console.log("Ваш доход минимален") } else if(appData.moneyPerDay > 100 && appData.moneyPerDay < 1000) { console.log("Средний уровень достатка") } else if(appData.moneyPerDay > 1000) { console.log("Высокий достаток") } else { console.log("ошибка") } }, checkSavings: function() { if (appData.savings == true) { let save = +prompt("Какова сумма накоплений?", ""), percent = +prompt("Под какой процент?", ""); appData.monthIncome = save/100/12*percent; alert("Доход в месяц с вашего депозита: " + appData.monthIncome); } }, chooseOptExpenses: function() { for (let i = 1; i < 4; ++i){ let a = prompt("Статья необязательных расходов", ""); if ((typeof(a)) === 'string' && (typeof(a)) !=null && a !='' ) { appData.optionalExpenses[i] = a; } } }, chooseIncome: function() { let items = prompt("Укажите дополнительный источник дохода? (Укажите через запятую)", ""); if (typeof(items) !="string" || items =="" || items ==null) { console.log("Данные указаны некорректно"); } else { appData.income = items.split(', '); appData.income.push(prompt("Может что-то еще?")); appData.income.sort(); } appData.income.forEach(function(source, i) { alert("Способы доп заработка: " + (i+1) + " - " + source); }); } }; for (let key in appData) { console.log("Наша программа включает в себя данные: " + key + " - " + appData[key]); } /* let i = 0; while (i<2) { i++; let a = prompt("Введите обязательную статью расходов?", ""), b = +prompt("Во сколько это обойдется?", ""); if (typeof(a) === 'string' && typeof(a) != null && typeof(b) != null && a !=='' && b !=='' && a.length < 50); { console.log("done"); appData.expenses[a] = b; } } */ /* let i = 0; do { let a = prompt("Введите обязательную статью расходов?", ""), b = +prompt("Во сколько это обойдется?", ""); if (typeof(a) === 'string' && typeof(a) != null && typeof(b) != null && a !=='' && b !=='' && a.length < 50); { console.log("done"); appData.expenses[a] = b; }; i++; } while (i <2); */ /* if (2*4 == 8) { console.log("Верно") } */ /* if (2*4 == 9) { console.log("Верно") } else { console.log("Неверно") } */ /* let num = 50; if (num < 49) { console.log("Неверно") } else if (num > 100) { console.log("Много") } else { console.log("Почти") }; */ /* let num = 50; (num == 50) ? console.log("Верно") : console.log("Неверно"); */ /* let num = 101; switch (num) { case num < 49: console.log("неверно"); break; case num > 100: console.log("Много"); break; case num > 80: console.log("Все еще много"); break; case 50: console.log("Верно!"); break; default: console.log("Ошибка"); break; } */ /* let num = 50; while (num < 55) { console.log(num); num++; } */ /* let num = 50; do { console.log(num); num++; } while (num < 55); */ /* for (let i = 1; i < 8; i++) { if (i == 6) { break; continue; } console.log(i); } */
const bs = require('browser-sync').create(); bs.init({ server: { baseDir: "./public" }, watchOptions: { ignoreInitial: true, ignored: '*.txt' }, files: ['./public'], host: 'localhost', port: 7301, logPrefix: "webpack", logLevel: "info", reloadDelay: 1500, //tunnel: "webpack", serveStatic: ['./public'], ui: { port: 8080 }, ghostMode: false });
import React, {useState, useEffect} from 'react'; import {connect} from 'react-redux'; import {getCategory} from '../redux/reducer'; import {withRouter} from 'react-router'; import CurrencyInput from 'react-currency-input'; const Categories = (props) => { const onInputChange = (float, mask, e) => { e.target.value = e.target.value.substring(1); props.updatePercent(props.index, +e.target.value) } return( <div className='mini-main'> <CurrencyInput id='currency' value={props.category_allocated} onChange={onInputChange} prefix="%" precision={0} className='edit-allocated'/> <h1 className='name-percent'>{props.category_name}</h1> <h1 className='mini-gray'> ${(props.category_balance.toFixed(2))} </h1> </div> ) } const mapStateToProps = (reduxState) => { return reduxState } export default connect (mapStateToProps, {getCategory})(withRouter(Categories));
(function () { 'use strict'; var Orders = require('../src/Orders'); var Fees = require('../src/Fees'); describe("Orders tests", function () { var mockOrderItems, mockFlattenedFees, mockFees; beforeEach(function () { mockOrderItems = [ { "order_item_id": 1, "type": "Real Property Recording", "pages": 3 }, { "order_item_id": 2, "type": "Real Property Recording", "pages": 1 }, { "order_item_id": 3, "type": "Birth Certificate", "pages": 1 } ]; mockFlattenedFees = { "Real Property Recording": { "flat": {'amount':'26.00'}, "per-page": {'amount':'1.00'} }, "Birth Certificate": { "flat": {'amount':'26.00'} } }; mockFees = [ { "order_item_type": "Real Property Recording", "fees": [ { "name": "Recording (first page)", "amount": "26.00", "type": "flat" }, { "name": "Recording (additional pages)", "amount": "1.00", "type": "per-page" } ], "distributions": [ { "name": "Recording Fee", "amount": "5.00" }, { "name": "Records Management and Preservation Fee", "amount": "10.00" }, { "name": "Records Archive Fee", "amount": "10.00" }, { "name": "Courthouse Security", "amount": "1.00" } ] }, { "order_item_type": "Birth Certificate", "fees": [ { "name": "Birth Certificate Fees", "amount": "23.00", "type": "flat" } ], "distributions": [ { "name": "County Clerk Fee", "amount": "20.00" }, { "name": "Vital Statistics Fee", "amount": "1.00" }, { "name": "Vital Statistics Preservation Fee", "amount": "1.00" } ] } ]; }); it("should return an order with calculated prices along with types", function () { var main, result, expected; expected = [ {"Order item Real Property Recording": "$28.00"}, {"Order item Real Property Recording": "$26.00"}, {"Order item Birth Certificate": "$26.00"} ]; result = Orders.calculateFee(mockOrderItems, mockFlattenedFees); expect(result).toEqual(expected); }); it("should return a calculation based on fees for a multipage order", function(){ var result; result = Orders.multiPageCalculation(mockOrderItems[0],mockFlattenedFees); expect(result).toBe("$28.00"); }); it("should return a calculation based on fees for a singlepage order", function(){ var result; result = Orders.singlePageCalculation(mockOrderItems[2], mockFlattenedFees); expect(result).toBe("$26.00") }); it("should calculate the order total for a list of order items", function(){ var testData, expected, result; testData = [ {"Order item (Real Property Recording)": "$28.00"}, {"Order item (Real Property Recording)": "$26.00"}, {"Order item (Birth Certificate)": "$26.00"} ]; expected = {'Order Total':'$80.00'}; result = Orders.calculateOrderTotal(testData); expect(result).toEqual(expected); }); it("should return a dollar amount from a number", function(){ var result; result = Orders.convertNumToCurrency(10); expect(result).toEqual('$10.00'); }); }); })();
"use strict"; let argv = require('yargs').argv, gulp = require('gulp'), concat = require('gulp-concat'), include = require('gulp-include'), pug = require('gulp-pug'), replace = require('gulp-replace'), stylus = require('gulp-stylus'), uglify = require('gulp-uglify'), browserify = require('browserify'), cleanCss = require('gulp-clean-css'), autoprefixer = require('gulp-autoprefixer'), rsync = require('gulp-rsync'), print = require('gulp-print'), sourcemaps = require('gulp-sourcemaps'), runSequence = require('run-sequence'), babel = require("gulp-babel"), shell = require('gulp-shell'), GulpSSH = require('gulp-ssh'), //sprite = require('gulp-node-spritesheet'), source = require('vinyl-source-stream'), buffer = require('vinyl-buffer'), gutil = require('gulp-util'), babelify = require('babelify'), browserify_shim = require('browserify-shim'); let fs = require('fs'); let del = require('del'); let path = require('path'); let extend = require('node.extend'); let BASEURL = argv.production ? 'http://alexnortn.com/' : ''; gulp.task('default', ['build']); // Removed "pug" gulp.task('build', [ 'images', 'js', 'css', 'fonts', 'plugins']); gulp.task('images', [ ], function () { gulp .src('./assets/images/**') .pipe(gulp.dest('./public/images/')); gulp .src('./assets/favicon*') .pipe(gulp.dest('./public/')); }); gulp.task('clean', function () { del([ './public/**' ]); }); // Compile pug --> HTML gulp.task('pug', function() { return gulp.src('views/**/*.pug') .pipe(pug({ client: true, })) // replace the function definition .pipe(replace('function template(locals)', 'module.exports = function(locals, pug)')) .pipe(gulp.dest('./public/views_js')) }); gulp.task('js', function () { let b = browserify({ entries: 'clientjs/entry.js', //debug: true, // defining transforms here will avoid crashing your stream transform: [ babelify, browserify_shim ], }); let stream = b.bundle() .pipe(source('bundle.min.js')) .pipe(buffer()) .pipe(replace(/__BASE_URL/g, `'${BASEURL}'`)); if (argv.production) { stream .pipe(sourcemaps.init()) .pipe(uglify()) .pipe(sourcemaps.write('./')) } return stream .pipe(gulp.dest('./public/js/')); }); gulp.task('css', [ ], function () { gulp.src([ 'assets/css/normalize.css', 'assets/css/main.styl', 'assets/css/*.css', ]) .pipe(concat('all.styl')) .pipe(stylus()) .pipe(replace(/\$GULP_BASE_URL/g, BASEURL)) .pipe(autoprefixer({ browser: "> 1%, last 2 versions, Firefox ESR" })) .pipe(cleanCss()) .pipe(gulp.dest('./public/css/')) }); gulp.task('fonts', function () { gulp.src([ 'assets/fonts/**' ]) .pipe(gulp.dest('./public/fonts/')) }) gulp.task('plugins', function () { gulp.src([ 'assets/plugins/**' ]) .pipe(gulp.dest('./public/plugins/')) }) gulp.task('watch', function () { gulp.watch([ 'assets/animations/**' ], [ 'animations' ]); gulp.watch([ 'assets/fonts/**' ], [ 'fonts' ]); gulp.watch([ 'assets/plugins/**' ], [ 'plugins' ]); gulp.watch([ 'assets/css/*' ], [ 'css' ]); gulp.watch([ 'assets/images/**' ], [ 'images' ]); gulp.watch([ 'clientjs/**', 'components/**' ], [ 'js' ]); gulp.watch([ 'views/**', ], [ 'pug' ]); }); // Only CSS + PUG + IMAGES (conserve juice) gulp.task('watch-lite', function () { gulp.watch([ 'assets/css/*' ], [ 'css' ]); gulp.watch([ 'assets/images/**' ], [ 'images' ]); gulp.watch([ 'views/**', ], [ 'pug' ]); });
#!/usr/bin/env node const path = require("path"); const fs = require("fs"); const YAML = require("yamljs"); const Handlebars = require("handlebars"); const program = require("commander"); program .version("1.0.0") .option("-o, --output <path>", "Docusaurus output documents path", "./docs") .option("-w, --website <path>", "Docusaurus website folder", "./website") ; var options = {}; var config = { "markdownExtension": ".md", "templateExtension": ".handlebars", "templates": "./templates", "extension": ".yaml" } program.parse(process.argv); let fn = (program.args.length > 0) ? program.args[0] : "yaml-to-docusaurus"; loadConfiguration(); fn = setMissingExtension(fn, config.extension); options = applyDefaultOptions(program.opts()); execute(fn); function execute(outlineFilename) { var doc = YAML.parse(fs.readFileSync(outlineFilename, "utf8")); var topics = doc.topics; // Generate topic markdown files if (!fs.existsSync(options.output)) { fs.mkdirSync(options.output); } generateDocuments(topics); // Generate sidebar.json in ./website folder if (!fs.existsSync(options.website)) { fs.mkdirSync(options.website) } generateSidebar(topics); } function generateSidebarFolders(topics) { let folders = []; let folder = {"title": "", "slugs": [], "last": "", "done": false, "folders": []}; topics.forEach(topic => { if (topic.folder) { folder.last = folder.slugs.pop(); if (folder.title.length > 0) { folders.push(folder); } let folderTitle = topic.title; folder = {"title": folderTitle, "slugs": [], "last": "", "done": false, "folders": []}; } folder.slugs.push(getTopicBasename(topic)); if (topic.topics) { topic.topics.forEach(childTopic => { folder.slugs.push(getTopicBasename(childTopic)); }); } }) if (!folder.done) { folder.last = folder.slugs.pop(); folder.done = true; folders.push(folder); } return folders; } function generateSidebar(topics) { let data = {}; data.folders = generateSidebarFolders(topics); data.last = data.folders.pop(); let result = generateFromTemplate("sidebars-template", data); let sidebarFilename = [options.website, "sidebars.json"].join("\\"); fs.writeFileSync(sidebarFilename, result, "utf8"); } function generateFromTemplate(templateBasename, data) { let tfn = setMissingExtension(templateBasename, config.templateExtension); tfn = [config.templates, tfn].join("\\"); let template = Handlebars.compile(fs.readFileSync(tfn, "utf8")); return template(data); } function generateHeaders(headers, level) { let content = ""; headers.forEach(header => { content += generateFromTemplate("header-template", { "headmark": "#".repeat(level), "title": header.title, "brief": header.brief, "content": (header.headers) ? generateHeaders(header.headers, level + 1) : "" }) }) return content; } function generateDocuments(topics) { topics.forEach(topic => { let data = {}; data.slug = getTopicBasename(topic); data.title = (topic.short) ? topic.short : topic.title; data.brief = topic.brief; data.content = (topic.headers) ? generateHeaders(topic.headers, 2) : ""; let result = generateFromTemplate("topic-template", data); writeDocument(topic, result); if (topic.topics) { generateDocuments(topic.topics); } }) } function getTopicBasename(topic) { let source = (topic.slug) ? topic.slug : (topic.short) ? topic.short : topic.title; return slug(source); } function getTopicFilename(topic) { let basename = getTopicBasename(topic); return setMissingExtension(basename, config.markdownExtension); } function slug(source) { // TODO: remove heading and trailing special characters // TODO: replace sequence of special characters with a single dash return source.trim().toLowerCase().replace(/ +/g, "-"); } function writeDocument(topic, body) { let filename = getTopicFilename(topic); filename = [options.output, filename].join("\\"); fs.writeFileSync(filename, body, "utf8"); } function applyDefaultOptions(opts) { return opts; } function loadConfiguration() { let fn = "yaml-to-docusaurus.json"; if (fs.existsSync(fn)) { config = JSON(fs.readFileSync(fn, "utf8")); } } function setMissingExtension(basename, extension) { let ext = path.extname(basename); if (ext.length == 0) { return basename.trim() + extension.trim(); } return basename.trim(); }
const express = require('express'); const fs = require('fs'); const router = express.Router(); var AdmZip = require('adm-zip'); const dbconnection = require('./../dataaccess/dbcontext'); const dbquery = require('./../dataaccess/query'); const multer = require('multer'); //const upload = multer({ dest: 'projects/' }); const storage = multer.diskStorage({ destination: function(req, file, callback) { callback(null, './projects'); }, filename: function(req, file, callback) { callback(null, (Math.floor(Date.now() / 1000) + '.' + file.originalname.split('.').pop())); //callback(null, file.filename); } }); const fileFilter = (request, file, callback) => { if(file.mimetype === 'application/x-zip-compressed') { callback(null, true); } else { callback(new Error('File extension is not supported'), false); } }; const upload = multer({ storage: storage, fileFilter: fileFilter }); var lamdas = require('./../models/lamda.js'); router.get('/:pageNumber/:pageSize', async (request, response) => { let pageSize = request.params.pageSize; let pageNumber = request.params.pageNumber; if(pageNumber == null ) pageNumber = 5; var queryGet = `SELECT * FROM lambda LIMIT ${pageSize} OFFSET ${pageNumber}`; var resultsGet; try { resultsGet = await dbquery(dbconnection, queryGet); } catch (error) { return response.status(500).json({message: error}); } var queryCount = `SELECT count(id) as count FROM lambda`; const resultsCount = await dbquery(dbconnection, queryCount); const result = {result: resultsGet, totalItems: resultsCount[0].count}; response.json(result); }); router.post('/triggerlambda/:trigger', async (request, response) => { var query = `SELECT * FROM lambda WHERE MATCH(_trigger) AGAINST ("%${request.params.trigger}%" IN NATURAL LANGUAGE MODE);`; const results = await dbquery(dbconnection, query); if(results.length <= 0) return response.status(400).json({msg: "Lambda not found"}) const result = results[0]; const lambdaProject = require('./../projects/' + result.name + '/' + result.handler); var lambdaResult; try { lambdaResult = lambdaProject[result.handler](request.body); } catch (error) { return response.status(500).json({message: error}); } var query = `UPDATE lambda SET invocations = invocations + 1 WHERE id = ${result.id}`; dbquery(dbconnection, query); response.status(200).json({data: lambdaResult}); }); router.post('/', async (request, response) => { var query = `INSERT INTO lambda (projectpath, name, handler, _trigger) VALUES ('/test/path/', '${request.body.name}', '${request.body.handler}', '${request.body._trigger}')`; try { const results = await dbquery(dbconnection, query); response.status(200).json({data: results.insertId}); } catch (error) { response.status(500).json({data: error}); } }); router.post('/uploadfile', upload.single('file') ,async (request, response) => { var zip = new AdmZip(request.file.path); zip.extractAllTo("./projects", true); var query = "INSERT INTO lambda (projectpath, name, handler, _trigger) VALUES ('projects/"+request.file.filename+"', '"+request.body.name+"', '"+request.body.handler+"', '"+request.body._trigger+"')"; try { const results = await dbquery(dbconnection, query); response.status(200).json({data: results.insertId}); } catch (error) { response.status(500).json({data: error}); } }); router.post('/removelambdas', async (request, response) => { var query; try { request.body.forEach(element => { query = `DELETE FROM lambda WHERE id = ${element};`; dbquery(dbconnection, query); }); response.status(200).json({data: "Successfully deleted"}); } catch (error) { response.status(500).json({data: error}); } }); module.exports = router;
const computePath = require('./utils').computePath module.exports = options => ({ entry: [computePath('../src/app.ts')], html: { template: computePath('../index.html') }, plugins: [ require('@poi/plugin-typescript')() ], publicPath: './', configureWebpack(config, context) { const tsLintRule = { test: /\.ts$/, enforce: 'pre', loader: 'tslint-loader', options: { formatter: 'stylish', configFile: computePath('./tslint.json') } } config.module.rules = config.module.rules.concat(tsLintRule) return config } })
import React from 'react'; import './ClockListItem.scss'; import AnalogClock from '../AnalogClock/AnalogClock'; const ClockListItem = ({clock, onDelete}) => { const getClockLabel = () => { if (clock.timezone) { const splitted = clock.timezone.split('/').reverse(); return ( splitted.map((item, index) => ( <span key={`${clock.id}_${item}`}>{item.replace('_', ' ')}</span> )) ); } return <span>Local time</span>; } return ( <li className="clock-list-item"> <button className="delete" onClick={e => onDelete(clock.id)}> <span aria-hidden="true">❌</span> <span className="visually-hidden">Delete</span> </button> <AnalogClock {...clock}/> <label htmlFor={clock.id}> {getClockLabel()} </label> </li> ) }; export default ClockListItem;
$(function(){ $('.carousel-item').eq(0).addClass('active'); var total = $('.carousel-item').length; var current = 0; $('#moveRight').on('click', function(){ var next=current; current= current+1; setSlide(next, current); }); $('#moveLeft').on('click', function(){ var prev=current; current = current- 1; setSlide(prev, current); }); function setSlide(prev, next){ var slide= current; if(next>total-1){ slide=0; current=0; } if(next<0){ slide=total - 1; current=total - 1; } $('.carousel-item').eq(prev).removeClass('active'); $('.carousel-item').eq(slide).addClass('active'); setTimeout(function(){ },400); console.log('current '+current); console.log('prev '+prev); } }); $(function(){ $('.work-carousel-item').eq(0).addClass('active'); var total = $('.work-carousel-item').length; var current = 0; $('#workMoveRight').on('click', function(){ var next=current; current= current+1; setSlide(next, current); }); $('#workMoveLeft').on('click', function(){ var prev=current; current = current- 1; setSlide(prev, current); }); function setSlide(prev, next){ var slide= current; if(next>total-1){ slide=0; current=0; } if(next<0){ slide=total - 1; current=total - 1; } $('.work-carousel-item').eq(prev).removeClass('active'); $('.work-carousel-item').eq(slide).addClass('active'); setTimeout(function(){ },800); console.log('current '+current); console.log('prev '+prev); } });
import actionTypes from './actionConstants'; const bankActionCreators = { depositIntoAccount(amount) { return { type: actionTypes.DEPOSIT_INTO_ACCOUNT, amount: amount }; }, withdrawFromAccount(amount) { return { type: actionTypes.WITHDRAW_FROM_ACCOUNT, amount: amount }; } }; export default bankActionCreators;
var express = require('express'), app = express(), XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var log = require('./logger').logger.getLogger("HTTP-Client"); var subscriptionService = require('../db/schemas/subscriptionService'), config = require('../config'), uuid = require('uuid'); // ip: {type: String, required: true}, // method: {type: String, required: true}, // url: {type: String, required: true}, // requestHeaders : {type: String, required: true}, // requestBody : {type: String, required: false}, // requestTimestamp : { type: Date, default: Date.now() }, // responseStatus : {type: String, required: true}, // responseHeaders: {type: String, required: false}, // responseBody: {type: String, required: false}, // //user: { type: String, required: true }, // //authToken: { type: String, required: true }, // responseTimestamp: { type: Date, default: Date.now() } var logService = require('../db/schemas/logService'); var logger = new logService(); exports.getClientIp = function(req, headers) { var ipAddress = req.connection.remoteAddress; var forwardedIpsStr = req.header('x-forwarded-for'); if (forwardedIpsStr) { // 'x-forwarded-for' header may return multiple IP addresses in // the format: "client IP, proxy 1 IP, proxy 2 IP" so take the // the first one forwardedIpsStr += "," + ipAddress; } else { forwardedIpsStr = "" + ipAddress; } headers['x-forwarded-for'] = forwardedIpsStr; return headers; }; exports.sendData = function(protocol, options, data, res, callBackOK, callbackError) { var xhr, body, result; options.headers = options.headers || {}; callbackError = callbackError || function(status, resp) { log.error("Error: ", status, resp); res.statusCode = status; if(config.logging){ logger.responseStatus = status; logger.responseBody = resp; logger.responseTimestamp = Date.now(); logger.save(function (err) { if (err) { log.error('New LOG Failed:', err); } else { log.debug('New LOG OK'); } }); } res.send(resp); }; callBackOK = callBackOK || function(status, resp, headers) { res.statusCode = status; var newSubscritpion = undefined; for (var idx in headers) { var header = headers[idx]; if(idx === 'location') newSubscritpion = header; res.setHeader(idx, headers[idx]); } if(config.logging){ log.debug("LOG Response:", status); logger.responseStatus = status; log.debug("LOG Headers:", JSON.stringify(headers)); logger.responseHeaders = JSON.stringify(headers); if(resp !== ""){ log.debug("LOG Body:", JSON.stringify(JSON.parse(resp))); logger.responseBody = JSON.stringify(JSON.parse(resp)); } logger.responseTimestamp = Date.now(); logger.save(function (err) { if (err) { log.error('New LOG Failed:', err); } else { log.debug('New LOG OK'); } }); } //check if new subscription and log if(config.rbac && (options.path === '/v2/subscriptions' || options.path === '/v2/subscriptions/') && newSubscritpion){ var service = new subscriptionService(); service.subscriptionId = newSubscritpion.split('/')[3]; service.user = options.headers['X-Nick-Name']; service.authToken = options.headers['x-auth-token']; service.save(function (err) { if (err) { log.error('New subscription LOG Failed:', err); } else { log.debug('New subscription LOG OK. Subscription ID:', newSubscritpion.split('/')[3], 'by user:', options.headers['X-Nick-Name']); } }); //log.error('New subscription with ID:', newSubscritpion.split('/')[3], 'by user:', options.headers['X-Nick-Name']); } res.send(resp); }; var url = protocol + "://" + options.host + ":" + options.port + options.path; xhr = new XMLHttpRequest(); if(config.logging){ logger = new logService(); logger.ip = options.headers['x-forwarded-for']; log.debug("LOG Method:", options.method); logger.method = options.method; log.debug("LOG URL:", options.path); logger.url = options.path; log.debug("LOG Request Headers:", options.headers); logger.requestHeaders = JSON.stringify(options.headers); logger.requestTimestamp = Date.now(); } xhr.open(options.method, url, true); if (options.headers["content-type"]) { xhr.setRequestHeader("Content-Type", options.headers["content-type"]); } for (var headerIdx in options.headers) { //log.error('headerIdx:', headerIdx, ':', options.headers[headerIdx]); switch (headerIdx) { // Unsafe headers case "host": case "connection": case "referer": // case "accept-encoding": // case "accept-charset": // case "cookie": case "content-type": case "origin": break; default: xhr.setRequestHeader(headerIdx, options.headers[headerIdx]); break; } } xhr.onerror = function(error) {} xhr.onreadystatechange = function () { // This resolves an error with Zombie.js if (flag) { return; } if (xhr.readyState === 4) { flag = true; if (xhr.status < 400) { var allHeaders = xhr.getAllResponseHeaders().split('\r\n'); var headers = {}; for (var h in allHeaders) { headers[allHeaders[h].split(': ')[0]] = allHeaders[h].split(': ')[1]; } callBackOK(xhr.status, xhr.responseText, headers); } else { callbackError(xhr.status, xhr.responseText); } } }; var flag = false; log.debug("Sending ", options.method, " to: " + url); log.debug("Headers: ", options.headers); log.debug("Body: ", data); if (data !== undefined) { //FIX for empty body (GET, DELETE) if (data.length === 0) { data = null; } else if (config.logging && options.path !== "/v3/auth/tokens"){ log.debug("LOG Request body:", JSON.stringify(JSON.parse(data))); logger.requestBody = JSON.stringify(JSON.parse(data)); } try { xhr.send(data); } catch (e) { callbackError(e.message); return; } } else { try { xhr.send(); } catch (e) { callbackError(e.message); return; } } }
function addNewLivechat(thing, livechat){ addNewThing(thing); things[thing.elemId].docId = livechat._id; let newLivechat = $('.livechat').clone(); newLivechat.removeClass('prototype'); newLivechat.css('display', 'flex'); $(`#${thing.elemId}`).append(newLivechat); livechat.messages.forEach((message) => { let newMessageElement = ` <div class='livechatMessage'> <div class='livechatSender'>${message.sender}:</div> <div class='livechatText'>${message.text}</div> </div> `; $(`#${thing.elemId}`).find('.livechatMessageContainer').append(newMessageElement); }) } function sendMessage(e) { let sender = $('#currentUserName').text(); let elemId = e.target.offsetParent.id; let content = $(`#${elemId}`).find('.livechatTextArea').val(); let dimensionName = $('#dimensionName').text(); let docId = things[elemId].docId; if(content.length > 0){ let message = { sender, content, elemId, dimensionName, docId } socket.emit("Send message", message); $('.livechatTextArea').val(""); $('.livechatTextArea').blur(); } } $(document).ready(() => { $(document).on('click', '.livechatSubmitMessage', (e) => { sendMessage(e); }) $(document).on('keypress', '.livechatTextArea', (e) => { if(e.keyCode == 13){ sendMessage(e); } }); }) socket.on('New livechat', data => { addNewLivechat(data.thing, data.livechat); }) socket.on('New message', message => { let newMessageElement = ` <div class='livechatMessage'> <div class='livechatSender'>${message.sender}</div> <div class='livechatText'>${message.content}</div> </div> `; let thisMessageContainer = $(`#${message.elemId}`).find('.livechatMessageContainer'); thisMessageContainer.append(newMessageElement); thisMessageContainer.scrollTop(thisMessageContainer[0].scrollHeight); })
'use strict'; /** * @ngdoc function * @name recnaleerfClientApp.controller:UserCtrl * @description * # UserCtrl * Controller of the recnaleerfClientApp */ angular.module('recnaleerfClientApp') .controller('menuCtrl', ['$scope','$location', 'UserSrv', '$ionicLoading','$state',function ($scope,$location,UserSrv,$ionicLoading,$state) { var userService = UserSrv; $scope.isLoggedIn = function() { return userService.isLoggedIn(); }; $scope.signin = function (user){ return userService.signin(user); }; $scope.logout = function () { return userService.logout(); }; $scope.signup = function (usr) { $ionicLoading.show(); $scope.signUpMessage = null; userService.signup(usr,$scope.signUpMessage,$scope.signUpSuccess) .then( function(newUser) { $scope.signUpSuccess = true; $scope.signUpMessage = 'User '+newUser.get('username')+' succesfully signed up'; console.log($scope.signUpMessage); $ionicLoading.hide(); $state.go('login'); }, function(value) { $scope.signUpSuccess = false; $scope.signUpMessage = 'User failed to signed up: '+value.error.code+':'+value.error.message;; console.log($scope.signUpMessage); $ionicLoading.hide(); } ); }; $scope.navClass = function (page) { var currentRoute = $location.path().substring(1) || ''; return page === currentRoute ? 'active' : ''; }; }]);
'use strict'; const { clone, camelCase } = require('../../../../node_modules/lodash'); const { errors } = require('../../../lib/constants'); const ServiceError = require('../../../lib/util/service-error.js'); const { supportedTypes } = require('../../../lib/repository/config-repository'); module.exports = (req, res, next) => { const type = camelCase(req.params.config); if (supportedTypes.includes(type)) { req.configQueryOptions = { type: type }; next(); } else { const error = clone(errors.malformedRequest); error.message = `Configuration type ${type} not supported`; next(new ServiceError(error)); } };
import React, { Component } from 'react'; import { AppRegistry, Text, View } from 'react-native'; import Database from '../../database/Database'; export default class LogoutComponent extends Component { static logoutUser = () => { Database.getItemWithChildPath (Database.firebaseRefs.userLocationsRef, `/${ Database.currentUser.uid }/`, (obj) => { if (Database.currentUser) { obj.logged_in = false; Database.addItemWithChildPath (Database.firebaseRefs.userLocationsRef, `/${ Database.currentUser.uid }/`, obj); Database.logout (() => { console.log ("Logged out"); }, () => { console.log ("Failure to log out"); }); } }) } render () { const { navigate } = this.props.navigation; return ( <View> <Text>This is the logout component</Text> </View> ); } } AppRegistry.registerComponent ('LogoutComponent', () => LogoutComponent);
document.addEventListener('DOMContentLoaded', Generator.welcome)
export { DetailCard } from './DetailCard';
import React, { Component } from 'react' import Square from './Squares' class GameBoard extends Component { constructor(props) { super(props); this.state = { previousBoard: Array(9).fill(null), board: Array(9).fill(null), xTurn: true, undoDisabled: true, restartDisabled: true, } } renderSquare(i) { return <Square value={this.state.board[i]} onClick={() => this.handleClick(i)} /> } handleClick(i) { const board = this.state.board.slice(); this.setState({ previousBoard: this.state.board, }); if (winner(board) || board[i]) { return; } board[i] = this.state.xTurn ? 'X' : 'O'; this.setState({ board: board, xTurn: !this.state.xTurn, undoDisabled: false, restartDisabled: false }); } handleRestart() { const board = this.state.board; for (let i = 0; i < board.length; i++) { board[i] = null; } this.setState({ board: board, xTurn: true, undoDisabled: true, restartDisabled: true }) } handleUndo() { console.log(this.state.previousBoard) this.setState({ board: this.state.previousBoard, xTurn: !this.state.xTurn, }); this.setState({ undoDisabled: true }); } render() { const win = winner(this.state.board); let turn; let gameStatus; if (win && win !== 'draw') { turn = "Player " + win.winner[0] + " Wins!" gameStatus = "Play Again!" } else if (win && win === 'draw') { turn = "It's a Draw!" gameStatus = "Play Again!" } else { turn = "Player " + (this.state.xTurn ? 'X' : 'O') + " Turn!" gameStatus = "Restart!" } return ( <div className="board"> <p className="turn">{turn}</p> <div className="row"> {this.renderSquare(0)} {this.renderSquare(1)} {this.renderSquare(2)} </div> <div className="row"> {this.renderSquare(3)} {this.renderSquare(4)} {this.renderSquare(5)} </div> <div className="row"> {this.renderSquare(6)} {this.renderSquare(7)} {this.renderSquare(8)} </div> <div className="button-row"> <button ref={undoBtn => { this.undoBtn = undoBtn; }} className="undo" onClick={() => this.handleUndo()} disabled={this.state.undoDisabled} > Undo Move </button> <button ref={rematchBtn => { this.rematchBtn = rematchBtn; }} className="restart" onClick={() => this.handleRestart()} disabled={this.state.restartDisabled} > {gameStatus} </button> </div> </div> ) } } function winner(board) { const winCons = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let i = 0; i < winCons.length; i++) { const [a, b, c] = winCons[i]; if (board[a] && board[a] === board[b] && board[a] === board[c]) { return { winner: board[a], line: [a, b, c] }; } } for (let i = 0; i < board.length; i++) { if (board[i] == null) { return null } } return 'draw'; } export default GameBoard;
import React from 'react'; import './Aside.scss'; const Aside = () => { return ( <aside className="react-aside"> <h2>DAYRY APP</h2> <div>Comment whit no sense</div> </aside> ); }; export default Aside;
const Route = require('express').Router() const UserController = require('../controllers/userController') Route.get('/', UserController.getUsers) Route.post('/register', UserController.register) Route.post('/login', UserController.login) Route.get('/unique/:email', UserController.cekEmail) module.exports = Route
const reducer = (state = [], action) => { Object.freeze(state); switch(action.type) { case 'ADD_FRUIT': return [ ...state, action.fruit ]; case 'REMOVE_FRUIT': let newState = [...state]; newState.pop(); return newState; default: return state; } }; export default reducer;
angular.module('rl-prevnext', []) .directive('rlPrevnext', ['$document', function ($document) { return { restrict: 'EA', replace: true, scope: { maxpages: '@', callback: '&' }, controller: ['$scope', function ($scope) { } ], templateUrl: "../scripts/lib/rl-prevnext/rl-prevnext.html", link: function (scope, element, attrs) { scope.$watch('maxpages', function (maxpages) { if (maxpages) { scope.initialize(); } }); scope.initialize = function () { scope.maxPage = scope.maxpages || 1; scope.currentPage = 1; } $document.bind('keydown', handleKey); scope.searchPrevClick = function () { if (scope.currentPage > 1) { scope.currentPage--; scope.callback({ e: scope.currentPage }); } } scope.searchNextClick = function () { if (scope.currentPage < scope.maxPage) { scope.currentPage++; scope.callback({ e: scope.currentPage }); } } function handleKey(e) { e.which = e.which ? e.which : e.keyCode; //ie8 if ([37, 39].indexOf(e.which) >= 0) { if ([37].indexOf(e.which) >= 0) scope.searchPrevClick(); if ([39].indexOf(e.which) >= 0) scope.searchNextClick(); e.preventDefault(); e.stopPropagation(); return false; } } } } } ]);
/** * Created by xyh on 2017/6/7. */ import React from 'react'; import { View, Image, Dimensions, ToastAndroid, StyleSheet } from 'react-native'; import ViewPager from 'react-native-viewpager'; var deviceWidth = Dimensions.get('window').width; const BANNER_IMGS = [ require('./../image/banner/1.png'), require('./../image/banner/2.png'), require('./../image/banner/3.png'), ]; var images = [ 'http://ac-c6scxa78.clouddn.com/f6b64dc4bf7bee56.jpg', 'http://ac-c6scxa78.clouddn.com/91ead58b0bb213b6.jpg', 'http://ac-c6scxa78.clouddn.com/d67316858f6c71f3.jpg', 'http://ac-c6scxa78.clouddn.com/c81c5b7be1838a1e.jpg', 'http://ac-c6scxa78.clouddn.com/54fe022399902788.jpg', ]; export default class MyViewPager extends React.Component { constructor(props) { super(props); // 用于构建DataSource对象 var dataSource = new ViewPager.DataSource({ pageHasChanged: (p1, p2) => p1 !== p2, }); // 实际的DataSources存放在state中 this.state = { dataSource: dataSource.cloneWithPages(images) } } _renderPage(data) { return ( <Image source={{uri: data}} style={styles.page} onPress={this._onPageClick}/> ); } /** dataSource: 提供页面数据, renderPage: 用于渲染页面视图, autoPlay: 为true 将自动播放, isLoop: 为true支持循环播放, locked: 为true禁止触摸滚动, onChangePage: 页面变化的回调, renderPageIndicator: 渲染自定义的 ViewPager indicator. */ render() { return ( <ViewPager style={this.props.style} dataSource={this.state.dataSource} renderPage={this._renderPage} isLoop={true} autoPlay={true}/> ); } _onPageClick(data) { ToastAndroid.show('Current page: ' + data, ToastAndroid.SHORT) } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', alignItems: 'flex-start', backgroundColor: '#999999', }, page: { width: deviceWidth,//设备宽(只是一种实现,此处多余) }, });
// Set the require.js configuration for your application. require.config({ deps: ["main"], baseUrl: "assets/js/app/", paths: { // app "main": "config/main", "app": "config/app", // base "jquery": "vendor/jquery/jquery-2.2.2", "backbone": "vendor/base/backbone", "underscore": "vendor/base/underscore", "layoutmanager": "vendor/base/backbone.layoutmanager", //sweiper "swiper": "vendor/jquery/swiper.jquery.min", "alloy_finger": "vendor/alloy_finger", "transform": "vendor/transform", // "moment":"vendor/moment", // utils // tween "TweenLite": "vendor/greensock/TweenMax", "TimelineLite": "vendor/greensock/TimelineMax", // media "howler": "vendor/media/howler.min", "buzz": "vendor/media/buzz", //exif "exif": "vendor/exif", //binaryajax "binaryajax": "vendor/binaryajax", //hammer "hammer":"vendor/ui/hammer.min", //loadimage "loadImage":"vendor/loadimg/load-image", "loadImageexif":"vendor/loadimg/load-image-exif", "loadImagexifmap":"vendor/loadimg/load-image-exif-map", "loadImagemeta":"vendor/loadimg/load-image-meta", //3ds "three":"vendor/threeds/three.min", "tween":"vendor/threeds/tween.min", "TrackballControls":"vendor/threeds/TrackballControls", "DeviceOrientationControls":"vendor/threeds/DeviceOrientationControls", "OrbitControls":"vendor/threeds/OrbitControls", "CSS3DRenderer":"vendor/threeds/CSS3DRenderer", "Detector":"vendor/threeds/Detector", "browser" : "vendor/jquery/jquery.browser.min", "parsequery" : "vendor/jquery/jquery.parsequery", "pinchzoom":"vendor/pinchzoom", //distpicker "distpicker":"vendor/distpicker" }, shim: { "main": { deps: ["swiper","layoutmanager", "TimelineLite", "howler","buzz", "browser","parsequery","transform","alloy_finger","exif","pinchzoom","distpicker"] //deps : ["layoutmanager"], }, "jquery": { exports: '$' }, "backbone": { deps: ["underscore", "jquery"], exports: "Backbone" }, "browser": { deps: ["jquery"], }, "parsequery": { deps: ["jquery"], }, "swiper": { deps: ["jquery"] }, "underscore": { exports: '_' }, "layoutmanager": { deps: ["backbone"], exports: "Backbone.LayoutManager" }, "buzz": { exports: "buzz" }, "binaryajax": { exports: 'binaryajax' }, // tween "TweenLite": { exports: "TweenLite" }, "TimelineLite": { deps: ["TweenLite"], exports: "TimelineLite" }, "RaphaelPlugin": { deps: ["TweenLite"] }, "three": { //exports: "THREE" }, "tween": { deps: ["three"] }, "TrackballControls": { deps: ["three"] }, "DeviceOrientationControls": { deps: ["three"] }, "OrbitControls": { deps: ["three"] }, "CSS3DRenderer": { deps: ["three"] }, " ": { deps: ["three"] }, /* "loadImage":{ deps: ["loadImage","loadImagexif","loadImagexifmap","loadImagemeta"] }*/ "distpicker": { deps: ["jquery"] } } });
import validator from "validator"; export const validatePhoneNumber = (number) => { const isValidPhoneNumber = validator.isMobilePhone(number); return isValidPhoneNumber; };
import React from 'react'; import { Text, StyleSheet } from 'react-native'; import { isFunction } from 'lodash'; const styles = StyleSheet.create({ main_text: { fontSize: 17, }, }); class Label extends React.PureComponent { setRef = (view) => { const { setRef } = this.props; if (isFunction(setRef)) setRef(this, view); }; render() { const { style, children, ...props } = this.props; return ( <Text {...props} ref={this.setRef} style={[styles.main_text, style]}> {children} </Text> ); } } export default Label;
$(document).ready(function () { "use strict"; var input1 = [36, 17, 28, 23]; var input2 = [20, 13, 14, 15]; var output1 = ["", "", "", ""]; var output2 = ["", "", "", ""]; var av = new JSAV("extMergeSortCON"); // Create an array object under control of JSAV library var arr1 = av.ds.array(input1, {indexed: false, left: 50, top: 30}); var arr2 = av.ds.array(input2, {indexed: false, left: 50, top: 130}); var arr3 = av.ds.array(output1, {indexed: false, left: 400, top: 30}); var arr4 = av.ds.array(output2, {indexed: false, left: 400, top: 130}); var setWhite = function (index, arr) { arr.css(index, {"background-color": "#FFFFFF" }); }; var setYellow = function (index, arr) { arr.css(index, {"background-color": "#FFFF00" }); }; av.umsg("Our approach to external sorting is derived from the Mergesort algorithm. The simplest form of external Mergesort performs a series of sequential passes over the records, merging larger and larger sublists on each pass."); var inputlabel1 = av.label("Input", {left: 90, top: 0}); var outputlabel1 = av.label("Output", {left: 435, top: 0}); var inputlabel2 = av.label("Runs of length 1", {left: 50, top: 195}); var outputlabel2 = av.label("Runs of length 2", {left: 400, top: 195}); var inputline1 = av.g.line(81, 43, 81, 79, {"stroke-width": "2"}); var inputline2 = av.g.line(111, 43, 111, 79, {"stroke-width": "2"}); var inputline3 = av.g.line(141, 43, 141, 79, {"stroke-width": "2"}); var inputline4 = av.g.line(81, 143, 81, 179, {"stroke-width": "2"}); var inputline5 = av.g.line(111, 143, 111, 179, {"stroke-width": "2"}); var inputline6 = av.g.line(141, 143, 141, 179, {"stroke-width": "2"}); var outputline1 = av.g.line(461, 43, 461, 79, {"stroke-width": "2"}); var outputline2 = av.g.line(461, 143, 461, 179, {"stroke-width": "2"}); av.displayInit(); av.umsg("A sorted sublist is called a run. Thus, each pass is merging pairs of runs to form longer runs."); av.step(); av.umsg("Take the first record from each input buffer"); setYellow(0, arr1); setYellow(0, arr2); av.step(); av.umsg("Write a run of length two to the first output buffer"); av.effects.moveValue(arr2, 0, arr3, 0); av.effects.moveValue(arr1, 0, arr3, 1); setYellow(0, arr3); setYellow(1, arr3); av.step(); av.umsg("Take the second record from each input buffer"); setWhite(0, arr1); setWhite(0, arr2); setWhite(0, arr3); setWhite(1, arr3); setYellow(1, arr1); setYellow(1, arr2); av.step(); av.umsg("Write a run of length two to the second output buffer"); av.effects.moveValue(arr2, 1, arr4, 0); av.effects.moveValue(arr1, 1, arr4, 1); setYellow(0, arr4); setYellow(1, arr4); av.step(); av.umsg("Take the third record from each input buffer"); setWhite(1, arr1); setWhite(1, arr2); setWhite(0, arr4); setWhite(1, arr4); setYellow(2, arr1); setYellow(2, arr2); av.step(); av.umsg("Write a run of length two to the first output buffer"); av.effects.moveValue(arr2, 2, arr3, 2); av.effects.moveValue(arr1, 2, arr3, 3); setYellow(2, arr3); setYellow(3, arr3); av.step(); av.umsg("Take the fourth record from each input buffer"); setWhite(2, arr1); setWhite(2, arr2); setWhite(2, arr3); setWhite(3, arr3); setYellow(3, arr1); setYellow(3, arr2); av.step(); av.umsg("Write a run of length two to the second output buffer"); av.effects.moveValue(arr2, 3, arr4, 2); av.effects.moveValue(arr1, 3, arr4, 3); setYellow(2, arr4); setYellow(3, arr4); av.step(); av.umsg("The roles of the input and output files are reversed"); setWhite(3, arr1); setWhite(3, arr2); setWhite(2, arr4); setWhite(3, arr4); arr1.value(0, 20); arr1.value(1, 36); arr1.value(2, 14); arr1.value(3, 28); arr2.value(0, 13); arr2.value(1, 17); arr2.value(2, 15); arr2.value(3, 23); arr3.value(0, ""); arr3.value(1, ""); arr3.value(2, ""); arr3.value(3, ""); arr4.value(0, ""); arr4.value(1, ""); arr4.value(2, ""); arr4.value(3, ""); inputline1.hide(); inputline3.hide(); inputline4.hide(); inputline6.hide(); outputline1.hide(); outputline2.hide(); inputlabel2.value("Runs of length 2"); outputlabel2.value("Runs of length 4"); av.step(); av.umsg("Take the first record from each input buffer"); setYellow(0, arr1); setYellow(1, arr1); setYellow(0, arr2); setYellow(1, arr2); av.step(); av.umsg("Write a run of length four to the first output buffer"); av.effects.moveValue(arr2, 0, arr3, 0); av.effects.moveValue(arr2, 1, arr3, 1); av.effects.moveValue(arr1, 0, arr3, 2); av.effects.moveValue(arr1, 1, arr3, 3); setYellow(0, arr3); setYellow(1, arr3); setYellow(2, arr3); setYellow(3, arr3); av.step(); av.umsg("Take the second record from each input buffer"); setWhite(0, arr1); setWhite(1, arr1); setWhite(0, arr2); setWhite(1, arr2); setWhite(0, arr3); setWhite(1, arr3); setWhite(2, arr3); setWhite(3, arr3); setYellow(2, arr1); setYellow(3, arr1); setYellow(2, arr2); setYellow(3, arr2); av.step(); av.umsg("Write a run of length four to the first output buffer"); av.effects.moveValue(arr1, 2, arr4, 0); av.effects.moveValue(arr2, 2, arr4, 1); av.effects.moveValue(arr2, 3, arr4, 2); av.effects.moveValue(arr1, 3, arr4, 3); setYellow(0, arr4); setYellow(1, arr4); setYellow(2, arr4); setYellow(3, arr4); av.step(); av.umsg("Only one run remains thus sorting is done"); av.step(); av.recorded(); });
/* 弹窗的基础类 */ cc.Class({ extends: cc.Component, properties: { TOP: false, //此视图是否需要保持在最上面 LOCK: false, //是否要锁定此界面,不能自动执行上拉动作 TIMID: false, //此弹窗打开时,不隐藏其他弹窗,直接覆盖其上 UNIQUE: true, //此视图是否同时只能显示一个 ALWAYS_SHOW: false, //是否一直显示此视图 _all_data: { default: {}, visible: false }, //打开视图时的全部参数 init_data: { default: {}, visible: false }, //初始化的数据 _is_inited: false, //是否已经初始化了 _action_type: 0, //显示类型: 0直接打开,1缩放打开,2从指定位置打开 load_data: { default: {}, visible: false }, //拿到的服务器数据 _is_data_loadded: false, //数据是否已经拿到 _enter_action: null, //进入动作 _is_enter_finish: false, //进入完成 _is_exit_finish: false, //退出完成 auto_setview_pushy: false, //不等进入动作完成,有数据就刷新 _is_setview_called: false, //setview是否已经被调用过 _normal_position: { default: cc.v2(), visible: false }, //视图正常的位置 _is_upwarding: false, //是否属于上拉状态 upwarding: { get() { return this._is_upwarding; }, set(upwarding) { this._is_upwarding = Boolean(upwarding); }, visible: false }, vid: { get() { return this._all_data.vid; }, visible: false }, }, //脚本被加载 onLoad() {}, swallowTouch(node) { node.on(cc.Node.EventType.TOUCH_START, () => {}, this, true); }, //初始化 init(params) { params = params || {}; this._all_data = params; this.initViewFeature(); this.initData(params); this.initUI(); this.initClick(); this.initEvent(); this._is_inited = true; }, //初始化此视图的特性 initViewFeature() { this.TOP = this._all_data.TOP !== undefined ? this._all_data.TOP : this.TOP; this.LOCK = this._all_data.LOCK !== undefined ? this._all_data.LOCK : this.LOCK; this.TIMID = this._all_data.TIMID !== undefined ? this._all_data.TIMID : this.TIMID; this.UNIQUE = this._all_data.UNIQUE !== undefined ? this._is_data_loadded.UNIQUE : this.UNIQUE; this.ALWAYS_SHOW = this._all_data.ALWAYS_SHOW !== undefined ? this._all_data.ALWAYS_SHOW : this.ALWAYS_SHOW; }, //初始化数据 initData(params) { this.init_data = params.init_data; this._is_data_loadded = params.loadded_data === true ? true : false; this._action_type = params.action_type ? params.action_type : 0; }, //初始化UI,对UI进行初始化操作 initUI() { }, //监听点击事件 initClick() { this.node.on(cc.Node.EventType.TOUCH_START, () => {}, this, true); this.node.on(cc.Node.EventType.TOUCH_END, () => { this.onClickSpace(); }, this); }, //监听Model派发的数据更新事件 initEvent() { }, //点击事件 onClick(touch, name) { switch (name) {} }, //触摸到了空白区域,默认关闭视图 onClickSpace() { if (this._is_enter_finish) { this.removeSelf(); } }, //进入完成时,强制恢复到正常状态 setNormalStatus() { this.opacity = 0; this.scale = 1.0; }, setView() { if (!this._is_data_loadded) { return false; } return true; }, //请求此视图的数据 reqData() {}, seekNodeByName(name, parent) { return qf.utils.seekNodeByName(name, parent || this.node); }, //服务器数据已拿到 setData(data) { this.load_data = data; this._is_data_loadded = true; if (this._is_enter_finish || this.auto_setview_pushy) { this._is_setview_called = true; this.setView(data); } }, show() { //直接打开 if (this._action_type === 0) { this.node.active = true; this.onEnterFinish(); } //缩放打开 else if (this._action_type === 1) { this.runEnterAction(() => { this.onEnterFinish(); }); } //从指定位置打开 else if (this._action_type === 2) { this.runSpecialEnterAction(() => { this.onEnterFinish(); }); } else { this.runCustomEnterAction(() => { this.onEnterFinish(); }); } }, onEnterFinish() { this._is_enter_finish = true; this.setNormalStatus(); if (this._is_data_loadded && !this._is_setview_called) { this._is_setview_called = true; this.setView(this.load_data); } }, removeSelf: function(simply) { qf.dm.remove(this._all_data.vid, simply); }, close() { //缩放打开时也缩放关闭 if (this._action_type === 1) { this.runExitAction(() => { this.onExitFinish(); }); } else { this.onExitFinish(); } }, //直接展示视图 display() { this.setNormalStatus(); this.node.active = true; this.node.position = this._normal_position; }, //直接隐藏 hide() { this.setNormalStatus(); if (this._enter_action) { this.node.stopAction(this._enter_action); this._enter_action = null; this.onEnterFinish(); } this.node.active = false; }, //退出动作完成回调 onExitFinish() { let vid = this._all_data.vid; this._is_exit_finish = true; this.node.active = false; qf.dm.remove(vid); }, //执行进入动作 runEnterAction(callback) { this.node.scale = 0.6; this.node.anchorX = this.node.anchorY = 0.5; this._normal_position = cc.v2(cc.winSize.width * 0.5, cc.winSize.height * 0.5); let action = this.node.runAction(cc.sequence( cc.scaleTo(0.2, 1.08).easing(cc.easeSineOut()), cc.scaleTo(0.2, 1.0).easing(cc.easeSineOut()), cc.delayTime(0), cc.callFunc((sender) => { this._enter_action = null; if (callback) callback(sender); }) )); this._enter_action = action; }, //执行从指定位置打开的进入动作 runSpecialEnterAction(callback) { let from_position = this._all_data.from_position || cc.v2(0, 0); this._normal_position = cc.v2(cc.winSize.width * 0.5, cc.winSize.height * 0.5); this.node.scale = 0; this.node.anchor = cc.v2(0.5, 0.5); this.node.position = from_position; let action = self.runAction(cc.sequence( cc.show(), cc.easeSineOut(cc.spawn( cc.moveTo(0.2, this._normal_position), cc.scaleTo(0.2, 1.0), cc.fadeIn(0.2) )), cc.easeSineOut(cc.scaleTo(0.1, 1.05)), cc.easeSineOut(cc.scaleTo(0.05, 1.0)), cc.delayTime(0), cc.callFunc((sender) => { this._enter_action = null; if (callback) callback(sender); }) )); this._enter_action = action; }, //override //执行视图定制的进入动作 runCustomEnterAction() { }, //开始执行退出动作 runExitAction(callback) { this.node.runAction(cc.sequence( cc.spawn( cc.scaleTo(0.1, 0.8), cc.fadeTo(0.1, 130) ), cc.callFunc((sender) => { if (callback) callback(sender); }) )); }, adjustIPhoneX(node_name) { let offset = qf.platform.getIPhoneXOffsetHeight(); let node = this.node.getChildByName(node_name); if (!node) return; let widget = node.getComponent(cc.Widget); if (!widget) return; widget.top = offset; widget.updateAlignment(); }, //override //视图被销毁 onDestroy() {} });
"use strict"; const StickerMessage = require(__dirname + "/../../lib/message/sticker-message"); exports.testBuildStickerMessageSanity = test => { const stickerId = 123; const message = new StickerMessage(stickerId); const messageBody = { "type": "sticker", "sticker_id": stickerId }; test.deepEqual(message.toJson(), messageBody); test.ok(!message.keyboard); test.done(); }; exports.testBuildStickerMessageWithKeyboard = test => { const keyboard = { foo: "bar" }; const message = new StickerMessage(1234, keyboard); test.deepEqual(message.keyboard, keyboard); test.done(); };
class FlowChart { }
const TEMPERATURE = "temperature"; const PRESSURE = "pressure"; const HUMIDITY = "humidity"; const TEMPERATURE_PL = "temperatura"; const PRESSURE_PL = "ciśnienie"; const HUMIDITY_PL = "wilgotność"; const URL = "http://192.168.191.239:1410/sensorsData"; const green = "rgb(0, 132, 0)"; const blue = "rgb(11,47,227)"; const red = "rgb(132, 0, 0)"; async function getChartData() { const response = await fetch(URL); return await response.json(); } async function getSensorData(dataType) { const chartData = await getChartData(); const measurementTimeAndData = chartData.sensorsData.reduce( (sum, current) => { const hour = new Date(current.measurementDate).getHours(); const minutes = new Date(current.measurementDate).getMinutes(); const doubleCharactersHour = hour < 10 ? `0${hour}` : hour; const doubleCharactersMinutes = minutes < 10 ? `0${minutes}` : minutes; const time = `${doubleCharactersHour}:${doubleCharactersMinutes}`; return { ...sum, [time]: current[dataType] }; }, {} ); return { time: Object.keys(measurementTimeAndData), measurement: Object.values(measurementTimeAndData), }; } function getLabel(dataType) { if (dataType === TEMPERATURE) { return TEMPERATURE_PL; } if (dataType === PRESSURE) { return PRESSURE_PL; } if (dataType === HUMIDITY) { return HUMIDITY_PL; } } async function init(dataType, color) { const getData = await getSensorData(dataType); const data = { labels: getData.time, datasets: [ { label: getLabel(dataType), backgroundColor: color, borderColor: color, data: getData.measurement, }, ], }; const config = { type: "line", data, options: { plugins: { legend: { display: false, }, }, }, }; new Chart(document.getElementById(`${dataType}Chart`), config); } init(TEMPERATURE, red); init(PRESSURE, green); init(HUMIDITY, blue);
import WelcomeController from "welcome/welcome.controller"; export default { templateUrl: "welcome/welcome.html", controller: WelcomeController };
$(function(){ // 初始化变量 $.fn.zidingyi=function(datas){ var datas=$.extend({ one:200, two:'eddie', three:false },datas); var aa=1; function f1(){ console.log(datas.one+','+datas.two+','+datas.three); }; f1(); } }(jQuery))
var website = require('../models/website.js'); // check if job is in the database and invoke callback with results exports.getWebsite = function (id, callback) { website.findOne({ id: id }, function (err, website) { callback(err, website); }); } // complete job by storing website in database exports.storeWebsite = function (id, url, content) { var websiteEntry = new website({ id: id, url: url, content: content }); websiteEntry.save(function (err) { if (err) { console.log("error trying to store website: " + url); } }); }
//Suvrajit karmaker function myFunction() { if (validate() == true) { let question1 = new InputTypeMethod("div1", "question1"); question1.removeElement(); question1.update(); let question2 = new McqMrqMethod("div2", "question2", "radio"); question2.removeElement(); question2.update(); let question3 = new McqMrqMethod("div3", "question3", "checkbox"); question3.removeElement(); question3.update(); let question4 = new TextAreaTypeMethod("div4", "question4"); question4.removeElement(); question4.update(); let submitButton = new Element("submit"); submitButton.removeElement(); } else { alert("You have to answer all of the questions."); } } /////////////////////////////////////form validation/////////////////////////////////////// function validate() { let isValidQuestion1 = document.getElementById('question1').value; isValidQuestion1 = isValidQuestion1.replace(/\s+/g, ' '); if (isValidQuestion1 == null || isValidQuestion1 == "") { return false; } let isValidQuestion4 = document.getElementById('question4').value; isValidQuestion4 = isValidQuestion4.replace(/\s+/g, ''); if (isValidQuestion4 == null || isValidQuestion4 == "") { return false; } let item = document.getElementsByTagName('input'); let countCheckbox = 0, countRadio = 0; for (let i = 0; i < item.length; i++) { if (item[i].type == "radio" && item[i].checked == true) { countRadio++; } if (item[i].type == "checkbox" && item[i].checked == true) { countCheckbox++; } } if (countCheckbox > 0 && countRadio > 0) { return true; } else { return false; } } //////////////////////////////// function createInheritance(child, parent) { child.prototype = Object.create(parent.prototype); } ////////////////////////////////// function Element(elementId) { this._elementId = elementId; } Element.prototype.addElement = function (parentId, html) { let parentElement = document.getElementById(parentId); parentElement.appendChild(html); } Element.prototype.removeElement = function () { let element = document.getElementById(this._elementId); element.remove(element); } //////////////////////////////////////// function InputTypeMethod(parentId, elementId) { this._parentId = parentId; Element.call(this, elementId); this._html = this.htmlGenaretor(); } createInheritance(InputTypeMethod, Element); InputTypeMethod.prototype.htmlGenaretor = function () { let str = document.getElementById(this._elementId).value; let newElement = document.createElement("p"); let node = document.createTextNode(str); newElement.appendChild(node); newElement.className = "forP"; return newElement; } InputTypeMethod.prototype.update = function () { Element.prototype.addElement.call(this, this._parentId, this._html); } /////////////////////////////////////////////// function TextAreaTypeMethod(parentId, elementId) { InputTypeMethod.call(this, parentId, elementId); } createInheritance(TextAreaTypeMethod, InputTypeMethod); TextAreaTypeMethod.prototype.htmlGenaretor = function () { let str = document.getElementById(this._elementId).value; let textAreaHeight = document.getElementById(this._elementId).style.height; let newElement = document.createElement("textarea"); newElement.setAttribute("readonly", ""); newElement.setAttribute("style", `height: ${textAreaHeight};`); let node = document.createTextNode(str); newElement.appendChild(node); return newElement; } /////////////////////////////////////////////// function McqMrqMethod(parentId, elementId, inputType) { this._inputType = inputType; InputTypeMethod.call(this, parentId, elementId); } createInheritance(McqMrqMethod, InputTypeMethod); McqMrqMethod.prototype.htmlGenaretor = function () { let createUl = document.createElement('ul'); let item = document.getElementById(this._elementId).getElementsByTagName('input'); for (let i = 0; i < item.length; i++) { if (item[i].type == this._inputType && item[i].checked == true) { let x = document.createElement("LI"); let t = document.createTextNode(item[i].value); x.appendChild(t); createUl.appendChild(x); } } return createUl; } //////////////////////////////////////// let textarea = document.querySelector('textarea'); textarea.addEventListener('keydown', autosize); function autosize() { let element = this; setTimeout(function () { element.style.cssText = 'height:auto; padding:0'; element.style.cssText = 'height:' + element.scrollHeight + 'px'; }, 0); }
/** * Created by Administrator on 2016/3/28. */ import React,{ View, Navigator, Text, BackAndroid,//回退按钮的功能 StyleSheet, Component } from "react-native" import {SearchIndex} from "./SearchIndex" import {SearchResult} from "./SearchResult" var _navigator; export class SearchWelcome extends Component{ configureScene(){ return Navigator.SceneConfigs.FadeAndroid; } renderScene(router,navigator){ _navigator = navigator; switch (router.title){ case "welcome": return (<SearchIndex navigator={navigator}/>) default: return (<SearchResult datasource={router.component}/>) } } componentDidMount() { var navigator = _navigator; BackAndroid.addEventListener('hardwareBackPress', function() { if (navigator && navigator.getCurrentRoutes().length > 1) { navigator.pop(); return true; } return false; }); } componentWillUnmount() { BackAndroid.removeEventListener('hardwareBackPress'); } render() { return ( <Navigator initialRoute={{title: 'welcome',component:[]}} configureScene={this.configureScene} renderScene={this.renderScene} /> ); } }
import React, { useContext } from 'react'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@material-ui/core/MenuItem'; import IconButton from '@material-ui/core/IconButton'; import LanguageIcon from '@material-ui/icons/Language'; import Tooltip from '@material-ui/core/Tooltip'; import Divider from '@material-ui/core/Divider'; import { useTranslation } from 'react-i18next'; import AppContext from '../../context/AppContext'; export default function LanguageMenu() { const { t, i18n } = useTranslation(); const [anchorEl, setAnchorEl] = React.useState(null); const { toggleLanguage } = useContext(AppContext); const handleClick = event => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const changeLanguage = lng => { i18n.changeLanguage(lng); // update context toggleLanguage(lng); // uncomment this if you want to close language slection after user selects a language // handleClose(); }; return ( <React.Fragment> <Tooltip title={t('choose_language')} onClick={handleClick}> <IconButton color="inherit"> <LanguageIcon /> </IconButton> </Tooltip> <Menu id="language-menu" anchorEl={anchorEl} keepMounted open={Boolean(anchorEl)} onClose={handleClose} > <MenuItem onClick={() => changeLanguage('en')}> {t('english')} </MenuItem> <Divider /> <MenuItem onClick={() => changeLanguage('hi')}> {t('hindi')} </MenuItem> <Divider /> <Divider /> </Menu> </React.Fragment> ); }
import React, { Component } from 'react'; import { withRouter } from 'react-router-dom'; import Style from './index.module.less'; import { inject, observer } from 'mobx-react'; import { notification } from 'antd'; import { addTopic } from '@common/api'; import Upload from '@components/upload/index'; import Avatar from '@components/avatar/index'; import Carousel from '@components/carousel/index'; let ImageUpload = ({ changeUploadStatus, uploadImgSuccess }) => { return ( <section className={Style['image-upload']}> <div> <span className={`${Style['icon']} ${Style['camera']}`}></span> <span><Upload successCb={uploadImgSuccess} className={'placeholder'} />上传照片</span> </div> <div> <span className={`${Style['icon']} ${Style['network']}`} onClick={() => {changeUploadStatus(1)}}></span> <span>从网络添加图片</span> </div> </section> ) } @inject('rootStore') @withRouter @observer class PostTopic extends Component { state = { uploadStatus: 0, // 0: 默认占位图 1: inputUrl 状态 2: 选择照片状态 imageList: [], showInputNotice: true, inputUrl: '', topicDescript: '', } // 更改图片输入状态 changeUploadStatus = (status) => { this.setState({ uploadStatus: status, imageList: [], }); } // 改变展示输入框提示 changeInpurUrlStatus = () => { this.setState({ showInputNotice: !this.state.showInputNotice, inputUrl: '', }); } // 关闭输入网络图片 closeInputUrl = () => { let imgLength = this.state.imageList.length if (imgLength === 0) { this.setState({ uploadStatus: 0, }); } else if (imgLength > 0) { this.setState({ showInputNotice: true, }); } } // 双向绑定 handelChange = (event) => { this.setState({ inputUrl: event.target.value }); } // 双向绑定textarea handelChangeTextArea = (event) => { this.setState({ topicDescript: event.target.value }); } // 从列表中去除图片 delectPhoto = (index) => { this.setState({ imageList: this.state.imageList.filter((_, i) => i !== index), }); } uploadImgSuccess = async (url) => { this.setState({ imageList: [...this.state.imageList, url], uploadStatus: 2, }); } // 添加网络图片 pushImgUrl = (event) => { if (event.key === 'Enter') { let url = event.target.value var img = document.createElement('img'); img.style.display = 'none'; img.crossorigin = 'anonymous'; img.src = url; // 图片无效 img.onerror = () => { notification['error']({ message: '请输入正确图片地址', }) }; // 图片有效 img.onload = () => { if (this.state.imageList.length === 0) { this.setState({ showInputNotice: true, }); } this.setState({ imageList: [...this.state.imageList, url], inputUrl: '', }); }; } } // 发帖 postTopic = async () => { if (this.state.imageList.length === 0) { notification['error']({ message: "请选择图片", }); return; } let resposne = await addTopic({ topicImg: this.state.imageList, topicTitle: this.state.topicDescript, }); notification['success']({ message: resposne.message, }); // 关闭发帖弹窗 this.props.togglePostTopic(true); } render() { let { userInfo } = this.props.rootStore.dataStore; let avatarStyle = { width: '40px', height: '40px', }; let InputUrl = () => { return ( <section key={1} className={Style['input-url']}> { this.state.showInputNotice ? <div className={Style['notice']} onClick={this.changeInpurUrlStatus}> <i className={Style['icon']}></i> { this.state.imageList.length > 0 ? <span>添加另一张</span> : <span>添加照片</span> } </div> : <div className={Style['input-container']}> <span className={Style['close-circle']} onClick={this.closeInputUrl}></span> <input type = 'text' defaultValue={this.state.inputUrl} onKeyPress={this.pushImgUrl} placeholder="输入图片地址后,按回车即可" /> </div> } </section> ) }; let ImgUpload = () => { return ( <section key={2} className={Style['input-url']}> <div className={Style['notice']}> <span className={Style['close-circle']} onClick={this.closeInputUrl}></span> <i className={Style['icon']}></i> <span><Upload successCb={this.uploadImgSuccess} className={'placeholder'} />添加另一张</span> </div> </section> ) }; let UploadPlaceholder = () => { return ( <div> { this.state.uploadStatus === 1 ? <InputUrl /> : '' } { this.state.uploadStatus === 2 ? <ImgUpload /> : '' } { this.state.uploadStatus === 0 ? <ImageUpload uploadImgSuccess={this.uploadImgSuccess} changeUploadStatus={this.changeUploadStatus} /> : '' } </div> ) }; return ( <div className={`${Style['post-topic']}`} > <section className={Style['topic-content']}> <header> <Avatar userInfo={userInfo} avatarStyle={avatarStyle}/> </header> { this.state.imageList.length > 0? ( <section className={Style['image-list']}> <Carousel imageList={this.state.imageList} delectPhoto={this.delectPhoto} showCloseBtn={true} showSlickDot={false}></Carousel> </section> ) : "" } {/* 上次占位图 */} <div className={Style['upload-style']}> <UploadPlaceholder /> </div> <div className={Style['descript']}> <textarea value={this.state.topicDescript} onChange={this.handelChangeTextArea} rows="4" cols="50" placeholder="愿意的话可以添加说明"></textarea> </div> <footer className={Style['footer']}> <span className={Style['close']} onClick={()=> this.props.togglePostTopic()}>关闭</span> <span className={Style['post']} onClick={this.postTopic}>发帖</span> </footer> </section> </div> ); } } export default PostTopic;
import React from 'react'; export const images = { defaultAddThumbnail: '/assets/images/add_thumbnail.png', thumbnailMedia: '/assets/media/show_thumb_2.png' };
const { ApolloServer, gql } = require("apollo-server"); // books example const books = [ { title: "arry potta", author: "jk rowling" }, { title: "jurassic park", author: "michael crichton" } ]; const typeDefs = gql` # book type Book { title: String author: String } # the 'query' type which serves as the root for all graphql queries. # (A "mutation" type will be covered later on) type Query { books: [Book] } `; // Resolver define technique for fetching types in schema. const resolvers = { Query: { books: () => books } }; const server = new ApolloServer({ typeDefs, resolvers }); server.listen().then(({ url }) => { console.log(`server is ready at ${url}`); });
var cloudinary = require('cloudinary'); cloudinary.config({ cloud_name: 'pricepls', api_key: '287145665136215', api_secret: 'Kfl99Unbk9CQKMf-kp6twk9DqeQ' }); var s3_key_id = "AKIAITBZK2MKHOYDZY4Q"; var s3_key = "n5PdKny+tDuoDXbC0I9QLXCe/EjuzrJ8gHofYEYQ"; var lwip = require('lwip'); var s3 = require('s3'); var BASE_IMAGE_URL = "http://pricepls.imgix.net/"; var client = s3.createClient({ maxAsyncS3: 20, // this is the default s3RetryCount: 3, // this is the default s3RetryDelay: 1000, // this is the default multipartUploadThreshold: 20971520, // this is the default (20 MB) multipartUploadSize: 15728640, // this is the default (15 MB) s3Options: { accessKeyId: "AKIAITBZK2MKHOYDZY4Q", secretAccessKey: "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" }, }); logger.log("debug", JSON.stringify(s3)); var AWS = require('aws-sdk'); AWS.config.update({accessKeyId: 'AKIAITBZK2MKHOYDZY4Q', secretAccessKey: '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'}); AWS.config.update({region: 'ap-southeast-1'}); var s3 = new AWS.S3(); //var multer = require('multer'); var fs = require('fs'); var mysqlDB = require('../lib/mysqldb')(); mysqlDB.init(); var mongodb = require('./mongodb'); var util = { uploadTocloudanary: function (image, publicId, callback) { cloudinary.uploader.upload(image, function (result) { //console.log(result) result.appshow_url = cloudinary.url('v' + result.version + '/' + result.public_id + '.' + result.format, { width: 200, crop: "scale" }); callback(result); }, {public_id: publicId}); }, createCloundinaryImages: function (image_url, callback) { var image_url = image_url.split('upload/'); var request_list_url = cloudinary.url(image_url[1], {width: 400, height: 250, crop: 'thumb'}); var booking_details_url = cloudinary.url(image_url[1], {width: 150, height: 150, crop: 'thumb'}); callback({'request_list_url': request_list_url, 'booking_details_url': booking_details_url}); }, uploadImage: function (req, res, next) { //multer({ dest: 'uploads/', // rename: function (fieldname, filename) { // return filename; // }, // onFileUploadStart: function (file) { // console.log(file.originalname + ' is starting ...') // }, // onFileUploadComplete: function (file) { // console.log(file.fieldname + ' uploaded to ' + file.path) // next(); // } //}); var tmp_path = req.files.thumbnail.path; // set where the file should actually exists - in this case it is in the "images" directory var target_path = './public/images/' + req.files.thumbnail.name; // move the file from the temporary location to the intended location fs.rename(tmp_path, target_path, function (err) { if (err) throw err; // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files fs.unlink(tmp_path, function () { if (err) throw err; res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes'); }); }); }, checkGraphNodeExits: function (vendor_id, listing_id) { mysqlDB.checkGraphNode(vendor_id, function (err, status) { }); }, getNextSequenceNumber: function (name, callback) { mongodb.getLastNumber(name, function (err, next) { if (err) callback(err, nul); else callback(null, next); }) }, uploadToS3: function (path, image, publicId, callback) { var BUCKET_NAME = 'listing.images/'+publicId; var fileBuffer = fs.readFileSync(path); var metaData = this.getContentTypeByFile(image.originalname); logger.debug("uploadToS3 bucket "+BUCKET_NAME); s3.upload({ ACL: 'public-read', Bucket: BUCKET_NAME, Key: image.originalname, Body: fileBuffer, ContentType: metaData }, function (error, response) { if(error) callback(error); else{ callback(null,response); } }); }, getModifiedImage:function(imgName,listing_number,w,h){ var url = BASE_IMAGE_URL+listing_number+'/'+imgName+'?fit=crop&h='+h+'&w='+w; return url; }, getContentTypeByFile: function (fileName) { var rc = 'application/octet-stream'; var fn = fileName.toLowerCase(); if (fn.indexOf('.html') >= 0) rc = 'text/html'; else if (fn.indexOf('.css') >= 0) rc = 'text/css'; else if (fn.indexOf('.json') >= 0) rc = 'application/json'; else if (fn.indexOf('.js') >= 0) rc = 'application/x-javascript'; else if (fn.indexOf('.png') >= 0) rc = 'image/png'; else if (fn.indexOf('.jpg') >= 0) rc = 'image/jpg'; return rc; }, cropImage :function(file,callback){ require('lwip').open("picture_not_available.png", function(err, image){ if(err){ throw err; } // check err... // define a batch of manipulations and save to disk as JPEG: image.batch() .scale(0.75) // scale to 75% .crop(200, 200) // crop a 200X200 square from center .writeFile('cropped/'+image_or.originalname, function(err){ callback(); }); }); }, downloadS3File: function(bucket,key,localfile,callback){ logger.log("debug","bucket "+bucket+" key "+key+" localfile "+localfile); try{ var http = require('https'); var fs = require('fs'); var file = fs.createWriteStream(localfile); var request = http.get(key, function(response) { response.pipe(file); callback(); }); }catch(e){ logger.error("error while downloading image "+e); } } } module.exports = util;
console.log("hello from js"); var xyz = 1; (function(){ console.log("hello from iify" + xyz ) })();
$( document ).ready(function() { // -------- MENU -------------------------------- showMenu(); // show menu function showMenu() { $("#show_menu").animate({width:"0px"}, 100, function() { $(".left_section").show(); $(".left_section").animate({width: "20%"}, 100); }); } $("#show_menu").click(function(){ showMenu(); }); // hide menu function hideMenu() { $(".left_section").animate({width: "0%"}, 100, function() { $(".left_section").hide(); $("#show_menu").animate({width:"20px"}, 100); }); } $("#hide_menu").click(function(){ hideMenu(); }); // menu item actions $("#new_delay").click(function() { addPedal("delay"); }); $("#new_drive").click(function() { addPedal("drive"); }); // -------- PEDAL -------------------------------- var fxcontrol_delay = 1; var fxcontrol_drive = 1; // add pedal function addPedal (type) { switch (type) { case "delay" : var js = document.createElement("script"); js.type = "text/javascript"; js.src = "js/fx_delay.js"; document.body.appendChild(js); fxcontrol_drive = 1; break; case "drive" : var js = document.createElement("script"); js.type = "text/javascript"; js.src = "js/fx_drive.js"; document.body.appendChild(js); fxcontrol_drive = 1; break; } } // -------- END -------------------------------- });
const state={ position:{}, //存放位置信息 city:'', //存放城市名称 orderAddress:'', //存放收货地址 showPosition:false, //表明首页是否出现要求选地址的页面 }; export default state;
const router = require('express').Router(); const Contact = require('../Models/ContactModel'); router .route('/') .get((req, res) => { Contact .find() .then(response => { res.status(200).json(response) }) .catch(err => { res.status(500).json({ errorMessage: "Contact Info could NOT be retrieved" }) }) }) .post((req, res)=> { const{ name, email } = req.body; const ContactInfo = new Contact({ name, email }); ContactInfo .save() .then(response => { res.status(201).json({ success: "New Contact Information Added", response }) }) .catch(err => { res.status(500).json({ errorMessage: "There was an error adding the Contact Info to the Database" }) }) }) module.exports = router;
const { PrismaClient } = require('@prisma/client') const prisma = new PrismaClient() const jwt = require('jsonwebtoken') require('dotenv').config() // Instead of using on middleware to authenticate user // Using two middlewares one for authentication and the other // for authorization helps when you just know if user is connected // and do different things on that module.exports.authentication = async (req, res, next) => { let token = req.query?.access_token // ability to pass token into url query if (!token && req.headers.authentication && req.headers.authentication.startsWith('Bearer ')) { token = req.headers.authentication.split('Bearer ')[1] } if (!token) return next() try { const data = jwt.verify(token, process.env.secretOrKey) if (data.action !== 'auth') return next() const user = await prisma.account.findUnique({ where: { email: data.id, }, }) if (user) { req.token = token req.user = user } } catch (error) { if (error instanceof jwt.TokenExpiredError) { return res.json({ ok: false, error: 'jwt.expired_token' }) } } next() } module.exports.authenticatedOnly = async (req, res, next) => { if (!req.user) { return res.status(401).json({ error: 'UnAuthorized' }) } next() }
import { Data, newCharacter, newSkill, newSkillEffect, newDamageSkill, newSingleTargetDamageSkill, newBasicSingleTargetDamageSkill } from '../CharacterDataStructure' Data.characters.push(newCharacter('Reimu Hakurei', 'https://en.touhouwiki.net/images/thumb/f/f7/Th175Reimu.png/355px-Th175Reimu.png', 18, 120, 100, [ newBasicSingleTargetDamageSkill('Hakurei Amulet', 0.8, [newSkillEffect('ATBModifierTarget', { value: -150 })]), newSkill('Dream Land "Great Duplex Barrier"', 'ally', 20, [ newSkillEffect('ApplyDamageAbsorbingShieldTarget', { name: 'Great Duplex Barrier', scaling: 1.2, boostscaling: 0.2, duration: 30 }) ]), newSingleTargetDamageSkill('Fantasy Heaven', 40, 2.5, 0.3) ]))
function e () { var type = arguments[0]; for (var i=0; i<arguments.length; i++ { } }
const express = require('express') const exphbs = require('express-handlebars'); let helper = require('./controller/helper'); var paginateHelper = require('express-handlebars-paginate'); const app = express() const port = process.env.PORT || 5000 // Configure template Engine and Main Template File app.engine('hbs', exphbs({ defaultLayout: 'layout', runtimeOptions:{ allowProtoPropertiesByDefault: true, allowProtoMethodsByDefault: true, }, extname: '.hbs', helpers: { createStarList: helper.createStarList, createStar: helper.createStar, createPagination: paginateHelper.createPagination } })); // Setting template Engine app.set('view engine', 'hbs'); //req.body for post const bp = require('body-parser') app.use(bp.json()) app.use(bp.urlencoded({ extended: true })) // routes app.use('/', require('./routes/indexRouter')); app.use('/products', require('./routes/productRouter')); app.use('/comment', require('./routes/commentRouter')); app.use('/review', require('./routes/reviewRouter')); app.get('/sync', (req, res) => { let models = require('./models'); models.sequelize.sync() .then(()=>( res.send('database sync completed') )); }); app.get('/:page', (req, res) => { var banner = { blog : 'Our blog', cart : 'Shopping Cart', category : 'Shop Category', checkout : 'Checkout', confirmation : 'Order Confirmation', contact : 'Contact Us', login :'Login/Register', register:'Register', 'single-blog': 'Blog Details', 'single-product': 'Shop Single', 'tracking-order': 'Order Tracking' } var page = req.params.page; res.render(page, {banner: banner[page]}); }); app.use('/', express.static('public')) app.listen(port, () => { console.log(`server is running at port ${port}`) })
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsDataUsage = { name: 'data_usage', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M13 2.05v3.03c3.39.49 6 3.39 6 6.92 0 .9-.18 1.75-.48 2.54l2.6 1.53c.56-1.24.88-2.62.88-4.07 0-5.18-3.95-9.45-9-9.95zM12 19c-3.87 0-7-3.13-7-7 0-3.53 2.61-6.43 6-6.92V2.05c-5.06.5-9 4.76-9 9.95 0 5.52 4.47 10 9.99 10 3.31 0 6.24-1.61 8.06-4.09l-2.6-1.53A6.95 6.95 0 0112 19z"/></svg>` };
var connect = require('connect'); var router = require('./middleware/router'); var router = { GET: { '/users': function(req, res){ res.end('tobi, loki, ferret'); }, '/user/:id': function(req, res, id){ res.end('user ' + id); } }, DELETE: { '/user/:id': function(req, res, id){ res.end('deleted user ' + id); } } }; function errorHandler(){ var env = process.evn.NODE_ENV || 'development'; return function(err, req, res, next){ res.status = 500; switch(env){ case 'development': res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(err)); break; default: res.end('Server error'); break; } }; } // connect() // .use(router(routes)) // .listen(3000); connect() .use(router(require('./routes/user'))) .use(router(require('./routes/admin'))) .use(errorHandler()) .listen(3000);
$(function () { var index = 0; var ulImg = $(".wrap-imgList"); var imgWidth = $(".wrap-imgList li").eq(0).width(); var timerid; timerid = setInterval(autoplay2, 4000); $(".wrap-hd li").on('mouseenter', function () { clearInterval(timerid); $(this).addClass("on").siblings().removeClass("on"); var i = $(this).index(); index = i; ulImg.stop().animate({ left: -imgWidth * i }, 400) }).mouseleave(function () { timerid = setInterval(autoplay2, 4000); }); function autoplay2() { if (index == 3) { ulImg.css("left", 0); index = 0; } index++; ulImg.stop().animate({ left: -imgWidth * index }, 400) if (index == 3) { $(".wrap-hd li").eq(0).addClass("on").siblings().removeClass("on"); } else { $(".wrap-hd li").eq(index).addClass("on").siblings().removeClass("on"); } } })
// Logging Middleware export const Logger = store => next => action => { console.group(action.type); console.log("%cPrevious state:", 'color: #b3bd2d; font-weight: bold', store.getState()); console.log("%cAction", 'color: #6FAAF7; font-weight: bold', action); let fin = next(action); console.log("%cCurrent state:", 'color: #2bba0b; font-weight: bold;', store.getState()); console.groupEnd(action.type); return fin; }
import dcopy from 'deep-copy'; export const defaultActionSet = { 'SetGlobalVariables': null, 'PlaySounds': [{ SoundType: 0, Val: '' }], 'InitializeActorDialog': null, 'SetZone': null, 'ResetGame': false }; export const defaultDialog = { 'IsRoot': true, 'EntryInput': [''], 'AlwaysExec': dcopy(defaultActionSet), 'childDialogIDs': [], 'parentDialogIDs': [] }; export const defaultZone = { 'Title': '', 'Triggers': {} }; export class SelectedEntity { constructor({ kind, data } = {}) { this.kind = kind; this._data = data; } get data() { return this._data; } }
module.exports = function(config){ config.set({ basePath : './', files : [ 'public/javascripts/vendor/require/build/require.js', 'public/javascripts/vendor/CesiumUnminified/Cesium.js', 'http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js', 'public/javascripts/vendor/angular/angular.js', 'public/javascripts/vendor/angular-mocks/angular-mocks.js', 'public/javascripts/vendor/angular-route/angular-route.js', 'public/javascripts/vendor/angular-resource/angular-resource.js', 'public/javascripts/vendor/angular-bootstrap/ui-bootstrap-tpls.js', 'public/javascripts/web3D.js', 'public/javascripts/controllers/*.js', 'public/javascripts/services/*.js', 'tests/unit/*.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['Chrome'], plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter' ], junitReporter : { outputFile: 'tests/unit/unit.xml', suite: 'unit' } }); };
'use strict'; describe('getData', function () { var scope; beforeEach(function () { module('utils'); inject(function ($rootScope) { scope = $rootScope.$new(); }); }); it('should invoke jasmine spy handler with object represented in json file', inject(function (getData) { var handler = jasmine.createSpy('success'); getData('test/test.json', handler); // FIXME TypeError: $browser.cookies is not a function scope.$digest(); expect(handler).toHaveBeenCalledWith(['data', 'for unit test']); })); it('should return object represented in local json file', inject(function (getData) { var data; getData('test/test.json', function (data_) { data = data_; }); scope.$digest(); expect(JSON.stringify(data)) .toEqual('["data", "for unit test"]'); // CHECK this error })); });
import riot from 'riot' import {secondsToPeriod} from 'utils' riot.mixin('format-helpers', { timeAgo: function (val) { if (!(val instanceof Date)) { val = new Date(Date.parse(val)) } const seconds = (new Date().getTime() - val.getTime()) / 1000 return `${secondsToPeriod(seconds)} ago` } })
module.exports = { jwtSecret: process.env.JWT_SECRET || '02bb575a-bfa9-4c8c-aaca-33a752744fef' };
module.exports = { port: 3000, server: { api: '/api' }, db: { path: 'mongodb://localhost/testTask' } };
/* @flow */ import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import createSagaMiddleware from 'redux-saga'; import ReduxThunk from 'redux-thunk'; import ReduxPromise from 'redux-promise'; import firebase from 'firebase'; import reducers from './reducers'; import Router from './Router'; import rootSaga from './sagas/todos'; const sagaMiddleware = createSagaMiddleware(); const middleware = [ ReduxThunk, ReduxPromise, sagaMiddleware ] const store = createStore(reducers, {}, applyMiddleware(...middleware)); sagaMiddleware.run(rootSaga); export default class App extends Component { componentWillMount() { const config = { apiKey: "AIzaSyAID3vyEG1ph4sLfvRMjQVJYbG7NnahRPo", authDomain: "todoapp-8e5b9.firebaseapp.com", databaseURL: "https://todoapp-8e5b9.firebaseio.com", storageBucket: "", messagingSenderId: "475809158457" }; firebase.initializeApp(config); } render() { return ( <Provider store={store}> <Router /> </Provider> ); } }
import electron from 'electron'; import fs from 'fs'; import path from 'path'; class Directories { constructor() { this.temp = this.initializeDir('temp', 'mpv'); this.files = this.initializeDir('appData', 'mpv-files'); } initializeDir(base, dir) { let fullDir = this.getDir(base, dir); this.createDir(fullDir); return fullDir; } getDir(base = 'music', dir = 'files') { let app = electron.app; if (electron.hasOwnProperty('remote')) app = electron.remote.app; return path.join(app.getPath(base), dir); } createDir(dir) { if (!fs.existsSync(dir)) fs.mkdirSync(dir); } } export default new Directories();
// API endpoints const historyUrl = "https://boston-weather.phillipbaker.repl.co/history"; const forecastUrl = "https://boston-weather.phillipbaker.repl.co/forecast"; const currentUrl = "https://boston-weather.phillipbaker.repl.co/current"; // SVG dimensions const w = 600; const w2 = 400; const h = 600; const h2 = 300; const xpad = 60; const ypad = 25; const msecToDay = 86400000; // Function to parse date function parseDate(dataset, field) { for (let i = 0; i < dataset.length; i++) { dataset[i][field] = new Date(dataset[i][field]); dataset[i][field] = new Date(dataset[i][field].getTime() + Math.abs(dataset[i][field].getTimezoneOffset()*60000)); }; return dataset; }; // 90-Day History Chart, radial heatmap d3.json(historyUrl, function(data) { const rowCount = data.days.length; // Stack Data to draw high and low arcs separately let stackedData = data.days.concat(data.days); parseDate(stackedData, "datetime"); // Measure max and min const xmax = d3.max(stackedData, d => d.datetime); const xmin = d3.min(stackedData, d => d.datetime); const vmax = d3.max(stackedData, d => d.temp); const vmin = d3.min(stackedData, d => d.temp); // Set scales const xScale = d3.scaleLinear() .domain([new Date(xmin), new Date(xmax)]) .range([xpad, w - xpad]); const vScale = d3.scaleLinear() .domain([vmin, vmax]) .range([0, 90]); // Create SVG const svg = d3.select("#container-right") .append("svg") .attr("width", w) .attr("height", h); // Create div for tooltip d3.select("body") .append("div") .attr("id", "tooltip"); // Draw radial heatmap svg.selectAll("path") .data(stackedData) .enter() .append("path") .attr("class", "arc") .attr("transform", "translate(300,300)") .attr("d", d3.arc() .innerRadius(d => Math.floor((d.datetime - xmin) / msecToDay / 7) * 14 + 40) .outerRadius(d => Math.floor((d.datetime - xmin) / msecToDay / 7) * 14 + 54) .startAngle(function(d, i) { if (i < rowCount) { return (d.datetime.getDay() + 1.3) * 2 * Math.PI / 7 + 3 * Math.PI / 2 } else if (i >= rowCount) { return (d.datetime.getDay() + 1.75) * 2 * Math.PI / 7 + 3 * Math.PI / 2 }; }) .endAngle(function(d, i) { if (i < rowCount) { return (d.datetime.getDay() + 1.25 + 0.5) * 2 * Math.PI / 7 + 3 * Math.PI / 2 } else if (i >= rowCount) { return (d.datetime.getDay() + 1.25 + 0.95) * 2 * Math.PI / 7 + 3 * Math.PI / 2 }; })) .attr("fill", function(d, i) { if (i < rowCount) { if (vScale(d.tempmin) > 50) { return "hsl(20, 100%, " + String(150 - vScale(d.tempmin)) + "%)" } else { return "hsl(180, 100%, " + String(50 + vScale(d.tempmin)) + "%)" } } else if (i >= rowCount) { if (vScale(d.tempmax) > 50) { return "hsl(20, 100%, " + String(150 - vScale(d.tempmax)) + "%)" } else { return "hsl(180, 100%, " + String(50 + vScale(d.tempmax)) + "%)" } } }) .attr("stroke", "#222244") .style("stroke-width", "2px") // Set tooltip behavior .on("mouseover", function(d, i) { d3.select('#tooltip') .html(d.datetime.toDateString() + "<br>" + "High: " + d.tempmax + " F<br>" + "Average: " + d.temp + " F<br>" + "Low: " + d.tempmin + " F<br>" + "Wind Speed: " + d.windspeed + " MPH<br>" + "Relative Humidity: " + d.humidity + "%<br>" + "Conditions: " + d.conditions) .transition() .duration(200) .style("opacity", 0.95) }) .on("mouseout", function() { d3.select("#tooltip") .style("opacity", 0) }) .on("mousemove", function() { d3.select("#tooltip") .style("left", (d3.event.pageX + 10) + "px") .style("top", (d3.event.pageY + 10) + "px") }); const weekMap = { 0: "Sun", 1: "Mon", 2: "Tue", 3: "Wed", 4: "Thu", 5: "Fri", 6: "Sat" }; // Draw labels function drawLabels(obj) { for (let key in obj) { svg.append("g") .attr("transform", "translate(" + String(300 + 255 * Math.cos(key * 2 * Math.PI / 7 + 3 * Math.PI / 2)) + "," + String(300 + 255 * Math.sin(key * 2 * Math.PI / 7 + 3 * Math.PI / 2)) + ")" + "rotate(" + String(90 + 270 + key * 360 / 7) + ")") .append("text") .style("font-family", "Ubuntu") .style("font-weight", "bold") .attr("fill", "white") .attr("text-anchor", "middle") .text(obj[key]); svg.append("g") .attr("transform", "translate(" + String(300 + 235 * Math.cos(key * 2 * Math.PI / 7 - 0.19 + 3 * Math.PI / 2)) + "," + String(300 + 235 * Math.sin(key * 2 * Math.PI / 7 - 0.19 + 3 * Math.PI / 2)) + ")" + "rotate(" + String(80 + 270 + key * 360 / 7) + ")") .append("text") .style("font-family", "Ubuntu") .attr("fill", "white") .attr("text-anchor", "middle") .text("Low"); svg.append("g") .attr("transform", "translate(" + String(300 + 235 * Math.cos(key * 2 * Math.PI / 7 + 0.19 + 3 * Math.PI / 2)) + "," + String(300 + 235 * Math.sin(key * 2 * Math.PI / 7 + 0.19 + 3 * Math.PI / 2)) + ")" + "rotate(" + String(100 + 270 + key * 360 / 7) + ")") .append("text") .style("font-family", "Ubuntu") .attr("fill", "white") .attr("text-anchor", "middle") .text("High"); }; }; drawLabels(weekMap); }); // 16-Day Forecast Chart d3.json(forecastUrl, function(data) { parseDate(data.days, "datetime"); // Measure max and min const xmax = new Date(d3.max(data.days, d => d.datetime)); const xmin = d3.min(data.days, d => d.datetime); const ymax = d3.max(data.days, d => d.tempmax); const ymin = d3.min(data.days, d => d.tempmin); // Set scales const xScale = d3.scaleTime() .domain([xmin, xmax]) .range([xpad, w2 - xpad]); const yScale = d3.scaleLinear() .domain([Number(ymin) - 5, Number(ymax) + 5]) .range([h2 - ypad, ypad]); // Create SVG const svg = d3.select("#container-left2") .append("svg") .attr("width", w2) .attr("height", h2); // Average temperature path svg.append("path") .datum(data.days) .attr("fill", "none") .attr("stroke", "white") .attr("stroke-width", 2) .attr("d", d3.line() .curve(d3.curveMonotoneX) .x(d => xScale(d.datetime)) .y(d => yScale(d.temp)) ); // Circles on average temperature path svg.selectAll("circle") .data(data.days) .enter() .append("circle") .attr("class", "circle") .attr("fill", "white") .attr("cx", d => xScale(d.datetime)) .attr("cy", d => yScale(d.temp)) .attr("r", 6) // Set tooltip behavior .on("mouseover", function(d, i) { d3.select('#tooltip') .html(d.datetime.toDateString() + "<br>" + "High: " + d.tempmax + " F<br>" + "Average: " + d.temp + " F<br>" + "Low: " + d.tempmin + " F<br>" + "Wind Speed: " + d.windspeed + " MPH<br>" + "Relative Humidity: " + d.humidity + "%<br>" + "Change of Precipitation: " + d.precipprob + "%<br>" + "Conditions: " + d.conditions) .transition() .duration(200) .style("opacity", 0.95) }) .on("mouseout", function() { d3.select("#tooltip") .style("opacity", 0) }) .on("mousemove", function() { d3.select("#tooltip") .style("left", (d3.event.pageX + 10) + "px") .style("top", (d3.event.pageY + 10) + "px") }); // Max temperature path svg.append("path") .datum(data.days) .attr("fill", "none") .attr("stroke", "orange") .attr("stroke-width", 2) .attr("d", d3.line() .curve(d3.curveMonotoneX) .x(d => xScale(d.datetime)) .y(d => yScale(d.tempmax)) ); // Min temperature path svg.append("path") .datum(data.days) .attr("fill", "none") .attr("stroke", "cyan") .attr("stroke-width", 2) .attr("d", d3.line() .curve(d3.curveMonotoneX) .x(d => xScale(d.datetime)) .y(d => yScale(d.tempmin)) ); // Draw axes const xAxis = d3.axisBottom(xScale) .tickFormat(d3.timeFormat("%d")); const yAxis = d3.axisLeft(yScale); svg.append("g") .attr("transform", "translate(0," + (h2 - ypad) + ")") .attr("id", "x-axis") .attr("class", "axis") .call(xAxis); svg.append("g") .attr("transform", "translate(" + xpad + ",0)") .attr("id", "y-axis") .attr("class", "axis") .call(yAxis); }); // Current Conditions KPI d3.json(currentUrl, function(data) { data.location.currentConditions.datetime = new Date(data.location.currentConditions.datetime); document.getElementById("today").innerHTML = data.location.currentConditions.datetime.toDateString() + "<br>" + "Temperature: " + data.location.currentConditions.temp + " F<br>" + "Wind Speed: " + data.location.currentConditions.wspd + " MPH<br>" + "Relative Humidity: " + data.location.currentConditions.humidity + "%<br>"; });
/*Almacenamos las urls de las APIs en un objeto*/ const api={PAISES:'https://restcountries.eu/rest/v2/all', VECINOS:'https://api.geodatasource.com/neighbouring-countries'} let lista = document.querySelector('#country'); /*Inicializamos el objeto XMLHttpRequest*/ function inicializaXhttp(){ return new XMLHttpRequest(); } function loadPage(){ /*1. Traemos la lista de paises a partir de la API "PAISES" */ request = inicializaXhttp(); request.open('GET',api.PAISES,true); request.send(); request.onload = loadCountries; } function loadCountries(){ /* 2. La respuesta de la API es un JSON que tenemos que convertir a un objeto para poder tratarlo */ let paises = JSON.parse(request.responseText); lista.options[0] = new Option("--selecciona--"); /*3. Recorremos la colección de países y obtenemos las propiedades name y alpha2Code que asignamos al texto y value de cada una de las opciones del desplegable*/ for(let pais of paises){ let option = new Option(pais.name); option.value = pais.alpha2Code; lista.add(option); } /*4. Asociamos el evento de cambio al selector para detectar cuando nos seleccionen una de las opciones */ lista.addEventListener('change',loadNeighbours); } function loadNeighbours(){ /*5. A partir de la opción seleccionada recuperamos la información de la API "VECINOS" */ let country = lista.options[lista.selectedIndex].value; if(country){ request = inicializaXhttp(); /*6. Los parámetros se pasan por la URL en los métodos GET a partir del símbolo "?", enlazando cada par clave:valor con el símbolo "&" */ request.open('GET',api.VECINOS+'?key=7PUKVKJJCBNQHZQOQO3ZJVBCVHZJHTEP&country_code='+country,true); request.send(); request.onload = showNeighbours; } } function showNeighbours(){ /*7. Leemos la respuesta de la API y la asociamos al contenido del textarea */ let neighbours = JSON.parse(request.responseText); let html=''; for(let vecino of neighbours){ html+=vecino.country_name+' | '; } document.querySelector('#neighbours').innerHTML = html; } window.addEventListener('load',loadPage);
(function () { "use strict"; var fs = require('fs'); var _ = require('underscore'); var util = require('util'); var when = require('when'); module.exports = function (_stream, _bytesCount, _width_set) { var avgbuf = [ ], avgindex = [ ], peakbuf = [ ]; function update(chunk) { for (var chunkIndex = 0; chunkIndex < chunk.length; chunkIndex ++) { var word = chunk.readUInt8(chunkIndex); word -= 128; word /= 128; for (var i = 0; i < _width_set.length; i ++) { if (avgindex[i] >= avgbuf[i].length) { avgindex[i] = 0; } avgbuf[i][avgindex[i]] = word; avgindex[i] ++; if (avgindex[i] >= avgbuf[i].length) { peakbuf[i].push(_.max(avgbuf[i])); } } } } for (var i = 0; i < _width_set.length; i ++) { var avgbuflen = parseInt(_bytesCount / _width_set[i]); avgbuf[i] = new Array(avgbuflen); avgindex[i] = 0; peakbuf[i] = []; } return when.promise(function (resolve, reject) { _stream.on('data', function (chunk) { update(chunk); }); _stream.on('end', function () { resolve(peakbuf); }); _stream.on('error', function (err) { reject(err); }); }); }; })();
class Ball { constructor(x,y,width,height){ var options = { isStatic : false, restituion:0.3, friction:0.5, density:1.2 } this.body = Bodies.circle(200,500, 5, [options] ) World.add(this.body,world) } display(){ ellipseMode(CENTER); fill("dark pink") ellipse(200,500,5) } }