text
stringlengths
7
3.69M
// ==UserScript== // @name BiliBili WebSocket Proxy Rebuild // @namespace http://tampermonkey.net/ // @version 0.1 // @description try to take over the world! // @author Shugen // @match *://*.bilibili.com/* // @match *://*.bilibili.com // @require https://cdnjs.cloudflare.com/ajax/libs/pako/1.0.10/pako.min.js // @grant none // ==/UserScript== (function () { 'use strict'; const consts = { "WS_OP_HEARTBEAT": 2, "WS_OP_HEARTBEAT_REPLY": 3, "WS_OP_MESSAGE": 5, "WS_OP_USER_AUTHENTICATION": 7, "WS_OP_CONNECT_SUCCESS": 8, "WS_OP_BATCH_DANMAKU": 9, "WS_OP_CHANGEROOM": 12, "WS_OP_CHANGEROOM_REPLY": 13, "WS_OP_REGISTER": 14, "WS_OP_REGISTER_REPLY": 15, "WS_OP_UNREGISTER": 16, "WS_OP_UNREGISTER_REPLY": 17, "WS_OP_DANMAKU": 1000, "WS_PACKAGE_HEADER_TOTAL_LENGTH": 16, "WS_PACKAGE_OFFSET": 0, "WS_HEADER_OFFSET": 4, "WS_VERSION_OFFSET": 6, "WS_OPERATION_OFFSET": 8, "WS_SEQUENCE_OFFSET": 12, "WS_COMPRESS_OFFSET": 16, "WS_CONTENTTYPE_OFFSET": 17, "WS_BODY_PROTOCOL_VERSION_NORMAL": 0, "WS_BODY_PROTOCOL_VERSION": 1, "WS_BODY_PROTOCOL_VERSION_DEFLATE": 2, "WS_HEADER_DEFAULT_VERSION": 1, "WS_HEADER_DEFAULT_OPERATION": 1, "WS_HEADER_DEFAULT_SEQUENCE": 1, "ws_header_default_sequence": 1, "WS_HEADER_DEFAULT_COMPRESS": 0, "WS_HEADER_DEFAULT_CONTENTTYPE": 0 } var textDecoder = new TextDecoder(); var textEncoder = new TextEncoder(); var loggerIncrement = 0; function convertToObject(data) { var dataView = new DataView(data); var result = { body: [] }; result.packetLen = dataView.getInt32(consts.WS_PACKAGE_OFFSET); result.headerLen = dataView.getInt16(consts.WS_HEADER_OFFSET); result.ver = dataView.getInt16(consts.WS_VERSION_OFFSET); result.op = dataView.getInt32(consts.WS_OPERATION_OFFSET); result.seq = dataView.getInt32(consts.WS_SEQUENCE_OFFSET); if (dataView.packetLen < data.byteLength) { convertToObject(data.slice(0, result.packetLen)) console.log(data.slice(result.packetLen,data.bodyLength)); } var a=false; switch (result.op) { case consts.WS_OP_HEARTBEAT_REPLY: result.body={count:dataView.getInt32(16)}; break; case consts.WS_OP_HEARTBEAT: result.body = textDecoder.decode(data.slice(result.headerLen, result.packetLen)); break; case consts.WS_OP_CONNECT_SUCCESS: if(result.packetLen>result.headerLen){ }else{ result.body=void 0; break; } case consts.WS_OP_REGISTER_REPLY: case consts.WS_OP_REGISTER: case consts.WS_OP_USER_AUTHENTICATION: case consts.WS_OP_MESSAGE: a=true; default: if(!a){ console.error("Unknown OperationID",result.op); //result.body=data.slice(result.headerLen, result.packetLen); } for (var offset = consts.WS_PACKAGE_OFFSET, bodyLength = result.packetLen, packetStart = "", c = ""; offset < data.byteLength; offset += bodyLength) { bodyLength = dataView.getInt32(offset); packetStart = dataView.getInt16(offset + consts.WS_HEADER_OFFSET); try { if (result.ver === consts.WS_BODY_PROTOCOL_VERSION_DEFLATE) { result.deflate = true; var deflateData = data.slice(offset + packetStart, offset + bodyLength), inflateData = pako.inflate(new Uint8Array(deflateData)); c = convertToObject(inflateData.buffer) } else { result.deflate = false; c = JSON.parse(textDecoder.decode(data.slice(offset + packetStart, offset + bodyLength))); } c && result.body.push(c) } catch (e) { console.error("decode body error:", new Uint8Array(data), result, e) } } break; case consts.WS_OP_BATCH_DANMAKU: var parseData = [] var g=18; var u=dataView.byteLength; for (var w = result.headerLen; w < dataView.byteLength; w += u) { u = dataView.getInt32(w); g = dataView.getInt16(w + consts.WS_HEADER_OFFSET); try { parseData.push(JSON.parse(textDecoder.decode(data.slice(w + g, w + u)))) } catch (f) { parseData.push(textDecoder.decode(data.slice(w + g, w + u))) } } result.body=parseData; break; } return result; } function convertToArrayBuffer(message){ switch(message.op){ case consts.WS_OP_USER_AUTHENTICATION: break; } var header= new ArrayBuffer(consts.WS_PACKAGE_HEADER_TOTAL_LENGTH) var body = new DataView() } var proxyDesc = { set: function (target, prop, val) { if (prop == 'onmessage') { var oldMessage = val; val = function (e) { console.log(`#${target.WSLoggerId} Msg from server << `, convertToObject(e.data)); oldMessage(e); }; } return target[prop] = val; }, get: function (target, prop) { var val = target[prop]; if (prop == 'send'){ val = function (data) { console.log(`#${target.WSLoggerId} Msg from client >> `, convertToObject(data)); target.send(data); };} else if (typeof val == 'function') val = val.bind(target); return val; } }; window.__rawWebSocket = window.WebSocket; window.WebSocket = new Proxy(window.__rawWebSocket, { construct: function (target, args, newTarget) { var obj = new target(args[0]); obj.WSLoggerId = loggerIncrement++; console.log(`WebSocket #${obj.WSLoggerId} created, connecting to`, args[0]); return new Proxy(obj, proxyDesc); } }) function extend(raw) { var handler = {} return new Proxy(raw, handler); } })();
import React, {Component} from 'react'; /* Component imports */ import NotFound from './NotFound'; import Photo from './Photo'; class PhotoContainer extends Component { componentDidMount() { /* Fetches data on mount based on query */ this.props.pageLoad(); if (this.props.data) { this.props.getPhotos(this.props.data); } else { this.props.getPhotos(this.props.match.params.query); } } componentDidUpdate(prevProps) { /* Fetches data on mount based on query (if statement prevents infinite loop) */ if (this.props.data && this.props.data !== prevProps.data) { this.props.pageLoad(); this.props.getPhotos(this.props.data); } else { if (this.props.match.params.query !== prevProps.match.params.query) { this.props.pageLoad(); this.props.getPhotos(this.props.match.params.query); } } } render() { return( <ul> { (this.props.photos.length > 0) ? this.props.photos.map(photo => <Photo key={photo.id} photos={photo} /> ) : <NotFound /> } </ul> ); } } export default PhotoContainer;
import React from 'react'; import { ListContainer } from '../../Shared/Styles/Containers'; const FeaturedList = (props) => { return( <ListContainer> <div>project 1</div> <div>project 2</div> <div>project 3</div> </ListContainer> ) }; export default FeaturedList;
import styled from "styled-components"; export const HeadingOne = styled.div` font-size: 55px; padding: 10px; `; export const HeadingTwo = styled.div` font-size: 40px; padding: 10px; `; export const HeadingThree = styled.div` font-size: 30px; `; export const Paragraph = styled.div` font-size: 22px; padding: 10px; `; export const breakPointMaxMedium = "(max-width: 768px)"; export const breakPointMaxLarge = "(max-width: 968px)";
'use strict'; class SomeStringDependentService { /** * @param {string} someString */ constructor(someString) { this.someString = someString; } } module.exports = SomeStringDependentService;
// const ticker = "time.updated"; let startDate = "2018-03-18"; let endDate = "2018-04-18"; let currency = "USD"; let api_url = `http://api.coindesk.com/v1/bpi/historical/close.json?currency=${currency}&start=${startDate}&end=${endDate}`; $(document).ready(() => { $("#date1").change(function () { startDate = $("#date1").val(); api_url = `http://api.coindesk.com/v1/bpi/historical/close.json?currency=${currency}&start=${startDate}&end=${endDate}`; axios .get(api_url) .then(res => res.data) .then(data => drawChart(data)) }) $("#date2").change(function () { endDate = $("#date2").val(); api_url = `http://api.coindesk.com/v1/bpi/historical/close.json?currency=${currency}&start=${startDate}&end=${endDate}`; console.log(api_url) axios .get(api_url) .then(res => res.data) .then(data => drawChart(data)) }) $("#currency").change(function () { currency = $("#currency").val(); api_url = `http://api.coindesk.com/v1/bpi/historical/close.json?currency=${currency}&start=${startDate}&end=${endDate}`; axios .get(api_url) .then(res => res.data) .then(data => drawChart(data)) }) }) axios .get(api_url) .then(res => res.data) .then(data => drawChart(data)) const drawChart = data => { let stockLabels = Object.keys(data.bpi); let stockPrice = Object.values(data.bpi); $("#max-value").text("Max: " + Math.max.apply(Math, stockPrice) + " " + currency) $("#min-value").text("Min: " + Math.min.apply(Math, stockPrice) + " " + currency) let ctx = document.getElementById("myChart").getContext("2d"); let chart = new Chart(ctx, { type: "line", data: { labels: stockLabels, datasets: [ { label: "Bitcoin Price Index", // backgroundColor: "rgb(255, 99, 132)", borderColor: "rgb(255, 99, 132)", data: stockPrice } ] } }); };
import React, {useState} from 'react'; import {Router} from '@reach/router'; import UserParent from './UserParent'; import CreateUser from './CreateUser'; import UpdateUser from "./UpdateUser"; const FormSelect = (props) => { const [users, setusers] = useState([{ fname: "", lname: "", password: "" }]) return( <div> <Router> <UserParent path="/" users={users} setusers={setusers} /> <CreateUser users={users} setusers={setusers} path="/create" /> <UpdateUser users={users} setusers={setusers} path="/update/:id" /> </Router> </div> ) } export default FormSelect;
/** # 46. Permutations (https://leetcode.com/problems/permutations/) Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. Example 1: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example 2: Input: nums = [0,1] Output: [[0,1],[1,0]] Example 3: Input: nums = [1] Output: [[1]] Constraints: 1 <= nums.length <= 6 -10 <= nums[i] <= 10 All the integers of nums are unique. */ /** * @param {number[]} nums * @return {number[][]} */ var permute = function(nums) { const out = []; const swap = (arr, a, b) => { const tmp = arr[a]; arr[a] = arr[b]; arr[b] = tmp; }; const sub = (cursor, input, level) => { let buff = []; for(let i = cursor; i < input.length; i++) { buff = [...input]; swap(buff, cursor, i); if (level === input.length-1) { out.push(input); } else { sub(level+1, buff, level+1); } } }; sub(0, nums, 0); return out; }; function doTest(arr) { console.log('> 46. Permutations: ', arr); console.log(permute(arr)); } doTest([1,2]); doTest([1,2,3]); doTest([1,2,3,4]);
import React ,{useState, useEffect} from 'react' import {motion} from "framer-motion" import "../maincomponent.css" import "./Dashboard.css" import {Line, Doughnut} from "react-chartjs-2" import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import firebase from "../../firebase"; import {set, useForm} from "react-hook-form" const dashvariant = { hidden: { opacity: 0, y: -50 }, visible:{ opacity:1, y:0, transition : { ease : "easeInOut", delay:0.3 } }, exit:{ x:-50, opacity:0, transition:{ ease: "easeInOut" } } } export default function Dashboard() { const db = firebase.firestore() const patients = db.collection("patients") const [countPatient, setCountPatient] = useState("0") const [newPat, setNewPat] = useState(false) // useEffect(()=>{ // patients. // },[]) return ( <motion.div variants={dashvariant} initial="hidden" animate="visible" exit="exit" className="container dashboard-container" > {newPat && <AddModal setNewPat={setNewPat} newPat={newPat} patients={patients}/>} <div className="patients total"> <div> <div className="add-patient" onClick={()=>setNewPat(!newPat)}> <FontAwesomeIcon icon="user-plus"/> </div> <div className="logo"> <FontAwesomeIcon icon="user"/> </div> <div className="content"> <p>Patients Registered</p> <p>250</p> </div> </div> </div> <div className="doctor total"> <div> <div className="logo"> <FontAwesomeIcon icon="user-md"/> </div> <div className="content"> <p>Doctor Registered</p> <p>50</p> </div> </div> </div> <div className="item1 total"> <div> <div className="logo"> <FontAwesomeIcon icon="user-md"/> </div> <div className="content"> <p>Doctor Registered</p> <p>50</p> </div> </div> </div> <div className="visits"> <div> <h2>Patients Visits</h2> </div> <div> <LineChart/> </div> </div> <div className="online"> <div> <h2>Users Online</h2> </div> <div> <p>User 1</p> <p>User 2</p> <p>User 3</p> <p>User 4</p> <p>User 5</p> <p>User 6</p> <p>User 7</p> <p>User 8</p> <p>User 9</p> </div> </div> <div className="chart1 doughnutChart"> <div> <DougnutChart/> </div> </div> <div className="chart2 doughnutChart"> <div> <DougnutChart/> </div> </div> </motion.div> ) } function LineChart(){ return( <Line data={{ labels: ["Jan", "Feb", "March", "April", "May", "June", "July"], datasets: [{ label: 'My First Dataset', data: [65, 59, 80, 81, 56, 55, 40], fill: false, borderColor: 'rgb(75, 192, 192)', tension: 0.4, backgroundColor : 'rgba(75, 192, 192, 0.5)' }] }} options={{ maintainAspectRatio: false, responsive: true }} /> ) } function DougnutChart(){ return( <Doughnut data={{ labels: [ 'Red', 'Blue', 'Yellow' ], datasets: [{ label: 'My First Dataset', data: [300, 50, 100], backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(54, 162, 235)', 'rgb(255, 205, 86)' ], hoverOffset: 4 }] }} options={{ maintainAspectRatio: false, responsive: true }} /> ) } function AddModal({setNewPat, newPat, patient}){ // const input ={ // docId: docId // } const [upload, setUpload] = useState(false) const { register, handleSubmit, errors, reset } = useForm(); const [load, setLoad] = useState(false) const sendNewRecordValue = data =>{ setLoad(true) const {name, nik, email, phone_number, address} = data; // let timestamp = firebase.firestore.Timestamp.fromDate(new Date(date)); // patient.doc(nik) // .set({ // conclusion: diagnose, // date: timestamp, // description: description, // subject:subject, // treatment: drug.replace(/\s/g, '').split(","), // doctors_id:docId // }) // .then(() => { // console.log("success"); // setUpdated(true) // setLoad(false) // }) // .catch((error) => { // console.error("failed: ", error); // setLoad(false) // }); } return( <div className="modal"> <h3>Add New Patient [in Development]</h3> {upload && <p>New Patient Succesfully Added</p>} {load && <p>Adding New Patient </p>} <form onSubmit={handleSubmit(sendNewRecordValue)} className="form"> <div> <label htmlFor="name">Name</label> <input type="text" id="name" placeholder="Patients name" {...register('name', { required: true }) } /> </div> <div> <label htmlFor="nik">NIK</label> <input type="text" id="nik" placeholder="Patients NIK" {...register('nik', { required: true }) } /> </div> <div> <label htmlFor="email">Email</label> <input type="email" id="email" placeholder="Patients Email" {...register('email', { required: true }) } /> </div> <div> <label htmlFor="phone_number">Phone Number</label> <input type="text" id="phone_number" placeholder="Patients Phone number" {...register('phone_number', { required: true }) } /> </div> <div> <label htmlFor="address">Address</label> <input type="text" id="address" placeholder="Patients Address, ex: [City Name], [Province]" {...register('address', { required: true }) } /> </div> <div className="buttons"> <button onClick={()=>setNewPat(!newPat)}>Cancel</button> <button type="submit">Upload</button> <div className="clear"></div> </div> </form> </div> ) }
#pragma strict function OnGUI() { GUI.Label(Rect(32, 32, 400, 400), "Move the sphere with the keyboard.\nThe cube follows the sphere with 1 second delay."); }
import http from 'http'; import express from 'express'; import config from './utils'; import graphQL from './graphql_server'; import dotenv from 'dotenv'; dotenv.config({ path: 'variables.env' }); const app = express(), PORT = process.env.PORT || 5000; graphQL.applyMiddleware({ app }); app.use(config); const httpServer = http.createServer(app); graphQL.installSubscriptionHandlers(httpServer); httpServer.listen(PORT, () => { console.log(`*** SERVER OPEN ${process.env.HTTP}://${process.env.BASE_URL_LOCAL}:${PORT}${graphQL.graphqlPath} ***`); console.log(`*** WS OPEN ON ${process.env.WS}://${process.env.BASE_URL_LOCAL}:${PORT}${graphQL.subscriptionsPath} ***`); });
import { combineReducers } from 'redux'; const createList = (type, childType) => { const ids = (state = [], action) => { switch(action.type) { case 'FETCH_ROUTINES_SUCCESS': return action.response.result; case 'ADD_ROUTINE_SUCCESS': return [...state, action.response.result] default: return state; } }; const active = (state = null, action) => { switch(action.type) { case 'ADD_ROUTINE_SUCCESS': return action.response.result; default: return state; } } const isLoading = (state = false, action) => { switch(action.type) { case 'FETCH_ROUTINES_REQUEST': case 'ADD_ROUTINE_REQUEST': return true; case 'FETCH_ROUTINES_SUCCESS': case 'FETCH_ROUTINES_FAILURE': case 'ADD_ROUTINE_SUCCESS': case 'ADD_ROUTINE_FAILURE': return false; default: return state; } } const errorMessage = (state = null, action) => { switch(action.type) { case 'FETCH_ROUTINES_FAILURE': case 'ADD_ROUTINE_FAILURE': return action.message; case 'FETCH_ROUTINES_SUCCESS': case 'ADD_ROUTINE_SUCCESS': return null; default: return state; } } return combineReducers({ ids, active, isLoading, errorMessage, }); } export default createList; export const getIds = state => state.ids; export const getIsLoading = state => state.isLoading; export const getErrorMessage = state => state.errorMessag
import React, { Component } from 'react'; import Login from './components/login/login.js'; import Home from './components/home/home'; import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'; export default class App extends Component { render(props) { return ( <Router> <div> {/* A <Switch> looks through its children <Route>s and renders the first one that matches the current URL. */} <Switch> <Route path="/login"> <Login /> </Route> <Route path="/home"> <Home /> </Route> </Switch> </div> </Router> ); } }
function validaExemplo() { var bValidado = true; // Limpar todos os spans de validação $("#vTexto").text(""); $("#vEscolha1").text(""); $("#vEscolha2").text(""); $("#vSelecao3").text(""); // Como validar input type=text (TextBox) if ( $("#txtTexto").val() == "") { $("#vTexto").text("Informe o texto"); bValidado = false; } // Como validar RadioButton if ($("#rbEscolha1").prop("checked") == false && $("#rbEscolha2").prop("checked") == false) { $("#vEscolha1").text("Selecione escolha 1 ou escolha 2"); bValidado = false; } // Como validar checkBox if ($("#chkEscolha2").prop("checked") == false) { $("#vEscolha2").text("Selecione ação e-mail"); bValidado = false; } // Como validar select/option (dropDownList) if ($("#ddlSelecao3").val() == "selecione") { $("#vSelecao3").text("Selecione opção"); bValidado = false; } return bValidado; } function formatar(mascara, documento) { var i = documento.value.length; var saida = mascara.substring(0, 1); var texto = mascara.substring(i) if (texto.substring(0, 1) != saida) { documento.value += texto.substring(0, 1); } }
'use strict' angular.module('sharedServices').directive("additionalField", function ($compile) { var linkFunction = function (scope, element, attributes, formController) { }; return { restrict: "E", link: linkFunction, require: '^form', replace: true, templateUrl: 'additionalfield.html', scope: { policyAdditionalField: '=policysubcategoryadditionalfield', policyAdditionalFieldOptions: '=policysubcategoryadditionalfieldoptions', formsubmitted: '=formsubmitted', controlname: '@controlname', setchildadditionalfield: '&setchildadditionalfield' } }; });
import auth0 from './auth0' if (process.env.NODE_ENV === 'production'){ auth0.getClient({ client_id: process.env.AUTH0_CLIENT_ID }, (err, client) => { if (err) console.log(err) let {callbacks} = client let urls = [ `${process.env.CMS_URL}/callback`,`${process.env.LUME_URL}/callback` ] urls.forEach( url => { if(!callbacks.includes(url)){ callbacks.push(url) } }) auth0.updateClient({ client_id: process.env.AUTH0_CLIENT_ID, }, { callbacks }, (err, client) => { if (err) console.log(err) }) }) }
import React from 'react' import PropTypes from 'prop-types' import './LiveMatch.scss' import PlayerTable from './PlayerTable' import { gameTime } from '../../actions/matchProcessing' import LiveValue from './LiveValue' import Progress from '../Progress' import Minimap from '../Minimap/Minimap' import MatchScore from './MatchScore' import Advantage from '../chart/Advantage' class LiveMatch extends React.Component { static propTypes = { wsGetLiveMatchDetails: PropTypes.func.isRequired, serverId: PropTypes.string.isRequired, teams: PropTypes.arrayOf(PropTypes.shape({ players: PropTypes.array.isRequired, team_name: PropTypes.string.isRequired, team_logo: PropTypes.string.isRequired, team_id: PropTypes.number.isRequired, score: PropTypes.number.isRequired, })), match: PropTypes.shape({ game_time: PropTypes.number.isRequired, game_mode: PropTypes.number.isRequired, league_id: PropTypes.number.isRequired }), average_mmr: PropTypes.number, graph_data: PropTypes.shape({ graph_gold: PropTypes.arrayOf(PropTypes.number.isRequired).isRequired }), updated: PropTypes.number, isLoading: PropTypes.bool, } static defaultProps = { isLoading: true, average_mmr: 0, graph_data: { graph_gold: [] }, teams: [], match: { game_time: 0, game_mode: 0, league_id: 0, }, updated: 0, } componentDidMount() { this.props.wsGetLiveMatchDetails(this.props.serverId) } render() { if (this.props.isLoading) { return <Progress /> } const [radiant, dire] = this.props.teams const graphGold = this.props.graph_data.graph_gold const lastAdvantageTick = graphGold[graphGold.length - 1] const teamAdvantage = <LiveValue shouldResetStyle={false} value={Math.abs(lastAdvantageTick)} /> return ( <div className='liveMatch'> <header> <div className='title d-flex justify-content-center align-items-center'> <span className='advantage-score'> { lastAdvantageTick > 0 ? teamAdvantage : ''} </span> <div className='match-score-container'> {MatchScore({ team_name_radiant: radiant.team_name || 'Radiant', radiant_score: radiant.score, team_name_dire: dire.team_name || 'Dire', dire_score: dire.score, })} </div> <span className='advantage-score'> {lastAdvantageTick < 0 ? teamAdvantage : ''} </span> </div> <div className='game-info-row justify-content-center'> <span className='material-icons md-18 mr-2'>timelapse</span> <span>{gameTime(this.props.match.game_time)}</span> </div> </header> <hr /> <h6>Radiant</h6> <PlayerTable players={radiant.players} /> <h6>Dire</h6> <PlayerTable players={dire.players} /> <br /> <Minimap radiant={radiant.players} dire={dire.players} /> <Advantage data={this.props.graph_data.graph_gold.map(d => ({ name: 'a', value : d }))} /> </div> ) } } export default LiveMatch
function EnviarDatos(){ var nombre = document.getElementById("inputName"); var apellido = document.getElementById("inputLastName"); var dni = document.getElementById("inputDni"); var legajo = document.getElementById("inputLegajo"); var sueldo = document.getElementById("inputSueldo"); var errores = []; if(!ValidarStrings(nombre)) { errores.push(nombre); alert("-El "+nombre.name+" no debe tener numeros, debe ser menor a 10 caraceteres y no debe estar vacío"); } if(!ValidarStrings(apellido)){ errores.push(apellido); alert("-El "+apellido.name+" no debe tener numeros, debe ser menor a 10 caraceteres y no debe estar vacío"); } if(!ValidarNumeros(dni)){ errores.push(dni); alert("-El "+dni.name+" no debe tener letras, debe ser menor a 10 caraceteres y no debe estar vacío"); } if (!ValidarNumeros(legajo)) { errores.push(legajo); alert("-El "+legajo.name+" no debe tener letras, debe ser menor a 10 caraceteres y no debe estar vacío"); } if(!ValidarNumeros(sueldo)) { errores.push(sueldo); alert("-El "+sueldo.name+" no debe tener letras, debe ser menor a 10 caraceteres y no debe estar vacío"); } MostrarErrores(errores); } function ValidarNumeros(inputNumerico){ if (!isNaN(inputNumerico.value) && inputNumerico.value != "" && inputNumerico.value != null && inputNumerico.value.length < 10) { return true; } return false; } function ValidarStrings(inputCaracteres){ if (isNaN(inputCaracteres.value) && inputCaracteres.value != "" && inputCaracteres.value.length < 10 && inputCaracteres.value != null) { return true; } return false; } function MostrarErrores(arrayIdErrores){ if (arrayIdErrores.length>0) { var mensaje= "Error al completar los campos: \n"; for (var i = 0; i < arrayIdErrores.length; i++){ mensaje += arrayIdErrores[i].name+"\n"; } alert(mensaje); } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Brand = void 0; class Brand { constructor(brand) { this.Brand = brand; } } exports.Brand = Brand; Object.seal(Brand);
$(document).ready(function() { // Transition effect for navbar $(window).scroll(function() { // checks if window is scrolled more than 300px, adds/removes solid class if ($(this).scrollTop() > 400) { $('.navbar').addClass('solid'); $('.navbar-nav>li>a ').addClass('maincolorbg'); $('.back-to-top').removeClass('display-none'); } else { $('.navbar').removeClass('solid'); $('.navbar-nav>li>a ').removeClass('maincolorbg'); $('.back-to-top').addClass('display-none'); } }); });
var model = require('model'), ui = require('ui');
define(['frame'], function(ngApp) { ngApp.provider.controller('ctrlReceived', ['$scope', 'http2', function($scope, http2) { $scope.page = { current: 1, size: 30, keyword: '' }; $scope.doSearch = function(page) { if (page) { $scope.page.current = page; } else page = $scope.page.current; var param = '?page=' + page + '&size=' + $scope.page.size + '&site=' + $scope.siteId; if ($scope.page.keyword && $scope.page.keyword.length > 0) param += '&keyword=' + $scope.page.keyword; http2.get('/rest/pl/fe/site/message/get' + param).then(function(rsp) { $scope.messages = rsp.data[0]; $scope.page.total = rsp.data[1]; }); }; $scope.viewUser = function(openid) { location.href = '/rest/mp/user?openid=' + openid; }; $scope.doSearch(); }]); });
import $ from "jquery"; import styled from 'styled-components' import "../containers/Calculator.css"; const blink_me = styled.div` color: #E0B612; ` export default function blinker() { $(blink_me).fadeOut(200); $(blink_me).fadeIn(200); } setInterval(blinker, 500);
var express = require("express"); var womenRoute = express.Router(); var Women = require("../models/women-schema"); womenRoute .get("/", function(req, res){ Women.find(function(err, womenArray){ if (err) res.status(500).send(err); res.send(womenArray); }) }) .post("/", function(req, res){ var newWoman = new Women(req.body); newWoman.user = req.user; newWoman.save(function(err, savedWoman){ if (err) res.status(500).send(err); res.status(201).send(savedWoman); }); }) .delete("/:id", function(req, res){ Women.findByIdAndRemove(req.params.id, function(err, deletedWomen){ if (err) res.status(500).send(err); res.send(deletedWomen); }) }) .put("/:id", function(req, res){ Women.findByIdAndUpdate({_id: req.params.id, user: req.usr._id}, req.body, {new: true}, function(err, editedWomen){ if (err) res.status(500).send(err); res.send(editedWomen); }) }) module.exports = womenRoute;
import RestfulDomainModel from '../base/RestfulDomainModel' export default new RestfulDomainModel([ { id: { name: 'ID', dataOnly: true }}, { avatar: { name: '头像' }}, { customID: { name: '微信号' }}, { nickname: { name: '昵称' }} ], '/im/profile')
import React from 'react' import logo from '../Images/app_bg.png' import firebase from '../firebase' function loadScript(src) { return new Promise(resolve => { const script = document.createElement('script') script.src = src script.onload = () => { resolve(true) } script.onerror = () => { resolve(false) } document.body.appendChild(script) }) } export default function Payment() { async function displayRazorpay() { const res = await loadScript('https://checkout.razorpay.com/v1/checkout.js'); if(!res){ alert('Page not loaded. Are you online?'); return } var getData = firebase.functions().httpsCallable('payment'); getData({amount:1,receipt:'receipt'}).then(function(result){ const options = { "key": "rzp_test_hTjjOef8p7eYTN", // Enter the Key ID generated from the Dashboard "amount": result.data.amount, "currency": "INR", "name": "Pidgin", "description": "Test Transaction", "image": logo, "order_id": result.data.order_id, "handler": function (response) { alert(response.razorpay_payment_id); alert(response.razorpay_order_id); alert(response.razorpay_signature) }, "theme": { "color": "#51F086" } }; const paymentObject = new window.Razorpay(options) paymentObject.open() }).catch(function(error){ console.log(error) }) } return ( <React.Fragment> <div className='wrap' > <div> <button onClick={displayRazorpay} > Pay </button> </div> </div> </React.Fragment> ) }
import React from "react"; import styled from "styled-components"; const Wrapper = styled.div` margin: 1em; `; const Welcome = () => { return ( <Wrapper> <h3> Our mission is to share children's books by Black authors where readers can learn through mirrors and windows. </h3> <h4>What are mirrors and windows in books?</h4> <p> Mirrors reflect a reader's own life. Seeing yourself, your family and your culture being valued in the world of a book provides a powerful sense of belonging. </p> <p> Books that are windows offer views into other experiences. Windows teach people to understand and appreciate differences. </p> <p> Please support the Black authors you find here by buying their books, requesting them at libraries, or donating copies to schools and community centers! </p> </Wrapper> ); }; export default Welcome;
import React, { useEffect } from "react"; import styled from "styled-components"; import { Density, Input, Color, Surface, ListItem } from "amino-ui"; import { useInput } from "react-hanger"; import useSWR from "swr"; import { fetcher } from "../../utils/fetcher"; import jwtDecode from "jwt-decode"; import { Dialog } from "../Layout/Dialog"; import { joinTeam } from "../../utils/joinTeam"; const Wrapper = styled.div` display: flex; flex-direction: column; input { flex: 1; font-size: 40px; display: flex; height: 80px; text-align: center; font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; } `; const Team = styled.div` border: 1px solid ${Color.gray.light}; border-radius: ${Surface.radius.base}; margin-top: ${Density.spacing.md}; padding: ${Density.spacing.md}; `; export const TeamCode = ({ eventId, onClose, open, title }) => { const teamCode = useInput(""); const { data: team } = useSWR( `${process.env.REACT_APP_API_URL}/events/${eventId}/teams/${teamCode.value}`, fetcher ); const { data: event } = useSWR( `${process.env.REACT_APP_API_URL}/events/${eventId}`, fetcher ); const { data: teamParticipants } = useSWR( () => `${process.env.REACT_APP_API_URL}/events/${eventId}/teams/${team.id}/participants`, fetcher ); const onJoin = () => { alert("it works"); onClose(); }; return ( <Dialog open={open} label={title} onClose={onClose}> <Wrapper> <Input spellCheck={false} label="Have a team code?" placeholder="00000000" {...teamCode} /> {team && team.name && event && teamParticipants ? ( <Team> <ListItem onClick={() => joinTeam(team.id, eventId) .then(onJoin) .catch(onClose) } icon="/images/join-team.svg" label={`Join team ${team.name}`} subtitle={`${teamParticipants.length} out of ${event.max_team_size}`} /> </Team> ) : null} </Wrapper> </Dialog> ); };
import api from '../services/api'; import { useMutation } from 'react-query'; export default function useUnlikePost() { return useMutation((id) => api.delete(`posts/${id}/unlike`)); }
import express from 'express'; import validate from 'express-validation'; import controller from '../../controllers/user.controller'; import { authorize, ADMIN, LOGGED_USER } from '../../middlewares/auth'; import { listUsers, createUser, replaceUser, updateUser, } from '../../validations/user.validation'; const router = express.Router(); /** * Load user when API with userId route parameter is hit */ router.param('userId', controller.load); router .route('/') // GET- v1/users List Users .get(authorize(ADMIN), validate(listUsers), controller.list) // POST- v1/users Create User .post(authorize(ADMIN), validate(createUser), controller.create); router .route('/profile') // GET- v1/users/profile User Profile .get(authorize(), controller.loggedIn); router .route('/:userId') // GET- v1/users/:id Get User .get(authorize(LOGGED_USER), controller.get) // PUT- v1/users/:id Replace User .put(authorize(LOGGED_USER), validate(replaceUser), controller.replace) // PATCH- v1/users/:id Update User .patch(authorize(LOGGED_USER), validate(updateUser), controller.update) // PATCH- v1/users/:id Delete User .delete(authorize(LOGGED_USER), controller.remove); export default router;
//API is communication protocol between different parts of a computer program /* //4.ReactDOM & JSX import React from 'react' import ReactDOM from 'react-dom' ReactDOM.render(<div><h1>Hello world</h1><p>My Name is James </p></div>,document.getElementById("root")) */ /* //5.ReactDOM & JSX Practice import React from 'react' import ReactDOM from 'react-dom' ReactDOM.render( <ul> <li>Tolu</li> <li>Shola</li> <li>Lola</li> </ul>, document.getElementById('root') */ /* //6.Function Components import React from 'react' import ReactDOM from 'react-dom' function MyApp(){ return( <ul> <li>Bola</li> <li>SHola</li> <li>Tolu</li> </ul> ) } ReactDOM.render( <MyApp />, document.getElementById('root') ) */ /* //7.Functional Components Practice import React from "react"; import ReactDOM from "react-dom"; function MyInfo() { return ( <div> <h1>Dere Sunday T</h1> <p>I am a software developer</p> <ul> <li>Andela</li> <li>Google</li> <li>China</li> </ul> </div> ); } ReactDOM.render(<MyInfo />, document.getElementById("root")); */ /* //8.Move Components into separate files import React from 'react' import ReactDOM from 'react-dom' import MyInfo from './components/MyInfo' ReactDOM.render( <MyInfo />, document.getElementById('root') ) */ /* //9. Parent/Child Components import React from 'react' import ReactDom from 'react-dom' import App from './App' ReactDom.render( <App />, document.getElementById('root') ) */ /* import React from "react" import NavBar from "./NavBar" import MainContent from "./MainContent" import Footer from "./components/Footer" function App(){ return( <div> <NavBar /> <MainContent /> <Footer /> </div> ) } export default App */ /* //11.todo app part 1 */ /* //12.Styling React With css classes */ //const App = {} => <h1>Error Function</h1> /*14.JSX to JS and JS -> JSX import React from "react"; import ReactDOM from "react-dom"; //import App from "./App"; import './App.css' function App(){ const date = new Date() const hours = date.getHours() let timeOfDay if(hours<12){ timeOfDay= "morning" }else if(hours>=12 && hours <17){ timeOfDay = "good afernoon" }else{ timeOfDay = "night" } return ( <div> <p>Good {timeOfDay}</p> </div> ) } ReactDOM.render(<App />, document.getElementById("root")); */ //16. TodoApp Phase 2 /* //17.PROPS PART 1:UNDERSTANGING THE CONCEPT //18.Pros Part 2 - Reusable COmponents //19. Props in React pros -- property import React from "react" import ContactCard from "./ContactCard" function App() { return ( <div> <ContactCard name="Mr John" imgUrl="dog.pnh" phone="+234" email="deesuntech" /> <ContactCard name="Mr John" imgUrl="dog.pnh" phone="+234" email="deesuntech" /> <ContactCard name="Mr John" imgUrl="dog.pnh" phone="+234" email="deesuntech" /> <ContactCard name="Mr John" imgUrl="dog.pnh" phone="+234" email="deesuntech" /> </div> ); } export default App; */ //21.Mapping Components /* import React from "react"; import Joke from "./components/Joke"; import jokeData from './components/jokeData' //checkout the link at scribma for this episode function App() { // const nameOfComponent = dataName.map(singleObjectName => <componentName /> ) //the 'joke' will receive the individual object const jokeComponents = jokeData.map( joke => <Joke key={joke.id} question={joke.question} punchLine={joke.punchLine} /> ) return ( <div> {jokeComponents} </div> ); } export default App; */ //23.TodoApp -Phase 3 //24.class based component //25.class based component practice
var ConfigModel = function () { this.table = "config"; this.init = (appCore) => { this.core = appCore; this.router = appCore.eRouter("configModel"); appCore.runRoute("model", this.router, "config"); this.db = appCore.connectDB(); }; this.getAll = () => { let q = this.core.qbSelect() .from(this.table) .field('*') .toString(); return this.db.run(q); }; this.set = (key, value) => { if (key && typeof key == "string" && value && typeof value == "string") { let q = this.core.qbInsert() .into(this.table) .set("key", key) .set("value", value) .toString(); let result = this.db.run(q); if (result.error) { console.log(result.error); } } }; }; module.exports = new ConfigModel();
console.log("bot start"); let Twit = require("twit"); var config = require("./config") var T = new Twit(config); //search parameters var params = { q: '#100DaysOfCode', count: 10 } T.get('search/tweets', params, function (err, data, response) { if (!err) { // Loop through the returned tweets for (let i = 0; i < data.statuses.length; i++) { // Get the tweet Id from the returned data let id = { id: data.statuses[i].id_str } // Try to Favorite the selected Tweet T.post('favorites/create', id, function (err, response) { // log the error message if (err) { console.log(err.message); } // log the url of the tweet else { let username = response.user.screen_name; let tweetId = response.id_str; console.log('Favorited: ', `https://twitter.com/${username}/status/${tweetId}`) } }); } } else { console.log(err); } }) // //user stream // var stream = T.stream('user'); // //someone follows me // stream.on('follow', followed); // //event message // function followed(eMsg) { // var name = eMsg.source.name; // var screenName = eMsg.source.screen_name; // twitIt(`@ ${screenName} Thanks for follow me`); // } // //twitIt(); // //setInterval(twitIt, 10000*60); // // tweet something // function twitIt(text) { // let randomNumber = Math.floor(Math.random()*200); // let tweet = { // status: text // } // T.post('statuses/update', tweet, // function (err, data, response) { // if(err){ // console.log(err); // }else{ // console.log(data) // } // }) // } // //get data // T.get('search/tweets', { q: 'banana since:2011-07-11', count: 100 }, // function(err, data, response) { // console.log(data); // })
import React, { Component } from 'react' import axios from 'axios' import { Link } from 'react-router-dom' import Grid from '@material-ui/core/Grid' import Card from '@material-ui/core/Card' import CardContent from '@material-ui/core/CardContent' import Typography from '@material-ui/core/Typography' import moment from 'moment' export default class SingleInvoice extends Component { state = { updatedInvoice: { amount: '', dateOfService: '', notes: '', paymentConfirmed: '', customerId: '' }, customerInfo: '', } componentDidMount() { this.refreshInvoice() } refreshInvoice = () => { const invoice = this.props.match.params.invoiceId axios.get(`/api/invoice/${invoice}`) .then((res) => { this.setState({ updatedInvoice: res.data }) axios.get(`/api/customer/${this.state.updatedInvoice.customerId}`) .then((res) => { this.setState({ customerInfo: res.data.singleCustomer }) }) }) } onUpdateInvoice = (event) => { event.preventDefault() const invoiceId = this.state.updatedInvoice._id axios.put(`/api/invoice/${invoiceId}`, this.state.updatedInvoice) } onNewInvoiceAmountChange = (event) => { const newInvoiceAmount = event.target.value const previousState = { ...this.state } previousState.updatedInvoice.amount = newInvoiceAmount this.setState(previousState) } onNewInvoiceDateChange = (event) => { const newInvoiceDate = event.target.value const previousState = { ...this.state } previousState.updatedInvoice.dateOfService = newInvoiceDate this.setState(previousState) } onNewInvoiceNoteChange = (event) => { const newInvoiceNote = event.target.value const previousState = { ...this.state } previousState.updatedInvoice.notes = newInvoiceNote this.setState(previousState) } onNewPaymentConfirmedChange = (event) => { console.log(event.target.value) const newPaymentConfirmed = event.target.value const previousState = { ...this.state } previousState.updatedInvoice.paymentConfirmed = newPaymentConfirmed this.setState(previousState) } render() { const selectedInvoice = this.state.updatedInvoice const customerInfo = this.state.customerInfo const customerLink = `/customer/${customerInfo._id}` return ( <div className='singleView'> <Link to={customerLink}><h1>{customerInfo.firstName} {customerInfo.lastName}</h1></Link> <Grid container direction="row" justify="space-around" alignItems="flex-start" > <Card className='card' variant='outlined'> <CardContent> <Typography className='title' color="textSecondary" gutterBottom> Notes: </Typography> <Typography variant="body1" component="p"> {selectedInvoice.notes} </Typography> <br /> <Typography className='title' color="textSecondary" gutterBottom> Amount: </Typography> <Typography variant="body1" component="p"> {selectedInvoice.amount} </Typography> <br /> <Typography className='title' color="textSecondary" gutterBottom> Date of Service: </Typography> <Typography variant="body1" component="p"> {moment(selectedInvoice.dateOfService).format('MMMM Do YYYY')} </Typography> </CardContent> </Card> </Grid> <div className="form-container"> <form onSubmit={this.onUpdateInvoice}> <input type='number' name="newInvoiceAmount" required="required" onChange={this.onNewInvoiceAmountChange} value={this.state.updatedInvoice.amount} /> <input type='text' name="newInvoiceNote" required="required" onChange={this.onNewInvoiceNoteChange} value={this.state.updatedInvoice.notes} /><span> Client Paid: </span> <span> <input type='radio' name="newPaymentConfirmed" onChange={this.onNewPaymentConfirmedChange} value={true} checked={this.state.updatedInvoice.paymentConfirmed} /> Yes </span> <span> <input type='radio' name="newPaymentConfirmed" onChange={this.onNewPaymentConfirmedChange} value={false} checked={!this.state.updatedInvoice.paymentConfirmed} /> No </span> <br /> <input type='submit' value="update" /> </form> </div> </div> ) } }
var gardenDisplay = ["img/branches/tree-nobranches.png", "img/branches/tree-2branches.png", "img/branches/tree-4branches.png", "img/branches/tree-6branches.png", "img/leaves/tree-1leaves.png", "img/leaves/tree-2leaves.png", "img/leaves/tree-3leaves.png", "img/leaves/tree-4leaves.png", "img/leaves/tree-5leaves.png", "img/leaves/tree-6leaves.png", "img/death/tree-autumn.png", "img/death/tree-autumn2.1.png"]; var hardWords = [ { w: "terraform", d: "sculpting planets" }, { w: "soliloquy", d: "one person's speech" }, { w: "reliquary", d: "container for holy things" }, { w: "kerfuffle", d: "a commotion" }, { w: "dignitary", d: "important person" }, { w: "schistosomiasis", d: "snail fever" }, { w: "antidisestablishmentarianism", d: "objection to the movement to officially secularize a country" } ] var gardenOfShame = [], j; var wordBlanks = [], i; console.log("hardWords length is " + hardWords.length); var wordChoice = Math.floor(Math.random() * hardWords.length); console.log("index of word is " + wordChoice); console.log("word is " + hardWords[wordChoice].w); console.log("definition is " + hardWords[wordChoice].d); document.onkeyup = function(event) { var playerEntry = String.fromCharCode(event.keyCode).toLowerCase(); console.log("letter guessed: " + playerEntry); if(hardWords[wordChoice].w.indexOf(playerEntry) > -1) { var indices = [], i; for(i = 0; i < hardWords[wordChoice].w.length; i++){ if (hardWords[wordChoice].w[i] === playerEntry){ indices.push(i); //display letter in the correct blanks } } console.log("index of letter guessed: " + indices); console.log("the letter is in the target word! " + playerEntry + " is in " + hardWords[wordChoice].w); } else { var letterCheck = /^[a-z]+$/; if(gardenOfShame.includes(playerEntry) || !(playerEntry.match(letterCheck))) { console.log("Not a valid guess."); } else { gardenOfShame.push(playerEntry); console.log("garden of shame: " + gardenOfShame); //display wrong guesses for(j = 0; j < gardenOfShame.length; j++) { j = gardenOfShame.indexOf(playerEntry); if(gardenOfShame.length == (j + 1)) { var showTree = gardenDisplay[j]; } else { var showTree = "#"; } var treeHtml = "<img src='" + showTree + "' alt='tree that moves from spring to fall as the player guesses wrong letters'>"; if(gardenOfShame.length == 12) { console.log("Winter is coming. Play again!"); } document.querySelector('#treeDisplay').innerHTML = treeHtml; } } } var gardenHtml = gardenOfShame.join(" "); document.querySelector('#gardenDisplay').innerHTML = gardenHtml; }
// (function() { // angular // .module('rocks-minerals-app') // .controller('googleCtrl', googleCtrl); // googleCtrl.$inject = ['$scope', 'Google']; // function googleCtrl($scope, Google){ // var vm = this; // console.log(window.location); // vm.content = "Google Image Search"; // vm.getGoogleImage = function(){ // var searchTerm = vm.searchTerm // console.log(searchTerm); // } // vm.getGoogleImage(); // } // }) // 'use strict'; /* jshint -W098 */ (function(){ angular .module('rocks-minerals-app') .controller('GoogleCtrl', GoogleCtrl); GoogleCtrl.$inject = ['$scope', 'Global', 'Search'] function GoogleCtrl ($scope, Global, Search) { $scope.global = Global; $scope.package = { name: 'search' }; $scope.customSearchResults = {}; $scope.search_term = ''; $scope.result_count = 10; $scope.submit = function () { $scope.search_term = $scope.search_term.trim(); if ($scope.search_term) { // if input is not blank... Search.getCustomSearchResults($scope.search_term, $scope.result_count) .then(function (results) { $scope.customSearchResults = results.data.items; }); } }; } });
/* * @Author: duchengdong * @Date: 2020-11-04 14:24:34 * @LastEditors: duchengdong * @LastEditTime: 2020-11-04 15:10:18 * @Description: */ import { createApp } from 'vue' import App from './App.vue' import router from './router' createApp(App).use(router).mount('#app')
import _ConnectionManager from './connection-manager' export const ConnectionManager = _ConnectionManager
const fs = require('fs'); const path = require('path'); const async = require('async'); const csv = require('fast-csv'); const should = require('should'); const {normalize} = require('../sro_utils'); const {findNodes} = require('../neo4j_utils'); const log = require('../sro_utils/logger')("ImportedEntitiesFromPlayer"); const csvOptions = { objectMode: true, headers: true }; let n = "IBM Open Cloud - IBM Cloud Computing - United States" log.debug(n.normalize()); let conceptRecordsNotFound = []; let contentRecordsNotFound = []; let = []; let totalConceptNodes = 0; let totalContentNodes = 0; let totalCleanedContentNodes = 0; describe('Integration Test', () => { it('Should have all the concept nodes imported from the csv file using perceptron player', (done) => { const findNodeOperations = []; csv.fromPath(path.join(__dirname,'../data/cloud_concepts_final.csv'), csvOptions) .on('data', (data) => { const node = { label: 'concept', name: data.Name.normalize() }; totalConceptNodes++; findNodeOperations.push(findNodes.bind(null, node)); }) .on('end', () => { async.parallel(findNodeOperations, (err, results) => { results.forEach((result) => { if(result.records.length < 1) { conceptRecordsNotFound.push(result); } }); // log.debug({records:conceptRecordsNotFound}); fs.writeFileSync(path.join(__dirname, './notFoundConceptNodes.json'), JSON.stringify(conceptRecordsNotFound)); log.debug(`Total Concept Nodes ${totalConceptNodes}`); log.debug(`Concept Nodes Not Found in Graph ${conceptRecordsNotFound.length}`); done(); }); }); }); it('Should have all the content nodes imported from the csv file using perceptron player', (done) => { const findNodeOperations = []; csv.fromPath(path.join(__dirname,'../data/cloud course_1423743638000.csv'), csvOptions) .on('data', (data) => { if(undefined !== typeof data.name && data['node type'] === 'content' ) { const node = { label: 'content', name: data.name.normalize() }; totalContentNodes++; findNodeOperations.push(findNodes.bind(null, node)); } }) .on('end', () => { async.parallel(findNodeOperations, (err, results) => { results.forEach((result) => { if(result.records.length < 1) { contentRecordsNotFound.push(result); } }); fs.writeFileSync(path.join(__dirname, './notFoundContentNodes.json'), JSON.stringify(contentRecordsNotFound)); log.debug(`Total Content Nodes ${totalContentNodes}`); log.debug(`Content Nodes Not Found in Graph ${contentRecordsNotFound.length}`); done(); }); }); }); it('Should have all the cleaned content nodes imported from the csv file using perceptron player', (done) => { const findNodeOperations = []; csv.fromPath(path.join(__dirname,'../data/cloud_course_results_with_summaries_cleanedup.csv'), csvOptions) .on('data', (data) => { if(undefined !== typeof data.name && data['node type'] === 'Content' ) { const node = { label: 'content', name: data.name.normalize() }; totalCleanedContentNodes++; findNodeOperations.push(findNodes.bind(null, node)); } }) .on('end', () => { async.parallel(findNodeOperations, (err, results) => { results.forEach((result) => { if(result.records.length < 1) { cleanedContentRecordsNotFound.push(result); } }); fs.writeFileSync(path.join(__dirname, './notFoundCleanedContentNodes.json'), JSON.stringify(contentRecordsNotFound)); log.debug(`Total Content Nodes ${totalCleanedContentNodes}`); log.debug(`Content Nodes Not Found in Graph ${cleanedContentRecordsNotFound.length}`); done(); }); }); }); });
$(function(){ $.ajaxSetup({ cache: false, }); //e.preventDefault(); $("a.load_courses").on("click", function(e){ e.preventDefault(); $.ajax({ method: "GET", url: this.action, data: $(this).serialize(), dataType: "json", success: function(courses){ courses.forEach(function(course){ let text = `<h2><a class="js-course-show" href="/courses/${course.id}">${course.title}</a></h2> <p>${course.description.substring(0, 50)}...</p> <a class="js-course-show" href="/courses/${course.id}">Read More</a></p> <small class="course-meta">by ${course.user.email}</small>` $("#indexCourses").append(`<li>${text}</li>`); }) } }) }) }) function getReviews(){ $("a.load_reviews").on("click", function(e){ e.preventDefault(); $.ajax({ method: "GET", url: this.action, data: $(this).serialize(), dataType: "json", success: function(json){ // debugger let alphabetizedList = json.reviews.sort(function(a, b){ if(a.comment.toUpperCase() < b.comment.toUpperCase()) return -1; if(a.comment.toUpperCase() > b.comment.toUpperCase()) return 1; return 0; }) alphabetizedList.forEach(function(review){ $("#test").append(`<li><a class="review_link" href="http://localhost:3000/courses/${json.id}/reviews/${review.id}">${review.comment.substring(0,20) + "..."}</li>`); }) } }) }) }; function Review(attributes) { this.id = attributes.id; this.comment = attributes.comment; this.overallQuality = attributes.overall_quality this.averageDifficulty = attributes.average_difficulty this.workAmount = attributes.work_amount this.amountLearned = attributes.amount_learned this.instructorQuality = attributes.course this.course = attributes.course; this.user = attributes.user; this.createdAt = attributes.created_at; } Review.prototype.renderReview = function() { let html = `<li> <a class="review_link" href="http://localhost:3000/courses/${this.course.id}/reviews/${this.id}"> ${this.comment.substring(0,20)}... </a> </li>`; $("#test").append(html); } function createReview() { $("form#new_review").on("submit", function(event) { event.preventDefault(); var $form = $(this); var url = this.action + "." + "json"; var data = $form.serialize(); $.ajax({ method: "POST", url: url, data: data, success: function(data) { $("#test").val(""); var review = new Review(data); review.renderReview(); } }) }) } //"http://localhost:3000/courses/4/reviews.json" $(document).ready(function() { getReviews(); createReview(); });
'use strict' var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ facebook_user_id: String, facebook_access_token: String, username: String, email: {type: String, lowercase: true}, pic: String, points: Number, achievements: Array }); module.exports = mongoose.model('User', UserSchema);
var password = 'azerty'; if (password.length > 5) { console.log('the password has more than 5 Characters') } else { console.log('the password has 5 characters or less') }
import React from 'react'; import styled from 'styled-components'; const SpriteImage = styled.img` transform: translate(-${({ left }) => left}px, -${({ top }) => top}px); user-drag: none; user-select: none; -moz-user-select: none; -webkit-user-drag: none; -webkit-user-select: none; -ms-user-select: none; `; const Image = ({ image, size, step, direction }) => { const { width, height } = size; const top = height * (direction - 1); const left = width * step; return <SpriteImage src={image} top={top} left={left} />; }; export default Image;
/** * raids.js * * Controls the initialization of a DataTable containing all raids. */ $(document).ready(function() { let ajaxRaidsUrl = "/raids"; let instanceSelector = $("#raidsInstanceSelect"); function reloadDataTable() { $("#raidsTable").DataTable({ responsive: true, order: [[1, "desc"]], columnDefs: [ {targets: [0], orderable: false} ] }); } instanceSelector.off("change").change(function() { $.ajax({ url: ajaxRaidsUrl, dataType: "json", data: { instance: $(this).val(), context: true }, beforeSend: function() { $("#raidsCardBody").empty().append(loaderTemplate); $(".loader-template").fadeIn(); }, success: function(data) { let body = $("#raidsCardBody"); body.find(".loader-template").fadeOut(100, function() { $(this).remove(); body.empty().append(data["table"]); reloadDataTable(); }); } }); }); /** * Generate DataTable. */ reloadDataTable(); /** * Allow users to export their raids data to a JSON file. */ $("#exportRaidsJson").off("click").click(function() { exportToJsonFile($("#jsonData").data("json"), "raids"); }); });
import React from "react"; import Item from "./Item"; const ItemList = ({articulos}) => { return ( <div className="grid-list" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr 1fr"}} > {articulos.map((articulo) => ( <Item key={articulo.id} item={articulo} /> ))} </div> ); }; export default ItemList;
import Microcastle from '../index.js'; import { createStore, combineReducers, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import I from 'immutable'; import thunk from 'redux-thunk'; const reducer = combineReducers({ microcastle: Microcastle.MicrocastleStore.reducer, }); const store = createStore(reducer, { microcastle: I.fromJS({ data: { news: {'1': {title: 'bob'}}, }, editor: {}, }), }, applyMiddleware(thunk)); const schema = { news: { onNew: sinon.spy((v) => Promise.resolve({[v.title]: v})) , onEdit: sinon.spy((v) => Promise.resolve(v)), attributes: { title: { onChange: sinon.spy((v) => {return Promise.resolve(v);}), type: 'text', }, } } }; describe('General', () => { afterEach(() => { schema.news.onNew.reset(); schema.news.onEdit.reset(); schema.news.attributes.title.onChange.reset(); }); it('Can Edit Entry', () => new Promise (resolve => { const rendered = mount( <Provider store={store}> <div> <Microcastle.MicrocastleEditor schemas={schema} /> <Microcastle.Button.EditEntry visible={true} schema='news' entry={'1'} /> </div> </Provider> ); rendered.find(Microcastle.Button.EditEntry).simulate('click'); rendered.find('textarea').simulate('change', {target: {value: 'fred'}}); rendered.find('button').at(0).simulate('click'); setTimeout(() => { expect(store.getState().microcastle.getIn(['data', 'news', '1', 'title'])).to.equal('fred'); resolve(); }, 0); })); it('Can Edit Attribute', () => new Promise (resolve => { const rendered = mount( <Provider store={store}> <div> <Microcastle.MicrocastleEditor schemas={schema} /> <Microcastle.Button.EditAttribute visible={true} schema='news' entry='1' attribute='title' /> </div> </Provider> ); rendered.find(Microcastle.Button.EditAttribute).simulate('click'); rendered.find('textarea').simulate('change', {target: {value: 'george'}}); rendered.find('button').at(0).simulate('click'); setTimeout(() => { expect(store.getState().microcastle.getIn(['data', 'news', '1', 'title'])).to.equal('george'); resolve(); }, 0); })); it('Can Create New', () => new Promise (resolve => { const rendered = mount( <Provider store={store}> <div> <Microcastle.MicrocastleEditor schemas={schema} /> <Microcastle.Button.Create visible={true} schema='news' /> </div> </Provider> ); rendered.find(Microcastle.Button.Create).simulate('click'); rendered.find('textarea').simulate('change', {target: {value: 'new'}}); rendered.find('button').at(0).simulate('click'); setTimeout(() => { expect(store.getState().microcastle.getIn(['data', 'news', 'new', 'title'])).to.equal('new'); resolve(); }, 0); })); });
import { getTheme } from '@fluentui/react' import React from 'react'; import * as $ from 'jquery'; import HeaderPage from './HeaderPage' require('bootstrap') const theme = getTheme(); function scrollFun(){ if($('#page')){ if ($('#page').scrollTop() >= document.getElementById("content").offsetTop - 350){ document.getElementById('stickyheader').classList.remove('nosticky') document.getElementById('stickyheader').classList.add('sticky') } else{ document.getElementById('stickyheader').classList.add('nosticky') document.getElementById('stickyheader').classList.remove('sticky') } } } class Fallback extends React.Component{ componentDidMount(){ document.title = "La Capsule - oups" } render(){ return( <div id="page" onScroll={scrollFun}> <HeaderPage /> <div id="content2" className="container"> </div> </div> ) } } export default Fallback
;(function(){ // 获知信息底下的鼠标移入放大 $(".xinxi_list img,.xinxi_list p").hover(function(){ $(this).parent().css("transform","scale(1.3)"); },function(){ $(this).parent().css("transform","scale(1)"); }) // 线下公告解读 $(".local a").mouseover(function(){ $(".local a").removeClass("active"); $(this).addClass("active"); $(".details").hide(); $(".details").eq($(this).index()).show(); }) // 联系方式 $(".address_list li").mouseover(function(){ $(".address_list li").removeClass("active"); $(this).addClass("active"); $(".tel_box").hide(); $(".tel_box").eq($(this).index()).show(); $(".map a").removeClass("active"); $(".map a").eq($(this).index()).addClass("active"); }) $(".map a").click(function(){ $(".map a").removeClass("active"); $(this).addClass("active"); $(".address_list li").removeClass("active"); $(".address_list li").eq($(this).index()).addClass("active"); $(".tel_box").hide(); $(".tel_box").eq($(this).index()).show(); }) //设置foot下的当前时间 var nowtime=new Date(); var nowyear=nowtime.getFullYear(); $(".nowtime").html(nowyear); })();
/* * * productDiscontinueApi.js * * Copyright (c) 2016 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. * */ 'use strict'; /** * Constructs the API to call the backend for product discontinue reporting. */ (function () { angular.module('productMaintenanceUiApp').factory('ProductDiscontinueApi', productDiscontinueApi); productDiscontinueApi.$inject = ['urlBase', '$resource']; /** * Constructs the API. * * @param urlBase The base URL to contact the backend. * @param $resource Angular $resource to extend. * @returns {*} The API. */ function productDiscontinueApi(urlBase, $resource) { return $resource(urlBase + '/pm/productDiscontinue/:id', null, { // Get the product discontinue report by a list of item codes. 'queryByItemCodes': { method: 'GET', url: urlBase + '/pm/productDiscontinue/itemCodes ', isArray:false }, // Get the product discontinue report by a list of UPCs. 'queryByUPCs': { method: 'GET', url: urlBase + '/pm/productDiscontinue/upcs', isArray:false }, // Get the product discontinue report by a list of product IDs. 'queryByProductIds': { method: 'GET', url: urlBase + '/pm/productDiscontinue/productIds', isArray:false }, // Retrieve a list of found and not found UPCs in the product discontinue table. 'queryForMissingUPCs': { method: 'GET', url: urlBase + '/pm/productDiscontinue/hits/upcs', isArray:false }, // Retrieve a list of found and not found item codes in the product discontinue table. 'queryForMissingItemCodes': { method: 'GET', url: urlBase + '/pm/productDiscontinue/hits/itemCodes', isArray:false }, // Retrieve a list of found and not found product IDs in the product discontinue table. 'queryForMissingProductIds': { method: 'GET', url: urlBase + '/pm/productDiscontinue/hits/productIds', isArray:false }, // Get the product discontinue report by a BDM. 'queryByBDM': { method: 'GET', url: urlBase + '/pm/productDiscontinue/bdm', isArray: false }, // Get the product discontinue report by a product hierarchy level. 'queryBySubDepartment': { method: 'GET', url: urlBase + '/pm/productDiscontinue/subDepartment', isArray: false }, // Get the product discontinue report by a product hierarchy level. 'queryByClassAndCommodity': { method: 'GET', url: urlBase + '/pm/productDiscontinue/classAndCommodity', isArray: false }, // Get the product discontinue report by a product hierarchy level. 'queryBySubCommodity': { method: 'GET', url: urlBase + '/pm/productDiscontinue/subCommodity', isArray: false }, // Gets discontinue data and returns it as a Map<string,string> with the csv as the value (key is CSV). 'exportToExcel': { method: 'GET', url: urlBase + '/pm/productDiscontinue/exportToExcel', isArray: false }, // Gets discontinue data report by a vendor. 'queryByVendor':{ method: 'GET', url: urlBase + '/pm/productDiscontinue/vendor', isArray:false }, // Get the product discontinue report by a product hierarchy level with criteria search is department, class, commodity, sub_commodity. 'queryByDepartmentAndClassAndCommodityAndSubCommodity': { method: 'GET', url: urlBase + '/pm/productDiscontinue/departmentAndClassAndCommodityAndSubCommodity', isArray: false }, // Get the product discontinue report by a product hierarchy level with criteria search is commodity, sub_commodity. 'queryByCommodityAndSubCommodity': { method: 'GET', url: urlBase + '/pm/productDiscontinue/commodityAndSubCommodity', isArray: false }, // Get the product discontinue report by a product hierarchy level with criteria search is department and class and commodity. 'queryByDepartmentAndClassAndCommodity': { method: 'GET', url: urlBase + '/pm/productDiscontinue/departmentAndClassAndCommodity', isArray: false }, // Get the product discontinue report by a product hierarchy level with criteria search is department and commodity and sub_commodity. 'queryByDepartmentAndCommodityAndSubCommodity': { method: 'GET', url: urlBase + '/pm/productDiscontinue/departmentAndCommodityAndSubCommodity', isArray: false }, // Get the product discontinue report by a product hierarchy level with criteria search is department and class code. 'queryByDepartmentAndClass': { method: 'GET', url: urlBase + '/pm/productDiscontinue/departmentAndClass', isArray: false } }); } })();
/** * Created by lijianxun on 2017/1/3. */ const Parse = require('./parseInit').Parse; let Like = Parse.Object.extend('Like'); let football = new Like(); football.set("price",50); let basketball = new Like(); basketball.set("price",100); let teacher = new Parse.Object("Teacher"); teacher.set("name", "tom"); teacher.set("age", 10); teacher.set("email", "tom@163.com"); let relation = new Parse.Relation(teacher,'likes'); relation.add(football); relation.add(basketball); //首先此段代码是跑不通的,必须先添加teacher才能添加relation关联 teacher .save() .then( (object) => { console.log("obj--", object.toJSON()); }, (err) => { console.log("err--", err); });
const initialState = { results: [], pageInfo: null, errorMsg: '', }; const contactReducer = (state = initialState, action) => { switch (action.type) { case 'LIST_CONTACT': { return { ...state, results: action.payload, pageInfo: action.pageInfo, }; } case 'SET_CONTACT_MESSAGE': { return { ...state, errorMsg: action.payload, }; } default: { return { ...state, }; } } }; export default contactReducer;
/** * Created by xinin on 13/02/16. */ 'use strict'; angular.module('wishList').service('Auth', function() { var user = undefined; return { isAuth: function(){ return (user)? true:false; }, getUser: function() { return user; }, setUser: function(value) { user = value; } }; });
/** * Copyright 2016 Google Inc. * * 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. */ goog.provide('audioCat.state.command.MoveEffectCommand'); goog.require('audioCat.state.command.Command'); /** * Moves an effect either within an effect manager or across different ones. * @param {!audioCat.state.effect.EffectManager} oldEffectManager The effect * manager we're moving from. * @param {number} oldIndex The previous index. * @param {!audioCat.state.effect.EffectManager} newEffectManager The effect * manager we're moving to. Could be the same as the origin. * @param {number} newIndex The new index. * @param {!audioCat.utility.IdGenerator} idGenerator Generates IDs unique * throughout the application. * @constructor * @extends {audioCat.state.command.Command} */ audioCat.state.command.MoveEffectCommand = function( oldEffectManager, oldIndex, newEffectManager, newIndex, idGenerator) { goog.base(this, idGenerator, true); /** * @private {!audioCat.state.effect.EffectManager} */ this.oldEffectManager_ = oldEffectManager; /** * @private {number} */ this.oldIndex_ = oldIndex; /** * @private {!audioCat.state.effect.EffectManager} */ this.newEffectManager_ = newEffectManager; /** * @private {number} */ this.newIndex_ = newIndex; }; goog.inherits(audioCat.state.command.MoveEffectCommand, audioCat.state.command.Command); /** * Moves an effect. * @param {!audioCat.state.effect.EffectManager} effectManagerA The effect * manager we are currently moving from. * @param {number} indexA The index into effect manager A. * @param {!audioCat.state.effect.EffectManager} effectManagerB The effect * manager we are currently moving to. * @param {number} indexB The index into effect manager B. * @private */ audioCat.state.command.MoveEffectCommand.prototype.moveEffect_ = function( effectManagerA, indexA, effectManagerB, indexB) { if (effectManagerA.getId() == effectManagerB.getId()) { // We're moving within the same effect manager. effectManagerA.moveEffect(indexA, indexB); } else { // We've moved an effect to a different effect manager. var effect = effectManagerA.getEffectAtIndex(indexA); effectManagerA.removeEffectAtIndex(indexA); effectManagerB.addEffect(effect, indexB); } }; /** @override */ audioCat.state.command.MoveEffectCommand.prototype.perform = function() { this.moveEffect_( this.oldEffectManager_, this.oldIndex_, this.newEffectManager_, this.newIndex_); }; /** @override */ audioCat.state.command.MoveEffectCommand.prototype.undo = function(project, trackManager) { this.moveEffect_( this.newEffectManager_, this.newIndex_, this.oldEffectManager_, this.oldIndex_); }; /** @override */ audioCat.state.command.MoveEffectCommand.prototype.getSummary = function( forward) { var oldEffectManager = this.oldEffectManager_; var newEffectManager = this.newEffectManager_; if (oldEffectManager.getId() == newEffectManager.getId()) { return 'Moved effect from position ' + this.oldIndex_ + ' to ' + this.newIndex_; } var origin = forward ? oldEffectManager : newEffectManager; var dest = forward ? newEffectManager : oldEffectManager; return 'Moved effect from ' + origin.getAudioSegmentLabel() + ' to ' + dest.getAudioSegmentLabel() + '.'; };
import React from "react"; import { createTweet } from "../../redux/reducers/tweet"; import { connect } from "react-redux"; import PropTypes from "prop-types"; class PostTweetPage extends React.Component { constructor(props) { super(props); this.state = { tweetText: "", selectedImage: "", image: "" }; this.onTweetImageChange = e => { this.setState({ selectedImage: window.URL.createObjectURL(e.target.files[0]), image: e.target.files[0] }); }; this.onTweetTextChange = e => { this.setState({ tweetText: e.target.value }); }; } render() { const { onPostButtonClicked } = this.props; const { tweetText, selectedImage, image } = this.state; return ( <div> <h1>Post Tweet</h1> <textarea placeholder="What is in your mind, dear?" onChange={this.onTweetTextChange} value={tweetText} rows="6" cols="40" /> <div> <img width="250" src={selectedImage} /> <input onChange={this.onTweetImageChange} type="file" /> </div> <button onClick={() => onPostButtonClicked({ tweetText, image })}> Post my tweet </button> </div> ); } } const mapDispatchToProps = dispatch => { return { onPostButtonClicked: cred => dispatch(createTweet(cred)) }; }; PostTweetPage.propTypes = { onPostButtonClicked: PropTypes.func.isRequired }; export default connect( null, mapDispatchToProps )(PostTweetPage);
var router = require('express').Router(); var Reward = require('./rewardModel'); router.get('/', function(req, res) { Reward.find({}, function(err, result) { res.json(err || result); }); }); router.post('/', function(req, res) { var newReward = new Reward(req.body); newReward.createdBy = req.user.username; newReward.save(function(err, result) { res.json(err || result); }); }); router.get('/:id', function(req, res) { Reward.findOne({'_id': req.params.id}, function(err, result) { res.json(err || result); }); }); router.post('/:id', function(req, res) { Reward.findOne({'_id': req.params.id}, function(err, result) { for(var key in req.body) { if(result[key] !== req.body[key]) { result[key] = req.body[key]; } } result.save(function(err, result) { res.json(err || result); }); }); }); router.delete('/:id', function(req, res) { Reward.findOneAndRemove({'_id': req.params.id}, function(err, result) { res.json(err || result); }); }); module.exports = router;
import { db } from 'src/lib/db' import { JsonRpcProvider } from '@ethersproject/providers' export const ads = () => { return db.ad.findMany() } export const ad = ({ id }) => { return db.ad.findOne({ where: { id }, }) } export const createAd = ({ input }) => { return db.ad.create({ data: input, }) } export const updateAd = async ({ id, input }) => { try { const walletlessProvider = new JsonRpcProvider(process.env.RPC_ENDPOINT) const { hash, owner, text, amount } = input console.log(owner) const ad = await db.ad.findOne({ where: { id }, }) const { amount: adAmount } = ad if (Number(adAmount) >= Number(amount)) return new Error('Amount is too small') // const receipt = await walletlessProvider.waitForTransaction(hash) // console.log(receipt) // if (receipt.status === 0) // return new Error(`Error updating ad ${id}. Transaction failed`) // Validate recipient // Validate the amount return db.ad.update({ data: { owner, text, amount: amount }, where: { id }, }) } catch (e) { return new Error(`Error updating ad ${id}. ${e}`) } } export const deleteAd = ({ id }) => { return new Error(`Only admins can do this!`) // return db.ad.delete({ // where: { id }, // }) }
window.addEventListener('load', function(){ var theForm = document.querySelector('#theFormulario'); var theEmail = document.querySelector('#email'); var theYearsOld = document.querySelector('#yearsOld'); var theDescription = document.querySelector('#description'); theForm.addEventListener('submit', function(event){ event.preventDefault(); if(theEmail.value == ''){ event.preventDefault(); } if(theYearsOld.value == ''){ event.preventDefault(); } if(description.value == ''){ event.preventDefault(); } }); });
import config from 'dotenv'; import db from './utils/db'; import Logger from './utils/logger'; import AuthService from './services/AuthService'; const logger = new Logger().logger(); config.config(); db.destroy() .then(() => { logger.info('Dropped tables'); db.initialize().then(() => { logger.info('Created tables'); AuthService.initializeAdmin().then(() => logger.info('Initialized admin')).catch((err) => logger.error(err)); }).catch((err) => logger.error(err)); });
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var http = require('http').Server(app); var io = require('socket.io')(http); var randomstring = require("randomstring"); var Game = require('./game.js'); var Player = require('./player.js'); app.use(bodyParser.json()); app.use(bodyParser.text()); var options = { root: __dirname + "/../" }; //URL mappings app.use('/public', express.static('./public/')); app.use('/bower_components', express.static('./bower_components/')); app.get('/', function(req, res) { res.sendFile('./public/index.html', options); }); app.get('/[a-zA-Z0-9]+/:color(black|white)', function(req, res) { // console.log(req.params.color); res.sendFile('./public/index.html', options); }); app.get('/*', function(req, res) { res.redirect('/'); }); //game creation var tokenRand; var lastGame; var games = []; io.on('connection', function(socket) { connect(socket); socket.on('join-new-game', function(msg) { joinNewGame(socket, msg); }); socket.on('join-existing-game', function(msg) { joinExistingGame(socket, msg); }); socket.on('move', function(msg) { move(socket, msg); }); socket.on('disconnect', function(msg) { disconnect(socket, msg); }); }); function connect(socket) { console.log('A new User connected'); socket.emit('connect-ack', { status: 'OK', message: 'You have successfully connected to the server' }); } function joinNewGame(socket, msg) { var game; var player = new Player(msg.username, socket); socket.player = player; if (lastGame === undefined || lastGame.hasStarted) { tokenRand = randomstring.generate(); lastGame = game = new Game(tokenRand); games[tokenRand] = game; game.join(player); } else { game = games[tokenRand]; game.join(player); } socket.join(tokenRand); socket.emit('join-new-game-ack', { status: 'OK', message: 'A new game was created', token: tokenRand, turn: game.turn === 'W' ? 'white' : 'black', tiles: game.tiles }); //if two players joined and game can be started if (game.playersCount === 2) { sendBothPlayersReady(game); } } function sendSecondPlayerJoins(player, opponentUsername) { player.socket.emit('second-player-joins', { status: 'OK', message: 'Your opponent has joined the game', color: player.color === 'W' ? 'white' : 'black', "username": opponentUsername }); } function sendBothPlayersReady(game) { if (!game.hasStarted) game.start(); sendSecondPlayerJoins(game.players.white, game.players.black.username); sendSecondPlayerJoins(game.players.black, game.players.white.username); } function joinExistingGame(socket, msg) { var game = games[msg.token]; if (game) { var player = game.rejoin(msg.color); if (player === undefined) { socket.emit('join-existing-game-ack', { status: 'ERROR', message: 'Someone already connected with this URL' }); return; } socket.player = player; player.socket = socket; socket.join(game.token); socket.emit('join-existing-game-ack', { status: 'OK', message: 'You have successfully rejoined the game', token: msg.token, "username": player.username, color: player.color === 'W' ? 'white' : 'black', tiles: game.tiles, turn: game.turn === 'W' ? 'white' : 'black' }); if (game.playersCount === 2) { sendBothPlayersReady(game); } } else { socket.emit('join-existing-game-ack', { status: 'ERROR', message: 'A game with given token does not exist' }); } } function move(socket, msg) { var game = games[msg.token]; var processedMove = game.makeMove(msg.move, socket.player); if (processedMove) { socket.broadcast.to(msg.token).emit('move', { status: 'OK', move: processedMove }); } else { console.log('Player ' + socket.player.username + ' tried to perform forbidden move!'); socket.emit('move', { status: 'ERROR', msg: 'You\'ve tried to perform disallowed move!' }); } } function disconnect(socket, msg) { //TODO 5 sec timeout +ADD_FEATURE var player = socket.player; if (player && player.game) { //if joining completed player.game.leave(player); socket.broadcast.to(player.game.token).emit('opponent-disconnected', null); socket.emit('disconnect-ack', { status: 'OK', message: 'You have been disconnected from the server' }); console.log('User disconnected from the server (game: ' + player.game.token + ')'); } } http.listen(3000, function() { console.log('listening on *:3000'); });
import PropTypes from 'prop-types' import { css } from '@emotion/core' import styled from '@emotion/styled' import { contained } from '../../../traits' import { grid } from '../../../macros' const Columns = styled.div( ...grid.styles(), contained.styles, ({ theme, columns }) => { let template = `repeat(${columns}, 1fr)` if (columns === 0) { const min = theme.grid.getColumnMin() template = `repeat(auto-fit, minmax(${min}, 1fr))` } return css` grid-template-columns: ${template}; ` } ) Columns.propTypes = { ...grid.propTypes(), columns: PropTypes.number, } Columns.defaultProps = { ...grid.defaultProps(), columns: 0, } export default Columns
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import { BrowserRouter } from 'react-router-dom'; import {Provider} from 'react-redux'; import configureStore from "./redux/store/configureStore"; import 'antd/dist/antd.css'; import { LocaleProvider } from 'antd'; import sp from 'antd/lib/locale-provider/es_ES'; import 'ant-design-pro/dist/ant-design-pro.css'; import {checkIfUser} from "./redux/actions/userActions"; export const store = configureStore(); store.dispatch(checkIfUser()); const WithRouter = () => ( <BrowserRouter> <LocaleProvider locale={sp}> <App/> </LocaleProvider> </BrowserRouter> ); const ReduxProvider = () => ( <Provider store={store}> <WithRouter/> </Provider> ); ReactDOM.render(<ReduxProvider/>, document.getElementById('root')); registerServiceWorker();
let filme = document.querySelector ("ul"); let corpo = document.querySelector ("body"); let filmes = [ {nome:"Frozen"}, {nome:"Alladin"}, {nome:"Olga"}, {nome:"Moana"}, ] let imprimirNomes = (cor) =>{ for(let filmes of filme){ lista.innerHTML += `<li>${filmes.nome}</li>` } corpo.style.backgroundColor = cor; } let adicionarCor = (callback) => { let escolherUmacor = prompt("Escolha uma cor EM INGLES"); setTimeout (() => { filmes.push({nome:"A freira"}); callback(escolherUmacor); } , 3000); adicionarCor(imprimirNomes); // function abrirAlert(nome){ // alert(nome); // } // function receberNome(callbackNome){ // let nome = "Karen" // callbackNome(nome); } // receberNome(abrirAlert);
import React, {Component} from 'react'; import {withRouter} from 'react-router-dom'; import {connect} from 'react-redux'; import PropTypes from 'prop-types'; import {ADMIN_USERS_URI} from './routes'; import {cleanFilters, getUsers, setEmailValue} from '../../store/modules/administration/adminUsers'; import {changeActivePage} from '../../store/modules/administration/adminMenu'; import Button from '../../components/Button'; import InfiniteScroll from '../../components/InfiniteScroll'; import {Input} from '../../components/Form'; import Form from '../../components/Form'; import Container from '../../components/Container'; import Loader from '../../components/Loader'; import Icon from '../../components/Icon'; import Text from '../../components/Text'; import Message from '../../components/Message'; import Item, {ItemContent, ItemGroup, ItemHeader, ItemImage, ItemSubHeader} from '../../components/Item'; import ScrollToTopButton from '../../components/ScrollToTopButton'; class UsersContainer extends Component { constructor() { super(); this.onClickOpenUserDetails = this.onClickOpenUserDetails.bind(this); this.loadMoreUsers = this.loadMoreUsers.bind(this); this.onChangeEmailInput = this.onChangeEmailInput.bind(this); this.onSubmitSearch = this.onSubmitSearch.bind(this); this.onClickCleanFilters = this.onClickCleanFilters.bind(this); } componentWillMount() { const {dispatch, pageToLoad, size, email} = this.props; dispatch(changeActivePage('users')); dispatch(getUsers(pageToLoad, size, email)); } onClickOpenUserDetails(userId) { const {history} = this.props; history.push(`${ADMIN_USERS_URI}/${userId}`); } loadMoreUsers() { const {dispatch, size, email, users, page} = this.props; users.length > 0 && dispatch(getUsers(page + 1, size, email)); } onChangeEmailInput(field, value) { const {dispatch} = this.props; dispatch(setEmailValue(value)); } onSubmitSearch() { const {dispatch, page, size, email} = this.props; dispatch(getUsers(page, size, email)); } onClickCleanFilters() { const {dispatch} = this.props; dispatch(cleanFilters()); } render() { const {isLast, users, filtered, email, loading} = this.props; const searchIcon = filtered ? <Icon name='delete' link onClick={this.onClickCleanFilters}/> : <Icon name='search' link onClick={this.onSubmitSearch}/>; return ( <InfiniteScroll page={-1} loadMore={this.loadMoreUsers} last={isLast} loader={<Loader active inline='centered' key={0}/>} > <Container> <Text id='users.search'/> <Form onSubmit={this.onSubmitSearch}> <Input value={email} onChange={this.onChangeEmailInput} icon={searchIcon} placeholderid='filter.by.email'/> </Form> </Container> {users.length === 0 && !loading ? <Message info> <p><Icon name='info'/>{filtered ? <Text id='no.users.with.data.provided'/> : <Text id='no.users'/>}</p> </Message> : <div> {filtered && <p><Text id='result.users.filtered' values={{email: email}}/></p>} <ItemGroup divided> { users.map(user => ( <Item key={user.id}> <ItemImage avatar size='tiny' src={user.avatar} alt='avatar'/> <ItemContent floated='right'> <ItemHeader as='a' onClick={() => this.onClickOpenUserDetails(user.id)}> {user.name} </ItemHeader> <ItemSubHeader> <span>{user.email}</span> </ItemSubHeader> <Button icon labelPosition='left' floated='right' primary onClick={() => this.onClickOpenUserDetails(user.id)}> <Icon name='info'/> <Text id='view.details'/> </Button> </ItemContent> </Item> )) } </ItemGroup> <ScrollToTopButton/> </div> } </InfiniteScroll> ); } } const mapStateToProps = ({adminReducers}) => { const {adminUsersReducer} = adminReducers; return { users: adminUsersReducer.users, page: adminUsersReducer.page, size: adminUsersReducer.size, numberOfPages: adminUsersReducer.numberOfPages, isLast: adminUsersReducer.isLast, email: adminUsersReducer.email, filtered: adminUsersReducer.filtered, loading: adminUsersReducer.loading } }; const mapDispatchToProps = dispatch => { return { dispatch } }; UsersContainer.propTypes = { users: PropTypes.array.isRequired, page: PropTypes.number.isRequired, size: PropTypes.number.isRequired, numberOfPages: PropTypes.number.isRequired, isLast: PropTypes.bool.isRequired, email: PropTypes.string.isRequired, filtered: PropTypes.bool.isRequired, loading: PropTypes.bool.isRequired, }; export default withRouter(connect( mapStateToProps, mapDispatchToProps )(UsersContainer));
import React from "react"; import Square from "./square"; export default class Board extends React.Component { render() { if (this.props.value < 10) { return <Square value={this.props.value} />; } } }
export { default as MapSection } from './MapSection';
/*============================================================================= # # Copyright (C) 2016 All rights reserved. # # Author: Larry Wang # # Created: 2016-06-27 18:53 # # Description: Route middleware to verify token. # =============================================================================*/ const jwt = require('jsonwebtoken'); const config = global.require('/config.json'); module.exports = (req, res, next) => { let token = req.query.token; if (!token) { res.status(403).json({error: 'No token provided.'}); return; } jwt.verify(token, config.JWT_SECRET, (err, decoded) => { if (err) { res.status(401).json({error: 'Invalid token.'}); } else { req.decoded = decoded; next(); } }); }
/* eslint-disable prettier/prettier */ import React,{Component} from 'react'; import {StyleSheet, ImageBackground,View,Alert, Button,Text} from 'react-native'; import { Container, } from 'native-base'; import { TextInput } from 'react-native-gesture-handler'; var gb = require('./images/b.jpg'); class Register extends Component { constructor() { super(); this.state = { UserName: '', UserEmail: '', UserPassword: '', }; } UserRegistrationFunction = () =>{ fetch('http://10.0.2.2:80/user_registration.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ name: this.state.UserName, email: this.state.UserEmail, password: this.state.UserPassword, }), }).then((response) => response.json()) .then((responseJson) => { // Showing response message coming from server after inserting records. Alert.alert(responseJson); }).catch((error) => { console.error(error); }); } render() { return ( <Container> <ImageBackground source={gb} style={{height: '100%', width: '100%'}}> <View style={styles.MainContainer}> <Text style= {styles.title}>User Registration </Text> <TextInput placeholder=" User Name" onChangeText={name => this.setState({UserName : name})} underlineColorAndroid="transparent" style={styles.TextInputStyleClass} /> <TextInput placeholder=" User Email" onChangeText={email => this.setState({UserEmail : email})} underlineColorAndroid="transparent" style={styles.TextInputStyleClass} /> <TextInput placeholder=" User Password" onChangeText={password => this.setState({UserPassword : password})} underlineColorAndroid="transparent" style={styles.TextInputStyleClass} secureTextEntry={true} /> <Button title="Click Here To Register" onPress={this.UserRegistrationFunction} color="#2196F3" /> <Text style={styles.moto}>Already registred! Login Me</Text> </View> </ImageBackground> </Container> ); }} export default Register; const styles = StyleSheet.create({ MainContainer :{ justifyContent: 'center', flex:1, margin: 10, }, TextInputStyleClass: { textAlign: 'center', marginBottom: 7, height: 40, borderWidth: 1, borderColor: '#2196F3', borderRadius: 5 , }, title:{ fontSize: 22, color: '#009688', textAlign: 'center', marginBottom: 15, }, moto: { marginLeft: 110, marginTop: 40, }, });
import './css/index.css'; // import './css/index.less' // import './css/index.scss' /** * 1. logo === 图片打包之后地址 * 2. 图片等静态文件需要放在"/src/assets"目录下 */ import logo from './assets/images/png/LOGO.png'; const hModel = require('./js/Header.js'); const cModel = require('./js/Content.js'); const fModel = require('./js/Footed.js'); hModel.createHeaderDiv(); cModel.createContentDiv(); fModel.createFootedDiv(); let fun = () => { console.log('fun。。。。。'); } fun(); Promise.resolve().then(()=> { console.log('Promise......'); }) let imgImg = document.createElement('img'); imgImg.src = logo; // imgImg.setAttribute('class', 'imgSize'); // // imgImg.src = logo; document.getElementById('root').appendChild(imgImg);
import React, { useState } from 'react' import { useDispatch } from 'react-redux' import { makeStyles } from '@material-ui/core/styles' import AppBar from '@material-ui/core/AppBar' import Button from '@material-ui/core/Button' import CssBaseLine from '@material-ui/core/CssBaseLine' import Menu from '@material-ui/core/Menu' import MenuItem from '@material-ui/core/MenuItem' import Toolbar from '@material-ui/core/Toolbar' import Typography from '@material-ui/core/Typography' const useStyles = makeStyles(theme => ({ root: { flexGrow: 1 }, menuButton: { marginRight: theme.spacing(2) }, list: { width: 250 }, title: { flexGrow: 1 }, vocabButton: { borderRadius: 20 } })) const Navbar = () => { const classes = useStyles() const [anchorEl, setAnchorEl] = useState(null) const open = Boolean(anchorEl) const handleOpen = event => { setAnchorEl(event.currentTarget) } const handleClose = () => { setAnchorEl(null) } return ( <React.Fragment> <CssBaseLine /> <AppBar position='static'> <Toolbar> <Typography variant='h6' className={classes.title} > JJAP </Typography> <div> <Button onClick={handleOpen} color='inherit' className={classes.vocabButton} > <Typography variant='h5' > あ </Typography> </Button> <Menu anchorEl={anchorEl} open={open} onClose={handleClose} keepMounted > <MenuItem onClick={handleClose}>JLPT N1</MenuItem> <MenuItem onClick={handleClose}>JLPT N2</MenuItem> <MenuItem onClick={handleClose}>JLPT N3</MenuItem> <MenuItem onClick={handleClose}>JLPT N4</MenuItem> <MenuItem onClick={handleClose}>JLPT N5</MenuItem> </Menu> </div> </Toolbar> </AppBar> </React.Fragment> ) } export default Navbar
bssim.controller("FormQueryController", function($scope, $routeParams, Noty, $http, $location){ var schemaTable = $routeParams["schemaTable"]; var config = angular.fromJson($routeParams["config"]); var path = $location.path(); Noty.loading('Loading...', path); $http.get("/tables/"+schemaTable+"/columns").success(function(result){ if(!result.status){ Noty.error(result.message, path); } else{ Noty.closeAll(); $scope.columns = result.data.columns; } }).error(function(){ Noty.error("网络异常...", path); }); $scope.navToFormName = function(){ $location.path("/form/name/"+schemaTable+"/"+angular.toJson(config)); }; $scope.navToFormCode = function(){ var queryList = []; for(var i=0; i<$scope.columns.length; i++){ if($scope.columns[i].checked){ queryList.push($scope.columns[i].meta.name); } } config.queryList = queryList; config.formName = (config.firstModule+config.secondModule+config.no+config.no_extension).toUpperCase(); $location.path("/form/" + schemaTable + "/" + angular.toJson(config)); }; });
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.pouchSumma = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ function incoming (doc) { // before storage return putValsDown(doc) } function putValsDown (obj) { for (var k in obj) { if (k[0] == '_') { // do nothing } else if (typeof obj[k] == 'object') { obj[k] = putValsDown(obj[k]) } else { obj[k] = {_val: obj[k]} } } return obj } function outgoing (doc) { // after retrieval return bringUpVal(doc) } function bringUpVal (obj) { if (Object.keys(obj).length == 1 && obj._val != undefined) { return obj._val } if (typeof obj == 'object') { for (var k in obj) { if (k[0] == '_') continue obj[k] = bringUpVal(obj[k]) } } return obj } module.exports = { incoming: incoming, outgoing: outgoing } },{}]},{},[1])(1) });
"use strict"; exports.default = void 0; var _bar_gauge = require("./gauges/bar_gauge"); var _default = _bar_gauge.dxBarGauge; /** * @name BarGaugeLegendItem * @inherits BaseLegendItem * @type object */ exports.default = _default; module.exports = exports.default; module.exports.default = exports.default;
import { css } from 'styled-components'; export const H1 = css` font-weight: bold; font-size: 40px; line-height: 48px; letter-spacing: -2px; `; export const H2 = css` font-weight: bold; font-size: 32px; line-height: 42px; letter-spacing: -1px; `; export const H3 = css` font-weight: bold; font-size: 25px; line-height: 32px; `; export const H4 = css` font-weight: 500; font-size: 20px; line-height: 30px; `; export const H5 = css` font-weight: 500; font-size: 18px; line-height: 27px; `; export const Body = css` font-weight: normal; font-size: 16px; line-height: 1.75; `; export const SmallCaps = css` font-weight: bold; font-size: 13px; line-height: 19px; letter-spacing: 1.5px; text-transform: uppercase; `;
//query database to show ajax recomendations // This uses an externam javascript library $(document).ready( function() { $('#search_box_center_input').keyup(function() { /* This function will run on every keyup event on the search box in in the landing page */ query = $('#search_box_center_input').val(); if (query) { var options = { url: function(query) { return "search/" + query; // The api endpoint }, getValue: "carname" ,// The key whose value to be extracted list: { showAnimation: { type: "fade", //normal|slide|fade time: 400, callback: function() {} }, hideAnimation: { type: "slide", //normal|slide|fade time: 400, callback: function() {} } } }; $("#search_box_center_input").easyAutocomplete(options); // Register the element with autocomplete } }); });
import React, { Component } from 'react'; import { getComments, postComment, deleteComment } from '../api' import CommentCard from './CommentCard' import CommentAdder from './CommentAdder' import ErrorPage from './ErrorPage' import { UserContext } from '../contexts/User' class Comments extends Component { state = { comments: [], hasError: false, errorMessage: '', isLoading: true } componentDidMount() { getComments(this.props.article_id, this.props.limit).then(comments => { this.setState({ comments, isLoading: false }) }) .catch(err => { const { response: { status, data: { msg } }, } = err this.setState({ hasError: true, errorMessage: `${status}! ${msg}` }) }) } addComment = (comment) => { // this.props.updateCommentCount(1) const { article_id } = this.props const { loggedInUser } = this.context postComment(comment, loggedInUser, article_id).then(comment => { this.setState(currState => { return { comments: [comment, ...currState.comments] } }) }) } removeComment = (commentId) => { // this.props.updateCommentCount(-1) this.setState(currState => { const newComments = currState.comments.filter(comment => { return comment.comment_id !== commentId }) return { comments: [...newComments] } }) deleteComment(commentId) .catch(err => { const { response: { status, data: { msg } }, } = err this.setState({ hasError: true, errorMessage: `${status}! ${msg}` }) }) } render() { const { comments, hasError, errorMessage, isLoading } = this.state if (hasError) { return <ErrorPage errorMessage={errorMessage} /> } else if (isLoading) { return <p>loading...</p> } else return ( <div className="comment-container"> <CommentAdder addComment={this.addComment} /> {comments.map(comment => { return <CommentCard key={comment.comment_id} comment_id={comment.comment_id} removeComment={this.removeComment} /> })} </div> ); } } Comments.contextType = UserContext export default Comments;
import React from "react"; import { Box, Text, Flex, Input, Button } from "@chakra-ui/core"; import { GiFishingBoat } from "react-icons/gi"; import { GrVisa } from "react-icons/gr"; import { RiMastercardFill } from "react-icons/ri"; import { BsArrowRight } from "react-icons/bs"; export default function Upgrade() { return ( <Box width="lg" className="upgrade-container" borderRadius="10px" p={5} backgroundColor="whiteAlpha.900" mt={5} mb={5} boxShadow="0px 21px 6px -16px #C0C0C0" > <Box className="upgrade-wrapper" p={1}> <Text fontWeight="bold" mb={2} mt={3} fontSize={"lg"}> Upgrade your plan </Text> <Text textAlign="left" fontSize="xs" pr={20} color="gray.400"> Please make the payment to start enjoying all the features of our premium plan as soon as possible. </Text> <Box mt={5} className="plan-description" borderRadius="3px" mb={5} p={0} > <Flex border="1px solid blue" borderRadius="3px" justifyContent="flex-start" p={5} backgroundColor="rgb(239,242,254)" position="relative" > <Box p={3} flexBasis="20%" mr={2} borderRadius="3px"> <Box bottom="15px" p={0} as={GiFishingBoat} size="60px" color="white" position="absolute" backgroundColor="messenger.500" borderRadius={"3px"} /> </Box> <Box flexBasis="30%" mr={8} p={0}> <Text fontSize="md" fontWeight="bold"> Small Business </Text> <Text fontSize="xs" color="messenger.500" fontWeight="bold" mt={2} letterSpacing={1} > CHANGE PLAN </Text> </Box> <Box flexBasis="40%" p={0} display="flex" justifyContent="flex-end" alignItems="center" > <Text as="sup" mr={1}> ${" "} </Text> <Text fontSize="2.0rem"> 8,350 </Text> <Text as="sub" ml={1} pt={2}> / year </Text> </Box> </Flex> </Box> <Box className="payment-details" mb={5} p={0}> <Text mb={3} fontWeight="bold" fontSize="md"> Payment details </Text> <Box className="card-container" p={0}> <Flex mb={3} justifyContent="space-between" p={1} className="card-info" > <Flex p={1} width="50%"> <Box flexBasis="30%" display="block" mr={5} className="card-image" borderRadius="3px" position="relative" > <Box bottom="0px" width="55px" height="40px" p={2} as={RiMastercardFill} color="rgb(255,192,50)" position="absolute" backgroundColor="gray.100" borderRadius={"3px"} /> </Box> <Box flexBasis="80%" className="card-number" p={0}> <Text fontWeight="bold" fontSize="sm"> Credit card </Text> <Text fontSize="xs" color="gray.400" fontWeight="bold" > 2344 xxxx xxxx 8880 </Text> </Box> </Flex> <Flex p={1} justifyContent="flex-end"> <Input size="xl" width="35%" placeholder="CVC" className="card-id" pl={1} borderRadius="3px" fontWeight="bold" /> </Flex> </Flex> <Flex mb={3} justifyContent="space-between" p={1} className="card-info" > <Flex p={1} width="50%"> <Box flexBasis="30%" display="block" mr={5} className="card-image" borderRadius="3px" position="relative" > <Box bottom="0px" width="55px" height="40px" p={2} as={GrVisa} color="rgb(0,145,250)" position="absolute" backgroundColor="gray.100" borderRadius={"3px"} /> </Box> <Box flexBasis="80%" className="card-number" p={0}> <Text fontWeight="bold" fontSize="sm"> Credit card </Text> <Text fontSize="xs" color="gray.400" fontWeight="bold" > 8890 xxxx xxxx 1234 </Text> </Box> </Flex> <Flex p={1} justifyContent="flex-end"> <Input size="xl" width="35%" placeholder="CVC" className="card-id" pl={1} borderRadius="3px" fontWeight="bold" /> </Flex> </Flex> <Text fontSize="xs" mb={10} color="messenger.500" fontWeight="bold" letterSpacing={2} > ADD PAYMENT METHOD </Text> </Box> </Box> <Box className="email-form" mb={5} p={1}> <Input placeholder="Email address" /> </Box> <Button width="full" color="whiteAlpha.900" backgroundColor="messenger.500" size="lg" variant="outline" p={8} > Proceed to payment <Box ml={4} mt={1} as={BsArrowRight} size="20px" color="white" borderRadius={"3px"} /> </Button> </Box> </Box> ); }
// ajax请求导航栏页面 (function(){ var head=document.querySelector("head"); var script=document.createElement("LINK"); script.rel="stylesheet" script.href="./css/nav.css" head.appendChild(script); var xhr=createXhr(); xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ var res=xhr.responseText; document.querySelector(".Nav").innerHTML=res; var search=document.querySelector(".search"); var button=document.querySelector(".drop_down-right>ul>li:first-child>a"); var focus=document.querySelector(".search>.searchText>.input>input"); button.onclick=function(){ search.style="display:block;top:-30px"; focus.focus(); document.querySelector("#fade").style.display="block"; focus.onblur=function(){ document.querySelector(".search>.searchText>div:nth-child(2)").style.display="none"; search.style.height="300px"; } focus.onfocus=function(){ document.querySelector(".search>.searchText>div:nth-child(2)").style.display="block"; search.style.height="390px"; } } // 搜索框 var img=document.querySelector(".search>div>img:first-child"); img.onclick=function(){ search.style="display:none"; document.querySelector("#fade").style.display="none"; } // 获取导航栏的高度,并且动态获取bg的高度,更改导航栏的margintop var container=document.querySelector(".container"); var ntHeight=document.querySelector(".notice").offsetHeight; window.onscroll=function(){ var top=document.documentElement.scrollTop; if(top>=ntHeight){ container.style.position="fixed"; var notice=document.querySelector(".notice"); notice.style.display="none"; }else{ container.style.position="staic"; var notice=document.querySelector(".notice"); notice.style.display="block"; } // 底部的左右选拉的时候改变fixed的元素left使得向右或者向左移动 var x=document.documentElement.scrollLeft; var nav=document.querySelector(".container") if(x>=1){ nav.style.left=-x+"px"; }else{ nav.style.left=x+"px"; } } var notice=createXhr(); notice.onreadystatechange=function(){ if(notice.readyState==4&&notice.status==200){ var r=notice.responseText; var no=JSON.parse(r); var html=""; for(var i=0;i<no.length;i++){ html+="<li>"; html+='<a href="">'+no[i].notice+'</a>' html+="</li>" } $("noticeText-left").innerHTML=html; html=""; } } notice.open("get","http://127.0.0.1:3000/notice/notice",true); notice.send(null); // 公告li循环缓慢显示播放 setTimeout(function(){ var li=document.querySelector(".notice>div:first-child>#noticeText-left>li"); var lis=document.querySelectorAll(".notice>div:first-child>#noticeText-left>li"); // 判断公告是否大于一条,小于则不轮播 if(lis.length>1){ var isNumber=0, isNotice=false; setInterval(()=>{ if(isNumber==(lis.length*li.offsetHeight-li.offsetHeight)){ isNotice=true; }if(isNumber==0){ isNotice=false; }if(isNotice){ li.style="transition:all 2s linear"; isNumber-=li.offsetHeight; li.style.marginTop=(-isNumber)+"px"; }else{ li.style="transition:all 2s linear"; isNumber+=li.offsetHeight; li.style.marginTop=(-isNumber)+"px"; } },5930) } },70) } } xhr.open("get","../common/nav.html",true); xhr.send(null); })();
export default function onPress(navigation) { navigation.navigate('Profile'); }
import React, { PureComponent, Component } from "react"; import { StyleSheet, Dimensions, Image, StatusBar, Alert } from "react-native"; import { Container, Header, Title, Content, Footer, FooterTab, Text, Icon, ListItem, Separator,Left, Right,Body, View } from "native-base"; import helper from '../Common/helper' import {menuStyles} from './style'; import {HeaderStyle} from './HeaderStyles'; import { HttpCall } from "../Apis/httpCall"; import { GET } from "../Hooks/constants"; import Util from "../Common/util"; var height = Dimensions.get("window").height; var width = Dimensions.get("window").width; export default class Menu extends PureComponent { constructor(props) { super(props); this.state = { username: "", isData: false, profileURL:"" }; } componentDidMount() { EventBus.getInstance().addListener("ProfilePictureUpdate", this.listener = data => { this.ProfilePictureAPI() }) this.ProfilePictureAPI() } ProfilePictureAPI(){ helper.retrieve_async('userData').then((tokenvalue) => { console.log("menuToken", tokenvalue) HttpCall('customer/me', GET, tokenvalue).then(response => { console.log("menuTokenResponse ;;;;;;;;", response) console.log("Profile URL :;; ", response.data) if(response.data.firstname != null && response.data.firstname != '' && response.data.lastName != null && response.data.lastName != ''){ this.setState({ username: response.data.firstname+' '+response.data.lastName, profileURL: response.data.userimage, }) } console.log(this.state.username) }) .catch(err => { setLoader(false) if (err.response.status === 403) { Alert.alert( 'Alert', 'Session Expired Please Login Again', [ { text: 'Ok', onPress: () => { helper.clear_Async(); Actions.replace('login') } }, ], { cancelable: false }, ); } console.log('hello', err.response.status) // handleError(err.response) }); }) } logout = () => { Alert.alert( 'Confirmation', 'Are you sure you want to logout ?', [ { text: 'Yes', onPress: () => { helper.clear_Async(); Actions.replace('login') } }, { text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel', }, ], { cancelable: false }, ); }; services=()=>{ // Actions.push('Profile'); Actions.push('OptionScreen'); EventBus.getInstance().fireEvent("drawerClose") } dashboard=()=>{ Actions.push('Home'); EventBus.getInstance().fireEvent("drawerClose") } projects=()=>{ Actions.push('ListProject'); EventBus.getInstance().fireEvent("drawerClose") } designs=()=>{ Actions.push('Designs'); EventBus.getInstance().fireEvent("drawerClose") } render() { return ( <Container> <StatusBar hidden={true} /> <Header style={menuStyles.header}> <View style={{backgroundColor:'white', width:70, height:70, borderRadius:50}}> <Image source={{uri: this.state.profileURL}} style={{width:70, height:70, borderRadius:50}}/> </View> <Body style={HeaderStyle.Body}> <Text style={[HeaderStyle.text,{fontSize: Util.normalize(11)}]}>{this.state.username}</Text> {/* <Text style={HeaderStyle.text}> MAKE MY HOUSE</Text>*/} </Body> {/* <Right style={HeaderStyle.Right}> */} {/* <Image source={menuButton} style={{ height: 30, width: 30, marginTop: -2, marginLeft: 0, alignSelf: 'flex-end' }} /> */} {/* </Right> */} </Header> <Content> {/* <Separator bordered> <Text style={{ fontSize: width * 0.03, fontFamily: "Roboto" }}> All Category </Text> </Separator> */} <ListItem onPress={() => this.dashboard()}> <Text style={menuStyles.headText}> HOME </Text> </ListItem> <ListItem onPress={() => this.services()}> <Text style={menuStyles.headText}> PROFILE </Text> </ListItem> <ListItem onPress={() => this.projects()}> <Text style={menuStyles.headText}> PROJECTS </Text> </ListItem> {/* <ListItem onPress={() => this.designs()}> <Image source={require('../../Assets/floorPlan.png')} style={{height:25, width:25}}/> <Text style={menuStyles.headText}> DESIGNS </Text> </ListItem> */} <ListItem last onPress={() => this.logout()}> <Icon name='logout' type='AntDesign' style={{fontSize: 22}}/> <Text style={menuStyles.headText}> LOGOUT </Text> </ListItem> </Content> <Footer> <FooterTab style={{ backgroundColor:'white' }} /> <Image source={require('../Assets/nextmcq.png')} resizeMode='contain' style={{width:'100%',height:'100%', alignSelf:'center', bottom:10, position:'absolute'}}/> </Footer> </Container> ); } }
var jsPerson1 = { name:"王小波", age:48, writeJs:function () { console.log("my name is" + this.name+", i can write js") } } jsPerson1.writeJs() var jsPerson2 = { name:"姚泽宇", age:18, writeJs:function () { console.log("my name is" + this.name+", i can write js") } } jsPerson2.writeJs() function creteJsPerson(name,age) { var obj = {} obj.name = name; obj.age = age; obj.writeJs=function () { console.log("my name is" + this.name+", i can write js") } return obj } var p1 = creteJsPerson("姚爱明",48) var p2 = creteJsPerson("姚明",28) p1.writeJs() p2.writeJs()
var crdt = require('crdt') , nodeStatic = require('node-static') , shoe = require('shoe') , MuxDemux = require('mux-demux'); var staticFiles = new(nodeStatic.Server)('./public'); var server = require('http').createServer(function (request, response) { request.addListener('end', function () { staticFiles.serve(request, response); }); }); var board = new crdt.Doc() board.on('row_update', function (row) { console.log(row.toJSON()) }) shoe(function (sock) { var mx; sock.pipe(mx = new MuxDemux(function (s) { if(!s.meta || s.meta.type !== 'board') s.error('Unknown Doc' + JSON.stringify(s.meta)) else s.pipe(board.createStream()).pipe(s) })).pipe(sock) }).install(server.listen(3000), '/shoe')
const Promise = require('bluebird'); const semver = require('semver'); const {headMessage, headBranch, headClean} = require('./core/git'); const VALIDATE = 'validate'; const UPGRADE = 'bump-dependencies'; const BUMP = 'auto-bump'; const SETUP = 'setup'; const DIRTY = 'warn-dirty'; const NOOP = 'noop'; const selectCommand = async () => { const [branch, message, clean] = await Promise.all([headBranch(), headMessage(), headClean()]); if (!clean) return DIRTY; if (branch !== 'master') return UPGRADE; // §todo: make it configurable if (semver.valid(message)) return UPGRADE; return BUMP; }; module.exports = { UPGRADE, BUMP, DIRTY, VALIDATE, SETUP, NOOP, selectCommand };
import { createStore } from 'redux' const initialState = { number: 0, number1: 0, number2: 0, nestedNumber: { number1: { number: 0, level2: { number: 0 }, }, number2: 0 } } export const reducers = (state = initialState, action) => { const newState = { ...state } switch (action.type) { case 'INC': return { ...state, number: state.number + 1 } case 'INC1': newState.nestedNumber.number1.number = newState.nestedNumber.number1.number + 1 return newState case 'INC2': newState.nestedNumber.number1.level2.number = newState.nestedNumber.number1.level2.number + 1 return newState case 'DECR': return { ...state, number: 1 } default: return state } } const store = createStore(reducers) export default store
import '../../stylesheets/component/common/topMenu.css'; import Links from '../../data/links.json'; const { topMenu } = Links; export default function TopMenu(props) { return ( <nav id="top-menu"> <ul> {topMenu.map((item, idx) => { return ( <a href={item.link}> <li className="menu-item"><span>{item.text}</span></li> </a> ); })} </ul> </nav> ); }
angular.module('AdSales').controller('NewSlsSttlmtOpController', function ($scope, $location, locationParser, SlsSttlmtOpResource ) { $scope.disabled = false; $scope.$location = $location; $scope.slsSttlmtOp = $scope.slsSttlmtOp || {}; $scope.save = function() { var successCallback = function(data,responseHeaders){ var id = locationParser(responseHeaders); $location.path('/SlsSttlmtOps/edit/' + id); $scope.displayError = false; }; var errorCallback = function() { $scope.displayError = true; }; SlsSttlmtOpResource.save($scope.slsSttlmtOp, successCallback, errorCallback); }; $scope.cancel = function() { $location.path("/SlsSttlmtOps"); }; });
/** * 本地开发环境的mock数据 */ const server_host = "http://localhost:3001"; // script/server.js 中配置,代理到http://www.mockhttp.cn const API = { ENTRY: { MESSAGE: server_host + "/calculator/v1/table/list" }, HOME: { // MESSAGE: } }; export default API;
const { body } = require('express-validator'); const signInSchema = require('./sign_in'); module.exports = [ body('name') .trim() .isString() .notEmpty() .exists() .withMessage('is required'), body('last_name') .trim() .isString() .notEmpty() .exists() .withMessage('is required'), ...signInSchema ];
// Simple Express server setup to serve for local testing/dev API server const compression = require('compression'); const helmet = require('helmet'); const express = require('express'); const fetch = require('cross-fetch'); const data = require('./places.json'); const app = express(); app.use(helmet()); app.use(compression()); const HOST = process.env.API_HOST || 'localhost'; const PORT = process.env.API_PORT || 3002; app.get('/api/places/', (req, res) => { let p = req.params.p; let places = data.places; console.log('hey' + p); console.log(places); let matchingPlaces = places.filter(place =>{ return place.indexOf(p) != -1; }); res.json(matchingPlaces); // fetch('./places.txt') // .then(data =>{ // console.log('Inside then block'); // console.log(data); // res.json({ places: data }); // }) // .catch(error => { // console.log(`Error occurred : ${error}`); // }); }); app.listen(PORT, () => console.log( `✅ API Server started: http://${HOST}:${PORT}/api/v1/endpoint` ) );
/** * 口座開設サンプル * @ignore */ const moment = require('moment'); const pecorino = require('../'); pecorino.mongoose.connect(process.env.MONGOLAB_URI); const redisClient = new pecorino.ioredis({ host: process.env.REDIS_HOST, // tslint:disable-next-line:no-magic-numbers port: parseInt(process.env.REDIS_PORT, 10), password: process.env.REDIS_KEY, tls: { servername: process.env.REDIS_HOST } }); async function main() { const accountRepo = new pecorino.repository.Account(pecorino.mongoose.connection); const accountNumberRepo = new pecorino.repository.AccountNumber(redisClient); const account = await pecorino.service.account.open({ name: 'PECORINO TARO', initialBalance: 1000000000 })({ account: accountRepo, accountNumber: accountNumberRepo }); console.log('account opened.', account); } main() .then(() => { console.log('success!'); }) .catch(console.error) .then(async () => { await pecorino.mongoose.disconnect(); await redisClient.quit(); });
/** * Promise A+规范 * https://juejin.im/post/6844903767654023182 * 参考资料 * 1. https://mp.weixin.qq.com/s/qdJ0Xd8zTgtetFdlJL3P1g * 2. https://juejin.im/post/6844903918686715917?utm_source=gold_browser_extension#heading-12 */ const PENDING = 'pending'; const FULFILLED = 'fulfilled'; const REJECTED = 'rejected'; function Promise(executor) { // promise的返回值 this.result = null; // promise的当前状态 this.status = PENDING; // fulfilled回调 this.fulfilledCallbacks = []; // rejected回调 this.rejectedCallbacks = []; resolve = (val) => { setTimeout(() => { // 2.1.1 只有在pending状态下才可能转换成fulfilled/rejected状态 if (this.status === PENDING) { this.status = FULFILLED; this.result = val; this.fulfilledCallbacks.forEach(callback => callback(val)); } }); } reject = (reason) => { setTimeout(() => { // 2.1.1 只有在pending状态下才可能转换成fulfilled/rejected状态 if (this.status === PENDING) { this.status = REJECTED; this.reason = reason; this.rejectedCallbacks.forEach(callback => callback(reason)); } }); } try { executor(resolve, reject); } catch (e) { reject(e); } } /** * * @param {Promise} promise 当前promise * @param {Promise} x 上一个promise的返回值 * @param {*} resolve resolve方法 * @param {*} reject reject方法 */ function resolvePromise(promise, x, resolve, reject) { // 如果上一个promise返回了自己, 循环引用 if (promise === x) { return reject(new TypeError('circular reference')); } let called = false; if (x !== null && (typeof x === 'object' || typeof x === 'function')) { try { let then = x.then; if (typeof then === 'function') { then.call(x, function(y) { if (called) { return; } called = true; resolvePromise(promise, y, resolve, reject); }, function(e) { if (called) { return; } called = true reject(e); }) } else { // 不是thenable的对象,直接透传 resolve(x) } } catch (e) { if (called) { return; } called = true; reject(e) } } else { resolve(x); } } // 2.2 then方法, 接受onFulfilled和onRejected两个参数 Promise.prototype.then = function(onFulfilled, onRejected) { /** * 2.2.1 onFulfilled 和 onRejected 都是可选参数:(给了默认值) * 2.2.1.1 如果 onFulfilled 不是函数,它会被忽略 * 2.2.1.2 如果 onRejected 不是函数,它会被忽略 */ typeof onFulfilled !== 'function' && (onFulfilled = value => value); typeof onRejected !== 'function' && (onRejected = reason => { throw reason }); let promise switch (this.status) { case PENDING: { promise = new Promise((resolve, reject) => { this.fulfilledCallbacks.push(() => { try { let x = onFulfilled(this.result); resolvePromise(promise, x, resolve, reject); } catch (e) { reject(e) } }); this.rejectedCallbacks.push(() => { try { let x = onRejected(this.reason); resolvePromise(promise, x, resolve, reject); } catch (e) { reject(e); } }); }); };break; case FULFILLED: { promise = new Promise((resolve, reject) => { setTimeout(() => { try { const x = onFulfilled(this.result); resolvePromise(promise, x, resolve, reject); } catch (e) { reject(e); } }); }); };break; case REJECTED: { promise = new Promise((resolve, reject) => { setTimeout(() => { try { const x = onRejected(this.reason); resolvePromise(promise, x, resolve, reject); } catch (e) { reject(e); } }); }); };break; default: } return promise; } Promise.prototype.catch = function(callback) { return this.then(null, callback); } Promise.prototype.finally = function(callback) { return this.then( res => Promise.resolve(callback()).then(() => res), err => Promise.resolve(callback()).then(() => { throw err; }) ) } // promises-aplus-tests 测试用方法 Promise.deferred = Promise.defer = function() { let dfd = {}; dfd.promise = new Promise((resolve, reject) => { dfd.resolve = resolve; dfd.reject = reject; }); return dfd; } try { module.exports = Promise; } catch (e) {}
import React, { PureComponent } from 'react'; import styled from 'styled-components'; import { Row, Col } from 'react-flexbox-grid'; import { DefaultPlayer as Video } from 'react-html5video'; import 'react-html5video/dist/styles.css'; import Logo from '../../assets/video/logo.mp4'; import {Link} from "react-router-dom"; export const PageHeader = styled(Col)` width: 100vw; margin: 0; padding: 0; `; export const Content = styled(Col)` height: 67vh; `; export const FullRow = styled(Row)` height: 100%; margin: 0; padding: 0; `; export const Column = styled(Col)` `; export const ColumnBlack = styled(Col)` background: #000; display: flex; align-items: center; justify-content: center; `; const Panel = styled.div` display: flex; align-items: center; justify-content: center; flex-direction: column; //height: 50vh; background: transparent; width: 100%; `; const Inner = styled.div` display: flex; align-items: center; justify-content: center; flex-direction: column; height: 40vh; background: rgba(255,255,255,0.75); width: 100%; `; const Paragraph = styled.p` text-align: center; padding: 0 25%; font-size: 38px; //font-weight: 600; ${props => props.theme.breakpoints.maxTablet} { font-size: 18px; text-align: justify; padding: 0 5%; } `; const MainIntro = styled.h1` font-family: ${props => props.theme.fonts.openSansSemiBold}; font-weight: 800; font-size: 58px; color: black; padding: 0 12px; margin: 0; text-shadow: 4px 4px #fff; > span { color: #ffffff; text-shadow: 4px 4px #000; } ${props => props.theme.breakpoints.maxTablet} { font-size: 20px; } `; const Button = styled(Link)` display: inline-block; padding: 0.7em 1.7em; margin: 18px 0.3em 0.3em 0; border-radius: 0.2em; box-sizing: border-box; text-decoration: none; font-family: 'Roboto',sans-serif; font-weight: 400; color: #FFFFFF; background-color: #3369ff; box-shadow: inset 0 -0.6em 1em -0.35em rgba(0,0,0,0.17),inset 0 0.6em 2em -0.3em rgba(255,255,255,0.15),inset 0 0 0em 0.05em rgba(255,255,255,0.12); text-align: center; position: relative; cursor: pointer; ${props => props.theme.breakpoints.maxTablet} { margin: 0.3em 1.5em; } `; class Home extends PureComponent { constructor(props){ super(props); this.state = { user: '', }; } async componentDidMount() { } render() { return ( <FullRow> <ColumnBlack xs={12}> <Video autoPlay controls={[]} style={{width: '100%', margin: '0'}} poster="http://sourceposter.jpg" onCanPlayThrough={() => { // Do stuff }}> <source src={Logo} type="video/webm" /> </Video> </ColumnBlack> <Column center='xs' xs={12} > <Panel> <Inner> <MainIntro>STEP 1: IMPORTANT NOTICE</MainIntro> <Paragraph> ****IMPORTANT: WHEN YOU COMPLETE THE FORM, PLEASE CHECK YOUR EMAIL ASAP! THE EMAIL SUBJECT WILL BE, 'MILLENNIALS SIGN UP, PLEASE CONFIRM THE SUBSCRIPTION'. MAKE SURE TO CLICK CONFIRM!!! </Paragraph> </Inner> </Panel> </Column> <ColumnBlack center='xs' xs={12} > <Panel> <Inner> <MainIntro>STEP 2: FILL OUT THE CREATOR FORM</MainIntro> <Paragraph> Millenials is an active online community curated to help creators of any type be better versions of themselves. It was created to expand our limits as creators, help push each other, share techniques, receive honest feedback on projects, network and a space for people to collaborate with each other. </Paragraph> </Inner> <Button to='/signup' style={{backgroundColor:'#000'}}> <span style={{fontSize: '3em', fontFamily:'Comic Sans MS', borderRight: '1px solid rgba(255,255,255,0.5)', paddingRight:'0.3em', marginRight: '0.3em', verticalAlign: 'middle'}}>M</span> Join Millennials form </Button> </Panel> </ColumnBlack> </FullRow> ); } } export default Home;
import React, { Component } from 'react' import { Card, Button, Form, Col, InputGroup } from 'react-bootstrap'; import {UtilityFunctions as UF} from '../../Common/Util'; import SSM from '../../Common/SimpleStateManager'; import Wrap from '../../Common/Wrap'; import './SellerPage.css'; import SimpleMessageModal from '../SimpleMessageModal/SimpleMessageModal'; import BE from '../../Common/comm'; export default class ItemForm extends Component { constructor(props){ super(props); this.backToManagerCB = props.backToManagerCB; this.submitCB = props.submitCB; this.state = { form:{ isValid:false, }, mName:props.data ? props.data.Name : "" , mId: props.data ? props.data.Id : "", mCategory: props.data ? props.data.Category : "", mDescription: props.data ? props.data.Description : "", mImgLink: props.data? props.data.ImgLink : "", mPrice: props.data? props.data.Price : "", mUnit: props.data? props.data.Unit :"" } } renderItemCreationForm(){ let validated = this.state.form.isValid; let ele = <div className="bodyDiv"> <div className="bodyContent"> <Form className="createShopForm" noValidate validated={validated} onSubmit={this.handleSubmit}> <Form.Row> <Form.Group controlId="validationCustom01"> <Form.Label>Item Name</Form.Label> <Form.Control required type="text" placeholder="myItem" name="mName" value = {this.state.mName} onChange = {this.handleInputChange.bind(this)} /> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> </Form.Group> </Form.Row> <Form.Row> <Form.Group controlId="validationCustom02"> <Form.Label>Id</Form.Label> <Form.Control required type="number" placeholder="" name="mId" value = {this.state.mId} onChange = {this.handleInputChange.bind(this)} /> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> </Form.Group> </Form.Row> <Form.Row> <Form.Group controlId="validationCustom02"> <Form.Label>Category</Form.Label> <Form.Control required type="text" placeholder="Books" name="mCategory" value = {this.state.mCategory} onChange = {this.handleInputChange.bind(this)} /> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> </Form.Group> </Form.Row> <Form.Row> <Form.Group controlId="validationCustomUsername"> <Form.Label>Image Link</Form.Label> <InputGroup> <InputGroup.Prepend> <InputGroup.Text id="inputGroupPrepend">@</InputGroup.Text> </InputGroup.Prepend> <Form.Control type="text" placeholder="Image URL" aria-describedby="inputGroupPrepend" required name="mImgLink" value = {this.state.mImgLink} onChange = {this.handleInputChange.bind(this)} /> <Form.Control.Feedback type="invalid"> This link is already taken. </Form.Control.Feedback> </InputGroup> </Form.Group> </Form.Row> <Form.Row> <Form.Group controlId="ItemDescription"> <Form.Label>Item Description</Form.Label> <Form.Control as="textarea" rows="3" name="mDescription" value = {this.state.mDescription} onChange = {this.handleInputChange.bind(this)} /> </Form.Group> <Form.Group controlId="validationCustom02"> <Form.Label>Price</Form.Label> <Form.Control required type="number" placeholder="" name="mPrice" value = {this.state.mPrice} onChange = {this.handleInputChange.bind(this)} /> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> </Form.Group> </Form.Row> <Form.Row> <Form.Group controlId="validationCustom02"> <Form.Label>Unit</Form.Label> <Form.Control required type="text" placeholder="" name="mUnit" value = {this.state.mUnit} onChange = {this.handleInputChange.bind(this)} /> <Form.Control.Feedback>Looks good!</Form.Control.Feedback> </Form.Group> </Form.Row> <Form.Row> <Form.Group> <Button type="submit">Submit form</Button> <Button type="button" variant="secondary" onClick={()=>this.backToManagerCB()}>Back</Button> </Form.Group> </Form.Row> </Form> </div> </div> return ele; } handleSubmit = (event) => { const form = event.currentTarget; event.preventDefault(); event.stopPropagation(); if (form.checkValidity() === false) { console.log("Invalid form , handle "+ form.checkValidity()) }else{ this.setValidated(true); let items = { Name: this.state.mName, Id : this.state.mId, Category: this.state.mCategory, Description: this.state.mDescription, ImgLink: this.state.mImgLink, Price: this.state.mPrice, Unit: this.state.mUnit } this.submitCB(items); this.backToManagerCB(); } }; setValidated(isValidated){ this.setState({ form:{ isValid:isValidated } }) } handleInputChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; this.setState({ [name]: value }); } render() { return ( <Wrap> {this.renderItemCreationForm()} </Wrap> ) } }
import React, { Component } from "react"; import { Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap"; import "./Login.css"; import Main from '../Main'; import Header from '../Login/Header' import { GoogleLogin } from 'react-google-login'; import LogoDC3 from 'assets/images/dc3_logo.jpg'; import About from "../Login/About"; //https://medium.com/@alexanderleon/implement-social-authentication-with-react-restful-api-9b44f4714fa export default class Login extends Component { constructor(props) { super(props); if (sessionStorage.getItem('userAuth')) { var userObj = JSON.parse(sessionStorage.getItem('userAuth')); var token = JSON.parse(sessionStorage.getItem('userAuthToken')); this.state = { email: userObj.Email, password: "", isAuthenticated: true, user: userObj, token: token }; } else { this.state = { email: "", password: "", isAuthenticated: false, user: null, token: '' }; } }; logout = () => { this.setState({ isAuthenticated: false, token: '', user: null }) }; googleResponse = (response) => { sessionStorage.setItem('googleAuth', JSON.stringify(response)); const tokenBlob = new Blob([JSON.stringify({ access_token: response.accessToken }, null, 2)], { type: 'application/json' }); const options = { method: 'POST', body: tokenBlob, mode: 'cors', cache: 'default' }; //send the request to back-end, get the token fetch('http://localhost:8000/auth/google', options).then(resp => { if (resp.status < 400) { const token = resp.headers.get('x-auth-token'); resp.json().then(user => { if (token) { sessionStorage.setItem('userAuth',JSON.stringify(user)); sessionStorage.setItem('userAuthToken',JSON.stringify(token)); this.setState({ isAuthenticated: true, user, token }); } }); } }); }; validateForm() { return this.state.email.length > 0 && this.state.password.length > 0; } handleChange = event => { this.setState({ [event.target.id]: event.target.value }); } render() { let content = this.state.isAuthenticated ? ( <div> <Main userInfo={this.state.user} logout={this.logout}/> </div> ) : ( <div className="Login"> <Header /> <img src={LogoDC3} className="logo" pullright /> <GoogleLogin clientId="204559914410-83fsef9pb97suhi6o550uqeo2utb8591.apps.googleusercontent.com" buttonText="Login with Google" onSuccess={this.googleResponse} onFailure={this.googleResponse} /> <About /> </div> ); return ( <div> {content} </div> ); } }
'use strict'; // Use local.env.js for environment variables that grunt will set when the server starts locally. // Use for your api keys, secrets, etc. This file should not be tracked by git. // // You will need to set these on the server you deploy to. module.exports = { CLIENT_ID: 'put your instagram client id here', CLIENT_SECRET: 'put your instagram client secret here', domain: 'put your development domain here - (example http://localhost:9000)' };
function onSendMsg() { if (!selToID) { alert("您还没有好友,暂不能聊天"); $("#send_msg_text").val(''); return; } //获取消息内容 var msgtosend = document.getElementsByClassName("msgedit")[0].value; var msgLen = webim.Tool.getStrBytes(msgtosend); if (msgtosend.length < 1) { alert("发送的消息不能为空!"); $("#send_msg_text").val(''); return; } var maxLen, errInfo; if (selType == SessionType.C2C) { maxLen = MaxMsgLen.C2C; errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)"; } else { maxLen = MaxMsgLen.GROUP; errInfo = "消息长度超出限制(最多" + Math.round(maxLen / 3) + "汉字)"; } if (msgLen > maxLen) { alert(errInfo); return; } if (!selSess) { selSess = new webim.Session(selType, selToID, selToID, friendHeadUrl, Math.round(new Date().getTime() / 1000)); } var msg = new webim.Msg(selSess, true); //解析文本和表情 var expr = /\[[^[\]]{1,3}\]/mg; var emotions = msgtosend.match(expr); if (!emotions || emotions.length < 1) { var text_obj = new webim.Msg.Elem.Text(msgtosend); msg.addText(text_obj); } else { for (var i = 0; i < emotions.length; i++) { var tmsg = msgtosend.substring(0, msgtosend.indexOf(emotions[i])); if (tmsg) { var text_obj = new webim.Msg.Elem.Text(tmsg); msg.addText(text_obj); } var emotion = webim.EmotionPicData[emotions[i]]; if (emotion) { var face_obj = new webim.Msg.Elem.Face( webim.EmotionPicDataIndex[emotions[i]], emotions[i]); msg.addFace(face_obj); } else { var text_obj = new webim.Msg.Elem.Text(emotions[i]); msg.addText(text_obj); } var restMsgIndex = msgtosend.indexOf(emotions[i]) + emotions[i].length; msgtosend = msgtosend.substring(restMsgIndex); } if (msgtosend) { var text_obj = new webim.Msg.Elem.Text(msgtosend); msg.addText(text_obj); } } webim.sendMsg(msg, function (resp) { addMsg(msg); curMsgCount++; $("#send_msg_text").val(''); turnoffFaces_box(); }, function (err) { alert(err.ErrorInfo); $("#send_msg_text").val(''); }); }
import './DivRight.css'; import React from 'react'; export default () => { return ( <div className='div-right'> <p class="open">Czynne pon.- pt. i niedz. 12-22, sob. 12-23 </p> <p>Dowóz na terenie Żagania gratis</p> </div> ) }
import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import store from '@/web-client/stores'; import history from '@/web-client/history'; import router from '@/web-client/router'; import '@/web-client/styles/base.css'; const render = async (location) => { const element = await router(location.pathname); ReactDOM.render( <Provider store={store}> {element} </Provider>, document.getElementById('App'), ); }; render(history.location); history.listen(render);
var DB = 1; exports.PATTERNS = [ ["GET", /^\/nihongo\/key\/(.*)$/, function(transaction, key) { transaction.redis.multi() .SELECT(DB) .LRANGE("key:" + decodeURIComponent(key), 0, -1) .exec(transaction.rwrap(function(results) { var m = transaction.redis.multi(); results[1].forEach(function(seq) { m.GET("entry:" + seq); }); m.exec(transaction.rwrap(function(results_) { transaction.serve_data(200, "text/plain", entries_list(results_.map(JSON.parse))); })); })); }] ] var LANG = { eng: "en", fre: "fr", ger: "de", rus: "ru" }; function entries_list(entries) { return $ol({ "class": "word" }, entries.map(function(entry) { return $li( $ul({ "class": "reading", lang: "ja" }, entry.kanji.map(function(k) { return $li($span({ "class": k[1] ? "primary" : false }, k[0])); }).join(""), entry.reading.map(function(r) { return $li($span({ "class": r[1] ? "primary" : false }, r[0])); }).join("")), $ol( entry.sense.map(function(sense) { return $li(sense.hasOwnProperty("pos") ? $span({ "class": "pos" }, sense.pos.join(", ")) : "", Object.keys(sense.gloss).map(function(lang) { var glosses = sense.gloss[lang]; return glosses.map(function(gloss) { return $span({ lang: LANG[lang] }, gloss) }).join("; "); }).join("; ")); }).join(""))); })); }
// TODO: remove when merging into get_smart require('vendor/i18n'); require('vendor/i18n_js_extension'); const moment = require('moment'); const I18n = window.I18n; I18n.translations = I18n.translations || {}; const canLolcalize = (process.env.NODE_ENV !== 'production' || window.DEPLOY_ENV === 'edge'); if (canLolcalize) { // don't add the extra overhead in prod const lolcalize = require('I18n.lolcalize.js'); // so that it's a valid locale I18n.translations.lol = I18n.translations.lol || {locales: {lol: '! LOL !'}}; const lookup = I18n.lookup.bind(I18n); I18n.lookup = function(scope, options) { var messages = lookup(scope, options); if (!lolcalize.isEnabled()) return messages; if (!options || options.locale !== 'en') return messages; // only lolcalize on the second lookup (fallback to en) return lolcalize(messages); }; } I18n.pluralize = function(count, scope, options) { var translation; try { translation = this.lookup(scope, options); } catch (error) { //don't blow chunk } if (!translation) { return this.missingTranslation(scope); } var message; options = this.prepareOptions(options, {precision: 0}); options.count = this.toNumber(count, options); var pluralizer = this.pluralizer(this.currentLocale()); var key = pluralizer(Math.abs(count)); var keys = ((typeof key === "object") && (key instanceof Array)) ? key : [key]; message = this.findAndTranslateValidNode(keys, translation); if (message === null) message = this.missingTranslation(scope, keys[0]); return this.interpolate(message, options); }; // disable lookups during app boot / module definitions, cuz we shouldn't // be doing that; always be translating at runtime const frdLookup = I18n.lookup; if (window.PREVENT_PREMATURE_I18N_LOOKUPS) { I18n.lookup = () => { throw new Error('Don\'t call I18n.t in a module definition (boot time), put it in a function (run time) so it actually gets translated'); }; } const momentLocaleMap = {'pt-BR': 'pt-br', 'zh': 'zh-cn'}; I18n.setLocale = function(locale) { I18n.locale = locale; moment.locale([momentLocaleMap[locale] || locale, 'en']); }; I18n.fallbacks = true; I18n.enableLookups = function() { I18n.lookup = frdLookup; }; // react-i18nliner preprocesses <Text> into this I18n.ComponentInterpolator = require('react-i18nliner/ComponentInterpolator'); I18n.l = I18n.localize = () => { return 'Use moment.js instead of I18n.localize'; }; module.exports = I18n;
import React from 'react'; import NotificationBanner from 'src/components/NotificationBanner'; import TopBar from 'src/components/nav/TopBar'; const PageMini = ({ children }) => { return ( <div className='Page-mini'> {/* <NotificationBanner /> */} <TopBar /> <div className='page-mini-wrapper'> {children} </div> </div> ) } export default PageMini;