text
stringlengths
7
3.69M
module.exports = Object.freeze({ single: 'single', teams: 'teams', });
import React, { useState, useEffect } from "react"; import "./App.css"; import { FiLoader } from "react-icons/fi"; function App() { const [search, setSearch] = useState(null); const [topic, setTopic] = useState("react"); const [information, setInformation] = useState(); const [page, setPage] = useState(1); const [isLoading, setIsLoading] = useState(false); useEffect(() => { setIsLoading(true); fetch(`http://hn.algolia.com/api/v1/search?query=${topic}&page=${page}`) .then((response) => response.json()) .then((json) => { setInformation(json.hits); setIsLoading(false); }).catch((error)=> console.log(error)) }, [topic, page]); const searchSpace = (event) => { let keyword = event.target.value; setSearch(keyword); }; /* const items = information.filter((data) => { if (search == null) return data; if (data.title.toLowerCase().includes(search.toLowerCase())) { return data; } */ const items = information && information.map((data) => { return ( <div> <ul> <li> <a href={data.url}> <span>{data.title}</span> </a> </li> </ul> </div> ); }); return ( <> {isLoading && ( <div className="loading">is loading... <FiLoader /> </div> )} <div className="searchbar"> <input type="text" placeholder="Enter item to be searched " onChange={(e) => searchSpace(e)} /> <button className="search" onClick={(e) => setTopic(search)}> Search </button> <button className="prev" disabled={page === 1} onClick={(e) => setPage(page - 1)}> Previous page </button> <div className="page">{page}</div> <button className="next" onClick={(e) => setPage(page + 1)}> Next page </button> </div> <div className="content">{!isLoading && items}</div> </> ); } export default App;
import { Map } from 'immutable' import { saveTweet, fetchTweet } from 'helpers/api' import { closeModal } from './modal' import { addSingleUsersTweet } from './usersTweets' const FETCHING_TWEET = 'FETCHING_TWEET' const FETCHING_TWEET_ERROR = 'FETCHING_TWEET_ERROR' const FETCHING_TWEET_SUCCESS = 'FETCHING_TWEET_SUCCESS' const ADD_TWEET = 'ADD_TWEET' const ADD_MULTIPLE_TWEETS = 'ADD_MULTIPLE_TWEETS' const STOP_FETCHING = 'STOP_FETCHING' function fetchingTweet () { return { type: FETCHING_TWEET } } function fetchingTweetError (error) { console.warn(error) return { type: FETCHING_TWEET_ERROR, error: 'Error fetching Tweet' } } function fetchingTweetSuccess (tweet) { return { type: FETCHING_TWEET_SUCCESS, tweet } } export function stopFetching () { return { type: STOP_FETCHING } } function addTweet (tweet) { return { type: ADD_TWEET, tweet } } export function addMultipleTweets (tweets) { return { type: ADD_MULTIPLE_TWEETS, tweets } } export function tweetFanout (tweet) { return function (dispatch, getState) { const uid = getState().users.authedId saveTweet(tweet) .then((tweetWithId) => { dispatch(addTweet(tweetWithId)) dispatch(closeModal()) dispatch(addSingleUsersTweet(uid, tweetWithId.tweetId)) }) .catch((err) => { console.warn('Error in tweetFanout', err) }) } } export function fetchAndHandleTweet (tweetId) { return function (dispatch, getState) { dispatch(fetchingTweet()) fetchTweet(tweetId) .then(tweet => dispatch(fetchingTweetSuccess(tweet))) .catch(err => dispatch(fetchingTweetError(err))) } } const initialState = Map({ isFetching: true, error: '' }) export default function tweets (state = initialState, action) { switch (action.type) { case FETCHING_TWEET : return state.merge({ isFetching: true }) case ADD_TWEET : case FETCHING_TWEET_SUCCESS : return state.merge({ error: '', isFetching: false, [action.tweet.tweetId]: action.tweet }) case FETCHING_TWEET_ERROR : return state({ isFetching: false, error: action.error }) case STOP_FETCHING : return state.merge({ error: '', isFetching: false }) case ADD_MULTIPLE_TWEETS : return state.merge(action.tweets) default : return state } }
TEMP['initAir'] = function(air){ var PublicRander = function(){ // 设置主题css this.setStyle(air.Options.themePath+'style.css',"theme-"+air.Options.theme+"-style"); // 获取UI模块 var ui = air.require('UI'); // 获取icons信息 var icons = air.require('icons'); // 清除图标节点里面的内容 air.Options.iconContainer.empty(); // 设置各个icon var newOrder=[]; var IconsOnDragfunction=function(tar,l,t){ var l = (l-20)/90; console.log(t); var t = (t)/105; var keyNow = tar.attr("id").split("-")[1]; var index = l*air.require("UI").vIconNum+t; var icons_Order = air.Options.icons_Order; var keyNowindex=icons_Order.indexOf(keyNow); var length = icons_Order.length; if(index>=length){ index=length-1; } newOrder=[]; for(var i=0;i<length;i++){ if(keyNowindex>index){ if(i == index)newOrder.push(keyNow); if(keyNow != icons_Order[i])newOrder.push(icons_Order[i]); }else{ if(keyNow != icons_Order[i])newOrder.push(icons_Order[i]); if(i == index)newOrder.push(keyNow); } } air.require("UI").resetIcons(newOrder); }; if(air.Options.icons_Order.length!=icons.length)air.Options.icons_Order=[]; for(var key in icons){ air.Options.icons_Order.push(icons[key]['id']); ui.newIcon({ name:icons[key]['name'], src:air.Options.iconPath+icons[key]['src']+".png", id:icons[key]['id'], click:icons[key]['click']?icons[key]['click']:null }).jqDrag(null,{ type:"grid", width:90, height:105, onDrag:function(tar,l,t){ IconsOnDragfunction(tar,l,t); }, onStop:function(){ //判断图表顺序是不是发生改变,如果是赋值并提示保存 if (air.Options.icons_Order.length == newOrder.length){ for (var i = 0; i < newOrder.length; i++) { if(air.Options.icons_Order[i]!=newOrder[i]){ air.Options.icons_Order=newOrder; air.require("notify").toast(air.Lang.icons_Order_save); break; } } } } }); } air.require("connectPanel").init(); }; // 注入样式表方法 var PublicSetStyle = function(path,id){ if($("#"+id).length>0)return; $("head").append('<link id="'+id+'" rel="stylesheet" href="'+path+"?v="+new Date().getTime()+'" type="text/css" media="screen" />'); }; var alertLowBattery=false; var statusHandle = function(data){ $(".connect-status").removeClass("unlink"); if(data.network_isWIFI!="true"){ $(".layout-taskbar-wifi").removeClass("wifi0 wifi1 wifi2 wifi3 wifi4").addClass("wifi0").attr("title",air.Lang.no_wifi); }else{ $(".layout-taskbar-wifi").removeClass("wifi0 wifi1 wifi2 wifi3 wifi4") .addClass("wifi"+data.wifi_RSSI_level.split("/")[0]).attr("title",data.wifi_ssid+":"+data.wifi_ip); } var asu = data.gsm_signal_asu,bin=0; if (asu < 0 || asu >= 99) bin = 0; else if (asu >= 16) bin = 4; else if (asu >= 8) bin = 3; else if (asu >= 4) bin = 2; else bin = 1; $(".layout-taskbar-signal").removeClass("signal0 signal1 signal2 signal3 signal4").addClass("signal"+bin).attr("title","dbm:"+data.gsm_signal_dbm); $(".layout-taskbar-battery-vbg").css("width",data.battery+"%"); if(data.battery_status=="charging"){ alertLowBattery=!1; $(".layout-taskbar-battery-vbg").addClass("charging"); $(".layout-taskbar-battery-v").addClass("i-taskbar-battery-v-charging"); }else{ $(".layout-taskbar-battery-vbg").removeClass("charging"); $(".layout-taskbar-battery-v").removeClass("i-taskbar-battery-v-charging"); } if(parseInt(data.battery)<20 && data.battery_status!="charging" && !alertLowBattery){ alertLowBattery=!0; air.require("notify").alertNotify(air.Lang.low_battery,air.Lang.low_battery_des); } if(parseInt(data.battery)<20){ $(".i-taskbar-battery-vbg").removeClass("i-taskbar-battery-vbg-full"); $(".i-taskbar-battery-vbg").addClass("i-taskbar-battery-vbg-low"); }else if(parseInt(data.battery)==100){ $(".i-taskbar-battery-vbg").removeClass("i-taskbar-battery-vbg-low"); $(".i-taskbar-battery-vbg").addClass("i-taskbar-battery-vbg-full"); }else{ $(".i-taskbar-battery-vbg").removeClass("i-taskbar-battery-vbg-low i-taskbar-battery-vbg-full"); } $(".layout-taskbar-battery-vt").text(data.battery+"%").attr("title",data.battery_status); } var tryConnectSocket = function(){ air.require("socket").addListener("receive",function(mes){ mes=mes.substring(0,mes.lastIndexOf("}")+1); mes = JSON.parse(mes); if(mes.type=="notify"){ air.require("notify").simpleNotify( 'http://'+air.Options.ip+':'+air.Options.port+'/?mode=image&package='+mes.data[0].packageName, mes.data[0].appName,mes.data[0].tickerText,function(){ if(mes.data[0].hasPendIntent) $.get('http://'+air.Options.ip+':'+air.Options.port+'/?mode=device&action=openNotify&activity='+mes.data[0].packageName); }); }else if(mes.type=="status"){ statusHandle(mes.data); }else if(mes.type=="sms"){ //if($("#"+mes.data.id).length==0) console.log(mes.data.id); air.require("notify").toast(air.Lang.text_sms+":"+air.Lang[mes.data.mes]); $("#"+mes.data.id+" .sms-mes-status").text(air.Lang["sms_status_"+mes.data.mes]); }else if(mes.type=="smsR"){ air.require("SmsPhone").smsReceiver(mes.data); }else if(mes.type=="phoneStatus"){ air.require("SmsPhone").phoneReceiver(mes.data); } }); }; var reConnectSocket=function(){ $(".layout-notify-container").addClass("refreshing"); air.require("socket").reConnectSocket(); }; var getBaseData = function(){//获取初始的联系人列表和软件列表 air.require("dataTran").getJson({mode:"device","action":"contacts"},function(data){ air.Options.baseData.contacts = data; }); air.require("dataTran").getJson({mode:"device","action":"apps"},function(data){ air.Options.baseData.apps = data; }); }; return { getBaseData:getBaseData, rander:PublicRander, setStyle:PublicSetStyle, reConnectSocket:reConnectSocket, tryConnectSocket:tryConnectSocket }; };
config({ 'editor/plugin/fore-color/cmd': {requires: ['editor/plugin/color/cmd']} });
const fs = require('fs'); const path = require('path'); const ext = '.' + process.argv[3]; fs.readdir(process.argv[2], function(err, list) { if (err) { console.log(err); return; } const filterdList = list.filter(function(name) { return path.extname(name) === ext; }); filterdList.forEach(function(name) { console.log(name); }); });
self.__precacheManifest = [ { "revision": "7fabae31eb077768646a", "url": "/static/js/main.f363061d.chunk.js" }, { "revision": "fdfcfda2d9b1bf31db52", "url": "/static/js/runtime~main.c5541365.js" }, { "revision": "120486d5ea3d110ed94e", "url": "/static/js/2.a45a557d.chunk.js" }, { "revision": "f24d961ff73a3edd31ca1607500213d5", "url": "/index.html" } ];
import Vue from 'vue' import Vuex from 'vuex' import { Toast } from 'vant'; Vue.use(Toast); Vue.use(Vuex) export default new Vuex.Store({ state: { arr:[], userArr:[], Hotel:[], //邮箱验证 emailRules: [{ required: true, message: '手机号不能为空', trigger: 'onBlur' }, { // 自定义校验规则 validator: value => { return /^1([3,4,5,7,8,9][0-9]|4[57]|5[0-35-9]|7[0678]|8[0-9])\d{8}$/ .test(value) }, message: '请输入正确手机号', trigger: 'onBlur' }], //密码验证 passwordRules: [{ required: true, message: '密码不能为空', trigger: 'onBlur' }, { // 自定义校验规则 validator: value => { return /^[\w.]{6,20}$/ .test(value) }, message: '请输入正确格式的password', trigger: 'onBlur' }], popular_places:[{ path:require('../assets/img/view1.png'), placeName:'Costa Rica Quest', place_num:'2 places', time:' 4 days', value:'$1019' },{ path:require('../assets/img/view2.png'), placeName:'Volcano Trail', place_num:'4 places', time:' 12 days', value:'$1387' } ], Area_arr: [{ path1: require("../assets/img/hotels2.1.png"), areaName: "Millennium Dubai Airport Hotel ", num: "Dubai – Subway Access", value: "$75 p/night", Rate:4, score:8.2 }, { path1: require("../assets/img/hotels2.2.png"), areaName: "Ibis Deira City Cent", num: "Garhoud, Dubai", value: "$103 p/night", Rate:2, score:6.7 }, { path1: require("../assets/img/hotels2.3.png"), areaName: "Grand Hyatt Dubai", num: "Bur Dubai, Dubai", value: "$127 p/night", Rate:5, score:9.3 }, ] }, mutations: { // toSetting(){ // Vue.$router.push("/Setting") // } reset(state,payload){ var users = JSON.parse(localStorage.getItem('user')) let obj = JSON.parse(localStorage.getItem('loginUser'))[0] for(var i =0;i<users.length;i++){ if(obj.username == users[i].username){ users.splice(i,1,obj) localStorage.setItem('user',JSON.stringify(users)) } } } }, actions: { }, modules: { } })
const fs = require('fs') const fsp = require('fs').promises const which = require('which') const {spawn, spawnSync} = require('child_process') const path = require('path') const tar = require('tar') const defaultSpawnOptions = { shell: true, stdio: ['ignore', 'inherit', 'inherit'] } const defaultSpawnOptionsWithInput = {...defaultSpawnOptions, stdio: 'inherit'} function waitForProcess(childProcess) { return new Promise((resolve, reject) => { childProcess.once('exit', (returnCode) => { if (returnCode === 0) { resolve(returnCode) } else { reject(returnCode) } }) childProcess.once('error', (err) => { reject(err) }) }) } async function copyNewEnvValues(fromPath, toPath) { await copyEnv(fromPath, toPath, false) } async function overwriteEnvFile(fromPath, toPath) { await copyEnv(fromPath, toPath) } async function throwIfDockerNotRunning() { if (!which.sync('docker')) { throw Error('docker command not found') } let childProcess = spawnSync('docker', ['info'], {encoding: 'utf8'}) if (childProcess.error) { throw childProcess.error } if (!childProcess.stdout || childProcess.stdout.includes('ERROR: error during connect')) { throw Error('docker is not running') } } async function bashIntoRunningDockerContainer(containerNamePartial, entryPoint = 'bash') { await throwIfDockerNotRunning() let childProcess = spawnSync('docker', ['container', 'ls'], {encoding: 'utf8'}) if (childProcess.error) { throw childProcess.error } let matchingLines = childProcess.stdout.split('\n').filter(line => line.includes(containerNamePartial)) if (!matchingLines || matchingLines.length === 0) { throw Error('container is not running') } if (matchingLines.length > 1) { throw Error('more than one container matches the provided containerNamePartial ' + containerNamePartial) } let stringArray = matchingLines[0].split(/(\s+)/) let containerName = stringArray[stringArray.length - 1] console.log('full container name: ' + containerName) const args = ['exec', '-it', containerName, entryPoint] return waitForProcess(spawn('docker', args, defaultSpawnOptionsWithInput)) } async function dockerContainerIsRunning(containerNamePartial) { await throwIfDockerNotRunning() let childProcess = spawnSync('docker', ['container', 'ls'], {encoding: 'utf8'}) if (childProcess.error) { throw childProcess.error } let matchingLines = childProcess.stdout.split('\n').filter(l => l.includes(containerNamePartial)) return !!matchingLines && matchingLines.length > 0 } async function copyEnv(fromPath, toPath, overrideAll = true) { await ensureFile(fromPath, toPath) let templateDict = getEnvDictionary(fromPath) let envDict = getEnvDictionary(toPath) // Determine what keys are missing from .env that are in template let templateKeys = Object.keys(templateDict) let envKeys = Object.keys(envDict) let missingKeys = templateKeys.filter(k => !envKeys.includes(k)) if (missingKeys.length > 0) { console.log(`Adding missing keys in ${toPath}: `, missingKeys) } // Merge missing values with existing let newEnvDict = {} for (const [key, value] of Object.entries(overrideAll ? templateDict : envDict)) { newEnvDict[key] = value } for (const key of missingKeys) { newEnvDict[key] = templateDict[key] } // Sort let newDictEntries = Object.entries(newEnvDict) let newSortedEntries = newDictEntries.sort((a, b) => { if (a < b) { return -1 } if (a > b) { return 1 } return 0 }) // Write to .env file let newEnvFileContent = '' for (let kvp of newSortedEntries) { newEnvFileContent += `${kvp[0]}=${kvp[1]}\n` } await fsp.writeFile(toPath, newEnvFileContent) } function getEnvDictionary(filePath) { let dict = {} fs.readFileSync(filePath).toString().split('\n').forEach(function (line) { if (line && line.indexOf('=') !== -1) { line = line.replace('\r', '').trim() let parts = line.split('=') dict[parts[0].trim()] = parts[1].trim() } }) return dict } async function ensureFile(fromPath, toPath) { if (!fs.existsSync(toPath)) { console.log('Creating new file ' + toPath) await fsp.copyFile(fromPath, toPath) } } exports.defaultSpawnOptions = { shell: true, cwd: __dirname, stdio: ['ignore', 'inherit', 'inherit'] } async function createTarball(directoryToTarball, outputDirectory, tarballName, cwd = '') { if (!directoryToTarball || directoryToTarball.length === 0) { throw new Error('directoryToTarball is required') } if (!outputDirectory || outputDirectory.length === 0) { throw new Error('outputDirectory is required') } if (!tarballName || tarballName.length === 0) { throw new Error('tarballName is required') } const tarballPath = path.join(outputDirectory, tarballName) console.log('directory to create tarball from: ' + directoryToTarball) console.log('output will be: ' + tarballPath) let normalizedDirectoryToTarball = !!cwd ? path.join(cwd, directoryToTarball) : directoryToTarball if (!fs.existsSync(normalizedDirectoryToTarball)) { throw new Error('error: dirToTarball directory does not exist: ' + normalizedDirectoryToTarball) } if (!fs.existsSync(outputDirectory)) { fs.mkdirSync(outputDirectory) } else { if (fs.existsSync(tarballPath)) { fs.unlinkSync(tarballPath) } } let options = {gzip: true, file: tarballPath} if (!!cwd) { options.cwd = cwd } await tar.c(options, [directoryToTarball]) } async function dockerCompose(command, projectName, dockerRelativeDirectory = 'docker', detached = false) { if (!projectName || projectName.length === 0) { throw new Error('projectName is required') } const dockerRelativeDir = dockerRelativeDirectory || './' const dockerWorkingDir = path.join(process.cwd(), dockerRelativeDir) if (!fs.existsSync(dockerWorkingDir)) { throw new Error('Docker directory does not exist: ' + dockerWorkingDir) } await throwIfDockerNotRunning() const dockerSpawnOptions = {...defaultSpawnOptions, cwd: dockerWorkingDir, stdio: 'inherit'} let args = ['--project-name', projectName, command] if (detached) { args.push('-d') } return waitForProcess(spawn('docker-compose', args, dockerSpawnOptions)) } async function dockerDepsUp(projectName, dockerRelativeDirectory) { return await dockerCompose('up', projectName, dockerRelativeDirectory) } async function dockerDepsUpDetached(projectName, dockerRelativeDirectory) { return await dockerCompose('up', projectName, dockerRelativeDirectory, true) } async function dockerDepsDown(projectName, dockerRelativeDirectory) { return await dockerCompose('down', projectName, dockerRelativeDirectory) } async function dockerDepsStop(projectName, dockerRelativeDirectory) { return await dockerCompose('stop', projectName, dockerRelativeDirectory) } async function dotnetBuild(release = true) { let args = ['build'] if (release) { args.push('-c', 'Release') } return waitForProcess(spawn('dotnet', args, defaultSpawnOptions)) } async function dotnetPack(projectDirectoryPath, release = true) { if (!projectDirectoryPath) { throw Error('projectDirectoryPath param is required') } let args = ['pack'] if (release === true) { args.push('-c', 'Release') } const spawnOptions = {...defaultSpawnOptions, cwd: projectDirectoryPath} logCommand('dotnet', args, spawnOptions) await waitForProcess(spawn('dotnet', args, spawnOptions)) } async function dotnetNugetPublish(projectDirectoryPath, csprojFilename, release = true, nugetSource = 'https://api.nuget.org/v3/index.json') { const apiKey = process.env.NUGET_API_KEY if (!apiKey) { throw Error('env var NUGET_API_KEY is required') } const packageDir = path.join(projectDirectoryPath, release ? 'bin/Release' : 'bin/Debug') const packageName = await getPackageName(projectDirectoryPath, csprojFilename) console.log('publishing package ' + packageName) const spawnOptions = {...defaultSpawnOptions, cwd: packageDir} await waitForProcess(spawn('dotnet', [ 'nuget', 'push', packageName, '--api-key', apiKey, '--source', nugetSource], spawnOptions)) } async function getPackageName(projectPath, csprojFilename) { const namespace = csprojFilename.substring(0, csprojFilename.indexOf('.csproj')) const csprojPath = path.join(projectPath, csprojFilename) const csproj = fs.readFileSync(csprojPath, 'utf-8') const versionTag = '<PackageVersion>' const xmlVersionTagIndex = csproj.indexOf(versionTag) const versionStartIndex = xmlVersionTagIndex + versionTag.length const versionStopIndex = csproj.indexOf('<', versionStartIndex) const version = csproj.substring(versionStartIndex, versionStopIndex) return `${namespace}.${version}.nupkg` } function logCommand(command, args, spawnOptions) { console.log('running command: ' + `${command} ${args.join(' ')}`) console.log('with spawn options: ' + JSON.stringify(spawnOptions)) } async function dotnetDllCommand(relativeDllPath, argsArray, cwd = null, useStdin = false) { throwIfRequiredIsFalsy(relativeDllPath, 'relativeDllPath') throwIfRequiredArrayIsFalsyOrEmpty(argsArray, 'argsArray') let args = [relativeDllPath, ...argsArray] let spawnOptions = {...defaultSpawnOptions} if (cwd !== null) { spawnOptions = {...spawnOptions, cwd: cwd} } if (useStdin) { spawnOptions = {...spawnOptions, stdio: 'inherit'} } return waitForProcess(spawn('dotnet', args, spawnOptions)) } async function dotnetPublish(cwd = null, outputDir = 'publish') { let spawnOptions = {...defaultSpawnOptions} if (!!cwd) { spawnOptions = {...spawnOptions, cwd: cwd} } if (!outputDir) { outputDir = 'publish' } let args = ['publish', '-o', outputDir] return waitForProcess(spawn('dotnet', args, spawnOptions)) } async function dotnetDbMigrationsList(dbContextName, relativeDbMigratorDirectoryPath) { throwIfRequiredIsFalsy(dbContextName, 'dbContextName') throwIfRequiredIsFalsy(relativeDbMigratorDirectoryPath, 'relativeDbMigratorDirectoryPath') let spawnOptions = {...defaultSpawnOptions, cwd: relativeDbMigratorDirectoryPath} return waitForProcess(spawn('dotnet', ['ef', 'migrations', 'list', '--context', dbContextName], spawnOptions)) } async function dotnetDbMigrate(dbContextName, relativeDbMigratorDirectoryPath, migrationName = '') { throwIfRequiredIsFalsy(dbContextName, 'dbContextName') throwIfRequiredIsFalsy(relativeDbMigratorDirectoryPath, 'relativeDbMigratorDirectoryPath') let args = ['ef', 'database', 'update'] if (!!migrationName) { args.push(migrationName) } args = [...args, '--context', dbContextName] let spawnOptions = {...defaultSpawnOptions, cwd: relativeDbMigratorDirectoryPath} return waitForProcess(spawn('dotnet', args, spawnOptions)) } async function dotnetDbAddMigration(dbContextName, relativeDbMigratorDirectoryPath, migrationName, withBoilerplate = false) { throwIfRequiredIsFalsy(dbContextName, 'dbContextName') throwIfRequiredIsFalsy(relativeDbMigratorDirectoryPath, 'relativeDbMigratorDirectoryPath') throwIfRequiredIsFalsy(migrationName, 'migrationName') const migrationsOutputDir = `Migrations/${dbContextName}Migrations` let args = ['ef', 'migrations', 'add', migrationName, '--context', dbContextName, '-o', migrationsOutputDir] let spawnOptions = {...defaultSpawnOptions, cwd: relativeDbMigratorDirectoryPath} await waitForProcess(spawn('dotnet', args, spawnOptions)) if (withBoilerplate) { await dotnetDbAddMigrationBoilerplate(dbContextName, relativeDbMigratorDirectoryPath, migrationName) } } async function dotnetDbAddMigrationBoilerplate(dbContextName, relativeDbMigratorDirectoryPath, migrationName) { console.log(`Attempting to write boilerplate to generated migration C# file`) const migrationsOutputDir = `Migrations/${dbContextName}Migrations` const dirPath = path.join(relativeDbMigratorDirectoryPath, migrationsOutputDir) console.log(`Checking for generated C# file in directory: ${dirPath}`) const filenames = fs.readdirSync(dirPath).filter(fn => fn.endsWith(`${migrationName}.cs`)); if (!filenames || filenames.length === 0) { console.log(`Unable to add boilerplate - could not find auto generated file in directory: ${dirPath}`) } const filename = filenames[0] const filePath = path.join(dirPath, filename) if (!fs.existsSync(filePath)) { console.log(`Could not find the file to add boilerplate to at: ${filePath}`) return } console.log(`Auto generated C# file to modify: ${filePath}`) const usingLine = 'using MikeyT.DbMigrations;' const upLine = `MigrationScriptRunner.RunScript(migrationBuilder, "${migrationName}.sql");` const downLine = `MigrationScriptRunner.RunScript(migrationBuilder, "${migrationName}_Down.sql");` const fileContents = await fsp.readFile(filePath, {encoding: 'utf8'}) let lines = fileContents.replaceAll('\r', '').split('\n') let newLines = [] newLines.push(lines[0].trim()) newLines.push(usingLine) let addUpLine = false let addDownLine = false let skipNextLineIfBlank = false for (let i = 1; i < lines.length; i++) { if (skipNextLineIfBlank && lines[i].trim().length === 0) { skipNextLineIfBlank = false continue } if (addUpLine) { let newLine = lines[i].replace('{', `{\n\t\t\t${upLine}`) newLines.push(newLine) addUpLine = false skipNextLineIfBlank = true continue } if (addDownLine) { let newLine = lines[i].replace('{', `{\n\t\t\t${downLine}`) newLines.push(newLine) addDownLine = false skipNextLineIfBlank = true continue } newLines.push(lines[i]) if (lines[i].includes('void Up')) { addUpLine = true } if (lines[i].includes('void Down')) { addDownLine = true } } const newFileContents = newLines.join('\n') await fsp.writeFile(filePath, newFileContents, {encoding: 'utf8'}) console.log(`Updated file with boilerplate - please ensure it is correct: ${filePath}`) const upScriptPath = path.join(relativeDbMigratorDirectoryPath, `Scripts/${migrationName}.sql`) const downScriptPath = path.join(relativeDbMigratorDirectoryPath, `Scripts/${migrationName}_Down.sql`) console.log('Creating corresponding empty sql files (no action will be taken if they already exist):') console.log(` - ${upScriptPath}`) console.log(` - ${downScriptPath}`) if (!fs.existsSync(upScriptPath)) { await fsp.writeFile(upScriptPath, '', {encoding: 'utf8'}) } else { console.log('Skipping Up sql script (already exists)') } if (!fs.existsSync(downScriptPath)) { await fsp.writeFile(downScriptPath, '', {encoding: 'utf8'}) } else { console.log('Skipping Down sql script (already exists)') } } async function dotnetDbRemoveMigration(dbContextName, relativeDbMigratorDirectoryPath) { throwIfRequiredIsFalsy(dbContextName, 'dbContextName') throwIfRequiredIsFalsy(relativeDbMigratorDirectoryPath, 'relativeDbMigratorDirectoryPath') let spawnOptions = {...defaultSpawnOptions, cwd: relativeDbMigratorDirectoryPath} return waitForProcess(spawn('dotnet', ['ef', 'migrations', 'remove', '--context', dbContextName], spawnOptions)) } function throwIfRequiredIsFalsy(requiredArg, argName) { if (!requiredArg) { throw Error(`${argName} is required`) } } function throwIfRequiredArrayIsFalsyOrEmpty(requiredArrayArg, argName) { if (!requiredArrayArg || requiredArrayArg.length === 0 || !Array.isArray(requiredArrayArg)) { throw Error(`${argName} array is required`) } } exports.defaultSpawnOptions = defaultSpawnOptions exports.defaultSpawnOptionsWithInput = defaultSpawnOptionsWithInput exports.waitForProcess = waitForProcess exports.copyNewEnvValues = copyNewEnvValues exports.overwriteEnvFile = overwriteEnvFile exports.throwIfDockerNotRunning = throwIfDockerNotRunning exports.bashIntoRunningDockerContainer = bashIntoRunningDockerContainer exports.dockerContainerIsRunning = dockerContainerIsRunning exports.createTarball = createTarball exports.dockerDepsUp = dockerDepsUp exports.dockerDepsUpDetached = dockerDepsUpDetached exports.dockerDepsDown = dockerDepsDown exports.dockerDepsStop = dockerDepsStop exports.dotnetBuild = dotnetBuild exports.dotnetPack = dotnetPack exports.dotnetNugetPublish = dotnetNugetPublish exports.dotnetDllCommand = dotnetDllCommand exports.dotnetPublish = dotnetPublish exports.dotnetDbMigrationsList = dotnetDbMigrationsList exports.dotnetDbMigrate = dotnetDbMigrate exports.dotnetDbAddMigration = dotnetDbAddMigration exports.dotnetDbRemoveMigration = dotnetDbRemoveMigration
var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var autoprefixer = require('autoprefixer'); function getBabelPresets(defaultPresets) { var presets = defaultPresets; if(!process.env.NODE_ENV) { presets.push('react-hmre') } return presets; } function getDevtool() { if(process.env.NODE_ENV === 'production') { return 'cheap-module-source-map' } else { return 'eval' } } module.exports = { devtool: getDevtool(), entry: { app: './src/index.js', vendor: [ 'react', 'react-dom' ] }, output: { path: './dist/js', filename: 'app.bundle.js' }, module: { preLoaders: [ { test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/ } ], loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: getBabelPresets(['es2015', 'react']) } }, { test: /\.scss$/, loaders: ["style", "css?modules&localIdentName=[name]__[local]__[hash:base64:5]", "postcss", "sass"] }, { test: /\.json$/, exclude: /node_modules/, loader: "json" } ] }, postcss: function() { return [autoprefixer] }, plugins: [ new HtmlWebpackPlugin({ filename: '../index.html', template: './src/index.html' }), new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify(process.env.NODE_ENV) } }) ] }
$(document).ready(function () { var index = 0; //used to determine which question we are on var right = 0; var wrong = 0; var guessed; var correctAnswer= ""; var hasGuessed= false; var timer= 10; //all correct answers are in index 0, we use a shuffle function to randomize where they appear var questionSet = [ { question: "1. What was Captain Wentworth's first ship?", answer: ["the Asp", "the Laconia", "the Thrush", "the Harville"]}, { question: "2. What is the name of the horse Willoughby gives to Marianne in Sense and Sensibility?", answer: ["Queen Mab ", "Lady Grey", "Guinnevere", "Brown Bess"]}, { question: "3. How did Marianne Dashwood get injured? ", answer: ["By falling down a hill ", "In a horse riding accident", "At a dance", "Falling down the stairs"]}, { question: "4. Where do the Bennets live?", answer: ["Hertfordshire", "Herefordshire", "Hampshire ", "Hartford"]}, { question: "5. How many nieces and nephews does Emma have?", answer: ["5", "4", "3", "0"]}, { question: "6. How many of Jane Austen's novels were published during her lifetime? ", answer: ["Four", "Two", "None", "All of them"]}, { question: "7. Jane Austen's 'Northanger Abbey' contains one of the earliest printed references to what sport? ", answer: ["Baseball" , "Golf", "Football", "Cricket"]}, { question: "8. What was Austen's first published novel? ", answer: ["Sense & Sensibility", "Lady Susan", "Pride and Prejudice", "Emma"]} ];// end question set array // create copy of array so we can shuffle elements inside while leaving original alone var questionSetCopy = JSON.parse(JSON.stringify( questionSet )); //this function is to shuffle the answers so it's not the same every time function shuffle(arr) { var counter = arr.length; while (counter > 0) { var index = Math.floor(Math.random() * counter); counter--; var temp = arr[counter]; arr[counter] = arr[index]; arr[index] = temp; } return arr; } $("#status").hide(); $("#timer").hide(); $("#question").hide(); $("#answers").hide(); $("#start").on("click", function(){ questionDisplay(); }); function questionDisplay(){ $("#status").show(); $("#timer").show(); $("#question").show(); $("#answers").show(); $("#start").hide(); hasGuessed=false; $("#status").hide(); $("#timer").html("Time Remaining: " + timer); shuffle(questionSetCopy[index].answer); $("#question").html("Question "+ (questionSet[index].question)); $("#answers").empty(); for (let j=0; j<4; j++){ var answer = $("<li>"); answer.attr("data-text", questionSetCopy[index].answer[j]); answer.text(questionSetCopy[index].answer[j]); $("#answers").append(answer); } correctAnswer = questionSet[index].answer[0]; // all correct answers are in index 0 countDown(); index++; $("li").on("click", function(){ if(hasGuessed) { return false; } else { guessed = $(this).attr("data-text"); if (guessed == correctAnswer){ $("li").addClass("incorrect"); $(this).addClass("correct").removeClass("incorrect"); } guess() } }); } function countDown() { var timeLeft= timer; $("#timer").show(); var count = setInterval(function() { timeLeft--; $("#timer").html("Time Remaining: " + timeLeft); if(timeLeft>0 && hasGuessed){ clearInterval(count); return false; } if (timeLeft == 0) { clearInterval(count); setTimeout(function() { //this is necessary to delay a bit to allow the time remaining to read 0 if(!hasGuessed){ $("#status").html("Times Up!"); $("#status").show(); } hasGuessed= true; wrongAnswer(); }, 250); } }, 1000); }// end countdown function function guess() { if( guessed === correctAnswer ){ $("#status").removeClass("wrong"); $("#status").html("Good Job!"); $("#status").show(); rightAnswer(); } else { $("#status").addClass("wrong"); $("#status").html("Sorry that's wrong"); $("#status").show(); wrongAnswer(); } } function wrongAnswer(){ wrong++; if (index==8){ displayEnd(); return; } hasGuessed = true; setTimeout(function() { questionDisplay(); }, 2800); } function rightAnswer(){ right++; if (index==8){ displayEnd(); return; } hasGuessed = true; setTimeout(function() { questionDisplay(); }, 2800); } function displayEnd(){ $("#start").on("click", function(){ questionDisplay(); }); $("#status").removeClass("wrong"); $("#status").html("Game Over"); $("#question").html("<br>You got " + right + " correct and " + wrong + " wrong! Play again?"); $("#status").show(); $("#timer").hide(); $("#question").show(); $("#answers").hide(); $("#start").show(); index = 0; right = 0; wrong = 0; guessed; correctAnswer= ""; hasGuessed= false; questionSetCopy = JSON.parse(JSON.stringify( questionSet )); return; } });//document ready function
'use strict'; const angular = require('angular'); const ngAdventure = angular.module('ngAdventure'); //map service is injected into player service //$q is promises for angular ngAdventure.factory('playerService', ['$q', '$log', 'mapService', playerService]); function playerService($q, $log, mapService) { $log.debug('init mapService'); //setup service let service = {}; //add features let turn = 0; let player = service.player = { name: 'Bob', //where the player starts off location: 'Waterfall', hp: 100, }; let history = service.history = [ { turn, desc:'welcome to the game', location: '', hp: player.hp, }, ]; service.movePlayer = function(direction) { return new $q((resolve, reject) => { turn++; //the room that the player is in, as set in playerService() initially let currentLocation = player.location; //direction passed in is where the player tries to move //if the direction is an available spot to move, new location is set to that value let newLocation = mapService.mapData[currentLocation][direction]; // if there is not a room in that direction, reject promise if (!newLocation) { history.unshift({ turn, desc: 'Wrong way.', location: player.location, hp: player.hp, }); console.log('history', history); return reject('No room in that direction!'); } history.unshift({ turn, location: player.location, desc: mapService.mapData[newLocation].desc, hp: player.hp, }); console.log('history', history); player.location = newLocation; return resolve(player.location); }); }; //return service return service; }
/* # ------------------ BEGIN LICENSE BLOCK ------------------ # # This file is part of SIGesTH # # Copyright (c) 2009 - 2015 Cyril MAGUIRE, <contact(at)ecyseo.net> # Licensed under the CeCILL v2.1 license. # See http://www.cecill.info/licences.fr.html # # ------------------- END LICENSE BLOCK ------------------- */ // marge est la distance entre le haut de la fenêtre et le haut du tableau // à partir de laquelle l'entête du tableau est en position fixe // Utile s'il y a un bloc fixe en haut de page, afin d'éviter que l'entête du tableau ne s'affiche en dessous if (marge == undefined || marge == null || isNaN(marge) == true) var marge = 0; if (idContainer == undefined || idContainer == null) { var idContainer; alert('Message de fixedTableHeader.js : Vous devez définir un container !'); } if (document.getElementById(idContainer) == undefined) { alert('Message de fixedTableHeader.js : Le container '+idContainer+' n\'existe pas !'); } ;(function(idContainer,marge,window,undefined){ 'use_strict'; if (idContainer == undefined || idContainer == null) return; // On convertit en integer en utilisant |0 à la place de parseInt moins fiable // voir http://www.js-attitude.fr/2012/12/26/convertir-un-nombre-en-texte-en-javascript/ marge = (marge|0); var isIE = isBrowserIE(); function isBrowserIE() { //var isMSIE = /*@cc_on!@*/0; var nav = navigator.userAgent.toLowerCase(); return (nav.indexOf('msie') != -1) ? (nav.split('msie')[1]|0) : false; } function Remove(idOfParent,idToRemove) { if (isIE) { document.getElementById(idToRemove).removeNode(true); } else { var Node1 = document.getElementById(idOfParent); var len = Node1.childNodes.length; for(var i = 0; i < len; i++){ if (Node1.childNodes[i] != undefined && Node1.childNodes[i].id != undefined && Node1.childNodes[i].id == idToRemove){ Node1.removeChild(Node1.childNodes[i]); } } } } function addElement(DomParent,elemToAdd,htmlToInsert,id) { var newElement = document.createElement('div'); document.body.appendChild(newElement); newElement.innerHTML = htmlToInsert; if (id != '') { newElement.setAttribute('id',id+'_wrapper'); } } function getScrollPosition() { return Array( (document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft, (document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop ); } function arrayCompare(a1, a2) { if (a1.length != a2.length) return false; var length = a2.length; for (var i = 0; i < length; i++) { if (a1[i] !== a2[i]) return false; } return true; } function inArray(needle, haystack) { var length = haystack.length; for(var i = 0; i < length; i++) { if(typeof haystack[i] == 'object') { if(arrayCompare(haystack[i], needle)) return true; } else { if(haystack[i] == needle) return true; } } return false; } /* Récupère la position réelle d'un objet dans la page (en tenant compte de tous ses parents) IN : Obj => Javascript Object ; Prop => Offset voulu (offsetTop,offsetLeft,offsetBottom,offsetRight) OUT : Numérique => position réelle d'un objet sur la page. */ function GetDomOffset( Obj, Prop ) { var iVal = 0; while (Obj && (Obj.tagName != 'body' || Obj.tagName != 'BODY')) { eval('iVal += Obj.' + Prop + ';'); Obj = Obj.offsetParent; } return iVal; } var fixedHeaderTable = { tbl:[], init: function() { this.addEventListener(window,"scroll", this); }, addEventListener: function(el, eventName, handler) { if (el.addEventListener) { el.addEventListener(eventName, handler, false); } else { el.attachEvent('on' + eventName, fixedHeaderTable.handleEvent); } }, handleEvent: function(e) { var evt = e ? e:event; if (isIE) { var obj = null; obj = fixedHeaderTable; } else { var obj = Object.create(null); obj = this; } var pos = getScrollPosition(); var tabPos = []; var c = obj.tbl.length; for (var i = 0; i < c; i++) { if (obj.tbl[i] != undefined) { tabPos[i] = (obj.tbl[i].posTop - (2*marge)) ; pos[1] += obj.tbl[i].containerPosTop; if (obj.tbl[i].posTop > 0 && obj.tbl[i].posBottom > 0) { if (pos[1] < tabPos[i]) { obj.action(i,false); } if (pos[1] > (tabPos[i]) ) { obj.action(i,true); } if (pos[1] >= obj.tbl[i].posBottom ) { obj.action(i,false); } } } }; }, action: function(i,display) { var clone = document.getElementById('fixedtableheader'+i); if (clone) { if (display === true) { clone.style.display = 'block'; } if (display === false) { clone.style.display = 'none'; } } }, }; var posBottom = 0; var posTop = 0; var mainDiv = document.getElementById(idContainer); var disp = mainDiv.style.display; if (disp == '') { disp = 'block'; } var containerPosTop = 0; // afin de déterminer la position des tableaux, on affiche le bloc qui les contient, s'il est masqué if(disp != 'block') { mainDiv.style.display = 'block'; containerPosTop = GetDomOffset( mainDiv, 'offsetTop' ); } var tables = mainDiv.getElementsByTagName('table'); // widths est l'ensemble des largeurs de colonnes pour chaque tableau var widths = []; if (tables.length > 0){ var c = tables.length; for (var i = 0; i < c; i++) { var lastcell = tables[i].getElementsByTagName('tr'); for (var j = 0,clast = lastcell.length; j <= clast; j++) { if(j == 0) { posTop = GetDomOffset(lastcell[0],'offsetTop');} if(j == clast) { posBottom = GetDomOffset(lastcell[j-1],'offsetTop');} } fixedHeaderTable.tbl[i] = new Object(); fixedHeaderTable.tbl[i].table = tables[i]; fixedHeaderTable.tbl[i].containerPosTop = containerPosTop; fixedHeaderTable.tbl[i].posTop = posTop; fixedHeaderTable.tbl[i].posBottom = posBottom; fixedHeaderTable.tbl[i].posLeft = GetDomOffset( tables[i], 'offsetLeft' ); var size = []; size[i] = tables[i].getElementsByTagName('thead'); var tableBody = []; tableBody[i] = tables[i].getElementsByTagName('tbody'); if (size[i][0]) { var nbOfRowsInHead = size[i][0].getElementsByTagName('tr').length; } // TBODY var tBod = tables[i].getElementsByTagName('tbody'); if (tBod[0]) { var nbOfRows = tBod[0].getElementsByTagName('tr'); } var nbOfCols = 0; var cellsOfThisRow = []; if (nbOfRows) { var allRowsOfBody = nbOfRows.length; for (var thisRow = 0; thisRow < allRowsOfBody; thisRow++) { cellsOfThisRow[thisRow] = nbOfRows[thisRow].getElementsByTagName('td'); var nbOfTdInThisRow = cellsOfThisRow[thisRow].length; nbOfCols = (nbOfTdInThisRow >= nbOfCols ? nbOfTdInThisRow : nbOfCols); } } var colWidth = []; var indexOfCol = 0; if (allRowsOfBody) { for (var row = 0; row < allRowsOfBody; row++) { var nbOfCells= cellsOfThisRow[row].length; for (var cel = 0; cel < nbOfCells; cel++) { var widthOfThisCell = cellsOfThisRow[row][cel].offsetWidth; colWidth[indexOfCol] = (widthOfThisCell > colWidth[indexOfCol] ? colWidth[indexOfCol] : widthOfThisCell); indexOfCol++; } } } // THEAD indexOfCol = 0; if (size[i][0]) { // largeurs est l'ensemble des largeurs de colonnes pour un tableau donné var largeurs = []; widths[i] = []; var dec = 0 var decalage = []; // Pour chaque ligne d'entête for (var k = 0; k < nbOfRowsInHead; k++) { if (size[i][k] != undefined) { if(disp == 'block') { fixedHeaderTable.tbl[i].posBottom -= ((size[i][k].offsetHeight/2)+marge); } else { fixedHeaderTable.tbl[i].containerPosTop -= ((size[i][k].offsetHeight*2)+marge); } var cells = size[i][k].getElementsByTagName('th'); var ccells = cells.length; for (var l = 0; l < ccells; l++) { largeurs[indexOfCol] = colWidth[indexOfCol]; if (indexOfCol<nbOfCols-1) { indexOfCol++; } else { break; } } var tot = largeurs.length; for (var larg = 0; larg < tot; larg++) { if (largeurs[larg] != null) { if (nbOfRowsInHead > 3) { var colsp = cells[larg].getAttribute('colspan'); if (colsp == null) { widths[i].push(largeurs[larg]); } } else { widths[i].push(largeurs[larg]); } var rowsp = cells[larg].getAttribute('rowspan'); if (rowsp == null) { decalage[dec] = largeurs[larg]; dec++; } } } var clone = size[i][k].cloneNode(true); var cloneBody = tableBody[i][k].cloneNode(true); var mainTab = document.createElement('div'); mainDiv.setAttribute('style', 'position:relative;'); cloneBody.setAttribute('style', 'visibility:hidden;border:none;'); var cellsBodyFake = cloneBody.getElementsByTagName('td'); var nbTds = cellsBodyFake.length; for (var m = 0; m < nbTds; m++) { cellsBodyFake[m].setAttribute('style','border:none;'); }; mainDiv.appendChild(mainTab); mainTab.innerHTML = '<table id="fixedtableheader'+i+'" class="fixedtableheader"></table>'; mainTab.setAttribute('style', 'position:relative;border:none;'); var tabFake = document.getElementById('fixedtableheader'+i); tabFake.setAttribute('style', 'display:block;position:fixed;top:'+marge+'px;max-width:'+mainTab.offsetWidth+'px;background:transparent;border:none;'); tabFake.style.display = 'none'; tabFake.appendChild(clone); tabFake.appendChild(cloneBody); var rowsFake = document.getElementById('fixedtableheader'+i).getElementsByTagName('tr'); var cellsFake = rowsFake[0].getElementsByTagName('th'); var indexOfWidth = 0; for (var m = 0; m < nbOfCols; m++) { if (cellsFake[m] != undefined) { var rowsp = cellsFake[m].getAttribute('rowspan'); if (rowsp == null && decalage[m] != undefined) { if (cellsFake[m].getAttribute('style') != '') { cellsFake[m].setAttribute('style','min-width:'+decalage[m]+'px;'); } } var colsp = cellsFake[m].getAttribute('colspan'); if (colsp != null && rowsp == null) { if (cellsFake[m].getAttribute('style') != '') { var w = 0; var colspanWidth = 0; while (w != colsp) { colspanWidth += widths[i][m+w]; w++; } cellsFake[m].setAttribute('style','min-width:'+colspanWidth+'px;'); indexOfWidth = m+w-1; } } else { if (cellsFake[m].innerHTML == '') { cellsFake[m].innerHTML = '&nbsp;'; cellsFake[m].setAttribute('style','min-width:'+widths[i][indexOfWidth]+'px;'); } if (cellsFake[m].getAttribute('style') != '') { cellsFake[m].setAttribute('style','width:'+widths[i][indexOfWidth]+'px;'); } } indexOfWidth++; } }; delete clone; delete cloneBody; } } } else { fixedHeaderTable.tbl.splice(i,1); } }; fixedHeaderTable.init(); } mainDiv.style.display = disp; })(idContainer,marge,window);
import axios from "axios"; import { API_URL } from '../constants'; import authHeader from './auth-header'; class PostService{ postMessage(content,file){ let formData = new FormData(); formData.append('image', file); formData.append('content', content); return axios.post(API_URL + 'posts',formData, { headers: authHeader() }); } deletePost(postId){ return axios.delete(API_URL + `posts/${postId}`,{ headers: authHeader() }); } reportPost(postId){ return axios.get(API_URL + `posts/report/${postId}`,{ headers: authHeader() }); } gettAllPosts(){ return axios.get(API_URL + 'posts', { headers: authHeader() }); } getPostsByUserId(userId){ return axios.get(API_URL + `posts/byuserId/${userId}`, { headers: authHeader() }); } gettAllReportedPosts(){ return axios.get(API_URL + 'posts/reported', { headers: authHeader() }); } likePost(postId,option){ return axios.post(API_URL + `posts/like/${postId}`,{option}, { headers: authHeader() }); } commentPost(postId,content){ return axios.post(API_URL + `comments`,{post_id:postId,content}, { headers: authHeader() }); } deleteComment(commentId){ return axios.delete(API_URL + `comments/${commentId}`,{ headers: authHeader() }); } } export default new PostService()
/** @jsx React.DOM */ var React = require('react'), Router = require('react-router'); var Util = require('../../../util'), Actions = require('../../../actions'); var Header = require('../header'), //Inlude the tabs Company = require('./company'); // React-router variables var Link = Router.Link; var RouteHandler = Router.RouteHandler; var Admin = React.createClass({ mixins: [ Router.State ], statics: { willTransitionTo: function(transition) { if (transition.path === '/admin' || transition.path === '/admin/') { transition.redirect('/admin/company'); } } }, getInitialState: function() { return { }; }, componentDidMount: function() { }, componentWillUnmount: function() { }, render: function() { // Get the route name var routeName = this.getRoutes().reverse()[0].name; return ( <div id="private"> <Header /> <div id="account" className="page"> <div id="content"> <div className="tabs"> <Link to="company">Manage Company</Link> </div> <RouteHandler component="div" key={routeName}/> </div> </div> </div> ); } }); module.exports = Admin;
import React, { Component } from 'react'; import { Input } from 'antd'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; const Search = Input.Search; class SearchBar extends Component { constructor(props) { super(props); } onSearch = (keyword) => { if (keyword !== '' && keyword !== this.props.keyword) { this.props.updateSearchKeyword(keyword); this.props.history.push(`/search?keyword=${window.encodeURIComponent(keyword)}`); } } render() { const { keyword } = this.props; return ( <Search placeholder="歌曲/专辑/艺人" defaultValue={ keyword || '' } onSearch={this.onSearch} enterButton size="large" /> ); } } function mapStateToProps(state) { return { keyword: state.searchKeyword }; } function mapDispatchToProps(dispatch) { return { updateSearchKeyword: (keyword) => { dispatch({ type: 'UPDATE_SEARCH_KEYWORD', data: keyword }); } }; } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(SearchBar));
import React from 'react'; import ReactDOM from 'react-dom'; import Pomodoro from './components/pomodoro'; const pomodoro = <Pomodoro></Pomodoro>; ReactDOM.render(pomodoro, document.querySelector('.app')); // Making a change from pomKing
import React, { Component } from 'react' import styled from 'styled-components' import { Label, Input, CheckboxInput, Textarea } from '../../mia-ui/forms' // import {Row, Column} from '../../mia-ui/layout' import { Button } from '../../mia-ui/buttons' // import Snackbar from '../../mia-ui/Snackbar' import { Spinner, Loading, Waiting } from '../../mia-ui/loading' import { Flex, Box } from 'grid-styled' import Joyride from 'react-joyride' import { ImagesQuery } from '../../../apollo/queries/images' export default class ImageUploader extends Component { tourId = 'ImageUploader' // componentWillReceiveProps(nextProps) { // try { // if (nextProps.showDemo) { // } // } catch (ex) { // console.error(ex) // } // } state = { files: [], uploading: false, hasRights: false, description: '', title: '', snackMessage: '', snackId: Math.random() } render() { const { handleFile, handleUpload, handleChange, handleCheckbox, state: { files, hasRights, description, title, uploading, snackId, snackMessage, preview } } = this return ( <Flex my={2} id={'upload-images-container'}> {uploading ? <Waiting /> : null} <Flex w={1 / 2} flexWrap={'wrap'} flexDirection={'column'} pr={2}> <Box w={1}> <Label>Image</Label> <input type={'file'} name={'files'} accept={'image/*'} onChange={handleFile} /> </Box> <Box w={1}> <Label>Title</Label> <Input name={'title'} value={title} onChange={handleChange} /> </Box> <Box w={1}> <Label>Description</Label> <Textarea name={'description'} value={description} onChange={handleChange} /> </Box> <Box w={1}> <Label>I have the right to distribute this image.</Label> <CheckboxInput value={'hasRights'} checked={hasRights} onChange={handleCheckbox} /> </Box> <Button onClick={handleUpload} disabled={ !hasRights || !description || !title || files.length < 1 || uploading } > Upload </Button> </Flex> <Box> {uploading ? <Spinner /> : null} {preview && !uploading ? ( <Preview src={preview} alt={`Preview of ${description}`} /> ) : null} </Box> {this.props.tour ? ( <Joyride run={this.props.tour.run(this)} steps={this.props.tour.steps(this)} stepIndex={this.props.tour.stepIndex} callback={this.props.tour.callback(this)} styles={{ buttonClose: { display: 'none' }, buttonNext: { display: 'none' }, buttonBack: { display: 'none' } }} disableOverlayClose={true} disableCloseOnEscape={true} /> ) : null} </Flex> ) } handleFile = ({ target: { name, files } }) => { this.setState({ [name]: files }) if (files[0]) { const reader = new FileReader() reader.onload = e => { this.setState({ preview: e.target.result }) } reader.readAsDataURL(files[0]) } } handleCheckbox = ({ target: { value, checked } }) => this.setState({ [value]: checked }) handleUpload = async () => { try { const { state: { files: [file], title, description }, props: { subdomain } } = this let form = new FormData() form.append('file', file) form.append('userId', localStorage.getItem('userId')) form.append('title', title) form.append('description', description) form.append('subdomain', subdomain) const url = process.env.FILE_STORAGE === 'local' ? `${process.env.TILE_URL}/image` : `${process.env.API_URL}/image` let options = { method: 'POST', body: form } this.setState({ uploading: true }) const response = await fetch(url, options) await response.json() this.setState({ uploading: false, files: [], hasRights: false, description: '', title: '', preview: '' }) await this.props.refetch() } catch (ex) { console.error(ex) } } handleChange = ({ target: { value, name } }) => this.setState({ [name]: value }) } const Preview = styled.img` height: 300px; object-fit: contain; ` const Message = styled.p` font-family: ${({ theme }) => theme.font.regular}; `
import React from "react"; import ActualDate from "./ActualDate"; import WeatherIcon from "./WeatherIcon"; import WeatherTemperature from "./WeatherTemperature"; import "./App.css"; export default function WeatherInfo(props) { return ( <div className="WeatherInfo"> {/* Main : city, day, description, icon, units*/} <div className="city-name"> <h1>{props.data.city}</h1> </div> <div className="dayAndTime"> <div className="todayDay"> <ActualDate date={props.data.date} /> </div> <div className="todayDescription"> <h4 className="description">{props.data.description}</h4> </div> </div> <div className="tempIcon"> <div className="icon row"> <div className="col pr-4"> <WeatherIcon code={props.data.icon} size={75} /> </div> <WeatherTemperature celsius={props.data.temp}/> </div> </div> {/* WeatherDescription */} <div className="weather-description"> <div className="feels-like"> <p> Feels like: <span>{Math.round(props.data.feelsLike)}°C</span> </p> <p> °C min: <span>{Math.round(props.data.tempMin)}°C</span> </p> <p> °C max: <span>{Math.round(props.data.tempMax)}°C</span>{" "} </p> </div> <div className="humid-wind-visib"> <p> Humidity: <span>{props.data.humidity}%</span> </p> <p> Wind: <span>{props.data.wind} km/h</span> </p> <p> Visibility: <span>{props.data.visibility} km</span>{" "} </p> </div> </div> </div> ); }
import axios from 'axios'; import fetchPosts from './fetchPosts'; const baseURL="https://kavya-lambdagram.herokuapp.com"; function addComment(newComment,postId,setPosts){ console.log('newcomment in addcomment=',newComment) axios.post(`${baseURL}/api/posts/${postId}/comments`,newComment) .then((res)=>{ console.log('res from addcomment',res) fetchPosts(setPosts); }) .catch(err=>{ console.log('err in addComment',err) }) } export default addComment;
//Remove Button, removes all current notes; d3.select('.remove') .on('click', function() { d3.selectAll('.note') .remove(); }); //Surprise Me Button d3.select('.lucky') .on('click', function(){ d3.selectAll('.note') .style('color', randomRGB) .style('background-color', randomRGB) .style('border', '8px solid black') }) //Global Variables const input = d3.select('input'); const preview = d3.select('.preview'); //Selects the new note input field and appends content to the DOM d3.select("#new-note") .on('submit', function() { d3.event.preventDefault(); //Prevents page reload on 'submit' d3.select("#notes") .append('p') .classed('note', true) .text(input.property('value')); input.property('value', ''); setPreview('') //hides after preview completion }); //Preview Input input.on('input', function() { const note = d3.event.target.value; //Value of input setPreview(note); }); //Set Preview Helper function setPreview(val) { preview.text(val) .classed('hide', val === ''); //hides if no value } //RGB Color Gen const randomRGB = () => { let r = Math.floor(Math.random() * 256); let g = Math.floor(Math.random() * 256); let b = Math.floor(Math.random() * 256); return 'rgb(' + r + ', ' + g + ', ' + b + ')'; }
'use strict'; describe('Filters:hostNameFromUrl', function(){ var filter; beforeEach(module('angularTestApp')); beforeEach(inject(function($filter){ filter = $filter('hostNameFromUrl'); })); it('should return hostname from url', function(){ var result = filter('http://www.yandex.ru/some_link'); expect(result).toBe('www.yandex.ru'); }) });
import React, { Component } from "react"; export default class Carousel extends Component { constructor() { super(); this.state = {}; } render() { return ( <div id="carouselBlk"> <div id="myCarousel" className="carousel slide"> <div className="carousel-inner"> <div className="item active"> <div className="container"> <a href="register.html"> <img style={{width: "100%"}} src="/images/carousel/1.png" alt="special offers" /> </a> <div className="carousel-caption"> <h4>First Thumbnail label</h4> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> </div> </div> </div> <div className="item"> <div className="container"> <a href="register.html"> <img style={{width: "100%"}} src="/images/carousel/2.png" alt="" /> </a> <div className="carousel-caption"> <h4>Second Thumbnail label</h4> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> </div> </div> </div> <div className="item"> <div className="container"> <a href="register.html"> <img src="/images/carousel/3.png" alt="" /> </a> <div className="carousel-caption"> <h4>Third Thumbnail label</h4> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> </div> </div> </div> </div> <a className="left carousel-control" href="#myCarousel" data-slide="prev">&lsaquo;</a> <a className="right carousel-control" href="#myCarousel" data-slide="next">&rsaquo;</a> </div> </div> ); } }
// Libraries import React from 'react'; // Components | Utils import UserAccount from '../UserAccount'; import getSounds from '../../../utils/soundUtils'; // Assets import * as Styled from './styles'; import WindowsXPShutdown from '../../../assets/images/winxp-shutdown.webp'; import WindowsXPLogo2 from '../../../assets/images/login-logo.webp'; const Login = () => { const [shutdownSound] = getSounds('shutdown'); /* ==================================================== ==================== RENDER ======================== ==================================================== */ return ( <Styled.LoginScreen> <Styled.Header /> <Styled.Main> <Styled.MainLeft> <img src={WindowsXPLogo2} alt="windows xp logo" width="205" height="118" /> <span>To begin, select your user</span> </Styled.MainLeft> <Styled.MainRight> <UserAccount isGuest /> <UserAccount /> </Styled.MainRight> </Styled.Main> <Styled.Footer> <div> <Styled.ShutdownButton onClick={() => shutdownSound.play()}> <img src={WindowsXPShutdown} alt="shutdown icon" height="25" width="25" /> <span>Turn off computer</span> </Styled.ShutdownButton> </div> <p> This XP cannot be turned off. After all these years we have been away, we wouldnt want to close, would we? But out of respect for you, I will play a shutdown sound. </p> </Styled.Footer> </Styled.LoginScreen> ); }; export default Login;
import thunkMiddleware from 'redux-thunk'; import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit'; import { createWrapper } from 'next-redux-wrapper'; import { deviceRegistryApi } from './services/deviceRegistry'; import selectedCollocateDevicesReducer from './services/collocation/selectedCollocateDevicesSlice'; import { collocateApi } from './services/collocation'; import collocationDataReducer from './services/collocation/collocationDataSlice'; import { createAccountSlice } from './services/account/CreationSlice'; import { userLoginSlice } from './services/account/LoginSlice'; const store = () => configureStore({ reducer: { [deviceRegistryApi.reducerPath]: deviceRegistryApi.reducer, [collocateApi.reducerPath]: collocateApi.reducer, selectedCollocateDevices: selectedCollocateDevicesReducer, collocationData: collocationDataReducer, [createAccountSlice.name]: createAccountSlice.reducer, [userLoginSlice.name]: userLoginSlice.reducer }, middleware: [thunkMiddleware, ...getDefaultMiddleware().concat(deviceRegistryApi.middleware, collocateApi.middleware)], }); export const wrapper = createWrapper(store); export default store;
$(function () { tradeRefreshTypeahead(true); }); //******************************* // COMPARE COUNTRY //******************************* $(function () { $('#chartCompareModal').on('show.bs.modal', function (e) { if (typeof e.relatedTarget !== 'undefined') { var chart = $(e.relatedTarget).parents('.chart-item'); } else if ($('.chart-item[data-chart-id=' + $('#chartCompareModal').data('chart-id') + ']').length > 0) { var chart = $('.chart-item[data-chart-id=' + $('#chartCompareModal').data('chart-id') + ']') } else { var chart = $('.chart-item:first'); } $('#chartCompareModal').data('chart-id', chart.data('chart-id')); var data = $('.chart-item-data[data-chart-id=' + chart.data('chart-id') + ']').data(); $('#chartCompareModal .chart-search-list-reporter .list-group-item[data-ref=' + data['reporter'] + ']').addClass('list-group-item-disabled'); tradeRefreshTypeahead(); $('#chartCompareModal .form-typeahead input').data('ref', '').typeahead('val', ''); if (typeof data['compare'] !== 'undefined') { compare = data['compare'].split(','); if (compare.length > 0) { for (var i = 0; i < compare.length; i++) { if (typeof compare[i] !== 'undefined' && compare[i] != '') { var label = $('.chart-search-list-reporter .list-group-item[data-ref=' + compare[i] + ']').data('label'); $('#ccmReporter-' + (i + 1)).data('ref', compare[i]).typeahead('val', label); } } $('.ccmSearchSave').addClass('btn-primary btn-inverse').removeClass('btn-disabled'); } } toggleClearBtns(); }); $('#chartCompareModal .chart-submit-btn').click(function () { var btn = $(this), chartId = btn.parents('.modal').data('chart-id'), code = btn.data('code'); if (typeof chartId !== 'undefined' && !$('#chartCompareModal .modal-body .btn').hasClass('btn-disabled')) { var compare = []; $('#chartCompareModal .ccmReporter input').each(function () { if (typeof $(this).data('ref') != 'undefined' && $(this).data('ref') != '' && $.inArray($(this).data('ref'), compare) === -1) { compare.push($(this).data('ref')); } }); compare = compare.join(); $('.chart-item-data[data-chart-id=' + chartId + ']').data('compare', compare); drawChart(chartId); btn.parents('.modal').modal('hide'); } }); }); //******************************* // INDICATOR //******************************* $(function () { $('#chartTradeModal').on('show.bs.modal', function (e) { //reset indicator form $('#chartTradeModal .model-title').text('Add Indicator'); $('#chartTradeModal .chart-submit-btn').html('<span class="fa fa-plus"></span> Add Indicator'); $('#chartTradeModal .chart-submit-btn').addClass('btn-disabled').removeClass('btn-primary btn-inverse').find('.fa').removeClass().addClass('fa fa-plus'); $('#aimIndicator').val(''); $('.aimReporter input, .aimSector input, .aimPartner input').data('ref', '').typeahead('val', ''); $('.aimSector input, .aimPartner input').parents('.form-group').hide(); $('.chart-search-list').hide(); $('.aimPartnerLabel').hide().find('.count').text('3 partner countries'); $('.aimSectorLabel').hide().find('.count').text('3 commodities'); $('#chartTradeModal .chart-submit-btn').data('update', 'add'); if (typeof e.relatedTarget !== 'undefined' && $(e.relatedTarget).parents('.chart-group').length > 0) { var group = $(e.relatedTarget).parents('.chart-group'); if(group.hasClass('add-fav')){ $('#chartTradeModal .chart-submit-btn').data('update', 'favorite'); } } else if (typeof $('#chartTradeModal').data('chart-id') !== 'undefined' && $('.chart-group[data-chart-id=' + $('#chartTradeModal').data('chart-id') + ']').length > 0) { var group = $('.chart-group[data-chart-id=' + $('#chartTradeModal').data('chart-id') + ']') } else { var group = $('.chart-group:first'); } $('#chartTradeModal').data('chart-id', group.data('chart-id')); $('.aimReporter').hide(); $('.aimIndicator').show(); if (typeof group.data('reporter') === 'undefined') { $('.aimIndicator').hide(); $('.aimReporter').slideDown(); } else { $('#aimReporter').data('ref', group.data('reporter')); } $('#chartTradeModal .chart-search-list-partner .list-group-item').show(); $('#chartTradeModal .chart-search-list-partner .list-group-item[data-ref=' + group.data('reporter') + ']').hide(); if ($(e.relatedTarget).hasClass('chart-edit-btn')) { tradeFormPreset($(e.relatedTarget).parents('.chart-item').data('chart-id')); } else if (group.find('.chart-item-data').length > 0 && typeof group.find('.chart-item-data').data('require-editing') !== 'undefined' && group.find('.chart-item-data').data('require-editing')) { tradeFormPreset(group.find('.chart-item-data').data('chart-id')); } validateSubmitBtn('trade'); }); $('#aimIndicator').change(function () { $('.aimPartnerLabel').hide().find('.count').text('3 partner countries'); $('.aimSectorLabel').hide().find('.count').text('3 commodities'); $('.aimSector, .aimPartner').find('input').data('ref', '').typeahead('val', ''); validateSubmitBtn('trade'); }); $('#chartTradeModal .chart-submit-btn').click(function () { var btn = $(this), chartId = btn.parents('.modal').data('chart-id'), partner = [], sector = []; if(!btn.hasClass('btn-disabled')) { btn.parents('.modal').modal('hide'); var reporter = $('#chartTradeModal .aimReporter input').data('ref'); var triggerLoading = true; if (typeof chartId !== 'undefined') { var group = $('.chart-group[data-chart-id=' + chartId + ']'); if(group.length == 0){ var group = $('.chart-item[data-chart-id=' + chartId + ']').parents('.chart-group'); } if(group.length != 0) { triggerLoading = false; renderChartLoading(group); if (typeof group.data('reporter') !== 'undefined') { reporter = group.data('reporter'); } } } var partner = []; $('.aimPartner input').each(function () { if (typeof $(this).data('ref') != 'undefined' && $(this).data('ref') != '' && $.inArray($(this).data('ref'), partner) === -1) { partner.push($(this).data('ref')); } }); partner = partner.join(); var sector = []; $('.aimSector input').each(function () { if (typeof $(this).data('ref') != 'undefined' && $(this).data('ref') != '' && $.inArray($(this).data('ref'), sector) === -1) { sector.push($(this).data('ref')); } }); sector = sector.join(); if (btn.data('update') == 'add' && typeof chartId !== 'undefined') { $.ajax({ url: siteData.data('url') + '/trade/chart/', dataType: 'json', data: { 'indicator': $('#aimIndicator').val(), 'reporter': reporter, 'period': group.find('.chart-period').data('period'), 'editable': group.data('editable'), 'partner': partner, 'sector': sector, 'view': 'data', }, success: function (returnData) { if (returnData.valid) { group.find('.chart-group-data').append(returnData.chart.data); //addChart(btn.parents('.chart-group'),data) drawChart(returnData.chart.chartId, triggerLoading); $('.chart-group-empty').hide(); } else { if (typeof returnData.error !== 'undefined') { for (var key in returnData.error) { addFlashMessage('danger', returnData.error[key]); } } group.find('.chart-loading').fadeOut(function () { $(this).remove(); }); } } }); } if (btn.data('update') == 'favorite') { $.ajax({ url: siteData.data('url') + '/user/addFavorite/', dataType: 'json', method: 'post', data: { 'favorite-type': 'trade', 'indicator': $('#aimIndicator').val(), 'reporter': reporter, 'period': group.find('.chart-period').data('period'), 'partner': partner, 'sector': sector, }, success: function (returnData) { if (returnData.valid) { $('.trade-add-fav:first').before('<div class="col-sm-6 user-favorite" style="display: none;">' + returnData.html + '</div>'); $('.chart-item-data[data-chart-id=' + returnData.chartId + ']').parents('.user-favorite').slideDown(); drawChart(returnData.chartId, triggerLoading); if ($('.trade-favorites .chart-group').length >= 7) { $('.trade-add-fav').slideDown(); } } else if (typeof returnData.error !== 'undefined') { for (var key in returnData.error) { addFlashMessage('danger', returnData.error[key]); } } } }); } if (btn.data('update') == 'edit' && typeof chartId !== 'undefined') { $('.chart-item-data[data-chart-id=' + chartId + ']').data('partner', partner); $('.chart-item-data[data-chart-id=' + chartId + ']').data('sector', sector); $('.chart-item-data[data-chart-id=' + chartId + ']').data('indicator', $('#aimIndicator').val()); $('.chart-item-data[data-chart-id=' + chartId + ']').data('require-editing', false); drawChart(chartId, triggerLoading); } } }); $('.chartTypeField input').click(function () { $('.chartTypeField input').parents('.btn').removeClass('btn-primary'); $(this).parents('.btn').addClass('btn-primary'); }); }); function tradeFormPreset (chartId) { var data = $('.chart-item-data[data-chart-id=' + chartId + ']').data(); $('#chartTradeModal').data('chart-id', chartId); if (typeof data['reporter'] !== 'undefined' && data['reporter'] != '') { var label = $('.chart-search-list-reporter .list-group-item[data-ref=' + data['reporter'] + ']').data('label'); $('#aimReporter').data('ref', data['reporter']).typeahead('val', label); } if (typeof data['indicator'] !== 'undefined') { $('#aimIndicator').val(data['indicator']).selectpicker('refresh'); } if (typeof data['partner'] !== 'undefined') { partners = data['partner'].split(','); if (partners.length > 0) { for (var i = 0; i < partners.length; i++) { if (typeof partners[i] !== 'undefined' && partners[i] != '') { var label = $('.chart-search-list-partner .list-group-item[data-ref=' + partners[i] + ']').data('label'); $('#aimPartner-' + (i + 1)).data('ref', partners[i]).typeahead('val', label); } } } } if (typeof data['sector'] !== 'undefined') { data['sector'] = '' + data['sector']; //fix: convert number to string sectors = data['sector'].split(','); if (sectors.length > 0) { for (var i = 0; i <= sectors.length; i++) { if (typeof sectors[i] !== 'undefined' && sectors[i] != '') { var label = $('.chart-search-list-sector .list-group-item[data-ref=' + sectors[i] + ']').data('label'); $('#aimSector-' + (i + 1)).data('ref', sectors[i]).typeahead('val', label); } } } } if (typeof data['compare'] !== 'undefined' && data['compare'] != '') { $('.aimSector').each(function (i) { if (i > 0) { $(this).hide(); } }); } if (typeof data['requireEditing'] === 'undefined' || !data['requireEditing']) { $('#chartTradeModal .model-title').text('Edit Indicator'); $('#chartTradeModal .chart-submit-btn').html('<span class="fa fa-pencil"></span> Edit Indicator'); } $('#chartTradeModal .chart-submit-btn').data('update', 'edit'); validateSubmitBtn('trade'); } function tradeRefreshTypeahead (init) { init = (typeof init !== 'undefined' ? init : false); var datasets = [], flow = (typeof $('#aimIndicator').val() !== 'undefined' && $('#aimIndicator').val().indexOf('flow-') !== -1 ? '-flow' : ''), reporter = (typeof $('#aimReporter').data('ref') !== 'undefined' ? $('#aimReporter').data('ref') : ''); if (!init) { filterLists($('#chartTradeModal .chart-search-list-reporter, #chartCompareModal .chart-search-list-reporter'), { type: 'reporter', }); filterLists($('#chartTradeModal .chart-search-list-partner'), { type: 'partner' + flow, reporter: $('#aimReporter').data('ref'), }); filterLists($('#chartTradeModal .chart-search-list-sector'), { type: 'sector' + flow, reporter: $('#aimReporter').data('ref'), }); } datasets.push({ 'selector': '.ccmReporter input', 'url': siteData.data('url') + '/autoComplete/reporterTrade?&term=%QUERY', }); datasets.push({ 'selector': '.aimReporter input', 'url': siteData.data('url') + '/autoComplete/reporterTrade?term=%QUERY', }); datasets.push({ 'selector': '.aimPartner input', 'url': siteData.data('url') + '/autoComplete/partner?reporter=' + reporter + '&filterType=partner' + flow + '&term=%QUERY', }); datasets.push({ 'selector': '.aimSector input', 'url': siteData.data('url') + '/autoComplete/sector?reporter=' + reporter + '&filterType=sector' + flow + '&term=%QUERY', }); refreshTypeahead('trade', datasets, init); } function tradeValidateSubmitBtn () { var valid = true; var reporter = ''; if (typeof $('#chartTradeModal .aimReporter input').data('ref') !== 'undefined' && $('#chartTradeModal .aimReporter input').data('ref') != '') { $('.aimIndicator').slideDown(); reporter = $('#aimReporter').data('ref'); } else { $('.aimIndicator, .aimPartner, .aimSector, aimPartnerLabel, aimSectorLabel').slideUp(); $('.chart-search-list').slideUp(); $('#aimIndicator').val(''); $('.aimSector input, .aimPartner input').data('ref', '').typeahead('val', ''); valid = false; } //disable indicators that are already in use $('#aimIndicator option').prop('disabled', false); if (reporter != '' && $('.chart-item-data').length > 0) { $('.chart-item-data').each(function () { if (typeof $(this).data('indicator') !== 'undefined' && typeof $(this).data('reporter') !== 'undefined' && $(this).data('reporter') == reporter && $(this).data('indicator') != $('#aimIndicator').val()) { $('#aimIndicator option[value=' + $(this).data('indicator') + ']').prop('disabled', true); } }); } $('#aimIndicator').selectpicker('refresh'); switch ($('#aimIndicator').val()) { //3 partners case 'trade-partner-ev': case 'trade-partner-iv': case 'trade-partner-tt': $('.aimPartner').slideDown(); $('.aimSector').hide(); $('.aimPartnerLabel').slideDown(); $('.aimSectorLabel').hide(); break; //3 sectors case 'trade-sector-ev': case 'trade-sector-iv': case 'trade-sector-tt': $('.aimPartner').hide(); $('.aimSector').slideDown(); $('.aimPartnerLabel').hide(); $('.aimSectorLabel').slideDown(); break; //3 partners and 1 sector case 'flow-partner-sector-iv': case 'flow-partner-sector-ev': $('.aimPartner').slideDown(); $('.aimSector').hide(); $('.aimSector:first').slideDown(); $('.aimPartnerLabel').slideDown(); $('.aimSectorLabel').slideDown().find('.count').text('1 commodity'); break; //1 partner case 'flow-partner-top10-iv': case 'flow-partner-top10-ev': $('.aimPartner').hide(); $('.aimPartner:first').slideDown(); $('.aimSector').hide(); $('.aimPartnerLabel').slideDown().find('.count').text('1 partner country'); $('.aimSectorLabel').hide(); break; //1 partner and 3 sectors case 'flow-sector-partner-iv': case 'flow-sector-partner-ev': $('.aimPartner').hide(); $('.aimPartner:first').slideDown(); $('.aimSector').slideDown(); $('.aimPartnerLabel').slideDown().find('.count').text('1 partner country'); $('.aimSectorLabel').slideDown(); break; //1 sector case 'flow-sector-top10-iv': case 'flow-sector-top10-ev': $('.aimPartner').hide(); $('.aimSector').hide(); $('.aimSector:first').slideDown(); $('.aimPartnerLabel').hide(); $('.aimSectorLabel').slideDown().find('.count').text('1 commodity'); break; //no partners or sectors default: $('.aimPartner').hide(); $('.aimSector').hide(); $('.aimPartnerLabel').hide(); $('.aimSectorLabel').hide(); break; } if ($('#aimIndicator').val() == '') { valid = false; } if (valid) { var hasPartner = false; $('.aimPartner').each(function (i) { if ($(this).is(':visible')) { hasPartner = true; } }); if (hasPartner) { valid = false; $('.aimPartner').each(function (i) { if ($(this).is(':visible') && typeof $(this).find('input').data('ref') !== 'undefined' && $(this).find('input').data('ref') != '') { valid = true; } }); } } if (valid) { var hasSector = false; $('.aimSector').each(function (i) { if ($(this).is(':visible')) { hasSector = true; } }); if (hasSector) { valid = false; $('.aimSector').each(function (i) { if ($(this).is(':visible') && typeof $(this).find('input').data('ref') !== 'undefined' && $(this).find('input').data('ref') != '') { valid = true; } }); } } if (valid) { $('#chartTradeModal .chart-submit-btn').addClass('btn-primary btn-inverse').removeClass('btn-disabled'); } else { $('#chartTradeModal .chart-submit-btn').addClass('btn-disabled').removeClass('btn-primary btn-inverse'); } var icon = 'plus'; if ($('.chart-submit-btn').data('update') == 'edit') { icon = 'pencil'; } $('#chartTradeModal .chart-submit-btn .fa').removeClass().addClass('fa fa-' + icon); tradeRefreshTypeahead(); }
const deepClone = (x) => { if (typeof x !== 'object') return x; let k; let tmp; const str = Object.prototype.toString.call(x); if (str === '[object Object]') { tmp = {}; Object.keys(x).forEach((key) => { if (key === '__proto__') { Object.defineProperty(tmp, key, { value: deepClone(x[key]), configurable: 1, enumerable: 1, writable: 1, }); } else { tmp[key] = deepClone(x[key]); } }); return tmp; } if (str === '[object Array]') { k = x.length; tmp = new Array(k); while (k >= 0) { tmp[k] = deepClone(x[k]); k -= 1; } return tmp; } if (str === '[object Set]') { tmp = new Set(); x.forEach((val) => { tmp.add(deepClone(val)); }); return tmp; } if (str === '[object Map]') { tmp = new Map(); x.forEach((val, key) => { tmp.set(deepClone(key), deepClone(val)); }); return tmp; } if (str === '[object Date]') { return new Date(+x); } if (str === '[object RegExp]') { tmp = new RegExp(x.source, x.flags); tmp.lastIndex = x.lastIndex; return tmp; } if (str.slice(-6) === 'Array]') { return new x.constructor(x); } return x; }; export default deepClone;
/** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.provide('audioCat.ui.tracks.TimeDomainRuler'); goog.require('audioCat.audio.EventType'); goog.require('audioCat.ui.text.Precision'); goog.require('audioCat.ui.visualization.TimeUnit'); goog.require('audioCat.ui.visualization.events'); goog.require('goog.asserts'); goog.require('goog.events'); /** * The ruler that denotes the time for tracks. Scales to updates. * @param {!audioCat.utility.DomHelper} domHelper Facilitates DOM interactions. * @param {!audioCat.ui.visualization.TimeDomainScaleManager} * timeDomainScaleManager Maintains and updates the current time-domain * scale. * @param {!audioCat.ui.visualization.Context2dPool} context2dPool Pools 2D * contexts so that we do not create too many. * @param {number} rulerHeight The height of the ruler in pixels. A whole * number. * @param {!audioCat.ui.window.ScrollResizeManager} resizeScrollManager Manages * resizing and scrolling. * @param {!audioCat.audio.play.TimeManager} timeManager Manages the current * displayed and stable play time. * @param {!audioCat.audio.play.PlayManager} playManager Manages playing. * @param {!audioCat.ui.text.TimeFormatter} timeFormatter Formats time. * @constructor */ audioCat.ui.tracks.TimeDomainRuler = function( domHelper, timeDomainScaleManager, context2dPool, rulerHeight, resizeScrollManager, timeManager, playManager, timeFormatter) { /** * Facilitates DOM interactions. * @private {!audioCat.utility.DomHelper} */ this.domHelper_ = domHelper; /** * Manages resizing and scrolling. * @private {!audioCat.ui.window.ScrollResizeManager} */ this.resizeScrollManager_ = resizeScrollManager; /** * Manages the current displayed and stable play time. * @private {!audioCat.audio.play.TimeManager} */ this.timeManager_ = timeManager; /** * Manages the playing of audio. * @private {!audioCat.audio.play.PlayManager} */ this.playManager_ = playManager; /** * @private {!audioCat.ui.text.TimeFormatter} */ this.timeFormatter_ = timeFormatter; /** * Maintains and updates the current time-domain scale. * @private {!audioCat.ui.visualization.TimeDomainScaleManager} */ this.timeDomainScaleManager_ = timeDomainScaleManager; // Redraw when the zoom level has changed. goog.events.listen(timeDomainScaleManager, audioCat.ui.visualization.events.ZOOM_CHANGED, this.handleZoomChange_, false, this); // Redraw when we change whether we're displaying using bars or time units. goog.events.listen(timeDomainScaleManager, audioCat.ui.visualization.events.SCORE_TIME_SWAPPED, this.handleScoreTimeSwapped_, false, this); // Redraw when the tempo changes. goog.events.listen(timeDomainScaleManager.getSignatureTempoManager(), audioCat.audio.EventType.TEMPO_CHANGED, this.handleTempoChanged_, false, this); var context2d = context2dPool.retrieve2dContext(); context2d.fillStyle = '#000'; var canvas = context2d.canvas; canvas.height = rulerHeight; /** * The 2D context for the canvas on which to draw the ruler. * @private {!CanvasRenderingContext2D} */ this.context2d_ = context2d; // When the user clicks on the ruler, set the current time. domHelper.listenForPress(canvas, this.handleClick_, false, this); /** * The height of the canvas for the ruler. A whole number. * @private {number} */ this.rulerHeight_ = rulerHeight; /** * The canvas Y value of the top of a major tick. A whole number. * @private {number} */ this.rulerMajorTickYValue_ = rulerHeight - 10; /** * The starting Y value (the top of) of the major tick. * @private {number} */ this.majorTickTopPosition_ = this.rulerMajorTickYValue_ - 3; /** * The canvas Y value of the top of a minor tick. A whole number. * @private {number} */ this.rulerMinorTickYValue_ = rulerHeight - 5; // TODO(chizeng): Consider the scroll upon load. this.draw(resizeScrollManager.getLeftRightScroll()); }; /** * Handles what happens when the user clicks on the canvas for the ruler. * Specifically, changes the play time. * @param {!goog.events.BrowserEvent} event The associated click event. * @private */ audioCat.ui.tracks.TimeDomainRuler.prototype.handleClick_ = function(event) { var wholisticPixelValue = this.domHelper_.obtainOffsetX(event) + this.resizeScrollManager_.getLeftRightScroll(); var associatedTime = this.timeDomainScaleManager_.getCurrentScale(). convertToSeconds(wholisticPixelValue); var playManager = this.playManager_; if (playManager.getPlayState()) { playManager.pause(); } this.timeManager_.setStableTime(associatedTime); }; /** * Handles what happens when the zoom changes. * @param {!audioCat.ui.visualization.ZoomChangedEvent} event The associated * event. * @private */ audioCat.ui.tracks.TimeDomainRuler.prototype.handleZoomChange_ = function(event) { this.redrawTakeScrollIntoAccount_(); }; /** * Handles what happens when we swap whether to display with time units or bars. * @private */ audioCat.ui.tracks.TimeDomainRuler.prototype.handleScoreTimeSwapped_ = function() { this.redrawTakeScrollIntoAccount_(); }; /** * Handles what happens when the tempo changes. Redraws the canvas if we are * displaying audio using bars instead of time units. * @private */ audioCat.ui.tracks.TimeDomainRuler.prototype.handleTempoChanged_ = function() { if (this.timeDomainScaleManager_.getDisplayAudioUsingBars()) { this.redrawTakeScrollIntoAccount_(); } }; /** * Redraws the ruler, taking into account the scroll. * @private */ audioCat.ui.tracks.TimeDomainRuler.prototype.redrawTakeScrollIntoAccount_ = function() { this.draw(this.resizeScrollManager_.getLeftRightScroll()); }; /** * Draws the ruler once. * @param {number} xScroll The number of pixels from the left the user has * scrolled. */ audioCat.ui.tracks.TimeDomainRuler.prototype.draw = function(xScroll) { var canvasWidth = this.domHelper_.getViewportSize().width; var context2d = this.context2d_; context2d.canvas.width = canvasWidth; context2d.clearRect(0, 0, canvasWidth, this.rulerHeight_); if (this.timeDomainScaleManager_.getDisplayAudioUsingBars()) { this.drawUsingBars_(xScroll); } else { this.drawUsingTimeUnits_(xScroll); } }; /** * Draws the ruler once assuming that we are displaying audio using bars. * @param {number} xScroll The number of pixels from the left the user has * scrolled. * @private */ audioCat.ui.tracks.TimeDomainRuler.prototype.drawUsingBars_ = function(xScroll) { var timeDomainScaleManager = this.timeDomainScaleManager_; var scale = timeDomainScaleManager.getCurrentScale(); var signatureTempoManager = timeDomainScaleManager.getSignatureTempoManager(); var context2d = this.context2d_; // Figure out how many pixels per beat. Save as a float. var pixelsPerBeat = scale.convertToPixels( 60 / signatureTempoManager.getTempo()); var beatIndex = xScroll / pixelsPerBeat; if (xScroll % pixelsPerBeat != 0) { beatIndex = Math.ceil(beatIndex); } // Find out the location of the first tick. var tickPosition = beatIndex * pixelsPerBeat - xScroll; // Draw the tick for the beat. Label it. context2d.beginPath(); context2d.textAlign = 'center'; var canvasWidth = context2d.canvas.width; var beatsPerMeasure = signatureTempoManager.getBeatsInABar(); // Make sure that major ticks never get closer than this many pixels. var minDistanceBetweenMajorTicks = 40; var skipCycle = beatsPerMeasure * Math.ceil( minDistanceBetweenMajorTicks / (pixelsPerBeat * beatsPerMeasure)); while (tickPosition < canvasWidth) { if (beatIndex % skipCycle) { // We have a minor tick. this.drawMinorTick_(context2d, Math.round(tickPosition)); } else { // Draw a major tick this.drawMajorTick_( context2d, Math.round(tickPosition), String(beatIndex)); } ++beatIndex; tickPosition += pixelsPerBeat; } context2d.closePath(); context2d.strokeStyle = '#000'; context2d.lineWidth = 1; context2d.stroke(); }; /** * Draws the ruler once assuming that we are displaying audio using time units. * @param {number} xScroll The number of pixels from the left the user has * scrolled. * @private */ audioCat.ui.tracks.TimeDomainRuler.prototype.drawUsingTimeUnits_ = function(xScroll) { var domHelper = this.domHelper_; var context2d = this.context2d_; var scale = this.timeDomainScaleManager_.getCurrentScale(); // The viewport size is an over-estimate of how long the ruler must be. var viewportSize = domHelper.getViewportSize(); var canvasWidth = viewportSize.width; context2d.canvas.width = canvasWidth; var rulerHeight = this.rulerHeight_; context2d.clearRect(0, 0, canvasWidth, rulerHeight); context2d.beginPath(); var majorTickPixelDistance = scale.getMajorTickWidth(); var majorTickTimeDelta = scale.getSecondsFromTimeUnits( scale.getMajorTickTime()); // Round up to next major tick equivalent. var nextMajorTickPixel = Math.ceil(xScroll / majorTickPixelDistance); // Find the time equivalent of that major tick. var firstMajorTickTime = nextMajorTickPixel * majorTickTimeDelta; // Go backwards and fill in minor ticks. var minorTicksPerMajorTick = scale.getMinorTicksPerMajorTick(); var minorTickDistance = majorTickPixelDistance / (minorTicksPerMajorTick + 1); var majorTickXPosition = nextMajorTickPixel * majorTickPixelDistance - xScroll; var mark = majorTickXPosition - minorTickDistance; if (minorTicksPerMajorTick > 0) { while (mark >= 0) { this.drawMinorTick_(context2d, this.computeWholePixelPosition_(mark)); mark -= minorTickDistance; } } // Configure the time format. var timeFormatter = this.timeFormatter_; var majorTickYValue = this.rulerMajorTickYValue_; var textHeight = majorTickYValue - 3; var timeUnit = scale.getTimeUnit(); context2d.textAlign = 'center'; while (majorTickXPosition < canvasWidth) { this.drawMajorTick_(context2d, majorTickXPosition, timeFormatter.formatTimeGivenScale(firstMajorTickTime, scale)); mark = majorTickXPosition; for (var i = 0; i < minorTicksPerMajorTick; ++i) { mark += minorTickDistance; this.drawMinorTick_(context2d, this.computeWholePixelPosition_(mark)); } majorTickXPosition += majorTickPixelDistance; firstMajorTickTime += majorTickTimeDelta; } context2d.closePath(); context2d.stroke(); }; /** * Draws a major tick. Assumes the path has begun. * @param {!CanvasRenderingContext2D} context2d The 2D context used to draw the * ruler. * @param {number} xPosition The x position in pixels at which to draw the tick. * @param {string=} opt_label If provided, labels the tick. * @private */ audioCat.ui.tracks.TimeDomainRuler.prototype.drawMajorTick_ = function(context2d, xPosition, opt_label) { var rulerMajorTickYValue = this.rulerMajorTickYValue_; this.drawVerticalLine_( context2d, xPosition, rulerMajorTickYValue, this.rulerHeight_); if (opt_label) { // TODO(chizeng): Cache the subtraction. context2d.fillText(opt_label, xPosition, this.majorTickTopPosition_); } }; /** * Draws a minor tick. Assumes the path has begun. * @param {!CanvasRenderingContext2D} context2d The 2D context used to draw the * ruler. * @param {number} xPosition The x position in pixels at which to draw the minor * tick. * @private */ audioCat.ui.tracks.TimeDomainRuler.prototype.drawMinorTick_ = function(context2d, xPosition) { this.drawVerticalLine_( context2d, xPosition, this.rulerMinorTickYValue_, this.rulerHeight_); }; /** * Draws a vertical line. Assumes the path has begun. * @param {!CanvasRenderingContext2D} context2d The 2D context used to draw the * ruler. * @param {number} xPosition The x position in pixels at which to draw the line. * @param {number} initialYPosition The Y position of the top of the line. * @param {number} height The height of the vertical line. * @private */ audioCat.ui.tracks.TimeDomainRuler.prototype.drawVerticalLine_ = function(context2d, xPosition, initialYPosition, height) { xPosition += 0.5; context2d.moveTo(xPosition, initialYPosition); context2d.lineTo(xPosition, height); }; /** * Computes a whole pixel position given a decimal point pixel position. * @param {number} decimalPixelPosition The unrounded pixel position. * @return {number} A whole number that represents the pixel position. * @private */ audioCat.ui.tracks.TimeDomainRuler.prototype.computeWholePixelPosition_ = function(decimalPixelPosition) { return Math.floor(decimalPixelPosition); }; /** * @return {!Element} The canvas element rendering the ruler. */ audioCat.ui.tracks.TimeDomainRuler.prototype.getDom = function() { return /** @type {!HTMLCanvasElement} */ (this.context2d_.canvas); };
let R = parseFloat(process.argv[2]); let RATE_1 = parseFloat(process.argv[3]); let RATE_2 = (RATE_1 * (1 + R)) / (1 - R); console.log(RATE_2);
// Create a Ninja class // add an attribute: name // add an attribute: health // add a attribute: speed - give a default value of 3 // add a attribute: strength - give a default value of 3 // add a method: sayName() - This should log that Ninja's name to the console // add a method: showStats() - This should show the Ninja's name, strength, speed, and health. // add a method: drinkSake() - This should add +10 Health to the Ninja // class Ninja { constructor(name, health, speed=3, strength=3) { this.name = name; this.health = health; this.speed = speed; this.strength = strength; } sayName() { console.log(this.name) } showStats() { console.log(`This is the name ${this.name}, This is the strength ${this.strength}, This is the speed ${this.speed}, This is the health ${this.health}`) } drinkSake() { this.health += 10; return "What one programmer can do in one month, two programmers can do in two months." } } class Sensei extends Ninja { constructor(name, wisdom=10) { super(name, 200, 10); this.wisdom = wisdom } speakWisdom() { const speakWisdom = super.drinkSake(); console.log(speakWisdom); } showStats() { console.log(`This is the name ${this.name}, This is the strength ${this.strength}, This is the speed ${this.speed}, This is the health ${this.health}, This is the wisdom ${this.wisdom}`); } } const ninja1 = new Ninja("Hyabusa", 15); ninja1.sayName(); ninja1.showStats(); console.log(ninja1.drinkSake()); ninja1.showStats(); const superSensei = new Sensei("Master Splinter", 15); superSensei.speakWisdom(); // -> "What one programmer can do in one month, two programmers can do in two months." superSensei.showStats(); // Extend the Ninja class and create the Sensei class. A Sensei should have 200 Health, 10 speed, and 10 strength by default. In addition, a Sensei should have a new attribute called wisdom, and the default should be 10. Finally, add the speakWisdom() method. speakWisdom() should call the drinkSake() method from the Ninja class, before console.logging a wise message. // example output // const superSensei = new Sensei("Master Splinter"); // superSensei.speakWisdom(); // -> "What one programmer can do in one month, two programmers can do in two months." // superSensei.showStats(); // -> "Name: Master Splinter, Health: 210, Speed: 10, Strength: 10" // create a class Sensei that inherits from the Ninja class // add an attribute: wisdom - default to 10 // create a method: speakWisdom() // create a method: drinkSake()
/** * Created by Paweł on 18.04.2017. */ var connArray = []; var resetAllLabels; jsPlumb.ready(function() { var p01 = jsPlumb.connect({ source:'p0', target:'p1', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label: "", id:"label01"}] ] }); var p02 = jsPlumb.connect({ source:'p0', target:'p2', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label02"}] ] }); var p03 = jsPlumb.connect({ source:'p0', target:'p3', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label03"}] ] }); var p13 = jsPlumb.connect({ source:'p1', target:'p3', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label13"}] ] }); var p16 = jsPlumb.connect({ source:'p1', target:'p6', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label16"}] ] }); var p17 = jsPlumb.connect({ source:'p1', target:'p7', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label17"}] ] }); var p24 = jsPlumb.connect({ source:'p2', target:'p4', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label24"}] ] }); var p25 = jsPlumb.connect({ source:'p2', target:'p5', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label25"}] ] }); var p32 = jsPlumb.connect({ source:'p3', target:'p2', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label32"}] ] }); var p37 = jsPlumb.connect({ source:'p3', target:'p7', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label37"}] ] }); var p38 = jsPlumb.connect({ source:'p3', target:'p8', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label38"}] ] }); var p46 = jsPlumb.connect({ source:'p4', target:'p6', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label46"}] ] }); var p48 = jsPlumb.connect({ source:'p4', target:'p8', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label48"}] ] }); var p49 = jsPlumb.connect({ source:'p4', target:'p9', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label49"}] ] }); var p59 = jsPlumb.connect({ source:'p5', target:'p9', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label59"}] ] }); var p78 = jsPlumb.connect({ source:'p7', target:'p8', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label78"}] ] }); var p89 = jsPlumb.connect({ source:'p8', target:'p9', connector:"Straight", paintStyle: { strokeStyle: "#5b9ada", lineWidth: 3 }, overlays:[ [ "Label", {label:"", id:"label89"}] ] }); //17 connArray.push(p01); connArray.push(p02); connArray.push(p03); connArray.push(p13); connArray.push(p16); connArray.push(p17); connArray.push(p24); connArray.push(p25); connArray.push(p32); connArray.push(p37); connArray.push(p38); connArray.push(p46); connArray.push(p48); connArray.push(p49); connArray.push(p59); connArray.push(p78); connArray.push(p89); console.log(connArray); console.log(posA.B.dist); resetAllLabels = function () { console.log(posA.B.factor); p01.setLabel('' + posA.B.dist + '<span>' + posA.B.factor + '</span>'); p02.setLabel('' + posA.C.dist + '<span>' + posA.C.factor + '</span>'); p03.setLabel('' + posA.D.dist + '<span>' + posA.D.factor + '</span>'); p13.setLabel('' + posB.D.dist + '<span>' + posB.D.factor + '</span>'); p16.setLabel('' + posB.G.dist + '<span>' + posB.G.factor + '</span>'); p17.setLabel('' + posB.H.dist + '<span>' + posB.H.factor + '</span>'); p24.setLabel('' + posC.E.dist + '<span>' + posC.E.factor + '</span>'); p25.setLabel('' + posC.F.dist + '<span>' + posC.F.factor + '</span>'); p32.setLabel('' + posD.C.dist + '<span>' + posD.C.factor + '</span>'); p37.setLabel('' + posD.H.dist + '<span>' + posD.H.factor + '</span>'); p38.setLabel('' + posD.I.dist + '<span>' + posD.I.factor + '</span>'); p46.setLabel('' + posE.G.dist + '<span>' + posE.G.factor + '</span>'); p48.setLabel('' + posE.I.dist + '<span>' + posE.I.factor + '</span>'); p49.setLabel('' + posE.J.dist + '<span>' + posE.J.factor + '</span>'); p59.setLabel('' + posF.J.dist + '<span>' + posF.J.factor + '</span>'); p78.setLabel('' + posH.I.dist + '<span>' + posH.I.factor + '</span>'); p89.setLabel('' + posI.J.dist + '<span>' + posI.J.factor + '</span>'); }; resetAllLabels(); }); $(window).resize(function() { jsPlumb.repaintEverything(); });
import React from 'react' import './Infobox.css'; import CountUp from 'react-countup'; function Infobox({title, number, total, active, ...props}) { if(number === undefined) { return 'Loading...'; } return ( <div onClick={props.onClick} className={`infobox ${active && "infobox--selected"}`}> <h4>{title}</h4> <h1> <CountUp start={0} end={number} duration={2.5} separator="," /> </h1> <h5> <CountUp start={0} end={total} duration={2.5} separator="," /> <span style={{color: 'lightgray'}}> total</span> </h5> </div> ) } export default Infobox
$(document).ready(function () { loadBoats(); }); function loadBoats() { $.getJSON("/boats.json", function (data) { let boat_data = ""; $.each(data, function (key, value) { let id = value.id boat_data += '<tr>'; boat_data += '<td>' + value.name + '</td>'; boat_data += '<td>' + value.boat_type + '</td>'; boat_data += '<td>' + value.capacity + '</td>'; boat_data += '<td>' + value.trips.length + '</td>' boat_data += '</tr>'; }) $('#boat-table').append(boat_data) }) } // function addBoat() { // $('#new-boat').on('submit', function () { // event.preventDefault(); // $("#boat-table").clear(); // let values = $(this).serialize() // let posting = $.post('/boats', values) // posting.done(function (data) { // $.each(data, function (key, value) { // let id = value.id // boat_data += '<tr>'; // boat_data += '<td>' + value.name + '</td>'; // boat_data += '<td>' + value.boat_type + '</td>'; // boat_data += '<td>' + value.capacity + '</td>'; // boat_data += '<td>' + value.trips.length + '</td>' // boat_data += '</tr>'; // }) // loadBoats(); // $('#boat-table').append(boat_data) // }) // }) // }
const dr = __dirname; console.log(`'${dr}'`) const logCount = 10; const fs = require('fs'); createLogFiles = () =>{ fs.readdir(dr, (err, files) => { for(let i = 0; i<logCount; i++){ let logName = `log${i}.txt`; console.log(`${logName}`); if(!files.includes(logName)){ fs.open(`${dr}\\${logName}`, 'w', (err, file) => {}); } } }); } deleteLogFiles = () =>{ fs.readdir(dr, (err, files) => { files.forEach(file => { if(file.includes('log') > 0){ fs.unlink(`${dr}\\${file}`,(err) => { if (err) throw err; console.log(`deleted file ...${file}`); }); } }); }); } createLogFiles(); deleteLogFiles();
import React from 'react'; import { Link } from 'react-router-dom'; const MobileNavLinks = () => { return ( <div className='mobile-nav-links'> <div className='close-mobile-nav-links'> <Link to='/'>X</Link> </div> <ul> <li> <Link to='/'>Home</Link> </li> <li> <Link to='/'>Quiz</Link> </li> <li> <Link to='/'>About</Link> </li> <li> <Link to='/'>Login</Link> </li> </ul> </div> ); }; export default MobileNavLinks;
module.exports = (fn) => { return (req, res, next) => {//this way, catchAsync will return a function that takes req,res,next as params and executes the controller function with these params. If there is any error it is caught and passed to the global error handler function using catch(async) console.log("inside catchAsync"); fn(req,res,next).catch(err=>next(err)); }; };
X.define('modules.request.sourcingRequest', ["model.productsModel", "modules.common.global", "modules.user.login", "modules.user.regist", "adapter.searchValidate","modules.common.multipleFiles","modules.common.checkIsIE", "modules.common.suspensionBox","modules.common.cookies","model.userModel","modules.common.commonRequest"], function (productsModel, global, login, regist, searchValidate,multipleFiles,checkIsIE,suspensionBox,cookies,userModel,commonRequest) { var view = X.view.newOne({ el: $('.js-content'), url: X.config.request.tpl.sourcingRequest, res: X.config.request.res.sourcingRequest }); var ctrl = X.controller.newOne({ view: view }); ctrl.deleteSpecialChar = function (value) { var temp = ''; for (var i = 0, len = value.length; i < len; i++) { var char = value.charAt(i); if (/[A-Za-z0-9\s(\`)(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\_)(\-)(\+)(\=)(\|)(\\)(\{)(\})(\')(\:)(\;)(\')(\")(',)(\[)(\])(\.)(\<)(\>)(\/)(\?)(\~)(\!)(\@)(\#)(\¥)(\%)(\…)(\&)(\*)(\()(\))(\—)(\+)(\|)(\{)(\})(\【)(\】)(\‘)(\;)(\:)(\”)(\“)(\’)(\。)(\,)(\、)(\?)]/.test(char)) { temp += char; } } return temp; }; ctrl.validateValue = function () { ctrl.view.el.find("input").keyup(function () { var value = $(this).val(); var temp = ctrl.deleteSpecialChar(value); if (temp != value) { $(this).val(ctrl.deleteSpecialChar(temp)); } }); ctrl.view.el.find("input").change(function () { var value = $(this).val(); var temp = ctrl.deleteSpecialChar(value); if (temp != value) { $(this).val(ctrl.deleteSpecialChar(temp)); } }); ctrl.view.el.find("textarea").keyup(function () { var value = $(this).val(); var temp = ctrl.deleteSpecialChar(value); if (temp != value) { $(this).val(ctrl.deleteSpecialChar(temp)); } }); ctrl.view.el.find("textarea").change(function () { var value = $(this).val(); var temp = ctrl.deleteSpecialChar(value); if (temp != value) { $(this).val(ctrl.deleteSpecialChar(temp)); } }); }; ctrl.area = function () { var countryCode = localStorage.getItem('countryCode'); var ifLoading = true; var ifDropdown = false; if (countryCode) { $("#phone").intlTelInput({ initialCountry: countryCode, autoPlaceholder: 'off', //autoHideDialCode: false, preferredCountries: [], utilsScript: "js/lib/utils.js" }); $(".selected-flag .iti-flag").removeClass('loading').css({'box-shadow': 'none'}); var countryData = $("#phone").intlTelInput("getSelectedCountryData"); $('.js-dialCode').text('+' + countryData.dialCode); countryName = countryData.name; ifLoading = false; ifDropdown =true; } else{ $("#phone").intlTelInput({ initialCountry: 'auto', autoPlaceholder: 'off', //autoHideDialCode: false, preferredCountries: [], geoIpLookup: function (callback) { $.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) { var countryCode = (resp && resp.country) ? resp.country : ""; callback(countryCode); }); }, utilsScript: "js/lib/utils.js" }); ifLoading=true; ifDropdown = true } $(".js-other").css({'background': 'url("../images/other.png")', 'box-shadow': 'none'}); $(".js-other").parent().parent().find('.dial-code').text(''); $(".iti-flag-add").removeClass('iti-flag'); if (ctrl.GetQueryString('phoneNum')) {ifLoading = false} if (ifLoading) {$(".selected-flag .iti-flag").addClass('loading').css({'box-shadow': 'none'});} if (ifDropdown) {$(".selected-flag").removeClass('w100p');} $("#phone").on("countrychange", function(e, countryData) { if (countryData.dialCode) { $('.js-dialCode').text('+' + countryData.dialCode); }else{ $('.js-dialCode').text(countryData.dialCode); } if (countryData.dialCode == 259) { var flag = $('.selected-flag .iti-flag-add'); flag.removeClass('iti-flag'); flag.css({'position':'absolute', 'top': '15px'}) } else { var flag2 = $('.selected-flag .iti-flag'); flag2.css({'position':'absolute', 'top': '0px'}) } if (countryData.name == 'Others') { var flag = $('.iti-flag.js-other'); flag.addClass('other'); }else{ var flag2 = $('.selected-flag .iti-flag'); flag2.removeClass('other') } }); }; ctrl.load = function(){ view.el.find(".js-home").attr("href",X.config.common.link.home); } ctrl.load(); return ctrl });
/** * Created by Alan on 2016/9/7. */ /*----------------------------------------调仓图表弹窗---------------------------------------------*/ var selectOptionsUrl = "/api/selectOptions"; var xData, yData; var chart; var gammaList = {}; var VAR, gamma; var slider; var selected = false; var idList = []; $('.close_alert').click(function () { $(this).parent().hide(300); }); $('#close').click(function (e) { $('#detail-table').fadeOut(300); $('#main-content').fadeTo(300, 1); slider.destroy(); }); $("#adjustBtn").click(function () { idList = []; $("input[name='option_id_picker']").each(function () { if ($(this).is(':checked')) { selected = true; idList.push($(this).parent().prev('input').val()); } }); if (selected) { gammaList = {}; VAR = gamma = 0; $('#chart-div').show(); $('#table-div').hide(); $('#var').text(""); $('#main-content').fadeTo(300, 0.3); $('#detail-table').fadeIn(300); var dom = document.getElementById("chart"); chart = echarts.init(dom); chart.showLoading(); $.ajax({ url: window.host + selectOptionsUrl, data: { option_list: idList }, traditional: true, timeout: 30000, success: function (res) { var data = response(res); if (data != null) { xData = data.x_data; yData = data.y_data; for (var i = 0; i < xData.length && i < yData.length; i++) { gammaList[xData[i]] = yData[i]; } /* ION SLIDER */ $("#range_1").ionRangeSlider({ min: 1, max: 1501, from: 1, type: 'single', step: 50, prefix: "Gamma ", prettify: false, hasGrid: true, onStart: function () { gamma = 1; var currentVar = gammaList[gamma]; $('#var').text(currentVar); VAR = currentVar; }, onChange: function (res) { gamma = res.from; var currentVar = gammaList[gamma]; $('#var').text(currentVar); VAR = currentVar; } }); slider = $("#range_1").data("ionRangeSlider"); loadFunction(chart, xData, yData); } } }); } else { $('#alert_warning').show(300); setTimeout(function () { $('.alert').hide(300); }, 3000); } }); /** * 加载函数 * @param chart * @param xData * @param yData */ function loadFunction(chart, xData, yData) { var option = { title: { text: 'VAR Selector' }, tooltip: { trigger: 'axis' }, legend: { data: ['Gamma'] }, grid: { left: '5%', right: '5%', bottom: '3%', nameGap: 30, containLabel: true }, xAxis: [ { name: 'Gamma', nameLocation: 'middle', type: 'category', boundaryGap: false, data: xData } ], yAxis: [ { name: 'Var', type: 'value' } ], series: [ { name: 'VAR', type: 'line', stack: '总量', areaStyle: {normal: {}}, data: yData } ] }; chart.setOption(option, true); chart.hideLoading(); } function resizeChart() { chart.resize(); } var predictResUrl = "/api/predictResult"; var adjustBinUrl = "/api/adjustBin"; /** * 进入预览界面 */ function preview() { $.ajax({ url: window.host + predictResUrl, data: { lower_gamma: gamma, option_list: idList }, timeout: 5000, traditional: true, success: function (res) { var data = response(res); if (data != null) { $('#name').text(data.futures_name); $('#number').text(data.number); $('#origin-cost').text(data.origin_cost); $('#origin-number').text(data.origin_number); $('#current-number').text(data.current_number); $('#origin-delta').text(data.origin_delta.toFixed(4)); $('#current-delta').text(data.current_delta.toFixed(4)); $('#current-var').text(VAR.toFixed(4)); if (data.safe == "warning") { $('#predict-safety').removeClass('label-success').addClass('label-warning').text("warning"); } $('#chart-div').hide(300); $('#table-div').show(300); } } }); } /*----------------------------------------数据详情弹窗---------------------------------------------*/ function reAdjust() { $('#chart-div').show(300); $('#table-div').hide(300); } function confirmAdjust() { $.ajax({ url: window.host + adjustBinUrl, data: { futures_id: futuresID, lower_gamma: gamma, option_list: idList }, timeout: 5000, traditional: true, success: function (res) { var data = response(res); $('#detail-table').hide(); $('#main-content').fadeTo(300, 1); if (data != null) { $('#alert_success').show(300); setTimeout(function () { location.reload(); }, 1500) } else { $('#alert_fail').show(300); } } }) } /*-----------------------------------------数据加载---------------------------------------------------*/ var futuresID = getParam(location.href, "futures_id"); var getHistoryUrl = "/api/capital"; loadResource(); function loadResource() { $.ajax({ url: window.host + getHistoryUrl, data: { futures_id: futuresID }, timeout: 5000, success: function (res) { var data = response(res); $('.loader--style3').hide(); if (data != null) { var cost = data.cost; var delta = data.delta; var safe = data.safe; $('#cost').text(cost.toFixed(2)); $('#delta').text(delta.toFixed(4)); switch (safe) { case "warning": $('#safe-block').removeClass('bg-green').addClass('bg-red'); $('#safe-div').removeClass('text-green').addClass('text-red'); $('#safe-condition').text(safe); break; } var historyList = data.data; for (var i = 0; i < historyList.length; i++) { var due_date = historyList[i].due_date; var single_delta = historyList[i].delta; var sell_price = historyList[i].sell_price; var future_price = historyList[i].futures_price; var single_cost = historyList[i].cost; var type = historyList[i].type; var optionID = historyList[i].option_id; loadHistory(due_date, single_delta, sell_price, future_price, single_cost, type, optionID); } } } }); } var history_template = '<tr> ' + '<td>due_date</td> ' + '<td>single_delta</td> ' + '<td>sell_price</td> ' + '<td>future_price</td> ' + '<td>single_cost</td> ' + '<td>sell_type</td>' + '<input type="hidden" value="option-id">' + '<td><input type="checkbox" name="option_id_picker"></td>' + '</tr>'; /** * 加载历史信息 * @param due_date * @param single_delta * @param sell_price * @param future_price * @param single_cost * @param type * @param optionID */ function loadHistory(due_date, single_delta, sell_price, future_price, single_cost, type, optionID) { var tags = ['due_date', 'single_delta', 'sell_price', 'future_price', 'single_cost', 'sell_type', 'option-id']; var data = [due_date, single_delta.toFixed(4), sell_price.toFixed(2), future_price.toFixed(2), single_cost.toFixed(2), type, optionID]; var template = replaceTemplate(history_template, tags, data); $('#data-table').append(template); }
exports.seed = function(knex) { return knex("organizations").insert([ { name: "Alloy Technology Solutions", phone: "8008008000" }, { name: "Test Organization 1", phone: "5005005000" } ]); };
import Vue from 'vue' import { generateAbsoluteURL } from '../../helpers/generate-absolute-url' import { generateCategoryString } from './helpers/productHelpers' const YEAR_IN_MILLISECONDS = 365 * 24 * 60 * 60 * 1000 export default function generateProductSchema (product) { const isOffer = product.offer_type || (product.offer_data && product.offer_data.expires) // first case is when we are on main page, second - SDO page const productAbsoluteURL = generateAbsoluteURL({ route: { name: 'product-ean-name', params: { ean: product.ean, name: product.url_key || product.urlName } } }, product.host, product.routes) const result = { '@context': 'http://schema.org/', '@type': 'Product', '@id': productAbsoluteURL + '#product', url: productAbsoluteURL, gtin13: product.ean, name: product.title, image: Vue.prototype.$vidaXLimageDomain + product.ean + '_s.jpg', offers: isOffer ? generateLimitedOffer(product) : generateOffer(product, productAbsoluteURL) } if (!isOffer && product.ean) { result.description = product.description result.review = generateReviews(product.reviews) result.category = generateCategoryString(product.category) result.sku = product.sku result.brand = product.brand // need to skip aggregateRating if a product doesn't have reviews yet // otherwise, Google will throw an error if (product.reviews.length) { result.aggregateRating = { ratingValue: product.product_rating, reviewCount: product.reviews.length } } } return result } function generateLimitedOffer (product) { return { '@type': 'Offer', priceCurrency: product.currency, priceSpecification: generatePriceSpecification(product) } } function generateOffer (product, url) { return { url, name: 'Purchase', availability: product.in_stock ? 'http://schema.org/InStock' : 'http://schema.org/OutOfStock', deliveryLeadTime: product.delivery_days, seller: product.seller && product.seller.title, priceCurrency: product.currency, priceSpecification: generatePriceSpecification(product), priceValidUntil: new Date(Date.now() + YEAR_IN_MILLISECONDS).toISOString() } } /** * check product price and check whether to add discount or not * @param price * @param vat * @param offer_type * @param discount_price * @param expires * @param offer_price * @returns {{'@type': string, price: *, valueAddedTaxIncluded: boolean}} */ export function generatePriceSpecification ({ price, special_price, offer_price, offer_type, expires, offer_data, vat, currency }) { const isWeeklyOffer = (offer_data && offer_data.is_weekly) || offer_type === 'weekly' // SDO page OR main page const expirationTimestamp = (offer_data && offer_data.expires) || expires // SDO page OR main page const currentPrice = +offer_price || +special_price || +price const result = { '@type': 'CompoundPriceSpecification', price: currentPrice && currentPrice.toFixed(2), valueAddedTaxIncluded: true, priceCurrency: currency || '' } if (expires || offer_price || (offer_data && offer_data.expires)) { result.validThrough = new Date(expirationTimestamp) result.validFrom = isWeeklyOffer ? firstDayOfWeek(expirationTimestamp) : startOfTheDay(expirationTimestamp) } if (!vat) return result const targetPrice = offer_price || price || special_price const priceExcludingVAT = targetPrice / (1 + vat) const valueOfVat = targetPrice - priceExcludingVAT result.priceComponent = [ { name: 'Price excluding VAT', price: priceExcludingVAT && priceExcludingVAT.toFixed(2), valueAddedTaxIncluded: false }, { name: 'VAT', price: valueOfVat && valueOfVat.toFixed(2), valueAddedTaxIncluded: true } ] if (!offer_type && special_price < price) { result.priceComponent.push({ name: 'Discount', price: (special_price - price).toFixed(2), valueAddedTaxIncluded: false }) } return result } function startOfTheDay (date) { const dateObject = new Date(date) dateObject.setUTCHours(0, 0, 0, 0) return dateObject } function firstDayOfWeek (date, firstDayOfWeekIndex) { const dateObject = new Date(date) const dayOfWeek = dateObject.getDay() const firstDayOfWeek = new Date(dateObject) const diff = dayOfWeek >= firstDayOfWeekIndex ? dayOfWeek - firstDayOfWeekIndex : 6 - dayOfWeek firstDayOfWeek.setDate(dateObject.getDate() - diff) firstDayOfWeek.setUTCHours(0, 0, 0, 0) return firstDayOfWeek } /** * take reviews and generate array with specific fields for Google 360 * @param reviews * @returns {*} */ function generateReviews (reviews) { return reviews.map((review) => { return { author: review.author.nickname, reviewBody: review.text, reviewRating: generateReviewRatings(review.ratings) } }) } /** * given array of ratings per each product option generate Google 360 ratings array * @param ratings * @returns {*} */ function generateReviewRatings (ratings) { return ratings.map((rating) => { return { reviewAspect: rating.label, ratingValue: rating.score } }) }
import React, { PropTypes, PureComponent } from 'react'; import { App, Navbar } from 'containers'; export class MainLayout extends PureComponent { static propTypes = { children: PropTypes.oneOfType([PropTypes.array, PropTypes.object]) }; render () { const { children } = this.props; return ( <App> <Navbar /> {children} </App> ); } } export default MainLayout;
$(function(){ let second = $(window).width(); if (second < 1600) { $('.acceuil').css({left:'0.5%'}); }; $(window).resize(function(){ let first = $(window).width(); if (first < 1600) { $('.acceuil').css({left:'-20%'}); } if(first >1600) { $('.acceuil').css({left: '0%'}); } }); //move triangle $('#apropos').on('click', function(){ $('.triangle').animate( {left:'-33%'},1500); }); $('#acceuil').on('click', function(){ $('.triangle').animate( {left:'0%'},1500); }); $('#contact').on('click', function(){ $('.triangle').animate( {left:'33%'},1500); }); //border menu and content start $('#apropos').on('click', function(){ $('#apropos').css({ borderWidth:'2px', borderStyle:'solid' }), $('#contact').css({ borderWidth:'0px', borderStyle:'none' }), $('#acceuil').css({ borderWidth:'0px', borderStyle:'none' }), $('.contact').css({ visibility: 'hidden' }), $('.apropos').css({ visibility: 'visible' }), $('.acceuil').css({ visibility: 'hidden' }), $('.tablemoteur').css({ visibility: 'visible' }), $('.tabletrans').css({ visibility: 'hidden' }) $('.tableperf').css({ visibility: 'hidden' }); }); $('#acceuil').on('click', function(){ $('#acceuil').css({ borderWidth:'2px', borderStyle:'solid' }), $('#contact').css({ borderWidth:'0px', borderStyle:'none' }), $('#apropos').css({ borderWidth:'0px', borderStyle:'none' }), $('.contact').css({ visibility: 'hidden' }), $('.apropos').css({ visibility: 'hidden' }), $('.acceuil').css({ visibility: 'visible' }), $('.tablemoteur').css({ visibility: 'hidden' }), $('.tabletrans').css({ visibility: 'hidden' }) $('.tableperf').css({ visibility: 'hidden' }); }); $('#contact').on('click', function(){ $('#contact').css({ borderWidth:'2px', borderStyle:'solid' }), $('#acceuil').css({ borderWidth:'0px', borderStyle:'none' }), $('#apropos').css({ borderWidth:'0px', borderStyle:'none' }), $('.contact').css({ visibility: 'visible' }), $('.apropos').css({ visibility: 'hidden' }), $('.acceuil').css({ visibility: 'hidden' }), $('.tablemoteur').css({ visibility: 'hidden' }), $('.tabletrans').css({ visibility: 'hidden' }) $('.tableperf').css({ visibility: 'hidden' }); }); //border menu and content end //sous menu ||apropos|| start $('#sousmoteur').on('click', function(){ $('.tablemoteur').css({ visibility: 'visible' }) $('.tableperf').css({ visibility: 'hidden' }) $('.tabletrans').css({ visibility: 'hidden' }) $('#sousperf').css({ backgroundColor: 'white', color: '#FC7A10' }) $('#sousmoteur').css({ backgroundColor: '#FC7A10', color: 'white' }) $('#soustrans').css({ backgroundColor: 'white', color: '#FC7A10' }) $('.hondamoteur').attr('src','img/honda.jpg'); }); $('#sousperf').on('click', function(){ $('.tableperf').css({ visibility: 'visible' }) $('.tablemoteur').css({ visibility: 'hidden' }) $('.tabletrans').css({ visibility: 'hidden' }) $('#sousperf').css({ backgroundColor: '#FC7A10', color: 'white' }) $('#sousmoteur').css({ backgroundColor: 'white', color:'#FC7A10' }) $('#soustrans').css({ backgroundColor: 'white', color:'#FC7A10' }) $('.hondamoteur').attr('src','img/honda2.jpg'); }); $('#soustrans').on('click', function(){ $('.tabletrans').css({ visibility: 'visible' }) $('.tableperf').css({ visibility: 'hidden' }) $('.tablemoteur').css({ visibility: 'hidden' }) $('#soustrans').css({ backgroundColor: '#FC7A10', color:'white' }) $('#sousmoteur').css({ backgroundColor: 'white', color: '#FC7A10' }) $('#sousperf').css({ backgroundColor: 'white', color: '#FC7A10' }) $('.hondamoteur').attr('src','img/honda3.jpg'); }); //sous menu ||apropos|| end });
var breads = [ "aish merahrah", "ajdov kruchabeld", "anadama bread", "anpan", "appam", "arepa", "babka", "bagel", "baguette", "balep korkun", "bammy", "banana bread", "bannock", "bara brith", "barbari bread", "barmbrack", "bastone", "bazlama", "beer bread", "bhakri", "bhatoora", "bing", "biscuit", "black bread", "bofrot", "bolani", "borodinsky", "boule", "roll", "breadstick", "brioche", "broa", "brown bread", "bublik", "bun", "canadian white", "\u010Desnica", "challah", "chapati", "chickpea bread", "christmas wafer", "ciabatta", "colomba pasquale", "coppia ferrarese", "cornbread", "cottage loaf", "cr\u00EApe", "crisp bread", "crumpet", "cuban bread", "curry bread", "damper", "dampfnudel", "doughnut", "dosa", "farl", "filone", "flatbread", "flatbr\u00F8d", "flatkaka", "focaccia", "fougasse", "frybread", "green onion pancake", "gugelhupf", "hallulla", "hardebrood", "hardtack", "himbasha", "hushpuppy", "injera", "johnnycake", "ka'ak", "khanom bueang", "kulcha", "lagana", "lahoh", "laobing", "laufabrau\u00F0", "lavash", "lefse", "luchi", "malooga", "mantou", "markook", "marraqueta", "matzo", "melonpan", "michetta", "monkey bread", "montreal-style bagel", "muffin", "naan", "ngome", "puran poli", "pain de mie", "pan de pascua", "pan dulce", "panbrioche", "pancake", "pandesal", "pandoro", "pane carasau", "pane di altamura", "pane ticinese", "panettone", "panfocaccia", "papadum", "paratha", "parotta", "penia", "piadina", "pita", "pizza", "massa sovada", "potato bread", "potbrood", "pretzel", "proja", "puftaloon", "pumpernickel", "puri", "quick bread", "rice bread", "roti", "rugbr\u00F8d", "rumali roti", "rye bread", "sacramental bread", "salt rising bread", "sangak", "scone", "sgabeo", "shirmal", "soda bread", "sopaipilla", "sourdough bread", "speckendick", "taftan", "tandoor bread", "teacake", "tiger bread", "tortilla", "tsoureki", "tunnbr\u00F6d", "v\u00E1no\u010Dka", "vienna bread", "white bread", "whole wheat bread", "yufka", "zopf", "zwieback" ];
import { delay } from 'dva-react2/saga'; export default { namespace: 'example', state: { count: 1, }, subscriptions: { setup({ dispatch, history }) { // eslint-disable-line dispatch({ type: 'watch' }); }, }, effects: { *fetch({ payload }, { call, put }) { // eslint-disable-line yield put({ type: 'save' }); }, *watch(_, { call, put }) { while (true) { yield call(delay, 1000); yield put({ type: 'plus' }); } }, }, reducers: { save(state, action) { return { ...state, ...action.payload }; }, plus(state) { return { ...state, count: state.count + 1 }; }, }, };
import React from 'react'; import './style.css'; import { Link } from 'react-router-dom'; class DetalhesUsuario extends React.Component { state = { posts: [], pessoa: {}, deuErro: false } componentDidMount() { fetch('https://jsonplaceholder.typicode.com/users/' + this.props.match.params.id) .then(function (response) { if (response.ok) { return response.json(); } throw { status: response.status, mensagem: response.statusText } }) .then((json) => { this.setState({ pessoa: json }); }) .catch((erro) => { this.setState({ deuErro: true }) }); fetch('https://jsonplaceholder.typicode.com/posts?userId=' + this.props.match.params.id) .then(function (response) { if (response.ok) { return response.json(); } throw { status: response.status, mensagem: response.statusText } }) .then((json) => { this.setState({ posts: json }); }) .catch((erro) => { this.setState({ deuErro: true }) }); } mostraPosts(posts) { return ( <div className="bodyy"> <tr> <td> <label>Id do post: {posts.id}</label> </td> </tr> <tr> <td> <label>Titulo: {posts.title}</label> </td> </tr> <tr> <td> <label>Corpo: {posts.body}</label> </td> </tr> </div> ) } render() { const { pessoa } = this.state; return ( <div className = "div2"> <Link to={"/usuarios/"}>Voltar</Link> <table> <thead > <td> <h2> Dados do Usuário: </h2> </td> </thead> <tbody> <tr> <td> <label>Id: {pessoa.id}</label> </td> </tr> <tr> <td> <label>Nome: {pessoa.name}</label> </td> </tr> <tr> <td> <label>Username: {pessoa.username}</label> </td> </tr> <tr> <td> <label>E-mail: {pessoa.email}</label> </td> </tr> <tr> <td> <label>Endereco: {pessoa.address ? pessoa.address.street + ', ' + pessoa.address.suite : ' '}</label> </td> </tr> <tr> <td> <label>Telefone: {pessoa.phone}</label> </td> </tr> <tr> <td> <label>Site: {pessoa.website}</label> </td> </tr> </tbody> </table> <table className = "table3"> <thead> <td> <h2 align="center"> Posts: </h2> </td> </thead> <tbody > {this.state.posts.map(this.mostraPosts)} </tbody> </table> </div> ) } } export default DetalhesUsuario;
window.project = true; // Project Shader Store // Browser Window Services ////////////////////////////////////////////// // Babylon Toolkit - Browser Window Services ////////////////////////////////////////////// /** Firelight Audio Shims */ window.firelightAudio = 0; window.firelightDebug = false; if (window.firelightAudio === 1 || window.firelightAudio === 2) { var fmodjs = "scripts/fmodstudio.js"; if (window.firelightDebug === true) { fmodjs = ("scripts/" + (window.firelightAudio === 1) ? "fmodstudioL.js" : "fmodL.js"); } else { fmodjs = ("scripts/" + (window.firelightAudio === 1) ? "fmodstudio.js" : "fmod.js"); } var script2 = document.createElement('script'); script2.setAttribute("type","text/javascript"); script2.setAttribute("src", fmodjs); if (document.head != null) { document.head.appendChild(script2); } else if (document.body != null) { document.body.appendChild(script2); } } /** Windows Launch Mode */ window.preferredLaunchMode = 0; if (typeof Windows !== "undefined" && typeof Windows.UI !== "undefined" && typeof Windows.UI.ViewManagement !== "undefined" &&typeof Windows.UI.ViewManagement.ApplicationView !== "undefined") { Windows.UI.ViewManagement.ApplicationView.preferredLaunchWindowingMode = (window.preferredLaunchMode === 1) ? Windows.UI.ViewManagement.ApplicationViewWindowingMode.fullScreen : Windows.UI.ViewManagement.ApplicationViewWindowingMode.auto; } /** Xbox Full Screen Shims */ document.querySelector('style').textContent += "@media (max-height: 1080px) { @-ms-viewport { height: 1080px; } }"; /** Xbox Live Plugin Shims */ window.xboxLiveServices = false; window.isXboxLivePluginEnabled = function() { var isXboxLive = (typeof Windows !== "undefined" && typeof Microsoft !== "undefined" && typeof Microsoft.Xbox !== "undefined" && typeof Microsoft.Xbox.Services !== "undefined"); var hasToolkit = (typeof BabylonToolkit !== "undefined" && typeof BabylonToolkit.XboxLive !== "undefined" && typeof BabylonToolkit.XboxLive.Plugin !== "undefined"); return (window.xboxLiveServices === true && isXboxLive === true && hasToolkit === true); } /** Generic Promise Shims */ window.createGenericPromise = function(resolveRejectHandler) { return new Promise(resolveRejectHandler); } window.resolveGenericPromise = function(resolveObject) { return Promise.resolve(resolveObject); } // test7.ts var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /* Babylon Mesh Component Template */ var PROJECT; /* Babylon Mesh Component Template */ (function (PROJECT) { var Man = /** @class */ (function (_super) { __extends(Man, _super); function Man(owner, scene, tick, propertyBag) { if (tick === void 0) { tick = true; } if (propertyBag === void 0) { propertyBag = {}; } var _this = _super.call(this, owner, scene, tick, propertyBag) || this; _this.animator = null; return _this; } Man.prototype.ready = function () { // Scene execute when ready }; Man.prototype.start = function () { // Start component function // this.animator = this.getComponent("BABYLON.AnimationState"); var str = this.getProperty("hello"); console.log(str); this.animator = this.getProperty("ani"); console.log(this.animator); }; Man.prototype.update = function () { // Update render loop function this.mesh.rotation.y += 0.01; if (this.animator != null) { this.animator.setBool("Walk Forward", true); } }; Man.prototype.after = function () { // After render loop function }; Man.prototype.destroy = function () { // Destroy component function }; return Man; }(BABYLON.MeshComponent)); PROJECT.Man = Man; })(PROJECT || (PROJECT = {}));
(function ($) { 'use strict'; $(function () { $('#show').avgrund({ height: 500, holderClass: 'custom', showClose: true, showCloseText: 'x', onBlurContainer: '.container-scroller', template: '<p>برای وارد شدن به حساب توییتر یا فیسبوک ما روی دکمه مورد نظر کلیک کرده و برای بسته شدن این پنجره روی آیکون ضربدر کلیک کنید و یا دکمه Esc روی کیبورد را بزنید .</p>' + '<div>' + '<a href="http://twitter.com/YourAccount target="_blank" class="twitter btn btn-twitter btn-block">Twitter</a>' + '<a href="http://dribbble.com/YourAccount" target="_blank" class="facebook btn btn-facebook btn-block">Face Book</a>' + '</div>' + '<div class="text-center mt-4">' + '<a href="#" target="_blank" class="btn btn-success ml-2">باشه !</a>' + '<a href="#" target="_blank" class="btn btn-light">لغو</a>' + '</div>' }); }) })(jQuery);
import { combineReducers } from 'redux'; import authentication from './authentication'; import cliente from './cliente'; import { routerReducer as routing } from 'react-router-redux'; export default combineReducers({ authentication, cliente, routing });
'use strict'; const dotenv = require('dotenv'); // Travis doesn't see the .env file; it has the token/domain as env variables already const fs = require('fs'); if (fs.existsSync('./.env')) { dotenv.load(); } const ACCT1_AUTH0_ID = process.env.ACCT1_AUTH0_ID; const ACCT2_AUTH0_ID = process.env.ACCT2_AUTH0_ID; const ACCT3_AUTH0_ID = process.env.ACCT3_AUTH0_ID; const ACCT4_AUTH0_ID = process.env.ACCT4_AUTH0_ID; const ACCT5_AUTH0_ID = process.env.ACCT5_AUTH0_ID; const ACCT6_AUTH0_ID = process.env.ACCT6_AUTH0_ID; const ACCT7_AUTH0_ID = process.env.ACCT7_AUTH0_ID; const ACCT8_AUTH0_ID = process.env.ACCT8_AUTH0_ID; const ACCT9_AUTH0_ID = process.env.ACCT9_AUTH0_ID; const DEMO_ACCT1_AUTH0_ID = process.env.DEMO_ACCT1_AUTH0_ID; const ADMIN_AUTH0_ID = ACCT7_AUTH0_ID; const STAFF_AUTH0_ID = ACCT5_AUTH0_ID; const COACH_AUTH0_ID = ACCT1_AUTH0_ID; const VOLUNTEER_AUTH0_ID = ACCT3_AUTH0_ID; module.exports = { ADMIN_AUTH0_ID, STAFF_AUTH0_ID, COACH_AUTH0_ID, VOLUNTEER_AUTH0_ID, ACCT1_AUTH0_ID, ACCT2_AUTH0_ID, ACCT3_AUTH0_ID, ACCT4_AUTH0_ID, ACCT5_AUTH0_ID, ACCT6_AUTH0_ID, ACCT7_AUTH0_ID, ACCT8_AUTH0_ID, ACCT9_AUTH0_ID, DEMO_ACCT1_AUTH0_ID, };
//** Merge Sort **// // It's a combination of two things - merging and sorting! // Exploits the fact that arrays of 0 or 1 elements are always sorted. // Works by decomposing an array into smaller arrays of 0 or 1 elements, then building newly sorted arrays. //** Merging Arrays **// // In order to implement merge sort, it's useful to first implement // a function responsible for merging two sorted arrays. // Given two arrays which are sorted, this helper function should // create a new array which is also sorted, and consists of all of // the elements in the two input arrays. // This function should run in O(n+m) time and O(n+m) space // and should not modify the parameters passed to it. //** Merge Pseudocode **// // Create an empty array, take a look at the smallest values in each input array. // While there are still values we haven't looked at.. // If the value in the first array is smaller than the value in // the second array, push the value in the first array into our // results and move on to the next value in the first array. // If the value in the first array is larger than the value in the // second array, push the value in the second array into our // results and move on to the next in the second array. // Once we exhaust one array, push in all remaining values from the other array. function merge(arr1, arr2) { let results = []; let i = 0; let j = 0; while(i < arr1.length && j < arr2.length){ if(arr2[j] > arr1[i]){ results.push(arr1[i]); i++; } else { results.push(arr2[j]); j++; } } while(i < arr1.length) { results.push(arr1[i]); i++; } while(j < arr2.length) { results.push(arr2[j]); j++; } return results; } // console.log(merge([1,10,50],[2,14,99,100])) //** mergeSort Pseudocode **// // Break up the array into halves until you have arrays that // are empty or have one element. // Once you have smaller sorted arrays, merge those arrays // with other sorted arrays until you are back at the full length // of the array. // Once the array has been merged back together, return the merged // (and sorted!) array. function mergeSort(arr) { if(arr.length <= 1) return arr; let mid = Math.floor(arr.length / 2); let left = mergeSort(arr.slice(0, mid)); let right = mergeSort(arr.slice(mid)); return merge(left, right); } console.log(mergeSort([10,24,76,73])) // Time Complexity: O(n log n) // O(log n) is the number of decompositions ([1], [2], [3], [4] => [1, 2, 3, 4]) // O(n) is the number of comparisons per decomposition (i.e. 4) // Space Complexity: O(n) // As we add more arrays through the decomposition process, more space is required, so it increases at the rate of O(n) and not O(1)
import axios from 'axios'; const initialState = { data: [], item: {}, isLoading: false, hasMore: false } const photoReducer = (state = initialState, action) => { switch (action.type) { case 'GET_PHOTOS': return { ...state, data: Object.values([...state.data, ...action.data].reduce((result, element) => { if (!result[element.id]) { result[element.id] = element; } return result; }, {})), hasMore: action.data.length > 0, isLoading: false } case 'GET_PHOTO': return { ...state, item: {...action.data}, isLoading: false } case 'LOADING_PHOTOS': return { ...state, isLoading: true } default: return state; } } export const getPhotos = (page, limit) => async dispatch => { dispatch(setLoadingPhotos()); const photos = await axios.get(`https://jsonplaceholder.typicode.com/photos?_page=${page}&_limit=${limit}`); return dispatch({ type: 'GET_PHOTOS', data: photos.data }) } export const getPhoto = (id) => async dispatch => { dispatch(setLoadingPhotos()); const photo = await axios.get(`https://jsonplaceholder.typicode.com/photos/${id}`); return dispatch({ type: 'GET_PHOTO', data: photo.data }) } const setLoadingPhotos = () => { return { type: 'LOADING_PHOTOS' } } export default photoReducer;
import React from 'react'; import Preloader from '../../components/preloader'; import ErrorIndicator from '../../components/error-indicator'; import CosmeticsList from '../../components/cosmetics-list'; import CartTable from '../../components/cart-table'; import cosmeticsModel from '../../common/models/cosmeticsModel'; class HomePage extends React.PureComponent { constructor(props) { super(props); } componentDidMount() { this.props.fetchCosmetics(); } render () { const { cosmetics, loading, error, items, orderTotal, onDelete, onIncrease, onDecrease } = this.props; const cosmeticsData = cosmeticsModel(cosmetics); if (loading) { return ( <Preloader /> ) } if (error) { return ( <ErrorIndicator /> ) } return ( <> <CosmeticsList cosmetics={cosmeticsData} /> <CartTable items={items} orderTotal={orderTotal} onDelete={onDelete} onIncrease={onIncrease} onDecrease={onDecrease} /> </> ); } } export default HomePage;
/** * @flow */ import * as JSON5 from 'json5'; import * as fs from './lib/fs'; import * as path from './lib/path'; import invariant from 'invariant'; import {resolve as resolveNodeModule} from './util'; import type {PackageManifest} from './types'; const MANIFEST_NAME_LIST = ['esy.json', 'package.json']; type ManifestResult = { manifest: PackageManifest, filename: string, }; export async function resolve( packageName: string, baseDirectory: string, ): Promise<?ManifestResult> { async function resolveToManifestPath(manifestName) { try { return await resolveNodeModule(`${packageName}/${manifestName}`, baseDirectory); } catch (_err) { return null; } } // Resolve all posible manifests and choose the one which is deeper in the // filesystem, with the Node modules layout deeper means more specific for the // package. // // TODO: Instead consider changin the search strategy to find esy.json or // package.json first at each directory level and only then recurse up the // directory tree. let manifestPaths = await Promise.all(MANIFEST_NAME_LIST.map(resolveToManifestPath)); manifestPaths = manifestPaths.filter(Boolean); manifestPaths.sort((a, b) => path.dirname(b).length - path.dirname(a).length); if (manifestPaths.length === 0) { return null; } else { const manifestPath = manifestPaths[0]; const manifestName = path.basename(manifestPath); const parse = manifestName === 'esy.json' ? JSON5.parse : JSON.parse; const manifest = await fs.readJson(manifestPath, parse); return {manifest: normalizeManifest(manifest), filename: manifestPath}; } } export async function read(packagePath: string): Promise<ManifestResult> { for (const manifestName of MANIFEST_NAME_LIST) { const manifestPath = path.join(packagePath, manifestName); if (!await fs.exists(manifestPath)) { continue; } const parse = manifestName === 'esy.json' ? JSON5.parse : JSON.parse; const manifest = await fs.readJson(manifestPath, parse); return {manifest: normalizeManifest(manifest), filename: manifestPath}; } invariant( false, 'Unable to find manifest in %s: tried %s', packagePath, MANIFEST_NAME_LIST.join(', '), ); } export function normalizeManifest(manifest: Object): PackageManifest { if (manifest.dependencies == null) { manifest.dependencies = {}; } if (manifest.peerDependencies == null) { manifest.peerDependencies = {}; } if (manifest.devDependencies == null) { manifest.devDependencies = {}; } if (manifest.scripts == null) { manifest.scripts = {}; } if (manifest.esy == null) { manifest.esy = {}; } manifest.esy.build = normalizeCommand(manifest.esy.build); manifest.esy.install = normalizeCommand(manifest.esy.install); if (manifest.esy.release == null) { manifest.esy.release = {}; } if (manifest.esy.exportedEnv == null) { manifest.esy.exportedEnv = {}; } if (manifest.esy.buildsInSource == null) { manifest.esy.buildsInSource = false; } if (manifest.esy.sandboxType == null) { manifest.esy.sandboxType = 'project'; } return manifest; } function normalizeCommand( command: null | string | Array<string | Array<string>>, ): Array<string | Array<string>> { if (command == null) { return []; } else if (!Array.isArray(command)) { return [command]; } else { return command; } }
'use strict'; angular .module('sbAdminApp') .directive('validator', function(ThirdPartyService) { return { require: 'ngModel', link: function(scope, element, attr, mCtrl) { function myValidation(value) { if( ThirdPartyService.validateCI(value)){ mCtrl.$setValidity('charE', true); }else{ mCtrl.$setValidity('charE', false); } return value; } mCtrl.$parsers.push(myValidation); } }; }) .controller('createPeopleController', function ($scope, $state, AlertService, PersonService) { var vm = this; $scope.profile = {}; vm.save = function () { PersonService.createProfile($scope.profile) .then(function () { AlertService.success('PROFILE'); $state.go('dashboard.people.list'); }) .catch(function () { AlertService.alert('error', 'PROFILE', 'ERROR_CREATE'); }); }; });
let assert = require("assert"); let fromWhere = require("../fromWhere"); describe('The fromWhere function',function(){ it('should return what town a registration number is from',function(){ assert.strictEqual(fromWhere('CA 123 456'),'Cape Town'); }); it('should return what town a registration number is from',function(){ assert.strictEqual(fromWhere('CY 123 456'),'Bellville'); }); });
import HyDeliveryOrderService from '@/services/hy/deliveryorder'; import { notification } from 'antd' export default { namespace: 'hydeliveryorder', state: { list: [], modalDeliveryOrderList: [], }, effects: { *getModalList({ payload, callback }, { call, put }) { const response = yield call(HyDeliveryOrderService.getModalList, payload); console.log('response', response); if (response.status === 'success') { const { data } = response callback && callback(data); yield put({ type: 'save', payload: { modalDeliveryOrderList: response, // shipMentOrderData: { // list: response.Data.Datas, // pagination: { // total: response.Data.Total, // pageSize: payload.pageSize, // current: payload.current, // pageNumber: payload.current // } // } }, }); } }, *confirmSelect({ payload, callback }, { call, put }) { const response = yield call(HyDeliveryOrderService.confirmSelect, payload); if (response.status === 'success') { callback && callback(response) } else { notification.error({ message: `请求错误`, description: response.message, }); } } }, reducers: { save(state, action) { return { ...state, ...action.payload, }; }, }, };
define([ 'client/views/graph/graph' ], function (Graph) { var VolumetricsGraph = Graph.extend({ minYDomainExtent: 1, numYTicks: 3, components: function () { var values = {}; values = { xaxis: { view: this.sharedComponents.xaxis }, yaxis: { view: this.sharedComponents.yaxis }, stack: { view: this.sharedComponents.line }, hover: { view: this.sharedComponents.hover }, callout: { view: this.sharedComponents.callout } }; if (this.formatOptions) { values.yaxis.options = {}; var self = this; values.yaxis.options.tickFormat = function () { return function (v) { return self.format(v, self.formatOptions); }; }; values.callout.options = {}; values.callout.options.formatValue = function (value) { if (value === null) { return '(no-data)'; } return this.format(value, this.graph.formatOptions); }; } return values; } }); return VolumetricsGraph; });
import React from 'react'; import store from 'store'; import { getLikes, getWhiskey, getSearches, changeFavorite } from 'api/data'; import Suggestions from 'ui/suggestions'; import UserSearches from 'ui/userSearches'; import SearchInput from 'ui/searchInput'; import { Link } from 'react-router'; import StarRating from 'ui/starRating'; import MoreButton from 'ui/moreButton'; import LikeHeart from 'ui/likeHeart'; import NoHeart from 'ui/noHeart'; import SaveSearch from 'ui/saveSearch'; require("assets/styles/productDetailPage.scss") require("assets/styles/comparables.scss") var x = []; export default React.createClass({ getInitialState: function(){ return ({ showHeart: this.props.showHeart || false, likedwhiskey: [], showSearch: false, showMoreButton: false }) }, componentWillMount: function(){ this.unsubscribe = store.subscribe(function(){ var currentStore = store.getState(); this.setState({ likedwhiskey: currentStore.userReducer.likedwhiskey, showSearch: currentStore.showReducer.showSearch, showMoreButton: currentStore.showReducer.showMoreButton }) }.bind(this)); }, getIDs: function(){ x = this.state.likedwhiskey.map(function(data){ return data.id; }) }, getStatus: function(item){ this.getIDs(); if(x.indexOf(item) === -1){ return false; } else { return true; } }, handleClick: function(item, e){ e.preventDefault(); getWhiskey(item.id); }, componentWillUnmount: function(){ this.unsubscribe(); }, render: function(){ return ( <div className="bigCompFlex prodDetailContainer"> <div className="compFlex"> {this.props.comparables.map(function(item, i){ return ( <div className="itemsLayout" key={item.id}> {this.getStatus(item.id) ? <LikeHeart item={item} /> : <NoHeart item={item} />} <Link to={"/productDetailPage/" + item.id}><div className="itemImageContainer"> <img className="itemImage" src={item.list_img_url} /> </div></Link> <div className="itemDescription"> <div className="titleDiv">{item.title}</div> <div className="textCategorys">Type/Region: <span className="priceColor">{item.region}</span></div> <div className="textCategorys" >Avg Price: <span className="priceColor">${item.price}</span></div> <StarRating rating={item.rating} /> </div> <div className="choices"> <Link to={"/productDetailPage/" + item.id}><div onClick={this.handleClick.bind(this, item)} className="choiceB">Details and Suggestions</div></Link> </div> </div> ) }.bind(this))} </div> </div> ) } })
import React from 'react'; import { Breadcrumb, Button, DatePicker, Select, Input, Row, Col, Table, Modal, Tooltip, Form, Icon, InputNumber, Card, Popconfirm, message, Spin, Tabs, ConfigProvider, } from 'antd'; import { connect } from 'dva'; import CurrencySearchBar from '@/components/SearchBar/CurrencySearchBar'; import zhCN from 'antd/es/locale/zh_CN'; import moment from 'moment'; import styles from './tableStyle.less'; @connect(({ guidePage, loading }) => ({ guidePage, loadingG: loading.effects['guidePage/getButtonGuideConfig'] || loading.effects['guidePage/getButtonGuideData'], })) @Form.create() export default class TableModulars extends React.Component { state = { expand: false, selectedRowKeys: [], //选择的那个表格行数据id selectedRow: [], //选择的那个表格行数据 page: 1, //表格所在的第几页 pageSize: 10, //表格每页展示多少行 FieldsValue: {}, //记录搜索条件 formData: {}, //处理后的搜索条件 autoCheck: false, //是否增加修改数据默认选择 data: _.get(this.props.guidePage.guidePageData, 'list', []), //表格数据 showColumns: [], // 当前展示页的子表表头 }; UNSAFE_componentWillMount = () => { let sendGuideData = _.get(this.props.guidePage, 'sendGuideData'); let isHaveData = sendGuideData[this.props.tableButton.BUTTON_GUIDE[this.props.current].RELATED_FIELD_GROUP]; if (isHaveData) { let selectedRowKeys = []; isHaveData.map(item => { selectedRowKeys.push(item.ID); }); this.setState({ selectedRowKeys, selectedRow: isHaveData, }); } setTimeout(() => { let { sendGuideData } = this.props.guidePage; let params = this.props.tableButton.BUTTON_GUIDE[this.props.current]; this.props.dispatch({ type: 'guidePage/getGuideBean', payload: { params, pageNum: 1, pageSize: 10, METHOD_BODY: params.METHOD_BODY, AllData: sendGuideData, id: this.props.tableTemplate.isEdit ? this.props.tableTemplate.detailData.thisComponentUid : null, }, callback: res => { if (res.status == 'success') { this.props.dispatch({ type: 'guidePage/getButtonGuideConfig', payload: { params, id: this.props.tableTemplate.isEdit ? this.props.tableTemplate.detailData.thisComponentUid : null, }, callback: Response => { this.setState({ showColumns: Response.data, autoCheck: Response.data.autoCheck, }); }, }); this.props.dispatch({ type: 'guidePage/getButtonGuideData', payload: { params, pageNum: 1, pageSize: 10, METHOD_BODY: params.METHOD_BODY, formData: this.props.guidePage.sendGuideData, id: this.props.tableTemplate.isEdit ? this.props.tableTemplate.detailData.thisComponentUid : null, }, callback: res => { this.props.closeSpin(); }, }); } }, }); }, 1000); }; componentDidMount = () => { this.props.onRef(this); this.props.closeSpin(); }; componentWillReceiveProps = nextProps => { if (_.get(nextProps.guidePage.guidePageData, 'list', []) != this.state.data) { this.setState({ data: _.get(nextProps.guidePage.guidePageData, 'list', []), }); } if ( this.props.tableButton.BUTTON_GUIDE[this.props.current].RELATED_FIELD_GROUP != nextProps.tableButton.BUTTON_GUIDE[nextProps.current].RELATED_FIELD_GROUP ) { let sendGuideData = _.get(this.props.guidePage, 'sendGuideData'); let { selectedRow, selectedRowKeys } = this.state; let CacheData = []; selectedRowKeys.map(items => { selectedRow.map(aa => { if (aa.ID == items) { CacheData.map((bb, gg) => { if (bb.ID == aa.ID) { CacheData.splice(gg, 1); } }); CacheData.push(aa); } }); }); sendGuideData[ this.props.tableButton.BUTTON_GUIDE[this.props.current].RELATED_FIELD_GROUP ] = CacheData; let isHaveData = _.cloneDeep( sendGuideData[this.props.tableButton.BUTTON_GUIDE[this.props.current].RELATED_FIELD_GROUP] ); if (isHaveData) { let selectedRowKeys = []; isHaveData.map(item => { selectedRowKeys.push(item.ID); }); this.setState({ selectedRowKeys, selectedRow: isHaveData, }); } setTimeout(() => { let { sendGuideData } = nextProps.guidePage; let params = nextProps.tableButton.BUTTON_GUIDE[nextProps.current]; this.props.dispatch({ type: 'guidePage/getGuideBean', payload: { params, pageNum: 1, pageSize: 10, METHOD_BODY: params.METHOD_BODY, AllData: sendGuideData, id: this.props.tableTemplate.isEdit ? this.props.tableTemplate.detailData.thisComponentUid : null, }, callback: res => { if (res.status == 'success') { this.props.dispatch({ type: 'guidePage/getButtonGuideConfig', payload: { params, id: this.props.tableTemplate.isEdit ? this.props.tableTemplate.detailData.thisComponentUid : null, }, callback: Response => { this.setState({ autoCheck: Response.data.autoCheck, }); }, }); this.props.dispatch({ type: 'guidePage/getButtonGuideData', payload: { params, pageNum: 1, pageSize: 10, METHOD_BODY: params.METHOD_BODY, formData: nextProps.guidePage.sendGuideData, id: this.props.tableTemplate.isEdit ? this.props.tableTemplate.detailData.thisComponentUid : null, }, callback: res => { this.props.closeSpin(); }, }); } }, }); }, 1000); //切换页面添加数据 let { isEdit, selectDate } = this.props.tableTemplate; let relatedFieldGroup = this.props.guidePage.guidePageColumns.relatedFieldGroup; this.state.selectedRow.map(item => { item.tablePageId = isEdit ? selectDate.ID : null; for (let i in item) { //对时间格式进行转换 if (typeof item[i] == 'string') { if (isNaN(item[i]) && !isNaN(Date.parse(item[i]))) { item[i] = moment(item[i]).valueOf(); } } } }); // this.props.dispatch({ // type:'guidePage/getSaveData', // payload:{relatedFieldGroup:relatedFieldGroup,data:this.state.selectedRow} // }) } }; onShowSizeChange = (current, pageSize) => { let params = this.props.tableButton.BUTTON_GUIDE[this.props.current]; this.props.dispatch({ type: 'guidePage/getButtonGuideData', payload: { pageNum: current, pageSize, params, id: this.props.tableTemplate.isEdit ? this.props.tableTemplate.detailData.thisComponentUid : null, }, }); this.setState({ page: current, pageSize, }); }; onPageChange = (page, pageSize) => { let current = page; let { formData } = this.state; let params = this.props.tableButton.BUTTON_GUIDE[this.props.current]; this.props.dispatch({ type: 'guidePage/getButtonGuideData', payload: { pageNum: current, searchData: formData, pageSize, params, id: this.props.tableTemplate.isEdit ? this.props.tableTemplate.detailData.thisComponentUid : null, }, }); this.setState({ page, pageSize, }); }; onSelectChange = (selectedRowKeys, selectedRow) => { let stateSelectedRow = this.state.selectedRow; selectedRow.map(item => { if (stateSelectedRow) { let idx = _.findIndex(stateSelectedRow, ii => ii.ID == item.ID); if (idx < 0) { stateSelectedRow.push(item); } } else { stateSelectedRow = selectedRow; } }); this.setState({ selectedRowKeys, selectedRow: stateSelectedRow }); }; disabledStartDate = (e, value) => { const endValue = this.state[`${value.FIELD_NAME}-end`]; if (!e || !endValue) { return false; } return e.valueOf() > endValue.valueOf(); }; disabledEndDate = (e, value) => { const startValue = this.state[`${value.FIELD_NAME}-start`]; if (!e || !startValue) { return false; } return e.valueOf() <= startValue.valueOf(); }; onDateChange = (field, value) => { this.setState({ [field]: value, }); }; onStartChange = (e, value) => { this.onDateChange(`${value.FIELD_NAME}-start`, e); }; onEndChange = (e, value) => { this.onDateChange(`${value.FIELD_NAME}-end`, e); }; //table数据改变 onTableChange = (e, FIELD_NAME, tableIndex, index, rowData) => { let { rtLinks } = this.props.guidePage.guidePageColumns; let idx = _.findIndex(this.state.selectedRow, ii => ii.ID == rowData.ID); if (rtLinks.includes(FIELD_NAME)) { rowData[FIELD_NAME] = e; let selectedRows = this.state.selectedRow; if (idx > -1) { selectedRows[idx][FIELD_NAME] = e; } this.setState({ selectedRow: selectedRows, }); let guidePageData = _.get(this.props.guidePage, 'guidePageData'); let guidePageColumns = _.get(this.props.guidePage, 'guidePageColumns'); let list = [ { updatedField: FIELD_NAME, objectType: guidePageData.objectType, policyFormFields: idx > -1 ? selectedRows[idx] : rowData, fieldGroupName: guidePageColumns.relatedFieldGroup, }, ]; this.props.dispatch({ type: 'guidePage/guideRtlink', payload: { list, }, callback: res => { let { data } = this.state; res.map(item => { item.fieldChanges.map(ii => { ii.changes.map(jj => { if (jj.field == 'FIELD_VALUE') { data[tableIndex][ii.field] = jj.value; rowData[ii.field] = jj.value; if (idx > -1) { selectedRows[idx][ii.field] = jj.value; this.setState({ selectedRow: selectedRows, }); } } }); }); }); this.setState({ data, }); }, }); } let { selectedRowKeys, selectedRow, autoCheck } = this.state; if (autoCheck) { let idx = _.findIndex(selectedRowKeys, item => item == rowData.ID); if (idx < 0 || selectedRowKeys.length == 0) { selectedRowKeys.push(rowData.ID); selectedRow.push(rowData); this.onSelectChange(selectedRowKeys, selectedRow); } else { // selectedRow[idx][FIELD_NAME] = e rowData[FIELD_NAME] = e; this.onSelectChange(selectedRowKeys, selectedRow); } } let tableData = this.props.guidePage.guidePageData; tableData.list[tableIndex][FIELD_NAME] = e; this.props.dispatch({ type: 'guidePage/save', payload: { guidePageData: tableData } }); }; toggle = () => { const { expand } = this.state; this.setState({ expand: !expand }); }; handleSearch = e => { const event = e || window.event; //阻止事件冒泡 event.stopPropagation(); event.preventDefault(); let newKey; let type; let formData = _.cloneDeep(this.props.form.getFieldsValue()); for (let i in formData) { if (typeof formData[i] == 'object' && formData[i]) { if (i.includes('-start') || i.includes('-end')) { newKey = i.split('-')[0]; formData[newKey] = {}; } } } for (let i in formData) { if (typeof formData[i] == 'object' && formData[i] != null) { formData[i] = formData[i].valueOf(); if (i.includes('-start') || i.includes('-end')) { newKey = i.split('-')[0]; type = i.split('-')[1]; formData[newKey][type] = formData[i].valueOf(); delete formData[i]; } } } let params = this.props.tableButton.BUTTON_GUIDE[this.props.current]; console.log('搜索参数', formData); this.setState({ formData, }); let { page, pageSize } = this.state; this.props.dispatch({ type: 'guidePage/getButtonGuideData', payload: { pageNum: this.state.page, pageSize: this.state.pageSize, searchData: formData, params, id: this.props.tableTemplate.isEdit ? this.props.tableTemplate.detailData.thisComponentUid : null, }, }); }; componentWillUnmount = () => { let { isEdit, selectDate } = this.props.tableTemplate; let relatedFieldGroup = this.props.guidePage.guidePageColumns.relatedFieldGroup; this.state.selectedRow.map(item => { item.tablePageId = isEdit ? selectDate.ID : null; for (let i in item) { //对时间格式进行转换 if (typeof item[i] == 'string') { if (isNaN(item[i]) && !isNaN(Date.parse(item[i]))) { item[i] = moment(item[i]).valueOf(); } } } }); this.props.dispatch({ type: 'guidePage/getSaveData', payload: { relatedFieldGroup: relatedFieldGroup, data: this.state.selectedRow }, }); }; //搜索功能 renderSearchForm = (props = []) => { let { expand } = this.state; const searchItems = _.filter(props, item => item.FILTERABLE == true); const count = this.state.expand ? searchItems.length : searchItems.length > 2 ? 2 : searchItems.length; const { getFieldDecorator } = this.props.form; return ( <ConfigProvider locale={zhCN}> <Row> <Form onSubmit={this.handleSearch} layout="inline" className="login-form"> {searchItems.length > 0 && searchItems.map((value, index) => { if (index >= count) return; if ( value.WIDGET_TYPE === 'Select' || value.WIDGET_TYPE === 'Reference' || value.WIDGET_TYPE === 'ObjectSelector' ) { return ( <Col span={this.state.expand ? 24 : 10} key={value.SEQUENCE + index} style={{ textAlign: 'right' }} > <Form.Item label={value.LABEL} style={{ display: index < count ? '' : 'none', marginRight: '0' }} key={value.SEQUENCE + index} > {getFieldDecorator(`${value.FIELD_NAME}`, {})( <Select allowClear showSearch filterOption={(inputValue, option) => _.includes(option.props.children, inputValue) } placeholder={`请选择${value.LABEL}`} // disabled={value.READ_ONLY_CONDITION} style={{ width: '165px', textOverflow: 'ellipsis', width: '195px' }} > {value.options.length && value.options.length > 0 ? _.map(value.options, (item, index) => { return ( <Select.Option title={item.text} key={item.value + item.text} value={item.value} > {item.text} </Select.Option> ); }) : null} </Select> )} </Form.Item> </Col> ); } else if (value.WIDGET_TYPE === 'DateTime') { return ( <Col span={this.state.expand ? 24 : 10} style={{ textAlign: 'right' }} key={value.SEQUENCE + index} > <Form.Item label={value.LABEL} key={value.SEQUENCE + index} style={{ marginRight: 0 }} > {getFieldDecorator(`${value.FIELD_NAME}`, {})( <RangePicker showTime={{ format: 'HH:mm' }} format="YYYY-MM-DD HH:mm" style={{ width: '195px' }} /> )} </Form.Item> </Col> ); } else if (value.WIDGET_TYPE === 'Date2') { return ( <Col span={this.state.expand ? 24 : 10} style={{ textAlign: 'right' }} key={value.SEQUENCE + index} > <Form.Item label={value.LABEL} key={value.SEQUENCE + index} style={{ marginRight: 0 }} > {getFieldDecorator(`${value.FIELD_NAME}`, {})( <DatePicker placeholder={`请选择${value.LABEL}`} style={{ width: '195px' }} format="YYYY-MM-DD" showTime={{ format: 'YYYY/MM/DD' }} /> )} </Form.Item> </Col> ); } else if (value.WIDGET_TYPE === 'Date') { let Date = [ { ...value, title: `起始${value.LABEL}`, DateType: 'start', }, { ...value, title: `结束${value.LABEL}`, FIELD_VALUE: null, DateType: 'end', }, ]; return Date.map((kk, gg) => { let type = kk.DateType; switch (type) { case 'start': return ( <Col span={this.state.expand ? 24 : 10} style={{ textAlign: 'right' }} key={value.SEQUENCE + gg} > <Form.Item style={{ marginRight: 0 }} label={kk.title} // style={{ display: expand ? 'flex' : index + 1 < count ? '' : 'none' }} > {getFieldDecorator(`${value.FIELD_NAME}-${kk.DateType}`, { initialValue: null, })( <DatePicker allowClear={true} placeholder={`请选择${kk.LABEL}`} format="YYYY-MM-DD" showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }} style={{ width: '195px' }} onChange={e => { this.onStartChange(e, kk); }} disabledDate={e => this.disabledStartDate(e, kk)} /> )} </Form.Item> </Col> ); break; case 'end': return ( <Col span={this.state.expand ? 24 : 10} style={{ textAlign: 'right' }} key={value.SEQUENCE + gg} > <Form.Item style={{ marginRight: 0 }} label={kk.title}> {getFieldDecorator(`${value.FIELD_NAME}-${kk.DateType}`, { initialValue: null, })( <DatePicker placeholder={`请选择${kk.LABEL}`} format="YYYY-MM-DD" showTime={{ defaultValue: moment('23:59:59', 'HH:mm:ss') }} style={{ width: '195px' }} allowClear={true} onChange={e => { this.onEndChange(e, kk); }} disabledDate={e => this.disabledEndDate(e, kk)} /> )} </Form.Item> </Col> ); break; default: break; } }); } else if (value.WIDGET_TYPE === 'Date') { return ( <Col span={this.state.expand ? 24 : 10} style={{ textAlign: 'right' }} key={value.SEQUENCE + index} > <Form.Item label={value.LABEL} key={value.SEQUENCE + index} style={{ marginRight: 0 }} > {getFieldDecorator(`${value.FIELD_NAME}`, {})( <DatePicker placeholder={`请选择${value.LABEL}`} style={{ width: '195px' }} format="YYYY-MM-DD" showTime={{ format: 'YYYY/MM/DD' }} /> )} </Form.Item> </Col> ); } else if (value.WIDGET_TYPE === 'Text') { return ( <Col span={this.state.expand ? 24 : 10} style={{ textAlign: 'right' }} key={value.SEQUENCE + index} > <Form.Item label={value.LABEL} key={value.SEQUENCE + index} style={{ marginRight: 0 }} > {getFieldDecorator(`${value.FIELD_NAME}`, { initialValue: '', })( <Input placeholder={`请输入${value.LABEL}`} style={{ width: '165px', textOverflow: 'ellipsis', width: '195px' }} /> )} </Form.Item> </Col> ); } else if (value.WIDGET_TYPE === 'Number') { return ( <Col span={this.state.expand ? 24 : 10} style={{ textAlign: 'right' }} key={value.SEQUENCE + index} > <Form.Item label={value.LABEL} key={value.SEQUENCE + index} style={{ marginRight: 0 }} > {getFieldDecorator(`${value.FIELD_NAME}`, {})( <Input type="number" placeholder={`请输入${value.LABEL}`} style={{ width: '165px', textOverflow: 'ellipsis', width: '195px' }} /> )} </Form.Item> </Col> ); } })} {searchItems.length > 0 && ( <Col span={this.state.expand ? 24 : 3} style={{ textAlign: 'right' }}> <Form.Item style={{ marginRight: 0 }}> <Button type="default" htmlType="submit"> <Icon type="search" /> </Button> <span style={{ display: 'inlineblock', padding: '8px' }}> <a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.toggle}> <Icon type={this.state.expand ? 'up' : 'down'} /> </a> </span> </Form.Item> </Col> )} </Form> </Row> </ConfigProvider> ); }; render() { const { TextArea } = Input; let columns = []; const { selectedRowKeys, selectedRow, data } = this.state; const rowSelection = { selectedRowKeys, selectedRow, onChange: this.onSelectChange, getCheckboxProps: record => ({ disabled: record.name === 'Disabled User', name: record.name, }), }; const { getFieldDecorator } = this.props.form; // let data = _.get(this.props.guidePage.guidePageData,'list',[]) let guidePageColumns = _.get(this.props.guidePage.guidePageColumns, 'policyFormFields', []).map( (item, index) => { if (item.READ_ONLY_CONDITION) { let obj; obj = { title: ( <Tooltip title={item.LABEL + '[' + item.FIELD_NAME + ']'}> <span>{item.LABEL}</span> </Tooltip> ), dataIndex: item.FIELD_NAME, key: item.FIELD_NAME + item.SEQUENCE, }; if (item.WIDGET_TYPE == 'Date' || item.WIDGET_TYPE == 'DateTime') { obj = { title: ( <Tooltip title={item.LABEL + '[' + item.FIELD_NAME + ']'}> <span>{item.LABEL}</span> </Tooltip> ), dataIndex: item.FIELD_NAME, key: item.FIELD_NAME + item.SEQUENCE, render: text => { return ( <div> {item.WIDGET_TYPE == 'Date' ? text ? moment(text).format('YYYY/MM/DD') : text : text ? moment(text).format('YYYY/MM/DD HH:mm:ss') : text} </div> ); }, }; } else if ( item.WIDGET_TYPE == 'Select' || item.WIDGET_TYPE == 'Reference' || item.WIDGET_TYPE == 'ObjectType' ) { obj = { title: ( <Tooltip title={item.LABEL + '[' + item.FIELD_NAME + ']'}> <span>{item.LABEL}</span> </Tooltip> ), dataIndex: item.FIELD_NAME, key: item.FIELD_NAME + item.SEQUENCE, render: text => { return ( <span> {item.options.map((gg, mm) => { if (gg.value == text) { return gg.text; } })} </span> ); }, }; } else if (item.WIDGET_TYPE == 'Number') { obj = { title: ( <Tooltip title={item.LABEL + '[' + item.FIELD_NAME + ']'}> <span>{item.LABEL}</span> </Tooltip> ), dataIndex: item.FIELD_NAME, key: item.FIELD_NAME + item.SEQUENCE, render: (text, record) => { let idxs = _.findIndex(selectedRow, zz => zz.ID == record.ID); return ( <div> {record[item.FIELD_NAME] * 1 == 0 ? idxs > -1 ? selectedRow[idxs][item.FIELD_NAME] * 1 : record[item.FIELD_NAME] * 1 : record[item.FIELD_NAME] * 1} </div> ); }, }; } columns.push(obj); } else { //不是只读的数据部分 switch (item.WIDGET_TYPE) { case 'Number': let NumberObj = { title: ( <Tooltip title={item.LABEL + '[' + item.FIELD_NAME + ']'}> <span>{item.LABEL}</span> </Tooltip> ), dataIndex: item.FIELD_NAME, key: item.FIELD_NAME + item.SEQUENCE, render: (text, record, tableIndex) => { let idxs = _.findIndex(selectedRow, zz => zz.ID == record.ID); return ( <Input type="number" max={text} style={{ minWidth: '120px', textAlign: 'right' }} onChange={e => this.onTableChange( e.target.value, item.FIELD_NAME, tableIndex, index, record ) } disabled={item.READ_ONLY_CONDITION} defaultValue={ idxs > -1 ? selectedRow[idxs][item.FIELD_NAME] * 1 : record[item.FIELD_NAME] } /> ); }, }; columns.push(NumberObj); break; case 'Text': let TextObj = { title: ( <Tooltip title={item.LABEL + '[' + item.FIELD_NAME + ']'}> <span>{item.LABEL}</span> </Tooltip> ), dataIndex: item.FIELD_NAME, key: item.FIELD_NAME + item.SEQUENCE, render: (text, record, tableIndex) => { return ( <Input style={{ minWidth: '150px' }} disabled={item.READ_ONLY_CONDITION} onChange={e => this.onTableChange( e.target.value, item.FIELD_NAME, tableIndex, index, record ) } defaultValue={text} /> ); }, }; columns.push(TextObj); break; case 'Select': case 'Reference': case 'ObjectType': let SelectObj = { title: ( <Tooltip title={item.LABEL + '[' + item.FIELD_NAME + ']'}> <span>{item.LABEL}</span> </Tooltip> ), dataIndex: item.FIELD_NAME, key: item.FIELD_NAME + item.SEQUENCE, render: (text, record, tableIndex) => { return ( <Select className={styles.selectData} disabled={item.READ_ONLY_CONDITION} defaultValue={text} allowClear showSearch filterOption={(inputValue, option) => _.includes(option.props.children, inputValue) } onChange={e => this.onTableChange(e, item.FIELD_NAME, tableIndex, index, record) } > {_.map(item.options, (v, i) => { return ( <Select.Option value={v.value} key={v.value}> {v.text} </Select.Option> ); })} </Select> ); }, }; columns.push(SelectObj); break; case 'Date': case 'DateTime': let DateObj = { title: ( <Tooltip title={item.LABEL + '[' + item.FIELD_NAME + ']'}> <span>{item.LABEL}</span> </Tooltip> ), dataIndex: item.FIELD_NAME, key: item.FIELD_NAME + item.SEQUENCE, render: (text, record, tableIndex) => { return ( <DatePicker disabled={item.READ_ONLY_CONDITION} style={{ minWidth: '150px' }} format={item.WIDGET_TYPE == 'Date' ? 'YYYY/MM/DD' : 'YYYY-MM-DD HH:mm:ss'} onChange={e => this.onTableChange(e.valueOf(), item.FIELD_NAME, tableIndex, index, record) } defaultValue={text ? moment(text) : null} /> ); }, }; columns.push(DateObj); break; case 'Textarea': let TextareaObj = { title: ( <Tooltip title={item.LABEL + '[' + item.FIELD_NAME + ']'}> <span>{item.LABEL}</span> </Tooltip> ), dataIndex: item.FIELD_NAME, key: item.FIELD_NAME + item.SEQUENCE, render: (text, record, tableIndex) => { return ( <TextArea style={{ minWidth: '150px' }} disabled={item.READ_ONLY_CONDITION} onChange={e => this.onTableChange( e.target.value, item.FIELD_NAME, tableIndex, index, record ) } defaultValue={text} /> ); }, }; columns.push(TextareaObj); break; case 'MultiObjectSelector': break; } } } ); return ( <div> { <div style={{ marginBottom: '5px' }}> {this.renderSearchForm( _.get(this.props.guidePage.guidePageColumns, 'policyFormFields', []) )} </div> } <ConfigProvider locale={zhCN}> <Table style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} scroll={{ x: true }} rowSelection={rowSelection} bordered dataSource={data} columns={columns} pagination={{ showSizeChanger: true, total: _.get(this.props.guidePage, 'guidePageData.totalRecord'), current: _.get(this.props.guidePage, 'guidePageData.currentPage'), pageSize: _.get(this.props.guidePage, 'guidePageData.pageSize'), pageSizeOptions: ['10', '20', '30', '50', '100'], onShowSizeChange: (current, pageSize) => this.onShowSizeChange(current, pageSize), onChange: (page, pageSize) => this.onPageChange(page, pageSize), showTotal: total => `共${this.props.guidePage.guidePageData.totalRecord}条数据`, }} /> </ConfigProvider> </div> ); } }
class MissingPage { constructor() { this.createSection() } createSection() { const div = document.createElement('div') div.innerText = 'Kunde inte hitta kontakten du sökte efter :(' const main = document.querySelector('main') main.append(div) } }
var orderCode = ""+ddsc.getUrlParam("orderCode"); $(function(){ obj.queryList() }) let obj = { queryList() { queryOrderinfos() } } //查询 function queryOrderinfos(){ console.log(orderCode) let obj = { orderCode } myAjax.request({ url: basepath + "/orderinfo/queryOrderinfosMobile.do", type: 'GET' }, obj) .then((result) => { if(result.status == 0){ let html = '' let h = '' console.log(result.data) result.data.map((item, index) => { html = ` <div class="title clearfix"> <div> <span>订单状态:</span> <span class="status warm">${item.statusName}</span> </div> <div> <span>交易时间:</span> <span class="date">${new Date(item.createTime).pattern('yyyy-MM-dd')}</span> <span class="time">${new Date(item.createTime).pattern('HH:mm:ss')}</span> </div> <div class="status"> <span>订单号码:</span> <span class="orderId">${item.orderCode}</span> </div> <i></i> </div> <div class="addressList"> <p class="userInfo"> <span>收货人:</span> <span class="userName">${item.consigneeName}</span> </p> <p> <span>手机号:</span> <span class="phone">${item.consigneeTel}</span> </p> <p class="address"> <span>地&nbsp;&nbsp;&nbsp;址:</span> <span>${item.address}</span> </p> <i></i> </div> <ul class="goods" id="goods${index}"> <li class="seller"> <i class="select sellerSelect"></i> <i class="shop"></i> <h3>${item.businessName}</h3> </li </ul> <div class="sellerTotal"> <span class="f_right">总计:<b>¥</b><i class="smallTotal">${item.totalPrice}</i></span> <span class="toPay f_right hide">立即支付</span> </div> ` $("#productlist").append(html) for(let i of item.getGoodsInfos){ h = ` <li> <img src="${i.picUrl}" alt=""> <div class="info"> <p class="name">${i.bookName}</p> <p class="price"><span class="warm">¥${i.goodsPirce}</span><i class="number f_right">x ${i.num}</i></p> </div> </li> ` $('#goods'+index).append(h) } }) } }) .catch((error) => { /*let layparams = { message: "报错了:"+error, } showToast(layparams)*/ console.error("报错了:"+error); }); }
'use strict'; /** * @ngdoc overview * @name vitacademicsForWebApp * @description * # vitacademicsForWebApp * * Main module of the application. */ angular .module('vitacademicsForWebApp', [ 'ngAnimate', 'ngAria', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch', 'ngMaterial', 'LocalStorageModule' ]) .config(['localStorageServiceProvider', function(localStorageServiceProvider) { localStorageServiceProvider.setPrefix('ls'); }]) .config(function($routeProvider) { $routeProvider // .when('/', { // templateUrl: 'views/main.html', // controller: 'MainCtrl' // }) .when('/login', { templateUrl: 'views/login.html', controller: 'LoginCtrl' }) .when('/me', { templateUrl: 'views/me.html', controller: 'MeCtrl' }) .otherwise({ redirectTo: '/login' }); }) .run(['$rootScope', '$location', 'localStorageService', function ($rootScope, $location, localStorageService) { // keep user logged in after page refresh $rootScope.globals = localStorageService.get('globals') || {}; $rootScope.$on('$locationChangeStart', function () { // redirect to login page if not logged in if ($location.path() !== '/login' && !$rootScope.globals.currentUser) { $location.path('/login'); } }); }]);
const numeral = require('numeral') module.exports.uptime = uptime => { let unit = 'second' if (uptime > 60) { uptime = uptime / 60 unit = 'minute' } if (uptime > 60) { uptime = uptime / 60 unit = 'hour' } if (uptime != 1) { unit = unit + 's' } return `${uptime} ${unit}` } module.exports.hashrate = hashes => { let unit = 'Sol/s' if (hashes >= 1000000) { hashes = hashes / 1000 / 1000 unit = 'Msol/s' } else if (hashes >= 1000) { hashes = hashes / 1000 unit = 'Ksol/s' } return module.exports.float(hashes) + ' ' + unit } module.exports.usd = dollars => numeral(dollars).format('$0,0.000') module.exports.integer = integer => numeral(integer).format('0,0') module.exports.float = number => numeral(number).format('0,0.00') // NOTE: numeral library returns NaN when you try to format numbers less than // 100 satoshis. For this reason, we let numeral format the whole numbers since // decimals don't need commas, etc. module.exports.coins = coins => { const whole = Math.trunc(coins) const decimal = parseFloat(coins - whole) return numeral(whole).format('0,0') + ('' + parseFloat(decimal).toFixed(8)).substr(1) }
AFRAME.registerComponent('mobile-move', { schema: { target: {type: 'string'}, height: {type: 'string', default: 2} }, init: function () { var el = this.el; var target = document.getElementById(this.data.target); var pos = el.getAttribute("position"); var height = this.data.height; if (target == null && target == undefined) { console.error("ERROR [mobile-move] : target is null") } else { el.addEventListener('click', function () { target.setAttribute("position", { x: pos.x, y: pos.y + height, z: pos.z }); }); } } });
const expect = require('expect.js'); const int = require('./int'); describe('Day 09', () => { it('Should support relative base instructions and print itself', () => { expect(int([109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99])).to.eql([109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99]); }); it('Should support relative base instructions and 16 digit numbers', () => { expect(int([1102, 34915192, 34915192, 7, 4, 7, 99, 0]).toString()).to.have.length(16); }); });
(function(){ var MatchFactory = function($http){ var service="match"; var factory={}; var matchForUpdate =[]; factory.getDataForAddMatch = function(){ var req={ method:'GET', url:'app/match', params:{service:service,operation:'getaddmatch'} } return $http(req); } factory.addNewMatch = function(matchDateTime,teamA,teamB,matchTitle,referee,court,matchMinutes,matchSeconds,breakTimeMinutes,breakTimeSeconds,halfTimeMinutes,halfTimeSeconds,newTemplate,timeoutTimeMinutes,timeoutTimeSeconds){ var req={ method:'POST', url:'app/match', data:{service:service, matchDateTime:matchDateTime,teamA:teamA,teamB:teamB,matchTitle:matchTitle,referee:referee,court:court,matchMinutes:matchMinutes,matchSeconds:matchSeconds,breakTimeMinutes:breakTimeMinutes,breakTimeSeconds:breakTimeSeconds,halfTimeMinutes:halfTimeMinutes,halfTimeSeconds:halfTimeSeconds,newTemplate:newTemplate,timeoutTimeMinutes:timeoutTimeMinutes,timeoutTimeSeconds:timeoutTimeSeconds} } return $http(req); } factory.getMatches = function(){ var req={ method:'GET', url:'app/match', params:{service:service,operation:'getdmatches'} } return $http(req); } factory.deleteMatches = function(matches){ var req={ method:'DELETE', url:'app/match', data:{service:service,matches:matches}, headers: {"Content-Type": "application/json;charset=utf-8"} } return $http(req); } factory.updateMatch = function(matchDateTime,teamA,teamB,matchTitle,referee,court,matchMinutes,matchSeconds,breakTimeMinutes,breakTimeSeconds,halfTimeMinutes,halfTimeSeconds,matchId,timeoutTimeMinutes,timeoutTimeSeconds){ var req={ method:'PUT', url:'app/match', data:{service:service, matchDateTime:matchDateTime,teamA:teamA,teamB:teamB,matchTitle:matchTitle,referee:referee,court:court,matchMinutes:matchMinutes,matchSeconds:matchSeconds,breakTimeMinutes:breakTimeMinutes,breakTimeSeconds:breakTimeSeconds,halfTimeMinutes:halfTimeMinutes,halfTimeSeconds:halfTimeSeconds,matchId:matchId,timeoutTimeMinutes:timeoutTimeMinutes,timeoutTimeSeconds:timeoutTimeSeconds} } return $http(req); } factory.saveMatchForUpdate = function(match){ matchForUpdate=match; } factory.getMatchForUpdate = function(match){ return matchForUpdate; } return factory; } angular.module('vollyboard').factory('MatchFactory',MatchFactory); }())
import React from 'react' import Section from './Section.jsx' class Cta extends React.Component { render () { return ( <Section> <h2>Get Started</h2> <pre>npm i rgx</pre> <p> Read the docs on GitHub to learn more. </p> <a href='//github.com/jxnblk/rgx' className='btn white bg-blue rounded'> GitHub </a> </Section> ) } } export default Cta
// Creating a dummy state in App.js, and passing it to Todos via props as // <Todos todos={ this.state.todos }/> import React, { Component } from 'react'; import Todos from './Todos'; import AddTodo from './AddTodo'; class App extends Component { // Dummy data state = { todos: [ {id: 1, content: 'buy some milk'}, {id: 2, content: 'play mario kart'} ] } // Function to delete todo. We need to pass it as props to Todos component, so when we click it // we can get an id of that todo deleteTodo = (id) => { // Running non-destructive method, which returns new array. const todos = this.state.todos.filter(todo => { // Returning todos with not the id clicked return todo.id !== id }); this.setState({ todos }) } // To add todos to the list we need to create a function that will interact with the state in App. // It receives todo (this.state of AddTodo) addTodo = (todo) => { // We need to add id. Simple random function todo.id = Math.random() // Not altering the original array directly. Creating a new array and dumping the content of // original array, using spread operator let todos = [...this.state.todos, todo] this.setState({ todos }) } render() { // Displaying header and Todos component. Passing props to Todos component return ( <div className="todo-app container"> <h1 className="center blue-text">Todo's</h1> <Todos todos={ this.state.todos } deleteTodo={ this.deleteTodo }/> <AddTodo addTodo={ this.addTodo }/> </div> ); } } export default App;
// Items are things that exist inside a game tile and can be collected by // and used by a player function Item(settings) { this.id = settings.id; this.type = settings.type || ''; this.createdAt = settings.createdAt || new Date().getTime(); this.position = settings.position; this.position.z = 0; } Item.prototype._out = function() { return [ this.type, this.createdAt, this.id, this.position.x, this.position.y ]; }; Item.prototype._in = function(data) { return { type: data[0], createdAt: data[1], id: data[2], position: {x: data[3], y: data[4]} }; }; if (typeof module != 'undefined') module.exports = Item;
import test from 'ava' import PetList from '../../src/js/views/pet-list' test('should render component', function (t) { const vnode = PetList.view() t.is(vnode.children.length, 2) t.is(vnode.children[0].tag, 'h2') t.is(vnode.children[0].text, 'Adoptable Pets') t.pass() })
import React, { Component } from 'react'; import { MDBBtn } from "mdbreact"; import {connect} from 'react-redux' class Header extends Component { constructor(props) { super(props) this.state=({ value:"" }) } handlechange=(event)=> { this.setState({ value:event.target.value }) } add=()=> { if(!this.state.value) return {} this.props.addReducertodo(this.state.value) this.setState({ value:'' }) } render() { return ( <div className='header-app form-group'> <input type="text" value={this.state.value} onChange={this.handlechange} className="form-control"/> <MDBBtn color="primary" onClick={this.add}>Add+</MDBBtn> </div> ); } } const mapDispatchToProps=(dispatch)=> { return { addReducertodo:x=> { dispatch({ type:'ADD_TODO', newtodo:x//ES6 ==>x:x (x) }) } } } export default connect(null,mapDispatchToProps)(Header);
module.exports = { preset: 'ts-jest', moduleFileExtensions: ['ts', 'tsx', 'js'], moduleNameMapper: { '@/(.*)': ['<rootDir>/$1'], }, testMatch: ['<rootDir>/**/*.spec.(ts|tsx)'], watchPathIgnorePatterns: ['node_modules'], watchman: false, };
import { parse } from '../parse'; describe('parse', () => { it('regular', () => { const out = parse( { display: 'value', button: { border: '0' }, '&.nested': { foo: '1px', baz: 'scale(1), translate(1)' } }, 'hush' ); expect(out).toEqual( [ 'hush{display:value;}', 'hush button{border:0;}', 'hush.nested{foo:1px;baz:scale(1), translate(1);}' ].join('') ); }); it('camelCase', () => { const out = parse( { fooBarProperty: 'value', button: { webkitPressSomeButton: '0' }, '&.nested': { foo: '1px', backgroundEffect: 'scale(1), translate(1)' } }, 'hush' ); expect(out).toEqual( [ 'hush{foo-bar-property:value;}', 'hush button{webkit-press-some-button:0;}', 'hush.nested{foo:1px;background-effect:scale(1), translate(1);}' ].join('') ); }); it('keyframes', () => { const out = parse( { '@keyframes superAnimation': { '11.1%': { opacity: '0.9999' }, '111%': { opacity: '1' } }, '@keyframes foo': { to: { baz: '1px', foo: '1px' } }, '@keyframes complex': { 'from, 20%, 53%, 80%, to': { transform: 'translate3d(0,0,0)' }, '40%, 43%': { transform: 'translate3d(0, -30px, 0)' }, '70%': { transform: 'translate3d(0, -15px, 0)' }, '90%': { transform: 'translate3d(0,-4px,0)' } } }, 'hush' ); expect(out).toEqual( [ '@keyframes superAnimation{11.1%{opacity:0.9999;}111%{opacity:1;}}', '@keyframes foo{to{baz:1px;foo:1px;}}', '@keyframes complex{from, 20%, 53%, 80%, to{transform:translate3d(0,0,0);}40%, 43%{transform:translate3d(0, -30px, 0);}70%{transform:translate3d(0, -15px, 0);}90%{transform:translate3d(0,-4px,0);}}' ].join('') ); }); it('font-face', () => { const out = parse( { '@font-face': { 'font-weight': 100 } }, 'FONTFACE' ); expect(out).toEqual(['@font-face{font-weight:100;}'].join('')); }); it('@media', () => { const out = parse( { '@media any all (no-really-anything)': { position: 'super-absolute' } }, 'hush' ); expect(out).toEqual( ['@media any all (no-really-anything){hush{position:super-absolute;}}'].join('') ); }); it('@import', () => { const out = parse( { '@import': "url('https://domain.com/path?1=s')" }, 'hush' ); expect(out).toEqual(["@import url('https://domain.com/path?1=s');"].join('')); }); it('cra', () => { expect( parse( { '@import': "url('path/to')", '@font-face': { 'font-weight': 100 }, 'text-align': 'center', '.logo': { animation: 'App-logo-spin infinite 20s linear', height: '40vmin', 'pointer-events': 'none' }, '.header': { 'background-color': '#282c34', 'min-height': '100vh', display: 'flex', 'flex-direction': 'column', 'align-items': 'center', 'justify-content': 'center', 'font-size': 'calc(10px + 2vmin)', color: 'white' }, '.link': { color: '#61dafb' }, '@keyframes App-logo-spin': { from: { transform: 'rotate(0deg)' }, to: { transform: 'rotate(360deg)' } } }, 'App' ) ).toEqual( [ "@import url('path/to');", 'App{text-align:center;}', '@font-face{font-weight:100;}', 'App .logo{animation:App-logo-spin infinite 20s linear;height:40vmin;pointer-events:none;}', 'App .header{background-color:#282c34;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;font-size:calc(10px + 2vmin);color:white;}', 'App .link{color:#61dafb;}', '@keyframes App-logo-spin{from{transform:rotate(0deg);}to{transform:rotate(360deg);}}' ].join('') ); }); it('@supports', () => { expect( parse( { '@supports (some: 1px)': { '@media (s: 1)': { display: 'flex' } }, '@supports': { opacity: 1 } }, 'hush' ) ).toEqual( [ '@supports (some: 1px){@media (s: 1){hush{display:flex;}}}', '@supports{hush{opacity:1;}}' ].join('') ); }); it('unwrapp', () => { expect( parse( { '--foo': 1, opacity: 1, '@supports': { '--bar': 'none' }, html: { background: 'goober' } }, '' ) ).toEqual( ['--foo:1;opacity:1;', '@supports{--bar:none;}', 'html{background:goober;}'].join('') ); }); it('nested with multiple selector', () => { const out = parse( { display: 'value', '&:hover,&:focus': { border: '0', span: { index: 'unset' } }, 'p,b,i': { display: 'block', '&:focus,input': { opacity: 1, 'div,span': { opacity: 0 } } } }, 'hush' ); expect(out).toEqual( [ 'hush{display:value;}', 'hush:hover,hush:focus{border:0;}', 'hush:hover span,hush:focus span{index:unset;}', 'hush p,hush b,hush i{display:block;}', 'hush p:focus,hush p input,hush b:focus,hush b input,hush i:focus,hush i input{opacity:1;}', 'hush p:focus div,hush p:focus span,hush p input div,hush p input span,hush b:focus div,hush b:focus span,hush b input div,hush b input span,hush i:focus div,hush i:focus span,hush i input div,hush i input span{opacity:0;}' ].join('') ); }); it('should handle the :where(a,b) cases', () => { expect( parse( { div: { ':where(a, b)': { color: 'blue' } } }, '' ) ).toEqual('div :where(a, b){color:blue;}'); }); it('should handle null and undefined values', () => { expect( parse( { div: { opacity: 0, color: null } }, '' ) ).toEqual('div{opacity:0;}'); expect( parse( { div: { opacity: 0, color: undefined // or `void 0` when minified } }, '' ) ).toEqual('div{opacity:0;}'); }); it('does not transform the case of custom CSS variables', () => { expect( parse({ '--cP': 'red' }) ).toEqual('--cP:red;'); expect( parse({ '--c-P': 'red' }) ).toEqual('--c-P:red;'); expect( parse({ '--cp': 'red' }) ).toEqual('--cp:red;'); expect( parse({ ':root': { '--cP': 'red' } }) ).toEqual(':root{--cP:red;}'); }); });
import socket from './socket' (function() { // let id = $('#id').data('id') // if(!id) // return; let channel = socket.channel("report:get", {}); channel.on("update_report", event =>{ console.log("update report"); }) channel.join() .receive("ok", resp => { console.log("Joined successfully report", resp) }) .receive("error", resp => { console.log("Unable to join", resp) }) }) ();
const fs = require("fs"); function FileSystemWrapper(){ function read({filePath}){ return new Promise((resolve, reject) => { fs.readFile(filePath, {encoding: "utf-8"}, (error, data) => { if(!error) { resolve(data); } else { reject(error); } }); }); } function write({content, outputPath}){ fs.writeFile(outputPath, content, (err) => { if(err) { return console.log("[X] Can not write file " + outputPath + " | error: " + err); } }); } function createPath({path}){ fs.mkdirSync(path) } function existPath({path}) { return fs.existsSync(path); } return { read: read, write: write, createPath: createPath, existPath: existPath }; } module.exports = FileSystemWrapper;
/** * 一款小巧的jQuery拾色器组件v0.2.29.04.2014 * @version 0.2.29.04.2014 * * @author Levi * @url http://levi.cg.am/archives/3467 */ ;(function ($) { $(function () { $(document).bind('click', function() { if ($iColor.is(':visible')) { $iColor.fadeOut('fast')[0].tar = null; } }); $iColor = $('<div id="iColorPicker"><table class="pickerTable"><thead></thead><tbody><tr><td colspan="16" id="colorPreview"></td></tr></tbody></table></div>').css({ 'display': 'none', 'position': 'absolute' }).appendTo($('body')).each(function() { var group = [], row = '', hx = [ 'f00', 'ff0', '0f0', '0ff', '00f', 'f0f', 'fff', 'ebebeb', 'e1e1e1', 'd7d7d7', 'ccc', 'c2c2c2', 'b7b7b7', 'acacac', 'a0a0a0', '959595', 'ee1d24', 'fff100', '00a650', '00aeef', '2f3192', 'ed008c', '898989', '7d7d7d', '707070', '626262', '555', '464646', '363636', '262626', '111', '000', 'f7977a', 'fbad82', 'fdc68c', 'fff799', 'c6df9c', 'a4d49d', '81ca9d', '7bcdc9', '6ccff7', '7ca6d8', '8293ca', '8881be', 'a286bd', 'bc8cbf', 'f49bc1', 'f5999d', 'f16c4d', 'f68e54', 'fbaf5a', 'fff467', 'acd372', '7dc473', '39b778', '16bcb4', '00bff3', '438ccb', '5573b7', '5e5ca7', '855fa8', 'a763a9', 'ef6ea8', 'f16d7e', 'ee1d24', 'f16522', 'f7941d', 'fff100', '8fc63d', '37b44a', '00a650', '00a99e', '00aeef', '0072bc', '0054a5', '2f3192', '652c91', '91278f', 'ed008c', 'ee105a', '9d0a0f', 'a1410d', 'a36209', 'aba000', '588528', '197b30', '007236', '00736a', '0076a4', '004a80', '003370', '1d1363', '450e61', '62055f', '9e005c', '9d0039', '790000', '7b3000', '7c4900', '827a00', '3e6617', '045f20', '005824', '005951', '005b7e', '003562', '002056', '0c004b', '30004a', '4b0048', '7a0045', '7a0026' ]; $.each(hx, function(num, color) { row += '<td style="background:#' + color + '" hx="' + color + '"></td>'; if (num % 16 == 15) { group.push('<tr>' + row + '</tr>'); row = ''; } }); $(this).find('thead').html(group.join('')); }).on({ 'mouseover': function(evt) { var hx = $(evt.target).attr('hx'); hx != undefined && $('#colorPreview').css('background', '#' + hx).attr('hx', hx); }, 'click': function(evt) { var t = this.tar, hx = $(evt.target).attr('hx'); if (!hx) { evt.stopPropagation(); return false; } t.set.call($(t).attr('hx', hx), hx); }, 'coord': function(e) { var num = $.extend({'x': 0, 'y': 0}, e.num||null); $(this).fadeIn('fast').css({ 'top': e.posix.y + num.y, 'left': e.posix.x + num.x }); } }); }); $.fn.iColor = function(arg, set) { var def = $.extend({ 'x': 0 , 'y': 0, 'type': 'click', 'open': function() {}, 'set': function(hx) { var val = '#' + hx; this[!this.attr('type') ? 'html' : 'val'](val).css('background', val); } }, arg); return this.each(function() { var $t = $(this), val = $t.attr('hx'); this.set = set || ($.isFunction(arg) ? arg : def.set); if (val) { val = $.trim(val); if (val[0] == '#') { val = val.substring(1); } !this.set && console.log(this); val.length && this.set.call($t, val + ['', '00', '0'][val.length % 3]); } })[def.type](function(e) { var t = e.target, od = $iColor[0].tar || null; if (od == t && t.show) { return; } t.show = true; e.stopPropagation(); def.open.call($(t), e); $iColor.trigger({'type': 'coord', 'num': set, 'posix': { 'x': e.pageX, 'y': e.pageY }})[0].tar = t; }); }; })(jQuery);
const errorText = "Невозможно определить координаты точки!<br>Укажите R!"; const blue = "#45688E"; const red = "red"; const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const width = canvas.getAttribute("width"); const height = canvas.getAttribute("height"); const form = document.getElementById("form"); const hiddenForm = document.getElementById("hiddenForm"); function paintPlot() { let rad = height / 40; let rad2 = height / 80; ctx.fillStyle = "white"; ctx.fillRect(0, 0, Number(width), Number(height)); //do white canvas ctx.fillStyle = blue; ctx.fillRect(width / 2, height / 2, 2 / 6 * width, 1 / 6 * height); ctx.beginPath(); ctx.arc(width / 2, height / 2, 1 / 6 * height, 1 / 2 * Math.PI, Math.PI); ctx.moveTo(width / 2, height / 2); ctx.lineTo(width / 2, 4 / 6 * height); ctx.lineTo(2 / 6 * width, height / 2); ctx.lineTo(width / 2, height / 2); ctx.fill(); ctx.beginPath(); ctx.moveTo(width / 2, height / 2); ctx.lineTo(2 / 6 * width, height / 2); ctx.lineTo(width / 2, 2 / 6 * height); ctx.lineTo(width / 2, height / 2); ctx.fill(); ctx.beginPath(); canvas_arrow(ctx, width / 2, height - rad, width / 2, rad); canvas_arrow(ctx, rad, height / 2, width - rad, height / 2); ctx.strokeText("X", Number(width) - rad, height / 2 - rad / 2); ctx.strokeText("Y", width / 2 + rad / 2, rad); addMark("-R", width / 2, 5 / 6 * height); addMark("-R/2", width / 2, 4 / 6 * height); addMark("R/2", width / 2, 2 / 6 * height); addMark("R", width / 2, 1 / 6 * height); addMark("R/2", 4 / 6 * width, height / 2); addMark("R", 5 / 6 * width, height / 2); addMark("-R/2", 2 / 6 * width, height / 2); addMark("-R", 1 / 6 * width, height / 2); ctx.stroke(); function addMark(label, x, y) { if (x === width / 2) { ctx.moveTo(x - rad2, y); ctx.lineTo(x + rad2, y); ctx.strokeText(label, x + rad, y); } if (y === height / 2) { ctx.moveTo(x, y - rad2); ctx.lineTo(x, y + rad2); ctx.strokeText(label, x, y - rad); } } function canvas_arrow(context, fromx, fromy, tox, toy) { let headlen = 10; // length of head in pixels let dx = tox - fromx; let dy = toy - fromy; let angle = Math.atan2(dy, dx); context.moveTo(fromx, fromy); context.lineTo(tox, toy); context.lineTo(tox - headlen * Math.cos(angle - Math.PI / 6), toy - headlen * Math.sin(angle - Math.PI / 6)); context.moveTo(tox, toy); context.lineTo(tox - headlen * Math.cos(angle + Math.PI / 6), toy - headlen * Math.sin(angle + Math.PI / 6)); } } function setColor(point, r) { const x = point['x']; const y = point['y']; if (x <= 0) { if (y >= 0) { if (y <= x + r / 2) { return red; } else { return blue; } } else { if (Math.pow(x, 2) + Math.pow(y, 2) <= Math.pow(r / 2, 2)) { return red; } else { return blue; } } } else { if (y > 0) { return blue; } else { if (x <= r && y >= -r / 2) { return red; } else { return blue; } } } } function addDots(r, history) { let rad = height / 40; let rad2 = height / 80; Array.prototype.forEach.call(history, function (point) { let x = width / 2 + point['x'] * Math.round(width / 3) / Number(r); let y = height / 2 - point['y'] * Math.round(height / 3) / Number(r); ctx.fillStyle = setColor(point, r); ctx.beginPath(); ctx.arc(x, y, 3, 0, 2 * Math.PI); ctx.fill(); }); } let curr_R = null; function newRad() { document.getElementById("checkedR").innerHTML = "<br><br>"; repaintPlot(); } function clickOnCanv(event) { if (curr_R == null) { document.getElementById("checkedR").innerHTML = errorText; //click with not choosen R } else { const x = event.pageX - (canvas.getBoundingClientRect().left + pageXOffset); const y = event.pageY - (canvas.getBoundingClientRect().top + pageYOffset); const cordX = (x - width / 2) * Number(curr_R) / Math.round(width / 3); const cordY = (height / 2 - y) * Number(curr_R) / Math.round(height / 3); //draw point ctx.fillStyle = setColor({'x': cordX, 'y': cordY}, Number(curr_R)); ctx.beginPath(); ctx.arc(x, y, 3, 0, 2 * Math.PI); ctx.fill(); //fill hidden form hiddenForm[hiddenForm.id + ":x_canv"].value = cordX; hiddenForm[hiddenForm.id + ":y_canv"].value = cordY; hiddenForm[hiddenForm.id + ":r_canv"].value = curr_R; hiddenForm[hiddenForm.id + ":submitCanvas"].click(); } } function repaintPlot() { paintPlot(); Array.prototype.forEach.call(form[form.id + ":r"], function (elem) { if (elem.checked === true) { curr_R = elem.value; } }); if (curr_R != null) addDots(Number(curr_R), JSON.parse(document.getElementById("history").innerHTML)); } { document.getElementById("canvas").onclick = clickOnCanv; repaintPlot(); }
import 'whatwg-fetch'; // Node:fs is only available server-side, so in this case load the fs functions. let readFileSync = null; let fileExists = null; if (import.meta.env.SSR) { import('node:fs').then( ({ readFileSync: readFileSyncFunc, existsSync }) => { readFileSync = readFileSyncFunc; fileExists = existsSync; }); } async function fetchResponseJSON(path) { // On server-side, load the JSON file synchronously from disk. if (import.meta.env.SSR) { try { if (fileExists('dist' + path)) { return JSON.parse(readFileSync('dist' + path)); } } catch (e) { console.error(e); return null; } } else { // Otherwise, in the browser, load it asynchronously via fetch. return fetch(path).then(response => response.json()).catch((e) => { console.error(e); return Promise.reject(e); }); } } function fetchResponseHTML(path) { // On server-side, load the HTML file synchronously from disk. if (import.meta.env.SSR) { try { return readFileSync('dist' + path, 'utf8'); } catch (e) { console.error(e); return null; } } else { // Otherwise, in the browser, load it asynchronously via fetch. return fetch(path).then(response => response.text()).catch((e) => { console.error(e); return Promise.reject(e); }); } } export { fetchResponseJSON, fetchResponseHTML };
import React from 'react' import { WebView } from 'react-native-webview'; import { View, Text } from 'react-native' export default class WebContainer extends React.Component { static navigationOptions = { title: '电子通行证', }; render() { const { navigation } = this.props; const url = navigation.getParam('url'); return ( <WebView startInLoadingState={true} renderLoading={() => <View style={{position: 'absolute', width: '100%', left: 0, top: '30%', textAlign: 'center'}}><Text style={{textAlign: 'center', fontSize: 16}}>数据加载中...</Text></View>} source={{ uri: url }} /> ) } }
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import {Link} from "react-router-dom"; import 'antd/dist/antd.css'; import { Card, Col, Row } from 'antd'; import { Icon } from 'antd'; import BannerAnim from 'rc-banner-anim'; import TweenOne, { TweenOneGroup } from 'rc-tween-one'; const { Element, Arrow, Thumb } = BannerAnim; const BgElement = Element.BgElement; const { Meta } = Card; class Kontak extends React.Component { render(){ return( <Card title="Kontak"> <div style={{ background: '#00000', padding: '20px' }}> <Row gutter={16}> <Col span={12}> <Card bordered={false}> <TweenOne animation={{ y: 30, opacity: 0, type: 'from' }}> <p><Icon type="phone" style={{fontSize: '25px'}} />&emsp; 082234316474</p> <p><Icon type="facebook" style={{fontSize: '25px'}} />&emsp; Miftakhul Jannah</p> <p><Icon type="instagram" style={{fontSize: '25px'}} />&emsp; jannahthn</p> <p><Icon type="google" style={{fontSize: '25px'}} />&emsp; miftakhulj577@gmail.com</p> </TweenOne> </Card> </Col> </Row> </div> </Card> ); } } export default Kontak;
{ function beer_findAll(doc, meta) { if (/^BEER/.test(meta.id)) { emit(meta.id, null); } if (doc.type && doc.type == "beer") { //emit(doc.id,null); emit(doc.name, doc.id) } } function brewery_findAll(doc, meta) { if (/^BREWERY/.test(meta.id)) { emit(meta.id, null); } if(doc.type && doc.type == "brewery") { emit(doc.name, doc.id); } } }
import React, { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; const CardInfoFull = () => { const id = useParams().id; const category = useParams().category; const [infoId, setInfoId] = useState([]); useEffect(() => { const fetchApi = async () => { // Fijate que como la url es "video", category es video tambien y esa no es la url correcta para una pelicula // (es "movie"). Por eso este componente anda con series pero no peliculas. // Si cambiamos la direccion de este componente en los links por /movie, ya funcionaria. const res = await fetch( `https://api.themoviedb.org/3/${category}/${id}?api_key=f56caaebb5b600d34fe93fe163881e2c` ); const data = await res.json(); setInfoId(data); }; fetchApi(); }, []); return ( <> <p>Nombre: {infoId.title || infoId.name}</p> <p>Rating: {infoId.vote_average} </p> </> ); }; export default CardInfoFull;
import VueSocketIO from 'vue-socket.io' export default async ({ Vue }) => { Vue.use(new VueSocketIO({ debug: true, // connection: `ws://${Vue.prototype.$config.server.base_url.replace(/http:\/\//, '')}` connection: Vue.prototype.$config.server.base_url // vuex: { // store, // actionPrefix: 'SOCKET_', // mutationPrefix: 'SOCKET_' // }, // options: { path: '/my-app/' } // Optional options })) }
self.__precacheManifest = [ { "revision": "5d9e4f5cc7cb20abea5b", "url": "/react-image-gallery/static/js/runtime~main.5d9e4f5c.js" }, { "revision": "392b24d14ed8ba6b3ca8", "url": "/react-image-gallery/static/js/main.392b24d1.chunk.js" }, { "revision": "1023a73806f1337a3dc0", "url": "/react-image-gallery/static/js/1.1023a738.chunk.js" }, { "revision": "392b24d14ed8ba6b3ca8", "url": "/react-image-gallery/static/css/main.eeb9ddab.chunk.css" }, { "revision": "ed92767652e7b9c8590cab9ad0c2d90a", "url": "/react-image-gallery/index.html" } ];
import { useEffect, useContext } from "react"; import { AuthData } from "../../data/authData"; import { useHistory } from "react-router"; const SignInCallBack = () => { const { signInRedirectCallback } = useContext(AuthData) const history = useHistory(); useEffect(() => { signInRedirectCallback(); history.push("/"); }, [history, signInRedirectCallback]); return <div>Sign In Redirecting...</div>; }; export default SignInCallBack;
import $ from 'jquery'; export const hideContext = () => { $(".react-contextmenu").css('display', 'none'); } export const unhideContext = () => { $(".react-contextmenu").css('display', 'block'); }
import React from 'react'; function MainMenuCategry({img, text}){ const handleOnMouseEnter = (e) => { e.preventDefault(); e.currentTarget.style.webkitFilter = 'grayscale(0%)'; e.currentTarget.querySelector('a').style.maxHeight = '5rem'; } const handleOnMouseLeave = (e) => { e.preventDefault(); e.currentTarget.style.webkitFilter = 'grayscale(100%)'; e.currentTarget.querySelector('a').style.maxHeight = '0'; } return ( <div className='main-menu-category' onMouseEnter={handleOnMouseEnter} onMouseLeave={handleOnMouseLeave} style ={{backgroundImage: `url(${img})`}}> <a href={'/'}>{text}</a> </div> ) } export default MainMenuCategry;
import React, { useEffect, useState } from "react"; import "./checkout.css"; import { saveProduct, getProductById, deleteProduct } from "../../../api/productApi"; export default function Checkout(props) { console.log(props.match.params.id); const [singleProduct, setSingleProduct] = useState({}); // fetching data from the local database useEffect(() => { getProductById(`/api/getProductsById/${props.match.params.id}`).then( fetchedData => { console.log(fetchedData); setSingleProduct({ ...fetchedData }); // console.log(singleProduct); } ); }, []); return ( <div> <div className="thm-container"> <div className="row"> <h1 style={{color: "black"}}>Checkout</h1> <div className="col-md-8"> <div className="contact-form-content"> {/* /.title */} <img src="https://i.pinimg.com/564x/b0/67/21/b06721c456a32c05c0d264ae2ac3bf21.jpg"/> <div className="form-result" /> {/* /.form-result */} </div> {/* /.contact-form-content */} </div> {/* /.col-md-8 */} <hr /> <div className="col-md-4"> <div className="contact-info text-center"> <div className="title text-center"> <h2>Contact Info</h2> </div> {/* /.title */} <div className="single-contact-info"> <h1 style={{color: "red"}}>Description:</h1> <h3>{singleProduct.description}</h3> </div> {/* /.single-contact-info */} <div className="single-contact-info"> <h1 style={{color: "red"}}>Location:</h1> <h3>{singleProduct.location}</h3> </div> {/* /.single-contact-info */} <div className="single-contact-info"> <h1 style={{color: "red"}}>Email:</h1> <h3>dorrchep@gmail.com</h3> </div> {/* /.single-contact-info */} <div className="single-contact-info"> <h1 style={{color: "red"}}>Contact:</h1><h3> +254 723352844</h3> {/* /.social */} </div> {/* /.single-contact-info */} </div> {/* /.contact-info */} </div> {/* /.col-md-4 */} </div> {/* /.row */} </div> </div> ); }
var DEGREE_TO_RAD = Math.PI / 180; // Order of the groups in the XML document. var INITIALS_INDEX = 0; var ILLUMINATION_INDEX = 1; var LIGHTS_INDEX = 2; var TEXTURES_INDEX = 3; var MATERIALS_INDEX = 4; var ANIMATIONS_INDEX = 5; var NODES_INDEX = 6; var GAMEVISUALS_INDEX = 7; var STOP = false; /** * MySceneGraph class, representing the scene graph. * @constructor */ function MySceneGraph(filename, scene) { this.loadedOk = null; this.filename = filename.replace(/\.xml/g, ''); this.scene = scene; this.nodes = []; this.idRoot = null; // The id of the root element. this.animations = []; this.selectableNodes = []; this.gamevisuals = {}; // Sequential numerical ID for intermediate nodes this.currentNumericID = 0; this.axisCoords = []; this.axisCoords['x'] = [1, 0, 0]; this.axisCoords['y'] = [0, 1, 0]; this.axisCoords['z'] = [0, 0, 1]; // File reading this.reader = new CGFXMLreader(); /* * Read the contents of the xml file, and refer to this class for loading and error handlers. * After the file is read, the reader calls onXMLReady on this object. * If any error occurs, the reader calls onXMLError on this object, with an error message */ this.reader.open('scenes/' + filename, this); } /* * Callback to be executed after successful reading */ MySceneGraph.prototype.onXMLReady = function() { console.log("XML Loading finished."); var rootElement = this.reader.xmlDoc.documentElement; // Here should go the calls for different functions to parse the various blocks var error = this.parseLSXFile(rootElement); if (error != null) { this.onXMLError(error); return; } this.loadedOk = true; //So that first loaded scenario is set as the initial one if(this.scene.scenarioNames[0] === this.filename) this.scene.onGraphLoaded(); } /** * Parses the LSX file, processing each block. */ MySceneGraph.prototype.parseLSXFile = function(rootElement) { if (rootElement.nodeName != "SCENE") return "root tag <SCENE> missing"; var nodes = rootElement.children; // Reads the names of the nodes to an auxiliary buffer. var nodeNames = []; for (var i = 0; i < nodes.length; i++) nodeNames.push(nodes[i].nodeName); var error; // Processes each node, verifying errors. var tags = ["INITIALS", "ILLUMINATION", "LIGHTS", "TEXTURES", "MATERIALS", "ANIMATIONS", "NODES", "GAMEVISUALS"]; var indexes = [INITIALS_INDEX, ILLUMINATION_INDEX, LIGHTS_INDEX, TEXTURES_INDEX, MATERIALS_INDEX, ANIMATIONS_INDEX, NODES_INDEX, GAMEVISUALS_INDEX]; var index; for (let i = 0; i < tags.length; ++i) { if ((index = nodeNames.indexOf(tags[i])) == -1) return "tag <" + tags[i] + "> missing"; else { var indexArg = index; if (index != indexes[i]) { this.onXMLMinorError("tag <" + tags[i] + "> out of order"); indexArg = indexes[i]; //Readjust index so we don't parse the right element with the wrong function } if ((error = this.parseElement(indexArg, nodes[index])) != null) return error; } } } MySceneGraph.prototype.parseElement = function(index, element) { switch (index) { case INITIALS_INDEX: return this.parseInitials(element); case ILLUMINATION_INDEX: return this.parseIllumination(element); case LIGHTS_INDEX: return this.parseLights(element); case TEXTURES_INDEX: return this.parseTextures(element); case MATERIALS_INDEX: return this.parseMaterials(element); case ANIMATIONS_INDEX: return this.parseAnimations(element); case NODES_INDEX: return this.parseNodes(element); case GAMEVISUALS_INDEX: return this.parseGameVisuals(element); } } /** * Parses the <INITIALS> block. */ MySceneGraph.prototype.parseInitials = function(initialsNode) { var children = initialsNode.children; var nodeNames = []; for (var i = 0; i < children.length; i++) nodeNames.push(children[i].nodeName); // Frustum planes. this.near = 0.1; this.far = 500; var indexFrustum = nodeNames.indexOf("frustum"); if (indexFrustum == -1) { this.onXMLMinorError("frustum planes missing. Assuming near=0.1 and far=500"); } else { this.near = this.reader.getFloat(children[indexFrustum], 'near'); this.far = this.reader.getFloat(children[indexFrustum], 'far'); var frustumError = null; if ((frustumError = this.checkNullAndNaN(this.near, "unable to parse value for near plane", "non-numeric value found for near plane")) != null) { this.onXMLMinorError(frustumError+"; defaulting to 0.1"); this.near = 0.1; } if ((frustumError = this.checkNullAndNaN(this.far, "unable to parse value for far plane", "non-numeric value found for far plane")) != null) { this.onXMLMinorError(frustumError+"; defaulting to 500"); this.far = 500; } if (this.near < 0) { this.near = 0.1; this.onXMLMinorError("'near' plane must be positive; clamping to 0.1"); } if (this.near >= this.far) { this.onXMLMinorError("'near' must be smaller than 'far', maybe you accidentally switched them. Swapping values"); let temp = this.near; this.near = this.far; this.far = temp; } } // Checks if at exactly one translation, three rotations, and one scaling are defined. if (initialsNode.getElementsByTagName('translation').length != 1) return "exactly one initial translation must be defined"; if (initialsNode.getElementsByTagName('rotation').length != 3) return "exactly three initial rotations must be defined"; if (initialsNode.getElementsByTagName('scale').length != 1) return "exactly one initial scaling must be defined"; // Initial transforms. this.initialTranslate = []; this.initialScaling = []; this.initialRotations = []; // Gets indices of each element. var translationIndex = nodeNames.indexOf("translation"); var thirdRotationIndex = nodeNames.indexOf("rotation"); var secondRotationIndex = nodeNames.indexOf("rotation", thirdRotationIndex + 1); var firstRotationIndex = nodeNames.lastIndexOf("rotation"); var scalingIndex = nodeNames.indexOf("scale"); // Check initial transformations' order if (translationIndex > thirdRotationIndex || translationIndex > scalingIndex) this.onXMLMinorError("initial translation out of order; result may not be as expected"); if (scalingIndex < firstRotationIndex) this.onXMLMinorError("initial scaling out of order; result may not be as expected"); // Checks if the indices are valid and in the expected order. // Translation. this.initialTransforms = mat4.create(); mat4.identity(this.initialTransforms); var tx = this.reader.getFloat(children[translationIndex], 'x'); var ty = this.reader.getFloat(children[translationIndex], 'y'); var tz = this.reader.getFloat(children[translationIndex], 'z'); var translationError = null; if ((translationError = this.checkNullAndNaN(tx, 'unable to parse x-value of initial translation', 'x-value of initial translation is non-numeric')) != null) { this.onXMLMinorError(translationError+"; defaulting to x = 0, therefore result may be different than expected"); tx = 0; } if ((translationError = this.checkNullAndNaN(ty, 'unable to parse y-value of initial translation', 'y-value of initial translation is non-numeric')) != null) { this.onXMLMinorError(translationError+"; defaulting to y = 0, therefore result may be different than expected"); ty = 0; } if ((translationError = this.checkNullAndNaN(tz, 'unable to parse z-value of initial translation', 'z-value of initial translation is non-numeric')) != null) { this.onXMLMinorError(translationError+"; defaulting to z = 0, therefore result may be different than expected"); tz = 0; } mat4.translate(this.initialTransforms, this.initialTransforms, [tx, ty, tz]); // Rotations. var initialRotations = []; initialRotations['x'] = 0; initialRotations['y'] = 0; initialRotations['z'] = 0; var rotationDefined = []; rotationDefined['x'] = false; rotationDefined['y'] = false; rotationDefined['z'] = false; var axis; var rotationOrder = []; var rotationError = null; // Third rotation (first rotation defined). if ((rotationError = this.parseRotation(children[thirdRotationIndex], initialRotations, rotationDefined, rotationOrder)) != null) this.onXMLMinorError(rotationError+"; skipping"); // Second rotation. if ((rotationError = this.parseRotation(children[secondRotationIndex], initialRotations, rotationDefined, rotationOrder)) != null) this.onXMLMinorError(rotationError+"; skipping"); // First rotation. if ((rotationError = this.parseRotation(children[firstRotationIndex], initialRotations, rotationDefined, rotationOrder)) != null) this.onXMLMinorError(rotationError+"; skipping"); // Checks for undefined rotations. if (!rotationDefined['x']) this.onXMLMinorError("rotation along the Ox axis undefined; assuming Rx = 0"); else if (!rotationDefined['y']) this.onXMLMinorError("rotation along the Oy axis undefined; assuming Ry = 0"); else if (!rotationDefined['z']) this.onXMLMinorError("rotation along the Oz axis undefined; assuming Rz = 0"); // Updates transform matrix. for (var i = 0; i < rotationOrder.length; i++) mat4.rotate(this.initialTransforms, this.initialTransforms, DEGREE_TO_RAD * initialRotations[rotationOrder[i]], this.axisCoords[rotationOrder[i]]); // Scaling. var sx = this.reader.getFloat(children[scalingIndex], 'sx'); var sy = this.reader.getFloat(children[scalingIndex], 'sy'); var sz = this.reader.getFloat(children[scalingIndex], 'sz'); var scalingError = null; if ((scalingError = this.checkNullAndNaN(sx, 'unable to parse x-value of initial scale', 'x-value of initial scale is non-numeric')) != null) { this.onXMLMinorError(scalingError+"; defaulting to sx = 1, therefore result may be different than expected"); sx = 1; } if ((scalingError = this.checkNullAndNaN(sy, 'unable to parse y-value of initial scale', 'y-value of initial scale is non-numeric')) != null) { this.onXMLMinorError(scalingError+"; defaulting to sy = 1, therefore result may be different than expected"); sy = 1; } if ((scalingError = this.checkNullAndNaN(sz, 'unable to parse z-value of initial scale', 'z-value of initial scale is non-numeric')) != null) { this.onXMLMinorError(scalingError+"; defaulting to sz = 1, therefore result may be different than expected"); sz = 1; } mat4.scale(this.initialTransforms, this.initialTransforms, [sx, sy, sz]); // ---------- // Reference length. this.referenceLength = 1; var indexReference = nodeNames.indexOf("reference"); if (indexReference == -1) this.onXMLMinorError("reference length undefined; assuming 'length = 1'"); else { // Reads the reference length. this.referenceLength = this.reader.getFloat(children[indexReference], 'length'); var lengthError = null; if ((lengthError = this.checkNullAndNaN(this.referenceLength, "unable to parse reference length value", "reference length value is non-numeric")) != null) { this.onXMLMinorError(lengthError+"; defaulting to 1"); this.referenceLength = 1; } if (length < 0) this.onXMLMinorError("reference length must be a non-negative value; defaulting to 1"); } console.log("Parsed initials"); return null; } MySceneGraph.prototype.checkNullAndNaN = function(valToCheck, nullError, nanError) { if (valToCheck == null) return nullError; if (isNaN(valToCheck)) return nanError; return null; } MySceneGraph.prototype.parseRotation = function(elem, initialRotations, rotationDefined, rotationOrder) { var axis = this.reader.getItem(elem, 'axis', ['x', 'y', 'z']); if (axis != null) { var angle = this.reader.getFloat(elem, 'angle'); if (angle != null && !isNaN(angle)) { initialRotations[axis] += angle; if (!rotationDefined[axis]) rotationOrder.push(axis); rotationDefined[axis] = true; return null; } else return "failed to parse initial rotation angle"; } return "failed to parse initial rotation axis"; } MySceneGraph.prototype.parseRGBAvalue = function(element, arr, comp, rgba_comp, block) { var parsed = this.reader.getFloat(element, rgba_comp); if (parsed != null) { if (isNaN(parsed)) return comp + " " + rgba_comp + " is a non numeric value on the " + block + " block"; if (parsed < 0 || parsed > 1) return comp + " " + rgba_comp + " must be a value between 0 and 1 on the " + block + " block"; arr.push(parsed); return null; } else return "unable to parse " + rgba_comp + " component of the " + comp + " illumination on the " + block + " block"; } /** * Parses the <ILLUMINATION> block. */ MySceneGraph.prototype.parseIllumination = function(illuminationNode) { var vars = ['r', 'g', 'b', 'a']; // Reads the ambient and background values. var children = illuminationNode.children; var nodeNames = []; for (let i = 0; i < children.length; i++) nodeNames.push(children[i].nodeName); // Retrieves the global ambient illumination. this.ambientIllumination = []; var ambientIndex = nodeNames.indexOf("ambient"); if (ambientIndex != -1) { var ambientError = null; for(let i = 0; i < vars.length; ++i) { if ((ambientError = this.parseRGBAvalue(children[ambientIndex], this.ambientIllumination, "ambient", vars[i], "ILLUMINATION")) != null) { if(i < 3) { this.onXMLMinorError(ambientError+"; defaulting to " + vars[i] + " = 0 therefore result may be different than expected"); this.ambientIllumination.push(0); } else { //'A' component should default to 1 instead of 0 this.onXMLMinorError(ambientError+"; defaulting to " + vars[i] + " = 1 therefore result may be different than expected"); this.ambientIllumination.push(1); } } } } else { this.ambientIllumination.push(0.1, 0.1, 0.1, 1); this.onXMLMinorError("global ambient illumination undefined; assuming Ia = (0.1, 0.1, 0.1, 1)"); } // Retrieves the background clear color. this.background = []; var backgroundIndex = nodeNames.indexOf("background"); if (backgroundIndex != -1) { var backgroundError = null; for(let i = 0; i < vars.length; ++i) { if ((backgroundError = this.parseRGBAvalue(children[backgroundIndex], this.background, "background color", vars[i], "ILLUMINATION")) != null) if(i < 3) { this.onXMLMinorError(backgroundError+"; defaulting to " + vars[i] + " = 0 therefore result may be different than expected"); this.background.push(0); } else { this.onXMLMinorError(backgroundError+"; defaulting to " + vars[i] + " = 1 therefore result may be different than expected"); this.background.push(1); } } } else { this.background.push(0, 0, 0, 1); this.onXMLMinorError("background clear colour undefined; assuming (R, G, B, A) = (0, 0, 0, 1)"); } console.log("Parsed illumination"); return null; } /** * Parses the <LIGHTS> node. */ MySceneGraph.prototype.parseLights = function(lightsNode) { var children = lightsNode.children; this.lights = []; var numLights = 0; var lightProperties = []; var nodeNames = []; // Any number of lights. for (var i = 0; i < children.length; i++) { if (children[i].nodeName != "LIGHT") { this.onXMLMinorError("unknown tag <" + children[i].nodeName + ">"); continue; } // Get id of the current light. var lightId = this.reader.getString(children[i], 'id'); if (lightId == null) return "no ID defined for light"; // Checks for repeated IDs. if (this.lights[lightId] != null) return "ID must be unique for each light (conflict: ID = " + lightId + ")"; lightProperties = children[i].children; // Specifications for the current light. nodeNames = []; for (var j = 0; j < lightProperties.length; j++) { console.log(lightProperties[j].nodeName); nodeNames.push(lightProperties[j].nodeName); } // Gets indices of each element. var enableIndex = nodeNames.indexOf("enable"); var positionIndex = nodeNames.indexOf("position"); var ambientIndex = nodeNames.indexOf("ambient"); var diffuseIndex = nodeNames.indexOf("diffuse"); var specularIndex = nodeNames.indexOf("specular"); // Light enable/disable var enableLight = true; if (enableIndex == -1) { this.onXMLMinorError("enable value missing for ID = " + lightId + "; assuming 'value = 1'"); } else { var aux = this.reader.getFloat(lightProperties[enableIndex], 'value'); if (aux == null) { this.onXMLMinorError("unable to parse value component of the 'enable light' field for ID = " + lightId + "; assuming 'value = 1'"); } else if (isNaN(aux)) this.onXMLMinorError("'enable value' is a non numeric value on the LIGHTS block; defaulting to true"); else if (aux != 0 && aux != 1) this.onXMLMinorError("'enable value' must be 0 or 1 on the LIGHTS block; defaulting to true"); else enableLight = aux == 0 ? false : true; } // Retrieves the light position. var coords = ['x', 'y', 'z', 'w']; var positionLight = []; if (positionIndex == -1) { this.onXMLMinorError("light position undefined for ID = " + lightId+"; skipping light"); continue; } var coordinateError = null; for (let i = 0; i < coords.length; ++i) { let currentCoord = this.reader.getFloat(lightProperties[positionIndex], coords[i]); if ((coordinateError = this.checkNullAndNaN(currentCoord, "unable to parse " + coords[i] + "-coordinate of position for light with ID " + lightId, coords[i] + "-coordinate of position for light with ID " + lightId + " is non-numeric")) != null) { this.onXMLMinorError(coordinateError+"; skipping light"); break; } if (i == 3) { //Parsing 'w' if (currentCoord != 0 && currentCoord != 1) { coordinateError = "w value of light position in light with ID " + lightId + " must be 0 or 1; skipping light"; this.onXMLMinorError(coordinateError); break; } } positionLight.push(currentCoord); } if(coordinateError != null) continue; //Retrieve illumination aspects var vars = ['r', 'g', 'b', 'a']; // Retrieves the ambient component. var ambientIllumination = []; var ambientError = null; if (ambientIndex == -1) { this.onXMLMinorError("ambient component undefined for light with ID " + lightId+"; defaulting to Ia = (0.1, 0.1, 0.1, 1)"); ambientIllumination.push(0, 0, 0, 1); }else{ for (let i = 0; i < vars.length; ++i) { if ((ambientError = this.parseRGBAvalue(lightProperties[ambientIndex], ambientIllumination, "ambient", vars[i], "LIGHTS")) != null) { this.onXMLMinorError(ambientError+"; skipping light"); break; } } } if(ambientError != null) continue; // Retrieves the diffuse component var diffuseIllumination = []; var diffuseError = null; if (diffuseIndex == -1) { this.onXMLMinorError("diffuse component undefined for light with ID " + lightId + "; defaulting to Id = (1, 1, 1, 1)"); diffuseIllumination.push(1, 1, 1, 1); } else { for (let i = 0; i < vars.length; ++i) { if ((diffuseError = this.parseRGBAvalue(lightProperties[diffuseIndex], diffuseIllumination, "diffuse", vars[i], "LIGHTS")) != null) { this.onXMLMinorError(diffuseError + "; skipping current light"); break; } } } if (diffuseError != null) continue; // Retrieves the specular component var specularIllumination = []; var specularError = null; if (specularIndex == -1) { this.onXMLMinorError("specular component undefined for light with ID " + lightID+"; defaulting to Is = (1, 1, 1, 1)"); specularIllumination.push(1, 1, 1, 1); } else{ for (let i = 0; i < vars.length; ++i) { if ((specularError = this.parseRGBAvalue(lightProperties[specularIndex], specularIllumination, "specular", vars[i], "LIGHTS")) != null) { this.onXMLMinorError(specularError+"; skipping current light"); break; } } } if(specularError != null) continue; // Light global information. this.lights[lightId] = [enableLight, positionLight, ambientIllumination, diffuseIllumination, specularIllumination]; numLights++; } if (numLights == 0) return "at least one light must be defined"; else if (numLights > 8) this.onXMLMinorError("too many lights defined; WebGL imposes a limit of 8 lights (some lights will be left out)"); console.log("Parsed lights"); return null; } /** * Parses the <TEXTURES> block. */ MySceneGraph.prototype.parseTextures = function(texturesNode) { this.textures = []; var textureArr = texturesNode.children; for (var i = 0; i < textureArr.length; i++) { var nodeName = textureArr[i].nodeName; if (nodeName != "TEXTURE") { this.onXMLMinorError("unknown tag name <" + nodeName + ">"); continue; } // Retrieves texture ID and checks if it's unique and valid var textureID = this.reader.getString(textureArr[i], 'id'); if (textureID == null) return "failed to parse texture ID"; if (this.textures[textureID] != null) return "texture ID must unique (conflict with ID = " + textureID + ")"; if (textureID === "null" || textureID == "clear") return "texture ID cannot be a keyword (null or clear)"; var texSpecs = textureArr[i].children; var filepath = null; var amplifFactorS = null; var amplifFactorT = null; // Retrieves texture specifications. for (var j = 0; j < texSpecs.length; j++) { var name = texSpecs[j].nodeName; if (name == "file") { if (filepath != null) return "duplicate file paths in texture with ID " + textureID; filepath = this.reader.getString(texSpecs[j], 'path'); if (filepath == null) return "unable to parse texture file path for ID = " + textureID; } else if (name == "amplif_factor") { if (amplifFactorS != null || amplifFactorT != null) return "duplicate amplification factors in texture with ID " + textureID; amplifFactorS = this.reader.getFloat(texSpecs[j], 's'); amplifFactorT = this.reader.getFloat(texSpecs[j], 't'); if (amplifFactorS == null || amplifFactorT == null) { this.onXMLMinorError("unable to parse texture amplification factors for ID " + textureID + "; defaulting to as=at=1, results may be different than expected"); amplifFactorS = 1; amplifFactorT = 1; } else if (isNaN(amplifFactorS)) { this.onXMLMinorError("'amplifFactorS' is a non numeric value for texture with ID " + textureID + "; defaulting to as=1, unexpected results may happen"); amplifFactorS = 1; } else if (isNaN(amplifFactorT)) { this.onXMLMinorError("'amplifFactorT' is a non numeric value for texture with ID " + textureID + "; defaulting to at=1, unexpected results may happen"); amplifFactorT = 1; } else if (amplifFactorS <= 0 || amplifFactorT <= 0) { this.onXMLMinorError("value for amplifFactors must be positive for texture with ID " + textureID + "; defaulting to as=at=1, results may be different than expected"); amplifFactorS = 1; amplifFactorT = 1; } } else this.onXMLMinorError("unknown tag name <" + name + ">"); } var texture = new CGFtexture(this.scene, "./scenes/" + filepath); this.textures[textureID] = [texture, amplifFactorS, amplifFactorT]; } console.log("Parsed textures"); } /** * Parses the <MATERIALS> node. */ MySceneGraph.prototype.parseMaterials = function(materialsNode) { var materialArr = materialsNode.children; this.materials = []; var oneMaterialDefined = false; for (var i = 0; i < materialArr.length; i++) { if (materialArr[i].nodeName != "MATERIAL") { this.onXMLMinorError("unknown tag name <" + materialArr[i].nodeName + ">"); continue; } //Validate material ID var materialID = this.reader.getString(materialArr[i], 'id'); if (materialID == null) return "no ID defined for material"; if (this.materials[materialID] != null) return "ID must be unique for each material (conflict: ID = " + materialID + ")"; if (materialID === "null") return "material ID cannot be keyword null"; var materialSpecs = materialArr[i].children; var nodeNames = []; for (var j = 0; j < materialSpecs.length; j++) nodeNames.push(materialSpecs[j].nodeName); // Determines the values for each field. var vars = ['r', 'g', 'b', 'a']; // Shininess. var shininessIndex = nodeNames.indexOf("shininess"); var shininess; if (shininessIndex == -1) { this.onXMLMinorError("no shininess value defined for material with ID = " + materialID + "; defaulting to n = 1"); shininess = 1; }else{ shininess = this.reader.getFloat(materialSpecs[shininessIndex], 'value'); var shininessError = null; if ((shininessError = this.checkNullAndNaN(shininess, "unable to parse shininess value for material with ID " + materialID, "shininess is a non numeric value")) != null) { this.onXMLMinorError(shininessError + "; defaulting to n = 1"); shininess = 1; } if (shininess <= 0) { this.onXMLMinorError("'shininess' must be positive for material with ID " + materialID + "; defaulting to n = 1"); shininess = 1; } } // Specular component. var specularIndex = nodeNames.indexOf("specular"); if (specularIndex == -1) return "no specular component defined for material with ID = " + materialID; var specularComponent = []; var specularError = null; // Diffuse component. var diffuseIndex = nodeNames.indexOf("diffuse"); if (diffuseIndex == -1) return "no diffuse component defined for material with ID = " + materialID; var diffuseComponent = []; var diffuseError = null; // Ambient component. var ambientIndex = nodeNames.indexOf("ambient"); if (ambientIndex == -1) return "no ambient component defined for material with ID = " + materialID; var ambientComponent = []; var ambientError = null; // Emission component. var emissionIndex = nodeNames.indexOf("emission"); if (emissionIndex == -1) return "no emission component defined for material with ID = " + materialID; var emissionComponent = []; var emissionError = null; for (let i = 0; i < vars.length; ++i) { if ((specularError = this.parseRGBAvalue(materialSpecs[specularIndex], specularComponent, "specular", vars[i], "MATERIALS")) != null) return specularError; if ((diffuseError = this.parseRGBAvalue(materialSpecs[diffuseIndex], diffuseComponent, "diffuse", vars[i], "MATERIALS")) != null) return diffuseError; if ((ambientError = this.parseRGBAvalue(materialSpecs[ambientIndex], ambientComponent, "ambient", vars[i], "MATERIALS")) != null) return ambientError; if ((emissionError = this.parseRGBAvalue(materialSpecs[emissionIndex], emissionComponent, "emission", vars[i], "MATERIALS")) != null) return emissionError; } // Creates material with the specified characteristics. var newMaterial = new CGFappearance(this.scene); newMaterial.setShininess(shininess); newMaterial.setAmbient(ambientComponent[0], ambientComponent[1], ambientComponent[2], ambientComponent[3]); newMaterial.setDiffuse(diffuseComponent[0], diffuseComponent[1], diffuseComponent[2], diffuseComponent[3]); newMaterial.setSpecular(specularComponent[0], specularComponent[1], specularComponent[2], specularComponent[3]); newMaterial.setEmission(emissionComponent[0], emissionComponent[1], emissionComponent[2], emissionComponent[3]); this.materials[materialID] = newMaterial; oneMaterialDefined = true; } if (!oneMaterialDefined) return "at least one material must be defined on the MATERIALS block"; this.generateDefaultMaterial(); console.log("Parsed materials"); } /** * Parses the <ANIMATIONS> block. */ MySceneGraph.prototype.parseAnimations = function(animationsNode) { var children = animationsNode.children; for(let i = 0; i < children.length; ++i) { if(children[i].nodeName != "ANIMATION"){ this.onXMLMinorError("unknown tag <" + children[i].nodeName + ">"); continue; } //Get Animation ID var animationID = this.reader.getString(children[i], 'id'); if (animationID == null) return "failed to retrieve animation ID"; // Checks if ID is valid. if (this.animations[animationID] != null) return "animation ID must be unique (conflict: ID = " + animationID + ")"; console.log("Processing animation " + animationID); var animationType = this.reader.getItem(children[i], 'type', ['linear', 'circular', 'bezier', 'combo']); if (animationType == null) { this.onXMLMinorError("animation type for " + animationID + " unrecognised or couldn't be parsed; skipping"); continue; } var argsError = null; switch(animationType){ case 'circular': let remainingInfo = {}; let attrs = ['speed', 'centerx', 'centery', 'centerz', 'radius', 'startang', 'rotang']; for(let index = 0; index < attrs.length; ++index){ let currVar = this.reader.getFloat(children[i], attrs[index]); if((argsError = this.checkNullAndNaN(currVar, 'unable to parse '+attrs[index]+' value for animation '+animationID, attrs[index]+' for animation '+animationID+' is non numeric')) != null){ this.onXMLMinorError(argsError+'; skipping'); continue; } remainingInfo[attrs[index]] = parseFloat(currVar); } this.animations[animationID] = new MyCircularAnimation(animationID, remainingInfo); break; case 'linear': case 'bezier': let speed = this.reader.getFloat(children[i], 'speed', true); if((argsError = this.checkNullAndNaN(speed, 'unable to parse speed value for animation '+animationID, 'speed for animation '+animationID+' is non numeric')) != null){ this.onXMLMinorError(argsError+'; skipping'); continue; } let cpElement = children[i].children; let controlPoints = []; for(let cpIndex = 0; cpIndex < cpElement.length; ++cpIndex) { if(cpElement[cpIndex].nodeName != "controlpoint"){ this.onXMLMinorError('Unknown tag <'+cpElement[cpIndex].nodeName+'>; expected <controlpoint>; skipping'); continue; } let x = this.reader.getFloat(cpElement[cpIndex], 'xx'); if((argsError = this.checkNullAndNaN(x, 'unable to parse x value for P'+(cpIndex+1)+' for '+animationID, 'P'+(cpIndex+1)+' x for animation '+animationID+' is non numeric')) != null){ this.onXMLMinorError(argsError+'; skipping'); continue; } let y = this.reader.getFloat(cpElement[cpIndex], 'yy'); if((argsError = this.checkNullAndNaN(y, 'unable to parse y value for P'+(cpIndex+1)+' for '+animationID, 'P'+(cpIndex+1)+' y for animation '+animationID+' is non numeric')) != null){ this.onXMLMinorError(argsError+'; skipping'); continue; } let z = this.reader.getFloat(cpElement[cpIndex], 'zz'); if((argsError = this.checkNullAndNaN(z, 'unable to parse z value for P'+(cpIndex+1)+' for '+animationID, 'P'+(cpIndex+1)+' z for animation '+animationID+' is non numeric')) != null){ this.onXMLMinorError(argsError+'; skipping'); continue; } controlPoints.push([x, y, z]); } if(animationType == 'bezier'){ if(controlPoints.length != 4){ this.onXMLMinorError('Not the exact amount of control points for animation '+animationID+'; skipping'); continue; } this.animations[animationID] = new MyBezierAnimation(animationID, speed, controlPoints); } else if(animationType == 'linear'){ if(controlPoints.length < 2){ this.onXMLMinorError('Not enough control points for animation '+animationID+'; skipping'); continue; } this.animations[animationID] = new MyLinearAnimation(animationID, speed, controlPoints); } break; case 'combo': let animationRefs = []; let refsElement = children[i].children; for(let refsIndex = 0; refsIndex < refsElement.length; ++refsIndex) { if(refsElement[refsIndex].nodeName != "SPANREF") { this.onXMLMinorError('unrecognised node name <'+refsElement[refsIndex].nodeName+'>, expected <SPANREF>; skipping'); continue; } let currRef = this.reader.getString(refsElement[refsIndex], 'id'); if(currRef == null) { this.onXMLMinorError('could not parse animation reference for combo animation '+animationID); continue; } animationRefs.push(currRef); } if(!animationRefs.length) { this.onXMLMinorError('combo animation '+animationID+' must have at least one valid animation reference; skipping'); continue; } this.animations[animationID] = new MyComboAnimation(animationID, animationRefs); break; } } var animationRefError = null; if((animationRefError = this.checkAnimations()) != null) return animationRefError; console.log("Parsed animations"); return null; } /** * Checks for any invalid animation references and substitutes IDs for respective object in ComboAnimations */ MySceneGraph.prototype.checkAnimations = function() { for(let animID in this.animations) { if(this.animations[animID] instanceof MyComboAnimation) { for(let j = 0; j < this.animations[animID].animations.length; ++j) { if(this.animations[this.animations[animID].animations[j]] == null) return "Referenced animation "+this.animations[animID].animations[j]+" is not defined"; if(this.animations[this.animations[animID].animations[j]] instanceof MyComboAnimation) return "Combo Animation cannot reference another Combo Animation"; this.animations[animID].animations[j] = this.animations[this.animations[animID].animations[j]]; } this.animations[animID].updateAnimationTime(); //Now that ComboAnimation has the objects instead of IDs, it has access to their animation times } } return null; } /** * Parses the <NODES> block. */ MySceneGraph.prototype.parseNodes = function(nodesNode) { // Traverses nodes. var children = nodesNode.children; for (var i = 0; i < children.length; i++) { var nodeName; if ((nodeName = children[i].nodeName) == "ROOT") { // Retrieves root node. if (this.idRoot != null) return "there can only be one root node"; var root = this.reader.getString(children[i], 'id'); if (root == null) return "failed to retrieve root node ID"; this.idRoot = root; } else if (nodeName == "NODE") { // Retrieves node ID. var nodeID = this.reader.getString(children[i], 'id'); if (nodeID == null) return "failed to retrieve node ID"; // Checks if ID is valid. if (this.nodes[nodeID] != null) return "node ID must be unique (conflict: ID = " + nodeID + ")"; console.log("Processing node " + nodeID); // Creates node. this.nodes[nodeID] = new MyGraphNode(this, nodeID); // Gathers child nodes. var nodeSpecs = children[i].children; var specsNames = []; var possibleValues = ["MATERIAL", "TEXTURE", "TRANSLATION", "ROTATION", "SCALE", "ANIMATIONREFS", "DESCENDANTS"]; for (let j = 0; j < nodeSpecs.length; ++j) { var name = nodeSpecs[j].nodeName; specsNames.push(name); // Warns against possible invalid tag names. if (possibleValues.indexOf(name) == -1) this.onXMLMinorError("unknown tag <" + name + "> for node with ID " + nodeID); } // Retrieves material ID. var materialIndex = specsNames.indexOf("MATERIAL"); if (materialIndex == -1) return "material must be defined (node ID = " + nodeID + ")"; var materialID = this.reader.getString(nodeSpecs[materialIndex], 'id'); if (materialID == null) return "unable to parse material ID (node ID = " + nodeID + ")"; if (materialID != "null" && this.materials[materialID] == null) return "ID does not correspond to a valid material (node ID = " + nodeID + ")"; this.nodes[nodeID].materialID = materialID; // Retrieves texture ID. var textureIndex = specsNames.indexOf("TEXTURE"); if (textureIndex == -1) return "texture must be defined (node ID = " + nodeID + ")"; var textureID = this.reader.getString(nodeSpecs[textureIndex], 'id'); if (textureID == null) return "unable to parse texture ID (node ID = " + nodeID + ")"; if (textureID != "null" && textureID != "clear" && this.textures[textureID] == null) return "ID does not correspond to a valid texture (node ID = " + nodeID + ")"; this.nodes[nodeID].textureID = textureID; var nodeTransformations = nodeSpecs; // Retrieves possible transformations. for (let j = 0; j < nodeTransformations.length; ++j) { var dataError = null; switch (nodeTransformations[j].nodeName) { case "TRANSLATION": // Retrieves translation parameters. var x = this.reader.getFloat(nodeTransformations[j], 'x'); if((dataError = this.checkNullAndNaN(x, "unable to parse x-coordinate for translation in node with ID " + nodeID, "non-numeric value for x-coordinate of translation in node with ID " + nodeID)) != null) { this.onXMLMinorError(dataError+"; skipping translation so unexpected results may happen"); continue; } var y = this.reader.getFloat(nodeTransformations[j], 'y'); if((dataError = this.checkNullAndNaN(y, "unable to parse y-coordinate for translation in node with ID " + nodeID, "non-numeric value for y-coordinate of translation in node with ID " + nodeID)) != null) { this.onXMLMinorError(dataError+"; skipping translation so unexpected results may happen"); continue; } var z = this.reader.getFloat(nodeTransformations[j], 'z'); if((dataError = this.checkNullAndNaN(z, "unable to parse z-coordinate for translation in node with ID " + nodeID, "non-numeric value for z-coordinate of translation in node with ID " + nodeID)) != null) { this.onXMLMinorError(dataError+"; skipping translation so unexpected results may happen"); continue; } mat4.translate(this.nodes[nodeID].transformMatrix, this.nodes[nodeID].transformMatrix, [x, y, z]); break; case "ROTATION": // Retrieves rotation parameters. var axis = this.reader.getItem(nodeTransformations[j], 'axis', ['x', 'y', 'z']); if (axis == null) { this.onXMLMinorError("unable to parse rotation axis in node with ID " + nodeID + "; skipping rotation so unexpected results may happen"); continue; } var angle = this.reader.getFloat(nodeTransformations[j], 'angle'); if((dataError = this.checkNullAndNaN(angle, "unable to parse angle for rotation in node with ID " + nodeID, "non-numeric value for angle of rotation in node with ID " + nodeID)) != null) { this.onXMLMinorError(dataError + "; skipping rotation so unexpected results may happen"); continue; } mat4.rotate(this.nodes[nodeID].transformMatrix, this.nodes[nodeID].transformMatrix, angle * DEGREE_TO_RAD, this.axisCoords[axis]); break; case "SCALE": // Retrieves scale parameters. var sx = this.reader.getFloat(nodeTransformations[j], 'sx'); if((dataError = this.checkNullAndNaN(sx, "unable to parse x-coordinate for scale in node with ID " + nodeID, "non-numeric value for x-coordinate of scale in node with ID " + nodeID)) != null) { this.onXMLMinorError(dataError + "; skipping scale so unexpected results may happen"); continue; } var sy = this.reader.getFloat(nodeTransformations[j], 'sy'); if((dataError = this.checkNullAndNaN(sy, "unable to parse x-coordinate for scale in node with ID " + nodeID, "non-numeric value for y-coordinate of scale in node with ID " + nodeID)) != null) { this.onXMLMinorError(dataError + "; skipping scale so unexpected results may happen"); continue; } var sz = this.reader.getFloat(nodeTransformations[j], 'sz'); if((dataError = this.checkNullAndNaN(sz, "unable to parse x-coordinate for scale in node with ID " + nodeID, "non-numeric value for z-coordinate of scale in node with ID " + nodeID)) != null) { this.onXMLMinorError(dataError + "; skipping scale so unexpected results may happen"); continue; } mat4.scale(this.nodes[nodeID].transformMatrix, this.nodes[nodeID].transformMatrix, [sx, sy, sz]); break; default: break; } } // Retrieves information about possible animations var animationsIndex = specsNames.indexOf("ANIMATIONREFS"); if(animationsIndex != -1) { let refs = nodeSpecs[animationsIndex].children; for(let animIndex = 0; animIndex < refs.length; ++animIndex) { if(refs[animIndex].nodeName != "ANIMATIONREF") continue; let animID = this.reader.getString(refs[animIndex], 'id'); if(animID == null) { this.onXMLMinorError("Could not parse animation reference for node "+nodeID+"; skipping animation"); continue; } if(this.animations[animID] == null) { this.onXMLMinorError("Animation reference by node "+nodeID+" is not defined; skipping animation"); continue; } this.nodes[nodeID].animations.push(animID); if(this.nodes[nodeID].currentAnimation == -1) ++(this.nodes[nodeID].currentAnimation); } } // Retrieves information about children. var descendantsIndex = specsNames.indexOf("DESCENDANTS"); if (descendantsIndex == -1) return "an intermediate node must have descendants"; var descendants = nodeSpecs[descendantsIndex].children; var sizeChildren = 0; for (var j = 0; j < descendants.length; j++) { if (descendants[j].nodeName == "NODEREF") { var curId = this.reader.getString(descendants[j], 'id'); console.log(" Descendant: " + curId); if (curId == null) this.onXMLMinorError("unable to parse descendant id for node with ID " + nodeID + "; skipping"); else if (curId == nodeID) return "a node may not be a child of its own"; else { this.nodes[nodeID].addChild(curId); sizeChildren++; } } else if (descendants[j].nodeName == "LEAF") { var leafInfo = {}; var type = this.reader.getItem(descendants[j], 'type', ['rectangle', 'cylinder', 'sphere', 'triangle', 'patch', 'obj']); if (type == null) { this.onXMLMinorError("leaf type for node " + nodeID + " descendant unrecognised or couldn't be parsed; skipping"); continue; } leafInfo.type = type; console.log(" Leaf: " + type); var argsStr = this.reader.getString(descendants[j], 'args'); var argsFloat = []; var args = argsStr.match(/[+-]?\d+(\.\d+)?/g); //Split numbers from string (integer or decimal) - returns values as strings if(type != 'obj') { for(let m = 0; m < args.length; m++) // Parse args values to float argsFloat[m] = parseFloat(args[m]); } var argsError = null; if((argsError = this.checkLeafArgs(type, argsFloat)) != null) { console.log(argsError + "; skipping"); continue; } leafInfo.args = argsFloat; let controlPoints = []; if (type == 'patch') { let patchChildren = descendants[j].children; for (let k = 0; k < patchChildren.length; k++) { // for each CLINE let currentCPLine = []; for (let index = 0; index < patchChildren[k].children.length; index++) { // for each CPOINT let cPointXX = this.reader.getFloat(patchChildren[k].children[index], 'xx'); let cPointYY = this.reader.getFloat(patchChildren[k].children[index], 'yy'); let cPointZZ = this.reader.getFloat(patchChildren[k].children[index], 'zz'); let cPointWW = this.reader.getFloat(patchChildren[k].children[index], 'ww'); let currentCPoint = [cPointXX, cPointYY, cPointZZ, cPointWW]; currentCPLine[index] = currentCPoint; } controlPoints.push(currentCPLine); } if((argsError = this.checkControlPoints(controlPoints)) != null) { console.log(argsError + "; skipping"); continue; } leafInfo.controlPoints = controlPoints; } if(type == 'obj') { // arg of obj is filename - need unparsed string value leafInfo.args = argsStr; } this.nodes[nodeID].addLeaf(new MyGraphLeaf(this, leafInfo)); this.nodes[nodeID].numericID = this.currentNumericID++; sizeChildren++; } else this.onXMLMinorError("unknown tag <" + descendants[j].nodeName + ">"); } if (sizeChildren == 0) return "at least one descendant must be defined for each intermediate node"; } else this.onXMLMinorError("unknown tag name <" + nodeName); } if(this.nodes[this.idRoot] == null) return "node identified as root not defined (id = " + this.idRoot + ")"; var descendantsError = null; if((descendantsError = this.checkNodesDescendants()) != null) return descendantsError; console.log("Parsed nodes"); return null; } MySceneGraph.prototype.checkNodesDescendants = function() { for(let i = 0; i < this.nodes.length; ++i) { for(let j = 0; j < this.nodes[i].children.length; ++j) { if(this.nodes[this.nodes[i].children[j]] == null) return "node " + this.nodes[i].nodeID + " references descendant node " + this.nodes[i].children[j] + " which is not defined"; } } return null; } MySceneGraph.prototype.checkLeafArgs = function(type, args) { switch(type) { case 'rectangle':{ if(args.length < 4) return "insufficient number of arguments for primitive rectangle"; if(args.length > 4) this.onXMLMinorError("too many arguments for primitive rectangle"); if(args[0] >= args[2] || args[1] <= args[3]) this.onXMLMinorError("unexpected vertices for primitive rectangle, expecting top left followed by bottom right"); return null; } case 'cylinder':{ if(args.length < 5) return "insufficient number of arguments for primitive cylinder"; if(args.length > 7) this.onXMLMinorError("too many arguments for primitive cylinder"); if(args.length == 6) { this.onXMLMinorError("missing top cover boolean arg: defaulting to 1"); args.push(1);} if(args.length == 5) { this.onXMLMinorError("missing cover boolean args: defaulting to 1 1"); args.push(1, 1);} if(args[0] <= 0) return "cylinder dimension args height must be a positive value"; if(args.slice(1, 3).filter(function(a) {return a>=0;}).length != 2) return "cylinder radius values must be non-negative"; if(args.slice(3, 5).filter(function(a) {return a > 0;}).length != 2) return "cylinder slices and stacks must be positive values"; if(args.length > 5 && (args[5] < 0 || args[6] < 0)) return "cylinder cover args must be booleans (0 for false, positive for true)"; return null; } case 'triangle': if(args.length < 9) return "insufficient number of arguments for primitive triangle"; if(args.length > 9) this.onXMLMinorError("too many arguments for primitive triangle"); return null; case 'patch': if(args.length < 2) return "insufficient number of arguments for primitive patch"; if(args.length > 2) this.onXMLMinorError("too many arguments for primitive patch"); if(args.filter(function(a) {return a > 0;}).length < 2) return "patch's number of divisions on each axis must be a positive value"; return null; case 'sphere': if(args.length < 3) return "insufficient number of arguments for primitive sphere"; if(args.length > 3) this.onXMLMinorError("too many arguments for primitive sphere"); if(args.filter(function(a) {return a > 0;}).length < 3) return "sphere args must be positive values"; return null; case 'obj': if(args.length < 0) return "insufficient number of arguments for primitive obj"; if(args.length > 1) this.onXMLMinorError("too many arguments for primitive obj"); return null; } } MySceneGraph.prototype.checkControlPoints = function(elem) { let length = null; for(let i = 0; i < elem.length; ++i) { if(i == 0) length = elem[i].length; else if(elem[i].length != length) return "all CPLINEs must have the same number of CPOINTs"; } return null; } /** * Parses the game visuals properties, i.e board and marker textures, piece materials */ MySceneGraph.prototype.parseGameVisuals = function(node) { let visuals = node.children; for(let i = 0; i < visuals.length; ++i) { switch(visuals[i].nodeName) { case "MARKERTEXTURE": this.gamevisuals.markertexture = new CGFtexture(this.scene, this.reader.getString(visuals[i], 'src')); break; case "BOARDTEXTURE": this.gamevisuals.boardtexture = new CGFtexture(this.scene, this.reader.getString(visuals[i], 'src')); break; case "WHITEMATERIAL": case "BLACKMATERIAL": { var materialSpecs = visuals[i].children; var nodeNames = []; for (var j = 0; j < materialSpecs.length; j++) nodeNames.push(materialSpecs[j].nodeName); // Determines the values for each field. var vars = ['r', 'g', 'b', 'a']; // Shininess. var shininessIndex = nodeNames.indexOf("shininess"); var shininess; if (shininessIndex == -1) { this.onXMLMinorError("no shininess value defined for piece material; defaulting to n = 1"); shininess = 1; }else{ shininess = this.reader.getFloat(materialSpecs[shininessIndex], 'value'); var shininessError = null; if ((shininessError = this.checkNullAndNaN(shininess, "unable to parse shininess value for pieces materials", "shininess is a non numeric value")) != null) { this.onXMLMinorError(shininessError + "; defaulting to n = 1"); shininess = 1; } } // Specular component. var specularIndex = nodeNames.indexOf("specular"); var specularComponent = []; var specularError = null; // Diffuse component. var diffuseIndex = nodeNames.indexOf("diffuse"); var diffuseComponent = []; var diffuseError = null; // Ambient component. var ambientIndex = nodeNames.indexOf("ambient"); var ambientComponent = []; var ambientError = null; // Emission component. var emissionIndex = nodeNames.indexOf("emission"); var emissionComponent = []; var emissionError = null; for (let i = 0; i < vars.length; ++i) { if ((specularError = this.parseRGBAvalue(materialSpecs[specularIndex], specularComponent, "specular", vars[i], visuals[i].nodeName)) != null) return specularError; if ((diffuseError = this.parseRGBAvalue(materialSpecs[diffuseIndex], diffuseComponent, "diffuse", vars[i], visuals[i].nodeName)) != null) return diffuseError; if ((ambientError = this.parseRGBAvalue(materialSpecs[ambientIndex], ambientComponent, "ambient", vars[i], visuals[i].nodeName)) != null) return ambientError; if ((emissionError = this.parseRGBAvalue(materialSpecs[emissionIndex], emissionComponent, "emission", vars[i], visuals[i].nodeName)) != null) return emissionError; } // Creates material with the specified characteristics. var newMaterial = new CGFappearance(this.scene); newMaterial.setShininess(shininess); newMaterial.setAmbient(ambientComponent[0], ambientComponent[1], ambientComponent[2], ambientComponent[3]); newMaterial.setDiffuse(diffuseComponent[0], diffuseComponent[1], diffuseComponent[2], diffuseComponent[3]); newMaterial.setSpecular(specularComponent[0], specularComponent[1], specularComponent[2], specularComponent[3]); newMaterial.setEmission(emissionComponent[0], emissionComponent[1], emissionComponent[2], emissionComponent[3]); if(visuals[i].nodeName === "WHITEMATERIAL") this.gamevisuals.whitematerial = newMaterial; else //BLACKMATERIAL this.gamevisuals.blackmaterial = newMaterial; } } } } /* * Callback to be executed on any read error */ MySceneGraph.prototype.onXMLError = function(message) { console.error("XML Loading Error: " + message); this.loadedOk = false; } /** * Callback to be executed on any minor error, showing a warning on the console. */ MySceneGraph.prototype.onXMLMinorError = function(message) { console.log("Warning: " + message); } /** * Generates a default material, with a random name. This material will be passed onto the root node, which * may override it. */ MySceneGraph.prototype.generateDefaultMaterial = function() { var materialDefault = new CGFappearance(this.scene); materialDefault.setShininess(1); materialDefault.setSpecular(0, 0, 0, 1); materialDefault.setDiffuse(0.5, 0.5, 0.5, 1); materialDefault.setAmbient(0, 0, 0, 1); materialDefault.setEmission(0, 0, 0, 1); // Generates random material ID not currently in use. this.defaultMaterialID = null; do this.defaultMaterialID = MySceneGraph.generateRandomString(5); while (this.materials[this.defaultMaterialID] != null); this.materials[this.defaultMaterialID] = materialDefault; } /** * Generates a random string of the specified length. */ MySceneGraph.generateRandomString = function(length) { // Generates an array of random integer ASCII codes of the specified length // and returns a string of the specified length. var numbers = []; for (var i = 0; i < length; i++) numbers.push(Math.floor(Math.random() * 256)); // Random ASCII code. return String.fromCharCode.apply(null, numbers); } /** * Displays the scene, processing each node, starting in the root node. */ MySceneGraph.prototype.displayScene = function() { // entry point for graph rendering this.nodes[this.idRoot].display('null', this.defaultMaterialID); }
import React, { Component, Fragment } from "react"; import SearchBox from "./SearchBox"; import DataTable from "datatables.net-bs4"; const queryString = require("query-string"); import "datatables.net-buttons"; // import 'datatables.net-buttons-bs4' // import 'datatables.net-buttons/js/buttons.colVis.min' // import 'datatables.net-buttons/js/dataTables.buttons.min' // import 'datatables.net-buttons/js/buttons.flash.min' import "datatables.net-buttons/js/buttons.html5.min"; import "datatables.net-colreorder"; import "datatables.net-fixedheader"; import dLocalTable from "../libs/dtdetail"; import ColumnModal from "../components/column-modal"; import BlockUi from "react-block-ui"; import Link from "next/link"; import Router from "next/router"; import { COMMON_CONSTANT } from "../context/common-context"; class ListDetail extends Component { constructor(props) { super(props); this.hideBlocking = this.hideBlocking.bind(this); this.forceReload = this.forceReload.bind(this); this.state = { blocking: false, ...this.props }; } reloadDataTable = url => { this.dts.ajax.url(url).load(); }; forceReload = async () => {}; hideBlocking = () => { this.setState({ blocking: false }); }; reRederDatatable = () => {}; componentDidMount() { const { columnList, model, dtClickAction, dtButton, saveColumnUrl, dData } = this.props; if (typeof dtClickAction == "function") { this.dtClickAction = dtClickAction; } const _this = this; $.fn.dataTable.ext.errMode = "log"; //var dts = new dTable(this, _this, model, columnList, dataTableUrl); var dts = new dLocalTable(this, _this, model, columnList, dData); dts .on("init preDraw", function() { dts.cells(".dtClickAction").every(function __triggerAction() { const cell = this; const anchor = $(cell.node()).find("a"); const href = anchor.attr("href"); anchor.click(function __actionOnClick(event) { event.preventDefault(); if (_this.dtClickAction) { _this.dtClickAction(href, anchor); } }); }); }) .on("preXhr", function() { _this.setState({ blocking: true }); }) .on("xhr.dt", function(e, settings, json, xhr) { $(".searchRewsultLength").text(json.recordsTotal); _this.hideBlocking(); }) .on("draw", function(e, settings, json, xhr) { $(".datatable tbody tr td:nth-child(1).dt-body-left").each(function(i) { let seq = settings._iDisplayStart + i + 1; let html = $(this).html(); $(this).html(`${html}<div class="row-number">${seq}</div>`); }); $(".datatable tbody tr td:nth-child(n+1)").each(function(i) { let html = $(this).html(); let text = $(this).text(); //if (text.length > 20) { $(this).attr("data-toggle", "tooltip"); $(this).attr("data-title", text); $(this).html(`${html}`); //} }); $(function() { //$('[data-toggle="tooltip"]').tooltip(); }); }); if (typeof dtButton == "function") { dtButton(); } if (typeof saveColumnUrl == "string") { this.columnSorting(dts, columnList, _this, saveColumnUrl); } $(function() { //$('[data-toggle="tooltip"]').popover(); }); } columnSorting = (dts, columns, _this, saveColumnUrl) => { var _this = this; const { menukey } = this.props; let columnListDefault = []; columns .filter(r => r.defaultOrder) .map(r => { columnListDefault.splice(r.defaultOrder - 1, 0, r); }); var sort = this.reSorting(); this.sort = sort; let currentColumn = $(`.column-display-${menukey} #currentColumn`).html(); let allColumn = $(`.column-display-${menukey} #allColumn`).html(); _this.setState({ currentColumn, allColumn }); $(".btn-save-column").on("click", function() { var a = sort.toArray(); if (a.length < 1) { alert("ไม่สามารถบันทึก Column ว่างได้"); return false; } localStorage.removeItem("B2PTable_" + btoa(_this.props.url)); var cols = []; var b = []; for (var aa in a) { let idx = dts.column(columns[a[aa]].name).indexes(); cols.push(columns[a[aa]].title); } $(`.column-display-${menukey} #currentColumn`) .find(".li") .each(function(e) { b.push($(this).data("id")); }); $(`.column-display-${menukey} #allColumn`) .find(".li") .each(function(e) { b.push($(this).data("id")); }); dts.columns().visible(false); dts.columns(a).visible(true, false); $(_this.el).css("width", "100%"); $.post(saveColumnUrl + "?colSeq=" + cols.join()) .done(function(res) { if (res.status == 200) { } else { alert("บันทึกการตั้งค่า Column ผิดพลาดจากระบบ"); } _this.forceReload(); }) .fail(function(err) { alert("ไม่สามารถบันทึกการตั้งค่า Column ได้"); }); }); $("body").on("click", "button.add-all", function() { $(this) .removeClass("add") .addClass("disabled"); var element = $(`.column-display-${menukey} #allColumn`).each(function() { var li_element = $(this).html(); $(`.column-display-${menukey} #currentColumn`).append(li_element); }); $(`.column-display-${menukey} #allColumn`) .find(".li") .remove(); $(`.column-display-${menukey} #currentColumn`) .find(".li button") .removeClass("add") .addClass("remove"); }); $("body").on("click", "button.remove-all", function() { $(`.column-display-${menukey} #currentColumn li`).each(function() { var li_element = $(this); if (li_element.length == 1) { $(`.column-display-${menukey} #allColumn`).append( '<li data-id="' + li_element.data("id") + '" class="' + li_element.attr("class") + '" id="' + li_element.attr("id") + '" data-name="' + li_element.attr("data-name") + '">' + li_element.html() + "</li>" ); $(this).remove(); } }); columnListDefault.map(function(r) { var li_element = $( `.column-display-${menukey} #allColumn li#${r.data.replace( COMMON_CONSTANT.REGEX_ID_HTML, "_" )}` ); if (li_element.length == 1) { $(`.column-display-${menukey} #currentColumn`).append( '<li data-id="' + li_element.data("id") + '" class="' + li_element.attr("class") + '" id="' + li_element.attr("id") + '" data-name="' + li_element.attr("data-name") + '">' + li_element.html() + "</li>" ); li_element.remove(); } }); $(`.column-display-${menukey} #currentColumn`) .find(".li button") .removeClass("add") .addClass("remove"); $(`.column-display-${menukey} #allColumn`) .find(".li button") .removeClass("remove") .addClass("add"); }); $("body").on( "click", `.column-display-${menukey} #allColumn button`, function() { $(this) .removeClass("add") .addClass("remove"); var element = $(this).parents(".li"); var target = $(`.column-display-${menukey} #currentColumn`); target.append( '<li data-id="' + element.data("id") + '" class="' + element.attr("class") + '" id="' + element.attr("id") + '" data-name="' + element.attr("data-name") + '">' + element.html() + "</li>" ); $(this) .parents(".li") .remove(); } ); $("body").on( "click", `.column-display-${menukey} #currentColumn .li:not(".fixed") button`, function() { var element = $(this).parents(".li"); var ul = element.parents("ul"); if (ul === undefined) { return false; } if (ul.find("li").length < 2) { alert("คุณไม่สามารถลบ Column ทั้งหมดได้"); return false; } $(this) .removeClass("remove") .addClass("add"); var target = $(`.column-display-${menukey} #allColumn`); target.append( '<li data-id="' + element.data("id") + '" class="' + element.attr("class") + '" id="' + element.attr("id") + '" data-name="' + element.attr("data-name") + '">' + element.html() + "</li>" ); $(this) .parents(".li") .remove(); } ); $(window).on("scroll", function() { let fix = $(".fixedHeader-floating"); if (fix.length > 0) { $(".fixedHeader-floating").css("width", $(".table__wrapper").width()); $(".fixedHeader-floating").scrollLeft( $(".dataTables_scrollBody").scrollLeft() ); } }); $(".dataTables_scrollBody").scroll(function() { $(".fixedHeader-floating").scrollLeft($(this).scrollLeft()); $(".fixedHeader-floating").css("width", $(".table__wrapper").width()); }); this.dts = dts; }; componentWillUnmount() { $("body").unbind("click"); } render() { const { title, breadcrumb, showSearchbox, columnList } = this.props; return ( <Fragment> <BlockUi tag="div" blocking={this.state.blocking}> <div className="table_wrapper table-responsive"> <table className="table datatable" ref={el => (this.el = el)} /> </div> </BlockUi> <ColumnModal title="Column List" columnList={columnList} {...this.props} {...this.state} /> </Fragment> ); } } export default ListDetail;
var str = 'some text'; function displayVariable(str) { return str; } console.log(str);
import { useState, useEffect } from 'react'; import axios from 'axios'; import styles from '../../styles/Blog.module.css'; import Link from 'next/link'; import { useTransition, animated, config } from 'react-spring'; const BlogPost = ({ props: { post } }) => { return ( <div className='blogpost'> <Link href={`/post/${post._id}`}> <h3 className='title'>{post.title}</h3> </Link> <p>{post.author.name}</p> <p className='date'> <span>{new Date(post.createdAt).toLocaleDateString()}, </span> <span>{new Date(post.createdAt).toLocaleTimeString()}</span> </p> <p className='content'>{post.content}</p> <div className={styles.tags}> {post.tags.map((tag) => ( <p key={tag} className={styles.tag}> #{tag} </p> ))} </div> </div> ); }; export default function Feed() { const [blogPosts, setBlogPosts] = useState([]); const [offset, setOffset] = useState(0); const [showNextBtn, setShowNextBtn] = useState(true); const fetchPosts = (inc) => { axios .get('/api/feed', { skip: offset + inc }) .then(({ data }) => { if (inc === -1) setShowNextBtn(true); if (inc === 1 && data[0]._id === blogPosts[0]._id) { setShowNextBtn(false); } else { setBlogPosts(data); } setOffset((o) => o + inc); }) .catch((err) => console.log(err)); }; useEffect(()=> { fetchPosts(0) }, []) const animation = useTransition(blogPosts, (item) => item._id, { from: { opacity: '0', transform: 'translateY(-100px)' }, enter: { opacity: '1', transform: 'translateY(0px)' }, trail: 520, config: config.wobbly, }); return ( <div className={styles.blog}> <h2>Feed</h2> {animation.map(({ item, props, key }) => { return ( <animated.div style={props} key={key}> <BlogPost props={{ post: item }} /> </animated.div> ); })} <button className={`${styles.btn} ${offset <= 0 && styles.btnInactive}`} onClick={() => offset > 0 && fetchPosts(-1)} > prev </button> <button className={`${styles.btn} ${!showNextBtn && styles.btnInactive}`} onClick={() => showNextBtn && fetchPosts(1)} > next </button> </div> ); }
/* * Author: Abdullah A Almsaeed * Date: 4 Jan 2014 * Description: * This is a demo file used only for the main dashboard (index.html) **/ /* global moment:false, Chart:false, Sparkline:false */ $(function () { 'use strict' // Get context with jQuery - using jQuery's .get() method. //var areaChartCanvas = $('#areaChart').get(0).getContext('2d') var areaChartData = { labels : ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho'], datasets: [ { label : 'Imóveis Penhorados', backgroundColor : 'rgba(60,141,188,0.9)', borderColor : 'rgba(60,141,188,0.8)', pointRadius : false, pointColor : '#3b8bba', pointStrokeColor : 'rgba(60,141,188,1)', pointHighlightFill : '#fff', pointHighlightStroke: 'rgba(60,141,188,1)', data : [28, 48, 40, 19, 86, 27, 90] }, { label : 'Imóveis para Negociacao', backgroundColor : 'rgba(210, 214, 222, 1)', borderColor : 'rgba(210, 214, 222, 1)', pointRadius : false, pointColor : 'rgba(210, 214, 222, 1)', pointStrokeColor : '#c1c7d1', pointHighlightFill : '#fff', pointHighlightStroke: 'rgba(220,220,220,1)', data : [65, 59, 80, 81, 56, 55, 40] }, ] } var areaChartOptions = { maintainAspectRatio : false, responsive : true, legend: { display: true }, scales: { xAxes: [{ gridLines : { display : true, } }], yAxes: [{ gridLines : { display : true, } }] } } //------------- //- LINE CHART - //-------------- var lineChartCanvas = $('#lineChart').get(0).getContext('2d') var lineChartOptions = $.extend(true, {}, areaChartOptions) var lineChartData = $.extend(true, {}, areaChartData) lineChartData.datasets[0].fill = false; lineChartData.datasets[1].fill = false; lineChartOptions.datasetFill = false var lineChart = new Chart(lineChartCanvas, { type: 'line', data: lineChartData, options: lineChartOptions }) var donutData = { labels: [ 'Tipo A', 'Tipo B', 'Tipo C', 'Tipo D' ], datasets: [ { data: [700,350,100,5], backgroundColor : ['#f56954', '#00a65a', '#f39c12', '#00c0ef'], } ] } var donutOptions = { maintainAspectRatio : false, responsive : true, } //------------- //- PIE CHART - //------------- // Get context with jQuery - using jQuery's .get() method. var pieChartCanvas = $('#pieChart').get(0).getContext('2d') var pieData = donutData; var pieOptions = { maintainAspectRatio : false, responsive : true, } //Create pie or douhnut chart // You can switch between pie and douhnut using the method below. var pieChart = new Chart(pieChartCanvas, { type: 'pie', data: pieData, options: pieOptions }) })
(function() { function Message($firebaseArray) { var ref = firebase.database().ref().child("messages"); var messages = $firebaseArray(ref); return { getByRoomId: function(roomId) { var list; ref.orderByChild('roomId').equalTo(roomId).on('value', function(d){ list = d.val(); }); console.log(list[1]); console.log('first: ' + list[0]) return list.splice(1, list.length); } }; } angular .module('blocChat') .factory('Message', ['$firebaseArray', Message ]); })();
var TypeConverter = function(){ } module.exports = TypeConverter; TypeConverter.convert = function(value, type, defaultVal){ if (value == null) return defaultVal; valStr = value.toString(); if (type == "integer") return parseInt(valStr); else if (type == "string") return valStr; else if (type == "number") return parseFloat(valStr); else return value; }
const test = require("ava"); const nock = require("nock"); const request = require("supertest"); const expressApp = require("./testApp")(); test("first request has correct context", t => { t.plan(1); const NUMBER = 6; const REQUEST_ID = "abc-456"; nock("http://mytestdomain.com") .get("/number") .reply(200, { number: NUMBER }); return request(expressApp) .get("/my/test/route") .set("X-Request-Id", REQUEST_ID) .expect(200) .then(response => { t.deepEqual(response.body, { "request-id": REQUEST_ID, "http-response": NUMBER, "timedout-answer": 42 }); }); }); test("second request has correct context", t => { t.plan(1); const NUMBER = 5; const REQUEST_ID = "abc-123"; nock("http://mytestdomain.com") .get("/number") .reply(200, { number: NUMBER }); return request(expressApp) .get("/my/test/route") .set("X-Request-Id", REQUEST_ID) .expect(200) .then(response => { t.deepEqual(response.body, { "request-id": REQUEST_ID, "http-response": NUMBER, "timedout-answer": 42 }); }); });
module.exports.items=[1,2,3,4] person={'name':'bob', 'age':20,} module.exports.singlePerson=person
import transactionSelector from 'selectors/transaction' describe('selectors - transaction', () => { it('returns the transaction item for the given id and null otherwise', () => { const state = { transactions: { items: { transactionA: { id: 'transactionA' } } } } expect(transactionSelector(state, 'transactionA')).toEqual({ id: 'transactionA' }) expect(transactionSelector(state, 'transactiona')).toBeNull() }) })
export const drawCard = (G, ctx, player, amount = 1) => { for (let i = 0; i < amount; i++) { if (G.players[player].deck.length != 0) { let card = G.players[player].deck.pop(); G.players[player].hand.push(card); } } };
import React from 'react'; import PropTypes from 'prop-types'; const MIN_SCALE = 0.25; const MAX_SCALE = 8; const SETTLE_RANGE = 0.1; const ADDITIONAL_LIMIT = 0.2; const DOUBLE_TAP_THRESHOLD = 300; const ANIMATION_SPEED = 0.4; const RESET_ANIMATION_SPEED = 0.8; const INITIAL_X = 0; const INITIAL_Y = 0; const INITIAL_SCALE = 1; const X_TOLERANCE = 15; const Y_TOLERANCE = 15; const SCALE_FACTOR = 0.03; const settle = (val, target, range) => { const lowerRange = val > target - range && val < target; const upperRange = val < target + range && val > target; return lowerRange || upperRange ? target : val; }; const inverse = (x) => x * -1; const getPointFromTouch = (touch, element) => { const rect = element.getBoundingClientRect(); return { x: touch.clientX - rect.left, y: touch.clientY - rect.top, }; }; const getMidpoint = (pointA, pointB) => ({ x: (pointA.x + pointB.x) / 2, y: (pointA.y + pointB.y) / 2, }); const getDistanceBetweenPoints = (pointA, pointB) => ( Math.sqrt(Math.pow(pointA.y - pointB.y, 2) + Math.pow(pointA.x - pointB.x, 2)) ); const between = (min, max, value) => Math.min(max, Math.max(min, value)); const getEventPosition = (e) => { const x = typeof e.clientX === 'undefined' ? e.changedTouches[0].clientX : e.clientX; const y = typeof e.clientY === 'undefined' ? e.changedTouches[0].clientY : e.clientY; return new Point(x, y); } class Point extends Array { //static get [Symbol.species]() { return Point; } get x() { return this[0]; } //get x() => this[0]; //get x() { return this[0]; } set x(x) { this[0] = x; } get y() { return this[1]; } set y(y) { this[1] = y; } get z() { return this[2]; } set z(z) { this[2] = z; } get w() { return this[3]; } set w(w) { this[3] = w; } add(x, y, z, w) { if(x instanceof Point) { return this.map((val, i) => val + x[i]); } else { return this.map((val, i) => val + this.arguments[i]); } } subtract(x, y, z, w) { if(x instanceof Point) { return this.map((val, i) => val - x[i]); } else { return this.map((val, i) => val - this.arguments[i]); } } multiply(s) { // if(!(s instanceof Number)) { if(isNaN(s)) { throw new TypeError("Points can only be multiplied by scalar numbers"); } return this.map((val) => val * s); } divide(s) { if(isNaN(s)) { throw new TypeError("Points can only be divided by scalar numbers"); } return this.map((val) => val / s); } // clone() {} // equals() {} // ... } class PinchZoomPan extends React.Component { constructor() { super(...arguments); this.state = this.getInititalState(); // get autobind working this.handleTouchStart = this.handleTouchStart.bind(this); this.handleTouchMove = this.handleTouchMove.bind(this); this.handleTouchEnd = this.handleTouchEnd.bind(this); this.handleMouseDown = this.handleMouseDown.bind(this); this.handleMouseMove = this.handleMouseMove.bind(this); this.handleMouseUp = this.handleMouseUp.bind(this); this.handleWheel = this.handleWheel.bind(this); } zoomTo(scale, midpoint) { const frame = () => { if (this.state.scale === scale) return null; const distance = scale - this.state.scale; const targetScale = this.state.scale + (ANIMATION_SPEED * distance); this.zoom(settle(targetScale, scale, SETTLE_RANGE), midpoint); this.animation = requestAnimationFrame(frame); }; this.animation = requestAnimationFrame(frame); } reset() { const frame = () => { if (this.state.scale === INITIAL_SCALE && this.state.x === INITIAL_X && this.state.y === INITIAL_Y) return null; const distance = INITIAL_SCALE - this.state.scale; const distanceX = INITIAL_X - this.state.x; const distanceY = INITIAL_Y - this.state.y; const targetScale = settle(this.state.scale + (RESET_ANIMATION_SPEED * distance), INITIAL_SCALE, SETTLE_RANGE); const targetX = settle(this.state.x + (RESET_ANIMATION_SPEED * distanceX), INITIAL_X, SETTLE_RANGE); const targetY = settle(this.state.y + (RESET_ANIMATION_SPEED * distanceY), INITIAL_Y, SETTLE_RANGE); const nextWidth = this.props.width * targetScale; const nextHeight = this.props.height * targetScale; this.setState({ x: targetX, y: targetY, scale: targetScale, width: nextWidth, height: nextHeight, translate: new Point(targetX, targetY), }, () => { this.animation = requestAnimationFrame(frame); }); }; this.animation = requestAnimationFrame(frame); } getInititalState() { return { x: INITIAL_X, y: INITIAL_Y, scale: INITIAL_SCALE, width: this.props.width, height: this.props.height, translate: new Point(INITIAL_X, INITIAL_Y), dragging: false, dragged: false }; } handleTouchStart(event) { this.animation && cancelAnimationFrame(this.animation); if (event.touches.length === 2) this.handlePinchStart(event); if (event.touches.length === 1) this.handleTapStart(event); } handleTouchMove(event) { if (event.touches.length === 2) this.handlePinchMove(event); if (event.touches.length === 1) this.handlePanMove(event); } handleTouchEnd(event) { if (event.touches.length > 0) return null; if (this.state.scale > MAX_SCALE) return this.zoomTo(MAX_SCALE, this.lastMidpoint); if (this.state.scale < MIN_SCALE) return this.zoomTo(MIN_SCALE, this.lastMidpoint); if (this.lastTouchEnd && this.lastTouchEnd + DOUBLE_TAP_THRESHOLD > event.timeStamp) { this.reset(); } this.lastTouchEnd = event.timeStamp; } handleTapStart(event) { this.lastPanPoint = getPointFromTouch(event.touches[0], this.container); } handlePanMove(event) { if (this.state.scale === 1) return null; event.preventDefault(); const point = getPointFromTouch(event.touches[0], this.container); const nextX = this.state.x + point.x - this.lastPanPoint.x; const nextY = this.state.y + point.y - this.lastPanPoint.y; this.setState({ x: between(this.props.width - this.state.width, 0, nextX), y: between(this.props.height - this.state.height, 0, nextY), }); this.lastPanPoint = point; } handlePinchStart(event) { const pointA = getPointFromTouch(event.touches[0], this.container); const pointB = getPointFromTouch(event.touches[1], this.container); this.lastDistance = getDistanceBetweenPoints(pointA, pointB); } handlePinchMove(event) { event.preventDefault(); const pointA = getPointFromTouch(event.touches[0], this.container); const pointB = getPointFromTouch(event.touches[1], this.container); const distance = getDistanceBetweenPoints(pointA, pointB); const midpoint = getMidpoint(pointA, pointB); const scale = between(MIN_SCALE - ADDITIONAL_LIMIT, MAX_SCALE + ADDITIONAL_LIMIT, this.state.scale * (distance / this.lastDistance)); this.zoom(scale, midpoint); this.lastMidpoint = midpoint; this.lastDistance = distance; } zoom(scale, midpoint) { const nextWidth = this.props.width * scale; const nextHeight = this.props.height * scale; const nextX = this.state.x + (inverse(midpoint.x * scale) * (nextWidth - this.state.width) / nextWidth); const nextY = this.state.y + (inverse(midpoint.y * scale) * (nextHeight - this.state.height) / nextHeight); this.setState({ width: nextWidth, height: nextHeight, x: nextX, y: nextY, scale, }); } handleMouseDown(e) { // Find start position of drag based on touch/mouse coordinates. const start = getEventPosition(e); // Update state with above coordinates, and set dragging to true. // const state = { this.setState({ start: start, init: start, last: start, dragging: true, dragged: false, }); } handleMouseMove(e) { // First check if the state is dragging, if not we can just return // so we do not move unless the user wants to move if (!this.state.dragging) { return; } const current = getEventPosition(e); if ( this.state.dragged // This conditional should be moved to the handleTouchMove function // (a mouse pointer doesn't usuallly need tolerance to differentiate // between a click and a drag) || Math.abs(Math.max(...current.subtract(this.state.start))) > X_TOLERANCE ) { this.setState({ dragged: true, ...this.panM( current, this.state.last, this.state.translate ) }); } } panM(current, last, translate) { // Subtract the current Event Point from the last Event Point const delta = current.subtract(last); // Add the delta to the current Translation const next = translate.add(delta); // Return the current Event Point as the new last Event Point // and the next Translate Point as the new current Translate Point //console.log({current, last, translate, delta, next}) return { last: current, translate: next, x: next.x, y: next.y, }; } handleMouseUp(e) { this.setState({dragging: false}); if(this.state.dragged) { e.stopPropagation(); } } handleWheel(e) { const current = getEventPosition(e); //console.log(current); this.setState( this.zoomM( current, e.deltaY, // get rid of. Use SCALE_FACTOR instead this.state.translate, this.state.scale ) ) } zoomM(current, delta, translate, scale) { //const ratio = (1 - (scale - delta * SCALE_FACTOR) / scale); const nextScale = scale + (-delta) * SCALE_FACTOR; const ratio = (1 - nextScale / scale); const next = translate.add( current .subtract(translate) .multiply(ratio) ); //console.log({next, nextScale, scale, delta, SCALE_FACTOR, ratio}); return { translate: next, scale: nextScale, x: next.x, y: next.y, } } render() { //console.log(this.state); return ( <g ref={(ref) => this.container = ref} onTouchStart={this.handleTouchStart} onTouchMove={this.handleTouchMove} onTouchEnd={this.handleTouchEnd} onMouseDown={this.handleMouseDown} onMouseMove={this.handleMouseMove} onMouseUp={this.handleMouseUp} onWheel={this.handleWheel} style={{ overflow: 'hidden', width: this.props.width, height: this.props.height, }} > {this.props.children(this.state.x, this.state.y, this.state.scale, this.state.dragging, this.state.dragged)} </g> ); } } PinchZoomPan.propTypes = { children: PropTypes.func.isRequired, }; export default PinchZoomPan;