text
stringlengths
7
3.69M
// server.js // set up ====================================================================== // get all the tools we need var express = require('express'); var app = express(); var port = process.env.PORT || 8080; var mongoose = require('mongoose'); var passport = require('passport'); var flash = require('connect-flash'); var path = require('path'); var configDB = require('./config/database.js'); var sessionStore = new express.session.MemoryStore(); // configuration =============================================================== mongoose.connect(configDB.url); // connect to our database require('./config/passport')(passport); // pass passport for configuration var myLogger = function(req, res, next) { console.log('GOT REQUEST: '+req.url); next(); }; app.configure(function() { // set up our express application //app.use(express.logger('dev')); // log every request to the console app.use(myLogger); app.use(express.cookieParser()); // read cookies (needed for auth) app.use(express.bodyParser({ uploadDir: 'Docs/uploaded' //keepExtentions: true, //limit: 10000000, //defer: true })); // get information from html forms app.set('view engine', 'ejs'); // set up ejs for templating // required for passport app.use(express.session({ store: sessionStore, secret: 'ilovescotchscotchyscotchscotch' })); // session secret app.use(passport.initialize()); app.use(passport.session()); // persistent login sessions //app.use(flash()); // use connect-flash for flash messages stored in session app.use(express.static(path.join(__dirname, 'angularjs'))); }); // websocket =================================================================== var ws = require("nodejs-websocket"); var connections = {}; //var newconn = {}; // Scream server example: "hi" -> "HI!!!" var server = ws.createServer(function (conn) { console.log("New connection"); //console.log(conn); conn.nickname = null; conn.on("text", function (str) { console.log("Received "+str); if(conn.nickname === null) { conn.nickname = str; connections[str] = conn; //console.log(connections); } else { var obj = JSON.parse(str); connections[obj.to].sendText(JSON.stringify({from: obj.from, msg: obj.msg})); } }) conn.on("close", function (code, reason) { console.log("Connection closed"); }) }).listen(8000); // routes ====================================================================== require('./app/routes.js')(app, passport, sessionStore, server); // load our routes and pass in our app and fully configured passport // launch ====================================================================== app.listen(port); console.log('The magic happens on port ' + port);
const UserRolePointer = 1; const UserRoles = { User: UserRolePointer, Admin: UserRolePointer + 1, SuperAdmin: UserRolePointer + 2 } module.exports = UserRoles
import React, { useState } from 'react'; const AddRent = () => { const [info, setInfo] = useState({}); const [file, setFile] = useState(null); const handleBlur = e => { const newInfo = {...info}; newInfo[e.target.name] = e.target.value; setInfo(newInfo); } const handleFileChange = (e) => { const newFile = e.target.files[0]; setFile(newFile); } const handleSubmit = (e) => { const formData = new FormData() formData.append('file', file); formData.append('title', info.title); formData.append('location', info.location); formData.append('bathroom', info.bathroom); formData.append('price', info.price); formData.append('bedroom', info.bedroom); fetch('https://powerful-fjord-39182.herokuapp.com/addRentHouse', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { console.log(data); alert('Service Added successfully!'); }) .catch(error => { console.error(error); alert('Fill all fields properly.'); }) e.preventDefault(); e.target.reset(); } return ( <section id="order" className="p-4"> <h3>Add Service</h3><br /> <div className="container"> <form onSubmit={handleSubmit}> <div className="row"> <div className="col-md-8 col-lg-6"> <label ><b>Service Title</b></label> <input type="text" onBlur={handleBlur} name="title" placeholder="Enter title" className="form-control " required /> <br /> <label ><b>Location</b></label> <input type="text" onBlur={handleBlur} name="location" placeholder="Enter Location" className="form-control" required /> <br /> <label ><b>No. of Bedrooms</b></label> <input type="text" onBlur={handleBlur} name="bedroom" placeholder="Enter Bedrooms" className="form-control" required /> </div> <div className="col-md-4 col-lg-6"> <label ><b>Price</b></label> <input type="text" onBlur={handleBlur} name="price" placeholder="Enter Price" className="form-control" required /> <br /> <label ><b>No. of Bathrooms</b></label> <input type="text" onBlur={handleBlur} name="bathroom" placeholder="Enter Bathrooms" className="form-control" required /> <br /> <div className="col-6 my-1"> <label><b>Thumbnail</b></label> <input type="file" onChange={handleFileChange} name="photo" /> </div> <br /> </div> </div> <br/> <input type="submit" className="btn btn-success ml-3 px-4" value="Submit"/> </form> </div> </section> ); }; export default AddRent;
// Foursquare API access secrets var FOURSQUARE_CLIENT_ID = ""; var FOURSQUARE_CLIENT_SECRET = ""; // OpenWeatherMap API key var OPENWEATHERMAP_API_KEY = ""; // News Search API key var BINGNEWSSEARCH_API_KEY = "";
import { call, put, select } from 'redux-saga/effects'; import { toast } from 'react-toastify'; import Api from '../../services/api'; import { Creators as DeveloperActions } from '../ducks/developer'; export function* addDeveloper(action) { try { const { data } = yield call(Api.get, `/users/${action.payload.developer.developerInput}`); const isDuplicate = yield select(({ developers }) => developers.data.find(dev => dev.id === data.id)); if (isDuplicate) { yield put(DeveloperActions.addDeveloperFailure('Usuário já adicionado.')); toast.warn('Usuário já adicionado.', { position: toast.POSITION.TOP_CENTER, }); } else { const { latitude, longitude } = action.payload.developer.lngLat; const developerData = { id: data.id, name: data.name, login: data.login, img: data.avatar_url, longitude, latitude, }; yield put( DeveloperActions.addDeveloperSuccess(developerData, 'Usuário adicionado com sucesso.'), ); toast.success('Usuário adicionado com sucesso.', { position: toast.POSITION.TOP_CENTER, }); } } catch (error) { yield put(DeveloperActions.addDeveloperFailure('Usuário não encontrado...')); toast.error('Usuário não encontrado...', { position: toast.POSITION.TOP_CENTER, }); } }
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number} */ var distributeCoins = function(root) { var ans= {val: 0}; dfs(root, ans); return ans.val; }; function dfs(node, ans) { if(!node) return 0; var L = dfs(node.left, ans); var R = dfs(node.right, ans); ans.val = ans.val + Math.abs(L) + Math.abs(R); return node.val + L + R -1; }
export default (state = {}, action) => { switch (action.type) { case 'SET_ACTIVE_NOTES': let newState = Object.assign({}, state); newState = (action.payload.notes && action.payload.notes instanceof Array) ? [...action.payload.notes] : []; return newState; case 'DELETE_NOTE': delete newState[action.payload.noteId]; return newState; default: return state; } }
import React, { useState } from 'react' import { withTranslation } from 'react-i18next' import { Row, Col, Card, CardHeader, FormGroup, Form, Input, Button } from 'reactstrap' function Stripe(props) { const publishableKey = useState(props.publishableKey || '') const secretKey = useState(props.secretKey || '') const [publishableKeyError] = useState(null) const [secretKeyError] = useState(null) const { t } = props return ( <Row className="mt-3"> <div className="col"> <Card className="shadow"> <CardHeader className="border-0"> <h3 className="mb-0">Stripe</h3> </CardHeader> <Form> <div className="pl-lg-4"> <Row> <Col md="8"> <label className="form-control-label" htmlFor="input-publishablekey"> {t('Publishable Key')} </label> <FormGroup className={ publishableKeyError === null ? '' : publishableKeyError ? 'has-success' : 'has-danger' }> <Input className="form-control-alternative" id="input-publishablekey" placeholder="e.g pk_test_lEaBbVGnTkzja2FyFiNlbqtw" type="password" defaultValue={publishableKey[0]} disabled></Input> </FormGroup> </Col> </Row> <Row> <Col md="8"> <label className="form-control-label" htmlFor="input-secretkey"> {t('Secret Key')} </label> <FormGroup className={ secretKeyError === null ? '' : secretKeyError ? 'has-success' : 'has-danger' }> <Input className="form-control-alternative" id="input-secretkey" placeholder="e.g sk_test_rKNqVc2tSkdgZHNO3XnPCLn4" type="password" defaultValue={secretKey[0]} disabled></Input> </FormGroup> </Col> </Row> <Row> <Col md="4"> <Button className="btn-block mb-2" type="button" color="primary" disabled size="lg"> {t('Save')} </Button> </Col> </Row> </div> </Form> </Card> </div> </Row> ) } export default withTranslation()(Stripe)
var Spotify = require("node-spotify-api"); var spotify = new Spotify({ id: "f975af9227df4eb1b9f131e3073b22db", secret: "2d83189fead745a8b9fc9f357ba0a69e", }); function Song() { this.findSongs = function(songSearch) { spotify .search({ type: 'track', query: songSearch }) .then(function(response) { for(var i = 0; i < response.tracks.items.length; i++) { var songData = [ "Artist: " + response.tracks.items[i].artists[0].name, "\nSong: " + response.tracks.items[i].name, "\nPreview: " + response.tracks.items[i].preview_url, "\nAlbum: " + response.tracks.items[i].album.name, "\n**************" ] console.log(songData.join(" ")); } // console.log(response); }) .catch(function(err) { console.log(err); }); } } module.exports = Song;
'use strict'; module.exports = { CORS: ['*'], PORT: 4000, AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY, AWS_REGION: process.env.AWS_REGION, AWS_BUCKET: process.env.AWS_BUCKET, LOB_API_KEY: process.env.LOB_API_KEY, SENDGRID_API_KEY: process.env.SENDGRID_API_KEY, SENDGRID_TEMPLATE_ID: process.env.SENDGRID_TEMPLATE_ID, TWITTER_CONSUMER_KEY: process.env.TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET: process.env.TWITTER_CONSUMER_SECRET, TWITTER_ACCESS_TOKEN_KEY: process.env.TWITTER_ACCESS_TOKEN_KEY, TWITTER_ACCESS_TOKEN_SECRET: process.env.TWITTER_ACCESS_TOKEN_SECRET };
import React, { Component } from 'react'; import '../App.css'; export class TodoItem extends Component { render() { return ( <div id="todoitem"> <p>{this.props.title}</p> <button type="submit">&#10003;</button> <button type="reset">X</button> </div> ) } } export default TodoItem
import styled from 'styled-components'; export const AlertStyle = styled.div` padding: 0.8rem; margin: 1rem 0; opacity: 0.9; background: ${(props) => `var(--${props.alertType}-color)`}; color: #333; `;
$(function () { var $img; var context; var canvas; var imageData; var imageDataOriginal; function fileOnload(e) { $img = $('<img>', { src: e.target.result }); canvas = $('#canvas')[0]; context = canvas.getContext('2d'); var MAX_WIDTH = 600; var MAX_HEIGHT = 400; var width = $img[0].width; var height = $img[0].height; if (width > height) { if (width > MAX_WIDTH) { height *= MAX_WIDTH / width; width = MAX_WIDTH; } } else { if (height > MAX_HEIGHT) { width *= MAX_HEIGHT / height; height = MAX_HEIGHT; } } canvas.height = height; canvas.width = width; $img.load(function () { context.drawImage(this, 0, 0, width, height); imageData = context.getImageData(0, 0, this.width, this.height); imageDataOriginal = context.getImageData(0, 0, this.width, this.height); setTimeout(function() { context.putImageData(imageData, 0, 0); }, 1000); }); } function getRed(imageData, x, y) { var index = (x + y * imageData.width) * 4; return imageData.data[index + 0]; } function getGreen(imageData, x, y) { var index = (x + y * imageData.width) * 4; return imageData.data[index + 1]; } function getBlue(imageData, x, y) { var index = (x + y * imageData.width) * 4; return imageData.data[index + 2]; } function setPixel(imageData, x, y, r, g, b, a) { var index = (x + y * imageData.width) * 4; imageData.data[index + 0] = r; imageData.data[index + 1] = g; imageData.data[index + 2] = b; imageData.data[index + 3] = a; } function resetFilter() { context.putImageData(imageDataOriginal, 0, 0); imageData = context.getImageData(0, 0, imageDataOriginal.width, imageDataOriginal.height); } function filtroNegativo() { resetFilter(); for (var x = 0; x < imageData.width; x++) { for (var y = 0; y < imageData.height; y++) { setPixel(imageData, x, y, 255 - getRed(imageData, x, y), 255 - getGreen(imageData, x, y), 255 - getBlue(imageData, x, y), 255); } } context.putImageData(imageData, 0, 0); } function filtroBrillo() { resetFilter(); for (var x = 0; x < imageData.width; x++) { for (var y = 0; y < imageData.height; y++) { setPixel(imageData, x, y, (getRed(imageData, x, y) + 50), (getGreen(imageData, x, y) + 50), (getBlue(imageData, x, y) + 50), 255); } } context.putImageData(imageData, 0, 0); } function filtroCustom(valR, valG, valB, reset) { if(reset) resetFilter(); for (var x = 0; x < imageData.width; x++) { for (var y = 0; y < imageData.height; y++) { setPixel(imageData, x, y, (getRed(imageData, x, y) * valR), (getGreen(imageData, x, y) * valG), (getBlue(imageData, x, y) * valB), 255); } } context.putImageData(imageData, 0, 0); } function filtroBlancoYNegro() { resetFilter(); for (var x = 0; x < imageData.width; x++) { for (var y = 0; y < imageData.height; y++) { var r = getRed(imageData, x, y); var g = getGreen(imageData, x, y); var b = getBlue(imageData, x, y); var val = (r + g + b) / 3; setPixel(imageData, x, y, val, val, val, 255); } } context.putImageData(imageData, 0, 0); } function aplicarFiltroMatriz(weights, opaque, reset) { if(reset) resetFilter(); var side = Math.round(Math.sqrt(weights.length)); var halfSide = Math.floor(side/2); var src = imageData.data; var sw = imageData.width; var sh = imageData.height; // pad output by the convolution matrix var w = sw; var h = sh; var output = context.createImageData(w, h); var dst = output.data; // go through the destination image pixels var alphaFac = opaque ? 1 : 0; for (var y=0; y<h; y++) { for (var x=0; x<w; x++) { var sy = y; var sx = x; var dstOff = (y*w+x)*4; // calculate the weighed sum of the source image pixels that // fall under the convolution matrix var r=0, g=0, b=0, a=0; for (var cy=0; cy<side; cy++) { for (var cx=0; cx<side; cx++) { var scy = sy + cy - halfSide; var scx = sx + cx - halfSide; if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) { var srcOff = (scy*sw+scx)*4; var wt = weights[cy*side+cx]; r += src[srcOff] * wt; g += src[srcOff+1] * wt; b += src[srcOff+2] * wt; a += src[srcOff+3] * wt; } } } dst[dstOff] = r; dst[dstOff+1] = g; dst[dstOff+2] = b; dst[dstOff+3] = a + alphaFac*(255-a); } } imageData = output; context.putImageData(imageData, 0, 0); } function download(){ var a = document.createElement("a"); a.href = canvas.toDataURL("image/png"); a.download = "descarga.png"; a.click(); } $('#backButtonConteiner').hide(); $('#downloadButtonConteiner').hide(); $('#filters').hide(); $('#backButtonConteiner').click(function () { $('#backButtonConteiner').hide(); $('#downloadButtonConteiner').hide(); $('#inputConteiner').show(); $('#filters').hide(); canvas.height = 0; canvas.width = 0; canvas = undefined; }); $('#downloadButtonConteiner').click(function () { download(); }); $('#f-negative').click(function () { filtroNegativo(); }); $('#f-brillo').click(function () { filtroBrillo(); }); $('#f-blancoYNegro').click(function () { filtroBlancoYNegro(); }); $('#f-custom').click(function () { filtroCustom(0.675, 0.275, 0.375, true); }); $('#f-sharp').click(function () { aplicarFiltroMatriz([0, -1, 0, -1, 5, -1, 0, -1, 0 ], 0.5, true); }); $('#f-border').click(function () { aplicarFiltroMatriz([1, 1, 1, 1, 0.7, -1, -1, -1, -1 ], 0.5, true); }); $('#f-blur').click(function () { aplicarFiltroMatriz([ 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9 ], 0.5, true); }); $('#f-custom-m').click(function () { resetFilter(); filtroCustom(0.675, 0.475, 0.675, false); aplicarFiltroMatriz([ 1, 1, -1, 1, -1, 1, 1, 1, -1 ], 0.5, false); }); $('#resetFilter').click(function () { resetFilter(); }); $('#file-input').change(function (e) { $('#filters').show(); $('#backButtonConteiner').show(); $('#downloadButtonConteiner').show(); $('#inputConteiner').hide(); var file = e.target.files[0], imageType = /image.*/; if (!file.type.match(imageType)) return; var reader = new FileReader(); reader.onload = fileOnload; reader.readAsDataURL(file); reader = new FileReader(); reader.onload = fileOnload; reader.readAsDataURL(file); $('#file-input').val(''); }); });
let page_count = 1; const speed = 12; window.addEventListener('scroll', snap); function snap() { if (this.oldScroll == null) { this.oldScroll = 0; } if (this.oldScroll < this.scrollY) { window.removeEventListener('scroll', snap); downscroller(); } else { page_count--; window.removeEventListener('scroll', snap); upscroller(); } this.oldScroll = this.scrollY; } function downscroller() { let dist = (page_count * window.innerHeight) - this.scrollY; if (dist <= speed) { window.scrollBy(0, dist); page_count++; this.oldScroll = this.scrollY setTimeout(() => window.addEventListener('scroll', snap), 50) return; } window.scrollBy(0, speed); setTimeout(downscroller, 1); } function upscroller() { let dist = this.scrollY - (page_count * window.innerHeight); console.log(dist); if (dist <= speed) { window.scrollBy(0, -dist); this.oldScroll = this.scrollY; setTimeout(() => window.addEventListener('scroll', snap), 50) return; } window.scrollBy(0, -speed); setTimeout(upscroller, 1); }
import React, { Component, createRef } from 'react'; import { SkipPrevious } from '../components/icons/av/SkipPrevious'; import { SkipNext } from '../components/icons/av/SkipNext'; import { Play } from '../components/icons/av/Play'; import { Pause } from '../components/icons/av/Pause'; import { withAudioEngine } from './WebAudioPlayer'; import styled from 'styled-components'; const Cont = styled.div` background: rgb(255,255,255); position: fixed; bottom: 0; left: 250px; width: calc(100% - 250px); height: 90px; z-index: 2000; ` const Details = styled.div` flex: 1; display: flex; flex-direction: column; justify-content: center; padding: 10px; ` const Volume = styled.div` flex: 1; display: flex; flex-direction: column; justify-content: center; align-items: flex-end; padding: 10px; ` const Actions = styled.div` flex: 1; display: flex; align-items: center; justify-content: center; ` const Nav = styled.nav` display: flex; height: calc(100% - 5px); ` const Progress = styled.div` height: 5px; background: #eee; position: relative; ` const Track = styled.div` background: #EC407A; height: 5px; width: 0px; position: absolute; top: 0; left: 0; transition: width 0.5s; ` const Artist = styled.div` font-size: 1em; font-style: italic; ` const Title = styled.div` font-weight: bold; ` export class PlayerComponent extends Component { constructor(props) { super(props); this.trackRef = createRef() } componentWillReceiveProps(props) { if (!this.audioEngine) { this.audioEngine = props.audioEngine; this.audioEngine.audio.addEventListener('timeupdate', (e) => { const progressPercent = (this.audioEngine.audio.currentTime / this.audioEngine.audio.duration)*100; if(this.trackRef.current) { this.trackRef.current.style.width = `${progressPercent}%` } }); } } render() { const { audioEngine } = this.props; if (!audioEngine.current) { return null; } const { track } = audioEngine.current; return ( <Cont> <Progress> <Track innerRef={this.trackRef} style={{width: `${audioEngine.progress}%` }}> </Track> </Progress> <Nav> <Details> <Title> {track.title} </Title> <Artist> {track.artist} </Artist> </Details> <Actions> <div onClick={() => audioEngine.skipPrevious()}> <SkipPrevious width="25px" /> </div> <div onClick={() => audioEngine.playPause()} > {audioEngine.audio.paused ? <Play width="40px" /> : <Pause width="40px" />} </div> <div onClick={() => audioEngine.skipNext()}> <SkipNext width="25px" /> </div> </Actions> <Volume> <div > <input type='range' min="0" max="1" step="0.1" value={audioEngine.audio.volume} onChange={(e) => audioEngine.setVolume(e.target.value)}/> </div> </Volume> </Nav> </Cont> ); } } export const Player = withAudioEngine(PlayerComponent);
var neuron = angular.module('neuron', ['ngRoute']); neuron.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) { $routeProvider. when('/', { templateUrl: 'view/neuron.html', controller: 'neuronController' }). when('/404', { templateUrl: 'view/404.html' // controller: 'ShowOrdersController' }). otherwise({ redirectTo: '/404' }); }]);
import React, { useState, useEffect } from "react"; import api from "../../services/api"; import M from "materialize-css"; function CreateIdea(props) { const [title, setTitle] = useState(''); const [description, setDescription] = useState(''); const handleSubmit = (async () => { await api.post("/ideas", { title, description }); setTitle('') setDescription('') }); useEffect(() => { M.AutoInit(); }, []); return ( <div> <button data-target="modalCreate" class="btn modal-trigger">New Idea</button> <div id="modalCreate" class="modal"> <div class="modal-content"> <h4>New Idea</h4> <form onSubmit={handleSubmit}> <label>Title</label> <input type="text" onChange={e => setTitle(e.target.value)} /> <label>Description</label> <input type="text" onChange={e => setDescription(e.target.value)} /> <button type="submit">Create</button> </form> </div> <div class="modal-footer"> </div> </div> </div> ); } export default CreateIdea;
const version = 'v0.1'; const prefix = "upshot"; const DEFINE_STATIC_CACHE = `${prefix}-static-${version}`; const DEFINE_RUNTIME_CACHE = `${prefix}-runtime-${version}`; const OFFLINE_URL = "offline.html"; var filesToCache = [ '/', '/scripts/client.min.js', '/styles/reset.css', '/styles/client.css', '/font2/ionicons-2.0.1/fonts/ionicons.eot?v=2.0.0', '/font2/ionicons-2.0.1/fonts/ionicons.eot?v=2.0.0#iefix', '/font2/ionicons-2.0.1/fonts/ionicons.ttf?v=2.0.0', '/font2/ionicons-2.0.1/fonts/ionicons.woff?v=2.0.0', '/font2/ionicons-2.0.1/fonts/ionicons.svg?v=2.0.0#Ionicons', '/font2/ionicons-2.0.1/css/ionicons.min.css', '/manifest.json', ]; self.addEventListener('install', function(event) { event.waitUntil( caches.open(DEFINE_STATIC_CACHE) .then(function(cache) { return cache.addAll(filesToCache).then( ()=>{ console.log('[ServiceWorker] Installed'); }); }) .then(self.skipWaiting()) ) }); var expectedCaches = [ DEFINE_STATIC_CACHE, DEFINE_RUNTIME_CACHE ]; self.addEventListener('activate', function(event) { event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.map(function(cacheName) { if (cacheName.startsWith(prefix + '-') && expectedCaches.indexOf(cacheName) === -1) { console.log('deleted'); return caches.delete(cacheName); } }) ); }) .then(()=> self.clients.claim() ) ); }); self.addEventListener('fetch', function (event) { event.respondWith( caches.match(event.request).then(function(response){ return response || fetchAndCache(event) }) ) }); const fetchAndCache = (event)=>{ var request = event.request.clone(); return fetch(request) .then(function(response){ var res = response.clone(); if (request.method === 'GET') { caches.open( DEFINE_RUNTIME_CACHE).then(function(cache) { console.log("cached....") cache.put(event.request.url, res); }); } return response; }) .catch(function(error) { return caches.match(OFFLINE_URL); console.log('Request failed:', error); }); } self.addEventListener('push', function(event) { if (!(self.Notification && self.Notification.permission === 'granted')) { return; } console.log('[Service Worker] Push Received.' , event.data.json()); let title = event.data.json().title || ''; let body = event.data.json().message || ''; let clickTarget = event.data.json().clickTarget || 'http://127.0.0.1:3000/'; let id = event.data.json().id || ""; let options = { body: body, icon: 'icons/', vibrate: [100, 50, 100], data: { dateOfArrival: Date.now(), clickTarget: clickTarget, id: id, } }; event.waitUntil(self.registration.showNotification(title, options)); }); self.addEventListener('notificationclick', function(event) { console.log('[Service Worker] Notification click Received.'); event.notification.close(); event.waitUntil( clients.openWindow( event.notification.data.clickTarget + "?show=" + event.notification.data.id) ); });
'use strict'; var mysql = require('mysql'), async = require('async'); var connection = mysql.createConnection(require('./config').mysql); connection.connect(); const defaults = { COUNTRY: 'us', // Default country LIMIT: 1, // Default results to return YEAR_MAX: 2014, // Defaults if config.year is not set or if config.max isn't set YEAR_MIN: 2014, // Defaults if config.year is not set YEAR_OFFSET: 10, // If config.year.max is set, set config.year.min to offset less than max YEAR_FLOOR: 1880, // Earliest year in data YEAR_CEIL: 2014, // Latest year in data POP_MAX: 100, // Defaults if config.popularity.max is not set POP_MIN: 97, // Defaults if config.popularity.min is not set POP_FLOOR: 0, // Lowest possible popularity value POP_CEIL: 100, // Heighest possible popularity value }; module.exports = function (format, config, callback) { if (typeof config === 'function') { callback = config; config = {}; } if (!config.gender || (config.gender !== 'M' && config.gender !== 'F')) { config.gender = Math.floor(Math.random() * 2) ? 'M' : 'F'; } if (!config.limit) { config.limit = defaults.LIMIT; } if (!config.country) { config.country = defaults.COUNTRY; } if (!config.year) { config.year = { min: defaults.YEAR_MIN, max: defaults.YEAR_MAX }; } else { if (!config.year.max || config.year.max > defaults.YEAR_MAX) { config.year.max = defaults.YEAR_MAX; } if (!config.year.min || config.year.min < defaults.YEAR_FLOOR) { let year = config.year.max - defaults.YEAR_OFFSET; config.year.min = year >= defaults.YEAR_FLOOR ? year : defaults.YEAR_FLOOR; } } if (!config.popularity) { config.popularity = { min: defaults.POP_MIN, max: defaults.POP_MAX }; } else { if (!config.popularity.min || config.popularity.min < defaults.POP_FLOOR) { config.popularity.min = defaults.POP_FLOOR; } if (!config.popularity.max || config.popularity.max > defaults.POP_CEIL) { config.popularity.max = defaults.POP_CEIL; } } async.times(config.limit, buildName, callback); function buildName (n, callback) { var str = format; async.parallel([ replaceGivenNames, replaceSurnames ], function (err) { return callback(err, str); }); function replaceGivenNames (callback) { async.whilst( // Test function () { return str.indexOf('{g}') !== -1; }, // Task function (callback) { var countQuery = getGivenNameCountQuery(config); // Get count of names for given config connection.query(countQuery, function (err, rows) { if (err) return callback(err); var getQuery = getNameQuery(config, rows[0].count, countQuery); connection.query(getQuery, function (err, rows) { if (err) return callback(err); str = str.replace('{g}', rows[0].name); return callback(null); }); }); }, // Callback callback ); } function replaceSurnames (callback) { async.whilst( // Test function () { return str.indexOf('{s}') !== -1; }, // Task function (callback) { var countQuery = getSurnameCountQuery(config); // Get count of names for given config connection.query(countQuery, function (err, rows) { if (err) return callback(err); var getQuery = getNameQuery(config, rows[0].count, countQuery); connection.query(getQuery, function (err, rows) { if (err) return callback(err); var surname = rows[0].name; surname = surname.charAt(0).toUpperCase() + surname.slice(1); str = str.replace('{s}', surname); return callback(null); }); }); }, // Callback callback ); } } }; function getGivenNameCountQuery (config) { var year = config.year.min + Math.floor(Math.random() * (config.year.max - config.year.min)); return 'SELECT COUNT(id) AS count FROM given_names WHERE gender="' + config.gender + '" AND country_code="' + config.country + '" AND year=' + year; } function getSurnameCountQuery (config) { return 'SELECT COUNT(id) AS count FROM surnames WHERE country_code="' + config.country + '" AND year=' + 2000; } function getNameQuery (config, count, countQuery) { var maxValue = Math.floor(count * config.popularity.max / 100), minValue = Math.floor(count * config.popularity.min / 100), offset = (minValue + Math.floor(Math.random() * (maxValue - minValue))), query = countQuery.replace('COUNT(id) AS count', 'name') + ' ORDER BY count ASC LIMIT 1 ' + 'OFFSET ' + offset; return query; }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; module.metadata = { 'stability': 'experimental' }; const { Cu } = require('chrome'); const { id, data } = require('sdk/self'); const { when: unload } = require('sdk/system/unload'); const { gDevTools } = Cu.import('resource:///modules/devtools/gDevTools.jsm', {}); const { merge } = require('sdk/util/object'); const events = require('sdk/system/events'); const { Worker } = require('sdk/content/worker'); const runtime = require('sdk/system/runtime'); const url = _ => _.startsWith('./') ? data.url(_.substr(2)) : _ ; const tools = new Map(); function onContent({subject: document}) { let window = document.defaultView; if (window && window.frameElement) { let id = window.frameElement.id.replace(/^toolbox-panel-iframe-/, ''); if (tools.has(id)) { let tool = tools.get(id); let { onAttach } = tool.definition; if (typeof onAttach === 'function') { let worker = Worker({ window: window, injectInDocument: true }); worker.on('detach', () => worker.destroy()); onAttach.call(tool, worker); tool.worker = worker; } } } } events.on('document-element-inserted', onContent, true); unload(() => events.off('document-element-inserted', onContent, true)); function register(tool) { let definition = { id: tool.id, icon: tool.icon ? url(tool.icon) : undefined, url: tool.url ? url(tool.url) : 'about:blank', label: tool.label, tooltip: tool.tooltip, ordinal: tool.ordinal || 0, inMenu: true, key: tool.key, modifiers: runtime.OS == "Darwin" ? "accel,alt" : "accel,shift", isTargetSupported: tool.isTargetSupported || (target => { return target.isLocalTab //&& /^https?/.test(target.url) }), build: function(window, toolbox) { let tool = tools.get(this.id); if (tool) { tool.window = window; tool.toolbox = toolbox; } }, onAttach: tool.onAttach }; tools.set(definition.id, { definition: definition, window: null, toolbox: null, worker: null }); gDevTools.registerTool(definition); unload(() => { unregister(definition); tools.delete(definition.id); }); } exports.register = register; function unregister(definition) { gDevTools.unregisterTool(definition); } exports.unregister = unregister;
import React from 'react' function Home() { return ( <div > <h5 className="mt-3 text-white text-center w-75 mx-auto"> Serach Any Movies Episodes Series. eg type batman and click serach,then a list of first 10 results will be shown on first page, click next to get the next 10 results. </h5> </div> ) } export default Home
angular.module("flashlightForFutureApp") .directive('genderPage', function() { return { restrict: 'E', templateUrl:'/templates/quiz/genderPage/genderPage.html' }; });
'use strict'; angular.module('orderComparisonApp',[ 'ui.router', 'core', 'ngCookies', 'settings', 'login', 'log', 'home', 'users', 'customersManagement', 'menuList', 'firstTable', 'secondTable', 'thirdTable', 'userMode', 'ui.bootstrap', 'basesManagement', 'addCustomer', 'articlesManagement', 'angularUtils.directives.dirPagination' ]);
import client from "../../client"; import { protectResolver } from "../users.util"; export default { Mutation: { follow: protectResolver(async (_, { username }, { loggedInUser }) => { const user = await client.user.findUnique({ where: { username }, }); if (!user) { return { ok: false, error: "User not found", }; } await client.user.update({ where: { id: loggedInUser.id }, data: { followings: { connect: { username, }, }, }, }); return { ok: true, }; }), }, };
function Player (args) { var args = args || {}; this.name = args.name || 'Player'; this.age = args.age || 6; this.health = args.health || 100; this.money = args.money || 0; this.items = args.items || new Array(); this.injure = function (damage) { this.health = Math.max(this.health - damage, 0); this.update(); if (this.health <= 0) { this.die(); } } this.die = function () { console.log('Your are dead. Game over.'); } this.giveItem = function (itemName) { if (this.items.indexOf(itemName) < 0) { this.items.push(itemName); } this.update(); } this.removeItem = function (itemName) { var index = this.items.indexOf(itemName); if (index >= 0) { this.items.splice(index, 1); } this.update(); } this.hasItem = function (itemName) { if (this.items.indexOf(itemName) > -1) { return true; } return false; } this.update = function () { $('#player-health').html(this.health); var html = ""; for (var i = 0; i < this.items.length; i++) { if (html.length > 0) { html += "<br />"; } html += this.items[i]; } $("#player-items").html(html); } }
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/building/_components/_like_tip" ], { 7097: function(e, t, n) { function o(e, t) { var n = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); t && (o = o.filter(function(t) { return Object.getOwnPropertyDescriptor(e, t).enumerable; })), n.push.apply(n, o); } return n; } function i(e, t, n) { return t in e ? Object.defineProperty(e, t, { value: n, enumerable: !0, configurable: !0, writable: !0 }) : e[t] = n, e; } Object.defineProperty(t, "__esModule", { value: !0 }), t.default = void 0; var r = n("2f62"), a = function(e) { return e && e.__esModule ? e : { default: e }; }(n("80d6")), c = "https://cdn.vip-wifi.com/hzfangchan/version-img/1.14.25/qr/hangzhou/hzgfzzj.jpg", u = { data: function() { return { qr_url: c, saving: !1 }; }, computed: function(e) { for (var t = 1; t < arguments.length; t++) { var n = null != arguments[t] ? arguments[t] : {}; t % 2 ? o(Object(n), !0).forEach(function(t) { i(e, t, n[t]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : o(Object(n)).forEach(function(t) { Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)); }); } return e; }({}, (0, r.mapState)([ "wxArticle" ])), methods: { hide: function() { this.$emit("hide"); }, save: function() { var e = this; wx.showLoading(), this.saving = !0, a.default.saveImgFromInternet({ url: c }).then(function(t) { e.finishSave(), wx.showToast({ title: "下载成功" }); }).catch(function() { e.finishSave(), wx.showToast({ title: "下载失败", icon: "none" }); }); }, finishSave: function() { this.saving = !1, setTimeout(wx.hideLoading, 1500); }, copyWx: function() { a.default.setClipboardData("cdgfzzj"); } }, props: { show: { type: Boolean }, content: { type: String }, show_copy: { type: Boolean }, title: { type: String } } }; t.default = u; }, a932: function(e, t, n) { n.d(t, "b", function() { return o; }), n.d(t, "c", function() { return i; }), n.d(t, "a", function() {}); var o = function() { var e = this, t = (e.$createElement, e._self._c, e.$canIdentifyQr()); e.$mp.data = Object.assign({}, { $root: { m0: t } }); }, i = []; }, aff7: function(e, t, n) {}, ca0b: function(e, t, n) { n.r(t); var o = n("a932"), i = n("d5e3"); for (var r in i) [ "default" ].indexOf(r) < 0 && function(e) { n.d(t, e, function() { return i[e]; }); }(r); n("f5f6"); var a = n("f0c5"), c = Object(a.a)(i.default, o.b, o.c, !1, null, "c845a03e", null, !1, o.a, void 0); t.default = c.exports; }, d5e3: function(e, t, n) { n.r(t); var o = n("7097"), i = n.n(o); for (var r in o) [ "default" ].indexOf(r) < 0 && function(e) { n.d(t, e, function() { return o[e]; }); }(r); t.default = i.a; }, f5f6: function(e, t, n) { var o = n("aff7"); n.n(o).a; } } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/building/_components/_like_tip-create-component", { "pages/building/_components/_like_tip-create-component": function(e, t, n) { n("543d").createComponent(n("ca0b")); } }, [ [ "pages/building/_components/_like_tip-create-component" ] ] ]);
Glagol.events.once('changed', _.reload(__filename)); module.exports = function (App) { return function (name) { console.groupCollapsed('loading plugin', name); try { var pluginRoot = Glagol.get('../plugins').get(name); if (!pluginRoot) return console.warn('no plugin', name); // make views directory special var views = pluginRoot.get('views'); if (views) { // globals for easier templating. maybe just remove views.options = require('extend')(views.options, { globals: function (file) { return { App: App, emit: function () { return _.emit.apply(null, arguments) }, h: function () { return _.h.apply(null, arguments) } } } }) // live reload when editing views views.events.onAny(function () { console.debug('template edited, refreshing'); App.View.update(App.Model()); }) } // make model globally accessible via App.Model var model = pluginRoot().model; if (model) App.Model.put(name, model); // if plugin has stylesheet, add it to the document head // if not, hope for one to appear // TODO custom auto-updating format for stylesheets (??) var style = pluginRoot.get('style.styl') || pluginRoot.get('style.css'); if (style) { addStyle(style); } else { console.debug('no stylesheet for', name) pluginRoot.events.on('added', expectStyle); } function addStyle (style) { console.debug('introducing stylesheet for', name, ':', style.path) _.insertCssLive(style); } function expectStyle (node) { if (node.name === 'style.styl' || node.name === 'style.css') { addStyle(node); pluginRoot.events.off('added', expectStyle); } } // execute entry point var entryPoint = pluginRoot.get('init.js'); if (entryPoint && entryPoint()) { console.debug('running', name + '/init'); entryPoint.events.on('changed', _.reload(name + ' entry point')); entryPoint()(App); } } catch (e) { console.groupEnd(); console.error(e); } console.groupEnd(); } }
/** * Checkout Module */ var config = require('../../config'); var dwocapi = require('../../dwocapi'); var checkout = { /** * Add to Cart * @param req * @param res * @param next */ addToCart : function(req,res,next){ var url = '/basket/this/add'; var data = { "product_id" : req.body.pid, "quantity" : parseInt(req.body.qty), "inventory_id" : config.api.inventory_id, }; dwocapi.post(url,data,function(err,data1){ req.session.cart = data1; res.redirect('/cart'); }); }, /** * Show Cart * @param req * @param res * @param next */ showCart : function(req,res,next){ url = '/basket/this'; res.cart = req.session.cart; next(); }, /** * Render Cart * @param req * @param res */ renderCART : function(req,res){ res.render('cart', {categories: res.cats.categories,cart: req.session.cart}); }, /** * Render Checkout Page * @param req * @param res */ renderCHECKOUT_SHIPPING : function(req,res){ res.render('checkout', {categories: res.cats.categories,cart: req.session.cart}); } }; module.exports = checkout; ////////////////////////////////////////
Template.articlePage.helpers({ ownArticle: function() { return this.userId === Meteor.userId(); }, comments: function() { return Comments.find({articleId: this._id}); }, statusLabel: function() { if (this.status === "fresh"){ return "success"; } else { return "warning"; } }, tags: function() { if (this.tags){ var tags = this.tags.split(","); return tags; } } }); Template.articlePage.events({ 'click .delete': function(e) { e.preventDefault(); if (confirm("Delete this article?")) { var currentArticleId = this._id; Articles.remove(currentArticleId); throwConfirmation("Article has been deleted successfully!"); Router.go('articlesList'); } } });
import React from 'react'; import { shallow } from 'enzyme'; import Nav from '../../components/Nav'; describe('Nav', () => { it('should render component', () => { const mockUser = { email: 'gizmo_da_corgi@doggos.com', password: 'stumper4lyfe' }; const wrapper = shallow( <Nav isLoggedIn={[mockUser]}/>); expect(wrapper).toMatchSnapshot(); }); });
var data = (function() { 'use strict'; function register(username, password){ var user = { username: username, passHash: CryptoJS.SHA1(password).toString() } console.log(user); var promise = new Promise(function(resolve, reject) { $.ajax({ url: 'api/users', method: 'POST', contentType: 'application/json', data: JSON.stringify(user), success: function(res){ resolve(res); }, error: function(err){ reject(err); } }) }); return promise; } function login(username, password) { var newUser = { username: username, passHash: CryptoJS.SHA1(password).toString() }; var promise = new Promise(function(resolve, reject) { $.ajax({ url: 'api/auth', method: 'PUT', contentType: 'application/json', data: JSON.stringify(newUser), success: function(res){ storage.setObject('user', res.result); resolve(res); }, error: function(err) { reject(err); } }) }); return promise; } function logout(){ storage.removeItem('user'); toastr.success("Successful logout!"); document.location.reload(true); } function isLogged(){ return getCurrentUser() !== null; } function getCurrentUser(){ return storage.getObject('user'); } function all(){ var promise = new Promise(function(resolve, reject) { $.ajax({ url: 'api/cookies', success: function(res){ resolve(res); }, error: function(err){ reject(err); } }) }); return promise; } function like(cookieId){ var req = { type: 'like' } var promise = new Promise(function(resolve, reject) { $.ajax({ url: 'api/cookies/' + cookieId, method: 'PUT', headers: { 'x-auth-key': getCurrentUser().authKey }, contentType: 'application/json', data: JSON.stringify(req), success: function(res){ resolve(res); }, error: function(err){ reject(err); } }); }); return promise; } function dislike(cookieId){ var req = { type: 'dislike' } var promise = new Promise(function(resolve, reject) { $.ajax({ url: 'api/cookies/' + cookieId, method: 'PUT', headers: { 'x-auth-key': getCurrentUser().authKey }, contentType: 'application/json', data: JSON.stringify(req), success: function(res){ resolve(res); }, error: function(err){ reject(err); } }); }); return promise; } function categories(){ var promise = new Promise(function(resolve, reject) { $.ajax({ url: 'api/categories', success: function(res){ resolve(res); } }) }); return promise; } function share(text, category, imageUrl){ var image = { text: text, category: category, img: imageUrl }; var promise = new Promise(function(resolve, reject) { $.ajax({ url: 'api/cookies', method: 'POST', contentType: 'application/json', headers: { 'x-auth-key': getCurrentUser().authKey }, data: JSON.stringify(image), success: function(res){ resolve(res); }, error: function(err){ reject(err); } }); }); return promise; } function hourlyCookie(){ var promise = new Promise(function(resolve, reject) { $.ajax({ url: 'api/my-cookie', headers: { 'x-auth-key': getCurrentUser().authKey }, success: function(res){ resolve(res); }, error: function(err){ reject(err); } }); }); return promise; } return{ users: { register: register, login: login, logout: logout, getCurrentUser: getCurrentUser, isLogged: isLogged }, cookies: { all: all, like: like, dislike: dislike, categories: categories, share: share, hourlyCookie: hourlyCookie } }; }());
import React from 'react'; import { connect } from 'react-redux'; import {EnhanceLoading} from '../../../components/Enhance'; import createTabPage from '../../../standard-business/createTabPage'; import {getPathValue} from '../../../action-reducer/helper'; import {Action} from '../../../action-reducer/action'; import helper from '../../../common/common'; import {search} from '../../../common/search'; import {buildOrderPageState} from '../../../common/state'; import {getDictionaryNames, fetchDictionary, setDictionary2,getStatus} from '../../../common/dictionary'; const URL_CONFIG = '/api/bill/pay_monthly_bill/config'; const URL_LIST = '/api/bill/pay_monthly_bill/list';//查询列表 const STATE_PATH = ['payMonthlyBill']; const action = new Action(STATE_PATH); import OrderPageContainer from './OrderPageContainer'; import AddContainer from './AddTabContainer'; import EditContainer from './EditTabContainer'; const getSelfState = (rootState) => { return getPathValue(rootState,STATE_PATH) }; const initActionCreator = () => async (dispatch) => { try{ let date,year,oldYear,allYear; dispatch(action.assign({status: 'loading'})); //初始化数据 const { index ,edit,addDialog ,editDialog} = helper.getJsonResult(await helper.fetchJson(URL_CONFIG)); //页面数据 const list = helper.getJsonResult(await search(URL_LIST, 0, index.pageSize, {})); //字典 const names = getDictionaryNames(index.tableCols,index.filters,edit.cols,editDialog.cols); const dictionary = helper.getJsonResult(await fetchDictionary(names)); //获取状态字典 const status = helper.getJsonResult(await getStatus("payable_month_bill")); const dictResult = {...dictionary, status_type1:status}; setDictionary2(dictResult, index.tableCols,index.filters,edit.cols,addDialog.tableCols,editDialog.cols); //设置年份下拉 从2018年到当前年份 date = new Date; year = date.getFullYear(); oldYear = 2018; allYear = []; while (oldYear <= year) { allYear.push({ title: oldYear, value: oldYear }); oldYear++ } helper.setOptions('periodOfyear', index.filters, allYear); helper.setOptions('periodOfyear', edit.controls, allYear); // 初始化搜索条件配置 index.filters = helper.initFilters('pay_month_bill_sort', index.filters); dispatch(action.assign({ status: 'page', index: buildOrderPageState(list, index, {tabKey: 'index', isSort: true}), activeKey: 'index', tabs: [{key: 'index', title: '应付月帐单', close: false}], editConfig:edit, addDialog, editDialog })); }catch (e){ helper.showError(e.message); dispatch(action.assign({status: 'retry'})); } }; //tab切换事件 const tabChangeActionCreator = (key) => { return action.assign({activeKey: key}); }; //tab关闭事件 const tabCloseActionCreator = (key) => (dispatch, getState) => { const {activeKey, tabs} = getSelfState(getState()); const newTabs = tabs.filter(tab => tab.key !== key); if (activeKey === key) { let index = tabs.findIndex(tab => tab.key === key); (newTabs.length === index) && (index--); dispatch(action.assign({tabs: newTabs, [activeKey]: undefined, activeKey: newTabs[index].key})); } else { dispatch(action.assign({tabs: newTabs, [key]: undefined})); } }; const actionCreators = { onInit: initActionCreator, onTabChange: tabChangeActionCreator, onTabClose: tabCloseActionCreator }; const mapStateToProps = (state) => { return getSelfState(state) }; //根据activeKey不同显示不同的组件 const getComponent = (activeKey) => { if (activeKey === 'index') { return OrderPageContainer; }else if(activeKey === 'add'){ return AddContainer }else if(activeKey.indexOf('edit_') === 0){ return EditContainer } }; const RootContainer = connect(mapStateToProps, actionCreators)(EnhanceLoading(createTabPage(getComponent))); export default RootContainer;
import React from 'react' import { Link } from 'react-router-dom' import styled from 'styled-components' import theme from '../../theme' const StyledTag = styled(Link)` padding: 5px; background: rgb(63, 207, 251); background: linear-gradient( 90deg, rgba(63, 207, 251, 1) 0%, rgba(144, 70, 252, 1) 100% ); color: ${theme.colors.gray_lighter_alt}; border-radius: 15px; margin: 0px 5px 5px 0px; text-decoration: none; outline: none; ` function Tag({ children, linkTo }) { return <StyledTag to={linkTo}>{children}</StyledTag> } Tag.defaultProps = { linkTo: '/', } export default Tag
import React from 'react' import 'assets/css/spinner.css' // import BaityLoading from 'assets/img/BaityLoading.gif'; const Spinner = (props) => ( <div className='spinner'></div> // <LoadImg src={BaityLoading} className="icons"/> ) export default Spinner;
import React from 'react'; import Logotype from './Logotype'; import './header.css'; function Header(props) { return( <header> <Logotype /> <div className="header__linker"> {props.showHidderButton} {props.showEditButton} {props.showActiveButton} </div> </header> ); } export default Header;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ramda = require('ramda'); var _ramda2 = _interopRequireDefault(_ramda); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var defaultState = {}; exports.default = function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultState; var action = arguments[1]; switch (action.type) { case 'CREATE_DOCS_LOADER': return Object.assign({}, state, _defineProperty({}, action.loaderName, { query: action.query, loaded: 0, endReached: false })); case 'REMOVE_DOCS_LOADER': return _ramda2.default.dissoc(action.loaderName, state); case 'LOAD_DOCS': if (!action.loaderName || !state[action.loaderName]) { return state; } var loader = state[action.loaderName]; return Object.assign({}, state, _defineProperty({}, action.loaderName, Object.assign({}, loader, { loaded: loader.loaded + action.docs.length, endReached: action.docs.length < (loader.query.limit || 25) }))); case 'REFRESH_LOADER': if (!action.loaderName || !state[action.loaderName]) { return state; } return Object.assign({}, state, _defineProperty({}, action.loaderName, Object.assign({}, state[action.loaderName], { loaded: 0, endReached: false }))); default: return state; } };
({ getPhoto: function (component, event) { let action = component.get('c.getDefaultPhoto'); action.setParams({ 'productId': component.get('v.product.Id') }); action.setCallback(this, function (response) { if (response.getState() === "SUCCESS") { component.set('v.photo', response.getReturnValue()); } if (response.getState() === "ERROR") { this.sendErrorMessage(response); } }); $A.enqueueAction(action); }, getRating: function (component, event) { let action = component.get('c.getRating'); action.setParams({ 'productId': component.get('v.product.Id') }); action.setCallback(this, function (response) { if (response.getState() === "SUCCESS") { component.set('v.rate', response.getReturnValue()); } if (response.getState() === "ERROR") { this.sendErrorMessage(response); } }); $A.enqueueAction(action); }, getPrice: function (component, event) { let action = component.get('c.getProductPrice'); action.setParams({ 'productId': component.get('v.product.Id') }); action.setCallback(this, function (response) { if (response.getState() === "SUCCESS") { try { if (response.getReturnValue().length > 1) { component.set('v.discount', true); component.set('v.discountPrice', response.getReturnValue()[response.getReturnValue().length-1].UnitPrice); } else { component.set('v.discount', false); } component.set('v.price', response.getReturnValue()[0].UnitPrice); } catch (e) { } } if (response.getState() === "ERROR") { this.sendErrorMessage(response); } }); $A.enqueueAction(action); }, goToDetails: function (component, event) { let redirect = $A.get("e.force:navigateToSObject"); redirect.setParams({ "recordId": component.get('v.product.Id'), "slideDevName": "details" }); redirect.fire(); }, sendErrorMessage: function (response) { let message; try { message = response.getError()[0].message; } catch (e) { message = $A.get('$Label.c.GS_Unknown_Error'); } this.sendMessage('Error', message, 'error'); }, sendMessage: function (title, message, type) { let toastParams = { title: title, message: message, type: type }; let toastEvent = $A.get("e.force:showToast"); toastEvent.setParams(toastParams); toastEvent.fire(); } });
import React, { Fragment } from 'react'; import { StyledSection } from './styles'; import Nav from '../../components/PublicNav'; import LoginContainer from '../../containers/LoginContainer'; const ForgotPassword = ({ location }) => { // pathname would be '/forgotPassword' const { pathname } = location; return ( <Fragment> <Nav pathname={pathname} /> <StyledSection> <LoginContainer pathname={pathname} /> </StyledSection> </Fragment> ); }; export default ForgotPassword;
import React, { PropTypes } from 'react' import { connect } from 'react-redux' import { Responsive, WidthProvider, utils } from 'react-grid-layout'; const ResponsiveReactGridLayout = WidthProvider(Responsive); import Actions from 'actions' import Link from './Blocks/Link' import Weather from './Blocks/Weather' import Clock from './Blocks/Clock' import Bookmarks from './Blocks/Bookmarks' import Userscript from './Blocks/Userscript' import sized from 'components/sized' // lib import 'react-resizable/css/styles.css' import 'react-grid-layout/css/styles.css' // custom import 'stylesheets/Grid.css' import 'stylesheets/Blocks.css' const STEP = 80 const COLS = {} const BREAKPOINTS = {} for (let i = 1; i < 16; i += 2) { const lbl = 'col_' + i COLS[lbl] = i BREAKPOINTS[lbl] = i * STEP } class BlocksGrid extends React.Component { static propTypes = { blocks: PropTypes.object.isRequired } constructor(props) { super(props) this.state = { layout: {}, ready: false } } componentDidMount() { setTimeout(() => { this.setState({ ready: true }) }, 1000) } updateBlockItem(item) { const id = item.i this.props.dispatch(Actions.updateBlock(id, { coords: { ...item } })) } onDragStop(layout, oldItem, newItem) { this.updateBlockItem(newItem) } onResizeStop(layout, oldItem, newItem) { this.updateBlockItem(newItem) } render() { const blocks = Object.entries(this.props.blocks).map((kv, idx) => { const id = kv[0], block = kv[1]; let { coords } = block if (typeof coords === 'undefined') { coords = { x: null, y: null, w: 2, h: 2 } } // modify coords if this is a new item if (coords.x === null || typeof coords.x === 'undefined') { coords.x = 0 if (this.state.layout) { coords.y = utils.bottom(this.state.layout) } else { coords.y = Infinity } } let blockView = null switch (block.type) { case 'clock': blockView = <Clock block={block} /> break; case 'weather': blockView = <Weather block={block} /> break; case 'bookmarks': blockView = <Bookmarks block={block} /> break; case 'feed': case 'link': blockView = <Link block={block} /> break; case 'userscript': blockView = <Userscript block={block} /> break; default: blockView = <Link block={block} /> break; } return ( <div key={id} data-grid={coords}> { blockView } </div> ) }) const { editing } = this.props const className = 'grid-layout ' + (this.state.ready ? 'ready' : 'unready') return ( <ResponsiveReactGridLayout className={className} measureBeforeMount={true} isDraggable={editing} isResizable={editing} // element changes onDragStop={this.onDragStop.bind(this)} onResizeStop={this.onResizeStop.bind(this)} breakpoints={BREAKPOINTS} cols={COLS} containerPadding={[0,0]} verticalCompact={true} rowHeight={STEP}> {blocks} </ResponsiveReactGridLayout> ) } } const mapStateToProps = state => { return { blocks: state.blocks, editing: state.layout.editing } } export default connect(mapStateToProps)(sized(BlocksGrid))
const User = require("../domain/user"); const UserService = require("../services/user-service"); var userService = new UserService(); exports.get = async (req, res) => { res.json(await userService.getAll()); }; exports.getAuth = async (req, res) => { console.log(req); res.json(await userService.getAuth(req.body.email, req.body.password)); } exports.getById = async (req, res) => { res.json(await userService.getById(req.params.id)); }; exports.post = async (req, res) => { if (req.body.email.length < 3 || req.body.password < 5) { res.status(400).send(); } else { let user = await userService.add( new User(req.body.email, req.body.password, req.body.country, req.body.occupation, req.body.name, req.body.birthday, req.body.fone, ) ); if (user != null) { res.status(201).json(user); } else { res.status(409).send(); } } }; exports.put = async (req, res) => { if (req.body.email.length < 3 || req.body.password < 5) { res.status(400).send(); } else { let user = await userService.update( req.params.id, new User(req.body.email, req.body.password, req.body.country, req.body.occupation, req.body.name, req.body.birthday, req.body.fone, ) ); if (user != null) { res.status(201).json(user); } else { res.status(409).send(); } } }; exports.delete = (req, res) => { res.json(userService.delete(req.params.id)); };
import Vue from 'vue' import App from './App.vue' import VueRouter from 'vue-router' //для того, чтобы зарегистрировать экземпляр VueRouter импортируем константу router import router from './routes' Vue.config.productionTip = false Vue.use(VueRouter) new Vue({ render: h => h(App), //регистрируем данный роутер, он регистрируется в экземпляре нашего приложения. т.к. значение и ключ совпадают то можно опустить значение роутера, блягодаря синтаксису ES6 router }).$mount('#app')
import React, { Component } from 'react'; import Options from '../../components/options'; import Master from '../../components/master'; import Detail from '../../components/detail'; import axios from 'axios'; import './style.css'; const url = "/" class MainContainer extends Component { constructor() { super(); this.repHandler = this.repHandler.bind(this); this.stateHandler = this.stateHandler.bind(this); this.handleSelect = this.handleSelect.bind(this); this.state = { rep: true, state: "UT", data: [], selected: null } this.senators = {}; this.representatives = {}; } render() { return ( <div className="mainContainer"> <Options rep={this.state.rep} state={this.state.state} stateHandler={this.stateHandler} repHandler={this.repHandler} /> <div className={"viewContainer"}> <div className="masterDetail"> <Master data={this.state.data} rep={this.state.rep} handleSelect={this.handleSelect} selected={this.state.selected}/> <Detail data={this.state.selected} rep={this.state.rep}/> </div> </div> </div> ); } componentDidMount() { this.update(); } repHandler() { this.setState({ rep: !this.state.rep }, this.update) } stateHandler(state) { this.setState({ state: state.value }, this.update(state.value)) } handleSelect(entity){ this.setState({ selected: entity }) } update(state) { this.getData(state) .then(res => { this.setState({ data: res, selected:null }) }) .catch(err => console.log(`ERROR GETTING DATA`, err)) } getData(state) { return new Promise((resolve, reject) => { let endpoint = this.state.rep ? 'representatives' : 'senators'; state = !state ? this.state.state : state; if (this[endpoint][state]) return resolve(this[endpoint][state]) axios.get(`${url}${endpoint}/${state}`) .then(res => { let data = res.data.results; this[endpoint][state] = data; return resolve(data); }) .catch(reject) }) } } export default MainContainer;
const page = require('./utils/page'); const download = require('./utils/download'); (async function (comicName, Indexurl) { const start = new Date().getTime(); let chapterUrls = await page.getChapterURLByIndex(Indexurl); // chapterUrls = chapterUrls.slice(58); //截取部分章节 for (let item of chapterUrls) { const start0 = new Date().getTime(); const url = item.replace('chapter', 'chapter_vip').replace('html', 'shtml'); //地址替换为滚轮模式 地址 const obj = await page.getImgageUrlsAndTitle(url); if (obj.title && obj.urlArr.length > 0) await download.download(comicName, obj.title, obj.urlArr); else console.log('当前章节为付费章节,以后章节大概率同样为付费章节,请先付费\n按Ctrl+C退出程序'); console.log(`章节${obj.title}下载完毕,耗时:${(new Date().getTime() - start0) / 1000}s`); } console.log('操作完成,总耗时:' + (new Date().getTime() - start) / 1000 + "s"); }) ("笼中人", 'http://www.u17.com/comic/181616.html'); //传入参数 漫画名称 , 漫画目录页地址 当前为测试《笼中人》参数
import 'core-js/stable'; import 'regenerator-runtime/runtime'; import app from './app'; const PORT = process.env.PORT || 3001; app.listen(PORT, () => { console.log(`CRA Server listening on port ${PORT}!`); });
var BigInteger = require("./bignumber.min"); function sumTwoHugeNumbers(value) { var num1 = BigInteger(value[0]); var num2 = BigInteger(value[1]); return num1.plus(num2).toString(10); } console.log(sumTwoHugeNumbers(['155', '65'])); console.log(sumTwoHugeNumbers(['123456789', '123456789'])); console.log(sumTwoHugeNumbers(['887987345974539','4582796427862587'])); console.log(sumTwoHugeNumbers(['347135713985789531798031509832579382573195807', '817651358763158761358796358971685973163314321'] ));
export default function Footer() { return ( <footer> <div className="container"> <div> <h2>Get involved</h2> <p> Radicle is free and open source software, we welcome all contributors. </p> <ul> <li>Follow us on <a href="https://twitter.com/radicle_xyz">twitter</a>.</li> <li>Contribute to the development on <a href="https://github.com/radicle-dev">github</a>.</li> <li>Join the conversation on <a href="https://radicle.community">discourse</a>.</li> <li>Drop in the <a href="irc://freenode:1/radicle">#radicle</a> channel on freenode.</li> </ul> </div> <div> <h2>Stay up to date</h2> <p>If you'd like to be informed of progress, hand us your e-mail and we'll keep you in the loop.</p> <form action="https://formspree.io/xrgbwygl" method="POST" className="input"> <input type="email" name="email" placeholder="E-mail" required /> <button type="submit">Subscribe</button> <input type="hidden" name="_subject" value="Subscription" /> <input type="hidden" name="_format" value="plain" /> <input type="hidden" name="_next" value="https://radicle.xyz/subscribed" /> </form> </div> </div> <div id="monadic"> <pre><code>--.., supported by </code></pre><a href="https://monadic.xyz">monadic.xyz</a><pre><code> --'`,---..-.--+--.,,-,,..._.--..-._.---.--..,___.--,--'`,---..-.--+--.,,-,,..._.--..-._.---.--..,___.--,--'`,---..-.--+--.,,-,,..._.--..-._.---..,,-,,..._.--..-._.---.--..,___.--,--'`,---..-.--+--.,,-,,..._.--..-._.---.--..,___.--,--'`,---..-.--+--.,,-,,..._.--..-._.---.</code></pre> </div> </footer>) }
import { RECEIVE_REVIEWS_ERRORS} from '../actions/reviews_actions'; const ReviewsErrorsReducer = (state , action) => { Object.freeze(state); switch (action.type) { case RECEIVE_REVIEWS_ERRORS: return action.errors; default: return state; } }; export default ReviewsErrorsReducer;
//The task of this method is to simple forward the value sent by popup.js to contentScript.js chrome.extension.onMessage.addListener(function (request, sender, sendResponse) { chrome.tabs.getSelected(null, function (tab){ chrome.tabs.sendMessage(tab.id, {type: request.type}); chrome.browserAction.setBadgeText({text: request.type}); }); return true; });
import React, { useContext } from 'react' import { SisuContext } from '../../contexts/SisuContenxt' import { HeaderBase } from './styles' const Header = () => { const { headerText } = useContext(SisuContext) return ( <HeaderBase> { headerText } </HeaderBase> ) } export default Header
(function (angular) { "use strict"; function unWrapData(d) { return d.data; } function getLength(d) { return d.length; } function printAndContinue(d) { console.log(d); return d; } angular.module('kyle.other', []) .controller('ddd', function ($scope, $q, $http) { var d1 = $q.defer(); var p1 = d1.promise; d1.resolve(333); var d2 = $q.defer(); var p2 = d2.promise; var p2prime = p2.then(function (d) { return d + "qqqqq"; }); p2.then(function (d) { console.log("P2 data is " + d); }, function (e) { console.log("P2 error is " + e); }); d2.reject("EEEEE"); var p3 = $http.get("index.html"); var d4 = $q.defer(); setTimeout(function () { d4.resolve("done"); }, 4000); $q.all([p1, p2prime, p3, d4.promise]).then(function (a) { console.log(a); }, function (e) { console.log("ALL error is " + e); }); var p8 = $http.get("QQQindex.html"); p8.then(null, function (e) { // return $q.reject("unhappy"); return "happy"; ///return $http.get("index.html"); }) .then(unWrapData) .then(getLength) .then(function (d) { console.log("p8 " + d); }, function (e) { console.log("p8 error is " + e); }); }); })(window.angular);
typeof web3 !== 'undefined' ? (web3 = new Web3(web3.currentProvider)) : (web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))); if (web3.isConnected()) { console.log('connected'); } else { console.log('not connected'); exit; } const contractAddress = '0xfe38991E2d47ae9D3EA304db06Da20eB70499851'; const smartContract = web3.eth.contract(abi).at(contractAddress); function showList() { const table = document.getElementById('table1'); const length = smartContract.getNumOfProjects(); smartContract.job().watch((err, res) => { if (!err) { console.dir(res); const row = table.insertRow(); const cell1 = row.insertCell(0); const cell2 = row.insertCell(1); const cell3 = row.insertCell(2); const cell4 = row.insertCell(3); cell1.innerHTML = res.args.jobName; cell2.innerHTML = res.args.jobStatus; cell3.innerHTML = res.args.jobBudget.c[0]; cell4.style.width = '60%'; cell4.innerHTML = new Date(res.args.timestamp.c[0] * 1000); } }); for (let i = 0; i < length; i++) { const project = smartContract.getProjectStruct(i); const toString = project.toString(); const strArray = toString.split(','); console.log(toString); const timestamp = new Date(strArray[3] * 1000); const row = table.insertRow(); const cell1 = row.insertCell(0); const cell2 = row.insertCell(1); const cell3 = row.insertCell(2); const cell4 = row.insertCell(3); cell1.innerHTML = strArray[0]; cell2.innerHTML = strArray[1]; cell3.innerHTML = strArray[2]; cell4.style.width = '60%'; cell4.innerHTML = timestamp; } } function addProject() { const INITSTATUS = "Ready" const proname = document.getElementById('proname').value; const prostatus = INITSTATUS; const probudget = document.getElementById('probudget').value; const account = document.getElementById('account').value; if (web3.personal.unlockAccount(account, document.getElementById('pass').value)) { smartContract.addJobStru( proname, prostatus, probudget, { from: account, gas: 2000000 }, (err, result) => { if (!err) alert('트랜잭션이 성공적으로 전송되었습니다.\n' + result); } ); } } $(function () { showList(); });
//Problem 1 function durhamRules(){ alert('Durham is awesome!'); } //Problem 2 const bands = ['Kiss', 'Aerosmith', 'ACDC', 'Led Zeppelin', 'Nickelback']; function favoriteBand(bands) { for (var i = 0; i < bands.length; i++) { alert(`I love ${bands[i]}`); } } //Problem 3 function iDontLikeNickelBack(bands) { for (var i = 0; i < bands.length; i++) { if (bands[i] === 'Nickelback') { alert(`I DON'T love ${bands[i]}`); } else { alert(`I love ${bands[i]}`); } } } //Problem 4 function findAverage(arr){ var sum = 0; for (var i = 0; i < arr.length; i++) { sum = sum + arr[i]; } return sum / arr.length; } //Problem 5 const array = ['a', 'b', 'c', 'd', 'c', 'b', 'b', 'c', 'a', 'e', 'b', 'e']; function mostAndLeast(array){ var mostFreq; var leastFreq; //make an object that holds letters as keys and frequency as values var countObj = array.reduce(function(indexes, instance) { if (instance in indexes) { indexes[instance]++ } else { indexes[instance] = 1; } return indexes; }, {}); //make an array of just the frequencies var arrOfFreq = Object.values(countObj); var max = Math.max(...arrOfFreq); var min = Math.min(...arrOfFreq); //if the value of a key is the maximum/minimum of frequency arr, then make mostFreq and leastFreq those keys for (var prop in countObj) { if (countObj[prop] === max) { mostFreq = prop; } else if (countObj[prop] === min) { leastFreq = prop; } } return `The most frequent item is: ${mostFreq}. The least frequent item is: ${leastFreq}`; } //Problem 6 function overlapIndex(arr1, arr2){ var result = []; for (var i = 0; i < arr1.length; i++) { for (var j = 0; j < arr2.length; j++) { if (arr1[i] === arr2[j]) { result.push(arr1[i]); arr2.splice(j, 1); } } } return result; } //Problem 7 function budgetToBills(cost, bills){ if (typeof cost !== 'number' || typeof bills !== 'object') { return 'Sorry, please enter valid inputs' } else { var wallet = {}; function descend(a, b){ return b - a; } bills = bills.sort(descend); for (var i = 0; i < bills.length; i++) { var amountOfBills = Math.floor(cost / bills[i]) wallet[bills[i]] = amountOfBills; cost = cost - amountOfBills * bills[i]; } for (var prop in wallet) { if (wallet[prop] === 0) { delete wallet[prop]; } } return wallet; } } /*I decided to go with the second version of the function with two inputs; invalid types of input are resolved in the first couple of lines, although for efficiency sake, I did not include code to convert string values of each input, though it would make it more practical in real-life functionality*/
import SelectBySearchHistory from './SelectBySearchHistory' const SearchHistory = (props) => { return( <div className='container'> <div>Select one or more to search from your history:</div> <br/> { props.prevSearch.length> 0 && props.prevSearch.map((item, index) =>{ return <span key={index} onClick={() => {props.setSearchByHistory([...props.searchByHistory, {'search': item.search, 'results': item.results}])}} className= 'user-input-search-history'> {item.search} </span> }) } <div> <SelectBySearchHistory props={props} searchByHistory={props.searchByHistory}/> </div> </div> ) } export default SearchHistory;
import React from 'react' import styled from 'styled-components' import Build from './Build' import Display from './Display' const Wrapper = styled.main` width: 100vw; height: 90vh; margin: 10vh 0 0 0; display: flex; justify-content: space-around; ` export default function CharacterCreator() { return ( <Wrapper> <Build /> <Display /> </Wrapper> ) }
/* */ // 1 hoc // function highFunc (lowFunc) { // let state = undefined // const tryState = () => { // try (state) { // catch '*': // // } // } // return function (props, type) { // let resultOfLowFunc = lowFunc(props) // if () // return resultOfLowFunc * resultOfLowFunc // } // } // // function addOne (number) { // return number + 1 // } // // // highFunc() function myMap (arr, fn) { // 他会新建一个空数组 let newArr = [] // 他会遍历老数组 // 把元素依次调用传给他的函数 // 然后将函数返回的东西,打到新数组里面,依次 for (let item of arr) { newArr.push(fn(item)) } // 最后他会返还给我们这个数组 return newArr } function myFilter (arr, fn) { // 他会新建一个空数组 let newArr = [] // 他会遍历老数组 // 把元素依次调用传给他的函数 // true 打入 false 舍弃 // 然后将函数返回的东西,打到新数组里面,依次 for (let item of arr) { fn(item) && newArr.push(item) } // 最后他会返还给我们这个数组 return newArr } [3, 2, 1] function myRank (arr, fn) { // 他会新建一个空数组 let newArr = [] // 遍历老数组,打给他两个元素,让他。。。比较大小? newArr = rank(arr, fn) // 最后他会返还给我们这个数组 return newArr } function rank (arr, fn) { let afterArr = arr for (let i = 0; i < arr.length ; i++) { for (let j = 0; j < arr.length - 1 - i; j++) { let a = arr[j] let b = arr[j+1] if (fn(a, b) < 0) { var space = arr[j] afterArr[j] = arr[j+1] afterArr[j+1] = space } } } return afterArr } let arr = myRank([3,6,8,5,2,5,7,98,6,1,3,5,7,9], (a, b) => { return b - a }) console.log(arr) const testArr = myMap([1,3,5,6], function (item) { if (item < 3) { return item } else { return 'toBig' } }) const testArr2 = myFilter([1,3,5,6], function (item) { return item < 4 }) console.log(testArr) console.log(testArr2)
describe('Protractor Demo App', function() { var firstNumber = element(by.model('first')); var secondNumber = element(by.model('second')); var goButton = element(by.id('gobutton')); var latestResult = element(by.binding('latest')); function addtion(var1, var2,total){ firstNumber.sendKeys(var1); secondNumber.sendKeys(var2); goButton.click(); expect(latestResult.getText()).toEqual(total); } beforeEach(function(){ browser.get('http://juliemr.github.io/protractor-demo/'); }) it('should have a title', function() { expect(browser.getTitle()).toEqual('Super Calculator'); }); it('adding 1 and 3', function() { addtion(1,3,'4'); }); it('adding 3 and 3', function() { addtion(3,3,'6'); }); it('adding 3 and 3', function() { addtion(5,5,'10'); browser.takeScreenshot() }); });
export function getHouseholdFromStorage() { try { return JSON.parse(localStorage.getItem("householdStorage")) || {}; } catch (error) { return {}; } } export function setHouseholdtoStorage(household) { localStorage.setItem("householdStorage", JSON.stringify(household)); }
import path from 'path'; // 文件夹路径 export let Dir = { dist: path.resolve(__dirname,'../dist'), // 开发环境文件目录 build: path.resolve(__dirname,'../build'),// 生产环境文件目录 src: path.resolve(__dirname,'../src'), // 编译前文件目录 asserts: path.resolve(__dirname,'../src/asserts') // 放置不被编译文件,直接输出 } // 配置文件路径 export let Path = { html: Dir.src + '/**/*.html', css: Dir.src + '/css/**/*.css', js: Dir.src + '/js/**/*.js', sass: Dir.src + '/sass/**/*.scss', img: Dir.src + '/img/**/*', asserts: Dir.src + '/asserts/**/*' }
var el = document.getElementById('resultado'); const usuarios = [ { nome: 'Caio', idade: 25, empresa: 'Google' }, { nome: 'Tiago', idade: 35, empresa: 'Microsoft' }, { nome: 'Felipe', idade: 30, empresa: 'Apple' }, ];
document.addEventListener("DOMContentLoaded", function() { const container= document.querySelector('#nav-toggle'); container.addEventListener('click',function(){ this.classList.toggle("navActive"); const contentItem= document.querySelector('.menu'); contentItem.classList.toggle("open"); }); });
import * as modules from './children/*/store.js' export default () => { return { namespaced: true, modules, } }
const q_data = [ { question : ' ؟لتعريف القائمة في لغة البايثون يتم استخدام ', a : '()', b : '<>', c : '{}', d : '[]', correct : 'd' }, { question : 'دالة if فيما تستخدم بلغة البايثون؟', a : 'لعمل شرط', b : 'لعمل تكرار', c : 'لعمل كلاس', d : 'لعمل دالة', correct : 'a' }, { question : 'لتعريف متغير في لغة البايثون؟ ', a : 'var', b : 'def', c : 'yeid', d : 'لا شيء مما سبق', correct : 'd' }, { question : 'لتحويل قيمة متغير رقمي إلى نصي في لغة البايثون يتم استخدام', a : 'str()', b : 'float()', c : 'int()', d : 'print()', correct : 'a' }, { question : 'لإدخال قيمة من خلال المستخدم يتم استخدام ', a : 'print()', b : 'input()', c : 'append()', d : 'join()', correct : 'b' }, ]; const quiz = document.getElementById('quiz'); const question = document.getElementById('question'); const a_text = document.getElementById('a_text'); const b_text = document.getElementById('b_text'); const c_text = document.getElementById('c_text'); const d_text = document.getElementById('d_text'); const btn = document.getElementById('submit'); const answer_elem= document.querySelectorAll('.answer'); let crrent_question = 0; let crrent_quiz = 0; let answer = undefined; let score = 0; load_quiz = ()=>{ console.log(q_data[crrent_quiz]); const crrent_quiz_data = q_data[crrent_quiz]; question.innerHTML = crrent_quiz_data.question; a_text.innerText = crrent_quiz_data.a; b_text.innerText = crrent_quiz_data.b; c_text.innerText = crrent_quiz_data.c; d_text.innerText = crrent_quiz_data.d; crrent_question++; }; getSelected = ()=>{ let answer= undefined; answer_elem.forEach((elem) =>{ if(elem.checked){ answer = elem.id; } }); return answer; }; deSelected = () =>{ answer_elem.forEach((elem) =>{ elem.checked = false; }); }; btn.addEventListener('click', ()=>{ const answer = getSelected(); if(answer){ if(answer===q_data[crrent_quiz].correct){ score++; } crrent_quiz++; } if(crrent_quiz < q_data.length){ load_quiz(); }else{ quiz.innerHTML = `<h2> you answerd correctly at ${score} / ${q_data.length} questions</h2> <button onclick = "location.reload()">إعادة المحاولة </button>` } }); load_quiz();
const cart = { type: 'object', required: ['id', 'name', 'amount'], properties: { id: { type: 'string', faker: 'random.uuid' }, name: { type: 'string', faker: 'commerce.productMaterial' }, amount: { type: 'number', faker: 'finance.amount' } } } const item = { type: 'object', required: ['id', 'name', 'amount'], properties: { id: { type: 'string', faker: 'random.uuid' }, name: { type: 'string', faker: 'commerce.product' }, amount: { type: 'number', format: 'integer', faker: { 'random.number': [10] } } } } const items = (limit, items) => ({ type: 'object', required: ['items'], properties: { items: { type: 'array', minItems: limit, maxItems: limit, items } } }) module.exports = { item, cart, items }
import * as React from "react"; function AccountIcon(props) { return ( <svg xmlns="http://www.w3.org/2000/svg" width="13.2" height="14.699" viewBox="0 0 13.2 14.699" {...props} > <g id="Group_640" data-name="Group 640" transform="translate(-119.4 -570.471)" > <path id="Path_19" data-name="Path 19" d="M1,19.556V18.037A3.018,3.018,0,0,1,4,15h6a3.018,3.018,0,0,1,3,3.037v1.519" transform="translate(119 565.015)" fill="none" stroke="#1d1d1d" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.2" /> <ellipse id="Ellipse_2" data-name="Ellipse 2" cx="3.202" cy="3.037" rx="3.202" ry="3.037" transform="translate(122.798 571.071)" fill="none" stroke="#1d1d1d" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.2" /> </g> </svg> ); } export default AccountIcon;
/*globals App Class Raphael Element Options $lambda */ App.ns('App.TextCircle'); App.TextCircle = new Class({ Extends: App.TextNode, Implements: Options, options: { cls: 'text-circle', fill: '#f00', stroke: '#fff', 'stroke-width': 10, opacity: 0.75, x: 0, y: 0, r: 300, min_r: 75, text: 'Lorem Ipsum', textSizeBuffer: 20 }, initialize: function(options) { var o = this.options, c_atr; // set options this.setOptions(options); // draw canvas and circle this._initialize_svg(); this._drawShape(); // draw text object c_atr = this.circle.attrs; this.parent({ cls: o.cls, text: o.text, x: c_atr.cx, y: c_atr.cy, w: 30 }); // does proper positioning this.setText(o.text); this._initialize_drag_drop(); this.fireEvent('create'); }, /** * setText * sets message text and readjusts underlying text and circle sizes to accomdate * @param String */ setText: function(text) { var o = this.options, longest_word = 0, size; this.parent(text); this.setOptions({text: text}); size = this.getTextSize(); text.split(' ').each(function(w) { if (w.length > longest_word) { longest_word = w.length; } }, this); // if line breaks are such that calculating width won't accomodate line width if (longest_word > 3 && longest_word > text.length/2) { this.grow(((longest_word/text.length)*size.w)/2*Math.sqrt(2) - o.r + o.textSizeBuffer); } // else extrapolate the estimated square size of the text else { this.grow(Math.sqrt(size.w*size.h)/2*Math.sqrt(2) - o.r + o.textSizeBuffer); } }, /** * grow * change the size of the shape and text node * @param Integer change in circle radius */ grow: function(dr) { var o = this.options, new_r = o.r + dr; if (!this.first) { new_r = o.r/2; this.first = true; } new_r = (new_r < this.options.min_r) ? this.options.min_r : new_r; this.setOptions({r: new_r}); this.animate(); // resize text node this.resize(this.circle.attrs.cx, this.circle.attrs.cy, this._width()); }, /** * moveTo * provides non animated translation * @param Integer x * @param Integer y */ moveTo: function(x, y) { var w = this._width(); this.circle.attr({cx: x, cy: y}); this.outline.attr({cx: x, cy: y}); this.setStyles({left: x - w/2, top: y - w/2}); }, /** * fade * fades elements * @param Float opacity value */ fade: function(opacity) { var o = this.options; this.getTextEl().setStyles({opacity: opacity}); this.setOptions({opacity: opacity}); this.animate('<'); }, /** * animate * animates in the currently specified configuration options * @param String name of Raphael.js easing function */ animate: function(easing) { easing = easing || "bounce"; if (!this.circle.in_animation) { this.circle.animate({ r: this.options.r, opacity: this.options.opacity }, 500, easing); } if (!this.outline.in_animation) { this.outline.animate({ r: this.options.r + this.options['stroke-width']/2, opacity: this.options.opacity }, 500, easing); } }, /** * remove * removes this element giving enough time for removal animation */ remove: function() { this.parent(); (function() { console.log('removing svg els'); this.circle.remove(); this.outline.remove(); }).delay(1000, this); }, // private methods // ............... /** * _initialize_svg * create svg drawing area, requires raphael.js */ _initialize_svg: function(){ App.TextCircle.paper = App.TextCircle.paper || Raphael(0, 0, '100%', '100%'); }, /** * _drawShape * draws the underlying svg shapes */ _drawShape: function() { var o = this.options; this.circle = App.TextCircle.paper.circle(o.x, o.y, o.r).attr({ fill: o.fill, opacity: o.opacity, stroke: 0 }); this.outline = App.TextCircle.paper.circle(o.x, o.y, o.r + o['stroke-width']/2).attr({ stroke: o.stroke, 'stroke-width': o['stroke-width'], opacity: o.opacity }); $(this.outline.node).setStyle('cursor', 'move'); }, /** * _initialize_drag_drop * initializes drag and drop * passes mousedown events from text to the svg node * builds drag and drop for the svg node */ _initialize_drag_drop: function() { this.addEvent('mousedown', function(e){ var fireOnThis = this.circle.node; var evObj = document.createEvent('MouseEvents'); evObj.initMouseEvent('mousedown', true, true, window, 1, e.client.x, e.client.y, e.client.x, e.client.y); fireOnThis.dispatchEvent(evObj); }.bind(this)); this.outline.drag(this._dd_functions()._moving, this._dd_functions()._startMove, this._dd_functions()._endMove); }, /** * _dd_functions * supporting drag and drop handlers * this becomes circle and self becomes instance */ _dd_functions: function(){ var self = this; return { _startMove: function () { this.ox = this.attr("cx"); this.oy = this.attr("cy"); this.attr({opacity: self.options.opacity/3}); self.circle.attr({opacity: self.options.opacity/3}); }, _moving: function (dx, dy) { var w = self._width(); this.attr({cx: this.ox + dx, cy: this.oy + dy}); self.circle.attr({cx: this.ox + dx, cy: this.oy + dy}); self.setStyles({left: this.ox + dx - w/2, top: this.oy + dy - w/2}); self.setOptions({x: this.attr("cx"), y: this.attr("cy")}); self.fireEvent('move', [self]); }, _endMove: function () { this.attr({opacity: self.options.opacity}); self.circle.attr({opacity: self.options.opacity}); self.setOptions({x: this.attr("cx"), y: this.attr("cy")}); self.fireEvent('afterMove', [self]); } }; }, /** * utility function to calculate an inscribed squares width within the circle */ _width: function() { return this.options.r*Math.sqrt(2); } });
var searchData= [ ['label',['label',['../structefp__atom.html#a0203cf0d653ceda28d23707f8c3ea55d',1,'efp_atom']]], ['libefp_5fversion_5fstring',['LIBEFP_VERSION_STRING',['../efp_8h.html#aedc79307a0109e1e2dc3a33900c6ca8e',1,'efp.h']]] ];
/** * 后台公用模块 */ define(["jquery", "config", "functions", 'jquery.cookie', 'bootstrap'], function($, C, D) { var Common = { init: function() { this.checkAuth(); this.placeholder(); this.headerHandle(); this.leftHandle(); this.middleHandle(); this.getLoginName(); }, checkAuth: function() { var authUrl = C.AUTH_API_PATH; //验证权限接口 var that = this; $.ajax({ url: authUrl, type: C.DATA_METHOD, dataType: C.DATA_TYPE, //跨域请求 xhrFields: { withCredentials: true }, success: function(res) { if (res.returnCode != C.SUCCESS_CODE) { $("#mainModal").find('.modal-title').text('提示'); $("#mainModal").find('.modal-body').html(res.msg); $('#mainModal').modal("show"); $('#mainModal').on('hidden.bs.modal', function(e) { D.goto('login.html'); $.removeCookie("sessionId"); $.removeCookie("loginName"); }) } else { var rootMenuList = res.result.rootMenuList; rootMenuList = $.parseJSON(rootMenuList); that.getRootMenu(rootMenuList); var subMenuList = res.result.subMenuList; subMenuList = $.parseJSON(subMenuList); that.getLeftMenu(subMenuList); } }, error: function() { layer.alert("服务端无响应", function() { D.goto("login.html"); }); } }) }, getRootMenu: function(rootMenuList) { Common.renderTpl("topModuleMenu", rootMenuList); }, getLoginName: function() { if (null != $.cookie('loginName')) { var loginName = $.cookie('loginName'); $("#loginName").html(loginName); } }, getLeftMenu: function(subMenuList) { var menu = []; $.each(subMenuList,function(index, el) { var menuChild = {} menuChild.parentCode = el.sysMenuCode; menuChild.menuList = el.childMenuList; menu.push(menuChild); }); this.renderTpl("lefModuleMenu",menu); }, //上部菜单切换 headerHandle: function() { $(".aloha-module-menu").on("click", "a", function() { $('ul[id^="admincpNavTabs_"]').hide(); $(".aloha-module-menu").find("li").removeClass("active"); var modules = $(this).parent().addClass("active").attr("data-param"); $("#admincpNavTabs_" + modules).show().find(".second").removeClass("active").first().addClass('active') .find(".mid-nav").show().find(".third").removeClass('active').first().addClass('active') .find('a:first').trigger('click'); }) }, //左侧菜单 leftHandle: function() { $(".lefModuleMenu").on("click",".second>.left-nav-tab", function() { if ($(this).parent().hasClass("active")) return; $(".second").removeClass("active"); $(".second").find(".mid-nav").hide(); $(this).parent().addClass('active').find(".mid-nav").show() .find(".third").removeClass('active').first().addClass('active') .find('a:first').trigger('click'); }) }, //中间菜单 middleHandle: function() { $(".lefModuleMenu").on("click",".third>a", function() { /*if($(this).parent().hasClass("active"))return;*/ $(".third").removeClass("active"); $(".second").removeClass("active"); $(this).parent().closest(".mid-nav").show(); $(this).parent().addClass("active"); $(this).parent().closest('.second').addClass('active'); var url = $(this).attr("url-param"); if (url == undefined) { $(".J_iframe").attr("src", "ie6update.html"); } $(".J_iframe").attr("src", url); }) }, placeholder: function() { /* * 为低版本IE添加placeholder效果 * * 使用范例: * [html] * <input id="captcha" name="captcha" type="text" placeholder="验证码" value="" > * [javascrpt] * $("#captcha").nc_placeholder(); * * 生效后提交表单时,placeholder的内容会被提交到服务器,提交前需要把值清空 * 范例: * $('[data-placeholder="placeholder"]').val(""); * $("#form").submit(); * */ (function($) { $.fn.aloha_placeholder = function() { var isPlaceholder = 'placeholder' in document.createElement('input'); return this.each(function() { if (!isPlaceholder) { $el = $(this); $el.focus(function() { if ($el.attr("placeholder") === $el.val()) { $el.val(""); $el.attr("data-placeholder", ""); } }).blur(function() { if ($el.val() === "") { $el.val($el.attr("placeholder")); $el.attr("data-placeholder", "placeholder"); } }).blur(); } }); }; })(jQuery) }, renderTpl: function(id, data) { require(['handelbars'], function(Handelbars) { var template = Handelbars.compile($("#" + id + "Tpl").html()); var html = template(data); $("#" + id).html(html); }) } } return Common; });
// Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {kChunkWidth, kChunkHeight} from './map-processor.mjs'; import {div, removeAllChildren, $} from './helper.mjs'; class State { constructor(mapPanelId, timelinePanelId) { this._nofChunks = 400; this._map = undefined; this._timeline = undefined; this._chunks = undefined; this._view = new View(this, mapPanelId, timelinePanelId); //TODO(zcankara) Depreciate the view this.mapPanel_ = $(mapPanelId); this._navigation = new Navigation(this, this.view); } set filteredEntries(value) { this._filteredEntries = value; if (this._filteredEntries) { //TODO(zcankara) update timeline view } } get filteredEntries() { return this._filteredEntries; } set entries(value) { this._entries = value; } get entries() { return this._entries; } get timeline() { return this._timeline } set timeline(value) { this._timeline = value; this.updateChunks(); this.view.updateTimeline(); this.mapPanel_.updateStats(this.timeline); } get chunks() { return this._chunks } get nofChunks() { return this._nofChunks } set nofChunks(count) { this._nofChunks = count; this.updateChunks(); this.view.updateTimeline(); } get mapPanel() { return this.mapPanel_; } get view() { return this._view } get navigation() { return this._navigation } get map() { return this._map } set map(value) { this._map = value; this._navigation.updateUrl(); this.mapPanel_.map = this._map; this.view.redraw(); } updateChunks() { this._chunks = this._timeline.chunks(this._nofChunks); } get entries() { if (!this.map) return {}; return { map: this.map.id, time: this.map.time } } } class Navigation { constructor(state, view) { this.state = state; this.view = view; } get map() { return this.state.map } set map(value) { this.state.map = value } get chunks() { return this.state.chunks } increaseTimelineResolution() { this.state.nofChunks *= 1.5; } decreaseTimelineResolution() { this.state.nofChunks /= 1.5; } selectNextEdge() { if (!this.map) return; if (this.map.children.length != 1) return; this.map = this.map.children[0].to; } selectPrevEdge() { if (!this.map) return; if (!this.map.parent()) return; this.map = this.map.parent(); } selectDefaultMap() { this.map = this.chunks[0].at(0); } moveInChunks(next) { if (!this.map) return this.selectDefaultMap(); let chunkIndex = this.map.chunkIndex(this.chunks); let chunk = this.chunks[chunkIndex]; let index = chunk.indexOf(this.map); if (next) { chunk = chunk.next(this.chunks); } else { chunk = chunk.prev(this.chunks); } if (!chunk) return; index = Math.min(index, chunk.size() - 1); this.map = chunk.at(index); } moveInChunk(delta) { if (!this.map) return this.selectDefaultMap(); let chunkIndex = this.map.chunkIndex(this.chunks) let chunk = this.chunks[chunkIndex]; let index = chunk.indexOf(this.map) + delta; let map; if (index < 0) { map = chunk.prev(this.chunks).last(); } else if (index >= chunk.size()) { map = chunk.next(this.chunks).first() } else { map = chunk.at(index); } this.map = map; } updateUrl() { let entries = this.state.entries; let params = new URLSearchParams(entries); window.history.pushState(entries, '', '?' + params.toString()); } } class View { constructor(state, mapPanelId, timelinePanelId) { this.mapPanel_ = $(mapPanelId); this.mapPanel_.addEventListener( 'statemapchange', e => this.handleStateMapChange(e)); this.mapPanel_.addEventListener( 'selectmapdblclick', e => this.handleDblClickSelectMap(e)); this.mapPanel_.addEventListener( 'sourcepositionsclick', e => this.handleClickSourcePositions(e)); this.timelinePanel_ = $(timelinePanelId); this.state = state; setInterval(this.timelinePanel_.updateOverviewWindow(), 50); this.timelinePanel_.createBackgroundCanvas(); this.isLocked = false; this._filteredEntries = []; } get chunks() { return this.state.chunks } get timeline() { return this.state.timeline } get map() { return this.state.map } handleClickSourcePositions(e){ //TODO(zcankara) Handle source position console.log("source position map detail: ", e.detail); } handleDblClickSelectMap(e){ //TODO(zcankara) Handle double clicked map console.log("double clicked map: ", e.detail); } handleStateMapChange(e){ this.state.map = e.detail; } handleIsLocked(e){ this.state.view.isLocked = e.detail; } updateTimeline() { let chunksNode = this.timelinePanel_.timelineChunks; removeAllChildren(chunksNode); let chunks = this.chunks; let max = chunks.max(each => each.size()); let start = this.timeline.startTime; let end = this.timeline.endTime; let duration = end - start; const timeToPixel = chunks.length * kChunkWidth / duration; let addTimestamp = (time, name) => { let timeNode = div('timestamp'); timeNode.innerText = name; timeNode.style.left = ((time - start) * timeToPixel) + 'px'; chunksNode.appendChild(timeNode); }; let backgroundTodo = []; for (let i = 0; i < chunks.length; i++) { let chunk = chunks[i]; let height = (chunk.size() / max * kChunkHeight); chunk.height = height; if (chunk.isEmpty()) continue; let node = div(); node.className = 'chunk'; node.style.left = (i * kChunkWidth) + 'px'; node.style.height = height + 'px'; node.chunk = chunk; node.addEventListener('mousemove', e => this.handleChunkMouseMove(e)); node.addEventListener('click', e => this.handleChunkClick(e)); node.addEventListener('dblclick', e => this.handleChunkDoubleClick(e)); backgroundTodo.push([chunk, node]) chunksNode.appendChild(node); chunk.markers.forEach(marker => addTimestamp(marker.time, marker.name)); } this.timelinePanel_.asyncSetTimelineChunkBackground(backgroundTodo) // Put a time marker roughly every 20 chunks. let expected = duration / chunks.length * 20; let interval = (10 ** Math.floor(Math.log10(expected))); let correction = Math.log10(expected / interval); correction = (correction < 0.33) ? 1 : (correction < 0.75) ? 2.5 : 5; interval *= correction; let time = start; while (time < end) { addTimestamp(time, ((time - start) / 1000) + ' ms'); time += interval; } this.drawOverview(); this.redraw(); } handleChunkMouseMove(event) { if (this.isLocked) return false; let chunk = event.target.chunk; if (!chunk) return; // topmost map (at chunk.height) == map #0. let relativeIndex = Math.round(event.layerY / event.target.offsetHeight * chunk.size()); let map = chunk.at(relativeIndex); this.state.map = map; } handleChunkClick(event) { this.isLocked = !this.isLocked; } handleChunkDoubleClick(event) { this.isLocked = true; let chunk = event.target.chunk; if (!chunk) return; this.state.view.isLocked = true; this.mapPanel_.mapEntries = chunk.getUniqueTransitions(); } drawOverview() { const height = 50; const kFactor = 2; //let canvas = this.backgroundCanvas; let canvas = this.timelinePanel_.backgroundCanvas; canvas.height = height; canvas.width = window.innerWidth; let ctx = canvas.getContext('2d'); let chunks = this.state.timeline.chunkSizes(canvas.width * kFactor); let max = chunks.max(); ctx.clearRect(0, 0, canvas.width, height); ctx.fillStyle = 'white'; ctx.beginPath(); ctx.moveTo(0, height); for (let i = 0; i < chunks.length; i++) { ctx.lineTo(i / kFactor, height - chunks[i] / max * height); } ctx.lineTo(chunks.length, height); ctx.strokeStyle = 'white'; ctx.stroke(); ctx.closePath(); ctx.fill(); let imageData = canvas.toDataURL('image/webp', 0.2); this.timelinePanel_.timelineOverview.style.backgroundImage = 'url(' + imageData + ')'; } redraw() { let canvas = this.timelinePanel_.timelineCanvas; canvas.width = (this.chunks.length + 1) * kChunkWidth; canvas.height = kChunkHeight; let ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, kChunkHeight); if (!this.state.map) return; //TODO(zcankara) Redraw the IC events on canvas. this.drawEdges(ctx); } setMapStyle(map, ctx) { ctx.fillStyle = map.edge && map.edge.from ? 'white' : '#aedc6e'; } setEdgeStyle(edge, ctx) { let color = edge.getColor(); ctx.strokeStyle = color; ctx.fillStyle = color; } markMap(ctx, map) { let [x, y] = map.position(this.state.chunks); ctx.beginPath(); this.setMapStyle(map, ctx); ctx.arc(x, y, 3, 0, 2 * Math.PI); ctx.fill(); ctx.beginPath(); ctx.fillStyle = 'white'; ctx.arc(x, y, 2, 0, 2 * Math.PI); ctx.fill(); } markSelectedMap(ctx, map) { let [x, y] = map.position(this.state.chunks); ctx.beginPath(); this.setMapStyle(map, ctx); ctx.arc(x, y, 6, 0, 2 * Math.PI); ctx.strokeStyle = 'white'; ctx.stroke(); } drawEdges(ctx) { // Draw the trace of maps in reverse order to make sure the outgoing // transitions of previous maps aren't drawn over. const kMaxOutgoingEdges = 100; let nofEdges = 0; let stack = []; let current = this.state.map; while (current && nofEdges < kMaxOutgoingEdges) { nofEdges += current.children.length; stack.push(current); current = current.parent(); } ctx.save(); this.drawOutgoingEdges(ctx, this.state.map, 3); ctx.restore(); let labelOffset = 15; let xPrev = 0; while (current = stack.pop()) { if (current.edge) { this.setEdgeStyle(current.edge, ctx); let [xTo, yTo] = this.drawEdge(ctx, current.edge, true, labelOffset); if (xTo == xPrev) { labelOffset += 8; } else { labelOffset = 15 } xPrev = xTo; } this.markMap(ctx, current); current = current.parent(); ctx.save(); // this.drawOutgoingEdges(ctx, current, 1); ctx.restore(); } // Mark selected map this.markSelectedMap(ctx, this.state.map); } drawEdge(ctx, edge, showLabel = true, labelOffset = 20) { if (!edge.from || !edge.to) return [-1, -1]; let [xFrom, yFrom] = edge.from.position(this.chunks); let [xTo, yTo] = edge.to.position(this.chunks); let sameChunk = xTo == xFrom; if (sameChunk) labelOffset += 8; ctx.beginPath(); ctx.moveTo(xFrom, yFrom); let offsetX = 20; let offsetY = 20; let midX = xFrom + (xTo - xFrom) / 2; let midY = (yFrom + yTo) / 2 - 100; if (!sameChunk) { ctx.quadraticCurveTo(midX, midY, xTo, yTo); } else { ctx.lineTo(xTo, yTo); } if (!showLabel) { ctx.strokeStyle = 'white'; ctx.stroke(); } else { let centerX, centerY; if (!sameChunk) { centerX = (xFrom / 2 + midX + xTo / 2) / 2; centerY = (yFrom / 2 + midY + yTo / 2) / 2; } else { centerX = xTo; centerY = yTo; } ctx.strokeStyle = 'white'; ctx.moveTo(centerX, centerY); ctx.lineTo(centerX + offsetX, centerY - labelOffset); ctx.stroke(); ctx.textAlign = 'left'; ctx.fillStyle = 'white'; ctx.fillText( edge.toString(), centerX + offsetX + 2, centerY - labelOffset) } return [xTo, yTo]; } drawOutgoingEdges(ctx, map, max = 10, depth = 0) { if (!map) return; if (depth >= max) return; ctx.globalAlpha = 0.5 - depth * (0.3 / max); ctx.strokeStyle = '#666'; const limit = Math.min(map.children.length, 100) for (let i = 0; i < limit; i++) { let edge = map.children[i]; this.drawEdge(ctx, edge, true); this.drawOutgoingEdges(ctx, edge.to, max, depth + 1); } } } export { State };
var nlp = require('./src/index'); // nlp.verbose('tagger'); var doc = nlp('She\'s coming by '); doc.debug();
//Show alert document.addEventListener("DOMContentLoaded", function() { var alert = document.createElement("div"); alert.setAttribute('class', 'alert alert-success alert-dismissible ' + 'blog-alert fade show'); alert.setAttribute('role', 'alert'); var msg = document.getElementById("alerts").getAttribute('data-msg') alert.innerText = msg; var btn = document.createElement('button'); btn.setAttribute('type', 'button'); btn.setAttribute('class', 'close'); btn.setAttribute('data-dismiss', 'alert'); btn.setAttribute('aria-label', 'Close'); var span = document.createElement('span'); btn.setAttribute('aria-hidden', 'true'); btn.innerText = '×'; btn.appendChild(span); alert.appendChild(btn); document.body.appendChild(alert); setTimeout(function() { document.body.removeChild(alert) }, 3000); });
/*global define, require, location*/ /*jshint laxcomma:true*/ (function () { 'use strict'; var pathRX = new RegExp(/\/[^\/]+$/) , locationPath = location.pathname.replace(pathRX, '/'); //dojoConfig = { // parseOnLoad: false, // async: true, // tlmSiblingOfDojo: false, // locale: "zh-cn", // has: { // 'extend-esri': 1 // }, // paths:{ // "echarts": locationPath + "../libs/echart/echarts.min" // }, // packages : [{ // name: 'controllers', // location: locationPath + 'map/controllers' // }, { // name: 'services', // location: locationPath + 'map/services' // }, { // name: 'utils', // location: locationPath + 'map/utils' // },{ // name: 'stores', // location: locationPath + 'map/stores' // }, { // name: 'widgets', // location: locationPath + 'map/widgets' // }, { // name : "onemap", // location : locationPath + "../onemap" // }, // {name: "jquery", location: locationPath + "../libs/jquery", main: "jquery-1.10.1"}] //}; // require({ async: true, aliases: [ ['text', 'dojo/text'] ], paths:{ "echarts": locationPath + "../libs/echart/echarts.min", "PouchDB": locationPath + "../libs/pouchdb.min" , "jquery": locationPath + "../libs/jquery/jquery-1.10.1" }, packages: [{ name: 'controllers', location: locationPath + '../gis.js/controllers' }, { name: 'services', location: locationPath + '../gis.js/services' }, { name: 'utils', location: locationPath + '../gis.js/utils' },{ name: 'stores', location: locationPath + '../gis.js/stores' }, { name: 'widgets', location: locationPath + '../gis.js/widgets' }, { name : "onemap", location : locationPath + "../onemap" }, // { // name: "PouchDB", // location : locationPath + "../libs/pouchdb.min" // }, { name: 'app', location: locationPath + '../gis.js', main: 'main' }] }, ['app']); })();
/*global define*/ /** * View for the menu * Will be shown in the menu region of the App */ define([ 'jquery', 'underscore', 'backbone', 'marionette', 'bootstrap' ], function ($, _, Backbone) { 'use strict'; var MenuView = Backbone.Marionette.ItemView.extend({ template: 'menu' }); return MenuView; });
import Document, { Head, Main, NextScript } from 'next/document' import flush from 'styled-jsx/server' import isEmpty from 'lodash.isempty' import AuthenticatedNavbar from 'components/navbar/authenticated' import UnauthenticatedNavbar from 'components/navbar/unauthenticated' export default class MyDocument extends Document { static getInitialProps ({ renderPage, req }) { const {html, head, errorHtml, chunks} = renderPage() const styles = flush() const isAuthenticated = !isEmpty(req.user) return { html, head, errorHtml, chunks, styles, isAuthenticated } } render () { const { html, isAuthenticated } = this.props return ( <html> <Head> <meta charSet='utf-8' /> <meta name='viewport' content='initial-scale=1.0, width=device-width' /> <link rel='stylesheet' href='https://fonts.googleapis.com/icon?family=Material+Icons' /> <link rel='stylesheet' type='text/css' href='/static/css/materialize.min.css' media='screen,projection' /> <script type='text/javascript' src='/static/js/lib/jquery-2.2.4.min.js' /> <script type='text/javascript' src='/static/js/lib/materialize.min.js' /> <script type='text/javascript' src='/static/js/app.js' /> </Head> <body> {isAuthenticated ? <AuthenticatedNavbar /> : <UnauthenticatedNavbar /> } <Main /> <NextScript /> </body> </html> ) } }
import axios from 'axios'; let base = process.env.API_ROOT; // let bases = "http://192.168.1.166:8118"; // let base = "http://192.168.1.71:5030"; //let bases = "http://test-tms.logwsd.com"; export const delstorehouse = params => { return axios.post(`${base}/storehouse/delete`, params ).then(res => res.data) }; export const getUserList = params => { return axios.get(`${base}/user/list`, { params: params }); }; export const getUserListPage = params => { return axios.get(`${base}/user/listpage`, { params: params }); }; export const removeUser = params => { return axios.get(`${base}/user/remove`, { params: params }); }; export const batchRemoveUser = params => { return axios.get(`${base}/user/batchremove`, { params: params }); }; export const editUser = params => { return axios.get(`${base}/user/edit`, { params: params }); }; export const addUser = params => { return axios.get(`${base}/user/add`, { params: params }); }; export const selectData = params => { return axios.get(`${base}/dispatcherStatist2/vehicleGroups`, { params: params }); }; export const lastLocation = params => { return axios.post(`${base}/gps/lastLocationPC`, params).then(res => res.data) }; export const truckTrack = params => { return axios.post(`${base}/gps/truckTrackPC`, params).then(res => res.data) }; export const historyTruckTrack = params => { return axios.post(`${base}/gps/historyTruckTrackPC`, params).then(res => res.data) }; export const orderList = params => { return axios.post(`${base}/gps/orderList`, params).then(res => res.data) }; export const getVehStatusNum = params => { return axios.get(`${base}/v3/getVehStatusNum`, { params: params }); }; export const getVehStatusList = params => { return axios.get(`${base}/v3/getVehStatusList`, { params: params});}; export const loadingTruckNum = params => { return axios.get(`${base}/vehicles/loadCar`, { params: params}); }; export const deliveryTruckNum = params => { return axios.get(`${base}/gpsV2_3/deliveryTruckNum`, { params: params }); }; export const waybillDetails = params => { return axios.get(`${base}/gpsV2/waybillDetails`, { params: params }); }; //export const finishOrder = params => { return axios.get(`${base}/gpsV2_3/finishWaybillDetails`, { params: params }); }; export const vehicleGroupsQuery = params => { return axios.get(`${base}/gpsV2_3/getVehgrpnam`, { params: params }); }; export const contractVehicle = params => { return axios.get(`${base}/gpsV2_3/getVehlicnum`, { params: params }); }; export const finishWaybillDetails = params => { return axios.get(`${base}/gpsV2_3/finishWaybillDetails`, { params: params }); }; export const historyTruckNum = params => { return axios.post(`${base}/gpsV2_3/historyTruckNum`, params).then(res => res.data) }; export const appointManage = params => { return axios.get(`${base}/vehicles/appoint_manage`, { params: params }); }; export const noSentOrder = params => { return axios.get(`${base}/vehicles/noSentOrder`, { params: params }); }; export const deliveryDetaileds = params => { return axios.get(`${base}/vehicles/deliveryDetaileds`, { params: params }); }; export const tit = params => { return axios.get(`${base}/gps/title`, { params: params }); };
// Credit for app goes to https://www.youtube.com/watch?v=8iuPNq553U0 $(document).ready(function(){ // key owned by Trilogy var apikey = "trilogy" // Submit method to pull content from movieForm and run event function $("#movieForm").submit(function(event){ event.preventDefault(); // Variable used in url for API call var movie = $("#movie").val() // Result will be displayed in html var result = "" // URL of the API data call var url = "https://www.omdbapi.com/?apikey=" + apikey // Get request for the API call $.ajax({ method: 'Get', url:url+"&t="+movie, success:function(data) { console.table(data); // Result to be displayed result = ` <img style="float:left" class="img-thumnail" width="200" height="200" src="${data.Poster}"/> <h5>Title: ${data.Title}</h5> <h5>Date Released: ${data.Released}</h5> <h5>Runtime: ${data.Runtime}</h5> <h5>Genre: ${data.Genre}</h5> <h5>Director: ${data.Director}</h5> <h5>Actors: ${data.Actors}</h5> ` // Actually displaying the result in html $("#result").html(result); } }) }) })
import React, { useContext } from "react"; import { useMutation } from "react-apollo-hooks"; import { Formik, Field } from "formik"; import context from "../../context"; import InputField from "../fields/InputField"; import changePassword from "../../graphql/user/mutations/changePassword"; import StyledForm from "../styled/StyledForm"; import StyledFormLogo from "../styled/StyledFormLogo"; import StyledFormButton from "../styled/StyledFormButton"; import StyledFormWrapper from "../styled/StyledFormWrapper"; const ChangePassword = ({ history, match }) => { const change = useMutation(changePassword); const { dispatch } = useContext(context); return ( <Formik onSubmit={async ({ password }) => { const response = await change({ variables: { input: { password, token: match.params.token } } }); if (response.data.changePassword) { history.push("/"); dispatch({ type: "INIT_USER", payload: response.data.changePassword }); } }} initialValues={{ password: "" }} > {({ handleSubmit }) => ( <StyledFormWrapper> <StyledForm onSubmit={handleSubmit}> <StyledFormLogo /> <Field name="password" label="Password" type="password" component={InputField} /> <StyledFormButton type="submit">Change Password</StyledFormButton> </StyledForm> </StyledFormWrapper> )} </Formik> ); }; export default ChangePassword;
require('dotenv').config() const express = require("express") const app = express() const router = require('./routes/router') const mongoose = require("mongoose") const bodyParser =require("body-parser") app.use(bodyParser.json()) app.use(bodyParser.urlencoded({extended:true})) app.use('/', router) const port = 3000 app.listen(port, () => { console.log(`app is listening on port ${port}`) }) mongoose.connect('mongodb://localhost:27017/Wealthy-Words', { useNewUrlParser: true}).then(() => { console.log('database conect ok') }).catch(()=> console.log('error'))
var myVar = 10; function myFunc() { // ... } var myVar = 10; var myFunc = function(){ // ... }
// @flow import * as React from 'react'; import classNames from 'classnames'; import IconButton from './IconButton'; import Icon from './Icon'; import { defaultProps } from './utils'; type Props = { classPrefix?: string, className?: string, expanded?: boolean, onToggle?: (expanded: boolean, event: SyntheticEvent<HTMLButtonElement>) => void }; class SidenavToggle extends React.Component<Props> { handleToggle = (event: SyntheticEvent<HTMLButtonElement>) => { const { onToggle, expanded } = this.props; onToggle && onToggle(!expanded, event); }; render() { const { expanded, className, classPrefix, ...props } = this.props; const classes = classNames(classPrefix, className, { collapsed: !expanded }); return ( <div {...props} className={classes}> <IconButton appearance="default" icon={<Icon icon={expanded ? 'angle-right' : 'angle-left'} />} onClick={this.handleToggle} /> </div> ); } } export default defaultProps({ classPrefix: 'sidenav-toggle' })(SidenavToggle);
// Generated by CoffeeScript 1.11.0 (function() { var go; $(document).ready(function() { return setTimeout(go, 90000); }); go = function() { if ($('#form1_link_add')) { return $.ajax({ url: 'http://wiki.xrkmedia.com:9099/j/data', success: function(data) { var i, j, k, len, o, ref; console.log('start...'); for (i = j = 0; j <= 10; i = ++j) { $('#form1_link_add').click(); } ref = data.li; for (i = k = 0, len = ref.length; k < len; i = ++k) { o = ref[i]; $("#form1_link" + (i + 1)).val(o.url); } $('#form1_email').val('test@126.com'); console.log('填充完毕,准备提交'); $('input[type=submit].js-submit').click(); return console.log('提交'); }, error: function() {} }); } }; }).call(this);
// pages/auth/auth.js import {request} from "../../request/index" import {getSetting, chooseAddress, openSetting, showModal, showToast, login} from "../../utils/asyncWX" import regeneratorRuntim, { AsyncIterator } from '../../lib/runtime/runtime' Page({ /** * 页面的初始数据 */ data: { }, async handleGetUserInfo(e){ try { // 获取用户信息 const { encrypteData, rawData, iv, signature } = e.detail; // 获取小程序登陆成功后的code const {code} = await login(); // 发送请求获取用户token const loginParams = {encrypteData, rawData, iv, signature , code}; const {token} = await request({ url:'/users/wxlogin', data:loginParams, method: 'post' }); // token = // 缓存token 跳转上一层 wx.setStorageSync('token', "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo"); wx.navigateBack({ delta: 1 }) } catch(err){ console.log(err) } } })
var searchData= [ ['timer_5fstate_5ftype_0',['timer_state_type',['../classAITimer.html#a71591ba6ecd0af62d75b4292a1308e24',1,'AITimer']]], ['type_5ft_1',['type_t',['../structAIStatefulTask_1_1Handler.html#a49239baf5f285bd7d8161234a54c45d1',1,'AIStatefulTask::Handler']]] ];
const dbpool = require('../config/dbconfig'); const loginModule = { userDao(arr){ return new Promise((resolve,reject)=>{ var sql = 'SELECT * FROM t_admin WHERE 1=1'; if(arr.length>0){ sql += ' AND a_name=?' } if(arr.length>1){ sql += ' AND a_pwd=?' } dbpool.connect(sql,arr,(err,data)=>{ resolve(data); }) }) } }; module.exports=loginModule;
function objectToArray(obj) { var objArray = []; for (var property in obj) { objArray.push(obj[property]); } return objArray; } function findNoteById(notes, id) { if (typeof notes == 'object') { notes = objectToArray(notes); } var note = {}; for (var index in notes) { if (notes[index]['id']==id) { note = notes[index]; } } return note; } function findNoteIndexById(notes, id) { if (typeof notes == 'object') { notes = objectToArray(notes); } var _index = null; for (i=0; i<notes.length; i++) { if (notes[i]['id']==id) { _index = i; } } return _index; }
const polyfillService = require('@financial-times/dotcom-ui-polyfill-service') module.exports = (request, response, next) => { const renderOptions = { pageTitle: 'Dynamically-loaded dogs', polyfillServiceUrl: polyfillService.enhanced() } try { response.render('home.hbs', renderOptions) } catch (error) { next(error) } }
function Controller() { function loadData() { APP.currentController.searchAddress(args.address); } function addAddress() { APP.openWindow({ controller: "Settings/EditAddress", controllerParams: { faaddress: tempArr[0], facity: tempArr[1] ? tempArr[1] : "", fastate: tempArr[2] ? tempArr[2] : "" } }); } require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "RightBarView/RecentlyAddressRow"; arguments[0] ? arguments[0]["__parentSymbol"] : null; arguments[0] ? arguments[0]["$model"] : null; arguments[0] ? arguments[0]["__itemTemplate"] : null; var $ = this; var exports = {}; var __defers = {}; $.__views.RecentlyAddressRow = Ti.UI.createView({ height: 30, top: 5, id: "RecentlyAddressRow" }); $.__views.RecentlyAddressRow && $.addTopLevelView($.__views.RecentlyAddressRow); loadData ? $.__views.RecentlyAddressRow.addEventListener("click", loadData) : __defers["$.__views.RecentlyAddressRow!click!loadData"] = true; $.__views.streetLabel = Ti.UI.createLabel({ color: "white", font: { fontSize: 14 }, left: 10, right: 115, top: 0, height: 15, id: "streetLabel" }); $.__views.RecentlyAddressRow.add($.__views.streetLabel); $.__views.streetLabel2 = Ti.UI.createLabel({ color: "white", font: { fontSize: 12 }, left: 10, right: 115, top: 14, height: 15, id: "streetLabel2" }); $.__views.RecentlyAddressRow.add($.__views.streetLabel2); $.__views.__alloyId212 = Ti.UI.createButton({ backgroundSelectedImage: "/images/bgBlackOpacity39.png", backgroundImage: "/images/transparent.png", color: "white", borderColor: "white", borderWidth: 1, borderRadius: 1, style: Ti.UI.iPhone.SystemButtonStyle.PLAIN, font: { fontSize: 14 }, right: 60, width: 50, height: 28, title: "Save", id: "__alloyId212" }); $.__views.RecentlyAddressRow.add($.__views.__alloyId212); addAddress ? $.__views.__alloyId212.addEventListener("click", addAddress) : __defers["$.__views.__alloyId212!click!addAddress"] = true; exports.destroy = function() {}; _.extend($, $.__views); var APP = require("/core"); var args = arguments[0] || {}; var tempArr = args.address.split(","); $.streetLabel.text = tempArr[0]; $.streetLabel2.text = (tempArr[1] ? tempArr[1] : "") + ", " + (tempArr[2] ? tempArr[2] : ""); __defers["$.__views.RecentlyAddressRow!click!loadData"] && $.__views.RecentlyAddressRow.addEventListener("click", loadData); __defers["$.__views.__alloyId212!click!addAddress"] && $.__views.__alloyId212.addEventListener("click", addAddress); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
// let a = 2, b = 1; // let x = " \t \n" - 2; // let n = 5; // // let c = ++a; // ? // // let d = b++; // ? // // alert(c); // // alert(d); // // n += 7; // // n *= 4; // // x = -x; // alert(`x = ${x}`); // // alert(`a = ${a}`); // let a = prompt("Первое число?", 1); // let b = prompt("Второе число?", 2); // alert(+a + +b); // let age = prompt("Введите возраст....", ""); // if (!(age >= 14 && age <= 90)) { // alert('в диапазоне'); // } // else if(Num < 0){ // alert(-1); // } // else{ // alert("Вне диапазона"); // } // let result = ((a + b) < 4) ? 'Мало': 'Много'; // let message = (login == 'Сотрудник') ? 'Привет' : // (login == 'Директор') ? 'Здравствуйте' : // (login == '') ? 'Нет логина' : // '';
import React, {useState} from 'react' import axios from 'axios'; import "./styles/Book.css" function Book() { const [searchTerm, setSearchTerm] = useState(""); const [books, setBooks] = useState({ items: [] }); const onInputChange = e => { setSearchTerm(e.target.value); }; let API_URL = `https://www.googleapis.com/books/v1/volumes`; const fetchBooks = async () => { const result = await axios.get(`${API_URL}?q=${searchTerm}`); setBooks(result.data); }; const onSubmitHandler = e => { e.preventDefault(); fetchBooks(); }; const bookAuthors = authors => { if (authors.length <= 2) { authors = authors.join(" and "); } else if (authors.length > 2) { let lastAuthor = " and " + authors.slice(-1); authors.pop(); authors = authors.join(", "); authors += lastAuthor; } return authors; }; return ( <div> <section className="book-section"> <div class="container justify-content-center"> <div class="card mt-5 p-4"> <h4 class="text mb-4 text-center">Search for any books</h4> <form onSubmit={onSubmitHandler}> <div class="input-group mb-3"> <input type="search" placeholder="Search for your programming book..." value={searchTerm} onChange={onInputChange} className="form-control"/> <div class="input-group-append"><button class="btn btn-primary" type="submit"><i class="fas fa-search"></i></button></div> </div> </form> </div> </div> <ul className="row container-fluid"> {books.items.map((book, index) => { return ( <li key={index}> <div className="book-cover d-flex justify-content-center"> <img alt={`${book.volumeInfo.title} book`} src={`http://books.google.com/books/content?id=${ book.id }&printsec=frontcover&img=1&zoom=1&source=gbs_api`} /> <div> <h3>{book.volumeInfo.title}</h3> <h5>{bookAuthors(book.volumeInfo.authors)}</h5> <p>{book.volumeInfo.publishedDate}</p> </div> </div> <hr /> </li> ); })} </ul> </section> </div> ) } export default Book
function range(start, end) { let r = (end) => { let arr = []; let st = start; while (end >= st) { arr.push(st++); } return arr; } if (end === undefined) { return r; } else { return r(end); } } console.log(range(3,3)); console.log(range(3,8)); console.log(range(3,0)); // [3] // [3,4,5,6,7,8] // [] var start3 = range(3); var start4 = range(4); console.log(start3(3)); console.log(start3(8)); console.log(start3(0)); console.log(start4(6)) // [3] // [3,4,5,6,7,8] // [] // [4,5,6]
import Phaser from 'phaser'; import { bindKeyboardConfig } from './KeyboardControl'; import playerImg from './assets/player/adventurer-idle-01.png'; import enemyImg from './assets/player/adventurer-idle-02.png'; import tilemapAsset from './assets/tiles/demo.json'; import tilesetAsset from './assets/tiles/atlas.png'; import Player from './Player'; import Enemy from './Enemy'; import MPlayer from './MPlayer'; import Demo from './Demo'; let player; let enemy; let cursors; let mplayer; const MMainStage = new Phaser.Class({ Extends: Phaser.Scene, initialize: function MMainStage () { Phaser.Scene.call(this, 'main'); }, preload: function() { this.load.image("playerImg", playerImg); this.load.image("enemyImg", enemyImg); this.load.image('atlas2', tilesetAsset); this.load.tilemapTiledJSON('demo', window.location.origin + '/tiles/demo.json'); }, create: function () { //boundaries this.cameras.main.setBounds(0, 296, 3392, 960); this.matter.world.setBounds(0, 296, 3392, 960); cursors = this.input.keyboard.createCursorKeys();//remove //this.matter.world.gravity.y = 680; mplayer = new MPlayer(this); // enemy = new Enemy(this); window.scene = this; //this.matter.add.collider(player.body, enemy.body); this.add.text(10, 10, 'Press wsad, 2 or 3', { font: '16px Courier', fill: '#00ff00' }); this.events.on('shutdown', this.shutdown, this); const mappy = this.make.tilemap({key: 'demo'}); const terrain = mappy.addTilesetImage('atlas2'); //layer let terrainLayer = mappy.createStaticLayer('obstacles', terrain, 0, 300).setDepth(-1); terrainLayer.setCollisionByProperty({collides: true}); this.matter.world.convertTilemapLayer(terrainLayer); //this.matter.add.collider(player.body, terrainLayer); console.log(mplayer.playerSprite); //Camera this.cameras.main.startFollow(mplayer.playerSprite.matterSprite, true, 0.08, 0.08); this.cameras.main.setZoom(1.0); }, update: function (){ mplayer.update(this); //enemy.update(); }, shutdown: function () { // We need to clear keyboard events, or they'll stack up when the Menu is re-run this.input.keyboard.shutdown(); } }); export default MMainStage;
var utils = { fillMat: function(input, mat) { for(var i = 0; i < input.length; i++) { for(var j = 0; j < input[0].length; j++) { mat.set(i, j, input[i][j]); } } return mat; }, // adds bias and sets gradients smartly // assumes that each ROW is a single example addBias: function(graph, biasMat, hiddenMat) { var sum = new R.Mat(hiddenMat.n, hiddenMat.d); var batchSize = hiddenMat.n; var hiddenSize = hiddenMat.d; var idx = 0; for(var i = 0; i < batchSize; i++) { for(var j = 0; j < hiddenSize; j++) { sum.w[i*hiddenSize + j] = hiddenMat.w[i*hiddenSize + j] + biasMat.w[j]; } } var back = function() { for(var i = 0; i < batchSize; i++) { for(var j = 0; j < hiddenSize; j++) { biasMat.dw[j] += sum.dw[i*hiddenSize + j]; hiddenMat[i*hiddenSize + j] += sum.dw[i*hiddenSize + j]; } } } graph.backprop.push(back); return sum; }, // attaches gradients to a batch of labels // assumes that each ROW is a single example softmaxBatchGrads: function(activationMat, hiddens, labels) { var cost = 0; var batchSize = labels.length; var idx = 0; for(var i = 0; i < batchSize; i++) { var label = labels[i]; for(var j = 0; j < label.length; j++) { hiddens.dw[idx] = activationMat.w[idx] - label[j]; if(label[j] == 1) { cost += -Math.log(activationMat.w[j]) } idx += 1; } } return cost; }, softmax: function(arrayVector) { var out = [] var maxval = -999999; for(var i=0;i<arrayVector.length;i++) { if(arrayVector[i] > maxval) maxval = arrayVector[i]; } var s = 0.0; for(var i=0;i<arrayVector.length;i++) { var exp = Math.exp(arrayVector[i] - maxval) out.push(exp); s += exp; } for(var i=0;i<out.length;i++) { out[i] /= s; } return out; }, softmaxBatch: function(hiddens) { var batchSize = hiddens.n; var inputSize = hiddens.d; var out = new R.Mat(hiddens.n, hiddens.d); for(var idx = 0; idx < batchSize; idx++) { var input = hiddens.w.slice(idx * inputSize, idx * inputSize + inputSize); var softmax = this.softmax(input); for(var j = 0; j < inputSize; j++) { out.set(idx, j, softmax[j]); } } return out; }, softmaxLayer: function(graph, graphMats, inputs, labels, weights, bias) { var mat_prod = graph.mul(inputs, graphMats[weights]); var hiddens = this.addBias(graph, graphMats[bias], mat_prod); var activations = this.softmaxBatch(hiddens); var cost = this.softmaxBatchGrads(activations, hiddens, labels); return cost; }, sigmoidLayer: function(graph, graphMats, inputs, weights, bias) { var mat_prod = graph.mul(inputs, graphMats[weights]); var hiddens = this.addBias(graph, graphMats[bias], mat_prod); var activations = graph.sigmoid(hiddens); return activations; }, reluLayer: function(graph, graphMats, inputs, weights, bias) { var mat_prod = graph.mul(inputs, graphMats[weights]); var hiddens = this.addBias(graph, graphMats[bias], mat_prod); var activations = graph.relu(hiddens); return activations; }, tanhLayer: function(graph, graphMats, inputs, weights, bias) { var mat_prod = graph.mul(inputs, graphMats[weights]); var hiddens = this.addBias(graph, graphMats[bias], mat_prod); var activations = graph.tanh(hiddens); return activations; } } module.exports = utils;
var searchData= [ ['human',['Human',['../class_human.html',1,'Human'],['../class_human.html#a4f84fcddcedd434023a001eba00a095c',1,'Human::Human()'],['../class_human.html#abfd57b90d90f9222384c76b44346ba7b',1,'Human::Human(const string &amp;name)'],['../class_human.html#a87baec7c1de5375cb7e0f15050d855d3',1,'Human::Human(const string &amp;name, const string &amp;surname)']]], ['humanclass_2eh',['HumanClass.h',['../_human_class_8h.html',1,'']]], ['hw',['hw',['../class_student.html#aa210ec262bbf18265a03b5300c6a2e54',1,'Student']]] ];
import React, { PropTypes } from 'react'; import { getObject } from '../../common/common'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './TreePage.less'; import {SuperTable, SuperToolbar, SuperTree, Indent, SuperTab} from '../index'; import {Input, Icon} from 'antd'; const InputSearch = Input.Search; const TREE_PROPS = ['tree', 'expand', 'select', 'searchValue', 'onExpand', 'onSelect']; const TABLE_EVENTS = ['onCheck', 'onDoubleClick']; const props = { tableCols: PropTypes.array, tableItems: PropTypes.array, buttons: PropTypes.array, tree: PropTypes.object, expand: PropTypes.object, select: PropTypes.string, searchValue: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), inputValue: PropTypes.string, placeholder: PropTypes.string, onInputChange: PropTypes.func, onClick: PropTypes.func, onReload: PropTypes.func //刷新树按钮响应函数 }; class TreePage extends React.Component { static propTypes = props; static PROPS = Object.keys(props); onInputChange = (e) => { const {onInputChange} = this.props; onInputChange && onInputChange(e.target.value); }; getSearchProps = () => { return { value: this.props.inputValue || '', placeholder: this.props.placeholder, onChange: this.onInputChange, onSearch: this.props.onClick.bind(null, 'search') } }; getToolbarProps = () => { return { buttons: this.props.buttons, onClick: this.props.onClick, }; }; getTreeProps = () => { return getObject(this.props, TREE_PROPS); }; getTableProps = () => { return { cols: this.props.tableCols, items: this.props.tableItems, maxHeight: 'calc(100vh - 150px)', callback: getObject(this.props, TABLE_EVENTS) }; }; getTabProps = () => { return { activeKey: this.props.activeKey || 'tree', tabs: this.props.tabs ? [ {key: 'tree', title: '目录', close: false}, {key: 'index', title: '索引', close: false} ] : [ {key: 'tree', title: '目录', close: false} ], onTabChange: this.props.onTabChange }; }; getIndexTableProps = () => { return { cols: this.props.indexTableCols || [], items:this.props.indexTableItems || [], checkbox: false, index: false, maxHeight: `calc(100vh - 195px)`, callback: { onLink: this.props.onLink } }; }; toTabContent = () => { const {activeKey = 'tree', onReload} = this.props; return activeKey === 'tree' ? ( <Indent> <div><InputSearch {...this.getSearchProps()} /> {onReload && <a onClick={onReload}><Icon type='reload'/></a>} </div> <SuperTree {...this.getTreeProps()} /> </Indent> ) : ( <Indent> <div><InputSearch {...this.getSearchProps()} /></div> <SuperTable {...this.getIndexTableProps()} /> </Indent> ) }; render = () => { return ( <div className={s.root}> <div> <SuperTab {...this.getTabProps()} /> {this.toTabContent()} </div> <Indent> <SuperToolbar {...this.getToolbarProps()} /> <SuperTable {...this.getTableProps()} /> </Indent> </div> ); }; } export default withStyles(s)(TreePage);
var searchData= [ ['tree',['tree',['../classtree.html#a9f2a566ac2710fafc31232456780e82d',1,'tree::tree()'],['../classtree.html#a3bf767f69bbd75f3e5daee29ce512762',1,'tree::tree(std::vector&lt; int &gt;)']]] ];
import React, {Component} from 'react'; import listStorage from "./../objects/ListStorage"; import "./../sass/savedLists.css"; class SavedList extends Component { constructor(props) { super(props); this.state = {savedShipLists: []}; } componentDidMount() { this.setState({savedShipLists: listStorage.getSavedShipLists()}); } componentWillUnmount() { } shareLink(key, data, proxy) { let button = proxy.target; if(button.disabled) return; button.disabled = true; fetch('https://api.kc-db.info/v1/list/ships', { method: 'put', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ data: data }) }) .then((data) => data.json()) .then((json) => { if(json.error){ return alert(json.error +`\n${json.description}`); } if(json.listId){ listStorage.saveShortLink(key,json.listId); let a = document.createElement("A"); a.href=`/#/ship-list-short/${json.listId}`; a.textContent="Short Link"; button.parentElement.replaceChild(a,button); } }) .catch((e) => { console.error("error", e); alert("Some error happened while performing request!"); }); } render() { return ( <div className={`container`}> <table className={`table savedLists`}> <tbody> { this.state.savedShipLists.map((l, k) => <tr key={`saved_sl_${k + 1}`}> <td className={"number"}>{k + 1}</td> <td className={"fullLink"}> <a href={`/#/ship-list/${l.list}`}>Full Link</a> </td> <td className={"shortlink"}> {typeof l.shortlink!=="undefined"? <a href={`/#/ship-list-short/${l.shortlink}`}>Short Link</a> : <button onClick={this.shareLink.bind(this, l.key, l.list)} type="button" className={"btn btn-info"}>Shortify</button> } </td> </tr> ) } </tbody> </table> </div> ); } } export default SavedList;
import Ember from 'ember'; import MultiStatsSocket from 'ui/utils/multi-stats'; export default Ember.Route.extend({ statsSocket: null, model() { return this.modelFor('host').get('host'); }, afterModel() { this.setupSocketConnection(); }, setupSocketConnection: function() { if (this.get('statsSocket')) { this.deactivate(); } let stats = MultiStatsSocket.create({ resource: this.modelFor('host').get('host'), linkName: 'containerStats', }); this.set('statsSocket',stats); stats.on('dataPoint', (data) => { let controller = this.get('controller'); if ( controller ) { controller.onDataPoint(data); } }); }, deactivate() { this.get('statsSocket').close(); } });
/* VUE App's MAIN Component. Copyright (c) 2018. Omar Pino. All Rights Reserved. */ 'use strict';import Vue from 'vue' import App from './App.vue' import './registerServiceWorker' import store from '@/store' import router from '@/router' Vue.config.productionTip = false class MainApp { constructor () { new Vue({ router, store, components: { App }, render: h => h( App ), }).$mount('#app'); } } // Main entry point of the application document.addEventListener('DOMContentLoaded', event => { const app = new MainApp(); });
$(document).ready(function() { $("#lesson_info").click(function() { var dataRaw = { 'lesson_id': '1' }; var dataStr = JSON.stringify(dataRaw); $.ajax({ type: 'POST', url: '/lessons/info', headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }, data: { info: dataStr }, dataType: 'json', success: function (answer) { alert(answer.res); } }); }); $("#send_mail").click(function() { $.ajax({ type: 'POST', url: '/mail', headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }, dataType: 'json', success: function (answer) { alert(answer.res); } }); }); });
'use strict'; const Bluebird = require('bluebird'); const Cheerio = require('cheerio'); const Request = Bluebird.promisify(require('request')); const BASE_URL = 'https://github.com/facebook'; async function getPage(url) { let response = await Request({ url, method: "GET", headers: { 'Cache-Control': 'no-cache' }, timeout: 10000 }) return response.body; } (async () => { console.log('Scrapping first page'); let $ = Cheerio.load(await getPage(BASE_URL)); let name = $('h1').text().trim(); let url = $('ul a.text-gray-dark').attr('href').trim(); let location = $('.has-location span').text().trim(); let result = { name, url, location, repos: [] } $('a[data-hovercard-type=repository]').toArray().forEach(el => { result.repos.push({ name: el.children[0].data.trim() }); }); let pageCount = Number($('.pagination .current').attr('data-total-pages')); if(pageCount && pageCount > 1) { for(let i = 2; i <= pageCount; i++) { console.log(`Scrapping page ${i}`); $ = Cheerio.load(await getPage(`${BASE_URL}?page=${i}`)); $('a[data-hovercard-type=repository]').toArray().forEach(el => { result.repos.push({ name: el.children[0].data.trim() }); }); } } console.log(result); return result; })()
import {LitElement, html} from 'lit-element'; class RetroBoxCounter extends LitElement { static get properties() { return { counter: {attribute:true} } } constructor() { super(); this.addEventListener('favclick', (e)=> { console.log(e.detail); this.counter = e.detail.counterVal + 1; }); } render() { return html` <div>${this.counter}</div> ` } } customElements.define('retro-box-counter', RetroBoxCounter);