text
stringlengths
7
3.69M
define(function(require, exports, module) { var $ = require('jquery'); var chart = require('./chart.js'); module.exports = { init: function() { var parentObj = 'base'; //顶部菜单点击事件 $('.dtm-tabh-h li').unbind('click').bind('click', function(event) { tabh = $(this).data('cpt-tabh'); if(tabh == 'chartConfigurer' && $(this).hasClass('dtm-tabh-hi-curr')) { return; } if(tabh == 'chartConfigurer') { if(!chart.loadData(module.exports)) { return; } } if(tabh == 'extendJs') { //chart.initCode(); setTimeout(function(){chart.initCode();}, 10); } $('.dtm-tabh-h li').removeClass('dtm-tabh-hi-curr'); $(this).addClass('dtm-tabh-hi-curr'); $('div[data-cpt-conh]').hide(); $('[data-cpt-conh="'+tabh+'"]').show(); }); //一级菜单点击事件 $('.dtm-tab0 li').unbind('click').bind('click', function(event) { parentObj = $(this).data('cpt-tab0'); $('.dtm-tab0 li').removeClass('dtm-tab0-hi-curr'); $(this).addClass('dtm-tab0-hi-curr'); $('div[data-cpt-con0]').hide(); $('[data-cpt-con0="'+parentObj+'"]').show(); }); //二级菜单点击事件 $('div[data-cpt-tab1]').unbind('click').bind('click', function(event) { var childObj = $(this).data('cpt-tab1'); $('[data-cpt-con0="'+parentObj+'"] div[data-cpt-tab1]').removeClass('dtm-tab1-hi-curr'); $(this).addClass('dtm-tab1-hi-curr'); $('[data-cpt-con0="'+parentObj+'"] div[data-cpt-con1]').hide(); $('[data-cpt-con0="'+parentObj+'"] [data-cpt-con1="'+childObj+'"]').show(); }); //表单标题点击事件,启动或者关闭项 /* $('div[data-dsp]').unbind('click').bind('click', function(event) { if($(this).parent().hasClass('cpt-disabled')) { $(this).parent().removeClass('cpt-disabled'); $(this).parent().removeClass('cpt-ggt-edtitm-disabled'); $(this).parent().removeClass('dtm-edtitm-disabled'); $(this).parent().find('div').removeClass('cpt-disabled'); $(this).parent().find('div').removeClass('cpt-sltggt-disabled'); $(this).parent().find('div').removeClass('dtm-edtitm-ggt-disabled'); $(this).parent().find('div').removeClass('cpt-chkbtn-disabled'); chart.setOption(this, true); } else { $(this).parent().addClass('cpt-disabled'); $(this).parent().addClass('cpt-ggt-edtitm-disabled'); $(this).parent().addClass('dtm-edtitm-disabled'); $(this).parent().find('div').addClass('cpt-disabled'); $(this).parent().find('div').addClass('cpt-sltggt-disabled'); $(this).parent().find('div').addClass('dtm-edtitm-ggt-disabled'); $(this).parent().find('div').addClass('cpt-chkbtn-disabled'); chart.setOption(this, false); } }); */ //单选按钮点击事件 $('.cpt-chkbtn-i').unbind('click').bind('click', function(event) { if($(this).parent().hasClass('cpt-disabled')) return; $(this).siblings('div').removeClass('cpt-chkbtn-i-active'); $(this).addClass('cpt-chkbtn-i-active'); chart.setOption(this, false, 'btn'); }); //输入框改变事件 $(':input').unbind('change').bind('change', function(event) { chart.setOption(this, false, 'ipt'); }); module.exports.renderData(); }, createSeries: function(seriesArr) { var index = $('#legend-div div[data-cpt-con1]').length; var content = ''; $.get(ctx+'/static/tushuo/static/gauge/tpl/legend.tpl').success(function(ctnt) { //$('#legend-div').append(content); content = ctnt; }).error(function (XMLHttpRequest, textStatus, errorThrown) { content = XMLHttpRequest.responseText; }).complete(function () { var menu1 = ' dtm-tab1-hi-curr'; var display = 'block'; for(var i=0; i<seriesArr.length; i++) { var series = seriesArr[i]; var seriesKey = series.zkey; var seriesName = series.name; if(module.exports.checkSeries(seriesKey)) { continue; } var c = content; $('#legend-menu').append('<div data-cpt-tab1="seriesTabKey'+seriesKey+'" class="cpt cpt-foreach-item dtm-tab1-hi'+menu1+'">系列'+(index++)+'</div>'); while(c.indexOf('$$key$$') != -1) { c = c.replace('$$key$$', seriesKey); } c = c.replace('$$name$$', seriesName); c = c.replace('$$display$$', display); $('#legend-div').append(c); menu1 = ''; display = 'none'; } module.exports.init(); }); }, checkSeries: function(zkey) { if($('#legend-div div[data-cpt-con1]').length == 0) { return false; } var divArr = $('#legend-div div[data-cpt-con1]'); for(var i=0; i<divArr.length; i++) { if($(divArr[i]).data('cpt-con1') == ('seriesTabKey'+zkey)) { return true; } } return false; }, renderData: function() { if(chartOpt != null) { this.renderSeries(); this.renderTitle(); this.renderLegend(); this.renderTooltip(); this.renderToolbox(); } }, renderSeries: function() { var seriesArr = chartOpt.series; for(var i=0; i<seriesArr.length; i++) { var series = seriesArr[i]; if(series.type == 'gauge') { if(series.clockwise != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('div[data-cate="clockwise"]').removeClass('cpt-chkbtn-i-active'); $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('div[data-type="clockwise.'+series.clockwise+'"]').addClass('cpt-chkbtn-i-active'); } if(series.center != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="center0"]').val(series.center[0].replace('%','')); $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="center1"]').val(series.center[1].replace('%','')); } if(series.radius != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="radius"]').val(series.radius.replace('%','')); } if(series.startAngle != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="startAngle"]').val(series.startAngle); } if(series.endAngle != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="endAngle"]').val(series.endAngle); } if(series.min != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="min"]').val(series.min); } if(series.max != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="max"]').val(series.max); } if(series.splitNumber != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="splitNumber"]').val(series.splitNumber); } if(series.axisTick.show != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('div[data-cate="axisTick.show"]').removeClass('cpt-chkbtn-i-active'); $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('div[data-type="axisTick.show.'+series.axisTick.show+'"]').addClass('cpt-chkbtn-i-active'); } if(series.splitLine.show != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('div[data-cate="splitLine.show"]').removeClass('cpt-chkbtn-i-active'); $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('div[data-type="splitLine.show.'+series.splitLine.show+'"]').addClass('cpt-chkbtn-i-active'); } if(series.title.show != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('div[data-cate="title.show"]').removeClass('cpt-chkbtn-i-active'); $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('div[data-type="title.show.'+series.title.show+'"]').addClass('cpt-chkbtn-i-active'); } if(series.title.offsetCenter != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="title.offsetCenter0"]').val(series.title.offsetCenter[0].replace('%','')); $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="title.offsetCenter"]').val(series.title.offsetCenter[1].replace('%','')); } if(series.pointer.length != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="pointer.length"]').val(series.pointer.length.replace('%','')); } if(series.pointer.width != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="pointer.width"]').val(series.pointer.width); } if(series.axisLine.lineStyle.width != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="axisLine.lineStyle.width"]').val(series.axisLine.lineStyle.width); } if(series.axisLine.lineStyle.color != null) { $('div[data-cpt-con1="seriesTabKey'+series.zkey+'"]').find('input[data-type="axisLine.lineStyle.color"]').val(JSON.stringify(series.axisLine.lineStyle.color)); } } } }, renderTitle: function() { var title = chartOpt.title; if(title.text != null) { $('input[data-type="title.text"]').val(title.text); } if(title.link != null) { $('input[data-type="title.link"]').val(title.link); } if(title.subtext != null) { $('input[data-type="title.subtext"]').val(title.subtext); } if(title.sublink != null) { $('input[data-type="title.sublink"]').val(title.sublink); } if(title.x != null) { $('div[data-cate="title.x"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="title.x.'+title.x+'"]').addClass('cpt-chkbtn-i-active'); } if(title.y != null) { $('div[data-cate="title.y"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="title.y.'+title.y+'"]').addClass('cpt-chkbtn-i-active'); } }, renderLegend: function() { var legend = chartOpt.legend; if(legend.show != null) { $('div[data-cate="legend.show"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="legend.show.'+legend.show+'"]').addClass('cpt-chkbtn-i-active'); } if(legend.x != null) { $('div[data-cate="legend.x"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="legend.x.'+legend.x+'"]').addClass('cpt-chkbtn-i-active'); } if(legend.y != null) { $('div[data-cate="legend.y"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="legend.y.'+legend.y+'"]').addClass('cpt-chkbtn-i-active'); } if(legend.orient != null) { $('div[data-cate="legend.orient"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="legend.orient.'+legend.orient+'"]').addClass('cpt-chkbtn-i-active'); } }, renderTooltip: function() { var tooltip = chartOpt.tooltip; if(tooltip.formatter != null) { $('input[data-type="tooltip.formatter"]').val(tooltip.formatter); } if(tooltip.show != null) { $('div[data-cate="tooltip.show"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="tooltip.show.'+tooltip.show+'"]').addClass('cpt-chkbtn-i-active'); } }, renderToolbox: function() { var toolbox = chartOpt.toolbox; if(toolbox.show != null) { $('div[data-cate="toolbox.show"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="toolbox.show.'+toolbox.show+'"]').addClass('cpt-chkbtn-i-active'); } if(toolbox.x != null) { $('div[data-cate="toolbox.x"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="toolbox.x.'+toolbox.x+'"]').addClass('cpt-chkbtn-i-active'); } if(toolbox.y != null) { $('div[data-cate="toolbox.y"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="toolbox.y.'+toolbox.y+'"]').addClass('cpt-chkbtn-i-active'); } if(toolbox.orient != null) { $('div[data-cate="toolbox.orient"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="toolbox.orient.'+toolbox.orient+'"]').addClass('cpt-chkbtn-i-active'); } if(toolbox.feature.dataZoom.show != null) { $('div[data-cate="toolbox.feature.dataZoom.show"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="toolbox.feature.dataZoom.show.'+toolbox.feature.dataZoom.show+'"]').addClass('cpt-chkbtn-i-active'); } if(toolbox.feature.dataView.show != null) { console.info(toolbox.feature.dataView.show); $('div[data-cate="toolbox.feature.dataView.show"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="toolbox.feature.dataView.show.'+toolbox.feature.dataView.show+'"]').addClass('cpt-chkbtn-i-active'); } if(toolbox.feature.restore.show != null) { $('div[data-cate="toolbox.feature.restore.show"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="toolbox.feature.restore.show.'+toolbox.feature.restore.show+'"]').addClass('cpt-chkbtn-i-active'); } if(toolbox.feature.saveAsImage.show != null) { $('div[data-cate="toolbox.feature.saveAsImage.show"]').removeClass('cpt-chkbtn-i-active'); $('div[data-type="toolbox.feature.saveAsImage.show.'+toolbox.feature.saveAsImage.show+'"]').addClass('cpt-chkbtn-i-active'); } } }; });
import React, {useContext} from 'react'; import { VideoListContext } from '../contexts/VideoContext'; import './VideoItem.css'; const VideoItem = ({video}) => { const { onVideoSelect } = useContext(VideoListContext) return ( <div onClick={() => onVideoSelect(video)} className="item video-item"> <img className="ui image" src={video.snippet.thumbnails.medium.url} alt="I am sohel"/> <div className="content"> <div className="header"> {video.snippet.title} </div> </div> </div> ); } export default VideoItem;
import Riego from '@/models/ModeloRiego'; export default { namespaced: true, state: { riego: new Riego('', '', '', '', '', '', '', '', '', ''), // Modelo Riego formRiegoValido: false, // Indica si el formulario de Riego es valido }, mutations: { // Coloca un nuevo Riego nuevoRiego(state, nuevoRiego) { state.riego = nuevoRiego }, // Vacia el modelo Riego vaciarRiego(state) { state.riego = new Riego('', '', '', '', '', '', '', '', '', '') }, // Cambia el estado del Formulario Riego cambiarEstadoValidoFormRiego(state, nuevoEstado) { state.formRiegoValido = nuevoEstado }, }, getters: { formRiegoValido: (state) => state.formRiegoValido, // Devuelve la variable formRiegoValido }, }
(function() { var Address, Mongo, Schema, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Mongo = require('diso.mongo'); Schema = Mongo.Schema; Address = (function(superClass) { extend(Address, superClass); function Address() { return Address.__super__.constructor.apply(this, arguments); } Address.schema({ type: Schema.String, value: Schema.String }); return Address; })(Mongo.EmbeddedModel); Object.defineProperty(Address.prototype, 'phone', { get: function() { var numbers; numbers = this.value.replace(/[^\d]+/g, ''); return "+1" + numbers; } }); Object.defineProperty(Address.prototype, 'email', { get: function() { return this.value; } }); module.exports = Address; }).call(this);
/* Spinal Tap Case Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes. Here are some helpful links: RegExp String.prototype.replace() */ function spinalCase(str) { // "It's such a fine line between stupid, and clever." // --David St. Hubbins return str.replace(/(?!^)([A-Z])/g, ' $1') .replace(/[_\s]+(?=[a-zA-Z])/g, '-').toLowerCase(); } spinalCase('This Is Spinal Tap');
const rp = require('request-promise'); var config = require('../config'); const baseUrl = config.url; const apiKey = config.api_key; module.exports = { getDefinition: async (word, printFlag) => { var url = baseUrl + '/word/' + word + '/definitions?api_key=' + apiKey; var result = []; await rp(url) .then(function(response) { if (response) { var defArray = JSON.parse(response); if (defArray && Array.isArray(defArray) && defArray.length > 0) { var def = ""; var i = 1; defArray.forEach((obj) => { result.push(obj.text); def += "(" + i + ") " + obj.text + "\n \n"; i++; }); if(printFlag == 1) { console.log('\nDefinition: \n \n', def); } } else { if(printFlag == 1) { console.warn('The word doesn\'t exist'); } } } else { if(printFlag == 1) { console.warn('Oops! Something went wrong!!!\n Error :', response); } } }) .catch(function(error) { if(printFlag == 1) { console.warn('Oops! Something went wrong!!!\n Error :', error.error); } }); return result; }, getSynonym: async (word, printFlag) => { var url = baseUrl + '/word/' + word + '/relatedWords?api_key=' + apiKey; var result = []; await rp(url) .then(function(response) { if (response) { var res = JSON.parse(response); var synArray; if(res.length == 1) { if(res[0].relationshipType == 'synonym') { synArray = res[0].words; } else { if(printFlag == 1) { console.warn('No synonym present for this word.'); console.log('\n'); } } } else if(res.length == 2) { if(res[0].relationshipType == 'synonym') { synArray = res[0].words; } else if(res[1].relationshipType == 'synonym') { synArray = res[1].words; } else { if(printFlag == 1) { console.warn('No synonym present for this word.'); console.log('\n'); } } } else { if(printFlag == 1) { console.warn('No synonym present for this word.'); console.log('\n'); } } if (synArray && Array.isArray(synArray) && synArray.length > 0) { result = synArray; if(printFlag == 1) { console.log("\nSynonyms: " + (synArray ? synArray.join(",") : '')); console.log('\n'); } } } else { if(printFlag == 1) { console.warn('Oops! Something went wrong!!!\n Error :', response); } } }) .catch(function(error) { if(printFlag == 1) { console.warn('Oops! Something went wrong!!!\n Error :', error.error); } }); return result; }, getAntonym: async (word, printFlag) => { var url = baseUrl + '/word/' + word + '/relatedWords?api_key=' + apiKey; var result = []; await rp(url) .then(function(response) { if (response) { var res = JSON.parse(response); var antArray; if(res.length == 1) { if(res[0].relationshipType == 'antonym') { antArray = res[0].words; } else { if(printFlag == 1) { console.warn('No antonym present for this word.'); console.log('\n'); } } } else if(res.length == 2) { if(res[0].relationshipType == 'antonym') { antArray = res[0].words; } else if(res[1].relationshipType == 'antonym') { antArray = res[1].words; } else { if(printFlag == 1) { console.warn('No antonym present for this word.'); console.log('\n'); } } } else { if(printFlag == 1) { console.warn('No antonym present for this word.'); console.log('\n'); } } if (antArray && Array.isArray(antArray) && antArray.length > 0) { result = antArray; if(printFlag == 1) { console.log("\nAntonyms: " + (antArray ? antArray.join(",") : '')); console.log('\n'); } } } else { if(printFlag == 1) { console.warn('Oops! Something went wrong!!!\n Error :', response); } } }) .catch(function(error) { if(printFlag == 1) { console.warn('Oops! Something went wrong!!!\n Error :', error.error); } }); return result; }, getExample: async (word, printFlag) => { var url = baseUrl + '/word/' + word + '/examples?api_key=' + apiKey; var result = []; await rp(url) .then(function(response) { if (response) { var res = JSON.parse(response); var defArray = res.examples; if (defArray && Array.isArray(defArray) && defArray.length > 0) { var def = ""; var i = 1; defArray.forEach((obj) => { result.push(obj.text); def += "(" + i + ") " + obj.text + "\n \n"; i++; }); if(printFlag == 1) { console.log('\nExamples: \n \n', def); } } else { if(printFlag == 1) { console.warn('The word doesn\'t exist'); } } } else { if(printFlag == 1) { console.warn('Oops! Something went wrong!!!\n Error :', response); } } }) .catch(function(error) { if(printFlag == 1) { console.warn('Oops! Something went wrong!!!\n Error :', error.error); } }); return result; }, getRandomWord: async () => { var url = baseUrl + '/words/randomWord?api_key=' + apiKey; var result = []; await rp(url) .then(function(response) { if (response) { var res = JSON.parse(response); var randomWord = res.word; result.push(randomWord); return randomWord; } else { console.warn('Oops! Something went wrong!!!\n Error :', body); } }) .then( async function(word) { if (word) { console.log("\n Word of the Day: " + word); result.push(await module.exports.getDefinition(word, 1)); result.push(await module.exports.getExample(word, 1)); result.push(await module.exports.getSynonym(word, 1)); result.push(await module.exports.getAntonym(word, 1)); } else { console.warn('Oops! Something went wrong!!!\n Error :', body); } }) .catch(function(error) { console.warn('Oops! Something went wrong!!!\n Error :', error.error); }); return result; }, play: async () => { var url = baseUrl + '/words/randomWord?api_key=' + apiKey; var result = []; await rp(url) .then(function(response) { if (response) { var res = JSON.parse(response); var randomWord = res.word; result.push(randomWord); return randomWord; } else { console.warn('Oops! Something went wrong!!!\n Error :', body); } }) .then( async function(word) { if (word) { result.push(await module.exports.getDefinition(word, 0)); result.push(await module.exports.getExample(word, 0)); result.push(await module.exports.getSynonym(word, 0)); result.push(await module.exports.getAntonym(word, 0)); } else { console.warn('Oops! Something went wrong!!!\n Error :', body); } }) .catch(function(error) { console.warn('Oops! Something went wrong!!!\n Error :', error.error); }); return result; } }
const mongoose = require('mongoose'); const db = require('./index.js'); mongoose.Promise = global.Promise; const gallerySchema = new mongoose.Schema({ listing_id: Number, photos: [{ position: Number, imageUrl: String, description: String, }, ], }); const Gallery = mongoose.model('Gallery', gallerySchema); module.exports = Gallery;
var files____c__8js_8js = [ [ "files__c_8js", "files____c__8js_8js.html#acccaebca3e0ff6ec53d409c4c6ad9b89", null ] ];
import routes from "../routers"; import { renderToString } from "react-dom/server"; import { StaticRouter, Route } from "react-router-dom"; import React from "react"; import { Provider } from "react-redux"; import { getStore } from "../store"; import { renderRoutes, matchRoutes } from "react-router-config"; import { Helmet } from "react-helmet"; const render = async (req) => { const store = getStore(); const matchedRoutes = matchRoutes(routes, req.path); const promises = []; matchedRoutes.forEach((item) => { if (item.route.loadData) { promises.push(item.route.loadData(store)); } }); await Promise.all(promises); const context = { css: [], }; const content = renderToString( <Provider store={store}> <StaticRouter location={req.path} context={context}> {/* {routes.map((route) => ( <Route {...route} /> ))} */} {renderRoutes(routes)} </StaticRouter> </Provider> ); const cssStr = context.css.length ? context.css.join("\n") : ""; const helmet = Helmet.renderStatic(); return ` <html> <head> <title>ssr</title> <style>${cssStr}</style> ${helmet.title.toString()} ${helmet.meta.toString()} </head> <body> <div id="root">${content}</div> <script> window._inject={ store: ${JSON.stringify(store.getState())} } </script> <script src="/index.js"></script> </body> </html> `; }; export default render;
// ** React Import import { useState, useEffect } from "react" import { useDispatch, useSelector } from "react-redux" // ** Custom Components import Sidebar from "@components/sidebar" import Select from "react-select" // ** Utils import { getImageUser } from "@utils" import Flatpickr from "react-flatpickr" import "@styles/react/libs/flatpickr/flatpickr.scss" // ** Third Party Components import classnames from "classnames" import { Button, FormGroup, Label, Form, Input, Col, Row } from "reactstrap" import { useForm } from "react-hook-form" // ** Store & Actions import { addItem, udpateItem, getAllCountriesSelect, getAllCitiesSelect, selectedCountryAdd, selectedCityLocal, selectedCityAdd, deleteSelectedCity, deleteSelectedCountry } from "../store/action" const SidebarNewItems = ({ open, toggleSidebar }) => { // ** States const dispatch = useDispatch() const store = useSelector((state) => state.providers) const baseUrl = "http://localhost:3000/api/" const [name, setName] = useState("") const [id, setId] = useState(0) const [contactForm, setContactForm] = useState(null) const [address, setAddress] = useState(null) const [country, setCountry] = useState("1") const [city, setCity] = useState("1") const [phone, setPhone] = useState(null) const [email, setEmail] = useState(null) const [web, setWeb] = useState(null) const { register, errors, handleSubmit, control, trigger } = useForm({ defaultValues: { dob: new Date() } }) //Country const optionCitySelected = [] const setCityHandle = (country) => { if (country) { const cities = store.cities cities.map((city) => { if (city.value === country.value) { optionCitySelected.push(city) } }) dispatch(selectedCityLocal(optionCitySelected)) } } const setCountrySelect = (e) => { dispatch(selectedCountryAdd(e)) setCountry(e) setCityHandle(e) } const handleChangeCountry = (e) => { setCountrySelect(e) } const handleChangeCity = (e) => { dispatch(selectedCityAdd(e)) setCity(e) } //City useEffect(() => { if (!!store.rowData._id) { setId(store.rowData._id) setName(store.rowData.name) setContactForm(store.rowData.contactForm) setAddress(store.rowData.address) setCity(store.rowData.city) setPhone(store.rowData.phone) setEmail(store.rowData.email) setWeb(store.rowData.web) if (!!store.rowData.country) { const countries = store.countries countries.map((country) => { if (country.label === store.rowData.country.name) { const e = { value: store.rowData.country.codeCountry, label: store.rowData.country.name, _id: store.rowData.country._id } setCountrySelect(e) } }) const statusLocal = store.rowData.country statusLocal.label = statusLocal.name setCountry(statusLocal) } if (!!store.rowData.city) { const statusLocalCity = store.rowData.city statusLocalCity.label = statusLocalCity.name setCity(statusLocalCity) } } else { setName('') setContactForm('') setAddress('') setCity('') setPhone('') setEmail('') setWeb('') setCity('') setCountry('') dispatch(getAllCountriesSelect()) dispatch(getAllCitiesSelect()) dispatch(deleteSelectedCity()) dispatch(deleteSelectedCountry()) setId(0) } }, [dispatch, store.isEdit]) // ** Store Vars const titlePanel = (val) => { if (id === 0) { return "Agregar proveedor" } else { return "Editar proveedor" } } const checkDisabled = () => { const disabled = false return disabled } // ** Vars // ** Function to handle form submit const onSubmit = (values, e) => { values["country"] = country._id values["city"] = city._id values["status"] = true values["idPlatform"] = store.rowData.idPlatform values["id"] = id //console.log(values) toggleSidebar() if (id === 0) { //console.log('Guardar') dispatch(addItem(values)) } else { dispatch(udpateItem(values)) } } return ( <Sidebar size="lg" open={open} title={titlePanel()} headerClassName="mb-1" contentClassName="pt-0" toggleSidebar={toggleSidebar} > <Form onSubmit={handleSubmit(onSubmit)} autoComplete="off"> <Row> <Col> <FormGroup> <Label for="full-name"> Nombre <span className="text-danger">*</span> </Label> <Input name="name" id="name" defaultValue={name} //onChange= { handleInputChange } placeholder="Ingresar el nombre" innerRef={register({ required: true })} className={classnames({ "is-invalid": errors["name"] })} /> </FormGroup> </Col> </Row> <Row> <Col> <FormGroup className="mb-2"> <Label for="contactForm">Persona de contacto</Label> <Input name="contactForm" id="contactForm" //onChange= { handleInputChange } defaultValue={contactForm} placeholder="Ingresar la persona de contacto" innerRef={register({ required: true })} className={classnames({ "is-invalid": errors["contactForm"] })} /> </FormGroup> </Col>{" "} </Row> <FormGroup> <Label for="address"> Dirección <span className="text-danger">*</span> </Label> <Input name="address" id="address" type="textarea" autoComplete={0} //onChange= { handleInputChange } defaultValue={address} placeholder="Ingresar la dirección" innerRef={register({ required: true })} className={classnames({ "is-invalid": errors["address"] })} /> </FormGroup> <Row> <Col> <FormGroup> <Label for="country">País: <span className="text-danger">*</span></Label> <Select name="country" id="country" isClearable value={country} options={store.countries} onChange={handleChangeCountry} innerRef={register({ required: true })} className={classnames({ "is-invalid": errors["country"] })} /> </FormGroup> </Col> <Col> <FormGroup> <Label for="city">Ciudad: <span className="text-danger">*</span></Label> <Select name="city" id="city" isClearable value={city} options={(store.selectedCityLocal) ? store.selectedCityLocal : store.cities} onChange={handleChangeCity} isDisabled = {!(store.selectedCountry)} innerRef={register({ required: true })} className={classnames({ "is-invalid": errors["city"] })} /> </FormGroup> </Col> </Row> <FormGroup> <Label for="phone"> Teléfono <span className="text-danger">*</span> </Label> <Input name="phone" id="phone" autoComplete={0} defaultValue={phone} //onChange= { handleInputChange } type="tel" placeholder="Ingresar el teléfono" innerRef={register({ required: true })} className={classnames({ "is-invalid": errors["phone"] })} /> </FormGroup> <Row> <Col xs="12" lg="6" md="6"> <FormGroup> <Label for="email"> Email </Label> <Input name="email" id="email" autoComplete={0} defaultValue={email} //onChange= { handleInputChange } type="email" placeholder="Ingresar el email" innerRef={register({ required: true })} className={classnames({ "is-invalid": errors["email"] })} /> </FormGroup> </Col> <Col xs="12" lg="6" md="6"> <FormGroup> <Label for="web">Website: </Label> <Input name="web" id="web" autoComplete={0} defaultValue={web} //onChange= { handleInputChange } type="web" placeholder="Ingresar el website" innerRef={register({ required: true })} className={classnames({ "is-invalid": errors["web"] })} /> </FormGroup> </Col> </Row> <Row> <Col> <Button type="submit" className="mr-1" color="primary" disabled={checkDisabled()} > Guardar </Button> <Button type="reset" color="secondary" outline onClick={toggleSidebar} > Cancelar </Button> </Col> </Row> </Form> </Sidebar> ) } export default SidebarNewItems
export default async (db, token) => ({ message: "user profile response" });
const db = require('../db'); const ExpressError = require('../helpers/expressError'); class User{ static async createUser(userObj){ const userQuery = await db.query(` INSERT INTO users (username, password, first_name, last_name, email, photo_url, is_admin) VALUES($1, $2, $3, $4, $5, $6, $7) RETURNING *`, [userObj.username.toLowerCase(), userObj.password, userObj.first_name, userObj.last_name, userObj.email,userObj.photo_url, userObj.is_admin]); return userQuery.rows[0]; } static async getUsers(){ const userQuery = await db.query(` SELECT username, first_name, last_name, email FROM users`); return userQuery.rows; } static async getSingleUser(username){ const userQuery = await db.query(` SELECT username, first_name, last_name, email, photo_url, is_admin FROM users WHERE username = $1`, [username]); if(!userQuery.rowCount){ throw new ExpressError(`${ username } not found`, 404); } const jobQuery = await db.query(` SELECT a.job_id, a.state, j.title, j.company_handle FROM applications a JOIN jobs j ON a.job_id = j.id WHERE username=$1`, [username]); return { user: userQuery.rows[0], jobs: jobQuery.rows }; } static async updateUser(updatedData){ const userQuery = await db.query(updatedData.query, updatedData.values); if(!userQuery.rowCount){ throw new ExpressError(`${ updatedData.values[updatedData.values.length-1] } not found`, 404); } const { username, first_name, last_name, email, photo_url } = userQuery.rows[0]; return { username, first_name, last_name, email, photo_url }; } static async deleteUser(username){ const userQuery = await db.query(` DELETE FROM users WHERE username = $1 RETURNING username `, [username]); if(!userQuery.rowCount){ throw new ExpressError(`${ username } not found`, 404); } return userQuery.rows[0]; } static async updateAdminStatus(username){ const userQuery = await db.query(` UPDATE users SET is_admin = CASE WHEN is_admin IS false THEN true ELSE false END where username = $1 RETURNING username `, [username]); return userQuery.rows[0] } } module.exports = User;
Ext.define('Gvsu.modules.users.view.PublUsersForm', { extend: 'Core.form.DetailForm', titleIndex: 'name', layout: 'border', defaults: { margin: '0', }, width: 400, height: 420, buildItems: function() { var me = this; return [{ xtype: 'panel', region: 'center', layout: 'anchor', bodyStyle: 'overflow: auto;padding: 10px;', defaults: { xtype: 'textfield', labelWidth: 150 ,anchor: '90%' }, items: me.buildFields() }] }, buildFields: function() { return [ { name: 'activated', xtype: 'checkbox', fieldLabel: D.t('Активирован') },/*{ name: 'status', xtype: 'checkbox', fieldLabel: D.t('Участник торгов') },*/{ name: 'login', fieldLabel: D.t('Логин') },{ inputType: 'password', name: 'password', fieldLabel: D.t('Пароль') },/*{ xtype: 'combo', name: 'org', fieldLabel: D.t('Организация'), valueField: '_id', displayField: 'name', queryMode: 'local', store: Ext.create('Core.data.ComboStore',{ dataModel: 'Gvsu.modules.orgs.model.OrgsModel', fieldSet: '_id,name' }) },*/{ name: 'org', inputType: 'hidden' },{ name: 'email', fieldLabel: D.t('Email') },{ name: 'fname', fieldLabel: D.t('Фамилия') },{ name: 'name', fieldLabel: D.t('Имя') },{ name: 'sname', fieldLabel: D.t('Отчество') },{ name: 'phone', fieldLabel: D.t('Телефон контактный') },{ name: 'mobile', fieldLabel: D.t('Телефон мобильный') },{ name: 'position', fieldLabel: D.t('Должность') }] } })
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PoemSchema = new Schema({ title: { type: String }, user: { type: Schema.Types.ObjectId, ref: 'user' }, stanza: [{ type: Schema.Types.ObjectId, ref: 'stanza' }] }); PoemSchema.statics.addStanza = function(id, content) { const Stanza = mongoose.model('stanza'); return this.findById(id) .then(poem => { const stanza = new Stanza({ content, poem }) poem.stanza.push(stanza) return Promise.all([stanza.save(), poem.save()]) .then(([Stanza, poem]) => poem); }); } PoemSchema.statics.findStanzas = function(id) { return this.findById(id) .populate('stanza') .then(poem => poem.stanza); } mongoose.model('poem', PoemSchema);
/* *@author samuel richards *@candidate number: 77513 * * Description: JavaScript passes all required files automatically when using Node.JS and Express. Creating this file that loads all images at the beginning of the game initialisation insures all images are passed to the client before they start the game. */ //function acts as a class var preloadedimages = function(){ //creates and loads the background image var background = new Image(); background.src = "../Images/hauntedHouseWithoutWindows.png"; //creates and loads the zombie sprite image var _zombieSprite = new Image(); _zombieSprite.src = "../Images/zombie_sprite.png"; //creates and loads the plank image var plank = new Image(); plank.src = "../Images/plank_right.png"; //creates and loads the crosshairs image var crossHairs = new Image(); crossHairs.src = "../Images/Crosshairs.png"; //creates and loads the bullet image image var bulletimg = new Image(); bulletimg.src = "../Images/bullet.png"; //creates and loads the bigger bullets pick up image var bigBulletIcon = new Image(); bigBulletIcon.src = "../Images/bigBulletIcon.jpg"; //creates and loads the player speed increase pick up image var bulletSpeedIncrease = new Image(); bulletSpeedIncrease.src = "../Images/bulletSpeedIncreaseIcon.jpg"; //creates and loads the health icon pick up image var healthIcon = new Image(); healthIcon.src = "../Images/healthIcon.png"; //creates and loads the piercing bullets pick up image var piercingBulletIcon = new Image(); piercingBulletIcon.src = "../Images/piercingBulletIcon.jpg"; //creates and loads the speed icon pick up image var speedIcon = new Image(); speedIcon.src = "../Images/speedIcon.jpg"; //creates and loads the player image var playerImage = new Image(); playerImage.src = "../Images/player.png"; //creates and loads the other player image used for other players playing the game var otherPlayer = new Image(); otherPlayer.src = "../Images/otherplayer.png"; //returns all the images loaded. So external classes may use them. return{ background:background, _zombieSprite:_zombieSprite, plank:plank, crossHairs:crossHairs, bulletimg:bulletimg, bigBulletIcon:bigBulletIcon, bulletSpeedIncrease:bulletSpeedIncrease, healthIcon:healthIcon, piercingBulletIcon:piercingBulletIcon, speedIcon:speedIcon, playerImage:playerImage, otherPlayer:otherPlayer } };
// 设置cookie function setCookie (name, value, day) { // 当设置的时间没有时,不设置expires属性,cookie在浏览器关闭后删除 if (day) { var expires = day * 24 * 60 * 60 * 1000; var date = new Date(+new Date()+expires); document.cookie = name + "=" + escape(value) + ";expires=" + date.toUTCString(); } else { document.cookie = name + "=" + escape(value); } }; // 获取cookie function getCookie (name) { var arr; var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); if (arr = document.cookie.match(reg)) return unescape(arr[2]); else return null; }; // 删除cookie function delCookie (name) { setCookie(name, ' ', -1); }; export { setCookie, getCookie, delCookie, }
import React from "react"; import { View, Text, StyleSheet, Dimensions } from "react-native"; import Color from "../constants/Color"; import TitleText from "./TitleText"; const Header = props => { return ( <View style={styles.header}> <TitleText>{props.title}</TitleText> </View> ); }; const styles = StyleSheet.create({ header: { width: "100%", height: Dimensions.get("window").height * 0.09, paddingTop: Dimensions.get("window").height * 0.03, backgroundColor: Color.grey2, alignItems: "center", justifyContent: "center" } }); export default Header;
import React from 'react'; import "./SocialMediaContainer.css"; import SocialMediaButtons from '../SocialMediaButtons/SocialMediaButtons'; import contactPicture from '../../../src/assets/images/profile-pic256px.png' import starsDecor from '../../../src/assets/misc/three-stars-svg.svg' import multipleStarsDecor from '../../../src/assets/misc/multiple-stars-svg.svg' const SocialMediaContainer = () => { return ( <div className="socialMediaContainer"> {/*Header Section above Buttons*/} <img src={contactPicture} className="contactPic" alt="profile picture"/> <h1 className="socials-header">My Socials</h1> <div className="connectText"> <span>Connect with me on any of my socials below!</span> </div> {/*Decorative Elements*/} <img src={starsDecor} className="star-decor-right"/> <img src={starsDecor} className="star-decor-left"/> <img src={multipleStarsDecor} className="multiple-stars-right"/> {/*Social Media Button Area*/} <SocialMediaButtons /> </div> ) } export default SocialMediaContainer
import React, { useContext, useState } from 'react'; import { Link } from 'react-router-dom'; import ProfileContext from '../../context/profile/profileContext'; export const Footer = () => { const profileContext = useContext(ProfileContext); const { language, toggleLanguage } = profileContext; const [newLanguage, setNewLanguage] = useState(false); return ( <div id="main-footer"> <a href="mailto:riad.ennaim@gmail.com"> { language === 'en' ? 'Send me a mail for a new collaboration' : 'Envoyez-moi un mail pour une nouvelle collaboration' } &nbsp;&#x1F60E; </a> <p> { language === 'en' ? 'Sourced on' : 'Source sur' } &nbsp; <a href="https://github.com/Riad-ENNAIM/cv">GitHub</a> </p> <p className="footer-links"> <a href="https://github.com/Riad-ENNAIM/" target="_blank" rel="noopener noreferrer" title="GitHub"> <i className="fab fa-github-square"></i> </a> <a href="https://www.linkedin.com/in/riad-ennaim/" target="_blank" rel="noopener noreferrer" title="LinkedIn"> <i className="fab fa-linkedin"></i> </a> <a href="https://riad-ennaim.github.io/bio/" target="_blank" rel="noopener noreferrer" title="Bio"> <i className="fas fa-address-card"></i> </a> </p> <p className="footer-copyright"> &copy; <Link to="/"> Riad ENNAIM </Link> {new Date().getFullYear()} </p> { newLanguage ? <span className="footer-lang" onClick={toggleLanguage} onMouseOut={() => setNewLanguage(!newLanguage)} title={ language === 'en' ? 'Passer au Français' : 'Switch to English' } > <i className="fas fa-globe-africa"></i> { language === 'en' ? ' Français' : ' English' } </span> : <span className="footer-lang" onMouseOver={() => setNewLanguage(!newLanguage)}> <i className="fas fa-globe-africa"></i> { language === 'en' ? ' English' : ' Français' } </span> } </div> ); } export default Footer;
import React from "react"; import { MdRefresh } from "react-icons/md"; const RefreshPanel = ({ transactionID }) => { return ( <div className="ref-panel"> <p style={{ textAlign: "center" }} > <b> <MdRefresh className="ref-icon" /> </b> </p> <h2 className="ref-title"> <b>Transaction pending</b> </h2> <p className="txt-bottom-h" style={{ textAlign: "center" }}> Transaction ID <br /> <span className="txt-bottom-h" style={{ textAlign: "center", color: "rgb(65, 125, 265)" }} > {transactionID} </span> </p> <p className="txt-bottom-h" style={{ textAlign: "center" }}> Lorem ipsum dolor sit amet, consectetur <br /> adipiscing elit, sed do eiusmod... </p> </div> ); }; export default RefreshPanel;
const userModel = require('../model/userModel'); module.exports = { save: (newUser,callBakc) => { newUser.save(callBakc); }, find: (callback) => { userModel.find(callback); } }
import express from 'express'; export const healthRouter = express.Router(); const healthPath = '/health'; healthRouter.get(healthPath, (_request, response) => { try { const healthy = { status: 'UP' }; response.send(healthy); } catch (e) { response.status(500).send(e.message); } });
module.exports = async (pg, logId) => { const entryResults = await pg.query({ name: 'fetch-log-entries', text: 'SELECT message, roll, result, created_at, log_id FROM entries WHERE log_id = $1 ORDER BY created_at DESC LIMIT 100;', values: [logId] }) return entryResults.rows }
import { connect } from 'react-redux'; import ShipComponent from './ShipComponent'; import { bsOperations } from './duck'; const mapStateToProps = (state) => { return { shipSelected: state.bs.arrange.shipSelected, placedShips: state.bs.arrange.placedShips } } const mapDispatchToProps = (dispatch) => { return { selectShip: (id) => { dispatch(bsOperations.selectShip(id)); } } } const ShipContainer = connect(mapStateToProps, mapDispatchToProps)(ShipComponent); export default ShipContainer;
/** * */ $(document).ready(function() {menu.getMenu(0); menu.getListBody();}); var font = "微博订单详细"; var valids = ["媒体订单DID", "订单号", "媒体名", "QQ", "备注", "状态", "最后修改时间", "最后修改人"]; var sizes = [100, 100, 100, 100, 100, 100, 100, 100]; var contents = ["媒体订单DID", "订单号", "媒体名", "QQ", "备注", "状态", "最后修改时间", "最后修改人"]; var keys = ["weichat_order_did", "order_no", "media_name", "qqnumber", "comment", "status_", "last_update_time", "last_update_by"];
var myArr = A[-1, 3, -4, 5, 1, -6, 2, 1,]; function solution(A) { if ( A.length > 0) { if (A.length == 1) return 0; var leftSize = 0; var rightSize = 0; var i=0; for (i;i<A.length;i++){ rightSize = rightSize+ A[i]; } for (i=0;i<A.length;i++){ if (i>0) leftSize=leftSize+A[i-1]; if (leftSize==(rightSize-leftSize-A[i])) return i; } return -1; } else return -1; } //--------------------------------- function solution(A){ var sum = getSum(A); var curSum = 0; for(var i = 0; i < A.length; i++){ curSum += A[i]; if((curSum - A[i]) == (sum - curSum)){ return i; } } return -1; function getSum(A){ var sum = 0; for(var i = 0; i < A.length; i++){ sum += A[i]; } return sum; } } //------------------------------------- var A = [1,4,-1,3,2]; function solution(A) { var N = A.length; var test = 0; for(var i = 0; i < N-1; i++) { for(var j = i; j < N; j++){ if(A[i] <= A[j] && (j - i) > test) test = j - i; } } return test; }
/* if */ var a = 1, b = 1; if (a==b) console.log("블록X"); if (a==b) console.log("1번줄") console.log("2번줄"); /* 세미콜론(;)까지 조건 if 실행 */ var a = 1, b = 1; if (a==b) { console.log("블록사용"); }; /* 블록에 작성한 내용을 다 실행. 블록 사용 권장 - 확장성과 일관성을 위해 */ // if(표현식) 문장1 else 문장2 -> 표현식이 true면 문장1을 false면 문장2를 반환 var a = 1, b = 2; if (a===b) console.log("1번줄, true"); else console.log("2번줄, false"); var a = 1, b = 2; if (a===b) { console.log("블록사용, true"); } else { console.log("블록사용, false"); }; /* debugger를 작성하면 debugger가 있는 위치에서 실행을 멈춘다. 브라우저 개발창이 열려 있을 때만 멈추고 열려 있지 않으면 멈추지 않는다. 자신이 테스트를 해야하는 줄만 테스트하고 싶을 때 많이 사용 */ /* while */ // 표현식의 평가가 false가 될 때까지 문장을 반복하여 실행! 반복이 종료되는 조건이 필요 var k = 1; while (k < 3) { console.log(k); k++; }; /* do ~ while */ //형태 : do 문장 whlie(표현식) var k = 1; do { console.log("do:", k); k++; } while (k < 3) { console.log("while:", k); }; /* true일 경우 do문의 블록을 실행 false일 경우 while문 블록을 실행해 반환 */ /* do { console.log("do:", k); k++; } while (k < 3); console.log("while:", k); 이렇게 작성도 가능*/ /* for */ // 형태 : for (초기값; 표현식; 증감) for (k=0; k<3; k++) { console.log(k); }; /* A -> B -> True면 반환 -> C -> B -> True면 반환 -> C -> B -> True면 반환 false면 종료*/ /* Break */ // 형태 : break;, break 식별자; -> 반복문 종료 // for, for~in, while, do~while, switch에서 사용 var k=0, m=0; while(k<3){ m++ if (m===2){ break; } console.log(k); } /* break를 만나면 아래의 문장을 수행하지 않고 반복문이 종료됨, break끝에 세미콜론은 자동 첨부 */ /* continyue */ // 형태 : continue; // for, for~in, while, do~while 에서 사용 for (var k=0; k < 5; k++) { if ( k === 2 || k ===3 ){ continue; }; console.log(k); }; /* continue를 만나면 반복문 처음으로 감. k가 2와 3일 경우 if문이 ture가 되어 if문의 블록을 실행 블록 문의 continue를 실행하면 console.log(k)를 실행하지 않고 for의 k++로 가서 실행 */ /* switch */ /* 형태 : switch(표현식) { case 표현식 : 문장 리스트; default 표현식 : 문장 리스트; } */ var exp = 1; switch(exp) { case 1 : console.log(100); case 2 : console.log(200); }; /* exp의 값이 1이므로 걊이 일치하는 case 1문을 수행 해야하는데 case1의 문만이 아닌 case1의 아래 모든 문을 실행 하므로 case2도 실행이 되어 100, 200의 값이 나온 것! 이를 방지하려면 break를 작성해주는 것이 좋다.*/ var exp = 1; switch(exp) { case 1 : console.log(100); break; case 2 : console.log(200); }; var exp = 7; switch(exp) { case 1 : console.log(100); default : console.log(700); case 2 : console.log(200); }; /* exp의 값이 1이므로 일치하는 값을 가진 case가 없으므로 default문이 실행을 하는데 위와 같이 default문의 아래 모든 문을 실행 하므로 case2도 실행된다. 이를 방지하기 위해서는 break를 작성해주는 것이 좋다 */ var exp = 7; switch(exp) { case 1 : value = 100; default : value = 700; case 2 : value = 200; }; console.log(value); /* 위와 같은 이유로 default문이 실행 value = 700을 가지지만 case2가 실행되면서 value의 값이 700 -> 200으로 변경되어 200이 반환 */ var exp = 7; switch(exp) { case 1 : value = 100; default : value = 700; break; case 2 : value = 200; }; console.log(value); /* break를 사용하면 default가 끝나면 문장을 끝내고 빠져나가므로 case2가 실행되지 않아 value의 값은 700이 나온다 */ var exp = 3; switch(exp) { case 1 : /* case1 : 과 case2 사이에 문장과 세미콜론이 없이 한번에 작성되면 OR이라는 의미 */ case 2 : value = 200; }; /* try-catch */ // 형태 : try 블록 catch(식별자) 블록, try 블록 finally 블록, try 블록 catch(식별자) 블록 finally 블록 var value; try { value = ball; } catch(error){ console.log("catch 실행"); }; /* try-catch를 사용하는 이유 : try문에서 에러가 발생해도 프로그램이 죽지 않고 catch문을 실행하기 때문에 에러 발생 가능성이 있을때 사용한다. */ /* 서버에서 데이타를 가저올때 통신에서 에러가 발생할 가능성이 있기때문에 서버에서 데이터를 가저올때 try문에 작성하는 것이 좋다.*/ var sport; try { sport = ball; } catch(error){ console.log("catch 실행"); } finally { console.log("finally 실행"); }; /* try문에서 에러가 발생했기 때문에 catch문 실행하고 finally문은 예외와 관계없이 기본적으로 실행한다. */ /* throw */ // 형태 : throw 표현식; 명시적으로 에러를 발생시킬때 사용 에러가 발생되면 catch문을 실행 try { throw "에러발생!" /*에러가 발생하면 아래문장을 수행하지 않고 바로 catch문으로 이동 */ var sports = "swimming"; } catch(error){ console.log(error); /* error에 "에러발생!"이라는 throw 표현식의 문자열이설정된다 */ console.log(sport); /* var sports = "swimming";이 실행되지 않았으므로 sports의 값이 없어 undefind가 반환된다. */ } try { throw { /* throw표현식에 오브젝트 사용 가능 {name:메세지} 형태 */ msg : "에러 발생!", bigo : "임의의 이름 사용" } } catch(error){ console.log(error.msg); console.log(error.bigo); }; try { throw new Error ("에러발생!"); /* new는 새로운 오브젝트를 생성 -> Error라는 오브젝트를 생성하였음 -> 생성된 오브젝트에 "에러발생!" 이라는 메세지를 설정*/ } catch(error){ console.log(error.message); }; /* strict 선언 */ // 형태 : "use strict"; 엄격하게 JS 문법을 사용하겠다 하고 선언 "use strict"; try { book = "변수를 선언하지 않음"; console.log(book); } catch(error){ console.log(error.message); }; /* 코딩 실수를 예방하기 위해서 use strict 작성은 필수! */
var router = require('express').Router() var Orderitems = require('../models/orderitems') router.index = function (req, res) { // 여기는 조건부로 바 /* var estimates = Estimates.find(function(err, estimates){ if (err) return console.error(err) console.log(estimates) res.render('pages/estimates/index', {estimates: estimates}) })*/ res.render('pages/deadline/index') } module.exports = router
import React from 'react'; import cx from 'classnames'; import PropTypes from 'prop-types'; import s from '../styles/Widget.module.scss'; function Widget({ title, className, children }) { return ( <section className={cx(s.widget, className)}> {title && (typeof title === 'string' ? ( <h5 className={s.title}>{title}</h5> ) : ( <header className={s.title}>{title}</header> ))} <div>{children}</div> </section> ); } export default Widget; Widget.propTypes = { title: PropTypes.node, className: PropTypes.string, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]), }; Widget.defaultProps = { title: null, className: null, children: [], };
const mongoose = require("mongoose"); const orangeTypeSchema = new mongoose.Schema({ name: String, price: Number, creationTime: Date, userId: mongoose.Schema.Types.ObjectId, }); const Orange = new mongoose.model("Oranges", orangeTypeSchema); module.exports = Orange;
import styled from 'styled-components'; export const Header = styled.header` background-color: ${({ theme }) => theme.surface}; padding-top: 10px; padding-bottom: 10px; box-shadow: 0 11px 10px -10px rgba(0,0,0,.1); `; export const MenuOverlay = styled.div` position: fixed; top: 0; right: 0; bottom: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.8); z-index: 998; display: ${({ open }) => open ? 'block' : 'none'}; `; export const Menu = styled.aside` display: flex; flex-direction: column; width: 260px; height: 100vh; position: fixed; top: 0; left: 0; transform: ${({ open }) => open ? 'translateX(0)' : 'translateX(-100%)'}; transition: transform .2s linear; z-index: 999; box-shadow: 0 8px 10px -5px rgb(0 0 0 / 20%), 0 16px 24px 2px rgb(0 0 0 / 14%), 0 6px 30px 5px rgb(0 0 0 / 12%); background-color: ${({ theme }) => theme.surface}; `; export const MenuNavigation = styled.nav` width: 100%; `; export const MenuHeader = styled.div` width: 100%; padding: 18px 20px; font-size: ${({ theme }) => theme.fontSize.l}; font-weight: ${({ theme }) => theme.bold}; border-bottom: 1px solid ${({ theme }) => theme.border}; `; export const MenuList = styled.ul` display: flex; flex-direction: column; width: 100%; padding: 10px; a { display: block; padding: 10px; border-radius: 2px; font-weight: ${({ theme }) => theme.bold}; color: ${({ theme }) => theme.textprimary}; &:hover { background-color: ${({ theme }) => theme.action}; } } `; export const Footer = styled.footer` padding-top: 20px; padding-bottom: 20px; margin-top: 20px; line-height: 1.7; text-align: center; font-weight: ${({ theme }) => theme.regular}; font-size: ${({ theme }) => theme.fontSize.s}; background-color: ${({ theme }) => theme.surface}; @media(min-width: 768px) { margin-top: 40px; text-align: left; } `; export const FooterCopyright = styled.p` padding-top: 20px; text-align: center; a { color: inherit; } `; export const Buttons = styled.div` display: flex; align-items: center; button { margin-left: 10px; @media(min-width: 992px) { margin-left: 15px; } } `;
import React, { useEffect, useState } from "react"; import { db } from "../Database/firebase"; import "./productDetailsPage.css"; import { BsBag } from "react-icons/bs"; import { LocalDatabase } from "../context/DataLayer"; import { Link } from "react-router-dom"; import { event, isArray } from "jquery"; const ProductDetailsPage = ({ match }) => { const [products, setproducts] = useState([]); const [state, dispatch] = LocalDatabase(); const rating = [1, 2, 3, 4, 5]; const addToCart = (i) => { console.log(i); dispatch({ type: "ADD_TO_CART", proId: i, }); }; useEffect(() => { (async () => { var docRef = db.collection("Products").doc(match.params.productId); try { var productsNew = await docRef.get().then((resp) => { setproducts(resp.data()); }); } catch (err) { console.log("Error getting documents", err); } })(); }, []); const imgs = document.querySelectorAll(".img-select a"); const imgBtns = [...imgs]; let imgId = 1; imgBtns.forEach((imgItem) => { imgItem.addEventListener(`click`, (event) => { event.preventDefault(); imgId = imgItem.dataset.id; slideImage(); }); }); function slideImage() { const displayWidth = document.querySelector(".img-showcase img:first-child") .clientWidth; document.querySelector(".img-showcase").style.transform = `translateX(${ -(imgId - 1) * displayWidth }px)`; } window.addEventListener("resize", slideImage); return ( <div className="card-wrapper-new"> <div className="card-new"> {/* Card Left */} <div className="product-img"> <div className="img-display"> <div className="img-showcase"> <img src={products.productImage} alt={products.productName} /> <img src={products.productImage} alt={products.productName} /> <img src={products.productImage} alt={products.productName} /> <img src={products.productImage} alt={products.productName} /> </div> </div> <div className="img-select"> <div className="img-item"> <Link to="#" data-id="1"> <img src={products.productImage} alt={products.productName} /> </Link> </div> <div className="img-item"> <Link to="#" data-id="2"> <img src={products.productImage} alt={products.productName} /> </Link> </div> <div className="img-item"> <Link to="#" data-id="3"> <img src={products.productImage} alt={products.productName} /> </Link> </div> <div className="img-item"> <a href="#" data-id="4"> <img src={products.productImage} alt={products.productName} /> </a> </div> </div> </div> <div className="product-content"> <h2 className="product-title">{products.productName}</h2> <Link className="product-link" to="/shop"> Visit the store </Link> <div className="product-rating"> {rating.map((item, id) => { return <i className="fas fa-star"></i>; })} <span>5.0(20)</span> </div> <div className="product-price"> <p className="last-price"> Old Price: <span>$500</span> </p> <p className="new-price"> New Price: <span>${products.productPrice}</span> </p> </div> <div className="product-detail"> <h2>About this item:</h2> <p>{products.productDesc}</p> {products?.inStock == "Yes" ? ( <div className="stock"> <p>In Stock</p> </div> ) : ( <div className="stock"> <p>Not In Stock</p> </div> )} <div className="colors-container"> {products?.Colors ? products.Colors.map((item, id) => { return <button style={{ background: item }}></button>; }) : null} </div> <div className="sizes-container"> {products?.Sizes ? products.Sizes.map((item, id) => { return <button className="size-btn">{item}</button>; }) : null} </div> </div> <div className="purchase-info"> <input type="number" min="0" value="1" /> <button type="button" className="btn" onClick={() => addToCart(match.params.productId)} > Add to Cart <i className="fas fa-shopping-cart"></i> </button> <button type="button" className="btn"> Compare </button> </div> <div className="social-links"> <p>Share all: </p> <Link to="#"> <i className="fab fa-facebook-f"></i> </Link> <Link to="#"> <i className="fab fa-twitter"></i> </Link> <Link to="#"> <i className="fab fa-instagram"></i> </Link> <Link to="#"> <i className="fab fa-whatsapp"></i> </Link> <Link to="#"> <i className="fab fa-pinterest"></i> </Link> </div> </div> </div> </div> ); }; export default ProductDetailsPage; //Storage // rules_version = '2'; // service firebase.storage { // match /b/{bucket}/o { // match /{allPaths=**} { // allow read, write: if true; // } // } // } //Cloud Firestore // rules_version = '2'; // service cloud.firestore { // match /databases/{database}/documents { // match /{document=**} { // allow read, write: if // request.time < timestamp.date(2021, 1, 20); // } // } // }
var orionClient = require('fiware-orion-mintaka'); var h = require('./helper'); var disabled = false; module.exports = { init: function(conf){ orionClient.configure(conf); }, initEntities: function(definition){ if(disabled) return; definition.entities.map(function(ent){ var attrObj = { attributes: ent.attributes }; h.deepLog(attrObj, ent.id + ' - init to send'); orionClient.registerEntityWithType(ent.id, ent.type, attrObj).then( function(success){ h.deepLog(success, ent.id + " - orion response"); console.log("entity registered", ent.id); }, function(error){ console.log("error registering entity", ent.id); } ); }); }, updateEntities: function(update){ if(disabled) return; var attrObj = { attributes: update.attributes }; h.deepLog(attrObj, update.entity + ' - update to send'); orionClient.updateAttributes(update.entity, attrObj); } };
import React from 'react' import { Tabs, useTabState, Panel } from '@bumaga/tabs' import LoginForm from './NoteloginForm'; import VendorPanel from './NoteVendorInfo'; import NoteServiceInfo from './NoteServiceInfo'; import NoteVendorUpload from './NoteVendorUpload'; const cn = (...args) => args.filter(Boolean).join(' ') const Tab = ({ children }) => { const { isActive, onClick } = useTabState() return ( <button className={cn('tab', isActive && 'active')} onClick={onClick}> {children} </button> ) } export default () => ( <div className="out-border"> <Tabs> <div className='tabs'> <div className='tab-list'> <Tab>User Information</Tab> <Tab>Vendor Information </Tab> <Tab>Service</Tab> <Tab>Uplpoad Profile</Tab> </div> <Panel> <LoginForm /> </Panel> <Panel> <VendorPanel /> </Panel> <Panel> <NoteServiceInfo /> </Panel> <Panel> <NoteVendorUpload /> </Panel> </div> </Tabs> </div> )
import React, { Component } from 'react'; import { Button, Tabs, Table, Menu, message, Breadcrumb } from 'antd'; const TabPane = Tabs.TabPane; import PunishTable from "./PunishTable"; import ClaimantTable from "./ClaimantTable"; import "./css/punish.css"; class PunishClaimant extends Component { constructor(props) { super(props); this.state = { key: "1", punishData: null,//处罚数据初始化 claimantData: null,//索赔数据初始化 punishPage: 1,//处罚page claimantPage: 1,//索赔page page: 1, info: 0 } } //tab切换事件 callback = (key) => { let _this = this; ajax({ url: "/txieasyui?taskFramePN=system&command=system.getLoginUserInfo&colname=json_ajax&colname1={'dataform':'eui_form_data','tablename':'detail0'}}", dataType: "json", type: "GET", async: true, success: function (res) { if (res.deptName.indexOf("事业") != "-1" || res.deptName.indexOf("交通") != "-1" || res.deptName.indexOf("高效")!="-1") { _this.setState({ info: 1 }) } } }); this.setState({ page: 1 }) if (key == "1") { this.initAjax("", 1, "UnDealt") } else { this.claimantD("", 1, "UnDealt") } } //处罚列表页数据 initAjax = (value, pageNum, type) => { let _this = this; ajax({ url: "/txieasyui?taskFramePN=exceptionInfoManage&command=supplier_pubish_list&colname=json_ajax&colname1={'dataform':'eui_datagrid_data','tablename':'detail0'}", dataType: "json", type: "POST", cache: false, data: { "supplierName": value, page: pageNum, rows: 10, type: type }, success: function (result) { console.log(result.EAF_ID) _this.setState({ punishData: result }); }, error: function (res) { message.error(res.EAF_ERROR); } }); } //索赔列表页数据 claimantD = (value, pageNum, type) => { let _this = this; ajax({ url: "/txieasyui?taskFramePN=exceptionInfoManage&command=suppiler_claim_list&colname=json_ajax&colname1={'dataform':'eui_datagrid_data','tablename':'detail0'}", dataType: "json", type: "POST", cache: false, data: { "supplierName": value, page: pageNum, rows: 10, type: type }, success: function (result) { console.log(result) _this.setState({ claimantData: result }); }, error: function (res) { message.error(res.EAF_ERROR); } }); } tabClick = () => { this.setState({ key: "" + Math.random(), key1: "" + Math.random(), }) } componentDidMount() { this.initAjax("", this.state.page, "UnDealt"); } render() { return ( <div> <Breadcrumb> <Breadcrumb.Item>供应商管理</Breadcrumb.Item> <Breadcrumb.Item>异常信息处理</Breadcrumb.Item> </Breadcrumb> <Tabs defaultActiveKey={this.state.key} onChange={this.callback} className="wl-tabs" onTabClick={this.tabClick}> <TabPane tab="供应商处罚" key={1} className="wl-attr"><PunishTable punishData={this.state.punishData} initAjax={this.initAjax} key={this.state.key} /></TabPane> <TabPane tab="供应商索赔" key={2}><ClaimantTable claimantData={this.state.claimantData} claimantD={this.claimantD} info={this.state.info} key={this.state.key1} /></TabPane> </Tabs> </div> ) } } export default PunishClaimant;
export const cipher = text => { let textToChars = text => text.split('').map(c => c.charCodeAt(0)) let byteHex = n => ("0" + Number(n).toString(16)).substr(-2) let applySaltToChar = code => textToChars(process.env.REACT_APP_SALT).reduce((a, b) => a ^ b, code) return text.split('') .map(textToChars) .map(applySaltToChar) .map(byteHex) .join('') } export const decipher = encoded => { let textToChars = text => text.split('').map(c => c.charCodeAt(0)) let applySaltToChar = code => textToChars(process.env.REACT_APP_SALT).reduce((a, b) => a ^ b, code) return encoded.match(/.{1,2}/g) .map(hex => parseInt(hex, 16)) .map(applySaltToChar) .map(charCode => String.fromCharCode(charCode)) .join('') } export const formatDate = date => { let diff = Date.now() - Date.parse(date) let days = diff / 86400000 let hours = diff / 3600000 let minutes = diff / 60000 if (days < 1) { if (hours < 1) { return `Il y a ${Math.floor(minutes)} minute${Math.floor(minutes) === 1 ? '' : 's'}` } return `Il y a ${Math.floor(hours)} heure${Math.floor(hours) === 1 ? '' : 's'}` } return `Il y a ${Math.floor(days)} jour${Math.floor(days) === 1 ? '' : 's'}` }
//Export results for use in cost estimation model //Systemwide point of interest (POI) variable var sys_poi = []; var sys_poi_out = []; var sys_poi_depth = []; var sys_poi_flooded = []; var sys_switch_flooded = []; //Results variables var light_rail_flood_depths = []; var hvy_rail_flood_depths = []; var green_line_depth = []; var red_line_depth = []; var orange_line_depth = []; var blue_line_depth = []; var silver_line_depth = []; var green_line_depth_x = []; var red_line_depth_x = []; var orange_line_depth_x = []; var blue_line_depth_x = []; var silver_line_depth_x = []; //Read the point of interest (POI) data file specified d3.csv("Input/systemwide_POI.csv", function(data) { //Using the unary plus operator, convert from text to number data.forEach(function(d){ d.x = +d.x; }); //Create the relevant global variable sys_poi = _.groupBy(data,'Line'); }); //Flood depth summary statistics function async function flood_depths_out() { //Reset results variables all_rail_flood_depths = []; light_rail_flood_depths = []; hvy_rail_flood_depths = []; green_line_depth = []; red_line_depth = []; orange_line_depth = []; blue_line_depth = []; silver_line_depth = []; all_rail_flood_depths_x = []; green_line_depth_x = []; red_line_depth_x = []; orange_line_depth_x = []; blue_line_depth_x = []; silver_line_depth_x = []; sys_poi_out = []; //For each line listed in key_list for (const key of key_list) { //And for each x-depth pair for each line for (i = 0; i < (rpt_elev[key].length - 1); i++) { //console.log(key + i); //Interpolate the segment of interest (between i and i+1) await segment_interpolation(rpt_elev[key][i].x, rpt_elev[key][i].y0, rpt_elev[key][i].y1, rpt_elev[key][i+1].x, rpt_elev[key][i+1].y0, rpt_elev[key][i+1].y1, key); } //Get the rpt_elev data associated with each POI by merging with rpt_elev sys_poi_out[key] = merge_object_arrays(sys_poi[key],JSON.parse(JSON.stringify(rpt_out[key])),"x"); } //Sort the results variables light_rail_flood_depths.sort(function(a,b){return b - a;}); hvy_rail_flood_depths.sort(function(a,b){return b - a;}); depth_x_processing(red_line_depth, red_line_depth_x); depth_x_processing(orange_line_depth, orange_line_depth_x); depth_x_processing(blue_line_depth, blue_line_depth_x); depth_x_processing(green_line_depth, green_line_depth_x); depth_x_processing(silver_line_depth, silver_line_depth_x); depth_x_processing(all_rail_flood_depths, all_rail_flood_depths_x); } //Segment interpolation set up function async function segment_interpolation(x_i,y0_i,y1_i,x_j,y0_j,y1_j,key_i) { //Get the slope and local intercept (where x_i = 0) of the depth function var m_d = (y1_j - y1_i - y0_j + y0_i)/(x_j - x_i); var b_d = y1_i - y0_i; //For the length of the segment of interest at the pre-specified increment for (x = 0; x < (x_j - x_i); x += 10) { await in_segment_interpolate(m_d,b_d,x,key_i); } } //In-segment interpolation function async function in_segment_interpolate(md, bd, x_i,key_i) { //Get the depth of interest depth = Math.max(0,Math.round((md*x + bd + Number.EPSILON) * 10) / 10); //IF the depth is nonzero, push to all rail output variable if (depth != 0) { all_rail_flood_depths.push(depth); } //Push the result to the correct output variable if (key_i.includes('GL') == true) { //Green Line (light rail) light_rail_flood_depths.push(depth); //Push to depth variable green_line_depth.push(depth); } else if (key_i.includes('SL') == true) { //Silver Line (BRT) silver_line_depth.push(depth); } else { //Red, Blue, Orange (heavy rail) hvy_rail_flood_depths.push(depth); //Push to relevant depth variable if (key_i.includes('RL') == true) { red_line_depth.push(depth); } else if (key_i.includes('OL') == true) { orange_line_depth.push(depth); } else if (key_i.includes('BL') == true) { blue_line_depth.push(depth); } } } //Depth_x data sorting and length pairing async function depth_x_processing(line_depth, line_depth_x) { //Initialize x variable var x_temp = 0; //Sort the depth_x data of interest line_depth.sort(function(a,b){return b - a;}); //For each sorted data point for (i = 0; i < line_depth.length; i ++) { //Make a x - depth pair, push to the specified depth_x variable line_depth_x.push({"x": x_temp, "depth": line_depth[i]}); //Iterate x_temp by 10 ft x_temp += 10; } } //Get the flood depths associated with each POI async function poi_depth_processing() { //Initialize variables var depth_temp = 0; sys_poi_depth = []; sys_poi_flooded = []; sys_switch_flooded = []; //For each line in key list for (const key of key_list) { //And for each POI for (poi = 0; poi < (sys_poi_out[key].length - 1); poi++) { //If there is a POI listed if (sys_poi_out[key][poi].POI != undefined) { //If the POI is not in sys_poi_depth if (sys_poi_flooded.includes(sys_poi_out[key][poi].POI) == false && sys_poi_out[key][poi].POI.includes("switch") == false && (sys_poi_out[key][poi]["Maximum HGL Feet"] - sys_poi_out[key][poi].invert_elev) > 0.1) { //Check to see if there is another x value associated with the POI (i.e., if the POI is a station) if (poi+1 < sys_poi_out[key].length && sys_poi_out[key][poi+1].POI == sys_poi_out[key][poi].POI) { //If so, then average the flood depths depth_temp = 0.5*((sys_poi_out[key][poi]["Maximum HGL Feet"] - sys_poi_out[key][poi].invert_elev) + (sys_poi_out[key][poi+1]["Maximum HGL Feet"] - sys_poi_out[key][poi+1].invert_elev)); } else { //Else, simply provide the depth at the POI depth_temp = sys_poi_out[key][poi]["Maximum HGL Feet"] - sys_poi_out[key][poi].invert_elev; } //Push the POI to the sys_poi_depth variable and the sys_poi_flooded variable sys_poi_depth.push({POI: sys_poi_out[key][poi].POI, depth: depth_temp, x: sys_poi_out[key][poi].x, Line: key}); sys_poi_flooded.push(sys_poi_out[key][poi].POI); //Else, if the POI is a switch } else if (sys_poi_flooded.includes(sys_poi_out[key][poi].POI) == false && sys_poi_out[key][poi].POI.includes("switch") == true) { //Get the flood depth depth_temp = sys_poi_out[key][poi]["Maximum HGL Feet"] - sys_poi_out[key][poi].invert_elev; //If the depth is nonzero if (depth_temp > 0.1) { //Push to sys_switch_flooded variable sys_switch_flooded.push({x: sys_poi_out[key][poi].x, depth: depth_temp, Line: sys_poi_out[key][poi].Line}); } } } } } }
import { Container } from "@material-ui/core"; import React from "react"; import Controls from "../../components/patient-ui/Echannelling/Controls"; import { Form } from "../../components/patient-ui/Echannelling/useForm"; import { useState } from "react"; import { useParams } from "react-router-dom"; import channellServices from "../../services/echannelling.Service"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import { useHistory } from "react-router"; import sessionServices from "../../services/doctorSession.service"; import { Button } from "@material-ui/core"; export default function EForm() { let { sessionID } = useParams(); const history = useHistory(); //demo button for the form const DemoChanell = () => { setFullName("Wishwa Gayanath Rathnaweera"); setEmailAddress("anjanadinethra@hotmail.com"); setNICNumber("981662067V"); setMobileNumber("0767990025"); setAge("23"); }; const handleSubmit = (e) => { console.log("submitted"); e.preventDefault(); const data = { session: sessionID, fullname: fullname, nic: nic, email: email, mobile: mobile, age: age, }; //validation of the form feilds if (data.email.includes("@" && ".com", 0)) { } else { toast.error("Invalid Email type please renter your Email address", { className: "error-toast", draggable: true, position: toast.POSITION.TOP_RIGHT, autoClose: false, }); // alert("email should contain a @"); return null; } var tempNic = data.nic; if (tempNic.length === 10) { } else { toast.error( "Invalid ID number {it must contain 9 digits and a V character at the end", { className: "error-toast", draggable: true, position: toast.POSITION.TOP_RIGHT, autoClose: false, } ); return null; } if ( data.mobile.includes( "0" || "1" || "2" || "3" || "4" || "5" || "6" || "7" || "8" || "9", 0 ) ) { } else { toast.error("Please ONLY enter numbers to the mobile number feild", { className: "error-toast", draggable: true, position: toast.POSITION.TOP_RIGHT, autoClose: false, }); return null; } var tempMobile = data.mobile; if (tempMobile.length === 10) { // alert("number sucessfull"); } else { toast.error("Mobile number must contain 10 digits", { className: "error-toast", draggable: true, position: toast.POSITION.TOP_RIGHT, autoClose: false, }); // alert("number must contain 10 digits"); return null; } var tempAge = data.age; if (tempAge.length === 2) { } else { toast.error("Invalid Age", { className: "error-toast", draggable: true, position: toast.POSITION.TOP_RIGHT, autoClose: false, }); return null; } //Create chanelling channellServices .create(data) .then(() => { sessionServices .increaseAppointmentCount(sessionID) .then(() => { history.push("/payments"); }) .catch((error) => { alert("couldn't update session : " + error); }); }) .catch((e) => { alert("this is the error:" + e); }); }; const [fullname, setFullName] = useState(""); const [nic, setNICNumber] = useState(""); const [email, setEmailAddress] = useState(""); const [mobile, setMobileNumber] = useState(""); const [age, setAge] = useState(""); const handlenameChange = (event) => { setFullName(event.target.value); }; const handlenicChange = (event) => { setNICNumber(event.target.value); }; const handleemailChange = (event) => { setEmailAddress(event.target.value); }; const handlmboileChange = (event) => { setMobileNumber(event.target.value); }; const handleageChange = (event) => { setAge(event.target.value); }; const [isDisabled, setIsDisabled] = useState(true); function changeCheck() { setIsDisabled(!isDisabled); } return ( <Container maxWidth="md"> <h3>E Channelling</h3> <h4>For channelling entry your details below</h4> <br /> <Form onSubmit={handleSubmit}> <container> <Controls.Input name="fullname" label="Full Name" value={fullname} onChange={handlenameChange} required /> <Controls.Input label="National Identity Card Number (NIC)" name="nic" value={nic} onChange={handlenicChange} required /> <Controls.Input label="Email" name="email" value={email} onChange={handleemailChange} required /> <Controls.Input label="Mobile" name="mobile" value={mobile} onChange={handlmboileChange} required /> <Controls.Input label="Age" name="age" value={age} onChange={handleageChange} required /> <Controls.Checkbox name="isConfirm" label="Confirming that all the above entered details are correct!" onChange={changeCheck} /> <div className="buttonAlignRight"> <Controls.Button disabled={isDisabled} type="submit" text="Channel" /> <Button size="medium" variant="contained" color="secondary" onClick={DemoChanell} > DEMO </Button> <ToastContainer /> </div> </container> </Form> </Container> ); }
import React from "react"; import Layout from "./../components/Layout/Layout"; import SimpleCard from "./../components/SimpleCard/SimpleCard"; import { Table, TableRow, TableHead, TableHeader, TableBody, TableCell, Button, } from "carbon-components-react"; import { useParams } from "react-router-dom"; import { connect } from "react-redux"; import { TrashCan16 } from "@carbon/icons-react"; function ContactStatus(props) { const { id } = useParams(); const deleteContact = () => {}; const contact = props.contacts.find((elm) => { return elm.id === id; }); return ( <div className="contact-status"> <SimpleCard title={contact.id}> <Layout col={2} first={ <div> <p> This is a list with all your contact’s available variables. To call them in the message, just type it’s name inside curly braces. </p> <br /> <br /> <p> If you call a variable that doesn’t exists, “undefined” is going to appear on its place in the message. </p> </div> } second={ <Table> <TableHead> <TableHeader> <h3>Available variables</h3> </TableHeader> </TableHead> <TableBody> {contact.variables.map((elm, i) => { return ( <TableRow key={i}> <TableCell> {`{ ${elm} }`}</TableCell> </TableRow> ); })} </TableBody> <TableHead> <TableHeader> <h3>Contacts Available</h3> </TableHeader> </TableHead> <TableBody> <TableRow> <TableCell> {contact.length} contacts </TableCell> </TableRow> </TableBody> </Table> } /> <Button onClick={deleteContact} kind="danger" renderIcon={TrashCan16}> Delete contact list </Button> </SimpleCard> </div> ); } const stateToProps = (state) => { return { contacts: state.firestore.ordered.contacts, }; }; export default connect(stateToProps)(ContactStatus);
export default { createReviewRequest: "CREATE_REVIEW_REQUEST", createReviewResponse: "CREATE_REVIEW_RESPONSE", deleteReviewRequest: "DELETE_REVIEW_REQUEST", deleteReviewResponse: "DELETE_REVIEW_RESPONSE" };
import React, { Component } from 'react'; import DatatableComponent from './Datatable.js' import './App.css'; import Modal from 'react-bootstrap/lib/Modal'; import Button from 'react-bootstrap/lib/Button'; const List = ({ items}) => ( <ul> { Object.keys(items).map((e, i) => (<li><h4>{e}: </h4>{items[e]}</li>)) } </ul> ); class App extends Component { constructor(props) { super(props) this.state = {showModal: false, description: {}} } showDetails(data) { this.setState({ description : data }); this.setState({ showModal : true }); } close(event) { // close modal event.preventDefault(); this.setState({ showModal : false }); } selectCategory(event) { this.refs.datatable.onCategoryChanged(event.target.value); } render() { return ( <div className="App"> <header className="App-header"> <h1 className="App-title">Star Wars</h1> <select onChange={this.selectCategory.bind(this)}> <option value="people">People</option> <option value="planets">Planets</option> <option value="films">Films</option> <option value="species">Species</option> <option value="vehicles">Vehicles</option> <option value="starships">Starships</option> </select> </header> <DatatableComponent className='datatable' name='datatable' ref="datatable" onCellClicked={this.showDetails.bind(this)}></DatatableComponent> <Modal className='modal' show = {this.state.showModal}> <Modal.Header> <Modal.Title> Description </Modal.Title> <Button className='closeBtn' onClick={this.close.bind(this)}>Close</Button> </Modal.Header> <Modal.Body> <List items={this.state.description} /> </Modal.Body> </Modal> </div> ); } } export default App
import React, { useContext, useState } from 'react'; import cn from 'classnames'; import { SliderButton } from '../SliderButton'; import { ForecastCard } from '../ForecastCard'; import style from './style.module.css'; import { StateContext } from '../../../../app/App'; import { setDaily, setHourly } from '../../../../state/actions'; export const ForecastPanel = () => { const { state: { timezone, nextDayId, daily, hourly, forecast, isFetching, }, dispatch, } = useContext(StateContext); const [leftDisabled, setLeftDisabled] = useState(false); const [rightDisabled, setRightDisabled] = useState(true); const cards = forecast === 'daily' ? daily : hourly; const setCards = forecast === 'daily' ? setDaily : setHourly; const onSlideLeft = () => { setRightDisabled(false); dispatch(setCards([...cards.slice(1).concat(cards[0])])); } const onSlideRight = () => { setLeftDisabled(false); dispatch(setCards([cards[cards.length - 1], ...cards.slice(0, -1)])); }; return ( <div className={style.forecast__panel}> <div className={style.forecast__body}> <div className={style["forecast-body__cards"]}> { cards.map((card) => { return ( <ForecastCard key={card.dt} forecast={forecast} data={card} timezone={timezone} isFirst={card.dt === nextDayId} showSpinner={isFetching} /> ) }) } </div> </div> <SliderButton className={cn(style["forecast-button"], style["forecast-button_reversed"], leftDisabled && style["forecast-button_disabled"])} onClick={onSlideLeft} /> <SliderButton className={cn(style["forecast-button"], rightDisabled && style["forecast-button_disabled"])} onClick={onSlideRight} /> </div> ) };
(function () { 'use strict'; angular.module('veegam-trials') .service('signupService', signupService); signupService.$inject = ['httpservice', 'apiUrl']; function signupService(httpservice, apiUrl) { var self = this; apiUrl = apiUrl + "/signup-service"; //check if username already exists. self.isUserNameExist = function (userName) { var url = apiUrl + '/user/username/' + userName + '/exists'; return httpservice.get(url); } //check if user email already exists. self.isUserEmailExist = function (email) { var url = apiUrl + '/user/useremail/' + email + '/exists'; return httpservice.get(url); } //create new publisher. self.createUser = function (publisher) { var url = apiUrl + '/signup'; return httpservice.post(url, publisher); } self.updateMetadata = function(metadata) { var url = apiUrl + '/user'; return httpservice.put(url, metadata); } return self; } })();
// Predict 1: // a count from 0 to 14 // Predict 2: // a count containing 3,6,9 // Predict 3: // prints 1,4,5,8,12,13,16 console.log("Predict 1 Results") for(var num = 0; num < 15; num++){ console.log(num); } console.log("") console.log("Predict 2 Results") for(var i = 1; i < 10; i+=2){ if(i % 3 == 0){ console.log(i); } } console.log("") console.log("Predict 3 Results") for(var j = 1; j <= 15; j++){ if(j % 2 == 0){ j+=2; } else if(j % 3 == 0){ j++; } console.log(j); }
import "./App.css"; import { NoAuthService, TokenAuthService } from "./service/auth_service"; import React, { Component } from "react"; import EmulatorScreen from "./components/emulator_screen"; import LoginPage from "./components/login_page"; import { ThemeProvider } from "@material-ui/styles"; const development = !process.env.NODE_ENV || process.env.NODE_ENV === "development"; var EMULATOR_GRPC = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port; if (development) { EMULATOR_GRPC = "http://localhost:8080"; } export default class App extends Component { constructor(props) { super(props); if (development) { this.auth = new NoAuthService({ onLogin: () => this.setState({ loggedIn: true }), onUnauthorized: () => this.setState({ loggedIn: false }) }); } else { this.auth = new TokenAuthService({ auth_uri: EMULATOR_GRPC + "/token", onLogin: () => this.setState({ loggedIn: true }), onUnauthorized: () => this.setState({ loggedIn: false }) }); } this.state = { loggedIn: this.auth.isLoggedIn() }; } render() { const { loggedIn } = this.state; return ( <ThemeProvider> {loggedIn ? ( <EmulatorScreen uri={EMULATOR_GRPC} auth={this.auth} /> ) : ( <LoginPage auth={this.auth} /> )} </ThemeProvider> ); } }
(function () { 'use strict'; angular .module('videoForm') .config(config); function config($stateProvider) { $stateProvider .state('videoForm', { url: '/video-form', views: { 'mainView': { templateUrl: 'video-form/video-form.tpl.html', controller: 'VideoFormCtrl', controllerAs: 'videoForm' }, 'layoutView': { templateUrl: 'partials/layoutView.html' } } }) .state('videoFormUpdate', { url: '/video-form/:videoId/:videotype', views: { 'mainView': { templateUrl: 'video-form/video-form.tpl.html', controller: 'VideoFormCtrl', controllerAs: 'videoForm' }, 'layoutView': { templateUrl: 'partials/layoutView.html' } } }); } }());
import React, { Component } from 'react'; import InfoItem from "../../components/InfoPanel/InfoItem"; import PropTypes from "prop-types"; class AdsCount extends Component { render() { return ( <InfoItem info={{ icon_color: "icon icon-info", icon: "fab fa-buysellads", value: "Adverts", fname: this.props.count }} /> ); } } AdsCount.propTypes = { count: PropTypes.string }; export default AdsCount;
/** * Created by ALTAIR on 06.04.2016. */ var RedColor = React.createClass({ render: function () { var lit = this.props.turnedOn ? 'color red on' : 'color red'; return ( <div id="redLight" className={lit}></div> ); } }); var YellowColor = React.createClass({ render: function () { var lit = this.props.turnedOn ? 'color yellow on' : 'color yellow'; return( <div id="yellowLight" className={lit}></div> ); } }); var GreenColor = React.createClass({ render: function () { var lit = this.props.turnedOn ? 'color green on' : 'color green'; return( <div id="greenLight" className={lit}></div> ); } }); var DataInput = React.createClass({ handleChange: function () { this.props.onUserInput ( this.refs.switchInput.checked ); }, render: function () { return ( <div className="dataInput"> <label > <input type="checkbox" checked={this.props.switchedOn} ref="switchInput" onChange={this.handleChange} /> On/Off </label> <button>&#x25BC;</button> </div> ) } }); var Semaphore = React.createClass({ getInitialState: function () { return {switchedOn: false, litRed: false, litYellow: false, litGreen: false}; }, handleUserInput: function (switchedOn) { this.setState({ switchedOn: switchedOn}); var msg = switchedOn ? 'Traffic Lights were switched On' : 'Traffic Lights were switched Off'; console.log(msg); if(!switchedOn) { this.setState({litRed: false, litYellow: false, litGreen: false}); clearInterval(needStop); document.getElementsByClassName('color')[0].innerHTML = ''; document.getElementsByClassName('color')[1].innerHTML = ''; document.getElementsByClassName('color')[2].innerHTML = ''; } else { setTimeout(this.step1,0); } }, step1: function () { if(this.state.switchedOn) { this.setState({litRed: true, litYellow: false, litGreen: false}); countdown('red', 10, this.step2, this.step1a); } else { this.setState({litRed: false, litYellow: false, litGreen: false}); } }, step1a: function () { this.setState({litYellow: true}); }, step2: function () { if(this.state.switchedOn) { this.setState({litYellow: false, litRed: false, litGreen: true}); countdown('green', 10, this.step1, this.step2a); } else { this.setState({litRed: false, litYellow: false, litGreen: false}); } }, step2a: function () { this.setState({litRed: false, litYellow: false, litGreen: false}); setTimeout(this.greenon, 500); var c = 3; var greenoff = this.greenoff; var greenon = this.greenon; var i = setInterval(function () { greenoff(); var j = setTimeout(greenon , 500); c--; if (c == 0) { greenoff(); clearInterval(i); clearTimeout(j); } } , 1000); }, greenon: function () { if(this.state.switchedOn) { this.setState({litGreen: true}); } }, greenoff: function () { if(this.state.switchedOn) { this.setState({litGreen: false}); } }, render: function () { return ( <div className="semaphore"> <RedColor turnedOn = {this.state.litRed} /> <YellowColor turnedOn = {this.state.litYellow} /> <GreenColor turnedOn = {this.state.litGreen} /> <DataInput switchedOn = {this.state.switchedOn} onUserInput = {this.handleUserInput} /> </div> ); } }); ReactDOM.render( <Semaphore />, document.getElementById('container') );
import Model from './Model'; import Component from './components/ViewProxy'; // Controller links Model and view class Controller { constructor(extent) { this.model = new Model({ extent }); let { xmin, ymin, xmax, ymax } = this.model.extent; this.view = new Component({ position: 'topright', xmin, ymin, xmax, ymax }); this.model.watch('extent', (val) => { this.view.update({ xmin: val.xmin, ymin: val.ymin, xmax: val.xmax, ymax: val.ymax }); }); } }; export default Controller;
import React from 'react'; import PropTypes from 'prop-types'; import Input from './elements/Input'; import InputGroup from './elements/InputGroup'; import Button from './elements/Button'; const AddGrocery = ({ onSubmit }) => ( <form className="container" onSubmit={onSubmit}> <h1> Add a Grocery Item{' '} <span className="glyphicon glyphicon-search" aria-hidden="true" /> </h1> <InputGroup name="name" labelText="Name"> <Input name="name" /> </InputGroup> <InputGroup name="price" labelText="Price"> <Input name="price" /> </InputGroup> <InputGroup name="quantity" labelText="Quantity"> <Input name="quantity" /> </InputGroup> <InputGroup name="category" labelText="Category"> <Input name="category" /> </InputGroup> <Button type="submit" color="primary"> Save Grocery Item </Button> </form> ); AddGrocery.propTypes = { onSubmit: PropTypes.func.isRequired }; export default AddGrocery;
var Tickets = Backbone.Collection.extend({ url: '/api/v1/tickets', parse: function(response) { return response.tickets; } });
import { combineReducers } from 'redux'; import commonReducer from './commonSlice'; import entranceReducer from './entranceSlice'; import writeReducer from './writeSlice'; import postcardReducer from './postcardSlice'; import postcardsReducer from './postcardsSlice'; import expireReducer from './expireSlice'; export default combineReducers({ common: commonReducer, entrance: entranceReducer, write: writeReducer, postcard: postcardReducer, postcards: postcardsReducer, expire: expireReducer, });
const COUNTDOWN = "COUNTDOWN"; const UPDATE_ROOM_STATE = "UPDATE_ROOM_STATE"; const RESET_ROOM = "RESET_ROOM"; const START_ROOM = "START_ROOM"; const TURN_TAKEN = "TURN_TAKEN"; const RESET_REQUEST_PROMPT = "RESET_REQUEST_PROMPT"; const WAITING_RESPONSE_PROMPT = "WAITING_RESPONSE_PROMPT"; const DECLINE_PROMPT = "DECLINE_PROMPT"; const ACCEPT_PROMPT = "ACCEPT_PROMPT"; const RESET_UI = "RESET_UI"; const DISPLAY_ALERT = "DISPLAY_ALERT"; export default { COUNTDOWN, UPDATE_ROOM_STATE, RESET_ROOM, START_ROOM, TURN_TAKEN, RESET_REQUEST_PROMPT, WAITING_RESPONSE_PROMPT, DECLINE_PROMPT, ACCEPT_PROMPT, RESET_UI, DISPLAY_ALERT }
const express = require('express'); const app = express(); const server = app.listen(9000); const io = require('socket.io')(server); var path = require("path"); var bodyParser = require('body-parser'); var session = require('express-session'); const flash = require('express-flash') var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/messageboard', { useNewUrlParser: true }); mongoose.Promise = global.Promise; app.use(express.static(__dirname + "/static")); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(flash()); app.use(bodyParser.urlencoded({ extended: true })); app.use(session({ secret: "It's Over 9000!", saveUninitialized: true, resave: false, cookie: { maxAge: 60000 } })) //=================================================================== // Schemas //=================================================================== const CommentSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Name must be 2 characters long'], minlength: 2 }, comment: { type: String, required: [true, 'Enter a Comment'], minlength: 2 }, }, { timestamps: true }) const MessageSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Name must be 2 characters long'], minlength: 2 }, message: { type: String, required: [true, 'Enter a Message'], minlength: 2 }, comment: [CommentSchema] }, { timestamps: true }) mongoose.model('Comment', CommentSchema); mongoose.model('Message', MessageSchema); var Comment = mongoose.model('Comment'); var Message = mongoose.model('Message'); //=================================================================== // Route to render and show index //=================================================================== app.get('/', (req, res) => { Message.find({}, (err, msg_arr, com_arr) => { if (err) { console.log('error!!!!', err) } else { console.log(msg_arr) res.render('index', { messages: msg_arr, comments: com_arr, }) } }) }) app.post('/addmsg', (req, res) => { console.log('POST DATA', req.body); Message.create(req.body, (err, data) => { if (err) { console.log('something went wrong', err) for (var key in err.errors) { req.flash('reg', err.errors[key].message) } res.redirect('/') } else { console.log('successfully added a message') res.redirect('/') } }) }) app.post('/addcomment', (req, res) => { console.log('POST DATA', req.body); Comment.create(req.body, (err, data) => { if (err) { console.log('something went wrong', err) for (var key in err.errors) { req.flash('reg', err.errors[key].message) } res.redirect('/') } else { Message.findOneAndUpdate({ _id: req.body.msg_id }, { $push: { comment: data } },(err, data) => { if (err) { console.log("Error adding comment to message", err.message) res.redirect("/") } else { console.log("Successfully added comment to message") res.redirect("/") } }) } }) }) app.get('*', (req, res) => { res.send("404 not a valid URL") });
$(document).ready(function() { var area = $('#inputAreaCite').val(); // area selected var month = $('#inputMonth').val(); // month selected var day = $('#inputDay').val(); // day selected // listen sockets socket.on('new-cite-registered', function(res) { // if date created by other user is not this selected if (res.date !== getDate().trim()) { return; } // 'delete' hour of DOM $("#inputHour").find('option[id="' + res.hour + '-option"]').remove(); }); // on change area $('#inputAreaCite').click(function() { // if area is equal at old if (area === $(this).val()) { return; } // new area value area = $(this).val(); // show alert loading getLoading("Obteniendo horarios disponibles....", "Loading.."); // load new area by date of database getHours(area, getDate()); }); // on change month $("#inputMonth").change(function() { // if area is equal at older if (month === $(this).val()) { return; } // new month value month = $(this).val(); // show alert loading getLoading("Obteniendo horarios disponibles....", "Loading.."); // get horary by date of database getHours(area, getDate()); }); // on change day $("#inputDay").change(function() { // if day is equal at older if (day === $(this).val()) { return; } // new day value day = $(this).val(); // show alert loading getLoading("Obteniendo horarios disponibles....", "Loading.."); // get horary by date getHours(area, getDate()); }); // submit data $("#form-cite").submit(function(event) { // prevent submit event.preventDefault(); // if area no select if ($('#inputArea').val() === '0') { return showDataInvalidArea(); } // show alert loading getLoading('Loading', 'Por favor espere.'); // submit data $.post("/cite", getDataCite(), function() {}) .done(function() { $('#inputDescription').val(''); // reset description input swal.fire( 'Cita registrada!', 'Se ha registrado la cita con éxito.', 'success' ); }) .fail(function(errResp) { showError(errResp, true); // show error }); }); });
import React from 'react' import { storiesOf } from '@storybook/react' import SearchBar from '../components/SearchBar/SearchBar' storiesOf('SearchBar', module) .add('default state', () => ( <SearchBar onSubmit={() => console.log('hey')}/> ))
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import './House.css'; class House extends React.Component { render() { return ( <Link to={"/requestDetail/userId/" + this.props.user_id + "/requestId/" + this.props.request_id} className="collection-item"> {this.props.listing.city} </Link> ) } } House.propTypes = { listing: PropTypes.object.isRequired, request_id: PropTypes.string.isRequired, user_id: PropTypes.string.isRequired, } export default House
//index.js //获取应用实例 const app = getApp() Page({ data: { }, onLoad: function () { var that = this wx.request({ url: "http://localhost:8080/lock/getDeviListInfo.action?method=getDeviList", headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }, success: function (res) { //请求成功 //console.log(res.data);//在调试器里打印网络请求到的json数据 that.setData({ list_data: res.data.body }) }, fail: function (res) { // 请求失败 } }) }, add: function () { wx.navigateTo({ url: '../addHouse/addHouse' }) }, viewByid(event){ if(event.currentTarget.dataset.s){ console.log(event.currentTarget.dataset.s); wx.navigateTo({ url: '../viewHouse/viewHouse?id=' + event.currentTarget.dataset.s, }) } }, setByid(event) { if (event.currentTarget.dataset.s) { console.log(event.currentTarget.dataset.s); wx.navigateTo({ url: '../setHouse/setHouse?id=' + event.currentTarget.dataset.s, }) } } })
// Your task is to make function, which returns the sum of a sequence of integers. // The sequence is defined by 3 non-negative values: begin, end, step (inclusive). // If begin value is greater than the end, function should returns 0 // Examples // 2,2,2 --> 2 // 2,6,2 --> 12 (2 + 4 + 6) // 1,5,1 --> 15 (1 + 2 + 3 + 4 + 5) // 1,5,3 --> 5 (1 + 4) // const sequenceSum = (begin, end, step) => { // // May the Force be with you // }; //parameters //start number, end number, interval //return // the sum of the array created //examples //console.log(sequenceSum(2, 6, 2)) //12 //console.log(sequenceSum(1, 5, 1)) //15 //console.log(sequenceSum(1, 5, 3)) //5 //pseudocode // need to create and array using the first two parameters, and increment with the third integer //need to reduce the array const sequenceSum = (begin, end, step) => { let numArr = []; for (let i = begin; i <= end; i += step) { numArr.push(i); } console.log(numArr) return numArr.reduce((a,b) => a + b, 0) }; console.log(sequenceSum(2, 6, 2))
import React from 'react'; import {convertDate} from '../user/UserItem'; const ProductItem = props => { const { product, deleteProduct, handleUpdateClick } = props; return ( <tr key={product.id}> <th>{product.name}</th> <th>{product.carat}</th> <th>{product.price}</th> <th>{product.stock}</th> <th>{product.description}</th> <th>{product.createdAt}</th> <th><button className="btn btn-default" onClick={deleteProduct}>Delete</button></th> <th><button className="btn btn-default" onClick={handleUpdateClick}>Update</button></th> </tr> ) } export default ProductItem;
var fs = require('fs'); var http = require('http'); var mime = require('mime-types'); const $path = require('path'); var port = process.env.PORT || 5000; http.createServer(function (request, response) { let contentType = 'text/plain'; let data; let path = request.url; let file = '.' + decodeURIComponent(request.url); file = $path.resolve(file); let publicDir = $path.resolve('.'); if (!file.startsWith(publicDir)) { data = "Error: you are not permitted to access that file."; response.statusCode = 403; // Forbidden console.log("User requested file '" + request.url + "' (not permitted)"); file = null; } else if (path === '/') { file = 'index.html'; } else if (path.indexOf('.') === -1) { file = 'index.html'; } else { file = '.' + decodeURIComponent(request.url); } try { if (file) { console.log('Serving ' + file); data = fs.readFileSync(file); contentType = mime.lookup(file); } } catch (error) { console.log(error); data = "Error: " + error.toString(); response.statusCode = 404; } response.setHeader('Content-Type', contentType + '; charset=utf-8'); response.write(data); response.end(); }).listen(port); console.log("Listening on port " + port);
import React from 'react'; import Aux from "../../../hoc/_Aux"; import Cart from '../Cart'; import './CartList.css'; const cart = new Cart(); class CartList extends React.Component { constructor(props) { super(props); this.state = { products: [], total_price: 0, }; var self = this; cart.getCart().then((result) => { self.setState({ products: result.products, total_price: result.total_price}); }); } componentDidMount() { var self = this; cart.getCart().then(function (result) { self.setState({ products: result.products, total_price: result.total_price}); }); } removeProductOfCartClick(product){ console.log(product); var self = this; cart.removeProductofCart(product).then(function (result) { self.componentDidMount(); }); } render() { return ( <Aux> <div className="card shopping-cart"> <div className="card-header bg-dark text-light"> Carrito de compras <i className="fa fa-shopping-cart" aria-hidden="true"></i> <a href="/shop" className="btn btn-outline-info btn-sm pull-right">Continuar Comprando</a> <div className="clearfix"></div> </div> <div className="card-body"> {this.state.products.map( cart_item => <div key={cart_item.product.pk} className="row"> <div className="col-12 col-sm-12 col-md-2 text-center"> <img className="img-size" alt={cart_item.product.pk} src={cart_item.product.image} /> </div> <div className="col-12 text-sm-center col-sm-12 text-md-left col-md-6"> <h4 className="product-name"><strong>{cart_item.product.id_product}</strong></h4> <h4> <small>{cart_item.product.description}</small> </h4> </div> <div className="col-12 col-sm-12 text-sm-center col-md-4 text-md-right row"> <div className="col-3 col-sm-3 col-md-6 text-md-right"> <h6><strong>${cart_item.product.price} <span className="text-muted">x</span></strong></h6> </div> <div className="col-4 col-sm-4 col-md-4"> <div className="quantity"> <input type="button" value="+" className="plus"/> <input type="number" step="1" max="99" min="1" value={cart_item.quantity} title="Qty" className="qty" size="4"/> <input type="button" value="-" className="minus"/> </div> </div> <div className="col-2 col-sm-2 col-md-2 text-right"> <button onClick={(e) => {this.removeProductOfCartClick(cart_item.product)}}type="button" className="btn btn-outline-danger btn-xs"> <i className="fa fa-trash" aria-hidden="true"></i> </button> </div> </div> </div> )} <div className="pull-right"> <a href='/' className="btn btn-outline-secondary pull-right"> Actualizar carrito de compras </a> </div> </div> <div className="card-footer"> <div className="pull-right"> <a href='/' className="btn btn-success pull-right">Proceder al Pago</a> <div className="pull-right m-2"> Precio total: <b>${this.state.total_price}</b> </div> </div> </div> </div> </Aux> ); } } export default CartList;
const rules = require("./rules"); const webpack = require("webpack"); const webpackMerge = require("webpack-merge"); const path = require("path"); module.exports = { context: path.join(__dirname, ".."), entry: ["./src/test.ts"], output: { filename: "build.js", path: path.resolve("temp"), publicPath: "/" }, resolve: { extensions: [ ".ts", ".js", ".json" ] }, devtool: "inline-source-map", module: webpackMerge({ rules: rules }, { // coverage rules: [ { test: /^((?!\.spec\.ts).)*.ts$/, exclude: /node_modules|\.spec\.js$/, loader: "istanbul-instrumenter-loader", enforce: "post", options: { esModules: true } }] }) };
import React from 'react'; import MySlider from './MySlider'; class Background extends React.Component { constructor(props) { super(props); this.state = { redValue: 0, blueValue: 0, greenValue: 0 }; } render() { return ( <div className="Parent-background-sliders"> <div className="Background-sliders"> <MySlider /> </div> </div> ); } } export default Background;
var searchData= [ ['audio_5fframes_5fper_5fvideo_5fframe_677',['audio_frames_per_video_frame',['../group__TransportControl.html#gaf28a3e9ee8b36a92309de372093f56f3',1,'jack_position_t']]] ];
// initialize the app const lib = { model: {}, view: {}, controller: {} };
import { userReducer } from '../userReducer'; import * as actions from '../../actions'; describe('userReducer reducer', () => { it('should return initial state', () => { expect(userReducer(undefined, {})).toEqual({}) }) it('should return a success case', () => { const state = {} const body = { email: 'awef@awef.com', id: 1000, } const actionResult = actions.userLogInSuccess(body) const expected = { email: 'awef@awef.com', id: 1000 } expect(userReducer(state, actionResult)).toEqual(expected) }) it('should return a failed case if something goes wrong', () => { const state = {} const body = { message: 'something' } const actionResult = actions.userLogInFail(body) const expected = {message: 'something'}; expect(userReducer(state, actionResult)).toEqual(expected) }) })
let mongoose = require('mongoose'); //连接数据库 mongoose.connect('mongodb://localhost/yonghu', { useNewUrlParser: true }); //上一行的yonghu指的是mongodb中的仓库名 //创建一个对象模型 var userSchema = new mongoose.Schema({ userTelNum:{ type:String, validate:{ validator: function(v) { return /^[1-9]\d{10}$/.test(v); }, message: "wrong1" }, require:[true,'wrong1'] }, userEmail:{ type:String, validate: { validator: function(v) { return /^[1-9]\d{7,10}@qq\.com$/.test(v); }, message: "wrong2" }, require:[true,'wrong2'] }, password:{ type:String, validate:{ validator: function(v) { return /^[a-zA-Z0-9]{8}$/.test(v); }, message: "wrong3" }, require:[true,'wrong3'] }, passwordSecond:{ type:String, validate:{ validator: function(v) { return /^[a-zA-Z0-9]{8}$/.test(v); }, message: "wrong4" }, require:[true,'wrong4'] }, gender:{ type:String, }, yonghuming:{ type:String, }, gexing:{ type:String, } }) //将对象和仓库数据导出去给其他地方引入 module.exports = mongoose.model('yonghu',userSchema);
export const DOMAIN_NAME = "https://phallery.herokuapp.com";
import React, { PropTypes } from 'react'; import { getObject } from '../../../common/common'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './TenantCurrency.less'; import {SuperTable, SuperToolbar, Indent} from '../../../components/index'; const TOOLBAR_EVENTS = ['onClick']; const TABLE_EVENTS = ['onCheck', 'onDoubleClick', 'onLink']; const props = { tableCols: PropTypes.array, tableItems: PropTypes.array, buttons: PropTypes.array }; class TenantCurrency extends React.Component { static propTypes = props; static PROPS = Object.keys(props); toToolbar = () => { const props = { buttons: this.props.buttons, option: {bsSize: 'small'}, callback: getObject(this.props, TOOLBAR_EVENTS) }; return <SuperToolbar {...props} />; }; toTable = () => { const {tableCols, tableItems} = this.props; const props = { cols: tableCols, items: tableItems, callback: getObject(this.props, TABLE_EVENTS) }; return <SuperTable {...props}/>; }; render = () => { return ( <Indent className={s.root}> {this.toToolbar()} {this.toTable()} </Indent> ); }; } export default withStyles(s)(TenantCurrency);
$(document).ready(function(){ $('table.invoice tfoot tr.addnew td:first button').click( function(e) { e.preventDefault(); var departmentField = $('table.invoice tfoot tr.addnew td:eq(1) input:first'); var descriptionField = $('table.invoice tfoot tr.addnew td:eq(1) input:eq(1)'); var costField = $('table.invoice tfoot tr.addnew td:last input'); departmentField.siblings('span').remove(); costField.siblings('span').remove(); if (!departmentField.val().length) { $(departmentField).after('<span>Please enter a title for this invoice entry</span>'); } else if (!costField.val().length) { $(costField).after('<span>Please enter a cost for this invoice entry</span>'); } else { var randomnumber = Math.floor(Math.random()*10000); $('table.invoice tbody').append( '<tr><td><input type="checkbox" checked="checked" name="includeextras[]" value="ext'+randomnumber+'" /></td><td><input type="text" value="'+departmentField.val()+'" name="ext'+randomnumber+'_department" /><input type="text" value="'+descriptionField.val()+'" name="ext'+randomnumber+'_description" /></td><td colspan="5"></td><td>&pound;<input type="text" value="'+costField.val()+'" name="ext'+randomnumber+'_cost" /></td></tr>' ); departmentField.val(''); departmentField.siblings('span').remove(); descriptionField.val(''); costField.val(''); costField.siblings('span').remove(); } }); $('span.recalculate').click( function (e) { $(e).calculateCost(); }); }); $.fn.calculateCost = function () { var totalCost = parseFloat(0); $('table.invoice tbody tr').find('td:last input').each ( function() { if ( parseFloat($(this).val()) ) totalCost += parseFloat($(this).val()); }); $('span.total').text(totalCost.toString()); }
var countOfPagesScrolled = 0; var searchPhrase = "Developer"; function scrollDown(height, countOfPagesScrolled){ scroll(0, document.body.clientHeight); setTimeout(function(){ if(height != document.body.clientHeight && countOfPagesScrolled > 0){ scrollDown(document.body.clientHeight, --countOfPagesScrolled); }else return sendRequest(); }, 1500); } function sendRequest(){ var contactsNum = 0; $.each( $('div.mn-person-card__card-actions button.mn-person-card__person-btn-ext'), function() { $(this).each(function() { $.each(this.attributes, function() { if(this.specified) { if (this.name.indexOf("data-ember-action-") >= 0){ var allInf = $("#ember"+(this.value-4)).text(); if (allInf.indexOf(searchPhrase) >= 0){ console.log($("#ember"+(this.value-4)).text()); contactsNum++; $(this).click(); } } } }); }); }); console.log('Just added contacts: ' + contactsNum); } scrollDown(document.body.clientHeight, countOfPagesScrolled);
var btnTranslate = document.querySelector("#btn-translate"); var txtInput = document.querySelector("#txt-input"); var output1Div = document.querySelector("#output"); var output2Div = document.querySelector("#weather"); function getTranslationURL(text){ return "https://api.openweathermap.org/data/2.5/weather?q=" + text + "&APPID=2b17d5a956eb1b02dcf3663da14bad12" } function errorHandler(error){ console.log("Error Occured", error); alert("Something wrong with server. Try again Later!") } function clickHandler() { var inputText = txtInput.value; // taking input // calling server for processing fetch(getTranslationURL(inputText)) .then(response => response.json()) .then(json => { var translatedText = json.main.temp - 273; var emoji; if(translatedText <=5 ){ emoji = "🌨️" } else if(translatedText > 5 && translatedText <= 20){ emoji = "❄" } else if(translatedText > 20 && translatedText <= 35){ emoji = "⛅" } else{ emoji = "☀️" } var weather = json.weather[0]["description"]; output1Div.innerText = translatedText.toFixed(0) + "°C" + emoji; output2Div.innerText = "Weather: " + weather; }) .catch(errorHandler) }; btnTranslate.addEventListener("click", clickHandler)
function () { var env = karate.env; // get system property 'karate.env' projectID = 1879048400 mjennerID = 1879048288 polearyID = 1879049107 karate.configure('connectTimeout', 6000000); karate.configure('readTimeout', 6000000); var config = { env: env, serverUrl : 'https://qa122.aconex.com/', password : 'ac0n3x72' } return config; }
import DOM from "./DOM" DOM.createDOM();
const { expect } = require('chai'); const noOutOfScopeVars = require('../checks/no-out-of-scope-vars'); describe("No Out Of Scope Variables", () => { it("skips if there is no orders file", async () => { const deployment = { serviceName: "streamliner" }; const results = await noOutOfScopeVars(deployment); expect(results.length).to.equal(0); }); it("accepts orders with no undefined variable use.", async () => { const deployment = { serviceName: "streamliner", ordersPath: "streamliner/orders", ordersContents: [ "export SOMETHING=hello", 'MORE="You had me at $SOMETHING"', 'echo "${MORE}"', ] } const results = await noOutOfScopeVars(deployment); expect(results.length).to.equal(0); }); it("rejects orders that reference undefined variables.", async () => { const deployment = { serviceName: "streamliner", ordersPath: "streamliner/orders", ordersContents: [ "export SOMETHING=hello", 'MORE="You had me at $SOMETHING"', 'echo "${MORE}"', "export JWT_ACCESS_FLAGS=$(($JWT_ROLE_GLG_USER | $JWT_ROLE_GLG_CLIENT))" ] } const results = await noOutOfScopeVars(deployment); expect(results.length).to.equal(1); expect(results[0]).to.deep.equal({ title: "Out of Scope Variable Reference", line: 4, level: "failure", path: deployment.ordersPath, problems: [ "GDS requires that all referenced variables be defined within the `orders` file. `.starphleet` has been deprecated.", "**Undefined Variable:** `JWT_ROLE_GLG_USER`", "**Undefined Variable:** `JWT_ROLE_GLG_CLIENT`", ] }) }); })
(function () { 'use strict'; angular .module('app.core') .factory('mockdata', mockdata); function mockdata() { var service = { getUnqueuedAircraft: getUnqueuedAircraft, getQueuedAircraft: getQueuedAircraft }; return service; function getUnqueuedAircraft() { var unqueuedAircraft = [ {id: 'JB1345', name: 'JetBlue 1345', type: 'Passenger', size: 'Small'}, {id: 'D534', name: 'Delta 534', type: 'Passenger', size: 'Large'}, {id: 'FEDX12', name: 'FedEx 12', type: 'Cargo', size: 'Small'}, {id: 'UPS7234', name: 'UPS 7234', type: 'Cargo', size: 'Large'}, {id: 'ALA23', name: 'Alaskan Airlines 23', type: 'Passenger', size: 'Small'}, {id: 'UN564', name: 'United 564', type: 'Passenger', size: 'Large'}, {id: 'US2351', name: 'USAir 2351', type: 'Cargo', size: 'Small'} ]; return unqueuedAircraft; } function getQueuedAircraft() { var queuedAircraft = [ {id: 'VA254', name: 'Virgin America 254', type: 'Passenger', size: 'Small'}, {id: 'JB556', name: 'JetBlue 556', type: 'Passenger', size: 'Small'}, {id: 'UPS672', name: 'UPS 672', type: 'Cargo', size: 'Small'}, {id: 'FEDX447', name: 'FedEx 447', type: 'Cargo', size: 'Large'}, {id: 'SW111', name: 'SouthWest 111', type: 'Passenger', size: 'Large'} ]; return queuedAircraft; } } })();
describe('P.behaviors.exercises.Descriptions', function() { 'use strict'; var Behavior = P.behaviors.exercises.Descriptions, Overlay = P.overlays.exercises.Description; var SimpleTestView = P.views.Item.extend({ template: function() { return '<span class="js-exercise-description">C&J</span>'; }, behaviors: { test: { behaviorClass: Behavior, Overlay: Overlay } } }); describe('getOverlayView', function() { // Avoid executing functions that are actually Backbone classes. it('returns Backbone views without calling them', function() { var behav = new Behavior({ Overlay: Overlay }); expect(behav.getOverlayView()).toBe(Overlay); }); it('returns the result of functions', function() { var behav = new Behavior({ Overlay: function() { return 66; } }); expect(behav.getOverlayView()).toBe(66); }); }); describe('showDescription', function() { beforeEach(function() { // Stubs spyOn(Overlay.prototype, 'initialize'); spyOn(Overlay.prototype, 'render'); spyOn(Sisse, 'showOverlay'); spyOn(Sisse, 'getUser').and.returnValue({ id: 'test' }); this.model = new Backbone.Model({ who: 'test' }); this.view = new SimpleTestView({ model: this.model }); this.view.render(); }); it('passes the name of exercise to the overlay class', function() { this.view.$('.js-exercise-description').click(); expect(Overlay.prototype.initialize).toHaveBeenCalledWith({ name: 'C&J' }); }); it('passes the owner id if it isnt the current user', function() { this.model.set('who', 'other-guy'); this.view.$('.js-exercise-description').click(); expect(Overlay.prototype.initialize).toHaveBeenCalledWith({ name: 'C&J', who: 'other-guy' }); }); }); });
/** * Created by zhuo on 2017/9/13. */ var fightState = new ListBox(); fightState.enemies = []; fightState.fightLog = []; fightState.lastState = mainState;//上一个场景 fightState.selectWindow = new ListBox(); fightState.inited = false; fightState.bgImg = null; fightState.init = function () { fightState.list = [operItems.checkEnemies, operItems.use, operItems.skill, operItems.escape]; fightState.bgGroup = game.add.group();//background image group fightState.fightWindowGroup = game.add.group(); fightState.logWindowGroup = game.add.group(); //选择窗初始化 fightState.selectWindow.group = game.add.group(); fightState.selectWindow.list = []; fightState.selectWindow.list.push({ name: '观察敌人', aDown: function () { //观察敌人只弹窗就算了 fightState.setVisible(false); selectEnemyDialog.reOpen(fightState.enemies, fightState, function cb(selectedItem) { var message = "名称:" + selectedItem.name + "\n" + selectedItem.desc + "\n物理抗性:" + selectedItem.pysicDefense + "\n魔法抗性:" + selectedItem.magicDefense; myAlertDialog.reOpen(message, function () { selectEnemyDialog.setVisible(true); currentCustomState = selectEnemyDialog; }, { font: "bold 20px Arial", fill: "#FFAEB9", boundsAlignH: "center", boundsAlignV: "middle" }, selectEnemyDialog); }); } }, { name: '使用道具', aDown: function () { fightState.setVisible(false); fightItemDialog.reOpen(player.getFightItems()); } }, { name: '技能', aDown: function () { fightState.setVisible(false); skillDialog.reOpen(player.getSkills()); } }, { name: '逃跑', aDown: function () { fightState.setVisible(false); myAlertDialog.reOpen('确定逃跑?\n\n需要计算成功率\n有失败可能', function cb() { currentCustomState = fightState; fightState.setVisible(true); fightState.escape(); }, null, fightState); } }); fightState.selectWindow.reset(); //set bg img this.bgImg = game.add.image(0,0,'mahojin',null,this.bgGroup); this.bgImg.height = 500; this.bgImg.width = 500; this.bgGroup.visible = false; this.bgGroup.fixedToCamera = true; this.inited = true; } fightState.escape = function () { var escapeSpeed = player.speed; var enemiesSpeed = 0; for (var i = this.enemies.length - 1; i >= 0; i--) { enemiesSpeed += this.enemies[i].speed; } if (escapeSpeed > enemiesSpeed) {//脱离战斗 this.setVisible(false); currentCustomState = mainState; mainState.setVisible(true); } else { this.addLog('逃跑失败!') this.playerTurnOver(); } } fightState.reOpen = function (enemies, lastState) { if(!fightState.inited){ this.init(); } fightState.enemies = enemies || []; fightState.lastState = lastState || mainState; fightState.turnNum = 0;//回合数 //清空log this.fightLog.splice(0, this.fightLog.length); this.addLog('进入战斗! 遭遇' + enemies.length + '个敌人!'); this.judgeFirstFight(); this.newTurnStart();//新回合开始 //change state fightState.lastState.setVisible(false); mainState.setVisible(false); currentCustomState = fightState; fightState.setVisible(true); fightState.reRender(); } fightState.reRender = function () { // console.info("I want to re-render"); this.renderFightWindow(); this.renderLogWindow(); //reset this.selectWindow.reset(); this.renderSelectWindow(); } //每次渲染调用 fightState.renderFightWindow = function () { // console.info("I want to render fight scene"); fightState.fightWindowGroup.removeAll(true); var leftStyle = {font: "bold 20px Arial", fill: "#9AFF9A", boundsAlignH: "left", boundsAlignV: "middle"}; var rightStyle = {font: "bold 20px Arial", fill: "#FFB5C5", boundsAlignH: "right", boundsAlignV: "middle"}; var titleStyle = {font: "bold 22px Arial", fill: "#FFFFFF", boundsAlignH: "center", boundsAlignV: "middle"}; //场景名称 var text = game.add.text(0, 0, "战斗场景", titleStyle); text.setTextBounds(0, 0, 500, 50); text.fixedToCamera = true; fightState.fightWindowGroup.add(text); //渲染玩家 var text = game.add.text(0, 0, player.name + '\t HP:' + player.health + '/' + player.maxHealth, leftStyle); text.setTextBounds(10, 50, 230, 50); text.fixedToCamera = true; fightState.fightWindowGroup.add(text); //渲染怪物 (function renderMonsterList() { var list = fightState.enemies; for (var i = 0; i < list.length; i++) { var the = list[i]; var text = game.add.text(0, 0, 'HP:' + the.health + '/' + the.maxHealth + '\t' + the.name, rightStyle); text.setTextBounds(260, i * 50 + 50, 230, 50); text.fixedToCamera = true; fightState.fightWindowGroup.add(text); } })(); } fightState.renderLogWindow = function () { var startX = 0; var startY = 250; fightState.logWindowGroup.removeAll(true); var style = {font: "bold 14px Arial", fill: "#9AFF9A", boundsAlignH: "left", boundsAlignV: "middle"}; var logStart = fightState.fightLog.length - 8; if (logStart < 0) logStart = 0; var logList = fightState.fightLog.slice(logStart, fightState.fightLog.length); //渲染记录 (function renderMonsterList() { var list = logList; for (var i = 0; i < logList.length; i++) { var text = game.add.text(0, 0, list[i].msg, style); text.setTextBounds(startX + 5, i * 30 + startY, 235, 30); text.fixedToCamera = true; fightState.logWindowGroup.add(text); } })(); } fightState.renderSelectWindow = function () { var startX = 250; var startY = 250; var group = this.selectWindow.group; group.removeAll(true); var style = {font: "bold 14px Arial", fill: "#fff", boundsAlignH: "right", boundsAlignV: "middle"}; var list = this.selectWindow.displayList; //渲染选项 (function renderSelections() { for (var i = 0; i < list.length; i++) { var text = game.add.text(0, 0, list[i].name, style); text.setTextBounds(startX + 5, i * 50 + startY, 235, 50); text.fixedToCamera = true; group.add(text); } })(); //渲染选择条 var barY = startY + (this.selectWindow.thePointer - this.selectWindow.displayListStart) * 50; var bar = game.add.graphics(); bar.beginFill(0x9AFF9A, 0.2); bar.drawRect(startX, barY, 235, 50); bar.fixedToCamera = true; group.add(bar); } fightState.setVisible = function (visible) { fightState.fightWindowGroup.visible = visible; fightState.logWindowGroup.visible = visible; fightState.selectWindow.group.visible = visible; fightState.bgGroup.visible = visible; } fightState.close = function () { //change current custom state fightState.setVisible(false); currentCustomState = this.lastState; this.lastState.reOpen(); } fightState.goDown = function () { fightState.selectWindow.thePointer++; fightState.selectWindow.displayListUpdate(); fightState.renderSelectWindow(); } fightState.goUp = function () { fightState.selectWindow.thePointer--; fightState.selectWindow.displayListUpdate(); fightState.renderSelectWindow(); } fightState.aDown = function () { var selected = fightState.selectWindow.getSelectedItem(); if (!selected)return; this.setVisible(false); selected.aDown(); // console.info('I selected: '+selected.name); } fightState.bDown = function () { // fightState.close(); return; } fightState.newTurnStart = function () { this.turnNum++; this.addLog('------回合' + this.turnNum + '开始------'); this.enemyFight(this.fastThanPlayer);//先手怪物 this.renderLogWindow(); this.renderFightWindow(); if (player.health < 1) { this.close(); mainState.gameReset(); } } fightState.clear = function () { } fightState.playerTurnOver = function () { //check fight over if (fightState.checkFightOver()) { return; } this.enemyFight(this.slowThanPlayer); this.renderFightWindow(); this.renderLogWindow(); if (player.health < 1) { console.log('你死了,health:'+player.health); this.close(); mainState.gameReset(); // myAlertDialog.reOpen('你死了', function () { // myAlertDialog.bDown(); // }, null, mainState); return; } // this.addLog('-------回合结束-------'); this.newTurnStart(); } fightState.checkFightOver = function () { for (var i = this.enemies.length - 1; i >= 0; i--) { if (this.enemies[i].health > 0)return false; } //counter exp var exp = 0; var items = []; for (var i = this.enemies.length - 1; i >= 0; i--) { exp += this.enemies[i].exp; items = items.concat(this.enemies[i].items); } //掉落道具 var itemsLog = '获得道具:'; for (var i = items.length - 1; i >= 0; i--) { itemsLog = itemsLog + items[i].name + ' '; player.getItem(items[i]); } this.close(); // myAlertDialog.reOpen('获得经验:' + exp + '\n' + itemsLog, function () { myAlertDialog.reOpen(itemsLog, function () { myAlertDialog.bDown(); }, null, mainState); return true; } fightState.judgeFirstFight = function () { var fastThanPlayer = []; var slowThanPlayer = []; var speed = player.speed; var enemies = this.enemies; for (var i = enemies.length - 1; i >= 0; i--) { if (enemies[i].speed < speed) { slowThanPlayer.push(enemies[i]); } else { fastThanPlayer.push(enemies[i]); } } this.fastThanPlayer = fastThanPlayer; this.slowThanPlayer = slowThanPlayer; } fightState.enemyFight = function (enemies) { for (var i = enemies.length - 1; i >= 0; i--) { if (enemies[i].isLiving) enemies[i].fuckPlayer(); } } fightState.addLog = function (msg) { this.fightLog.push({msg: msg}); } fightState.damageAnimaOn = function (num) { console.log('开始播放动画'); //创建一个短时动画 var damageAnima = game.add.sprite(350,50+50*num-10,'damage1',null,fightState.fightWindowGroup); damageAnima.fixedToCamera = true; damageAnima.animations.add('fuck',[1,2,3,4,5]); damageAnima.play('fuck',null,true); damageAnima.height = 60; damageAnima.width = 60; game.time.events.add(Phaser.Timer.HALF * 1, function () { damageAnima.destroy(); }, this); }
console.log("traverse-connect"); $( document ).ready(function() { console.log( "ready!" ); // Interesting life of dom elements ////////////////////////////////////// // tree traversals ***************************** // children(), parent(), parents(), parentsUntil() siblings(), closest(), find(), next(), nextAll(), nextUntil(), offsetParent(), , prev(), prevAll(), prevUntil() $(".music-gene").children().css( "color", "green"); // selects sibling elements except the specified element $(".jonas"). If two p tags have .jonas then both are selected. They hug and color each other. $(".jonas").siblings().css("color", "red"); // selects sibling div element if found but doesn't color ".knowls" $(".knowls").siblings('div').css("color", "aqua"); // Immediate catches hold of the element after the "taylor-the-heartless". a clear rebound. $(".taylor-the-showoff").next().css("color", "blue"); // Immediate catches hold of all the elements after itself. Everybody will do attitude. $(".justin-is-resting").nextAll().css("color", "blueviolet "); // bear it until a point then `we are done`. $(".giving-chances").nextUntil(".brake-up").css("color", "brown"); // prev(), prevAll() & prevUntil() Methods do exactlt like the above. Going back in time and reminiscing! // manipulations***************************** // .each() // $( "li" ).each(function( index ) { // console.log( index + ": " + $( this ).text() ); // }); // filtering ********************************** // filter(), first(), has(),is(), last(), map(), slice(),eq() $(".riri").has(".music-collaboration").css("background-color", "cyan "); $(".single-hits p").first().css("color", "burlywood "); $(".will-be-back-soon-guys p").last().css("color", "cadetblue"); // I have the power to randomly pick who ever i wish in the index. $(".song-now-playing").eq(3).css("color", "chartreuse"); // you can filter the elements $("li").filter(".still-disses").css("background-color", "coral"); // Miscellaneous ********************************** // add(), addBack(), andSelf(), contents(), end(), not() $(".pals").not(".no-invite").css("background-color", "cornflowerblue "); // **************************************************** // $( ".columns" ).find('a').css( "color", "green"); // $( ".columns" ).find('a').each(function(index, el) { // console.log(el) // var beta = $(this); // console.log(beta); // var title = beta.text(); // console.log(title) // }); // // console.log($(".box").find('p').text()) // ///////// // $(".box").filter(function(index) { // var data = $(this); // console.log(data) // var title = data.children().text(); // console.log(title) // // return something; // }); }); // $('div:not(:has(div)) [href*="hello/"]').css( "color", "red");//this works
/* * Module code goes here. Use 'module.exports' to export things: * module.exports.thing = 'a thing'; * * You can import it from another modules like this: * var mod = require('screeps.stats'); * mod.thing == 'a thing'; // true */ var logger = require("screeps.logger"); logger = new logger("screeps.stats"); var stats = function() { this.startOfMain = Game.cpu.getUsed(); this.startTick = function() { this.startOfMain = Game.cpu.getUsed(); this.mem = {}; this.mem.stats = {}; for(var s in RawMemory.segments) { logger.log(s) } if (RawMemory.segments[99]) { var mem = RawMemory.segments[99].split("\n"); this.mem = JSON.parse(mem[3]) logger.log(JSON.stringify(this.mem)) } if (!this.mem.stats.paths) { this.mem.stats.paths = {}; } this.mem.stats.paths.searches = 0; this.mem.stats.paths.searchCPU = 0; this.mem.stats.paths.flowsUsed = 0; this.mem.stats.paths.pathUsed = 0; } this.logTick = function() { return; if (Memory.profiler) { for (var func in Memory.profiler.map) { Memory.profiler.map[func].name=func; } var i = 0; var lim = 100; var m = _.sortBy(Memory.profiler.map, ["time"]); var totalTicks = Game.time - Memory.profiler.enabledTick; if (!this.mem.stats.profile) { this.mem.stats.profile = {}; } //logger.log("kjkjh--", m); for (var func in m) { var fData = m[func]; var p = fData.name.split("."); var on = p[0]; var fn = p[1]; //var n = fData.name.replace(".","-"); if (!this.mem.stats.profile[on]) { this.mem.stats.profile[on] = {}; } if (!this.mem.stats.profile[on][fn]) { this.mem.stats.profile[on][fn] = {}; } this.mem.stats.profile[on][fn].time = fData.time /totalTicks; this.mem.stats.profile[on][fn].calls = fData.calls / totalTicks; this.mem.stats.profile[on][fn].avg = fData.time / fData.calls; this.mem.stats.profile[on][fn].totalTicks = totalTicks; if (i >= lim) { break; } i++; } } this.setStat("gcl", "progress", Game.gcl.progress); this.setStat("gcl", "progressTotal", Game.gcl.progressTotal); this.setStat("gcl", "level", Game.gcl.level); this.setStat("cpu", "start", this.startOfMain); this.setStat("cpu", "bucket", Game.cpu.bucket); this.setStat("cpu", "limit", Game.cpu.limit); this.runningAvgStat("cpu", "change", Game.cpu.getUsed() - this.mem.lastCPU, 0.9); this.setStat("cpu", "getUsed", Game.cpu.getUsed()); this.runningAvgStat("cpu", "runningUsed", Game.cpu.getUsed(), 0.9); //turn this.mem.lastCPU = Game.cpu.getUsed() var headers = [] headers.push("application/json"); headers.push(Game.time); headers.push(new Date()); //logger.log(JSON.stringify( this.toGrafana("mem", this.mem))) RawMemory.segments[99] = headers.join("\n") + "\n" + JSON.stringify(this.mem); }, this.runningAvgStat = function(objName, statName, value, lerp) { // if (!lerp) { // lerp = 0.9; // } // if (!this.mem.stats[objName]) { // this.mem.stats[objName] = {}; // } // if (!this.mem.stats[objName][statName]) { // this.mem.stats[objName][statName] = value; // } // this.mem.stats[objName][statName] = this.mem.stats[objName][statName]*lerp + value*(1-lerp); } this.setStat = function(objName, statName, value) { // if (!this.mem.stats[objName]) { // this.mem.stats[objName] = {}; // } // this.mem.stats[objName][statName] = value; }, this.setSubStat = function(objName, statName, subStatName, value) { // if (!this.mem.stats[objName]) { // this.mem.stats[objName] = {}; // } // if (!this.mem.stats[objName][statName]) { // this.mem.stats[objName][statName] = {}; // } // this.mem.stats[objName][statName][subStatName] = value; }, this.pathSearched = function(cpuUsed) { // this.mem.stats.paths.searches++; // this.mem.stats.paths.searchCPU += cpuUsed; }, this.flowUsed = function() { // this.mem.stats.paths.flowsUsed++; }, this.pathUsed = function() { // this.mem.stats.paths.pathUsed++; }, this.toGrafana = function(name, obj) { var out = []; if (_.isObject(obj) || _.isArray(obj)) { for(var i in obj) { var converted = this.toGrafana(name + (name.length > 0 ? "." : "") + i, obj[i]); //logger.log(i, JSON.stringify(converted)) out = out.concat(converted); } } else { out.push(name + " " + obj); } return out; } this.fromGrafana = function(dataString) { var lines = dataString.split("\n"); var out = {}; for(var l in lines) { var line = lines[l]; logger.log("doin line", line) parts = line.split(" "); var name = parts[0]; var value = parts[1]; var path = name.split("."); var curTarget = out; for(var loc in path) { var thisName = path[loc] var lastInPath = loc == path.length-1; if (lastInPath) { curTarget[thisName] = value; } else { if (!curTarget[thisName] ) { curTarget[thisName] = {}; } curTarget = curTarget[thisName]; } } curTarget = value; } return out; } this.logRoomTick = function(roomManager) { } }; module.exports = stats;
$(function () { var h = $("#content").height(); var h2 = $(".breadcrumb").height(); $("#content .row-fluid").height(h - h2); DungouViewer.init("earth"); // 加载球模型 DungouViewer.initLeftClick(globalviewer,function(){}); var surveymanager = new SurveyManager(globalviewer,function(){}); initPipingPit(); /** *工具栏按钮点击 */ $("#appendTools i").each(function(){ $(this).click(function(){ $(".detailInfo").hide(); if($(this).hasClass("active")){ //设置方法为none surveymanager.setSurveyType(SurveyType.NONE); //移除原有的监听事件 DungouViewer.removeListener(); //初始化相应的监听事件 switch ($(this).attr("id")) { //统计查询 case "TJCX": $("#img").hide(); surveymanager.setSurveyType(SurveyType.QUERY) break; //距离测量 case "JLCL": $("#echartarea").hide(); $("#img").hide(); surveymanager.setSurveyType(SurveyType.LINE_DISTANCE); break; //方位测量 case "FWCL": $("#echartarea").hide(); $("#img").hide(); surveymanager.setSurveyType(SurveyType.Azimuth_DISTANCE); break; //面积测量 case "MJCL": $("#echartarea").hide(); $("#img").hide(); break; //地面刨切 case "DMPQ": $("#echartarea").hide(); surveymanager.setSurveyType(SurveyType.Geology_SLICING); break; //其他 default: break; } }else{ //隐藏echarts和img窗口 $("#echartarea").hide(); $("#img").hide(); //删除三维页面所有的线、标签 //设置方法为none surveymanager.setSurveyType(SurveyType.NONE); //初始化原有的监听事件 DungouViewer.initLeftClick(globalviewer,function(){}); } }); }); }); var centerpoint = []; /** * 通过计算插入管道(管道无ID) * @param lon 经度 * @param lat 纬度 * @param height 高度 * @param gdlength 管道长度 * @param num 数量 * @returns geometryInstances 数组 */ function calculateZB1(longitude,latitude,height,gdlength,num){ //地理坐标 var cartographic1 = {longitude:2.0534816290463516, latitude:0.6811787630410361,height:height}; var cartographic2 = {longitude:2.053488770056539, latitude:0.6811771826112164,height:height}; //经度差值 var amplitude1 = (cartographic1.longitude-cartographic2.longitude); //纬度差值 var amplitude2 = (cartographic1.latitude-cartographic2.latitude); //地理坐标转世界坐标 var cartesian1 = globalviewer.scene.globe.ellipsoid.cartographicToCartesian (cartographic1); var cartesian2 = globalviewer.scene.globe.ellipsoid.cartographicToCartesian (cartographic2); //两点距离的平方 var dsquare = FreeDo.Cartesian3.distanceSquared(cartesian1,cartesian2); //gblength所对应的经度差值与纬度差值 var proportion = Math.pow(gdlength,2)/dsquare; var gbamplitude1 = amplitude1*Math.sqrt(proportion); var gbamplitude2 = amplitude2*Math.sqrt(proportion); //geometryInstances var DTWL = []; //临时起始点 var tempZB1 = {longitude:longitude, latitude:latitude} //临时终止点 var tempZB2 = {longitude:0, latitude:0} for (var i = 1; i <=num; i++) { tempZB2.longitude = tempZB1.longitude-gbamplitude1; tempZB2.latitude = tempZB1.latitude-gbamplitude2; //centerpoint.push({lon:tempZB1.lon-d1/2,lat:tempZB1.lat-d2/2,height:height}); var obj = new Freedo.GeometryInstance({ geometry : new Freedo.PolylineVolumeGeometry({ //vertexFormat : Freedo.VertexFormat.DEFAULT,2.0534816290463516, latitude: 0.6811787630410361 polylinePositions : Freedo.Cartesian3.fromRadiansArrayHeights([ tempZB1.longitude, tempZB1.latitude, height, tempZB2.longitude, tempZB2.latitude, height ]), shapePositions : computeCircle(5.0) }), attributes : { color : Freedo.ColorGeometryInstanceAttribute.fromColor(Freedo.Color.DARKGRAY) } }); tempZB1.longitude=tempZB2.longitude; tempZB1.latitude=tempZB2.latitude; //console.log(tempZB1.longitude+","+tempZB1.latitude); DTWL.push(obj); } return DTWL; } /** * 通过计算插入管道 * @param lon 经度 * @param lat 纬度 * @param height 高度 * @param gdlength 管道长度 * @param num 数量 * @returns geometryInstances 数组 */ function calculateZB2(longitude,latitude,height,gdlength,num){ //地理坐标 var cartographic1 = {longitude:2.0534816290463516, latitude:0.6811787630410361,height:height}; var cartographic2 = {longitude:2.053488770056539, latitude:0.6811771826112164,height:height}; //经度差值 var amplitude1 = (cartographic1.longitude-cartographic2.longitude); //纬度差值 var amplitude2 = (cartographic1.latitude-cartographic2.latitude); //地理坐标转世界坐标 var cartesian1 = globalviewer.scene.globe.ellipsoid.cartographicToCartesian (cartographic1); var cartesian2 = globalviewer.scene.globe.ellipsoid.cartographicToCartesian (cartographic2); //两点距离的平方 var dsquare = FreeDo.Cartesian3.distanceSquared(cartesian1,cartesian2); //gblength所对应的经度差值与纬度差值 var proportion = Math.pow(gdlength,2)/dsquare; var gbamplitude1 = amplitude1*Math.sqrt(proportion); var gbamplitude2 = amplitude2*Math.sqrt(proportion); //geometryInstances var DTWL = []; //临时起始点 var tempZB1 = {longitude:longitude, latitude:latitude} //临时终止点 var tempZB2 = {longitude:0, latitude:0} for (var i = 1; i <=num; i++) { tempZB2.longitude = tempZB1.longitude-gbamplitude1; tempZB2.latitude = tempZB1.latitude-gbamplitude2; //centerpoint.push({lon:tempZB1.lon-d1/2,lat:tempZB1.lat-d2/2,height:height}); var obj = new Freedo.GeometryInstance({ id : "第"+i+"环", geometry : new Freedo.PolylineVolumeGeometry({ //vertexFormat : Freedo.VertexFormat.DEFAULT,2.0534816290463516, latitude: 0.6811787630410361 polylinePositions : Freedo.Cartesian3.fromRadiansArrayHeights([ tempZB1.longitude, tempZB1.latitude, height, tempZB2.longitude, tempZB2.latitude, height ]), shapePositions : computeCircle(5.0) }), attributes : { color : Freedo.ColorGeometryInstanceAttribute.fromColor(Freedo.Color.DARKGRAY) } }); tempZB1.longitude=tempZB2.longitude; tempZB1.latitude=tempZB2.latitude; DTWL.push(obj); } return DTWL; } function computeCircle(radius) { var positions = []; for (var i = 0; i < 360; i++) { var radians = Freedo.Math.toRadians(i); positions.push(new Freedo.Cartesian2(radius * Math.cos(radians), radius * Math.sin(radians))); } return positions; } /*//显示标牌 function showlabel(id,position){ $(".msgInfo").hide(); var pick= new FreeDo.Cartesian2(position.x,position.y); cartesian = globalviewer.scene.globe.pick(globalviewer.camera.getPickRay(pick), globalviewer.scene); if(id!=undefined&&id.indexOf("管道")>-1){ removeFollowLisener(); addFollowListener(); $(".msgInfo").html(id).show(); } } //标牌跟随移动 var cartesian= null; var flag = false; var htmlOverlay = document.getElementById('showmsg'); var addFollowListener=function(){ flag = globalviewer.scene.preRender.addEventListener(setScreenPostion); } var removeFollowLisener= function(){ if(flag==true){ globalviewer.scene.preRender.removeEventListener(setScreenPostion); flag = false; } } var setScreenPostion=function (){ var canvasPosition = globalviewer.scene.cartesianToCanvasCoordinates(cartesian); if (FreeDo.defined(canvasPosition)) { htmlOverlay.style.top = canvasPosition.y -150+ 'px'; htmlOverlay.style.left = canvasPosition.x +220+ 'px'; } }*/ //加载坑和管道 var guandao2 = null; function initPipingPit(){ var userdata2 =[ [ {lon:117.65370310938958,lat: 39.02934846731648,height:0}, {lon:117.65616588189279,lat: 39.02878641322159,height:0}, {lon:117.65606451946124,lat: 39.028480607240965,height:0}, {lon:117.66036385771528,lat: 39.02753995829354,height:0}, {lon:117.66010911739728,lat: 39.02689057245006,height:0}, {lon:117.6533791730346,lat: 39.02839160339337,height:0} ], [ {lon:117.65370310938958,lat: 39.02934846731648,height:-15}, {lon:117.65616588189279,lat: 39.02878641322159,height:-13}, {lon:117.65606451946124,lat: 39.028480607240965,height:-20}, {lon:117.66036385771528,lat: 39.02753995829354,height:-15}, {lon:117.66010911739728,lat: 39.02689057245006,height:-22}, {lon:117.6533791730346,lat: 39.02839160339337,height:-11} ], [ {lon:117.65370310938958,lat: 39.02934846731648,height:-27}, {lon:117.65616588189279,lat: 39.02878641322159,height:-33}, {lon:117.65606451946124,lat: 39.028480607240965,height:-26}, {lon:117.66036385771528,lat: 39.02753995829354,height:-22}, {lon:117.66010911739728,lat: 39.02689057245006,height:-32}, {lon:117.6533791730346,lat: 39.02839160339337,height:-24} ], [ {lon:117.65370310938958,lat: 39.02934846731648,height:-50}, {lon:117.65616588189279,lat: 39.02878641322159,height:-50}, {lon:117.65606451946124,lat: 39.028480607240965,height:-50}, {lon:117.66036385771528,lat: 39.02753995829354,height:-50}, {lon:117.66010911739728,lat: 39.02689057245006,height:-50}, {lon:117.6533791730346,lat: 39.02839160339337,height:-50} ] ] var imgarray = [ "static/page/shigongguanli/dungou/img/Land001.jpg", "static/page/shigongguanli/dungou/img/Land002.jpg", "static/page/shigongguanli/dungou/img/Land004.jpg" ]; FreeDoUtil.dig(globalviewer,userdata2,imgarray); var pitch = 0; var matrix = null; //盾构机旋转 globalviewer.scene.preRender.addEventListener(function(){ if(pitch>360)pitch=0; pitch = pitch+1; primitive.modelMatrix = getModelMatrix(180*2.0534865154587263/Math.PI,180*0.6811776815929453/Math.PI,-23,287,pitch,0,1.2,1.2,1.2); }); var primitive = globalviewer.scene.primitives.add(FreeDo.Model.fromGltf( { id: "盾构机", url: "static/page/shigongguanli/dungou/gltf/dun_gou_dao_tou.gltf", show: true, // default modelMatrix:getModelMatrix(180*2.0534865154587263/Math.PI,180*0.6811776815929453/Math.PI,-23,287,0,0,1.2,1.2,1.2), allowPicking: true, // not pickable debugShowBoundingVolume: false, // default debugWireframe: false })); console.log(primitive); var offsetwenli = new Freedo.Cartesian2(100, 1); var array1 = calculateZB1(2.0534816290463516,0.6811787630410361,-28,1.2,20); var array2 = calculateZB2(2.0534807581666916,0.6811761975379643,-28,1.2,344); var guandao1 = globalviewer.scene.primitives.add(new Freedo.Primitive({ geometryInstances : array1, appearance: new FreeDo.PerInstanceColorAppearance( { flat : true, translucent : false }) })); guandao2 = globalviewer.scene.primitives.add(new Freedo.Primitive({ geometryInstances : array2, appearance: new FreeDo.PerInstanceColorAppearance( { flat : true, translucent : false }) })); /*setInterval(function () { if (offsetwenli.x > 51) { offsetwenli.x = 50; } offsetwenli.x += 0.005; }, 10);*/ } function fanxuanTree(id){ var treeObj = $.fn.zTree.getZTreeObj("tree"); var nodes = treeObj.getNodes()[0].children; if (nodes.length>0) { treeObj.selectNode(nodes[id-1]); } } function getModelMatrix(lon,lat,height,heading,pitch,roll,scaleX,scaleY,scaleZ) { var scaleCartesian3=new FreeDo.Cartesian3(scaleX,scaleY,scaleZ); //获得三元素,直接通过数字获得 var scaleMatrix=FreeDo.Matrix4.fromScale(scaleCartesian3);//获得缩放矩阵 var position = FreeDo.Cartesian3.fromDegrees(lon,lat,height);//根据经纬高获得位置三元素 var heading=FreeDo.Math.toRadians(heading); var pitch=FreeDo.Math.toRadians(pitch); var roll=FreeDo.Math.toRadians(roll); var hpr=new FreeDo.HeadingPitchRoll(heading,pitch,roll); var transform=FreeDo.Transforms.headingPitchRollToFixedFrame(position,hpr);//获得姿态矩阵 var matrix4=new FreeDo.Matrix4(); FreeDo.Matrix4.multiply(transform,scaleMatrix,matrix4); return matrix4; }
import React, { Component } from "react"; import { Link } from "react-router-dom"; import Grid from '@material-ui/core/Grid'; import Button from '@material-ui/core/Button'; class Landing extends Component { render() { return ( <Grid container style={{height: "75vh"}} justify="center" alignItems="center" > <Grid item xs={12} container justify="center" alignItems="center"> <h2 style={{textAlign: "center"}}> Welcome to the Central Tutor Support Portal! </h2> </Grid> <Grid container justify="space-around"> <Grid item container justify="center" xs={4}> <Link to="/register" style={{ color: 'white', width: "100%", textDecoration: "none" }}> <Button size="large" variant="contained" color="primary" fullWidth> Register </Button> </Link> </Grid> <Grid item xs={4} container justify="center"> <Link to="/login" style={{ textDecoration: "none", width: "100%", color: "white" }}> <Button size="large" variant="contained" color="secondary" fullWidth> Log In </Button> </Link> </Grid> </Grid> </Grid> ); } } export default Landing;
import React from 'react' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' import withStates from "./components/hoc/withStates" import './App.css' import Navbar from "./components/navbar/Navbar" import Home from "./components/pages/Home" import About from "./components/pages/About" import Registration from "./components/registration/Registration" import Login from "./components/login/Login" import Alert from "./components/alert/Alert" import PrivateRoute from "./components/routing/PrivateRoute" import ClearDb from "./components/clearDb/ClearDb" function App() { return ( <Router> <Navbar /> <div className="container"> <Alert /> <Switch> <PrivateRoute exact path='/' component={Home} /> <PrivateRoute exact path='/about' component={About} /> <Route exact path="/registration" component={Registration} /> <Route exact path="/login" component={Login} /> <Route exact path="/clear" component={ClearDb} /> </Switch> </div> </Router> ) } export default withStates(App)
function ObjAjax() { var xmlhttp = false; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { xmlhttp = new XMLHttpRequest(); } return xmlhttp; } function BorrarUsuario(id, rolid, idfichausuario) { $.confirm({ title: 'Confirmación!', content: '¿Esta seguro que desea eliminar este usuario?', buttons: { confirm: function() { $.alert('Se ha eliminado correctamente'); var result = document.getElementById('tview'); const ajax = new ObjAjax(); ajax.open("POST", "main.php", true); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { if (ajax.status == 200) { result.innerHTML = ajax.responseText; $(document).ready(function() { $('#tableusuario').DataTable({ "language": { "url": "../assets/datatables/Spanish.json" } }); }); } else { console.log("Ups, Me equivoque;"); } } }; ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("ctrl=usuario&acti=eliminar&id=" + id + "&rol=" + rolid); }, cancel: function() { $.alert('Has cancelado la eliminación'); } } }); } function InsertUsuario() { var result = document.getElementById('tview'); var id = document.formulario.id.value; var nombre = document.formulario.nombre.value; var apellido = document.formulario.apellido.value; var contraseña = document.formulario.contraseña.value; var correo = document.formulario.correo.value; var rol = document.getElementById('rol').value; var estado = document.getElementById('estado').value; var identi = document.getElementById('identi').value; const ajax = new ObjAjax(); ajax.open("POST", "main.php", true); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { if (ajax.status == 200) { result.innerHTML = ajax.responseText; $(document).ready(function() { $('#tableusuario').DataTable({ "language": { "url": "../assets/datatables/Spanish.json" } }); }); } else { console.log("Ups, Me equivoque;"); } } }; ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("ctrl=usuario&acti=insertar&id=" + id + "&nombre=" + nombre + "&apellido=" + apellido + "&contraseña=" + contraseña + "&correo=" + correo + "&rol=" + rol + "&estado=" + estado + "&identi=" + identi); } function EditarUsuario(id, nombre, apellido, contraseña, correo, rol, estado, identi) { document.formulario.id.value = id; document.formulario.validationid.value = id; document.formulario.nombre.value = nombre; document.formulario.apellido.value = apellido; document.formulario.contraseña.value = ""; document.formulario.correo.value = correo; document.getElementById('rol').value = rol; document.getElementById('estado').value = estado; document.getElementById('identi').value = identi; document.getElementById("btnguardar").innerHTML = "Actualizar"; document.getElementById("titleusuario").innerHTML = "Actualizar usuario"; } function UpdateUsuario() { var result = document.getElementById('tview'); var valid = document.formulario.validationid.value; var id = document.formulario.id.value; var nombre = document.formulario.nombre.value; var apellido = document.formulario.apellido.value; var contraseña = document.formulario.contraseña.value; var correo = document.formulario.correo.value; var rol = document.getElementById('rol').value; var estado = document.getElementById('estado').value; var identi = document.getElementById('identi').value; const ajax = new ObjAjax(); ajax.open("POST", "main.php", true); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { if (ajax.status == 200) { result.innerHTML = ajax.responseText; $(document).ready(function() { $('#tableusuario').DataTable({ "language": { "url": "../assets/datatables/Spanish.json" } }); }); document.getElementById("btnguardar").innerHTML = "Crear"; } else { console.log("Ups, Me equivoque;"); } } }; ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("ctrl=usuario&acti=actualizar&nombre=" + nombre + "&apellido=" + apellido + "&contraseña=" + contraseña + "&correo=" + correo + "&rol=" + rol + "&estado=" + estado + "&identi=" + identi + "&id=" + id + "&valid=" + valid); document.getElementById('rol').value = rol; document.getElementById("titleusuario").innerHTML = "Crear usuario"; } function CancelarUsuario() { $(".alert").alert('close'); document.getElementById("btnguardar").innerHTML = "Crear"; document.getElementById("titleusuario").innerHTML = "Crear usuario"; } //codigo para agregar una ficha// function AgregarFicha(idusu) { var result = document.getElementById('umodal'); const ajax = new ObjAjax(); ajax.open("POST", "main.php", true); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { if (ajax.status == 200) { result.innerHTML = ajax.responseText; $("#modalfichasAll").modal("show"); document.getElementById("usuariofichaagregar").value = idusu; } else { console.log("Ups, Me equivoque;"); } } }; ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("ctrl=usuario&acti=selectficha&idss=" + idusu); } function AgregarCancelar() { document.getElementById("usuariofichaagregar").value = ""; } function AgregarFichaConfirmar() { var result = document.getElementById('tview'); var idusu = document.getElementById("usuariofichaagregar").value; var ficha = document.getElementById("fichaagregar").value; if(ficha != 0){ const ajax = new ObjAjax(); ajax.open("POST", "main.php", true); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { if (ajax.status == 200) { result.innerHTML = ajax.responseText; $(document).ready(function() { $('#tableusuario').DataTable({ "language": { "url": "../assets/datatables/Spanish.json" } }); }); document.getElementById("btnguardar").innerHTML = "Crear"; } else { console.log("Ups, Me equivoque;"); } } }; ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("ctrl=usuario&acti=agregarficha&ficha=" + ficha + "&idusu=" + idusu); }else{ $.alert("Sin fichas disponibles"); } } function EliminarFicha(usu_numdnt) { var result = document.getElementById('umodal'); const ajax = new ObjAjax(); ajax.open("POST", "main.php", true); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { if (ajax.status == 200) { result.innerHTML = ajax.responseText; document.getElementById("usuariofichaeliminar").value = usu_numdnt; $("#modalfichasUSU").modal("show"); } else { console.log("Ups, Me equivoque;"); } } }; ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("ctrl=usuario&acti=selectficha&idss=" + usu_numdnt); } function EliminarCancelar() { document.getElementById("fichaeliminar").value = ""; document.getElementById("fichaeliminar").value = ""; } function EliminarFichaConfirmar() { var result = document.getElementById('tview'); // var idusu = document.getElementById("usuariofichaeliminar").value; var usfid = document.getElementById("fichaeliminar").value; if(usfid != 0){ const ajax = new ObjAjax(); ajax.open("POST", "main.php", true); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { if (ajax.status == 200) { result.innerHTML = ajax.responseText; $(document).ready(function() { $('#tableusuario').DataTable({ "language": { "url": "../assets/datatables/Spanish.json" } }); }); } else { console.log("Ups, Me equivoque;"); } } }; ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("ctrl=usuario&acti=eliminarficha&usfid=" + usfid); }else{ $.alert("Sin fichas asignadas"); } } //Fin codigo para agregar una ficha// function ConfirmUsuario(id) { var result = document.getElementById('tview'); document.getElementById('rol').value = id; if (id == 3) { document.getElementById('NumDoc').innerHTML = "Numero identificador de ficha"; document.getElementById('UsuName').innerHTML = "Nombre Abreviatura"; document.getElementById('Last').innerHTML = "Numero ficha"; document.getElementById('apellido').removeAttribute("onkeypress"); document.getElementById('correolabel').innerHTML = "Nombre de usuario"; document.getElementById('correo').setAttribute("type", "text"); document.getElementById('divtipid').setAttribute("hidden", ""); document.getElementById("errorid").innerHTML = "Ingrese un Número identificador de ficha"; document.getElementById("errorname").innerHTML = "Ingrese un Nombre Abreviatura"; document.getElementById("errorlast").innerHTML = "Ingrese un Numero ficha"; document.getElementById("errorpass").innerHTML = "Ingrese una Contraseña"; document.getElementById("erroremail").innerHTML = "Introduzca un Nombre de usuario."; document.getElementById("errorestado").innerHTML = "Seleccione un Campo."; } const ajax = new ObjAjax(); ajax.open("POST", "main.php", true); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { if (ajax.status == 200) { result.innerHTML = ajax.responseText; $(document).ready(function() { $('#tableusuario').DataTable({ "language": { "url": "../assets/datatables/Spanish.json" } }); }); } else { console.log("Ups, Me equivoque;"); } } }; ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("ctrl=usuario&acti=seleccion&rolid=" + id); } function SeleccionarUsuario() { var result = document.getElementById('tview'); document.getElementById("NumDoc").innerHTML = "Numero de documento"; document.getElementById("UsuName").innerHTML = "Nombre"; document.getElementById('Last').innerHTML = "Apellido"; document.getElementById('apellido').setAttribute("onkeypress", "return soloLetras(event)"); document.getElementById("correolabel").innerHTML = "Correo"; document.getElementById('correo').setAttribute("type", "email"); document.getElementById('divtipid').removeAttribute("hidden"); document.getElementById("errorid").innerHTML = "Ingrese un Número de Documento"; document.getElementById("errorname").innerHTML = "Ingrese un Nombre"; document.getElementById("errorlast").innerHTML = "Ingrese un Apellido"; document.getElementById("errorpass").innerHTML = "Ingrese una Contraseña"; document.getElementById("erroremail").innerHTML = "Introduzca una Dirección de Correo Valida."; document.getElementById("errorestado").innerHTML = "Seleccione un Campo."; const ajax = new ObjAjax(); ajax.open("POST", "main.php", true); ajax.onreadystatechange = function() { if (ajax.readyState == 4) { if (ajax.status == 200) { result.innerHTML = ajax.responseText; } else { console.log("Ups, Me equivoque;"); } } }; ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("ctrl=usuario&acti=recargar"); } function VerPass() { if ($('#contraseña').attr('type') == 'password') { $('#contraseña').attr('type', 'text'); $('#vpss').attr('src', '../assets/img/img-perfil/ojonegro.svg'); } else { $('#contraseña').attr('type', 'password'); $('#vpss').attr('src', '../assets/img/img-perfil/invisible.svg'); } } function soloLetras(e) { var key = e.keyCode || e.which, tecla = String.fromCharCode(key).toLowerCase(), letras = " áéíóúabcdefghijklmnñopqrstuvwxyz", especiales = [8, 37, 39, 46], tecla_especial = false; for (var i in especiales) { if (key == especiales[i]) { tecla_especial = true; break; } } if (letras.indexOf(tecla) == -1 && !tecla_especial) { return false; } }
/* DOM(Document Object Model) 브라우저의 렌더링 머신이 웹문서를 로드한 후 파싱하여 메모리에 적제하는데 이를 DOM이라 한다. 모든 요소와 요소의 어트리뷰터, 텍스트를 각각의 객체로만들고 이들 객체를 트리로 구성한것. js를 통해 동적으로 변경 가능하다. * 기능 - html 문서에 대한 모델 구성 이 때 모델을 객체의 트리로 구성하고 이를 DOM Tree라고 한다. - html 문서 내의 각 요소에 접근/ 수정 DOM Tree DOM에서 모든 요소, 어트리뷰트, 텍스트는 하나의 객체이며 Document 객체의 자식이다. DOM Tree의 진입점은 document 객체이며 최종점은 요소의 텍스트를 나타네는 객체이다. * DOM Tree의 노드들 -문서 노드(Document Node) 트리의 최상위에 존재, 시작점(Entry point) 역할 -요소 노드(Element Node) HTML 요소를 표현. 요소들은 중첩에 의해 부자 관계를 가지며 이를 통해 정보를 구조화 한다. -어트리뷰트 노드(Attribute Node) 어트피뷰트는 요소의 자식이 아니라 요소의 일부로 표현됨. -텍스트 노드(Text Node) 텍스트 노드는 요소 노드의 자식이며 자식노드를 가질 수 없다. DOM Query/Traversing *DOM Query - document.getElementById(id) id 어트리뷰트 값으로 첫번째 요소를 반환한다. Return:HTMLElement를 상속받은 객체 - document.querySelector(cssSelector) CSS 셀렉터를 사용하여 첫번째 요소 반환 Return:HTMLElement를 상속받은 객체 - document.getElementByClassName(class) class 어트리뷰트 값으로 요소 노드를 모두 선택 공백으로 구분하여 여러 개의 class 지정할 수 있다. Return:HTMLCollection(Live) HTMLCollection은 유사배열객체 이고, Node의 상태를 실시간으로 반영하기 때문에(Live) 아예 배열화 시켜주는 것을 추천한다. - document.getElementsByTagName(tagName) 태그명으로 요소 노드를 모두 선택 Return:HTMLColection(live) - document.querySelectorAll(selector) 지정된 CSS 선택자를 사용하여 요소 노드를 모두 선택. Return: NodeList(non-Live) -> array가 아니지만 forEach 사용할 수 있다. *DOM Traversing(탐색) -ParentNode -firstChild, lastChild -firstElementChild, lastElementChild -hasChildNodes() 자식 노드가 있는지 확인 Return: Boolean 값 -childNodes 자식 노드의 컬렉션을 반환. 텍스트 요소를 포함한 모든 자식 요소를 반환. Return: NodeList(non-live) -children 자식 노드의 컬렉션을 반환. 자식 요소 중에서 Element type 요소 만을 반환. Return: HTMLCollection(live) -previousSibling, nextSibling 형제 노드를 탐색. text node를 포함한 모든 형제 노드를 탐색. Return: HTMLElement를 상속받은 객체 -previousElementSibling, nextElementSibling 형제 노드를 탐색. Element type 요소만을 탐색 Return: HTMLElement를 상속받은 객체 DOM Maipulation(조작) *텍스트 노드에의 접근/수정 텍스트 노드의 firstChild 프로퍼티를 사용하여 텍스트 노드 탐색 텍스트 노드는 nodeValue 라는 프로퍼티 하나만 가지고 있음. nodeValue를 이용하여 수정. -nodeValue Return: 텍스트 노드의 경우 문자열, 요소 노드의 경우 null 반환. *어트리뷰트 노드에의 접근/수정 -className class 어트리뷰트의 값을 취득 도는 변경한다. className 프로퍼티에 값을 할당하면 class 어트리뷰트를 생성하고 지정된 값을 설정할 수도 있다. class 어트리뷰트가 여러 개일 경우, 공백으로 구분된 문자열이 반환되므로 String 메소드 split(' ')을 사용하여 배열로 변경하여 사용한다. -classList 여러 메소드 제공. -id id 어트피뷰트 값을 취득 또는 변경. id 프로퍼티에 값을 할당하면, id 어트리뷰트를 생성하고 지정된 값을 설정. -hasAttribute(attribute) HTML 콘텐츠 조작(Manipulation) -textContent 요소의 콘텐츠를 취득 또는 변경. */
$(document).ready(function(){ var gameInProgress = true; restart(); function restart(){ $('.x, .o').removeClass('x o'); gameInProgress = true; } $('.newGame').on('click', function(){ restart(); }) $('.square').on('click', function(){ if (!gameInProgress) { return; } $(this).addClass('x'); setTimeout(testSolutions); setTimeout(computer, 500); }) function computer(){ if (!gameInProgress) { return; } var availableSpaces = $('.square').not('.x, .o'); var number = Math.floor(Math.random() * availableSpaces.length); availableSpaces.eq(number).addClass('o'); setTimeout(testSolutions, 50); } var solutions = [ // rows [0, 1, 2], [3, 4, 5], [6, 7, 8], // diag [2, 4, 6], [0, 4, 8], // cols [0, 3, 6], [1, 4, 7], [2, 5, 8], ]; // Grab all cells var $cells = $('.square'); function testSolutions(){ var solved = false; // Goes through each solution solutions.forEach(function(solution) { solved = checkSolution(solution); if (solved) { //winner alert(solved + ' is the winner!'); gameInProgress = false; return; } }) } function checkSolution(map) { var $solutionCells = $cells.filter(function(index) { return map.indexOf(index) != -1; }); if ($solutionCells.filter('.x').length === 3) { console.log('checkSolution', 'XXX', map); return 'X'; } if ($solutionCells.filter('.o').length === 3) { console.log('checkSolution', 'OOO', map); return 'O'; } return false; } });
import React, { useContext } from "react"; import { Button, Container, Nav, Navbar } from "react-bootstrap"; import { Link } from "react-router-dom"; import { UserContext } from "../../App"; const Header = () => { const [loggedInUser, setLoggedInUser] = useContext(UserContext); return ( <header> <Navbar sticky="top" bg="danger" variant="dark" expand="lg"> <Container> <Navbar.Brand as={Link} to="/">Highway Transports</Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="ml-auto"> <Nav.Link className = "mr-4 text-white text-decoration-none" as={Link} to="/home">Home</Nav.Link> <Nav.Link className = "mr-4 text-white text-decoration-none" as={Link} to="/destination">Destination</Nav.Link> <Nav.Link className = "mr-4 text-white text-decoration-none" as={Link} to="/blog">Blog</Nav.Link> <Nav.Link className = "mr-4 text-white text-decoration-none" as={Link} to="/contact">Contact</Nav.Link> </Nav> {loggedInUser.email || loggedInUser.name ? <h2>{loggedInUser.email}</h2> : <Button className ="bg-success" variant="primary" as={Link} to="/login" variant="danger">Log In</Button>} </Navbar.Collapse> </Container> </Navbar> </header> ) }; export default Header;
//goalFactory.js (function() { 'use strict'; angular.module('goalsFactory', []) .factory('goals', goals) // a factory named goals goals.$inject = ['$http'] // goals factory function goals($http){ var goalsUrl = '/api/goals' var goals = {} goals.list_all = function() { console.log("calling http.get all goals") return $http.get(goalsUrl) } // list all for given user goals.list = function(user_id) { return $http.get(goalsUrl + '/users/' + user_id ) } goals.show = function(goalId) { return $http.get(goalsUrl + '/' + goalId) } goals.addGoal = function(userId, goal) { return $http.post(goalsUrl + '/users/' + userId, goal) } goals.updateGoal = function(goal) { return $http.patch(goalsUrl + '/' + goal._id, goal) } goals.removeGoal = function(goalId) { return $http.delete(goalsUrl + '/' + goalId) } return goals } }());
'use strict'; import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import reducers from './reducers/reducerIndex.js'; const configureStore = () => { const createStoreWithMiddleware = applyMiddleware(thunk)(createStore); if(process.env.NODE_ENV !== 'production'){ return createStoreWithMiddleware(reducers, window.devToolsExtension && window.devToolsExtension()); } return createStoreWithMiddleware(reducers); }; export default configureStore;
import React from 'react'; import 'Styles/index.css'; import PropTypes from 'prop-types'; import HeaderContainer from 'Components/atoms/container/header-container'; import ButtonText from 'Components/molecules/button/button-text'; import { Icon } from 'Components/atoms/icon'; import Button from 'Components/atoms/button'; import { ShoppingCartHandler } from 'handlers/shopping-cart-handler'; import announcementObject from 'Redux/reducers/announcement'; export const HeaderDefault = (props) => { const ActionView = `flex ml-auto mr-0 flex-none justify-center ${props.titlePosition === 'center' && 'absolute right-0 transform -translate-x-4'}`; const titleBoldElement = <b>{props.title}</b>; const { total: cartNotification, getShoppingCartCount } = ShoppingCartHandler.useShoppingCartCount(); const dispatch = useDispatch(); let ActionPlace = <></>; let IconButtonOne = <></>; let IconButtonTwo = <></>; let IconButtonThree = <></>; let titleView = ''; React.useEffect(() => { if (props.nameIconOne === 'cart-outline' || props.nameIconTwo === 'cart-outline' || props.nameIconThree === 'cart-outline') { getShoppingCartCount(); } if ([props.nameIconOne, props.nameIconTwo, props.nameIconThree].includes('message-outlined')) { dispatch(announcementObject.actions.requestAnnouncementList()); } }, []); const messageIcon = (key) => { return key === 'message-outlined' ? ( <div className="absolute top-0 right-0 -mr-2" style={{ marginTop: '-6px' }} > {/* <BadgeNotif notification={getDefault(unreadAnnouncement?.length, 0) + unreadMessage} /> */} </div> ) : null; }; if (props.button === true) { ActionPlace = ( <div className={ActionView}> <ButtonText label={props.action} onClick={props.onClick} /> </div> ); } else { ActionPlace = <></>; } if (props.showIconOne && props.button === false) { IconButtonOne = ( <div className="relative"> {messageIcon(props.nameIconOne)} {props.nameIconOne === 'cart-outline' ? ( <div className="absolute top-0 right-0 -mr-2" style={{ marginTop: '-6px' }} > {/* <BadgeNotif notification={cartNotification} /> */} </div> ) : null} <Button label={<Icon name={props.nameIconOne} color={props.iconColor} size="medium" />} onClick={props.menuOneClick} /> </div> ); } if (props.showIconTwo && props.button === false) { IconButtonTwo = ( <div className="relative"> {messageIcon(props.nameIconTwo)} {props.nameIconTwo === 'cart-outline' ? ( <div className="absolute top-0 right-0 -mr-2" style={{ marginTop: '-6px' }} > {/* <BadgeNotif notification={cartNotification} /> */} </div> ) : null} <Button label={<Icon name={props.nameIconTwo} color={props.iconColor} size="medium" />} onClick={props.menuTwoClick} /> </div> ); } if (props.showIconThree && props.button === false) { IconButtonThree = ( <div className="relative"> {messageIcon(props.nameIconThree)} {props.nameIconThree === 'cart-outline' ? ( <div className="absolute top-0 right-0 -mr-2" style={{ marginTop: '-6px' }} > {/* <BadgeNotif notification={cartNotification} /> */} </div> ) : null} <Button label={<Icon name={props.nameIconThree} color={props.iconColor} size="medium" />} onClick={props.menuThreeClick} /> </div> ); } if (props.titlePosition === 'center') { if (props.button === true) { titleView = ' w-full text-center cursor-default'; } else { titleView = ' w-full text-center cursor-default'; } } else { titleView = 'cursor-default'; } return ( <HeaderContainer bgColor={props.bgColor} shadow={props.shadow} id={props.id} className={props.className}> <div className={titleView}>{props.titleBold ? titleBoldElement : props.title}</div> {ActionPlace} {(props.showIconOne || props.showIconTwo || props.showIconThree) && <div className="flex mr-0 ml-auto space-x-3 items-center absolute right-0 transform -translate-x-4"> {IconButtonThree} {IconButtonTwo} {IconButtonOne} </div> } </HeaderContainer> ); }; HeaderDefault.defaultProps = { title: PropTypes.string, button: PropTypes.bool, action: PropTypes.string, onClick: PropTypes.func, titlePosition: PropTypes.oneOf(['center' | 'left']), bgColor: PropTypes.string, shadow: PropTypes.bool, titleBold: PropTypes.bool, className: PropTypes.string, id: PropTypes.any, showIconOne: PropTypes.bool, showIconTwo: PropTypes.bool, showIconThree: PropTypes.bool, nameIconOne: PropTypes.iconName, nameIconTwo: PropTypes.iconName, nameIconThree: PropTypes.iconName, iconColor: PropTypes.colorPalette, menuOneClick: PropTypes.func, menuTwoClick: PropTypes.func, menuThreeClick: PropTypes.func, } HeaderDefault.defaultProps = { title: 'Title Page', action: 'Button', button: false, titlePosition: 'left', shadows: true, titleBold: false, iconColor: 'nero', showIconOne: false, showIconTwo: false }; export default HeaderDefault;
let DetailsCtrl = function($scope, CharactersService, $stateParams){ let id = $stateParams; CharactersService.getChar(id).then( (res) => { $scope.char = res.data; }) }; DetailsCtrl.$inject = ['$scope', 'CharactersService', '$stateParams']; export default DetailsCtrl;
{ "class" : "Page::ring::conversation" }
import distinct from '../signals/processes/distinct' import pipe from '../signals/pipe' import scroll from './scroll' import throttle from '../signals/processes/throttle' export default pipe( scroll, throttle(300), distinct )
import React from "react"; import AlbumSelectors from "selectors/AlbumSelectors"; import { connect } from "react-redux"; import { wrapper } from "redux/configureStore"; import * as Util from "utils/Util"; import AlbumView from "components/AlbumView"; import AlbumActions from "redux/AlbumRedux"; import SearchBar from "components/SearchBar"; class AlbumPage extends React.Component { componentDidMount() { this.props.fetchAlbumsRequest(this.props.params.artistName); } render() { const { albums } = this.props; return ( <> <SearchBar /> {Util.getDisplayStatus(albums)} <AlbumView artist={this.props.params.artistName} albums={albums} /> </> ); } } export const getServerSideProps = wrapper.getServerSideProps((context) => { return { props: { params: context.params, }, }; }); const mapStateToProps = (state) => ({ albums: AlbumSelectors.albums(state), }); const mapDispatchToProps = (dispatch) => { return { fetchAlbumsRequest: (artist) => dispatch(AlbumActions.fetchAlbumsRequest(artist)), }; }; export default connect(mapStateToProps, mapDispatchToProps)(AlbumPage);
const HorizontalRule = ({ style }) => { return ( <div className={`${style} w-[90%] mx-auto flex items-center justify-center space-x-3 my-16 sm:my-20 md:my-24 lg:my-32`} > <div className=" w-full sm:w-[200px] md:w-[250px] lg:w-[300px] xl:w-[350px] h-[2px] bg-hLight dark:bg-hDark"></div> <div> <div className="w-5 md:w-7 lg:w-9 h-[2px] lg:h-[3px] bg-hLight dark:bg-hDark rotate-[45deg]"></div> <div className="w-5 md:w-7 lg:w-9 h-[2px] lg:h-[3px] bg-hLight dark:bg-hDark rotate-[-45deg] -mt-[2px]"></div> </div> <div className=" w-full sm:w-[200px] md:w-[250px] lg:w-[300px] xl:w-[350px] h-[2px] bg-hLight dark:bg-hDark"></div> </div> ); }; export default HorizontalRule;
export function getFizzBuzzUntil(n) { //* declare empty array for storing values let fizzBuzz = []; //* for loop, where we start i at 1 instead of 0 to prevent getting a FizzBuzz return for 0 //* also, using <= to ensure we iterate on the value passed for (let i = 1; i <= n; i++) { //* we check for FizzBuzz first becaause we can only enter one block, so if Fizz or Buzz was checked first, FizzBuzz could never happen. //* we use the remainder operator to check if the remainder of i is 0, for 3 AND 5, push 'FizzBuzz' to the array if true if (i % 3 === 0 && i % 5 === 0) { fizzBuzz.push("FizzBuzz"); } else if (i % 3 === 0) { //* not much special here, check for Fizz by checking the remainder of i against only 3. push 'Fizz' to the array if true fizzBuzz.push("Fizz"); //* andddd check for Buzz by checking the remainder of i against only 5. push 'Buzz' to the array if true } else if (i % 5 === 0) { fizzBuzz.push("Buzz"); } else { //* else block to catch everything that does not fall into the above conditions. push the current value of i(current iteration) to the array fizzBuzz.push(i); } } return fizzBuzz; } //! this is a challenge I have done in the past in Python, it's basically the same, and I believe this is one of the shortest ways to do it, could be shortened by removing brackets I suppose. There is a Typo in your Readme example that shows that 6 should be in the array. :) Only pointing out in case it was a test :P.
// Hooks import { useState, useCallback } from 'react' import { useTranslation } from 'next-i18next' import { useBackend } from 'site/hooks/useBackend.mjs' import { useDropzone } from 'react-dropzone' import { useToast } from 'site/hooks/useToast.mjs' // Components import { Icons, welcomeSteps, BackToAccountButton } from './shared.mjs' import { ContinueButton } from 'site/components/buttons/continue-button.mjs' import { SaveSettingsButton } from 'site/components/buttons/save-settings-button.mjs' export const ns = ['account', 'toast'] export const ImgSettings = ({ app, title = false, welcome = false }) => { const backend = useBackend(app) const toast = useToast() const { t } = useTranslation(ns) const [img, setImg] = useState(false) const onDrop = useCallback((acceptedFiles) => { const reader = new FileReader() reader.onload = () => { setImg(reader.result) } acceptedFiles.forEach((file) => reader.readAsDataURL(file)) }, []) const { getRootProps, getInputProps } = useDropzone({ onDrop }) const save = async () => { app.startLoading() const result = await backend.updateAccount({ img }) if (result === true) toast.for.settingsSaved() else toast.for.backendError() app.stopLoading() } const nextHref = '/docs/guide' return ( <> {title ? <h2 className="text-4xl">{t('imgTitle')}</h2> : null} <div> {!welcome || img !== false ? ( <img alt="img" src={img || app.account.img} className="shadow mb-4" /> ) : null} <div {...getRootProps()} className={` flex rounded-lg w-full flex-col items-center justify-center lg:h-64 lg:border-4 lg:border-secondary lg:border-dashed `} > <input {...getInputProps()} /> <p className="hidden lg:block p-0 m-0">{t('imgDragAndDropImageHere')}</p> <p className="hidden lg:block p-0 my-2">{t('or')}</p> <button className={`btn btn-secondary btn-outline mt-4 w-64`}> {t('imgSelectImage')} </button> </div> </div> {welcome ? ( <> <button className={`btn btn-secondary mt-4 w-64`} onClick={save} disabled={!img}> {t('save')} </button> <ContinueButton app={app} btnProps={{ href: nextHref }} link /> {welcomeSteps[app.account.control].length > 0 ? ( <> <progress className="progress progress-primary w-full mt-12" value={700 / welcomeSteps[app.account.control].length} max="100" ></progress> <span className="pt-4 text-sm font-bold opacity-50"> 7 / {welcomeSteps[app.account.control].length} </span> <Icons done={welcomeSteps[app.account.control].slice(0, 6)} todo={welcomeSteps[app.account.control].slice(7)} current="img" /> </> ) : null} </> ) : ( <> <SaveSettingsButton app={app} btnProps={{ onClick: save }} /> <BackToAccountButton loading={app.loading} /> </> )} </> ) }
module.exports = function(app) { app.use('/api/auth', require('./auth.js')); app.use('/api/post', require('./post.js')); }
var defines________________________________6________________8js________8js____8js__8js_8js = [ [ "defines________________6________8js____8js__8js_8js", "defines________________________________6________________8js________8js____8js__8js_8js.html#a6f4e5e64def0b1adf1c7901d2575d422", null ] ];