text
stringlengths
7
3.69M
function numbers () { let n = 1; return function () { return n++; }; } let f = numbers (); let f2 = numbers (); for (let i=0; i<100; i++) { console.log (f()); } console.log (f2());
var React = require('react'); var Router = require('react-router'); var Link = Router.Link; var notFound = React.createClass({ render() { return( <div> <h3>404 Not Found</h3> <p>Were you looking for one of these:</p> <ul> <li><Link to="/audience">Join as audience </Link> </li> <li><Link to="/speaker">Start the presentation</Link> </li> <li><Link to="/board">View the board</Link> </li> </ul> </div> ); } }); module.exports = notFound;
import Vue from 'vue' import Router from 'vue-router' import Home from '@/views/Home.vue' import Login from '@/views/Login.vue' import Register from '@/views/Register.vue' import titleManage from '@/views/titleManage.vue' import monsterList from '@/views/monster/list.vue' import levelMonsterSet from '@/views/monster/set.vue' import equipmentList from '@/views/equipmentList.vue' import itemList from '@/views/itemList.vue' import dailyTask from '@/views/task/daily.vue' import eventTask from '@/views/task/event.vue' import cacuTask from '@/views/task/cacu.vue' import blueTask from '@/views/task/blue.vue' Vue.use(Router) export default new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/', name: 'home', component: Home }, { path: '/person/title_manage', name: 'home', component: titleManage, meta: {title:'职业模板维护'} }, { path: '/monster/list', name: 'monsterList', component: monsterList, meta: {title:'怪物维护'} }, { path: '/monster/set', name: 'levelMonsterSet', component: levelMonsterSet, meta: {title:'关卡怪物设置'} }, { path: '/equipment/list', name: 'equipmentList', component: equipmentList, meta: {title:'装备模板维护'} }, { path: '/item/list', name: 'itemList', component: itemList, meta: {title:'物品模板维护'} }, { path: '/daily/task', name: 'dailyTask', component: dailyTask, meta: {title:'日常任务'} }, { path: '/event/task', name: 'eventTask', component: eventTask, meta: {title:'活动任务'} }, { path: '/blue/task', name: 'blueTask', component: blueTask, meta: {title:'蓝色任务'} }, { path: '/cacu/task', name: 'cacuTask', component: cacuTask, meta: {title:'任务统计'} }, { path: '/login', name: 'login', component: Login }, { path: '/register', name: 'register', component: Register } ] })
import colors from '@config/colors'; import { FONT_FAMILY } from '@config/typography'; import React from 'react'; import { StyleSheet, Text, View, Image } from 'react-native'; import { Tooltip } from 'react-native-elements'; import { Colors, Spacing, Typography } from '../config'; import { useTranslation } from 'react-i18next'; import TextPriceCommon from './TextPriceCommon'; export default function ItemCart({ title, content, assets, tips, titleStyle, valueStyle, heightTooltip, widthTooltip, unit, subTextStyle, }) { const { t } = useTranslation(); return ( <View style={[styles.box]}> <View style={styles.row}> <Text style={[styles.titleItem, titleStyle]}>{title}</Text> {tips && ( <Tooltip popover={<Text style={styles.tipText}>{tips}</Text>} backgroundColor={colors.grayBorder01} height={heightTooltip} width={widthTooltip} overlayColor={null}> <Image source={assets} style={styles.tooltip} /> </Tooltip> )} </View> {typeof content === 'number' ? ( <TextPriceCommon style={[styles.contentItem, valueStyle]} value={content} /> ) : ( <Text style={[styles.contentItem, valueStyle]}>{content}</Text> )} {unit && <Text style={[styles.subText, subTextStyle]}>{unit}</Text>} </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: colors.grayBackground, }, box: { flexDirection: 'row', justifyContent: 'space-between', borderBottomColor: Colors.silver, borderBottomWidth: 0.5, paddingHorizontal: 16, paddingVertical: 10, backgroundColor: Colors.background, }, row: { flex: 1, flexDirection: 'row', alignItems: 'center', }, ig: { width: 80, height: 60, }, apartmentName: { fontSize: 15, fontFamily: FONT_FAMILY.REGULAR, color: colors.colorPrimary, }, address: { fontSize: 13, fontFamily: FONT_FAMILY.REGULAR, paddingLeft: 7, }, apartment: { fontFamily: FONT_FAMILY.REGULAR, fontSize: 15, color: colors.bodyText, lineHeight: 22, }, titleItem: { marginVertical: 7, fontSize: Typography.FONT_SIZE.BASE, fontFamily: FONT_FAMILY.REGULAR, color: colors.bodyText, paddingRight: Spacing.small, }, contentItem: { fontFamily: FONT_FAMILY.REGULAR, fontSize: Typography.FONT_SIZE.BASE, color: colors.bodyText, fontWeight: '600', }, txtDiscount: { fontFamily: FONT_FAMILY.REGULAR, fontSize: Typography.FONT_SIZE.BASE, color: Colors.red, fontWeight: '600', }, footer: { backgroundColor: colors.TextLink, paddingHorizontal: 16, paddingBottom: 15, }, boxReduction: { marginVertical: 8, paddingVertical: 12, paddingHorizontal: 16, backgroundColor: Colors.background, }, boxInPutReduction: { height: 40, borderColor: Colors.silver, borderWidth: Spacing.very_small, justifyContent: 'space-around', marginBottom: 15, }, iconTxtReduction: { borderRightWidth: 1, borderRightColor: Colors.silver, margin: 5, paddingTop: 5, paddingRight: 7, }, btnApply: { justifyContent: 'center', padding: Spacing.small + 2, }, txtBtnApply: { fontFamily: FONT_FAMILY.BOLD, fontSize: Typography.FONT_SIZE.SMALL - 1, fontWeight: '600', color: colors.gradient, }, boxIntoMoney: { paddingVertical: 12, justifyContent: 'space-between', }, titleIntoMoney: { fontSize: Typography.FONT_SIZE.EXTRA_SMALL + 1, color: Colors.background, }, txtinfoMoney: { fontFamily: FONT_FAMILY.REGULAR, color: colors.gradient, }, tipText: { color: colors.bodyText, fontFamily: FONT_FAMILY.REGULAR, fontSize: 15, textAlign: 'center', }, subText: { width: 6, fontFamily: FONT_FAMILY.REGULAR, fontWeight: '600', fontSize: 10, textAlignVertical: 'top', }, tooltip: { padding: 5, margin: 7, } });
import React from "react"; import { storiesOf } from "@storybook/react"; import "../src/css/tailwind.css"; import { Heading } from "../src/index"; import { withInfo } from "@storybook/addon-info"; const stories = storiesOf("Heading", module).addDecorator(withInfo); stories.add("normal", () => <Heading>This is a sample heading</Heading>); stories.add("custom alignment", () => <Heading align="center">This is a sample heading</Heading>); stories.add("heading type", () => <Heading type="2">This is a sample heading</Heading>); stories.add("weight", () => <Heading weight="light">This is a sample heading</Heading>); stories.add("color", () => <Heading color="red">This is a sample heading</Heading>); stories.add("font family", () => <Heading family="heading">This is a sample heading</Heading>); stories.add("size", () => <Heading size="5xl">This is a sample heading</Heading>); stories.add("Click Event Handle", () => ( <Heading click={() => { alert("Yay! I have been clicked"); }} > This is a sample heading </Heading> )); stories.add("Custom Tailwind classes", () => <Heading classes="tracking-wide">This is a sample heading</Heading>); stories.add("All Props", () => ( <Heading type="2" color="red" family="heading" size="5xl" classes="tracking-wide" click={() => { alert("Yay! I have been clicked"); }} style={{ marginLeft: "140px" }} responsive={{ smallDevice: { type: 2, weight: "light", color: "primary", family: "text", size: "3xl", classes: "tracking-wide", style: { marginLeft: "40px" }, }, }} > This is a sample heading </Heading> ));
jQuery(document).ready(function($){ var headerHeight = $('#header-nav').outerHeight(true); var footerHeight = $('#footer').outerHeight(true); var $resultsSidebar = $('.results-sidebar'); /* $resultsSidebar.on('affix.bs.affix', function(){ $(this).css({'top': 25, 'margin-top': 0}); }); $resultsSidebar.on('affix-top.bs.affix', function(){ $(this).css({'margin-top':80}); }); $resultsSidebar.affix({ offset:{ //top:headerHeight, top: function(){ return headerHeight + 55; }, bottom:function(){ return footerHeight + 40; } } });*/ });
window.onload = function () { document.querySelector('h1').onmouseover = h1OnMouseOver; document.querySelector('h1').onmouseover = h1OnMouseOver; document.querySelector('h2').onmouseover = h1OnMouseOver; document.querySelector('h2').onmouseover = h2OnMouseOver; // document.querySelector('ul li').onmousover = liMouseOver; console.log(document.querySelectorAll('ul li')); for (let i of document.querySelectorAll('ul li')) { i.onmouseover = liMouseOver; i.onmouseout = liMouseOut; } }
const croppie = require('croppie'); const $form = $('#image-picker').find('form'); if($form.length > 0) { $form.on('dragover', (e) => { e.preventDefault(); $form.addClass('dragging'); }); $form.on('dragleave', () => { $form.removeClass('dragging'); }); $form.on('drop', (e) => { e.preventDefault(); $form.removeClass('dragging'); $('input#photo')[0].files = e.originalEvent.dataTransfer.files; }); const croppieSize = $(window).width() < 570 ? $(window).width() - 70 : 500; const resize = $('#crop').croppie({ enableExif: true, enableOrientation: true, viewport: { width: croppieSize, height: croppieSize, type: 'circle' }, boundary: { width: croppieSize, height: croppieSize } }); if(window.photo_url !== undefined) { $('.crop-container').removeClass('d-none'); resize.croppie('bind',{ url: photo_url }) } $('input#photo').on('change', (e) => { if(e.target.files.length > 0) { const reader = new FileReader(); reader.readAsDataURL(e.target.files[0]); reader.onload = (e) => { $('.crop-container').removeClass('d-none'); resize.croppie('bind',{ url: e.target.result }) }; } }); $('#upload').on('click', () => { resize.croppie('result', { type: 'blob', size: { width: 500, height: 500 } }).then(function (img) { const fd = new FormData; fd.append('photo', img); axios({ method: 'post', headers: { 'Content-Type': 'multipart/form-data' }, url: '/users/uploadPhoto', data: fd }).then(() => { location.reload(); }) }); }) }
/* exported headers */ const startButton = document.querySelector('#start'); const downloadButton = document.querySelector('#download'); const testsDiv = document.querySelector('#tests'); const testsSummaryDiv = document.querySelector('#tests-summary'); const testsDetailsDiv = document.querySelector('#tests-details'); const saveToLS = document.querySelector('#save-to-ls'); const compareWithLS = document.querySelector('#compare-with-ls'); const compareWithFile = document.querySelector('#compare-with-file'); const diffDiv = document.querySelector('#diff'); const diffDetailsDiv = document.querySelector('#diff-details'); const diffSummaryDiv = document.querySelector('#diff-summary'); const includeAllPropsCheckbox = document.querySelector('#include-all-props'); const includeEventsCheckbox = document.querySelector('#include-events'); const headers = fetch('/reflect-headers').then(r => r.json()); // object that contains results of all tests const results = { page: 'fingerprinting', date: null, results: [] }; /** * Test runner */ function runTests () { startButton.setAttribute('disabled', 'disabled'); downloadButton.removeAttribute('disabled'); testsDiv.removeAttribute('hidden'); results.results.length = 0; results.date = (new Date()).toUTCString(); let all = 0; let failed = 0; testsDetailsDiv.innerHTML = ''; function updateSummary () { testsSummaryDiv.innerText = `Collected ${all} datapoints${failed > 0 ? ` (${failed} failed)` : ''}. Click for details.`; } tests.forEach(test => { if (test.category === 'all-props' && !includeAllPropsCheckbox.checked) { return; } if (test.category === 'events' && !includeEventsCheckbox.checked) { return; } all++; const resultObj = { id: test.id, category: test.category }; results.results.push(resultObj); let categoryUl = document.querySelector(`.category-${test.category} ul`); if (!categoryUl) { const category = document.createElement('div'); category.classList.add(`category-${test.category}`); category.innerText = test.category; categoryUl = document.createElement('ul'); category.appendChild(categoryUl); testsDetailsDiv.appendChild(category); } const li = document.createElement('li'); li.id = `test-${test.category}-${test.id}`; li.innerHTML = `${test.id} - <span class='value'></span>`; const valueSpan = li.querySelector('.value'); categoryUl.appendChild(li); try { const value = test.getValue(); if (value instanceof Promise) { value.then(v => { valueSpan.innerHTML = `(${Array.isArray(v) ? 'array' : (typeof v)}) - <code>${JSON.stringify(v, null, 2)}</code>`; resultObj.value = v; }).catch(e => { valueSpan.innerHTML = `❌ error thrown ("${e}")`; failed++; updateSummary(); }); } else { valueSpan.innerHTML = `(${Array.isArray(value) ? 'array' : (typeof value)}) - <code>${JSON.stringify(value, null, 2)}</code>`; resultObj.value = value; } } catch (e) { valueSpan.innerHTML = `❌ error thrown ("${e}")`; failed++; } }); updateSummary(); startButton.removeAttribute('disabled'); saveToLS.removeAttribute('disabled'); compareWithFile.removeAttribute('disabled'); // when there is data in localStorage enable comparing with localStorage if (localStorage.getItem('results')) { compareWithLS.removeAttribute('disabled'); } } function downloadTheResults () { const data = JSON.stringify(results, null, 2); const a = document.createElement('a'); const url = window.URL.createObjectURL(new Blob([data], { type: 'application/json' })); a.href = url; a.download = 'fingerprinting-results.json'; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); a.remove(); } function compareResults (resultsA, resultsB) { const resultsAObj = {}; const resultsBObj = {}; resultsA.results.forEach(result => { resultsAObj[result.id] = result; }); resultsB.results.forEach(result => { resultsBObj[result.id] = result; }); const diff = DeepDiff(resultsAObj, resultsBObj).filter(item => { // filter out differences where on object A property doesn't exist, but on object B it exists with value 'undefined' if (item.kind === 'N' && item.rhs === undefined) { return false; } return true; }); console.log(diff); const list = document.createDocumentFragment(); if (diff === undefined) { diffSummaryDiv.innerText = 'Results are identical.'; } else { diffSummaryDiv.innerText = `There are ${diff.length} difference${diff.length === 1 ? '' : 's'} between those results. Click for details.`; diff.forEach(change => { const li = document.createElement('li'); const testId = change.path[0]; let path = ''; change.path.forEach((segment, idx) => { if (idx < 2) { return; } path += '→ ' + segment; }); // const testA = resultsAObj[testId] const testB = resultsBObj[testId]; if (change.kind === 'E') { // modified property li.innerHTML = `<strong>${testId}</strong> ${path} - value <span class='changed'>changed</span> from <code>${JSON.stringify(change.lhs, null, 2)}</code> to <code>${JSON.stringify(change.rhs, null, 2)}</code>`; } else if (change.kind === 'A') { // array change if (change.item.kind === 'N') { li.innerHTML = `<strong>${testId}</strong> ${path} - new item <code>${JSON.stringify(change.item.rhs, null, 2)}</code> <span class='added'>added</span>`; } else if (change.item.kind === 'D') { li.innerHTML = `<strong>${testId}</strong> ${path} - item <code>${JSON.stringify(change.item.lhs, null, 2)}</code> <span class='removed'>removed</span>`; } } else if (change.kind === 'D') { // deleted property if (change.item) { li.innerHTML = `<strong>${testId}</strong> ${path} - item <code>${JSON.stringify(change.item.rhs, null, 2)}</code> <span class='removed'>removed</span>`; } else { li.innerHTML = `<strong>${testId}</strong> ${path} - property <span class='removed'>missing</span>`; } } else if (change.kind === 'N') { // added property if (change.item) { li.innerHTML = `<strong>${testId}</strong> ${path} - new item <span class='added'>added</span> <code>${JSON.stringify(change.item.lhs, null, 2)}</code> (<code>${JSON.stringify(testB.value, null, 2)}</code>)`; } else { li.innerHTML = `<strong>${testId}</strong> ${path} - <span class='added'>new</span> property (<code>${JSON.stringify(change.rhs, null, 2)}</code>)`; } } list.appendChild(li); }); } diffDetailsDiv.innerHTML = ''; diffDetailsDiv.appendChild(list); diffDiv.removeAttribute('hidden'); } saveToLS.addEventListener('click', () => { localStorage.setItem('results', JSON.stringify(results, null, 2)); }); compareWithLS.addEventListener('click', () => { const oldResults = JSON.parse(localStorage.getItem('results')); compareResults(oldResults, results); }); compareWithFile.addEventListener('change', event => { const reader = new FileReader(); reader.onload = () => { const oldResults = JSON.parse(reader.result); compareResults(oldResults, results); }; reader.readAsText(compareWithFile.files[0]); }); downloadButton.addEventListener('click', () => downloadTheResults()); // run tests if button was clicked or… startButton.addEventListener('click', () => runTests()); // if url query is '?run' start tests imadiatelly if (document.location.search === '?run') { runTests(); }
(function () { 'use strict'; angular .module('app') .controller('RestaurantController', RestaurantController); function RestaurantController($scope, $location, $routeParams, RestaurantDataService) { $scope.restaurants = getRestaurants(); if ($routeParams && $routeParams.id) getRestaurantById(); $scope.restaurantService = { getRestaurants: getRestaurants, getRestaurantById: getRestaurantById, getRestaurantByName: getRestaurantByName, addRestaurant: addRestaurant, updateRestaurant: updateRestaurant, deleteRestaurant: deleteRestaurant, filterRestaurantsByName: filterRestaurantsByName } $scope.goAddRestaurant = function () { $location.path('/AddRestaurant/'); }; $scope.goRestaurantList = function () { $location.path('/RestaurantList/'); } function addRestaurant() { RestaurantDataService .addRestaurant($scope.restaurant) .then(function (restaurants) { $location.path('/RestaurantList'); alert('Novo restaurante registrado com sucesso.'); $scope.restaurants = restaurants; $scope.restaurant = {}; }); } function deleteRestaurant(id) { RestaurantDataService .deleteRestaurant(id) .then(function (restaurants) { $location.path('/RestaurantList'); alert('Restaurant com Id: ' + id + ' deletado com sucesso'); $scope.restaurants = restaurants; }); } function updateRestaurant() { var req = { Id: $scope.restaurant.Id, Name: $scope.restaurant.Name }; RestaurantDataService .updateRestaurant(req) .then(function (restaurants) { $location.path('/RestaurantList'); alert('Alteração realizada com sucesso.'); $scope.restaurants = restaurants; }); } function getRestaurants() { RestaurantDataService .getRestaurants() .then(function (restaurants) { $scope.restaurants = restaurants; }); } function getRestaurantById(id) { RestaurantDataService .getRestaurantById(id || $routeParams.id) .then(function (restaurant) { $scope.restaurant = restaurant; }); } function getRestaurantByName(name) { RestaurantDataService .getRestaurantByName(name || $routeParams.name) .then(function (restaurant) { $scope.restaurant = restaurant; }); } function filterRestaurantsByName(name) { if (name && name.length) RestaurantDataService .getRestaurantsByName(name || $routeParams.name) .then(function (restaurants) { $scope.restaurants = restaurants; }); else getRestaurants(); } } })();
import React from 'react'; import Divider from 'material-ui/Divider'; /** * A simple divider with equal spacing to the top and bottom. */ const PrettyDivider = () => ( <Divider style={{ marginTop: '0.5em', marginBottom: '0.5em' }} /> ); export default PrettyDivider;
import React from 'react'; import FormControlSelect from './FormControlSelect'; export default { component: FormControlSelect, title: 'Form Control: Select', excludeStories: /.*Data$/, }; export const Default = () => <FormControlSelect />;
const express = require('express'); const morgan = require('morgan'); const tourRouter = require('./routes/tourRoutes'); const userRouter = require('./routes/userRoutes'); const app = express(); // MIDDLEWARES console.log(process.env.NODE_ENV); app.use(express.json()); //middleware or body-parser if (process.env.NODE_ENV === 'development') { app.use(morgan('dev')); } app.use(express.static(`${__dirname}/public`)); app.use((req, res, next) => { console.log('Hello from the middleware'); next(); }); app.use((req, res, next) => { req.requestTime = new Date().toISOString(); next(); }); // app.get('/', (req, res) => { // res // .status(200) // .json({ message: 'Hello from the server side...', app: 'notours' }); // }); // app.post('/', (req, res) => { // res.send('You can post to this endpoint...'); // }); // const tours = JSON.parse( // fs.readFileSync(`${__dirname}/dev-data/data/tours-simple.json`) // ); //ROUTE HANDLERS // const getAllTours = (req, res) => { // console.log(req.requestTime); // res.status(200).json({ // status: 'success', // requestedAt: req.requestTime, // results: tours.length, // data: { // tours, // // tours: tours, // }, // }); // }; // const getTour = (req, res) => { // console.log(req.params); // const id = req.params.id * 1; // const tour = tours.find((el) => el.id === id); // if (id > tours.length) { // return res.status(404).json({ // status: 'fail', // message: 'Invalid ID', // }); // } // res.status(200).json({ // status: 'success', // data: { // tours: tour, // // tours: tours, // }, // }); // }; // const createTour = (req, res) => { // // console.log(req.body); // const newId = tours[tours.length - 1].id + 1; // const newTour = Object.assign({ id: newId }, req.body); // tours.push(newTour); // fs.writeFile( // `${__dirname}/dev-data/data/tours-simple.json`, // JSON.stringify(tours), // (err) => { // res.status(201).json({ // status: 'success', // data: { // tour: newTour, // }, // }); // } // ); // }; // const updateTour = (req, res) => { // if (req.params.id * 1 > tours.length) { // return res.status(404).json({ // status: 'fail', // message: 'Invalid ID', // }); // } // res.status(200).json({ // status: 'success', // data: { // tour: '<Updated tour here...>', // }, // }); // }; // const deleteTour = (req, res) => { // if (req.params.id * 1 > tours.length) { // return res.status(404).json({ // status: 'fail', // message: 'Invalid ID', // }); // } // res.status(204).json({ // status: 'success', // data: null, // }); // }; // const getAllUsers = (req, res) => { // res.status(500).json({ // status: 'error', // message: 'This ruote is not yet defined!', // }); // }; // const getUser = (req, res) => { // res.status(500).json({ // status: 'error', // message: 'This ruote is not yet defined!', // }); // }; // const createUser = (req, res) => { // res.status(500).json({ // status: 'error', // message: 'This ruote is not yet defined!', // }); // }; // const updateUser = (req, res) => { // res.status(500).json({ // status: 'error', // message: 'This ruote is not yet defined!', // }); // }; // const deleteUser = (req, res) => { // res.status(500).json({ // status: 'error', // message: 'This ruote is not yet defined!', // }); // }; // app.get('/api/v1/tours', getAllTours); // app.post('/api/v1/tours', createTour); // app.get('/api/v1/tours/:id', getTour); // app.patch('/api/v1/tours/:id', updateTour); // app.delete('/api/v1/tours/:id', deleteTour); //ROUTES // const tourRouter = express.Router(); // const userRouter = express.Router(); // // tourRouter.route('/').get(getAllTours).post(createTour); // // tourRouter.route('/:id').get(getTour).patch(updateTour).delete(deleteTour); // // app.route('/api/v1/users').get(getAllUsers).post(createUser); // // app // // .route('/api/v1/users/:id') // // .get(getUser) // // .patch(updateUser) // // .delete(deleteUser); // userRouter.route('/').get(getAllUsers).post(createUser); // userRouter.route('/:id').get(getUser).patch(updateUser).delete(deleteUser); app.use('/api/v1/tours', tourRouter); app.use('/api/v1/users', userRouter); //START SERVER // const port = 3000; // app.listen(port, () => { // console.log(`App running on the port ${port}... `); // }); module.exports = app;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _express = require("express"); var _AuthenticateUserService = _interopRequireDefault(require("../services/AuthenticateUserService")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const sessionsRouter = (0, _express.Router)(); sessionsRouter.post('/', async (request, response) => { const { email, password } = request.body; const authencateUser = new _AuthenticateUserService.default(); const { user, token } = await authencateUser.execute({ email, password }); const userWithoutPassword = { id: user.id, name: user.name, email: user.email, created_at: user.created_at, updated_at: user.updated_at }; return response.json({ user: userWithoutPassword, token }); }); var _default = sessionsRouter; exports.default = _default;
'use strict'; //function togglePlayPause() { // Grab a handle to the audio // var audio = document.getElementById('audioelement'); // var playpause = document.getElementById('playpause'); // document.createElement("audio"); // // audio.addEventListener("canplaythrough", function() { // audio.play(); // } // ); // ///*var ss = document.createElement('audio'); //audio.appendChild(ss); //*/ // // // // if (audio.paused || audio.ended) { // playpause.className = 'volume-off'; // /* var sound = new Audio(); // var sound = new Audio("/audio/cxlykter.mp3"); // sound.play(); // */ // audio.play(); // } else { // playpause.className = 'volume'; // audio.pause(); // } //} function stopScrolling() { skrollr.get().stopAnimateTo(); } /*function detectIE() { var ua = window.navigator.userAgent; var msie = ua.indexOf('MSIE '); var trident = ua.indexOf('Trident/'); if (msie > 0) { // IE 10 or older => return version number return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10); } if (trident > 0) { // IE 11 (or newer) => return version number var rv = ua.indexOf('rv:'); return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10); } // other browser return false; }*/ (function(window, skrollr){ var s = skrollr.init({ easing: { x : function(p) { var s = p; // console.log('sin: ' + s); return s; }, y : function(p){ var stopSin = 0.70; var c; if(stopSin <= p) { c = 1; // c= 0.99; // console.log('cos****: ' + c); } else { c = Math.sin(2*p); } // console.log('cos: ' + c); return c; } }, smoothScrolling: true, mobileDeceleration:0.7 }); window.onload = function(){ function resize() { var viewportWidth = $(window).width(); $('#slides').css({width: $('#slide4').height() * 3.55 + 'px'}); $('#slide4verscontainer').css({width: $('#slide4').height() * 3.55 + 'px'}); $('p.vers').css({'font-size': ($(window).height() / 40) + 'px', 'padding': ($(window).height() / 300) + 'em'}); var slide4Width = $('#slide4').width(); var vers2 = $('#vers2'), vers2StartScroll = 355, vers2SluttScroll = 395, vers2StartLeft = 4, vers2SluttLeft = 35, vers2StartTop = 0, vers2SluttTop = 0; var refreng2 = $('#refreng2'), refreng2StartScroll = 395, refreng2SluttScroll = 410, refreng2StartLeft = 35, refreng2SluttLeft = 55; var vers3 = $('#vers3'), vers3StartScroll = 410, vers3SluttScroll = 420, vers3StartLeft = 60, vers3SluttLeft = 70; /*Posisjoner akebilde*/ var akeBilde = $('#akeBilde'), akeStartScroll = 300, //xl akeSluttScroll = 320, //l akeStartLeft = 6, //m akeStartTop = 20, akeSluttLeft = 45, akeSluttTop = 70; if(viewportWidth < 300) { akeStartLeft = 3; akeSluttScroll = 395; vers2StartScroll = 350; vers2SluttScroll = 380; //390 vers2StartLeft = 1; vers2SluttLeft = 30; //37 refreng2StartScroll = 380; refreng2SluttScroll = 410; refreng2StartLeft = 23;//28; refreng2SluttLeft = 35; vers3StartScroll = 410; vers3SluttScroll = 430; vers3StartLeft = 20;//53; vers3SluttLeft = 21; } else if(viewportWidth > 300 && viewportWidth < 500) { akeStartLeft = 6; //m akeSluttScroll = 370; //l vers2StartScroll = 350; vers2SluttScroll = 380; //390 vers2StartLeft = 1; vers2SluttLeft = 30; //37 refreng2StartScroll = 380; refreng2SluttScroll = 410; refreng2StartLeft = 23;//28; refreng2SluttLeft = 35; vers3StartScroll = 410; vers3SluttScroll = 430; vers3StartLeft = 20;//53; vers3SluttLeft = 21; } else { akeStartLeft = 10; //xl akeSluttScroll = 400; //xl vers2StartScroll = 350; vers2SluttScroll = 380; //390 vers2StartLeft = 1; vers2SluttLeft = 30; //37 refreng2StartScroll = 380; refreng2SluttScroll = 410; refreng2StartLeft = 23;//28; refreng2SluttLeft = 35; vers3StartScroll = 410; vers3SluttScroll = 430; vers3StartLeft = 20;//53; vers3SluttLeft = 21; } akeBilde.css({width: slide4Width/25}); akeBilde.attr('data-'+ akeStartScroll +'p', 'left[x]:'+akeStartLeft+'%;top[y]:'+akeStartTop+'%'); akeBilde.attr('data-'+ akeSluttScroll +'p', 'left[x]:'+akeSluttLeft+'%;top[y]:'+ akeSluttTop+'%'); // akeBilde.attr('data-'+ (akeSluttScroll +50) +'p', 'left[x]:'+(akeSluttLeft+5)+'%;top[y]:'+ (akeSluttTop)+'%'); console.log("log left: "+akeBilde.css("left")); var imageWidth = $('#slides').width(); var percentage = 100 - ((viewportWidth / imageWidth) * 100); $('#slides').attr('data-450p', 'transform:translate(-' + percentage + '%,-66.66%);'); var transform = 'translate(' + (imageWidth - viewportWidth) + 'px, 200%)'; $('#slide5').css({'transform': transform, '-moz-transform': transform, '-webkit-transform': transform}); skrollr.get().refresh(); } resize(); $(window).resize(function () { console.log('resize'); resize(); }); function getReceipientFromUrl() { var l = location ? location : (window.location ? window.location : document.location); var query = l.hash ? l.hash.substr(1):(l.search?l.search.substr(1):''); var indexLng = query.indexOf('='); if(indexLng !== -1) { var receipient = query.substring((indexLng + 4)); return decodeURIComponent(receipient); } else { return decodeURIComponent(query); } } function setReceipient(receipient) { var lang = i18n.lng(); var norsk = (lang==='no'||lang==='nb-NO'||lang==='nn-NO'||lang==='nb'||lang==='nn')?true:false; $('.to').text(receipient || getReceipientFromUrl() ||(norsk?'Deg':'You')); } setReceipient(); function setLanguage() { var l = location ? location : (window.location ? window.location : document.location); var query = l.hash ? l.hash.substr(1):(l.search?l.search.substr(1):''); //hvis det er language på var indexLng = query.indexOf('='); var lng = query.substring((indexLng + 1), (indexLng + 3)); if(indexLng !== -1) { i18n.setLng(lng, function(t) {}); } else { i18n.setLng('no', function(t) {}); } } setLanguage(); function generateSnow(backgroundId, canvasId) { var canvas = document.getElementById(canvasId); var snowBackground = document.getElementById(backgroundId); var ctx = canvas.getContext('2d'); var width = 510; //window.innerWidth; var height = 550; //window.innerHeight; canvas.width = width; canvas.height = height; var maxPixels = 5; var particles = []; for(var i = 0 ; i < maxPixels; i++) // particles.forEach(function() { particles.push({ x: Math.random()*width, y: Math.random()*height, r: Math.random()*3, d: Math.random()*maxPixels }); } function draw() { ctx.clearRect(0,0,width,height); ctx.fillStyle = 'rgba(255, 255, 255, 0.8)'; ctx.beginPath(); for(var i = 0; i < maxPixels; i++){ var p = particles[i]; ctx.moveTo(p.x,p.y); ctx.arc(p.x,p.y, p.r, 0, Math.PI*2, true); ctx.fill(); update(); } } //Function to move the snowflakes //angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes var angle = 0; function update() { angle += 0.01; for(var i = 0; i < maxPixels; i++) { var p = particles[i]; //Updating X and Y coordinates //We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards //Every particle has its own density which can be used to make the downward movement different for each flake //Lets make it more random by adding in the radius p.y += Math.cos(angle+p.d) + 1 + p.r/2; p.x += Math.sin(angle) * 2; //Sending flakes back from the top when it exits //Lets make it a bit more organic and let flakes enter from the left and right also. if(p.x > width+5 || p.x < -5 || p.y > height) { if(i%3 > 0) //66.67% of the flakes { particles[i] = {x: Math.random()*width, y: -10, r: p.r, d: p.d}; } else { //If the flake is exitting from the right if(Math.sin(angle) > 0) { //Enter from the left particles[i] = {x: -5, y: Math.random()*height, r: p.r, d: p.d}; } else { //Enter from the right particles[i] = {x: width+5, y: Math.random()*height, r: p.r, d: p.d}; } } } } } //animation loop setInterval(draw, 50); } generateSnow('snowBackground1', 'snowWindow1'); generateSnow('snowBackground2', 'snowWindow2'); }; function autoplay() { if(s.getScrollTop() === 0 ) { s.animateTo(document.body.offsetHeight, { duration: 80000}, {interruptible: true}); } } setTimeout(autoplay, 1000); }(window, skrollr)); i18n.init({ detectLngQS: 'lang', useCookie : false }, function(t) { $(".slide").i18n(); }); //setup audio behaviour (function() { var audio = document.getElementById('audioelement'); var playpause = document.getElementById('playpause'); var playing = false; playpause.addEventListener('click', function(){ if(audio){ if(audio.paused == true) { console.log('Button clicked'); console.log(audio.play()); $('#audioelement').attr('autoplay'); playpause.className = 'volume'; playing = true; } else { playing = false; playpause.className = 'volume-off'; audio.pause(); } } }); var hidden = 'hidden'; // Standards: if (hidden in document){ document.addEventListener("visibilitychange", onchange); } else if ((hidden = "mozHidden") in document) { document.addEventListener("mozvisibilitychange", onchange); } else if ((hidden = "webkitHidden") in document){ document.addEventListener("webkitvisibilitychange", onchange); } else if ((hidden = "msHidden") in document) { document.addEventListener("msvisibilitychange", onchange); } // IE 9 and lower: else if ("onfocusin" in document){ document.onfocusin = document.onfocusout = onchange; } // All others: else { window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange; } function onchange (evt) { if(this !== undefined) { if(this[hidden]){ playpause.className = 'volume-off'; audio.pause(); } else if(playing) { playpause.className = 'volume'; audio.play(); } } } // set the initial state (but only if browser supports the Page Visibility API) if( document[hidden] !== undefined ) onchange({type: document[hidden] ? "blur" : "focus"}); })();
// ============================================================================= // This file contains gulp tasks for automating the building process. // By the moment, there are only tasks for the front-end // ============================================================================= var gulp = require('gulp'); var inject = require('gulp-inject'); // Inject all css and js client files into index.html gulp.task('frontend:build', [], function(){ var sources = gulp.src([ './public/**/*.js', './common/**/*.js', './public/**/*.css' ], {read: false}); gulp.src('./public/index.html') .pipe(inject(sources, { relative: true, removeTags: false })) .pipe(gulp.dest('./public/')); }); gulp.task('default', ['frontend:build'], function(){});
import React from 'react'; import { Formik, Form, Field } from "formik"; import { fields } from "./fields"; import { initialValues } from './initialValues'; import ButtonForm from '../../shared/components/ButtonForm'; import { useDispatch} from 'react-redux'; import { authOperations } from '../../redux/auth'; import styles from './LoginView.module.css' const LoginView = () => { const dispatch = useDispatch(); return ( <Formik onSubmit={(values) => {dispatch(authOperations.logIn(values))}} initialValues={initialValues} > <Form className={styles.form} autoComplete="off" > <label className={styles.label}> <Field className={styles.field} {...fields.email} /> </label> <label className={styles.label}> <Field className={styles.field} {...fields.password} /> </label> <ButtonForm>Log in</ButtonForm> </Form> </Formik> ); } export default LoginView;
/** * Created by cnaisin06 on 2017/6/21. */ // var baseUrl = "http://192.168.31.248:7070/AXGY_OP/"; //本地联调地址 //var baseUrl = "https://rest.cnaisin.com:8443/AXGY_OP/"; var baseUrl = "https://rest.cnaisin.com:15443/AXGY_OP/"; //product var workDetailUrl = baseUrl + "workDetail"; //作品详情 var modifyTutorInfoUrl = baseUrl + "modifyTutorInfo"; //修改辅导老师 $.fn.serializeObject = function() { var list=[]; var name=[]; var phone=[]; var a = this.serializeArray(); $.each(a, function(index,obj) { if (obj.name == 'teacher') { name.push(obj.value) } if (obj.name == 'teachertel') { phone.push(obj.value) } }); for(var i=0;i<name.length;i++){ var o={}; if(name[i]!=""|| phone[i]!=""){ o.name=name[i]; o.phone=phone[i]; list.push(o); } } var key= a.length+1 var v={"name":"teacherTel","value":JSON.stringify(list)} a[key]=v; return a; }; function GetQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配 var context = ""; if (r != null) context = r[2]; reg = null; r = null; return context == null || context == "" || context == "undefined" ? "" : context; } var actphone=GetQueryString("actRegisterPhone"); console.log(GetQueryString("actRegisterPhone")); var workNumber=GetQueryString("workNumber"); $("#actphone").attr("value",actphone) $("#workNumber").attr("value",workNumber); var name=GetQueryString("name"); console.log(name); /*让文字和标签的大小随着屏幕的尺寸做变话 等比缩放*/ var html = document.getElementsByTagName('html')[0]; var width = window.innerWidth; var fontSize = 100/640*width; if(width>640){ fontSize=100; } html.style.fontSize = fontSize +'px'; window.onresize = function(){ var html = document.getElementsByTagName('html')[0]; var width = window.innerWidth; var fontSize = 100/640 * width; html.style.fontSize = fontSize +'px'; } $(function () { $("#add").on("click", function () { $(".addd").first().append($(".addtitle1:first").first().clone(true).attr('class',"addtitle1 clone").attr("style","display:block")); $(".remove").on("click", function () { $(this).parent(".clone").remove(); }) }); }) $("#sbm").on("click", function () { $("myform").serializeObject(); console.log($("#myform").serializeObject()); $.ajax({ url:modifyTutorInfoUrl, type:"post", data:$("#myform").serializeObject(), success: function (data) { console.log(data) if(data.ok==true){ layer.open({ skin:"demo-class", title:"提示", content:"修改成功", end: function () { window.location.href=document.referrer // window.location.href='../workshow/show.html'+"?actRegisterPhone="+actphone // window.history.back().reload() } }) } else if(data.ok==false){ layer.open({ skin:"demo-class", title:"提示", content:"修改失败" }) } } }) }) $.ajax({ url:workDetailUrl, datatype:"json", type:"post", data:{"actRegisterPhone":actphone,"workNumber":workNumber}, success: function (result) { console.log(result.data.teacherTel); var html = template("teachermsg",result.data) $(".addtitle").html(html) } })
import React, { Component } from "react"; export class CreateUser extends Component { render() { return ( <div> <p>You are on the Create User Component</p> </div> ); } } export default CreateUser;
import Ember from 'ember'; export default Ember.Route.extend({ actions: { ipgpsLookup(params) { this.transitionTo('getip-gps-results', params.url); } } });
const express = require('express') // const bodyParser = require('body-parser'); // Check below comment // whenever I try to remove bodyParser my post will stop working const dataRoute = require('./route/data') const userRoute = require('./route/user') const app = express() app.use(express.json())//Comment this and do as the Multiline comment below. /* app.use(express.json()) // This will worj the same way body-parser works */ app.use(dataRoute) app.use('/user',userRoute) app.listen(3000)
import { getMidiNumberAttributes, MAX_MIDI_NUMBER } from './midiHelpers'; function buildKeyboardShortcuts(startNote, keyboardConfig) { let currentMidiNumber = startNote; let naturalKeyIndex = 0; let keyboardShortcuts = []; while (naturalKeyIndex < keyboardConfig.length && currentMidiNumber <= MAX_MIDI_NUMBER) { const key = keyboardConfig[naturalKeyIndex]; const { isAccidental } = getMidiNumberAttributes(currentMidiNumber); if (isAccidental) { keyboardShortcuts.push({ key: key.flat, midiNumber: currentMidiNumber, }); } else { keyboardShortcuts.push({ key: key.natural, midiNumber: currentMidiNumber, }); naturalKeyIndex += 1; } currentMidiNumber += 1; } return keyboardShortcuts; } export default buildKeyboardShortcuts;
import 'phaser'; /*global Phaser*/ export default class mirror extends Phaser.Scene { constructor(mirrorID) { super({key: 'mirror'}); console.log('Running mirror'); console.log(mirrorID) this.localSys = {}; } preload() { } create() { } update() { } }
var https = require("https"); var http = require("http"); var url = require("url"); var connectToDb = require('../../db'); var promisifiedHttpsGet = require("../utils/promisifiedHttpsGet.js").promisifiedHttpsGet; var promisifiedHttpGet = require("../utils/promisifiedHttpsGet.js").promisifiedHttpGet; var Song = require("mongoose").model("Song"); var People = require("mongoose").model("Person"); var bearerToken = "BQDxWyRJJbtBNJQWyI8cIx1pR2po4ATpo5vJ_xcAAujw8UZPGHkoz_BI8k5by-l0FUux5g7E4tROWhd7Sps70mKWqG7UYNboJM1vcaRigtYe-EaZJaBIiOz3jCE2DeS6kIqqEHmrE0QyhtJhE-RsBuTQQR1GIhvpOzEB59khfSAESfmGSSyZe4umKeDctcPDPmbfZxc8aEBs0VbINIlndbzf1qIiotp4AGZ86vazVxtNDTNNWmzayRmKOyA-6BE28tK8cFTUK6D6VCIxOS7QOlIaNoCm1t7wD6bI"; var usernames = [] People.find() .then(function(people){ people.forEach(function(person){ usernames.push(person.spotifyHandle) }) // the next line should be usernames.forEach() usernames.forEach(function(username){ getPlaylists(username) }) }).then(null, console.error); function getPlaylists(username) { var userOptions = { hostname: "api.spotify.com", port: 443, path: "/v1/users/" + username + "/playlists", headers: { "Authorization": "Bearer " + bearerToken } } return promisifiedHttpsGet(userOptions) .then(function(body){ console.log(3) var playlists = JSON.parse(body).items; // console.log(playlists) console.log("Getting playlists..."); var promisedPlaylists = []; playlists.forEach(function(playlist) { promisedPlaylists.push(getTracks(playlist.tracks.href, username)); }) return Promise.all(promisedPlaylists); }) } var tracksProcessed = 0; function getTracks(playlistLink, username) { var linkToPlaylist = playlistLink; var linkToPlaylistObj = url.parse(linkToPlaylist); // console.log(linkToPlaylistObj) var playlistOptions = { hostname: linkToPlaylistObj.hostname, port: 443, path: linkToPlaylistObj.path, headers: { "Authorization": "Bearer " + bearerToken } }; promisifiedHttpsGet(playlistOptions) .then(function(body){ var trackList = JSON.parse(body).items; console.log("Getting tracks for each playlist") var promisedTracks = []; trackList.forEach(function(track) { tracksProcessed++; if (tracksProcessed > 120) { console.log("too many songs") return; } var trackName = track.track.name; var trackUrl = track.track.uri; var trackArtist = track.track.artists[0].name; // console.log(track) var song = { username: username, songTitle: trackName, songArtist: trackArtist, songUrl: trackUrl } promisedTracks.push(getValence(trackName, trackArtist, song)); console.log('pushed track to promisedTracks') }) Promise.all(promisedTracks) .then(function resolve(tracks) { console.log(tracks); console.log('\n\n\ntracks logged\n\n\n') // tracks = tracks.filter(function(song) { return !song.username }); return Song.create(tracks) }) .then(function(songs){ console.log('Created ' + songs.length + 'songs.'); }).then(null, function(err) { console.error('You done messed up, but we\'ll take care of it'); return 1 }) }) } var index = 0; function getValence(trackName, trackArtist, song) { trackName = trackName.replace(/[.,-\/#!$%\^&\*;:{}=\-_`~()]/g, "").split(" ").join("%20").toLowerCase(); if(trackName === "should’ve%20been%20us") return trackArtist = trackArtist.replace(/[.,-\/#!$%\^&\*;:{}=\-_`~()]/g, "").split(" ").join("%20").toLowerCase(); var echonestUrl = "http://developer.echonest.com/api/v4/song/search?api_key=CCFQ1SJBPJYEFFOCP&artist=" + trackArtist + "&title=" + trackName + "&bucket=audio_summary" return promisifiedHttpGet(echonestUrl) .then(function(body){ if(JSON.parse(body).response.songs[0] === undefined){ return } var songInfo = JSON.parse(body).response.songs[0]; // console.log(songInfo) song.songValence = Number(songInfo.audio_summary.valence); // console.log(song); return song; }) } // module.exports =
import React, { useState, useEffect} from 'react'; import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom' import 'bootstrap/dist/css/bootstrap.min.css'; import logo from './logo.svg'; import './App.css'; import Navi from './components/navi/Navi'; import Landing from './components/landing/Landing'; import Progress from './components/progress/Progress'; import WhatsNext from './components/whatsnext/WhatsNext'; import Help from './components/help/Help'; import Done from './components/done/Done'; function App() { //0 is homepage //1 is progress (What have you accomplished?) //2 is whatsnext (What are you working on next?) //3 is help (Do you need any help?) //4 is done (Done! Send an email) const [step, setStep] = useState(0); const [one, setOne] = useState("Hello"); const [two, setTwo] = useState(""); const [three, setThree] = useState(-1); //0 is no, 1 is yes const updateStep = (stepNumber) => { setStep(stepNumber); } const updateOne = (one) => { setOne(one); } const updateTwo = (two) => { setTwo(two); } const updateThree = (three) => { setThree(three) } useEffect(() => { updateOne(window.localStorage.getItem("one")); updateTwo(window.localStorage.getItem("two")); updateThree(window.localStorage.getItem("three")); }) return ( <div className="App"> <Navi step={step} updateStep={updateStep} /> <Router> <Switch> <Route path="/done"> <Done updateStep={updateStep} one={one} two={two} three={three} updateOne={updateOne} updateTwo={updateTwo} updateThree={updateThree}/> </Route> <Route path="/progress"> <Progress updateStep={updateStep} one={one} updateOne={updateOne} /> </Route> <Route path="/whatsnext"> <WhatsNext updateStep={updateStep} two={two} updateTwo={updateTwo} /> </Route> <Route path="/help"> <Help updateStep={updateStep} three={three} updateThree={updateThree} /> </Route> <Route path="/"> <Landing updateStep={updateStep}/> </Route> </Switch> </Router> </div> ); } export default App;
import React, { useEffect, useState } from 'react'; import {StyleSheet, FlatList, Text, View} from 'react-native'; import { getUser,getFollowers } from '../github/users'; const data = [ 'hello', 'from', 'the', 'other', 'side' ] export const List = () => { const [resp,setResp] = useState("") useEffect(async () => { let res = await getUser("ndan11") setResp(res) },[]) return( <> {/* <FlatList data={data} renderItem={({item,index}) => <Text key={index}>{item}</Text>} ListHeaderComponent = {<Text>Header</Text>} ListFooterComponent = {<Text>Footer</Text>} ItemSeparatorComponent={(index) => ( <View key={index} style={{ height : 50, backgroundColor : 'red' }} /> ) } /> */} <Text> {resp} </Text> </> ) } const styles = StyleSheet.create({ })
var Election = artifacts.require("./Election.sol"); contract ("Election", function(accounts) { var electionInstance; //testing presence of 2 candidates it ("initializes with two candidates", function(){ return Election.deployed().then(function(instance) { return instance.candidatesCount(); }).then(function(count){ assert.equal(count,2); }); }); //testing name of candidate is correct //testing vote Count //testing ID it("initializes the candidates with the correct values", function() { return Election.deployed().then(function(instance) { electionInstance = instance; return electionInstance.candidates(1); }).then(function(candidate) { assert.equal(candidate[0],1,"contains correct id"); assert.equal(candidate[1],"Candidate 1","contains correct name"); assert.equal(candidate[2],0,"correct vote count"); return electionInstance.candidates(2); }).then(function(candidate) { assert.equal(candidate[0],2,"contains correct id"); assert.equal(candidate[1],"Candidate 2","contains correct name"); assert.equal(candidate[2],0,"correct vote count"); }); }); //check if vote count is increased and voter address is entered // to voter mapping to prevent double voting it("allows a voter to cast a vote", function() { return Election.deployed().then(function(instance) { electionInstance = instance; candidateId = 1; return electionInstance.vote(candidateId, { from: accounts[0] }); }).then(function(receipt) { assert.equal(receipt.logs.length, 1, "an event was triggered"); assert.equal(receipt.logs[0].event, "votedEvent", "the event type is correct"); assert.equal(receipt.logs[0].args._candidateId.toNumber(), candidateId, "the candidate id is correct"); return electionInstance.voters(accounts[0]); }).then(function(voted) { assert(voted, "the voter was marked as voted"); return electionInstance.candidates(candidateId); }).then(function(candidate) { var voteCount = candidate[2]; assert.equal(voteCount, 1, "increments the candidate's vote count"); }) }); //to throw exception for invalid candidates it("throws an exception for invalid candiates", function() { return Election.deployed().then(function(instance) { electionInstance = instance; return electionInstance.vote(99, { from: accounts[1] }) }).then(assert.fail).catch(function(error) { assert(error.message.indexOf('revert') >= 0, "error message must contain revert"); return electionInstance.candidates(1); }).then(function(candidate1) { var voteCount = candidate1[2]; assert.equal(voteCount, 1, "candidate 1 did not receive any votes"); return electionInstance.candidates(2); }).then(function(candidate2) { var voteCount = candidate2[2]; assert.equal(voteCount, 0, "candidate 2 did not receive any votes"); }); }); //to throw exception for double voting it("throws an exception for double voting", function() { return Election.deployed().then(function(instance) { electionInstance = instance; candidateId = 2; electionInstance.vote(candidateId, { from: accounts[1] }); return electionInstance.candidates(candidateId); }).then(function(candidate) { var voteCount = candidate[2]; assert.equal(voteCount, 1, "accepts first vote"); // Try to vote again return electionInstance.vote(candidateId, { from: accounts[1] }); }).then(assert.fail).catch(function(error) { assert(error.message.indexOf('revert') >= 0, "error message must contain revert"); return electionInstance.candidates(1); }).then(function(candidate1) { var voteCount = candidate1[2]; assert.equal(voteCount, 1, "candidate 1 did not receive any votes"); return electionInstance.candidates(2); }).then(function(candidate2) { var voteCount = candidate2[2]; assert.equal(voteCount, 1, "candidate 2 did not receive any votes"); }); }); });
import React from "react"; import Pdf from "react-to-pdf"; import Card from "@material-ui/core/Card"; import CardContent from "@material-ui/core/CardContent"; import Button from "@material-ui/core/Button"; import Grid from "@material-ui/core/Grid"; import invoice from "../../assets/images/invoice.svg"; import IspirithaleBlueLogo from "../../assets/2.png"; import { Payhere, AccountCategory } from "payhere-js-sdk"; import { Customer, CurrencyType, PayhereCheckout, CheckoutParams, } from "payhere-js-sdk"; Payhere.init("1218569", AccountCategory.SANDBOX); function onPayhereCheckoutError(errorMsg) {} function checkout() { const customer = new Customer({ first_name: "Ispirithalei", last_name: "WACYAMDA", phone: "+94771234567", email: "plumberhl@gmail.com", address: "No. 50, Highlevel Road", city: "Panadura", country: "Sri Lanka", }); const checkoutData = new CheckoutParams({ returnUrl: "http://localhost:3000/return", cancelUrl: "http://localhost:3000/cancel", notifyUrl: "http://localhost:8080/notify", order_id: "112233", itemTitle: "ispirithalei", currency: CurrencyType.LKR, amount: 2500, }); const checkout = new PayhereCheckout( customer, checkoutData, onPayhereCheckoutError ); var win = window.open("/payments", "title"); checkout.start(); win(); } const ref = React.createRef(); const tempPrice = "RS.2750.00"; const currentDate = new Date().toDateString(); const CreditPdf = (props) => { return ( <> <Grid container xs={12}> <div> <Grid item md={6} style={{ marginTop: "50px", marginLeft: "310px" }}> <div className="Post" ref={ref}> <Card style={{ border: "solid", marginLeft: "70px", height: "700px" }} > <CardContent> <img src={IspirithaleBlueLogo} alt="70" /> <h3> Invoice <hr></hr> </h3> <Grid container style={{ marginTop: "30px" }}> <Grid item xs={12} style={{ textAlignLast: "justify", marginTop: "50px", marginBottom: "20px", }} > <h4>Email: {props.email}</h4> </Grid> <Grid container> <Grid item xs={6}> <h4>Customer name:</h4> </Grid> <Grid item xs={6} style={{ textAlign: "right" }}> <h4> {props.name}</h4> </Grid> </Grid> <Grid container> <Grid item xs={6} style={{ marginTop: "20px" }}> <h4>Date of payment:</h4> </Grid> <Grid item xs={6} style={{ textAlign: "right", marginTop: "20px" }} > <h4> {currentDate}</h4> </Grid> </Grid> <Grid container> <Grid item xs={6} style={{ marginTop: "20px" }}> <h4>Chanelling Fee:</h4> </Grid> <Grid item xs={6} style={{ textAlign: "right", marginTop: "20px" }} > <h4>Rs.2000.00</h4> </Grid> </Grid> <Grid container> <Grid item xs={6} style={{ marginTop: "20px" }}> <h4>Hospital Fee:</h4> </Grid> <Grid item xs={6} style={{ textAlign: "right", marginTop: "20px" }} > <h4>Rs.500.00</h4> </Grid> </Grid> <Grid container> <Grid item xs={6} style={{ marginTop: "20px" }}> <h4>VAT:</h4> </Grid> <Grid item xs={6} style={{ textAlign: "right", marginTop: "20px" }} > <h4>Rs.250.00</h4> </Grid> </Grid> <Grid container> <Grid item xs={6} style={{ marginTop: "20px" }}> <h4>Total Bill:</h4> </Grid> <Grid item xs={6} style={{ textAlign: "right", marginTop: "20px" }} > <h4>{tempPrice}</h4> </Grid> </Grid> </Grid> <Card style={{ marginTop: "80px", border: "solid", textAlign: "right", }} > <CardContent> <h1>{tempPrice}</h1> </CardContent> </Card> </CardContent> </Card> </div> </Grid> </div> </Grid> <Pdf targetRef={ref} filename={props.name}> {({ toPdf }) => ( <div> <Grid direction="column" md={12} style={{ textAlign: "center", padding: "0px" }} > <form noValidate> <img src={invoice} alt="invoiceimage" /> <Card> <CardContent> <Button variant="contained" color="primary" onClick={toPdf}> Download as PDF </Button> <Button variant="contained" color="primary"> Download as JPG </Button> </CardContent> </Card> <Button variant="contained" color="primary" onClick={checkout} style={{ marginTop: "50px", height: "50px", width: "500px", }} > Pay with PayHere </Button> </form> </Grid> </div> )} </Pdf> </> ); }; export default CreditPdf;
const nodeModulePath = require('path') const webpack = require('webpack') const ManifestPlugin = require('webpack-manifest-plugin') const BabelMinifyPlugin = require('babel-minify-webpack-plugin') const ExtractTextPlugin = require('extract-text-webpack-plugin') const { PATH_RESOURCE_PACK, PATH_RESOURCE_PACK_DLL_MANIFEST, DLL_NAME_MAP } = require('./config') const { HashedModuleIdsPlugin, DefinePlugin, BannerPlugin, DllReferencePlugin, optimize: { CommonsChunkPlugin, ModuleConcatenationPlugin } } = webpack const NODE_ENV = process.env.NODE_ENV const IS_PRODUCTION = NODE_ENV === 'production' const OPTIONS = { BABEL_LOADER: { babelrc: false, presets: [ [ 'env', { targets: IS_PRODUCTION ? '>= 5%' : { node: 9 }, modules: false } ], 'react' ], plugins: [ 'transform-class-properties', [ 'transform-object-rest-spread', { useBuiltIns: true } ] ] } } const addEntryPolyfill = (entry) => Object.entries(entry).reduce((o, [ key, value ]) => { o[ key ] = [ 'babel-polyfill', value ] return o }, {}) module.exports = { entry: addEntryPolyfill({ 'main': 'pack-source/index' }), output: { path: PATH_RESOURCE_PACK, filename: IS_PRODUCTION ? '[name]-[chunkhash:8].js' : '[name].js' }, resolve: { alias: { 'pack-source': nodeModulePath.resolve(__dirname, 'pack-source'), 'config.pack': nodeModulePath.resolve(__dirname, 'config.pack') } }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', options: OPTIONS.BABEL_LOADER } ] } ] }, plugins: [ new ExtractTextPlugin(IS_PRODUCTION ? '[name]-[contenthash:8].css' : '[name].css'), new DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV), '__DEV__': !IS_PRODUCTION }), new HashedModuleIdsPlugin(), new CommonsChunkPlugin({ name: 'runtime' }), new DllReferencePlugin({ context: '.', manifest: require(nodeModulePath.resolve(PATH_RESOURCE_PACK_DLL_MANIFEST, `${DLL_NAME_MAP.VENDOR}.json`)) }), new DllReferencePlugin({ context: '.', manifest: require(nodeModulePath.resolve(PATH_RESOURCE_PACK_DLL_MANIFEST, `${DLL_NAME_MAP.VENDOR_FIREBASE}.json`)) }), new ManifestPlugin({ fileName: 'manifest/main.json' }), ...(IS_PRODUCTION ? [ new ModuleConcatenationPlugin(), new BabelMinifyPlugin(), new BannerPlugin({ banner: '/* eslint-disable */', raw: true, test: /\.js$/, entryOnly: false }), new BannerPlugin({ banner: '/* stylelint-disable */', raw: true, test: /\.css$/, entryOnly: false }) ] : []) ] }
const bcrypt = require('bcryptjs'); module.exports = { register: async(req, res) => { const {email, firstName, lastName, password} = req.body; const {session} = req; const db = req.app.get('db'); let user = await db.user_get(email); user = user[0]; console.log('user:', user); if(user){ return res.status(400).send('A user with that email already exists. Please log in.') } console.log('email:', email, 'first:', firstName, 'last:', lastName); const salt = bcrypt .genSaltSync(10); const hash = bcrypt.hashSync(password, salt); let newUser = await db.user_register({email, firstName, lastName}); newUser = newUser[0]; const userId = newUser.users_id; await db.user_password({hash, userId}); session.user = newUser; console.log('r session user:', session.user); // await db.cat_post_overflow({userId}) res.status(200).send(session.user); }, login: async(req, res) => { const {email, password} = req.body; const {session} = req; const db = req.app.get('db'); let user = await db.user_get(email); user = user[0]; if(!user){ return res.status(400).send('Email not found'); } const authenticated = bcrypt.compareSync(password, user.passwords_password); if(authenticated){ delete user.passwords_password; delete user.passwords_id; session.user = user; console.log('session user:', session.user) res.status(202).send(session.user) } else { res.status(401).send('Incorrect password') console.log('you suck') } }, checkUser: (req, res) => { if(req.session.user){ console.log('check session:', req.session.user); res.status(200).send(req.session.user); } else { res.status(400).send('User not found'); } }, logout: (req, res) => { req.session.destroy(); res.sendStatus(200); } }
import React from 'react'; import './css/WeeklyAverages.css'; import {Spring} from 'react-spring/renderprops'; //This component contains a function to calculate the average weekly average for a selected property. This component uses that function to calculate various weekly aveages and then displays them. const WeeklyAverages = ({weather}) => { //getAverage is a function that loops through the array that is passed to the function, in this case the weather array (all the weather data for the city), and calculates the average of a specified property. Property1 is parent property and Property2 is the child property of each array element const getAverage = (weather,property1,property2) => { var runningTotal = 0; weather.forEach((curr)=> { runningTotal = runningTotal + curr[property1][property2]; }); return (runningTotal/weather.length); }; //Calculate averages to be displayed var averagePressure = getAverage(weather,'main','pressure'); var averageTemperature = getAverage(weather,'main','temp'); var averageHumidity = getAverage(weather,'main','humidity'); var averageWindSpeed = getAverage(weather,'wind','speed'); return ( <Spring from={{opacity:0}} to={{opacity:1}} config={{delay:400}}> {props=>( <div style={props}> <div className="AverageWeather"> <div className="content"> <div className="header"> Weekly Averages <br/> </div> <div className="averageData"> Pressure: {averagePressure.toFixed(2)} hPa<br/> Temperature: {averageTemperature.toFixed(2)} &deg; C<br/> Humidity: {averageHumidity.toFixed(2)}%<br/> Wind Speed: {averageWindSpeed.toFixed(2)} m/s<br/> </div> </div> </div> </div> )} </Spring> ); }; export default WeeklyAverages;
import React from "react"; import { MainComponent } from "./components/MainComponent/MainComponent"; import "./App.css"; export function App() { return ( <> <MainComponent /> </> ); }
import React from 'react'; import ReactDOM from 'react-dom'; import classnames from 'classnames'; import {Alert, Dialog, Intent, ProgressBar, Spinner} from '@blueprintjs/core'; /* screen main-view-no-subtitles xs …800 best effort sm 800…1024 794 (subtitles always hidden) md 1024…1200 940 if no subtitles, 794 if subtitles lg 1200… 1140 if no subtitles, 940 if subtitles */ class PlayerApp extends React.PureComponent { render () { const {containerWidth, viewportTooSmall, PlayerControls, StepperView, SubtitlesBand, isReady, progress, error} = this.props; return ( <div id='player-app'> <Dialog isOpen={!isReady} title={"Preparing playback"} isCloseButtonShown={false} > <div style={{margin: '20px 20px 0 20px'}}> <ProgressBar value={progress} intent={Intent.SUCCESS} /> </div> </Dialog> {isReady && <div id='main' style={{width: `${containerWidth}px`}} className={classnames([viewportTooSmall && 'viewportTooSmall'])}> <PlayerControls/> <StepperView/> <SubtitlesBand/> </div>} {error && <Alert intent={Intent.DANGER} icon='error' isOpen={!!error} onConfirm={this.reload}> <p style={{fontSize: '150%', fontWeight: 'bold'}}>{"A fatal error has occured while preparing playback."}</p> <p>{"Source: "}{error.source}</p> <p>{"Error: "}{error.message}</p> <p>{"Details: "}{error.details}</p> <p style={{fontWeight: 'bold'}}>{"Click OK to reload the page."}</p> </Alert>} </div> ); } reload = () => { window.location.reload(); }; } function PlayerAppSelector (state, props) { const {PlayerControls, StepperView, SubtitlesBand} = state.get('scope'); const viewportTooSmall = state.get('viewportTooSmall'); const containerWidth = state.get('containerWidth'); const player = state.get('player'); const isReady = player.get('isReady'); const progress = player.get('progress'); const error = player.get('error'); return { viewportTooSmall, containerWidth, PlayerControls, StepperView, SubtitlesBand, isReady, progress, error }; } export default function (bundle) { bundle.defineView('PlayerApp', PlayerAppSelector, PlayerApp); };
xdescribe("tests of addScope function", function() { var mock; var I18nProvider; var translateProvider; beforeEach(module('rd.services.I18nService')); beforeEach(function() { mock = {alert: jasmine.createSpy()}; module(function($provide) { $provide.value('$translateProvider', mock); }); inject(function($injector) { I18nProvider = $injector.get('I18n'); }); inject(function($injector) { //translateProvider = $injector.get('$translateProvider'); }); }); var prefix,defaultLanguage; it('Access the init function', function(){ spyOn(I18nProvider, 'init').and.callThrough(); //I18nProvider.init(prefix,defaultLanguage); //expect(I18nProvider.init).toBeDefined(); //var instance = new translateProvider(); //var provider = instance.init(prefix,defaultLanguage); //console.log("22222"+provider); console.log("11111"+I18nProvider); //expect(translateProvider.init(prefix,defaultLanguage)).toBeDefined(); }); });
import Vue from 'vue' import VueRouter from 'vue-router' import ProductView from '../views/ProductView.vue' import ProductTypeView from '../views/ProductTypeView' import ProductDetailView from '../views/ProductDetailView' import OperationView from '../views/OperationView' import OperationTypeView from '../views/OperationTypeView' Vue.use(VueRouter) const routes = [ { path: '/', name: 'product', component: ProductView }, { path: '/producttype', name: 'producttype', component: ProductTypeView }, { path: '/operation', name: 'operation', component: OperationView }, { path: '/operationtype', name: 'operationtype', component: OperationTypeView }, { path: '/product/:id', name: 'productDetailView', component: ProductDetailView } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
import React from 'react' import styles from './titleBar.module.scss'; export default function TitleBar({ first, middle, last }) { return ( <div className={styles['title-bar']}> <div className={styles['first']}>{first}</div> <div className={styles['middle']}>{middle}</div> <div className={styles['last']}>{last}</div> </div> ) }
const Animation = require("../models/Animation.model"), Ankle = require("../models/Ankle.model"), Badge = require("../models/Badge.model"), Bank = require("../models/Bank.model"), Ign = require("../models/Ign.model"), Infraction = require("../models/Infraction.model"), Missionary = require("../models/Missionary.model"), Remind = require("../models/Remind.model"), Server = require("../models/Server.model"), Spoiler = require("../models/Spoiler.model"), Star = require("../models/Star.model"), Tag = require("../models/Tag.model"), User = require("../models/User.model"), WebhookId = require("../models/WebhookId.model"), config = require("../config/config.json"), moment = require("moment"), mongoose = require("mongoose"); const {Collection} = require("discord.js"), serverSettings = new Collection(); mongoose.connect(config.db.db, config.db.settings); const models = { animation: { save: async function(data) { let newAnimation = new Animation(data); return await newAnimation.save(); }, fetch: async function(animationId) { return await Animation.findOne({animationId}).exec(); }, fetchAll: async function(time = 14) { let since = new Date(Date.now() - (time * 24 * 60 * 60 * 1000)); return await Animation.find({date: { $gte: since }}).exec(); } }, ankle: { save: async function(data) { let newLostAnkle = new Ankle(data); return newLostAnkle.save(); }, getAnkles: async function(time = 365) { let since = new Date(Date.now() - (time * 24 * 60 * 60 * 1000)); return await Ankle.find({timestamp: { $gte: since }}).exec(); }, getChannelSummary: async function(channelId, time = 10000) { channelId = channelId.id ? channelId.id : channelId; let since = new Date(Date.now() - (time * 24 * 60 * 60 * 1000)); let records = await Ankle.find({channel: channelId, timestamp: { $gte: since }}).exec(); return { channelId: channelId, perUser: records.reduce((acc, r) => { // Group lost ankles by user. // perUser attribute is an object with User IDs as keys and counts (within the channel) as values if (acc.has(r.discordId)) acc.set(r.discordId, acc.get(r.discordId) + 1); else acc.set(r.discordId, 1); return acc; }, new Collection()), total: records.length }; }, getUserSummary: async function(discordId, time = 10000) { if (discordId.id) discordId = discordId.id; let since = new Date(Date.now() - (time * 24 * 60 * 60 * 1000)); let records = await Ankle.find({discordId, timestamp: { $gte: since }}).exec(); return { discordId, perChannel: records.reduce((acc, r) => { // Group lost ankles by channel. // perChannel attribute is an object with Channel IDs as keys and counts as values if (acc.has(r.channel)) acc.set(r.channel, acc.get(r.channel) + 1); else acc.set(r.channel, 1); return acc; }, new Collection()), total: records.length }; }, getSummary: async function(time = 10000) { let since = new Date(Date.now() - (time * 24 * 60 * 60 * 1000)); let records = await Ankle.find({timestamp: { $gte: since }}).exec(); return { perChannel: records.reduce((acc, r) => { // Group lost ankles by channel. // perChannel attribute is an object with Channel IDs as keys and counts as values if (acc.has(r.channel)) acc.set(r.channel, acc.get(r.channel) + 1); else acc.set(r.channel, 1); return acc; }, new Collection()), perUser: records.reduce((acc, r) => { // Group lost ankles by user. // perUser attribute is an object with User IDs as keys and counts (within the channel) as values if (acc.has(r.discordId)) acc.set(r.discordId, acc.get(r.discordId) + 1); else acc.set(r.discordId, 1); return acc; }, new Collection()), total: records.length }; } }, badge: { create: async function(data) { let badge = new Badge(data); return await badge.save(); }, fetch: async function(id) { if (id) { return await Badge.findOne({_id: id}).exec(); } else { return await Badge.find({}).exec(); } }, findByName: async function(title) { return await Badge.findOne({title}).exec(); } }, bank: { getBalance: async function(discordId, currency = "gb") { if (discordId.id) discordId = discordId.id; let record = await Bank.aggregate([ { $match: { discordId, currency }}, { $group: { _id: null, balance: {$sum: "$value"}}} ]).exec(); if (record && (record.length > 0)) return {discordId, currency, balance: record[0].balance}; else return {discordId, currency, balance: 0}; }, getAwardsFrom: async function(givenFrom = [], since = 0, currency = "em") { let awards = await Bank.find({ currency, timestamp: { $gte: since }, mod: { $in: givenFrom } }).exec(); return awards; }, getRegister: async function(discordId, currency = "gb") { if (discordId.id) discordId = discordId.id; let register = await Bank.find({discordId, currency}).exec(); return { discordId, currency, balance: register.reduce((c, r) => c + r.value, 0), register: register }; }, addCurrency: async function(data, currency = "gb") { if (data.discordId.id) data.discordId = data.discordId.id; let record = new Bank({ discordId: data.discordId, description: data.description, currency: data.currency || currency, value: data.value, mod: data.mod }); return await record.save(); } }, ign: { delete: async function(discordId, system) { if (discordId.id) discordId = discordId.id; return await Ign.findOneAndRemove({ discordId, system }).exec(); }, find: async function(discordId, system) { if (discordId.id) discordId = discordId.id; if (Array.isArray(system)) return await Ign.find({discordId, system: {$in: system} }).exec(); else if (Array.isArray(discordId)) return await Ign.find({discordId: {$in: discordId}, system }).exec(); else if (system) return await Ign.findOne({discordId, system}).exec(); else return await Ign.find({discordId}).exec(); }, findName: async function(ign, system) { return await Ign.findOne({ign: new RegExp(`^${ign}$`, "i"), system}).exec(); }, getList: async function(system) { return await Ign.find({system}).exec(); }, save: async function(discordId, system, name) { if (discordId.id) discordId = discordId.id; return await Ign.findOneAndUpdate( { discordId, system }, { $set: { ign: name } }, { upsert: true, new: true } ).exec(); } }, infraction: { getSummary: async function(discordId, time = 28) { let since = new Date(Date.now() - (time * 24 * 60 * 60 * 1000)); let records = await Infraction.find({discordId, timestamp: { $gte: since }}).exec(); return { discordId, count: records.length, points: records.reduce((c, r) => c + r.value, 0), time, detail: records }; }, getByFlag: async function(flag) { if (flag.id) flag = flag.id; return await Infraction.findOne({flag}).exec(); }, save: async function(data) { let record = new Infraction({ discordId: data.discordId, channel: data.channel, message: data.message, flag: data.flag, value: data.value, description: data.description, mod: data.mod }); return await record.save(); }, retract: async function(flag, mod) { if (mod.id) mod = mod.id; if (flag.id) flag = flag.id; return await Infraction.findOneAndDelete({flag, mod}).exec(); }, update: async function(id, data) { return await Infraction.findByIdAndUpdate(id, data, {new: true}).exec(); } }, mission: { save: async function(data) { return await Missionary.findOneAndUpdate( { discordId: data.discordId }, { $set: data }, { upsert: true, new: true } ).exec(); }, findEmail: async function(email) { return await Missionary.findOne({ email }).exec(); }, delete: async function(discordId) { return await Missionary.findOneAndRemove({ discordId }); }, findAll: async function() { return await Missionary.find({}).exec(); } }, reminder: { complete: async function(reminder) { return await Remind.findOneAndRemove({_id: reminder._id}).exec(); }, fetchReminders: async function() { return await Remind.find({timestamp: {$lte: new Date()}}).exec(); }, setReminder: async function(data) { let reminder = new Remind(data); return await reminder.save(); } }, server: { addServer: async function(guild) { let newServer = new Server({ serverId: guild.id }); let server = await newServer.save(); serverSettings.set(server.serverId, server); return server; }, getSetting: function(guild, setting) { if (!serverSettings.has(guild.id)) models.server.addServer(guild); return serverSettings.get(guild.id)?.[setting]; }, saveSetting: async function(guild, setting, value) { let updateOptions = {}; updateOptions[setting] = value; let server = await Server.findOneAndUpdate( {serverId: guild.id}, {$set: updateOptions}, {upsert: true, new: true} ).exec(); serverSettings.set(server.serverId, server); return server; } }, spoiler: { save: async function(data) { let newSpoiler = new Spoiler(data); return await newSpoiler.save(); }, fetchAll: async function(time = 14) { let since = new Date(Date.now() - (time * 24 * 60 * 60 * 1000)); return await Spoiler.find({timestamp: { $gte: since }}).exec(); }, fetch: async function(spoilerId) { return await Spoiler.findOne({spoilerId: spoilerId}).exec(); } }, starboard: { denyStar: async function(starId) { return await Star.findOneAndUpdate({starId}, {$set: {deny: true}}).exec(); }, fetchStar: async function(starId) { return await Star.findOne({starId}).exec(); }, fetchMessage: async function(messageId) { return await Star.findOne({messageId}).exec(); }, saveStar: async function(message, starpost) { let newStar = new Star({ author: message.author.id, messageId: message.id, channelId: message.channel.id, boardId: starpost.channel.id, starId: starpost.id, deny: false, timestamp: message.createdAt }); return await newStar.save(); }, approveStar: async function(star1, star2) { return await Star.findOneAndUpdate( {starId: star1.id}, {$set: {starId: star2.id}} ).exec(); } }, tags: { addTag: async function(data) { let cmd = await Tag.findOneAndUpdate( {serverId: data.serverId, tag: data.tag}, {$set: {response: data.response, attachment: data.attachment}}, {upsert: true, new: true} ).exec(); if (cmd.attachment) { let fs = require("fs"); let axios = require("axios"); let response = await axios({ method: "get", url: data.url, responseType: "stream" }); response.data.pipe(fs.createWriteStream(process.cwd() + "/storage/" + cmd._id)); } return cmd; }, fetchTags: async function(data = {}) { return await Tag.find(data).exec(); }, removeTag: async function(guild, tag) { return await Tag.findOneAndRemove({serverId: guild.id, tag: tag}).exec(); } }, user: { addXp: async function(users) { users = Array.from(users.values()); let response = { users: [], xp: 0 }; if (users.length == 0) return response; else { let xp = Math.floor(Math.random() * 11) + 15; response.xp = xp; let allUsersMod = await User.updateMany( { discordId: {$in: users} }, { $inc: { posts: 1 } }, { new: true, upsert: true } ).exec(); let rankUsersMod = await User.updateMany( { discordId: {$in: users}, excludeXP: false }, { $inc: { currentXP: xp, totalXP: xp } }, { new: true, upsert: false } ).exec(); let userDocs = await User.find({ discordId: {$in: users} }).exec(); response.users = userDocs; return response; } }, applyBadge: async function(discordId, badge) { if (discordId.id) discordId = discordId.id; if (badge._id) badge = badge._id; return await User.findOneAndUpdate( {discordId}, {$addToSet: {badges: badge}}, {new: true, upsert: false} ).exec(); }, fetchCurrentRankings: async function(limit = 50, page = 1) { return await User.find({excludeXP: false}) .sort({currentXP: -1, totalXP: -1}) .skip(limit * (page - 1)) .limit(limit) .exec(); }, fetchLifetimeRankings: async function(limit = 50, page = 1) { return await User.find({excludeXP: false}) .sort({totalXP: -1, currentXP: -1}) .skip(limit * (page - 1)) .limit(limit) .exec(); }, fetchStarRankings: async function(limit = 50, page = 1) { let docs = await User.find({stars: {$gt: 0}, posts: {$gt: 0}}) .sort({totalXP: -1, currentXP: -1}) .exec(); docs = docs?.map(u => { u.quality = Math.floor(1000 * u.stars / u.posts); return u; }) .sort((a, b) => ((b.stars / b.posts) - (a.stars / a.posts))); return docs; }, fetchUser: async function(discordId) { if (discordId.id) discordId = discordId.id; return await User.findOne({discordId}).exec(); }, findLifetimeRank: async function(discordId) { if (discordId.id) discordId = discordId.id; let userDoc = await User.findOne({discordId}).exec(); let userRank = await User.countDocuments({"$or": [{totalXP: {"$gt": userDoc.totalXP}}, {totalXP: userDoc.totalXP, currentXP: {"$gt": userDoc.currentXP}}]}).exec(); userDoc.rank = userRank + 1; return userDoc; }, findXPRank: async function(discordId) { if (discordId.id) discordId = discordId.id; let userDoc = await User.findOne({discordId}).exec(); let currentRank = await User.countDocuments({"$or": [{currentXP: {"$gt": userDoc.currentXP}}, {currentXP: userDoc.currentXP, totalXP: {"$gt": userDoc.totalXP}}]}).exec(); userDoc.currentRank = currentRank + 1; let lifeRank = await User.countDocuments({"$or": [{totalXP: {"$gt": userDoc.totalXP}}, {totalXP: userDoc.totalXP, currentXP: {"$gt": userDoc.currentXP}}]}).exec(); userDoc.lifeRank = lifeRank + 1; return userDoc; }, getUsers: async function(options) { return await User.find(options).exec(); }, newUser: async function(discordId) { if (discordId.id) discordId = discordId.id; let exists = await User.findOne({discordId}).exec(); if (exists) return exists; else { let newMember = new User({ discordId, currentXP: 0, totalXP: 0, posts: 0, stars: 0, preferences: 0, ghostBucks: 0, house: null, excludeXP: true, twitchFollow: false, roles: [] }); return newMember.save(); } }, removeBadge: async function(discordId, badge) { if (discordId.id) discordId = discordId.id; if (badge._id) badge = badge._id; return await User.findOneAndUpdate( {discordId}, {$pull: {badges: badge}}, {new: true, upsert: false} ).exec(); }, resetXP: async function() { return await User.updateMany( {}, { currentXP: 0 }, { new: true, upsert: true } ).exec(); }, update: async function(discordId, options) { if (discordId.id) discordId = discordId.id; return await User.findOneAndUpdate( {discordId}, {$set: options}, {new: true, upsert: false} ).exec(); }, updateRoles: async function(member) { return await User.findOneAndUpdate( {discordId: member.id}, {$set: {roles: Array.from(member.roles.cache.keys())}}, {new: true, upsert: false} ).exec(); }, updateTenure: async function(member) { return await User.findOneAndUpdate( {discordId: member.id}, {$inc: { priorTenure: moment().diff(moment(member.joinedAt), "days") }}, {new: true, upsert: false} ).exec(); } }, webhookId: { getOptions: async function(channelId, username) { channelId = channelId.channel?.id || channelId?.id || channelId; let hookId = await WebhookId.findOne({channelId, tag: username.toLowerCase()}).exec(); if (hookId) { return { username: hookId?.username, avatarURL: hookId?.avatarURL, disableMentions: "everyone" }; } else return null; }, save: async function(channelId, username, avatarURL) { channelId = channelId.channel?.id || channelId?.id || channelId; let webhookId = new WebhookId({channelId, username, tag: username.toLowerCase(), avatarURL}); return await WebhookId.findOneAndUpdate( { channelId, tag: username.toLowerCase() }, { $set: { username, avatarURL } }, { upsert: true, new: true } ).exec(); } } }; module.exports = models;
$(document).ready(function(){ var i=1; $(".icon").click(function(){ if(i%2!=0){ $('#total').show(); $("#header").animate({height:'253px'}); $("#iconUp").hide(); $("#iconDown").show(); $('.icon').animate({top:'180px'}); } if(i%2==0){ $('#total').fadeOut('slow'); $("#header").animate({height:'650px'}); $("#iconUp").show(); $("#iconDown").hide(); $('.icon').animate({top:'580px'}); } i++; }); $('#inner').mouseover(function(){ $('#inner').animate({marginLeft:'-1800px'},5000); }); $('#inner').mouseout(function(){ $('#inner').stop(); }); });
import React from 'react'; import CalendarItem from './CalendarItem'; import { useDays } from '../hooks'; import './Calendar.scss'; export default React.memo(function Calendar() { const [, days] = useDays(); return ( <div className="Calendar"> <div className="grid"> {days.map(props => ( <div key={props.day} className="cell"> <CalendarItem {...props} /> </div> ))} </div> </div> ); });
import React, { useState } from "react"; import styled from "styled-components"; import Infos from "../../../components/molecules/Infos"; const ParachuteContainer = styled.div` position: absolute; top: 7vh; left: 50vw; img { filter: grayscale(1); transition: filter 0.3s ease-in-out, transform 2.5s ease-in-out; transform: translateX(0) translateY(0); } .moveParachute { filter: grayscale(0); transform: translateX(-3vw) translateY(25vw); } `; const Parachute = () => { const [ hovered, setHovered ] = useState(0) const isHovered = function(bool) { setHovered(bool) } console.log(hovered) return ( <ParachuteContainer> <Infos setIsAnimated={isHovered} title="Armée de l'air" content="Lorem ipsum dolor" top="25" left="25" rightCard="250" topCard="500" /> <img className={hovered ? "moveParachute" : null} src="../assets/img/chap_2/part_1/parachute.png" alt="parachuteur"/> </ParachuteContainer> ); }; export default Parachute;
import React, { Component } from 'react'; import moment from 'moment'; import {Icon} from 'antd'; import _ from 'lodash'; const renderdate = (arr,val)=>{ const found = _.find(arr,x=>x.value==val); return found?found.text:''; } const renderText = (arr,val)=>{ const found = _.find(arr,x=>x.value==val); return found?found.text:''; } /*const instanceStatus = [{ value: '', text: '全部' },{ value: '0', text: '未启动' },{ value: '1', text: '挂起' },{ value: '2', text: '正常执行中' },{ value: '3', text: '作废' },{ value: '4', text: '终止' },{ value: '5', text: '已完成' },{ value: '7', text: '调度异常' },{ value: '8', text: '归零,流程回退到开始节点' },{ value: '9', text: '流程回退中' }]; const instanceSign = [{ value: '0', text: '撤单流程' },{ value: '1', text: '正常流程' }];*/ const instanceIsSyn = [{ value: '0', text: '否' },{ value: '1', text: '是' }]; const columns = [{ title:'异常标识', dataIndex:'id', width:120, metaHeader:true }, {title:'接口编码',dataIndex:'commandCode',width:150,metaContent:true}, {title:'工作项',dataIndex:'workItemId',width:100,metaContent:true}, {title:'路由',dataIndex:'route',width:80,metaContent:true}, {title:'状态',dataIndex:'state',width:80,metaContent:true}, {title: '流程实例标识', dataIndex: 'processInstanceId', sorter: true, width:140, metaFooter:true}, /* {title: '状态',dataIndex: 'state', //filters: instanceStatus, render(val) { return renderText(instanceStatus,val); }, width:70, content:true }, */ {title: '创建日期', dataIndex: 'createDate', sorter: true, render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>, width:150, footer:true}, /*{title:'处理日期',dataIndex:'dealDate',render: val=><span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,width:150}, {title:'处理次数',dataIndex:'dealTimes',width:80}, {title:'tacheId',dataIndex:'tacheId',width:80},*/ {title: '监控信息', dataIndex: 'commandMsg', sorter: true, width:300}, {title: '详情', dataIndex: 'commandResultMsg', sorter: true, width:300} ]; const formConfig={ layout:'inline-block', fields:[ { rowId: 1, col: 8, orderNum:1, label: '开始时间', showLabel: true, key:'startDate', type: 'date', props: { placeholder: '开始时间', defaultValue: ()=>moment(new Date()).subtract(1, 'days') }, needExpend: false, formItemLayout: { labelCol: { xs: { span: 24 }, sm: { span: 6 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 18 }, } } }, { rowId: 1, col: 8, orderNum:2, label: '结束时间', showLabel: true, key:'endDate', type: 'date', props: { placeholder: '结束时间', defaultValue: ()=>moment(new Date()) }, needExpend: false, formItemLayout: { labelCol: { xs: { span: 24 }, sm: { span: 6 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 18 }, } } }, /*{ rowId: 1, col: 8, orderNum:1, label: '接口编码', showLabel: true, key:'commandCode', type: 'select', props: { placeholder: '全部', defaultValue:'' }, needExpend: false, options:[{ value: '', text: '全部' },{ value: 'createProcessInstance', text: 'createProcessInstance' },{ value: 'startProcessInstance', text: 'startProcessInstance' },{ value: 'createWorkOrder', text: 'createWorkOrder' },{ value: 'completeWorkItem', text: 'completeWorkItem' },{ value: 'disableWorkItem', text: 'disableWorkItem' },{ value: 'reportProcessState', text: 'reportProcessState' },{ value: 'suspendWorkItem', text: 'suspendWorkItem' },{ value: 'abortProcessInstance', text: 'abortProcessInstance' },{ value: 'rollbackProcessInstance', text: 'rollbackProcessInstance' },{ value: 'createAndStartProcessInstance', text: 'createAndStartProcessInstance' },{ value: 'terminateProcessInstance', text: 'terminateProcessInstance' },{ value: 'suspendProcessInstance', text: 'suspendProcessInstance' },{ value: 'resumeProcessInstance', text: 'resumeProcessInstance' },{ value: 'setRuntimeInfo', text: 'setRuntimeInfo' },{ value: 'addDispatch', text: 'addDispatch' }], formItemLayout: { labelCol: { xs: { span: 24 }, sm: { span: 6 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 18 }, } } }, { rowId: 1, col: 8, orderNum:1, label: '流程状态', showLabel: true, key:'state', type: 'select', props: { placeholder: '全部', defaultValue:'' }, needExpend: false, options:[{ value: '', text: '全部' },{ value: '0', text: '未启动' },{ value: '1', text: '挂起' },{ value: '2', text: '正常执行中' },{ value: '3', text: '作废' },{ value: '4', text: '终止' },{ value: '5', text: '已完成' },{ value: '7', text: '调度异常' },{ value: '8', text: '归零,流程回退到开始节点' },{ value: '9', text: '流程回退中' }], formItemLayout: { labelCol: { xs: { span: 24 }, sm: { span: 6 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 18 }, } } },*/ { rowId: 1, col: 6, orderNum:3, label: '流程实例', showLabel: false, key:'processInstanceId', type: 'input', props: { placeholder: '请输入流程实例ID', defaultValue:'', addonAfter:(<button type="submit"><Icon type="search" /></button>) }, needExpend: false, formItemLayout: { labelCol: { xs: { span: 24 }, sm: { span: 6 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 18 }, } } }, ], submitButtonProps: { } } export {columns,formConfig}
module.exports = { HUB_ID: process.env.HUB_ID, FACEIT_API_KEY: process.env.FACEITAPI_KEY, FACEIT_API_URL: process.env.FACEITAPI_URL, SEASON_START_DATE: process.env.SEASON_STARTDATE, };
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Text, Spinner, Card, Subtitle, Icon, View } from '@shoutem/ui'; import Video from 'react-native-video'; import { updatePlayTime, playNextSong } from './actions'; import { streamUrl } from './soundcloudHelper'; import SoundCloudWave from './SoundCloudWave'; import Controls from './Controls'; import Timer from './Timer'; class Player extends Component { get song() { const { songs, currentlyPlaying } = this.props; let song = null; if (currentlyPlaying.genre && currentlyPlaying.songIndex >= 0) { if (songs[currentlyPlaying.genre.id]) { song = songs[currentlyPlaying.genre.id][currentlyPlaying.songIndex]; } } return song; } get percentPlayed() { const { currentlyPlaying: { currentTime } } = this.props; return currentTime / (this.song.full_duration/1000); } onPlayProgress = ({ currentTime }) => { this.props.dispatch(updatePlayTime(currentTime)) } onPlayEnd = () => { this.props.dispatch(playNextSong()) } render() { const { currentlyPlaying: { paused, currentTime } } = this.props, { dispatch } = this.props; if (!this.song) { return ( <Card style={{height: 85, alignItems: "center"}}> <Spinner /> </Card> ); } return ( <Card style={{height: 85, alignItems: 'center'}}> <Video source={{uri: streamUrl(this.song.uri) }} ref="audio" volume={1.0} muted={false} paused={paused} playInBackground={true} playWhenInactive={true} onProgress={this.onPlayProgress} onEnd={this.onPlayEnd} resizeMode="cover" repeat={false}/> <View style={{position: 'absolute', top: 0, height: 85}}> <SoundCloudWave song={this.song} width={180} height={85} percent={this.percentPlayed}/> </View> <View style={{position: 'absolute', top: 0, height: 85, alignItems: 'center'}}> <Controls /> <Timer currentTime={currentTime} /> </View> </Card> ); } } export default connect( (state) => ({ currentlyPlaying: state.currentlyPlaying, songs: state.songs }) )(Player);
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { Link } from 'react-router-dom'; const useStyles = makeStyles(theme => ({ new: { backgroundColor: theme.palette.primary.dark, margin: '4vw 0', border: '2px solid', borderColor: theme.palette.primary.main, display: 'flex', position: 'relative', boxShadow: '0px 3px 1px -2px rgba(0, 0, 0, 0.2), 0px 2px 2px 0px rgba(0, 0, 0, 0.14), 0px 1px 5px 0px rgba(0, 0, 0, 0.12)', }, image: { '& img': { width: '250px', margin: '1vw', border: '1px solid', borderColor: theme.palette.primary.light, borderRadius: '5px', }, }, title: { color: theme.palette.primary.main, fontSize: '30px', paddingLeft: '1vw', paddingTop: '1.3vw', paddingBottom: '0.5vw', }, categories: { paddingLeft: '3vw', color: 'gray', }, body: { color: theme.palette.primary.light, padding: '0.6vw', paddingLeft: '1vw', fontSize: '18px', lineHeight: '30px', }, source: { position: 'absolute', right: 0, bottom: 0, display: 'flex', alignItems: 'center', padding: '0.7vw', fontSize: '20px', fontWeight: '700', backgroundColor: theme.palette.primary.lightText, color: theme.palette.primary.dark, borderTop: '1px solid', borderLeft: '1px solid', borderColor: theme.palette.primary.light, '& img': { marginRight: '10px', width: '40px', }, }, })); const NewsItem = ({ news }) => { const classes = useStyles(); if (!news) return null; return ( <a href={news.url} style={{ textDecoration: 'none', color: '#8ddffe' }}> <div className={classes.new}> <div className={classes.image}> <img src={news.imageurl} alt='newsImage' /> </div> <div className={classes.source}> <img src={news.source_info.img} alt='newsSource' /> {news.source_info.name} </div> <div> <div className={classes.title}>{news.title}</div> <div className={classes.categories}>{news.categories}</div> <div className={classes.body}>{news.body}</div> </div> </div> </a> ); }; export default NewsItem;
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin const path = require('path') const resolve = (dir) => path.join(__dirname, dir) const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV) module.exports = { chainWebpack: (config) => { // 添加别名 config.resolve.alias .set('@', resolve('src')) .set('assets', resolve('src/assets')) .set('api', resolve('src/api')) .set('views', resolve('src/views')) .set('components', resolve('src/components')) // 打包分析 if (IS_PROD) { config.plugin('webpack-report').use(BundleAnalyzerPlugin, [ { analyzerMode: 'static', }, ]) } }, css: { loaderOptions: { sass: { prependData: '@import "./src/assets/css/global.scss";', }, }, }, devServer: { proxy: { '/api': { target: 'https://test.xxx.com', changOrigin: true, pathRewrite: { '^/api': '/', }, }, }, }, productionSourceMap: false, }
var monkey,monkey_running; var bananaGroup,bananaImg var obstacleGroup,obstacleImg; var back,backImg; var score; var ground; var PLAY = 1; var END = 0; var gameState = PLAY; function preload(){ backImg = loadImage("jungle.jpg"); monkey_running = loadAnimation("Monkey_01.png","Monkey_02.png","Monkey_03.png","Monkey_04.png","Monkey_05.png","Monkey_06.png","Monkey_07.png","Monkey_08.png","Monkey_09.png","Monkey_10.png"); bananaImg = loadImage("banana.png"); obstacleImg = loadImage("stone.png"); } function setup() { createCanvas(400, 400); back = createSprite(200,200,400,400); back.addImage("jungle",backImg); back.velocityX = -4; back.x = back.x/2; monkey = createSprite(50,380,20,30); monkey.addAnimation("monkey",monkey_running); monkey.scale = 0.1; ground = createSprite(200,383,400,10) ground.visible = false; score = 0; bananaGroup = new Group(); obstacleGroup = new Group(); } function draw() { background(220); monkey.collide(ground); if (gameState === PLAY){ if (back.x < 0){ back.x = back.width/2; } if (keyDown("space") && monkey.y >= 314){ monkey.velocityY = -17; } monkey.velocityY = monkey.velocityY + 0.8; spawnBanana(); spawnObstacles(); if (bananaGroup.isTouching(monkey)){ bananaGroup.destroyEach(); score = score + 2; } if (obstacleGroup.isTouching(monkey) && monkey.scale === 0.1){ gameState = END; } else if (obstacleGroup.isTouching(monkey) && monkey.scale >= 0.1){ obstacleGroup.destroyEach(); monkey.scale = 0.1; score = score - 10; } } else if (gameState === END){ back.velocityX = 0; monkey.velocityY = 0; obstacleGroup.setVelocityXEach(0); bananaGroup.setVelocityXEach(0); obstacleGroup.setLifetimeEach(-1); bananaGroup.setLifetimeEach(-1); } switch(score) { case 10: monkey.scale = 0.12; break; case 20: monkey.scale = 0.14; break; case 30: monkey.scale = 0.16; break; case 40: monkey.scale = 0.18; break; default: break; } drawSprites(); stroke("white"); textSize(20); fill("white"); text("Score: " + score,300,50); } function spawnBanana(){ if(frameCount % 120 === 0){ var banana = createSprite(400,120,20,20); banana.addImage(bananaImg); banana.y = random(120,200); banana.scale = 0.06; banana.velocityX = -4; banana.lifetime = 100; bananaGroup.add(banana); } } function spawnObstacles(){ if(frameCount % 300 === 0){ var stone = createSprite(400,355,50,50); stone.addImage(obstacleImg); stone.scale = 0.1; stone.velocityX = -4; stone.lifetime = 134; obstacleGroup.add(stone); } }
$(function() { $('#create_model').click(function() { $('#table_name').change(); }); $('#db_group').change(function() { window.location.search = '?db_group=' + $(this).val(); }); $('#table_name').change(function() { $.get('/model_create/' + $(this).val() + '/create?c_ajax=1&db_group=' + $('#db_group').val(), function(return_data) { if (cl4.process_ajax(return_data)) { $('#model_code_container').val(return_data.model_code); } else { $('#model_code_container').val('There was a problem generating the model.'); } }); }); });
export default class ArtInstitute { static searchArt(search) { return fetch(`https://api.artic.edu/api/v1/artworks/search?q=${search}&fields=id,title,image_id&limit=20`) .then(function (response) { if (!response.ok) { throw Error(response.statusText); } return response.json(); }) .catch(function (error) { return error; }); } // api call url: https://api.artic.edu/api/v1/artworks/[id] static searchObject(id){ return fetch(`https://api.artic.edu/api/v1/artworks/${id}`) .then(function(response){ if (!response.ok){ throw Error(response.statusText); } return response.json(); }) .catch(function (error) { return error; }); } }
$(function(){ var key = getSearch('key'); // console.log(key); $('.search-input').val(key); render(); function render(){ var params ={}; params.proName = $('.search-input').val(); params.page = 1; params.pageSize = 100; var $current = $('.lt-sort a.current'); if($current.length > 0){ var sortName = $current.data('type'); var sortValue = $current.find('i').hasClass('fa-angle-down') ? 2 : 1; params[sortName] = sortValue; } setTimeout(function(){ $.ajax({ type:'get', url:'/product/queryProduct', data:params, dataType:'json', success:function(info){ // console.log(info); var htmlStr = template('proTpl',info); $('.lt-pro').html(htmlStr); } }) },500) } $('.search-btn').on('click',function(){ var key = $('.search-input').val().trim(); if(key === ""){ mui.toast('请输入关键字',{duration:3000}) return; } render(); var history = localStorage.getItem('search_list') || '[]'; var arr = JSON.parse(history); if(arr.indexOf(key) > -1){ arr.splice(arr.indexOf(key),1) } if(arr.length >= 10){ arr.pop(); } arr.unshift(key); localStorage.setItem('search_list',JSON.stringify(arr)); }) $('.lt-sort a[data-type]').click(function(){ if($(this).hasClass('current')){ $(this).find('i').toggleClass('fa-angle-up').toggleClass('fa-angle-down'); }else{ $(this).addClass('current').siblings().removeClass('current'); } render(); }) })
function now() { return new Date().toISOString(); } function randColor() { return '#' + Math.floor(Math.random() * 16777215).toString(16); }
import mapPostsData from './mapPostsData'; const getPostsData = (category, successCallback, errorCallback, number) => { let filterNumber = ''; if (number) { filterNumber = '&per_page=' + number; } $.ajax({ url: Constants.apiUrl + 'posts?categories=' + category + filterNumber + '&_embed=1', crossDomain: true }) .done((data) => { const posts = mapPostsData(data); successCallback(posts); }) .fail((xhr) => { errorCallback(xhr); }); }; export default getPostsData;
$('.review__items').slick({ mobileFirst: true, slidesToShow: 1, speed: 300, cssEase: "ease-in", dots: true, arrows: false, adaptiveHeight: true, responsive: [ { breakpoint: 1199, settings: { dots: false, arrows: true } } ] }); $('.tariffs__slider').slick({ mobileFirst: true, slidesToShow: 1, speed: 300, cssEase: "ease-in", dots: true, arrows: false, initialSlide: 1, responsive: [ { breakpoint: 700, settings: "unslick" } ] }); function initMap() { var coords = { lat: 59.9391, lng: 30.3232 }; var markerImage = "img/contacts-marker.svg" var myMap = new google.maps.Map(document.querySelector(".map"), { zoom: 17, scrollwheel: false, center: coords }); var markers = [ { coordinates: { lat: 59.93895, lng: 30.32329 }, image: markerImage, info: "ул. Большая Конюшенная,19/8" } ] for (var i = 0; i < markers.length; i++) { addMarker(markers[i]); } function addMarker(properties) { var marker = new google.maps.Marker({ position: properties.coordinates, map: myMap }); if (properties.image) { marker.setIcon(properties.image); } if (properties.info) { var infoWindow = new google.maps.InfoWindow({ content: properties.info }) marker.addListener("click", function () { infoWindow.open(myMap, marker); }) infoWindow.open(myMap, marker); } } }
window.HRworksReceipt = $.extend(true, window.HRworksReceipt, { "config": { "layoutSet": "navbar", "navigation": [ { title: Globalize.localize("receipts"), action: "#home", icon: "home" }, { title: Globalize.localize("about"), action: "#about", icon: "info" } ] } });
const rijndael = require('rijndael-js'); const md5 = require('md5') const CryptoJS = require('crypto-js'); const crypto = require('crypto'); const ivSize = 16; const iv = crypto.randomBytes(ivSize); let PUBLIC_KEY= 'BNXPRIVATEKEY2019'; const encrypt = (userName, Password) => { let privateKey = userName; let userSecret = Password; let publicKey = md5(PUBLIC_KEY) let cipher = new rijndael(md5(privateKey), 'cbc'); let ciphertext = Buffer.from(cipher.encrypt(userSecret, 256, publicKey)); let encryptedCredentials= md5(ciphertext.toString('base64')) return encryptedCredentials } module.exports={encrypt}
(function printOption (options, key) { return _.colors.blue(key) + ' ' + options[key]; })
import { createContext } from 'react'; const ItemsContext = createContext({ items: [], generateNewItems: (num) => {}, resetList: () => {}, }); export default ItemsContext;
import React from 'react'; import'./App.css'; import{BrowserRouter as Router, Route} from "react-router-dom" import Header from "./Components/Header"; import Popup from './Components/Popup'; import Sidebar from './Components/Sidebar'; import Weather from "./Components/Weather"; import Weatherform from "./Components/Weatherform"; import Projects from "./Components/Projects"; import About from "./Components/About"; const Api_Key = "02d6c46890f0adaf5c47d81ad7142d3d"; const date = new Date(); const year = date.getFullYear(); const months = ["January","February","March","April","May","June","July","August","September","October","November","December"]; const month = months[date.getMonth()]; const day = date.getDate(); const week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] const wday = week[date.getDay()]; class App extends React.Component { constructor(props) { super(props); this.state = { showPopup: false, temperature: undefined, city: undefined, country: undefined, humidity: undefined, description: undefined, error: undefined, status:false}; } aboutme(){ this.setState({ showPopup:!this.state.showPopup }); } getWeather = async (e) => { const city = e.target.elements.city.value; const country = e.target.elements.country.value; e.preventDefault(); const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}, ${country}&units=metric&appid=${Api_Key}`); const response = await api_call.json(); console.log(response); if(city && country){ this.setState({ temperature: response.main.temp, city: response.name, country: response.sys.country, humidity: response.main.humidity, description: response.weather[0].description, error: "", }) } else{ this.setState({ error: "Please input search values...", }) } } render() { return ( <Router> <div className="container1"> <Route exact path="/" render={props=>( <React.Fragment> <Header className="header1"/> <p className="date">It's {year}{", "}{month}{" "}{day}{", "}{wday}{". "}</p> <button className="popupbtn" onClick={this.aboutme.bind(this)}>My Philosophy</button> {this.state.showPopup ? <Popup className="popup" text='Conceive, Believe, Achieve' closePopup={this.aboutme.bind(this)} /> : null } <p className="weathertext"> Today outside looks like </p> <Weatherform loadWeather={this.getWeather}/> <Weather temperature={this.state.temperature} city={this.state.city} country={this.state.country} humidity={this.state.humidity} description={this.state.description} error={this.state.error}/> </React.Fragment> )}/> <Route path="/about" component={About}/> <Route path="/projects" component={Projects}/> <Route path= "/contact" component={Sidebar}/> </div> </Router> ) }; } export default App;
/* * Copyright (c) 2019. - Eighty / 20 Results by Wicked Strong Chicks. * ALL RIGHTS RESERVED * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact us at mailto:info@eighty20results.com */ (function ($) { 'use strict'; let e20rConfirmationForm = { init: function () { this.confirmationForm = $('#e20r-email-confirmation-form'); this.submitBtn = this.confirmationForm.find('input.e20r-email-submit'); this.toggleSMS = this.confirmationForm.find('input.e20r-use-sms'); this.smsFields = this.confirmationForm.find('div.e20r-sms-input'); this.emailFields = this.confirmationForm.find('div.e20r-email-input'); let self = this; self.toggleSMS.unbind('click').on('click', function () { window.console.log("Toggle fields"); if (self.smsFields.is(':hidden')) { self.smsFields.show(); self.emailFields.hide(); } else { self.smsFields.hide(); self.emailFields.show(); } }); self.submitBtn.unbind('click').on('click', function (e) { e.preventDefault(); // $('.e20r-warning-message').hide(); self.submit(); }); }, submit: function () { let self = this; window.console.log("Trigger submit action!"); $('html,body').css('cursor', 'progress'); let request_data = { action: 'e20r_send_confirmation', 'e20r_email_conf': self.confirmationForm.find('input#e20r_email_conf').val(), 'e20r_email_address': self.confirmationForm.find('input.e20r-recipient-email').val(), 'e20r_phone_number': self.confirmationForm.find('input.e20r-recipient-phone').val(), }; $.ajax({ url: e20r_pec.ajaxUrl, timeout: (parseInt(e20r_pec.timeout) * 1000), data: request_data, success: function ($response) { let msg = $('.e20r-warning-message'); let warnings = $('div.e20r-warnings'); if (false === $response.success) { msg.html($response.data); msg.addClass('e20r-error-msg'); warnings.show(); return false; } window.console.log("Returned: ", $response); let redirect = $('#e20r-redirect-slug').val(); let $success_msg = $('#e20r-confirmation-msg').val(); if (typeof redirect !== 'undefined' && '' !== redirect) { location.href = '/' + redirect + '/'; } else { msg.addClass('e20r-success-msg'); msg.html($success_msg); warnings.show(); } $('html,body').css('cursor', 'default'); }, error: function ($response) { window.console.log("Error: ", $response); let msg = $('.e20r-warning-message'); let warnings = $('div.e20r-warnings'); msg.html($response.data); msg.addClass('e20r-error-msg'); warnings.show(); $('html,body').css('cursor', 'default'); }, }); } } $(document).ready(function () { e20rConfirmationForm.init(); }); })(jQuery);
export const GET_INSIDE_SELECT = 'GET_INSIDE_SELECT'; export const ADD_INSIDE = 'ADD_INSIDE'; export const GET_INSIDE_LIST = 'GET_INSIDE_LIST'; export const CHANGE_INSIDE_STATU = 'CHANGE_INSIDE_STATU'; export const GET_INSIDE_INFO = 'GET_INSIDE_INFO'; export const GET_OUT_TARGET = 'GET_OUT_TARGET'; export const ADD_MAP_TARGET = 'ADD_MAP_TARGET'; export const GET_MAP_LIST = 'GET_MAP_LIST'; export const CHANGE_MAP_STATUS = 'CHANGE_MAP_STATUS';
import {GET_INPUT_VALUE } from './actionTypes'; export const sendInputNu=(Num)=>{ return {type: GET_INPUT_VALUE, mode:'NUM', Num} } export const sendInputOpr=(Opr)=>{ return {type: GET_INPUT_VALUE, mode:'OPR', Opr} }
// private IIFE Expression var className = (function(nm){ let _privateProperty1 = nm; let _pp2 = 1; // private return { prop3: 1203, //public get pp2(){ // accessor return _pp2; }, set pp2(s){ pp2=s; } } })(); var a = undefined ?? 100; //or this._varname = null; for private class var alert([2, 4].every(isComposite)); // => false (2 is prime, 4 is not)
var svg = d3.select('svg'), width = +svg.attr('width'), height = +svg.attr('height'), g = svg.append('g').attr('transform', 'translate(' + (width / 2 + 40) + ',' + (height / 2 + 90) + ')'); var stratify = d3.stratify().parentId(function(d) { return d.id.substring(0, d.id.lastIndexOf('.')); }); var tree = d3 .tree() .size([2 * Math.PI, 500]) .separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; }); root = d3.hierarchy(json, function(d) { console.log('d ', d); return d.children; }); root.x0 = height / 2; root.y0 = 0; console.log('rtt root ', root); var link = g .selectAll('.link') .data(root.data) .enter() .append('path') .attr('class', 'link') .attr( 'd', d3 .linkRadial() .angle(function(d) { console.log('d ', d); return d.x; }) .radius(function(d) { return d.y; }) ); var node = g .selectAll('.node') .data(root.children) .enter() .append('g') .attr('class', function(d) { return 'node' + (d.children ? ' node--internal' : ' node--leaf'); }) .attr('transform', function(d) { return 'translate(' + radialPoint(d.x, d.y) + ')'; }); node.append('circle').attr('r', 2.5); node .append('text') .attr('dy', '0.31em') .attr('x', function(d) { return d.x < Math.PI === !d.children ? 6 : -6; }) .attr('text-anchor', function(d) { return d.x < Math.PI === !d.children ? 'start' : 'end'; }) .attr('transform', function(d) { return 'rotate(' + (d.x < Math.PI ? d.x - Math.PI / 2 : d.x + Math.PI / 2) * 180 / Math.PI + ')'; }) .text(function(d) { return d.id.substring(d.id.lastIndexOf('.') + 1); }); function radialPoint(x, y) { return [(y = +y) * Math.cos((x -= Math.PI / 2)), y * Math.sin(x)]; }
import React,{ Component } from 'react' import withFetch from './hoc/withFetch' const Joke = withFetch('https://randomuser.me/api/')(props=>{ return <div>{props.data.results[0].email}</div> }) // class Joke extends Component { // state = { // loading: true, // joke: null // } // componentDidMount(){ // fetch('https://randomuser.me/api/') // .then(res=>res.json()) // .then(joke=>{ // this.setState({ // loading: false, // joke // }) // }) // } // render(){ // if(this.state.loading){ // return <div>loading</div> // }else{ // return <div>{this.state.joke.results[0].email}</div> // } // } // } export default Joke
/** * Overlay content for exercise descriptions. */ P.overlays.exercises.Description = P.views.Layout.extend({ templateId: 'exercise.desc.overlay', regions: { rDescs: '.r-descs' }, initialize: function(attrs) { this.name = attrs.name; this.collection = new P.models.exercises.DescriptionCollection(); }, onRender: function() { var collection = new P.overlays.exercises.Collection({ collection: this.collection, name: this.name, who: Sisse.getUser().id, load: !this.collection.__loaded, hideOptions: this.hideOptions }); this.rDescs.show(collection); }, serializeData: function() { return { name: this.name }; } });
var mongoose = require('mongoose'); var nicknameSchema = new mongoose.Schema({ nickname: String, stones : Number, showHalves : Boolean, poundsLost : Number }); mongoose.model('Nickname', nicknameSchema);
import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import { Burger } from '../../components/burgerMenu.js'; import { SideMenu } from "../../components/sideMenu.js"; import { CSearch } from "../../components/search"; export const Header = () => { const [open, setOpen] = useState(false) return ( <> <header> <Link to="/"> NEWS </Link> {open ? <></> : <CSearch />} <div> <Burger open={open} setOpen={setOpen} /> <SideMenu open={open} setOpen={setOpen} /> </div> </header> </> ); }
/** * Created by sheshash on 3/24/2017. */ define(function() { 'use strict'; return function(data) { data.toString = data.id + data.memberName + data.memberType; return { data: data, toString: function() { return data.toString; }, getId: function() { return data.id; }, getMemberName: function() { return data.memberName; }, getMemberType: function() { return data.memberType; } }; }; });
import memoize from 'utils/memoize' import { createSelector } from 'reselect' import { selectors as panoSelectors } from 'morpheus/casts/modules/pano' import { lifecycle } from 'morpheus/casts/actions' import { actions as sceneActions } from 'morpheus/scene' import { isActive, selectors as gamestateSelectors } from 'morpheus/gamestate' import createLoader from 'utils/loader' import { ACTION_TYPES } from 'morpheus/constants' import createLogger from 'utils/logger' const logger = createLogger('cast:modules:preload') const selectors = memoize(scene => { const sceneToLoad = cast => { const { type } = cast const actionType = ACTION_TYPES[type] switch (actionType) { case 'DissolveTo': case 'ChangeScene': { const { param1: nextSceneId } = cast return nextSceneId } default: return null } } const selectCastsToLoad = createSelector( () => scene.casts, gamestateSelectors.forState, (casts, gamestates) => casts.filter(cast => isActive({ cast, gamestates, }), ), ) const selectNewScenesToLoad = scenesToLoad => scene.casts .map(sceneToLoad) .filter(sceneId => sceneId && !scenesToLoad.find(s => s.id === sceneId)) return { castsToLoad: selectCastsToLoad, newScenesToLoad: selectNewScenesToLoad, sceneToLoad, } }) const loader = createLoader() export const delegate = memoize(scene => { const preloadSelectors = selectors(scene) return { applies() { return false }, update(position) { return dispatch => { // const angle = panoSelectors(scene).rotation(getState()); // console.log(angle.y, position); loader.load({ item: scene, filter: ({ toLoad }) => preloadSelectors.newScenesToLoad(toLoad), loader: async ({ id }) => { const sceneToLoad = await dispatch(sceneActions.fetch(id)) await dispatch(lifecycle.doPreload(sceneToLoad)) logger.info(`preload ${id}`) }, }) } }, } })
// Firebase data provider impl for the Poop Monitor function PMDataProvider() { this.firebaseURI = "https://<your Firebase app id>.firebaseio.com/events/"; this.firebaseRef = new Firebase(this.firebaseURI); } // Fire callback once for each event in the system PMDataProvider.prototype.getEvents = function(callback) { this.firebaseRef.on("child_added", function(dataSnapshot) { callback(dataSnapshot.val()); }); }; // Persist the given event. callback fired once complete PMDataProvider.prototype.saveEvent = function(event, callback) { this.firebaseRef.push(event, function complete(error) { if (error) { return callback( error ); } callback(); }.bind(this)); }; // Close the provider PMDataProvider.prototype.close = function() { this.firebaseRef.off(); };
const path = require('path'); const cv = require('opencv4nodejs'); const src = cv.imread(path.resolve(__dirname, './data/hongkong.bmp')); const rows = src.rows; const cols = src.cols; const w = 0.95; const t0 = 0.1; const minMat = new cv.Mat(rows, cols, cv.CV_8UC1); const trans32F = new cv.Mat(rows, cols, cv.CV_32FC1); const dst = new cv.Mat(rows, cols, cv.CV_8UC3); const startTime = new Date().getTime() // 获取最小值图 for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { const [B, G, R] = src.atRaw(r, c); const minV = Math.min(B, G, R); minMat.set(r, c, minV); } } // 最小值滤波获取暗通道图 const k = 7; const block = 2 * 7 + 1; let g = [], h = [], hFlip = [], temp = []; for (let r = 0; r < rows; r++) { for (let c = cols - 1; c >= 0; c--) { temp[cols - 1 - c] = minMat.atRaw(r, c); } for (let c = 0; c < cols; c++) { if (c % block == 0) { g[c] = minMat.atRaw(r, c); hFlip[c] = temp[c]; } else { g[c] = Math.min(g[c - 1], minMat.atRaw(r, c)); hFlip[c] = Math.min(hFlip[c - 1], temp[c]); } } for (let c = 0; c < cols; c++) { h[c] = hFlip[cols - 1 - c]; } for (let c = 0; c < cols; c++) { if (c < k) { minMat.set(r, c, Math.min(g[c + k])); } else if (c >= cols - k) { minMat.set(r, c, Math.min(h[c - k])); } else { minMat.set(r, c, Math.min(g[c + k], h[c - k])); } } } g = []; h = []; hFlip = []; temp = []; for (let c = 0; c < cols; c++) { for (let r = rows - 1; r >= 0; r--) { temp[rows - 1 - r] = minMat.atRaw(r, c); } for (let r = 0; r < rows; r++) { if (r % block == 0) { g[r] = minMat.atRaw(r, c); hFlip[r] = temp[r]; } else { g[r] = Math.min(g[r - 1], minMat.atRaw(r, c)); hFlip[r] = Math.min(hFlip[r - 1], temp[r]); } } for (let r = 0; r < rows; r++) { h[r] = hFlip[rows - 1 - r]; } for (let r = 0; r < rows; r++) { if (r < k) { minMat.set(r, c, Math.min(g[r + k])); } else if (c >= cols - k) { minMat.set(r, c, Math.min(h[r - k])); } else { minMat.set(r, c, Math.min(g[r + k], h[r - k])); } } } const darkChannel8U = minMat.copy(); // for (let r = 0; r < rows; r++) { // for (let c = 0; c < cols; c++) { // let minV = 255; // for (let i = r - k; i < r + k; i++) { // for (let j = c - k; j < c + k; j++) { // if (i < 0 || j < 0 || i >= rows || j >= cols) { // continue; // } // if (minV > minMat.atRaw(i, j)) { // minV = minMat.atRaw(i, j); // } // } // } // darkChannel8U.set(r, c, minV); // } // } // 根据暗通道图获取大气光值A let sortArray = []; for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { sortArray.push({ r: r, c: c, val: darkChannel8U.atRaw(r, c) }) } } sortArray.sort(function(a, b) { return a.val < b.val; }) let sumB = 0, sumG = 0, sumR = 0; for (let i = 0; i < (rows * cols / 1000); i++) { const [B, G, R] = src.atRaw(sortArray[i].r, sortArray[i].c); sumB += B; sumG += G; sumR += R; } const Ab = sumB / (rows * cols / 1000); const Ag = sumG / (rows * cols / 1000); const Ar = sumR / (rows * cols / 1000); const A = parseInt(0.1140 * Ab + 0.5870 * Ag + 0.2989 * Ar); // const A = 220; console.log('A =', A); // 获取透射率图 for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { let t = 1.0 - (w * darkChannel8U.atRaw(r, c) / A); t < 0 && (t = 0); trans32F.set(r, c, t); } } // 对透射率图进行引导滤波 const src32F = src.convertTo(cv.CV_32F, 1.0/255, 0.0); const guideTrans32F = trans32F.guidedFilter(src32F, 100, 0.01, -1); // Gamma矫正 const gama = 0.8; const GammaTable = []; for (let i = 0; i < 256; i++) { let fT = (i + 0.5)/255; fT = Math.pow(fT, gama); let iT = parseInt(fT * 255); iT > 255 && (iT = 255); iT < 0 && (iT = 0); GammaTable.push(iT); } // 获取去雾后图像 for (let r = 0; r < rows; r++) { for (let c = 0; c < cols; c++) { const [B, G, R] = src.atRaw(r, c); const t = Math.max(guideTrans32F.atRaw(r, c), t0); let dstB = parseInt((B - Ab) / t + Ab); let dstG = parseInt((G - Ag) / t + Ag); let dstR = parseInt((R - Ar) / t + Ar); dstB > 255 && (dstB = 255); dstG > 255 && (dstG = 255); dstR > 255 && (dstR = 255); dstB < 0 && (dstB = 0); dstG < 0 && (dstG = 0); dstR < 0 && (dstR = 0); // dst.set(r, c, [dstB, dstG, dstR]); dst.set(r, c, [GammaTable[dstB], GammaTable[dstG], GammaTable[dstR]]); } } const endTime = new Date().getTime() console.log(`运行时间为: ${(endTime - startTime) / 1000}s`) cv.imshowWait("src", src); // cv.imshowWait("darkChannel", minMat); // cv.imshowWait("trans", trans32F); // cv.imshowWait("guided", guideTrans32F); cv.imshowWait("dst", dst); cv.imwrite('./data/src.jpg', src); cv.imwrite('./data/dst.jpg', dst);
function runTest() { FBTest.openNewTab(basePath + "console/api/6438/issue6438.html", function(win) { FBTest.openFirebug(function() { FBTest.enableConsolePanel(function(win) { var config = {tagName: "div", classes: "logRow"}; // Wait for the log entry to be displayed FBTest.waitForDisplayedElement("console", config, function(row) { var expected = new RegExp("console.log\\(\\) allows patterns like %d, which are "+ "replaced by additional function arguments. Example: 100"); // Test whether the message is displayed correctly FBTest.compare(expected, row.textContent, "Message must be displayed correctly"); FBTest.testDone(); }); FBTest.reload(); }); }); }); }
/*const db = require('../../../lib/db') const { CreateRoutes } = require('../../../lib/helper-routes') const _escape = require('sql-template-strings') function Properties(){ this.getAllProperties = async () => { let query = await db.query("select * from properties"); if(query){ return query } return false; } } let prop = new Properties(); export default async function handler(req, res) { const route = new CreateRoutes(req, res); route.get('/api/properties/', async function(req, res){ let all = await prop.getAllProperties(); res.send(all) }) }*/
import React, { useState, useEffect } from "react"; import styled from "styled-components"; // Atoms import Icon from "../../../components/atoms/icon/icon"; // SVG Images import bottleFull from "../../../images/profile/water_bottle/bottleFull.svg"; import bottle1 from "../../../images/profile/water_bottle/bottle1.svg"; import bottle2 from "../../../images/profile/water_bottle/bottle2.svg"; import bottle3 from "../../../images/profile/water_bottle/bottle3.svg"; import bottle4 from "../../../images/profile/water_bottle/bottle4.svg"; import bottle5 from "../../../images/profile/water_bottle/bottle5.svg"; import bottle6 from "../../../images/profile/water_bottle/bottle6.svg"; import bottle7 from "../../../images/profile/water_bottle/bottle7.svg"; import bottleEmpty from "../../../images/profile/water_bottle/bottleEmpty.svg"; const WaterBottleGauge = ({ children, ...props }) => { const { point_current } = props; const gaugeFill = () => { switch (true) { case point_current === 1: return ( <Icon svg={bottle1} alt="1 serving of water" title="Current: 1 serving of water" /> ); case point_current === 2: return ( <Icon svg={bottle2} alt="2 serving of water" title="Current: 2 serving of water" /> ); case point_current === 3: return ( <Icon svg={bottle3} alt="3 serving of water" title="Current: 3 serving of water" /> ); case point_current === 4: return ( <Icon svg={bottle4} alt="4 serving of water" title="Current: 4 serving of water" /> ); case point_current === 5: return ( <Icon svg={bottle5} alt="5 serving of water" title="Current: 5 serving of water" /> ); case point_current === 6: return ( <Icon svg={bottle6} alt="6 serving of water" title="Current: 6 serving of water" /> ); case point_current === 7: return ( <Icon svg={bottle7} alt="7 serving of water" title="Current: 7 serving of water" /> ); case point_current >= 8: return ( <Icon svg={bottleEmpty} alt="8+ servings of water" title="Current: Goal Complete!" /> ); default: return ( <Icon svg={bottleFull} alt="0 servings of water" title="Current: 0 servings of water" /> ); } }; props.debug && console.log(`[Before return]:`, point_current); return ( <> <StyledGauge className="StyledGauge"> <MobileCardWater className="MobileCardWater"> {gaugeFill(point_current)} </MobileCardWater> </StyledGauge> </> ); }; const StyledGauge = styled.div` position: relative; height: 19rem; width: 14.9rem; `; const MobileCardWater = styled.div` position: absolute; width: 3.176rem; height: 5.8rem; left: 6.428rem; right: 6.396rem; top: 5.6rem; bottom: 7.6rem; `; export default WaterBottleGauge;
import React, { Component } from 'react' import PropTypes from 'prop-types' import { withStyles } from '@material-ui/core/styles' import Card from '@material-ui/core/Card' import CardActionArea from '@material-ui/core/CardActionArea' import CardActions from '@material-ui/core/CardActions' import CardContent from '@material-ui/core/CardContent' import CardMedia from '@material-ui/core/CardMedia' import Button from '@material-ui/core/Button' import Typography from '@material-ui/core/Typography' import Modal from '@material-ui/core/Modal' function rand() { return Math.round(Math.random() * 20) - 10 } function getModalStyle() { const top = 50 + rand() const left = 50 + rand() return { top: `${top}%`, left: `${left}%`, transform: `translate(-${top}%, -${left}%)`, } } const styles = theme => ({ card: { maxWidth: 1000, marginTop: 10, }, media: { objectFit: 'cover', }, paper: { position: 'absolute', width: theme.spacing.unit * 50, backgroundColor: theme.palette.background.paper, boxShadow: theme.shadows[5], padding: theme.spacing.unit * 4, }, }) class SavedTournamets extends Component { constructor() { super() this.state = { data: JSON.parse(localStorage.getItem("savedItems")), open: false, deletingIndex: null } } deleteItem = (index) => { const nextState = JSON.parse(localStorage.getItem("savedItems")).filter((_, i) => i !== index) localStorage.setItem("savedItems", JSON.stringify(nextState)) this.setState({ data: nextState }) this.closeModal() } modalOpen = (i) => { this.setState({ open: true, deletingIndex: i }) } closeModal = () => { this.setState({ open: false, deletingIndex: null }) } getSavedItems = () => { const { classes } = this.props const data = JSON.parse(localStorage.getItem('savedItems')) return data && data.map((item, index) => { return (<Card className={classes.card} key={index}> <CardActionArea> <CardMedia component="img" alt={item.title} className={classes.media} height="200" image={item.image} title={item.title} /> <CardContent> <Typography gutterBottom variant="h5" component="h4"> {item.title} </Typography> <Typography component="p"> {item.description} </Typography> </CardContent> </CardActionArea> <CardActions> <Button variant="contained" color="secondary" className={classes.button} onClick={() => this.modalOpen(index)}> Delete </Button> </CardActions> </Card>) }) } render() { const { classes } = this.props return( <div> <p>Saved items</p> {this.getSavedItems()} <Modal aria-labelledby="simple-modal-title" aria-describedby="simple-modal-description" open={this.state.open} onClose={this.closeModal} > <div style={getModalStyle()} className={classes.paper}> <Typography variant="h6" id="modal-title"> You want delete this item,are yor Sure </Typography> <Typography variant="subtitle1" id="simple-modal-description"> <Button variant="outlined" className={classes.button} onClick={()=> this.closeModal()}> Cancel </Button> <Button variant="contained" color="secondary" className={'delete-button ' + classes.button} onClick={() => this.deleteItem(this.state.deletingIndex)}> Delete </Button> </Typography> </div> </Modal> </div> ) } } SavedTournamets.propTypes = { classes: PropTypes.object } export default withStyles(styles)(SavedTournamets)
/** * Created by PatrikGlendell on 08/03/2017. */ var nodemailer = require('nodemailer2'); // var types = require('../constants/types'); module.exports.sendMail = function (username, password, socket, language) { var transporter = nodemailer.createTransport({ host: '', port: '', auth: { user: '', pass: '' }, secureConnection: false, tls: { rejectUnauthorized: false, ciphers: '' } }); var mailOptions = { from: '', to: username, subject: languageTitleSwitch(language), text: languageSwitch(language, username, password) }; transporter.sendMail(mailOptions, function (error, info) { if (error) { // socket.emit('action', { // type: types.ERROR_ON_SEND_EMAIL, // data: {code: 500, message: {error: error, info: info}} // }); } else { // socket.emit('action', { // type: types.EMAIL_TRANSMITTED, // data: {code: 200, message: 'OK'} // }); } }); }; module.exports.sendMailShield = function (username, password, socket) { var transporter = nodemailer.createTransport({ host: '', port: '', auth: { user: '', pass: '' }, secureConnection: false, tls: { rejectUnauthorized: false, ciphers: 'SSLv3' } }); var mailOptions = { from: '', to: username, subject: '', text: '' }; transporter.sendMail(mailOptions, function (error, info) { if (error) { // socket.emit('action', { // type: types.ERROR_ON_SEND_EMAIL, // data: {code: 500, message: {error: error, info: info}} // }); } else { // socket.emit('action', { // type: types.EMAIL_TRANSMITTED, // data: {code: 200, message: 'OK'} // }); } }); }; module.exports.sendMailNew = function (username, password, language) { var transporter = nodemailer.createTransport({ host: process.env.MAIL_HOSTNAME, port: process.env.MAIL_PORT, auth: { user: process.env.MAIL_USERNAME, pass: process.env.MAIL_PASSWORD, }, secureConnection: false, tls: { rejectUnauthorized: false, ciphers: 'SSLv3' } }); var mailOptions = { from: process.env.MAIL_FROM, to: username, subject: languageTitleSwitch(language), text: languageSwitch(language, username, password) }; transporter.sendMail(mailOptions, function (error, info) { if (error) { console.log("error:",error); } else { console.log("info:",info); } }); }; function languageTitleSwitch(language) { switch (language) { case 'da-DK': return 'Geometra - Inloggningsuppgifter'; case 'nl-NL': return 'Geometra - Login information'; case 'nl-BE': return 'Geometra - Login information'; case 'en-GB': return 'Geometra - Login information'; case 'en-US': return 'Geometra - Login information'; case 'nb-NO': return 'Geometra - Påloggningsinformasjon'; case 'sv-SE': return 'Geometra - Inloggningsuppgifter'; } } function languageSwitch(language, username, password) { switch (language) { case 'da-DK': return ''; case 'nl-NL': return ''; case 'nl-BE': return ''; case 'en-GB': return ''; case 'en-US': return ''; case 'nb-NO': return ''; case 'sv-SE': return ''; } }
Ext.define('CBA.controller.MainController', { extend: 'Ext.app.Controller', requires: [ 'Ext.app.Route' ], config: { routes: { '': 'showMain', 'view/:viewName': 'showMiew' }, refs: { menuBtn: 'mainView button[iconCls="menu"]', backBtn: 'mainView button[iconCls="back"]', menuList: 'menuView list', mainView: 'mainView', busList: 'mainView dataview[cls="bus-view"]', mapBtn: 'busView button[iconCls="map"]', busView: { selector: 'busView', xtype: 'busView', autoCreate: true }, tabPanel: 'busView tabpanel', tarifeView: 'tarifeView', listBilete: 'tarifeView tabpanel list[title="Bilete"]', tarifeTabPanel: 'tarifeView tabpanel', mapView: { selector: 'mapView', xtype: 'mapView', autoCreate: true } }, control: { backBtn: { tap: 'onBackBtnTap' }, menuBtn: { tap: 'onMenuBtnTap' }, mapBtn: { tap: 'onMapBtnTap' }, menuList: { itemtap: 'onMenuItemTap' }, busList: { itemtap: 'onBusItemTap' }, tabPanel: { activeitemchange: 'onTabChanged' }, tarifeTabPanel: { activeitemchange: 'onTarifeTabChanged' } } }, onBackBtnTap: function(button, e, eOpts) { var bStore = Ext.getStore('BusStore'), sbStore = Ext.getStore('StBusStore'), busView = this.getBusView(); bStore.clearFilter(); sbStore.clearFilter(); // we set visibility of toolbar buttons according to view var bool = this.getMainView().getActiveItem().config.xtype === 'busView' || this.getMainView().getActiveItem().config.xtype === 'searchView'; // sbStore remains filtered from getting the other buses which pass through a specific station //we need to filter sbStore if (this.getMainView().getActiveItem().config.xtype === 'mapView') sbStore.filter('bID', busView.getRecord().get("id")); this.getBackBtn().setHidden(bool); this.getMenuBtn().setHidden(!bool); window.history.back(); }, onMenuBtnTap: function(button, e, eOpts) { Ext.Viewport.toggleMenu('left'); }, onMapBtnTap: function(button, e, eOpts) { // we set visibility of toolbar buttons according to view this.getBackBtn().setHidden(false); this.getMenuBtn().setHidden(true); this.redirectTo('view/mapView'); var mapView = this.getMapView(), map = mapView.getMap(), sbStore = Ext.getStore("StBusStore"), stStore = Ext.getStore("StationStore"); busView = this.getBusView(), currBus = busView.getRecord(), busStore = Ext.getStore("BusStore"); sbStore.clearFilter(); sbStore.filter("bID", currBus.get("id")); if (map !== null) { stStore.filter(CBA.util.Filters.getC1Filter()); var contor = 0; //clear all markers from the map for (var i = 0; i < CBA.app.pointers.length; i++) { CBA.app.pointers[i].setMap(null); } //clear flightPath if (CBA.app.flightPath) { CBA.app.flightPath.setMap(null); } var statiiOrdine = []; stStore.each(function (item, index, length) { //get the other buses who pass through current station var buses = ""; //if it is the first bus the we don't put "," var contorBuses = 0; sbStore.clearFilter(); sbStore.filter("stID", item.get("id")); sbStore.each(function (item, index, length) { var numeBus = busStore.findRecord('id', item.get("bID"), 0, false, false, true).get('name'); buses = contorBuses == 0 ? buses + " " + numeBus : buses + ", " + numeBus; contorBuses = contorBuses + 1; }); var infowindow = new google.maps.InfoWindow({ content: item.get('sName') + '<div>Aici opresc: <h3>'+ buses +'</h3></div>' }); var position = new google.maps.LatLng(item.get('lat'), item.get('lang')); //get idx by bID, stID to know the order sbStore.clearFilter(); sbStore.filter("bID", currBus.get("id")); sbStore.filter("stID", item.get("id")); statiiOrdine[sbStore.findRecord('bID', currBus.get("id"), 0, false, false, true).get('idx')] = position; var marker = new google.maps.Marker({ position: position, title: item.get('sName'), map: map }); google.maps.event.addListener(marker, 'click', function () { infowindow.open(map, marker); }); CBA.app.pointers[contor] = marker; contor = contor + 1; }); CBA.app.flightPath = new google.maps.Polyline({ path: statiiOrdine, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 3 }); CBA.app.flightPath.setMap(map); setTimeout(function () { //pan to first station map.panTo(statiiOrdine[0]); }, 1000); } }, onMenuItemTap: function(dataview, index, target, record, e, eOpts) { switch (record.get('id')) { case 1: var bStore = Ext.getStore('BusStore'), sbStore = Ext.getStore('StBusStore'); bStore.clearFilter(); sbStore.clearFilter(); this.redirectTo(''); break; case 2: var sStore = Ext.getStore('SchedStore'), stStore = Ext.getStore('StationStore'); //clear all filters stStore.clearFilter(); sStore.clearFilter(); this.redirectTo('view/searchView'); break; case 3: var tStore = Ext.getStore('TarifStore'); tStore.filter('tip', "bilet"); this.redirectTo('view/tarifeView'); this.getTarifeTabPanel().setActiveItem(0); break; case 4: this.redirectTo('view/contactView'); break; default: this.redirectTo(''); break; } Ext.Viewport.toggleMenu('left'); }, onBusItemTap: function(dataview, index, target, record, e, eOpts) { var busId = record.get('id'), hStore = Ext.getStore('SchedStore'), sbStore = Ext.getStore('StBusStore'), busView = this.getBusView(), stStore = Ext.getStore('StationStore'); //we pass bus details to our component for updating tpl this.getBusView().down('component').setData(record.data); busView.setRecord(record); this.redirectTo('view/busView'); // we clear old filters and apply new ones hStore.clearFilter(); hStore.filter('bID', busId); // we filter for working day and set tab1 active hStore.filter('type', "W"); this.getTabPanel().setActiveItem(0); sbStore.clearFilter(); sbStore.filter('bID', busId); }, onTabChanged: function(tabPanel, tab, oldTab){ var sStore = Ext.getStore('SchedStore'), busView = this.getBusView(), currBus = busView.getRecord(), date = new Date(), hours = date.getHours(), minutes = date.getMinutes(); sStore.clearFilter(); sStore.filter('bID', currBus.get('id')); //sStore.filter('type', tab.config.itemId === "work" ? "W" : "F"); switch (tab.config.itemId) { case "work": sStore.filter('type', 'W'); break; case "free": sStore.filter('type', 'F'); break; case "now": var dayType = date.getDay(); // we filter according to current day type: 0 - Sunday, 1 - Monday, ..., 6 - Saturday sStore.filter('type', dayType === 0 || dayType === 6 ? "F" : "W"); // we filter start time to be greater than current time var hFilter = new Ext.util.Filter({ filterFn: function(item) { return parseFloat(item.get('start')) > parseFloat(minutes<10 ? hours+".0"+minutes : hours+"."+minutes); } }); sStore.filter(hFilter); break; default: sStore.filter('type', 'W'); this.getTabPanel().setActiveItem(0); break; } }, onTarifeTabChanged: function(tabPanel, tab, oldTab){ var tStore = Ext.getStore('TarifStore'); tStore.clearFilter(); switch (tab.config.title) { case "Bilete": tStore.filter('tip', 'bilet'); break; case "Abonamente": tStore.filter('tip', 'abonament'); break; case "Gratuitati": tStore.filter('tip', 'gratuitate'); break; default: tStore.filter('tip', 'bilet'); this.getTabPanel().setActiveItem(0); break; } }, showMain: function() { this.showView('mainView'); this.getMainView().setActiveItem(0); }, showMiew: function(viewName) { var view = this.getMainView(), miew = view.child(viewName) || view.add({ xtype: viewName }); view.setActiveItem(miew); miew.show(); return view; }, getBusNameById: function(busStore, id){ return busStore.findRecord('id', id, 0, false, false, true).get('name'); }, showView: function(xtype) { var view = Ext.Viewport.child(xtype) || Ext.Viewport.add({ xtype: xtype }); if (view.isInnerItem()) { Ext.Viewport.setActiveItem(view); } else { view.show(); } return view; } });
import React from 'react'; const HomePage = () => ( <div className='HomePage'> <h1 className='HomePage-major'>Timothy James</h1> <h2 className='HomePage-minor'>I like to design and build web applications.</h2> </div> ); export default HomePage;
// controller.js app.controller('projectsCtrl', function($scope, $http){ // delete project $scope.deleteProject = function(id){ // confirm if(confirm("Are you sure?")){ $http({ method: 'POST', data: { 'id' : id }, url: 'api/project/delete.php' }).then(function successCallback(response){ Materialize.toast(response.data, 4000); $scope.getAll(); }); } } // update project / save changes $scope.updateProject = function(){ $http({ method: 'POST', data: { 'id' : $scope.id, 'name' : $scope.name, 'content' : $scope.content, //'challenge' : $scope.challenge, //'solution' : $scope.solution, //'result' : $scope.result, 'thumbnail' : $scope.thumbnail, 'logo' : $scope.logo, 'gallery' : $scope.gallery }, url: 'api/project/update.php' }).then(function successCallback(response){ Materialize.toast(response.data, 4000); $('#modal-project-form').modal('close'); $scope.clearForm(); $scope.getAll(); }) } // get data to fill out form $scope.readOne = function(id){ $('#modal-project-title').text("Edit Project"); $('#btn-update-project').show(); $('#btn-create-project').hide(); // post id of project to be edited $http({ method: 'POST', data: {'id' : id}, url: 'api/project/read_one.php' }).then(function successCallback(response){ // put values in form $scope.id = response.data[0]["id"]; $scope.name = response.data[0]["name"]; $scope.content = response.data[0]["content"]; $scope.thumbnail = response.data[0]["thumbnail"]; $scope.logo = response.data[0]["logo"]; $scope.gallery = response.data[0]["gallery"]; // show modal $('#modal-project-form').modal('open'); }).catch(function(data, status, headers, config) { Materialize.toast('Unable to retrieve record.', 4000); }); } // get data to fill table $scope.getAll = function(){ $http({ method: 'GET', url: 'api/project/read.php' }).then(function successCallback(response){ $scope.names = response.data; }); } $scope.showCreateForm = function(){ // clear form $scope.clearForm(); // change modal title $('#modal-project-title').text("Create New Project"); // hide update project button $('#btn-update-project').hide(); // show create project button $('#btn-create-project').show(); } $scope.clearForm = function(){ $scope.id = ""; $scope.name = ""; $scope.content = ""; $scope.thumbnail = ""; $scope.logo = ""; $scope.gallery = ""; } $scope.$watch('logos', function(newValue, oldValue) { if(!newValue || newValue === oldValue) return; console.log('value added'); //At this point, newValue contains the new value of your persons array $('select').material_select(); }); // create new project $scope.createProject = function(){ $http({ method: 'POST', data: { 'name' : $scope.name, 'content' : $scope.content, 'thumbnail' : $scope.thumbnail, 'logo' : $scope.logo, 'gallery' : $scope.gallery }, url: 'api/project/create.php' }).then(function successCallback(response){ // Successfully created Materialize.toast(response.data, 4000); // close modal and reset $('#modal-project-form').modal('close'); $scope.clearForm(); $scope.getAll(); }); } // tinyMCE $scope.tinymceOptions = { plugins: 'link image code', menubar: false, style_formats: [ { title: 'Section Header', block: 'h2', classes: 'section-header' }, { title: 'Section Content', block: 'p', classes: 'section-text' }, { title: 'link', inline: 'a', classes: 'section-link' } ], toolbar: 'styleselect', statusbar: false }; });
// {/* <script> */} // const Home = { template: '<div> Home page </div>' }; // let routes = [ // { path: '/home.php', component: Home } // ] // const router = new VueRouter({ // mode: 'history', // routes // short for `routes: routes` // }) var app = new Vue({ el: '#app', // router, data: { user:{ id:'', name:'', email:'', mobile:'', password:'' }, login: 'Login', loading: false, seen: false, users: [], editmode: false }, methods: { updateUser(id) { console.log(id) app.loading = true; axios.patch('api/user-create.php?action=update&id='+id, { name: this.user.name, email: this.user.email, mobile: this.user.mobile, password: this.user.password }) .then(function (response) { app.loading = false; app.editmode = false; if (response.data.error) { console.log(response.data.error); Swal({ type: 'error', title: 'Oops...', text: response.data.error }) } else { $('#openModal').modal('hide'); console.log(response.data.success); app.getAllUsers(); const toast = Swal.mixin({ toast: true, position: 'top-right', showConfirmButton: false, timer: 3000 }); toast({ type: 'success', title: response.data.success }) } }); }, editModal(user) { app.editmode = true; this.user.id = user.id; this.user.name = user.name; this.user.email = user.email; this.user.mobile = user.mobile; this.user.password = user.password; $('#openModal').modal('show'); }, getAllUsers(){ axios.get('api/user-create.php?action=read') .then(response => { if (response.data.error) { console.log(response.data.error); } else { console.log(response.data) app.users = response.data; } }) }, loginUser(){ app.loading = true; axios.post('api/user-create.php?action=create', { name: this.user.name, email: this.user.email, mobile: this.user.mobile, password: this.user.password }) .then(function (response) { app.loading = false; if (response.data.error) { console.log(response.data.error); Swal({ type: 'error', title: 'Oops...', text: response.data.error }) } else { app.seen = false; console.log(response.data.success); app.getAllUsers(); swal( 'Deleted!', response.data.success, 'success' ) } }); }, deleteUser(id){ swal({ title: 'Are you sure?', text: "You won't be able to revert this!", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { //send Request to the server if(result.value) { axios.delete('api/user-create.php?action=delete&id='+id) .then(response => { if (response.data.error) { console.log(response.data.error); } else { console.log(response.data.success) this.getAllUsers(); swal( 'Deleted!', response.data.success, 'success' ) } }) } }) }, add() { if (app.editmode == true) { this.user.id = '', this.user.name = '', this.user.email = '', this.user.mobile = '', this.user.password = '' } } }, mounted() { this.getAllUsers(); } }) {/* </script> */}
import React from 'react'; class ItemBlock extends React.Component { render() { return(<div className="flexbox__item"> <div className={this.props.classBlock}></div> <h3>{this.props.title}</h3> <p>{this.props.children}</p> </div> ) } } export default ItemBlock;
import React from 'react'; import { StyleSheet, View, Platform, StatusBar, } from 'react-native'; const ItScreenContainer = (props) => { const { barStyle, children } = props; const { container } = styles; return ( <View {...props} style={container}> {Platform.OS === 'ios' && ( <StatusBar barStyle={barStyle || 'light-content'} /> )} {children} </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#FFFFFF', }, }); export { ItScreenContainer };
/** * Created by guominghui on 17/8/11. */ class DataChannel{ constructor(rtcpeerconnection,name){ this.dc = rtcpeerconnection.createDataChannel(name); } send(){ } }
import React, { useEffect } from 'react'; import CodeMirror from "react-codemirror" import "codemirror/lib/codemirror.css" // import "@uiw/react-codemirror" import "codemirror/mode/xml/xml" import "codemirror/mode/css/css" import "codemirror/mode/javascript/javascript" import 'codemirror/theme/3024-day.css' import 'codemirror/theme/3024-night.css' import 'codemirror/theme/abcdef.css' import 'codemirror/theme/ambiance.css' import 'codemirror/theme/ambiance-mobile.css' import 'codemirror/theme/ayu-dark.css' import 'codemirror/theme/ayu-mirage.css' import 'codemirror/theme/base16-dark.css' import 'codemirror/theme/base16-light.css' import 'codemirror/theme/bespin.css' import 'codemirror/theme/blackboard.css' import 'codemirror/theme/cobalt.css' import 'codemirror/theme/colorforth.css' import 'codemirror/theme/dracula.css' import 'codemirror/theme/dracula.css' import 'codemirror/theme/duotone-dark.css' import 'codemirror/theme/duotone-light.css' import 'codemirror/theme/eclipse.css' import 'codemirror/theme/elegant.css' import 'codemirror/theme/gruvbox-dark.css' import 'codemirror/theme/hopscotch.css' import 'codemirror/theme/icecoder.css' import 'codemirror/theme/idea.css' import 'codemirror/theme/isotope.css' import 'codemirror/theme/lesser-dark.css' import 'codemirror/theme/liquibyte.css' import 'codemirror/theme/lucario.css' import 'codemirror/theme/material-darker.css' import 'codemirror/theme/material.css' import 'codemirror/keymap/sublime'; import '../styles/codeMirror.css' // import {*} from "codemirror/theme" const Editor = ({name,language,setcode,theme}) => { let options={ lineNumbers:true, mode:language, theme:theme, keyMap:"sublime" } function updateCode(newCode){ setcode(newCode) // console.log(newCode); } return ( <div className="editor" > <h3>{name}</h3> <CodeMirror options={options} onChange={updateCode} /> </div> ); } export default Editor;
// document.getElementById("btn-submit-secret").addEventListener("click", updateOtp); function setCookie(cname, cvalue) { var d = new Date(); d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1); } if (c.indexOf(name) === 0) { return c.substring(name.length, c.length); } } return ""; } document.getElementById('btn-submit-secret').onclick = function() { // localStorage['secret'] = $('#secret').val(); setCookie('secret', $('#secret').val()); console.log(getCookie('secret');); updateOtp(); };
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const name = require('./fields/fields-name'); const description = require('./fields/fields-description'); const type = require('./fields/fields-type'); const attack = require('./fields/fields-attack.js'); const defense = require('./fields/fields-defense.js'); const height = require('./fields/fields-height'); const create_at= require('./fields/fields-create_at.js'); const _schema = { name, description, type, attack, defense, height, create_at }; module.exports = new Schema(_schema);
var buttom = $('#arrow'); buttom.click(dropDown); function dropDown () { $('#songs').slideUp(3000, function () { $('#songs').remove() }) }
for (var i = 0; i< document.querySelectorAll(".drum").length; i++){ document.querySelectorAll(".drum")[i].addEventListener("click", function (){ var buttonInnerHTML = this.innerHTML; makeSound(buttonInnerHTML); buttonAnimation(buttonInnerHTML); }); } document.addEventListener("keypress", function(event){ makeSound(event.key); buttonAnimation(event.key); }); function makeSound(key){ switch (key) { case "A": var tom1 = new Audio("sounds/tom-1.mp3"); // var a = new Audio("sounds/a.mp3"); tom1.play(); // a.play(); break; case "B": var tom1 = new Audio("sounds/tom-2.mp3"); //var b = new Audio("sounds/b.mp3"); tom1.play(); //b.play(); break; case "C": var tom1 = new Audio("sounds/tom-3.mp3"); tom1.play(); break; case "D": var tom1 = new Audio("sounds/tom-4.mp3"); tom1.play(); break; case "E": var tom1 = new Audio("sounds/crash.mp3"); tom1.play(); break; case "F": var tom1 = new Audio("sounds/kick-bass.mp3"); tom1.play(); break; case "G": var tom1 = new Audio("sounds/snare.mp3"); tom1.play(); break; default:console.log(buttonInnerHTML); } } function buttonAnimation(currentkey){ var activeButton = document.querySelector("."+currentkey); activeButton.classList.add("pressed"); setTimeout(function(){ activeButton.classList.remove("pressed"); }, 100); }
const { describe, it } = require('mocha'); const { expect } = require('chai'); const fs = require('fs'); const sinon = require('sinon'); const fileUtil = require('../../app/utils/fileUtil'); describe('fileUtil methods', () => { it('createMenuFile(): should create a menu.pug file', (done) => { const writeStub = sinon.stub(fs, 'writeFile'); const menus = [ { uri: 'tshirts', name: 'T-Shirts' }, { uri: 'shoes', name: 'Shoes' }, { uri: 'jackets', name: 'Jackets' }, ]; fileUtil.createMenuFile(menus); const { args } = writeStub.getCall(0); expect(args.length).to.be.equal(3); // Three arguments: path, content, callback expect(args[0]).to.be.equal('./app/views/includes/menu.pug'); // path is fixed // content should looks like below expect(args[1]).to.be.equal( "li\n a(href='/categories/tshirts') T-Shirts\n" + "li\n a(href='/categories/shoes') Shoes\n" + "li\n a(href='/categories/jackets') Jackets\n", ); writeStub.restore(); done(); }); });
import history from '../utils/history' export const like = courseId => ({ type: 'LIKE', courseId }) export const goComment = id => { history.push(`/c/${id}`) return { type: 'GO_COMMENT' } } export const deleteCmt = id => ({ type: 'DELETE_COMMENT', id }) export const addComment = comment => ({ type: 'ADD_COMMENT', comment })
/** classe para executar animações. **/ function Animate(){ this.speed = 250; /** - fadeOut Esconde um objeto; [arg1] Div _div - Div que irá animar. [arg2] Function _callBack - O que fazer quando finalizar a animação. [arg3] Number _speed - Velocidade da animação (se não definida, segue o padrão). **/ this.fadeOut = function(_div, _callBack, _speed){ var _objectJQuery = _div.getjQueryObject(); _callBack = _callBack || function(){}; _speed = _speed || this.speed; if(main.isMobile) _speed = 1; _objectJQuery.animate({ opacity: 0 }, _speed, function(){ _objectJQuery.css("display", "none"); _callBack(); }); } /** - fadeIn Mostra um objeto; [arg1] Div _div - Div que irá animar. [arg2] Function _callBack - O que fazer quando finalizar a animação. [arg3] Number _speed - Velocidade da animação (se não definida, segue o padrão). **/ this.fadeIn = function(_div, _callBack, _speed){ var _objectJQuery = _div.getjQueryObject(); _callBack = _callBack || function(){}; _speed = _speed || this.speed; if(main.isMobile) _speed = 1; _objectJQuery.css("display", "block"); _objectJQuery.animate({ opacity: 1}, _speed, function(){ _callBack() } ); } }
import React from "react" export default class Toast extends React.Component{ render(){ let bg = this.props.bgColor let text = this.props.textColor let cn = `toast align-items-center text-${text} bg-${bg} border-0` return ( <div className="position-fixed bottom-0 end-0" style={{zIndex:5}}> <div className={cn} id={this.props.id} role="alert" aria-live="polite" aria-atomic="true" data-bs-delay="10000"> <div className="d-flex"> <div className="toast-body"> {this.props.children} </div> </div> </div> </div> ); } }
// libraries import React from 'react'; import styled from 'styled-components'; // styled elements import Grid from './../elements/Grid'; import g from './../js/global'; // textures import img_headline from './../assets/textures/games01.jpeg'; import img_pic2 from './../assets/textures/games02.jpeg'; import img_pic3 from './../assets/textures/games03.jpeg'; import img_pic4 from './../assets/textures/games04.jpeg'; import icn_sword from './../assets/textures/sword.png'; import icn_target from './../assets/textures/target.png'; import icn_shield from './../assets/textures/shield.png'; const Home = () => { const ImageContainer = styled.div` overflow:hidden; `; const HeadlineImage = styled.img` width: 100%; margin:-20% 0; filter: grayscale(50%); `; const HeadlineText = styled.div` height: 200px; width: 100%; background-image: linear-gradient(rgb(30, 30, 30), rgb(25, 25, 25), rgb(10, 10, 10)); text-align: center; color: white; h1 { position: relative; top: 50%; transform: translateY(-50%); } `; const GridContainerContainer = styled.div` background-color: ${g.BGColor2}; `; const GridContainerContainer2 = styled.div` position: relative; overflow: hidden; `; const BGImage = styled.div` background-image: url(${img_pic4}); width: 100%;; height: 100%;; position: absolute; z-index: -1; `; const GridContainer = styled(Grid.Container)` width: 80%; margin: auto; @media ${g.Sizes.M} { width: 100%; } @media ${g.Sizes.S} { width: 100%; display: block; padding: 0px; } `; const GridItem1 = styled(Grid.Item)` color: ${g.BodyFColor}; h2 { position: relative; top: 40%; transform: translateY(-50%); text-align: center; } img { width: 100%; } @media ${g.Sizes.S} { h2 { position: unset; top: unset; transform: unset; } } `; const GridItem2 = styled(Grid.Item)` color: ${g.BodyFColor}; padding: 50px; background-color: rgba(0, 0, 0, 0.9); border-radius: 20px; text-align: center; img { width: 100px; } h1 { padding: 10px; font-weight: 400; } @media ${g.Sizes.M} { padding: 20px; } @media ${g.Sizes.S} { border-radius: 0; &:nth-child(odd) { background-color: rgba(30, 30, 30, 0.9); } } `; return ( <body> <div> <ImageContainer> <HeadlineImage src={img_headline} alt="" /> </ImageContainer> <HeadlineText> <h1> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Dolor ullam corporis fugiat. </h1> </HeadlineText> </div> {/* ======================================== */} <GridContainerContainer> <GridContainer columns={2} gap={20}> <GridItem1> <img src={img_pic2} alt="" /> </GridItem1> <GridItem1> <h2> Lorem ipsum dolor, sit amet consectetur adipisicing elit. </h2> </GridItem1> <GridItem1> <h2> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Qui non sapiente distinctio? Est, officia accusamus! </h2> </GridItem1> <GridItem1> <img src={img_pic3} alt="" /> </GridItem1> </GridContainer> </GridContainerContainer> {/* ======================================== */} <GridContainerContainer2> <BGImage></BGImage> <GridContainer columns={3} gap={20} padding={50}> <GridItem2> <img src={icn_sword} alt="" /> <h1>Lorem ipsum dolor sit amet consectetur adipisicing elit. culpa ex ipsum deserunt tempore dolor illum, alias veritatis dolore ea, optio minima perferendis error voluptatum repellat explicabo cupiditate officia consequuntur.</h1> </GridItem2> <GridItem2> <img src={icn_target} alt="" /> <h1>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quis recusandae itaque illum laboriosam ipsam architecto!</h1> <h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi vitae recusandae commodi?</h1> <h1>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nobis, veritatis?</h1> </GridItem2> <GridItem2> <img src={icn_shield} alt="" /> <h1>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas sapiente, nesciunt doloremque in voluptate quisquam totam magni, ad dolor, architecto quibusdam cum similique?</h1> <h1>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nobis, voluptate?</h1> </GridItem2> </GridContainer> </GridContainerContainer2> </body> ) } export default Home
async function showAvatar() { // запрашиваем JSON с данными пользователя let response = await fetch('/article/promise-chaining/user.json'); let user = await response.json(); // запрашиваем информацию об этом пользователе из github let githubResponse = await fetch(`https://api.github.com/users/${user.name}`); let githubUser = await githubResponse.json(); // отображаем аватар пользователя let img = document.createElement('img'); img.src = githubUser.avatar_url; img.className = "promise-avatar-example"; document.body.append(img); // ждём 3 секунды и затем скрываем аватар await new Promise((resolve, reject) => setTimeout(resolve, 3000)); img.remove(); return githubUser; } showAvatar(); // async function loadJson(url) { // let response = await fetch(url) // if (response.status == 200) { // let json = await response.json() // return json // } // throw new Error(response.status) // } // loadJson('no-such-user.json').catch(alert) class HttpError extends Error { constructor(response) { super(`${response.status} for ${response.url}`); this.name = 'HttpError'; this.response = response; } } async function loadJson(url) { let response = await fetch(url) if (response.status == 200) { return response.json() } else { throw new HttpError(response); } } async function demoGithubUser() { let user while (true) { let name = prompt('Enter login', 'iliakan') try { user = await loadJson(`https://api.github.com/users/${name}`) break; } catch (err) { if (err instanceof HttpError && err.response.status == 404) { alert("Такого пользователя не существует, пожалуйста, повторите ввод.") } else { throw err } } } alert(`Полное имя: ${user.name}`) return user } demoGithubUser() let range = { from: 1, to: 5, // for await..of вызывает этот метод один раз в самом начале [Symbol.asyncIterator]() { // (1) // ...возвращает объект-итератор: // далее for await..of работает только с этим объектом, // запрашивая у него следующие значения вызовом next() return { current: this.from, last: this.to, // next() вызывается на каждой итерации цикла for await..of async next() { // (2) // должен возвращать значение как объект {done:.., value :...} // (автоматически оборачивается в промис с помощью async) // можно использовать await внутри для асинхронности: await new Promise(resolve => setTimeout(resolve, 1000)); // (3) if (this.current <= this.last) { return { done: false, value: this.current++ }; } else { return { done: true }; } } }; } }; (async () => { for await (let value of range) { // (4) alert(value); // 1,2,3,4,5 } })()
class Sling{ constructor(bodyA,bodyB,offsetX,offsetY ){ this.offsetX=offsetX this.offsetY=offsetY var options ={ bodyA:bodyA, bodyB:bodyB, pointB:{x:this.offsetX,y:this.offsetY} } // this.pointB=pointB; this.rope=Matter.Constraint.create(options); World.add(world,this.rope); } display(){ var pA=this.rope.bodyA.position; var pB=this.rope.bodyB.position; var Anchor1X=pA.x var Anchor1Y=pA.y var Anchor2X=pB.x+this.offsetX var Anchor2Y=pB.y+this.offsetY strokeWeight(4); stroke(0); line(Anchor1X,Anchor1Y,Anchor2X,Anchor2Y); } }
import React from 'react'; import { fireEvent } from '@testing-library/react'; import FilterBox from '../FilterBox'; import { initialState as filtersInitialState } from './../../../redux/reducers/filters'; import { initialState as townInitialState } from './../../../redux/reducers/town'; import { renderRedux } from '../../../utils/test'; /** * this component manages Filter mode (Filter Setter o FilterApply ) */ const props = { filteredUsersNumber: 1000, }; const initialState = { filters: filtersInitialState, town: townInitialState, }; describe('FilterBox Component tests', () => { it('FilterBox Snapshot', () => { expect( renderRedux(<FilterBox {...props} />, { initialState: initialState, }).baseElement ).toMatchSnapshot(); }); it('FilterBox when !isAnyFilterApplied && !filteringMode show not paint FiltersApplied nor FilterSetter', () => { const { queryByTestId } = renderRedux( <FilterBox filteredUsersNumber={1000} isAnyFilterApplied={false} filteringMode={false} />, { initialState: initialState, } ); expect(queryByTestId('FiltersApplied')).toBeFalsy(); expect(queryByTestId('FilterSetter')).toBeFalsy(); }); it('FilterBox when !isAnyFilterApplied && filteringMode should paint Filters Applied', () => { const { queryByTestId } = renderRedux( <FilterBox filteredUsersNumber={1000} isAnyFilterApplied={false} filteringMode={true} />, { initialState: initialState, } ); expect(queryByTestId('FiltersApplied')).toBeFalsy(); expect(queryByTestId('FilterSetter')).toBeTruthy(); }); it('FilterBox when isAnyFilterApplied && !filteringMode should paint Filters Applied', () => { const { queryByTestId } = renderRedux( <FilterBox filteredUsersNumber={1000} isAnyFilterApplied={true} filteringMode={false} />, { initialState: initialState, } ); expect(queryByTestId('FiltersApplied')).toBeTruthy(); expect(queryByTestId('FilterSetter')).toBeFalsy(); }); it('FilterBox when isAnyFilterApplied && filteringMode should paint Filters Applied', () => { const { queryByTestId } = renderRedux( <FilterBox filteredUsersNumber={1000} isAnyFilterApplied={true} filteringMode={false} />, { initialState: initialState, } ); expect(queryByTestId('FiltersApplied')).toBeTruthy(); expect(queryByTestId('FilterSetter')).toBeFalsy(); }); it('FilterBox when press filter icon button should call prop setFilteringMode', () => { const setFilteringMode = jest.fn(); const { container } = renderRedux( <FilterBox filteredUsersNumber={1000} isAnyFilterApplied={true} filteringMode={false} setFilteringMode={setFilteringMode} />, { initialState: initialState, } ); expect(setFilteringMode).toHaveBeenCalledTimes(0); const button = container.querySelector('button'); fireEvent.click(button); expect(setFilteringMode).toHaveBeenCalledTimes(1); }); });
/* ---------------------------------------------------- +/ ## Locations ## All code related to the Locations collection goes here. /+ ---------------------------------------------------- */ Locations = new Meteor.Collection('locations'); // Allow/Deny Locations.allow({ insert: function(userId, doc){ return can.createLocation(userId); }, update: function(userId, doc, fieldNames, modifier){ return can.editLocation(userId, doc); }, remove: function(userId, doc){ return can.removeLocation(userId, doc); } }); // Methods Meteor.methods({ createLocation: function(location){ if(can.createLocation(Meteor.user())) Locations.insert(location); }, removeLocation: function(location){ if(can.removeLocation(Meteor.user(), location)){ Locations.remove(location._id); }else{ throw new Meteor.Error(403, 'You do not have the rights to delete this location.') } } });
import React from "react"; import "./styles.css"; import PropTypes from "prop-types"; import MaterialTitlePanel from "./material_title_panel"; const styles = { sidebar: { width: 256, height: "100%" }, sidebarLink: { display: "block", padding: "16px 0px", color: "#757575", textDecoration: "none" }, divider: { margin: "8px 0", height: 1, backgroundColor: "#757575" }, content: { padding: "16px", height: "100vh", backgroundColor: "white" } }; class Categories extends React.Component { state = { data: [], page: 1, totalPages: null, sizeOfPost: 25, sidebarOpen: false }; onSetSidebarOpen = open => { this.setState({ sidebarOpen: open }); }; fetchPost() { const URL = `https://public-api.wordpress.com/rest/v1.1/sites/truecaller.blog/categories`; fetch(URL) .then(function(response) { return response.json(); }) .then(x => { this.setState({ data: x.categories }); }); } componentDidMount() { this.fetchPost(); } render() { const style = this.props.style ? { ...styles.sidebar, ...this.props.style } : styles.sidebar; return ( <MaterialTitlePanel title="Menu" style={style}> <div style={styles.content}> <div style={styles.divider} /> {this.state.data.map((e, i) => ( <a key={i} href="#" style={styles.sidebarLink}> {e.name} </a> ))} </div> </MaterialTitlePanel> ); } } Categories.propTypes = { style: PropTypes.object }; export default Categories;
//comment my first java Script code console.log('Hello Vik JS in separate file'); let name = 'Vik'; //string literal console.log(name); //cannot be reserved keyword //should be meaningful //cannot start with a number //cannot contain space or hyphen(-) //are cse-sensitive //use camelCase let firstName ='Victoria'; let lastName ='Gontarik'; console.log(firstName,lastName); const interestRate = 0.3; console.log(interestRate); let age=38; //number literal let isApproved=true; //boolean literal let isDeclined =false; let selectedColor=null; //when we want to clear the vlue of the var let selectedType = undefined; var addition=4+4; console.log(addition); let addStrings= "4" + "4"; console.log(addStrings); let subtruct= 1299354454-128; console.log(subtruct); let multipl=12*100 console.log(multipl); let div= 500/10 console.log(div); let x = 5; let y = 2; let modulus = x % y; console.log(modulus);
import Vue from 'vue' import Router from 'vue-router' import Dashboard from './views/Dashboard.vue' import Power from './views/Power.vue' import Water from './views/Water.vue' import NGas from './views/NGas.vue' Vue.use(Router) export default new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/', name: 'dashboard', component: Dashboard }, { path: '/power', name: 'power', component: Power }, { path: '/water', name: 'water', component: Water }, { path: '/ngas', name: 'ngas', component: NGas } ] })
import React, { Component } from 'react'; import GirlImage from "../components/GirlImg.js"; import axios from "../axios"; import NavBar from "../components/navBar.js"; class DetailScreen extends Component { constructor(props){ super(props); this.state = { comment: [], newComment: "", images: "" } this.commentText = this.commentText.bind(this); } componentDidMount() { axios.get(`/api/images/${this.props.match.params.imageId}`) .then(data => { console.log(data.data); this.setState({ images: data.data, }) }) .catch(err => console.error(err)); } onSearchChange = text => this.setState({search: text}); commentText(e) { console.log(e.target.value) this.setState({ comment: e.target.value }) } onKeyUp(e) { let text = e.target.value; if(e.keyCode === 13){ if(!text) return; text = text.trim(); if(!text) return; axios.post(`/${this.state.images.imageId}/comments`) } } render() { return ( <div className=""> <NavBar onSearchChange={this.onSearchChange} username={this.props.username} onLogin={this.props.onLogin}/> <div className="main_content container"> <div className="row"> <div className="col-6 mr-auto ml-auto"> { this.state.images ? <GirlImage img={this.state.images} /> : '' } <input type="text" className="form-control" onChange={this.commentText} onKeyUp={this.addComment} /> </div> </div> </div> </div> ); } } export default DetailScreen;