text
stringlengths
7
3.69M
import get from 'lodash.get'; import { readFile, writeFile, exists } from './lib/fs'; /** * Compiles the project from source files into a distributable * format and copies it to the output (build) folder. */ const setRoute = (router, type, value) => { router = router.replace( new RegExp(`// import routes from '([^']*)'; // ${type}`), ($0, $1) => `import routes from '${$1}'; // ${type}`, ); if (!value) { router = router.replace( new RegExp(`import routes from '([^']*)'; // ${type}`), ($0, $1) => `// import routes from '${$1}'; // ${type}`, ); } return router; }; async function route() { const args = process.argv.splice(2); let routeValue; for (let i = 0; i < args.length; i++) { const arg = args[i]; const matches = arg.match(/--route=(.*)/); if (matches) { routeValue = get(matches, '[1]', 'production'); break; } } if (routeValue) { if (routeValue === 'dev') { const path = 'src/routes/index.dev.js'; if (!await exists(path)) { const content = await readFile('tools/devTemplate.txt'); await writeFile(path, content); } else { let content = await readFile(path); if (/- www\.react\w*\.com/.test(content)) { content = content.replace(/- www.react\w*.com/g, ''); await writeFile(path, content); } } } const url = 'src/router.js'; let router = await readFile(url); router = setRoute(router, 'production', routeValue === 'production'); router = setRoute(router, 'dev', routeValue === 'dev'); router = setRoute(router, 'api', routeValue === 'api'); await writeFile(url, router); } } export default route;
// Place your application-specific JavaScript functions and classes here // This file is automatically included by javascript_include_tag :defaults $(document).ready(function() { setTimeout(hideFlashMessages, 3000); }); function hideFlashMessages() { $('p#notice, p#warning, p#error').fadeOut(2000) }
import { postJSON } from '@lodgify/fetch-helpers'; import { ORIGIN } from '../constants'; import { getUrl } from '../utils/getUrl'; import { setFunctionName } from '../utils/setFunctionName'; import { PATHNAME, RESOURCE_NAME } from './constants'; import { getAdaptedPath } from './utils/getAdaptedPath'; import { getAdaptedHost } from './utils/getAdaptedHost'; /** * @param {string} host * @param {string} path * @param {string} cookie * @return {Promise} */ export const post = (host, path, cookie) => { const url = getUrl(ORIGIN, PATHNAME); const adaptedPath = getAdaptedPath(path); const adaptedHost = getAdaptedHost(host); return postJSON( url, { host: adaptedHost, path: adaptedPath, }, { Cookie: cookie } ); }; setFunctionName(post, RESOURCE_NAME);
import React, { Component } from 'react'; import { useState, useEffect } from 'react'; const Recipes = (props) => { const [top, setTop] = useState(12); return ( <div className=" container mx-auto relative"> <img src="../slike/slika1.png" className="w-24 rounded-full h-auto" alt="" /> </div> ); }; export default Recipes;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const CsvReader_1 = require("./CsvReader"); const utils_1 = require("./utils"); class MatchFormatter { constructor(reader, matches) { this.reader = reader; this.matches = matches; } // Static methods are methods that can be run without a new instance of a class static async fromCSV(file) { return await new MatchFormatter(new CsvReader_1.CsvReader(file)).run(); } async run(type) { const reader = await this.reader.read(); this.matches = reader.data.map(this.formatData); return this; } formatData(row) { return [ utils_1.parseDate(row[0]), row[1], row[2], parseInt(row[3], 10), parseInt(row[4], 10), row[5], row[6], ]; } } exports.MatchFormatter = MatchFormatter; // tslint:disable-next-line: max-classes-per-file class WinsAnalyzer { constructor(team, matches) { this.team = team; this.matches = matches; this.wins = 0; this.losses = 0; this.draws = 0; this.result = ""; } run(type) { switch (type) { case "losses": if (this.matches) { let tempLosses = 0; for (const match of this.matches) { if (match[1] === this.team && match[5] === utils_1.Winner.away) { tempLosses++; } else if (match[2] === this.team && match[5] === utils_1.Winner.home) { tempLosses++; } } this.losses = tempLosses; this.result = `${this.team} lost ${this.losses} matches this season`; } return this; case "draws": if (this.matches) { let tempDraws = 0; for (const match of this.matches) { if (match[1] === this.team && match[5] === utils_1.Winner.draw) { tempDraws++; } else if (match[2] === this.team && match[5] === utils_1.Winner.draw) { tempDraws++; } } this.draws = tempDraws; this.result = `${this.team} has ${this.draws} matches ending with a draw`; } return this; default: if (this.matches) { let tempWins = 0; for (const match of this.matches) { if (match[1] === this.team && match[5] === utils_1.Winner.home) { tempWins++; } else if (match[2] === this.team && match[5] === utils_1.Winner.away) { tempWins++; } } this.wins = tempWins; this.result = `${this.team} won ${this.wins} matches this season`; } return this; } } } exports.WinsAnalyzer = WinsAnalyzer; // tslint:disable-next-line: max-classes-per-file class GoalsAnalyzer { constructor(team, matches) { this.team = team; this.matches = matches; this.goalsFor = 0; this.goalsAgainst = 0; this.goalDiff = 0; } run(type) { return this; } } exports.GoalsAnalyzer = GoalsAnalyzer;
var asyncDemo = require('./async-demo'); console.log('------------ Sync --------------') asyncDemo.runSync(); console.log('------------ Async --------------') asyncDemo.runAsync();
// display the base map mapboxgl.accessToken = 'pk.eyJ1IjoiYWxleHlzaHUyMjYiLCJhIjoiY2puMzl0bzRrMmR5eDNwcXZ6YTk1b2x4MSJ9.YExeZS4oHiM3y4zZtiWO7g'; const map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/alexyshu226/cjvgs9wdh0eki1fqmvaycd9vs', center: [-0.127,51.517], zoom: 10.75 }); // categories and color palette var categories = [ 'Italian','Chinese','Indian','Japanese_Korean','Pakistani','Southeast_Asian','Mediterranean','Middle_Eastern','French','American','European_Other','African','Latin_American','Other' ]; var colors = ['#fc9977','#fcbd90','#b48d6c','#bd6666','#a3d96a','#80d996','#57cfc9','#51c0db','#54a2ab','#70a5d4','#6d74cf','#584478','#e1afbe','#debb59'] // category info and borough info var cat = { "African": { "max": 21, "mean": 4.333333333, "total": 143 }, "American": { "max": 74, "mean": 10.57575758, "total": 349 }, "Chinese": { "max": 179, "mean": 26.60606061, "total": 878 }, "European_Other": { "max": 72, "mean": 12.18181818, "total": 402 }, "French": { "max": 109, "mean": 10.72727273, "total": 354 }, "Indian": { "max": 81, "mean": 29.03030303, "total": 958 }, "Italian": { "max": 332, "mean": 47.15151515, "total": 1556 }, "Japanese_Korean": { "max": 173, "mean": 19.63636364, "total": 648 }, "Latin_American": { "max": 74, "mean": 14.90909091, "total": 492 }, "Mediterranean": { "max": 110, "mean": 23.57575758, "total": 778 }, "Middle_Eastern": { "max": 93, "mean": 8.272727273, "total": 273 }, "Other": { "max": 34, "mean": 4.272727273, "total": 141 }, "Pakistani": { "max": 41, "mean": 15.09090909, "total": 498 }, "Southeast_Asian": { "max": 104, "mean": 18.42424242, "total": 608 } }; var brgh = { "Westminster": { "Italian": 22.17768871, "Chinese": 11.95724783, "Indian": 5.410821643, "Japanese_Korean": 11.55644623, "Pakistani": 2.738810955, "Southeast_Asian": 6.947227789, "Mediterranean": 7.348029392, "Middle_Eastern": 6.21242485, "French": 7.281229125, "American": 4.943219773, "European_Other": 4.809619238, "African": 1.402805611, "Latin_American": 4.943219773, "Other": 2.271209085 }, "Camden": { "Italian": 21.68508287, "Chinese": 9.806629834, "Indian": 9.392265193, "Japanese_Korean": 12.15469613, "Pakistani": 3.729281768, "Southeast_Asian": 7.872928177, "Mediterranean": 11.60220994, "Middle_Eastern": 2.348066298, "French": 4.696132597, "American": 2.900552486, "European_Other": 4.834254144, "African": 1.243093923, "Latin_American": 5.939226519, "Other": 1.79558011 }, "Islington": { "Italian": 20.39473684, "Chinese": 6.359649123, "Indian": 7.894736842, "Japanese_Korean": 8.333333333, "Pakistani": 3.728070175, "Southeast_Asian": 11.18421053, "Mediterranean": 13.81578947, "Middle_Eastern": 1.754385965, "French": 5.48245614, "American": 2.850877193, "European_Other": 3.947368421, "African": 3.070175439, "Latin_American": 9.210526316, "Other": 1.973684211 }, "Hackney": { "Italian": 12.72084806, "Chinese": 8.127208481, "Indian": 9.187279152, "Japanese_Korean": 5.653710247, "Pakistani": 1.766784452, "Southeast_Asian": 13.07420495, "Mediterranean": 18.3745583, "Middle_Eastern": 1.413427562, "French": 3.886925795, "American": 5.653710247, "European_Other": 4.240282686, "African": 3.180212014, "Latin_American": 11.30742049, "Other": 1.413427562 }, "Hammersmith and Fulham": { "Italian": 22.60273973, "Chinese": 8.904109589, "Indian": 8.219178082, "Japanese_Korean": 7.876712329, "Pakistani": 4.452054795, "Southeast_Asian": 12.32876712, "Mediterranean": 8.904109589, "Middle_Eastern": 6.164383562, "French": 1.712328767, "American": 4.109589041, "European_Other": 6.849315068, "African": 1.712328767, "Latin_American": 4.452054795, "Other": 1.712328767 }, "Tower Hamlets": { "Italian": 11.5902965, "Chinese": 9.433962264, "Indian": 18.86792453, "Japanese_Korean": 7.277628032, "Pakistani": 10.2425876, "Southeast_Asian": 8.086253369, "Mediterranean": 12.39892183, "Middle_Eastern": 1.886792453, "French": 2.425876011, "American": 4.851752022, "European_Other": 3.773584906, "African": 1.347708895, "Latin_American": 5.121293801, "Other": 2.69541779 }, "Southwark": { "Italian": 18.18181818, "Chinese": 11.81818182, "Indian": 11.51515152, "Japanese_Korean": 5.757575758, "Pakistani": 4.848484848, "Southeast_Asian": 9.090909091, "Mediterranean": 9.696969697, "Middle_Eastern": 1.818181818, "French": 4.848484848, "American": 3.03030303, "European_Other": 6.666666667, "African": 3.636363636, "Latin_American": 7.878787879, "Other": 1.212121212 }, "Kensington and Chelsea": { "Italian": 29.56730769, "Chinese": 4.326923077, "Indian": 5.288461538, "Japanese_Korean": 9.134615385, "Pakistani": 3.605769231, "Southeast_Asian": 6.25, "Mediterranean": 8.173076923, "Middle_Eastern": 5.769230769, "French": 7.932692308, "American": 6.25, "European_Other": 5.288461538, "African": 1.682692308, "Latin_American": 3.846153846, "Other": 2.884615385 }, "Lambeth": { "Italian": 15.06849315, "Chinese": 9.315068493, "Indian": 9.589041096, "Japanese_Korean": 7.671232877, "Pakistani": 4.109589041, "Southeast_Asian": 6.575342466, "Mediterranean": 6.575342466, "Middle_Eastern": 2.191780822, "French": 3.287671233, "American": 4.383561644, "European_Other": 9.589041096, "African": 4.931506849, "Latin_American": 15.61643836, "Other": 1.095890411 }, "City of London": { "Italian": 24.75570033, "Chinese": 5.211726384, "Indian": 6.51465798, "Japanese_Korean": 19.21824104, "Pakistani": 2.931596091, "Southeast_Asian": 7.817589577, "Mediterranean": 4.885993485, "Middle_Eastern": 0.977198697, "French": 5.863192182, "American": 4.885993485, "European_Other": 5.863192182, "African": 0.325732899, "Latin_American": 9.446254072, "Other": 1.302931596 }, "Wandsworth": { "Italian": 20.94594595, "Chinese": 12.16216216, "Indian": 16.55405405, "Japanese_Korean": 5.405405405, "Pakistani": 9.459459459, "Southeast_Asian": 7.77027027, "Mediterranean": 3.716216216, "Middle_Eastern": 2.364864865, "French": 5.067567568, "American": 4.054054054, "European_Other": 4.72972973, "African": 1.013513514, "Latin_American": 5.405405405, "Other": 1.351351351 }, "Richmond upon Thames": { "Italian": 31.66666667, "Chinese": 7.222222222, "Indian": 12.22222222, "Japanese_Korean": 5.555555556, "Pakistani": 5.555555556, "Southeast_Asian": 10, "Mediterranean": 6.666666667, "Middle_Eastern": 1.666666667, "French": 5, "American": 5, "European_Other": 4.444444444, "African": 0.555555556, "Latin_American": 2.222222222, "Other": 2.222222222 }, "Hounslow": { "Italian": 13.28671329, "Chinese": 9.79020979, "Indian": 26.57342657, "Japanese_Korean": 2.797202797, "Pakistani": 9.79020979, "Southeast_Asian": 11.18881119, "Mediterranean": 4.895104895, "Middle_Eastern": 2.797202797, "French": 4.195804196, "American": 5.594405594, "European_Other": 4.195804196, "African": 0.699300699, "Latin_American": 2.097902098, "Other": 2.097902098 }, "Lewisham": { "Italian": 12.25806452, "Chinese": 16.77419355, "Indian": 16.77419355, "Japanese_Korean": 1.290322581, "Pakistani": 10.32258065, "Southeast_Asian": 9.677419355, "Mediterranean": 10.96774194, "Middle_Eastern": 0.64516129, "French": 2.580645161, "American": 3.225806452, "European_Other": 4.516129032, "African": 3.870967742, "Latin_American": 5.806451613, "Other": 1.290322581 }, "Barnet": { "Italian": 17.59259259, "Chinese": 15.27777778, "Indian": 11.11111111, "Japanese_Korean": 9.259259259, "Pakistani": 9.722222222, "Southeast_Asian": 6.481481481, "Mediterranean": 13.42592593, "Middle_Eastern": 4.62962963, "French": 1.851851852, "American": 3.240740741, "European_Other": 2.314814815, "African": 1.851851852, "Latin_American": 2.777777778, "Other": 0.462962963 }, "Croydon": { "Italian": 16.86746988, "Chinese": 16.86746988, "Indian": 12.04819277, "Japanese_Korean": 1.807228916, "Pakistani": 8.43373494, "Southeast_Asian": 6.626506024, "Mediterranean": 9.036144578, "Middle_Eastern": 1.204819277, "French": 2.409638554, "American": 4.21686747, "European_Other": 4.21686747, "African": 1.807228916, "Latin_American": 12.65060241, "Other": 1.807228916 }, "Ealing": { "Italian": 10.34482759, "Chinese": 6.896551724, "Indian": 21.26436782, "Japanese_Korean": 5.172413793, "Pakistani": 14.94252874, "Southeast_Asian": 5.747126437, "Mediterranean": 9.195402299, "Middle_Eastern": 8.045977011, "French": 2.298850575, "American": 2.873563218, "European_Other": 6.32183908, "African": 0.574712644, "Latin_American": 2.873563218, "Other": 3.448275862 }, "Newham": { "Italian": 12.23021583, "Chinese": 13.66906475, "Indian": 28.05755396, "Japanese_Korean": 4.316546763, "Pakistani": 5.035971223, "Southeast_Asian": 6.474820144, "Mediterranean": 7.913669065, "Middle_Eastern": 0.71942446, "French": 0.71942446, "American": 5.035971223, "European_Other": 4.316546763, "African": 2.158273381, "Latin_American": 7.913669065, "Other": 1.438848921 }, "Merton": { "Italian": 17.29323308, "Chinese": 17.29323308, "Indian": 11.27819549, "Japanese_Korean": 9.77443609, "Pakistani": 8.270676692, "Southeast_Asian": 6.015037594, "Mediterranean": 5.263157895, "Middle_Eastern": 3.007518797, "French": 2.255639098, "American": 4.511278195, "European_Other": 6.015037594, "African": 0.751879699, "Latin_American": 7.518796992, "Other": 0.751879699 }, "Waltham Forest": { "Italian": 15.78947368, "Chinese": 20, "Indian": 11.57894737, "Japanese_Korean": 2.105263158, "Pakistani": 11.57894737, "Southeast_Asian": 8.421052632, "Mediterranean": 10.52631579, "Middle_Eastern": 1.052631579, "French": 2.105263158, "American": 3.157894737, "European_Other": 4.210526316, "African": 2.105263158, "Latin_American": 6.315789474, "Other": 1.052631579 }, "Brent": { "Italian": 10.49382716, "Chinese": 9.87654321, "Indian": 24.69135802, "Japanese_Korean": 3.703703704, "Pakistani": 12.96296296, "Southeast_Asian": 4.320987654, "Mediterranean": 6.172839506, "Middle_Eastern": 8.641975309, "French": 0, "American": 1.851851852, "European_Other": 6.790123457, "African": 2.469135802, "Latin_American": 7.407407407, "Other": 0.617283951 }, "Sutton": { "Italian": 20.89552239, "Chinese": 17.91044776, "Indian": 11.94029851, "Japanese_Korean": 2.985074627, "Pakistani": 13.43283582, "Southeast_Asian": 10.44776119, "Mediterranean": 8.955223881, "Middle_Eastern": 0, "French": 1.492537313, "American": 5.970149254, "European_Other": 4.47761194, "African": 0, "Latin_American": 1.492537313, "Other": 0 }, "Haringey": { "Italian": 15.16853933, "Chinese": 10.6741573, "Indian": 11.23595506, "Japanese_Korean": 5.056179775, "Pakistani": 3.370786517, "Southeast_Asian": 3.93258427, "Mediterranean": 24.15730337, "Middle_Eastern": 1.685393258, "French": 3.93258427, "American": 4.494382022, "European_Other": 6.741573034, "African": 3.370786517, "Latin_American": 5.056179775, "Other": 1.123595506 }, "Greenwich": { "Italian": 11.71171171, "Chinese": 16.21621622, "Indian": 12.61261261, "Japanese_Korean": 7.207207207, "Pakistani": 9.009009009, "Southeast_Asian": 5.405405405, "Mediterranean": 6.306306306, "Middle_Eastern": 1.801801802, "French": 3.603603604, "American": 7.207207207, "European_Other": 4.504504505, "African": 2.702702703, "Latin_American": 8.108108108, "Other": 3.603603604 }, "Kingston upon Thames": { "Italian": 19.31818182, "Chinese": 13.63636364, "Indian": 12.5, "Japanese_Korean": 21.59090909, "Pakistani": 11.36363636, "Southeast_Asian": 6.818181818, "Mediterranean": 3.409090909, "Middle_Eastern": 2.272727273, "French": 1.136363636, "American": 5.681818182, "European_Other": 0, "African": 1.136363636, "Latin_American": 1.136363636, "Other": 0 }, "Bromley": { "Italian": 22.95081967, "Chinese": 17.21311475, "Indian": 14.75409836, "Japanese_Korean": 1.639344262, "Pakistani": 10.6557377, "Southeast_Asian": 4.098360656, "Mediterranean": 10.6557377, "Middle_Eastern": 0, "French": 3.278688525, "American": 4.098360656, "European_Other": 4.918032787, "African": 0.819672131, "Latin_American": 3.278688525, "Other": 1.639344262 }, "Hillingdon": { "Italian": 23.02158273, "Chinese": 13.66906475, "Indian": 22.30215827, "Japanese_Korean": 3.597122302, "Pakistani": 8.633093525, "Southeast_Asian": 3.597122302, "Mediterranean": 7.913669065, "Middle_Eastern": 2.158273381, "French": 2.877697842, "American": 5.035971223, "European_Other": 2.877697842, "African": 0, "Latin_American": 2.877697842, "Other": 1.438848921 }, "Redbridge": { "Italian": 9, "Chinese": 20, "Indian": 18, "Japanese_Korean": 2, "Pakistani": 21, "Southeast_Asian": 4, "Mediterranean": 10, "Middle_Eastern": 7, "French": 1, "American": 4, "European_Other": 3, "African": 0, "Latin_American": 0, "Other": 1 }, "Harrow": { "Italian": 13.1147541, "Chinese": 9.836065574, "Indian": 40.98360656, "Japanese_Korean": 0.819672131, "Pakistani": 8.196721311, "Southeast_Asian": 2.459016393, "Mediterranean": 9.016393443, "Middle_Eastern": 4.098360656, "French": 2.459016393, "American": 2.459016393, "European_Other": 2.459016393, "African": 0.819672131, "Latin_American": 1.639344262, "Other": 1.639344262 }, "Havering": { "Italian": 23.72881356, "Chinese": 18.6440678, "Indian": 18.6440678, "Japanese_Korean": 0, "Pakistani": 11.86440678, "Southeast_Asian": 5.084745763, "Mediterranean": 6.779661017, "Middle_Eastern": 0, "French": 0, "American": 5.084745763, "European_Other": 5.084745763, "African": 0, "Latin_American": 3.389830508, "Other": 1.694915254 }, "Enfield": { "Italian": 17.17171717, "Chinese": 10.1010101, "Indian": 14.14141414, "Japanese_Korean": 0, "Pakistani": 12.12121212, "Southeast_Asian": 2.02020202, "Mediterranean": 30.3030303, "Middle_Eastern": 2.02020202, "French": 3.03030303, "American": 3.03030303, "European_Other": 3.03030303, "African": 1.01010101, "Latin_American": 2.02020202, "Other": 0 }, "Bexley": { "Italian": 19.71830986, "Chinese": 15.49295775, "Indian": 25.35211268, "Japanese_Korean": 0, "Pakistani": 12.67605634, "Southeast_Asian": 2.816901408, "Mediterranean": 8.450704225, "Middle_Eastern": 0, "French": 2.816901408, "American": 4.225352113, "European_Other": 5.633802817, "African": 0, "Latin_American": 2.816901408, "Other": 0 }, "Barking and Dagenham": { "Italian": 4.545454545, "Chinese": 18.18181818, "Indian": 18.18181818, "Japanese_Korean": 0, "Pakistani": 18.18181818, "Southeast_Asian": 0, "Mediterranean": 13.63636364, "Middle_Eastern": 0, "French": 0, "American": 13.63636364, "European_Other": 4.545454545, "African": 0, "Latin_American": 9.090909091, "Other": 0 } }; // add functional features map.on('load',function(){ // add tileset sources map.addSource('resta_dots', { "type": "vector", "url": "mapbox://alexyshu226.3egwtdt1" }); map.addSource('borough',{ "type":"vector", "url":"mapbox://alexyshu226.71acgrbj" }); // add dot layers by category for (var i = 0; i < categories.length; i++) { map.addLayer({ 'id': categories[i], 'type': 'circle', 'source': 'resta_dots', 'source-layer': 'restaurants_final-0qa9rl', // name of tilesets 'layout': {'visibility': 'visible'}, 'paint': { 'circle-color': colors[i], 'circle-opacity': 1, 'circle-radius': { 'base': 2, 'stops': [[12, 3], [14, 6]] }, }, 'filter': ['==','general_ca',categories[i]] },'place-city-label-minor','place-city-label-major'); }; // add hover layers by category map.addLayer({ 'id': 'dot_click', 'type': 'circle', 'source': 'resta_dots', 'source-layer': 'restaurants_final-0qa9rl', // name of tilesets 'layout': {'visibility':'visible'}, 'paint': { 'circle-color': '#ffffff', 'circle-opacity': 1, 'circle-radius': { 'base': 2, 'stops': [[12, 3], [14, 6]] }, 'circle-stroke-color': '#000000', 'circle-stroke-width': 2, 'circle-stroke-opacity': 1 }, 'filter': ['==','general_ca',""] },'place-city-label-minor','place-city-label-major'); //change cursor to pointer when over dots map.on('mousemove',function(e){ var dot = map.queryRenderedFeatures(e.point,{ layers:[ 'Italian','Chinese','Indian','Japanese_Korean','Pakistani','Southeast_Asian','Mediterranean','Middle_Eastern','French','American','European_Other','African','Latin_American','Other' ] }); if (dot.length > 0) { map.getCanvas().style.cursor = 'pointer'; } else { map.getCanvas().style.cursor = ''; }; }); // add a click for each category map.on('click', function (e) { var cate = map.queryRenderedFeatures(e.point, { layers: [ 'Italian','Chinese','Indian','Japanese_Korean','Pakistani','Southeast_Asian','Mediterranean','Middle_Eastern','French','American','European_Other','African','Latin_American','Other' ] }); if (cate.length > 0) { var current_ca = cate[0].properties.general_ca; var current_co = cate_count[categories.indexOf(current_ca)]; document.getElementById('cate_info').innerHTML = "<strong>"+current_ca+"</strong>"+"<br><strong>Total</strong> # in London: "+current_co.toString()+"<br><strong>Mean</strong> # in a borough: "+cat[current_ca].mean.toString()+"<br><strong>Max</strong> # in a borough: "+cat[current_ca].max.toString(); map.setFilter('dot_click', ["==", "general_ca", current_ca]); } else { document.getElementById('cate_info').innerHTML = 'click on dots for infomation about the category'; map.setFilter('dot_click',["==",'general_ca','']); } }); //add borough layer map.addLayer({ 'id': 'boroughs', 'type': 'line', 'source': 'borough', 'source-layer': 'borough_final-dzvk5z', // name of tilesets 'layout': {'visibility':'visible'}, 'paint': { 'line-color': '#b8b8b8', 'line-opacity': 1, 'line-width': 2 } },'Italian','Chinese','Indian','Japanese_Korean','Pakistani','Southeast_Asian','Mediterranean','Middle_Eastern','French','American','European_Other','African','Latin_American','Other','place-city-label-minor','place-city-label-major'); //add invisible borough layer for clicking map.addLayer({ 'id': 'borough_fill', 'type': 'fill', 'source': 'borough', 'source-layer': 'borough_final-dzvk5z', // name of tilesets 'layout': {'visibility':'visible'}, 'paint': { 'fill-color': '#ffffff', 'fill-opacity': 0 } },'Italian','Chinese','Indian','Japanese_Korean','Pakistani','Southeast_Asian','Mediterranean','Middle_Eastern','French','American','European_Other','African','Latin_American','Other','place-city-label-minor','place-city-label-major'); //add borough hover layer map.addLayer({ 'id': 'borough_hover', 'type': 'line', 'source': 'borough', 'source-layer': 'borough_final-dzvk5z', // name of tilesets 'layout': {'visibility':'visible'}, 'paint': { 'line-color': '#595959', 'line-opacity': 1, 'line-width': 4 }, 'filter': ['==','name',''] },'place-city-label-minor','place-city-label-major'); map.on('mousemove',function(e){ var br = map.queryRenderedFeatures(e.point,{ layers:['borough_fill'] }); if (br.length > 0) { b_name = br[0].properties.name; map.setFilter('borough_hover',['==','name',b_name]); document.getElementById('br_name').innerHTML = '<strong>'+b_name+'</strong>'; var brgh_pct = []; for (var x in categories) { brgh_pct.push(brgh[b_name][categories[x]].toFixed(2)) }; barchartplotter('brgh_bar',brgh_pct,'%'); } else { document.getElementById('br_name').innerHTML = 'hover over boroughs for more information'; map.setFilter('borough_hover',['==','name','']) } }); }); // add legend with on/off switch for (var i = 0; i < categories.length; i++) { var id = categories[i]; var link = document.createElement('a'); link.href = '#'; link.className = 'active'; link.textContent = id; link.style = "color:"+colors[i]; link.onclick = function(e){ var clickedLayer = this.textContent var visibility = map.getLayoutProperty(clickedLayer,'visibility'); e.preventDefault(); e.stopPropagation(); if (visibility === 'visible') { this.className = ''; map.setLayoutProperty(clickedLayer, 'visibility', 'none'); } else { this.className = 'active'; map.setLayoutProperty(clickedLayer, 'visibility', 'visible'); } } var layers = document.getElementById('legend'); layers.appendChild(link); }; // define function to generate barchart function barchartplotter(id,data,label){ new Chart(document.getElementById(id), { type: 'horizontalBar', data: { labels: categories, datasets: [{ label: label, data: data, backgroundColor: colors, }] }, options: { events: ['click'], scales: { yAxes: [{ ticks: { beginAtZero: false } }] } } }); }; // the total count barchart var cate_count = []; for (var x in categories) { cate_count.push(cat[categories[x]].total) }; barchartplotter('total_bar',cate_count,'# of restaurants'); // control the open and close of side collapsibles function openStat() { document.getElementById("statPanel").style.width = "297px"; } function closeStat() { document.getElementById("statPanel").style.width = "0"; } function openCate() { document.getElementById("catePanel").style.width = "297px"; } function closeCate() { document.getElementById("catePanel").style.width = "0"; } function openBr() { document.getElementById("brPanel").style.width = "297px"; } function closeBr() { document.getElementById("brPanel").style.width = "0"; }
const cookieparser = process.server ? require('cookieparser') : undefined export const actions = { async nuxtServerInit({ commit, dispatch, $axios }, { req, res }) { let token = null if (req.headers.cookie) { const parsed = cookieparser.parse(req.headers.cookie) try { token = parsed.token commit('auth/setToken', token) await dispatch('auth/getUserInfo') } catch (err) { // No valid cookie found } } await dispatch('app/overview') }, }
console.log("setup.js was loaded");
import React, { Component } from "react"; export default class ListedProduct extends Component { render() { const { name, img, description, price } = this.props; return ( <div key={name} className="shadow-1 pa3 mv4 flex flex-wrap br3 ba dark-gray b--black-10 shadow-5 center" > <div className="w-100 w-20-l"> <h2 className="tc">{name}</h2> <img className="center br3" src={img} alt={name} /> </div> <div className="w-100 w-80-l f3 pl4"> <p className="f4">{description}</p> <h4 className="pl4 f4">{price}</h4> </div> </div> ); } }
import React, { Component } from 'react' import { Icon, Button, Input } from 'antd' import { connect } from 'react-redux' import Axios from 'axios' import Signup from './Signup' import Toggle from './Toggle' import './Login.css' import { Redirect } from 'react-router-dom' class Login extends Component { constructor () { super() this.state = { loading: false, user: {} } } authUser = () => { Axios.get( `/api/authUser?username=${this.props.login.user.username}&password=${ this.props.login.user.password }` ).then(resp => { console.log('Working') if (this.props.verifyUser(resp.data)) { console.log(resp.data) this.props.setAuthentication(resp.data) } else { alert('Username or Password is incorrect. Please try again.') } }) } render () { console.log(this.props.login.user) return ( <div className='loginBackground'> <Toggle /> </div> ) } } const mapStateToProps = state => { console.log('State:', state) return state } const mapDispatchToProps = dispatch => ({ setUsername (e) { dispatch({ type: 'SET_USERNAME', payload: e.target.value }) }, setPassword (e) { dispatch({ type: 'SET_PASSWORD', payload: e.target.value }) }, setAuthentication (val) { dispatch({ type: 'USER_AUTH', payload: val }) }, verifyUser (user) { dispatch({ type: 'VERIFY_USER', payload: user }) } }) export default connect( mapStateToProps, mapDispatchToProps )(Login)
import React, { Component } from 'react'; import { render } from 'react-dom'; import ImageUpload from './components/ImageUpload'; function UserInfo(props) { return ( <div> UserInfo: {props.user} </div> ); } function ppHoc(WrappedComponent) { return class PP extends React.Component { render() { const newProps = { user: 'currentLoggedInUser' } return <WrappedComponent {...this.props} {...newProps} ></WrappedComponent> } } } const AddedUserInfoComponent = ppHoc(UserInfo); const App = ( <div> <AddedUserInfoComponent></AddedUserInfoComponent> </div> ); render( App, document.getElementById('root') );
import React, { useState, useEffect } from "react"; import { Link } from "react-router-dom"; import Sidebar from "../../../Shared/Sidebar/Sidebar"; import "./BookpageWithoutServiceId.css"; const BookingpageWithhoutServiceId = () => { const [serviceDetail, setServiceDetail] = useState([]); useEffect(() => { fetch("http://localhost:4000/serviceDetail") .then((res) => res.json()) .then((data) => { setServiceDetail(data); }); }, []); return ( <div> <Sidebar></Sidebar> <div className="container mt-5 BookpageWithoutServiceId"> <div className="row mt-5"> {serviceDetail.map((serviceDetail) => ( <div class="col-md-3 mt-4"> <div class="card h-100 "> <img src={serviceDetail.imageURL} class="card-img-top" alt="..." style={{ height: "253px" }} /> <div class="card-body"> <p class="card-title"> <strong style={{ fontSize: "22px" }}> {serviceDetail.device} </strong>{" "} <br /> <strong>{serviceDetail.service}</strong> </p> <p class="card-text">{serviceDetail.description}</p> <p class="card-text"> <small class="text-muted">Last updated 3 mins ago</small> </p> </div> <Link to={"/book/" + serviceDetail._id}> <button class="serviceButton"> <span>Go for Service </span> </button> </Link> </div> </div> ))} </div> </div> </div> ); }; export default BookingpageWithhoutServiceId;
const environment = process.env.NODE_ENV; let url; if (environment === 'sandbox') { url = 'https://okapi-sandbox.frontside.io'; } else { // url = 'http://192.168.0.245:9130'; url = 'http://192.168.0.28:9130'; } module.exports = { okapi: { url, tenant: 'diku' }, config: { autoLogin: { username: 'diku_admin', password: 'admin' }, logCategories: 'core,path,mpath,mquery,xhr', logPrefix: 'cat-stripes', logTimestamp: false, showPerms: true, showHomeLink: true, listInvisiblePerms: true, hasAllPerms: true, softLogout: true }, modules: { '@folio/cataloging': {}, } };
import React,{useState} from 'react'; import database from './firebaseConfig'; const Loginpage =() => { const [userName, setUser]= useState(""); const handleLogin= (e)=>{ e.preventDefault(); const provider= new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider); // .then(result =>{ // const user=result.user; // d // }) // database.collection('users').add({ // fullName: userName, // }) // console.log(userName) } return ( <div className="loginForm"> <h1>Login</h1> {/* <form onSubmit={handleLogin}> */} {/* <input type="text" placeholder="Name" value={userName} onChange={e=>{setUser(e.target.value)}}></input> <input placeholder="Input Password" type="password" ></input> */} <button onClick={Loginpage}>signinwithgoogle</button> {/* </form> */} </div> ); } export default Loginpage;
import AsyncStorage from '@react-native-community/async-storage' import { Events } from '@constants' import { actionTypeConst } from './constants' import { fetchGetUser, fetchAnonymousSignin } from './service' const requestGetUser = () => ({ type: actionTypeConst.getUser.REQUEST }) const successGetUser = ({ data, code }) => ({ type: actionTypeConst.getUser.SUCCESS, data: data.data, code }) const failureGetUser = ({ error, code }) => ({ type: actionTypeConst.getUser.FAILURE, error, code, }) const requestAnonynousSignin = () => ({ type: actionTypeConst.anonymousSignin.REQUEST }) const successAnonynousSignin = ({ data, code }) => { AsyncStorage.setItem(Events.ACCESS_TOKEN, data.data.token) return ({ type: actionTypeConst.anonymousSignin.SUCCESS, data: data.data, code }) } const failureAnonynousSignin = ({ error, code }) => ({ type: actionTypeConst.anonymousSignin.FAILURE, error, code, }) const clearupUser = () => ({ type: actionTypeConst.clearup }) export const getUser = () => dispatch => { dispatch(requestGetUser()) fetchGetUser() .then(response => dispatch(successGetUser(response))) .catch(error => dispatch(failureGetUser(error))) } export const anonynousSignin = (data) => dispatch => { dispatch(requestAnonynousSignin()) fetchAnonymousSignin(data) .then(response => dispatch(successAnonynousSignin(response))) .catch(error => dispatch(failureAnonynousSignin(error))) } export const clearUser = () => dispatch => dispatch(clearupUser())
export { default as PinSelector } from './PinSelector/PinSelector'; export { default as PinDisplay } from './PinDisplay/PinDisplay'; export { default as MiniPinDisplay } from './MiniPinDisplay/MiniPinDisplay'; export { default as FullBoard } from './FullBoard/FullBoard';
const FormatCache = require('./FormatCache'); const LinkCache = require('./LinkCache'); //------------------------------------------- const cacheLink = new LinkCache(); exports.addLink = (url) => { return cacheLink.addLink(url); } exports.removeVid = (videoId) => { return cacheLink.removeVid(videoId); } exports.getInfo = (videoId) => { return cacheLink.getInfo(videoId); } exports.getLinkList = () => { return cacheLink.getLinkList().map(x => x); // Clone } //------------------------------------------- const cacheFormat = new FormatCache(); exports.setFormat = (format) => { if (!this.isValideFormat(format)) return; cacheFormat.setFormat(format); } exports.isValideFormat = (format) => { return this.getFormatList().filter(fmt => fmt.name === format).length > 0; } exports.getDefaultFormat = () => { return cacheFormat.getDefaultFormat(); } exports.getFormatList = () => { return cacheFormat.getFormatList().map(x => x); // Clone }
const { Router } = require('express');// // Importar todos los routers; // Ejemplo: const authRouter = require('./auth.js'); const router = Router(); const dogsRoute=require('./dogs'); const temperamentsRoute=require('./temperament'); const createdDogRoute=require('./createdDog'); const dogIdRoute=require('./dogId'); // Configurar los routers // Ejemplo: router.use('/auth', authRouter); router.use("/",dogsRoute); router.use("/",temperamentsRoute); router.use("/",createdDogRoute); router.use("/",dogIdRoute); module.exports = router;
/*TMODJS:{"version":76,"md5":"9ecef53d4c035695ff1d874824002f47"}*/ define(function(require) { return require("../template")("brand/list", function($data, $id) { var $helpers = this, $each = $helpers.$each, data = $data.data, $value = $data.$value, $index = $data.$index, $escape = $helpers.$escape, $string = $helpers.$string, cut = $data.cut === undefined ? $helpers.cut : $data.cut, $out = ""; $each(data, function($value, $index) { $out += ' <li class="main clearfix"> <dl> <dt> <a href="'; $out += $escape($value.brandinfo_url); $out += '"> <img src="'; $out += $escape($value.apply_brand_img); $out += '"> </a> </dt> <dd> <ul> <li><span class="bold mr_2">品牌名称:</span>'; $out += $string(cut($value.apply_brand_name, 7)); $out += '</li> <li><span class="bold mr_2">品牌描述:</span>'; $out += $string(cut($value.apply_brand_seodesc, 10)); $out += '</li> <a href="'; $out += $escape($value.brandinfo_url); $out += '" class="entry-btn"> <span>进入展厅</span> <span class="entry-logo"></span> </a> </ul> </dd> </dl> <img src="/lgwx/static/system/wap/brand/'; if ($value.certified_status == "0") { $out += "no"; } else if ($value.certified_status == "1") { $out += "yes"; } $out += '.png" width="20%" class="status"> </li> '; }); return new String($out); }); });
$(function() { "use strict"; // chart 1 // chart 2 });
import React, { Component, Fragment } from 'react'; import { Dialog } from '@reach/dialog'; import { Button } from 'reactstrap'; class ConfirmationDialog extends Component { state = { showDialog: false }; openDialog = () => { this.setState({ showDialog: true }); }; closeDialog = () => { this.setState({ showDialog: false }); }; handleConfirm = () => { this.props.confirmAction(); this.closeDialog(); }; render() { return ( <Fragment> <Button color='danger' onClick={this.openDialog} className='w-100'> {this.props.buttonText} </Button> <Dialog isOpen={this.state.showDialog} onDismiss={this.closeDialog}> <h3>{this.props.title}</h3> <p>{this.props.description}</p> <Button onClick={this.handleConfirm}>Yes</Button>{' '} <Button onClick={this.closeDialog}>No</Button> </Dialog> </Fragment> ); } } export default ConfirmationDialog;
import Main from '@/views/Main.vue'; // 不作为Main组件的子页面展示的页面单独写,如下 export const loginRouter = { path: '/login', name: 'login', meta: { title: 'Login - 登录' }, component: () => import('@/views/login.vue') }; export const itemRouter = { path: '/ib/item/:path', name: 'login', meta: { title: '浏览' }, component:() => import('@/views/inventory-browsing/main.vue') }; export const page404 = { path: '/*', name: 'error-404', meta: { title: '404-页面不存在' }, component: () => import('@/views/error-page/404.vue') }; export const page403 = { path: '/403', meta: { title: '403-权限不足' }, name: 'error-403', component: () => import('@//views/error-page/403.vue') }; export const page500 = { path: '/500', meta: { title: '500-服务端错误' }, name: 'error-500', component: () => import('@/views/error-page/500.vue') }; export const preview = { path: '/preview', name: 'preview', component: () => import('@/views/form/article-publish/preview.vue') }; export const locking = { path: '/locking', name: 'locking', component: () => import('@/views/main-components/lockscreen/components/locking-page.vue') }; // 作为Main组件的子页面展示但是不在左侧菜单显示的路由写在otherRouter里 export const otherRouter = { path: '/', name: 'otherRouter', redirect: '/home', component: Main, children: [ {path: 'home', title: '首页', name: 'home_index', component: () => import('@/views/home/home.vue')}, { path: 'ownspace', title: '个人中心', name: 'ownspace_index', component: () => import('@/views/own-space/own-space.vue') }, {path: 'message', title: '消息中心', name: 'message_index', component: () => import('@/views/message/message.vue')}, {path: 'time', title: '时间表', name: 'time_index', component: () => import('@/views/main-components/time-table/time-table-v.vue')}, ] }; // 作为Main组件的子页面展示并且在左侧菜单显示的路由写在appRouter里 export const appRouter = [ /* { path: '/access', icon: 'key', name: 'access', title: '权限管理', component: Main, children: [ {path: 'index', title: '权限管理', name: 'access_index', component: () => import('@/views/access/access.vue')} ] }, { path: '/access-test', icon: 'lock-combination', title: '权限测试页', name: 'accesstest', access: 0, component: Main, children: [ { path: 'index', title: '权限测试页', name: 'accesstest_index', access: 0, component: () => import('@/views/access/access-test.vue') } ] }, */ { path: '/ib', icon: 'cube', title: '库存浏览', name: 'Inventory browsing', component: Main, children: [ { path: 's-hty', title: '和田玉', name: '和田玉', component: () => import('@/views/inventory-browsing/main.vue') }, { path: 's-nh', title: '南红', name: '南红', component: () => import('@/views/inventory-browsing/main.vue') }, { path: 's-1', title: '碧玉', name: '碧玉', component: () => import('@/views/inventory-browsing/main.vue') }, { path: 's-2', title: '翡翠', name: '翡翠', component: () => import('@/views/inventory-browsing/main.vue') }, { path: 's-3', title: '绿松石', name: '绿松石', component: () => import('@/views/inventory-browsing/main.vue') }, { path: 's-4', title: '蜜蜡', name: '蜜蜡', component: () => import('@/views/inventory-browsing/main.vue') }, { path: 's-5', title: '玛瑙', name: '玛瑙', component: () => import('@/views/inventory-browsing/main.vue') }, { path: 'xql', title: '镶嵌类', name: 'xql', component: () => import('@/views/inventory-browsing/main.vue') }, { path: 'pj', title: '配件', name: 'pj', component: () => import('@/views/inventory-browsing/main.vue') }, { path: 'yl', title: '原料', name: 'yl', component: () => import('@/views/inventory-browsing/main.vue') } ] }, { path: '/inventory-manager', icon: 'cube', title: '库存管理', name: 'Inventory Manage', component: Main, children: [ { path: 'rk', title: '入库', name: 'Inventory Manage1', component: () => import('@/views/kcgl/rk/main.vue') }, { path: 'ck', title: '出库', name: 'Inventory Manage2', component: () => import('@/views/kcgl/ck/main.vue') }, { path: 'gh', title: '归还', name: 'Inventory Manage4', component: () => import('@/views/kcgl/rk/gh.vue') }, { path: 'kcpd', title: '库存盘点', name: 'Inventory Manage3', component: () => import('@/views/kcgl/kcpd/main.vue') }, ] }, { path: '/rzjl', icon: 'cube', title: '日志记录', name: 'rzjl', component: Main, access: 1, children: [ { path: 'kcrz', title: '库存日志', name: 'kcrz', component: () => import('@/views/rzjl/kcrz.vue') }, { path: 'pdrz', title: '盘点日志', name: 'pdrz', component: () => import('@/views/rzjl/pdrz.vue') }, ] }, { path: '/yggl', icon: 'cube', title: '员工管理', name: 'yggl', access: 2, component: Main, children: [ { path: 'yg', title: '员工管理', name: 'yg', component: () => import('@/views/yggl/yggl.vue') }, ] }, { path: '/sjtj', icon: 'cube', title: '数据统计', name: 'sjtj', access: 1, component: Main, children: [ { path: 'sj', title: '数据统计', name: 'sj', component: () => import('@/views/sjtj/sjtj.vue') }, ] }, { path: '/khgl', icon: 'cube', title: '客户管理', name: 'khgl', access: 1, component: Main, children: [ { path: 'khgl1', title: '客户管理', name: 'khgl1', component: () => import('@/views/khgl/main.vue') }, ] }, ]; // 所有上面定义的路由都要写在下面的routers里 export const routers = [ loginRouter, otherRouter, itemRouter, preview, locking, ...appRouter, page500, page403, page404 ];
const yargs = require("yargs"); const fs = require("fs"); const chalk = require("chalk"); yargs.command({ command: 'list', describe : 'Liste des notes', handler: () => { console.log("Voici la liste des notes :"); fs.readFile("data.json", "utf-8", (err,data) => { if(err) console.log(err); else { const notes = JSON.parse(data); notes.forEach(note => { console.log(`${note.id} : ${note.title}`); }) } }) } }).command({ command: 'add', describe : 'Ajout de note', builder: { title: { describe: "Titre de ma note", demandOption: true, type: "string" }, message: { describe: "Message de ma note", demandOption: false, type: "string" }, id: { describe: "Numéro de la note", demandOption: true, type: "string" } }, handler: (argv) => { fs.readFile("data.json", "utf-8", (err, data) => { if(err) console.log(err); else { const notes = JSON.parse(data); const newNote = { id: argv.id, title: argv.title, message: argv.message } if(argv.id === notes.id){ console.log(chalk.red("Id existant")); } else { notes.push(newNote); } const notesJSON = JSON.stringify(notes); fs.writeFile("data.json", notesJSON, (err) => { if(err) console.log(err); else { console.log(chalk.yellowBright("Nouvelle note sauvegardée")); } }) } }) } }).command({ command: 'remove', describe : ' Supprimer', handler: (argv) => { console.log("Supprimer une note"); fs.readFile("data.json", "utf-8", (err,data) => { if (err) console.log(err) else{ const notes = JSON.parse(data); // console.log(notes); const supNote = { title: argv.title, } notes.pop(supNote); /*<-Retire le dernier élément du tableau*/ // console.log(notes); const notesJSON = JSON.stringify(notes); // console.log(notesJSON); fs.writeFile("data.json", notesJSON, (err) => { if(err) console.log(err); else { console.log(chalk.redBright("Note supprimée")); } }) } }) } }).command({ command: 'read', describe : 'Lire', handler: (argv) => { console.log("Détail de ma note"); fs.readFile("data.json", "utf-8", (err, data) =>{ if (err) console.log(err) else { // console.log(data); const notes = JSON.parse(data); console.log(notes); const searchNote = { title : argv.title } if ( searchNote === notes.title){ console.log(`${notes.title}, ${notes.message}`); } else { console.log(chalk.red("Note non trouvée")); } } }) } }).argv
import React, { Component } from "react"; import FeedbackOptions from "./feedbackOptions/FeedbackOptions"; import Section from "./section/Section"; import Statistics from "./statistics/Statistics"; export default class App extends Component { state = { good: 0, neutral: 0, bad: 0 }; static defaultProps = { step: 1, title: "Please leave feedback" }; onHandleClick = e => { const name = e.target.name; this.setState(prevState => ({ [name]: prevState[name] + this.props.step })); }; countTotalFeedback = () => { return this.state.good + this.state.neutral + this.state.bad; }; countPositiveFeedbackPercentage = () => { return Math.round((this.state.good * 100) / this.countTotalFeedback()); }; render() { return ( <> <Section title={this.props.title}> <FeedbackOptions good={this.onHandleClick} neutral={this.onHandleClick} bad={this.onHandleClick} /> <Statistics good={this.state.good} neutral={this.state.neutral} bad={this.state.bad} total={this.countTotalFeedback()} positivePercentage={this.countPositiveFeedbackPercentage()} /> </Section> </> ); } }
function Entity(model, uniforms, attributes, shaderProgram, vertexShaderSource, fragmentShaderSource) { this.model = model; this.uniforms = uniforms; this.attributes = attributes; this.shaderProgram = shaderProgram; if(shaderProgram === null) { this.shaderProgram = CreateShaderProgram(vertexShaderSource, fragmentShaderSource); webglApp.GetAttributeLocations(this.shaderProgram, this.attributes); webglApp.GetUniformLocations(this.shaderProgram, this.uniforms); this.textures = []; } webglApp.BufferAttributeData(this.shaderProgram, this.attributes); } Entity.prototype.SetupTextures = function(textureImageSources) { textureImageSources.forEach((textureImageSource) => { this.textures.push(webglApp.SetupTexture(textureImageSource)); }); let samplerNumbers = []; this.textures.forEach((texture) => { samplerNumbers.push(texture.textureUnitNumber); }); return samplerNumbers; } Entity.prototype.SetupSkybox = function(skyboxImageSource) { this.textures.push(webglApp.SetupTexture(skyboxImageSource)); let samplerNumbers = []; this.textures.forEach((texture) => { samplerNumbers.push(texture.textureUnitNumber); }); return samplerNumbers; } Entity.prototype.UpdateUniformValues = function(uniformValueSet) { Object.keys(this.uniforms).forEach((uniformName, uniformIndex) => { this.uniforms[uniformName].value = uniformValueSet[uniformIndex]; }); } Entity.prototype.Draw = function() { webglApp.SetShaderProgram(this.shaderProgram); webglApp.SpecifyAttributes(this.attributes); Object.keys(this.uniforms).forEach((uniformName) => { let uniform = this.uniforms[uniformName]; if(uniform.isMatrix) { uniform.glCopyUniformFunction.call(webglApp.gl, uniform.location, false, uniform.value); } else { uniform.glCopyUniformFunction.call(webglApp.gl, uniform.location, uniform.value); } }); if(this.hasOwnProperty("textures")) { webglApp.EnableTextures(this.textures); } webglApp.Draw(this.model.vertices.length / 3); }
const { DataTypes } = require('sequelize'); const db = require('../config/database'); // Cart products model const cartProducts = db.define('cartProducts', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, title: { type: DataTypes.STRING, }, price: { type: DataTypes.FLOAT, }, image1: { type: DataTypes.STRING, }, quantity: { type: DataTypes.INTEGER, defaultValue: 1, }, category: { type: DataTypes.STRING, }, totalPrice: { type: DataTypes.FLOAT, }, defualtPrice: { type: DataTypes.FLOAT, }, discountedPrice: { type: DataTypes.FLOAT, }, discount: { type: DataTypes.INTEGER, defaultValue: 0, }, available: { type: DataTypes.INTEGER, defaultValue: 1, }, slug: { type: DataTypes.STRING, }, }); module.exports = cartProducts;
import React from 'react'; import { connect } from 'react-redux'; import callAPI from './util/callAPI'; import Navbar from './Component/NavBar'; import Content from './Component/Content'; import Form from './Component/Form'; import PreviousFileUpload from './Component/previuosFileUpload'; import * as action from './appRedux/actions/index'; class App extends React.Component{ constructor(props){ super(props); this.state = { valueTag : '', previous: [], } } componentDidMount = async () => { const jwt = JSON.parse(localStorage.getItem('token')); const res = await callAPI('picture', 'GET', {}, { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' }) if(res.data !== false){ return this.props.getPictureFromServer(res.data); } else{ localStorage.clear(); this.props.history.push('/'); } } onLogout = ()=>{ localStorage.clear(); this.props.history.push('/'); } closeModal = (e)=>{ this.props.closeForm(); } getImg = (value)=>{ let arrImg = [...value]; arrImg.map( (img) => { const reader = new FileReader(); reader.onloadend = ()=>{ const { previous } = this.state; previous.push(reader.result); this.setState({ previous: previous }) }; return reader.readAsDataURL(img); } ) } removeImg = (index)=>{ //we will remove one display image when we click to X icon const { previous } = this.state; previous.splice(index, 1); this.setState({ previous: previous }); } render() { const { valueTag, previous } = this.state; const { isClicked } = this.props; let form, classNames = ''; if(isClicked){ classNames= ' show-my-modal' form = <Form valueTag = { valueTag } getImg = { this.getImg } /> } else{ form = null; } return ( <div> <div id='scroll'> <Navbar onLogout = { this.onLogout } /> </div> <div className='container-fluid'> <div className={`my-modal${classNames}`}> <div className='wrap-content'> <span className="close-hover close" onClick={this.closeModal}>&times;</span> <div className='modal-content my-modal-content' > <div className='d-flex flex-wrap'> <div className='col-8'> { form } </div> <div className='col-4 mt-2 pt-5'> {/* previous */} <div className='col-6 no-padding d-flex flex-wrap'> { PreviousFileUpload(previous, this.removeImg) } </div> </div> </div> </div> </div> </div> <Content > </Content> </div> </div> ) } } const mapStateToProps = (state)=>{ return { isClicked : state.isClicked } } const mapDispathToProps = (dispath) =>{ return { closeForm : ()=>{ dispath(action.checkClick()); }, getPictureFromServer: (pictures) => { dispath(action.listPictures(pictures)); } } } export default connect(mapStateToProps, mapDispathToProps)(App);
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * Gallery Image Model * =========== * A database model for uploading images to the local file system */ var GalleryImage = new keystone.List('GalleryImage', {noedit: true}); var myStorage = new keystone.Storage({ adapter: keystone.Storage.Adapters.FS, fs: { path: keystone.expandPath('./public/uploads/gallery/'), // required; path where the files should be stored publicPath: '/uploads/gallery/', // path where files will be served }, schema: { size: true, mimetype: true, path: true, originalname: true, url: true, } }); GalleryImage.add({ name: { type: Types.Key, index: true}, galleryId: { type: Types.Relationship, ref: 'Gallery', many: false, initial: true, required: true }, url: {type: String}, file: { type: Types.File, storage: myStorage, initial: true, required: true }, createdTimeStamp: { type: String }, alt1: { type: String }, attributes1: { type: String }, category: { type: String }, //Used to categorize widgets. priorityId: { type: String }, //Used to prioritize display order. parent: { type: String }, children: { type: String }, fileType: {type: String}, }); GalleryImage.schema.pre('save', function (next) { this.wasNew = this.isNew; this.url = this.file.url; next(); }); GalleryImage.schema.post('save', async function () { if (this.wasNew){ try { let gallery = await keystone.list('Gallery').model.findOne({ _id: this.galleryId}).exec(); gallery.images.push(this._id); gallery.save(); } catch (e) { console.log(err); } } }); var fs = require('fs'); GalleryImage.schema.pre('remove', function (next) { fs.unlink(keystone.expandPath('/public'+this.url), (err) => console.log(err)) next(); }); GalleryImage.schema.post('remove',async function() { try { let gallery = await keystone.list('Gallery').model.findOne({ _id: this.galleryId }).exec(); if (!gallery) { next(new Error('This gallery does not exist')) } const index = gallery.images.findIndex(image=>(image.toString()===this._id.toString())); if (index > -1) { gallery.images.splice(index, 1); gallery.save(); } } catch (e) { throw new Error(e); } }); // GalleryImage.schema.pre('remove', function (next) { // console.log('rer'); // console.log(this); // console.log(doc); // keystone.list('Gallery').model.findOne({ id: this.galleryId}).exec((err, gallery)=>{ // if (err) { // throw new Error(err); // return // } // console.log(gallery); // gallery.images = gallery.images.filter(e => e !== this._id); // gallery.save((err, gallery)=>{ // if (err) { // console.log(err); // } // next() // }); // }) // }); GalleryImage.defaultColumns = 'name, galleryId, file, url'; GalleryImage.register();
'use strict'; module.exports = ({reservationRepository}) => { return reservationRepository.find(); };
import React, { useState } from 'react' import { Link } from 'react-router-dom' import Header from '../../components/Header' import PostComp from '../../components/PostComp' import './styles.css' function Main() { const [postComps, setComps] = useState([{ username: "Yuri Reis", numLike: "+17", content: "Uma breve descrição a respeito do Design responsivo para web. Técnicas para aumentar a produtividade na área.", url: "https://avatars.githubusercontent.com/YuriReiss" }, { username: "Douglas Sousa", numLike: "+14", content: "O que as empresas de Marketing buscam em novos profissionais. Saiba o que precisa ser feito para que você consiga seu primeiro emprego na área.", url: "https://avatars.githubusercontent.com/douglas541" }, { username: "Isaac Brasil", numLike: "+9", content: "7 dicas essenciais para o novo profissional de TI (extra: meus 3 palpites de frameworks para aprender em 2021)", url: "https://avatars.githubusercontent.com/isaacbrasil" }, { username: "Yuri Reis", numLike: "+9", content: "7 dicas essenciais para o novo profissional de TI (extra: meus 3 palpites de frameworks para aprender em 2021)", url: "https://avatars.githubusercontent.com/YuriReiss" }, { username: "João Victor", numLike: "+9", content: "7 dicas essenciais para o novo profissional de TI (extra: meus 3 palpites de frameworks para aprender em 2021)", url: "https://instagram.fgyn3-1.fna.fbcdn.net/v/t51.2885-19/s150x150/73387412_774779042984351_3504585325173276672_n.jpg?_nc_ht=instagram.fgyn3-1.fna.fbcdn.net&_nc_ohc=7JS_ZKW8UPMAX9ix-Rh&tp=1&oh=7a8580041c405bb07cd6d1c159b322b7&oe=602D4AB7" }, { username: "Douglas Sousa", numLike: "+9", content: "7 dicas essenciais para o novo profissional de TI (extra: meus 3 palpites de frameworks para aprender em 2021)", url: "https://avatars.githubusercontent.com/douglas541" }]); const postList = postComps.map((Comps) => { return ( <div key={Comps.username}> <PostComp username={Comps.username} numLike={Comps.numLike} content={Comps.content} url={Comps.url} /> </div> ); }) return ( <div> <div id="main-page"> <Header url="https://avatars.githubusercontent.com/YuriReiss" link="/profile" /> <div id="main-page-container"> <div id="main-page-nav-container"> <nav id="main-page-nav"> <Link to="#"><b>Social</b></Link> <Link to="/empregos">Empregos</Link> <Link to="/rank">Rank</Link> </nav> </div> <div id="main-post-container"> {postList} </div> </div> </div> </div> ); } export default Main;
import mongoose from 'mongoose'; import {ShippingParcel} from "../shipping/shipping.model"; import {registerEvents} from './product.events'; /** * VariantMedia Schema */ export const VariantMediaSchema = new mongoose.Schema({ mediaId: { type: String, optional: true }, priority: { type: Number, optional: true }, updatedAt: { type: Date, optional: true }, createdAt: { type: Date, autoValue: function () { if (this.isInsert) { return new Date; } else if (this.isUpsert) { return { $setOnInsert: new Date }; } }, denyUpdate: true } }); /** * ProductPosition Schema */ export const ProductPositionSchema = new mongoose.Schema({ tag: { type: String, optional: true }, position: { type: Number, optional: true }, pinned: { type: Boolean, optional: true }, weight: { type: Number, optional: true, defaultValue: 0, min: 0, max: 3 }, updatedAt: { type: Date } }); /** * ProductVariant Schema */ export const ProductVariantSchema = new mongoose.Schema({ ancestors: { type: [String], defaultValue: [] }, // since implementing of flattened model this property is used for keeping // array index. This is needed for moving variants through list (drag'n'drop) index: { label: "Variant position number in list", type: Number, optional: true }, isVisible: { type: Boolean, index: 1, defaultValue: false }, isDeleted: { type: Boolean, index: 1, defaultValue: false }, barcode: { label: "Barcode", type: String, optional: true, custom: function () { return "required"; } }, compareAtPrice: { label: "MSRP", type: Number, optional: true, decimal: true, min: 0, defaultValue: 0.00 }, fulfillmentService: { label: "Fulfillment service", type: String, optional: true }, weight: { label: "Weight", type: Number, min: 0, optional: true, defaultValue: 0, custom: function () { return "required"; } }, length: { label: "Length", type: Number, min: 0, optional: true, defaultValue: 0 }, width: { label: "Width", type: Number, min: 0, optional: true, defaultValue: 0 }, height: { label: "Height", type: Number, min: 0, optional: true, defaultValue: 0 }, inventoryManagement: { type: Boolean, label: "Inventory Tracking", optional: true, defaultValue: true, custom: function () { return "required"; } }, // this represents an ability to sell item without keeping it on stock. In // other words if it is disabled, then you can sell item even if it is not in // stock. inventoryPolicy: { type: Boolean, label: "Deny when out of stock", optional: true, defaultValue: false, custom: function () { return "required"; } }, lowInventoryWarningThreshold: { type: Number, label: "Warn at", min: 0, optional: true, defaultValue: 0 }, inventoryQuantity: { type: Number, label: "Quantity", optional: true, defaultValue: 0, min: 0, custom: function () { return "required"; } }, minOrderQuantity: { label: "Minimum order quantity", type: Number, optional: true }, // Denormalized field: Indicates when at least one of variants // `inventoryQuantity` are lower then their `lowInventoryWarningThreshold`. // This is some kind of marketing course. isLowQuantity: { label: "Indicates that the product quantity is too low", type: Boolean, optional: true }, // Denormalized field: Indicates when all variants `inventoryQuantity` is zero isSoldOut: { label: "Indicates when the product quantity is zero", type: Boolean, optional: true }, price: { label: "Price", type: Number, decimal: true, defaultValue: 0.00, min: 0 }, shopId: { type: String, index: 1, label: "Variant ShopId" }, sku: { label: "SKU", type: String, optional: true }, type: { label: "Type", type: String, defaultValue: "variant" }, taxable: { label: "Taxable", type: Boolean, defaultValue: true, optional: true }, taxCode: { label: "Tax Code", type: String, defaultValue: "0000", optional: true }, taxDescription: { type: String, optional: true, label: "Tax Description" }, // Label for customers title: { label: "Label", type: String, defaultValue: "" }, // Option internal name optionTitle: { label: "Option", type: String, optional: true, defaultValue: "Untitled Option" }, createdAt: { label: "Created at", type: Date, optional: true }, updatedAt: { label: "Updated at", type: Date, optional: true }, originCountry: { type: String, optional: true } }); export const PriceRangeSchema = new mongoose.Schema({ range: { type: String, defaultValue: "0.00" }, min: { type: Number, decimal: true, defaultValue: 0, optional: true }, max: { type: Number, decimal: true, defaultValue: 0, optional: true } }); export const ProductImageSchema = new mongoose.Schema({ path: { type: String, defaultValue: null, trim: true }, originalName: { type: String, defaultValue: null, trim: true } }); export const ProductImage = mongoose.model('ProductImage', ProductImageSchema); export const ProductCategorySchema = new mongoose.Schema({ code: { type: String, required: true }, value :{ type: String, required: true }, name: { type: String, required: true }, title: { type: String, defaultValue: "", label: "Category Title" }, description: { type: String, optional: true }, type: { label: "Type", type: String, defaultValue: "simple" } }); export const ProductCategory = mongoose.model('ProductCategory', ProductCategorySchema); /** * Product Schema */ const ProductSchema = new mongoose.Schema({ name: { type: String, required: true }, categories: { type: [ProductCategorySchema], defaultValue: [{code: 'other', value:'other', name: 'Other', description: 'Other categories', title: 'Other'}] }, images: { type: [ProductImageSchema], defaultValue: [] }, ancestors: { type: [String], defaultValue: [] }, title: { type: String, defaultValue: "", label: "Product Title" }, pageTitle: { type: String, optional: true }, description: { type: String, optional: true }, originCountry: { type: String, optional: true }, type: { label: "Type", type: String, defaultValue: "simple" }, vendor: { type: String, optional: true }, positions: { type: Object, // ProductPosition blackbox: true, optional: true }, // Denormalized field: object with range string, min and max price: { label: "Price", type: PriceRangeSchema }, // Denormalized field: Indicates when at least one of variants // `inventoryQuantity` are lower then their `lowInventoryWarningThreshold`. // This is some kind of marketing course. isLowQuantity: { label: "Indicates that the product quantity is too low", type: Boolean, optional: true }, // Denormalized field: Indicates when all variants `inventoryQuantity` is zero isSoldOut: { label: "Indicates when the product quantity is zero", type: Boolean, optional: true }, // Denormalized field. It is `true` if product not in stock, but customers // anyway could order it. isBackorder: { label: "Indicates when the seller has allowed the sale of product which" + " is not in stock", type: Boolean, optional: true }, requiresShipping: { label: "Require a shipping address", type: Boolean, defaultValue: true, optional: true }, parcel: { type: ShippingParcel, optional: true }, hashtags: { type: [String], optional: true, index: 1 }, twitterMsg: { type: String, optional: true, max: 140 }, facebookMsg: { type: String, optional: true, max: 255 }, googleplusMsg: { type: String, optional: true, max: 255 }, pinterestMsg: { type: String, optional: true, max: 255 }, metaDescription: { type: String, optional: true }, handle: { type: String, optional: true, index: 1 }, isDeleted: { type: Boolean, index: 1, defaultValue: false }, isVisible: { type: Boolean, index: 1, defaultValue: false }, template: { label: "Template", type: String, defaultValue: "productDetailSimple" }, createdAt: { type: Date, autoValue: function () { if (this.isInsert) { return new Date; } else if (this.isUpsert) { return { $setOnInsert: new Date }; } } }, updatedAt: { type: Date, autoValue: function () { return new Date; }, optional: true }, publishedAt: { type: Date, optional: true }, publishedScope: { type: String, optional: true } }); registerEvents(ProductSchema); export default mongoose.model('Product', ProductSchema);
var assignments = [ { name: "Algebra Quiz" }, { name: "Spelling Quiz" }, { name: "Biography Paper" }, { name: "Show and Tell" } ];
"use strict"; const {Router} = require(`express`); const csrf = require(`csurf`); const HttpCode = require(`~/constants`); const { buildArticleData, getArticleCategoriesIds, buildCommentData, prepareErrors, } = require(`~/utils`); const { checkAuth, checkAdmin, upload, } = require(`~/express/middlewares`); const api = require(`~/express/api`).getAPI(); const ROOT = `articles`; const articlesRouter = new Router(); const csrfProtection = csrf(); const getEditArticleData = async (id, userId) => { const [article, categories] = await Promise.all([ api.getArticle({id, userId, withComments: true}), api.getCategories() ]); return [article, categories]; }; const getAddArticleCategories = () => { return api.getCategories({withCount: false}); }; articlesRouter.get(`/add`, [ checkAuth, checkAdmin, csrfProtection ], async (req, res) => { const {session, query} = req; const {user} = session; const article = Object.keys(query).length ? query : null; const categories = await api.getCategories(); const date = new Date(); const csrfToken = req.csrfToken(); res.render(`${ROOT}/add`, { user, article, categories, date, csrfToken, }); }); articlesRouter.post(`/add`, [ checkAuth, checkAdmin, upload.single(`picture`), csrfProtection, ], async (req, res) => { const {user} = req.session; const article = buildArticleData(req); try { await api.createArticle(article); return res.redirect(`../my`); } catch (error) { const articleCategories = article.categories; const categories = await getAddArticleCategories(); const validationMessages = prepareErrors(error); const csrfToken = req.csrfToken(); return res.render(`${ROOT}/add`, { user, article, articleCategories, categories, validationMessages, csrfToken, }); } }); articlesRouter.get(`/edit/:id`, [ checkAuth, checkAdmin, csrfProtection ], async (req, res) => { const {params, session} = req; const {id} = params; const {user} = session; const userId = user.id; const csrfToken = req.csrfToken(); try { const [article, categories] = await getEditArticleData(Number(id), userId); const articleCategories = getArticleCategoriesIds(article); res.render(`${ROOT}/add`, { user, article, articleCategories, categories, csrfToken, }); } catch (error) { return res.render(`errors/404`).status(HttpCode.NOT_FOUND); } return null; } ); articlesRouter.post( `/edit/:id`, [ checkAuth, checkAdmin, upload.single(`picture`), csrfProtection, ], async (req, res) => { const {id} = req.params; const article = buildArticleData(req); try { await api.editArticle(Number(id), article); return res.redirect(`/articles/${id}`); } catch (error) { const articleCategories = article.categories; const categories = await getAddArticleCategories(); const validationMessages = prepareErrors(error); const csrfToken = req.csrfToken(); return res.render(`${ROOT}/add`, { article, articleCategories, categories, validationMessages, csrfToken, }); } }); articlesRouter.post( `/:id`, [ checkAuth, checkAdmin, ], async (req, res) => { const {params, session} = req; const {id} = params; const {user} = session; const userId = user.id; try { await api.removeArticle({ id, userId, }); return res.redirect(`/my`); } catch (error) { const {status, statusText} = error.response; return res .status(status) .send(statusText); } } ); articlesRouter.get(`/:id`, csrfProtection, // Для коммментирования async (req, res) => { const {params, session} = req; const {id} = params; const {user} = session; const userId = user ? user.id : null; const csrfToken = req.csrfToken(); const [article, categories] = await Promise.all([ api.getArticle({id, userId, withComments: true}), api.getCategories({withCount: true}), ]); const selectedCategoriesIds = getArticleCategoriesIds(article); res.render(`${ROOT}/article`, { user, article, categories, selectedCategoriesIds, csrfToken, }); }); articlesRouter.get( `/:id/comments`, (_req, res) => res.redirect(`./`) ); articlesRouter.post( `/:id/comments`, [ checkAuth, csrfProtection, ], async (req, res) => { const {params, body, session} = req; const {id} = params; const {text} = body; const {user} = session; const userId = user.id; const commentData = buildCommentData(text, user); try { const comment = await api.createComment(id, commentData); return res.redirect(`/${ROOT}/${id}#${comment.id}`); } catch (error) { const [article, categories] = await Promise.all([ api.getArticle({id, userId, withComments: true}), api.getCategories({withCount: true}), ]); const validationMessages = prepareErrors(error); const csrfToken = req.csrfToken(); return res.render(`${ROOT}/article`, { user, article, categories, newComment: text, validationMessages, csrfToken, }); } } ); articlesRouter.post( `/:articleId/comments/:commentId`, [ checkAuth, checkAdmin, ], async (req, res) => { const {params, session} = req; const {articleId, commentId} = params; const {user} = session; const userId = user.id; try { await api.removeComment({ articleId, commentId, userId, }); return res.redirect(`/my/comments`); } catch (error) { const {status, statusText} = error.response; return res .status(status) .send(statusText); } } ); articlesRouter.get(`/category/:id`, async (req, res) => { const {params, session} = req; const {id} = params; const {user} = session; const userId = user ? user.id : null; const [selectedCategory, categories, articles] = await Promise.all([ api.getCategory(id), api.getCategories({withCount: true}), api.getArticles({userId, withComments: true}), ]); const articlesWithCategory = articles.filter((article) => article.categories.some((category) => category.id === selectedCategory.id) ); const selectedCategoriesIds = [selectedCategory.id]; res.render(`${ROOT}/articles-with-category`, { user, categories, selectedCategoriesIds, articlesWithCategory, }); }); module.exports = articlesRouter;
(function () { 'use strict'; angular .module('articleForm') .config(config); function config($stateProvider) { $stateProvider .state('articleForm', { url: '/article-form', views: { 'mainView': { templateUrl: 'article-form/article-form.tpl.html', controller: 'ArticleFormCtrl', controllerAs: 'articleForm' }, 'layoutView': { templateUrl: 'partials/layoutView.html' } } }) .state('articleFormUpdate', { url: '/article-form/:articleId', views: { 'mainView': { templateUrl: 'article-form/article-form.tpl.html', controller: 'ArticleFormCtrl', controllerAs: 'articleForm' }, 'layoutView': { templateUrl: 'partials/layoutView.html' } } }); } }());
const { register } = require('../../dist/node') register({ hookIgnoreNodeModules: false, hookMatcher(fileName) { return fileName.includes('foo') || fileName.includes('index') }, })
import owlCarousel from 'owl.carousel2'; $('.owl-carousel').owlCarousel({ loop: true, items: 6, autoplay: true, autoplayTimeout: 5000, autoplayHoverPause: false, autoplaySpeed: 1000, margin: 30, nav: false, navText: ["<i class='fa fa-chevron-left slide-nav slide-previous' aria-hidden='true'></i>", "<i class='fa fa-chevron-right slide-nav slide-next' aria-hidden='true'></i>"], dots: false, })
// Copyright 2012 Andrew Dittrich // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.using System; // This is a collection of scripts used on the Administration.aspx page. function updateHelpTextFromSelectControl (selectControl) { // get the currently selected type from the passed in select control selectedIndex = selectControl.selectedIndex; selectedType = selectControl.options[selectedIndex].value; updateHelpText(selectedType); } function updateHelpText(serviceType) { // look up the help text for this type from the serviceHelpMap. This map is produced dynamically // when the page loads from the code behind. It maps 'type' to 'help', and should look // something like this: // var serviceHelpMap = =[{ type: "ArcGISMapService", help: "ArcGIS help text" }, // { type: "WebMapService", help: "Web Map Service help text" }]; if (serviceHelpMap != null) { for (index in serviceHelpMap) { serviceHelp = serviceHelpMap[index]; if (serviceHelp.type == selectedType) { helpText = document.getElementById("HelpText"); helpText.innerText = serviceHelp.help; } } } } // make this script play nicely with the ASP.NET ScriptManager. Tell it when it is done loading. // This must be the last line in the script if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
/** * This file is part of Sesatheque. * Copyright 2014-2015, Association Sésamath * * Sesatheque is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation. * * Sesatheque 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Sesatheque (LICENCE.txt). * @see http://www.gnu.org/licenses/agpl.txt * * * Ce fichier fait partie de l'application Sésathèque, créée par l'association Sésamath. * * Sésathèque est un logiciel libre ; vous pouvez le redistribuer ou le modifier suivant * les termes de la GNU Affero General Public License version 3 telle que publiée par la * Free Software Foundation. * Sésathèque est distribué dans l'espoir qu'il sera utile, mais SANS AUCUNE GARANTIE, * sans même la garantie tacite de QUALITÉ MARCHANDE ou d'ADÉQUATION à UN BUT PARTICULIER. * Consultez la GNU Affero General Public License pour plus de détails. * Vous devez avoir reçu une copie de la GNU General Public License en même temps que Sésathèque * (cf LICENCE.txt et http://vvlibri.org/fr/Analyse/gnu-affero-general-public-license-v3-analyse * pour une explication en français) */ 'use strict'; const filters = require('sesajstools/utils/filters'); const Ressource = require('./Ressource'); /** * Objet SequenceModele, issu d'une séquence sesalab. C'est une séquence sans élève mise au format Ressource * @extends Ressource */ class SequenceModele extends Ressource { /** * @param {object} parametres L'objet sequence passé par sesalab, sans ses propriétés commençant par _ et $ */ constructor(values) { super(values || {}); this.parametres = values ? filters.object(values, /^(\$|_)/) : {}; } } module.exports = SequenceModele;
// Copyright 2020-2021 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 const { Digest, checkCredential, KeyType, publish, VerifiableCredential, VerificationMethod, KeyCollection } = require('../node/identity_wasm') const { createIdentity } = require('./create_did'); const { EXPLORER_URL, CLIENT_CONFIG } = require('./config') /* This example shows how to sign/revoke verifiable credentials on scale. Instead of revoking the entire verification method, a single key can be revoked from a MerkleKeyCollection. This MerkleKeyCollection can be created as a collection of a power of 2 amount of keys. Every key should be used once by the issuer for signing a verifiable credential. When the verifiable credential must be revoked, the issuer revokes the index of the revoked key. */ async function merkleKey() { //Creates new identities (See "create_did" example) const alice = await createIdentity(); const issuer = await createIdentity(); //Add a Merkle Key Collection Verification Method with 8 keys (Must be a power of 2) const keys = new KeyCollection(KeyType.Ed25519, 8); const method = VerificationMethod.createMerkleKey(Digest.Sha256, issuer.doc.id, keys, "key-collection") // Add to the DID Document as a general-purpose verification method issuer.doc.insertMethod(method, "VerificationMethod"); issuer.doc.previousMessageId = issuer.messageId; issuer.doc.sign(issuer.key); //Publish the Identity to the IOTA Network and log the results, this may take a few seconds to complete Proof-of-Work. const nextMessageId = await publish(issuer.doc.toJSON(), CLIENT_CONFIG); console.log(`Identity Update: ${EXPLORER_URL}/${nextMessageId}`); // Prepare a credential subject indicating the degree earned by Alice let credentialSubject = { id: alice.doc.id.toString(), name: "Alice", degreeName: "Bachelor of Science and Arts", degreeType: "BachelorDegree", GPA: "4.0" }; // Create an unsigned `UniversityDegree` credential for Alice const unsignedVc = VerifiableCredential.extend({ id: "http://example.edu/credentials/3732", type: "UniversityDegreeCredential", issuer: issuer.doc.id.toString(), credentialSubject, }); // Sign the credential with Issuer's Merkle Key Collection method, with key index 0 const signedVc = issuer.doc.signCredential(unsignedVc, { method: method.id.toString(), public: keys.public(0), secret: keys.secret(0), proof: keys.merkleProof(Digest.Sha256, 0) }); //Check the verifiable credential const result = await checkCredential(signedVc.toString(), CLIENT_CONFIG); console.log(`VC verification result: ${result.verified}`); // The Issuer would like to revoke the credential (and therefore revokes key 0) issuer.doc.revokeMerkleKey(method.id.toString(), 0); issuer.doc.previousMessageId = nextMessageId; const revokeMessageId = await publish(issuer.doc.toJSON(), CLIENT_CONFIG); console.log(`Identity Update: ${EXPLORER_URL}/${revokeMessageId}`); //Check the verifiable credential const newResult = await checkCredential(signedVc.toString(), CLIENT_CONFIG); console.log(`VC verification result: ${newResult.verified}`); } exports.merkleKey = merkleKey;
var cli = require('./cli'), log = require('./log'), config = require('./config'), tasks = require('./tasks'), tracker = require('./tracker'); function fromCli(options) { return execute(cli.parse(options)); } function execute(cliArgs) { var options = config.mergeOptions(cliArgs); return tracker.askPermissionAndTrack(options).then(function() { if(cliArgs.version) { cli.version(); tracker._track('version'); } else if(cliArgs.help) { cli.help(); tracker._track('help'); } else { if(options.force) { log.warn('Using --force, I sure hope you know what you are doing.'); } if(options.debug) { require('when/monitor/console'); } log.debugDir(options); return tasks.run(options); } }).catch(function(error) { log.error(error); if(options.debug) { throw error; } }); } module.exports = { cli: fromCli, execute: execute };
import React, { Fragment } from "react"; //importing style exclusive for this component import "../Resources/resourceList.css"; //import the icons import ArrowIcon from "../../icons/Arrow icon.svg"; import Blood from "../../icons/blood.png"; import Meds from "../../icons/💊.png"; import Microscope from "../../icons/🔬.png"; import Oxygen from "../../icons/😷.png"; import Injection from "../../icons/💉.png"; import Bed from "../../icons/bed.png"; import Ambulance from "../../icons/Ambulance.png"; import Epidemic from "../../icons/Epidemic.png"; //order // "💉": "Vaccine", // "🔬": "COVID Testing", // "😷": "Oxygen", // "🛏": "Hospital Beds", // "💊": "Pharmacies", // "🚑": "Ambulance", // "🩸": "Plasma / Blood Bank", const resourceItems = [ { id: 1, src: Bed, title: "Hospital Beds", description: "Find information about availability of Hospital Beds.", }, { id: 2, src: Meds, title: "Pharmacies", description: "Find nearest pharm. for drugs other than Ramdesivir , Tocillzumab.", }, { id: 3, src: Ambulance, title: "Ambulance", description: "Find information about availability of nearest ambulance services", }, { id: 4, src: Blood, title: "Plasma / Blood", description: "Find information about availability of Blood/Plasma.", }, { id: 5, src: Epidemic, title: "Epidemic Crisis", description: "Sponsor a child", }, ]; const ResourcesLIst = () => { return ( <Fragment> <h3 className="text-light">Essentials</h3> <div className="grid grid-1x2 resource-block"> {resourceItems.map(({ id, src, title, description }) => { return ( <div key={id} className="card card--dark"> <img className="card__image" src={src} alt="oops" /> <div className="card__header"> <h3 className="card__title" id={`card-${id}-title`}> {title} </h3> <p className="card__description" id={`card-${id}-desc`}> {description} </p> </div> </div> ); })} </div> </Fragment> ); }; export default ResourcesLIst; /* <Menu onClick={handleClick} style={{ width: "90%", boxSizing: "border-box", background: "#151515", color: "white", }} mode="vertical" > <SubMenu key="sub1" icon="🩸" title="Navigation One"></SubMenu> <SubMenu style={{ borderBottom: "2px solid black" }} key="sub2" icon={<AppstoreOutlined />} title="Navigation Two" ></SubMenu> <SubMenu key="sub4" icon={<SettingOutlined />} title="Navigation Three" ></SubMenu> </Menu> {Object.keys(resourceItems).map((emojis, i) => { return ( <div className="list"> {Object.values(resourceItems).map((options, i) => { return ( <div className="emoji-and-option" style={{ background: "crimson" }} > {emojis} <h2>{options}</h2> </div> ); })} </div> ); })} */
var Modeler = require("../Modeler.js"); var className = 'Typeaddresslink'; var Typeaddresslink = function(json, parentObj) { parentObj = parentObj || this; // Class property definitions here: Modeler.extend(className, { navlinkid: { type: "string", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "navlinkid", "s:annotation": { "s:documentation": "The navlink ID" }, "s:simpleType": { "s:restriction": { base: "s:string", "s:maxLength": { value: 38 } } }, type: "s:string" }, mask: Modeler.GET | Modeler.SET, required: false }, address: { type: "Typeaddresslinkaddress", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "address", type: "tns:addresslinkaddress", "s:annotation": { "s:documentation": "Addresslink address" } }, mask: Modeler.GET | Modeler.SET, required: false }, erhistory: { type: "TypeArrayOfErhistoryitem", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "erhistory", type: "tns:ArrayOfErhistoryitem", "s:annotation": { "s:documentation": "Previous Electoral Roll items" } }, mask: Modeler.GET | Modeler.SET, required: false }, notices: { type: "TypeArrayOfNotice", wsdlDefinition: { minOccurs: 0, maxOccurs: 1, name: "notices", type: "tns:ArrayOfNotice", "s:annotation": { "s:documentation": "Contains all details for a data level NOC or NOD" } }, mask: Modeler.GET | Modeler.SET, required: false } }, parentObj, json); }; module.exports = Typeaddresslink; Modeler.register(Typeaddresslink, "Typeaddresslink");
const express = require('express'); const cors = require('cors'); const { runInNewContext } = require('vm'); const app = express(); //MIDDLEWARE app.use(express.json()); //used for body app.use(cors()); const inventory = ['voltron lego', 'card', 'Wagon', 'computer', 'table', 'chair', 'milk', 'sailboat', 'conditioner', 'rusty nail', 'Desk']; app.get('/api/inventory', (req, res) => { if(req.query.item){ const filteredItems = inventory.filter(invItems => { return invItems.toLowerCase().includes(req.query.item.toLowerCase()); }); res.status(200).send(filteredItems) } else { res.status(200).send(inventory) } }); app.get("/api/inventory/:id", (req, res) => { res.status(200).send(inventory[+req.params.id]) }); app.listen(5050, () => console.log('Server up and running, my boy!'));
import React from 'react' import tw, { styled, theme } from 'twin.macro' import { BsPlayFill, BsPauseFill } from 'react-icons/bs' import Button from '@/elements/Button' import exec from '@/lib/exec' import usePlayer from '@/lib/usePlayer' // Macros can't use absolute imports because they get stripped out import snapshot from '../../lib/snapshot.macro' import Tree from './shared/Tree' import useSyntaxTree from './shared/useSyntaxTree' import { Slider } from '../Slider' const code = `let a = 10` const visitors = ['Identifier', 'VariableDeclaration'] const algorithm = snapshot(function traverse(tree) { // eslint-disable-next-line no-debugger debugger const children = Object.values(tree) .filter(isAstNode) .flatMap((node) => (Array.isArray(node) ? node : [node])) children.forEach(traverse) }) export default function TraverseVisitor() { const [tree] = useSyntaxTree(code) const steps = React.useMemo(() => exec(algorithm.entryPoint, [tree]), [tree]) const { models, actions } = usePlayer(steps) const activeNodeType = models.state.tree.type return ( <div> <Controls> <Button onClick={actions.toggle}> {models.isPlaying ? <BsPauseFill /> : <BsPlayFill />} </Button> <Slider type="range" min="0" max={steps.length - 1} value={models.activeStepIndex} onInput={(evt) => actions.setIndex(evt.target.valueAsNumber)} /> </Controls> <ContentWrapper> <Tree tree={tree} code={code} depth={Number.POSITIVE_INFINITY} activeNodeType={activeNodeType} /> <Visitor> <VisitorTitle>Visitor</VisitorTitle> {visitors.map((nodeType) => ( <Handler key={nodeType} active={nodeType === activeNodeType}> {nodeType} </Handler> ))} </Visitor> </ContentWrapper> </div> ) } function isAstNode(value) { if (Array.isArray(value)) { const [first] = value if (first) { return typeof first === 'object' && first.hasOwnProperty('type') } } if (value && typeof value === 'object') { return value.hasOwnProperty('type') } return false } const Controls = styled.div` padding: 0 32px; margin-bottom: 24px; display: flex; > :first-child { margin-right: 16px; } ` const ContentWrapper = styled.div` display: grid; grid-template-columns: 2fr 1fr; grid-column-gap: 16px; align-items: flex-start; overflow-x: auto; padding: 0 32px; @media screen and (min-width: ${theme`screens.md`}) { padding: 0 2px; } ` const Visitor = styled.ul` font-family: var(--text-mono); background: var(--gray200); border-radius: 8px; padding: 16px; border: 2px solid var(--border-color); > li { margin-top: 4px; } ` const VisitorTitle = styled.h1` margin-bottom: 16px; ` const Handler = styled.li` --color-background: ${({ active }) => active ? `var(--color-highlight-secondary)` : 'revert'}; --color-text: ${({ active }) => (active ? 'white' : 'revert')}; background: var(--color-background); color: var(--color-text); border-radius: 4px; padding: 6px; `
import { name, version } from '../data.mjs' export const plugin = { name, version, hooks: { insertText: (locale, text, data) => { if (!data) { console.log( "No data was passed to the i18n plugin. This plugin won't do much without injecting data into it" ) return text } if (data.t) { return data.t(text) } else { const prefix = data.prefix || '' return typeof data.strings[locale][prefix + text] === 'undefined' ? text : data.strings[locale][prefix + text] } }, }, } // More specifically named exports export const i18nPlugin = plugin export const pluginI18n = plugin
function initDisplay() { window.canvas = new Canvas('mainCanvas'); window.canvas.initCanvasSize(); } function initEvents() { $('#mainCanvas').live('mousedown', function(e) { var offset = $('#mainCanvas').offset(); console.log(offset); window.canvas.mousedown(e.pageX - offset.left, e.pageY - offset.top); }); $('#mainCanvas').live('mouseup', function(e) { var offset = $('#mainCanvas').offset(); window.canvas.mouseup(e.pageX - offset.left, e.pageY - offset.top); }); $('#mainCanvas').live('mousemove', function(e) { var offset = $('#mainCanvas').offset(); window.canvas.mousemove(e.pageX - offset.left, e.pageY - offset.top); }); } $(function() { initDisplay(); initEvents(); });
/** * * * 颜色 * @Author Jason * @Date 2017-5-11 * * */ ;(function() { function Color(fn) { if(!this instanceof Color) return new Color(fn); this.name = "Color"; fn.call(Object.create(null), this); } Color.prototype = { constructor: Color }; window.vm = window.vm || {}; window.vm.module = window.vm.module || {}; window.vm.module["color"] = Color; }(void(0)));
import React from 'react'; import { StyleSheet, View, Text, Picker, Button, TouchableHighlight, Dimensions, Alert } from 'react-native'; import AsyncStorage from '@react-native-community/async-storage'; class SettingsScreen extends React.Component{ state = { meters: '', } componentDidMount() { AsyncStorage.getItem('meters').then( (value) => this.setState({ 'meters': value })) } render(){ return( <View style={styles.container}> <Text style={styles.text}>Distanza in metri per l'aggiornamento della posizione</Text> <Picker itemStyle={{color: '#fff'}} selectedValue = {this.state.meters} onValueChange = {this.setIntervalMeters} > <Picker.Item label = "1 metro" value = "1" /> <Picker.Item label = "2 metri" value = "2" /> <Picker.Item label = "5 metri" value = "5"/> </Picker> <TouchableHighlight style={styles.eraseButton} onPress={this.eraseAllData} > <Text style={styles.text}>Elimina dati di navigazione</Text> </TouchableHighlight> </View> ) } setIntervalMeters = async (value) => { await AsyncStorage.setItem('meters', value); this.setState({ 'meters': value }); } eraseAllData = () => { AsyncStorage.removeItem('listNavigation',() => Alert.alert("Informazione","Lista di navigazione svuotata con successo","OK")); } } SettingsScreen.navigationOptions = ({navigation}) => ({ headerTitle: 'Impostazioni', headerLeft: ( <Button title="Indietro" color='#fff' onPress={() => navigation.goBack()} /> ) }) const styles = StyleSheet.create({ container: { flex:1, padding: 10, flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'stretch', backgroundColor: '#054', }, text:{ fontSize: 20, fontFamily: 'Avenir' }, eraseButton:{ height: 40, alignItems: 'center', justifyContent: 'center', backgroundColor: '#f20', width: Dimensions.get('window').width / 3, } }) export default SettingsScreen;
$(document).ready(function() { "use strict"; var av_name = "PDAtoCFLCON"; var av = new JSAV(av_name); // Load the config object with interpreter and code created by odsaUtils.js var arrow = String.fromCharCode(8594); var grammar = "[[\"S\",\"→\",\"aSA\"],\ [\"S\",\"→\",\"aAA\"],\ [\"S\",\"→\",\"b\"],\ [\"A\",\"→\",\"bBBB\"],\ [\"B\",\"→\",\"b\"]]"; var grammerArray = JSON.parse(grammar); var lastRow = grammerArray.length; grammerArray.push(["", arrow, ""]); var grammerMatrix = av.ds.matrix(grammerArray, {style: "table", left: 10}); av.displayInit(); var transformer = new PDAtoGrammarTransformer(av, grammar, grammerMatrix); transformer.convertToPDA(); av.recorded(); });
var express = require('express'); var router = express.Router(); var db = require('../db') var common=require('commonmark'); var reader = new common.Parser(); var writer = new common.HtmlRenderer(); /* GET home page. */ router.get('/:username/:postid', function(req, res){ db.get().collection('Posts',function (err, collection) { collection.find({username: req.params.username, postid: parseInt(req.params.postid)}).toArray(function (err, result) { if (err) { //res.status(404); console.log('Error:' + err); return; } console.log(result); if(result.length==0){ res.status(404); res.render('error',{"message":"cannot find this post","error":{"status":"404","stack":""}}); }else{ let parsed = reader.parse(result[0].title); // parsed is a 'Node' tree // transform parsed if you like... let title = writer.render(parsed); let parsed1 = reader.parse(result[0].body); // parsed is a 'Node' tree // transform parsed if you like... let body = writer.render(parsed1); res.render('postlist', {"title": title, "body": body}); res.status(200).json(); } }); }); }); let getFive = function(name, page,limit, callback) { db.get().collection('Posts', function (err, collection) { if(err){ console.log('Error:' + err); return; } collection.count({username:"cs144",postid:{$gte:limit}}, function (err, total) { console.log("total:"+total); collection.find({username:name,postid:{$gte:limit}}).sort({postid:1}).limit(5).skip( (page-1)*5 ).toArray(function (err, docs) { if (err) { console.log(err); return callback(err); } console.log(docs); docs.forEach(function (doc) { let parsed = reader.parse(doc.title); // parsed is a 'Node' tree // transform parsed if you like... doc.title = writer.render(parsed); let parsed1 = reader.parse(doc.body); // parsed is a 'Node' tree // transform parsed if you like... doc.body = writer.render(parsed1); //let dt=new Date(doc.created); //doc.created=dt.setTime(); //doc.modified=dt.setTime(doc.modified); // console.log(doc.created); //console.log(doc.modified); }); //console.log(docs); callback(null, docs, total); }); }); }); }; router.get('/:username', function(req, res) { let limit = req.query.start ? parseInt(req.query.start) : 0; if(isNaN(limit)){ res.status(404); res.render('error',{"message":"the start postid should be an integer","error":{"status":"404","stack":""}}); return;} let page = req.query.p ? parseInt(req.query.p) : 1; let username=req.params.username; console.log("limit:"+limit+"page:"+page); if(limit<0){ res.status(404); res.render('error',{"message":"the start postid should be larger than 0","error":{"status":"404","stack":""}}); return; } getFive(username, page, limit,function (err, posts, total) { if (err) { posts = []; } if(posts.length==0){ res.status(404); res.render('error',{"message":"cannot find any post","error":{"status":"404","stack":""}}); return; }else { res.status(200); res.render('postEachUser', { //total:total.length, username: username, posts: posts, page: page, isFirstPage: (page - 1) == 0, isLastPage: ((page - 1) * 5 + posts.length) < total, user: username, start:limit //success: req.flash('success').toString(), // error: req.flash('error').toString() }); } }); }); module.exports = router;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _reactNativeSvg = require("react-native-svg"); var _PrettyWire = _interopRequireDefault(require("./PrettyWire.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var _default = function _default(_ref) { var extraProps = _extends({}, _ref); return _react["default"].createElement(_PrettyWire["default"], _extends({ Svg: _reactNativeSvg.Svg, Path: _reactNativeSvg.Path }, extraProps)); }; exports["default"] = _default;
export default { troll: { id: "troll", name: "Troll", stats: { strength: 86, agility: 57, stamina: 96, intellect: 86, spirit: 101, mana: 1240, crit: 0.0201602611156427, healing: 0, mp5: 0 } }, orc: { id: "orc", name: "Orc", stats: { strength: 86, agility: 57, stamina: 96, intellect: 86, spirit: 101, mana: 1240, crit: 0.0201602611156427, healing: 0, mp5: 0 } } }
import { PageIcon } from 'shared/components/icons.mjs' import { useTranslation } from 'next-i18next' export const PageOrientationPicker = ({ gist, updateGist }) => { const { t } = useTranslation(['workbench']) return ( <button className={` btn btn-primary flex flex-row gap-2 items-center hover:text-primary-content `} onClick={() => updateGist( ['_state', 'layout', 'forPrinting', 'page', 'orientation'], gist._state?.layout?.forPrinting?.page?.orientation === 'portrait' ? 'landscape' : 'portrait' ) } > <span className={ gist._state?.layout?.forPrinting?.page?.orientation === 'landscape' ? 'rotate-90' : '' } > <PageIcon /> </span> <span>{t(`pageOrientation`)}</span> </button> ) }
const form = document.forms.namedItem('button1'); form.addEventListener ( 'submit', (event) => { event.preventDefault(); document.location.href = "table.html"; } );
import PropTypes from 'prop-types' const propTypes = { trackProps: PropTypes.shape({ isSliding: PropTypes.bool, showLeftArrow: PropTypes.bool, showRightArrow: PropTypes.bool, left: PropTypes.number, parentWidth: PropTypes.number, trackWidth: PropTypes.number, trackBounds: PropTypes.object, }), } export default propTypes
document.getElementById("factGenerate").addEventListener("click", function(event) { event.preventDefault(); const value = document.getElementById("factList").value; if(value === "") return; document.getElementById("factList").innerHTML = "Loading..."; const url = "https://cors-anywhere.herokuapp.com/cat-fact.herokuapp.com/facts"; console.log(url); fetch(url, {mode:'cors'}) .then(function(response) { return response.json(); }).then(function(json) { console.log(json); var factNumber = Math.floor(Math.random() * json.all.length); console.log(factNumber); document.getElementById("factList").innerHTML = json.all[factNumber].text; }); }); document.getElementById("factBomb").addEventListener("click", function(event) { event.preventDefault(); const value = document.getElementById("factList").value; if(value === "") return; document.getElementById("factList").innerHTML = "I hope you're ready for this..."; const url = "https://cors-anywhere.herokuapp.com/cat-fact.herokuapp.com/facts"; console.log(url); fetch(url, {mode:'cors'}) .then(function(response) { return response.json(); }).then(function(json) { console.log(json); var result = ""; for (let i = 0; i < 10; i++) { result += "<p>" var factNumber = Math.floor(Math.random() * json.all.length); console.log(factNumber); result += json.all[factNumber].text; result += "</p>" } document.getElementById("factList").innerHTML = result; }); });
import React from 'react' import {Link} from 'react-router-dom' const Buttons = (props) => { return ( <ul className="right hide-on-med-and-down"> <li><Link to="/about">About</Link></li> <li onClick={props.fresh}><a><i className="material-icons">refresh</i></a></li> <li onClick={props.action}><a><i className="material-icons">{(props.grid) ? "view_list" : "view_module"}</i></a></li> </ul> ) } export default Buttons
module.exports = { secret: 'Who but me? Loves JWT' };
// objects = used to store many values instead of one single one let frodo = { race: "hobbit", rings: 1, cloak: true } //Arrays => containers that hold lists of items //denoted by square brackets [] let list =['item1','item2','item3']; let burritos = ['large', 4, true]; //DataType Literals //A literal represents a fixed value that we as developers insert into the code //Includes strings, numbers, booleans, objects, arrays //String Literal let car = 'Ford'; //Numberic Literal let december = 12; //Boolean Literal let tired = true; //Object Literal let soup = { a: 'chicken noodle', b: 'tomato', c: 'beef and barley', d: 'chili', e: 'cereal' };
import React from 'react'; import { setURL, setType } from '../../store/request-form-reducer'; import { connect } from 'react-redux'; function URL(props) { const { type, url } = props; const { setURL, setType } = props; let updateState = async (key, value) => { switch (key) { case 'url': setURL(value); break; case 'type': setType(value); break; default: break; } } let handleInput = e => { updateState('url', e.target.value) } let handleRadio = e => { console.log(e.target.value); updateState('type', e.target.value); } let isSelected = selectedType => { console.log(selectedType); if (selectedType === type) { console.log('Is selected type') return 'selected'; } return false; } let setValue = () => { if (url) { return url; } return undefined; } return ( <section> <select className="dropDown" onChange={handleRadio}> <option value="GET" selected={isSelected('GET')}>GET</option> <option value="POST" selected={isSelected('POST')}>POST</option> <option value="PUT" selected={isSelected('PUT')}>PUT</option> <option value="PATCH" selected={isSelected('PATCH')}>PATCH</option> <option value="DELETE" selected={isSelected('DELETE')}>DELETE</option> </select> <input type="text" className="wide" name="url" placeholder="URL" value={setValue()} onChange={handleInput}></input> <label><button className="submitBtn" type="submit">Go!</button></label> </section> ); } function mapStateToProps(state) { return { type: state.request.type, url: state.request.url, }; } function mapDispatchToProps(dispatch) { return { setURL: (url) => dispatch(setURL(url)), setType: (type) => dispatch(setType(type)), } } export default connect( mapStateToProps, mapDispatchToProps )(URL);
function userCreator(name, score) { this.name = name; this.score = score; } userCreator.prototype.sayName = function() { console.log("I'm " + this.name); } userCreator.prototype.increment = function() { this.scope++; } const user1 = new userCreator('Phill', 2); const user2 = new userCreator('Tim', 4); user1.sayName(); function paidUserCreator(paidName, paidScore, accountBalance) { userCreator.call(this, paidName, paidScore); // userCreator.apply(this, [paidName, paidScore]) this.accountBalance = accountBalance; } paidUserCreator.prototype = Object.create(userCreate.prototype); paidUserCreator.prototype.increaseBalance = function() { this.accountBalance++; } const paidUser1 = new paidUserCreator('Alyssa', 8, 25); paidUser1.increaseBalance(); paidUser1.sayName() // I'm Alyssa
$(document).ready(function(){ $("img.edit").each(function(i){ //设置节点信息可编辑 setNodeEditable(this,i); }); }); function setNodeEditable(obj,i){ $(obj).css("cursor","pointer").click(function(){ var id = $(this).prev().attr('id'); var pid= $(this).prev().attr('pid'); var name = $(this).prev().attr('name'); var title = $(this).prev().attr('title'); if(''==title) { title = name; } $(".editForm").remove(); var html = '<span class="editForm"><div>'; html +='<fieldset><legend>Edit Node Info</legend>'; html += '<label>Name: </label>'+name+'<br />'; html += '<label>Title: </label><input type="text" class="title" value="'+title+'"><br />'; html += '<label>   </label><input type="button" value="Submit" class="submit"/>&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="Cancel" class="cancel"/><br />'; html += '</fieldset></div></span>'; $(this).after(html); $(".editForm div").show('slow'); $(".editForm input.submit").click(function(){ title = $(".editForm .title").val(); $.post(_URL_+"/update",{ 'id' : id, 'pid' : pid, 'name' : name, 'title': title },function(str){ if(str.substr(0,1)=='1') { if('0'==pid) { myAlert("Submit success!"); myLocation('',1000); } else{ id = str.substr(2); $(obj).prev().attr('class', 'c'+id); $(obj).prev().attr('id', id); $(obj).prev().attr('title', title); $(obj).prev().html(''==title ? name : title); $(obj).attr('src',IMAGE_FOLDER+'form_edit.gif'); $(".editForm").remove(); myAlert("Submit success!"); myOK(1000); } } else { myAlert(str); } }); }); $(".editForm input.cancel").click(function(){ $(".editForm div").hide('slow'); }); $(document).keydown(function(e){ var keyCode=e.keyCode ||window.event.keyCode; if(keyCode==27)//Esc { $(".editForm div").hide('slow'); } }); }); }
export const products = [ { _id: '1', name: 'Top G1', category: 'Gio', image: '/images/product-1.png', price: 300, brand: 'City', rating: 4.5, numReviews: 8, description: 'blue robot', countInStock: 10 }, { _id: '2', name: 'Top GP G2', category: 'Gundam', image: '/images/product-2.jpeg', price: 280, brand: 'City', rating: 3, numReviews: 3, description: 'robot with orrnage', countInStock: 5 }, { _id: '3', name: 'Guit G3', category: 'Unioql', image: '/images/product-3.jpeg', price: 500, brand: 'Bandi', rating: 2.5, numReviews: 7, description: 'bGG suit', countInStock: 4 }, { _id: '4', name: 'Top G4', category: 'Gundam', image: '/images/product-4.jpg', price: 1230, brand: 'Ghio', rating: 3, numReviews: 4, description: 'blue robot', countInStock: 0 }, { _id: '5', name: 'TYGI', category: 'Cioo', image: '/images/product-5.jpg', price: 3000, brand: 'Bandi', rating: 4.5, numReviews: 3, description: 'blue robot', countInStock: 4 }, { _id: '6', name: 'FAFA G', category: 'Cioo', image: '/images/product-6.jpg', price: 30, brand: 'Jueq', rating: 5, numReviews: 3, description: 'Hello FG', countInStock: 4 }, ];
export const Raven_conf = "https://56522fc35e9b4a5db5da92ca6652fd0a@sentry.io/1533391"; export const Version = "0.0.2"; // export const firebaseConfig = { // apiKey: "AIzaSyCVVtfr0pWoENIpv67-_PK_KE7D9L0tQjs", // authDomain: "panup-4ba27.firebaseapp.com", // databaseURL: "https://panup-4ba27.firebaseio.com", // projectId: "panup-4ba27", // storageBucket: "panup-4ba27.appspot.com", // messagingSenderId: "982615458649", // appId: "1:982615458649:web:45bbded47dc633c2" // }; // export const firebaseConfig = { // apiKey: "AIzaSyANaoJDIXK-94MICiJmWdSowlNF2VrBKHM", // authDomain: "snipper-010.firebaseapp.com", // databaseURL: "https://snipper-010.firebaseio.com", // projectId: "snipper-010", // storageBucket: "snipper-010.appspot.com", // messagingSenderId: "863369684354", // appId: "1:863369684354:web:da63e4fa07b0372f" // }; export const firebaseConfig = { apiKey: "AIzaSyD_2pelFQpsBASAFseRzEC6craRqvn6yMQ", authDomain: "panup-4ba27.firebaseapp.com", databaseURL: "https://panup-4ba27.firebaseio.com", projectId: "panup-4ba27", storageBucket: "panup-4ba27.appspot.com", messagingSenderId: "982615458649", appId: "1:982615458649:web:45bbded47dc633c2" };
import React from "react"; import Icon from "react-native-vector-icons/MaterialIcons"; import COLORS from "../../constants/Colors" import SIZES from "../../constants/Sizes" export default props => { let color = props.focused ? COLORS.tabItemActive : COLORS.tabItemInactive return ( <Icon name="add-alert" size={SIZES.tabIconSize} color={color} rounded /> ) }
/// <reference path="jquery.cookie.js" /> var map; var infowindow; var marker = new google.maps.Marker(); var ltlng = []; var markers = []; var array = []; var newmarkers = []; var accpo = "*Accpo Apikeyinizi yazınız*"; var xml = "Xml erişim linkinizi yazınız"; $(document).ready(function InitializeMap() { var latlng = new google.maps.LatLng(40.756, -73.986); var myOptions = { center: latlng, scrollWheel: false, zoom: 13 }; map = new google.maps.Map(document.getElementById("map"), myOptions); AddMarker(); }); function insertmarker() { markers = []; var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var labelIndex = 0; for (var i = 0; i < ltlng.length; i++) { marker = new google.maps.Marker({ map: map, position: ltlng[i], draggable: false, title: array[i].split(',')[2].trim(), content: "<div class='text-center'><h4>" + array[i].split(',')[2].trim() + "</h4></div><hr/><div class='btn-group text-center' style='margin:0 auto'><a class='btn btn-warning btn-sm' data-toggle='modal' data-target='#yeniwizard' onclick='EditPoint(\"" + i + "\")'>Düzenle</a><a class='btn btn-danger btn-sm' onclick='DeletePoint(\"" + array[i].split(',')[3].trim() + "\")'>Sil</a></div>", id: i, dataid: array[i].split(',')[3].trim() }); google.maps.event.addListener(marker, 'click', function () { // Calling the open method of the infoWindow if (!infowindow) { infowindow = new google.maps.InfoWindow(); } infowindow.setContent(this.content); infowindow.open(map, this); }); markers.push(marker); } } function AddMarker() { $.ajax({ type: "POST", url: "Default.aspx/SaveProject", contentType: "application/json; charset=utf-8", data: "{accpo:'" + accpo + "',xml:'" + xml + "'}", dataType: "json", async: false, cache: false, success: function (response) { DataList(); setmarker(); }, error: function (request, status, error) { } }); function DataList() { $.ajax({ type: "POST", url: "Default.aspx/GetData", contentType: "application/json; charset=utf-8", dataType: "json", async: false, cache: false, success: function (response) { $("#mapjs").html(response.d); }, error: function (request, status, error) { } }); } function setmarker() { ltlng = []; $.ajax({ type: "POST", url: "Default.aspx/GetMarker", contentType: "application/json; charset=utf-8", dataType: "json", async: false, cache: false, success: function (response) { array = response.d; for (var i = 0; i < array.length; i++) { ltlng.push(new google.maps.LatLng(array[i].split(',')[0].trim(), array[i].split(',')[1].trim())); } insertmarker(); map.setCenter(ltlng[ltlng.length - 1]); map.setZoom(8); }, error: function (request, status, error) { } }); } function deletelastmarkers() { for (var i = 0; i < newmarkers.length; i++) { newmarkers[i].setMap(null); } } google.maps.event.addListener(map, 'click', function (event) { //call function to create marker //delete the old marker deletelastmarkers(); if (markers.length == 0) { setmarker(); } marker = new google.maps.Marker({ position: event.latLng, map: map }); map.setCenter(marker.position); map.setZoom(12); newmarkers.push(marker); google.maps.event.addListener(marker, 'click', function () { if (!infowindow) { infowindow = new google.maps.InfoWindow(); } infowindow.setContent(" <h5>Burayı Kaydetmek Istermisiniz ?</h5><div class='text-center'><a data-toggle='modal' data-target='#yeniwizard' onclick='SaveArea(\"" + event.latLng + "\")' class='btn btn-info btn-sm' style='margin:0 auto'>Kaydet</a></div>"); infowindow.open(map, marker); }); //creer à la nouvelle emplacement }); } function ShowPoint(index) { map.setCenter(markers[index].position); if (!infowindow) { infowindow = new google.maps.InfoWindow(); } infowindow.setContent(markers[index].content); infowindow.open(map, markers[index]); markers[index].setAnimation(google.maps.Animation.j); map.setZoom(12); $('.point').removeClass('active'); $('#point-' + index).addClass('active'); } function SaveArea(latlng) { var array = latlng.split(','); var lat = array[0].replace('(', ''); var lng = array[1].replace(')', ''); $("#lat").val(lat); $("#lng").val(lng); $("#btnedit").hide(); $("#btnmodal").show(); } function Save() { if ($("#txtareaname").val().trim() != "") { var name = $("#txtareaname").val(); var lat = $("#lat").val(); var lng = $("#lng").val(); $.ajax({ type: "POST", url: "Default.aspx/SaveData", contentType: "application/json; charset=utf-8", data: "{name:'" + name + "',lat:'" + lat + "',lng:'" + lng + "'}", dataType: "json", async: false, cache: false, success: function (response) { $("#yeniwizard").modal('toggle'); location.reload(); $("#txtareaname").val(""); }, error: function (request, status, error) { } }); } } function EditPoint(index) { $("#txtareaname").val(markers[index].title); $("#lat").val(markers[index].position.lat()); $("#lng").val(markers[index].position.lng()); $("#dataid").text(markers[index].dataid); $("#btnedit").show(); $("#btnmodal").hide(); } function EditData() { if ($("#txtareaname").val().trim() != "") { var id = $("#dataid").text(); var name = $("#txtareaname").val(); $.ajax({ type: "POST", url: "Default.aspx/EditData", contentType: "application/json; charset=utf-8", data: "{dataid:'" + id + "',name:'" + name + "'}", dataType: "json", async: false, cache: false, success: function (response) { location.reload(); }, error: function (request, status, error) { console.log(error); } }); } } function DeletePoint(id) { swal({ title: "Nokta silinsin mi?", text: name, type: "warning", showCancelButton: true, cancelButtonText: "Hayır", confirmButtonColor: "#DD6B55", confirmButtonText: "Sil", closeOnConfirm: true }, function () { $.ajax({ type: "POST", url: "Default.aspx/DeleteData", contentType: "application/json; charset=utf-8", data: "{id:" + JSON.stringify(id) + "}", dataType: "json", async: false, cache: false, success: function (response) { if (response.d) { location.reload(); swal("Silindi!", "Nokta Başarıyla Silindi.", "success"); } else { swal("Hata", "Silme İşlemi Sırasında Bir Hata Meydana Geldi.", "error"); } }, error: function (request, status, error) { swal("Hata", "Bir Hatayla Karşılaşıldı", "error"); } }) }); } function Ara(address) { geocoder = new google.maps.Geocoder(); insertmarker(); var address = document.getElementById("aranankelime").value; geocoder.geocode({ 'address': address }, function (results, status) { console.log(results); if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); if (results[0].formatted_address) { region = results[0].formatted_address + '<br />'; } var infowindow = new google.maps.InfoWindow({ content: '<div style =width:400px; height:400px;>Konum Bilgisi:<br/>Ülke Adı:<br/>' + region + '<br/>Enlem-Boylam Bilgisi:<br/>' + results[0].geometry.location + '</div>' }); google.maps.event.addListener(marker, 'click', function () { // Calling the open method of the infoWindow infowindow.open(map, marker); }); google.maps.event.addListener(map, 'click', function (event) { //delete the old marker if (marker) { marker.setMap(null); insertmarker(); } //creer à la nouvelle emplacement marker = new google.maps.Marker({ position: event.latLng, map: map }); google.maps.event.addListener(marker, 'click', function () { if (!infowindow) { infowindow = new google.maps.InfoWindow(); } infowindow.setContent("<h5>Burayı Kaydetmek Istermisiniz ?</h5> <hr/><div class='text-center'> <a data-toggle='modal' data-target='#yeniwizard' onclick='SaveArea(\"" + event.latLng + "\")' class='btn btn-info btn-sm' style='margin:0 auto'>Kaydet</a></div>"); infowindow.open(map, marker); }); }); } else { alert("Geocode was not successful for the following reason: " + status); } }); }
import React, { Component } from "react"; import { connect } from "react-redux"; import { reduxForm, Field } from "redux-form"; import QueryString from "query-string"; import FormInputTextField from "../common/FormInputTextField"; import SearchLicenseDropdown from "./SearchDropdown"; import SearchForkCheckbox from "./SearchForkCheckbox"; import Button from "../common/Button"; // validators import { validateStars, validateQuery, requiredInput } from "../../utils/searchFormValidators"; import FIELDS from "./searchFields"; //actions import * as actions from "../../actions"; // css import "../../assets/css/searchForm.css"; function getValidators(field) { if (field === "query") { return [requiredInput, validateQuery]; } else if (field === "stars") { return [requiredInput, validateStars]; } } class SearchForm extends Component { renderFormFields() { const fieldMapper = { select: ({ label, name, gridClass, type, options }) => { return ( <SearchLicenseDropdown key={name} label={label} gridClass={gridClass} type={type} options={options} /> ); }, text: ({ label, name, gridClass, type }) => { // updateValue={() => { // if (name === "query") return formValues.query; // return formValues.stars; // } return ( <Field key={name} type={type} name={name} component={FormInputTextField} label={label} className={gridClass} validate={getValidators(name)} /> ); }, checkbox: ({ label, name, gridClass, type }) => { return ( <SearchForkCheckbox name={name} label={label} gridClass={gridClass} type={type} key={name} /> ); } }; return FIELDS.map((row, index) => { var rowFields = row.map(({ label, name, gridClass, type, options }) => { return fieldMapper[type]({ label, name, gridClass, type, options }); }); return ( <div key={index} className="row"> {rowFields} </div> ); }); } render() { let { handleFormSubmit, handleSubmit, invalid, formValues, license, fork, history, location } = this.props; return ( <div className="container search-form-container center"> <div className="form-heading"> Even Financial Github Repository Search </div> <form className="search-form" onSubmit={handleSubmit(() => handleFormSubmit(formValues, license, fork, history) )} > {this.renderFormFields()} <Button disable={invalid} /> </form> </div> ); } } // function getFormValuesFromQueryString(qString) { // let queryArray = qString.q.split(" "); // let formObj = { // query: queryArray[0], // stars: queryArray[1].split(":")[1] // }; // return formObj; // } function mapStateToProps(state) { // let formObj = getFormValuesFromQueryString( // QueryString.parse(ownProps.location.search) // ); return { formValues: state.form.searchForm && state.form.searchForm.values, license: state.selectedLicense, fork: state.showOnlyForkedRepos }; } export default reduxForm({ form: "searchForm" })(connect(mapStateToProps)(SearchForm));
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); if (!localStorage.overlist) { localStorage.setItem("overlist", ""); } export default new Vuex.Store({ state: { overthing: "", overnumber: localStorage.overlist.split(",").length }, mutations: { overlist(state, list) { state.overthing = list; if (!localStorage.overlist) { localStorage.setItem("overlist", list); state.overnumber = list.length; } else { localStorage.overlist = localStorage.overlist .split(",") .concat(list) .join(","); state.overnumber = localStorage.overlist.split(",").concat(list).length; } }, overnumber(state, list) { state.overnumber = list; } } });
var mongoose = require('mongoose'), schema = mongoose.Schema; var docterModel = new Schema({ _id : String, name: String, age : Number }); module.exports= mongoose.model('Doctar', docterModel);
const util = require("util"); const mysql = require("mysql2"); const dotenv = require("dotenv"); const { ErrorHandler } = require("./error"); dotenv.config(); /** * Connection to the database. * */ var pool = mysql.createPool({ connectionLimit: 10000, host: process.env.SQL_HOST, user: process.env.SQL_USER, password: process.env.SQL_PASSWORD, database: process.env.SQL_DATABASE, multipleStatements: true, }); pool.getConnection((err, connection) => { try { if (err) { console.error("Something went wrong connecting to the database ..: ",err); throw new ErrorHandler(500, "Can't connect to database"); } if (connection) connection.release(); return; } catch (exception) { throw exception; } }); pool = pool.promise(); module.exports = pool;
// // import 文を使って sub.js ファイルを読み込む。 // import {hello} from './sub'; // // // sub.jsに定義されたJavaScriptを実行する。 // hello(); // // Bootstrapのスタイルシート側の機能を読み込む // import "bootstrap/dist/css/bootstrap.min.css"; // // // BootstrapのJavaScript側の機能を読み込む // import "bootstrap"; // BootstrapのJavaScript側の機能を読み込む import "bootstrap"; // スタイルシートを読み込む import "./index.scss";
'use strict'; const express = require('express'); const router = express.Router(); const user = require('../service/user'); const tag = require('../domain/entity/tag'); // GET /users/:id router.get('/:id', (req, res) => { const id = parseInt(req.params.id); if (id === null || id === '') { res.status(412).json({}); return; } user.findById(id) .then((data) => { if (data === null) { res.status(404).json({}); return; } res.status(200).json({ body : { 'id': data.id, 'nickname': data.name, 'birth': data.birth, 'gender': data.gender }}); return; }) .catch((e) => { res.status(500).json({}); return; }); }); // GET /users/:id/profile?redirect={redirect} 프로필 테스트 필요 // false 일때 테스트 필요 router.get('/:id/profile', (req, res) => { const id = parseInt(req.params.id); const redirect = (req.query.redirect === 'true') || false; if (id === null || id === '') { res.status(412).json({}); return; } user.findById(id) .then((data) => { if (data === null) { res.status(404).json({}); return; } if (redirect) { res.redirect('https://s3.ap-northeast-2.amazonaws.com/' + data.profile); return; } res.json({body : 'https://s3.ap-northeast-2.amazonaws.com/' + data.profile}); return; }) .catch((e) => { res.status(500).json({}); return; }); }); // GET /users/:id/tags router.get('/:id/tags', (req, res) => { const id = parseInt(req.params.id); if (id === null || id === '') { res.status(412).json({}); return; } user.getTrack(id) .then((data) => { if(data === null) { res.status(404).json({}); return; } let ides = []; const tracks = data.tracks; for (let i = 0; i < tracks.length; i++) { ides.push(tracks[i].id); } if(tracks.length > 0) { user.getGenres(ides) .spread((results) => { ides = []; for (let i = 0; i < results.length; i++) { ides.push({ 'id': results[i].tagId }); } if(results.length > 0) { user.getTag(ides) .then((data) => { res.status(200).json({body : data}); return; }) .catch((e) => { res.status(500).json({}); return; }); }else { res.status(200).json(ides); return; } }) .catch((e) => { res.json(500); return; }); }else { res.status(200).json(ides); return; } }) .catch((e) => { res.status(500).json({}); return; }); }); // DELETE /users/:id router.delete('/:id', (req, res) => { const id = parseInt(req.params.id); if (id === null || id === '') { res.status(412).json({}); return; } user.destroy(id) .then((data) => { if (data === '' || data === null) { res.status(404).json({}); return; } res.status(204).json({}); return; }); }); module.exports = router;
// JavaScript Document var utm_source = "", utm_medium = "", utm_campaign = "", utm_term = "", utm_content = "", url_param = ""; function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } function _uGC(l, n, s) { if (!l || l == "" || !n || n == "" || !s || s == "") return "-"; var i, i2, i3, c = "-"; i = l.indexOf(n); i3 = n.indexOf("=") + 1; if (i > -1) { i2 = l.indexOf(s, i); if (i2 < 0) { i2 = l.length; } c = l.substring((i + i3), i2); } return c; } $(function () { var u_s = "(direct)"; var u_c = "(none)"; var ref = document.referrer; //if (ref) { // u_s = "http://" + ref.split("/")[2] + "/"; // u_c = 'referral'; //} utm_source = getQueryString("utm_source") || u_s; utm_medium = getQueryString("utm_medium") || u_c; utm_campaign = getQueryString("utm_campaign") || ''; utm_term = getQueryString("utm_term") || ''; utm_content = getQueryString("utm_content") || ''; if (utm_source == "" && utm_medium == "") { utm_source = _uGC(utmz, "utmcsr", "|"); utm_medium = _uGC(utmz, "utmcmd", "|"); } var browser = { versions: function () { var u = navigator.userAgent, app = navigator.appVersion; return { trident: u.indexOf('Trident') > -1, //IE内核 presto: u.indexOf('Presto') > -1, //opera内核 webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核 mobile: !!u.match(/AppleWebKit.*Mobile/) || !!u.match(/Windows Phone/) || !!u.match(/Android/) || !!u.match(/MQQBrowser/), //是否为移动终端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器 iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1, //是否iPad webApp: u.indexOf('Safari') == -1 //是否web应该程序,没有头部与底部 }; }() } if (utm_campaign != "") url_param += "?utm_campaign=" + utm_campaign; if (utm_term != "") { if (url_param != "") url_param += "&utm_term=" + utm_term; else url_param += "?utm_term=" + utm_term; } if (utm_content != "") { if (url_param != "") url_param += "&utm_content=" + utm_content; else url_param += "?utm_content=" + utm_content; } if ($.cookie('utm_source') == null) { $.cookie('utm_source', '' + utm_source + '', { expires: 365 }); } else { if ($.cookie('utm_source') != utm_source && utm_source != "(direct)") $.cookie('utm_source', '' + utm_source + '', { expires: 365 }); } if ($.cookie('utm_medium') == null) { $.cookie('utm_medium', '' + utm_medium + '', { expires: 365 }); } else { if ($.cookie('utm_medium') != utm_medium && utm_medium != "(none)") $.cookie('utm_medium', '' + utm_medium + '', { expires: 365 }); } if (utm_source != "(direct)") { if (url_param != "") url_param += "&utm_source=" + utm_source; else url_param += "?utm_source=" + utm_source; } if (utm_medium != "(none)") { if (url_param != "") url_param += "&utm_medium=" + utm_medium; else url_param += "?utm_medium=" + utm_medium; } $.cookie('utm_campaign', '' + utm_campaign + '', { expires: 365 }); $.cookie('utm_term', '' + utm_term + '', { expires: 365 }); $.cookie('utm_content', '' + utm_content + '', { expires: 365 }); //if (browser.versions.iPad) { // //存cookie // //如果传递了参数 // if (url_param != "") { // $.cookie('utm_campaign', '' + utm_campaign + '', { expires: 365 }); // $.cookie('utm_term', '' + utm_term + '', { expires: 365 }); // $.cookie('utm_content', '' + utm_content + '', { expires: 365 }); // } //} //else { // //电脑 // window.location.href = "http://www.vwbeetle.cn/pc/" + url_param; //} }); //var url = location.href; //var pos = url.indexOf("?"); //var str = ""; //if (pos != -1) { // str = url.substr(pos); //} //if (browser.versions.ios || browser.versions.android || browser.versions.iPhone || browser.versions.iPad) { // //手机 // window.location.href = "/valentine/mobi/" + str; //} else { // //电脑 // // window.location.href = "/xingzuo/" + str; //} $(function () { //var picsize = $('#downLoadMain .pic').size(); //$("#count").html("1/"+picsize); // if ($("#slider_big a").size() > 0) { // // var str = $("#slider_big").html(); // $("#slider_small").html(str); // // // $('#slider_big').slidesjs({ // width: 507, // height: 472, // callback: { // complete: function (n) { // $("#slider_small a").removeClass("cur"); // $("#slider_small a").eq(n - 1).addClass("cur"); // } // } // }); // $("#slider_small a").eq(0).addClass("cur"); // $("#slider_small a").click(function () { // var index = $(this).index(); // $(".slidesjs-pagination li").eq(index).find("a").click(); // }); // } // // $(window).bind('orientationchange', function (e) { // ort(); // }); // function ort() { // if (window.orientation == 0 || window.orientation == 180) { // // $("#view-potrait").show(); // } else { // // $("#view-potrait").hide(); // } // } // ort(); });
const express = require("express") const todo = require("../models").Todo const router = express.Router(); const Sequelize = require("sequelize") var Op = Sequelize.Op; exports.createTodo = (req,res) => { todo.create({ name: req.body.name }).then((todo) => { if(todo){ // return res.redirect("/") // return category res.json({ message: "success" }) } else{ res.json({ message: "error" }) } }) } exports.allTodo = async (req,res) => { const todos = await todo.findAll({ }) res.json({ todos: todos }); // return todos } exports.deleteTodo = async (req,res,next) => { todo.destroy( { where: { id: { [Op.eq]: req.params.todo_id, } } } ).then((data) =>{ if(data){ // res.redirect("/") res.json({ message: "success" }) } else{ res.json({ message: "ID does not exists" }) } }) } exports.updateTodo = async (req,res,next) => { todo.update({ name: req.body.name }, { where: { id: { [Op.eq]: req.params.todo_id } } } ) .then(() => { res.json({ message: "Success" }) }) .catch((error) => { res.json({ message: "Error" }) }) }
import Link from 'next/link'; import React from 'react'; const ServicesArea = () => { return ( <> <div className="ac-chose-area mb-130"> <div className="container ac-chose-bg"> <div className="row"> <ChoseItem duration='.3s' delay='.5s' icon='flaticon-group' title={<>Professional <br /> Team</>} text={'24+ Team Member'} /> <ChoseItem duration='.5s' delay='.7s' item_num={'tpchosebox-three'} color="fea-color-5" icon='fas fa-star' title={<>Competitive <br /> Rate</>} text={'100% Client Satisfied'} /> <ChoseItem duration='.7s' delay='.9s' item_num={'tpchosebox-two'} color="fea-color-4" icon='flaticon-web' title={<>Certified <br /> Globally</>} text={'65.04 k Reach'} /> <ChoseItem duration='.9s' delay='1s' icon='fas fa-star' title={<>Competitive <br /> Rate</>} text={'100% Client Satisfied'} /> </div> </div> </div> </> ); }; export default ServicesArea; const ChoseItem = ({ duration, delay, item_num, icon, title, text, color }) => { return ( <div className="col-xl-3 col-lg-6 col-md-6 col-12 wow tpfadeUp" data-wow-duration={duration} data-wow-delay={delay}> <div className="tp-chose-item mb-30"> <div className={`tpchosebox ${item_num && item_num}`}> <div className={`tpchosebox__icon ${color && color} mb-30`}> <a href="#"><i className={icon}></i></a> </div> <div className="tpchosebox__content"> <h4> <Link href="/service-details"> <a>{title}</a> </Link> </h4> <p>{text}</p> </div> </div> </div> </div> ) }
$(document).ready(function() { $("#square").click(function() { $("#circle").animate({top: 0}, 0).animate({top: '100%'}, 1500); }); });
const Home = () => (<div><h1>Home</h1></div>) export default Home
const initialState = null; export default(state = initialState, action) => { switch (action.type) { case 'SET_TICKER': return action.ticker; default: return state; }; }
module.exports={ 'login':"/act/login", 'getLoginImg':"/act/getCode", 'loginWeight':"/api/role/queryRoleMenus", 'loginOut':'/act/logout' }
// --------- Dependencies --------- let messages = require.main.require('./config/messages'); // Define common route configurations used across Dash let routes = { SETUP: [ { NAME: 'Facebook', ROUTE: 'groups', MESSAGE: messages.STATUS.FACEBOOK.GROUPS_UPDATED, METHOD: 'saveFacebookGroups' }, { NAME: 'Facebook', ROUTE: 'pages', MESSAGE: messages.STATUS.FACEBOOK.PAGES_UPDATED, METHOD: 'saveFacebookPages' }, { NAME: 'YouTube', ROUTE: 'subscriptions', MESSAGE: messages.STATUS.YOUTUBE.SUBSCRIPTIONS_UPDATED, METHOD: 'saveYouTubeSubs' } ], REMOVE: [ { NAME: 'Facebook', METHOD: 'removeFacebook' }, { NAME: 'YouTube', METHOD: 'removeYouTube' } ], AUTHENTICATION: [ { NAME: 'Facebook', SCOPE: ['user_managed_groups', 'user_likes'] }, { NAME: 'YouTube', SCOPE: [ 'https://www.googleapis.com/auth/youtube.force-ssl', 'https://www.googleapis.com/auth/youtube.readonly' ] } ], AUTH_CALLBACK: ['Facebook', 'YouTube'], REFRESH_TOKEN: ['Facebook', 'YouTube'] }; module.exports = routes;
window.GOVUKAdmin = window.GOVUKAdmin || {}; window.GOVUKAdmin.Modules = window.GOVUKAdmin.Modules || {};
//用来处理数据,比如获取数据,添加数据,删除数据等 const fs = require('fs'); const path = require('path'); const util = require('util'); const filepath = path.normalize(__dirname+'/../data/item.json'); //异步处理读取文件获取数据 const readFile = util.promisify(fs.readFile); async function get(){ //1.读取文件数据 const data = await readFile(filepath,{flag:'r',encoding:'utf-8'}) //2.返回数据 const arr = JSON.parse(data); return arr; } //异步处理读取文件获取数据 const writeFile = util.promisify(fs.writeFile); async function add(task){ //1.读取文件获取数据 const data = await readFile(filepath,{flag:'r',encoding:'utf-8'}) //2.将字符串数据转换成数组 const arr = JSON.parse(data); //3.生成任务对象并将其添加到数组中(时间托) const obj = { id:Date.now().toString(), task:task } arr.push(obj); //4.再将数组转换成字符串写入文件覆盖原来的内容 await writeFile(filepath,JSON.stringify(arr)) //5.返回任务对象 return obj; } //异步处理删除文件 async function del(id){ //1.读取文件获取数据 const data = await readFile(filepath,{flag:'r',encoding:'utf-8'}) //2.将字符串数据转换成数组 const arr = JSON.parse(data); //3.根据id将数组中对应的对象数据删除\ const newArr = arr.filter(function(item){ // console.log(item) return item.id != id; }) //4.再将数组转换成字符串写入文件覆盖原来的内容 await writeFile(filepath,JSON.stringify(newArr)); } module.exports = { get, add, del }
var intervalID; var laDiv; var redSquare; var canvas; var ctx; var size = 50; var x = 0; var y = 0; var speed = 10; function init(){ canvas = document.getElementById('canvas'); ctx = canvas.getContext("2d"); ctx.fillStyle = "red"; ctx.fillRect(0, 0, size, size); move(); } function move(){ intervalID = setInterval(squareMovePositive,100); } function squareMovePositive(){ x += speed; ctx.fillRect(x, y, size, size); ctx.clearRect(x-10, y, 10, size); if(x === canvas.width-size){ clearInterval(intervalID); intervalID = setInterval(squareMoveNegative,100); } } function squareMoveNegative(){ x += -speed; ctx.fillRect(x, y, size, size); ctx.clearRect(x+size, y, 10, size); if(x === 0){ clearInterval(intervalID); intervalID = setInterval(squareMovePositive,100); } }
import React, {createContext, useEffect, useState} from 'react'; import axios from 'axios'; export const Context = createContext(); export const Provider = ({children}) => { const [trackList, setTrackList] = useState([]); const [heading, setHeading] = useState('Top 10 Tracks'); useEffect(() => { const fetchData = async () => { const result = await axios(`https://cors-access-allow.herokuapp.com/https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=10&country=us&f_has_lyrics=1&apikey=${process.env.REACT_APP_MM_KEY}`); setTrackList(result.data.message.body.track_list); }; fetchData(); }, []); return ( <Context.Provider value={{trackList:[trackList, setTrackList], heading: [heading, setHeading]}}> {children} </Context.Provider> ) }
/**************************************************************************************** * LiveZilla ChatDisplayLayoutClass.js * * Copyright 2014 LiveZilla GmbH * All rights reserved. * LiveZilla is a registered trademark. * ***************************************************************************************/ function ChatDisplayLayoutClass() { } ChatDisplayLayoutClass.prototype.resizeAll = function() { this.resizeUserControlPanel(); this.resizeTicketList(); this.resizeTicketDetails(); this.resizeEmailDetails(); this.resizeOptions(); this.resizeResources(); this.resizeAddResources(); this.resizeEditResources(); this.resizeTicketReply(); this.resizeVisitorDetails(); this.resizeVisitorInvitation(); this.resizeOperatorForwardSelection(); this.resizeMessageForwardDialog(); this.resizeArchivedChat(); //console.log($(window).width() + ' x ' + $(window).height()); }; ChatDisplayLayoutClass.prototype.resizeTicketList = function() { if (lzm_chatDisplay.selected_view == 'tickets' && !lzm_chatDisplay.isApp && !lzm_chatDisplay.isMobile && $(window).width() > 1000) { var leftWidth = ($(window).width()-33-350); var rightWidth = (lzm_displayHelper.checkIfScrollbarVisible('ticket-list-body')) ? 305 - lzm_displayHelper.getScrollBarWidth() : 305; $('#ticket-list-left').css({width: leftWidth+'px'}); $('#ticket-list-right').css({width: rightWidth+'px'}); $('.ticket-list').css({height: ($('#ticket-list-body').height() - 12) + 'px'}); } }; ChatDisplayLayoutClass.prototype.resizeTicketDetails = function() { var myHeight = Math.max($('#ticket-details-body').height(), $('#email-list-body').height()); myHeight = Math.max(myHeight, $('#visitor-information-body').height()); var myWidth = Math.max($('#ticket-details-body').width(), $('#email-list-body').width()); myWidth = Math.max(myWidth, $('#visitor-information-body').width()); if (myHeight > 0) { var historyHeight, detailsHeight; if (myHeight > 600) { historyHeight = 245; detailsHeight = myHeight - historyHeight - 90; } else { detailsHeight = (myHeight > 535) ? 265 : (myHeight > 340) ? 200 : 120; historyHeight = myHeight - detailsHeight - 90; } var newInputHeight = Math.max(detailsHeight - 48, 150); var commentInputHeight = Math.max(140, myHeight - 44); $('.ticket-history-placeholder-content').css({height: historyHeight + 'px'}); $('.ticket-details-placeholder-content').css({height: detailsHeight + 'px'}); $('#ticket-comment-list').css({'min-height': (detailsHeight - 22) + 'px'}); $('#ticket-message-text').css({'min-height': (detailsHeight - 22) + 'px'}); $('#ticket-message-details').css({'min-height': (detailsHeight - 22) + 'px'}); $('#ticket-attachment-list').css({'min-height': (detailsHeight - 22) + 'px'}); $('#ticket-message-list').css({'min-height': (historyHeight - 22) + 'px'}); $('#ticket-ticket-details').css({'min-height': (historyHeight - 22) + 'px'}); $('#ticket-new-input').css({height: newInputHeight + 'px'}); $('#comment-text').css({'min-height': (myHeight - 22)+'px'}); $('#comment-input').css({width: (myWidth - 28)+'px', height: commentInputHeight + 'px'}); } }; ChatDisplayLayoutClass.prototype.resizeTicketReply = function() { if ($('#ticket-details-body').length > 0) { var displayViews = {'reply': 2, 'preview': 1}; var tabControlWidth = 0, ticketDetailsBodyHeight = $('#ticket-details-body').height(); for (var view in displayViews) { if (displayViews.hasOwnProperty(view)) { if ($('#' + view + '-placeholder-content-' + displayViews[view]).css('display') == 'block') { tabControlWidth = $('#' + view + '-placeholder-content-' + displayViews[view]).width(); } } } $('.reply-placeholder-content').css({height: (ticketDetailsBodyHeight - 40) + 'px'}); $('#message-comment-text').css({'min-height': (ticketDetailsBodyHeight - 62) + 'px'}); $('#message-attachment-list').css({'min-height': (ticketDetailsBodyHeight - 62) + 'px'}); if (tabControlWidth != 0) { $('#preview-comment-text').css({'min-height': (ticketDetailsBodyHeight - 62) + 'px'}); $('#new-message-comment').css({width: (tabControlWidth - 28) + 'px', height: (ticketDetailsBodyHeight - 85) + 'px'}); } } }; ChatDisplayLayoutClass.prototype.resizeEmailDetails = function() { if ($('#email-list-body').length > 0) { var myHeight = $('#email-list-body').height() + 10; var listHeight = Math.floor(Math.max(myHeight / 2, 175) - 45); var contentHeight = (myHeight - listHeight) - 93; $('.email-list-placeholder-content').css({height: listHeight + 'px'}); $('.email-placeholder-content').css({height: contentHeight + 'px'}); $('#incoming-email-list').css({'min-height': (listHeight - 22) + 'px'}); $('#email-text').css({'min-height': ($('.email-placeholder-content').height() - 95) + 'px'}); $('#email-content').css({'min-height': (contentHeight - 22) + 'px'}); $('#email-attachment-list').css({'min-height': (contentHeight - 22) + 'px'}); } }; ChatDisplayLayoutClass.prototype.resizeOptions = function() { if ($('#user-settings-dialog-body').length > 0) { var tabContentHeight = $('#user-settings-dialog-body').height() - 40; $('.settings-placeholder-content').css({height: tabContentHeight+'px'}); $('#notification-settings').css({'min-height': (tabContentHeight - 22) + 'px'}); var chatSettingsHeight = tabContentHeight - 22, backgroundSettingsHeight = 0; if (lzm_chatDisplay.isApp && appOs == 'android') { chatSettingsHeight = Math.max(35, Math.floor(tabContentHeight / 2) - 22); backgroundSettingsHeight = Math.max(35, Math.floor(tabContentHeight / 2) - 27); } $('#chat-settings').css({'min-height': chatSettingsHeight + 'px'}); if (lzm_chatDisplay.isApp && appOs == 'android') { $('#background-settings').css({'min-height': backgroundSettingsHeight + 'px'}); } var posBtnWidth = 0, posBtnHeight = 0; $('.position-change-buttons-up').each(function() { posBtnWidth = Math.max(posBtnWidth, $(this).width()); posBtnHeight = Math.max(posBtnHeight, $(this).height()); }); var positionButtonPadding = Math.floor((18 - posBtnHeight) / 2) + 'px ' + Math.ceil((18 - posBtnWidth) / 2) + 'px ' + Math.ceil((18 - posBtnHeight) / 2) + 'px ' + Math.floor((18 - posBtnWidth) / 2) + 'px'; $('.position-change-buttons-up').css('padding', positionButtonPadding); $('.position-change-buttons-down').css('padding', positionButtonPadding); } }; ChatDisplayLayoutClass.prototype.resizeUserControlPanel = function() { var userstatusButtonWidth = 50; var usersettingsButtonWidth = 150; var mainArticleWidth = $('#content_chat').width(); if (mainArticleWidth > 380) { usersettingsButtonWidth = 250; } else if (mainArticleWidth > 355) { usersettingsButtonWidth = 225; } else if (mainArticleWidth > 330) { usersettingsButtonWidth = 200; } else if (mainArticleWidth > 305) { usersettingsButtonWidth = 175; } var wishlistButtonWidth = 40; lzm_chatDisplay.blankButtonWidth = mainArticleWidth - userstatusButtonWidth - usersettingsButtonWidth - wishlistButtonWidth - 5; $('#userstatus-button').css({width: userstatusButtonWidth+'px'}); $('#usersettings-button').css({width: usersettingsButtonWidth+'px'}); $('#wishlist-button').css({width: wishlistButtonWidth+'px'}); $('#blank-button').css({width: lzm_chatDisplay.blankButtonWidth+'px'}); $('#wishlist-button').children('.ui-btn-inner').css({'padding-left': '0px'}); $('#blank-button').find('.ui-btn-inner').css({'padding-left': '3px', 'padding-right': '5px'}); if (lzm_chatDisplay.debuggingDisplayWidth != mainArticleWidth) { lzm_chatDisplay.debuggingDisplayWidth = mainArticleWidth; } }; ChatDisplayLayoutClass.prototype.resizeResources = function() { var resultListHeight; if ($('#qrd-tree-body').children('div').length > 0) { $('.qrd-tree-placeholder-content').css({height: ($('#qrd-tree-body').height() - 40) + 'px'}); resultListHeight = $('#qrd-tree-body').height() - $('#search-input').height() - 89; $('#search-results').css({'min-height': resultListHeight + 'px'}); $('#recently-results').css({'min-height': ($('#qrd-tree-body').height() - 62) + 'px'}); $('#all-resources').css({'min-height': ($('#qrd-tree-body').height() - 62) + 'px'}); } else if($('#qrd-tree-dialog-body').length > 0) { $('.qrd-tree-placeholder-content').css({height: ($('#qrd-tree-dialog-body').height() - 40) + 'px'}); resultListHeight = $('#qrd-tree-dialog-body').height() - $('#search-input').height() - 89; $('#search-results').css({'min-height': resultListHeight + 'px'}); $('#recently-results').css({'min-height': ($('#qrd-tree-dialog-body').height() - 62) + 'px'}); $('#all-resources').css({'min-height': ($('#qrd-tree-dialog-body').height() - 62) + 'px'}); } }; ChatDisplayLayoutClass.prototype.resizeAddResources = function() { if ($('#qrd-add-body').length > 0 || $('#qrd-tree-dialog-body').length > 0 || $('#ticket-details-body').length > 0) { var qrdTextHeight = Math.max((lzm_chatDisplay.FullscreenDialogWindowHeight - 307), 100); var textWidth = lzm_chatDisplay.FullscreenDialogWindowWidth - 50; if (lzm_displayHelper.checkIfScrollbarVisible('qrd-add-body') || lzm_displayHelper.checkIfScrollbarVisible('qrd-tree-dialog-body') || lzm_displayHelper.checkIfScrollbarVisible('ticket-details-body')) { textWidth -= lzm_displayHelper.getScrollBarWidth(); } var thisQrdTextInnerCss = { width: (textWidth - 2)+'px', height: (qrdTextHeight - 20)+'px', border: '1px solid #ccc', 'background-color': '#f5f5f5' }; var thisQrdTextInputCss = { width: (textWidth - 2)+'px', height: (qrdTextHeight - 20)+'px', 'box-shadow': 'none', 'border-radius': '0px', padding: '0px', margin: '0px', border: '1px solid #ccc' }; var thisQrdTextInputControlsCss; thisQrdTextInputControlsCss = { width: (textWidth - 2)+'px', height: '15px', 'box-shadow': 'none', 'border-radius': '0px', padding: '0px', margin: '7px 0px', 'text-align': 'left' }; var thisTextInputBodyCss = { width: (textWidth - 2)+'px', height: (qrdTextHeight - 51)+'px', 'box-shadow': 'none', 'border-radius': '0px', padding: '0px', margin: '0px', 'background-color': '#ffffff', 'overflow-y': 'hidden', 'border-top': '1px solid #ccc' }; var myHeight = Math.max($('#qrd-add-body').height(), $('#qrd-tree-dialog-body').height(), $('#ticket-details-body').height()); $('#add-resource').css({'min-height': (myHeight - 61) +'px'}); $('#qrd-add-text-inner').css(thisQrdTextInnerCss); $('#qrd-add-text-controls').css(thisQrdTextInputControlsCss); $('#qrd-add-text').css(thisQrdTextInputCss); $('#qrd-add-text-body').css(thisTextInputBodyCss); var uiWidth = Math.min(textWidth - 10, 300); var selectWidth = uiWidth + 10; $('.short-ui').css({width: uiWidth + 'px'}); $('select.short-ui').css({width: selectWidth + 'px'}); $('.long-ui').css({width: (textWidth - 10) + 'px'}); $('select.long-ui').css({width: textWidth + 'px'}); } }; ChatDisplayLayoutClass.prototype.resizeEditResources = function() { if ($('#qrd-edit-body').length > 0) { var qrdTextHeight = Math.max((lzm_chatDisplay.FullscreenDialogWindowHeight - 251), 100); var textWidth = lzm_chatDisplay.FullscreenDialogWindowWidth - 50; if (lzm_displayHelper.checkIfScrollbarVisible('qrd-edit-body') || lzm_displayHelper.checkIfScrollbarVisible('qrd-tree-dialog-body') || lzm_displayHelper.checkIfScrollbarVisible('ticket-details-body')) { textWidth -= lzm_displayHelper.getScrollBarWidth(); } var thisQrdTextInnerCss = { width: (textWidth - 2)+'px', height: (qrdTextHeight - 20)+'px', border: '1px solid #ccc', 'background-color': '#f5f5f5' }; var thisQrdTextInputCss = { width: (textWidth - 2)+'px', height: (qrdTextHeight - 20)+'px', 'box-shadow': 'none', 'border-radius': '0px', padding: '0px', margin: '0px', border: '1px solid #ccc' }; var thisQrdTextInputControlsCss; thisQrdTextInputControlsCss = { width: (textWidth - 2)+'px', height: '15px', 'box-shadow': 'none', 'border-radius': '0px', padding: '0px', margin: '7px 0px', 'text-align': 'left' }; var thisTextInputBodyCss = { width: (textWidth - 2)+'px', height: (qrdTextHeight - 51)+'px', 'box-shadow': 'none', 'border-radius': '0px', padding: '0px', margin: '0px', 'background-color': '#ffffff', 'overflow-y': 'hidden', 'border-top': '1px solid #ccc' }; var myHeight = Math.max($('#qrd-edit-body').height(), $('#qrd-tree-dialog-body').height(), $('#ticket-details-body').height()); $('#edit-resource').css({'min-height': (myHeight - 61) +'px'}); $('#edit-resource-inner').css({width: textWidth + 'px'}); $('#qrd-edit-text-inner').css(thisQrdTextInnerCss); $('#qrd-edit-text-controls').css(thisQrdTextInputControlsCss); $('#qrd-edit-text').css(thisQrdTextInputCss); $('#qrd-edit-text-body').css(thisTextInputBodyCss); var uiWidth = Math.min(textWidth - 10, 300); var selectWidth = uiWidth + 10; $('.short-ui').css({width: uiWidth + 'px'}); $('select.short-ui').css({width: selectWidth + 'px'}); $('.long-ui').css({width: (textWidth - 10) + 'px'}); $('select.long-ui').css({width: textWidth + 'px'}); } }; ChatDisplayLayoutClass.prototype.resizeVisitorDetails = function() { if ($('#visitor-information-body').length > 0) { var visBodyheight = $('#visitor-information-body').height(); var visBodyWidth = $('#visitor-information-body').width(); var contentHeight = visBodyheight - 40; var upperFieldsetHeight = Math.max(Math.floor(contentHeight / 3), 120); var lowerFieldsetHeight = Math.max(contentHeight - upperFieldsetHeight - 49, 120); var inputHeight = Math.max(140, visBodyheight - 44); var scrollbarHeight = 0; $('.visitor-info-placeholder-content').css({height: contentHeight + 'px'}); $('#visitor-comment-list').css({'min-height': upperFieldsetHeight + 'px'}); $('#visitor-comment-text').css({'min-height': lowerFieldsetHeight + 'px'}); $('#visitor-invitation-list').css({'min-height': (contentHeight - 22) + 'px'}); $('#visitor-history-list').css({'min-height': (contentHeight - 22) + 'px'}); $('#visitor-details-list').css({'min-height': (contentHeight - 22) + 'px'}); $('#comment-text').css({'min-height': (visBodyheight - 22) + 'px'}); $('#comment-input').css({width: (visBodyWidth - 28)+'px', height: inputHeight + 'px'}); scrollbarHeight = (lzm_displayHelper.checkIfScrollbarVisible('visitor-info-placeholder-content-4', 'horizontal')) ? lzm_displayHelper.getScrollBarHeight() : 0; $('#matching-chats-inner').css({'min-height': (upperFieldsetHeight - 15 - scrollbarHeight) + 'px'}); $('#chat-content-inner').css({'min-height': (lowerFieldsetHeight - 14) + 'px'}); scrollbarHeight = (lzm_displayHelper.checkIfScrollbarVisible('visitor-info-placeholder-content-5', 'horizontal')) ? lzm_displayHelper.getScrollBarHeight() : 0; $('#matching-tickets-inner').css({'min-height': (upperFieldsetHeight - 15 - scrollbarHeight) + 'px'}); $('#ticket-content-inner').css({'min-height': (lowerFieldsetHeight + 15) + 'px'}); } }; ChatDisplayLayoutClass.prototype.resizeVisitorInvitation = function() { if ($('#chat-invitation-body').length > 0) { var invTextHeight = Math.max((lzm_chatDisplay.dialogWindowHeight - 235), 100); var textWidth = lzm_chatDisplay.dialogWindowWidth - 39; if (lzm_displayHelper.checkIfScrollbarVisible('chat-invitation-body')) { textWidth -= lzm_displayHelper.getScrollBarWidth(); } var thisInvitationTextCss = {width: textWidth+'px', height: invTextHeight+'px'}; var thisInvitationTextInnerCss = {width: textWidth+'px', height: (invTextHeight - 20)+'px'}; var thisTextInputCss = {width: textWidth+'px', height: (invTextHeight - 20)+'px'}; var thisTextInputControlsCss; if (!lzm_chatDisplay.isMobile && !lzm_chatDisplay.isApp) { thisTextInputControlsCss = {width: textWidth+'px', height: '15px'}; } var thisTextInputBodyCss = {width: textWidth+'px', height: (invTextHeight - 50)+'px'}; $('#user-invite-form').css({'min-height': ($('#chat-invitation-body').height() - 22) + 'px'}); $('#invitation-text-div').css(thisInvitationTextCss); $('#invitation-text-inner').css(thisInvitationTextInnerCss); $('#invitation-text').css(thisTextInputCss); $('#invitation-text-controls').css(thisTextInputControlsCss); if (!lzm_chatDisplay.isMobile && !lzm_chatDisplay.isApp) { $('#invitation-text-body').css(thisTextInputBodyCss); } var langSelWidth = $('#language-selection').parent().width(); var groupSelWidth = $('#group-selection').parent().width(); var browserSelWidth = $('#browser-selection').parent().width(); $('#language-selection').css({width: langSelWidth + 'px'}); $('#group-selection').css({width: groupSelWidth + 'px'}); $('#browser-selection').css({width: browserSelWidth + 'px'}); } }; ChatDisplayLayoutClass.prototype.resizeOperatorForwardSelection = function() { if ($('#operator-forward-selection-body').length > 0) { var fwdTextHeight = Math.max((lzm_chatDisplay.dialogWindowHeight - 195), 100); var selWidth = lzm_chatDisplay.dialogWindowWidth - 38; if (lzm_displayHelper.checkIfScrollbarVisible('operator-forward-selection')) { selWidth -= lzm_displayHelper.getScrollBarWidth(); } $('#forward-text').css({width: selWidth + 'px', height: fwdTextHeight + 'px'}); $('#fwd-container').css({'min-height': ($('#operator-forward-selection-body').height() - 22) + 'px'}); } }; ChatDisplayLayoutClass.prototype.resizeMessageForwardDialog = function() { if ($('#message-forward-placeholder').length > 0) { var contentHeigth = $('#ticket-details-body').height() - 40; $('.message-forward-placeholder-content').css({height: contentHeigth + 'px'}); var inputMaxWidth = $('#message-forward-placeholder-content-0').width() - 18; if (lzm_displayHelper.checkIfScrollbarVisible('message-forward-placeholder-content-0')) { inputMaxWidth -= lzm_displayHelper.getScrollBarWidth(); } var filesHeight = (!isNaN(parseInt($('#forward-files').height()))) ? $('#forward-files').height() + 45 : 0; var inputWidth = Math.min(500, inputMaxWidth); var textareaHeight = Math.max(100, $('#message-forward-placeholder-content-0').height() - 166 - filesHeight); $('#forward-email-addresses').css({width: inputWidth}); $('#forward-subject').css({width: inputWidth}); $('#forward-text').css({width: (inputMaxWidth - 12) + 'px', height: textareaHeight + 'px'}); } }; ChatDisplayLayoutClass.prototype.resizeArchivedChat = function() { if ($('#matching-chats-body').length > 0) { var myBodyHeight = $('#matching-chats-body').height(); var listHeight = Math.max(200, Math.floor((myBodyHeight - 39) / 2)); var contentHeight = myBodyHeight - listHeight - 44; var listScrollbarHeight = (lzm_displayHelper.checkIfScrollbarVisible('matching-chats-placeholder-content-0', 'horizontal')) ? lzm_displayHelper.getScrollBarHeight() : 0; $('.matching-chats-placeholder-content').css({'height': (myBodyHeight - 39) + 'px'}); $('#matching-chats-inner').css({'min-height': (listHeight - 22 - listScrollbarHeight) + 'px'}); $('#chat-content-inner').css({'min-height': (contentHeight - 22) + 'px'}); } }; ChatDisplayLayoutClass.prototype.resizeFilterCreation = function() { var myHeight = $('#visitor-filter-body').height(); var upperFieldsetHeight = 100; var lowerFieldsetHeight = myHeight - upperFieldsetHeight - 93; $('.visitor-filter-placeholder-content').css({height: (myHeight - 39) + 'px'}); $('#visitor-filter-main').css({'min-height': upperFieldsetHeight + 'px'}); $('#visitor-filter-base').css({'min-height': lowerFieldsetHeight + 'px'}); $('#visitor-filter-reason').css({'min-height': (myHeight - 61) + 'px'}); $('#visitor-filter-expiration').css({'min-height': (myHeight - 61) + 'px'}); };
export class RestaurantCalendar extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({ mode: "open" }); const template = document.getElementById("RestaurantCalendar"); const fragment = document.importNode(template.content, true); shadowRoot.appendChild(fragment); const now = new Date(); this.year = now.getFullYear(); this.month = now.getMonth(); this.$sr = $(shadowRoot); this.$sr.find("#month-prev").on("click", this.onMonthPrev.bind(this)); this.$sr.find("#month-next").on("click", this.onMonthNext.bind(this)); this.$sr.find(".cells").on("click", this.onCellsClick.bind(this)); this.renderYearAndMonth(); } renderYearAndMonth() { const year = this.year; const month = this.month; const first = new Date(year, month, 1); const last = new Date(year, month + 1, 0); const offset = first.getDay(); const count = last.getDate(); const $cells = this.$sr.find(".cell"); const monthName = first.toLocaleString("en-us", { month: "long" }); this.$sr.find("#year-month").text(`${monthName} ${year}`); // Cells before this month const lastDayOfLastMonth = new Date(year, month, 0).getDate(); for (let i = 0; i < offset; i++) { $cells .eq(i) .text(lastDayOfLastMonth - offset + i + 1) .attr("disabled", true); } // Cells for this month for (let i = 0; i < count; i++) { $cells .eq(offset + i) .text(i + 1) .attr("disabled", false); } // Cells after this month for (let i = 0; i < 42 - count - offset; i++) { $cells .eq(offset + count + i) .text(i + 1) .attr("disabled", true); } } onMonthPrev() { this.month -= 1; if (this.month === -1) { this.month = 11; this.year -= 1; } this.renderYearAndMonth(); } onMonthNext() { this.month += 1; if (this.month === 12) { this.month = 0; this.year += 1; } this.renderYearAndMonth(); } onCellsClick(event) { const day = Number(event.target.innerText); const date = new Date(this.year, this.month, day, 0, 0, 0, 0); const newEvent = new CustomEvent("datechange", { detail: date }); this.dispatchEvent(newEvent); } }
import MouseTool from "./mouseTool"; import * as Registry from "../../core/registry"; import TextFeature from "../../core/textFeature"; import SimpleQueue from "../../utils/simpleQueue"; import paper from "paper"; import PositionTool from "./positionTool"; import Params from "../../core/params"; export default class InsertTextTool extends MouseTool { constructor() { super(); this.typeString = "TEXT"; this.setString = "Standard"; this.currentFeatureID = null; let ref = this; this.lastPoint = null; this.showQueue = new SimpleQueue( function() { ref.showTarget(); }, 20, false ); this.up = function(event) { // do nothing }; this.move = function(event) { ref.lastPoint = MouseTool.getEventPosition(event); ref.showQueue.run(); }; this.down = function(event) { Registry.viewManager.killParamsWindow(); paper.project.deselectAll(); ref.createNewFeature(MouseTool.getEventPosition(event)); }; } createNewFeature(point) { let newFeature = TextFeature.makeFeature( Registry.text, this.typeString, this.setString, new Params( { position: PositionTool.getTarget(point), height: 200 }, { position: "Point" }, { height: "Float", text: "String" } ) ); // this.currentFeatureID = newFeature.getID(); Registry.currentLayer.addFeature(newFeature); Registry.viewManager.saveDeviceState(); } showTarget() { let target = PositionTool.getTarget(this.lastPoint); Registry.viewManager.updateTarget(this.typeString, this.setString, target); } }
var main = function () { }; function changeText() { var date= new Date(); text = String(date); document.getElementById('pText').innerHTML=date.toDateString(); document.getElementById('Hour').innerHTML= date.getHours(); document.getElementById('Minute').innerHTML=date.getMinutes(); document.getElementById('Second').innerHTML=date.getSeconds(); } function changePicture(image){ document.getElementById("imgClickAndChange").src = image; } $(document).ready(main);
import React from "react"; import axios from "axios"; import { BrowserRouter as Router, Route } from "react-router-dom"; import HeaderForm from "./components/HeaderForm"; import RedirectionsList from "./components/RedirectionsList"; import Redirector from "./components/Redirector"; // declare and export component export default class App extends React.Component { //use construtor if you want to do something prior to componenDidMount // state own by the component state = { isLoading: true, // to toggle when loading is done redirections: [] //array all of existing redirections }; //retrieve all current redirections that exist on the server side : async componentDidMount() { //Debug: check components has been used: /* console.log( "componentDidMount has been called from ", this.constructor.name ); */ axios .get(`https://short-url-back-florent-argod.herokuapp.com/redirection`) .then(response => { //Debug: check response content: // console.log(response.data); this.setState({ redirections: response.data, //pu isLoading: false // loading done }); }); } // Update component state when a user submit a new url to short handleSubmit = newRedirection => { console.log("handleSubmit has been called from App"); let nextRedirections = [newRedirection, ...this.state.redirections]; this.setState({ redirections: nextRedirections }); }; //render App :) render() { if (this.state.isLoading) { console.log("loading"); // anything you want to render before loading end return null; } // anything you want to render after loading const { redirections } = this.state; //destructuring in case code evolution and growing state return ( <Router> <div> {/* <div>Je suis le composant {this.constructor.name}</div> use for debug at the origin*/} <HeaderForm onSubmit={this.handleSubmit} /> </div> <Route exact path="/" render={() => { return <RedirectionsList redirections={redirections} />; // display redirections list }} /> <Route path="/:fromUrlKey" component={Redirector} /> </Router> ); } }
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Search from '../src/component/Search'; import { BrowserRouter as Router, Route, Link, withRouter } from 'react-router-dom' import Create from './component/CreateFormer'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as userActions from './actions/userActions'; import Farmers from './component/ListForms'; class App extends Component { constructor(props){ super(props); } render() { return ( <div className="App"> <header className="App-header"> <h1 className="App-title">Welcome to Farmer</h1> </header> <div> <nav> <Link to="/create"> Create Farmer</Link> </nav> <nav> <Link to="/farmers">View Farmer</Link> </nav> <Route path="/create" component={Create}/> <div> <Route path="/farmers" component={Farmers}/> </div> <div> </div> </div> <div className="footer"> </div> </div> ); } } function mapDispatchToProps(dispatch) { return { action: bindActionCreators(userActions, dispatch) } } function mapStateToProps(state, ownProps) { return { user: state.user } } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App))
import jsonp from './jsonp' import {commonConfig,options,OK} from './config' import axios from 'axios' export function getSingerList() { const url = 'https://c.y.qq.com/v8/fcg-bin/v8.fcg' const data = Object.assign({}, commonConfig, { channel: 'singer', page: 'list', key: 'all_all_all', pagesize: 100, pagenum: 1, hostUin: 0, needNewCode: 0, platform: 'yqq', g_tk:1664029744 }) return jsonp(url, data, options) } export function getsingerDetail(singerId) { const url = 'http://c.y.qq.com/v8/fcg-bin/fcg_v8_singer_track_cp.fcg' const data = Object.assign({}, commonConfig, { hostUin: 0, needNewCode: 0, platform: 'yqq', order: 'listen', begin: 0, num: 80, songstatus: 1, singermid: singerId }) return jsonp(url, data, options) } export function getTopList() { const url = 'https://c.y.qq.com/v8/fcg-bin/fcg_myqq_toplist.fcg' const data = Object.assign({}, commonConfig, { uin: 0, needNewCode: 1, platform: 'h5' }) return jsonp(url, data, options) } export function getMusicList(topid) { const url = 'https://c.y.qq.com/v8/fcg-bin/fcg_v8_toplist_cp.fcg' const data = Object.assign({}, commonConfig, { topid, needNewCode: 1, uin: 0, tpl: 3, page: 'detail', type: 'top', platform: 'h5' }) return jsonp(url, data, options) }
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Die Software darf unter den Bedingungen // der APGL ( Affero Gnu Public Licence ) genutzt werden // // weblet: warehouse/outgoing/detail // ================================================================================ { var i; var str = ""; var ivalues = { schema : 'mne_warehouse', query : 'partoutgoing', okfunction : 'partoutgoing_ok', delfunction : 'partoutgoing_del', fetchfunction : 'partoutgoing_fetch', orderfunction : 'partoutgoing_order', showbuttons : true, revokelocation : 'revokelocation', revokelocationid : 'tostoragelocationid' }; var svalues = { }; weblet.initDefaults(ivalues, svalues); weblet.loadview(); weblet.obj.mkbuttons.push( { id : "fetch", value : weblet.txtGetText("#mne_lang#Abgeholt#"), space : 'before' } ); weblet.obj.mkbuttons.push( { id : "order", value : weblet.txtGetText("#mne_lang#Auftrag setzen#") } ); if ( weblet.initpar.showbuttons != true ) weblet.obj.mkbuttons = []; var attr = { hinput : false, partidInput : { inputcheckobject : "partname" }, spartstoragelocationidInput : { inputcheckobject : "storagelocationname" }, outstoragelocationidInput : { inputcheckobject : "outstoragelocationname" }, outstorageidInput : { checktype : 'notempty' } } weblet.findIO(attr); weblet.showLabel(); weblet.showids = new Array('partoutgoingid'); weblet.defvalues = { 'outstorageid' : null }; if ( weblet.initpar.showbuttons == true ) { weblet.titleString.add = weblet.txtGetText("#mne_lang#Auslagerung hinzufügen"); weblet.titleString.mod = weblet.txtGetText("#mne_lang#Auslagerung bearbeiten"); } else { weblet.obj.title = null; } weblet.showValue = function(weblet, param) { if ( weblet == null || typeof weblet.act_values.partoutgoingid == 'undefined' || weblet.act_values.partoutgoingid == '################') { this.add(); return; } MneAjaxWeblet.prototype.showValue.call(this,weblet, {noinputcheck : true} ); } weblet.ok = function(setdepend) { var p = { schema : this.initpar.schema, name : this.initpar.okfunction, typ0 : "text", typ1 : "text", typ2 : "text", typ3 : "text", typ4 : "long", typ5 : "text", sqlend : 1 } p = this.addParam(p, "par0", this.obj.inputs.partoutgoingid); p = this.addParam(p, "par1", this.obj.inputs.outstoragelocationid); p = this.addParam(p, "par2", this.obj.inputs.spartstoragelocationid); p = this.addParam(p, "par3", this.obj.inputs.orderproductpartid); p = this.addParam(p, "par4", this.obj.inputs.count); p = this.addParam(p, "par5", this.obj.inputs.personid); if ( MneAjaxWeblet.prototype.write.call(this,'/db/utils/connect/func/execute.xml', p) == 'ok') { this.act_values.partoutgoingid = this.act_values.result; this.showValue(this); this.setDepends("showValue"); return false; } return true; } weblet.del = function() { if ( this.noconfirm != true ) if ( this.confirm(this.txtSprintf(this.titleString.del, this.act_values[this.titleString.delid])) != true ) return false; this.noconfirm = false; if ( this.act_values.storagelocationid == '' ) { var weblet = this.parent.subweblets[this.initpar.revokelocation]; weblet.popup.show(); weblet.showValue(this); { var popup = weblet.popup; var timeout = function() { popup.resize.call(popup, true, false); } window.setTimeout(timeout, 10); } weblet.onbtnobj = this; return false; } var p = { schema : this.initpar.schema, name : this.initpar.delfunction, typ0 : "text", typ1 : "text", sqlend : 1 } p = this.addParam(p, "par0", this.obj.inputs.partoutgoingid); p = this.addParam(p, "par1", this.act_values.storagelocationid); if ( MneAjaxWeblet.prototype.write.call(this,'/db/utils/connect/func/execute.xml', p) == 'ok') { this.add(); return false; } return true; } weblet.fetch = function() { var p = { schema : this.initpar.schema, name : this.initpar.fetchfunction, typ0 : "text", sqlend : 1 } p = this.addParam(p, "par0", this.obj.inputs.partoutgoingid); if ( MneAjaxWeblet.prototype.write.call(this,'/db/utils/connect/func/execute.xml', p) == 'ok') { this.act_values.partoutgoingid = this.act_values.result; this.showValue(this); this.setDepends("showValue"); return false; } return true; } weblet.order = function() { var p = { schema : this.initpar.schema, name : this.initpar.orderfunction, typ0 : "text", typ1 : "text", sqlend : 1 } p = this.addParam(p, "par0", this.obj.inputs.partoutgoingid); p = this.addParam(p, "par1", this.obj.inputs.orderproductpartid); if ( MneAjaxWeblet.prototype.write.call(this,'/db/utils/connect/func/execute.xml', p) == 'ok') { this.act_values.partoutgoingid = this.act_values.result; this.showValue(this); this.setDepends("showValue"); return false; } return true; } weblet.onbtnok = function(button) { if ( button.weblet == this.parent.subweblets[this.initpar.revokelocation] ) { if ( typeof button.weblet.act_values[this.initpar.revokelocationid] != 'undefined' ) { this.act_values.storagelocationid = button.weblet.act_values[this.initpar.revokelocationid]; button.weblet.popup.hidden(); this.noconfirm = true; this.del(); } else { this.error("#mne_lang#Kein Ziellagerplatz ausgewählt"); } return; } return MneAjaxWeblet.prototype.onbtnok.call(this, button); } }
import InputField from '../../components/InputField/inputField'; import PropTypes from 'prop-types'; import styles from './myProfile.scss'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as actions from '../../reducers/session/actions'; import { Form } from 'reactstrap'; import JumbotronComponent from '../../components/Jumbotron/jumbotron'; import ProgressButton from '../../components/ProgressButton/PorgressButton'; import * as modalActions from '../../reducers/modal/actions'; const jumbotronData = { title: 'Need Help?', buttonText: 'Talk to our experts! ', subtitle: 'We have you covered. Our expert planners will work with you to make your event fantastic and make sure your needs are met.' }; var dummyPassword = "Pister735@bnhnk"; const mapStateToProps = state => ({ user: state.session.user, isLoading : state.session.loading, error : state.session.error, apiStatus : state.session.apiStatus }); const mapDispatchToProps = dispatch => ({ actions: bindActionCreators({ ...actions }), dispatch }); class MyProfile extends Component { constructor(props) { super(props); this.emailRef = React.createRef(); this.nameRef = React.createRef(); this.phoneRef = React.createRef(); this.passwordRef = React.createRef(); this.state = { name: this.nameRef.value, phoneno: this.phoneRef.value, password: this.passwordRef.value }; } componentWillMount() { if (this.props.user){ this.setState({name: this.props.user.name , phoneno: this.props.user.phoneno,password: dummyPassword}); } } handleFormChange = (e) => { this.setState({ [e.target.id]: e.target.value }); } handleOnClick = () => { } componentDidUpdate(prevProps){ if (this.props.user != prevProps.user){ this.setState({name: this.props.user.name , phoneno: this.props.user.phoneno,password: dummyPassword}); } if ((this.props.apiStatus != prevProps.apiStatus) && this.props.apiStatus == true){ let modalContent = { heading: '', message: "Update successful!", type: 'success' }; this.props.dispatch(modalActions.showModal(modalContent)); } } validateMyProfileForm = () => { let name = this.nameRef.current.validateFormInput(document.getElementById('name')); let phoneno = this.phoneRef.current.validateFormInput(document.getElementById('phoneno')); let password = this.passwordRef.current.validateFormInput(document.getElementById('password')); if (name && phoneno && password) { const params = { name: this.state.name, phoneno: this.state.phoneno } if(this.state.password != dummyPassword){ params.password = this.state.password; } this.props.dispatch(actions.updateProfile(params)); } } render() { return ( <div> {this.props.user && <div className={styles.profileContainer}> <h1 className="mb-5 text-center">My Profile</h1> <div> <Form> <InputField placeHolder="Name" id="name" ref={this.nameRef} type="text" onChange={e => this.handleFormChange(e)} value={this.props.user.name}/> <InputField placeHolder="Email Address" id="email" ref={this.emailRef} type="email" onChange={e => this.handleFormChange(e)} value={this.props.user.email} disabled={true}/> <InputField placeHolder="Contact Number" id="phoneno" ref={this.phoneRef} type="tel" onChange={e => this.handleFormChange(e)} value={this.props.user.phoneno}/> <InputField placeHolder="Password" id="password" ref={this.passwordRef} type="password" isChangePassword={true} onChange={e => this.handleFormChange(e)} value={dummyPassword}/> </Form> <div className="text-center mt-4"> <ProgressButton className="primary-button" onClick={() => this.validateMyProfileForm()} title="Update Changes" isLoading={this.props.isLoading}></ProgressButton> <div className={styles.error}>{this.props.error}</div> </div> </div> </div> } <JumbotronComponent data={jumbotronData} bgcolor="#f8f8f8" isTalkToAhwanam={true} containerStyle="otherWrap"/> </div> ); } } MyProfile.propTypes = { dispatch: PropTypes.func, isLoading: PropTypes.bool, user: PropTypes.object, apiStatus : PropTypes.object, error : PropTypes.string }; export default connect( mapStateToProps, mapDispatchToProps, )(MyProfile);
import React, { useState } from "react"; const Form = ({ changeFilter }) => { const [inputValue, setInputValue] = useState(""); const handleInputChange = (e) => { setInputValue(e.target.value); }; const handleFormSubmit = (e) => { e.preventDefault(); changeFilter(inputValue); setInputValue(""); }; return ( <form className="ui form" onSubmit={handleFormSubmit}> <div className="ui grid center aligned"> <div className="row"> <div className="column five wide"> <input value={inputValue} onChange={handleInputChange} type="text" placeholder="Search for keywords (separated by space)" /> </div> <div className="column two wide"> <button type="submit" className="ui button circular icon brown"> <i className="ui search icon"></i> </button> </div> </div> </div> </form> ); }; export default Form;
function numberReverse(input) { return (''+input).split('').reverse().join(''); } module.exports.numberReverse = numberReverse;
import React from 'react'; import { storiesOf } from '@storybook/react'; import { Button } from '@storybook/react/demo'; import '../src/App.css' import TopBar from '../src/components/topBar'; import IssueLabel from '../src/components/issueLabel'; import AddIssue from '../src/components/addIssue'; import User from '../src/components/user'; storiesOf('Button', module) .add('with text', () => ( <Button >Hello Button</Button> )) .add('with some emoji', () => ( <Button ><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button> )); storiesOf('Navigation', module) .add("TopBar", ()=> <TopBar></TopBar>); storiesOf('Issue', module) .add('label', ()=> <IssueLabel text="must have"color="#e5b7a2"></IssueLabel>) .add('addButton', ()=> <AddIssue></AddIssue>) .add('user', ()=><User username="BryCur" avatarURL="https://avatars0.githubusercontent.com/u/30982987?s=460&v=4"></User>)
//dependencies var assert = require('assert'); var mongoose = require('mongoose'); var mongooseUtils = require('../index'); var common = require('./utils/common'); var db = common.db; var Schema = mongoose.Schema; describe('index', function () { var MockSchema = new Schema(); describe('#default', function() { MockSchema.plugin(mongooseUtils.slugify); MockSchema.plugin(mongooseUtils.ancestorTree); it('should be initialising all fields.', function(done){ assert.strictEqual(typeof MockSchema.paths.title, 'object'); assert.strictEqual(typeof MockSchema.paths.slug, 'object'); assert.strictEqual(typeof MockSchema.paths.parent, 'object'); assert.strictEqual(typeof MockSchema.paths.ancestors, 'object'); done(); }); }); });
const header = { wrapper: document.querySelector('.header'), mobile: document.querySelector('.header-main-mobile'), menuMobile: document.querySelector('.menu-mobile'), menuMobileTrigger: document.querySelector('.header-main-mobile-button'), categories: document.querySelectorAll('.header__category-wrapper'), more: document.querySelector('.header__menu-button'), search: document.querySelector('.header__search-button'), searchMobile: document.querySelector('.header-main-mobile-search'), overlay: document.querySelector('.search__wrapper'), closeOverlay: document.querySelector('.search-close'), selectTarget: (link, attr) => { const selector = link.getAttribute(attr); const target = document.querySelector(`[data-parent=${selector}]`); return target; }, expandHeader: (elm) => { if (elm.classList.contains('is-expanded')) { setTimeout(() => { elm.classList.remove('is-expanded'); }, 450); } else { elm.classList.add('is-expanded'); } }, closeAll: (arr, event) => { arr.forEach((item) => { if (event.target !== item) { item.classList.remove('is-active'); } }); }, checkTransparency: (elm) => { if (elm.dataset.transparent === 'true') { return true; } return false; }, checkWasTransparant: (elm) => { if (elm.dataset.wasTransparent === 'true') { return true; } return false; }, sticky: (elm) => { const getDistance = () => { const topDist = elm.offsetTop + 50; return topDist; }; const stickPpoint = getDistance(); window.onscroll = () => { const dist = getDistance() - window.pageYOffset; const offset = window.pageYOffset; if (dist <= 0 && !header.stuck) { elm.classList.add('is-sticky'); header.wrapper.setAttribute('data-transparent', 'false'); header.wrapper.setAttribute('data-was-transparent', 'false'); if (elm.dataset.transparent) { elm.classList.remove('is-transparent'); header.swapLogo(false); } header.stuck = true; } else if (header.stuck && offset <= stickPpoint) { elm.classList.remove('is-sticky'); header.wrapper.setAttribute('data-transparent', 'true'); header.wrapper.setAttribute('data-was-transparent', 'false'); if (elm.dataset.transparent) { elm.classList.add('is-transparent'); header.swapLogo(true); } header.stuck = false; } }; }, swapLogo: (bool) => { const logo = document.querySelector('.header__logo'); const logoSource = logo.querySelector('source'); const logoImg = logo.querySelector('img'); if (!bool) { logoSource.setAttribute('srcset', './assets/img/logo.png'); logoImg.setAttribute('src', './assets/img/logo.webp'); } else { logoSource.setAttribute('srcset', './assets/img/logo-alt.png'); logoImg.setAttribute('src', './assets/img/logo-alt.webp'); } }, stuck: false, init: () => { if (header.wrapper) { header.sticky(header.wrapper); } if (header.categories) { header.categories = Array.from(header.categories); header.categories.push(header.more); const menus = document.querySelectorAll('.header__category-menu'); header.categories.forEach((category) => { category.addEventListener('click', (e) => { e.preventDefault(); header.wrapper.focus(); const isTransparent = header.checkTransparency(header.wrapper); const wasTransparent = header.checkWasTransparant(header.wrapper); let target = header.selectTarget(category, 'href'); header.categories.forEach((link) => { if (link === category && !link.classList.contains('is-active')) { link.classList.add('is-active'); } else { link.classList.remove('is-active'); } }); if (category.hasAttribute('data-target')) { target = header.selectTarget(category, 'data-target'); } menus.forEach((menu) => { if (menu === target) { menu.classList.toggle('is-active'); if (menu.classList.contains('is-active')) { header.wrapper.classList.add('is-expanded'); if (isTransparent) { header.wrapper.classList.remove('is-transparent'); header.swapLogo(false); header.wrapper.setAttribute('data-was-transparent', 'true'); } } else { header.wrapper.classList.remove('is-expanded'); if (wasTransparent) { header.wrapper.classList.add('is-transparent'); header.swapLogo(true); header.wrapper.setAttribute('data-was-transparent', 'false'); } } } else { menu.classList.remove('is-active'); } }); }); }); } if (header.search && header.overlay && header.closeOverlay) { header.search.addEventListener('click', (e) => { e.preventDefault(); header.overlay.classList.add('is-active'); document.body.classList.add('is-modal-open'); }); header.closeOverlay.addEventListener('click', (e) => { e.preventDefault(); header.overlay.classList.remove('is-active'); document.body.classList.remove('is-modal-open'); }); } if (header.mobile) { const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0); if (vw < 1200) { header.sticky(header.mobile); if (header.menuMobile && header.menuMobileTrigger) { header.menuMobileTrigger.addEventListener('click', (e) => { e.preventDefault(); header.menuMobile.classList.toggle('is-active'); header.menuMobileTrigger.classList.toggle('is-active'); header.mobile.classList.toggle('is-menu-active'); document.body.classList.toggle('is-modal-open'); }); } if (header.searchMobile) { header.searchMobile.addEventListener('click', (e) => { e.preventDefault(); header.overlay.classList.add('is-active'); document.body.classList.add('is-modal-open'); }); header.closeOverlay.addEventListener('click', (e) => { e.preventDefault(); header.overlay.classList.remove('is-active'); document.body.classList.remove('is-modal-open'); }); } } } }, }; export default header;
document.write("<h1>" + "CURRENCY IN PKR" + "</h1>" ); var us_dollers = 10; var saudi_riyals = 25; var pakistani_rupees = (us_dollers * 155) + (saudi_riyals * 41); document.write("Total Currency in PKR =" + pakistani_rupees);