text
stringlengths
7
3.69M
import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import DisplayErrorsStyled from './DisplayErrorsStyled'; const DisplayErrors = ({ getErrorMessage, msg }) => { const handleClick = () => { getErrorMessage(false, []); }; return ( <DisplayErrorsStyled> <div className="form-error"> <h1 className="form-error-title">{(msg === 'jwt expired' || msg === 'invalid signature') ? '' : msg }</h1> {(msg === 'Email non reconnu') && ( <div className="form-error-message"> Merci de vérifier votre email ou de vous enregistrer <Link to="/register" className="form-error-message--link" onClick={handleClick}>ici</Link> </div> )} {(msg === 'Mauvais mot de passe') && ( <div className="form-error-message"> Vous l'avez oublié? Renouvelez le <Link to="/password" className="form-error-message--link" onClick={handleClick}>ici</Link> </div> )} {(msg === 'Mot de passe non valide' || msg === 'Les deux mots de passe sont différents') && ( <div className="form-error-message"> Merci de recommencer... </div> )} {(msg === 'Email déjà utilisé') && ( <div className="form-error-message"> Vous êtes déjà membre? Connectez-vous <Link to="/" className="form-error-message--link" onClick={handleClick}>ici</Link> </div> )} {(msg === 'invalid signature') && ( <div className="form-error-message"> Le lien de réinitialisation a déjà été utilisé </div> )} {(msg === 'jwt expired') && ( <div className="form-error-message"> Le lien de réinitialisation a expiré </div> )} </div> </DisplayErrorsStyled> ); }; DisplayErrors.propTypes = { msg: PropTypes.string.isRequired, getErrorMessage: PropTypes.func.isRequired, }; export default DisplayErrors;
import firebase from 'firebase' const config = { apiKey: 'AIzaSyDkBwk4y_0owfwnO5ojDvIYved6gOLzppc', authDomain: 'cspot-ify.firebaseapp.com', databaseURL: 'https://cspot-ify.firebaseio.com', projectId: 'cspot-ify', storageBucket: 'cspot-ify.appspot.com', messagingSenderId: '154842492597' } export const firebaseApp = firebase.initializeApp(config) export const binRef = firebaseApp.database().ref().child('bin') export const usersRef = firebaseApp.database().ref().child('users') export const plansRef = firebaseApp.database().ref().child('plans') export const songsRef = firebaseApp.database().ref().child('songs') export const typesRef = firebaseApp.database().ref().child('types') export const rolesRef = firebaseApp.database().ref().child('roles') export const itemsRef = firebaseApp.database().ref().child('items')
const express = require("express"); const connection = require("./db/connection"); require("console.table"); const inquirer = require("inquirer"); require("mysql"); require("mysql2"); // const callback = require("./db/callback"); const PORT = process.env.PORT || 3001; const app = express(); connection.connect((err) => { if (err) throw err; console.log("Database connected."); prompt(); }); // BEGIN PROMPT function prompt() { inquirer .prompt({ type: "list", message: "What would you like to do?", name: "startingChoice", choices: [ "View All Departments", "View All Roles", "View All Employees", "Add A Department", "Add New Roles", "Add An Employee" ], }) .then((answers) => { switch (answers.startingChoice) { case "View All Departments": viewAllDepartments(); break; case "View All Roles": viewAllRoles(); break; case "View All Employees": viewAllEmployees(); break; case "Add A Department": newDepartment(); break; case "Add New Roles": addNewRole(); break; case "Add An Employee": addNewEmployee(); break; } }); } //View all Departments function viewAllDepartments() { const sql = `SELECT * FROM departments`; connection.query(sql, (err, res) => { console.table(res); prompt(); }); } //View all Roles function viewAllRoles() { const sql = `SELECT * FROM roles`; connection.query(sql, (err, res) => { console.table(res); prompt(); }); } //View all Employees function viewAllEmployees() { const sql = `SELECT * FROM employees`; connection.query(sql, (err, res) => { console.table(res); prompt(); }); } //Add a Department function newDepartment() { inquirer .prompt([ { type: "input", name: "addDep", message: "What department would you like to add?", }, ]) .then((answer) => { const sql = `INSERT INTO departments (department_name) VALUES (?)`; connection.query(sql, answer.addDep, (err, result) => { if (err) throw err; viewAllDepartments(); }); }); } function addNewEmployee() { inquirer .prompt([ { type: "input", name: "new_first_name", message: "What is this employees first name?", }, { type: "input", name: "new_last_name", message: "What is this employees last name?", }, { type:"input", name:"new_job_title", message:"What is this employees job title?" }, { type: "input", name: "employeeRole", message: "What role ID does this employee have?", }, { type: "input", name: "employeeManager", message: "Who is this employees manager?", }, ]) .then((answers) => { const sql = `INSERT INTO employees (first_name, last_name, job_title, roles_id, manager_id) VALUES (?,?,?,?,?)`; const params = [ answers.new_first_name, answers.new_last_name, answers.new_job_title, answers.employeeRole, answers.employeeManager ]; connection.query(sql, params, (err, rows) => { if (err) { throw err; } viewAllEmployees(); console.table(rows); prompt(); }) }); } function addNewRole() { inquirer .prompt([ { type: "input", name: "new_title", message: "What is this new role?", }, { type: "input", name: "new_salary", message: "What is this roles salary?", }, { type:"input", name:"new_department_ID", message:"What is this roles department ID?" } ]) .then((answers) => { const sql = `INSERT INTO roles (title, salary, department_id) VALUES (?,?,?)`; const params = [ answers.new_title, answers.new_salary, answers.new_department_ID ]; connection.query(sql, params, (err, rows) => { if (err) { throw err; } viewAllRoles(); console.table(rows); prompt(); }) }); }
import React, { Component } from 'react'; import { View, Button, StyleSheet } from 'react-native'; export default class LikeBar extends Component { displayBtn = (name) => { alert(name); } render() { return ( <View style={styles.controlContainer} > <View style={styles.controlBar}> <Button title="Like" color="#797D7F" onPress={() => this.displayBtn('Like')}/> <Button title="Comment" color="#797D7F" onPress={() => this.displayBtn('Comment')} /> <Button title="Share" color="#797D7F" style={{color: 'red'}} onPress={() => this.displayBtn('Share')}/> </View> </View> ); } }; const styles = StyleSheet.create({ controlContainer: { width: '100%', height: '7%', backgroundColor: 'whitesmoke', justifyContent: 'center', alignItems: 'center', borderBottomColor: 'black', borderBottomWidth: 2 }, controlBar: { width: '70%', height: '70%', display: 'flex', flexDirection: 'row', alignItems: 'stretch', justifyContent: 'space-around', } });
import React from 'react'; import { slide as Menu } from 'react-burger-menu'; import SideItem from './side-item' import SideNav from 'react-simple-sidenav'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' export default props => { return ( <Menu> <a className="menu-item" href="/"> Home </a> <a className="menu-item" href="/cities"> Cities </a> <a className="menu-item" href="/news"> News </a> <a className="menu-item" href="/videos"> Videos </a> <a className="menu-item" href="/sign-in"> Sign-in </a> <a className="menu-item" href="/sign-out"> Sign-out </a> <a className="menu-item" href="/node"> Contact </a> </Menu> ); }; // const Side =(props)=>{ // return ( // <div> // <SideNav // showNavBar={props.showNavBar} // onHideNav={props.onHideNav} // navStyle={{ // background:'#242424', // maxWidth:'220px' // }} // > // OPTIONS // <SideItem> </SideItem> // </SideNav> // </div> // ) // } // export default Side
/* |-------------------------------------------------------------------------- | Utils |-------------------------------------------------------------------------- */ import path from 'path'; import fs from 'fs'; import mmd from 'musicmetadata'; import globby from 'globby'; import Promise from 'bluebird'; const musicmetadataAsync = Promise.promisify(mmd); /** * Parse an int to a more readable string * * @param int duration * @return string */ const parseDuration = (duration) => { if(duration !== null && duration !== undefined) { let hours = parseInt(duration / 3600); let minutes = parseInt(duration / 60) % 60; let seconds = parseInt(duration % 60); hours = hours < 10 ? `0${hours}` : hours; minutes = minutes < 10 ? `0${minutes}` : minutes; seconds = seconds < 10 ? `0${seconds}` : seconds; let result = hours > 0 ? `${hours}:` : ''; result += `${minutes}:${seconds}`; return result; } return '00:00'; }; /** * Format a list of tracks to a nice status * * @param array tracks * @return string */ const getStatus = (tracks) => { const status = parseDuration(tracks.map((d) => d.duration).reduce((a, b) => a + b, 0)); return `${tracks.length} tracks, ${status}`; }; /** * Parse an URI, encoding some characters * * @param string uri * @return string */ const parseUri = (uri) => { const root = process.platform === 'win32' ? '' : path.parse(uri).root; const location = uri .split(path.sep) .map((d, i) => { return i === 0 ? d : encodeURIComponent(d); }) .reduce((a, b) => path.join(a, b)); return `file://${root}${location}`; }; /** * Parse data to be used by img/background-image with base64 * * @param string format of the image * @param string data base64 string * @return string */ const parseBase64 = (format, data) => { return `data:image/${format};base64,${data}`; }; /** * Sort an array of int by ASC or DESC, then remove all duplicates * * @param array array of int to be sorted * @param string 'asc' or 'desc' depending of the sort needed * @return array */ const simpleSort = (array, sorting) => { if(sorting === 'asc') { array.sort((a, b) => { return a - b; }); } else if (sorting === 'desc') { array.sort((a, b) => { return b - a; }); } const result = []; array.forEach((item) => { if(!result.includes(item)) result.push(item); }); return result; }; /** * Strip accent from String. From https://jsperf.com/strip-accents * * @param String str * @return String */ const stripAccents = (str) => { const accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž'; const fixes = 'AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz'; const split = accents.split('').join('|'); const reg = new RegExp(`(${split})`, 'g'); function replacement(a) { return fixes[accents.indexOf(a)] || ''; } return str.replace(reg, replacement).toLowerCase(); }; /** * Remove duplicates (realpath) and useless children folders * * @param array the array of folders path * @return array */ const removeUselessFolders = (folders) => { // Remove duplicates let filteredFolders = folders.filter((elem, index) => { return folders.indexOf(elem) === index; }); const foldersToBeRemoved = []; filteredFolders.forEach((folder, i) => { filteredFolders.forEach((subfolder, j) => { if(subfolder.includes(folder) && i !== j && !foldersToBeRemoved.includes(folder)) { foldersToBeRemoved.push(subfolder); } }); }); filteredFolders = filteredFolders.filter((elem) => { return !foldersToBeRemoved.includes(elem); }); return filteredFolders; }; /** * Cut an array in smaller chunks * * @param array the array to be chunked * @param int the length of each chunk * @return array */ const chunkArray = (array, chunkLength) => { const chunks = []; for(let i = 0, length = array.length; i < length; i += chunkLength) { chunks.push(array.slice(i, i + chunkLength)); } return chunks; }; const getDefaultMetadata = () => { return { album : 'Unknown', albumartist : [], artist : ['Unknown artist'], disk : { no: 0, of: 0, }, duration : 0, genre : [], loweredMetas : {}, path : '', playCount : 0, title : '', track : { no: 0, of: 0, }, year : '', }; }; const getLoweredMeta = (metadata) => { return { artist : metadata.artist.map((meta) => stripAccents(meta.toLowerCase())), album : stripAccents(metadata.album.toLowerCase()), albumartist : metadata.albumartist.map((meta) => stripAccents(meta.toLowerCase())), title : stripAccents(metadata.title.toLowerCase()), genre : metadata.genre.map((meta) => stripAccents(meta.toLowerCase())), }; }; const getWavMetadata = async (track) => { const defaultMetadata = getDefaultMetadata(); let audioDuration = 0; try { audioDuration = await getAudioDurationAsync(track); } catch (err) { console.warn(err); audioDuration = 0; } const metadata = { ...defaultMetadata, duration: audioDuration, path : track, title : path.parse(track).base, }; metadata.loweredMetas = getLoweredMeta(metadata); return metadata; }; const getMusicMetadata = async (track) => { const defaultMetadata = getDefaultMetadata(); let data; try { const stream = fs.createReadStream(track); data = await musicmetadataAsync(stream, { duration: true }); delete data.picture; stream.close(); } catch (err) { data = defaultMetadata; console.warn(`An error occured while reading ${track} id3 tags: ${err}`); } const metadata = { ...defaultMetadata, ...data, album : data.album === null || data.album === '' ? 'Unknown' : data.album, artist : data.artist.length === 0 ? ['Unknown artist'] : data.artist, duration : data.duration === '' ? 0 : data.duration, path : track, title : data.title === null || data.title === '' ? path.parse(track).base : data.title, }; metadata.loweredMetas = getLoweredMeta(metadata); if (metadata.duration === 0) { try { metadata.duration = await getAudioDurationAsync(track); } catch (err) { console.warn(`An error occured while getting ${track} duration: ${err}`); } } return metadata; }; /** * Get a file metadata * * @param path (string) * @return object * */ const getMetadata = async (track) => { // metadata should have the same shape as getDefaultMetadata() object const wavFile = path.extname(track).toLowerCase() === '.wav'; const metadata = wavFile ? await getWavMetadata(track) : await getMusicMetadata(track); return metadata; }; const getAudioDurationAsync = (path) => { const audio = new Audio; return new Promise((resolve, reject) => { audio.addEventListener('loadedmetadata', () => { resolve(audio.duration); }); audio.addEventListener('error', (e) => { const message = `Error getting audio duration: (${e.target.error.code}) ${path}`; reject(new Error(message)); }); audio.preload = 'metadata'; audio.src = path; }); }; const fetchCover = async (trackPath) => { if(!trackPath) { return null; } const stream = fs.createReadStream(trackPath); const data = await musicmetadataAsync(stream); if(data.picture[0]) { // If cover in id3 return parseBase64(data.picture[0].format, data.picture[0].data.toString('base64')); } // scan folder for any cover image const folder = path.dirname(trackPath); const pattern = path.join(folder, '*'); const matches = await globby(pattern, { nodir: true, follow: false }); return matches.find((elem) => { const parsedPath = path.parse(elem); return ['album', 'albumart', 'folder', 'cover'].includes(parsedPath.name.toLowerCase()) && ['.png', '.jpg', '.bmp', '.gif'].includes(parsedPath.ext.toLowerCase()) ; }); }; export default { parseDuration, getStatus, parseUri, simpleSort, stripAccents, removeUselessFolders, chunkArray, getMetadata, fetchCover, };
/*var html = "Сайн уу "; html = html.replace("уу", " байна уу "); console.log(html); var a = "<p>Сайн уу </p>"; html1 = a.replace("p", " strong"); console.log(html1); var b = "<el>Сайн уу </el>"; html = b.replace(/el/gi, " emmat"); console.log(html); */ var incDiv = document.querySelector(".income"); incDiv.insertAdjacentHTML("beforeend", "Цалин : 2500000"); incDiv.insertAdjacentHTML("beforeend", "<br>Сугалаа : 15000000"); incDiv.insertAdjacentHTML("beforeend", "<br>сугалаа : 15000000");
$(function () { $('#lbl_btn_new').click(function () { $('#site-map').hide(); $('#tab-body').show(); $('.main-display').show(); $('.main-sheet').resizable(); }); }); $(function () { $('#add_card').click(function () { $('#rotate-div').show(); }); });
import { h, Component } from 'preact'; import axios from 'axios'; import TimeAgo from 'javascript-time-ago'; import en from 'javascript-time-ago/locale/en'; import Rheostat from 'preact-rheostat'; import './rheostat.css'; import Select from 'preact-material-components/Select'; import 'preact-material-components/List/style.css'; import 'preact-material-components/Menu/style.css'; import 'preact-material-components/Select/style.css'; import TextField from 'preact-material-components/TextField'; import 'preact-material-components/TextField/style.css'; import Coin from './coin'; import style from './style'; TimeAgo.locale(en); const timeAgo = new TimeAgo('en-AU'); const timeAgoStyle = { units: ['second', 'minute', 'hour', 'day'] }; export default class Home extends Component { constructor (props) { super(props); this.state = { coins: [], minCoinRank: 1, maxCoinRank: 200, comparisons: [], chosenComparison: 0, comparison: {}, loadingComparison: false, search: '' }; } componentDidMount() { axios.get(`./db/db.json`) .then(res => { this.setState({ coins: res.data.latest.coins, maxScore: res.data.latest.coins[0].totalScore, lastUpdated: res.data.latest.date, comparisons: res.data.dates }); }) .catch(err => console.error(new Error('Couldn\'t get JSON'))); } updateComparison = (date) => { axios.get(`./db/db-${date}.json`) .then(res => { this.setState({ comparison: res.data.latest, loadingComparison: false }); }) .catch(err => console.error(new Error('Couldn\'t get comparison'))); } getCoinComparison = (coin) => { if (this.state.comparison.hasOwnProperty('coins')) { const filtered = this.state.comparison.coins.filter((cCoin) => cCoin.id === coin.id); return filtered.length ? filtered[0] : null; } else { return null; } } handleSliderUpdate = (data) => { this.setState({ minCoinRank: data.values[0], maxCoinRank: data.values[1] }); } handleCompareChange = (e) => { const comparison = this.state.comparisons[e.selectedIndex-1]; if (typeof comparison === 'object' && comparison.hasOwnProperty('date')) { this.updateComparison(this.state.comparisons[e.selectedIndex-1].date); this.setState({ chosenComparison: e.selectedIndex, loadingComparison: true }); } else { this.setState({ comparison: {}, chosenComparison: e.selectedIndex }); } } handleSearchUpdate = (e) => { this.setState({ search: e.target.value }); } renderCoins = () => this.state.coins.map(coin => { // Rank if (coin.rank >= this.state.minCoinRank && coin.rank <= this.state.maxCoinRank) { // Search let search = this.state.search.toUpperCase(); let name = coin.name.toUpperCase(); let symbol = coin.symbol.toUpperCase(); if (search === '' || name.indexOf(search) >= 0 || symbol.indexOf(search) >= 0) { return <Coin coin={coin} comparison={this.getCoinComparison(coin)} percent={coin.totalScore / this.state.maxScore * 100} />; } } }); renderComparisonOptions = () => { return this.state.comparisons.map(comparison => <Select.Item>{timeAgo.format(parseInt(comparison.date, 10), timeAgoStyle)}</Select.Item>) } render(props, state) { return ( <div class={style.home}> <h1>Top CryptoCurrencies by Reddit Mentions</h1> <p style={{margin: '-8px 0 20px', fontStyle: 'italic'}}>Last updated {timeAgo.format(parseInt(state.lastUpdated, 10), timeAgoStyle)}</p> <div class={style.controls}> <div class={style.control}> <label class={style.label}>Filter</label> <TextField value={state.search} placeholder="Search..." onInput={this.handleSearchUpdate} /> </div> <div class={style.control}> <label class={style.label}>Compare to previous runs {state.loadingComparison && `(loading...)`}</label> <Select _hintText="Compare with" selectedIndex={state.chosenComparison} onChange={this.handleCompareChange} > <Select.Item>None</Select.Item> {this.renderComparisonOptions()} </Select> </div> <div class={style.control}> <label class={style.label}>Include coins ranked: {state.minCoinRank} - {state.maxCoinRank}</label> <Rheostat min={1} max={200} values={[state.minCoinRank, state.maxCoinRank]} snap onValuesUpdated={this.handleSliderUpdate} /> </div> </div> {this.renderCoins()} </div> ); } }
import { Typography } from "@material-ui/core"; import React from "react"; function MyTypography(props) { return ( <Typography variant="h3" {...props}> {props.children} </Typography> ); } export default MyTypography;
let path = require('path') let webpack = require('webpack') let ExtractTextPlugin = require('extract-text-webpack-plugin') const join = (dest) => { return path.resolve(__dirname, dest) } let config = module.exports = { entry: { application: [ join('web/static/css/application.scss'), join('web/static/js/application.js') ] }, output: { path: join('priv/static'), filename: 'js/application.js' }, debug: true, devtool: 'source-map', resolve: { extensions: ['', '.js', '.scss'], modulesDirectories: ['node_modules'] }, module: { noParse: /vendor\/phoenix/, loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { cacheDirectory: true, plugins: ['transform-decorators-legacy'], presets: ['react', 'es2015', 'stage-2', 'stage-0'] } }, { test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css!sass?includePaths[]=' + __dirname + '/node_modules') } ] }, plugins: [ new ExtractTextPlugin('css/application.css') ] }
import fs from './fs' import pify from 'pify' export async function rm (filepath) { try { await pify(fs().unlink)(filepath) } catch (err) { if (err.code !== 'ENOENT') throw err } }
var Tree = function(value) { var newTree = {}; newTree.value = value; // your code here _.extend(newTree, treeMethods); newTree.children = null; // fix me newTree.parent = null; return newTree; }; var treeMethods = {}; treeMethods.addChild = function(value) { this.children = this.children === null ? [] : this.children; var newChild = new Tree(value); this.children.push(newChild); newChild.parent = this; }; treeMethods.contains = function(target) { if (this.children) { for (var i = 0; i < this.children.length; i++) { //if children node value matches target, exit function and return true if (this.children[i].contains(target)) { return true; } } } //base case: compare current node to target return target === this.value; }; treeMethods.removeFromParent = function(value) { if (this.value === value) { var parent = this.parent; this.parent = null; for (var i = 0; i < parent.children.length; i++) { var child = parent.children[i]; if (child.value === value) { parent.children.splice(i, 1); //set children to null if removing value leaves no children if (parent.children.length === 0) { parent.children = null; } } } //return value removed return this.value; } else if (this.children) { for (var i = 0; i < this.children.length; i++) { this.children[i].removeFromParent(value); } } else { return undefined; } }; /* * Complexity: What is the time complexity of the above functions? addChild: O(1) - constant time complexity; contains: O(n) - linear time complexity. Has to search through the tree. */
const common = require('./common'); module.exports = { ...common, globals: { NODE_ENV: 'test', TEST_ENV: 'browser' }, testEnvironment: 'jsdom', resolver: '<rootDir>/jest/resolver.js' };
/** * Created by alex on 22.10.2015. */ class Type { constructor (name, size = null, def = null) { this.name = name; this.size = size; this.def = def; } toSQL () { let typeStr = `${this.name}`; if (this.size) return `${typeStr}(${this.size})`; return typeStr; } } class Varchar extends Type { constructor (size, def) { super('VARCHAR', size, def); } } class Boolean extends Type { constructor (def) { super('TINYINT', 4, def); } } class Integer extends Type { constructor (size, def) { super('INT', size, def); } } class Date extends Type { constructor (def) { super('TIMESTAMP', null, def); } } export default { Varchar, Boolean, Integer, Date }
import * as types from "./constant" const initialState = { animals: [], loading: false, authen: false, login: "" }; const myReducer = (state = initialState,action) => { switch(action.type){ case types.AUTHENTICATION: return { ...state, authen: true }; case types.AUTHENTICATION_NO: return { ...state, authen: false }; case types.GET_ANIMAL_PENDING: return{ ...state, loading: true } case types.GET_ANIMAL_SUCCESS: return{ ...state, loading: false, animal: action.payload.animals, totalPages: action.payload.pagination.total_pages } case types.GET_ANIMAL_FAIL: return{ ...state, loading: false, error: action.payload, animal: [] } default: return state; } } export default myReducer;
import ComList from './container/ComList' import reducer from './reducer' export { ComList, reducer }
function handleAjax(data) { var status = data.status; switch(status) { case "begin": // This is invoked right before ajax request is sent. break; case "complete": // This is invoked right after ajax response is returned. break; case "success": // This is invoked right after successful processing of ajax response and update of HTML DOM. multiply(); divide(); break; } }
import placeholders from '../text/placeholders'; import getErrorMessage from './getErrorMessage'; export function get(key) { return (obj) => obj[key]; } export function equal(key, value) { return (obj) => obj[key] === value; } export function getField({ field: { value, error }, id, name, onChange, }) { return ({ id, name, value, placeholder: placeholders[id], errorMessage: getErrorMessage({ type: id, error }), onChange, }); }
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsSouthEast = { name: 'south_east', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 9h-2v6.59L5.41 4 4 5.41 15.59 17H9v2h10V9z"/></svg>` };
'use strict'; module.exports = { async getAllUsers() { return new Promise(function (resolve, reject) { db.query('SELECT * FROM tb_usuarios', function (err, result) { if (err) return reject(err); return resolve(result); }); }); }, async getUserByid(id) { return new Promise(function (resolve, reject) { db.query('SELECT * FROM tb_usuarios WHERE id = ?', [id], function (err, result) { if (err) return reject(err); return resolve(result); }); }); }, async getUserByLoginAndPass(login,pass) { return new Promise(function (resolve, reject) { db.query('SELECT * FROM tb_usuarios WHERE login = ? AND senha = ?', [login, pass], function (err, result) { if (err) return reject(err); return resolve(result); }); }); }, async getUserbyOffset(limit, offset) { return new Promise(function (resolve, reject) { db.query('SELECT * FROM tb_usuarios LIMIT ? OFFSET ?', [limit, offset], function (err, result) { if (err) return reject(err); return resolve(result); }); }); }, async newUser(login, password, email) { return new Promise(function (resolve, reject) { db.query("INSERT INTO tb_usuarios (login,senha,email) VALUES (?,?,?)", [login, password, email], function (err, result) { if (err) return reject(err); return resolve(result); }); }); }, async editUser(login, senha, email, id) { return new Promise(function (resolve, reject) { db.query('UPDATE tb_usuarios SET login = ?, senha = ?, email = ? WHERE id = ?', [login, senha, email, id], function (err, result) { if (err) return reject(err); return resolve(result); }); }); }, async deleteUser(id) { return new Promise(function (resolve, reject) { db.query('DELETE FROM tb_usuarios WHERE ID = ?', [id], function (err, result) { if (err) return reject(err); return resolve(result); }); }); } }
import { IndividualItemMain } from './individual-item'; import { Link } from "react-router-dom"; //Código do item único do portifólio que receberá por parâmetro //a lista de itens da coleção 'Portifolio-item' export const PortifolioItemMain = ({ items }) => { return ( items.map((individualItem) => { //Map pela lista recebida por parâmetro if (individualItem.checkType === 'img1') { //Verificando se o tipo de página de descrição é o 1 return ( <Link to={"/portfolio-details-1/" + individualItem.ID} key={individualItem.ID}> <IndividualItemMain key={individualItem.ID} individualItemMain={individualItem} /> </Link> ) } else if (individualItem.checkType === 'img2') { //Verificando se o tipo de página de descrição é o 2 return ( <Link to={"/portfolio-details/" + individualItem.ID} key={individualItem.ID}> <IndividualItemMain key={individualItem.ID} individualItemMain={individualItem} /> </Link> ) } else if (individualItem.checkType === 'img3') { //Verificando se o tipo de página de descrição é o 3 return ( <Link to={"/portfolio-details-2/" + individualItem.ID} key={individualItem.ID}> <IndividualItemMain key={individualItem.ID} individualItemMain={individualItem} /> </Link> ) } } )) };
import React from "react"; import styles from "./Button.module.css"; const Button = () => { return <button className={styles.button}>CALL TO ACTION</button>; }; export default Button;
import axios from 'axios'; import { put, takeLatest } from 'redux-saga/effects'; import { ActionType, AllUsersAction } from '../actionTypes'; function* fetchAllUsers() { try { const response = yield axios.get('api/user/all'); yield put(AllUsersAction.set(response.data)); } catch (error) { console.log('Get all users request failed', error); } } function* userSaga() { yield takeLatest(ActionType.FETCH_ALL_USERS, fetchAllUsers); } export default userSaga;
var modules = [ [ "Device addresses", "group___device_addrs.html", "group___device_addrs" ], [ "General Constants", "group___general_constants.html", "group___general_constants" ], [ "Device settings", "group___device_settings.html", "group___device_settings" ], [ "Errors and warnings", "group___error_codes.html", "group___error_codes" ] ];
'use strict'; const extender = require(`object-extender`); const utilities = require(`../../modules/utilities`); /* * Allows all dependencies to be obtained on a single line. */ function prepareDependencies () { return { database: this.__dep(`database`), MessageObject: this.__dep(`MessageObject`), sharedLogger: this.__dep(`sharedLogger`), scheduler: this.__dep(`scheduler`), }; } /* * Updates the bot's memory with the result of the hook execution. */ async function updateBotMemory (hookResult, action, recUser) { // Do we need to remember the result? if (!action.memory || !recUser) { return; } // Update the bot's memory. try { await this.updateUserMemory(hookResult, action.memory, recUser, action.errorMessage); } catch (err) { throw new Error(`Failed to update memory after hook because of "${err}".`); } } /* * Do something useful with the error message coming from the hook. */ async function handleHookError (err, action, recUser, sharedLogger, MessageObject) { // If an error message has been specified lets send it to the user. if (action.errorMessage && recUser) { const newMessage = MessageObject.outgoing(recUser, { text: action.errorMessage }); await this.sendMessage(recUser, newMessage); } sharedLogger.error(err); } /* * Execute the hook specified in the action and wait for it to resolve. */ module.exports = async function __executeActionExecuteHook (action, recUser, message) { const hook = this.__getHook(action.hook); if (!hook) { throw new Error(`The hook "${action.hook}" has not been defined.`); } const hookFunc = hook.definition; if (typeof hookFunc !== `function`) { throw new Error(`The hook "${action.hook}" does not export a function.`); } const { database, MessageObject, sharedLogger, scheduler } = prepareDependencies.call(this); const actionCopy = extender.clone(action); const variables = this.prepareVariables(recUser); let finishMode = null; // All the items and methods that get made available to the hook. const resources = { database, MessageObject, sharedLogger, recUser, sendMessage: this.sendMessage.bind(this), scheduler, message, flows: this.flows, evaluateReferencedVariables: this.evaluateReferencedVariables.bind(this), evaluateConditional: this.evaluateConditional.bind(this), updateUserMemory: this.updateUserMemory.bind(this), doesTextMatch: this.doesTextMatch.bind(this), executeAnotherHook: this.executeAnotherHook.bind(this, recUser, message), delay: utilities.delay, trackUser: this.trackUser.bind(this), trackEvent: this.trackEvent.bind(this), handleCommandIfPresent: this.handleCommandIfPresent.bind(this), finishFlowAfterHook: () => finishMode = `after-hook`, changeFlow: nextUri => { finishMode = `immediately`; return this.__executeActionChangeFlow({ type: `change-flow`, nextUri }, recUser, message); }, }; // Attempt to execute the hook. try { const hookResult = await hookFunc(actionCopy, variables, resources); // If we changed flow or otherwise caused a break, then we don't do anything with the hook result and must stop. if (finishMode === `immediately`) { return false; } await updateBotMemory.call(this, hookResult, action, recUser); } catch (err) { handleHookError.call(this, err, action, recUser, sharedLogger, MessageObject); return false; } // Allow the flow to continue onto the next action as long as the hook didn't trigger a break. return (finishMode !== `after-hook`); };
// defino dato deltemperamento const {DataTypes}=require('sequelize'); module.exports=(sequelize)=>{ sequelize.define('temperament',{ //id se genera solo, sequelize por defecto lo genera solo name:{ type:DataTypes.STRING, allowNull:true }, },{ timestamps: false, }); };
import React from "react"; import AxiosGet from "./components/AxiosGet"; function App(){ return ( <div> <h1>Start React 2021!</h1> <AxiosGet /> </div> ); }; export default App;
showConstruction = false; showNodeConnections = true; var Curve = function() { this.timeKnot = new Knot(0,0,true); this.knots = new Array(); this.nodes = new Array(); }; Curve.prototype.draw = function(ctx) { if (showNodeConnections) { // Connect nodes with a line setColors(ctx,'rgb(10,70,160)'); for (var i = 1; i < this.nodes.length; i++) { drawLine(ctx, this.nodes[i-1].x, this.nodes[i-1].y, this.nodes[i].x, this.nodes[i].y); } // Draw nodes setColors(ctx,'rgb(10,70,160)','white'); for (var i = 0; i < this.nodes.length; i++) { this.nodes[i].draw(ctx); } } ctx.lineWidth = 2; setColors(ctx,'black'); // TODO: Draw the curve // you can use: drawLine(ctx, x1, y1, x2, y2); var steps = 100 * this.nodes.length; // degree of the polynom var k = 3; var bDB = false; if(this.nodes.length >= k) { // begin and end of the current part of the curve var curBeginX = null; var curBeginY = null; var curEndX = null; var curEndY = null; var dbcurBeginX = null; var dbcurBeginY = null; var dbcurEndX = null; var dbcurEndY = null; // get min and max for the t intervall var min = this.knots[k].value; var max = this.knots[this.nodes.length].value; // calc the first point var curPt = BSpline(this.nodes.length, k + 1, min, this.nodes, this.knots, false, ctx); curBeginX = curPt[0]; curBeginY = curPt[1]; if (this.nodes.length >= 4 && bDB) { var dbcurPt = deBoor(min, k, this.nodes, ctx, false); dbcurEndX = dbcurPt[0]; dbcurEndY = dbcurPt[1]; } // get the step length for uniform steps in the interval var stepLength = (max - min) / steps; for(var i = 0; i < steps; i++) { var factor = min + stepLength * i; var curPt = BSpline(this.nodes.length, k + 1, factor, this.nodes, this.knots); curEndX = curPt[0]; curEndY = curPt[1]; // draw the line setColors(ctx,'black'); drawLine(ctx, curBeginX, curBeginY, curEndX, curEndY); // set the new beginning curBeginX = curEndX; curBeginY = curEndY; if (this.nodes.length >= 4 && bDB) { var dbcurPt = deBoor(factor, k, this.nodes, ctx, false); dbcurEndX = dbcurPt[0]; dbcurEndY = dbcurPt[1]; // draw the line setColors(ctx,'green'); drawLine(ctx, dbcurBeginX, dbcurBeginY, dbcurEndX, dbcurEndY); // set the new beginning dbcurBeginX = dbcurEndX; dbcurBeginY = dbcurEndY; } } } ctx.lineWidth = 1; if (this.nodes.length >= 4) { // TODO: Show how the curve is constructed // you can use: drawLine(ctx, x1, y1, x2, y2); // you can use: drawCircle(ctx, x, y, radius); // De Boor construction if (showConstruction) { if(this.timeKnot.value < min) { BSpline(this.nodes.length, 4, min, this.nodes, this.knots, true, ctx); } else if (this.timeKnot.value > max) { BSpline(this.nodes.length, 4, max, this.nodes, this.knots, true, ctx); } else { deBoor(this.timeKnot.value, k, this.nodes, ctx, true); BSpline(this.nodes.length, 4, this.timeKnot.value, this.nodes, this.knots, true, ctx); } } } } Curve.prototype.addNode = function(x,y) { this.nodes.push(new Node(x,y)); if (this.knots.length == 0) { this.knots.push(new Knot(0,0,false)); this.knots.push(new Knot(1,1,false)); this.knots.push(new Knot(2,2,false)); this.knots.push(new Knot(3,3,false)); this.knots.push(new Knot(4,4,false)); } else { this.knots.push(new Knot(this.knots[this.knots.length-1].value+1,this.knots.length,false)); } }
import React, { useEffect, useState } from 'react'; import './App.css'; import logo from './logo.svg'; function App() { const heros = ['Sharukh Khan', 'Salman Khan', 'Irfan Khan', 'Amir Khan', 'Sakib Khan', 'Salman Khan'] const products = [ { name: 'Photoshop', price: '99.99' }, { name: 'Illustrator', price: '69.99' }, { name: 'PDF', price: '29.99' }, ] // const heroNames = heros.map(hero => hero); return (<div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 style={{ color: "" }}>I am a <code style={{ color: "green" }}>REACT</code> person</h1> <Counter> </Counter> <Users></Users> {/* <Product product={products[0]}></Product> <Product product={products[1]}></Product> <Product product={products[2]}></Product> */} <ul style={{ border: '2px solid red', width: '400px' }}> { heros.map(hero => <li>{hero}</li>) } </ul> <ol style={{ border: '2px solid white', width: '400px' }}> { products.map(product => <li>{product.name}</li>) } </ol> { heros.map(hero => <Person hero={hero}></Person>) } { products.map(pd => <Product product={pd}></Product>) } <Person hero="Sahrukh Khan" heroin="Rani Mukharji"></Person> <Person hero="Salman Khan" heroin="Katrina Kaif"></Person> <Person hero="Irfan Khan" heroin="Bhumika Chaula"></Person> <Person hero="Amir Khan" heroin="Awisharia Ray"></Person> </header> </div> ); } //set count function Counter() { const [count, setCount] = useState(10); const handleIncrease = () => setCount(count + 1); return ( <div> <h1>Count:{count} </h1> <button onClick={() => setCount(count - 1)}>Decrease</button> {/* <button onClick= { handleIncrease}>Increase</button> */} <button onClick={() => setCount(count + 1)}>Increase</button> </div> ) } // users function Users() { const [users, setUsers] = useState([]) useEffect(() => { fetch('https://jsonplaceholder.typicode.com/users') .then(res => res.json()) .then(data => setUsers(data)) }, []); return ( <div> <h2>Dynamic Users: {users.length}</h2> { users.map(user => <li>{user.name}g</li>) } </div> ) } // Hero Function function Person(props) { const personStyle = { border: "5px Solid Red", margin: "10px", borderRadius: '20px', width: "400px" } return ( <div style={personStyle}> <h1 style={{ color: 'tomato' }}> Hero: {props.hero}</h1> <h3> Hero of {props.heroin}</h3> </div> ) } // Products Function function Product(props) { const productStyle = { border: "5px Solid Red", margin: "10px", backgroundColor: 'Gray', borderRadius: '20px', width: '400px', height: '300px', float: 'left' } const { name, price } = props.product; return ( <div style={productStyle}> <h1>{name}</h1> <h2>{price}</h2> <button>Buy Now</button> </div> ) } export default App;
const userAuthController = require('../controller/userAuthController') var router = require('express').Router(); module.exports = function(){ const userCntrl = new userAuthController(); router.post('/register', userCntrl.signUp ); router.post('/authenticate', userCntrl.login); return router; }
(function(){ $(function(){ Route.getcoupon(function(data){ var str = template('txt',data); $('main ul').html(str); }) }) })();
import React,{Component}from 'react' import Person from './Person/Person' class Persons extends Component{ UNSAFE_componentWillMount(){ console.log("[Person.js] componentWillMount.") } componentDidMount(){ console.log("[Person.js] componentDidMount") } UNSAFE_componentWillReceiveProps(){ console.log("[Person.js] componentWillReceiveProps") } shouldComponentUpdate(nextProps,nextState){ console.log("[persons.js] shouldComponentUpdate") if(nextProps.persons !== this.props.persons){ return true }else{ return false } } componentDidUpdate(){ console.log("[Person.js] componentDidUpdate") } render(){ console.log('[persons.js] rendering....') return( this.props.persons.map( (person,index) => <Person name={person.name} age = {person.age} Delete = {() => this.props.Deleted(index)} key = {person.id} change = {(event) => this.props.changeName(event,person.id)}/> ) ) } } export default Persons
'use strict'; const React = require('react'); const { Component } = React; const PropTypes = require('prop-types'); const classnames = require('classnames'); const Header = require('./header'); const Footer = require('./footer'); require('./index.less'); class Layout extends Component { render() { const { className, children, navigation } = this.props; const layoutClassNames = classnames('layout', className); return ( <div className={layoutClassNames}> <Header className="layout__header" navigation={navigation} /> <div className="layout__main"> {children} </div> <Footer className="layout__footer">2018</Footer> </div> ); } } Layout.propTypes = { className: PropTypes.string, children: PropTypes.node, navigation: PropTypes.array }; module.exports = Layout;
import React, {Component} from 'react'; import {connect} from 'react-redux'; import PropTypes from 'prop-types'; import {Alert, Col, Row} from 'reactstrap'; import {addFlashMessage} from '../../actions/flashMessageAction'; import {getTopicById} from '../../actions/topicAction'; import TopicMainBox from '../../components/topicView/TopicView'; class TopicMain extends Component { constructor(props) { super(props); this.state = { topicsData: [], errors: {} }; } componentWillMount() { this.getById(); } getById() { let topicId = this.props.match.params.id; this.props.getTopicById(topicId).then( (data) => { let topic = data.val(); this.setState({topicsData: topic}); }, (res) => { console.log(res); this.setState({errors: res.response.data, isLoading: false}); } ); } render() { const {isAuthenticated} = this.props.currentUser; if (isAuthenticated) { return ( <div className='topicMainContainer'> <Row> <Col xs='12' className='topicMain'> <TopicMainBox topicData={this.state.topicsData}/> </Col> </Row> </div> ); } else { return ( <Alert color='danger' className='row justify-content-center'> <span>You don't have permissions to see this</span> </Alert> ); } } } TopicMain.propTypes = { currentUser: PropTypes.object.isRequired }; function mapStateToProps(state) { return { currentUser: state.currentUser }; } export default connect(mapStateToProps, {addFlashMessage, getTopicById})(TopicMain);
import * as api from '@/api/card' export default { namespaced: true, state: { cards: [] }, getters: { getCards: ({ cards }) => boardListId => { return Array.isArray(cards) ? cards.filter(card => card.boardListId == boardListId) : null }, getCard: ({ cards }) => id => Array.isArray(cards) ? cards.find(item => item.id == id) : null, }, mutations: { //state不可以解构, updateCards(state, data) { if (!state.cards) { state.cards = [] } state.cards = [...state.cards, ...data] }, addCard(state, data) { state.cards.push(data) }, editCard(state, data) { state.cards = state.cards.map(card => { if (card.id == data.id) { return { ...card, ...data } } return card }) }, addAttachment(state, data) { state.cards = state.cards.map(card => { if (card.id == data.boardListCardId) { return { ...card, attachments: [...card.attachments, data], } } return card }) }, removeAttachment(state, { cardId, attachmentId }) { state.cards = state.cards.map(card => { if (card.id == cardId) { return { ...card, attachments: card.attachments.filter( item => item.id != attachmentId, ), } } return card }) }, setCover(state, { cardId, attachmentId }) { state.cards = state.cards.map(card => { if (card.id == cardId) { return { ...card, attachments: card.attachments.map(atta => { return { ...atta, isCover: attachmentId == atta.id, } }), } } return card }) }, removeCover(state, { cardId, attachmentId }) { state.cards = state.cards.map(card => { if (card.id == cardId) { return { ...card, attachments: attachments.map(atta => { return { ...atta, isCover: false, } }), } } return card }) }, }, actions: { async getCards({ commit, state }, boardListId) { const res = await api.getCards(boardListId) commit('updateCards', res.data) }, async addCard({ commit }, data) { const res = await api.addCard(data) commit('addCard', res.data) }, async editCard({ commit }, data) { const res = await api.editCard(data) commit('editCard', data) }, async uploadAttachment({ commit }, data) { const res = await api.uploadAttachment(data) commit('addAttachment', res.data) }, async deleteAttachment({ commit }, data) { const res = await api.deleteAttachment(data.attachmentId) commit('removeAttachment', data) }, async removeCover({ commit }, data) { const res = await api.removeCover(data.attachmentId) commit('removeCover', { ...data, isCover: false }) }, async setCover({ commit }, data) { const res = await api.setCover(data.attachmentId) commit('setCover', { ...data, isCover: true }) }, }, }
const mongoose = require('mongoose'); const Schema = mongoose.Schema; /** * 定义模型 会议室表模型 */ const meetingSchema = new Schema({ name: String, position: String, capacity: Number, equipment: String, icon: String, status: { type: Boolean, default: true, }, appointment_list: [{ start: Number, end: Number, }], }); const Meeting = mongoose.model('Meeting', meetingSchema); module.exports = Meeting;
import React from 'react' // import { Link, useParams } from 'react-router-dom' const Profile = (props) => { return ( <div> <div> <div id='description'> <ol className="list-decimal list-inside m-6"> {props.project} </ol> </div> {/* <ReactMarkdown source={props.readme} /> */} </div> </div> ) } Profile.propTypes = {} export default Profile
import React from 'react'; import { Link } from 'react-router-dom'; const Greeting = ({ currentUser, logoutSession }) => { const sessionLinks = () => ( <nav className='session-links'> <Link to="/login">Login</Link> <br/> <Link to="/signup">Sign up!</Link> </nav> ); const personalGreeting = () => ( <nav className='personal-greeting'> <h2>Hi, {currentUser.username}</h2> <button onClick={logoutSession}>Log Out</button> </nav> ); return ( <div className="nav-bar"> <nav className="nav-bar-left"> <Link to='/'><img className='nav-bar-logo' src={window.logoURL} alt="Dotify Logo" /></Link> </nav> <nav className="nav-bar-right"> {currentUser ? personalGreeting() : sessionLinks()} </nav> </div> ) }; export default Greeting;
angular.module('focus.models.userprofile', [ 'ngResource' ]) .factory('userProfileModel', [ '$resource', function($resource) { return $resource( '/api/user/:id', { id: '@Id' }, {}); } ]);
import React from 'react'; import PropTypes from 'prop-types'; import './styles/circleButton.css'; export const CircleButton = ({ onClick, isClicked, innerCircleClassName, innerCircleClickedClassName, outerCicleClassName, circlesContainerClassName }) => { const innerCircleClasses = isClicked ? innerCircleClickedClassName : ''; return ( <div className={circlesContainerClassName}> <div className={outerCicleClassName} onClick = { (e) => { if (!isClicked) { onClick(); } } } > <div className={`${innerCircleClassName} ${innerCircleClasses}`}> </div> </div> </div> ); }; CircleButton.propTypes = { innerCircleClassName: PropTypes.string.isRequired, innerCircleClickedClassName: PropTypes.string.isRequired, outerCicleClassName: PropTypes.string.isRequired, circlesContainerClassName: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired, isClicked: PropTypes.bool.isRequired }; export default CircleButton;
import { all, takeLatest } from 'redux-saga/effects' import { LoginTypes } from '../reducers/LoginReducer' import client from 'controllers/HttpClient'; import {test} from './LoginSagas' /* ------------- API ------------- */ // The API we use is only used from Sagas, so we create it here and pass along // to the sagas which need it. const api = client; /* ------------- Connect Types To Sagas ------------- */ export default function* root() { yield all([ // some sagas only receive an action takeLatest(LoginTypes.TEST_REQUEST, test), ]) }
/*global define, d3*/ define( [ 'jquery', 'underscore', 'qvangular', 'text!./swr-calendarview.ng.html', 'text!./swr-calendarview.css', 'text!./colorbrewer.css', './../../js/calendar', // no return value './../../external/d3/d3.min' ], function ( $, _, qvangular, ngTemplate, cssContent, cssColorBrewer, calendar ) { 'use strict'; qvangular.directive( 'swrCalendarview', [function () { $( "<style>" ).html( cssContent ).appendTo( "head" ); $( "<style>" ).html( cssColorBrewer ).appendTo( "head" ); /** * Returns the minimum year value. * @param data * @returns {Number} */ //function getMinYear ( data ) { // var s = d3.values( data ) // .sort( function ( a, b ) { return d3.ascending( a.Date, b.Date ); } ) // [0]; // return (s) ? parseInt( s.Date.substr( 0, 4 ) ) : -1; //} /** * Returns the maximum year value. * @param data * @returns {Number} */ //function getMaxYear ( data ) { // var s = d3.values( data ) // .sort( function ( a, b ) { return d3.descending( a.Date, b.Date ); } ) // [0]; // return (s) ? parseInt( s.Date.substr( 0, 4 ) ) : -1; //} /** * Return the absolute minimum value. * @param data * @returns {Number} */ function getMinValue ( data ) { var s = d3.values( data ) .sort( function ( a, b ) { return d3.ascending( a.Measure, b.Measure ); } ) [0]; return (s) ? parseFloat( s.Measure ) : null; } /** * Return the absolute maximum value. * @param data * @returns {Number} */ function getMaxValue ( data ) { var s = d3.values( data ) .sort( function ( a, b ) { return d3.descending( a.Measure, b.Measure ); } ) [0]; return (s) ? parseFloat( s.Measure ) : null; } /** * Returns a range of the years to display * @param data * @returns {Array} */ function getYearsRange ( data ) { var years = []; d3.nest() .key( function ( d ) { return d.Date.substr( 0, 4 ); } ) .sortKeys( d3.ascending ) .entries( data ) .forEach( function ( v ) { years.push( parseInt( v.key ) ); } ); return years; } /** * Render the D3 Calendar View * @param objectId {string} * @param cvData {object} */ function renderChart ( objectId, cvData, cvProps, width ) { var sundayIsLastDayOfWeek = cvProps.sundayIsLastDayOfWeek; if ( !cvData || cvData.length === 0 ) { return; } $( '#chart_' + objectId ).empty(); // Not used anymore because we fetch the getYearsRange ... //var minYear = getMinYear( cvData ); //var maxYear = getMaxYear( cvData ); /*jshint -W016, -W052*/ var w = width - 25, pw = 14, z = ~~((w - pw * 2) / 53), ph = z >> 1, h = z * 7; /*jshint +W016, +W052*/ var yearsRange = getYearsRange( cvData ); var vis = d3.select( '#chart_' + objectId ) .selectAll( "svg" ) //.data( [1990, 1994] ) //Todo: exclude empty years by default or add at least an option for doing so //.data( d3.range( minYear, (maxYear + 1) ) ) .data( yearsRange ) .enter().append( "svg:svg" ) .attr( "width", w ) .attr( "height", h + ph * 2 ) .attr( "class", "RdYlGn" ) .append( "svg:g" ) .attr( "transform", "translate(" + pw + "," + ph + ")" ); vis.append( "svg:text" ) .attr( "transform", "translate(-6," + h / 2 + ")rotate(-90)" ) .attr( "text-anchor", "middle" ) .text( function ( d ) { return d; } ); vis.selectAll( "rect.D3CV_day" ) .data(function(year){ return calendar.dates(year, sundayIsLastDayOfWeek); }) .enter().append( "svg:rect" ) .attr( "x", function ( d ) { return d.week * z; } ) .attr( "y", function ( d ) { return d.day * z; } ) .attr( "class", "D3CV_day" ) .attr( "width", z ) .attr( "height", z ); vis.selectAll( "path.D3CV_month" ) .data(function(year){ return calendar.months(year, sundayIsLastDayOfWeek); }) .enter().append( "svg:path" ) .attr( "class", "D3CV_month" ) .attr( "d", function ( d ) { /*jshint -W014*/ return "M" + (d.firstWeek + 1) * z + "," + d.firstDay * z + "H" + d.firstWeek * z + "V" + 7 * z + "H" + d.lastWeek * z + "V" + (d.lastDay + 1) * z + "H" + (d.lastWeek + 1) * z + "V" + 0 + "H" + (d.firstWeek + 1) * z + "Z"; /*jshint +W014*/ } ); var data = d3.nest() .key( function ( d ) { return d.Date; } ) //.rollup(function (d) { return d[0].Measure; }) .rollup( function ( d ) { return {"Measure": d[0].Measure, "ToolTip": d[0].ToolTip}; } ) .map( cvData ); var minValue = getMinValue( cvData ); var maxValue = getMaxValue( cvData ); // If only a single value is displayed, we have to prevent that min and max value are equal. if ( minValue === maxValue ) { minValue = minValue * 2; maxValue = maxValue * 2; } var divTooltip = d3.select( '#chart_' + objectId ).append( 'div' ) .attr( 'class', 'D3CV_ToolTip' ) .style( 'opacity', 0 ); // disabled as of now //var divAction = d3.select( '#chart_' + objectId ).append( 'div' ) // .attr( 'class', 'D3CV_ToolTip' ) // .style( 'opacity', 0 ); var color = d3.scale.quantize() //.domain([-.05, .05]) .domain( [minValue, maxValue] ) .range( d3.range( 9 ) ) ; var leftOffset = $( '#chart_' + objectId ).offset().left; var topOffset = $( '#chart_' + objectId ).offset().top; vis.selectAll( "rect.D3CV_day" ) //.attr("class", function (d) { return "D3CV_day q" + ((d !== 'undefined' && d.Date !== 'undefined' && data[d.Date].Measure !== 'undefined') ? color(data[d.Date].Measure) : 'xx') + "-9"; }) .attr( "class", function ( d ) { // In case we have selected only a single date, if we have only // a single items, let's not choose one of the colors but gray instead if ( !_.isEmpty( data[d.Date] ) ) { if ( Object.keys( data ).length > 1 ) { return "D3CV_day q" + color( data[d.Date].Measure ) + "-9"; } else { return "D3CV_day D3CV_day_single"; } } else { return "D3CV_day"; } } ) .on( 'click', function ( /*d*/ ) { //console.log('Select Texts in Column' + d.Date); //_t.Data.SelectTextsInColumn( 0, true, d.Date ); //console.log('Check it ...'); //console.log(d); //console.log(d.Date); //console.log(data[d.Date]); //Prototype code for adding a right-click context menu to the chart. //divAction.transition() // .duration(200) // .style('opacity', .99) // .style('display', 'block'); //divAction.html('Select date <br/>Select week<br/>Select month') // .style('left', (d3.event.pageX) - leftOffset + 'px') // .style('top', ((d3.event.pageY) - divTooltip.attr('height') - topOffset + 5) + 'px'); } ) .on( 'mouseover', function ( d ) { //console.clear(); //console.log(d.Date); //console.log(data[d.Date]); divTooltip.transition() .duration( 200 ) .style( 'opacity', 0.99 ) .style( 'display', 'block' ); divTooltip.html( 'Date: ' + d.Date + '<br/>' + (!_.isEmpty( data[d.Date] ) ? data[d.Date].ToolTip : '') ) .style( 'left', (d3.event.pageX) - leftOffset + 'px' ) .style( 'top', ((d3.event.pageY) - divTooltip.attr( 'height' ) - topOffset + 5) + 'px' ); } ) .on( 'mouseout', function ( /* d */ ) { divTooltip.transition() .duration( 200 ) .style( 'opacity', 0 ) .style( 'display', 'none' ); } ) // Do not display the title anymore since we have the tooltip //.append("svg:title") // .text(function (d) { return d.Date + ": " + (data[d.Date]); }) ; } return { restrict: 'EA', scope: { objectId: '=', cvData: '=', cvProps: '=' }, template: ngTemplate, link: function ( $scope/*, $element , $attrs*/ ) { $scope.$watchCollection( 'cvData', function ( /*newVal, oldVal*/ ) { //console.log( 'swr-calendarview:newVal', newVal ); $scope.render(); } ); $scope.$watch( function () { return [$( '#chart_' + $scope.objectId ).width(), $( '#chart_' + $scope.objectId ).height()].join( 'x' ); }, function ( newVal, oldVal ) { if ( newVal !== oldVal ) { console.log( 'new size', newVal ); $scope.render(); } } ); $scope.render = function () { //console.info( 'render Chart', $scope.objectId ); //console.log( '-- data', $scope.cvData ); renderChart( $scope.objectId, $scope.cvData, $scope.cvProps, $( '#chart_' + $scope.objectId ).width() ); }; } }; }] ); } );
// Another way of creating map const x = new Map([ ["Hello", "Ramesh"], ["How are you", "Tell me"], [1, "Java"], [2, "Javascript"], [3, "Golang"] ]); console.log(x); // So what i am getting here MAP => array of array // so lets do one trick // here is an object const weekdays = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']; const openingHours = { [weekdays[3]]: { open: 12, close: 22, }, [weekdays[4]]: { open: 11, close: 23, }, [weekdays[5]]: { open: 0, // Open 24 hours close: 24, }, }; // Lets se we want to iterate over (opening hours) object so we need to firstly convert them in to array console.log(openingHours); // Here we get an array console.log(Object.entries(openingHours)); // But now lets convert object in to map // we know map is array of array const tom = new Map(Object.entries(openingHours)); console.log(tom); // Printout only those no. whose value is language for (const [key, value] of x) if (typeof key === 'number') console.log(`No. is ${key} and value is : ${value}`); // converting map to an object using spread console.log([...x]);
import styled from 'styled-components'; export const Title = styled.Text` color: black; justify-content: center; font-weight: bold; align-items: center; `; export const Button = styled.TouchableOppacity` color: black; height: 30px; width: 80px; align-items: center; justify-content: centar; `;
'use strict'; module.exports = function(app){ var apiKey = process.env.TRANSLATE_KEY , sentiment = require('sentiment') , googleTranslate = require('google-translate')(apiKey); return { index: function(phrase){ return q.nbind(googleTranslate.translate, googleTranslate)(phrase, 'es', 'en').then(function(response){ return sentiment(response.translatedText); }); } }; };
const Recipes = require('./recipeModel'); const express = require('express'); const router = express.Router(); //get all recipes router.get('/', async (req, res) => { try { const recipes = await Recipes.getRecipes(); res.json(recipes); } catch (err) { res.status(500).json({ message: 'Failed to get schemes' }); } }); //get ingredients and quantities router.get('/:id/shoppingList', async (req, res) => { const { id } = req.params; try { const shoppingList = await Recipes.getIngredients(id); res.status(200).json(shoppingList); } catch (err) { res.status(500).json({ message: 'Failed to get shoppingList' }); } }); //get instructions router.get('/:id/instructions', async (req, res) => { const { id } = req.params; try { const instructions = await Recipes.getInstructions(id); res.status(200).json(instructions); } catch (err) { res.status(500).json({ message: 'Failed to get instructions' }); } }); module.exports = router;
// <%= projectName %>
import React from "react"; import "../Style/Decrease.css"; import { connect } from "react-redux"; function Decrease(props) { const {decrease} = props return ( <div className={"decrease"}> <button onClick={decrease} className={"dec__button"}>DECREASE</button> </div> ); } function mapDispatchToProps(dispatch) { return { decrease: () => dispatch({ type: "DECREASE", }), }; } export default connect(null, mapDispatchToProps)(Decrease);
const functions = require("firebase-functions"); const admin = require("firebase-admin"); const newUser = functions.auth.user().onCreate((user) => { return addUser(user); }); // It creates a new Document when a new User joins const addUser = (cred) => { return admin .firestore() .collection("users") .doc(cred.uid) .set({ email: cred.email, displayName: cred.email.split("@")[0], emailVerified: cred.emailVerified, phoneNumber: cred.phoneNumber, location: null, facebookUrl: "", twitterUrl: "", instagramUrl: "", photoURL: cred.photoURL, joined: admin.firestore.FieldValue.serverTimestamp(), }) .then(() => functions.logger.info("New User has been Added")) .catch((err) => Error(err.message)); }; const deleteUser = functions.auth.user().onDelete((user) => { return removeUser(user); }); const removeUser = (cred) => { return admin .firestore() .collection("users") .doc(cred.uid) .delete() .then(() => { return deletePostersbyId(cred.uid); }) .then(() => { return deleteJobsbyId(cred.uid); }); }; const deletePostersbyId = (userId) => { var promises = []; var collectionRef = admin .firestore() .collection("posters") .where("userId", "==", userId); return collectionRef .get() .then((qs) => { qs.forEach((docSnapshot) => { promises.push(docSnapshot.ref.delete()); }); return Promise.all(promises); }) .then(() => { return functions.logger.info("POSTERS REMOVED"); }) .then(() => {}); }; const deleteJobsbyId = (userId) => { var promises = []; var collectionRef = admin .firestore() .collection("jobs") .where("userId", "==", userId); return collectionRef .get() .then((qs) => { qs.forEach((docSnapshot) => { promises.push(docSnapshot.ref.delete()); }); return Promise.all(promises); }) .then(() => { functions.logger.info("JOBS REMOVED"); }); }; module.exports = { newUser, deleteUser };
const mongoose = require('mongoose') const Schema = mongoose.Schema mongoose.connect('mongodb://localhost:27017/blogProject', {useNewUrlParser: true, useUnifiedTopology: true}) const UserSchema = new Schema({ email: { type: String, required: true }, nickname: { type: String, required: true }, password: { type: String, required: true }, created_date: { type: Date, default: Date.now // 不要去调用,也就是不要加括号,而且就用Date.now就行了 }, last_modified_date: { type: Date, default: Date.now }, avatar: { type: String, default: '/public/img/avatar-default.png' }, bio: { type: String, default: '' }, sex: { type: Number, enum: [-1, 0, 1], default: -1 }, status: { type: Number, // 状态码 0:无限制;1:禁止发言;2:禁止登陆 enum: [0, 1, 2], default: 0 }, birthday: { type: Date } }) module.exports = mongoose.model('User', UserSchema)
Ext.define('PWApp2.store.WellTypeStore', { extend: 'Ext.data.Store', storeId: 'WellTypeStore', fields: ['name' ], data : [ { name: 'CBM' }, { name: 'CONVENTIONAL HYDROCARBON' }, { name: 'GEOTHERMAL' }, { name: 'SHALE GAS' }, { name: 'TIGHT GAS' }, { name: 'TIGHT OIL' }, { name: 'UNKNOWN' }, { name: 'WATER' } ] });
const url = "https://striveschool-api.herokuapp.com/api/product/"; let urlParams = new URLSearchParams(window.location.search); let id = urlParams.get("id"); const fetchProduct = async () => { try { let response = await fetch(url + id, { headers: { Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MDUxZTIxMjg5YzI2ZjAwMTU3ZjljMjIiLCJpYXQiOjE2MTU5OTE2OTEsImV4cCI6MTYxNzIwMTI5MX0.xILIO3GQJT9ouqgILUtxz0epGQhl2SGf2_lMFm5iw2M", }, }); let data = await response.json(); console.log(data); let myProduct = { name: document.getElementById("name-input"), description: document.getElementById("description-input"), brand: document.getElementById("brand-input"), imageUrl: document.getElementById("image-url-input"), price: document.getElementById("price-input"), }; myProduct.name.value = data.name; myProduct.description.value = data.description; myProduct.brand.value = data.brand; myProduct.imageUrl.value = data.imageUrl; myProduct.price.value = data.price; } catch (error) {} }; const handleSubmit = async (event) => { event.preventDefault(); let myProduct = { name: document.getElementById("name-input").value, description: document.getElementById("description-input").value, brand: document.getElementById("brand-input").value, imageUrl: document.getElementById("image-url-input").value, price: document.getElementById("price-input").value, }; console.log(myProduct); try { let response = await fetch(url + id, { method: "PUT", headers: { "Content-Type": "application/json", Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MDUxZTIxMjg5YzI2ZjAwMTU3ZjljMjIiLCJpYXQiOjE2MTU5OTE2OTEsImV4cCI6MTYxNzIwMTI5MX0.xILIO3GQJT9ouqgILUtxz0epGQhl2SGf2_lMFm5iw2M", }, body: JSON.stringify(myProduct), }); if (response.ok) { alert("Event was edited successfully"); } else { console.log(response.body); alert("something went wrong"); } } catch (error) { console.log(error); } }; window.onload = fetchProduct;
class Player { constructor() { this.spot = 0; } roll() { let r = floor(random(1, 4)); this.spot += r; } reset() { this.spot = 0; } show(tiles) { let current = tiles[this.spot]; fill(255); let center = current.getCenter(); ellipse(center[0], center[1], 32); } }
/** * Copyright (c) Benjamin Ansbach - all rights reserved. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const Endian = require('./../../Endian'); const CompositeType = require('./../CompositeType'); const Int32 = require('./../Core/Int32'); const AccountNumber = require('./AccountNumber'); const BytesWithFixedLength = require('./../Core/BytesFixedLength'); const NOperation = require('./NOperation'); const OperationHashType = require('./../../Types/OperationHash'); /** * Simple wrapper for an unsigned Int32 value (used for the n_operation value) */ class OperationHash extends CompositeType { /** * Constructor. * * @param {String} id */ constructor(id = null) { super(id || 'ophash'); this.description('A pascalCoin operation hash'); this.addSubType( new Int32('block', true, Endian.LITTLE_ENDIAN) .description('The block the operation is in.') ); this.addSubType( new AccountNumber('account') .description('The account number that signed the operation.') ); this.addSubType( new NOperation('nOperation', 4) .description('The n_operation value of the account with the current operation.') ); this.addSubType( new BytesWithFixedLength('md160', 20) .description('The RIPEMD160 hash of the operation data.') ); } /** * Reads a value and returns a new PascalCoin AccountNumber instance. * * @param {BC|Buffer|Uint8Array|String} bc * @param {Object} options * @param {*} all * @returns {OperationHash} */ decodeFromBytes(bc, options = {}, all = null) { const decoded = super.decodeFromBytes(bc); return new OperationHashType(decoded.block, decoded.account, decoded.nOperation, decoded.md160); } /** * Appends the given pascalcoin account number to the BC. * * @param {OperationHash} value * @return {BC} */ encodeToBytes(value) { return super.encodeToBytes(value); } } module.exports = OperationHash;
import React from "react"; import { StyleSheet, View, FlatList, Button, Text, TouchableOpacity, } from "react-native"; import { useSelector, useDispatch } from "react-redux"; import Colors from "../constants/Colors"; import * as trackerActions from "../store/actions/trackerActions"; const ListaTrackers = ({ navigation }) => { const trackers = useSelector((state) => state.trackers.trackers); const dispatch = useDispatch(); dispatch(trackerActions.carregarTrackers()); return ( <View style={{ height: "100%" }}> <FlatList data={trackers} keyExtractor={(item) => item.id} renderItem={(itemData) => ( <TouchableOpacity onPress={() => navigation.navigate("DeetsTracker", { endereco: itemData.item.endereco, trackerId: itemData.item.id, }) } > <View style={{ padding: 15, borderBottomWidth: 1, borderTopWidth: 1, borderColor: "#ccc", justifyContent: "center", alignItems: "center", }} > <Text style={{ fontSize: 18 }}>{itemData.item.endereco}</Text> </View> </TouchableOpacity> )} /> <View style={{ margin: 10 }}> <View style={{ margin: 5 }}> <Button color={Colors.foto} title="Nova foto" onPress={() => navigation.navigate("SalvarUnica")} /> </View> <View style={{ margin: 5 }}> <Button color={Colors.foto} title="Novo trajeto" onPress={() => navigation.navigate("Tracker")} /> </View> </View> </View> ); }; export default ListaTrackers; const styles = StyleSheet.create({});
var fs = require('fs'); var cp = require('child_process'); var serverFile = 'jsTicket.js'; var server = cp.fork(serverFile); console.log('Server Script gestartet'); fs.watchFile(serverFile, function (event, filename) { server.kill(); console.log('Server stopped'); server = cp.fork(serverFile); console.log('Server restarted'); });
import {firebaseAction} from 'vuexfire'; export const setLocations = firebaseAction(({bindFirebaseRef}, ref) => { bindFirebaseRef('locations', ref); }); export const setUser = ({ commit }, user) => { commit('SET_USER', user); }; export const mapCenter = ({ commit }, data) => { commit('SET_MAPCENTER', data); };
import React from 'react' import styled from 'styled-components' import NumberFormat from 'react-number-format'; import {db} from './firebase' function CartItem ({ id, item }) { const deletItem = (e) => { e.preventDefault() db.collection('cartitems').doc(id).delete(); } let options = [] for (let i = 1; i < Math.max(item.quantity + 1, 30); i++) { options.push(<option value={ i }> Qty: {i}</option>) } const changeQuantity = (newQuantity) => { db.collection('cartitems').doc(id).update({ quantity: parseInt(newQuantity) }) } return ( <Container> <ItemsContainer> <img src={item.image} alt="" /> </ItemsContainer> <InfoContainer> <InfoTop> <h2>{item.name}</h2> </InfoTop> <InfoBottom> <ItemQuantity> <select value={ item.quantity } onChange={(e) => changeQuantity(e.target.value)} > {options} </select> </ItemQuantity> <ItemDelete onClick={deletItem}> Delete </ItemDelete> </InfoBottom> </InfoContainer> <ItemPrice> <NumberFormat value={item.price} displayType={'text'} thousandSeparator={true} prefix={'₹'}/> </ItemPrice> </Container> ) } export default CartItem const Container = styled.div` padding-top: 12px; padding-bottom: 12px; display: flex; border-bottom: 1px solid #DDD; `; const ItemsContainer = styled.div` width: 180px; height: 180px; flex-shrink: 0; flex-grow: 0; margin-right: 16px; img{ object-fit: contain; height: 100%; width: 100%; } `; const InfoContainer = styled.div` flex-grow: 1; `; const InfoTop = styled.div` color: #0090FF; h2{ font-size: 18px; } `; const InfoBottom = styled.div` display: flex; margin-top: 4px; align-items: center; `; const ItemQuantity = styled.div` select{ border-radius: 7px; background-color: #f0f2f2; padding: 8px; box-shadow: 0 2px 5px rgba(15, 17, 17, .15); :focus { outline: none; } } `; const ItemDelete = styled.div` color: #0090FF; margin-left: 16px; cursor: pointer; `; const ItemPrice = styled.div` font-size: 18px; font-weight: 700; margin-left: 16px; `;
import shared from 'shared/utils/helpers'; var helpers = Object.assign({}, shared, { sortDates(objects, field, order){ return objects.sort((a, b) => { let dateA = a[field] ? new Date(a[field]) : 0, dateB = b[field] ? new Date(b[field]) : 0; if (dateA > dateB) return 1; if (dateA < dateB) return -1; return 0; }); }, sortStrings(objects, field){ return objects.sort((a, b) => { if (a[field].toLowerCase() > b[field].toLowerCase()) return 1; if (a[field].toLowerCase() < b[field].toLowerCase()) return -1; return 0; }); }, }); export default helpers;
const mongoose = require( 'mongoose' ) ; const { errData } = require('../../response') ; var itemSchema = new mongoose.Schema ({ Name : { type : String, index: { unique: true } }, Qty : Number, Unit : String, UserID : { type : mongoose.Schema.Types.ObjectId, required : true }, }); itemSchema.statics.AddNewItem = async ( itemData ) => { try { const item = new Item() ; Object.assign( item, itemData ) ; // For 'Logging' where itemData is update before passing it logger in 'item.controller.js' itemData.LogQty = { Old:0, New:itemData.Qty } ; return await item.save() ; } catch ( err ) { if ( err.code === 11000 ) throw { err : errData.duplicateErr, info : `Item : ${itemData.Name} ( Already Exist )` } ; throw err ; } } itemSchema.statics.Update = async ( { Name, Unit, Qty } ) => { let fieldsToBeUpdated = {} ; if ( Unit ) fieldsToBeUpdated.Unit = Unit ; if ( Qty ) fieldsToBeUpdated.Qty = Qty ; const updateStatus = await Item.updateOne( { Name : Name }, { $set : fieldsToBeUpdated } ) ; if ( updateStatus.n === 0 ) throw { err : errData.resNotFound, info : `Item : ${ Name } ( Not Found ). Please Add the Item before updating.` } ; } itemSchema.statics.Detail = async ( itemName ) => { const itemFound = await Item.findOne( { Name : itemName }, { _id : 0, Qty:1, Unit:1 } ) ; if ( !itemFound ) throw { err : errData.resNotFound, info : `Item : ${ itemName } ( Not Found ).` } ; return itemFound ; } itemSchema.statics.IncItemQty = async ( itemQtyPair ) => { const itemNameList = Object.keys( itemQtyPair ) ; const query = { filter : { Name: { $in : itemNameList } } , project : { _id:1, Name:1, Qty:1 } , } const itemDocList = await Item.find( query.filter, query.project ); if ( itemNameList.length != itemDocList.length ) throw { err : errData.resNotFound, info : "One of the item is doesn't exist in DB", } for ( const itemDoc of itemDocList ) itemDoc.Qty += parseInt(itemQtyPair[ itemDoc.Name ]) ; for( const doc of itemDocList ) await doc.save(); } itemSchema.statics.DecItemQty = async ( itemQtyPair ) => { const itemNameList = Object.keys( itemQtyPair ) ; const query = { filter : { Name: { $in : itemNameList } } , project : { _id:1, Name:1, Qty:1 } , } const itemDocList = await Item.find( query.filter, query.project ); if ( itemNameList.length != itemDocList.length ) throw { err : errData.resNotFound, info : "One of the item is doesn't exist in DB", } for ( const itemDoc of itemDocList ) { const QtyToBeReduced = itemQtyPair[ itemDoc.Name ] ; const AvailableQty = itemDoc.Qty ; if ( QtyToBeReduced > AvailableQty ) throw { err : errData.notEnoughStock, info : `Item : '${ itemDoc.Name }' Stock is low, cannot perform the operation`, } ; itemDoc.Qty -= parseInt(QtyToBeReduced); } for ( const doc of itemDocList ) await doc.save(); } const Item = mongoose.model( 'items', itemSchema ) ; module.exports = Item ;
import React from 'react' function UserAvatar({user}) { return ( <> <img className= 'user-avatar' src={user.avatar} alt="avatar"/> </> ) } export default UserAvatar
let growing = {}; const addPlant = (seedObj) => { return growing.push(seedObj); }; const usePlants = (growing) => { return growing; }; // Array.isArray(seedObj) // let seedObj = createCorn; // console.log(seedObj);
// Your logo, game name, sponsors etc that shows up when the player starts the game // Create intro state var IntroState = { preload: function() { }, create: function() { }, update: function() { } }
import React from 'react'; import { fireEvent, render } from '@testing-library/react'; import InformationForm from './InformationForm'; import placeholders from '../text/placeholders'; describe('InformationForm', () => { const fields = { sender: { id: 'sender', name: '보내는 사람', value: '', placeholder: placeholders.sender, errorMessage: '', onChange: jest.fn(), }, receiver: { id: 'receiver', name: '받는 사람', value: '', placeholder: placeholders.receiver, errorMessage: '', onChange: jest.fn(), }, secretMessage: { id: 'secretMessage', name: '엽서 암호', value: '', placeholder: placeholders.secretMessage, errorMessage: '', onChange: jest.fn(), }, }; const isPrivate = true; const onClick = jest.fn(); const handleRadioChange = jest.fn(); const handlePreviousClick = jest.fn(); const { getByLabelText, getAllByPlaceholderText, getByText } = render(( <InformationForm fields={fields} onHandleClick={onClick} onRadioChange={handleRadioChange} isPrivate={isPrivate} onClickPrevious={handlePreviousClick} /> )); it('renders InformationForm', () => { fireEvent.click(getByText('이전')); expect(handlePreviousClick).toBeCalled(); expect(getByText('엽서 작성하기')).not.toBeNull(); Object.entries(fields).forEach(([, { name, onChange, }]) => { expect(getByLabelText(name)).not.toBeNull(); fireEvent.change(getByLabelText(name), { target: { value: 'test' } }); expect(onChange).toBeCalled(); }); expect(getAllByPlaceholderText(placeholders.sender)).toHaveLength(2); expect(getAllByPlaceholderText(placeholders.secretMessage)).toHaveLength(1); expect(getByText('관리자에게 쓰고 싶은 편지가 있다면 받는 사람을 ‘관리자’로 입력해주세요.')).not.toBeNull(); expect(getByText('엽서를 확인 또는 파기하기 위해 사용되며 받는 사람에게도 공유됩니다.')).not.toBeNull(); expect(getByText('공개 여부')).not.toBeNull(); expect(getByLabelText('비공개')).not.toBeNull(); expect(getByLabelText('비공개')).toBeChecked(); fireEvent.click(getByLabelText('공개')); expect(handleRadioChange).toBeCalled(); expect('신중하게 선택해 주세요. 공개 시 다른 사람에게도 공개 되며 수정이 불가능 하며 공개하고 싶지 않다면 삭제 해야 합니다.') .not.toBeNull(); expect(getByText('다음')).not.toBeNull(); fireEvent.click(getByText('다음')); expect(onClick).toBeCalled(); }); });
import React from 'react'; import Header from './Header'; const Home = (props) => <div><Header/><h1>Our site</h1>{props.children}</div>; export default Home
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; exports.default = difference;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Add from 'material-ui-icons/Add'; import Button from 'material-ui/Button'; import Remove from 'material-ui-icons/Remove'; import Table, { TableBody, TableCell, TableHead, TableRow } from 'material-ui/Table'; import TextField from 'material-ui/TextField'; import { withStyles } from 'material-ui/styles'; import tableStyle from '../styles/tables'; import * as statusTypes from '../constants/status'; class AgentsManager extends Component { constructor(props) { super(props); this.state = { agentName: '', agentUrl: '' }; this.handleChange = this.handleChange.bind(this); this.handleAddAgent = this.handleAddAgent.bind(this); } handleChange(key, value) { this.setState({ ...this.state, [key]: value }); } handleAddAgent() { const { agentName, agentUrl } = this.state; if (agentName && agentUrl) { this.props.addAgent(agentName.trim(), agentUrl.trim()); this.setState({ ...this.state, agentName: '', agentUrl: '' }); } } render() { const { classes, agents, deleteAgent } = this.props; return ( <Table> <TableHead> <TableRow> <TableCell>Agent name</TableCell> <TableCell>Agent url</TableCell> <TableCell>Action</TableCell> </TableRow> </TableHead> <TableBody> {agents && agents.map(({ name, url, status }) => ( <TableRow key={name} className={classNames({ [classes.tableRowError]: status === statusTypes.FAILED })} > <TableCell>{name}</TableCell> <TableCell>{url}</TableCell> <TableCell> <Button type="remove" onClick={() => { deleteAgent(name); }} > <Remove /> </Button> </TableCell> </TableRow> ))} <TableRow> <TableCell> <TextField placeholder="Agent name" value={this.state.agentName || ''} onChange={e => this.handleChange('agentName', e.target.value)} type="text" /> </TableCell> <TableCell> <TextField placeholder="Agent url" value={this.state.agentUrl || ''} onChange={e => this.handleChange('agentUrl', e.target.value)} type="text" /> </TableCell> <TableCell> <Button type="add" onClick={this.handleAddAgent}> <Add /> </Button> </TableCell> </TableRow> </TableBody> </Table> ); } } AgentsManager.propTypes = { addAgent: PropTypes.func.isRequired, deleteAgent: PropTypes.func.isRequired, agents: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string.isRequired, url: PropTypes.string.isRequired }) ).isRequired, classes: PropTypes.shape({ tableRowError: PropTypes.string.isRequired }).isRequired }; export default withStyles(tableStyle)(AgentsManager);
import React from "react"; import "./mobile.css"; function mobile() { return ( <div class="container1" style={{ background: "#be3956" }}> <div class="text-with-animation">Not supported on</div> <div class="subtext-with-animation"> <span>Mobile</span> <span>Phones</span> </div> </div> ); } export default mobile;
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Switch, Route} from "react-router-dom"; import { Header, Footer} from './components'; import { About, Users, Main, Error } from './pages'; import { ThemeProvider, createTheme } from '@material-ui/core/styles'; import CssBaseline from '@material-ui/core/CssBaseline'; // import reportWebVitals from './reportWebVitals'; const theme = createTheme(); const Routing = () => { return( <Router> <div style={{position: 'relative', height: '100vh'}}> <Header/> <Switch> <Route exact path="/" component={Main} /> <Route exact path="/about" component={About} /> <Route exact path="/users" component={Users} /> <Route path="*" component={Error} /> </Switch> <Footer/> </div> </Router> ) } ReactDOM.render( <React.StrictMode> <ThemeProvider theme={theme}> <CssBaseline /> <Routing /> </ThemeProvider> </React.StrictMode>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals // reportWebVitals();
var mongoose = require('mongoose'); var eventSchema = mongoose.Schema({ title: String, start: Date, details: String, userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' } }); //this is if there were multiple models in one file // module.exports = { // User: mongoose.model('User', userSchema) // } module.exports = mongoose.model('Event', eventSchema);
var array=[]; $(document).ready(function () { // $('.lista-seleccionable').selectable(); // $('.lista-seleccionable li').draggable(); $('.lista-seleccionable').sortable({ update:function (event, ui) { array.push(ui.item[0].innerText) console.log(ui.item[0].innerText) console.log(array) } }); }); console.log(array)
const { db } = require("../../database"); const { createToken } = require("../../helpers/jwt"); const crypto = require("crypto"); const BASE_URL = "https://warehouse-3.purwadhikafs2.com"; module.exports = { adminLogin: (req, res) => { const { email, password } = req.body; const hashPassword = crypto .createHmac("sha1", process.env.SECRET_KEY) .update(req.body.password) .digest("hex"); const getUserDataQuery = `SELECT * from admin WHERE email='${email}' AND password='${password}'`; db.query(getUserDataQuery, (err, result) => { if (err) res.status(400).send(err); if (result.length === 0) { res.status(200).send({ status: "failed", message: "User not found" }); } else { let token = createToken({ idAdmin: result[0].id_admin, }); res.status(200).send({ status: "success", data: result[0], token }); } }); }, keepLogin: (req, res) => { let idAdmin = req.user.idAdmin; const getAdminDataQuery = `SELECT * from admin WHERE id_admin='${idAdmin}'`; db.query(getAdminDataQuery, (err, result) => { if (err) res.status(400).send(err); if (result.length === 0) { res.status(200).send({ status: "failed", message: "User not found" }); } else { res.status(200).send({ status: "success", data: result[0] }); } }); }, getlistTransaction: (req, res) => { const getTransactionList = `SELECT pay.order_number, pay.date, pay.payment_image, pay.nama_pemilik_rekening, pay.nominal, o.order_date, u.username, o.status FROM warehouse.payment pay INNER JOIN warehouse.order o ON pay.order_number = o.order_number INNER JOIN warehouse.user u ON u.id_user = o.id_user;` db.query(getTransactionList, (err, result) => { if (err) { console.log(err); res.status(400).send(err); } res.status(200).send(result); }); }, getlistTransactionDetail: (req, res) => { const {order_number} = req.body const getTransactionList = `SELECT od.id_orderdetail, od.order_number, o.status, o.order_date, od.id_product, od.quantity, p.date, pr.product_name, pr.product_price FROM warehouse.payment p INNER JOIN warehouse.order o on p.order_number = o.order_number INNER JOIN warehouse.orderdetail od on p.order_number = od.order_number INNER JOIN warehouse.product pr on pr.id_product = od.id_product WHERE od.order_number = '${order_number}';` db.query(getTransactionList, (err, result) => { if (err) { console.log(err); res.status(400).send(err); } res.status(200).send(result); }); }, updateStatusPembayaran: (req,res) =>{ const {ordernumber, status} = req.body; const updatestatus = `UPDATE warehouse.order SET status = '${status}' WHERE order_number = '${ordernumber}'; ` db.query(updatestatus, (err, result) => { if (err) { console.log(err); res.status(400).send(err); } const getTransactionList = `SELECT pay.order_number, pay.date, pay.payment_image, pay.nama_pemilik_rekening, pay.nominal, o.order_date, u.username, o.status FROM warehouse.payment pay INNER JOIN warehouse.order o ON pay.order_number = o.order_number INNER JOIN warehouse.user u ON u.id_user = o.id_user;` db.query(getTransactionList, (err2, result2) => { if (err2) { console.log(err2); res.status(400).send(err2); } res.status(200).send(result2); }); // res.status(200).send(result); }); }, filterTransaction: (req, res) => { const {number} = req.body; const filterquerry = ` SELECT pay.order_number, pay.date, pay.payment_image, pay.nama_pemilik_rekening, pay.nominal, o.order_date, u.username, o.status FROM warehouse.payment pay INNER JOIN warehouse.order o ON pay.order_number = o.order_number INNER JOIN warehouse.user u ON u.id_user = o.id_user WHERE pay.order_number LIKE '%${number}%' ;` // OR address LIKE '%${editData}%' OR kecamatan LIKE '%${editData}%' // OR kabupaten LIKE '%${editData}%' // OR total_price LIKE '%${editData}%' OR quantity LIKE '%${editData}%' OR product_name LIKE '%${editData}%' db.query(filterquerry, (err, result) => { if (err) { console.log(err); res.status(400).send(err); } res.status(200).send(result); }); } };
var searchData= [ ['main_2ecpp',['main.cpp',['../main_8cpp.html',1,'']]], ['map_5findex',['map_index',['../classtree.html#a3d4607480844b71710879a7986e8e5aa',1,'tree']]], ['match',['match',['../classgraph__cluster.html#acc9ec322b82fe84e82c2b6c10ba8ab1c',1,'graph_cluster']]] ];
/** * ESP * Boilerplate app for combining * Express & Socket.IO with auth * from Passport. */ const config = require('./config'); const express = require('express'); const session = require('express-session'); const passport = require('passport'); const cookie = require('cookie'); const memoryStore = new session.MemoryStore(); // see README - don't use MemoryStore in prod const GoogleStrategy = require('passport-google-oauth20').Strategy; // instantiate an express app const app = express(); // basic session configuration, use our memoryStore (see README) app.use(session({ secret: config.SESSION_SECRET, store: memoryStore, resave: false, saveUninitialized: true, })); // provide an http server for our app, and bind socket.io to it const http = require('http').Server(app); const io = require('socket.io')(http); // time to configure passport... // serialize the user to save in the session store. // generally speaking, you just want to store a unique id // to keep session storage small. passport.serializeUser((userObject, done) => { done(null, userObject.id); }); // inverse of the above. take the serialized user (their id) // and fetch the full user object. this will be attached to // every request as req.session.passport.user passport.deserializeUser((userId, done) => { done(null, { id: userId }); }); // add passport middleware to app app.use(passport.initialize()); app.use(passport.session()); // configure passport strategies // Google OAuth2 passport.use(new GoogleStrategy({ clientID: config.GOOGLE_CLIENT_ID, clientSecret: config.GOOGLE_CLIENT_SECRET, callbackURL: config.GOOGLE_AUTH_CALLBACK_URL, }, function googleStrategyCallback(accessToken, refreshToken, googleProfile, callback) { /** * This is called by Passport when the user comes back from the Google OAuth2 sign-in. * We take the profile object returned by Google and find our matching user. * In a real app, this is where you'd want to look in your DB for the user, like: * * db.users.findOne({ * googleProfileId: googleProfile.id * }).then(user => { * return callback(null, user); * }).catch(err => { * return callback(err); * }); * * But! for this basic demo, we just return an object with an id property. */ return callback(null, { id: googleProfile.id }); } )); // add the route for signing in via Google app.get('/auth/google', passport.authenticate('google', { scope: ['email'] // request specific scope/permissions from Google })); // callback route that Google will redirect to after a successful login app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), function successfulGoogleAuthCallback(req, res) { // the user's now successfully authenticated. // their user object is now available on each subsequent request: console.log(req.session.passport.user); res.redirect('/loggedin'); } ); // serve the index. // you can see this regardless of whether you're logged in or not. app.get('/', (req, res) => { res.sendFile(__dirname + '/views/index.html'); }); /** * express auth middleware. * prevents access to an express route if the user isn't authed. * * this middleware will apply to any routes that match the specified * path - ie, /loggedin AND /loggedin/foobar * and will be applied to any routes declared AFTER the middleware. */ app.use('/loggedin', function authMiddleware(req, res, next) { if(!req.session.passport) { return res.redirect('/'); } next(); }); // serve our logged-in page. // auth middleware will prevent access to this unless you're logged in. app.get('/loggedin', (req, res) => { res.sendFile(__dirname + '/views/loggedin.html'); }); /** * socket.io auth middleware * prevent socket connection if the user isn't authed. */ io.use((socket, next) => { // the same cookie that express sets is passed to the socket request // so we need to parse it, and try and load a session from the store. // this is more-or-less what app.use(passport.session()) does for our // express routes. const parsedCookie = cookie.parse(socket.request.headers.cookie); const sessionId = parsedCookie['connect.sid']; // not absolutely sure why we need to substring this, i guess MemoryStore // doesn't use the entire ID as a key. const shortId = sessionId.substr(2, 32); memoryStore.load(shortId, function(err, session){ if(!session || !session.passport) { return next(new Error('Not authenticated')); } next(); }); }); // socket.io connection handler io.on('connection', (socket) => { console.log('a socket is now connected'); socket.on('message', function socketMessageHandler(){ console.log('message received'); }); }); // start the http server http.listen(config.PORT, () => { console.log(`Running on ${config.PORT}`); });
if (!window.guru) window.guru = {}; if (!guru.shapes) guru.shapes = {}; if (!guru.error) { guru.error = function(message) { console.log('%c ERROR %c %s', 'background-color: red; color: white;', 'background-color: transparent; color: inherit;', message); }; } if (!guru.warn) { guru.warn = function(message) { console.log('%c WARN %c %s', 'background-color: gold; color: black;', 'background-color: transparent; color: inherit;', message); }; } if (!guru.success) { guru.success = function(message) { console.log('%c SUCCESS %c %s', 'background-color: green; color: white;', 'background-color: transparent; color: inherit;', message); }; } if (!guru.log) { guru.log = function(message) { console.log('%c LOG %c %s', 'background-color: #1c1c1c; color: white;', 'background-color: transparent; color: inherit;', message); }; } if(!guru.getJSON) { guru.getJSON = function(url, success, error) { var xhr = new XMLHttpRequest(); xhr.open("get", url, true); xhr.responseType = "json"; xhr.onload = function() { if(xhr.status === 200) { success(xhr.response); } else { error(xhr.status); } }; xhr.send(); }; } if(!guru.createID) { guru.createID = function() { return Math.random().toString(36).substr(2, 9); }; } if (!guru.random) { guru.random = function(min, max, allowNegative) { var result = Math.floor(Math.random() * (max - min + 1) + min); var modifier = 1; if (allowNegative) { modifier = (Math.round(Math.random()) === 0 ? -1 : 1); } result *= modifier; return result; }; } if(!guru.randomDecimal) { guru.randomDecimal = function(allowNegative) { var modifier = 1; if (allowNegative) { modifier = (Math.round(Math.random()) === 0 ? -1 : 1); } return Math.random() * modifier; }; } if (!guru.createLoop) { guru.createLoop = function(callback) { function tick() { callback(); window.requestAnimationFrame(tick); } window.requestAnimationFrame(tick); }; } if (!guru.loadTheme) { guru.loadTheme = function(url) { var link = document.createElement("link"); link.id = this._id; link.rel = "stylesheet"; link.type = "text/css"; link.media = "all"; link.href = url; document.getElementsByTagName("head")[0].appendChild(link); }; } if (!guru.Color) { guru.Color = function(r, g, b, a) { if (arguments.length === 3 || arguments.length === 4) { this._r = r; this._g = g; this._b = b; this._a = 255; if (arguments.length === 4) this._a = a; } else { this._r = 0; this._g = 0; this._b = 0; this._a = 255; } this._css = "rgba(" + this._r + ", " + this._g + ", " + this._b + ", " + this._a + ")"; }; guru.Color.prototype.getRGB = function() { return { r: this._r, g: this._g, b: this._b, a: this._a }; }; guru.Color.prototype.setRGB = function(r, g, b, a) { if(!a) a = 255; this._r = r; this._g = g; this._b = b; this._a = a; this._css = "rgba(" + this._r + ", " + this._g + ", " + this._b + ", " + this._a + ")"; return this; }; guru.Color.prototype.fromHex = function(hex) { var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if(result) { this._r = parseInt(result[1], 16); this._g = parseInt(result[2], 16); this._b = parseInt(result[3], 16); this._a = 255; this._css = "rgba(" + this._r + ", " + this._g + ", " + this._b + ", " + this._a + ")"; } return this; }; } if (!guru.shapes.Polygon) { guru.shapes.Polygon = function() { this._color = new guru.Color(); this._vertices = []; this.vertexCount = 0; }; guru.shapes.Polygon.prototype.setColor = function(color) { this._color = color; return this; }; guru.shapes.Polygon.prototype.addVertex = function(x, y) { this._vertices.push([x, y]); this.vertexCount = this._vertices.length; return this; }; guru.shapes.Polygon.prototype.move = function(x, y) { for (var i = this._vertices.length - 1; i >= 0; i--) { this._vertices[i][0] += x; this._vertices[i][1] += y; }; } guru.shapes.Polygon.prototype.moveVertex = function(i, x, y) { this._vertices[i][0] += x; this._vertices[i][1] += y; } guru.shapes.Polygon.prototype.getVertexCoords = function(i) { return { x: this._vertices[i][0], y: this._vertices[i][1] }; } guru.shapes.Polygon.prototype.render = function(context) { var oldStyle = context.fillStyle; context.fillStyle = this._color._css; context.beginPath(); for (var i = this._vertices.length - 1; i >= 0; i--) { var vertex = this._vertices[i]; if (i === this._vertices.length - 1) { context.moveTo(vertex[0], vertex[1]); } else { context.lineTo(vertex[0], vertex[1]); } }; context.closePath(); context.fill(); context.fillStyle = oldStyle; return this; }; } if (!guru.shapes.Rectangle) { guru.shapes.Rectangle = function(x, y, width, height) { this._x = x; this._y = y; this._width = width; this._height = height; this._color = new guru.Color(); }; guru.shapes.Rectangle.prototype.setColor = function(color) { this._color = color; return this; }; guru.shapes.Rectangle.prototype.getPosition = function() { return { x: this._x, y: this._y }; }; guru.shapes.Rectangle.prototype.move = function(x, y) { this._x += x; this._y += y; return this; }; guru.shapes.Rectangle.prototype.render = function(context) { var oldStyle = context.fillStyle; context.fillStyle = this._color._css; context.fillRect(this._x, this._y, this._width, this._height); context.fillStyle = oldStyle; return this; }; } if(!guru.shapes.Circle) { guru.shapes.Circle = function(x, y, radius) { this._x = x; this._y = y; this._radius = radius; this._color = new guru.Color(); }; guru.shapes.Circle.prototype.setColor = function(color) { this._color = color; return this; }; guru.shapes.Circle.prototype.getPosition = function() { return { x: this._x, y: this._y }; }; guru.shapes.Circle.prototype.move = function(x, y) { this._x += x; this._y += y; return this; }; guru.shapes.Circle.prototype.render = function(context) { var oldStyle = context.fillStyle; context.fillStyle = this._color._css; context.beginPath(); context.arc(this._x, this._y, this._radius, 0, 2 * Math.PI, true); context.fill(); context.closePath(); context.fillStyle = oldStyle; return this; }; } if (!guru.TextureManager) { guru.TextureManager = function() { this._textures = {}; this.onCompleted = function() {}; }; guru.TextureManager.prototype.addTexture = function(id, src) { if (this._textures.hasOwnProperty(id)) { guru.error("[addTexture] A texture with the ID \"" + id + "\" is already registered within the TextureManager."); return this; } var texture = new Image(); texture.src = src; texture.loaded = false; var that = this; texture.onload = function() { texture.loaded = true; if(that.completed()) that.onCompleted(); } this._textures[id] = texture; return this; }; guru.TextureManager.prototype.getTexture = function(id) { if (!this._textures.hasOwnProperty(id)) { guru.error("[getTexture] Texture \"" + id + "\" is not registered within the TextureManager."); return null; } if (!this._textures[id].loaded) { guru.warn("[getTexture] Texture \"" + id + "\" has not finished loading."); } return this._textures[id]; }; guru.TextureManager.prototype.completed = function() { for (var id in this._textures) { if (this._textures.hasOwnProperty(id)) { var texture = this._textures[id]; if (!texture.loaded) return false; } } return true; }; } if (!guru.Text) { guru.Text = function(text, x, y, font, size, color) { this._text = text; this._x = x; this._y = y; this._rotation = 0; this._font = font; this._size = size; this._color = color; this._centerVertical = false; this._centerHorizontal = false; } guru.Text.prototype.setCentered = function(vertical, horizontal) { this._centerVertical = vertical; this._centerHorizontal = horizontal; return this; }; guru.Text.prototype.setText = function(text) { this._text = text; return this; }; guru.Text.prototype.setColor = function(color) { this._color = color; return this; }; guru.Text.prototype.setSize = function(size) { this._size = size; return this; }; guru.Text.prototype.rotate = function(angle) { this._rotation += angle; return this; }; guru.Text.prototype.render = function(context) { var oldBaseline = context.textBaseline, oldTextAlign = context.textTextAlign, oldFillStyle = context.fillStyle, oldFont = context.font; context.textBaseline = (!this._centerVertical ? "top" : "middle"); context.textAlign = (!this._centerHorizontal ? "left" : "center"); context.fillStyle = this._color._css; context.font = this._size + 'px "' + this._font + '"'; context.fillText(this._text, this._x, this._y); context.textBaseline = oldBaseline; context.textAlign = oldTextAlign; context.fillStyle = oldFillStyle; context.font = oldFont; return this; }; } if (!guru.Sprite) { guru.Sprite = function(x, y, width, height) { this._x = x; this._y = y; this._width = width; this._height = height; this._cropping = { x: 0, y: 0, width: width, height: height }; this._color = new guru.Color(); this._texture = null; this._interval = -1; this._frames = []; this._frame = 0; this._frames.push(this._cropping); }; guru.Sprite.prototype.move = function(x, y) { this._x += x; this._y += y; return this; }; guru.Sprite.prototype.setColor = function(color) { this._color = color; return this; }; guru.Sprite.prototype.setTexture = function(texture) { this._texture = texture; return this; }; guru.Sprite.prototype.setCropping = function(cropping) { this._cropping = cropping; return this; }; guru.Sprite.prototype.addFrame = function(cropping) { this._frames.push(cropping); return this; }; guru.Sprite.prototype.render = function(context) { if (!this._texture) { var oldStyle = context.fillStyle; context.fillStyle = this._color._css; context.fillRect(this._x, this._y, this._width, this._height); context.fillStyle = oldStyle; } else { var cropping = this._frames[this._frame]; context.drawImage(this._texture, cropping.x, cropping.y, cropping.width, cropping.height, this._x, this._y, this._width, this._height); } return this; }; guru.Sprite.prototype.incrementAnimation = function() { this.setCropping(this._frames[this._frame]); if (this._frame < this._frames.length) this._frame++; if (this._frame === this._frames.length) this._frame = 0; return this; }; guru.Sprite.prototype.stopAnimation = function() { clearInterval(this._interval) this._interval = -1; return this; }; guru.Sprite.prototype.startAnimation = function(speed) { var that = this; this._interval = setInterval(function() { that.incrementAnimation(this); }, speed || 150); return this; }; guru.Sprite.prototype.loadAnimation = function(url, error) { if (!error) { error = function(status) { guru.error("Could not load animation from \"" + url + "\": " + status + "."); }; } var success = function(data) { if (data.frames) { this._frames = data.frames; if(this._frames.length === 0) { this._frames.push(this._cropping); } } else { guru.warn("Animation \"" + url + "\" did not contain an array of frames."); } }; guru.getJSON(url, success, error); return this; }; } if (!guru.GUIManager) { guru.GUIManager = function(id) { this._elements = []; this._container = document.createElement("div"); this._inner = document.createElement("div"); this._id = "_" + (id || guru.createID()); this._container.id = "guru-gui-container" + this._id; this._container.style["z-index"] = "999"; this._inner.id = "guru-gui-inner" + this._id; this._inner.style.position = "relative"; this._inner.style.height = "100%"; this._inner.style.width = "100%"; this._inner.className = "guru-gui-inner"; this._container.appendChild(this._inner); document.body.appendChild(this._container); }; guru.GUIManager.prototype.clearElements = function() { while (this._inner.hasChildNodes()) { this._inner.removeChild(this._inner.lastChild); } return this; }; guru.GUIManager.prototype.addElement = function(element) { this._inner.appendChild(element._element); return this; }; guru.GUIManager.prototype.loadTheme = function(url) { var style = document.createElement("style"); if (!(/firefox/.test(navigator.userAgent.toLowerCase()))) { guru.warn("Scoped styles are not supported in your browser, this theme will be applied to the entire document. (loadTheme: \"" + url + "\")"); } style.id = this._id; style.type = "text/css"; style.setAttribute("scoped", ""); style.appendChild(document.createTextNode("@import url('" + url + "');")); this._container.appendChild(style); return this; }; } if (!guru.GUIElement) { guru.GUIElement = function(type, value, id) { this._type = type || "button"; this._value = value || ""; this._id = id || guru.createID(); this._element = document.createElement("input"); this._element.type = this._type; this._element.value = this._value; this._element.id = this._id; this._element.className = "guru-gui-element"; this.onclick = function() {}; var that = this; this._element.onclick = function(e) { that.onclick(e); }; }; guru.GUIElement.prototype.center = function() { this._innerElement = this._element; this._element = document.createElement("div"); this._element.id = this._id; this._element.style.width = "100%"; this._element.style["box-sizing"] = "border-box"; this._element.style.display = "block"; this._element.style.textAlign = "center"; this._innerElement.style.display = "inline-block"; this._element.appendChild(this._innerElement); return this; }; guru.GUIElement.prototype.setPlaceholder = function(value) { if (this._innerElement) { this._innerElement.placeholder = value; } else { this._element.placeholder = value; } return this; }; guru.GUIElement.prototype.applyStyle = function(key, value) { if (typeof value === "Number") { value = value.toString() + "px"; } if (this._innerElement) { this._innerElement.style[key] = value; } else { this._element.style[key] = value; } return this; }; guru.GUIElement.prototype.setPosition = function(x, y) { if (this._innerElement) { this._innerElement.style.position = "absolute"; this._innerElement.style.top = (y || 0).toString() + "px"; this._innerElement.style.left = (x || 0).toString() + "px"; } else { this._element.style.position = "absolute"; this._element.style.top = y.toString() + "px"; this._element.style.left = x.toString() + "px"; } return this; }; guru.GUIElement.prototype.setOnclick = function(onclick) { this.onclick = onclick; return this; }; guru.GUIElement.prototype.setValue = function(value) { this._value = value || ""; if(this._innerElement) { this._innerElement.value = this._value; } else { this._element.value = this._value; } return this; }; } if (!guru.GUILabel) { guru.GUILabel = function(value, id) { this._value = value || ""; this._id = id || guru.createID(); this._element = document.createElement("span"); this._element.appendChild(document.createTextNode(this._value)); this._element.id = this._id; this._element.className = "guru-gui-label"; this.onclick = function() {}; var that = this; this._element.onclick = function(e) { that.onclick(e); }; }; guru.GUILabel.prototype.center = function() { this._innerElement = this._element; this._element = document.createElement("div"); this._element.id = this._id; this._element.style.width = "100%"; this._element.style["box-sizing"] = "border-box"; this._element.style.display = "block"; this._element.style.textAlign = "center"; this._innerElement.style.display = "inline-block"; this._element.appendChild(this._innerElement); return this; }; guru.GUILabel.prototype.setPlaceholder = function(value) { if (this._innerElement) { this._innerElement.placeholder = value; } else { this._element.placeholder = value; } return this; }; guru.GUILabel.prototype.applyStyle = function(key, value) { if (typeof value === "Number") { value = value.toString() + "px"; } if (this._innerElement) { this._innerElement.style[key] = value; } else { this._element.style[key] = value; } return this; }; guru.GUILabel.prototype.setPosition = function(x, y) { this._element.style.position = "absolute"; this._element.style.top = y.toString() + "px"; this._element.style.left = x.toString() + "px"; return this; }; guru.GUILabel.prototype.setOnclick = function(onclick) { this.onclick = onclick; return this; }; guru.GUILabel.prototype.setValue = function(value) { this._value = value || ""; if(this._innerElement) { this._innerElement.innerHTML = this._value; } else { this._element.innerHTML = this._value; } }; } if (!guru.Canvas) { guru.Canvas = function(selector, options) { this._guiManager = null; this._element = document.querySelectorAll(selector)[0]; this._context = this._element.getContext("2d"); if (options) { if (options.width) this._element.width = options.width; if (options.height) this._element.height = options.height; if (options.fullscreen) { this._element.width = window.innerWidth; this._element.height = window.innerHeight; var oldResize = function() {}; if (window.onresize) oldResize = window.onresize; var that = this; window.onresize = function() { oldResize(); if(options.noResize) return; that._element.width = window.innerWidth; that._element.height = window.innerHeight; that.width = that._element.width; that.height = that._element.height; } if(options.css) { document.body.style.margin = "0"; this._element.style.display = "inline-block"; this._element.style.float = "left"; } } } this.width = this._element.width; this.height = this._element.height; }; guru.Canvas.prototype.clear = function(color) { if(color && color._css) { this._context.fillStyle = color._css; this._context.fillRect(0, 0, this.width, this.height); return this; } this._context.clearRect(0, 0, this.width, this.height); return this; }; guru.Canvas.prototype.render = function(renderable) { renderable.render(this._context); return this; }; guru.Canvas.prototype.setGUIManager = function(guiManager) { this._guiManager = guiManager; this._guiManager._container.style.position = "absolute"; this._guiManager._container.style.top = this._element.getBoundingClientRect().top.toString() + "px"; this._guiManager._container.style.left = this._element.getBoundingClientRect().left.toString() + "px"; this._guiManager._container.style.width = this.width.toString() + "px"; this._guiManager._container.style.height = this.height.toString() + "px"; return this; }; }
({ /** * aura method to be invoked from Master Flow * * @param {Component} * component * @param {Event} * event * @param {Helper} * helper * @return parameters to be sent to master component */ getAttributeMethod: function(component, event, helper) { var params = event.getParam('arguments'); params.Quotelst = component.get("v.Quotelst"); params.SelectedQuoteLine = component.get("v.SelectedQuoteLine"); console.log('************' + JSON.stringify(params)); params.navigate = true; //no validation in child components. Can move to next component return params; //returns to master component } })
import React, { Component } from "react" import PropTypes from "prop-types" import styled from "styled-components" import { connect } from "react-redux" import { Markdown } from "../common" import LessonActions from "../../redux/lessonStore" import { ReactComponent as SkipIcon } from "../../assets/images/skip.svg" const Container = styled.div` height: 100%; padding: 20px; ` const Title = styled.div` display: inline-block; font-family: "ThaiSans Neue"; font-style: normal; font-weight: bold; font-size: 30px; line-height: 39px; color: #c4c4c4; background-color: #202020; padding: 6px 30px; box-sizing: border-box; ` const MarkdownContainer = styled.div` font-family: "ThaiSans Neue"; color: #c4c4c4; background-color: #202020; height: calc(100% - 20px - 51px - 29px - 40px); padding: 10px 30px; margin: 14px 0px; overflow: auto; ` const ButtonContainer = styled.div` display: flex; justify-content: center; ` const Button = styled.div` font-family: "ThaiSans Neue"; font-style: normal; font-weight: bold; font-size: 21px; line-height: 27px; border: 1px solid #61d0ff; box-sizing: border-box; border-radius: 3px; padding: 0px 22px; cursor: pointer; & svg { width: 12px; height: 12px; } ` const BackButton = styled(Button)` color: #61d0ff; margin-right: 10px; & svg { margin-right: 8px; transform: scaleX(-1); & path { fill: #61d0ff; } } ` const NextButton = styled(Button)` color: #272727; background-color: #61d0ff; & svg { margin-left: 8px; } ` class Content extends Component { render() { const lesson = this.props.lessons.filter(lesson => { return lesson.id === this.props.currentLesson })[0] if (lesson === undefined) { return null } const group = this.props.group.filter(group => { return group.id === lesson.lessonGroup })[0] return ( <Container> <Title>{`${group && group.name} - ${lesson.topic}`}</Title> <MarkdownContainer> <Markdown data={lesson.description} /> </MarkdownContainer> <ButtonContainer> {lesson.index > 0 ? ( <BackButton onClick={() => { const prevLesson = this.props.lessons[lesson.index - 1] this.props.dispatch( LessonActions.setCurrentLesson(prevLesson.id) ) }} > <SkipIcon /> Previous lesson </BackButton> ) : null} {lesson.index !== this.props.lessons.length - 1 ? ( <NextButton onClick={() => { const nextLesson = this.props.lessons[lesson.index + 1] if (this.props.learned.includes(nextLesson.id)) { this.props.dispatch( LessonActions.setCurrentLesson(nextLesson.id) ) return } this.props.dispatch(LessonActions.learnLesson(nextLesson.id)) }} > Next lesson <SkipIcon /> </NextButton> ) : null} </ButtonContainer> </Container> ) } } Content.propTypes = { dispatch: PropTypes.func, group: PropTypes.array, lessons: PropTypes.array, learned: PropTypes.array, currentLesson: PropTypes.number, } const mapStateToProps = state => ({ group: state.lessonStore.group, lessons: state.lessonStore.lessons, learned: state.lessonStore.learned, currentLesson: state.lessonStore.currentLesson, }) export default connect(mapStateToProps)(Content)
export function unique (l) { return Array.from(new Set(l)) } export function sentimentToPhrasesMap (expressedSentiments) { const map = {} expressedSentiments.forEach(expressedSentiment => { if (map[expressedSentiment.sentiment] === undefined) { map[expressedSentiment.sentiment] = [expressedSentiment.phrase] } else { map[expressedSentiment.sentiment].push(expressedSentiment.phrase) } }) return map } export function sentimentToPhrasesList (expressedSentiments) { const map = sentimentToPhrasesMap(expressedSentiments) return Object.keys(map).map(key => { return { sentiment: key, phrases: map[key] } }) } export function creatorToPhrasesMap (createdPhrases) { const map = {} createdPhrases.forEach(createdPhrase => { if (map[createdPhrase.creator] === undefined) { map[createdPhrase.creator] = [createdPhrase.phrase] } else { map[createdPhrase.creator].push(createdPhrase.phrase) } }) return map } export function creatorToPhrasesList (createdPhrases) { const map = creatorToPhrasesMap(createdPhrases) return Object.keys(map).map(key => { return { creator: key, phrases: map[key] } }) } export function sentimentToExpressersMap (expressedSentimentsExt) { const map = {} expressedSentimentsExt.forEach(es => { if (map[es.sentiment] === undefined) { map[es.sentiment] = [es.expresser] } else { map[es.sentiment].push(es.expresser) map[es.sentiment] = unique(map[es.sentiment]) } }) return map } export function sentimentToExpressersList (expressedSentimentsExt) { const map = sentimentToExpressersMap(expressedSentimentsExt) return Object.keys(map).map(key => { return { sentiment: key, expressers: map[key] } }) }
import RouterHelper from '../RouteHelper'; import React from 'react'; const title = '运输订单'; const prefix = '/order'; const children = [ require('./input').default, require('./import').default, require('./accept').default, require('./pending').default, require('./complete').default, require('./all').default, require('../track/trackOrder').default, ]; export default RouterHelper(prefix, title, children);
import React, {Component} from 'react'; import {ScrollView, Text} from 'react-native'; import styles from '../../assets/jammStyle'; import favicon from '../../assets/favicon.png'; export default class ButtonInstr extends Component { constructor(props) { super(props); this.buttonPress = this.buttonPress.bind(this); this.state = { buttonPress: false } } buttonPress() { this.setState({ buttonPress: !this.state.buttonPress }, () => { console.log('buttonpress: ', this.state.buttonPress ? 'true' : 'false'); }); } render() { return ( <ScrollView style={{height: 50}}> <Text>Instrument Menu</Text> <Text>Instrument Menu</Text> <Text>Instrument Menu</Text> <Text>Instrument Menu</Text> <Text>Instrument Menu</Text> </ScrollView> ) } }
var searchData= [ ['enforceconstraint2_2ecs_67',['EnforceConstraint2.cs',['../_enforce_constraint2_8cs.html',1,'']]] ];
// initial migration of users table export function up(knex, Promise) { return Promise.all([ knex.schema.createTable('users', function (table) { table.bigIncrements('id').primary().unsigned(); table.string('first_name', 50); table.string('last_name', 50); table.string('email', 50); table.string('password', 255); table.timestamps(); table.unique('email'); }) ]); } export function down(knex, Promise) { return Promise.all([ knex.schema.dropTable('users') ]); }
import React from 'react'; import { connect } from 'react-redux'; import { Platform, Text, TouchableOpacity, View, FlatList, Image, ActivityIndicator, Dimensions, ScrollView, ImageBackground } from 'react-native'; import ProgressCircle from '../components/ProgressCircle'; import BasicButton from '../components/BasicButton'; import {mS, mC} from '../constants/masterStyle'; // Actions import { secureComputeSMC, secureComputeFHESimple, getAnswers, secureComputeFHEBuffered } from '../redux/actions'; class Home extends React.Component { static navigationOptions = ({ navigation }) => { return { headerTitle: () => (<Text style={mS.screenTitle}>{'Enya Demonstrator'}</Text>), } } constructor (props) { super(props); const { compute } = this.props; const { account } = this.props.user; const { answers } = this.props.answer; const { progress } = this.props.fhe; this.state = { //answers percentAnswered: (answers.percentAnswered || 0), //0 to 100 //compute result: (compute.result || 0.0), //e.g. 14.5 current: (compute.current || false), //is the score valid/current? computing: (compute.computing || false), compute_type: (compute.compute_type || 'smc'), //FHE key gen FHE_key_inventory: (progress.FHE_key_inventory || 0), FHE_keys_ready: (progress.FHE_keys_ready || false), FHE_key_computing: (progress.FHE_key_computing || false), //this screen recalculating: false, }; } handleClickItem = (page) => { if (page === 'RESULT_SC') { this.props.navigation.navigate('ResultSC'); } else if (page === 'GIVE_ANSWERS') { this.props.navigation.navigate('Questionnaire'); } } UNSAFE_componentWillReceiveProps(nextProps) { const { compute } = nextProps; const { answers } = nextProps.answer; const { progress } = nextProps.fhe; const { account } = nextProps.user; this.setState({ percentAnswered: (answers.percentAnswered || 0.0), result: (compute.result || 0.0), current: (compute.current || false), computing: (compute.computing || false), compute_type: (compute.compute_type || 'smc'), FHE_key_inventory: (progress.FHE_key_inventory || 0), FHE_key_computing: (progress.FHE_key_computing || false), FHE_keys_ready: (progress.FHE_keys_ready || false), }) //go to fresh result once calculation is done if ( this.state.recalculating && !this.state.computing ) { this.setState({recalculating: false}); this.props.navigation.navigate('ResultSC'); } } handleSMCCalculate = () => { const {answers} = this.props.answer; this.props.dispatch( secureComputeSMC(answers) ); this.setState({recalculating:true,computing:true}); } handleFHECalculateS = () => { const {answers} = this.props.answer; this.props.dispatch(secureComputeFHESimple(answers)); this.setState({recalculating:true,computing:true}); } handleFHECalculateB = () => { const {answers} = this.props.answer; this.props.dispatch(secureComputeFHEBuffered(answers)); this.setState({recalculating:true,computing:true}); } render() { const { current, percentAnswered, result, computing, compute_type, FHE_keys_ready, FHE_key_inventory, FHE_key_computing } = this.state; var score = parseFloat(result).toFixed(1); return ( <View style={mS.containerCenterA}> <ScrollView contentContainerStyle={{alignItems: 'center'}} showsVerticalScrollIndicator={false} overScrollMode={'always'} > {/******************************************** THE FIRST BOX - Summary **********************************************/} <View style={mS.shadowBox}> <ImageBackground source={require('../assets/images/id.png')} style={{width: '100%', height: 50}}> <Text style={mS.boxTitle}>{'Overview'}</Text> </ImageBackground> {!current && <View style={mS.textBlock}> <Text style={mS.mediumDark}>{'We cannot compute your score yet.'}</Text> <Text style={mS.smallGray}>{'Please answer the questions about you. With that \ information, we can VALUE_PROP. Lorem ipsum dolor sit amet, consectetur adipiscing \ elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'}</Text> </View> } {current && (score <= 10) && <View style={mS.textBlock}> <Text style={mS.mediumDark}>{'We have securely computed your score.'}</Text> <Text style={mS.smallGray}>{'\nYour score is '} <Text style={[mS.smallGray, {fontWeight: 'bold'}]}>{score}%</Text> {'. Since your score is below 10, lorem ipsum dolor sit amet, \ consectetur adipiscing elit, sed do eiusmod tempor.'}</Text> </View> } {current && (score > 10) && <View style={mS.textBlock}> <Text style={mS.mediumDark}>{'We have securely calculated your score.'}</Text> <Text style={mS.smallGray}>{'\nYour score is '} <Text style={[mS.smallGray, {fontWeight: 'bold'}]}>{score}%</Text> {'. Since your score is above 10, lorem ipsum dolor sit amet, \ consectetur adipiscing elit, sed do eiusmod tempor.'}</Text> </View> } </View> {/******************************************** App info and status box **********************************************/} {computing && <View style={mS.shadowBox}> <ImageBackground source={require('../assets/images/id.png')} style={{width: '100%', height: 50}}> <Text style={mS.boxTitle}>{'Status'}</Text> </ImageBackground> {(compute_type == 'fhes') && <View style={mS.textBlock}> <Text style={mS.mediumDark}>{'Unbuffered FHE calculation.'}</Text> <Text style={mS.smallGray}>{"This is the 'slowest' way to compute a result. Expect the result to arrive in about 1 minute."}</Text> </View> } {(compute_type == 'fheb') && <View style={mS.textBlock}> <Text style={mS.mediumDark}>{'Buffered FHE calculation.'}</Text> <Text style={mS.smallGray}>{'This computation uses precomputed FHE keys to provide a better user experience.'}</Text> </View> } {(compute_type == 'smc') && <View style={mS.textBlock}> <Text style={mS.mediumDark}>{'Secure Multiparty Computation.'}</Text> <Text style={mS.smallGray}>{'This is the fastest way to compute a result.'}</Text> </View> } </View> } {/******************************************** THE THIRD BOX - SMC **********************************************/} <View style={mS.shadowBox}> <ImageBackground source={require('../assets/images/id.png')} style={{height: 50}}> <Text style={mS.boxTitle}>{'Secure Computation'}</Text> </ImageBackground> <View style={{display: 'flex', flexDirection: 'row'}}> <View style={mS.smc}> {/*'there is an SC result - allow people to view the result and to update their answers'*/} {current && <View> <BasicButton text={'View Result'} width="80%" onClick={()=>this.handleClickItem('RESULT_SC')} /> <TouchableOpacity style={{marginTop: 20}} hitSlop={{top: 30, bottom: 30, left: 30, right: 30}} onPress={()=>this.handleClickItem('GIVE_ANSWERS')}> <Text style={mS.largeAction}>{'Change Answers and Recompute'}</Text> </TouchableOpacity> </View> } {/*'no SMC result - prompt people to answer questions and to give/update their answers'*/} {!current && (percentAnswered < 100) && <View> <TouchableOpacity hitSlop={{top: 30, bottom: 30, left: 30, right: 30}} onPress={()=>this.handleClickItem('GIVE_ANSWERS')} > <Text style={mS.largeAction}>{'Complete my information'}</Text> </TouchableOpacity> <Text style={[mS.smallGray, {marginTop: 5}]}>{'to get personalized recommendations.'}</Text> </View> } {/*'no SMC result - but we have all the data and need to recalculate'*/} {!current && (percentAnswered === 100) && <View> <Text style={mS.smallGray}>{'All questions answered'}</Text> <View style={{marginTop: 20}}> <BasicButton text={'SMC Compute'} width="100%" onClick={this.handleSMCCalculate} enable={!computing} /> </View> <View style={{marginTop: 20}}> <BasicButton text={'FHE_S Compute'} width="100%" onClick={this.handleFHECalculateS} enable={!computing} /> </View> <View style={{marginTop: 20}}> <BasicButton text={'FHE_B Compute'} width="100%" onClick={this.handleFHECalculateB} enable={!computing} keys_ready={FHE_keys_ready} /> </View> </View> } </View> {/*the right side of the SMC panel*/} <View style={mS.smcRight}> {current && <View> <Text style={[mS.gray, {textAlign: 'center', fontWeight: 'bold', fontSize: 30}]}>{score}%</Text> <Text style={[mS.smallGray, {textAlign: 'center'}]}>{'Your Score'}</Text> </View> } {/*'not enough data - display progress answering questions'*/} {!current && !computing && <View style={mS.circleProgress}> <ProgressCircle percent={percentAnswered}> <Text style={mS.progressIcon}>{`${percentAnswered}%`}</Text> </ProgressCircle> <View> <Text style={mS.progressText}>{'Questions Answered'}</Text> </View> </View> } {/*show progress indicator when calculating risk*/} {computing && <View style={mS.circleProgress}> <ActivityIndicator size="large" color='#33337F' /> <Text style={[mS.progressText]}>{'Computing'}</Text> </View> } </View> </View> </View> </ScrollView> </View>); }} const mapStateToProps = state => ({ user: state.user, answer: state.answer, compute: state.compute, fhe: state.fhe, }); export default connect(mapStateToProps)(Home);
const env = process.env; const http = require('http') const port = 5000 function sortObject(o) { var sorted = {}, key, a = []; for (key in o) { if (o.hasOwnProperty(key)) { a.push(key); } } a.sort(); for (key = 0; key < a.length; key++) { sorted[a[key]] = o[a[key]]; } return sorted; } const requestHandler = (request, response) => { response.writeHead(200, {'Content-Type': 'application/json'}); response.end(JSON.stringify(sortObject(process.env), null, 4) + "\n"); } const server = http.createServer(requestHandler); server.listen(port, (err) => { if (err) { return console.log('something bad happened', err); } console.log(`server is listening on ${port}`); })
import React from "react"; import "./App.css"; import 'bootstrap/dist/css/bootstrap.min.css'; import Template from "./template/Template"; function App() { return ( <> <Template/> </> ); } export default App;
//此页面利用reducer进行数据的处理,使得数据处理更加高效 //immutable的特点:1、一旦创建,就不能被更改,任何修改或添加删除都会返回一个新的immutable对象 //2、对象书中一个节点发生变化,只修改这个节点和受它影响的节点,其他节点进行共享 import * as types from './actionTypes.js' import { fromJS } from 'immutable' const defaultState = fromJS({//初始化默认数据,用fromJS方法将数据转换为immutable对象 list:['吃饭','睡觉','打豆豆'], task:'' }) //reducer是一个纯函数(有固定的输入就用固定的输出) //reducer不能直接改变state,因为sate由store进行管理,而store中的数据由所有组件共享, //可以用一个newState来改变自身state,而且getState获取的state数据还是是store里面的state //将初始化默认数据赋给reducer函数里的state并返回出去 export default (state = defaultState,action)=>{ //当action里的type是'change_item'时,将action里的payload赋给newstate里的task if(action.type == types.CHANG_ITEM){//处理输入时数据变化 // const newState = JSON.parse(JSON.stringify(state) // newState.task = action.payload; // return newState; //map对象要用set方法设置 return state.set('task',action.payload) } if(action.type == types.ADD_ITEM){//处理添加时数据变化 // const newState = JSON.parse(JSON.stringify(state)) // newState.list.push(newState.task)//将输入框的数据添加进newState的List(增加) // newState.task = '' // return newState const list = [...state.get('list')]; list.push(state.get('task')) return state.merge({//设置多个属性不能用set方法,要用merge方法 list:list, task:'' }) } if(action.type == types.DEL_ITEM){//处理删除时数据变化 // const newState = JSON.parse(JSON.stringify(state)) // newState.list.splice(action.payload,1)//根据index截取list里的莫一项(删除) // return newState const list = [...state.get('list')] list.splice(action.payload,1) return state.set('list',list) } if(action.type == types.DATA_LOAD){ // const newState = JSON.parse(JSON.stringify(state)) // newState.list = action.payload // return newState return state.set('list',action.payload) } return state;//如果上述都没有,返回state }
// Pokemon import React, { Component } from 'react'; import * as actionCreators from './../../../../store/actions' import { Grid, Image } from 'react-bootstrap' import fetch from 'isomorphic-fetch'; import './style.css' import Img from './../../../elements/Img' class Pokemon extends Component { constructor(props) { super(props); this.state = { pokemon: null, } } handlePokemonClick(id) { console.log('pokemonClick') actionCreators.updateCurrentPokemonId(id) } componentDidMount() { let url = `https://pokeapi.co/api/v2/pokemon/${this.props.id}` fetch(url) .then((response) => { return response.json() }) .then((json) => { this.setState({ pokemon: json, }) }) } render () { const { pokemon } = this.state if (pokemon === null) { return null; } // console.log(pokemon.species.name) // works return ( <div className='pokemon-card'> <p className='pokemon-name'>{pokemon.species.name}</p> <Img src={this.props.image} alt='picture of pokemen' onClick={this.handlePokemonClick(this.props.id)}/> </div> ) } } export default Pokemon;
import Link from 'next/link' import moment from 'moment' import renderHTML from 'react-render-html' import { API } from '../../config' const Card = ({ blog }) => { const blogCatagories = () => { return blog.catagories.map((c, i) => ( <Link key={i} href={`/catagories/${c.slug}`}> <a className="btn btn-primary ml-1 mr-1 mt-3">{c.name}</a> </Link> )) } const blogTags = () => { return blog.tags.map((t, i) => ( <Link key={i} href={`/tags/${t.slug}`}> <a className="btn btn-outline-primary ml-1 mr-1 mt-3">{t.name}</a> </Link> )) } return ( <div> <div className="lead pb-4"> <header> <Link href={`/blogs/${blog.slug}`}> <a><h1 className='font-weight-bold pt-3 pb-3'>{blog.title}</h1></a> </Link> </header> <section> <p className="mark ml-1 pb-2 pt-2"> Written by <Link href={`${blog.postedBy.profile}`}><a>{blog.postedBy.username}</a></Link> | Published {moment(blog.updatedAt).fromNow()} </p> </section> <section> {blogCatagories()} {blogTags()} <br /> <br /> </section> <section className="row"> <div className="col-md-4"> <section> {blog.photo ? <img src={`${API}/blog/photo/${blog.slug}`} alt={`${blog.title}`} style={{ maxHeight: 'auto', width: '100%' }} className="img img-fliud" /> : ''} </section> </div> <div className="col-md-8"> <section> <div className='pb-3'> {renderHTML(blog.excerpt)} </div> <Link href={`/blogs/${blog.slug}`}> <a className='btn btn-primary pt-2'>Read More</a> </Link> </section> </div> </section> </div> </div> ) } export default Card
import { Mongo } from 'meteor/mongo'; import SimpleSchema from 'simpl-schema'; SimpleSchema.extendOptions(['autoform']); export const Carts = new Mongo.Collection('carts'); Carts.attachSchema(new SimpleSchema({ username: { type: String, label: "Username", optional: false, }, seller: { type: String, label: "Seller", optional: false, }, title: { type: String, label: "Title", optional: false, }, qty: { type: Number, label: "Quantity", min: 1, optional: false, }, })); Carts.allow ({ insert: function() { return true; }, });
import { invertColor } from './../helpers.js'; export const LegoDetail = (brick) => { let block = `<section class="block-wrapper" style="background-color:#${brick.ColorHex}"> <h3>Name: ${brick.LegoName.toUpperCase()}</h3> <div class="block-years">Manufactured ${brick.YearFrom} - ${brick.YearTo}</div> `; const link = brick.ColorstreamLinkImage; const notes = brick.Notes; // If Else Statements... // If 'link' exists and there are notes, wrap in link and append note to end. if (link !== "" && notes !== "") { return ( `<a href="${link}" target="_blank" style="color:#${invertColor(brick.ColorHex)}"> ${block} <p>${notes}</p> </a> </section> `); // If link exists and there are no notes, wrap in link } else if (link !== "" && notes === "") { return ( `<a href="${link}" target="_blank" style="color:#${invertColor(brick.ColorHex)}"> ${block} </a> </section> `); // If link does not exist, but there are notes, append notes. } else if (link === "" && notes !== "") { return ( ` ${block} <p>${notes}</p> </section> `); // If link does not exist, and notes do not exist, just return block } else { return ( ` ${block} </section> `); } }
import React, { useContext } from 'react'; import { UserContext } from '../views/context/User'; // import '../custom.css' function AuthenticatedUser(props) { const { user, loading } = useContext(UserContext) return ( <div className="text-nowrap"> { loading ? <div>Loading . . . </div> : <div>{user.name}</div> } </div> ) } export default AuthenticatedUser
// Метод ФУНКЦИИ в объекте const playList = { name: "My list", rating: 5, tracks: ["track-1", "track-2", "track-3"], // trackCount: 3, // старый способ написания функции getName(x) { console.log("This is function getName :)"); }, // modern way to declare function in object changeName(newName) { this.name = newName; }, addTrack(track) { this.tracks.push(track); // this.trackCount = this.tracks.length; }, updateRating(newRating) { this.rating = newRating; }, getTrackCount() { return this.tracks.length; }, }; // call a function playList.getName("Try to call a function"); playList.changeName("Новое имя плейлиста"); playList.addTrack("New track"); playList.addTrack("New track - 2"); playList.updateRating(10); console.log(playList); console.log(playList.getTrackCount());
$(function () { $('.slider').slick({ cssEase: 'ease-in', dots: false, autoplay: true, autoplaySpeed: 2000, arrows: true }); $('.tabs-stage > div').hide(); $('.tabs-stage > div:nth-child(1)').show(); $('.tabs-nav > li:first-child a').addClass('tab-active'); $('.tabs-nav > li > a').on('click', function (event) { event.preventDefault(); $('.tabs-nav > li a').removeClass('tab-active'); $(this).addClass('tab-active'); $('.tabs-stage > div').hide(500); $($(this).attr('href')).show(500); }); $('.list_lesson').perfectScrollbar(); $('.vid-list-container').perfectScrollbar(); var acc = document.getElementsByClassName("accordion"); var i; for (i = 0; i < acc.length; i++) { acc[i].onclick = function () { this.classList.toggle("active_accordion"); var panel = this.nextElementSibling; if (panel.style.maxHeight) { panel.style.maxHeight = null; } else { panel.style.maxHeight = panel.scrollHeight + "px"; } } } var description = $('.vid-list > .vid-item'); description.each(function (i, obj) { $(obj).on('click', function (event) { var v_desc = $(this).children('.desc').text(); $('.vid-container > h4').text(v_desc); }); }); $('.false').click(function () { $(this).css('background-color', '#ff7058'); $('.test_overlay').css('opacity', '1'); }); $('.true').click(function () { $(this).css('background-color', '#70d958'); $('.test_overlay').css('opacity', '1'); }); $(".hamburger_collapsed").click(function () { // alert('hello'); $('.list_video').toggleClass("hamburger_block"); $('.video_container .vid-list-container').toggleClass("hamburger_block2"); $(this).toggleClass("hamburger-expanded"); }); new WOW().init(); });
import IStore from '../store/IStore.js'; import { Model } from '../lib/mvc.js'; let fileWatches, disableWatch; const fs = window.require("fs"), path = window.require('path'); class FileSystem { static "@inject" = { store:IStore, pool:"pool", root: [Model, {scope:"root"}] } onSetSkin( skin ){ nw.Window.get().resizeTo( skin.width, skin.height ); } embed(url){ let parent = document.getElementById("embed"); let wv = parent.children[0]; document.getElementById("main").classList.add("embed"); if( !wv ){ wv = document.createElement("webview"); parent.appendChild( wv ); } wv.src = url; } initWatches(){ if( !fs ) return; fileWatches = fileWatches || []; fileWatches.forEach( w => { w.file.close(); if( w.hnd ) clearTimeout( w.hnd ); }); fileWatches.length = 0; } saveFile( name, content ){ let lsp = this.root.getItem("ram.localSourcePath", ""); let fulltarget = path.resolve( lsp, name ); disableWatch = fulltarget; this.store.saveFile( name, content ); setTimeout( _=>{ if( disableWatch === fulltarget ) disableWatch = null; }, 500); } watchFile( ffp, cb ){ let lsp = this.root.getItem("ram.localSourcePath", ""); if( !fs || !lsp || fileWatches.find( x=>x.path == ffp) ) return; let watch, reload; let watcher = { path:ffp, name:ffp.substr( lsp.length+1 ) }; let loadFile = _ => { fs.readFile( ffp, 'utf-8', (err,txt) => { if( err ) return cb( watcher.name ); cb( watcher.name, txt ); watch(); if( fileWatches.indexOf(watcher) == -1 ) fileWatches.push(watcher); }); }; watch = () => { if( watcher.file ) watcher.file.close(); watcher.file = fs.watch( watcher.path, {persistent:false}, _ => { if( watcher.hnd ) clearTimeout(watcher.hnd); watcher.hnd = setTimeout( reload.bind( this, watcher ), 50 ); }); }; reload = (watcher) => { if( disableWatch == watcher.path ) setTimeout( _ => watch(watcher), 100 ); else loadFile(); }; loadFile(); } } module.exports = FileSystem;
function smoothScroll(target,duration){ let target = document.querySelector(target); console.log(target); } smoothScroll("#header-scroll",1000);
const assert = require('assert'); const Dinosaur = require('../dinosaur.js'); const Park = require('../park.js'); describe('Park', function(){ let tyrannosaurus; let pteradactyl; let dilophosaurus; let park; beforeEach(function(){ tyrannosaurus = new Dinosaur("Tyrannosaurus", 3); pteradactyl = new Dinosaur("Pteradactyl", 1); dilophosaurus = new Dinosaur("Dilophosaurus", 2); park = new Park(); }) it('enclosure starts off empty', function(){ assert.strictEqual(park.enclosure.length, 0); }) it('can add dino to enclosure', function(){ park.addDinosaur(tyrannosaurus); assert.strictEqual(park.enclosure.length, 1); }) it('can clear all dinos', function(){ park.addDinosaur(tyrannosaurus); park.addDinosaur(tyrannosaurus); park.removeAllDinos(); assert.strictEqual(park.enclosure.length, 0); }) it('can remove all tyrannosaurus dinos', function(){ park.addDinosaur(tyrannosaurus); park.addDinosaur(tyrannosaurus); park.addDinosaur(pteradactyl); park.removeAllDinosByType("Tyrannosaurus"); assert.strictEqual(park.enclosure.length, 1); assert.deepEqual(park.enclosure, [pteradactyl]); }) it('can get all dinos offspring rate above 2', function(){ park.addDinosaur(tyrannosaurus); park.addDinosaur(tyrannosaurus); park.addDinosaur(pteradactyl); let dinoHighOffSpringRate = [tyrannosaurus, tyrannosaurus]; assert.deepEqual(park.findAllDinosOffspringRateAboveAmount(2), dinoHighOffSpringRate); }) it('should be able to calculate number of dinosaurs after 1 year starting with 1 dinosaur', function(){ park.addDinosaur(tyrannosaurus); assert.strictEqual(park.calculateDinosaurs(1), 4); }); it('should be able to calculate number of dinosaurs after 2 years starting with 1 dinosaur', function(){ park.addDinosaur(tyrannosaurus); assert.strictEqual(park.calculateDinosaurs(2), 16); }); it('should be able to calculate number of dinosaur after year two starting with 2 dinosaurs', function(){ park.addDinosaur(tyrannosaurus); park.addDinosaur(dilophosaurus); assert.strictEqual(park.calculateDinosaurs(2), 25); }); })
'use strict'; module.exports = { check(rules, data) { return this.app.validator.validate(rules, data); }, v(rules, data) { if (!data) { data = Object.assign({}, this.query, this.request.body, this.params); } const errors = this.check(rules, data); if (errors) { const { errorStatus, errorMessage, errorCode } = this.app.config.httpParameter; this.throw(errorStatus, errorMessage, { code: errorCode, errors, }); } return data; }, };
const puppeteer = require('puppeteer'); const GetItems = async (searchTerm ) => { const browser = await puppeteer.launch({ headless: false, defaultViewport: null }); const page = await browser.newPage(); await page.goto( `https://www.jumia.co.ke/catalog/?q=${encodeURI(searchTerm)}` ); const itemList = await page.waitForSelector( 'div >section> div > article >a.core' ).then(()=> page.evaluate(() => { const itemArray =[]; const itemNodeList = document.querySelectorAll('div >section> div > article >a'); //console.log(itemNodeList) // to iterate thourgh nonelist itemNodeList.forEach(item => { const itemTitle= item.getAttribute("data-name") //console.log(itemTitle) const itemPrice = item.querySelector(" div.info > div.prc").innerHTML //console.log(itemPrice) const itemURL = `https://www.jumia.co.ke${item.getAttribute('href')}`; //console.log(itemURL); const itemImg = item.querySelector('div > img').getAttribute('data-src') //console.log(itemImg) //push info into array itemArray.push({ itemTitle, itemPrice, itemURL, itemImg }) }); //console.log(itemArray); return itemArray; }) ) //page.evaluate allows us to get browser content .catch(() => console.log('selector error')); console.log(itemList) // instead of loggin this info lets return it return itemList; }; GetItems('iphone 10');
import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter } from "react-router-dom"; import { createStore, applyMiddleware } from "redux"; import logger from "redux-logger"; import { Provider } from "react-redux"; import { composeWithDevTools } from "redux-devtools-extension"; import App from "./components/App"; import loginReducer from "./reducers/loginReducer"; import "./styles.css"; const spaStore = createStore( loginReducer, composeWithDevTools(applyMiddleware(logger)) ); ReactDOM.render( <Provider store={spaStore}> <BrowserRouter> <App /> </BrowserRouter> </Provider>, document.getElementById("root") ); /* STORE: {loggedIn:false} ACTIONS: {type:"LOGIN"} {type:"LOGOUT"} */