text
stringlengths
7
3.69M
import React from 'react'; import './Cards.css'; const MainCard = ({message, closeMenu}) => { return( <article onClick={closeMenu} className="br2 shadow-2 bw2 my-bg"> <h6 className="pv1 ml3">{message}</h6> <hr/> <div className = "circle"> <span className="count pv1">0</span> </div> <div className="pa2 ph3-ns pb3-ns"> <section className = "border"> <div> <span className="count1">0</span> <p>Acceptance SLA about to breach</p> </div> <div> <span className="count1">0</span> <p>Invoiced SLA about to breach</p> </div> </section> </div> </article> ); } export default MainCard;
import * as React from 'react'; import { XYPlot, XAxis, YAxis, HorizontalGridLines, VerticalGridLines, LineSeries, MarkSeries } from 'react-vis'; import {getColorFromWindSpeed} from "./Hurricane"; function StormInfo(props) { const {stormInfo, selectedPoint, onChange, exitStormInfo} = props; function getColorToHex(windSpeed) { const color = getColorFromWindSpeed(windSpeed); return "#" + ((1 << 24) + (color[0] << 16) + (color[1] << 8) + color[2]).toString(16).slice(1); } const pointInfo = stormInfo.track_points[selectedPoint]; return ( <div className="storm-info"> <div style={{marginBottom: "20px"}}> <h3 style={{float: "left", marginTop: 0, marginBottom: 0}}>{stormInfo["name"]} {stormInfo["season"]}</h3> <button onClick={evt => exitStormInfo(evt)} style={{float: "right", }}>&times;</button> </div> {pointInfo["ir_image_url"] && <div> <img src={pointInfo["ir_image_url"]} style={{width: "300px"}}/> </div> } <div> <XYPlot xType="time" width={300} height={150} style={{marginBottom: "10px"}} > <XAxis title="Time" /> <YAxis title="Wind Speed (knots)" /> <LineSeries stroke="black" data={stormInfo.track_points.map((point, i) => ({ x: new Date(point.date_time).getTime(), y: point.wind, }))} /> <MarkSeries fillType="literal" strokeType="literal" data={stormInfo.track_points.map((point, i) => ({ x: new Date(point.date_time).getTime(), y: point.wind, fill: getColorToHex(point.wind), opacity: i === selectedPoint ? 1 : 0.75, stroke: i === selectedPoint ? "#000000" : "#FFFFFF" }))} size="4px" /> </XYPlot> {stormInfo.min_pressure && <XYPlot xType="time" width={300} height={150} colorType="literal" > <YAxis title="Pressure (mb)" /> {stormInfo.min_pressure && // For some reason this breaks if you remove the conditions <LineSeries color="#000000" data={stormInfo.track_points.map(point => ({ x: new Date(point.date_time).getTime(), y: point.pressure ? point.pressure : 1000 }))} /> } {stormInfo.min_pressure && <MarkSeries colorType="literal" data={[{ x: new Date(pointInfo.date_time).getTime(), y: pointInfo.pressure ? pointInfo.pressure : 1000, color: "#000000" }]} size="4px" /> } </XYPlot> } </div> <div key={'selectedPoint'} className="input"> <label>{"Select Point: "}</label> <button name="backwardSelectedPoint" onClick={evt => onChange(evt)}>{"<"}</button> <input name="selectedPoint" type="range" value={selectedPoint} min={0} max={stormInfo.track_points.length - 1} onChange={evt => onChange(evt)} /> <button name="forwardSelectedPoint" onClick={evt => onChange(evt)}>{">"}</button> </div> <div>Date/Time: {pointInfo.date_time}</div> <div>Wind: {pointInfo.wind} Pressure: {pointInfo.pressure}</div> </div> ); } export default React.memo(StormInfo);
'use strict'; import * as _ from 'underscore'; import * as storage from 'modules/storage'; import * as EventManager from 'modules/events'; var currentPage, prevPage; const pages = [ 'inbox', 'favorites', 'trash' ]; function setPage(page, savePrev) { if (page) { if (_.contains(pages, page)) { if (savePrev) { prevPage = currentPage; } currentPage = page; } else { throw new Error(`AppState page ${page} not found`); } } else if (prevPage) { currentPage = prevPage; } } var currentOverlay = null; const overlays = [ 'settings', 'jobView' ]; function setOverlay(overlay) { if (overlay) { if (_.contains(overlays, overlay)) { currentOverlay = overlay; } else { throw new Error(`AppState overlay ${overlay} not found`); } } else { currentOverlay = null; } } var currentState; const states = [ 'loading', 'ready', 'error', 'empty' ]; function setState(state = 'ready') { if (_.contains(states, state)) { currentState = state; } else { throw new Error(`AppState state ${state} not found`); } } EventManager.on('ready', () => { setPage('inbox'); setState('empty'); }); EventManager.on('listStartUpdate', () => { setState('loading'); }); EventManager.on('jobsReceived', () => { setState('ready'); }); EventManager.on('settingsInit', () => { setOverlay('settings'); }); EventManager.on('folderChanged', options => { var opts = options || {}, folder = opts.folder; if (folder === 'favorites' || folder === 'trash') { let folderData = storage.get(folder); if (!folderData || !folderData.length) { setState('empty'); } } setPage(opts.folder); }); EventManager.on('jobItemInit', () => { setOverlay('jobView'); }); EventManager.on('settingsHide settingsSaved jobItemHide', () => { setOverlay(); }); // ---------------- // public methods // ---------------- // format of state is: (page|overlay).state var pIs = function(state) { state = state.split('.'); var page = state.shift(), stateMatch = (page === currentPage || page === currentOverlay); if (stateMatch && state.length) { stateMatch = false; _.each(state, function(stateItem) { stateItem = stateItem.split('|'); stateItem.every(item => { if (item === currentState) { stateMatch = true; return false; } else { return true; } }); }); } return stateMatch; }; // --------- // interface // --------- export { pIs as is };
// Code your solution in this file! function distanceFromHqInBlocks(someValue) { return Math.abs(42 - someValue); } function distanceFromHqInFeet(someValue) { return 264 * distanceFromHqInBlocks(someValue); } function distanceTravelledInFeet(start, destination) { return Math.abs(start - destination) * 264; } function calculatesFarePrice(start, destination) { const distance = distanceTravelledInFeet(start, destination); if (distance <= 400) { return 0; } else if (distance <= 2000) { return (distance - 400) * 2 / 100; } else if (distance <= 2500) { return 25; } else { return 'cannot travel that far'; } }
import React, { Component } from "react"; import Sidebar from "../Sidebar/Sidebar"; import Dishes from "../Dishes/Dishes"; import SearchPanel from "../SearchPanel/SearchPanel"; import "./SelectDish.css"; class SelectDish extends Component { constructor(props){ super(props); } render() { return ( <div className="SelectDish"> <Sidebar id="sidebarView" model={this.props.model}/> <div id="searchView"> <SearchPanel/> <Dishes /> </div> </div> ); } } export default SelectDish;
'use strict' const hounds = require('../') const quarry = hounds.writers.error() const logTo = hounds.writers.url() let i = 1000 const hunt = hounds.release({ url: 'http://localhost:8111', maxFollows: 25, waitAfterLoadedFor: 5000, before: nightmare => { return nightmare .viewport(1200, 800) .goto('http://localhost:8111/user/login') .type('input[name=name]', process.env.HOUNDS_EXAMPLE_AUTH_USER) .type('input[name=pass]', process.env.HOUNDS_EXAMPLE_AUTH_PASS) .click('input[name=op]') .wait(2000) }, after: nightmare => { return nightmare .goto('http://localhost:8111/user/logout') }, screenshot: (url) => { return `${process.cwd()}/${i++}_${url.replace(/[^\w]/g, '-')}.png` }, keepAlive: true, logTo, urlFilter: (url, domainFiltered) => { return /\#./.test(url) && domainFiltered }, nightmare: { show: true, openDevTools: true } }) .on('error', err => { console.error(err) process.exit() }) .on('end', process.exit) hunt.pipe(quarry)
import BaseAxios from 'axios'; import jwtDecode from 'jwt-decode'; import {BASE_URL, BASE_TEST_URL} from '../api/config'; export const axios = BaseAxios.create({baseURL: BASE_URL}); export const testAPi = BaseAxios.create({baseURL: BASE_TEST_URL}); const whiteList = ['auth']; const inWhiteList = (url) => { const match = whiteList.find((i) => url.includes(i)); return !!match; }; export const tokenValid = (token) => { if (!token) return false; try { const currentDate = new Date(); const {exp} = jwtDecode(token); if (exp === undefined) return false; return !(exp * 1000 < currentDate.getTime()); } catch (error) { return false; } }; export const setAxiosInterceptors = (token, logout) => { axios.interceptors.request.use( async (request) => { if (token && !inWhiteList(request.url ?? '')) { const newRequest = {...request}; newRequest.headers.Authorization = 'Bearer ' + token; return newRequest; } return request; }, (error) => { console.log('got error in request ', error); return Promise.reject(error); }, ); axios.interceptors.response.use( (response) => { console.log('got response data ', response); return response?.data ?? response; }, async (error) => { if ( error && error.response && (error.response.status === 401 || error.response.status === 403) && token ) { logout(); return null; } console.log('got response data err', error); return Promise.reject(error); }, ); }; testAPi.interceptors.response.use( (response) => { return response.data; }, async (error) => { // const { token } = store.getState().login if ( error && error.response && (error.response.status === 401 || error.response.status === 403) // && token ) { // eslint-disable-next-line no-void // void store.dispatch(doLogout()) return null; } return Promise.reject(error); }, );
/* Copyright 2016-2018 Stratumn SAS. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { sign as nacl } from 'tweetnacl'; import { encodePEM, decodePEM, encodePKToPEM, decodePKFromPEM, encodeSKToPEM, decodeSKFromPEM, encodeSignatureToPEM, decodeSignatureFromPEM } from '../src/encoding'; const randomBuffer = length => Buffer.from( new Uint8Array(length).map(() => Math.random() * Math.floor(255)) ); describe('#encodePEM', () => { it('encodes a Buffer to a PEM string with a label', () => { const buf = Buffer.from([0, 1, 2]); const encoded = encodePEM(buf, 'label'); const { body, label } = decodePEM(encoded); body.should.deepEqual(buf); label.should.be.exactly('label'); }); it('throws an error if no label is specified', () => { const buf = Buffer.from([1, 2, 3]); (() => encodePEM(buf)).should.throw('PEM encoding failed: missing label'); }); }); describe('#decodePEM', () => { it('decodes a PEM string and returns its body and label', () => { const PEMstr = `-----BEGIN label----- AAEC -----END label-----`; const { body, label } = decodePEM(PEMstr); body.should.deepEqual(Buffer.from([0, 1, 2])); label.should.be.exactly('label'); }); it('decodes a PEM string with extra empty lines', () => { const PEMstr = '-----BEGIN label-----\nAAEC\n\n-----END label-----\n\n\n'; const { body, label } = decodePEM(PEMstr); body.should.deepEqual(Buffer.from([0, 1, 2])); label.should.be.exactly('label'); }); it('throws an error if no labels are found', () => { const PEMstr = `-----BEGIN ----- AAEC -----END -----`; (() => decodePEM(PEMstr)).should.throw('Missing PEM label'); }); it('throws an error if begin and end header do not match', () => { const PEMstr = `-----BEGIN one----- AAEC -----END two-----`; (() => decodePEM(PEMstr)).should.throw( 'Mismatch between BEGIN and END labels' ); }); it('throws an error if the format is wrong', () => { const PEMstr = 'test'; (() => decodePEM(PEMstr)).should.throw('string is not PEM encoded'); }); it('throws an error if the provided data is not a string', () => { (() => decodePEM(null)).should.throw('PEM data must be a string'); }); }); describe('#encodePKToPEM', () => { const keyType = 'ED25519 PUBLIC KEY'; const fakePK = randomBuffer(nacl.publicKeyLength); it('encodes a byte array to a PEM string containing the ASN.1 representation of a public key', () => { const PKInfo = encodePKToPEM(fakePK, keyType); decodePEM(PKInfo, keyType).should.not.throw(); decodePKFromPEM(PKInfo, keyType).should.deepEqual({ publicKey: fakePK, type: keyType }); }); it('handles bad key types', () => (() => encodePKToPEM(fakePK, 'bad')).should.throw( 'Could not encode public key: unknown public key algorithm' )); it('handles bad key format', () => (() => encodePKToPEM({}, keyType)).should.throw( 'Could not encode public key: Unsupported type: object at: ["publicKey"]' )); }); describe('#decodePKFromPEM', () => { const testPEMPublicKey = `-----BEGIN ED25519 PUBLIC KEY----- MCowBQYDK2VwAyEA4lGE3bR+ZeEO3N8dOjAEVWy8dpW36m601kae1tStpFI= -----END ED25519 PUBLIC KEY-----`; it('decodes a PEM string containing the ASN.1 representation of a public key to a byte array', () => { const { publicKey, type } = decodePKFromPEM(testPEMPublicKey); publicKey.length.should.be.exactly(nacl.publicKeyLength); encodePKToPEM(publicKey, type).should.be.exactly(testPEMPublicKey); }); it('handles bad key format', () => (() => decodePKFromPEM({})).should.throw('PEM data must be a string')); it('handles bad key encoding', () => (() => decodePKFromPEM( '-----BEGIN ED25519 PUBLIC KEY-----\nBEAu3UcG9B1K7E7YbzeVUJPbU9v62rSQPSr87rCbPkwCg+JRhN20fmXhDtzfHTow\n-----END ED25519 PUBLIC KEY-----' )).should.throw( 'Could not decode public key: Failed to match tag: "seq" at: (shallow)' )); }); describe('#encodeSKToPEM', () => { const keyType = 'ED25519 PUBLIC KEY'; const fakeSK = randomBuffer(nacl.secretKeyLength); it('encodes a byte array to a PEM string containing the ASN.1 representation of a secret key', () => { const SKInfo = encodeSKToPEM(fakeSK, keyType); decodePEM(SKInfo, { tag: keyType }).should.not.throw(); decodeSKFromPEM(SKInfo, keyType).should.deepEqual({ secretKey: fakeSK, type: keyType }); }); it('handles bad key types', () => (() => encodePKToPEM(fakeSK, 'bad')).should.throw( 'Could not encode public key: unknown public key algorithm' )); it('handles bad key format', () => (() => encodePKToPEM({}, keyType)).should.throw()); }); describe('#decodeSKFromPEM', () => { const testPEMPrivateKey = `-----BEGIN ED25519 PRIVATE KEY----- BEAu3UcG9B1K7E7YbzeVUJPbU9v62rSQPSr87rCbPkwCg+JRhN20fmXhDtzfHTow BFVsvHaVt+putNZGntbUraRS -----END ED25519 PRIVATE KEY-----`; it('decodes a PEM string containing the ASN.1 representation of a public key to a byte array', () => { const { secretKey, type } = decodeSKFromPEM(testPEMPrivateKey); secretKey.length.should.be.exactly(nacl.secretKeyLength); encodeSKToPEM(secretKey, type).should.be.exactly(testPEMPrivateKey); }); it('handles bad key format', () => (() => decodeSKFromPEM({})).should.throw('PEM data must be a string')); it('handles bad key encoding', () => (() => decodeSKFromPEM( '-----BEGIN ED25519 PRIVATE KEY-----\nBEAu3UcG9B1K7E7YbzeVUJPbU9v62rSQPSr87rCbPkwCg+JRhN20fmXhDtzfHTow\n-----END ED25519 PRIVATE KEY-----' )).should.throw( 'Could not decode secret key: Failed to match body of: "octstr" at: (shallow)' )); }); describe('#encodeSignatureToPEM', () => { const tag = 'MESSAGE'; const fakeSig = randomBuffer(nacl.signatureLength); it('encodes a byte array signature to a PEM string', () => { const PEMSig = encodeSignatureToPEM(fakeSig, tag); decodePEM(PEMSig, { tag }).should.not.throw(); decodeSignatureFromPEM(PEMSig).signature.should.deepEqual(fakeSig); }); it('handles bad signature format', () => (() => encodeSignatureToPEM(null)).should.throw()); }); describe('#decodeSignatureFromPEM', () => { const testPEMSignature = `-----BEGIN MESSAGE----- epuH8CD4adt7XVG8A5tFUAN+X0bV9ytanYWjCofsITg35gdXAKPiwMWa5hcdKGnG kOdXBkj4/e30X6rvntzeCA== -----END MESSAGE-----`; it('decodes o a PEM string containing the signature to a byte array', () => { const { signature, type } = decodeSignatureFromPEM(testPEMSignature); signature.length.should.be.exactly(nacl.signatureLength); encodeSignatureToPEM(signature, type).should.be.exactly(testPEMSignature); }); it('handles bad signature format', () => (() => decodeSignatureFromPEM(null)).should.throw()); });
import { always, compose, complement, concat, curry, defaultTo, either, flatten, flip, head, ifElse, includes, isEmpty, isNil, last, map, match, pipe, split, splitAt, uniq, } from "ramda"; const fconcat = flip(concat); // truncate :: Number -> String -> String export const truncate = curry((length, content) => pipe( splitAt(length), head, fconcat("...") )(content) ); // getIdFromUrl :: String -> String export const getIdFromFilmUrl = pipe( match(/films\/[0-9]*/gi), map(split("/")), flatten, last ); // integerToRoman :: Number -> String export const integerToRoman = integer => { const toRoman = defaultTo(0, integer) switch (toRoman) { case 1: return "I"; case 2: return "II"; case 3: return "III"; case 4: return "IV"; case 5: return "V"; case 6: return "VI"; case 7: return "VII"; default: return toRoman.toString(); } }; const colors = ["red","orange","yellow","olive","green","teal","blue","violet","purple","pink","brown","grey","black"] const predicate = (input) => colors => includes(input, colors) export const getColor = input => ifElse(predicate(input), always(input), always('blue'))(colors) export const addToArray = visit => compose(uniq, concat([visit])) export const isEmptyOrNull = either(isEmpty, isNil) export const isNotEmpty = complement(isEmptyOrNull)
import React, { useContext, useEffect, useState } from 'react'; import NavBar from '../NavBar/NavBar'; import './HomeDetails.css'; import { useForm } from 'react-hook-form'; import homeDetailImage1 from '../../../images/Rectangle 410.png'; import homeDetailImage2 from '../../../images/Rectangle 409.png'; import homeDetailImage3 from '../../../images/Rectangle 408.png'; import homeDetailImage4 from '../../../images/Rectangle 407.png'; import temporaryImage from '../../../images/Rectangle 398.png'; import { UserContext } from '../../../App'; import { Link, useHistory, useParams } from 'react-router-dom'; const HomeDetails = () => { const { register, handleSubmit, watch, errors } = useForm(); const [rentHouse, setRentHouse] = useContext(UserContext); const [loggedInUser, setLoggedInUser]= useContext(UserContext); const [allApartments, setAllApartments] = useState([]); const {_id} = useParams(); const history = useHistory(); useEffect(() => { fetch('https://powerful-fjord-39182.herokuapp.com/apartments') .then(res => res.json()) .then(data => { setAllApartments(data); }) },[]) const house = allApartments.find(apartment => apartment._id === _id) || { }; const onSubmit = (data, event) => { const apartmentPrice = house.price; const apartmentTitle = house.title; const newBooking = {...data, apartmentPrice, apartmentTitle}; fetch('https://powerful-fjord-39182.herokuapp.com/addBooking',{ method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(newBooking) }) .then(res=>res.json()) .then(data=>{ if(data){ alert('Your booking is successfully complete'); event.target.reset(); history.push('/huntPage') } }) console.log(rentHouse) } return ( <div style={{backgroundColor: '#E5E5E5'}} className="pb-5"> <NavBar /> <div className="row headingStyle "> <div className="col-md-12 pt-5"> <h1 className="text-center text-white mt-5 fonts">Apartment</h1> </div> </div> <div className="container"> <div className="row justify-content-center mt-4"> <div className="col-md-8"> <img src={temporaryImage} className="img-fluid" alt=""/> <div className="row justify-content-center mt-4"> <div className="col-md-3"> <img src={homeDetailImage1} className="img-fluid" alt=""/> </div> <div className="col-md-3"> <img src={homeDetailImage2} className="img-fluid" alt=""/> </div> <div className="col-md-3"> <img src={homeDetailImage3} className="img-fluid" alt=""/> </div> <div className="col-md-3"> <img src={homeDetailImage4} className="img-fluid" alt=""/> </div> </div> <div className="row justify-content-between mt-4"> <div className="pl-3"> <h2>{house.title}</h2> </div> <div className="pr-3"> <h2 style={{color: '#275A53', fontWeightAbsolute:'bold'}}>${house.price}</h2> </div> </div> <p className="mt-3">3000 sq-ft., {house.bedroom} Bedroom, Semi-furnished, Luxurious, South facing Apartment for Rent in Rangs Malancha, Melbourne.</p> <div className="mt-4"> <h4>Price Details</h4> <p className="mt-3">Rent/Month: $550 (negotiable) Service Charge : 8,000/= Tk per month, subject to change Security Deposit : 3 month’s rent Flat Release Policy : 3 months earlier notice required</p> </div> <div className="mt-4"> <h4>Property Details</h4> <p className="mt-3">Address & Area : Rangs Malancha, House-68, Road-6A (Dead End Road), Dhanmondi Residential Area. Flat Size : 3000 Sq Feet. Floor : A5 (5th Floor) (6 storied Building ) (South Facing Unit) Room Category : {house.bedroom} Large Bed Rooms with {house.bedroom} Verandas, Spacious Drawing, Dining & Family Living Room, Highly Decorated Kitchen with Store Room and Servant room with attached Toilet. Facilities : 1 Modern Lift, All Modern Amenities & Semi Furnished. Additional Facilities : a. Electricity with full generator load, b. Central Gas Geyser, c. 2 Car Parking with 1 Driver’s Accommodation, d. Community Conference Hall, e. Roof Top Beautified Garden and Grassy Ground, f. Cloth Hanging facility with CC camera </p> </div> </div> <div className="col-md-4 p-3 formStyle "> <div className="pt-4"> <form onSubmit={handleSubmit(onSubmit)} style={{backgroundColor: '#F4F4F4'}}> <div className="form-group"> <input type="text" name="name" className="form-control" placeholder="Full Name" defaultValue={loggedInUser.name} ref={register({ required: true })} /> {errors.name && <span className="error">Name is required</span>} </div> <div className="form-group"> <input type="text" name="phone" className="form-control" placeholder="Phone No" ref={register({ required: true })}/> {errors.name && <span className="error">Phone Number is required</span>} </div> <div className="form-group"> <input type="email" name="email" className="form-control" placeholder="Email Address" defaultValue={loggedInUser.email} ref={register({ required: true })}/> {errors.name && <span className="error">Email is required</span>} </div> <div className="form-group"> <textarea name="message" className="form-control" rows="4" placeholder="Message" ref={register({ required: true })}></textarea> {errors.name && <span className="error">Message is required</span>} </div> <input type="submit" className="btn btn-block btnStyle" value="Request Booking"/> </form> </div> </div> </div> </div> </div> ); }; export default HomeDetails;
const initState = { activeElementId: 1, stepsNumber: 4, showFinal: false } export default function topBar (state = initState, action) { switch (action.type) { case 'INCREMENT_ACTIVE_ID': return { ...state, activeElementId: state.activeElementId + 1 } case 'DECREMENT_ACTIVE_ID': return { ...state, activeElementId: state.activeElementId - 1 } case 'SHOW_FINAL_INFO': return { ...state, showFinal: true } case 'START_SURVEY': return { ...initState } default: return state; } }
import React from 'react'; import expect from 'expect'; import { shallow } from 'enzyme'; import Comment from '../../containers/Comment'; describe('Comment', () => { it('adds is-author class is user is author', () => { const comment = { author_id: 0, datetime: '2015-01-23T18:31:43.511Z' }; const wrapper = shallow(<Comment currentUser={0} {...comment} />); expect(wrapper.find('li').hasClass('is-author')).toEqual(true); }); it('sets isAuthor in state correctly', () => { const comment = { author_id: 0, datetime: '2015-01-23T18:31:43.511Z' }; const wrapper = shallow(<Comment currentUser={0} {...comment} />); expect(wrapper.state().isAuthor).toEqual(true); }); });
import React from 'react' import styles from './ShowCaseSection.styl' const IMAGES = [ require('./assets/resize_bags/JPEG/Pack-1135.jpg'), require('./assets/resize_bags/JPEG/Pack-1137.jpg'), require('./assets/resize_bags/JPEG/Pack-1140.jpg'), require('./assets/resize_bags/JPEG/Pack-1166.jpg'), require('./assets/resize_bags/JPEG/Pack-1154.jpg'), require('./assets/resize_bags/JPEG/Pack-1156.jpg'), require('./assets/resize_bags/JPEG/Pack-1146.jpg'), require('./assets/resize_bags/JPEG/Pack-1187.jpg') ] const ShowCaseSection = React.createClass({ renderBlockImage (image) { return ( <div className={styles.blockImageContainer} style={{ backgroundImage: `url(${image})`, backgroundSize: 'cover', backgroundPosition: 'center' }} > </div> ) }, render () { return ( <div className={styles.container}> {IMAGES.map(x => this.renderBlockImage(x))} </div> ) } }) export default ShowCaseSection
// TODO refactor/complete import React from 'react'; import { makeStyles } from '@material-ui/core'; const useStyles = makeStyles(theme => ({ root: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, zIndex: 2000, backgroundColor: 'rgba(255,255,255,0.6)', }, })); export default function DisableOverlay({ before, after, light }) { const classes = useStyles(); return <div className={classes.root} />; }
'use strict'; module.exports = function(Pingconsumer1) { };
"use strict"; const path = require('path'); const webpack = require('webpack'); const htmlPlugin = require('html-webpack-plugin'); const openBrowserPlugin = require('open-browser-webpack-plugin'); const DashboardPlugin = require('webpack-dashboard/plugin'); const autoprefixer = require('autoprefixer'); const PATHS = { root: path.join(__dirname, '/'), app: path.join(__dirname, 'app'), images: path.join(__dirname, 'img'), css: path.join(__dirname, 'app/css'), build: path.join(__dirname, 'dist') }; const options = { host: 'localhost', port: '3000' }; module.exports = { entry: { app: PATHS.app+"/index.js" }, output: { path: PATHS.build, filename: 'bundle.js' }, devServer: { historyApiFallback: true, hot: true, inline: true, stats: 'errors-only', host: options.host, port: options.port }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['env'] } } }, { test: /\.css$/, exclude: ['/node_modules/'], include: [PATHS.css], use:[ { loader: 'css', query: { sourceMap: true, plugins: [], } }, ] } ], }, plugins: [ new DashboardPlugin({port:"3001"}), new webpack.HotModuleReplacementPlugin({ multiStep: true }), new openBrowserPlugin({ url: `http://${options.host}:${options.port}` }) ] }
import DomHelpers from '../helpers/DomHelpers.js'; import SimulationHelpers from '../helpers/SimulationHelpers.js'; const S = new SimulationHelpers(); const D = new DomHelpers(); export default function QAM(d, SB_N0_DB, NO_OF_BITS) { const NO_OF_SYMBOLS = NO_OF_BITS / 3; const M = 8; const RIGHT = d / 2 + (M / 4 - 1) * d; const LEFT = -RIGHT; const Es = 1.5 * (d ** 2); const SER = new Array(SB_N0_DB.length); const SER_THEORETICAL = S.getTheoreticalSerQam8(SB_N0_DB, Es); const constellation = S .linspace(LEFT, RIGHT, d) .map((point) => [[point, d / 2], [point, -d / 2]]) .flat(); const Bk = S.randi([0, 1], NO_OF_BITS); // message const Sk = Bk.reduce((acc, bit, i) => { // modulation if (i % 3 === 0) { const tribit = [bit]; acc.push(tribit); } else { acc[acc.length - 1].push(bit); } return acc; }, []).map((tribit) => constellation[parseInt(tribit.join(''), 2)]); for (let i = 0; i < SB_N0_DB.length; i += 1) { const Nk = S.getAWGN(SB_N0_DB[i], [NO_OF_SYMBOLS, 2]); // AWGN noise const Yk = new Array(NO_OF_SYMBOLS).fill(0).map((_, j) => S.sum(Sk[j], Nk[j])); const sHat = Yk.map(([x1, y1]) => { let shortestDistance = Infinity; let closestPoint; constellation.forEach(([x2, y2]) => { const distance = Math.hypot(x2 - x1, y2 - y1); if (distance < shortestDistance) { shortestDistance = distance; closestPoint = [x2, y2]; } }); return S.dec2bin(D.indexOf(constellation, closestPoint), 3).split('').map((char) => Number(char)); }); const unchangedSymbols = sHat.reduce((acc, symbol, j) => { const s = Bk.slice(3 * j, 3 * j + 3); // eslint-disable-next-line no-param-reassign if (symbol.toString() === s.toString()) acc += 1; return acc; }, 0); SER[i] = 1 - (unchangedSymbols / NO_OF_SYMBOLS); } return [SER, SER_THEORETICAL]; }
import Reveal from 'reveal.js' import { api } from './assets/api' const deck = new Reveal() deck.initialize()
import React, { Fragment } from 'react' import { Route, Switch } from 'react-router-dom' import { LoginSignUp, Home, ShowSource, ShowArticle, SearchSources, SavedArticles } from '../components' const Routes = () => { return( <Fragment> <Switch> <Route exact path='/' component={LoginSignUp}/> <Route exact path='/home' render={routerProps => <Home {...routerProps}/>} /> <Route exact path='/source/search' component={SearchSources} /> <Route exact path='/article/saved' render={routerProps => <SavedArticles {...routerProps}/>} /> <Route path={`/source/:_id`} render={ShowSource} /> <Route path={`/article/:_id`} render={ShowArticle} /> </Switch> </Fragment> ) } export default Routes
export const imageBaseUrl = 'https://image.tmdb.org/t/p/w500'; export const youtubeApiKey = 'AIzaSyDtyPgGm1oQ-06qoFl1MunRyRM_MRZDK3c'; export const theMoveDBApiKey = '52a8b3c73b5f4ab98371169fc9a5ffaa'; export const apiBaseURL = 'https://api.themoviedb.org/3/'; export const noImage = 'https://bento.cdn.pbs.org/hostedbento-prod/filer_public/_bento_media/img/no-image-available.jpg'; //Views Names export const SEARCH_TV_SHOWS_VIEW = 'SEARCH_TV_SHOWS_VIEW'; export const TRAILER_VIEW = 'TRAILER_VIEW';
const test = require('narval') const gpioIn = require('gpio-in-domapic') const Mock = function () { let sandbox = test.sinon.createSandbox() let eventListener const stubs = { init: sandbox.stub().resolves(), events: { on: sandbox.stub().callsFake((eventName, cb) => { eventListener = cb }) } } const Constructor = sandbox.stub(gpioIn, 'Gpio').callsFake(function () { return stubs }) Constructor.eventNames = { CHANGE: 'change' } const restore = () => { sandbox.restore() } return { restore, stubs: { Constructor, instance: stubs }, utils: { getEventListener: () => eventListener } } } module.exports = Mock
function HashMap() { var map = {}; this.setHash = function(key, value) { map["\""+key+"\""] = value; } this.getValue = function(key) { return map["\""+key+"\""]; } } var map = new HashMap(); map.setHash("abc", 5); map.setHash(5, "qw"); console.log(map.getValue("abc")); console.log(map.getValue(5));
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsModeComment = { name: 'mode_comment', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z"/></svg>` };
import React, { Component, PropTypes } from 'react'; import Login from '../components/auth/Login'; export default class LoginPage extends Component { render() { const { login, loadLocale, pushState } = this.props.children; return ( <div id="LoginPage"> Please Login: <Login login={ login } loadLocale={ loadLocale } pushState={ pushState } /> </div> ); } } LoginPage.propTypes = { children: PropTypes.object };
import React, {useContext} from 'react' import {Link} from 'react-router-dom'; import {GlobalState} from '../../../../GS'; function ProductItem({product, isAdmin}) { const state = useContext(GlobalState); const addCart = state.userAPI.addCart; return ( <div className="product_card"> { isAdmin && <input type="checkbox" checked={product.checked}/> } <img src={product.images.url} alt="" /> <div className="product_box"> <h2 title={product.title}>{product.title}</h2> <span>$ {product.price}</span> <p>{product.description}</p> </div> <div className="btn_row"> { isAdmin ? <> <Link id="btn_buy" to="#!"> Delete </Link> <Link id="btn_view" to={`/edit_item/${product._id}`} > Edit </Link> </> : <> <Link id="btn_buy" to="#!" onClick={()=>addCart(product)}> Order </Link> <Link id="btn_view" to={`/detail/${product._id}`} > View </Link> </> } </div> </div> ) } export default ProductItem
//const axios = require('axios').default; function getRequest() { var resultado = document.getElementById("getResult1"); resultado.innerHTML =""; axios.get('http://158.69.194.104:8082/vb/v1/abcd123/config/2') .then(function(response){ console.log(response.data.result.cards[2]); }) .catch(function (error) { // handle error console.log(error); }) }
$(document).ready(function(){ var classTitle = $("h3.title"); classTitle.click(function(){ $(this).next("div").slideToggle("slow"); }); })
const router = require('express').Router() const bodyParser = require("body-parser"); const ab2str = require('arraybuffer-to-string'); const sendEmail = require('./sendEmail') const Web3 = require('web3'); const voucher_codes = require('voucher-code-generator'); const mysql = require('mysql'); const settings = require("./settings.internal"); const ethUtil = require('ethereumjs-util'); const zerorpc = require("zerorpc"); const utils = require("./utils"); const uuid = require('uuid'); router.use(bodyParser.json()) router.post('/signup', (request, response) => { console.log("signup"); try{ //const ApprovalAddress = request.body.ApprovalAddress; const ReferCode = request.body.ReferCode; const FirstName = request.body.FirstName; const LastName = request.body.LastName; const Email = request.body.Email; //const LastLoginTicker = request.body.LastLoginTicker; const Message = request.body.Message; const Signature = request.body.Signature; const LastLoginTicker = Message.replace(/^\D+/g, ''); console.log(LastLoginTicker); const sig = ethUtil.fromRpcSig(Signature); const prefix = new Buffer("\x19Ethereum Signed Message:\n"); const prefixedMsg = ethUtil.sha3( Buffer.concat([prefix, new Buffer(String(Message.length)), ethUtil.toBuffer(Message)]) ); const publicKey = ethUtil.ecrecover(prefixedMsg, sig.v, sig.r, sig.s); const addrBuf = ethUtil.pubToAddress(publicKey); const address = ethUtil.bufferToHex(addrBuf); const ApprovalAddress = address; console.log("Msg: " + Message); console.log("recovered address:" + address); var con = getDBConn(); con.connect(function(err) { con.query("SELECT * FROM UserInfo WHERE ApprovalAddress = ? OR Email = ?", [ApprovalAddress, Email], function (err, result, fields) { if (err) throw err; let id = 0; for(var i=0; i<result.length; i++) { id = result[i].Id; const status = result[i].Status; if(status=='signup') { response.send({status: 'Error', message: 'user already exist'}); return; } break; } if(id>0) { con.query("UPDATE UserInfo SET FirstName = ?, LastName = ?, Email = ?, ApprovalAddress = ?, LastLoginTicker = ?, Status = 'signup' WHERE Id = ?", [FirstName, LastName, Email, ApprovalAddress, LastLoginTicker, id], function (err, result, fields) { if (err) throw err; response.send({status: 'OK', message: 'user created successfully', userId: id}); } ); } else { const ownReferCode = voucher_codes.generate()[0]; con.query("SELECT * FROM SystemSetting", function(err, result, fields){ if (err) throw err; for(var i=0; i<result.length; i++) { var version = result[i].Version; if(version == 'beta'){ var code = result[i].MasterReferCode; if(code != ReferCode) { response.send({status: 'Error', message: 'Invalid Coupon Code for Beta version'}); return; } } break; } console.log("referralCode: " + ReferCode); con.query("INSERT INTO UserInfo (FirstName, LastName, Email, ApprovalAddress, SignupCodeUsed, OwnReferCode, LastLoginTicker, Status) VALUES(?,?,?,?,?,?,?,'signup')", [FirstName, LastName, Email, ApprovalAddress, ReferCode, ownReferCode, LastLoginTicker], function (err, result, fields) { if (err) throw err; const newId = result.insertId; console.log("newId: " + newId); var expDate = new Date(); expDate.setHours(expDate.getHours() + 24); const token= uuid.v4().replace(/-/g,""); con.query("INSERT INTO OAuthAccessToken (UserId, AccessToken, DateExpiration) VALUES (?,?,?)", [newId, token, expDate], function (err, result, fields) { if (err) throw err; response.send({status: 'OK', message: 'user created successfully', userId: newId, token: token}); }); }); }) } }); }); } catch(error){ console.log(error + 'internal_app_error'); throw error; } }) router.post('/login', (request, response) => { try{ console.log("/Login"); //const LastLoginTicker = request.body.LastLoginTicker; const Message = request.body.Message; const Signature = request.body.Signature; const LastLoginTicker = Message.replace(/^\D+/g, ''); const sig = ethUtil.fromRpcSig(Signature); const prefix = new Buffer("\x19Ethereum Signed Message:\n"); const prefixedMsg = ethUtil.sha3( Buffer.concat([prefix, new Buffer(String(Message.length)), ethUtil.toBuffer(Message)]) ); const publicKey = ethUtil.ecrecover(prefixedMsg, sig.v, sig.r, sig.s); const addrBuf = ethUtil.pubToAddress(publicKey); const address = ethUtil.bufferToHex(addrBuf); const ApprovalAddress = address; console.log("wallet: " + ApprovalAddress + ", signature: " + Signature); var con = getDBConn(); con.connect(function(err) { con.query("SELECT * FROM UserInfo WHERE ApprovalAddress = ?", [ApprovalAddress], function (err, result, fields) { if (err) throw err; console.log("ApproverWallet: " + ApprovalAddress); if(result.length==0) { response.send({status: 'Error', message: 'user does not exist'}); return; } var ret = {}; let userId = 0; for(var i=0; i<result.length; i++) { userId = result[i].Id; ret = {FirstName: result[i].FirstName, LasttName: result[i].LastName, Email: result[i].Email, UserId: result[i].Id}; break; } con.query("UPDATE UserInfo SET LastLoginTicker = ? WHERE ApprovalAddress = ?", [LastLoginTicker, ApprovalAddress], function (err, result, fields) { if (err) throw err; var expDate = new Date(); expDate.setHours(expDate.getHours() + 24); const token= uuid.v4().replace(/-/g,""); con.query("INSERT INTO OAuthAccessToken (UserId, AccessToken, DateExpiration) VALUES (?,?,?)", [userId, token, expDate], function (err, result, fields) { if (err) throw err; response.send({status: 'OK', message: 'user login successfully', userId: userId, firstName: ret.FirstName, token: token}); return; } ); }); }); }); } catch(error){ console.log(error + 'internal_app_error'); throw error; } }) router.post('/invite', (request, response) => { try{ console.log("/invite"); const Signature = request.body.Signature; const ApprovalAddress = request.body.ApprovalAddress; const InviteeEmail = request.body.InviteeEmail; const InviterId = request.body.InviterId; console.log("wallet: " + ApprovalAddress + ", signature: " + Signature); //TODO verify signature var con = getDBConn(); con.connect(function(err) { con.query("SELECT * FROM UserInfo WHERE Email = ?", [InviteeEmail], function (err, result, fields) { if (err) throw err; if(result.length>0) { response.send({status: 'Error', message: 'user was already invited'}); return; } con.query("SELECT * FROM UserInfo WHERE Id = ?", [InviterId], function (err, result, fields) { if (err) throw err; let referCode = ""; for(var i=0; i<result.length; i++) { referCode = result[i].OwnReferCode; break; } const signupUrl = settings.system.portalHost + "/signup?email=" + InviteeEmail + "&refercode=" + referCode; var html = settings.invite_email.html; var subject = settings.invite_email.subject; var from = settings.invite_email.from; html = html.replace(/\{signupurl\}/gi, signupUrl); sendEmail(from, InviteeEmail, subject, html); response.send({status: 'OK', message: 'invitation has been sent to user'}); } ); }); }); } catch(error){ console.log(error + 'internal_app_error'); throw error; } }) router.post('/getdetail', (request, response) => { try{ console.log("/getdetail"); const userId = request.body.userId; const email = request.body.email; console.log("userId: " + userId); //TODO verify signature var con = getDBConn(); con.connect(function(err) { let query = "SELECT * FROM UserInfo WHERE Email = ?"; let id = email; if(userId) { query = "SELECT * FROM UserInfo WHERE Id = ?"; id = userId; } con.query(query, [id], function (err, result, fields) { if (err) throw err; if(result.length==0) { response.send({status: 'Error', message: 'user does not exist'}); return; } for(var i=0; i<result.length; i++) { if(!result[i].ApprovalAddress) { response.send({status: 'Error', message: 'user does not signup it'}); return; } const address = result[i].ApprovalAddress.substring(0,6) + '***************************'; response.send({FirstName: result[i].FirstName, LastName: result[i].LastName, Email: result[i].Email, UserId: result[i].Id, ApprovalAddress: address}); return; } }); }); } catch(error){ console.log(error + 'internal_app_error'); throw error; } }) router.post('/getwallet', (request, response) => { try{ console.log("/getwallet"); const token = request.body.token; console.log("token: " + token); //TODO verify signature var con = getDBConn(); con.connect(function(err) { con.query("SELECT * FROM OAuthAccessToken WHERE AccessToken = ?", [token], function (err, result, fields) { if (err) throw err; if(result.length==0) { response.send({status: 'Error', message: 'user is not authenticated'}); return; } let userId = 0; for(var i=0; i<result.length; i++) { userId = result[i].UserId; break; } console.log("userId: " + userId); con.query("SELECT * FROM WalletApprover join Wallet WHERE UserId = ? AND WalletApprover.WalletId = Wallet.Id AND Status <> 'pending'", [userId], function (err, result, fields) { if (err) throw err; if(result.length==0) { response.send({status: 'Error', message: 'user does not setup any wallet yet'}); return; } const walletList = []; for(var i=0; i<result.length; i++) { walletList.push({Wallet: result[i].Wallet, Alias: result[i].Alias}); } response.send({status: 'OK', walletList: walletList}); return; }); }); }); } catch(error){ console.log(error + 'internal_app_error'); throw error; } }) router.post('/createwallet', (request, response) => { try{ console.log("/createwallet"); const WalletType = request.body.WalletType; const EmailList = request.body.EmailList.split(","); const Alias = request.body.Alias; console.log("EmailList: " + EmailList); console.log("Alias: " + Alias); //TODO verify signature var con = getDBConn(); let newEmailList = EmailList.length === 0 ? "" : "'" + EmailList.join("','") + "'"; let userIdList = []; con.connect(function(err) { con.query("SELECT * FROM UserInfo WHERE Email IN (" + newEmailList + ")", function (err, result, fields) { if (err) throw err; if(result.length==0) { response.send({status: 'Error', message: 'user does not exist'}); return; } try{ const addressList = []; for(var i=0; i<result.length; i++) { userIdList.push(result[i].Id); addressList.push(result[i].ApprovalAddress); } const Wallet = "0x00000000000000000000000"; con.query("INSERT INTO Wallet (Wallet,WalletType,Status,Alias) VALUES(?,?,'pending',?)", [Wallet, WalletType, Alias], function (err, result, fields) { if(err) throw err; for(var i=0; i<userIdList.length; i++) { con.query("INSERT INTO WalletApprover (UserId, WalletId) VALUES(?,?)", [userIdList[i], result.insertId], function (err, result, fields) {}); } var from = settings.walllet_email.from; var html = settings.walllet_email.html.replace(/\{ApproverEmailList\}/gi, EmailList.join(",")).replace(/\{WalletId\}/gi, result.insertId); sendEmail(settings.walllet_email.from, settings.system.supportEmail, settings.walllet_email.subject, html); response.send({status: "OK", message: "wallet creation is pending"}); }); } catch(error){ utility.handleError(request, response, error, 'internal_app_error') } }); }); } catch(error){ console.log(error + 'internal_app_error'); throw error; } }) router.post('/logout', (request, response) => { try{ console.log("/logout"); const token = request.body.token; console.log("token: " + token); //TODO verify signature var con = getDBConn(); con.connect(function(err) { var expDate = new Date(); expDate.setMinutes(expDate.getMinutes() - 1); con.query("Update OAuthAccessToken SET DateExpiration = ? WHERE AccessToken = ?", [expDate, token], function (err, result, fields) { if (err) throw err; console.log("log user out:"); response.send({status: 'OK', message: 'user signout successfully'}); }); }); } catch(error){ console.log(error + 'internal_app_error'); throw error; } }) router.post('/transferfund', (request, response) => { try{ var data = request.body.data; var fromAccount = request.body.fromAccount; var toAddress = request.body.toAddress; var amount = request.body.amount; var client = new zerorpc.Client(); client.connect(settings.system.rpcUrl); client.on("error", function(error) { console.error("RPC client error:", error); }); client.invoke("get_signer_count", fromAccount, function(error, result, more) { if(error) { console.error(error.message); response.send({error: error.message}) return; } else { client.invoke("init_tx", data, function(error, result, more) { if(error) { console.error(error.message); response.send({error: error.message}) return; } else { var result = ab2str(result); var txid = result.result; } if(!more) { console.log("Done."); } }); } if(!more) { console.log("Done."); } }); } catch(error){ console.log(error + 'internal_app_error'); throw error; } }) var getDBConn = () => { var conn = mysql.createConnection({ host: settings.dbconnection.host, user: settings.dbconnection.user, password: settings.dbconnection.password, database: settings.dbconnection.database, }); return conn; } module.exports = router
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Created with IntelliJ IDEA. * User: Natalia.Ukhorskaya * Date: 3/30/12 * Time: 3:37 PM */ var RunProvider = (function () { function RunProvider() { var instance = { onExecutionFinish:function (data) { }, onFail:function (message) { }, onErrorsFound:function(message){ }, run:function (configuration, programText, args) { run(configuration, programText, args); } }; function run(configuration, programText, args) { if (configuration.type == Configuration.type.JAVA) { runJava(configuration, programText, args); } else { runJs(configuration, programText, args); } } function runJava(configuration, programText, args) { var confTypeString = Configuration.getStringFromType(configuration.type); $.ajax({ url:generateAjaxUrl("run", confTypeString), context:document.body, success:function (data) { if (checkDataForNull(data)) { if (checkDataForException(data)) { if (isDataForHighlighting(data)) { instance.onErrorsFound(data); } else { instance.onExecutionFinish(data); } } else { instance.onFail(data); } } else { instance.onFail("Incorrect data format.") } }, dataType:"json", type:"POST", data:{text:programText, consoleArgs:args}, timeout:10000, error:function (jqXHR, textStatus, errorThrown) { instance.onFail(textStatus + " : " + errorThrown); } }); } function runJs(configuration, programText, args) { Kotlin.modules = { stdlib: Kotlin.modules.stdlib, builtins: Kotlin.modules.builtins }; if (configuration.mode == Configuration.mode.CLIENT.name) { try { var data; try { data = $("#myapplet")[0].translateToJS(programText, args); data = eval(data); } catch (e) { loadJsFromServer(configuration, programText, args); return; } if (checkDataForNull(data)) { if (checkDataForException(data)) { if (isDataForHighlighting(data)) { instance.onErrorsFound(data); } else { var dataJs; try { dataJs = eval(data[0].text); } catch (e) { instance.onFail(e); return; } var output = [ {"text":safe_tags_replace(dataJs), "type":"out"}, {"text":data[0].text, "type":"toggle-info"} ]; instance.onExecutionFinish(output); } } else { instance.onFail(data); } } else { instance.onFail("Incorrect data format."); } } catch (e) { instance.onFail(e); } } else { loadJsFromServer(configuration, programText, args); } } function loadJsFromServer(configuration, i, arguments) { var confTypeString = Configuration.getStringFromType(configuration.type); $.ajax({ url:generateAjaxUrl("run", confTypeString), context:document.body, success:function (data) { if (checkDataForNull(data)) { if (checkDataForException(data)) { if (isDataForHighlighting(data)) { instance.onErrorsFound(data); } else { var dataJs; try { dataJs = eval(data[0].text); } catch (e) { instance.onFail(e); return; } var output = [ {"text":safe_tags_replace(dataJs), "type":"out"}, {"text":data[0].text, "type":"toggle-info"} ]; instance.onExecutionFinish(output); } } else { instance.onFail(data); } } else { instance.onFail("Incorrect data format."); } }, dataType:"json", type:"POST", data:{text:i, consoleArgs:arguments}, timeout:10000, error:function (jqXHR, textStatus, errorThrown) { instance.onFail(textStatus + " : " + errorThrown); } }); } return instance; } return RunProvider; })();
// LauncherOSX // // Created by Boris Schneiderman. // Modified by Daniel Weck // Copyright (c) 2016 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. define (["jquery", "../helpers"], function($, Helpers) { /** * Wrapper of a smil iterator object. * A smil iterator is used by the media overlay player, to move along text areas which have an audio overlay. * Such areas are specified in the smil model via parallel smil nodes (text + audio). * * @class Models.SmilIterator * @constructor * @param {Models.SmilModel} smil The current smil model */ var SmilIterator = function(smil) { /** * The smil model * * @property smil * @type Models.SmilModel */ this.smil = smil; /** * The current parallel smil node * * @property currentPar * @type object */ this.currentPar = undefined; /** * Resets the iterator. * In practice, looks for the first parallel smil node in the smil model * * @method reset */ this.reset = function() { this.currentPar = findParNode(0, this.smil, false); }; /* this.firstDeep = function(container) { var par = container.nodeType === "par" ? container : findParNode(0, container, false); return par; }; */ // // this.ensureNextValidTextElement = function() // { // if (!this.currentPar) // { // console.debug("Par iterator is out of range"); // return; // } // // while (this.currentPar && !this.currentPar.element) // { // this.next(); // } // }; /** * Looks for a text smil node identified by the id parameter * Returns true if the id param identifies a text smil node. * * @method findTextId * @param {Number} id A smil node identifier * @return {Boolean} */ this.findTextId = function(id) { if (!this.currentPar) { console.debug("Par iterator is out of range"); return; } if (!id) { return false; } while (this.currentPar) { if (this.currentPar.element) { if (id === this.currentPar.text.srcFragmentId) //this.currentPar.element.id { return true; } // OUTER match var parent = this.currentPar.element.parentNode; while(parent) { if (parent.id && parent.id == id) { return true; } parent = parent.parentNode; } //console.log(parent); // INNER match //var inside = this.currentPar.element.ownerDocument.getElementById(id); var inside = $("#" + Helpers.escapeJQuerySelector(id), this.currentPar.element); if (inside && inside.length && inside[0]) { return true; } } // moves to the next parallel smil node this.next(); } return false; } /** * Looks for the next parallel smil node * * @method next */ this.next = function() { if(!this.currentPar) { console.debug("Par iterator is out of range"); return; } this.currentPar = findParNode(this.currentPar.index + 1, this.currentPar.parent, false); }; /** * Looks for the previous parallel smil node * * @method previous */ this.previous = function() { if(!this.currentPar) { console.debug("Par iterator is out of range"); return; } this.currentPar = findParNode(this.currentPar.index - 1, this.currentPar.parent, true); }; /** * Checks if the current parallel smil node is the last one in the smil model * * @method isLast * @return {Bool} */ this.isLast = function() { if(!this.currentPar) { console.debug("Par iterator is out of range"); return; } if (findParNode(this.currentPar.index + 1, this.currentPar.parent, false)) { return false; } return true; } /** * Moves to the parallel smil node given as a parameter. * * @method goToPar * @param {Containter} par A parallel smil node * @return {Boolean} */ this.goToPar = function(par) { while(this.currentPar) { if(this.currentPar == par) { break; } this.next(); } }; /** * Looks for a parallel smil node in the smil model. * * @method findParNode * @param {Number} startIndex Start index inside the container * @param {Models.SMilModel} container The smil model * @param {Boolean} previous True if search among previous nodes * @return {Smil.ParNode} */ function findParNode(startIndex, container, previous) { for(var i = startIndex, count = container.children.length; i >= 0 && i < count; i += (previous ? -1 : 1)) { var node = container.children[i]; if(node.nodeType == "par") { return node; } // assert(node.nodeType == "seq") node = findParNode(previous ? node.children.length - 1 : 0, node, previous); if(node) { return node; } } if(container.parent) { return findParNode(container.index + (previous ? -1 : 1), container.parent, previous); } return undefined; } this.reset(); }; return SmilIterator; });
describe('EventsCollection::indexEvents', function() { var Collection = P.models.calendars.EventCollection, collection; beforeEach(function() { collection = new Collection(); }); it('creates a map of YYYY-MM-DD -> Events', function() { collection.add(new Backbone.Model({ start: '2014-05-13', title: 'foo1' })); collection.add(new Backbone.Model({ start: '2014-05-13', title: 'foo2' })); collection.add(new Backbone.Model({ start: '2014-05-14', title: 'foo3' })); collection.indexEvents(); var keys = Object.keys(collection.eventIndex); expect(keys) .toEqual(['2014-05-13', '2014-05-14']); }); });
import Ember from 'ember'; export default Ember.Controller.extend({ usefulPools: function() { return this.get('model.all').filter((pool) => { return !!pool.get('driverName'); }); }.property('model.all.@each.driverName'), });
import React from "react"; import Logo from "../assets/img/logo.svg"; import User from "../assets/icon/users.svg"; import Server from "../assets/icon/server.svg"; import Location from "../assets/icon/location.svg"; import HeroImage from "../assets/img/Hero-Illustration.svg"; import OfferImage from "../assets/img/Offer-Illustration.svg"; import { Navbar, Nav, Container, Button } from "react-bootstrap"; const Hero = () => { return ( <div> <Navbar expand="lg" className="el_cozy"> <Container> <Navbar.Brand href="#"> <img src={Logo} alt="logo" /> Lasles<span>vpn</span> </Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="me-auto"> <Nav.Link href="#about">About</Nav.Link> <Nav.Link href="#features">Features</Nav.Link> <Nav.Link href="#pricing">Pricing</Nav.Link> <Nav.Link href="#testimonial">Testimonials</Nav.Link> <Nav.Link href="#help">Help</Nav.Link> </Nav> <div className="sign-up-buttons"> <Button variant="outline-primary">Sign In</Button> <Button variant="outline-secondary" className="sign-up"> Sign Up </Button> </div> </Navbar.Collapse> </Container> </Navbar> <Container> <div className="hero-section py-5"> <div className="text-description pe-lg-3"> <p className="fs-1"> Want anything to be <br /> easy with <span>LaslesVPN.</span> </p> <p className="fs-5 mt-3"> Provide a network for all your needs with ease and fun using <span> LaslesVPN</span> discover interesting features from us. </p> <Button variant="outline-primary" className="mt-3"> Get Started </Button> </div> <div className="hero-illustration col-md-5"> <img src={HeroImage} className="img-fluid" alt="" /> </div> </div> </Container> <Container> <div className="hero-summary py-5"> <div className="rey-card col"> <div className="card-image"> <div> <img src={User} className="img-fluid" alt="" /> </div> </div> <div className="card-text"> <p className="number">90+</p> <p className="text">Users</p> </div> </div> <div className="rey-card col"> <div className="card-image"> <div> <img src={Location} className="img-fluid" alt="" /> </div> </div> <div className="card-text"> <p className="number">30+</p> <p className="text">Locations</p> </div> </div> <div className="rey-card col"> <div className="card-image"> <div> <img src={Server} className="img-fluid" alt="" /> </div> </div> <div className="card-text"> <p className="number">50+</p> <p className="text">Servers</p> </div> </div> </div> </Container> <Container> <div className="offer"> <div className="offer-illustration col-md-7"> <img src={OfferImage} className="img-fluid" alt="" /> </div> <div className="offer-text px-md-2"> <p className="fs-1"> We Provide Many <br /> Features You Can Use </p> <p className="fs-5 mt-3"> You can explore the features that we provide with fun and have their own functions each feature. </p> <ul> <li>Powerfull online protection.</li> <li>Internet without borders.</li> <li>Supercharged VPN</li> <li>No specific time limits.</li> </ul> </div> </div> </Container> </div> ); }; export default Hero;
'use strict'; var bunyan = require('bunyan'); var log = bunyan.createLogger({ name: 'request-service-discovery' }); module.exports = log;
module.exports = { Test: { 'VlTitles': require('./test/e2e/components/vl-titles.js'), }, };
// window.open ("yourPageURL","mywindow","status=1,toolbar=0"); // window.onbeforeunload = function() { // return "you can not refresh the page"; // } // $(document).ready(function(){ // $('#continue').click(function(){ // var clickBtnValue = $(this).val(); // var ajaxurl = 'question.php', // data = {'action': clickBtnValue}; // $.post(ajaxurl, data, function (response) { // // Response div goes here. // alert("action performed successfully"); // }); // }); // }); function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); }; $(document).ready(function(){ $(document).on("keydown", disableF5); }); var d_sound = document.getElementById("default_Audio"); var r_sound = document.getElementById("right_Audio"); var f_sound = document.getElementById("false_Audio"); var t_sound = document.getElementById("time_Audio"); var timeleft = 19; var downloadTimer = setInterval(function(){ if(timeleft <= -1){ clearInterval(downloadTimer); t_sound.play(); document.getElementById("countdown").innerHTML = "Time is Out!!!"; var reg_to=("<div id=myModal class=modal><div class=modal-content><span class=close>&times;</span><br><p id=expl_to>အချိန်ပြည့်ပါပြီ။</p><a href=index.php><button name=home id=home>Home</button></a></div></div>"); document.getElementById("myplace").innerHTML=reg_to; $('.modal').css( { 'display': 'block', 'position': 'fixed', 'z-index': '1', 'padding-top': '100px', 'left': '0', 'top': '0', 'width': '100%', 'height': '100%', 'overflow': 'auto', 'background-color': 'rgb(0,0,0)', 'background-color': 'rgba(0,0,0,0.4)' }); $('.modal-content').css( { 'background-color': '#e5edf2', 'margin': 'auto', 'padding': '20px', 'border': '6px solid #f7b733', 'width': '50%', 'border-radius':'10px' }); $('.close').css( { 'color': '#aaaaaa', 'float': 'right', 'font-size': '28px', 'font-weight': 'bold' }); $('.close').hover(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').focus(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').on('click', function(){ $('.modal').css({'display':'none'}); }) // var modal = document.getElementById("myModal"); // window.onclick = function(event) { // if (event.target == modal) { // modal.style.display = "none";} // } } else { document.getElementById("countdown").innerHTML = timeleft + " s"; } timeleft -= 1; }, 1000); $("#loop_num").css({ "display":"inline" }); var ajax=new XMLHttpRequest(); var method="GET"; var url="includes/carry.php"; var asynchronous=true; ajax.open(method,url,asynchronous); ajax.send(); ajax.onreadystatechange=function() { if(this.readyState==4 && this.status==200) { var data= JSON.parse(this.responseText); var ran=$('#suff_num').html(); var a=ran-1; var qid_dis=data[a].qid; var cate_dis=data[a].category; var ques_dis=data[a].question; var op1_dis=data[a].op_one; var op2_dis=data[a].op_two; var op3_dis=data[a].op_three; var op4_dis=data[a].op_four; var ans_dis=data[a].answer; var expl_dis=data[a].expl_a; var btn1_val=$("#btn1").html(); var btn2_val=$("#btn2").html(); var btn3_val=$("#btn3").html(); var btn4_val=$("#btn4").html(); var count_num=$("#cnum").html(); /*button1 functions start here ၊ ၊ ၊ ၊ ၊ ၊ ၊_______________________________________________*/ $('#btn1').click(function () { // $('#myform').css({ // 'display':'block' // }); clearInterval(downloadTimer); if(btn1_val==ans_dis){ r_sound.play(); var reg_true=("<div id=myModal class=modal><div class=modal-content><span class=close>&times;</span><br><p id=expl_t>သင့်အဖြေမှန်ကန်ပါသည်။<br>သင် အမှတ် ၁၀၀ ရရှိပါသည်။<br>"+expl_dis+"</p><form method=post id=myform><a href=question.php><button name=continue_r type=submit id=continue_r>Continue</button></a></form></div></div>"); document.getElementById("myplace").innerHTML=reg_true; $('#continue').click(function(){ // if(count_num=="9"){ // location.replace("testing.php"); // } // location.replace("question.php"); }); // $('#btn1').css({ // 'background':'green', // 'color':'white' // }); $('.modal').css( { 'color':'black', 'display': 'block', 'position': 'fixed', 'z-index': '1', 'padding-top': '100px', 'left': '0', 'top': '0', 'width': '100%', 'height': '100%', 'overflow': 'auto', 'background-color': 'rgb(0,0,0)', 'background-color': 'rgba(0,0,0,0.4)' }); $('.modal-content').css( { 'background-color': '#e5edf2', 'margin': 'auto', 'padding': '20px', 'border': '6px solid rgb(30,170,203)', 'width': '50%', 'border-radius':'10px' }); $('.close').css( { 'color': '#aaaaaa', 'float': 'right', 'font-size': '28px', 'font-weight': 'bold' }); $('.close').hover(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').focus(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').on('click', function(){ $('.modal').css({'display':'none'}); }) // var modal = document.getElementById("myModal"); // window.onclick = function(event) { // if (event.target == modal) { // modal.style.display = "none";} // } } else{ clearInterval(downloadTimer); f_sound.play(); var reg_false=("<div id=myModal class=modal><div class=modal-content><span class=close>&times;</span><br><p id=expl_f>သင့်အဖြေမှားယွင်းပါသည်။<br>အဖြေမှန်မှာ "+ans_dis+" ဖြစ်ပါသည်။</p><p id=expl1>"+expl_dis+"</p><form method=post id=myform><a href=question.php><button name=continue_w type=submit id=continue_w>Continue</button></a></form></div></div>"); document.getElementById("myplace").innerHTML=reg_false; $('#continue').click(function(){ // if(count_num=="9"){ // location.replace("testing.php"); // } // location.replace("question.php"); }); // $('#btn1').css({ // 'background':'red', // 'color':'white' // }); $('.modal').css( { 'display': 'block', 'position': 'fixed', 'z-index': '1', 'padding-top': '100px', 'left': '0', 'top': '0', 'width': '100%', 'height': '100%', 'overflow': 'auto', 'background-color': 'rgb(0,0,0)', 'background-color': 'rgba(0,0,0,0.4)' }); $('.modal-content').css( { 'background-color': '#e5edf2', 'margin': 'auto', 'padding': '20px', 'border': '6px solid rgb(246,79,89)', 'width': '50%', 'border-radius':'10px' }); $('.close').css( { 'color': '#aaaaaa', 'float': 'right', 'font-size': '28px', 'font-weight': 'bold' }); $('.close').hover(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').focus(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').on('click', function(){ $('.modal').css({'display':'none'}); }) // var modal = document.getElementById("myModal"); // window.onclick = function(event) { // if (event.target == modal) { // modal.style.display = "none";} // } } }); /*button2 functions start here ၊ ၊ ၊ ၊ ၊ ၊ ၊_______________________________________________*/ $('#btn2').click(function() { clearInterval(downloadTimer); if(btn2_val==ans_dis){ r_sound.play(); var reg_true=("<div id=myModal class=modal><div class=modal-content><span class=close>&times;</span><br><p id=expl_t>သင့်အဖြေမှန်ကန်ပါသည်။<br>သင် အမှတ် ၁၀၀ ရရှိပါသည်။<br>"+expl_dis+"</p><form method=post id=myform><a href=question.php><button name=continue_r type=submit id=continue_r>Continue</button></a></form></div></div>"); document.getElementById("myplace").innerHTML=reg_true; $('#continue').click(function(){ location.replace("question.php"); }); // $('#btn2').css({ // 'background':'green', // 'color':'white' // }); $('.modal').css( { 'display': 'block', 'position': 'fixed', 'z-index': '1', 'padding-top': '100px', 'left': '0', 'top': '0', 'width': '100%', 'height': '100%', 'overflow': 'auto', 'background-color': 'rgb(0,0,0)', 'background-color': 'rgba(0,0,0,0.4)' }); $('.modal-content').css( { 'background-color': '#e5edf2', 'margin': 'auto', 'padding': '20px', 'border': '6px solid rgb(30,170,203)', 'width': '50%', 'border-radius':'10px' }); $('.close').css( { 'color': '#aaaaaa', 'float': 'right', 'font-size': '28px', 'font-weight': 'bold' }); $('.close').hover(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').focus(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').on('click', function(){ $('.modal').css({'display':'none'}); }) // var modal = document.getElementById("myModal"); // window.onclick = function(event) { // if (event.target == modal) { // modal.style.display = "none";} // } } else{ clearInterval(downloadTimer); f_sound.play(); var reg_false=("<div id=myModal class=modal><div class=modal-content><span class=close>&times;</span><br><p id=expl_f>သင့်အဖြေမှားယွင်းပါသည်။<br>အဖြေမှန်မှာ "+ans_dis+" ဖြစ်ပါသည်။</p><p id=expl1>"+expl_dis+"</p><form method=post id=myform><a href=question.php><button name=continue_w type=submit id=continue_w>Continue</button></a></form></div></div>"); document.getElementById("myplace").innerHTML=reg_false; $('#continue').click(function(){ location.replace("question.php"); }); // $('#btn2').css({ // 'background':'red', // 'color':'white' // }); $('.modal').css( { 'display': 'block', 'position': 'fixed', 'z-index': '1', 'padding-top': '100px', 'left': '0', 'top': '0', 'width': '100%', 'height': '100%', 'overflow': 'auto', 'background-color': 'rgb(0,0,0)', 'background-color': 'rgba(0,0,0,0.4)' }); $('.modal-content').css( { 'background-color': '#e5edf2', 'margin': 'auto', 'padding': '20px', 'border': '6px solid rgb(246,79,89)', 'width': '50%', 'border-radius':'10px' }); $('.close').css( { 'color': '#aaaaaa', 'float': 'right', 'font-size': '28px', 'font-weight': 'bold' }); $('.close').hover(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').focus(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').on('click', function(){ $('.modal').css({'display':'none'}); }) // var modal = document.getElementById("myModal"); // window.onclick = function(event) { // if (event.target == modal) { // modal.style.display = "none";} // } } }); /*button3 functions start here ၊ ၊ ၊ ၊ ၊ ၊ ၊_______________________________________________*/ $('#btn3').click(function() { clearInterval(downloadTimer); if(btn3_val==ans_dis){ r_sound.play(); var reg_true=("<div id=myModal class=modal><div class=modal-content><span class=close>&times;</span><br><p id=expl_t>သင့်အဖြေမှန်ကန်ပါသည်။<br>သင် အမှတ် ၁၀၀ ရရှိပါသည်။<br>"+expl_dis+"</p><form method=post id=myform><a href=question.php><button name=continue_r type=submit id=continue_r>Continue</button></a></form></div></div>"); document.getElementById("myplace").innerHTML=reg_true; $('#continue').click(function(){ location.replace("question.php"); }); // $('#btn3').css({ // 'background':'green', // 'color':'white' // }); $('.modal').css( { 'display': 'block', 'position': 'fixed', 'z-index': '1', 'padding-top': '100px', 'left': '0', 'top': '0', 'width': '100%', 'height': '100%', 'overflow': 'auto', 'background-color': 'rgb(0,0,0)', 'background-color': 'rgba(0,0,0,0.4)' }); $('.modal-content').css( { 'background-color': '#e5edf2', 'margin': 'auto', 'padding': '20px', 'border': '6px solid rgb(30,170,203)', 'width': '50%', 'border-radius':'10px' }); $('.close').css( { 'color': '#aaaaaa', 'float': 'right', 'font-size': '28px', 'font-weight': 'bold' }); $('.close').hover(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').focus(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').on('click', function(){ $('.modal').css({'display':'none'}); }) // var modal = document.getElementById("myModal"); // window.onclick = function(event) { // if (event.target == modal) { // modal.style.display = "none";} // } } else{ clearInterval(downloadTimer); f_sound.play(); var reg_false=("<div id=myModal class=modal><div class=modal-content><span class=close>&times;</span><br><p id=expl_f>သင့်အဖြေမှားယွင်းပါသည်။<br>အဖြေမှန်မှာ "+ans_dis+" ဖြစ်ပါသည်။</p><p id=expl1>"+expl_dis+"</p><form method=post id=myform><a href=question.php><button name=continue_w type=submit id=continue_w>Continue</button></a></form></div></div>"); document.getElementById("myplace").innerHTML=reg_false; $('#continue').click(function(){ location.replace("question.php"); }); // $('#btn3').css({ // 'background':'red', // 'color':'white' // }); $('.modal').css( { 'display': 'block', 'position': 'fixed', 'z-index': '1', 'padding-top': '100px', 'left': '0', 'top': '0', 'width': '100%', 'height': '100%', 'overflow': 'auto', 'background-color': 'rgb(0,0,0)', 'background-color': 'rgba(0,0,0,0.4)' }); $('.modal-content').css( { 'background-color': '#e5edf2', 'margin': 'auto', 'padding': '20px', 'border': '6px solid rgb(246,79,89)', 'width': '50%', 'border-radius':'10px' }); $('.close').css( { 'color': '#aaaaaa', 'float': 'right', 'font-size': '28px', 'font-weight': 'bold' }); $('.close').hover(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').focus(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').on('click', function(){ $('.modal').css({'display':'none'}); }) // var modal = document.getElementById("myModal"); // window.onclick = function(event) { // if (event.target == modal) { // modal.style.display = "none";} // } } }); /*button4 functions start here ၊ ၊ ၊ ၊ ၊ ၊ ၊_______________________________________________*/ $('#btn4').click(function() { clearInterval(downloadTimer); if(btn4_val==ans_dis){ r_sound.play(); var reg_true=("<div id=myModal class=modal><div class=modal-content><span class=close>&times;</span><br><p id=expl_t>သင့်အဖြေမှန်ကန်ပါသည်။<br>သင် အမှတ် ၁၀၀ ရရှိပါသည်။<br>"+expl_dis+"</p><form method=post id=myform><a href=question.php><button name=continue_r type=submit id=continue_r>Continue</button></a></form></div></div>"); document.getElementById("myplace").innerHTML=reg_true; $('#continue').click(function(){ location.replace("question.php"); }); // $('#btn4').css({ // 'background':'green', // 'color':'white' // }); $('.modal').css( { 'display': 'block', 'position': 'fixed', 'z-index': '1', 'padding-top': '100px', 'left': '0', 'top': '0', 'width': '100%', 'height': '100%', 'overflow': 'auto', 'background-color': 'rgb(0,0,0)', 'background-color': 'rgba(0,0,0,0.4)' }); $('.modal-content').css( { 'background-color': '#e5edf2', 'margin': 'auto', 'padding': '20px', 'border': '6px solid rgb(30,170,203)', 'width': '50%', 'border-radius':'10px' }); $('.close').css( { 'color': '#aaaaaa', 'float': 'right', 'font-size': '28px', 'font-weight': 'bold' }); $('.close').hover(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').focus(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').on('click', function(){ $('.modal').css({'display':'none'}); }) // var modal = document.getElementById("myModal"); // window.onclick = function(event) { // if (event.target == modal) { // modal.style.display = "none";} // } } else{ clearInterval(downloadTimer); f_sound.play(); var reg_false=("<div id=myModal class=modal><div class=modal-content><span class=close>&times;</span><br><p id=expl_f>သင့်အဖြေမှားယွင်းပါသည်။<br>အဖြေမှန်မှာ "+ans_dis+" ဖြစ်ပါသည်။</p><p id=expl1>"+expl_dis+"</p><form method=post id=myform><a href=question.php><button name=continue_w type=submit id=continue_w>Continue</button></a></form></div></div>"); document.getElementById("myplace").innerHTML=reg_false; $('#continue').click(function(){ location.replace("question.php"); }); // $('#btn4').css({ // 'background':'red', // 'color':'white' // }); $('.modal').css( { 'display': 'block', 'position': 'fixed', 'z-index': '1', 'padding-top': '100px', 'left': '0', 'top': '0', 'width': '100%', 'height': '100%', 'overflow': 'auto', 'background-color': 'rgb(0,0,0)', 'background-color': 'rgba(0,0,0,0.4)' }); $('.modal-content').css( { 'background-color': '#e5edf2', 'margin': 'auto', 'padding': '20px', 'border': '6px solid rgb(246,79,89)', 'width': '50%', 'border-radius':'10px' }); $('.close').css( { 'color': '#aaaaaa', 'float': 'right', 'font-size': '28px', 'font-weight': 'bold' }); $('.close').hover(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').focus(function(){ $(this).css({'color': '#000', 'text-decoration': 'none', 'cursor': 'pointer'}) }); $('.close').on('click', function(){ $('.modal').css({'display':'none'}); }) // var modal = document.getElementById("myModal"); // window.onclick = function(event) { // if (event.target == modal) { // modal.style.display = "none";} // } } }); } }
const Game = require('./game'); const Player = require('./player'); var game = new Game(); var player1 = new Player("Spongebob"); var player2 = new Player("Squidward"); var player3 = new Player("Patrick"); var player4 = new Player("Sandy"); game.addPlayer(player1); game.addPlayer(player2); game.addPlayer(player3); game.addPlayer(player4); console.log(game.getBoard()); console.log(game.sockets);
import { v4 as uuidv4 } from "uuid"; function chillHop() { return [ { name: "Beaver Creek", cover: "https://chillhop.com/wp-content/uploads/2020/09/0255e8b8c74c90d4a27c594b3452b2daafae608d-1024x1024.jpg", artist: "Aso, Middle School, Aviino", audio: "https://mp3.chillhop.com/serve.php/?mp3=10075", color: ["#205950", "#2ab3bf"], id: uuidv4(), active: true, }, { name: "Daylight", cover: "https://chillhop.com/wp-content/uploads/2020/07/ef95e219a44869318b7806e9f0f794a1f9c451e4-1024x1024.jpg", artist: "Aiguille", audio: "https://mp3.chillhop.com/serve.php/?mp3=9272", color: ["#EF8EA9", "#ab417f"], id: uuidv4(), active: false, }, { name: "Keep Going", cover: "https://chillhop.com/wp-content/uploads/2020/07/ff35dede32321a8aa0953809812941bcf8a6bd35-1024x1024.jpg", artist: "Swørn", audio: "https://mp3.chillhop.com/serve.php/?mp3=9222", color: ["#CD607D", "#c94043"], id: uuidv4(), active: false, }, { name: "Nightfall", cover: "https://chillhop.com/wp-content/uploads/2020/07/ef95e219a44869318b7806e9f0f794a1f9c451e4-1024x1024.jpg", artist: "Aiguille", audio: "https://mp3.chillhop.com/serve.php/?mp3=9148", color: ["#EF8EA9", "#ab417f"], id: uuidv4(), active: false, }, { name: "Reflection", cover: "https://chillhop.com/wp-content/uploads/2020/07/ff35dede32321a8aa0953809812941bcf8a6bd35-1024x1024.jpg", artist: "Swørn", audio: "https://mp3.chillhop.com/serve.php/?mp3=9228", color: ["#CD607D", "#c94043"], id: uuidv4(), active: false, }, { name: "Under the City Stars", cover: "https://chillhop.com/wp-content/uploads/2020/09/0255e8b8c74c90d4a27c594b3452b2daafae608d-1024x1024.jpg", artist: "Aso, Middle School, Aviino", audio: "https://mp3.chillhop.com/serve.php/?mp3=10074", color: ["#205950", "#2ab3bf"], id: uuidv4(), active: false, }, { name: "Mirage", cover: "https://chillhop.com/wp-content/uploads/2020/09/09fb436604242df99f84b9f359acb046e40d2e9e-1024x1024.jpg", artist: "Nymano, j'san", audio: "https://mp3.chillhop.com/serve.php/?mp3=10136", color: ["#5B5585", "#A1728B"], id: uuidv4(), active: false, }, { name: "burn my mind", cover: "https://chillhop.com/wp-content/uploads/2020/06/52bd092974ccce9aa610c33f03575fc2d7f9c7d2-1024x1024.jpg", artist: "Tesk", audio: "https://mp3.chillhop.com/serve.php/?mp3=8137", color: ["#AFD2CF", "#2E4D90"], id: uuidv4(), active: false, }, { name: "Swimming", cover: "https://chillhop.com/wp-content/uploads/2020/07/25a182a6a21588b8f7ad5605ba1118a8ea61bdc2-1024x1024.jpg", artist: "Sleepy Fish", audio: "https://mp3.chillhop.com/serve.php/?mp3=7993", color: ["#72BED5", "#22183D"], id: uuidv4(), active: false, }, { name: "jam session", cover: "https://chillhop.com/wp-content/uploads/2020/07/4b06cedf68f3f842d3a0fc13ae62564dec6056c8-1024x1024.jpg", artist: "Montell Fish", audio: "https://mp3.chillhop.com/serve.php/?mp3=9003", color: ["#8299BD", "#F6A19D"], id: uuidv4(), active: false, }, { name: "At Our Core", cover: "https://chillhop.com/wp-content/uploads/2020/07/8f8345d4f6a785737417ddd625a2d20664b244b6-1024x1024.jpg", artist: "fantompower", audio: "https://mp3.chillhop.com/serve.php/?mp3=9065", color: ["#EFB09F", "#691A1D"], id: uuidv4(), active: false, }, //ADD MORE HERE //Audio link can be found by watching network traffic in inspect page mode when recording the song being told to play ]; } export default chillHop;
import { combineReducers } from 'redux'; import items from 'items/items.reducer'; import headlines from 'headlines/headlines.reducer'; const rootReducer = combineReducers({ items, stories: headlines, }); export default rootReducer;
import React from "react"; import { Text, TouchableOpacity, View, Button } from "react-native"; import Tts from 'react-native-tts'; const remedios = [ "losartana", "amoxicilina", "dipirona", "dorflex", "doxflan" ] export default class AlertaEstoque extends React.Component { remedio= ''; constructor(props){ super(props); this.state = { texto: 'Você tem somente 10 comprimidos de ', remedio: '' } } async componentWillMount() { Tts.setDefaultLanguage('pt-BR'); Tts.setDefaultRate(1.0, true); Tts.setDucking(true); Tts.setDefaultPitch(1.0); Tts.addEventListener('tts-start', (event) => console.log("start", event)); Tts.addEventListener('tts-finish', (event) => console.log("finish", event)); Tts.addEventListener('tts-cancel', (event) => console.log("cancel", event)); this.falarAlerta(); } falarAlerta(){ Tts.getInitStatus().then(() => { Tts.speak(remedio); }); } getRemedio(){ let indice = Math.random() * 5; indice= Math.round(indice,0); remedio = 'Você tem somente 11 comprimidos de ' + remedios[indice]; return remedio; } render() { return ( <View style={{flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center'}}> <Text style={{fontSize: 20}}> {this.getRemedio()} </Text> {/* <Button title="iniciar speech" onPress={() => this.falarAlerta()}/> */} </View> ) } }
angular.module('projects') .component('projects', { templateUrl: 'app/components/projects/projects.html' });
Ext.Loader.setPath({ 'cfa' : 'app', 'Deft' : 'app/lib/deft' }); Ext.require(['Deft.*','cfa.helper.PhoneGapHelper','cfa.helper.ChromeHelper', 'cfa.utils.HelperUtil', 'cfa.utils.FileUtils']); Ext.application({ name : 'cfa', helpUrl: 'root', requires : [ 'Ext.MessageBox', 'cfa.proxy.File', 'cfa.proxy.ChromeFile' ], profiles : ['Tablet', 'Phone'], stores : ['Base','Dashboards', 'Events', 'Cases', 'Contacts', 'References','LSContacts', 'EventsLocal', 'ReferencesLocal', 'CaseForms', 'SearchCases', 'SearchTemplates', 'Users', 'ReferencesDownloaded'], icon : { '57' : 'resources/icons/Icon.png', '72' : 'resources/icons/Icon~ipad.png', '114' : 'resources/icons/Icon@2x.png', '144' : 'resources/icons/Icon~ipad@2x.png' }, isIconPrecomposed : true, startupImage : { '320x460' : 'resources/startup/320x460.jpg', '640x920' : 'resources/startup/640x920.png', '768x1004' : 'resources/startup/768x1004.png', '748x1024' : 'resources/startup/748x1024.png', '1536x2008' : 'resources/startup/1536x2008.png', '1496x2048' : 'resources/startup/1496x2048.png' }, buildVersion: null, launch : function() { this.buildVersion = new Ext.Version('1.1'); Formpod.init(FD_Forms, Formpod.FormEngine.CodeGenerators.Sencha); Ext.getStore('CaseForms').setData(Formpod.Forms); Deft.Injector.configure({ contactStore: { fn: function() { if (cfa.helper.PhoneGapHelper.isOnLine()) { var store = Ext.create('cfa.store.Contacts'); store.setOfflineStore(Ext.create('cfa.store.LSContacts')); return store; } else { return Ext.create('cfa.store.LSContacts'); } } }, eventStore: { fn: function() { if (cfa.helper.PhoneGapHelper.isOnLine()) { var store = Ext.create('cfa.store.Events'); store.setOfflineStore(Ext.create('cfa.store.EventsLocal')); return store; } else { return Ext.create('cfa.store.EventsLocal' ); } } }, referenceStore:{ fn: function() { if (cfa.helper.PhoneGapHelper.isOnLine()) { var store = Ext.create('cfa.store.References'); store.setOfflineStore(Ext.create('cfa.store.ReferencesLocal')); return store; } else { return Ext.create('cfa.store.ReferencesLocal' ); } } } }); //Destroy the #appLoadingIndicator element Ext.fly('appLoadingIndicator').destroy(); }, onUpdated : function() { Ext.Msg .confirm( "Application Update", "This application has just successfully been updated to the latest version. Reload now?", function(buttonId) { if (buttonId === 'yes') { window.location.reload(); } }); } });
import gulp from 'gulp'; import p from '../package.json'; module.exports = (options) => { gulp.task('images', () => { return gulp.src('app/images/**/*.{jpg,png}') .pipe($.if($.if.isFile, $.cache($.imagemin({ progressive: true, interlaced: true, svgoPlugins: [{ cleanupIDs: false }] })) .on('error', function (err) { console.log(err); this.end(); }))) .pipe($.if('*.jpg', $.imageResize({ width : 1280, height : 800, crop : true, quality : 0.6 }))) .pipe(gulp.dest('dist/images')); }); gulp.task('fonts', () => { return gulp.src(require('main-bower-files')({ filter: '**/*.{eot,svg,ttf,woff,woff2}' }).concat('app/fonts/**/*')) .pipe(gulp.dest('.tmp/fonts')) .pipe(gulp.dest('dist/fonts')); }); gulp.task('extras', () => { return gulp.src([ 'app/**/*.*', '!app/**/*.html', '!app/scripts/lib/*.js', '!app/**/*.scss', '!app/**/*.jade' ], { dot: true }).pipe(gulp.dest('dist')); }); };
// Challenge 2 function genCat() { var image = document.createElement('img'); var div = document.getElementById('flex-genCat'); image.src = "http://thecatapi.com/api/images/get?format=src&type=gif&size=small"; // div.appendChild(image); // div.append(image); div.appendChild(image); }
import React from 'react' import { Link as GLink } from 'gatsby' import { Link, Box, useThemeUI, get } from 'theme-ui' import { buildResponsiveVariant as rv } from '../../utils' import CardMediaIcon from './Card.Media.Icon' import CardMediaImage from './Card.Media.Image' const DEFAULT_IMAGE_VARIANT = 'vertical' const styles = { link: { userSelect: `none`, textAlign: `center`, position: `relative`, display: `block`, height: `full` } } const CardMedia = ({ imageVariant, omitMedia, mediaType, title, slug, link, ...props }) => { const context = useThemeUI() if (omitMedia) return null const { variant, thumbnail, thumbnailText } = props const imageVar = imageVariant || get(context.theme, rv(variant, 'imageVariant')[0]) || DEFAULT_IMAGE_VARIANT const image = thumbnail && thumbnail[imageVar] const linkProps = link ? { as: 'a', href: link, target: '_blank', rel: 'noopener noreferrer' } : { as: GLink, to: slug } return ( <Box sx={{ variant: rv(variant, 'media') }}> <Link {...linkProps} sx={styles.link} aria-label={title}> {mediaType === 'image' && image && ( <CardMediaImage image={image} {...props} /> )} {(mediaType === 'icon' || thumbnailText) && ( <CardMediaIcon {...props} /> )} {/* {featured && ( <Badge variant="featured"> <FaStar /> </Badge> )} */} </Link> </Box> ) } CardMedia.defaultProps = { mediaType: 'image' } export default CardMedia
define(function() { 'use strict'; function QueryClause() { var self = this; self.queryClauses = []; self.operator = 'MUST'; } return QueryClause; });
// variable with an array of questions var questions = [ { title: "The condition in an if / else statement is enclosed within ____.", choices: ["quotes", "curly brackets", "parentheses", "square brackets"], answer: "parentheses" }, { title: "What tag defines a division or the beginning/end of an individual section in an HTML document?", choices: ["<table>", "<meta>", "<img>", "<div>"], answer: "<div>" }, { title: "Commonly used data types DO NOT include:", choices: ["strings", "booleans", "alerts", "numbers"], answer: "alerts" }, { title: "String values must be enclosed within ____ when being assigned to variables.", choices: ["commas", "curly brackets", "quotes", "parenthesis"], answer: "quotes" }, { title: "In JavaScript, what is used in conjunction with HTML to “react” to certain elements?", choices: ["RegExp", "Events", "boolean", "Condition"], answer: "Events" }, { title: "What is the type of loop that continues through a block of code as long as the specified condition remains TRUE?", choices: ["Conditional Loop", "Else Loop", "While Loop", "For Loop"], answer: "While Loop" }, ]; // declared variables to count the score var score = 0; var questionIndex = 0; // begin my variables to strt working code var currentTime = document.querySelector("#currentTime"); var timer = document.querySelector("#startTime"); var questionsDiv = document.querySelector("#questionsDiv"); var wrapper = document.querySelector("#wrapper"); // seconds lrft of 15 seconds var secondsLeft = 76; // holds interval time var holdInterval = 0; // holds penalty time var penalty = 10; // new list element var ulCreate = document.createElement("ul"); // timer function that shows the timer going down. timer.addEventListener("click", function () { if (holdInterval === 0) { holdInterval = setInterval(function () { secondsLeft--; currentTime.textContent = "Time: " + secondsLeft; if(secondsLeft <= 0) { clearInterval(holdInterval); allDone(); currentTime.textContent = "Time's up!"; } }, 1000); } render(questionIndex); }); // rendering questions and choices to the page function render(questionIndex) { // clear existing data questionsDiv.innerHTML = ""; ulCreate.innerHTML = ""; // for loop to go through the array of questions for (var i = 0; i < questions.length; i++) { var userQuestion = questions[questionIndex].title; var userChoices = questions[questionIndex].choices; questionsDiv.textContent = userQuestion; }; // new for each for question choices userChoices.forEach(function (newItem) { var listItem = document.createElement("li"); listItem.textContent = newItem; questionsDiv.appendChild(ulCreate); ulCreate.appendChild(listItem); listItem.addEventListener("click", (compare)); }); }; // event to compare choices with the correct answer function compare(event) { var element = event.target; if (element.matches("li")) { var createDiv = document.createElement("div"); createDiv.setAttribute("id", "createDiv"); // Correct condition if (element.textContent == questions[questionIndex].answer) { score++; createDiv.textContent = "Correct! The answer is: " + questions[questionIndex].answer; // Correct condition } else { // need to deduct time if wrong answer secondsLeft = secondsLeft - penalty; createDiv.textContent = "Wrong! The correct answer is: " + questions[questionIndex].answer; } } // question index to determine which question user is on questionIndex++; if (questionIndex >= questions.length) { // all doen question to append wth the user stats allDone(); createDiv.textContent = "End of quiz!" + " " + "You got " + score + "/" + questions.length + " Correct!"; } else { render(questionIndex); } questionsDiv.appendChild(createDiv); } // all done appends last page function allDone() { questionsDiv.innerHTML = ""; currentTime.innerHTML = ""; // heading var createH1 = document.createElement("h1"); createH1.setAttribute("id", "createH1"); createH1.textContent = "All Done!" questionsDiv.appendChild(createH1); // paragraph var createP = document.createElement("p"); createP.setAttribute("id", "createP"); questionsDiv.appendChild(createP); // calc timer remaining and replace with score if (secondsLeft >= 0) { var timeRemaining = secondsLeft; var createP2 = document.createElement("p"); clearInterval(holdInterval); createP.textContent = "Your final score is: " + timeRemaining; questionsDiv.appendChild(createP2); } // label var createLabel = document.createElement("label"); createLabel.setAttribute("id", "createLabel"); createLabel.textContent = "Enter your initials: "; questionsDiv.appendChild(createLabel); // input var createInput = document.createElement("input"); createInput.setAttribute("type", "text"); createInput.setAttribute("id", "initials"); createInput.textContent = ""; questionsDiv.appendChild(createInput); // submit question var createSubmit = document.createElement("button"); createSubmit.setAttribute("type", "submit"); createSubmit.setAttribute("id", "Submit"); createSubmit.textContent = "Submit"; questionsDiv.appendChild(createSubmit); // event listener to capture initials and local storage for initials and score createSubmit.addEventListener("click", function () { var initials = createInput.value; if (initials === null) { console.log("No value entered!"); } else { var finalScore = { initials: initials, score: timeRemaining } console.log(finalScore); var allScores = localStorage.getItem("allScores"); if (allScores === null) { allScores = []; } else { allScores = JSON.parse(allScores); } allScores.push(finalScore); var newScore = JSON.stringify(allScores); localStorage.setItem("allScores", newScore); // Travels to final page window.location.replace("./highscore.html"); } }); }
/** * Copyright 2016 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var yarp = require('../../yarp'); var ibm_text_port_receiver = new yarp.Port('bottle'); ibm_text_port_receiver.open('/ibmjs/text:i'); var ibm_text_port_sender = new yarp.Port('bottle'); ibm_text_port_sender.open('/ibmjs/text:o'); var ibm_R1_img_request= new yarp.Port('bottle'); ibm_R1_img_request.open('/ibmjs/ibm_R1_img_request:o'); //CONNECTION WITH CONVERSATION yarp.Network.connect('/ibmjs/text:o', '/ibmjs/text_to_speech:i'); var AssistantV1 = require('watson-developer-cloud/assistant/v1'); // Set up Assistant service wrapper. //var conversation = new AssistantV1({ // username: '889ac465-58a9-4a37-8731-5c3e2954f822', // replace with service username // password: 'YRWSxUmWmp2o', // replace with service password // version: '2018-02-16' //}); //var b = Yarp.Bottle(); const conversation = new AssistantV1({ username: process.env.ASSISTANT_USERNAME || '889ac465-58a9-4a37-8731-5c3e2954f822', password: process.env.ASSISTANT_PASSWORD || 'YRWSxUmWmp2o', version: '2018-02-16' }); var workspace_id = '17c67878-e1ed-4206-a42e-0098751b47f0'; // replace with workspace ID var response_=null; var user_input=null; var flag='flag'; // Start conversation with empty message. conversation.message({ workspace_id: process.env.WORKSPACE_ID || '17c67878-e1ed-4206-a42e-0098751b47f0' }, processResponse); // Message from user ibm_text_port_receiver.onRead(function(msg){ var user_input=msg.toString(); console.log('Message from Yarp: ',msg.toString()); conversation.message({ workspace_id: workspace_id, input: { text: user_input }, // Send back the context to maintain state. context : response_.context, }, processResponse) }); // Process the service response. function processResponse(err, response) { if (err) { console.error(err); // something went wrong return; } var endConversation = false; response_=response; // Check for action flags. if (response.output.action === 'display_time') { // User asked what time it is, so we output the local system time. console.log('The current time is ' + new Date().toLocaleTimeString() + '.'); } else if (response.output.action === 'end_conversation') { // User said goodbye, so we're done. console.log(response.output.text[0]); endConversation = true; response_=null; } else { // Display the output from dialog, if any. if (response.output.text.length != 0) { console.log(response.output.text[0]); ibm_text_port_sender.write(response.output.text[0]); if(response.output.text[0]=='Perfect, your prescription is valid!. Please go to the waiting room, we will call you. Do you still need my help ?') {console.log('Giulia');} //{ibm_R1_img_request.write('Request image');} } } } /* * Updates the response text using the intent confidence * @param {Object} input The request to the Conversation service * @param {Object} response The response from the Conversation service * @return {Object} The response with the updated message */ /* module.exports = function(app) { app.post('/api/message', (req, res, next) => { console.log('qui'); const workspace = process.env.WORKSPACE_ID || '<workspace-id>'; if (!workspace || workspace === '<workspace-id>') { return res.json({ output: { text: 'The app has not been configured with a <b>WORKSPACE_ID</b> environment variable. Please refer to the ' + '<a href="https://github.com/watson-developer-cloud/conversation-simple">README</a> ' + 'documentation on how to set this variable. <br>' + 'Once a workspace has been defined the intents may be imported from ' + '<a href="https://github.com/watson-developer-cloud/conversation-simple/blob/master/training/car_workspace.json">here</a> ' + 'in order to get a working application.' } }); } const payload = { workspace_id: workspace, context: req.body.context || {}, input: user_input || {} //input: req.body.input || {} }; console.log(payload); // Send the input to the conversation service conversation.message(payload, (error, data) => { if (error) { return next(error); } console.log('response', res.json(updateMessage(payload, data))); return res.json(updateMessage(payload, data)); }); }); }; const updateMessage = (input, response) => { var responseText = null; if (!response.output) { response.output = {}; } else { return response; } if (response.intents && response.intents[0]) { var intent = response.intents[0]; // Depending on the confidence of the response the app can return different messages. // The confidence will vary depending on how well the system is trained. The service will always try to assign // a class/intent to the input. If the confidence is low, then it suggests the service is unsure of the // user's intent . In these cases it is usually best to return a disambiguation message // ('I did not understand your intent, please rephrase your question', etc..) if (intent.confidence >= 0.75) { responseText = 'I understood your intent was ' + intent.intent; } else if (intent.confidence >= 0.5) { responseText = 'I think your intent was ' + intent.intent; } else { responseText = 'I did not understand your intent'; } } response.output.text = responseText; console.log('response text: ',responseText); return response; }; */
// 默认任务 const fs = require('fs') const { Transform } = require('stream') const { log } = require('console') exports.default = () => { // 文件读取流 const read = fs.createReadStream('normalize.css') // 文件写入流 const write = fs.createWriteStream('normalize.min.css') // 文件转换流 const transform = new Transform({ transform: (chunk, encoding, callback) => { // 核心转换实现 // chunk --- 读取流中的读取内容 buffer const input = chunk.toString() // 去掉所有空格和注释 const output = input.replace(/\s+/g, '').replace(/\/\*.+?\*\//g, '') // 执行回调函数 错误优先 callback(null, output) } }) // 把读取出来的文件导入写入文件的流 read .pipe(transform) // 转换 .pipe(write) // 写入 return read }
var React = require('react'); var RadonTypeahead = require('../lib/typeahead.js'); var carBrandsArray = require('./list-of-car-brands.js'); module.exports = React.createClass({ getInitialState() { return { selectedVal: '' }; }, onTypeaheadChange(val, asyncListCallback) { // mimic async ajax call setTimeout(() => { // Make the ajax call with `val` var filteredList = carBrandsArray.filter(function (brand) { return brand.toLowerCase().indexOf(val.toLowerCase()) === 0; }); // success handler e.g. `success: function(res) { asyncListCallback(res.list); }` // handle case that val is empty asyncListCallback(val ? filteredList : []); }, 1000); }, onTypeaheadSelection(val) { this.setState({ selectedVal: val }); }, render() { return ( <div> <p>Selected: {this.state.selectedVal}</p> <RadonTypeahead list={this.state.ajaxList} onChange={this.onTypeaheadChange} onSelectOption={this.onTypeaheadSelection} manualMode={true} /> </div> ); } });
import React from 'react'; import "./place.css"; class Place extends React.Component { constructor(props) { super(props); } render() { let placeData = this.props.place.data; let place = <div key={placeData.SERIAL_NO} className="place"> <img className="picture" src={this.props.place.imgSrcs} /> <div className="title">{placeData.stitle}</div> <div className="category">{placeData.CAT2}</div> </div>; return <>{place}</>; } } export default Place;
import React from 'react'; import Dialog from '@material-ui/core/Dialog'; import Slide from '@material-ui/core/Slide'; import withAppContext from '../../context/withAppContext'; import PostForm from './post/PostForm'; import { useMediaQuery } from 'react-responsive'; const Transition = React.forwardRef(function Transition(props, ref) { return <Slide direction='up' ref={ref} {...props} />; }); const PostDialog = props => { const handleNewPost = async (title, content) => { await props.context.newPost( props.context.user.id, title, content, props.context.user.username, props.context.user.token ); props.onClose(); }; const desktop = useMediaQuery({ query: '(min-width: 850px)' }); return ( <Dialog fullScreen open={props.open} onClose={props.onClose} TransitionComponent={Transition} > <PostForm onClose={props.onClose} newPost={handleNewPost} desktop={desktop} {...props} /> </Dialog> ); }; export default withAppContext(PostDialog);
"Use Strict" //-------------------------------------------------------------------------------------------// // TRIBAL KNOWLEDGE SYSTEM ------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// // URL QUERYSTRING APPEND -------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// $(function() { if ( (window.location.href === "http://localhost:8080/tk/tk.html") || (window.location.href === "http://localhost:8080/tk/")) { window.history.pushState("object or string", "Title", "http://localhost:8080/tk/tk.html?pageType=category") } loadPageData() }) //-------------------------------------------------------------------------------------------// // PAGE TRANSITIONS -------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// $('#mainSection').css('display', 'none').fadeIn(1000) $("body").on("click", "a, nav a", function(e) { e.preventDefault() var link = $(this).attr("href") var newurl if(link != '#') { $("#mainSection").fadeOut(100, function() { console.log("link ==>" + link) //location.href = link if(link == 'tk.html') { newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + link newurl = newurl.replace("tk.htmltk.html", "tk.html?pageType=category") console.log("===> " + newurl) } else { newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + link } console.log("newurl ==>" + newurl) window.history.pushState({path:newurl},'',newurl); window.loadPageData() }) $("#mainSection").fadeIn(100) } }) //-------------------------------------------------------------------------------------------// // LOAD PAGE DATA ---------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// var loadPageData = function() { console.log("%c loadPageData() ", "color: #ff7b00") var pageType = getParameterByName("pageType") // CHECK USER checkUser(function(data) { isAdmin = data console.log("USER LEVEL IS " + JSON.stringify(data)) if(data.admin != "False") { sessionStorage.setItem("admin", data.admin) sessionStorage.setItem("adminName", data.adminName) sessionStorage.setItem("userLevel", data.userLevel) } else { sessionStorage.setItem("admin", data.admin) sessionStorage.setItem("adminName", data.adminName) sessionStorage.setItem("userLevel", data.userLevel) } }) // LOAD NAVIGATION doData("categoryNav", "category", showNavElement) // POPULATE CATEGORIES DROPDOWN BY PAGE TYPE switch(pageType) { case "content": doData("content", "pageContent", showResults) // show content doData("category", "runCb", function(data) { showCategories(data)}) // build category dropdown break case "contentDetails": doData("contentDetails", "pageContent", showResults) // show content details break case "adminContent": doData("adminContent", "pageContent", showResults) // show admin content doData("category", "runCb", function(data) { showCategories(data)}) // build category dropdown break case "category": doData("category", "pageContent", showResults) // show category content break case "categoryDetails": doData("categoryDetails", "pageContent", showResults) // show category details break case "adminCategory": doData("adminCategory", "pageContent", showResults) // show admin category break case "adminKeywords": doData("adminKeywords", "pageContent", showResults) // show admin keywords break } } //-------------------------------------------------------------------------------------------// // CHECK USER -------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function checkUser(cb) { console.log("%c checkUser(cb) ", "color: #ff7b00") $.ajax({ type : 'GET', url : 'checkUser.asp', dataType : 'JSON', encode : true, success : function(data) { cb(data) }, error : function(data) { console.log("ERROR" + JSON.stringify(data)) } }) } //-------------------------------------------------------------------------------------------// // GET PARAMETER BY NAME --------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function getParameterByName(name, url) { console.log("%c getParameterByName(name, url) ", "color: #ff7b00") if (!url) url = window.location.href name = name.replace(/[\[\]]/g, '\\$&') var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url) if (!results) return null if (!results[2]) return '' return decodeURIComponent(results[2].replace(/\+/g, ' ')) } //-------------------------------------------------------------------------------------------// // LOAD NAVIGATION -------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function loadNavigation(categories) { console.log("%c loadNavigation(categories) ", "color: #ff7b00") var userName = sessionStorage.getItem("adminName") userName = userName.replace(/\./g,' ') $.ajax({ type : 'GET', url : 'navigation.asp', success : function(data) { // APPEND DATA TO DOM FIRST THEN FIND $("#holder").html(data).find('#categoriesMenu').html(""+categories+"") // USER LEVEL CHECK - EXTERNAL USERS if( (sessionStorage.admin === "True" && sessionStorage.userLevel === "2") || (sessionStorage.admin === "False" && sessionStorage.userLevel === "2") ) { $("#holder").find('#adminbtn').html("") } $("#userName").html("Hello: " + userName) var newNav = $("#holder") // HIDE ADMIN $("#holder").remove() $("#navigation").html(newNav) }, error : function(data) { console.log("ERROR" + JSON.stringify(data)) } }) } //-------------------------------------------------------------------------------------------// // EVENT HANDLERS ---------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// // ADD UPDATE DELETE $("body").on("click", "[data-type='delete']", function() { promptUser( $(this).data('id'), $(this).data('db'), "mDelete" ) }) $("body").on("click", "[data-type='update']", function() { promptUser( $(this).data('id'), $(this).data('db'), "mUpdate" ) }) $("body").on("click", "[data-type='add']", function() { showModal("","mAdd","", $(this).data('db')) }) // ALLOW TINYMCE FOCUS $("body").on("focusin", function(e) { if ($(e.target).closest(".mce-window").length) { e.stopImmediatePropagation() } }) // TABLE CONTAINER HOVER AND CLICK $("body").on({ "mouseenter" : function() { if($(this).find('a.link').length) { $(this).addClass("tableContainerHover") } }, "mouseleave" : function() { if($(this).find('a.link').length) { $(this).removeClass("tableContainerHover") } }, "click" : function() { if($(this).find('a.link').length) { //window.location = $(this).children().attr("href") } } }, ".tableContainer > table > tbody > tr > td") // TK LOGO SWAP HOVER AND CLICK $("body").on({ "mouseenter" : function() { tk = 'T<div class="k">K</div>' home = "<i class='fa fa-home'></i>" time = 100 $(".navbar-icons").empty().fadeOut(time, function() { $(".navbar-icons").html(home).fadeIn(time)}) }, "mouseleave" : function() { $(".navbar-icons").empty().fadeOut(time, function() { $(".navbar-icons").html(tk).fadeIn(time)}) }, "click" : function() { $(".navbar-icons").empty().fadeOut(time, function() { $(".navbar-icons").html(tk).fadeIn(time)}) } }, ".navbar-brand") // REVERT TO PREVIOUS STATE window.addEventListener('popstate', function(event) { //window.history.pushState(event.state); window.loadPageData() //updateContent(event.state); }) //-------------------------------------------------------------------------------------------// // GET DATA --------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function doData(dbTable, dataUse, cb) { console.log("%c doData(dbTable, dataUse, cb)", "color: #ff7b00") cb = cb || ""; dbTable = dbTable || "category"; // default to category dataUse = dataUse || "pageContent"; //default to pageContent // PASS THIS FOR DETAIL QUERIES var categoryId = getParameterByName("categoryId") var contentId = getParameterByName("contentId") $.ajax({ type : 'GET', url : 'doData.asp?sqlType='+dbTable+'&categoryId='+categoryId+'&contentId='+contentId+'&sqlRecordId='+categoryId+'', dataType : 'json', encode : true, success : function(data) { if(dataUse == "pageContent") { showResults(dbTable, data) } else { cb(data) } }, error : function(data) { console.log("ERROR" + JSON.stringify(data)) } }) $("button[type=button]").removeAttr("disabled") } //-------------------------------------------------------------------------------------------// // SEARCH -----------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function doSearch(search, list, cb) { console.log("%c doSearch(search, list, cb) ", "color: #ff7b00") $("#mainSection").fadeIn(100) var options = { tokenize: true, findAllMatches: true, includeScore: false, // adds 'item:' to JSON threshold: 0.1, location: 0, distance: 100, maxPatternLength: 32, minMatchCharLength: 1, keys: [{ name: 'taggles', weight: 0.4 }, { name: 'contentContent', weight: 0.6 }] } var fuse = new Fuse(list, options) // "list" is the item array var result = fuse.search(search) cb(result) } //-------------------------------------------------------------------------------------------// // SHOW NAV ELEMENTS ------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function showNavElement(data) { console.log("%c showNavElement(data) ", "color: #ff7b00") var tbl = "" //FILTER SPECIFIC CATEGORY //var filtered = data.filter(function(item) { return item.categoryTitle=="Title two"}) // BUILD NAVIGATION ELEMENT for (let i = 0, l = data.length; i < l; i++) { if(data[i].ct != 0) { tbl += '<li><a href="?pageType=categoryDetails&categoryId='+data[i].categoryId+'" data-categoryid="'+data[i].categoryId+'">'+data[i].categoryTitle+ ' ' +badgeStatus(data[i].countDifference)+'</li>' } } loadNavigation(tbl) } //-------------------------------------------------------------------------------------------// // PROMPT USER ------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function promptUser(id, dbTable, modalType) { console.log("%c promptUser(id, dbTable, modalType) ", "color: #ff7b00") // USER LEVEL CHECK - ADMIN - APPEND TABLE NAME TO REMOVE ADMIN FOR TABLES if((sessionStorage.admin === "True" && sessionStorage.userLevel == "1") || (sessionStorage.admin === "True" && sessionStorage.userLevel == "3")) { dbTable = dbTable.replace("admin",'') dbTable = dbTable.toLowerCase() } // APPEND ID TO dbTable FOR LOOKUP var tableRecordId = dbTable + 'Id' var formData = { tableRecordId : id } var newdbTable, formData // DETERMINE WHAT QUERY TO REQUEST VIA ASP switch(modalType) { case "mDelete": newdbTable = dbTable + "Query" break case "mUpdate": newdbTable = dbTable + "Query" break case "mAdd": newdbTable = dbTable + "Insert" break } // GET CURRENT CATEGORY VALUES $.ajax({ type : 'POST', url : 'doData.asp?sqlType='+newdbTable+'&sqlRecordId='+id+'', data : formData, dataType : 'json', encode : true, success : function(data) { // SHOW YES NO PROMPT IN MODAL console.log("==> " + data + "==>" + JSON.stringify(data)) showModal(data[0], modalType, id, dbTable) }, error : function(data) { console.log("ERROR" + JSON.stringify(data)) } }) return false } //-------------------------------------------------------------------------------------------// // GET FORM DATA ----------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function getFormData(recordId, currentForm, dbTable) { console.log("%c getFormData(recordId, currentForm, dbTable) ", "color: #ff7b00") // GET INPUTS OF FORM THAT HAS FOCUS // removed :not([name^=keywords]) so keywords are required var inputs = document.forms[currentForm].querySelectorAll("input[type=text]:not([name=keywords]),input[type=number], input[type=hidden], input[type=hidden],select,textarea").length, inputsName = document.forms[currentForm].querySelectorAll("input[type=text]:not([name=keywords]),input[type=number],input[type=hidden],select,textarea"), valid = true, formData = {} // CHECK FOR INPUT IN INPUTS AND DISPLAY ALERT WARNING for (var i = 0; i < inputs; i++) { // MODIFIED FOR TINYMCE if (inputsName[i].value.trim() === "") { document.forms[currentForm][i].classList.add("errinput") document.forms[currentForm][i].classList.add("alert-warning") console.log("missing fields " + inputsName[i].getAttribute("name")) valid = false return valid } } // VALID AND BUILD FORMDATA if (valid) { for(var x = 0; x < inputs; x++) { // TAGGLE KEYWORDS ADDED if(inputsName[x].getAttribute('name')=== "taggles") { formData["taggles"] = [] $('input[name^="taggles"]').each(function() { formData["taggles"].push(($(this).val())) }) formData["taggles"] = formData["taggles"].toString() } else { formData[""+inputsName[x].getAttribute('name')+""] = ""+inputsName[x].value.trim()+"" } } formData[""+dbTable+"Id"] = recordId } return formData } //-------------------------------------------------------------------------------------------// // MODIFY DATA ------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function modifyData(recordId, dbTable, modalType) { console.log("%c modifyData(recordId, dbTable, modalType) ", "color: #ff7b00") var newdbTable, formData, valid, inputs, inputsName, dataForm // DETERMINE WHAT QUERY TO REQUEST VIA ASP switch(modalType) { case "mDelete": newdbTable = dbTable + "Delete" formData = {} formData["adminName"] = "" + sessionStorage.getItem("adminName") + "" formData["modifiedDate"] = "" + getDate() + "" break case "mUpdate": newdbTable = dbTable + "Update" // ID of table to get update from dataForm = dbTable + "Update" // TRIGGER SAVE ON MCE TO UPDATE DATA FOR CONTENT if(dbTable === "content") { tinyMCE.triggerSave() } formData = getFormData(recordId, dataForm, dbTable) formData["adminName"] = "" + sessionStorage.getItem("adminName") + "" formData["modifiedDate"] = "" + getDate() + "" break case "mAdd": newdbTable = dbTable + "Insert" dataForm = dbTable + "Insert" // TRIGGER SAVE ON MCE TO UPDATE DATA FOR CONTENT if(dbTable === "content") { tinyMCE.triggerSave() } formData = getFormData(recordId, dataForm, dbTable) formData["adminName"] = "" + sessionStorage.getItem("adminName") + "" formData["modifiedDate"] = "" + getDate() + "" break } if(formData != false) { $.ajax({ type : 'POST', url : 'doData.asp?sqlType='+newdbTable+'&sqlRecordId='+recordId+'', data : formData, encode : true, async : true, cache : false, success : function(data) { switch(modalType) { case "mAdd": // UPLOAD FILES uploadFile(formData) break case "mUpdate": // SHOW SUCCESS IF CATEGORY if(dbTable === "category" || dbTable === "keywords") { showModal("","mSuccess","","") } else { // UPLOAD FILES uploadFile(formData) } break default: // SHOW SUCCESS AND CLEAR FORM FIELDS showModal("","mSuccess","","") } }, error : function(data) { console.log("ERROR" + JSON.stringify(data)) } }) } return false } //-------------------------------------------------------------------------------------------// // UPLOAD FILES -----------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function uploadFile(formData) { console.log("%c uploadFile(formData) ", "color: #ff7b00") var data = new FormData() $.each($(':input[type=file]')[0].files, function(i, file) { data.append('file-'+i, file) }) $.ajax({ type : 'POST', url : 'doFileUpload.asp', data : data, async : true, cache : false, contentType : false, processData : false, success : function(data) { // SHOW SUCCESS AND CLEAR FORM FIELDS showModal("","mSuccess","","") }, error : function(data) { // SHOW ERROR console.log("ERROR" + JSON.stringify(data)) } }) } //-------------------------------------------------------------------------------------------// // ADD DATA ---------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function addData(currentForm) { console.log("%c addData(currentForm) ", "color: #ff7b00") // VALIDATE FORM DATA BEFORE PROCEEDING formData = getFormData("", currentForm, "") if(formData != false) { $.ajax({ type : 'POST', url : 'doData.asp?sqlType='+currentForm+'', data : formData, dataType : 'HTML', encode : true, success : function(data) { $("#"+currentForm+"")[0].reset() showModal("","mSuccess","","") loadPageData() }, error : function(data) { console.log("ERROR" + JSON.stringify(data)) } }) } return false } //-------------------------------------------------------------------------------------------// // FORM SUBMIT ------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// // FORM SUBMIT FIND ID AND PASS TO ADD DATA $("body").on("submit", "form", function(e) { var currentForm = this.id if(currentForm == "contentSearch") { var searchValue = this[0].value.trim() if(searchValue.length <= 0) { e.preventDefault } else { $("#mainSection").fadeOut(100, function() { doData("content", "docallback", function(data) { doSearch(""+searchValue+"", data, function(result) { showResults("searchDetails", result) }) }) }) } } else { addData(currentForm) } return false e.preventDefault }) //-------------------------------------------------------------------------------------------// // SHOW MODAL -------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function showModal(data, modalType, id, dbTable) { console.log("%c showModal(data, modalType, id, dbTable) ", "color: #ff7b00") // SHOW SUCCESS AND CLEAR FORM FIELDS $('form').find('input, select, textarea').val('') // RESET MODAL BUTTONS $("#siteModal #saveBtn, #siteModal #deleteBtn").removeAttr("style") // SUCCESS FORM if(modalType === 'mSuccess') { $("#siteModal .modal-title").text("SUCCESS") $("#siteModal .modal-body").text(data) $("#siteModal #saveBtn, #siteModal #deleteBtn").css("display","none") } // DELETE FORM if (modalType === 'mDelete') { // SHOW YES NO PROMPT IN MODAL $("#siteModal .modal-body").addClass("delete") $("#siteModal .modal-title").text("DELETE") $("#siteModal .modal-body").text("Are you sure you want to delete "+data[''+dbTable+''+"Title"]+"?") $("#siteModal #saveBtn").css("display","none") $("#modal-footer").removeAttr("") $("#deleteBtn").attr("onClick","modifyData('"+id+"','"+dbTable+"','"+modalType+"')") } // CATEGORY UPDATE FORM if (modalType === 'mUpdate' && dbTable === 'category') { console.log("update category" + data.categoryTitle) $("#siteModal .modal-title").text("UPDATE CATEGORY") $("#siteModal .modal-body").html("<p><form id='categoryUpdate'> "+ "<div class='form-group'>"+ "<label>Category Title: </label>"+ "<input type='text' name='categoryTitle' class='form-control' value='"+data.categoryTitle+"'> "+ "</div>"+ "</form>") $("#siteModal #deleteBtn").css("display","none") $("#saveBtn").attr("onClick","modifyData('"+id+"','"+dbTable+"','"+modalType+"')") } // CATEGORY ADD FORM if (modalType === 'mAdd' && dbTable === 'category') { console.log("added content") var contentCategoryId = data.categoryId $("#siteModal .modal-title").text("ADD CATEGORY") $("#siteModal .modal-body").html("Add a new record:<P><form id='categoryInsert'> "+ "<div class='form-group'>"+ "<label>Category Title: </label>"+ "<input class='form-control' name='categoryTitle' type='text'>"+ "</div>"+ "<input type='hidden' name='categoryDate' value="+getDate()+">"+ "</form>") $("#siteModal #deleteBtn").css("display","none") $("#saveBtn").attr("onClick", "addData('categoryInsert')") } // KEYWORD ADD FORM if(modalType === 'mAdd' && dbTable === 'adminKeywords') { console.log("added keywords") $("#siteModal .modal-title").text("ADD KEYWORD") $("#siteModal .modal-body").html("Add a new record:<P><form id='keywordsInsert'> "+ "<div class='form-group'>"+ "<label>Keyword: </label>"+ "<input class='form-control' name='keywordsTitle' type='text'>"+ "</div>"+ "</form>") $("#siteModal #deleteBtn").css("display","none") $("#saveBtn").attr("onClick", "addData('keywordsInsert')") } // KEYWORD UPDATE FORM if(modalType === 'mUpdate' && dbTable === 'keywords') { console.log("update keywords" + data.keywordsTitle) $("#siteModal .modal-title").text("UPDATE KEYWORD") $("#siteModal .modal-body").html("<p><form id='keywordsUpdate'> "+ "<div class='form-group'>"+ "<label>Keyword: </label>"+ "<input type='text' name='keywordsTitle' class='form-control' value='"+data.keywordsTitle+"'> "+ "</div>"+ "</form>") $("#siteModal #deleteBtn").css("display","none") $("#saveBtn").attr("onClick","modifyData('"+id+"','"+dbTable+"','"+modalType+"')") } // CONTENT ADD FORM if(modalType === 'mAdd' && dbTable === 'content') { console.log("added content") var contentCategoryId = data.categoryId $("#siteModal .modal-title").text("ADD CONTENT") $("#siteModal .modal-body").html("Add a new record:<P><form id='contentInsert'>\ <div class='form-group'>\ <label>Category Title: </label>\ <select class='form-control categorySelect' name='categoryTitle'></select>\ </div>\ <div class='form-group'>\ <label>User Level: </label>\ <select class='form-control' name='userLevel'>\ <option value='1' selected>Internal</option>\ <option value='2'>External</option>\ </select>\ </div>\ <div class='form-group'>\ <label>Post Title: </label>\ <input type='text' name='contentTitle' class='form-control' placeholder='Post title'>\ </div>\ <div class='form-group'>\ <label>Post Content:</label>\ <textarea id='contentContent' name='contentContent' class='form-control' rows='4'></textarea>\ </div>\ <label>Search Tags</label>\ <div class='input textarea clearfix custom taggleTags'></div>\ <input type='file' name='file1' id='file1' class='hidden'/>\ <input name='image' type='file' id='upload' class='hidden' onchange=''>\ <input type='hidden' name='contentDate' value="+getDate()+">\ </form>") $("#siteModal #deleteBtn").css("display","none") $("#saveBtn").attr("onClick", "modifyData('','"+dbTable+"','"+modalType+"')") doData("category", "runCb", function(data) { showCategories(data)}) // build category dropdown initTaggle() initTinyMce() } // CONTENT UPDATE FORM if (modalType === 'mUpdate' && dbTable === 'content') { console.log("update content" + data.contentTitle) var contentCategoryId = data.categoryId $("#siteModal .modal-title").text("UPDATE CONTENT") $("#siteModal .modal-body").html("Update the following record:<P><form id='contentUpdate'> "+ "<div class='form-group'>"+ "<label>Category Title: </label>"+ "<select class='form-control categorySelect' name='categoryId'>"+ ""+doData("category","runCb", function(data) { showCategories(data,contentCategoryId) })+""+ "</select>"+ "</div>"+ "<div class='form-group'>"+ "<label>User Level:</label>"+ "<select class='form-control' name='userLevel' id='updateLevel'>"+ ""+showOptions(data.userLevel, getUserLevel(data.userLevel))+""+ "</select>"+ "</div>"+ "<div class='form-group'>"+ "<label>Post Title: </label>"+ "<input type='text' name='contentTitle' class='form-control' value='"+data.contentTitle+"'> "+ "</div>"+ "<div class='form-group'>"+ "<label>Post Content: </label>"+ "<textarea name='contentContent' class='form-control' rows='4'>"+htmlEntities(data.contentContent)+"</textarea>"+ "</div>"+ "<label>Search Tags</label>"+ "<div class='input textarea clearfix custom taggleTags'></div>"+ "<input name='image' type='file' id='upload' class='hidden' onchange=''>"+ "<input type='hidden' name='contentDate' value="+getDate()+">"+ "</form>") $("#siteModal #deleteBtn").css("display","none") $("#saveBtn").attr("onClick","modifyData('"+id+"','"+dbTable+"','"+modalType+"')") initTaggle(data) initTinyMce() } // GET CURRENT DATE WHEN PAGE LOADS //getDate() // SHOW MODAL $('#siteModal').modal('toggle') } //-------------------------------------------------------------------------------------------// // TAGGLE -----------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function initTaggle(data) { console.log("%c initTaggle(data) ", "color: #ff7b00") // TAGGLE data = data || "" var tagField = new Taggle($('.taggleTags.textarea')[0], { placeholder: 'Add search tags', allowDuplicates: false, allowedTags: ['html', 'javascript', 'js', 'jquery', 'xml', 'sharepoint', 'css', 'ecmascript'], duplicateTagClass: 'bounce' }); var container = tagField.getContainer() var input = tagField.getInput() if(data) { var cTags = data.taggles.toString() var tags = cTags.split(",") tagField.add(tags) } $(input).autocomplete({ source: function(request, response) { $.ajax({ type : 'GET', url : 'doData.asp?sqlType=keywordsQuery', dataType : 'json', encode : true, success : function(data) { response($.map( data, function( item ) { return { label: item.keywordsTitle, value: item.keywordsTitle } })); }, error : function(data) { console.log(JSON.stringify(data)) } }) }, appendTo: container, position: { at: "left bottom", of: container }, select: function(event, data) { event.preventDefault(); // ADD TAG IF USER SELECTS if (event.which === 1) { tagField.add(data.item.value) } } }) } //-------------------------------------------------------------------------------------------// // MODAL ------------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// $('#siteModal').on('show.bs.modal', function () { // $(this).find('.modal-body').css({'max-height':'100%','max-width':'100%'}) if( $(this).find('.modal-title').text() == "UPDATE CONTENT" || $(this).find('.modal-title').text() == "ADD CONTENT" ) { $('.modal-content').css({'width':'80vw'}) $('.modal-body').css({"height":"80vh"}) } }) //-------------------------------------------------------------------------------------------// // HIDE MODAL -------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// $('#siteModal').on('hidden.bs.modal', function () { $("#siteModal .modal-body").removeClass("delete") $(".modal-content, .modal-body").removeAttr("style") var pageType = getParameterByName("pageType") if(pageType != "category") { tinyMCE.remove() } // RESET MODAL POSITION ON HIDE $(".ui-draggable, .ui-resizable").removeAttr("style") loadPageData() }) //-------------------------------------------------------------------------------------------// // TINY MCE 4.5 -----------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function initTinyMce() { console.log("%c initTinyMce() ", "color: #ff7b00") tinymce.init({ selector: "textarea", height: 250, theme: "modern", paste_data_images: false, // ADD PLUGINS plugins: [ "advlist autolink lists link image charmap print preview hr anchor pagebreak", "searchreplace wordcount visualblocks visualchars fullscreen", "insertdatetime nonbreaking table contextmenu directionality", "template paste textcolor colorpicker textpattern codesample code" ], // BUILD TOOLBARS toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image uploadfile | codesample code | print | forecolor backcolor", // ADD BUTTON TO EDITOR setup: function(editor) { // ADD FILE UPLOAD BUTTON editor.addButton('uploadfile', { icon: 'browse', tooltip: "Upload and attach a file", onclick: function() { // OPEN WINDOW FOR FILE ADDING editor.windowManager.open({ title: "Add a file", html: '<form id="file_attach_form"><div class="form-group"><label for="file_attach">Click below to choose a file</label><input type="file" class="form-control-file" name="file" id="file_attach"></div></form>', url: "", width: 400, height: 150, buttons: [{ text: "Attach", subtype: "primary", onclick: function(e) { // APPEND FILENAME var file = $('#file_attach').get(0).files[0] var fileext = file.name.split(".") var newFileName = fileext[0] + "_" + (new Date()).getTime() + "." + fileext[1] var formData = new FormData() formData.append('file', file, newFileName) // FILE UPLOAD //var formData = new FormData($("#file_attach_form")[0]) $.ajax ({ url: 'doFileUpload.asp', type: 'POST', data: formData, async: false, success: function (data) { // APPEND FILE LINK TO EDITOR var path = JSON.stringify(data) editor.insertContent("<a href=\"files"+data.location+"\" class=\"fileAttachment\">FILE</a>") }, cache: false, contentType: false, processData: false }) // END FILE UPLOAD this.parent().parent().close() } }, { text: "Close", onclick: function() { this.parent().parent().close() } }] }) } }) }, // CODESAMPLE SETTINGS content_css: ['css/prismDark.css'], codesample_dialog_height: 400, codesample_dialog_width: 600, codesample_languages: [ {text: 'HTML/XML', value: 'markup'}, {text: 'JavaScript', value: 'javascript'}, {text: 'CSS', value: 'css'}, {text: 'PHP', value: 'php'}, {text: 'JSON', value: 'jsn'} ], // ALLOW IMAGE ATTACHMENTS AND UPLOAD image_advtab: false, // IMAGE ADVANCED TAB images_upload_url: 'doFileUpload.asp', images_upload_base_path: 'files', images_upload_credentials: true, automatic_uploads: true, file_picker_types: 'image', file_picker_callback: function(callback, value, meta) { if (meta.filetype =='image') { $('#upload').on('change', function() { var file = this.files[0] var reader = new FileReader() reader.onload = function(e) { var name = file.name.split('.')[0] var base64 = reader.result.split(',')[1] // OPTIONAL BASE 64 STORAGE var id = 'attachmentid' + (new Date()).getTime() // RANDOM ID var blobCache = tinymce.activeEditor.editorUpload.blobCache var blobInfo = blobCache.create(id, file, reader.result) blobCache.add(blobInfo) callback(blobInfo.blobUri(), {alt: file.name, title: name}) } reader.readAsDataURL(file) }) $('#upload').trigger('click') } } }) tinyMCE.triggerSave() } //-------------------------------------------------------------------------------------------// // HTML ENTITIES CONVERSION FOR HTML CODE SNIPPETS ------------------------------------------// //-------------------------------------------------------------------------------------------// function htmlEntities(str) { console.log("%c htmlEntries(str) ", "color: #ff7b00") return String(str).replace(/&/g, '&').replace(/</g, '&lt;').replace(/>/g, '>').replace(/"/g, '"') } //-------------------------------------------------------------------------------------------// // SHOW RESULTS -----------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function showResults(typeOf, data) { console.log("%c showResults(typeOf, data) ", "color: #ff7b00") var $catTitle = $("#categoryTitle") $catTitle.empty() // BUILDS A TABLE OR PANEL FOR DATA REQUESTED var result = "" // USER LEVEL CHECK - ADMIN OR INTERNAL - DISPLAY TABLE FOR ADMIN CATEGORY LISTINGS if(typeOf === "adminCategory" && sessionStorage.userLevel === "3" || typeOf === "adminCategory" && sessionStorage.userLevel === "1" ) { result += '<div class="panel panel-default">\ <div class="panel-heading">MANAGE CATEGORIES <div class="btn-group btn-group-xs float-right" role="group"><button type="button" class="btn btn-success align-left navbar-left" data-db="category" data-type="add"><i class="fa fa-1x fa-plus"></i></button></div></div>\ <div class="tableContainer">\ <table class="table" id="categoryDetailsResult"><tbody><tr><th>Category</th><th>Last Updated</th>' // USER LEVEL CHECK - ADMIN OR INTERNAL - DISPLAY EDIT OPTION if((sessionStorage.admin == "True" && sessionStorage.userLevel === "3") || (sessionStorage.admin == "True" && sessionStorage.userLevel === "1")) { result += '<th>Edit</th>' } result += '</tr>' for (let i = 0, l = data.length; i < l; i++) { result += '<tr><td><a href="?pageType=categoryDetails&categoryId='+data[i].categoryId+'" data-categoryId="'+data[i].categoryId+'" class="link">'+data[i].categoryTitle.trim()+'</a>&nbsp' + badgeStatus(data[i].countDifference) + '</td><td>'+convertDate(data[i].ctDate)+'</td><td>' // USER LEVEL CHECK - ADMIN - DISPLAY DELETE if(sessionStorage.admin == "True" && sessionStorage.userLevel === "3") { result += '<button type="button" class="btn btn-primary btn-danger" data-db='+typeOf+' data-type="delete" data-id='+data[i].categoryId+'><i class="fa fa-trash-o"></i></button>' } // USER LEVEL CHECK - ADMIN OR INTERNAL - DISPLAY EDIT if((sessionStorage.admin == "True" && sessionStorage.userLevel === "3") || (sessionStorage.admin == "True" && sessionStorage.userLevel === "1") ) { result += '<button type="button" class="btn btn-primary btn-success" data-db='+typeOf+' data-type="update" data-id='+data[i].categoryId+'><i class="fa fa-pencil"></i></button>' } result +='</td></tr>' } result += '</tbody></table>' result += '</div></div></div>' // RECORDSET PAGER //result += '<nav><ul class="pager"><li><a href="#">Previous</a></li><li><a href="#">Next</a></li></ul></nav>' $catTitle.append("Category Management") } // DISPLAY TABLE FOR CATEGORY LISTINGS if(typeOf === "category") { console.log("data result: " + JSON.stringify(data)) result += '<div class="panel panel-default">\ <div class="panel-heading">AVAILABLE CATEGORIES <div class="btn-group btn-group-xs float-right" role="group">' result += '</div></div>\ <div class="tableContainer">\ <table class="table" id="categoryDetailsResult">\ <tbody><tr><th>Category</th><th>Last Updated</th></tr>' for (let i = 0, l = data.length; i < l; i++) { result += '<tr><td><a href="?pageType=categoryDetails&categoryId='+data[i].categoryId+'" data-categoryId="'+data[i].categoryId+'" class="link">'+data[i].categoryTitle.trim()+'</a>&nbsp; '+badgeStatus(data[i].countDifference)+'</td><td>'+convertDate(data[i].ctDate)+'</td>' result +='</tr>' } result += '</tbody></table>' result += '</div></div></div>' // RECORDSET PAGER //result += '<nav><ul class="pager"><li><a href="#">Previous</a></li><li><a href="#">Next</a></li></ul></nav>' $catTitle.append("Available Categories") } // DISPLAY TABLE FOR CONTENT LISTINGS if(typeOf === "content") { result += '<div class="panel panel-default">\ <div class="panel-heading">AVAILABLE CONTENT <div class="btn-group btn-group-xs float-right" role="group"> <button type="button" class="btn btn-success align-left navbar-left" data-db="content" data-type="add"><i class="fa fa-1x fa-plus"></i></button>\ </div></div>\ <div class="panel-body">\ <div class="tableContainer">\ <table class="table" id="categoryDetailsResult">\ <tbody><tr><th>Content</th><th>Date</th><th>Category</th><th>User Level</th><th>Edit</th></tr>' for (let i = 0, l = data.length; i < l; i++) { result += '<tr><td><a href="?pageType=contentDetails&contentId='+data[i].contentId+'" data-contentid="'+data[i].contentId+'" class="link">'+data[i].contentTitle+'</a></td><td>'+convertDate(data[i].contentDate)+'</td><td>'+data[i].categoryTitle.trim()+'</td><td>'+getUserLevel(data[i].userLevel)+'</td><td><button type="button" class="btn btn-primary btn-danger" data-db='+typeOf+' data-type="delete" data-id='+data[i].contentId+'><i class="fa fa-trash-o"></i></button> <button type="button" class="btn btn-primary btn-success" data-db='+typeOf+' data-type="update" data-id='+data[i].contentId+'><i class="fa fa-pencil"></i></button></td></tr>' } result += '</tbody></table>' result += '</div></div></div>' $catTitle.append("Content Management") getDate() } // USER LEVEL CHECK - ADMIN OR INTERNAL - DISPLAY TABLE FOR KEYWORD LISTINGS if( (typeOf === "adminKeywords" && sessionStorage.userLevel === "3") || (typeOf === "adminKeywords" && sessionStorage.userLevel === "1" )) { result += '<div class="panel panel-default">\ <div class="panel-heading">AVAILABLE KEYWORDS <div class="btn-group btn-group-xs float-right" role="group"> <button type="button" class="btn btn-success align-left navbar-left" data-db="adminKeywords" data-type="add"><i class="fa fa-1x fa-plus"></i></button>\ </div></div>\ <div class="panel-body">\ <div class="tableContainer">\ <table class="table" id="categoryDetailsResult">\ <tbody><tr><th>Content</th>' // USER LEVEL CHECK - ADMIN OR INTERNAL - EDIT KEYWORDS if((sessionStorage.admin == "True" && sessionStorage.userLevel === "3") || (sessionStorage.admin == "True" && sessionStorage.userLevel === "1")) { result += '<th>Edit</th>' } result += '</tr>' for (let i = 0, l = data.length; i < l; i++) { result += '<tr><td>'+data[i].keywordsTitle+'</td><td>' // USER LEVEL CHECK - ADMIN - DELETE KEYWORDS if(sessionStorage.admin == "True" && sessionStorage.userLevel === "3") { result += '<button type="button" class="btn btn-primary btn-danger" data-db='+typeOf+' data-type="delete" data-id='+data[i].keywordsId+'><i class="fa fa-trash-o"></i></button>' } // USER LEVEL CHECK - ADMIN OR INTERNAL - EDIT KEYWORDS if((sessionStorage.admin == "True" && sessionStorage.userLevel === "3") || (sessionStorage.admin == "True" && sessionStorage.userLevel === "1") ) { result += '<button type="button" class="btn btn-primary btn-success" data-db='+typeOf+' data-type="update" data-id='+data[i].keywordsId+'><i class="fa fa-pencil"></i></button>' } result +='</td></tr>' } result += '</tbody></table>' result += '</div></div></div>' $catTitle.append("Keyword Management") } // USER LEVEL CHECK - ADMIN OR INTERNAL - DISPLAY TABLE FOR CONTENT LISTINGS if(typeOf === "adminContent" && sessionStorage.userLevel === "3" || typeOf === "adminContent" && sessionStorage.userLevel === "1" ) { result += '<div class="panel panel-default">\ <div class="panel-heading">AVAILABLE CONTENT <div class="btn-group btn-group-xs float-right" role="group"> <button type="button" class="btn btn-success align-left navbar-left" data-db="content" data-type="add"><i class="fa fa-1x fa-plus"></i></button>\ </div></div>\ <div class="panel-body">\ <div class="tableContainer">\ <table class="table" id="categoryDetailsResult">\ <tbody><tr><th>Content</th><th>Date</th><th>Category</th><th>User Level</th>' // USER LEVEL CHECK - ADMIN OR INTERNAL - CONTENT EDIT if((sessionStorage.admin == "True" && sessionStorage.userLevel === "3") || (sessionStorage.admin == "True" && sessionStorage.userLevel === "1")) { result += '<th>Edit</th>' } result += '</tr>' for (let i = 0, l = data.length; i < l; i++) { result += '<tr><td><a href="?pageType=contentDetails&contentId='+data[i].contentId+'" data-contentid="'+data[i].contentId+'" class="link">'+data[i].contentTitle+'</a></td><td>'+convertDate(data[i].contentDate)+'</td><td>'+data[i].categoryTitle.trim()+'</td><td>'+getUserLevel(data[i].userLevel)+'</td><td>' // USER LEVEL CHECK - ADMIN - DELETE CONTENT if(sessionStorage.admin == "True" && sessionStorage.userLevel === "3") { result += '<button type="button" class="btn btn-primary btn-danger" data-db='+typeOf+' data-type="delete" data-id='+data[i].contentId+'><i class="fa fa-trash-o"></i></button>' } // USER LEVEL CHECK - ADMIN OR INTERNAL - EDIT CONTENT if((sessionStorage.admin == "True" && sessionStorage.userLevel === "3") || (sessionStorage.admin == "True" && sessionStorage.userLevel === "1") ) { result += '<button type="button" class="btn btn-primary btn-success" data-db='+typeOf+' data-type="update" data-id='+data[i].contentId+'><i class="fa fa-pencil"></i></button>' } result +='</td></tr>' } result += '</tbody></table>' result += '</div></div></div>' $catTitle.append("Content Management") getDate() } // DISPLAY TABLE FOR CATEGORY DETAIL LISTING if(typeOf === "categoryDetails") { // USER LEVEL CHECK - EXTERNAL - REMOVE DATA NOT EQUAL TO EXTERNAL LEVEL if( sessionStorage.userLevel === "2") { data = data.filter(function(item) { return item.userLevel == "2" }); } // NO DATA RETURNED FOR CATEGORY DETAILS if(data.length <= 0) { doData("categoryQuery", "-", function(data) { $catTitle.append(data[0].categoryTitle) }) result += '<div class="panel panel-default">\ <div class="panel-heading">No content for this category</div>\ <div class="panel-body">\ <div class="tableContainer">\ </div>\ </div>\ </div>' } else { result += '<div class="panel panel-default">\ <div class="panel-heading">'+data[0].categoryTitle.trim()+'</div>\ <div class="panel-body">\ <div class="tableContainer">\ <table class="table" id="categoryDetailsResult">\ <tbody><tr><th>Title</th><th>Date</th><th>Link</th></tr>' for ( let i = 0, l = data.length; i < l; i++) { result += '<tr><td><a href="?pageType=contentDetails&contentId='+data[i].contentId+'" class="link">'+data[i].contentTitle+'</a></td><td>'+convertDate(data[i].contentDate)+'</td><td><div class="btn-group btn-group-xs" role="group"><a href="?pageType=contentDetails&contentId='+data[i].contentId+'" class="btn btn-tk">Read More</a></div></td></tr>' } result += '</tbody></table>' result += '</div></div></div>' $catTitle.append(data[0].categoryTitle.trim()) } } // DISPLAY TABLE FOR CONTENT DETAILS if(typeOf === "contentDetails") { result += '<div class="panel panel-default">\ <div class="panel-heading" id="contentTitle">'+data[0].contentTitle+'</div>\ <div class="panel-body">\ <p id="contentContent">'+data[0].contentContent+'</p>\ <p>'+displayTags(data[0].taggles)+'</p>\ </div>' $catTitle.append("<a href='?pageType=categoryDetails&categoryId="+data[0].contCatId+"' class='link'>" + data[0].categoryTitle.trim() + "</a>") } // DISPLAY TABLE FOR SEARCH RESULTS if(typeOf === "searchDetails") { // USER LEVEL CHECK - EXTERNAL - REMOVE DATA NOT EQUAL TO EXTERNAL LEVEL if( sessionStorage.userLevel === "2") { data = data.filter(function(item) { return item.userLevel == "2" }); } result += '<div class="panel panel-default searchResults">\ <div class="panel-heading">Search Results</div>\ <div class="panel-body">\ <div class="tableContainer">\ <table class="table" id="categoryDetailsResult">' if( data.length <= 0) { result += '<tr><td colspan="3">NO RESULTS FOUND</td></tr>' } else { // INITIAL SEARCH RESULT for ( let i = 0, l = data.length; i < l; i++) { result += '<tr colspan="3"><td><h4><a href="?pageType=contentDetails&contentId='+data[i].contentId+'">'+data[i].contentTitle+'</a></h4>'+ '<p>'+ searchClean(data[i].contentContent.substring(0,200)) +'....</p>'+ '<a href="?pageType=contentDetails&contentId='+data[i].contentId+'" class="searchurl">?pageType=contentDetails&contentId='+data[i].contentId+'</a> </td></tr>' } } result += '</tbody></table>' result += '</div></div></div>' $catTitle.append("Search Results") } // DISPLAY DATA $("#"+typeOf+"Count, #"+typeOf+"Result").empty() $("#Result").empty() $("#Result").append(result) $("#"+typeOf+"Count").append(data.length) // HIGHLIGHT CODE SECTIONS IF ADDED $("pre code").each(function() { Prism.highlightElement($(this)[0]) }) // ADD CODE COPY BUTTON $("pre").each(function () { $this = $(this) $button = $('<button>Copy</button>') $this.wrap('<div/>').removeClass('copy-button') $wrapper = $this.parent() $wrapper.addClass('copy-button-wrapper').css({position: 'relative'}) $button.css({position: 'absolute', top: 10, right: 10}).appendTo($wrapper).addClass('copy-button btn btn-code') // INITIATE CLIPBOARDJS var copyCode = new ClipboardJS('button.copy-button', { target: function (trigger) { return trigger.previousElementSibling } }) copyCode.on('success', function (event) { event.clearSelection() event.trigger.textContent = 'Copied' window.setTimeout(function () { event.trigger.textContent = 'Copy' }, 2000) }) copyCode.on('error', function (event) { event.trigger.textContent = 'Press "Ctrl + C" to copy' window.setTimeout(function () { event.trigger.textContent = 'Copy' }, 2000) }) }) } //-------------------------------------------------------------------------------------------// // DISPLAY TAGS -----------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function displayTags(x) { console.log("%c displayTags(x) ", "color: #ff7b00") var result = '<hr /><ul class="taggle_list">' var xx = x x = x || "" if(x.length <= 0) { result = '' } else { x = x.split(",") $(x).each(function(index, elem) { result += '<li class="taggle"><span class="taggle_text">'+ elem +'</span></li>' }) result += '</ul>' } return result } //-------------------------------------------------------------------------------------------// // BADGE STATUS -----------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function badgeStatus(x) { console.log("%c badgeStatus(x) ", "color: #ff7b00") var result; if(x > 0) { result = '<span class="badge">'+x+'</span>' } else { result = '<span class="badge badge-0">'+x+'</span>' } return result } //-------------------------------------------------------------------------------------------// // SEARCH CLEAN ----------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function searchClean(string) { console.log("%c searchClean(string) ", "color: #ff7b00") var output = string //JSON.stringify(string).replace(/\\n/g, '') if(string.includes("<table")) { output = output.replace(/<\/?[^>]+(>|$)/g, "") } return output } //-------------------------------------------------------------------------------------------// // SEARCH HIGHLIGHT -------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function searchHighlight(string, indices) { console.log("%c searchHighlight(string, indices) ", "color: #ff7b00") var start, end, length, output start = indices[0] end = indices[1] length = end - start + 1 // IMAGE OR ALT MATCH DO NOT HIGHLIGHT if(string.includes("<img")) { output = string; } else { output = string.slice(0,start)+'<span class="searchHighlight">'+string.slice(start,start+length)+'</span>'+string.slice(start+length) } return output.substring(0, 150) } //-------------------------------------------------------------------------------------------// // SEARCH SCORE -----------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function searchScore(a) { console.log("%c searchScore(a) ", "color: #ff7b00") var b = Math.max( Math.ceil(a * 10) / 10, 2.8 ) return a } //-------------------------------------------------------------------------------------------// // ESCAPE SPECIAL CHARS ---------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function specialChars(chars) { console.log("%c specialChars(chars) ", "color: #ff7b00") return chars .replace(/&/g, "&") .replace(/</g, "&lt;") .replace(/>/g, ">") .replace(/"/g, "&quot;") .replace(/'/g, "'") } //-------------------------------------------------------------------------------------------// // CONVERT DATE -----------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function convertDate(p) { console.log("%c convertDate(p) ", "color: #ff7b00") if( p == null) { p = "No Updates" } else { p = p.slice(0, 10) p = p.replace(/-/g, '/') p = p.split('/') p = p[1].replace(/(^|-)0+/g, "$1") + '-' + p[2].replace(/(^|-)0+/g, "$1") + '-' + p[0] } return p } //-------------------------------------------------------------------------------------------// // CONVERT LEVELS TO TEXT -------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function getUserLevel(level) { console.log("%c getUserLevel(level) ", "color: #ff7b00") var strLevel if(level == 1) { strLevel = "Internal <i class='fa fa-user-secret'></i>" } else if(level == 2) { strLevel = "External <i class='fa fa-share-alt'></i>" } else if(level == 3) { strLevel = "Admin" } return strLevel } //-------------------------------------------------------------------------------------------// // GET CATEGORY NAME ------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function getCategoryName(data, currCat) { console.log("%c getCategoryName(data, currCat) ", "color: #ff7b00") // data[2].categoryId var currentCat = "" var flag = true for(var i = 0; i < data.length; i++) { if(data[i].categoryId == currCat) { console.log("matchs") currentCat == data[i].categoryTitle flag = false return currentCat } } } //-------------------------------------------------------------------------------------------// // SHOW CATEGORIES --------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function showCategories(data, currCat) { console.log("%c showCategories(data, currCat) ", "color: #ff7b00") $(".categorySelect").empty() // prevent duplication var categoryOptions = "" var selectedCat = currCat for(var i = 0; i < data.length; i++) { if(selectedCat == data[i].categoryId) { categoryOptions+="<option value='"+data[i].categoryId+"' selected>"+data[i].categoryTitle+"</option>" } else { categoryOptions+="<option value='"+data[i].categoryId+"'>"+data[i].categoryTitle+"</option>" } } $(".categorySelect").append(categoryOptions) } //-------------------------------------------------------------------------------------------// // GET DATE ---------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function getDate() { console.log("%c getDate() ", "color: #ff7b00") var today = new Date() var dd = today.getDate() var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear() if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = yyyy+"-"+mm+"-"+dd+"T"+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds() document.getElementById("todaysDate").value = today return today } //-------------------------------------------------------------------------------------------// // SHOW OPTIONS -----------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------// function showOptions(currRecord, currentLevel) { console.log("%c showOptions(currRecord, currentLevel) ", "color: #ff7b00") // GET CURRENT USER LEVEL AND APPEND SELECT var userLevelOptions="" var optionNum=2 for(var i=1;i<=optionNum;i++) { if(currRecord == i) { userLevelOptions+="<option value='"+i+"' selected>"+currentLevel+"</option>" } else { userLevelOptions+="<option value='"+i+"'>"+getUserLevel(i)+"</option>" } } return userLevelOptions }
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin') module.exports = { entry: path.resolve(__dirname, 'src/index.tsx'), output: { filename: 'js/bundle.js', path: path.resolve(__dirname, 'dist'), publicPath: '', }, module: { rules: [ { test: /\.(ts|js)x?$/, exclude: /node_modules/, loader: 'babel-loader', }, ], }, resolve: { extensions: ['.tsx', '.ts', '.jsx', '.js'], }, plugins: [ new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'public/index.html'), }), new CopyWebpackPlugin([ { from: path.resolve(__dirname, 'public/css'), to: 'css' }, ]), ], devServer: { port: 3200, host: 'localhost', historyApiFallback: true, contentBase: path.resolve(__dirname, 'dist'), stats: 'errors-only', }, stats: 'errors-only', }
/** * Created by 10184092 on 2016/8/23. */ (function() { return { "en_US": { greetings: 'test', greetings1:'test1', neid:'neid' }, "zh_CN": { greetings: '测试', greetings1:'测试1', neid:'网元id' } } })();
$(document).ready(function(){ $("#submit").click(function() { if($("#name").val()=="") { alert("enter your name"); $("#name").focus(); return false; } if($("#password").val()=="") { alert("enter your password"); $("#password").focus(); return false; } }); });
import React, { forwardRef, useState, useEffect } from 'react' import PropTypes from 'prop-types' import { Scroll } from '@/components' import { useRequest } from '@/hooks' const INIT_PAGE = 1 const List = forwardRef((props, ref) => { const { requestMethod, renderItem, getSource, rowKey, } = props const [page, setPage] = useState(INIT_PAGE) const [list, setList] = useState([]) let [source, isLoading, isError] = useRequest(() => { return requestMethod({ page }) }, [page], null) useEffect(() => { if (!source) return if (getSource(source).page === INIT_PAGE) { setList(getSource(source).list) } else { setList([...list, getSource(source).list]) } }, [source]) if (isLoading || isError) { return <span>loading...</span> } return ( <Scroll> {list && Array.isArray(list) ? ( <ul> {list.map((item, index) => ( <li key={item[rowKey]}> {renderItem(item, index)} </li> ))} </ul> ) : null} </Scroll> ) }) List.propTypes = { requestMethod: PropTypes.func.isRequired, renderItem: PropTypes.func.isRequired, getSource: PropTypes.func, rowKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired } List.defaultProps = { } export default List
const getYouTubeID = require("get-youtube-id"); const fetchVideoInfo = require("youtube-info"); const request = require("request"); const ytdl = require("ytdl-core"); var names = []; var idlist = []; function youtube(args) { if (args.toLowerCase().indexOf('://') > -1) return true; else return false; } function play(id, message) { message.guild.voiceChannel = message.member.voiceChannel; if (message.guild.dispatcher) message.guild.dispatcher.end(); message.guild.voiceChannel.join() .then(connection => { const stream = ytdl("https://www.youtube.com/watch?v=" + id, { filter: 'audioonly' }); message.guild.dispatcher = connection.playStream(stream); message.guild.dispatcher.on('end', () => { message.guild.queue.shift(); message.guild.queueNames.shift(); message.guild.queueUser.shift(); if (message.guild.queue.length === 0) { message.guild.playing = false; message.guild.voiceChannel.leave(); } else { setTimeout(function() { play(message.guild.queue[0], message); }, 500); } }); }); } exports.run = (client, message, args) => { if (!message.guild.queue) { message.guild.queue = []; message.guild.queueNames = [], message.guild.queueUser = [], message.guild.isPlaying = false, message.guild.dispatcher = null, message.guild.voiceChannel = null, message.guild.skipReq = 0, message.guild.skippers = [] } if (message.member.voiceChannel || message.guild.voiceChannel ) { if (youtube(args[0])) { const id = getYouTubeID(args[0]); fetchVideoInfo(id, (err, videoInfo) => { if (message.guild.isPlaying || message.guild.queue.length > 0) { message.guild.queue.push(id); message.guild.queueNames.push(id); message.guild.queueUser.push(message.author.id); message.reply(`added to queue: **${videoInfo.title}**`); } else { message.guild.queue.push(id); message.guild.queueNames.push(id); message.guild.queueUser.push(message.author.id); play(id, message); message.reply(`now playing: **${videoInfo.title}**`); } }); } else { message.guild.voiceChannel = message.member.voiceChannel request("https://www.googleapis.com/youtube/v3/search?part=id&type=video&q=" + encodeURIComponent(args.join(' ')) + "&key=" + process.env.KEY, function(error, response, body) { names = []; idlist = []; const json = JSON.parse(body); const list = json.items.slice(0, 5); list.forEach(item => { fetchVideoInfo(item.id.videoId, (err, videoInfo) => { if(videoInfo) { idlist.push(item.id.videoId); names.push(videoInfo.title); } }); }); setTimeout(async function () { let reply = "No results!" if (names.length > 0) reply = "1⃣" + names[0]; if (names.length > 1) reply = reply + "\n2⃣" + names[1] if (names.length > 2) reply = reply + "\n3⃣" + names[2] if (names.length > 3) reply = reply + "\n4⃣" + names[3] if (names.length > 4) reply = reply + "\n5⃣" + names[4] const msg = await message.channel.send(reply) const filter = (reaction, user) => user === message.author && (0 < parseInt(reaction.emoji.name) && parseInt(reaction.emoji.name) < names.length + 1 || reaction.emoji.name === '❌') const collector = msg.createReactionCollector(filter, { time: 60000, max: 1 }); collector.on('end', r => msg.delete()) collector.on('collect', r => { if (r.emoji.name !== '❌') { const number = parseInt(r.emoji.name); if (message.guild.isPlaying || message.guild.queue.length > 0) { message.guild.queue.push(idlist[number - 1]); message.guild.queueNames.push(names[number - 1]); message.guild.queueUser.push(message.author.id); message.reply(`added to queue: **${names[number-1]}**`); } else if (message.member.voiceChannel) { message.guild.queue.push(idlist[number - 1]); message.guild.queueNames.push(names[number - 1]); message.guild.queueUser.push(message.author.id); play(idlist[number - 1], message); message.reply(`now playing: **${names[number-1]}**`); } else message.reply("join a voice channel first."); } }); if (names.length > 0 && !msg.deleted) await msg.react('1⃣').catch(err => console.log(err)); if (names.length > 1 && !msg.deleted) await msg.react('2⃣').catch(err => console.log(err)); if (names.length > 2 && !msg.deleted) await msg.react('3⃣').catch(err => console.log(err)); if (names.length > 3 && !msg.deleted) await msg.react('4⃣').catch(err => console.log(err)); if (names.length > 4 && !msg.deleted) await msg.react('5⃣').catch(err => console.log(err)); if (!msg.deleted) msg.react('❌'); }, 2000); }); } } else { message.reply("join a voice channel first."); } } exports.help = { description: "Plays audio from youtube.", usage: prefix => prefix + "play <link/query>" }
import React from 'react'; import { Typography } from '@material-ui/core'; const Product = ({ product, onAddToCart }) => { const handleAddToCart = () => onAddToCart(product.id, 1); return ( <div> <div> <img src={product.media.source} alt="loading" style={{width:'100%'}} class="w3-hover-opacity"/> <div class="w3-container w3-white"> <p><b>{product.name}</b></p> <p class="w3-opacity">${product.price.formatted}</p> <p> <Typography dangerouslySetInnerHTML={{ __html: product.description }} variant="body2" color="textSecondary" component="p" /></p> <button class="w3-button w3-black w3-margin-bottom" onClick={handleAddToCart}>Add to Cart</button> </div> </div> </div> ); }; export default Product;
const APP_CONFIG = require('./config') const express = require('express') const mongoose = require('mongoose') const bodyParser = require('body-parser') const cors = require('cors') const APP_ROUTER = require('./routes') const app = express() // Middleware plugin app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()) app.use(cors()) // Routes app.use(APP_ROUTER) app.use('/files', express.static('files')) // Database initialization mongoose.connect(`mongodb://${APP_CONFIG.database.host}:${APP_CONFIG.database.port}/${APP_CONFIG.database.database}`, { auth: { user: APP_CONFIG.database.username, password: APP_CONFIG.database.password }, useNewUrlParser: true, useUnifiedTopology: true }, (err) => { if (err) { console.error('[!] Error connecting to the database', err) return } else { console.log('[+] Database up') // Server initializacion app.listen(APP_CONFIG.server.port, (err) => { if (err) { console.error('[!] Error uploading the server', err) return } else { console.log('[+] Server up') } }) } })
export var loggerfunction = (store)=>(next)=>(action)=>{ console.log("log action which needs to be performed" , action.type) var result = next(action) console.log("log after this", action.type , "updated state" , store.getState()) return result } // can u perform asyncs actions into redux ? - No // yes we can perform with the help of middlewares // custom middleware // userdefined middlewares // async - thunk , redux-promise , redux-saga // aync api that we will call in middleware and based on the async result we will dispatch the action
const express = require('express'); const bodyParser = require('body-parser'); const morgan = require('morgan'); const cors = require('cors'); const config = require('./config/config.json'); const routes = require('./routes'); // App Setup const app = express(); app.use(morgan('dev')); app.use(cors()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use('/', routes); const PORT = process.env.PORT || config.api_server_port; app.listen(PORT, () => { console.log(`[API] HTTP API SERVER STARTED ON PORT: ${PORT}`); });
/** * 幸福家园控制层 */ Ext.define('eapp.controller.IntegratematerialTow', { extend: 'Ext.app.Controller', config: { refs: { mainview: 'mainview', integratemateriallisttow:'integratemateriallisttow', integratematerialdetailtow:'integratematerialdetailtow', newsbutton:{selector: 'integratemateriallisttow toolbar button[name=dsbuttontowname]'}, gonggaobutton:{selector: 'integratemateriallisttow toolbar button[name=tzbottontowname]'}, fuwubutton:{selector: 'integratemateriallisttow toolbar button[name=fwbuttontowname]'}, }, control: { newsbutton: { tap:'OnNewsbuttonTap', }, gonggaobutton: { tap:'OnGonggaobuttonTap', }, fuwubutton: { tap:'OnFuwubuttonTap', }, integratemateriallisttow: { itemtap:'OnItemTap', } } }, /** * 点击列表 */ OnItemTap:function(element, index, target, record, e, eOpts) { var me = this; var integratematerialdetailtow = me.getIntegratematerialdetailtow(); if(integratematerialdetailtow == null || integratematerialdetail == 'undefined') { integratematerialdetailtow = Ext.create('eapp.view.xinfujiayuan.IntegratematerialDetailTow'); } integratematerialdetailtow.init(record); me.getMainview().push(integratematerialdetailtow); var len = eapp.app.pageStack.length; if(eapp.app.pageStack[len-1] != 'integratematerialdetailtow') { eapp.app.pageStack.push('integratematerialdetailtow'); } }, /** * 点击党史按钮 */ OnNewsbuttonTap:function() { var me = this; var integratemateriallisttow = me.getIntegratemateriallisttow(); /** * 初始化Stroe */ integratemateriallisttow.setStore(null); integratemateriallisttow.setPageNo(1); integratemateriallisttow.setTotalpages(0); /** * 查询资料列表 * moduleTypeid: 模块类别id (1:智慧之窗 2:幸福家园 3:红色堡垒 4:社工加油站 5: 智慧视听) * materialState:资料状态(0:未审批;1:正在审批;2:通过;3:未通过) * showTypeid:展示类别id(1:新闻动态 2:通知公告 3:政务服务 4:党史 5:知识卡片 6:学习动态,15社区工作知识卡片16,优秀社区工作者展示 ) */ integratemateriallisttow.init(2,2,4); }, /** * 点击知识卡片按钮 */ OnGonggaobuttonTap:function() { var me = this; var integratemateriallisttow = me.getIntegratemateriallisttow(); /** * 初始化Stroe */ integratemateriallisttow.setStore(null); integratemateriallisttow.setPageNo(1); integratemateriallisttow.setTotalpages(0); /** * 查询资料列表 * moduleTypeid: 模块类别id (1:智慧之窗 2:幸福家园 3:红色堡垒 4:社工加油站 5: 智慧视听) * materialState:资料状态(0:未审批;1:正在审批;2:通过;3:未通过) * showTypeid:展示类别id(1:新闻动态 2:通知公告 3:政务服务 4:党史 5:知识卡片 6:学习动态,15社区工作知识卡片16,优秀社区工作者展示 ) */ integratemateriallisttow.init(2,2,5); }, /** * 点击政务服务按钮 */ OnFuwubuttonTap:function() { var me = this; var integratemateriallisttow = me.getIntegratemateriallisttow(); /** * 初始化Stroe */ integratemateriallisttow.setStore(null); integratemateriallisttow.setPageNo(1); integratemateriallisttow.setTotalpages(0); /** * 查询资料列表 * moduleTypeid: 模块类别id (1:智慧之窗 2:幸福家园 3:红色堡垒 4:社工加油站 5: 智慧视听) * materialState:资料状态(0:未审批;1:正在审批;2:通过;3:未通过) * showTypeid:展示类别id(1:新闻动态 2:通知公告 3:政务服务 4:党史 5:知识卡片 6:学习动态,15社区工作知识卡片16,优秀社区工作者展示 ) */ integratemateriallisttow.init(2,2,3); } });
import Vue from 'vue' import Router from 'vue-router' import HomeView from '@/components/HomeView' import MyTasks from '@/components/MyTasks' import DetailView from '@/components/DetailView' import PostView from '@/components/PostView' import About from '@/components/About' import CreateRequest from '@/components/CreateRequest' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'home', component: HomeView }, { path:'/createrequest', name: 'createrequest', component: CreateRequest }, { path: '/myTask', name: 'myTask', component: MyTasks }, { path: '/detail/:id', name: 'detail', component: DetailView }, { path: '/post', name: 'post', component: PostView }, { path: '/about', name: 'about', component: About } ] })
import 'jsdom-global/register'; import React from 'react'; import { expect } from 'chai'; import { mount, shallow } from 'enzyme'; import RecentArticle from './RecentArticles'; function getStubPost(number){ let post = { node:{ frontmatter:{ title: "any title"+number }, path: "/anyPath"+number+"/" } }; return post; } function getStubPosts(numPosts){ let posts = []; for(let i = 0; i < numPosts;i++){posts.push(getStubPost(i))} return posts; } function findLink(numPosts){ let wrapper = shallow(<RecentArticle posts={getStubPosts(numPosts)} />); return wrapper.find(".link-recent-articles"); } describe("<RecentArticle />",function(){ it("three post show three links", function () { let linkPages = findLink(3); expect(linkPages.length).to.equal(3); }); it("max limit five pages", function () { let linkPages = findLink(8); expect(linkPages.length).to.equal(5); }); xit("Items are sorted from most recent to oldest", function () { //test broken let pages = getStubPosts(8); let wrapper = shallow(<RecentArticle posts={pages} />); let linkPages = wrapper.find("li"); pages = pages.reverse().slice(0,5); expect(linkPages.length).to.equal(5); let i = 0; linkPages.forEach(function (node) { expect(node.childAt(0).children().text()).to.equal(pages[i].node.frontmatter.title); i++; }); }); });
/* eslint-disable react/no-unused-prop-types */ import React from 'react'; import PropTypes from 'prop-types'; import fetch from 'node-fetch'; import ProductList from './product-list'; import SortConstants from '../../constants/sortConstants'; import PriceConstants from '../../constants/priceConstants'; import UrlConstants from '../../constants/urlConstants'; /** * Wrapper to make HTTP calls to fetch data */ class ProductListContainer extends React.Component { static getCategoryFilterUrl(filters) { if (filters.length === 1) { // filter where category is equal to filter return `${UrlConstants.category_equal}${filters[0]}&`; } else if (filters.length > 1) { // filter where category is either filters return `${UrlConstants.category_either}${filters.toString()}&`; } return ''; } static getPriceFilterUrl(filters) { if (filters) { return `${UrlConstants.price_less_than}${filters * PriceConstants.divisor}&`; } return ''; } static getSortUrl(sort) { if (sort && sort !== SortConstants.none) { // determine how data is sorted return `${UrlConstants.sort}${sort}&`; } return ''; } static getPaginateUrl(paginations) { if (paginations[0] && paginations[1]) { return `${UrlConstants.page_number}${paginations[0]}${UrlConstants.page_size}${paginations[1]}&`; } return ''; } constructor(props) { super(props); this.state = { products: [], links: [], }; } componentDidMount() { this.fetchData(UrlConstants.main); } componentWillReceiveProps(nextProps) { const filterUrl = (nextProps.priceFilters === '0') ? ProductListContainer.getCategoryFilterUrl(nextProps.categoryFilters) : ProductListContainer.getPriceFilterUrl(nextProps.priceFilters); const sortUrl = ProductListContainer.getSortUrl(nextProps.sort); const paginateUrl = ProductListContainer.getPaginateUrl(nextProps.paginations); this.fetchData(`${UrlConstants.main}?${filterUrl}${sortUrl}${paginateUrl}`); } /** * fetch data via API * @param string - url */ fetchData(url) { fetch(url) .then(res => res.json()) .then((json) => { this.setState({ products: json.data, links: json.links, // used for testing }); this.props.setPageRange(json.links); }); } render() { return ( <ProductList products={this.state.products} /> ); } } ProductListContainer.propTypes = { categoryFilters: PropTypes.arrayOf(PropTypes.string).isRequired, priceFilters: PropTypes.string.isRequired, sort: PropTypes.string.isRequired, paginations: PropTypes.arrayOf(PropTypes.string).isRequired, setPageRange: PropTypes.func.isRequired, }; export default ProductListContainer;
import axios from 'axios' import cookies from 'vue-cookies' const API_SERVER_URL = process.env.VUE_APP_API_SERVER_URL const homeStore = { namespaced: true, state: { homeSubscribeChannelRanking: [], homeViewsChannelRanking: [], homeRecommandChannels: [], homeRecommandVideos: [], companyIndustry: '' }, mutations: { setHomeSubscribeChannelRanking(state, data) { state.homeSubscribeChannelRanking = data }, setHomeViewsChannelRanking(state, data) { state.homeViewsChannelRanking = data }, setHomeRecommandChannels(state, data) { state.homeRecommandChannels = data }, setHomeRecommandVideos(state, data) { state.homeRecommandVideos = data }, setCompanyIndustry(state, data) { state.companyIndustry = data } }, actions: { // 채널 랭킹 top5 조회 async getChannelRankingData({ commit }) { const config = { headers: { token: cookies.get('token') } } axios.get(`${API_SERVER_URL}/search/subscribe`, config).then(response => { commit('setHomeSubscribeChannelRanking', response.data) }) const response = await axios.get(`${API_SERVER_URL}/search/avgview`, config) commit('setHomeViewsChannelRanking', response.data) }, // 카테고리별 추천 채널 조회 async getHomeRecommandChannels({ commit }) { const config = { headers: { token: cookies.get('token'), companyid: cookies.get('companyId') } } const response = await axios.get(`${API_SERVER_URL}/search/catechannel`, config) commit('setHomeRecommandChannels', response.data) }, async getHomeRecommandVideos({ commit }) { const config = { headers: { token: cookies.get('token'), companyid: cookies.get('companyId') } } const response = await axios.get(`${API_SERVER_URL}/search/catevideo`, config) commit('setHomeRecommandVideos', response.data) }, // companyIndustry 죄회 async getCompanyIndustry({ commit }) { const config = { headers: { token: cookies.get('token'), companyid: cookies.get('companyId') } } const response = await axios.get(`${API_SERVER_URL}/company/${cookies.get('companyId')}`, config) commit('setCompanyIndustry', response.data.company_industry) } } } export default homeStore
const input = require('prompt-sync')() function main(){ let codigo =1; while(codigo === 1){ let nota_1 = Number(input('Informe aqui a primeira nota: ')); while(nota_1 < 1 || nota_1 > 10){ console.log('Nota informada inválida!') nota_1 = Number(input('Por favor informe um valor válido para a primeira nota: ')) } let nota_2 = Number(input('Informe a segunda nota: ')) while(nota_2 < 1 || nota_2 > 10){ console.log('Nota informada inválida!'); nota_2 = Number(input('Por favor informe uma nota válida para essa nota: ')) } console.log(`Média = ${(nota_1 + nota_2) / 2}`); codigo = Number(input('Novo cálculo? (1-Sim) e (2-Não) ')); } } main()
// pages/vote_detail/vote_detail.js const request_01 = require('../../utils/request/request_01.js'); const request_05 = require('../../utils/request/request_05.js'); const router = require('../../utils/tool/router.js'); const tool = require('../../utils/tool/tool.js'); const app = getApp(); Page({ /** * 页面的初始数据 */ data: { IMGSERVICE: app.globalData.IMGSERVICE, imgVideoType: 1, isRed: false, isZan: 0, isShare: false, isXin: false, num: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26], videoUrl: 'https://game.flyh5.cn/resources/game/wechat/szq/images/video_04.mp4', firstShow: false, }, isZan() { const user_id = wx.getStorageSync('userInfo').user_id; const vote_id = this.data.vote_id; const type = 1; request_05.doVote({ user_id, vote_id, type }).then(res => { const status = res.data.data.status this.setData({ status, }) }) }, isRed() { this.setData({ isRed: !this.data.isRed }); }, dianz() { console.log(this.data.activeStatus); if (this.data.activeStatus == 4) { tool.alert('活动已结束'); return; } let activity_id = this.data.activity_id; let user_id = wx.getStorageSync('userInfo').user_id let vote_id = this.data.vote_id; let is_favorite = this.data.is_favorite; let vote_info = this.data.vote_info let type = 1; if (is_favorite == 0) { let isZan = this.data.isZan; let ding = setInterval(() => { isZan++; this.setData({ isZan, }) if (isZan == 27) { clearInterval(ding) this.setData({ isZan: 4, is_favorite: 1, }) } }, 50) is_favorite = 1 vote_info.votes = vote_info.votes + 1 this.setData({ vote_info, }) request_05.doVote({ user_id, vote_id, type }).then(res => { tool.alert(res.data.msg) }) } else { request_05.doVote({ user_id, vote_id, type }).then(res => { tool.alert('您今天已为TA投过票~'); }) } }, // 分享按钮 isShare() { // 判断是否分享进入 if (!this.data.options.user_id || this.data.options.user_id == wx.getStorageSync('userInfo').user_id) { if (this.data.vote_info.status == 1 || this.data.vote_info.status == null || this.data.vote_info.status == 3) { this.setData({ isShare: !this.data.isShare }); } else { tool.alert('审核未通过,不能分享') } } else { this.setData({ isShare: !this.data.isShare }); } }, // 分享海报 bindShare() { let activity_id = this.data.activity_id let user_id = this.data.user_id let share_userId = this.data.share_userId console.log(user_id,'user_id') let vote_id = this.data.vote_id; let type = 2; request_05.myVote({ activity_id, user_id }).then(res => { router.jump_nav({ url: `/pages/poster/poster?activity_id=${activity_id}&vote_id=${vote_id}&user_id=${user_id}`, }) request_05.doVote({ user_id, vote_id, type }).then(res => { console.log(res); }) }) }, // 分享好友 shareFriend() { const activity_id = this.data.activity_id const user_id = wx.getStorageSync('userInfo').user_id const vote_id = this.data.vote_id; const type = 2; request_05.doVote({ user_id, vote_id, type }).then(res => { console.log(res); }) }, // 初始化数据 initData(options) { console.log(options) let activity_id = ''; let vote_id = ''; let parent_id = ''; if (options.scene) { let scene = decodeURIComponent(options.scene); console.log(scene) scene.split('&').forEach((item) => { console.log(item.split('=')) if (item.split('=')[0] == 'p') { //找到channel_id并存储 parent_id = item.split('=')[1] } if (item.split('=')[0] == 'a') { //找到channel_id并存储 activity_id = item.split('=')[1] } if (item.split('=')[0] == 'v') { //找到user_id并存储 vote_id = item.split('=')[1] } }) } else { console.log(options) activity_id = options.activity_id; vote_id = options.vote_id; } tool.loading('加载中') console.log("activity_id", activity_id) console.log("vote_id", vote_id) let hav_rank = 1; let user_id = wx.getStorageSync('userInfo').user_id; if(!this.data.user_id){ this.setData({ user_id, }) } console.log(user_id,'user_id') this.setData({ activity_id, }) request_05.voteIndex({ user_id, activity_id }).then(res => { this.setData({ activeStatus: res.data.data.status, }) }) if (vote_id != null) { request_05.voteDetail({ user_id, vote_id, hav_rank }).then(res => { console.log("voteDetail", res) let vote_info = res.data.data; let is_favorite = res.data.data.is_favorite; console.log('vote_info.rank', vote_info.rank) if (vote_info.is_favorite == 0) { this.setData({ //未点赞 isZan: 3 }) } else { this.setData({ isZan: 4 }) } this.setData({ vote_info, vote_id, is_favorite, isXin: true, isHid: true, }) }) tool.loading_h(); } else { request_05.myVote({ user_id, activity_id }).then(res => { console.log("detail", res); console.log("{ user_id, vote_id, hav_rank }", { user_id, activity_id }) let vote_info = res.data.data.info let vote_id = res.data.data.info.vote_id this.setData({ vote_info, vote_id, isHid: false, }) }) tool.loading_h(); } }, // 立即参与 toPartake() { let activity_id = this.data.activity_id; router.jump_red({ url: `/pages/lj_partake/lj_partake?activity_id=${activity_id}`, }) }, // 回到首页 toHome() { let activity_id = this.data.activity_id; router.jump_nav({ url: `/pages/vote_page/vote_page?activity_id=${activity_id}`, }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { console.log('options', options) request_01.login(() => { this.initData(options); }) let hav_rank = options.hav_rank let vote_id = options.vote_id let user_id = options.user_id let type = options.type let activity_id = options.activity_id this.setData({ options, activity_id, vote_id, user_id }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function() { tool.loading_h(); this.setData({ firstShow: true }) }, /** * 生命周期函数--监听页面显示 */ onShow: function() { let options = this.data.options if (this.data.firstShow) { this.initData(options) } }, /** * 生命周期函数--监听页面隐藏 */ onHide: function() { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function() { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function() { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function() { }, /** * 用户点击右上角分享 */ onShareAppMessage: function(options) { let user_id = wx.getStorageSync('userInfo').user_id; let vote_id = this.data.vote_id; let activity_id = this.data.activity_id; let type = 1; let parent_id = this.data.parent_id; console.log(vote_id, user_id); let obj = { title: '大侠请留步!帮我点个赞,赢京东500元购物卡!', path: `/pages/vote_detail/vote_detail?vote_id=${vote_id}&user_id=${user_id}&activity_id=${activity_id}&parent_id=${parent_id}`, imageUrl: this.data.IMGSERVICE + "/activity/vote.jpg" }; return obj; }, })
(function(){ 'use strict'; angular.module('yrzb.controllers') .controller('MyFinancingCtrl', function($scope, $api, $ui, $state) { //默认搜索 $scope.type = '0'; $scope.hasPermission = false; resetSearchCondition(); function resetSearchCondition(){ $scope.prjList = []; $scope.page = {current_page:1}; $scope.isNoData = false; } //变更搜索类型 $scope.changeType = function(nav){ $scope.type = nav.$index; $scope.typeLabel = $scope.subNav[$scope.type].label; resetSearchCondition(); }; $scope.subNav = [ {label: '全部记录', action: $scope.changeType, icon: 16}, {label: '审批中', action: $scope.changeType, icon: 12}, {label: '审批通过', action: $scope.changeType, icon: 10}, {label: '审批不通过', action: $scope.changeType, icon: 14} ]; $scope.typeLabel = $scope.subNav[$scope.type].label; $api.checkPermission(function(data){ if(data.boolen === 1){ $scope.hasPermission = true; } }) //加载更多 $scope.loadMore = function(){ $api.getList({p:$scope.page.current_page, status: $scope.type}, function(data){ if(data.boolen ===1){ $scope.prjList = $scope.prjList.concat(data.data.list); $scope.page = data.data.page; if($scope.page.current_page >= $scope.page.total_page){ $scope.isNoData = true; }else{ $scope.$broadcast('scroll.infiniteScrollComplete'); } } }) } }) .controller('MyFinancingDetailsCtrl', function($scope, $api, $ui, $state) { $scope.prj = {id:$state.params.id}; $api.getFinancingApplyData({id:$scope.prj.id},function(data){ if(data.boolen ===1){ $scope.prj = data.data; } }) }) .controller('DemandAddCtrl', function($scope, $api, $ui, $sessionStorage, $rootScope, $state, $userInfo) { $scope.userinfo = $sessionStorage.getObject('userinfo'); $rootScope.rootAddDemandForm.user_type = $scope.userinfo.user_type; $scope.items_finance_amount = []; $scope.items_time_limit = []; $scope.items_money_using = []; $api.getBorrower(function(data){ if(data.boolen ===1){ var json = data.data; $rootScope.rootAddDemandForm.uname = json.user.uname; $rootScope.rootAddDemandForm.corp_name = json.corp.corp_name; $rootScope.rootAddDemandForm.corp_legal_work_year = json.corp_legal.work_years; } }) $api.getDict(function(data){ if(data.boolen ===1){ $scope.items_finance_amount = data.data.items_finance_amount; $scope.items_time_limit = data.data.items_time_limit; $scope.items_money_using = data.data.items_money_using; } }) $scope.$watch('rootAddDemandForm.uid_type', function(){ $api.getManagersCustomers({uid_type: $rootScope.rootAddDemandForm.uid_type},function(data){ if(data.boolen ===1){ console.log(data); } }) }) $scope.selectProducts = function(){ if(!$scope.validForm()) { return false; } $state.go('app.products'); } }) .controller('DemandAddProductCtrl', function($scope, $api, $ui, $rootScope, $state) { $scope.applySubmit = function(){ if(!$scope.validForm()) { return false; } $api.addData($rootScope.rootAddDemandForm,function(data){ if(data.boolen ===1){ $state.go("app.demandAddSuccess"); } }) }; }) .controller('DemandAddSuccessCtrl', function($scope, $api, $ui) { }) .controller('ProductsCtrl', function($scope, $api, $ui, $rootScope, $state) { $scope.searchCondition = {}; $state.params.prodName && ($scope.searchCondition.prodName = $state.params.prodName); $state.params.financeAmountNo && ($scope.searchCondition.financeAmountNo = $state.params.financeAmountNo); $state.params.periodItemNo && ($scope.searchCondition.periodItemNo = $state.params.periodItemNo); $state.params.financeUseNo && ($scope.searchCondition.financeUseNo = $state.params.financeUseNo); $api.getProducts($scope.searchCondition, function(data){ if(data.boolen ===1){ console.log(data); $rootScope.products = data.data; } }) }) .controller('ProductCtrl', function($rootScope, $scope, $api, $ui, $state) { $rootScope.rootAddDemandForm.ubsp_product_no = $state.params.ubsp_product_no; $rootScope.rootAddDemandForm.ubsp_product_name = $state.params.ubsp_product_name; var ubsp_product_no = $state.params.ubsp_product_no; $scope.product = {}; $api.getProducts({ubsp_product_no:ubsp_product_no},function(data){ if(data.boolen ===1){ console.log(data); $scope.product = data.data; $rootScope.rootAddDemandForm.ubsp_product_no = $scope.product.prodNo; $rootScope.rootAddDemandForm.ubsp_product_name = $scope.product.prodName; } }) }) .controller('RealControllerCtrl', function($scope, $api, $ui) { }) .controller('ProductsSearchCtrl', function($scope, $api, $ui, $state) { $scope.items_finance_amount = []; $scope.items_time_limit = []; $scope.items_money_using = []; $scope.search ={}; $api.getDict(function(data){ if(data.boolen ===1){ $scope.items_finance_amount = data.data.items_finance_amount; $scope.items_time_limit = data.data.items_time_limit; $scope.items_money_using = data.data.items_money_using; } }) $scope.applySearch = function(){ $state.go('app.products',{ prodName: $scope.search.prodName, financeAmountNo: $scope.search.financeAmountNo, periodItemNo: $scope.search.periodItemNo, financeUseNo: $scope.search.financeUseNo, time: Date.parse(new Date()) }); //$api.getProducts($scope.search,function(data){ // if(data.boolen ===1){ // console.log(data); // $scope.product = data.data; // } //}) }; }) .controller('HasRepaymentCtrl', function($scope, $api, $ui) { }) .controller('ForRepaymentCtrl', function($scope, $api, $ui) { }) .controller('MoneyCtrl', function($scope, $api, $ui) { }) .controller('MoneyRecordCtrl', function($scope, $api, $ui) { }) .controller('MoneyRepaymentCtrl', function($scope, $api, $ui) { }) .controller('BankSelectCtrl', function($rootScope, $scope, $api, $ui, $state) { $scope.account_no_show = $rootScope.rootAddDemandForm.loanbank_account; $scope.bankCardList = []; $api.getBorrower(function(data){ if(data.boolen ===1){ console.log(data); $scope.bankCardList = data.data.bank_list; } }) $scope.getItem = function($this){ $rootScope.rootAddDemandForm.loanbank_account_show = $this.item.account_no_show; $rootScope.rootAddDemandForm.loanbank_account = $this.item.id; $rootScope.rootAddDemandForm.bank_name = $this.item.bank_name; }; $scope.applySelect = function(){ if(!$rootScope.rootAddDemandForm.loanbank_account){ $ui.alert('请选择放款银行卡!'); return; } $state.go('app.demandAddProduct'); }; }) }());
'use strict'; module.exports = { server: 500, validation: 422, unauthorized: 401, noPermission: 403, notFound: 404, conflict: 409 };
var fs = require('fs'); var util = require('util'); var et = require('elementtree'); var path = require('path'); exports = module.exports = {}; // // main func which applies all active rules // var go = function (threadGroupName, fileName) { var rules = require('./lib/rules.js').rules; data = fs.readFileSync(fileName).toString(); etree = et.parse(data); var threadGroup = null; var hashTree = null; if (threadGroupName) { // // in jmeter, threadGroup is one element and all it subelements are in its // hastree. the problem is that this hashTree is actualy its sibling // element. so this code should handel that. // threadGroup = etree .find('.//ThreadGroup[@testname="' + threadGroupName + '"]'); console.log(util.inspect(threadGroup)); var hashTreeId = threadGroup ._children[threadGroup._children.length - 1]._id + 1; var allHashTrees = etree.findall('.//hashTree'); allHashTrees.forEach(function (tree) { if (tree._id == hashTreeId) { hashTree = tree; } return false; }); console.log(util.inspect(hashTree)); } // apply each rule rules.forEach(function (rule) { if (rule.active) { var elements; if (threadGroup && hashTree) { elements = hashTree.findall(rule.xpath); elements = elements.concat(threadGroup.findall(rule.xpath)) } else { elements = etree.findall(rule.xpath); } //console.log(elements); elements.forEach(function (el) { var original = el.text; rule.fn(el); }); if (rule.changesCount) { console.log(rule.name + ': ' + rule.changesCount); } } }); //console.log(etree.write()); //TODO: hardcoded file name, move to some config/parameter fs.writeFileSync('new_' + path.basename(fileName), etree.write({indent: 2})); } exports.go = go;
import React, { Component } from "react"; import { Consumer } from "../../context"; import BookingForm from "./BookingForm"; class BookingModal extends Component { render() { const { id, handleClose, show, availability } = this.props; return ( <Consumer> {value => { const { dispatch } = value; return show ? ( <div className="booking-modal" ref={node => { this.node = node; }} > <div className="modal-body" ref={this.modalRef}> <div className="modal-content"> <h1 className="booking-title">Your Booking</h1> <h2 className="booking-date">Date: Today</h2> <h3 className="booking-availability"> It is{" "} {availability ? ( <span className="open">Available!</span> ) : ( <span className="taken">Unavailable, sorry!</span> )} </h3> <BookingForm availability={availability} id={id} handleClose={handleClose} dispatch={dispatch} /> </div> </div> </div> ) : null; }} </Consumer> ); } } export default BookingModal;
import './recommands.less'; import React from 'react'; import { Link } from 'react-router'; class Recommands extends React.Component { render() { return ( <div className="recommands"> <h2>推荐阅读</h2> <ul className="recommands-list"> {this._renderRecommands()} </ul> </div> ); } _renderRecommands() { return this.props.data.map(function(item) { var url = '/' + item.channel.name + '/' + item.type + '/' + item.id; return ( <li key={item.id}> <Link className="recommands-item-link" to={url}> <span className="recommands-item-thumbnail"><img src={item.thumb} /></span> <span className="recommands-item-title">{item.title}</span> </Link> </li> ); }); } } export default Recommands;
function lanzardados() { let dado1 = getNumRand(1, 6); let dado2 = getNumRand(1, 6); let suma = dado1 + dado2; document.getElementById("ImgDado1").src="dados/"+dado1+".png"; document.getElementById("ImgDado2").src="dados/"+dado2+".png"; document.getElementById("SumaDados").innerHTML = suma; } function getNumRand(min, max) { return Math.round(Math.random()*(max-min)+parseInt(min)); }
import React from 'react'; import { Card } from 'react-bootstrap'; import { Link } from 'react-router-dom'; const MovieSimilar = ({ movies }) => { console.log(movies); return ( <div className="mt-3 pl-4 pb-5" style={{ width: '95%' }}> <h5 className="pb-1">Similar Movies</h5> {movies.length === 0 && ( <span> Insufficient Data to suggest similar movies!</span> )} {movies.length !== 0 && ( <div className="d-flex flex-row flex-nowrap pt-2 pl-3" style={{ overflowX: 'auto' }} > {movies.map((movie, index) => { return ( <Card key={`movie_similar_${movie.id}`} className="col-md-4 px-0" style={{ minWidth: '300px', maxWidth: '350px', backgroundColor: 'transparent', border: '0px', }} > <Link to={`/movie/${movie.id}`} style={{ textDecoration: 'none' }} > <Card.Img loading="lazy" src={`https://image.tmdb.org/t/p/w780${movie.backdrop_path}`} /> <Card.Text className="pl-1 pt-1" style={{ color: '#c3d1d9' }}> <strong>{movie.title}</strong> </Card.Text> </Link> </Card> ); })} </div> )} </div> ); }; export default MovieSimilar;
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import faker from 'faker'; import { createUser } from './store'; const Nav = ({ create, users, location: { pathname } })=> { return( <nav> <Link to = '/' className = { pathname === '/' ? 'selected' : ''}>Home</Link> <Link to = '/users' className = { pathname === '/users' ? 'selected' : ''}>Users ({ users.length })</Link> <Link to = '/users/create' className = { pathname === '/users/create' ? 'selected' : ''}>Create User</Link> </nav> ); } export default connect( state => state, (dispatch, { history })=> { return { create: (name)=> { dispatch(createUser(name, history)); //console.log(name); } } } )(Nav);
const express = require('express'); const mongoose = require('mongoose'); const bodyparser = require('body-parser'); const passport = require('passport'); //bring all routes const auth = require('./routes/api/auth'); const profile = require('./routes/api/profile'); const questions = require('./routes/api/questions'); const app = express(); //middleware fore body-parser app.use(bodyparser.urlencoded({extended : false})); app.use(bodyparser.json()); //mongoDB configuration const db = require('./setup/myurl').mongoURL //attemp to connect to database mongoose .connect(db) .then(() => console.log("mongoDB connected successfully")) .catch( err => console.log(err) ) var port = process.env.PORT || 3000; var hostname = "127.0.0.1"; //just for testing route app.get('/', (req, res) => { res.send("hello this is small stack "); }); //passport middileware app.use(passport.initialize()); //config for jWT strategy require('./strategies/jsonwtStrategy')(passport); //auctual routes app.use('/api/auth', auth); app.use('/api/profile', profile); app.use('/api/questions', questions); app.listen(port, hostname, () => { console.log(`server is running at http://${hostname}:${port}`); });
import { createMuiTheme } from '@material-ui/core'; const theme = createMuiTheme({ palette: { primary: { main: '#64dd17', }, secondary: { main: '#ff5252', }, tertiary: { main: '#3949ab', dark: '#273377', light: '#606dbb', contrastText: '#fff', }, }, typography: { fontFamily: 'Segoe UI', }, shape: { borderRadius: 25, }, }); export default theme;
angular.module('ControllerModule', []) .controller('ControllerOne',['$scope','MessageService',function($scope, MessageService){ $scope.output= MessageService.message(); console.log("Inside Controller 1"); }]);
module.exports = { common: { login: '登录', register: '注册', logout: '退出登录', tip: '温馨提示', logintip: '请先登录', expect: '敬请期待!', delete: '确定删除吗?', nodata: '暂无记录', set: '设置', update: '修改', person:"个人中心" }, header: { index: '首页', exchange: '币币交易', otc: 'Launchpad', asset: '财务中心', ucenter: '账户中心', service: '公告', downloadapp: "扫码进行下载安装", appdownlaod: 'APP下载', help: "帮助" }, sectionPage: { ptaqTitle: '平台安全', ptaqContent: '采用哈希算法加密,全球领先的安全认证', ptslTitle: '平台实力', ptslContent: '全球最大的比特币交易平台', newsTitle: '多终端APP' }, nav: { shouye: '首页', jiaoyi: 'launchpad', dingdan: '订单管理', zijin: '财务中心', yonghu: '用户中心', bibi: '币币交易', fabu: '发布广告', ptjy: '平台交易', ptaq: '平台安全', ptsl: '平台实力', xwzx: '多终端APP' }, progress: { already: "已挖矿", total: "可挖矿总量60亿 BHB" }, service: { BC: 'QC', USDT: 'USDT', BTC: 'BTC', ETH: 'ETH', CUSTOM: '自选', COIN: '币种', favor:'收藏', symbol: '交易对', NewPrice: '最新价', ExchangeNum: '交易数量', Change: '24h涨跌', OpenPrice: '开盘价', PriceTrend: '价格趋势', Operate: '操作', Exchange: '去交易', high: "24h最高价", low: "24h最低价" }, exchange: { coin: '币种', symbol:"交易对", lastprice: '最新价', daychange: '24h涨跌', market: '市场', favorite: '收藏', do_favorite: '已收藏', cancel_favorite: '取消收藏', high: '高', low: '低', vol: '24H量', buy: '买入', sell: '卖出', limited_price: '限价', market_price: '市价', fees_rate: '费率', balance: '资产', or: '或', starttrade: '开始交易', canuse: '可用', recharge: '充币', buyprice: '买入价', buynum: '买入量', amount: '交易额', buyin: '买入', buytip: '以市场上最优价格买入', sellprice: '卖出价', sellnum: '卖出量', sellout: '卖出', selltip: '以市场上最优价格卖出', curdelegation: '当前委托', hisdelegation: '委托历史', realtransaction: '实时成交', num: '数量', price: '价格', direction: '方向', time: '时间', stall: '档位', total: '累计', traded: '已成交', action: '操作', undo: '撤单', delegationnum: '委托量', done: '已成交', status: '状态', finished: '已完成', canceled: '已取消', tip: '温馨提示', buyamounttip: '请输入买入量', buyamounttipwarning: '买入数量不能高于', success: '提交成功', pricetip: '请输入交易额', pricetipwarning: '交易额不能高于', sellamounttip: '请输入卖出量', sellamounttipwarning: '卖出数量不能高于', sellpricetip: '请输入卖出价格', sellpricetipwarning: '卖出价格不能高于', undotip: '是否确认撤单?', marketprice: '市价', expand: { time: '时间', price: '价格', amount: '数量', fee: '手续费', }, realtime: '分时', }, otc: { ad: '广告中心', buyin: '买入', sellout: '卖出', merchant: '商家', applymerchant: '申请为认证商家', volume: '交易笔数', paymethod: '付款方式', amount: '数量', limitAmount: "限额", price:"单价", price_coin: '价格/币', operate: '操作', validate: '请先进行实名认证', sell: '卖出', buy: '买入', transaction: '买卖交易', myad: { title: '我的广告', post: '发布广告', alert: '【温馨提示】:当广告最小交易额所购买数量加上手续费大于广告剩余数量,该广告自动下架', no: '广告编号', type: '广告类型', sell: '在线出售', buy: '在线购买', limit: '订单限额', remain: '剩余数量', coin: '币种', created: '创建时间', operate: '操作', errmsg: '广告下架后才可编辑修改', update: '修改', shelf: '上架', dropoff: '下架', delete: '删除', }, myorder: '我的订单', chatline: { status_1: '买家未付款,等待买家付款!', status_2: '买家已付款,等待卖家放行!', status_3: '订单已完成交易!', status_4: '订单正在申诉中!', status_5: '订单已取消!', loadmore: '加载更多', warning: '防诈骗提示:近期,屡有诈骗份子利用银行转账汇款信息和假汇款凭据进行诈骗,请一定登陆自己的收款账号核实。保证汇入资金的安全,避免银行卡被冻结的风险!', contenttip: '请输入聊天内容 回车键发送', contentmsg: '消息不能为空', }, chat: { seller: '卖家', buyer: '买家', exchangeamount: '交易金额', operatetip: '操作提示', operatetip_1: '请在规定的时限内按照对方给出的账号完成支付,并在本页面点击', finishpayment: '付款完成', operatetip_1_1: '转账时请在留言中备注好交易单号', operatetip_1_2: '卖方收到款项后会在网站确认收款,系统会自动将您所购买的数字资产发放至您的账户,请注意查收', note: '注意', notetip: '请不要使用其他聊天软件与对方沟通,更不要接受对方向您发送的任何文件、邮箱附件等,所有沟通环节请都在本页面的聊天窗口完成', operatetip_2_1: '您所出售的数字资产,已交由平台托管冻结。请在确定收到对方付款后,点击', operatetip_2_2: '请不要相信任何催促放币的理由,确认收到款项后再释放数字资产,避免造成损失!', operatetip_2_3: '在收到账短信后,请务必登录网上银行或手机银行确认款项是否入账,避免因收到诈骗短信错误释放数字资产!', confirmrelease: '确认放行', paydigital: '支付数字资产', orderstatus: '订单状态', orderstatus_1: '付款完成', orderstatus_2: '订单申诉', orderstatus_3: '确认放行', orderstatus_4: '取消交易', orderstatus_5: '订单申诉', order: '订单', and: '与', transition: '的交易', transprice: '交易价格', transnum: '交易数量', transmoney: '交易金额', tip1: '用户暂时未添加银行卡卡号', tip2: '用户暂时未添加支付宝账号', tip3: '用户暂时未添加微信账号', zfb: '支付宝', wx: '微信', qrcode: '二维码', msg1: '您确定已经付款完成吗', msg2: '已付款项并不退还!您确定取消订单吗?', msg3: '【重要】:已付款项并不退还!您确定取消订单吗?', msg4: '已付款,未收到币', msg5: '已付币,未收到款', tip: '提示', comptype: '投诉类型', compremark: '投诉备注', willcomp: '我要投诉', msg6: '是否确认放币?', result_1: '等待付款', result_2: '等待放行', result_3: '已完成', result_4: '申诉中', result_5: '已取消', msg7: '资金密码', msg7tip: '请填写资金密码', }, checkuser: { emaildone: '邮件已认证', emailundo: '邮件未认证', teldone: '手机号码已认证', telundo: '手机号码未认证', idcarddone: '身份证已认证', idcardundo: '身份证未认证', language: '语言', languagetext: '中文', registtime: '注册时间', exchangetimes: '累计交易次数', exchangeinfo: '的交易信息', tablabel1: '在线出售', tablabel2: '在线购买', col_symbol: '币种', col_paymode: '付款方式', col_num: '数量', col_price: '价格', col_created: '发布时间', col_operate: '操作', operatemsg: '请先进行实名认证', buyin: '买入', sellout: '卖出', }, tradecenter: { postad: '发布广告', exchange: 'GCC交易', buyin: '我要买入', sellout: '我要卖出', }, tradeinfo: { emaildone: '邮件已认证', emailundo: '邮件未认证', teldone: '手机号码已认证', telundo: '手机号码未认证', idcarddone: '身份证已认证', idcardundo: '身份证未认证', exchangetimes: '交易次数', price: '价格', num: '数量', paymethod: '付款方式', exchangelimitamount: '交易限额', location: '所在地', location_text: '中国', exchangeperiod: '交易期限', minute: '分钟', amounttip: '请输入金额', numtip: '请输入数量', remarktip: '告诉他您的要求', remarktitle: '备注信息', exchangetitle: '交易须知', exchange_tip1: '在您发起交易请求后,数字货币被锁定在托管中,受到平台保护。 如果您是卖家,发起交易请求后,您可通过充值并等待买家付款。买家在付款时限内进行付款。您在收到付款后应放行处于托管中的数字货币。', exchange_tip2: '交易前请阅读《平台网络服务条款》以及常见问题、交易指南等帮助文档。', exchange_tip3: '当心骗子!交易前请检查该用户收到的评价,并对新近创建的账户多加留意。', exchange_tip4: '请注意,四舍五入和价格的波动可能会影响最终成交的数字货币数额。您输入的固定数额决定最后数额,数字货币金额将在请求发布的同一时间由即时的汇率算出。', exchange_tip5: '托管服务保护网上交易的买卖双方。在发生争议的情况下,我们将评估所提供的所有信息,并将托管的数字货币放行给其合法所有者。', warning1: '最多输入2位小数', warning2: '下单金额为', warning3: '最多输入8位小数', warning4: '下单数量为', confirmbuyin: '确认买入', confirmsellout: '确认卖出', buyin: '买入', sellout: '卖出', warning5: '请按要求填写订单', }, publishad: { createad: '创建一个广告交易', msg1: '如果您经常进行交易,您可以创建自己的交易广告。如果您只是偶尔交易,我们建议您直接搜索', msg2: '创建一则交易广告是', msg3: '免费的', msg4: '若您想直接编辑已创建的广告,请查看', tradead: '交易广告', myad: '我的广告', iwant: '我想要', sellonline: '在线出售', buyonline: '在线购买', exchangecoin: '交易币种', country: '国家', currency: '货币', openfixedprice: '开启固定价格', open: '开启', close: '关闭', usetip: '启用后,您的币价不会随市场波动,价格不变。', premiseprice: '溢价', premisepricetip: '请设置您的溢价', fixedprice: '固定价格', fixedpricetip: '请输入您的交易价格', marketprice: '市场参考价格', marketpricetip: '溢价是指高于当前市场价格多少百分比进行', exchangeprice: '交易价格', formual: '计价公式', num: '数量', num_text1: '请输入您要', num_text2: '的数量', exchangeperiod: '交易期限', exchangeperiod_text1: '请输入您的交易期限', minute: '分钟', tip1: '可接受买方在多少时间内交易,请输入整数', tip2: '【提示】可前往个人中心绑定/增加支付方式', tip3: '请输入您的最小交易额', tip4: '请输入您的最大交易额', tip5: '可以内备注信息里填写您的特殊要求,例如:对买方的要求,在线时间等。', paymode: '付款方式', minlimit: '最小交易额', maxlimit: '最大交易额', remark: '备注信息', openautoreply: '开启自动回复', msg5: '启用后,用户通过此广告向您发起交易时,系统自动将您选择的自动回复用语发送给对方。', autoreply: '自动回复', autoreplytip: '在接收订单后,自动回复给买家的信息,例如:收款方式、收款账号等。', fundpwd: '资金密码', fundpwdtip: '请输入您的资金密码', submit: '提交', warning1: '请输入正确数字', warning2: '溢价值为0-20', warning3: '请输入您的最大交易额!', warning4: '请输入整数', warning5: '最大交易额必须大于最小交易额!', warning6: '最大交易额不能超过您的卖出总金额', warning7: '请输入您的最小交易额!', warning8: '最小交易额必须大于等于100!', warning9: '最小交易额必须小于最大交易额', sellout: '卖出', buyin: '买入', inputtip1: '请输入币种', inputtip2: '请输入正确选项', inputtip3: '溢价值为0-20,且不能为0', inputtip4: '请输入正确固定价格', inputtip5: '请输入正确数字,并且最大交易数量不超过100币', inputtip6: '请输入正确交易限期', inputtip7: '请选择交易方式', inputtip8: '请输入资金密码', zfb: '支付宝', wx: '微信', unionpay: '银联', submit_failure: '提交失败!', submit_success: '', submittip1: '请先进行实名等一系列认证', submittip2: '请先进行手机等一系列认证', submittip3: '请先进行资金密码等一系列认证', submittip4: '请至少绑定一种支付方式', }, index: { title: '优质广告推荐', exchangetimes: '交易次数', exchangeprice: '交易价格', exchangelimit: '交易限额', paymode: '付款方式', buy: '购买', sell: '卖出', viewmore: '查看更多', bot1: '安全可靠', bot1_tip: '超过10年金融风控经验团队全方为\n可定制的安全策略体系', bot2: '快速便捷', bot2_tip: '点对点的用户自由交易模式支持多\n种资金渠道的兑换方式', bot3: '币种全面', bot3_tip: '甄选主流数字资产交易币种满足多\n方面的多资产交易体验', ibuy: '我要买入', isell: '我要卖出', bottom1:"随时随地多平台开启交易", bottom2: "下载JINGUI Android APP或IOS APP移动客户端,看行情、秒 交易随心体验,您的交易之旅即将开始。", logoTitle:'全球领先的数字资产交易所', logoText1:'追赶', logoText2:'卓越', logoText3:'引领', more:'更多>>', } }, uc: { login: { noaccount: '没有账号?请点击注册', register: '注册', login: '登录', welcomelogin: '欢迎登录', usertip: '手机号', pwdtip: '密码', validatecodeload: '正在加载验证码', validatemsg: '请先完成验证', forget: '忘记密码?', loginvalidate: '请输入手机号', pwdvalidate1: '请输入密码', pwdvalidate2: '密码长度不能少于6位', success: '登录成功', }, forget: { hasaccount: '已有账号?请点击登录', login: '登录', sendcode: '发送验证码', newpwd: '请输入新密码', confirmpwd: '请再次确认密码', save: '保存', pwdvalidate1: '请输入确认密码', pwdvalidate2: '两次密码输入不一致!', resettelpwd: '重置手机密码', resetemailpwd: '重置邮箱密码', newpwdtip: '请输入新密码', pwdvalidate3: '密码长度不能少于6位', telno: '手机号', smscode: '短信验证码', teltip: '请输入手机号', smscodetip: '请输入短信验证码', email: '邮箱', emailcode: '邮箱验证码', emailtip: '请输入邮箱', emailcodetip: '请输入邮箱验证码', resetpwdsuccess: '重置密码成功', smswarn: '请注意查收短信', }, finance: { center: '财务中心', personalassets: '个人资产', billdetail: '资产流水', tradetail: '交易挖矿', paydividends: '持币分红', invitingmining: '邀请挖矿奖励', charge: '充币', pickup: '提币', money: { cointype: '币种名称', balance: '可用资产', frozen: '冻结资产', operate: '操作', charge: '充币', pickup: '提币', getaddress: '获取地址', resetsuccess: '获取成功', match: '配对', matchtip1: '可配对GCX的数量', matchtip2: '请输入配对数量', matcherr1: '请输入有效的数量!', matcherr2: '超出最大配对数量!', matchsuccess: '配对成功!', needreleased: "待释放资产" }, record: { start_end: '起止时间', to: '至', operatetype: '操作类型', search: '搜索', charge: '充值', pickup: '提现', transaccount: '转账', exchange: '币币交易', otcbuy: '法币买入', otcsell: '法币卖出', activityaward: '活动奖励', promotionaward: '推广奖励', dividend: '分红', vote: '投票', handrecharge: '人工充值', match: '配对', chargetime: '交易时间', type: '类型', fee: '手续费', shouldfee: '应付手续费', discountfee: '抵扣手续费', realfee: '实付手续费', symbol: '币种', num: '数量', status: '状态', finish: '已完成', }, paydividende: { money_holding: '持币分红已返还累计(ETH) : ', money_hold: '持币分红待返还累计(ETH) : ', paydividends: '持币分红(ETH)', account_date: '到帐时间', datehodld: '持币日期', start_end: '起止时间', to: '至', operatetype: '操作类型', search: '搜索', charge: '充值', pickup: '提现', transaccount: '转账', exchange: '币币交易', otcbuy: '法币买入', otcsell: '法币卖出', activityaward: '活动奖励', promotionaward: '推广奖励', dividend: '分红', vote: '投票', handrecharge: '人工充值', match: '配对', chargetime: '交易时间', type: '类型', fee: '手续费', symbol: '币种', num: '数量', status: '状态', finish: '已完成', }, trade: { accumulative_return: '累计挖矿(BHB) : ', accumulat_return: '待挖矿(BHB) : ', start_end: '起止时间', account_date: '到帐时间', to: '至', operatetype: '操作类型', search: '搜索', charge: '充值', pickup: '提现', transaccount: '转账', exchange: '币币交易', otcbuy: '法币买入', otcsell: '法币卖出', activityaward: '活动奖励', promotionaward: '推广奖励', dividend: '分红', vote: '投票', handrecharge: '人工充值', match: '配对', chargetime: '订单生成时间', type: '类型', fee: '挖矿手续费返还(BHB)', symbol: '币种', num: '数量', status: '状态', finish: '已完成', transactionTime: '交易时间', symbol: '交易对', direction: '交易方向', price: '价格', entrustment: '委托量', havedeal: '已成交', poundageAmount: '手续费', exchangeOrderId: "订单ID", mineAmount: "挖币数量 (BHB)" }, inviting: { accumulative_return: '邀请挖矿奖励已返还累计(BHB) : ', accumulat_return: '邀请挖矿奖励待返还累计(BHB) : ', start_end: '起止时间', account_date: '到帐时间', to: '至', operatetype: '操作类型', search: '搜索', charge: '充值', pickup: '提现', transaccount: '转账', exchange: '币币交易', otcbuy: '法币买入', otcsell: '法币卖出', activityaward: '活动奖励', promotionaward: '推广奖励', dividend: '分红', vote: '投票', handrecharge: '人工充值', match: '配对', chargetime: '订单生成时间', type: '类型', fee: '挖矿手续费返还(BHB)', symbol: '币种', num: '数量', status: '状态', finish: '已完成', refereename: '被推荐人姓名', referetel: '被推荐人手机号', invitingawards: '邀请挖矿奖励(BHB)', refere: '被推荐人', refereinput: '请输入姓名/手机号' }, recharge: { recharge: '充币', symbol: '币种', address: '充币地址', copy: '复制', qrcode: '二维码', msg1: '请勿向上述地址充值任何非币种资产,否则资产将不可找回。', msg2: '您充值至上述地址后,需要整个网络节点的确认,2次网络确认后到账,6次网络确认后可提币。', msg3: '最小充值金额:0.01币,小于最小金额的充值将不会上账。', msg4: '您的充值地址不会经常改变,可以重复充值;如有更改,我们会尽量通过网站公告或邮件通知您。', msg5: '请务必确认电脑及浏览器安全,防止信息被篡改或泄露。', record: '充值记录', copysuccess: '复制成功!', copyerr: '复制失败!请手动复制', time: '到账时间', amount: '充值数量' }, withdraw: { pickup: '提币', addressmanager: '提币地址管理', symbol: '币种', address: '提币地址', num: '数量', avabalance: '可用余额', msg1: '提币数量低于', msg2: '时自动到账,否则需要人工审核', increase: '提升额度', tip1: '最多输入', tip11: '位小数,最小值为', tip2: '最大值为', numtip1: '输入提币数量', fee: '手续费', range: '范围', arriamount: '到账数量', msg3: '最小提币数量为', msg4: '币', msg5: '为保障资金安全,当您账户安全策略变更、密码修改、使用新地址提币,我们会对提币进行人工审核,请耐心等待工作人员电话或邮件联系', msg6: '请务必确认电脑及浏览器安全,防止信息被篡改或泄露。', record: '提现记录', symboltip: '请选择币种', addresstip: '请填入地址', numtip2: '请填写正确提币数量,最小值为', numtip3: '提币数量不得小于手续费', feetip1: '手续费最小值为', feetip2: '最大值为', time: '提现时间', status: '状态', status_1: '审核中', status_2: '转账中', status_3: '失败', status_4: '成功', remark: '备注', add: '添加', addresslist: '地址列表', safevalidate: '安全验证', telno: '手机号', smscode: '手机验证码', second: '秒', clickget: '点击获取', email: '邮箱', emailcode: '邮箱验证码', save: '保 存', delete: '删除', telerr: '手机号不正确', emailerr: '邮箱不正确', codeerr: '验证码不正确', remarktip: '请输入备注', savemsg1: '保存失败!', savemsg2: '保存成功!', operate: '操作', fundpwdtip: '请输入资金密码', click: '点击', filtrate: '可筛选' } }, member: { securitycenter: '安全中心', securitysetting: '安全设置', accountsetting: '账户设置' }, order: { ordercenter: '订单中心', myorder: '我的订单', myad: '我的广告', }, regist: { hasaccount: '已有账号?请点击登录', login: '登录', username: '用户名', recommand: '推荐码', country: '国家', smscode: '短信验证码', sendcode: '发送验证码', pwd: '登录密码', confrimpwd: '确认密码', agreement: '我已阅读并同意', userprotocol: '用户协议', regist: '注册', teltip: '请输入手机号', telerr: '手机号码格式不正确,请重新输入', emailtip: '请输入邮箱', emailerr: '邮箱格式不正确,请重新输入', confirmpwdtip: '请输入确认密码', confirmpwderr: '两次密码输入不一致!', telregist: '手机号注册', emailregist: '邮箱注册', usernametip: '请输入用户名', usernamemsg: '用户名长度不能少于3位,多于15位', recommandtip: '请输入推荐码', recommandmsg: '推荐手机号码格式不正确,请重新输入', countrytip: '请选择国家', smscodetip: '请输入短信验证码', pwdtip: '请输入登录密码', pwdmsg: '密码长度不能少于6位', telno: '手机号', email: '邮箱', agreementtip: '请点击同意', modaltitle: '请校验', }, safe: { safelevel_low: '安全等级:低', safelevel_high: '安全等级:高', safelevel_medium: '安全等级:中', nickname: '昵称', bind: '绑定', binded: '已绑定', binding: '审核中', binderr: '失败', bindretry: '重试', verified: '实名认证', verifiedtip: '为保障您的账户安全,请完成实名认证后方可交易操作!', realname: '真实姓名', idcard: '身份证号', upload: '点击上传', upload_positive: '上传身份证正面照', upload_negative: '上传身份证反面照', upload_hand: '上传手持身份证照', save: '保 存', reset: '重置', email: '邮箱', bindemail: '绑定邮箱', loginpwd: '登录密码', emailcode: '邮箱验证码', clickget: '点击获取', second: '秒', phone: '手机', bindphone: '绑定手机', phonecode: '手机验证码', logintip: '登录平台时使用', edit: '修改', oldpwd: '原登录密码', newpwd: '新登录密码', confirmnewpwd: '确认新密码', fundpwd: '资金密码', fundtip: '账户资金变动时,需先验证资金密码', set: '设置', confirmpwd: '确认密码', oldfundpwd: '原资金密码', newfundpwd: '新资金密码', newpwdmsg1: '请输入不小于6位新登录密码', newpwdmsg2: '新登录密码不一致', pwdmsg1: '请输入不小于6位密码', pwdmsg2: '密码不一致', emailtip: '请输入邮箱号', codetip: '请输入验证码', telnotip: '请输入手机号', oldpwdtip: '请输入原密码', realnametip: '请输入真实姓名', idcardtip: '请输入身份证号码', bindphonetip: '请先绑定手机!', resetfundpwd: '重置资金密码', upload_positivetip: '请上传身份证正面照', upload_negativetip: '请上传身份证反面照', upload_handtip: '请上传手持身份证照', save_success: '保存成功!', save_failure: '保存失败!', }, account: { pagetitle: '绑定实名帐号', pagetip: '请设置您的收款方式,请务必使用本人的实名账号', backcardno: '银行卡账号', backcardtip: '个人银行卡信息未绑定', modify: '修改', bind: '绑定', name: '姓 名', bankaccount: '开户银行', bankbranch: '开户支行', bankno: '银行卡号', confirmbankno: '确认卡号', fundpwd: '资金密码', save: '保 存', zfbaccount: '支付宝账号', zfbaccounttip: '个人支付宝账户未绑定', wxaccount: '微信账号', wxaccounttip: '个人微信账户未绑定', banknomsg1: '请输入正确银行卡号', banknomsg2: '两次输入的银行卡号不一致!', verifiedmsg: '请先进行实名认证', bankaccountmsg: '请选择开户银行', bankbranchmsg: '请输入开户支行', banknomsg: '请输入正确的银行卡号', fundpwdmsg1: '请输入正确的资金密码', fundpwdmsg2: '密码不得少于6个字符', zfbaccountmsg: '请输入支付宝账号', wxaccountmsg: '请输入微信账号', save_success: '保存成功!', save_failure: '保存失败!', imgtip: '请上传您的收款码', }, otcorder: { unpaid: '未付款', paided: '已付款', finished: '已完成', canceled: '已取消', appealing: '申诉中', searchtip: '输入订单编号开始搜索', orderno: '订单号', created: '创建时间', symbol: '交易币种', type: '交易类型', type_sell: '卖出', type_buy: '买入', tradename: '交易对象', amount: '数量', money: '金额', fee: '手续费', }, identity: { certified: "已认证", placeholder: "请填写取消原因", apply: '申请成为商家', become: '成为JINGUI认证商家, 享更多交易特权', zhusnhu: "商家享有专属广告展位,增加交易成功率", tijiaoziliao: "提交商家认证资料", place: "请您将准备好的商家认证资料上传至平台并提交", tijiao: "您的商家认证审核已提交", tijiaosuc: "恭喜!您的商家认证审核已通过", tijiaofail: "抱歉!您的商家认证审核未通过", zhuxiaotijiao: "您的商家注销申请已提交", shenhefail: "您的商家注销申请审核未通过", shenhesuc: "您的商家注销申请审核已通过", shangjiazhuxiao: "商家注销", shenheshibai: "审核失败", shenagain: "重新审核", sheqinggain: "重新申请", reason: "原因", shenqingtuibao: "申请退保", getquan: "您获得以下权限", read: "我已阅读并同意", lijishenqing: "立即申请", tips: "提示", wufachexiao: "您正在进行商家注销操作,确认提交申请操作后,将无法撤销。", suredo: "是否确认执行此操作?", shuzizichan: "数字资产交易证明", gerenzichan: "个人数字资产证明", second: { line: "如何申请成为商家?", step1: "第一步:按要求准备商家申请资料", step1c1: "准备如下申请资料:", step1c2: "手机号、微信号、QQ号、个人数字资产证明(图片)、数字资产交易证明(图片)", step2: "第二步:提交申请", step2c: "完成需要填写和上传的商家认证审核资料,点击提交审核。", step3: "第三步:资料审核", stepc: "我们将在3-5个工作日内对您的商家申请资料进行审核,请随时关注审核状态,可在提交页面查看。审核通过后,您即可在法币交易区发布广告。", agree: "同意冻结", agreec: "作为商家保证金", shenqingchngweishangjia: "申请成为商家", }, yuanyin: "原因", tijiaoshenqing: "提交申请", bizhong: "保证金币种", shuliang: "保证金数量", chosen: "选择币种", seat: '专属展位', service: '一对一服务', lowfee: '更低手续费', phone: '手机', balance: '个人资产情况', cardphoto: '身份证正反面照片', wx: '微信', exchange: '是否从事过数字资产的场外交易', handphoto: '用户手持身份证照片', qq: 'QQ', ploy: '是否有相应的风控策略', agreement: '《认证商家协议》', applyfor: '确认申请', sendcode: '发送验证码', confirm: '确定', prepare: '准备资料', review: '提交审核', result: "等待结果", passed: '审核通过', approve: '请同意认证商家协议', emailtip1: '请将如下材料用邮件发送至', emailtip2: '我们将尽快对您的申请进行审核。', }, extension: { title1: '推广链接', title2: '推广好友', title3: '我的佣金', linkdesc: '以下网址是您对外界进行推广的地址,您可以通过朋友、QQ、微信、微博、博客、论坛或者自己的网站进行推广,所有通过该地址访问过来的人,注册后就都属于您的用户,而当这些用户在本站提交策略时,您就可以赚取佣金了,详细的推广情况可到访问记录里查看。', linktitle: '您的推广链接', copy: '复制', copy_msg1: '复制成功!', copy_msg2: '复制失败!请手动复制', username: '用户名', currrecharge: '当前交易', userlevel: '推荐级别', createdtime: '注册时间', currcommission: '当前佣金', managerfee: '管理费', yuan: '元', symbol: '币种', amount: '金额', remark: '备注', amounttime: '发放时间', } }, cms: { noticecenter: '公告中心', newshelp: '新手帮助', appdownload: 'APP下载', onlineservice: '在线客服', faq: '常见问题', notice: '公告', servicecenter: '客服中心', about: '关于', joinus: '加入我们', aboutus: '关于我们', exchangerule: '交易规则', useprotocol: '使用协议', feenote: '资费说明', merchantprocotol: '商家协议', }, description: { // message1: 'SSL、动态身份验证等银行级别安全技术,\n保障交易安全;支持多种数字货币交易', // message2: '严格的项目准入门槛,确保平台用户利益;\n100%保证金,钱包冷热隔离,确保用户资金安全', // message3: 'JINGUI数字资产交易平台支持每秒1000笔交易,给用户带来酣畅淋漓\n的交易体验', title1: '金融级安全保障', title2: '快便捷的产品体验捷', title3: '全球优质快捷', title4:'24小时在线服务', message1: '多级防火墙,多重签名,冷热隔离钱包,核心 步骤采用断网方式处理,保障用户资产安全。', message2: '丰富的开发经验让我们的产品功能、访问速度、 高并发交易能力在业内遥遥领先。', message3: '充值提现快速到账T+O交易一键成交', message4: '成熟的客户服务和技术支持体系快速响应用户需求, 解决运营问题,让您更专注于交易。' }, footer: { gsmc: '国际数字加密资产交易平台', ul1:'条款说明', ul1li1:'用户协议', ul1li2:'条款说明', ul2:'工具', ul2li1:'API文档', ul2li2:'操作手册', ul3:'关于', ul3li1:'关于jingui', ul3li2:'项目动态', ul3li3:'行业资讯', ul3li4:'官方公告', ul3li5:'上币申请', ul4:'联系我们', ul4li1:'客服邮箱', ul4li2:'媒体邮箱', ul4li3:'社群邮箱', ul4li5:'国际商务合作邮箱', ul4li6:'上币申请微信', notice:"风险提示:由于数字货币交易风险较大,易受外界、币种等因素影响,价格波动较大,我们强烈建议您在自身能承受的风险范围内参与数字货币交易!投资有风险,入市需谨慎。", }, financeNav: { wdzc: '我的资产' }, index: { circulation: "BHB 安全与发展基金流通量", hourEth: '今日待分配收入累计折合', yesterdayEth: '昨日分配收入累计折合', yesterday: '昨日挖矿产出', bhbTotal: "BHB 总流通量", bhbSecond: "BHB二级市场流通量", checkMineprinciple: "查看挖矿原理", checkFlowVolum: '检查流通量说明', checkLockPosition: '查看锁仓情况', BHBregister: "JINGUI账户注册", tibi: "提币到账时间及限额", line_plane: "BHB上线计划、流通量及手续费返还公告", fenpeijizhi: '关于JINGUI收入分配机制的说明', jiangli_jihua: "邀请挖矿奖励计划", friend_fanhuan: "邀请好友、赚取额外手续费返还" }, plate: { title: "平台收入分配方案 (BHB 持有者权益)", content1: "正如白皮书所描述的,JINGUI会拿出平台的80% (扣除税费后) 的收入分配给JINGUI持有者,20%的收入用来支持平台的研发及运营。", content2: "收入分配以日为一个分配周期,2018年6月6日为首个分配日。之后的每一天,会将前一天累积的所有待分配收入,一次性的按比例分给BHB持有者", content3: "(注:1.此处的BHB仅指已经释放的/可流通的BHB,具体请参见【", content3_1: '关于BHB流通量/参与收入分配比例的说明', content3_2: "2.每小时(整点)快照并计算一次,收入分配执行为每天一次)。", hourFenpei: "今日分配收入折合", hourTotal: '今日平台总收入折合', xiangqing: '今日收入分配详情', yesterdaytit: "昨日天分配收入折合", yesterdaytotal: "昨日平台总收入折合", yesterdayxiangqing: "昨日收入分配详情", /*yesterday:{ total:"平台总手续费", allocated:"待分配收入", }*/ }, feereturn: { ruletitle: "返还规则", rulecontent: "白皮书里已经对BHB的分配比例有详细的说明。51%比例的BHB通过“交易即挖矿”的方式逐步回馈给交易用户。一旦51%的BHB全部回馈完成,“挖矿”即自动终止。", recordtitle: '返还记录', recordcontent: '每日(UTC+8,以下同)都会将前一日的用户所产生交易手续费,100%折算成BHB返还给用户,折算价格按前一交易日BHB的均价(均价计算方式为总成交金额/总成交量)。我们将于每日上午11点,开始发放前一日交易手续费折合BHB的返还。', /*time:"日期", todaycharge:"当日JINGUI均价(ETH)", totalChange:'当日总手续费折合(ETH)', returnCharge:"当日挖矿手续费返还(BHB)", todayChargeReturn:"当日挖矿收入倍增计划返还(BHB)"*/ }, homeadd:{ introduce:{ title:'服务全球用户的数字资产交易平台', p1:'JINGUI交易平台是全球最早成立的交易平台之一,注册用户遍布全球100多个国家和地区。目前已经成立:俄罗斯站、欧洲站、东南亚、巴西、北美站、日韩等多个分站,全球化的商务团队和服务体系,为用户提供安全便捷、优质贴心。', p2:'JINGUI的业务板块包括:JINGUI交易平台,JINGUIATM、JINGUIPOS等数字货币领域相关的金融业务。' }, mapbox:{ title:'BOBIT全球联盟分站体系', p:'未来我们将在全球各主要国家或地区开设更多的分站,为用户提供更优质的服务', city1:'俄罗斯站', city2:'欧洲站', city3:'日韩站', city4:'东南亚站', city5:'非洲站', city6:'巴西站', city7:'北美站', city8:'澳洲站', }, pricebox:{ today:'今日全站交易量', btcprice1:'BTC市场价', ethprice1:'ETH市场价', }, welcome:{ title:'欢迎加入JINGUI交易平台社区', p:'JINGUI交易平台用户遍布全球100多个国家地区,与全球爱好者分享交易经验,捕捉市场趋势。', }, cooperation:{ title:"合作伙伴", }, }, ethusdt:{ remaining: "剩余", grab: "已抢完", buySuccess:"购买成功", ethexchange:"1ETH兑换价", bobotco:"jingui交易所生态通证", plan:"ZFL百日疯抢计划", currentPrice:"实时市场价", todayPrice:"今日兑换价", exchangeTop: "每天限额10ETH/每天15:00准时开抢", placehold: "输入您要的抢购金额(ETH)", buy: "购买", notStart: "未开始", notice: "(每天每人限购10ETH抢购价递增,越早购买越便宜)", rule1: "一、zfl抢购规则:", rule11: "1、抢购价:初始抢购价1ETH=10000ZFL,价格每天递增10ZFL", rule12:"2、抢购周期:100天", rule13:"3、每天限购总量:10 ETH等值ZFL", rule14:"4、每人每天限购:10 ETH等值ZFL", rule15:"5、抢购ZFL均为锁仓状态,并从抢购第二天起开启线性解锁,每天自动解锁3‰(约333天释放完),可加速解锁,最高5倍加速:每天解锁15‰(约66天释放完)。", rule2: "二、ZFL加速解锁规则:", rule21: "1、所有抢购ZFL的默认释放速度是每天解锁持有量的3‰。二级市场购买的ZFL不锁仓。", rule22:"2、当一级有效邀请人数达到6人,次日自动激活二倍加速解锁,解锁速度每天6‰。", rule23:"3、当一级有效邀请人数达到6人,二级有效邀请人数达12人,次日自动激活三倍加速解锁,解锁速度每天9‰。", rule24:"4、当一级有效邀请人数达到8人,二级有效邀请人数达20人,次日自动激活四倍加速解锁,解锁速度每天12‰。", rule25:"5、当一级有效邀请人数达到12人,二级有效邀请人数达56人,次日自动激活五倍加速解锁,解锁速度每天15‰。", rule26: "有效邀请指:账号充值转入金额大于或等于10 ETH为有效邀请。", rule3: "三、ZFL抢购返佣规则:", rule31: "1、按照受邀人抢购ZFL金额的对应比例进行返佣", rule32:"一级邀请返佣10%(含5%ETH+5%ZFL锁仓返佣),", rule33:"二级邀请返佣5%(含2.5%ETH+2.5%ZFL锁仓返佣)", rule34:"2、返佣的ETH 不锁仓,返佣的ZFL实行锁仓,解锁条件与抢购得到的ZFL一致,同样享有加速权利。", rule35:"3、每次抢购成功的邀请返佣在次日进行结算", rule36: "举例:一级受邀人用1,000 ETH抢购了10,000 ZFL(抢购价为0.1ETH),二级受邀人用600 ETH抢购了3,000 ZFL(抢购价为0.2ETH),则邀请人会获得", rule37: "一级返佣:1,000 x 5%=50 ETH(直接返还),10,000 x 5% = 500ZFL(每天解锁3‰)", rule38: "二级返佣:600 x 2.5% = 15 ETH(直接返还),3,000 x 2.5% = 75 ZFL(每天解锁3‰)", rule39: "共计:75 ETH 以及 575 ZFL", service: "撩下客服小姐姐", title: "jingui交易平台对本活动拥有最终解释权,活动规则变更一经公布即刻生效。" }, add: { announcement:'公告', help:'帮助中心', launchpadtitle: "区块链资产发行平台", all:'所有', ing:'正在进行', end:'已经结束', newest:'最新价', hour24:'24h涨跌', highest:'24h最高价', lowest:'24h最低价', transaction:'24h成交量', please:'请先', select:"自选", notdata:"暂无数据", more:"查看更多>>", transactionPair:"交易对", type:"类型", amount:"成交金额", personal:"个人中心", accountManagement:"账户管理", assetManagement:"资产管理", coinManagement:"币币管理", currentCommission:"当前委托", historicalCommission:"历史委托", launchpadManagement:"法币管理", myPromotion:"我的推广", sponsoredUrl:"推广链接", memberDetails:"会员详情", name:"昵称", tel:"手机号码", rechargeETH:"充值ETH", rechargeBTC:"充值BTC", rechargeUSDT:"充值USDT", tradingPlatform:"新上线交易平台", mainingTitle:"我们赋予您在一个无界的支付平台以您自 己的方式使用您自己的钱的权利。随时随 地买入、储存和兑换您的数字或传统货币...", totall:"公募总量:", startTime:"开始日期:", endTime:"结束日期:", notAccount:"没有账号", goregister:"立即注册", aboutUs:"关于我们", aboutText:"JINGUI交易所,是一家注册成立于香港的区块链数字资产交易所,主要面向全球用户提供比特币、以太坊、莱特币、狗狗币等数字资产的撮合交易服务,由JINGUI经营。JINGUI交易所是由全球顶尖技术团队和专业的数字资产爱好者创办,核心团队来自微软、腾讯、阿里等知名企业,旨在为用户提供更加安全、便捷、优质透明的区块链资产交易和兑换服务,聚合全球优质区块链资产,致力于打造世界级的区块链资产交易平台", read:" 阅读", getAmount:"到账数量", dynamic_1:"TRX即将上线 BTC、ETH、USDT交易区", dynamic_2:"NIOX上线NSD交易区公告", dynamic_3:"PROT上线BTC交易区公告", dynamic_4:"RPZX上线BTC交易区公告", dynamic_5:"Nerthus (NTS)上线USDT交易区公告", dynamic_6:"关于RET提现的公告", dynamic_7:"Dentacoin(DCN)上线USDT交易区公告", dynamic_8:"恒星币Stellar(XLM)上线多比BTC,USDT交易区公告", news_1: "美国国会听证会:用区块链技术改变世界", news_2:"OCTOWILL 介绍", news_3:"JINGUI平台币-DOB介绍", news_4:"韩国The Wing Corp 与jingui交易平台战略合作成功签署,多比进军海外市场扬帆起航", news_5:"多比和知道创宇达成战略合作为多比生态安全保驾护航", news_6:"与买房相比,英国21%的千喜一代更愿意买币", news_7:"希尔顿家族钟情于加密货币,欲以比特币标价出售3800万美元豪宅", news_8:"John McAfee以吃鞋为賭注:最后一枚比特币价值五千亿美元", add_1:"平台公告", add_2:"限价", add_3:"市价", add_4:"买入", add_5:"买出", add_6:"搜索", add_7:"清空条件", add_8:"请选择搜索日期范围", add_9:"充币地址二维码", add_10:"推广二维码", add_11:"审核未通过", add_12:"请重试", add_13:"忘记密码?", add_14:"提示", add_15:"帮助中心", add_16:"此组别内的文章", add_17:"帮助中心", add_18:"请先登录", add_19:"实名认证", add_20:"请先", add_21:"订单详情", add_22:"忘记密码", add_23:"推广二维码", add_24:'邀请码', add_25:"推广链接:", add_26:"公告列表", add_27:"上一篇", add_28:"下一篇", add_29:"JINGUI 全球领先区块链|虚拟币|数字资产交易平台", start_end_tiime:"起止时间:", currencyType: "币种:", jiaoyidui: "交易对", type:"类型", direction:"方向:", endAmount:"成交金额", select_input:"请选择", otcMain_1: "市场一口价", otcMain_2:"根据市场价格实时波动", otcMain_3:"完全免手续费", otcMain_4:"用户所见即所得,买卖价格外,无需任何平台手续费", otcMain_6:"即时成交", otcMain_7:"引入平台服务商家,智能匹配,成交订单,无须等待撮合", otcMain_8:"平台担保", otcMain_9:"平台认证商家,安全有保障,24小时客服为交易保驾护航", otcMain_10:"法币交易", otcMain_11:"便捷、安全、快速买卖数字货币", otcMain_12:"成为商家", }, zfl:{ title:"首次公开发行", page1title:"我通过我自己的方式付款。我通过 ZFL 付款。", page1text:"我们赋予您在一个无界的支付平台以您自己的方式使用您自己的钱的权利。随时随地买入、储存和兑换您的数字或传统货币。", page2title:"一卡管所有", page2text:"您的新一代多币旅行卡. ZFL Visa 卡在销售终端可自动转换超过 20 种数字货币和传统货币,让您在现实生活中无缝消费您的加密货币和多种传统货币,只要那里支持 Visa 卡。您的银行卡能做到吗?", zflLeft1:"代币名称:", zflLeft2:"总额:", zflLeft3:"开始时间:", zflLeft4:"结束时间:", zflLeft5:"上市日期:", zflLeft6:"可接受的货币:", zflRight1:"ZFL", zflRight2:"300,000,000 ZFL", zflRight3:"2019年9月24日(GMT + 8)", zflRight4:"2019年12月23日(GMT + 8)", zflRight5:"2019年12月24日(GMT + 8)", invite:"邀请码:", url:"推广链接:" }, apiDocument:{ menu_1 :"授权", menu_11:"API授权", menu_2 :"交易API", menu_21:"委托下单", menu_22:"撤销下单", menu_23:"全部委托", menu_24:"当前委托", menu_25:"交易规则", menu_26:"交易市场", menu_3 :"行情API", menu_31:"最新行情", menu_32:"市场挂单", menu_33:"成交记录", menu_34:"K线", menu_4 :"用户API", menu_41:"K线", p_1:"JINGUI交易平台开放API", p_2:"应用程序可通过调用JINGUI开放平台提供的API获取到资产、交易等数据,因为涉及数据隐私,所以在使用前必须获得JINGUI的", p_3:"授权", p_4:"(登陆后获取),才可以调用API", p_5:"公共参数", p_6:"请求地址", p_7:"环境", p_8:"正式环境", p_9:"参数", p_10:"是否必填", p_11:"描述", p_12:"示例值", p_13:"是", p_14:"固定为", p_15:"否", p_16:"zh-*:中文,en-*:英文,默认(中文)", p_17:"公共请求参数", p_18:"类型", p_19:"最大长度", p_20:"API访问密匙", p_21:"Unix时间戳", p_22:"接口版本,固定为1.0", p_23:"请求参数的签名串,详见", p_24:"签名", p_25:"公共响应参数", p_26:"参数类型", p_27:"0失败1成功2错误", p_28:"返回状态描述", p_29:"操作成功", p_30:"请求应答数据", p_31:"请求", p_32:"请求方法", p_33:"请求参数", p_34:"需要传公共参数", p_35:"响应参数", p_36:"用户绑定手机号", p_37:"用户资产,btc_over为btc可用额, btc_lock为btc冻结额,其它币类推", p_38:"请求示例", p_39:"HTTP请求", p_40:"响应示例", p_41:"JSON示例值", p_42:"签名算法", p_43:"(以下是完整示例)", p_44:"步骤1、将参数的key按ascii升序排序 例", p_45:"步骤2、拼装成字符串,并进行URL-encode(否则特殊字符将导致签名不通过),得到queryString 例:", p_46:"步骤3、將secret key(示例值:fe01ce2a7fbac8fafaed7c982a04e229)与queryString 用HMAC-SHA1算法加密得到签名字符串, 例:", }, }
import * as echarts from 'echarts'; import $ from 'jquery'; class xChart { PieChart(options){ var defaultOption={ conId:'', //内容id radius:'60%', roseType:'radius', center:['50%','50%'], name:'', showLegend:false, //是否显示图例 legendArray:[], // 图例数据 name value (percent) legendRight:15, //图例位置 itemWidth:10, itemHeight:10, fontSize:18, itemGap:20, showLabel:false, //显示标签 showLabelLine:false, // 标签线 showLabelPer:false, colorArray:['#EF7663', '#1AA7B3', '#F968A9', '#F968A9', '#804FCD', '#FFB55E', '#2247B2'], dataArray:[], //数据 fn:function(){} }; options = $.extend(false,defaultOption,options); //获取数据 var legendName=[]; var labelPercent = []; var legendValue = null; for(var i=0;i<options.dataArray.length;i++){ legendName.push(options.dataArray[i].name); labelPercent.push(options.dataArray[i].percent); } var option={ tooltip : { formatter:function(params){ var index = params.dataIndex; var per = labelPercent[index]; if(per) { return params.name + ":" + params.value + " " + "(" + per + "%)" }else{ return params.name + ":" + params.value } } }, legend: { show:options.showLegend, type: 'scroll', orient: 'vertical', top:'middle', itemGap:10, right: options.legendRight, itemWidth:options.itemWidth, itemHeight:options.itemHeight, textStyle:{ color:'rgba(255,255,255,1)', fontSize:options.fontSize }, formatter: function (name) { for(var i=0;i<options.dataArray.length;i++){ var obj=options.dataArray[i]; if(name == obj.name){ legendValue = obj.value; } } return name +' '+ legendValue; }, data:legendName, }, color:options.colorArray, series : [ { name:options.name, type:'pie', center:options.center, radius :options.radius, roseType:options.roseType, clockwise:false, label: { normal: { show:options.showLabel, fontSize:options.fontSize, color:'rgba(255,255,255,0.75)', formatter:function(params){ if(options.showLabelPer){ return params.name + ':' + params.percent + '%' }else{ return params.name } } }, }, labelLine: { normal: { show: options.showLabelLine, length:8 } }, itemStyle:{ emphasis:{ color:'#80fbff' } }, data:options.dataArray } ] }; var dom = null; if(typeof options.conId === 'string'){ dom = document.getElementById(options.conId); }else{ dom = $(options.conId)[0]; } var myChart = echarts.init(dom);// 图表初始化的地方,在页面中要有一个地方来显示图表 myChart.setOption(option); //显示图形 myChart.on('click',options.fn) } } const charts = new xChart(); export default charts
/** * 共建和谐控制层 */ Ext.define('eapp.controller.Volunteer', { extend:'Ext.app.Controller', config: { refs: { mainview: 'mainview', volunteerpageview:'volunteerpageview', addideaView:'addideaView', applyvolunteerview:'applyvolunteerview', applyvolunteertowview:'applyvolunteertowviewq', shequwanggename:{selector: 'volunteerpageview formpanel fieldset labelEx[name=shequwanggename]'}, shenqinggezhangname:{selector: 'volunteerpageview formpanel fieldset labelEx[name=shenqinggezhangname]'}, wodewanggename:{selector: 'volunteerpageview formpanel fieldset labelEx[name=wodewanggename]'}, tijiaoyijianname:{selector: 'volunteerpageview formpanel fieldset labelEx[name=tijiaoyijianname]'}, gezhagnfengcainame:{selector: 'volunteerpageview formpanel fieldset labelEx[name=gezhagnfengcainame]'}, gezhangtoupiaoname:{selector: 'volunteerpageview formpanel fieldset labelEx[name=gezhangtoupiaoname]'}, nextbuttonname:{selector: 'applyvolunteerview formpanel button[name=nextbuttonname]'}, addsublmitname:{selector: 'applyvolunteertowview formpanel button[name=addsublmitname]'}, }, control: { shequwanggename: { tap:'OnShequwanggenameTap', }, shenqinggezhangname: { tap:'OnShenqinggezhangnameTap', }, wodewanggename: { tap:'OnWodewanggenameTap', }, tijiaoyijianname: { tap:'OnTijiaoyijiannameTap', }, gezhagnfengcainame: { tap:'OnGezhagnfengcainameTap', }, gezhangtoupiaoname: { tap:'OnGezhangtoupiaonameTap', }, nextbuttonname: { tap:'OnNextbuttonnameTap' }, addsublmitname: { tap:'OnAddsublmitnameTap', } } }, /** * 提交格长申请信息 */ OnAddsublmitnameTap:function() { var me = this; var applyvolunteertowview = me.getApplyvolunteertowview(); // 网格编号 var number = Ext.ComponentQuery.query('#nonumberid',applyvolunteertowview)[0].getValue(); // 意见内容 var context = Ext.ComponentQuery.query('#remarkContentid',applyvolunteertowview)[0].getValue(); var user = eapp.util.GlobalData.getCurrentUser(); var userid = user.get('userid'); Ext.Viewport.setMasked({ xtype: 'loadmask', message: '请稍候...'}); var volunteerServiece = Ext.create('eapp.business.VolunteerService'); volunteerServiece.addVolunteer(userid,number,context, { success:function(jsonData) { if(jsonData == 'OK') { eapp.view.Dialogs.showAlert('智慧潘家园','申请成功!~'); }else { eapp.view.Dialogs.showAlert('智慧潘家园','申请失败!~'); } Ext.Viewport.setMasked(false); }, failure:function(message) { console.log(message); Ext.Viewport.setMasked(false); } }); }, /** * 下一步 */ OnNextbuttonnameTap:function() { var me = this; var applyvolunteerview = me.getApplyvolunteerview(); if(applyvolunteerview == null || applyvolunteerview == 'undefined') { applyvolunteerview = Ext.create('eapp.view.gongjianhexie.ApplyVolunteer'); } var checkboxs = Ext.ComponentQuery.query('#checkboxs',applyvolunteerview)[0]; var labels = ''; for(var i = 0;i<checkboxs.getItems().length-1;i++) { if(checkboxs.getItems().items[i+1].getChecked()) { labels += checkboxs.getItems().items[i+1].getLabel()+','; } } if(labels == "" || labels.length <= 0) { eapp.view.Dialogs.showAlert('智慧潘家园','请选择网格编号!~'); return; } var applyvolunteertowview = me.getApplyvolunteertowview(); if(applyvolunteertowview == null || applyvolunteertowview == '') { applyvolunteertowview = Ext.create('eapp.view.gongjianhexie.ApplyVolunteerTow'); } Ext.ComponentQuery.query('#nonumberid', applyvolunteertowview)[0].setValue(labels); me.getMainview().push(applyvolunteertowview); var len = eapp.app.pageStack.length; if(eapp.app.pageStack[len-1] != 'applyvolunteertowview') { eapp.app.pageStack.push('applyvolunteertowview'); } }, /** * 社区网格 */ OnShequwanggenameTap:function() { alert(0); }, /** * 申请格长 */ OnShenqinggezhangnameTap:function() { var me = this; var applyvolunteerview = me.getApplyvolunteerview(); if(applyvolunteerview == null || applyvolunteerview == 'undefined') { applyvolunteerview = Ext.create('eapp.view.gongjianhexie.ApplyVolunteer'); } applyvolunteerview.init(); me.getMainview().push(applyvolunteerview); var len = eapp.app.pageStack.length; if(eapp.app.pageStack[len-1] != 'applyvolunteerview') { eapp.app.pageStack.push('applyvolunteerview'); } }, /** * 我的网格 */ OnWodewanggenameTap:function() { alert('我的网格'); }, /** * 提交建议 */ OnTijiaoyijiannameTap:function() { var me = this; var addideaView = me.getAddideaView(); if(addideaView == null || addideaView == 'undefined') { addideaView = Ext.create('eapp.view.gongjianhexie.AddIdea'); } me.getMainview().push(addideaView); var len = eapp.app.pageStack.length; if(eapp.app.pageStack[len-1] != 'addideaview') { eapp.app.pageStack.push('addideaview'); } }, /** * 格长风采 */ OnGezhagnfengcainameTap:function() { alert('格长风采'); }, /** * 显示所有格长列表 */ OnGezhangtoupiaonameTap:function() { alert('格长投票'); } });
import Statistic from '../models/statistic.model'; require("@babel/polyfill"); // Get Статистична інформація про доходи кампанії та працівників const getStatData = async (req,res)=>{ try{ const data = await Statistic.find({}); console.log(data); res.send(data) }catch(err){ console.log("Error"+err); } } //Post Додає дані на сайт const addStaticData = async (req,res)=>{ try{ const data = await Statistic.create(req.body); console.log(data); res.send(data) }catch(err){ console.log("Error"+err); } } export default { getStatData, addStaticData }
// @flow import React, { Component } from "react"; import _ from "lodash"; // keys const LEFT = 37; const RIGHT = 39; const UP = 38; const DOWN = 40; const ENTER = 13; const BROWSER_BACK = 8; const WEBOS_BACK = 461; const TIZEN_BACK = 10009; const WEBOS_YELLOW_KEY = 405; const TIZEN_YELLOW_KEY = 405; const WEBOS_BLUE_KEY = 406; const TIZEN_BLUE_KEY = 406; const PC_YELLOW_PSEUDO_KEY = 17; // ctrl const PC_BLUE_PSEUDO_KEY = 18; // alt const KEY_ZERO = 48; const KEY_ONE = 49; const KEY_TWO = 50; const KEY_THREE = 51; const KEY_FOUR = 52; const KEY_FIVE = 53; const KEY_SIX = 54; const KEY_SEVEN = 55; const KEY_EIGHT = 56; const KEY_NINE = 57; const NUM_KEY_ZERO = 96; const NUM_KEY_ONE = 97; const NUM_KEY_TWO = 98; const NUM_KEY_THREE = 99; const NUM_KEY_FOUR = 100; const NUM_KEY_FIVE = 101; const NUM_KEY_SIX = 102; const NUM_KEY_SEVEN = 103; const NUM_KEY_EIGHT = 104; const NUM_KEY_NINE = 105; export type Vertice = { node: HTMLElement, name: string, left?: string, up?: string, down?: string, right?: string, focusOnEnter: ?string }; type PathfinderState = { vertices: Array<Vertice>, current_vertice: ?Vertice }; export default class Pathfinder extends Component<any, PathfinderState> { remoteHandler: Function; handleEnter: Function; defineVertice: Function; setupInitial: Function; refChild: Component<any>; state: PathfinderState = { vertices: [], current_vertice: null }; remoteHandler = ( e: SyntheticKeyboardEvent<HTMLButtonElement> | number ): void => { let _obj = typeof e === "object"; let code = _obj ? e.keyCode : e; switch (code) { case ENTER: _obj && e.preventDefault(); if (this.state) this.handleEnter(this.state.current_vertice); break; case BROWSER_BACK: case WEBOS_BACK: case TIZEN_BACK: if ( this.state.current_vertice && this.state.current_vertice.node && this.state.current_vertice.node.tagName !== "INPUT" ) { _obj && e.preventDefault(); this.handleBack(); } break; case WEBOS_YELLOW_KEY: case TIZEN_YELLOW_KEY: case PC_YELLOW_PSEUDO_KEY: _obj && e.preventDefault(); this.handleYellowKey(); break; case WEBOS_BLUE_KEY: case TIZEN_BLUE_KEY: case PC_BLUE_PSEUDO_KEY: _obj && e.preventDefault(); this.handleBlueKey(); break; case LEFT: this.handleLeftKey(); break; case RIGHT: this.handleRightKey(); break; case UP: this.handleUpKey(); break; case DOWN: this.handleDownKey(); break; default: this.handleKey(e.keyCode); } }; handleKey = (code: number): void => { if (typeof this.refChild.handleKey === "function") this.refChild.handleKey(code); }; handleLeftKey = (): void => { if (typeof this.refChild.handleLeftKey === "function") this.refChild.handleLeftKey(); else this.changeVerticeByDirection("left"); }; handleRightKey = (): void => { if (typeof this.refChild.handleRightKey === "function") this.refChild.handleRightKey(); else this.changeVerticeByDirection("right"); }; handleUpKey = (): void => { if (typeof this.refChild.handleUpKey === "function") this.refChild.handleUpKey(); else this.changeVerticeByDirection("up"); }; handleDownKey = (): void => { if (typeof this.refChild.handleDownKey === "function") this.refChild.handleDownKey(); else this.changeVerticeByDirection("down"); }; handleEnter = (vertice: ?Vertice): void => { if (!vertice) return; if (vertice.to) { this.props.history.push(vertice.to); return; } if (vertice.node && vertice.node.tagName !== "INPUT") { vertice.node.click(); } else if (vertice.focusOnEnter) { this.changeVertice(vertice.focusOnEnter); } }; handleBack = (): void => { this.props.history.goBack(); }; handleYellowKey = (): void => { if (typeof this.refChild.handleYellowKey === "function") this.refChild.handleYellowKey(); }; handleBlueKey = (): void => { if (typeof this.refChild.handleBlueKey === "function") this.refChild.handleBlueKey(); }; checkWrappedComponent = (ref: ?Component<any>): void => { if (!ref) return; if (ref.getWrappedInstance) { try { this.refChild = ref.getWrappedInstance(); } catch (e) { return console.error(e); } } else { this.refChild = ref; } }; setupInitial = (vertice: string | Vertice): void => { this.changeVertice(vertice); }; defineVertice = (vertice: Vertice): void => { let verticeIndex = _.findIndex(this.state.vertices, { name: vertice.name }); let vertices = this.state.vertices; if (verticeIndex >= 0) _.assign(vertices[verticeIndex], vertice); else { vertices.push(vertice); this.setState({ vertices: vertices }); } }; changeVertice = (new_vertice: Vertice | string): void => { if (!new_vertice) return; if (typeof new_vertice === "string") { new_vertice = _.find(this.state.vertices, { name: new_vertice }); } if (!new_vertice) return; this.setState({ current_vertice: new_vertice }); this.setupFocus(new_vertice.node); }; changeVerticeByDirection = (direction: string): void => { if (!this.state.current_vertice) return; // condition for free replacing caret into input element // focus replaces to another vertice only when caret starts or ends of input value if ( this.state.current_vertice.node.tagName === "INPUT" && ((this.state.current_vertice.node.selectionStart !== 0 && direction === "left") || (direction === "right" && this.state.current_vertice.node.selectionStart !== this.state.current_vertice.node.value.length)) ) { return; } if (this.state.current_vertice[direction]) this.changeVertice(this.state.current_vertice[direction]); else this.setupFocus(this.state.current_vertice.node); }; setupFocus = (node: HTMLElement): void => { if (node) node.focus(); }; componentDidMount() { window.addEventListener("keydown", this.remoteHandler); } componentWillUnmount() { window.removeEventListener("keydown", this.remoteHandler); } render() { return ( <div className="pathfinder" style={{ position: "relative" }}> {this.props && React.cloneElement(this.props.children, { ref: ref => this.checkWrappedComponent(ref), defineVertice: this.defineVertice, setupInitial: this.setupInitial })} </div> ); } }
import Vue from 'vue' window.$ = window.JQuery = require('jquery') require('jquery-ui/ui/widgets/datepicker') require('jquery-ui-dist/jquery-ui.min.css') import Dev from './serve.vue' Vue.config.productionTip = false new Vue({ render: h => h(Dev), }).$mount('#app')
/* Based on grunt-doxication * Copyright © 2014 Gion Kunz * Free to use under the WTFPL license. * http://www.wtfpl.net/ */ 'use strict'; var fs = require('fs'), path = require('path'), dox = require('dox'), async = require('async'), _ = require('lodash'), YAML = require('yamljs'), mkdirp = require('mkdirp'); function readFileAsyncUtf8(file, cb) { fs.readFile(file, 'utf8', function (err, result) { cb(err, JSON.parse(result)); }); } function prepareProperty(element) { element.memberType = "property"; element.displayName = element.name; return element; } function prepareMethod(element) { element.memberType = "method"; element.displayName = element.name; return element; } function prepareConstructor(namespace, constructor) { constructor.memberType = "constructor"; constructor.displayName = "new " + namespace.name + "." + constructor.name; return constructor; } function memberSort(a, b) { return (a.name < b.name) ? -1 : (a.name > b.name) ? 1 : 0; } function getDerivedClasses(classes, qualifiedClassName) { return classes.filter(function(c) { return c.extends.length === 1 && c.extends[0] === qualifiedClassName; }).map(function(c) { return c.qualifiedClassName; }); } module.exports = function (grunt) { grunt.registerMultiTask('jsdoc-assemble', 'JSDoc/Assemble grunt plugin', function () { var defaultOptions = { fileName: 'jsdoc-assemble.json' }; var sources = this.filesSrc, done = this.async(), options = _.extend({}, defaultOptions, this.options()), dest = this.data.dest || options.fileName; mkdirp(path.dirname(dest), function (err) { if (err) { throw err; } async.map(sources, readFileAsyncUtf8, function (err, results) { if (err) { throw err; } var inputNamespace = results[0]['namespaces'][0]; var inputClasses = inputNamespace['classes']; var outputPages = []; outputPages.push({ "filename": "index", "data": { "layout": "api-index.html", "title": "API Reference", "nav_title": "API Reference", "section": "API" } }) inputClasses.forEach(function(inputClass) { inputClass.qualifiedClassName = inputNamespace.name + "." + inputClass.name; }); inputClasses.forEach(function(inputClass) { outputPages.push({ "filename": inputNamespace.name + "-" + inputClass.name, "data": { "title": inputClass.qualifiedClassName + " Class", "nav_title": inputClass.qualifiedClassName, "api_types": ['Classes'], "section": "API", "description": inputClass.description, "extends": (inputClass.extends) ? inputClass.extends[0] : null, "derivedClasses": getDerivedClasses(inputClasses, inputClass.qualifiedClassName), "constructor": prepareConstructor(inputNamespace, inputClass.constructor), "properties": (inputClass.properties || []).map(prepareProperty).sort(memberSort), "methods": (inputClass.functions || []).map(prepareMethod).sort(memberSort) }, "content": inputClass.description }); }); outputPages.sort(function(a, b) { return (a.filename < b.filename) ? -1 : (a.filename > b.filename) ? 1 : 0; }); var output = { "pages": outputPages }; fs.writeFile(dest, JSON.stringify(output, null, 2), function (err) { if (err) { throw err; } done(); }); }); }); }); };
import styled from "styled-components"; import { Container, } from "../../components/toolbox"; import React from "react"; // -------------------------------------------------- const Wrapper = styled(Container)` white-space: pre-wrap; word-wrap: break-word; font-size: 11px; font-family: monospace; `; export default data => () => <Wrapper>{console.log(data)}</Wrapper>;
'use strict'; module.exports = { id: require( 'bson-objectid' ) };
define(['apps/system3/production/production.controller'], function (app) { app.factory("changeService", function (Restangular, stdApiUrl, stdApiVersion) { var restSrv = Restangular.withConfig(function (configSetter) { configSetter.setBaseUrl(stdApiUrl + stdApiVersion); }) return { // 变更单 create: function (info) { return restSrv.all("form").customPOST(info,'change'); }, // 更新 update: function (info) { return restSrv.one("form/change", info.ID).customPUT(info); }, // 获取变更单信息 getChangeInfo: function (id) { return restSrv.one("form/change",id).get(); }, } }); });
const prodConfig = { app: { env: 'development', logLevel: 'info', port: 9010, secretKey: 'ovaphlow' }, auth: { excludeUrl: [ '/api/user/login' ] }, storage: { user: 'ovaphlow', password: 'ovaph@HD.1123', host: '192.168.1.154', database: 'haxi' } } const develConfig = { app: { env: 'development', logLevel: 'debug', port: 9010, secretKey: 'ovaphlow' }, auth: { excludeUrl: [ '/api/user/login', '/api/user/register' ] }, storage: { user: 'ovaphlow', password: 'ovaph@CDT.1123', host: '192.168.1.161', database: 'splendid' } } module.exports = develConfig
import styled from 'styled-components'; export const Container = styled.div` background: white; min-height: calc(100vh - 200px); padding: 0 30px; @media (max-width: 590px) { min-height: calc(100vh - 200px); padding: 0 20px; text-align: center; } @media (max-width: 360px) { min-height: calc(100vh - 220px); } `; export const NavigationContainer = styled.div` height: 100%; display: flex; justify-content: space-around; align-items: center; a { margin-right: 15px; color: black } a:hover { text-decoration: line-through; } `; export const Nothing = styled.div` width: 100%; display: flex; justify-content: center; align-items: center; height: 50px; `;
var express = require("express"); var router = express.Router(); var chatModel = require("../models/chatsSchema"); var io = require("socket.io")(); var utility = require("../utility/utility"); chatModel.watch().on("change", changes => { io.emit("chatChanged", { changes: changes }); }); router.get("/chats", (req, res) => { chatModel .find({}) .then(data => { res.send(utility.responseHandler(data, false)); }) .catch(err => { res.send(utility.responseHandler(data, true)); }); }); router.put("/chats", (req, res) => { chatModel .findOneAndUpdate({ _id: req["_body"]["_id"] }) .then(data => { res.send(utility.responseHandler(data, false)); }) .catch(err => { res.send(utility.responseHandler(data, true)); }); }); router.delete("/chats", (req, res) => { chatModel .findOneAndDelete({ _id: req["body"]["_id"] }) .then(data => { res.send(utility.responseHandler(data, false)); }) .catch(err => { res.send(utility.responseHandler(data, true)); }); }); router.post("/chats", (req, res) => { var chatInstance = new chatModel(req["body"]); chatInstance .save() .then(data => { res.send(utility.responseHandler(data, false)); }) .catch(err => { res.send(utility.responseHandler(data, true)); }); }); module.exports = router;
var dir_b99be74980755d6fa11d413ede35bd93 = [ [ "ToolTipsLayoutSampleActivity.java", "_tool_tips_layout_sample_activity_8java.html", [ [ "ToolTipsLayoutSampleActivity", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1commonstyle_1_1notifications_1_1tooltips_3675d87175d62c90936780931c7fddbd.html", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1commonstyle_1_1notifications_1_1tooltips_3675d87175d62c90936780931c7fddbd" ] ] ], [ "ToolTipsOverviewActivity.java", "_tool_tips_overview_activity_8java.html", [ [ "ToolTipsOverviewActivity", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1commonstyle_1_1notifications_1_1tooltips_1_1_tool_tips_overview_activity.html", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1samples_1_1commonstyle_1_1notifications_1_1tooltips_1_1_tool_tips_overview_activity" ] ] ] ];
module.exports = function (grunt) { var semver = require('semver'), f = require('util').format; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), version: '<%= pkg.version %>', banner: [ '/*!', ' * semantic-tokenfield <%= version %>-sui1', ' * https://github.com/m4tx/semantic-tokenfield', ' * Copyright 2015 m4tx, Licensed MIT', ' *', ' * bootstrap-tokenfield <%= version %>', ' * https://github.com/sliptree/bootstrap-tokenfield', ' * Copyright 2013-2014 Sliptree and other contributors; Licensed MIT', ' */\n\n' ].join('\n'), copy: { dist: { files: { 'dist/<%= pkg.name %>.js': 'js/<%= pkg.name %>.js' } }, assets: { files: [{ expand: true, flatten: true, src: [ 'bower_components/bootstrap/js/affix.js', 'bower_components/bootstrap/js/scrollspy.js', 'bower_components/typeahead.js/dist/typeahead.bundle.min.js' ], dest: 'docs-assets/js/' }] } }, uglify: { options: { banner: '<%= banner %>' }, dist: { files: { 'dist/<%= pkg.name %>.min.js': 'dist/<%= pkg.name %>.js' } }, docs: { files: { 'docs-assets/js/docs.min.js': 'docs-assets/js/docs.js' } } }, less: { compile: { files: { 'dist/css/<%= pkg.name %>.css': 'less/<%= pkg.name %>.less', 'dist/css/tokenfield-typeahead.css': 'less/tokenfield-typeahead.less' } }, minify: { options: { cleancss: true, report: 'min' }, files: { 'dist/css/<%= pkg.name %>.min.css': 'dist/css/<%= pkg.name %>.css', 'dist/css/tokenfield-typeahead.min.css': 'dist/css/tokenfield-typeahead.css' } } }, jekyll: { docs: {} }, watch: { copy: { files: 'js/**/*', tasks: ['copy'] }, less: { files: 'less/**/*', tasks: ['less'] }, jekyll: { files: ['dist/**/*', 'index.html', 'docs-assets/**/*'], tasks: ['uglify:docs', 'jekyll'] }, livereload: { options: { livereload: true }, files: ['dist/**/*'], } }, exec: { git_is_clean: { cmd: 'test -z "$(git status --porcelain)"' }, git_on_master: { cmd: 'test $(git symbolic-ref --short -q HEAD) = master' }, git_add: { cmd: 'git add .' }, git_commit: { cmd: function(m) { return f('git commit -m "%s"', m); } }, git_tag: { cmd: function(v) { return f('git tag v%s -am "%s"', v, v); } }, git_push: { cmd: 'git push && git push --tags' }, update_docs: { cmd: [ 'git checkout gh-pages', 'git reset master --hard', 'sed -i.bak \'s/%VERSION%/v<%= version %>/\' index.html', 'rm -rf index.html.bak', 'git add index.html', 'git commit -m "Update docs to <%= version %>"', 'git checkout master' ].join(' && ') }, npm_publish: { cmd: 'npm publish' } } }); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-jekyll'); grunt.loadNpmTasks('grunt-sed'); grunt.loadNpmTasks('grunt-exec'); grunt.registerTask('manifests', 'Update manifests.', function(version) { var _ = grunt.util._, pkg = grunt.file.readJSON('package.json'), bower = grunt.file.readJSON('bower.json'), jqueryPlugin = grunt.file.readJSON('bootstrap-tokenfield.jquery.json'); bower = JSON.stringify(_.extend(bower, { name: pkg.name, version: version }), null, 2); jqueryPlugin = JSON.stringify(_.extend(jqueryPlugin, { name: pkg.name, title: pkg.name, version: version, author: pkg.author, description: pkg.description, keywords: pkg.keywords, homepage: pkg.homepage, bugs: pkg.bugs, maintainers: pkg.contributors }), null, 2); pkg = JSON.stringify(_.extend(pkg, { version: version }), null, 2); grunt.file.write('package.json', pkg); grunt.file.write('bower.json', bower); grunt.file.write('bootstrap-tokenfield.jquery.json', jqueryPlugin); }); grunt.registerTask('release', 'Ship it.', function(version) { var curVersion = grunt.config.get('version'); version = semver.inc(curVersion, version) || version; if (!semver.valid(version) || semver.lte(version, curVersion)) { grunt.fatal('invalid version dummy'); } grunt.config.set('version', version); grunt.task.run([ 'exec:git_on_master', 'exec:git_is_clean', 'manifests:' + version, 'build', 'exec:git_add', 'exec:git_commit:' + version, 'exec:git_tag:' + version, 'exec:update_docs' //'exec:git_push', //'exec:npm_publish', ]); }); // Build task grunt.registerTask('build', ['copy', 'uglify', 'less']); }
$(document).ready(function () { "use strict"; var empty = []; empty.length = 11; var av = new JSAV("collisionCON7"); // Create an array object under control of JSAV library var arr = av.ds.array(empty, {indexed: true}); av.umsg("Let's see what happens when we use a hash table of size M = 11 (a prime number), our primary hash function is a simple mod on the table size (as usual), and our secondary hash function is h<sub>2</sub>(k) = 1 + (k % (M-1))."); av.label("h<sub>2</sub>(k) = 1 + (k % (M-1))", {top: 55, left: 350}); av.displayInit(); av.umsg("Insert 55."); arr.highlight(0); arr.value(0, 55); av.step(); av.umsg("Insert 66. This causes a collision at slot 0."); av.step(); av.umsg("Compute h<sub>2</sub>(66) = 1 + (66 % 10) = 7. So we will now do linear probing by steps of 7. Slot 0 + 7 = 7 is checked first, and it is empty."); arr.unhighlight(0); arr.highlight(7); arr.value(7, 66); av.step(); av.umsg("Insert 11. This causes a collision at slot 0."); arr.unhighlight(7); arr.highlight(0); av.step(); av.umsg("Compute h<sub>2</sub>(11) = 1 + (11 % 10) = 2. So we will now do linear probing by steps of 2. Slot 0 + 2 = 2 is checked first, and it is empty."); arr.unhighlight(0); arr.highlight(2); arr.value(2, 11); av.step(); av.umsg("Insert 24. This causes a collision at slot 2."); av.step(); av.umsg("Compute h<sub>2</sub>(24) = 1 + (24 % 10) = 5. So we will now do linear probing by steps of 5. Slot 2 + 5 = 7 is checked first, and we get another collision."); arr.unhighlight(2); arr.highlight(7); av.step(); av.umsg("Step again by 5 to slot 7 + 5 = 12 % 11 = 1. Slot 1 is free."); arr.unhighlight(7); arr.highlight(1); arr.value(1, 24); av.recorded(); });
// pages/payOrder/payOrder.js var network = require("../../utils/network.js") var common = require("../../utils/common.js") var orderId; var totalMoney; var couponList=[]; Page({ /** * 页面的初始数据 */ data: { showAddr: false, showAddAddr: true, totalMoney: 0,//总金额 detail: [], }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { orderId = options.orderId; console.log("------------" + orderId) let that = this let url = "https://mall.cmdd.tech/mall/api/getOrder" let method = "GET" var params = { orderId: orderId } wx.showLoading({ title: '加载中...', }), network.POST(url, params, method).then((res) => { wx.hideLoading(); // console.log("订单的结果是:" + res.data.shopInfo[0].checked); var goods = res.data.shopInfo; var total = 0; for (let i = 0; i < goods.length; i++) { total += goods[i].number * goods[i].integral; } totalMoney = total that.setData({ detail: goods, totalMoney: total }) }).catch((errMsg) => { wx.hideLoading(); // console.log(errMsg); //错误提示信息 wx.showToast({ title: '网络错误', icon: 'loading', duration: 1500, }) }); }, /** * 生命周期函数--监听页面显示 */ onShow: function() { }, //获取用户地址 getAddress() { if (wx.chooseAddress) { wx.chooseAddress({ success: (res) => { this.setData({ showAddAddr: false, showAddr: true, name: res.userName, addrdetail: res.provinceName + res.cityName + res.countyName + res.detailInfo, tel: res.telNumber }) }, }) } else { common.showTip("当前微信版本不支持获取地址", "loading"); } }, //选择使用现金券 selectTap: function(e) { var that = this; var index = e.currentTarget.dataset.index; var list = that.data.detail; console.log("点击前的状态是" + list[parseInt(index)].checked); var checked = list[parseInt(index)].checked; if(checked==null){ checked = false; } if (index != null ) { //优惠券 var coupon = list[parseInt(index)].coupon.coupon var money = that.data.totalMoney; //如果之前是选中的状态 if (list[parseInt(index)].checked) { //当前总金额 money+=coupon; list[parseInt(index)].checked=false; that.setData({ detail: list, totalMoney: money }) } else { list[parseInt(index)].checked = true; money = money - coupon; that.setData({ detail: list, totalMoney: money }) } } }, //支付 payOrder: function() { let that = this; if (!that.data.showAddr) { common.showTip("请先选择地址", "loading"); return; } let url = "https://weixin.cmdd.tech/weixin/getRepayId" let method = "GET" let openId = wx.getStorageSync("openId") var money = that.data.totalMoney * 100 console.log("价格是:" + money); var params = { openId: openId, money: money } wx.showLoading({ title: '加载中...', }), network.POST(url, params, method).then((res) => { wx.hideLoading(); // console.log("支付的返回值是:" + res.data); wx.requestPayment({ 'timeStamp': res.data.timeStamp, 'nonceStr': res.data.nonceStr, 'package': res.data.package, 'signType': 'MD5', 'paySign': res.data.paySign, 'success': function(res) { // console.log("调起支付成功") wx.hideLoading(); wx.showToast({ title: "支付成功", icon: 'succes', duration: 1500 }) that.paySuccess(); }, 'fail': function(res) { console.log("调起支付失败" + res) wx.showToast({ title: "支付失败", duration: 1500 }) }, 'complete': function(res) {} }) }).catch((errMsg) => { wx.hideLoading(); console.log(errMsg); //错误提示信息 wx.showToast({ title: '网络错误', icon: 'loading', duration: 1500, }) }); }, //支付返回通知 paySuccess: function() { let that = this; let url = "https://mall.cmdd.tech/mall/api/editOrderStatus" let method = "POST" //当前的商品数组 var list = that.data.detail; for(var i=0;i<list.length;i++){ if(list[i].checked){ console.log("当前优惠券是:"+list[i].coupon.id); couponList.push(list[i].coupon.id); } } var params = { couponList:couponList, orderId: orderId, status: 1 } wx.showLoading({ title: '加载中...', }), network.POST(url, params, method).then((res) => { wx.hideLoading(); // console.log("支付的返回值是:" + res.data); wx.navigateTo({ url: '../order/order?id=1', }) }).catch((errMsg) => { wx.hideLoading(); console.log(errMsg); //错误提示信息 wx.showToast({ title: '网络错误', icon: 'loading', duration: 1500, }) }); } })
export default (l = {x: 0, y: 0}, width, height) => { const inRange = (p, w) => {return p >= 0 && p < w}; const neigbors = []; for(let i = -1; i <= 1; i++) { for(let j = -1; j <= 1; j++) { if(inRange(l.x + i, width) && inRange(l.y + j, height)) { neigbors.push({x: l.x + i, y: l.y+ j}); } } } return neigbors; }
import React from 'react'; import HabitForm from '../components/habit/HabitForm'; import HabitList from '../components/habit/HabitList'; import './Habit.css'; function Habit() { return ( <div className='habit-container'> <div className='habit-title-container'> <h1 className='habit-title'> Habit Builder</h1> </div> <div className='habit-body-container'> {/* TODO: Habit Score List */} {/* TODO: Habit implementation intentions/goals */} {/* TODO: Little pop tips on making better goals for changing a habit */} <HabitList /> <HabitForm /> </div> </div> ); } export default Habit;
import { pushStateLocationPlugin } from 'ui-router-react'; import { home, user, albums, fail } from './states'; export const plugins = [ pushStateLocationPlugin ] export const states = [ home, user, albums, fail ]