text
stringlengths
7
3.69M
/* * theadFixer * * https://github.com/Mystist/theadFixer * * Copyright (c) 2013 Foundation and other contributors * * License: https://github.com/Mystist/theadFixer/blob/master/MIT-LICENSE.txt * */ (function($) { var methods = { init: function(options) { var defaults = { "bindResize": false, "overflow_x": "hidden", "floatMode": true, "renderBetter": false }; var settings = $.extend(defaults, options); var theadFixer = new TheadFixer(); theadFixer.$this = this; theadFixer.initialize(settings); return theadFixer; } }; function TheadFixer() { this.$this = null; this.resizeTimer = null; this.overflow_x = null; this.floatMode = null; this.winWidth = $(window).width(); this.winHeight = $(window).height(); this.t1 = null; this.t2 = null; this.t3 = null; this.t4 = null; this.hasUsed = false; } TheadFixer.prototype = { constructor: TheadFixer, initialize: function(st) { this.overflow_x = st.overflow_x; this.floatMode = st.floatMode; if(st.renderBetter) { $(this.$this[0]).find("table,thead,tbody").hide(); } this.built(); if (st.bindResize) { this.bindResize(); } if(st.renderBetter) { $(this.$this[0]).find("table,thead,tbody").show(); } }, built: function() { this.setTdWidth(); this.builtHtml(); this.setWidth(); if(this.floatMode) { this.appendTheadAndSetPosition(); } this.syncScrollBar(); this.hasUsed = true; }, setTdWidth: function() { var tThis = this; var tableWidth = 0; tThis.$this.find("thead tr").children().each(function(i) { var tWidth = ""; if ($(this).attr("width")) { tWidth = $(this).attr("width"); $(this).attr("thewidth", tWidth); } else { tWidth = $(this).width() + "px"; $(this).attr("thewidth", "none").attr("width", tWidth); } tThis.$this.find("tbody tr:first td").eq(i).attr("width", tWidth); tableWidth += tWidth; }); this.t3 = tThis.$this.find("table").css("table-layout"); tThis.$this.find("table").css({ "table-layout": "fixed", "width": tableWidth }); }, builtHtml: function() { var tThis = this; this.t1 = tThis.$this.find("table").attr("style"); this.t2 = tThis.$this.find("table").attr("class"); this.t4 = tThis.$this.find("table").css("border-top"); tThis.$this.find("table").wrap('<div class="m_innerwrapper"></div>'); tThis.$this.find("thead").unwrap().wrap('<table></table>'); tThis.$this.find("tbody").wrap('<table></table>'); tThis.$this.find("table:first").attr("style", this.t1).attr("class", this.t2).css("table-layout", "fixed"); tThis.$this.find("table:last").attr("style", this.t1).attr("class", this.t2).css({ "table-layout": "fixed", "border-top": "none" }); tThis.$this.find("thead").parent().wrap('<div class="m_wrap" style="overflow:hidden;"></div>'); var height = tThis.$this.children().height() - tThis.$this.find("table:first").outerHeight(true); tThis.$this.find("tbody").parent().wrap('<div class="m_wrapper" style="height:' + height + 'px; width: 100%; overflow-y:auto; overflow-x:' + tThis.overflow_x + '">'); }, setWidth: function() { var tThis = this; var fixNumber = 0; if (tThis.$this.find(".m_wrapper").height() < tThis.$this.find("table:last").outerHeight(true)) { fixNumber = 17; } tThis.$this.find("table:first").css("width", tThis.$this.find("table:first").width() - fixNumber + "px"); tThis.$this.find("table:last").css("width", tThis.$this.find("table:last").width() + "px"); var fixNumber2 = 0; if (tThis.$this.find(".m_wrapper").width() < tThis.$this.find("table:last").outerWidth(true) && fixNumber!=0) { fixNumber2 = 17; } tThis.$this.find(".m_wrap").css("width", tThis.$this.find(".m_wrapper").width() - fixNumber2 + "px"); }, appendTheadAndSetPosition: function() { var tThis = this; tThis.$this.find(".m_innerwrapper") .width(tThis.$this.find(".m_innerwrapper").width()) .height(tThis.$this.find(".m_innerwrapper").height()); tThis.$this.find(".m_wrapper").height(tThis.$this.children().height()); tThis.$this.find(".m_wrap").css({ "position": "absolute", "z-index": 1 }); tThis.$this.find(".m_wrapper").css({ "position": "absolute", "z-index": 0 }); tThis.$this.find("table:last").css("border-top", tThis.t4); var el = tThis.$this.find("table:first thead")[0].outerHTML; tThis.$this.find("table:last").prepend(el); }, removeTheadAndRevertPosition: function() { var tThis = this; tThis.$this.find("table:last").find("thead").remove(); tThis.$this.find(".m_wrap").css({ "position": "" }); tThis.$this.find(".m_wrapper").css({ "position": "" }); }, revertHtml: function() { var tThis = this; tThis.$this.find("tbody").parent().unwrap(); tThis.$this.find("tbody").unwrap(); tThis.$this.find("thead").parent().unwrap(); tThis.$this.find("thead").unwrap(); tThis.$this.find(".m_innerwrapper").wrapInner('<table style="' + this.t1 + '" class="' + this.t2 + '"></table>'); tThis.$this.find("table").unwrap(); }, revertTdWidth: function() { var tThis = this; tThis.$this.find("thead tr").children().each(function(i) { if ($(this).attr("thewidth") == "none") { $(this).removeAttr("thewidth").removeAttr("width"); } else { $(this).attr("width", $(this).attr("thewidth")).removeAttr("thewidth"); } tThis.$this.find("tbody tr:first td").eq(i).removeAttr("width"); }); tThis.$this.find("table").css({ "table-layout": this.t3, "width": "" }); }, syncScrollBar: function() { var tThis = this; tThis.$this.find(".m_wrapper").bind("scroll", function() { var first = tThis.$this.find(".m_wrap"); var last = tThis.$this.find(".m_wrapper"); if (first.scrollLeft() != last.scrollLeft()) { first.scrollLeft(last.scrollLeft()); } }); }, bindResize: function() { var tThis = this; $(window).unbind("resize").resize(function() { var winNewWidth = $(window).width(), winNewHeight = $(window).height(); if(Math.abs(tThis.winWidth-winNewWidth)>20 || Math.abs(tThis.winHeight-winNewHeight)>20) { clearTimeout(tThis.resizeTimer); tThis.resizeTimer = setTimeout(function() { tThis.revert(); tThis.built(); }, 200); } tThis.winWidth = winNewWidth; tThis.winHeight = winNewHeight; }); }, revert: function() { if(this.hasUsed) { if(this.floatMode) { this.removeTheadAndRevertPosition(); } this.revertHtml(); this.revertTdWidth(); this.hasUsed = false; } } }; $.fn.theadFixer = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('No ' + method + ' method.'); } }; })(jQuery);
const TelegramClass = function (name,desc,members) { this.name = name; this.desc = desc; this.members = members; this.members.sort( (a,b) => { if (a.optional && !b.optional) { return 1; } else if (!a.optional && b.optional) { return -1; } else { return 0; } }) this.getFilename = function () { return this.name + '.php'; } this.getImportFilename = function () { return this.getFilename().replace(/.php$/g,''); } } const lowerCamelCase = function (name) { let index = name.search(/_[a-z]/g); while (index >= 0) { name = name.substr(0,index) + name[index+1].toUpperCase() + name.substr(index+2,name.length); index = name.search(/_[a-z]/g); } return name; } const upperCamelCase = function (name) { name = lowerCamelCase(name); return name.charAt(0).toUpperCase() + name.slice(1); } const Writer = function () { const classes = []; const getClassIndex = function (name) { return classes.findIndex( c => c.name === name); } this.existsClass = function (name) { return classes.some (c => c.name === name) } this.getClass = function (name) { const i = getClassIndex(name); return i < 0 ? null : classes[i]; } this.addClass = function (name,desc,members) { const c = new TelegramClass(name,desc,members); const ci = getClassIndex(name); if (ci < 0) { classes.push(c) } else { classes[ci] = c; } return this; } this.parseType = type => { if (/ or /g.test(type)) { return this.parseType(type.replace(/^(.+) or .+$/g, '$1')); } else if (/^<a href="#[^"]+">(.+)<\/a>/g.test(type)) { return this.parseType(type.replace(/^<a href="#[^"]+">(.+)<\/a>/g, '$1')) } else if (type === 'True') { return 'boolean'; } else if (type === 'Boolean') { return 'boolean'; } else if (type === 'String') { return 'string'; } else if (type === 'CallbackGame') { return 'any'; } else if (type === 'InputFile') { return 'any'; } else if (type === 'InputMessageContent') { return 'any'; } else if (type === 'Integer') { return 'number'; } else if (type === 'Float' || type === 'Float number') { return 'number'; } else if (/^Array of/g.test(type)) { return this.parseType(type.replace(/^Array of (.+)$/g, '$1[]')); } else { return type.trim(); } } const isMemberTypeAClass = memberType => { const classIndex = classes.findIndex( cc => { const r = new RegExp('^'+cc.name+'((\\[\\])+)*$','g'); return r.test(memberType); }); return classIndex >= 0; } const getMemberTypeClass = memberType => { const classIndex = classes.findIndex( cc => { const r = new RegExp('^'+cc.name+'((\\[\\])+)*$','g'); return r.test(memberType); }); return classIndex >= 0 ? classes[classIndex] : null; } this.getClassDependecies = function (name) { const dep = []; const c = (name instanceof TelegramClass) ? name : this.getClass(name); if ( c !== null) { c.members.forEach( member => { const classIndex = classes.findIndex( cc => { const r = new RegExp('^'+cc.name+'((\\[\\])+)*$','g'); return r.test(member.type); }); const isClass = classIndex >= 0; if (isClass) { const cc = classes[classIndex]; const isAlready = (cc.name === c.name) || dep.some(c => cc.name === c.name) if (!isAlready) { dep.push(cc) } } }) } return dep; } this.forEachClass = function (callback) { classes.forEach( c => callback(c,this)); return this; } const writeClassDependecies = (c) => { const dep = this.getClassDependecies(c); return ` <?php namespace App; `; } const writeClassFillable = (name) => { let code = ''; const c = (name instanceof TelegramClass) ? name : this.getClass(name); code +=` protected $fillable = [`; c.members.forEach(member => { code += ` '${member.name}',`; }) code += ` ]; `; return code; } const writeClassMemberDeclarations = name => { let code = ''; const c = (name instanceof TelegramClass) ? name : this.getClass(name); code +=``; c.members.forEach(member => { code += ` /* ${member.desc.length < 120 ? member.desc : member.desc.substr(0,117)+'...'} */ private ${member.name}: ${member.type}`; if (member.optional) { code += ' = null'; } code+=';\n'; }) code += ``; return code; } const writeClassGetters = name => { let code = ''; const c = (name instanceof TelegramClass) ? name : this.getClass(name); code +=``; c.members.forEach(member => { code += ` public function get${upperCamelCase(member.name)}Attribute() { return $this->attributes['${member.name}']; } `; }) code += ``; return code; } const writeClassSetters = name => { let code = ''; const c = (name instanceof TelegramClass) ? name : this.getClass(name); code +=``; c.members.forEach(member => { const isClass = isMemberTypeAClass(member.type) && member.type.substr(-2) !== '[]'; code += ` public function set${upperCamelCase(member.name)}Attribute(${isClass ? member.type+' ' : ''}\$${lowerCamelCase(member.name)}) { $this->attributes['${member.name}'] = \$${lowerCamelCase(member.name)}; } `; }) code += ``; return code; } this.writeClass = function (name) { let code = ''; const c = (name instanceof TelegramClass) ? name : this.getClass(name); code += writeClassDependecies(c); code += '\n'; code += ` class ${c.name} extends BaseModel { /** * The attributes that are mass assignable. * * @var array */ ${writeClassFillable(c)} /* Getters*/ ${writeClassGetters(c)} /* Setters*/ ${writeClassSetters(c)} } ` return code.trim() + '\n'; } Object.defineProperties(this,{ 'length': { 'configurable': false, 'enumerable': true, 'get': () => classes.length, }, }); } module.exports = Writer;
const mongoClient = require("mongodb").MongoClient const connectionUrl = " mongodb://127.0.0.1:27017" const dbName = "animalfarm" mongoClient.connect(connectionUrl, {useUnifiedTopology: true}, (error, client) => { if(error){ throw "Error connecting to mongodb" + error } const animalFarm = client.db(dbName) const buildings = animalFarm.collection('buildings') buildings.updateOne({type:"windmill"},{$set: {type: "brooder house"}}) //The $set stage is an alias for $addFields. buildings.insertOne({type: "cow house", size: { height: 12, width: 14}}) })
import React, { useEffect, useCallback, useRef } from 'react'; import Swiper from 'swiper'; import { useDispatch, useSelector } from 'react-redux'; import { requsetGoodList, goodListSelector } from '../../store/Good/Good'; import './style.scss'; let IScroll = window.IScroll; const GoodBanner = function(props) { const swiperRef = useRef(); useEffect(() => { new Swiper(swiperRef.current, { direction: 'horizontal', autoplay: true, }); }, []); return ( <div className='banner swiper-container' ref={swiperRef}> <div className='swiper-wrapper'> {props.imglist.map((item, index) => { return ( <div className='swiper-slide' key={index}> <img src={item} alt='good轮播图' /> </div> ); })} </div> </div> ); }; const Good = function(props) { // 取出仓库方法 传入dispatch const dispatch = useDispatch(); const list = useSelector(goodListSelector); const box = useRef(); const reqData = useCallback(() => { dispatch(requsetGoodList()); }, [list]); useEffect(() => { // dom更新后执行 // 不传入第二个参数时 // 等价于 componentDidMount componentDidUpdate 两个生命周期函数 // 数据请求, 暂不明为何会出现死循环 if (list.length > 0) { console.log(list); return; } else { reqData(); } const scrollBox = new IScroll(box.current, { bounce: true, click: true, mouseWheel: true, tap: true, }); scrollBox.on('beforeScrollStart', () => { scrollBox.refresh(); }); }); return ( <div className='page' id='Good' ref={box}> <div className='wrap'> {list.map((item) => { return ( <div className='item' key={item.id}> <p className='i-title'>{item.title}</p> <GoodBanner imglist={item.listPic} /> <p className='i-intro'>{item.text}</p> <p className='i-mes'> {item.timestamp} / {item.minNum} - {item.maxNum} </p> </div> ); })} </div> </div> ); }; export default Good;
import Koa from 'koa'; import Router from 'koa-router'; import jwt from 'jsonwebtoken'; import config from 'config'; const app = new Koa(); const router = new Router(); router.post('/', (ctx, next) => { const { email, password } = ctx.request.body; if (email === 'admin' && password === 'password') { const secret = config.get('app.secret'); const user = { username: 'admin' }; const token = jwt.sign({ ...user, role: 'admin' }, secret, { expiresIn: '1h' }); ctx.session.authUser = token; ctx.body = user; return; } ctx.throw(401, 'bad credentials'); }); app.use(router.routes()); app.use(router.allowedMethods()); export default app;
export const Numero = (props) => { const { numero } = props; return <input type="number" value={numero} readOnly />; };
var name = 'Allegheny Elementary'; var students = ["Lorean Seybert", "Lowell Brumfield", "Vicki Hunley", "Karole Riley", "Doloris Steffy",   "Sharda Patel", "Elvira Bednar",   "Lyndia Peil", "Jesus Pennywell",  "Sanford Duffie", "Dana Jeon", "Janean Hodnett",   "Verna Hester", "Annette Keating", "Tatiana Sevilla",   "Frank Towers", "Gillian Frederick",   "Philomena Cates",   "Kyle Marnell", "Berniece Ocallaghan"] var students2 = ['Carlee Febres', 'Monserrate Lowrance', 'Rochelle Adelson', 'Usha Kampen', 'Margarett Hoose', 'Marguerite Dismukes', 'Lucia Oden', 'Delmar Gondek', 'Deloras Coram', 'Patrick Vickers', 'Claribel Disandro', 'Janetta Bonhomme', 'Alysha Cutshaw', 'Son Virgin', 'Cristy Bock', 'Felica Landa', 'Sammy Nishimura', 'Germaine Lannon', 'Loreta Bollin', 'Coralie Samuelson', 'Cher Bermejo', 'Pilar Cusson', 'Billi Ridinger', 'Letisha Aubry', 'Antione Barnhill']; var students3 = ['Earle Lo', 'Melissa Mazzoni', 'Glinda Thach', 'Simone Bona', 'Elliott Wattley', 'Alexander Lapierre', 'Matha Hackbarth', 'Shanna Henault', 'Sherron Sandusky', 'Georgie Overland', 'Jarred Baldwin', 'Erich Marzano', 'Maribeth Stemm', 'Rex Durante', 'Elwood Fenton', 'Madeleine Tijerina', 'Terrance Ertle', 'Brittaney Dunklin', 'Charles Boller', 'Jacob Trunnell', 'Nathan Yarnell', 'Angel Dickey', 'Hugo Clarkson', 'Tina Trudel', 'Roberta Jennings']; $(document).ready(function() { for (var i = 0; i < students.length; i++) { if (i < students.length/3) { $("#after_school-form #students").append(document.createElement('LI').innerHTML = students[i] + "<br />"); } else if (i < 2*students.length/3) { $("#enrichment-form #students").append(document.createElement('li').innerHTML = students[i] + "<br />"); } else { $("#field_trip-form #students").append(document.createElement('li').innerHTML = students[i] + "<br />"); } } $("#slider").dateRangeSlider({ bounds: { min: new Date(2012, 0, 1), max: (new Date).getTime() }, defaultValues: { min: new Date(2012, 0, 1), max: (new Date).getTime() }, arrows: false }); $('#sidebar li').click(function(){ $('.sidebar-highlight').removeClass('sidebar-highlight'); $(this).addClass('sidebar-highlight'); var newTitle = $(this).html(); $(".title").html(newTitle); }); $('#info-nav li').click(function(){ $('.nav-highlight').removeClass('nav-highlight'); $(this).addClass('nav-highlight'); }); $('#after_school').click(function() { $('#after_school-form').show(); $('#enrichment-form').hide(); $('#field_trip-form').hide(); }); $('#enrichment').click(function() { $('#after_school-form').hide(); $('#enrichment-form').show(); $('#field_trip-form').hide(); }); $('#field_trip').click(function() { $('#after_school-form').hide(); $('#enrichment-form').hide(); $('#field_trip-form').show(); }); });
import React from 'react'; import Logom from './immagini/logo_B2.png'; import classes from './Logo.module.css'; const logo = props => ( <div className={classes.Logo}> <img src={Logom} width="75%" alt="stemma_meldola"></img> </div> ) export default logo;
import React from 'react' import styles from '../hero.modules.css' import { DEEP_RED, RED, YELLOW, GREEN } from '../data/constants' const PositivityLegend = ({ x = 0, y = 0 }) => { const legendData = [ [GREEN, '<3% positivity rate'], [YELLOW, '3% - 5%'], [RED, '5% - 10%'], [DEEP_RED, '10% +'], ] return ( <g transform={`translate(${x}, ${y})`}> { legendData.map( (item, index) => ( <g key={index} transform={`translate(0, ${ index * 15 })`}> <rect width="10" height="10" fill={ item[0] }/> <text x="15" y="8" className={ styles.AxisText }>{ item[1] }</text> </g> )) } </g> ) } export default PositivityLegend
/** * @flow */ import * as path from 'path'; import * as rcUtil from '@esy-ocaml/esy-install/src/util/rc.js'; import {parse} from '@esy-ocaml/esy-install/src/lockfile'; type Rc = { 'esy-import-path': Array<string>, 'esy-prefix-path': ?string, }; export function getRcConfigForCwd(cwd: string): Rc { return rcUtil.findRc('esy', cwd, (fileText, filePath) => { const filePathDir = path.dirname(filePath); const {object: values} = parse(fileText, 'esyrc'); function coerceToPath(key, fallback = null) { const v = values[key]; if (v != null) { values[key] = path.resolve(filePathDir, v); } else { values[key] = fallback; } } function coerceToPathList(key, fallback = []) { const v = values[key]; if (v != null) { values[key] = v.split(':').map(v => path.resolve(filePathDir, v)); } else { values[key] = fallback; } } coerceToPathList('esy-import-path'); coerceToPath('esy-prefix-path'); return values; }); }
export const AMOUNT_MAX_LENGTH = 16; export const MIN_WIDTH_COLUMN_TH = 140;
$(document).ready(function(){ //counters and initial score var wins = 0; var losses = 0; var total = 0; //html gem grabbers var garnet = $("#garnet"); var amethyst = $("#amethyst"); var pearl = $("#pearl"); var pink = $("#pink_diamond"); //reset gem values var garnetsValue = 0; var amethystsValue = 0; var pearslValue = 0; var pinksValue = 0; //player starting score var playerScore = 0; //game over var over = false; //number for player to match reset var number = 0; //winning/losing text $(".winner").text("Congrats! You won!"); $(".loser").text("Oops! You busted! Click Start Over to play again."); //clicking the start button will initiate the functions: var letsPlay = $("#start").on("click", function() { initialize(); }) //clicking a gem button will sum the gems value and the player total garnet.on("click", function(){ total = total + garnetsValue; console.log(total); playerScore.text(total); check(total, number); }) amethyst.on("click", function(){ total = total + amethystsValue; console.log(total); playerScore.text(total); check(total, number); }) pearl.on("click", function(){ total = total + pearlsValue; console.log(total); playerScore.text(total); check(total, number); }) pink.on("click", function(){ total = total + pinksValue; console.log(total); playerScore.text(total); check(total, number); }) //checks winning/losing conditions function check(total_check, number_check) { if (!over){ if (total_check == number_check){ console.log("You win!") wins++ console.log(wins) $(".wins").text("Number of wins: " + wins) $("#start").show(); $("#start").text("Play again") $(".winner").show(); over = true; } else if (total_check > number_check){ console.log("You lost!") losses++ console.log(losses) $(".losses").text("Number of losses: " + losses) $("#start").show(); $("#start").text("Start Over") $(".loser").show(); over = true; } else{ return; } } } //selects random number function initialize() { number = (Math.floor(Math.random() * 121)) + 19; console.log(number); $(".generator").text(number); $("#start").hide(); $(".loser").hide(); $(".winner").hide(); //puts total score on the screen total = 0; playerScore = $(".playerScore"); playerScore.text(total); //sets a random value for the gems and console logs it garnetsValue = (Math.floor(Math.random() * 12)); console.log(garnetsValue); amethystsValue = (Math.floor(Math.random() * 12)); console.log(amethystsValue); pearlsValue = (Math.floor(Math.random() * 12)); console.log(pearlsValue); pinksValue = (Math.floor(Math.random() * 12)); console.log(pinksValue); over = false; } })
import React, { useEffect } from 'react' import { useTranslation } from 'next-i18next' import { clearCurrentCourse, setCurrentCourse } from '../../store/courses/reducer' import { clearLessons, setLessons } from '../../store/lesson/reducer' import { useDispatch, useSelector } from 'react-redux' import { getLessons } from '../../store/lesson/selectors' import { getCurrentCourse } from '../../store/courses/selectors' import Loader from '../Loader/Loader' import LessonsListCard from './LessonsListCard' const LessonsList = ({ course, lessons }) => { const dispatch = useDispatch() const { t } = useTranslation('navbar') const currentLessons = useSelector(getLessons) const currentCourse = useSelector(getCurrentCourse) useEffect(() => { dispatch(setCurrentCourse(course)) dispatch(setLessons(lessons)) return () => { dispatch(clearCurrentCourse()) dispatch(clearLessons()) } }, []) if (!currentLessons && !currentCourse) { return <Loader/> } const lessonBlock = currentLessons.map((lesson, index) => { return <LessonsListCard lesson={lesson} lessonIndex={index} key={lesson._id}/> }) return ( <div> <div className="container my-5"> <div className="row"> <div className="col-sm-12 col-md-12"> <div className="col-12 сol-sm-6 profile-welcome" style={{ backgroundColor: 'rgb(240, 196, 215)' }}> <div className="profile-welcome-block"> <h3 className="profile-welcome-title">{course.title}</h3> <p className="profile-welcome-subtitle">{course.description}</p> </div> <div className="col-12 col-sm-6 d-flex align-items-center"> <img className="profile-welcome-course-img" src={course.coursePreview.url} alt="upgrade"/> </div> </div> <div className="profile-courses"> <h3 className="profile-courses-title">{t('content')}({currentLessons.length})</h3> {lessonBlock} </div> </div> </div> </div> </div> ) } export default LessonsList
import { Meteor } from 'meteor/meteor'; import { Foods } from './foods'; Meteor.publish('foods.getListIfNotLoggedIn', function getListIfNotLoggedIn() { if (this.userId) { return this.ready(); } return Foods.find(); }); Meteor.publish('foods.getListIfLoggedIn', function getListIfLoggedIn() { if (!this.userId) { return this.ready(); } return Foods.find(); });
// Default import fix var anime = require('animejs').default ? require('animejs').default : require('animejs'); function SideMenuAnimate(config) { var activeAnimation; var option = Object.assign( { }, { easing: 'easeInOutCubic', duration: 300, }, config ); this._nodesObserver = new MutationObserver(function (mutations) { var changedNodes = mutations .filter(function (mutation) { return ( mutation.target.classList.contains('sidebar-menu__entry--nested') || mutation.target.classList.contains('sidebar-submenu__entry--nested') ); }) .map(function (mutation) { return { target: mutation.target, wasOpen: mutation.oldValue.indexOf('open') >= 0, }; }); changedNodes.forEach(function (node) { var isOpen = node.target.classList.contains('open'); if (isOpen !== node.wasOpen) { var menu = node.target.querySelector('.sidebar-submenu'); if (activeAnimation && !activeAnimation.completed) { activeAnimation.reset(); } activeAnimation = anime({ targets: menu, height: isOpen ? [0, menu.scrollHeight] : [menu.scrollHeight, 0], duration: option.duration, easing: option.easing }); activeAnimation.finished.then(function() { menu.style.height = ''; }); } }); }); } /** * Assigns the parent sidebar element, and attaches a Mutation Observer * which watches the coallapsable nodes inside of the sidebar menu * and animates them on chenages * * @param {HTMLElement} parentElement SidebarMenu parent */ SideMenuAnimate.prototype.assignParentElement = function (parentElement) { // Reassign Observer Element this._nodesObserver.disconnect(); this._nodesObserver.observe(parentElement, { attributes: true, attributeFilter: ['class'], attributeOldValue: true, subtree: true }); }; /** * Disconnects the observer */ SideMenuAnimate.prototype.destroy = function() { this._nodesObserver.disconnect(); }; /** * Disconnects the observer */ SideMenuAnimate.prototype.destroy = function() { this._nodesObserver.disconnect(); } module.exports = SideMenuAnimate;
import React from 'react'; import './App.css'; import Home from './componets/pages/Home'; import Services from './componets/pages/Services'; import Products from './componets/pages/Products'; import SignUp from './componets/pages/SignUp'; import Navbar from './componets/Navbar'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; function App() { return ( <Router> <Navbar /> <Routes> <Route path="/" element={<Home />} /> <Route path="/services" element={<Services />} /> <Route path="/products" element={<Products />} /> <Route path="/sign-up" element={<SignUp />} /> </Routes> </Router> ); } export default App;
const insuranceItemReducer = (state = [], action) => { switch(action.type) { case 'ADD_INSURANCE_ITEM': return [...state, action.payload]; default: return state; } }; export default insuranceItemReducer;
function isVowel(char){ var vowel = false; switch(char) { case 'a': case 'e': case 'i': case 'o': case 'u': vowel = true; break; default: vowel = false; } return vowel; } function pigLatin(str){ var ay = "ay"; var outputStr = ""; for (var i = 0; i < str.length; i++){ if(isVowel(str[i])){ if ( i === 0) { ay = "way"; } outputStr = str.substr(i, str.length - i) + str.substr(0, i) + ay; return outputStr; } } return str + ay; } module.exports = pigLatin;
const Main = (input) => { const tmp = input.split(' ') const a = tmp[0] const b = tmp[1] if (a * b % 2 === 0) { return 'Even' } else { return 'Odd' } } module.exports = Main
// @flow strict import PdfViewer from './src/PdfViewer'; export { default as PdfViewAndStore } from './src/PdfViewAndStore'; export default PdfViewer;
/** * Created by descombes on 16/03/17. */ loadZnetsConfiguration = function() { callAJAX('getConfig.json', '', 'json', displayZnetsConfiguration, null); } /*********************************************************************************/ displayZnetsConfiguration = function(json) { var formatter = new JSONFormatter(json); $("#showConf-result").append(formatter.render()); }
import React from "react" import Layout from "../components/layout" import { graphql } from "gatsby" import SEO from "../components/seo" import Post from "../components/post" export default function BlogCategory({ data }) { // sorted by post length const categories = data.allWpCategory ? data.allWpCategory.nodes.sort((a, b) => { return a.posts.nodes.length < b.posts.nodes.length }) : null return ( <Layout> <SEO title="Tutorials | How to | Coding" /> <div id="archive"> {categories.map(category => ( <Category key={category.key} category={category} /> ))} </div> </Layout> ) } const Category = ({ category }) => { const posts = category.posts.nodes if (!posts.length) { return null } return ( <div> <header> <h1 className="section-header">{category.name}</h1> <p className="post-count">{posts.length} Articles</p> </header> <div className="row"> {posts.map(post => ( <Post key={post.id} post={post} className="col-12 col-md-5" /> ))} </div> </div> ) } export const query = graphql` query { allWpCategory { nodes { id name posts { nodes { databaseId slug title excerpt } } } } } `
import React from 'react'; import styles from '../styles/styles'; import { Text, Container } from 'native-base'; export default class Feedback extends React.Component { render() { return ( <Container style={styles.centerText}> <Text>TODO FEEDBACK COMPONENT</Text> </Container> ); } }
import Ember from 'ember'; import truncateDecimal from 'great-tipper/utils/truncate-decimal'; export default Ember.Component.extend({ tagName: 'button', classNames: ['btn', 'btn-primary'], mealCost: null, tipPercentage: null, // preset calculations for 15%, 18%, and 20% tips // automatic calculations for 15%, 18%, and 20%. // When the user enters an amount for the cost of the meal, they should automatically see these three values. tipAmount: Ember.computed('mealCost', 'tipPercentage', { get: function() { let mealCost = this.get('mealCost'), tipPercentage = this.get('tipPercentage'), tipAmount = mealCost * (tipPercentage / 100); return truncateDecimal(tipAmount) || 0; } }), click: function() { this.send('setTipPercentage', this.get('tipPercentage')); }, actions: { setTipPercentage: function(value) { this.sendAction('setTipPercentage', value); } } });
(function () { "use strict"; describe("AuthMgmtService", function () { // --------------------- // Testing setup // --------------------- var $httpBackend, $http, $log, $state, userService, service, defer, AlertsService, ApiService; beforeEach(function () { inject(function (_$injector_, _$q_) { $httpBackend = _$injector_.get("$httpBackend"); service = _$injector_.get("AdminMgmtService"); $http = _$injector_.get("$http"); $log = _$injector_.get("$log"); $state = _$injector_.get("$state"); userService = _$injector_.get("userService"); AlertsService = _$injector_.get("AlertsService"); ApiService = _$injector_.get("ApiService"); defer = _$q_.defer(); }); $httpBackend.whenGET(/.*\?wsdl$/).respond(200); $httpBackend.whenGET(/app\/login\/\w+\.html/).respond(200); spyOn($http, "post").and.callFake(function () { return defer.promise; }); spyOn($state, "go"); spyOn(AlertsService, "addErrors"); spyOn(userService, "setUserInfo"); spyOn(userService, "destroySession"); spyOn(ApiService, "callEndpoint").and.callFake(function() { return defer.promise; }); }); afterEach(function () { $httpBackend.flush(); }); // --------------------- // Method tests // --------------------- describe("service.signIn", function () { it("should make a request to the AuthMgmtService:signIn method", function () { service.signIn("testUser", "testPass"); expect(ApiService.callEndpoint).toHaveBeenCalledWith("/services/AdminMgmtService/omi_signOn", { userAttributes: { "omit:userName": "testUser", "omit:password": "testPass", }, }); }); describe("when response is a success", function () { var username, handle; beforeEach(function () { username = "testUser"; handle = "abc123"; }); afterEach(function () { resolveDeferred(); }); it("should call userService.setUserInfo", function () { service.signIn("testUser", "testPass").then(function () { expect(userService.setUserInfo).toHaveBeenCalledWith({ id: username, handle: handle, }); }); }); it("should redirect to the content page", function () { service.signIn("testUser", "testPass").then(function () { expect($state.go).toHaveBeenCalledWith("app.content"); }); }); function resolveDeferred() { defer.resolve({ result: { "resultText": "Success", "resultCode": 0, "resultId": username, }, sessionHandle: { "handle": handle, }, }); } }); describe("when response is not a success", function () { afterEach(function () { resolveDeferred(); }); it("sends the errors to the AlertsService", function () { service.signIn("testUser").then(function () { expect(AlertsService.addErrors).toHaveBeenCalledWith("Invalid credentials"); }); }); }); function resolveDeferred() { defer.resolve({ result: { "resultText": "Invalid credentials", "resultCode": 4, }, }); } }); describe("service.signOut", function () { beforeEach(function () { spyOn(userService, "getUserInfo").and.returnValue({ id: "testUser", handle: "abc123", }); }); afterEach(function () { defer.resolve(); }); it("should make a request to the AuthMgmtService:signOff method", function () { service.signOut(); expect($http.post).toHaveBeenCalledWith("/services/AdminMgmtService/omi_signOff"); // the sessionHandle gets injected by an HTTP interceptor }); it("should call the userService.destroySession method", function () { service.signOut().then(function () { expect(userService.destroySession).toHaveBeenCalled(); }); }); it("should redirect the user to the login screen", function () { service.signOut().then(function () { expect($state.go).toHaveBeenCalledWith("login.signIn"); }); }); }); }); }());
const assert = require('assert') const { Signature } = require('../../lib') describe('Test MySignature', () => { it(`Normal Test`, async () => { const appid = 'abcdefg' const secret = '123456' const signature = new Signature(secret, 600) const expires = signature.getExpires() const queryParams = { x: 123, y: 456, } queryParams['_appid'] = appid queryParams['_expires'] = expires const method = 'GET' const apiPath = '/api/xxx/' const body = { xxx: 1, abc: 'abc', } queryParams['_token'] = signature.sign(method, apiPath, queryParams, body) assert.ok(signature.checkExpires(queryParams)) assert.ok(signature.checkSign(method, apiPath, queryParams, body)) }) })
import React from "react"; const SearchBox = ({ value, onChange }) => { return ( <div className="search-container"> <div className="search-box"> <input type="text" name="query" className="" placeholder="search your favourite plant..." value={value} onChange={(e) => onChange(e.currentTarget.value)} /> </div> </div> ); }; export default SearchBox;
import React, {useState, useEffect, useContext} from 'react'; import {Navbar, Nav, Button, Container, Modal, ModalTitle, ModalBody, Form} from 'react-bootstrap'; import {Link} from "react-router-dom"; import styled from "styled-components"; import ModalHeader from "react-bootstrap/ModalHeader"; import axios from "axios"; import { useHistory } from "react-router-dom"; import {API_REGISTRATION} from "../../Adress"; const Styles = styled.div` a, .navbar-brand, .navbar-nav .nav-link { color: black; &:hover { color: black; } ; b, .navbar{ background-color: #61dafb; } } ` const Header = () => { let history = useHistory(); let [users, setUsers] = useState([]); let [user, setUser] = useState({}); let [curr, setCurr] = useState(JSON.parse(localStorage.getItem('currentUser')) ? JSON.parse(localStorage.getItem('currentUser')) : 'asd'); useEffect(() => { axios.get(API_REGISTRATION).then(res => { setUsers(res.data); }) },[]); function handleInps(e){ let obj = { ...user, [e.target.name]: e.target.value }; setUser(obj); } function login(){ let check = false; let currentUser = {}; users.forEach((p) => { if(p.account === user.account && p.password === user.password){ check = true; currentUser = p; localStorage.setItem('currentUser', JSON.stringify(currentUser)); } }); if(check){ history.push('/') } else { alert('No such user'); } } const [show, setShow] = useState(false); const handleClose = () => setShow(false); const handleShow = () => setShow(true); return ( <div style={{marginBottom: '60px'}} > <Styles> <Navbar collapseOnSelect expand="lg" bg="light" variant="light" fixed="top" > <Navbar.Toggle aria-controls="responsive-navbar-nav"/> <Navbar.Collapse id="responsive-navbar-nav"> <Nav> <Link to="/"><img style={{maxHeight:'30px'}} src={'https://images.creativemarket.com/0.1.0/ps/6715521/1820/1214/m1/fpnw/wm0/mountain-logo-.jpg?1563738224&s=3897e57c7910893aea53fb4f380f3f73'} /></Link> </Nav> <Nav className="mx-auto"> <Nav.Link><Link to="/">SKI</Link></Nav.Link> <Nav.Link><Link to="/">SNOWBOARD</Link></Nav.Link> <Nav.Link><Link to="/">COMPANY</Link></Nav.Link> </Nav> <Nav> <button className={'btn btn-primary mr-2'} onClick={() => history.push('/favourite')} >Favourite</button> <button className={'btn btn-primary mr-2'} onClick={() => history.push('/cart')} >Cart</button> <Nav.Link><Link to="/list">SHOP</Link></Nav.Link> { curr.account ? ( <Nav.Link onClick={() => localStorage.clear()}><Link onClick={() => window.location.reload()}>LOGOUT: {curr.account.toUpperCase()}</Link></Nav.Link> ) : <Nav.Link><Link onClick={handleShow}>ACCOUNT</Link></Nav.Link> } </Nav> </Navbar.Collapse> </Navbar> </Styles> <Modal show={show} onHide={handleClose}> <ModalHeader closeButton> <ModalTitle>Log in</ModalTitle> </ModalHeader> <ModalBody> <Form> <Form.Group controlId='fromBasicEmail'> <Form.Label>Email Address</Form.Label> <Form.Control onChange={handleInps} type='email' name={'account'} placeholder='Enter email'/> [Photo] <Form.Text className='text-muted'>We'll never share your email with anyone else.</Form.Text> </Form.Group> <Form.Group controlId='fromBasicPassword'> <Form.Label>Password</Form.Label> <Form.Control onChange={handleInps} name={'password'} type='password' placeholder='Enter password'/> </Form.Group> <button onClick={login} >Login</button> <button onClick={()=> history.push('register')} >Register</button> </Form> </ModalBody> </Modal> </div> ); }; export default Header;
import React, { PureComponent } from 'react' import { Text, StyleSheet ,TouchableOpacity} from 'react-native' import { scale, width,colors } from '@/utils/device'; export default class LargeBtn extends PureComponent { render(){ return( <TouchableOpacity style={[styles.btn,this.props.btnStyle]} activeOpacity={0.6} onPress={this.props.press}> <Text style={styles.btnText}>{this.props.title}</Text> </TouchableOpacity> ) } } const styles = StyleSheet.create({ btn: { marginTop: scale(25), marginBottom: scale(20), height: scale(44), backgroundColor: colors.blue2, alignItems: 'center', justifyContent: 'center' }, btnText: { fontSize: scale(18), color: 'white' }, })
export class Card { constructor(data, template, userId, {handleCardClick, handleLikeClick, handleDeleteClick}) { this._name = data.name; this._link = data.link; this._likes = data.likes; this._cadrId = data._id; this._ownerId = data.owner._id; this._userId = userId; this._handleLikeClick = handleLikeClick; this._handleDeleteClick = handleDeleteClick; this._template = document.querySelector(template); this._element = this._getTemplate(); this._cardImage = this._element.querySelector('.element__photo'); this._handleCardClick = handleCardClick; this._cardContent = this._element.querySelector('.element__name'); this._buttonDelete = this._element.querySelector('.element__button-delete'); this._buttonLike = this._element.querySelector('.element__button-like'); this._counter = this._element.querySelector('.element__button-like-counter'); } _getTemplate() { return this._template.content.querySelector('.element').cloneNode(true); } createCard() { this._cardContent.textContent = this._name; this._cardImage.alt = this._name; this._cardImage.src = this._link; this._setEventListeners(); this.setLikesStart(); return this._element; } _setEventListeners() { this._buttonLike.addEventListener('click', () => this._handleLikeClick(this._cadrId, this._checkLike())); this._cardImage.addEventListener('click', () => this._handleCardClick(this._link, this._name)); if (this._ownerId === this._userId.id) { this._buttonDelete.addEventListener('click', () => this._handleDeleteClick(this._cadrId)); } else { this._buttonDelete.style.display = 'none'; } } _checkLike() { return this._buttonLike.classList.contains("button-like_yes") } deleteCard(){ this._element.remove() } setLike() { this._buttonLike.classList.toggle('button-like_yes'); } setCounter(arr){ this._counter.textContent = arr.length; } setLikesStart() { this.setCounter(this._likes); if (this._likes.some((element) => element._id === this._userId.id)) { this._buttonLike.classList.add('button-like_yes'); } else { this._buttonLike.classList.remove('button-like_yes'); } } }
services. service('PushNotificationService', ['$rootScope', '$state', '$cordovaPush', '$cordovaDialogs', '$cordovaMedia', '$cordovaToast', 'ionPlatform', 'Account', function ($rootScope, $state, $cordovaPush, $cordovaDialogs, $cordovaMedia, $cordovaToast, ionPlatform, Account) { var notifications = []; var regId; function register() { var config = null; if (ionic.Platform.isAndroid()) { config = { "senderID": "272271445486" // REPLACE THIS WITH YOURS FROM GCM CONSOLE - also in the project URL like: https://console.developers.google.com/project/434205989073 }; } else if (ionic.Platform.isIOS()) { config = { "badge": "true", "sound": "true", "alert": "true" } } $cordovaPush.register(config).then(function (result) { console.log("Register success ", result); //$cordovaToast.showShortCenter('Registered for push notifications'); if (ionic.Platform.isIOS()) { regId = result; storeDeviceToken("ios"); } }, function (err) { console.log("Register error ", err) }); // Notification Received $rootScope.$on('pushNotificationReceived', function (event, notification) { console.log('Push Notification received'); console.log(JSON.stringify([notification])); if (ionic.Platform.isAndroid()) { handleAndroid(notification); } else if (ionic.Platform.isIOS()) { handleIOS(notification); } }); }; // Android Notification Received Handler function handleAndroid(notification) { console.log("In foreground " + notification.foreground + " Coldstart " + notification.coldstart); if (notification.event == "registered") { regId = notification.regid; storeDeviceToken("android"); } else if (notification.event == "message") { console.log('notificacion:: ', JSON.stringify(notification)); $state.go('app.notifications.list'); } else if (notification.event == "error") $cordovaDialogs.alert(notification.msg, "Push notification error event"); else $cordovaDialogs.alert(notification.event, "Push notification handler - Unprocessed Event"); } // IOS Notification Received Handler function handleIOS(notification) { if (notification.foreground == "1") { if (notification.sound) { var mediaSrc = $cordovaMedia.newMedia(notification.sound); mediaSrc.promise.then($cordovaMedia.play(mediaSrc.media)); } if (notification.body && notification.messageFrom) { $cordovaDialogs.alert(notification.body, notification.messageFrom); } else $cordovaDialogs.alert(notification.alert, "Push Notification Received"); if (notification.badge) { $cordovaPush.setBadgeNumber(notification.badge).then(function (result) { console.log("Set badge success " + result) }, function (err) { console.log("Set badge error " + err) }); } } // Otherwise it was received in the background and reopened from the push notification. Badge is automatically cleared // in this case. You probably wouldn't be displaying anything at this point, this is here to show that you can process // the data in this situation. else { if (notification.body && notification.messageFrom) { $cordovaDialogs.alert(notification.body, "(RECEIVED WHEN APP IN BACKGROUND) " + notification.messageFrom); } else $cordovaDialogs.alert(notification.alert, "(RECEIVED WHEN APP IN BACKGROUND) Push Notification Received"); } } // Stores the device token in a db using node-pushserver (running locally in this case) // // type: Platform type (ios, android etc) function storeDeviceToken(type) { Account.addTokenMobile({token: regId}, {}).$promise .then(function (res) { console.log("Token stored, device is successfully subscribed to receive push notifications."); }) .catch(function (err) { console.log("Error storing device token."); }); } // Removes the device token from the db via node-pushserver API unsubscribe (running locally in this case). // If you registered the same device with different userids, *ALL* will be removed. (It's recommended to register each // time the app opens which this currently does. However in many cases you will always receive the same device token as // previously so multiple userids will be created with the same token unless you add code to check). function removeDeviceToken() { Account.removeTokenMobile({token: regId}, {}).$promise .then(function (res) { console.log("Token removed"); }) .catch(function (err) { console.log("Error removing device token."); }); } /* Unregister - Unregister your device token from APNS or GCM Not recommended: See http://developer.android.com/google/gcm/adv.html#unreg-why and https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/index.html#//apple_ref/occ/instm/UIApplication/unregisterForRemoteNotifications Instead, just remove the device token from your db and stop sending notifications ** */ function unregister() { console.log("Unregister called"); removeDeviceToken(); //need to define options here, not sure what that needs to be but this is not recommended anyway /*$cordovaPush.unregister(options).then(function(result) { console.log("Unregister success " + result);// }, function(err) { console.log("Unregister error " + err) });*/ } return { register: register, unregister: unregister } }]);
import React from 'react'; import { Nav, Navbar, NavDropdown, Form, FormControl, Button, } from 'react-bootstrap'; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import { Link } from "react-router-dom"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faCartPlus } from '@fortawesome/free-solid-svg-icons'; import Menu from './Components/Menu/Menu'; import Chefs from './Components/Chefs/Chefs'; import Signin from './Components/Signin/Signin'; import 'bootstrap/dist/css/bootstrap.min.css'; import './App.css'; export default class App extends React.Component{ constructor(){ super(); this.state = { loggedInStatus: false, } } render() { return ( <> <Router> <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark"> <Link to="/"> <Navbar.Brand >Postmates 2.0</Navbar.Brand> </Link> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse > <Nav className="mr-auto"> <Link to="/Menu"> <Navbar.Text>Menu</Navbar.Text> </Link> <Link to="/Chefs"> <Navbar.Text>Chefs</Navbar.Text> </Link> <Form inline> <FormControl className="mr-sm-2" type="text" placeholder="Search"/> <Button variant="outline-info">Search</Button> </Form> </Nav> <Nav> <Link to="/Signin"> <Navbar.Text> Sign-In </Navbar.Text> </Link> <NavDropdown title={<FontAwesomeIcon icon={faCartPlus} size="2x" />} id="collapsible-nav-dropdown" alignRight > <NavDropdown.Item> My Cart </NavDropdown.Item> </NavDropdown> </Nav> </Navbar.Collapse> </Navbar> <Switch> <Route exact path="/menu" component={Menu} /> <Route exact path="/Chefs" component={Chefs} /> <Route exact path="/Signin" component={Signin} /> </Switch> </Router> </> ) } }
import React, { Component } from 'react'; import './App.css'; import { connect } from 'react-redux'; import SnackList from '../SnackList/SnackList'; import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles'; // import { withStyles } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; import TextField from '@material-ui/core/TextField'; const theme = createMuiTheme({ overrides: { MuiButton: { root: { background: 'linear-gradient(40deg, #D7006E 5%, #FFCFC4 80%)', borderRadius: 3, border: 0, color: 'black', fontWeight: "bold", height: 28, margin: 5, padding: '0 30px', boxShadow: '1px 2px 2px 1px #C90060', }, }, }, }); class App extends Component { constructor(props) { super(props); this.state = { newSnack: '', }; } // tracking snack input field handleChange = (event) => { this.setState({ newSnack: event.target.value }); } // quick, snack to the reducer mobile! submitSnax = (event) => { event.preventDefault(); //hey browser html we got it // const action = { type: 'ADD_SNACK', snack: this.state.newSnack } this.props.dispatch({ type: 'ADD_SNACK', snack: this.state.newSnack }); //trying it the one-liner way this.setState({ newSnack: '', }); } render() { return ( <MuiThemeProvider theme={theme}> <div className="App"> <h3>IT'S FOR SNACKS</h3> <TextField label="snack it up" placeholder="s n a c k s" onChange={this.handleChange} value={this.state.newSnack} margin="normal" /> <Button onClick={this.submitSnax}>s n a c k</Button> <SnackList /> </div> </MuiThemeProvider> ); } } export default connect()(App);
var s; var scl=10; var tuna; const SPEED = 20; function setup() { createCanvas(400, 400); s = new Snake(); frameRate(SPEED); pickLocation(); } function pickLocation(){ var cols = floor(width/scl); var rows = floor(height/scl); tuna = createVector(floor(random(cols)),floor(random(rows))); tuna.mult(scl); } function draw() { background('#000000'); s.die(); s.update(); s.show(); if(s.eat(tuna)){ pickLocation(); } noStroke(); fill('#6ef075'); rect(tuna.x,tuna.y,scl,scl); } function keyPressed(){ if(keyCode === UP_ARROW){ s.dir(0, -1); } if(keyCode === DOWN_ARROW){ s.dir(0, 1); } if(keyCode === LEFT_ARROW){ s.dir(-1, 0); } if(keyCode === RIGHT_ARROW){ s.dir(1, 0); } }
import { loginout,login,cadastro } from "./login.js"; export function pag_home(){ var bt1 = window.document.getElementById("bt1"); var bt2 = window.document.getElementById("bt2"); bt1.addEventListener("click",login); bt2.addEventListener("click",cadastro); } export function pag_root(){ var bt3 = window.document.getElementById("bt3"); bt3.addEventListener("click",loginout); }
test('des01', () => { const alphabetGrec = [ 'α', 'β', 'γ', 'δ', 'ε' ] const alpha = alphabetGrec[0] const beta = alphabetGrec[1] console.log(alpha, beta) });
(function() { "use strict"; angular .module("vcas") .factory("ApiService", ApiService); /* @ngInject */ function ApiService($q, $http, AlertsService) { return { callEndpoint: callEndpoint, }; ////////// function callEndpoint (url, payload, errorMsg) { /** * Calls the API endpoint with the supplied URL and Payload of data * @param {string} url The URL of the endpoint * @param {object} payload The payload data sent with the request * @param {string} errorMsg The error alert message specific to the API call * @return {promise} */ var deferred = $q.defer(); $http.post(url, payload) .success(successCB) .error(errorCB); return deferred.promise; function successCB (response) { /** * Handle the successful response of the HTTP request * @private * @param {object} response The API response data */ var responseData = response.resultList || response.queryResult || response; handleResults(responseData, deferred, errorMsg); } function errorCB (error) { /** * Handle the error response of the HTTP request * @private * @param {object|string} response The API response data */ AlertsService.addErrors(error || "Server Error"); // provide helpful feedback to error callback deferred.reject({ feedback: "the server returned an error" }); } } function handleResults (responseData, promise, errorMsg) { /** * Parse the response for successes and errors. * Display only error alerts (leave the success alerts up to the controller) * and return the data * * @param {object} responseData The API response * @param {promise} promise The promise used for the request * @param {string} errorMsg The error alert message specific to the API call */ var results = angular.isArray(responseData.result) ? responseData.result : [responseData.result], successes = _.filter(results, {resultCode: "0"}), errors = _.filter(results, function(result) {return result.resultCode !== "0";}); // Display all the Error alerts: if (errors.length === 1) { AlertsService.addErrors((errorMsg || "Request error:") + " " + errors[0].resultText + " (" + errors[0].resultCode + ")"); } else if (errors.length > 1) { AlertsService.addErrors(_.pluck(errors, "resultId"), errorMsg); } if (successes.length) { promise.resolve(responseData); } else { promise.reject({feedback: "the api returned an error"}); } } } })();
// JavaScript Document $(function(){ var deviceWidth = document.documentElement.clientWidth; if(deviceWidth > 750) deviceWidth = 750; document.documentElement.style.fontSize = deviceWidth / 7.5 + 'px'; //年份 var day=new Date(); var d = day.getFullYear(); $(".nowtime").html(d); //点击显示导航 $(".zg_daoh").click(function(){ if($(".zg_daoh_cet").is(":hidden")){ $(this).find("img").attr("src","images/zg_hpic_ac.png"); $(this).css("background","#2dc571"); }else{ $(this).find("img").attr("src","images/zg_hpic.png"); $(this).css("background",""); } $(".zg_daoh_cet").toggle(); $(".mask").toggle(); if($(".mask").is(":hidden")){ $("html,body").css("overflow-y","visible"); }else{ $("html,body").css("overflow-y","hidden"); } }); $(".mask").click(function(){ $(".zg_daoh_cet").hide(); $(".mask").hide(); $(".zg_daoh").find("img").attr("src","images/zg_hpic.png"); $(".zg_daoh").css("background",""); $("html,body").css("overflow-y","visible"); }); $(".header_layer .box_l").on("click", ".click", function() { var self = $(this); var index = self.index() - 1; $(".zg_daoh_cet .box_l").find(".click").removeClass("act"); self.addClass("act"); $(".zg_daoh_cet .box_r").find("ul").hide(); $(".zg_daoh_cet .box_r").find("ul").eq(index).show(); }); //教师考试 切换 $(".zg_tt_top li").each(function(i){ $(this).click(function(){ $(".zg_tt_top li").removeClass("hov"); $(this).addClass("hov"); $(".zg_tt_bot").hide(); $(".zg_tt_bot").eq(i).show(); }); }); //回到顶部 $(window).on("scroll", function() { var h = $(window).scrollTop(); if(h > 50) { $(".back-top").css("display", "block"); } else { $(".back-top").css("display", "none"); } }); $(".back-top").click(function() { $("html,body").animate({ scrollTop: 0 }, 500); }); //换一批 var reLen=$(".reading_list li").length; for (var i = 0; i < 5; i++) { $(".reading_list li").eq(i).show(); } $(".reading_list li").eq(4).addClass("nobobt"); var reArr=[]; for (var i = 0; i < reLen; i++) { reArr.push(i); } reArr.sort(function(){ return 0.5-Math.random(); }) $(".batch").click(function(){ $(".reading_list li").removeClass("nobobt"); $(".reading_list li").hide(); for (var i = 0; i < 5; i++) { $(".reading_list li").eq(reArr[i]).show(); } var max=Math.max.apply(null,reArr.slice(0,5)); $(".reading_list li").eq(max).addClass("nobobt"); reArr.sort(function(){ return 0.5-Math.random(); }) }) // 底部导航 $(".fixed").on("click", "a", function() { $(".fixed li").removeClass("act"); $(this).parent().addClass("act"); }); //栏目切换 $(".list a").on("click",function(){ $(this).parent().parent().find("a").removeClass("act"); $(this).addClass("act"); }) // 微信分享 $(".vxf").click(function() { $(".mask2").show(); }) $(".mask2").click(function() { $(this).hide(); }) // share window._bd_share_config = { "common": { "bdSnsKey": {}, "bdText": "", "bdMini": "2", "bdMiniList": false, "bdPic": "", "bdStyle": "0", "bdSize": "16" }, "share": {}, }; // window._bd_share_config = { // share : [{ // "bdSize" : 16 // }], // selectShare : [{ // "bdselectMiniList" : ['weixin','tqq','qzone','tsina','sqq'] // }] // } with(document) 0[(getElementsByTagName('head')[0] || body).appendChild(createElement('script')).src = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=' + ~(-new Date() / 36e5)]; });
const mongoose = require('mongoose'); const expensesSchema = new mongoose.Schema({ merchant: { type: String, minlength: [4, 'Merchant must be at least 4 characters.'], maxlength: [20, 'Merchant must be less than 20 characters.'], required: true }, total: { type: String, required: true }, category: { type: String, required: true }, description: { type: String, required: true, minlength: [3, 'Description must be at least 3 characters.'], maxlength: [30, 'Description must be less than 30 characters.'], }, report: { type: Boolean, required: true, default: false }, user: { type: mongoose.Types.ObjectId, ref: 'User', required: true } }); module.exports = mongoose.model('Expenses', expensesSchema);
'use strict'; /** * @ngdoc function * @name laoshiListApp.controller:LoginCtrl * @description * # LoginCtrl * Controller of the laoshiListApp */ angular.module('laoshiListApp') .controller('LoginCtrl', ['currentAuth', '$scope', 'firebasePath', '$location', 'Auth', function (currentAuth, $scope, firebasePath, $location, Auth) { if(currentAuth) { $location.path('/'); } $scope.someInfo = Auth.$getAuth(); $scope.alerts = []; $scope.login = function() { $scope.alerts.push({type:'info', msg: 'Attempting to log you in...'}); Auth.$authWithPassword({ email : $scope.usr.email, password : $scope.usr.password }).then(function(authData) { $scope.alerts.push({type:'success', msg: authData.password.email + ' has been logged in. You will now be redirected.'}); $location.path('/'); }).catch(function(error) { $scope.alerts.push({type: 'danger', msg: 'Login failed. Please try again, reset your password, or contact an administrator.'}); console.log('Login Failed!', error); }); }; }]);
import Vue from 'vue' import VModal from '../src/index.js' import ModalAlert from './modal-alert.vue' import App from './app.vue' Vue.use(VModal, { register: { 'alert': ModalAlert, }, }) Vue.component('App', App) new Vue({ render: h => h('App') }).$mount('#app')
/*global describe:true, it:true, before:true, after:true */ 'use strict'; var _ = require('lodash'), demand = require('must'), fs = require('fs'), path = require('path'), redis = require('redis'), sinon = require('sinon') ; var Reflip = require('../index'); var testfile = path.join(__dirname, './mocks/features.json'); var testFeatures = require('./mocks/features.json'); var file2 = path.join(__dirname, './mocks/f2.json'); describe('Reflip', function() { before(function(done) { var r = redis.createClient(); var chain = r.multi(); var features = []; _.each(testFeatures.features, function(item) { features.push(item.name); chain.hmset('reflip:' + item.name, item); }); chain.set('reflip:ttl', testFeatures.ttl); chain.sadd('reflip:features', features); chain.exec(function(err, replies) { done(); }); }); describe('with file adapter', function() { it('can be constructed', function(done) { var flipper = new Reflip( { storage: new Reflip.FileAdapter({ filename: testfile }), }); flipper.must.be.an.object(); done(); }); it('calls refresh on its adapter', function(done) { var flipper = new Reflip({ storage: new Reflip.FileAdapter({ filename: testfile }), }); flipper.on('ready', function() { flipper.must.have.property('storage'); flipper.must.have.property('features'); flipper.features.must.be.an.object(); Object.keys(flipper.features).length.must.equal(4); done(); }); }); }); describe('with redis adapter', function() { it('can be constructed', function(done) { var flipper = new Reflip({ storage: new Reflip.RedisAdapter({ client: redis.createClient() }), }); flipper.must.be.an.object(); done(); }); it('calls refresh on its adapter', function(done) { var flipper = new Reflip({ storage: new Reflip.RedisAdapter({ client: redis.createClient() }), }); flipper.on('ready', function() { flipper.must.have.property('storage'); flipper.storage.must.have.property('refreshTimer'); flipper.storage.refreshTimer.must.be.an.object(); flipper.storage.ttl.must.equal(60000); flipper.features.must.be.an.object(); Object.keys(flipper.features).length.must.equal(4); done(); }); }); }); describe('register()', function() { var flipper; before(function(done) { flipper = new Reflip({ features: {} }); done(); }); it('is a function on the reflip object', function(done) { flipper.register.must.be.a.function(); done(); }); it('adds a feature to the reflip object', function(done) { function check() { return true; } flipper.register('aardwolf', check); flipper.features.must.have.property('aardwolf'); flipper.features.aardwolf.type.must.equal('custom'); flipper.features.aardwolf.checker.must.equal(check); done(); }); it('the checker function is called when the registered feature is checked', function(done) { var check = sinon.stub(); check.returns(true); flipper.register('anaconda', check); var feature = flipper.features.anaconda; feature.check().must.equal(true); check.called.must.be.truthy(); done(); }); it('can accept a Feature object argument', function(done) { var feature = new Reflip.Feature( { name: 'armadillo', type: 'boolean', enabled: true }); flipper.register(feature); flipper.features.must.have.property('armadillo'); done(); }); }); describe('flip()', function() { var flipper; before(function(done) { flipper = new Reflip({ storage: new Reflip.FileAdapter({ filename: testfile }), }); flipper.on('ready', done); }); it('returns a function', function(done) { var middleware = flipper.flip(); middleware.must.be.a.function(); done(); }); it('behaves like connect middleware', function(done) { var middleware = flipper.flip(); var request = {}, response = {}, next = sinon.spy(); middleware(request, response, next); next.calledOnce.must.be.truthy(); done(); }); it('decorates its first argument with a check function', function(done) { var middleware = flipper.flip(); var request = {}, response = {}; middleware(request, response, function() { request.must.have.property('check'); request.check.must.be.a.function(); var features = request.check(); features.must.be.an.object(); features.alpacas.must.be.truthy(); features.aardvarks.must.be.true(); features.archaeopteryx.must.equal(request.check('archaeopteryx')); request.check('agouti').must.equal(flipper.default); done(); }); }); it('obeys its `exportName` option', function(done) { var f2 = new Reflip({ exportName: 'wobble', storage: new Reflip.FileAdapter({ filename: testfile }), }); var middleware = f2.flip(); var request = {}, response = {}; middleware(request, response, function() { request.must.have.property('wobble'); request.wobble.must.be.a.function(); done(); }); }); }); describe('gate()', function() { var flipper; before(function(done) { flipper = new Reflip({ storage: new Reflip.FileAdapter({ filename: testfile }), }); flipper.on('ready', done); }); it('requires a feature name argument', function(done) { function shouldThrow() { return flipper.gate(); } shouldThrow.must.throw(); done(); }); it('returns a function', function(done) { var gater = flipper.gate('archaeopteryx'); gater.must.be.a.function(); done(); }); it('invokes its callback with no argument if the feature is enabled', function(done) { var req = {}, res = {}; req.check = sinon.stub(); req.check.returns(true); var next = sinon.spy(); var gater = flipper.gate('aardvarks'); gater(req, res, next); req.check.calledOnce.must.be.truthy(); next.calledOnce.must.be.truthy(); done(); }); it('invokes its callback with reflip.httpcode if the feature is disabled', function(done) { var req = {}, res = {}; req.check = sinon.stub(); req.check.returns(false); res.send = sinon.spy(); var next = sinon.spy(); var gater = flipper.gate('archaeopteryx'); gater(req, res, next); req.check.calledOnce.must.be.truthy(); res.send.calledOnce.must.be.truthy(); next.calledOnce.must.be.false(); var arglist = res.send.args[0]; arglist.length.must.equal(2); arglist[0].must.equal(404); arglist[1].must.be.a.string(); arglist[1].must.equal('Not Found'); done(); }); it('allows specifying a custom failure handler if the feature is disabled', function(done) { var req = {}, res = {}; req.check = sinon.stub(); req.check.returns(false); res.json = sinon.spy(); var next = sinon.spy(); var gater = flipper.gate('aardwolf', function(req, res) { res.json(403, { code: 'ForbiddenError', message: 'This feature is unavailable.' }); }); gater(req, res, next); req.check.calledOnce.must.be.truthy(); res.json.calledOnce.must.be.truthy(); next.calledOnce.must.be.false(); var arglist = res.json.args[0]; arglist.length.must.equal(2); arglist[0].must.equal(403); arglist[1].must.eql( { code: 'ForbiddenError', message: 'This feature is unavailable.' }); done(); }); it('updates its responses', function(done) { var features2 = { "features": [ { "name": "aardvarks", "type": "boolean", "enabled": false }, { "name": "archaeopteryx", "type": "boolean", "enabled": true }, { "name": "aardwolf", "type": "metered", "enabled": true, "chance": 25 } ] }; fs.writeFile(file2, JSON.stringify(testFeatures), function(err) { demand(err).not.exist(); var flipper = new Reflip({ storage: new Reflip.FileAdapter({ filename: file2 }), }); var count = 0; function blort() { var bar = flipper.features.aardvarks.check({}); if (count === 0) { fs.writeFileSync(file2, JSON.stringify(features2)); count++; } if (bar === false) { flipper.shutdown(); flipper.removeListener('ready', blort); done(); } } flipper.on('ready', blort); }); }); after(function(done) { flipper.shutdown(); done(); }); }); after(function(done) { fs.unlink(file2, function(err) { demand(err).not.exist(); var r = redis.createClient(); var chain = r.multi(); chain.del('reflip:ttl'); chain.del('reflip:features'); _.each(Object.keys(testFeatures.features), function(k) { chain.del('reflip:' + k); }); chain.exec(function(err, replies) { done(); }); }); }); });
export const ADD_CARDS = 'ADD_CARDS'; export const ADD_TO_CART = 'ADD_TO_CART'; export const REMOVE_FROM_CART = 'REMOVE_FROM_CART';
import React from 'react'; import Paper from '@material-ui/core/Paper'; import Grid from '@material-ui/core/Grid'; import InputAdornment from '@material-ui/core/InputAdornment'; import TextField from '@material-ui/core/TextField'; import style from '../modules/root.module.css'; import Button from '@material-ui/core/Button'; import { useDispatch, useSelector } from "react-redux"; import { log } from '../actions/user.actions'; import { Link, Redirect } from 'react-router-dom'; const Login = () => { const dispatch = useDispatch(); const { loggingIn, loggedIn } = useSelector(state => state.authentication); const submitHandler = (event) => { event.preventDefault(); const email = event.target.email.value; const password = event.target.password.value; const user = { email , password }; dispatch(log(user)); } if (loggedIn) { return <Redirect to="/keys" /> } return ( <Grid container spacing={3} justify="center" direction="column" > <form onSubmit={submitHandler}> <Grid item xs={6} className={style.marginTop} > <Paper > <TextField className={'sdsd'} variant="outlined" label="Password" // value={10} type="password" name="password" fullWidth InputProps={{ startAdornment: <InputAdornment position="start">Password</InputAdornment>, }} /> </Paper> </Grid> <Grid item xs={6} className={style.marginTop} > <Paper > <TextField className={'sdsd'} variant="outlined" label="Email" type="text" name="email" // value={10} fullWidth InputProps={{ startAdornment: <InputAdornment position="start">Email</InputAdornment>, }} /> </Paper> </Grid> <Grid item xs={6} className={style.marginTop}> <Button variant="contained" color="primary" type="submit"> Login </Button> </Grid> </form> <Grid item xs={6} className={style.marginTop}> <Link to="/registration">Registration</Link> </Grid> </Grid> ); } export default Login;
import React from 'react'; import Logo from 'images/logo_dash.svg'; const DashLogo = () => ( <span className="dash-logo"> <Logo /> </span> ); export default DashLogo;
/** * Utilities */ /* Methods -------------------------------------------------------------------*/ /** * Returns value for an exponential curve * @param {number} progress The p value for the curve * @param {number} start The start value for the curve * @param {number} end The end value for the curve * @returns {number} The exponential value */ function exp(progress, start, end) { return start + (end - start) * (progress * progress); } /** * Returns a curve object based on the common curve options * @param {object} opts The config for the curve (base, limit, step, curve) * @returns {object} The curve object */ function tween(opts) { let step = 0; return function _tweenStep(progress) { if (progress === undefined) step++; return (opts.curve || exp)(Math.min(1, ((progress === undefined) ? step : progress / (opts.steps || 1))), opts.base, opts.limit); }; } /** * Parses the results from the data-source query * @param {*} results The raw results * @param {array} ids The list of ids to look for in the response * @param {*} params The original parameters of the query * @returns {object} The indexed result set found */ function basicParser(results, ids, params = {}) { if (results === null || results === undefined) return {}; ids = ids.map(id => `${id}`); if (Array.isArray(results)) { return results.reduce((acc, curr) => { if (ids.includes(`${curr.id}`)) { acc[curr.id] = curr; } return acc; }, {}); } const keys = Object.keys(results).map(id => `${id}`); return keys.reduce((acc, curr) => { if (ids.includes(curr)) { acc[curr] = results[curr]; } return acc; }, {}); } /** * Deferred promise helper * @returns {object} A deferred promise handler */ function deferred() { let resolve; let reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); return { promise, resolve, reject }; } /** * Returns a context key based on query parameters * @param {array} u The list of uniqueness identifying parameters for the query * @param {*} params The parameters for the query * @returns {string} The context key */ function contextKey(u, params) { return Array.from(u || []).map(opt => `${opt}=${JSON.stringify(params[opt])}`).join(';'); } /** * Returns a record key based on a context key and an id * @param {*} context The context key * @param {*} id The id * @returns {string} The record key */ function recordKey(context, id) { return `${context}::${id}`; } /* Exports -------------------------------------------------------------------*/ module.exports = { deferred, exp, tween, basicParser, contextKey, recordKey };
import React from 'react'; import {Layout} from "../Layout"; import {connect} from 'react-redux'; import {compose, lifecycle} from 'recompose'; import {getProfile} from "./store/action"; import {InfoAlert} from "../Alerts"; import { Button, Card, CardBody, CardText, Col, Row, } from 'reactstrap'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import '../Layout/css/main.css'; import {redirectTo} from "../../functions/redirect"; import {TextTruncate} from "../Layout/TextContainer"; import {Fetching} from "../Layout/Loader"; const mapStateToProps = ({ userReducer: { profile } }) => ({ profile }); const ProfileOuting = ({outing, history}) => ( <Card> <CardBody className={'text-center'}> <CardText> <TextTruncate maxSize={33} unDeploy content={outing.name}/> </CardText> <Button className={'primary white-text'} onClick={() => redirectTo(history, outing['@id'])}> <FontAwesomeIcon icon="eye" /> Voir l'annonce </Button> </CardBody> </Card> ); export const Profile = compose( connect( mapStateToProps, dispatch => ({ getProfile: () => dispatch(getProfile()) }) ), lifecycle({ componentDidMount() { this.props.getProfile(); } }) )(({profile, ...rest}) => ( <Layout padding defaultContainer {...rest}> { profile ? <div className={'b-ws'}> <h1 className={'text-center'}>Bienvenue sur votre profil {profile.username}</h1> <Row className={'pt-3 pb-3'}> <Col xs={12} md={6} className={'b-right-md'}> <p className={'text-center font-italic'}>Sorties créées</p> { (profile.outingsOwner && profile.outingsOwner.length) ? profile.outingsOwner.map((outing, index) => ( <ProfileOuting key={index} outing={outing} {...rest}/> )) : <InfoAlert content={'Vous n\'avez créé aucune sortie'}/> } </Col> <Col xs={12} md={6} className={'b-left-md'}> <p className={'text-center font-italic'}>Participation aux sorties</p> { (profile.outingsParticipate && profile.outingsParticipate.length) ? profile.outingsParticipate.map((outing, index) => ( <ProfileOuting key={index} outing={outing.participateTo} {...rest}/> )) : <InfoAlert content={'Vous n\'avez participé à aucune sortie'}/> } </Col> </Row> </div> : <Fetching content={'de votre profil'}/> } </Layout> ));
import React from "react"; import "./instruction.css"; import Navbar from '../../components/Navbar' const instructionPage = ({ match }) => ( <div> <Navbar page="instructions"/> <div class="wrapper"> <br></br> <div class="half"> <div class="tab"> <input id="tab-one" type="checkbox" name="tabs"/> <label for="tab-one">What is a <i>service</i> defined as?</label> <div class="tab-content"> <p>A <i>service</i> is something a student wants to provide or offer to others.</p> </div> </div> <div class="tab"> <input id="tab-two" type="checkbox" name="tabs"/> <label for="tab-two">What is a <i>job</i> defined as?</label> <div class="tab-content"> <p>A <i>job</i> is something a student requests to be done by someone else.</p> </div> </div> <div class="tab"> <input id="tab-three" type="checkbox" name="tabs"/> <label for="tab-three">Who is allowed to use <i>The Quarry?</i></label> <div class="tab-content"> <p><i>The Quarry</i> is a University of North Carolina at Charlotte based website. All UNCC students, staff, and faculty are permitted to use the site in its entirety. Anyone outside of the UNCC community is not permitted at this time.</p> </div> </div> <div class="tab"> <input id="tab-four" type="checkbox" name="tabs"/> <label for="tab-four">How do I find my <i>UNCC ID number?</i></label> <div class="tab-content"> <p><a href="https://aux.uncc.edu/49er-card">Click here</a> for more information regarding your UNCC ID.</p> </div> </div> <div class="tab"> <input id="tab-five" type="checkbox" name="tabs"/> <label for="tab-five">Does my <i>username</i> have to be the same as my UNCC login?</label> <div class="tab-content"> <p>No, the <i>username</i> you create can be whatever you would like it to be as long as it's appropriate.</p> </div> </div> <div class="tab"> <input id="tab-six" type="checkbox" name="tabs"/> <label for="tab-six">My account was <i>banned</i>, what can I do now?</label> <div class="tab-content"> <p>If your account is temporarily banned there is no appeal process. However, if your account is temporarily banned you may submit an appeal.</p> </div> </div> <div class="tab"> <input id="tab-seven" type="checkbox" name="tabs"/> <label for="tab-seven">How do I advertise a <i>job</i> or <i>service</i>?</label> <div class="tab-content"> <p>Once you sign up and log in you will be directed to <i>service</i> and <i>job</i> form you can fill out.</p> </div> </div> <div class="tab"> <input id="tab-eight" type="checkbox" name="tabs"/> <label for="tab-eight">How do I search for help? </label> <div class="tab-content"> <p>Simply click on the <i>browse</i> tab and search for help depending on whether you need help with <i>job</i> or <i>service</i>.</p> </div> </div> <br></br> <br></br> <br></br> </div> </div> </div> ); export default instructionPage;
function TrelloAuthenticationRepository(){ return { apiKey: "08a27147750faeb03030d310b919258c", apiToken: "4439c681d1629b22c8c14a8f80052c9b950cf524e10b7c8d83a9a38150982eca" }; } module.exports = TrelloAuthenticationRepository;
import React, { Component } from 'react'; import { Text, View, Image, ListView, ScrollView, Dimensions, StyleSheet, } from 'react-native'; import { Tile, List, ListItem, Card, } from 'react-native-elements'; import GiftedSpinner from 'react-native-gifted-spinner'; import Swiper from 'react-native-swiper'; import { configData } from '../branding/index'; import Communications from 'react-native-communications'; const { width, height } = Dimensions.get('window'); class UserDetail extends React.Component { constructor(props){ super(props); this.state = {}; } render() { return ( <ScrollView> <Swiper style={styles.wrapper} showsButtons={false} width={width} height={width/1.5} showsPagination={false} autoplay loop > { configData.infoLabor.labor_images.map((entry, index) => { return ( <Tile key={index} imageSrc={entry} featured /> ); }) } </Swiper> <Card containerStyle={{marginLeft: 0 , marginRight: 0}} > <Text style={{marginBottom: 10}}> {`${configData.infoLabor.location.name.toUpperCase()}`} </Text> <Text style={{marginBottom: 10}}> {`${configData.infoLabor.location.street}, ${configData.infoLabor.location.postcode}, ${configData.infoLabor.location.city}`} </Text> </Card> <List> { configData.infoLabor.phone ? <ListItem title="Phone" rightTitle={configData.infoLabor.phone} rightTitleStyle={{color: '#000'}} hideChevron onPress={() => { Communications.phonecall(configData.infoLabor.phone_click ? configData.infoLabor.phone_click : configData.infoLabor.phone, true); }} /> : null } { configData.infoLabor.cell ? <ListItem title="Fax" rightTitle={configData.infoLabor.cell} rightTitleStyle={{color: '#000'}} hideChevron /> : null } </List> <List> { configData.infoLabor.email ? <ListItem title="Email" rightTitle={configData.infoLabor.email} rightTitleStyle={{color: '#000'}} hideChevron onPress={() => { Communications.email([configData.infoLabor.email],null,null,'','') }} /> : null } { configData.infoLabor.url ? <ListItem title="Site" rightTitle={configData.infoLabor.url} rightTitleStyle={{color: '#000'}} hideChevron /> : null } </List> </ScrollView> ); } } const styles = StyleSheet.create({ wrapper: { }, slide: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#9DD6EB', }, scrollView: { }, container: { flex: 1, marginTop: 20, }, separator: { flex: 1, height: 1, backgroundColor: '#8E8E8E', }, }); export default UserDetail;
import { BrowserRouter,Link, Route, Switch} from 'react-router-dom' import {Nav} from '../Nav/Nav' import Main from "../Main/main"; import About from "../About/about"; import ProductsList from "../Products/ProductsList"; import Product from "../Products/Product"; import Blog from "../Blog/Blog"; import MyForm from "../Form/MyForm"; import ToDoList from "../ToDoList/ToDoList" export default function Routing(props) { return ( <BrowserRouter> <Nav theme={props.theme}/> <main> <Switch> <Route path="/" exact> <Main /> </Route> <Route path="/about" > <About/> </Route> <Route path="/product/:id" component={(props)=><Product />} /> <Route path="/blog/:id" component={Blog}/> <Route path="/myform" > <MyForm/> </Route> <Route path="/todolist" > <ToDoList/> </Route> <Route path="/products" > <ProductsList bucket={props.bucket}/></Route> {/* <Route path="/product/:id" component={ProductDetail} /> */} </Switch> </main> </BrowserRouter> ); }
Ext.define('Samurai.store.UserStore', { extend: 'Ext.data.Store', model: 'Samurai.model.User', autoLoad: true, autoSync: true, proxy: { type: 'ajax', api: { read: 'User/GetUsers', update: 'User/Update' }, reader: { type: 'json', root: 'users', successProperty: 'success' } } });
function validateForm() { var name = document.forms["contactForm"]["name"].value; var email = document.forms["contactForm"]["email"].value; var msg = document.forms["contactForm"]["message"].value; if (name == "") { alert("Please fill in your name."); return false; } if (email == "") { alert("Please fill in your email address."); return false; } if (msg == "") { alert("Please leave a short message for us."); return false; } } function WebClick() { $('#message-id').focus(); document.getElementById("message-id").value = "I am interested in Web page"; } function WebBasic() { $('#message-id').focus(); document.getElementById("message-id").value = "I am interested in Basic Web page"; } function WebStandard() { $('#message-id').focus(); document.getElementById("message-id").value = "I am interested in Standard Web page"; } function WebPremium() { $('#message-id').focus(); document.getElementById("message-id").value = "I am interested in Premium Web page"; } function clear() { document.forms["contactForm"].reset(); }
import React, { useEffect } from 'react' import { useMutation, gql } from '@apollo/client' import { useRouter } from 'next/router' import styled from 'styled-components' import { useMessages } from '../../context/useMessages' import RegisterForm from './RegisterForm' const MainLayout = styled.div` background: #f0f2f5; width: 90vw; height: 100vh; display: flex; align-items: center; justify-content: center; ` const REGISTER = gql` mutation register($input: UserInput!) { registerUser(input: $input) { id username role firstName lastName imageUrl } } ` const RegisterContainer = () => { const router = useRouter() const { displayMessage } = useMessages() const [register, { data, loading, error }] = useMutation(REGISTER) useEffect(() => { if (!loading && error) { displayMessage({ type: 'error', message: JSON.stringify(error.message) }) } else if (data && data.registerUser) { displayMessage({ type: 'notify', message: 'Успешно зарегистрированный в систему' }) router.push('/login') } }, [data, loading, error]) const handleSubmit = values => { register({ variables: { input: values }, errorPolicy: 'all' }) } return ( <MainLayout> <RegisterForm onSubmit={handleSubmit} /> </MainLayout> ) } export default RegisterContainer
import React, {Component} from 'react'; import Header from "../Components/Header"; import TabComponents from "../Components/TabComponents"; import Footer from "../Components/Footer"; class Main extends Component { render() { return ( <> <Header/> <div style={containerStyle} className='container'> <TabComponents/> </div> <Footer/> </> ); } } export default Main; const containerStyle = { width: '80%', margin: "0 auto" }
import ImageService from "./image-service.js"; //Your ImageService is a global class what can you do here to instantiate it? let _imageService = new ImageService function draw(image) { document.getElementById("bg").style.backgroundImage = `url(${image.large_url})` } export default class ImageController { constructor() { _imageService.getImage(draw) } }
//export appointment tablet module.exports = (sequelize,DataTypes) => { var Appointment = sequelize.define('Appointment', { reservation_date: { type: DataTypes.STRING, defaultValue: "", // allowNull: false, }, reservation_time: { type: DataTypes.STRING, // allowNull: false, }, barber_name: { type: DataTypes.STRING, defaultValue: "" }, customer_name: { type: DataTypes.STRING, defaultValue: "", }, customer_email: { type: DataTypes.STRING, validate: { } }, customer_phone: { type: DataTypes.STRING, validate: { len: [0, 15] } } }); ////////////////////////////////////////////////////////////////////////////////////////////// // Temporarily commented out the associate with the Employee model to get the app to run. ////////////////////////////////////////////////////////////////////////////////////////////// //Associate with Appointment.associate = models => { // Appointment.belongsTo(models.Employee,{ // EmployeeId: { // allowNull: false // } // }); Appointment.belongsTo(models.User,{ username: { allowNull: false } }); }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// return Appointment; };
import React from 'react'; import classNames from 'classnames'; import SignupForm from '../SignupForm/SignupForm'; import Translator from '../Translator/Translator'; import styles from './App.scss'; class App extends React.Component { state = { reordered: false, }; handleSignIn = () => { this.setState(state => ({ reordered: !state.reordered, })); }; render() { const { reordered } = this.state; return ( <div className={styles.container}> <Translator className={classNames( styles.translator, reordered && styles.reordered, )} onSignIn={this.handleSignIn} /> <SignupForm className={classNames(styles.form, reordered && styles.reordered)} /> </div> ); } } export default App;
const dateOfBirth = document.querySelector("#date-of-birth"); const luckyNumber = document.querySelector("#lucky-number"); const checkButton = document.querySelector("#check-btn"); const outputBox = document.querySelector("#output-box") function luckyOrNot (sum , luckyNumber ) { if ( sum % luckyNumber === 0) { outputBox.innerText = "Your Birthday is Lucky but don't wait for Luck, go and work" } else { outputBox.innerText = "Your Birthday is not Lucky but don't worry, now You can make your own Luck" } } function birthdayLuckyOrNot() { const birthDate = dateOfBirth.value; const sum = fetchSum(birthDate); luckyOrNot (sum , luckyNumber.value) } function fetchSum (birthDate) { birthDate = birthDate.replaceAll ("-" , "") let sum = 0; for(let v = 0 ; v < birthDate.length ; v++ ){ sum = sum + Number(birthDate.charAt(v)); } return sum; } checkButton.addEventListener("click" , birthdayLuckyOrNot)
'use strict' const http = require('http') , express = require('express') , app = express() , server = http.createServer(app); var count = 0; app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.use(express.static('./public/')); app.get('/count',(req,res)=>{ console.log(count); res.send({count: count}); }); app.get('/inc',(req,res)=>{ ++count; console.log(count); res.send({count: count}); }); app.get('/dec',(req,res)=>{ --count; res.send({count: count}); }); app.get('/reset',(req,res)=>{ count=0; res.send({count: count}); }); //App server ----------> server.listen(process.env.PORT || 1100, err => { if(err){ throw err } console.log('Server running on 1100') })
// the purpose of tor-manager is to buy the TOR router ASAP // so that another script can buy the port breakers. This script // dies a natural death once tor is bought. export async function main(ns) { const torCost = 200000; var hasTorRouter = false; while (true) { if (hasTorRouter) { break; } if (hasTor(ns)) { hasTorRouter = true; } else { if (torCost <= getPlayerMoney(ns)) { ns.purchaseTor(); } } await ns.sleep(200); } } function getPlayerMoney(ns) { return ns.getServerMoneyAvailable("home"); } function hasTor(ns) { var homeNodes = ns.scan("home"); return homeNodes.includes("darkweb"); }
/* eslint-disable global-require */ /* eslint-disable promise/catch-or-return */ // import * as pdfjs from 'pdfjs-dist'; import { isWebApp } from './env'; export function findFileById(files, id) { for (let i = 0; i < files.length; i += 1) { // eslint-disable-next-line no-underscore-dangle if (files[i]._id === id) { return files[i]; } } return null; } export function getFileId(file) { // eslint-disable-next-line no-underscore-dangle return file._id; } export function replaceFileById(files, id, newFile) { return files.map((file) => { if (getFileId(file) === id) { return newFile; } return file; }); } export function getTodoId(todo) { return todo.id; } export function findTodoById(todos, id) { for (let i = 0; i < todos.length; i += 1) { // eslint-disable-next-line no-underscore-dangle if (todos[i]._id === id) { return todos[i]; } } return null; } export function replaceTodoById(todos, id, newTodo) { return todos.map((todo) => { if (getTodoId(todo) === id) { return newTodo; } return todo; }); } export const newNoteId = 'new'; export function isNewNote(id) { return id === newNoteId; } export function getNoteId(note) { // eslint-disable-next-line no-underscore-dangle if (note._id) { // eslint-disable-next-line no-underscore-dangle return note._id; } return note.id; } export function findNoteById(notes, id) { return notes[id]; } export function replaceNoteById(notes, id, newNote) { return { ...notes, [id]: newNote, }; } export function scaleRect(rect, decimalScale0) { //const decimalScale = decimalScale0 * 2.0; const decimalScale = decimalScale0; return { top: rect.top * decimalScale, left: rect.left * decimalScale, width: rect.width * decimalScale, height: rect.height * decimalScale, }; } export function getElectron() { /* WEB-INT */ if (isWebApp()) { return null; } // this is so that it works for next.js return eval("require('electron')"); } export function getFs() { /* WEB-INT */ if (isWebApp()) { return null; } // this is so that it works for next.js return eval("require('fs')"); } export function generateId() { return ( Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15) ); } export function toggleTodoDependency(dataApi, noteId, todoId) { const note = dataApi.GetNoteById(noteId); console.log('todo dependency change: original note is ', note); const newDependency = note.todoDependency ? [...note.todoDependency] : []; const i = newDependency.indexOf(todoId); if (i === -1) { newDependency.push(todoId); } else { newDependency.splice(i, 1); } console.log('new dependency ', newDependency); const newNote = { ...note }; newNote.todoDependency = newDependency; return newNote; } export function compareDate(a, b) { // console.log(`compare ${a} with ${b}`); const da = Date.parse(a); const db = Date.parse(b); const result = db - da; // console.log(`result is ${result}`); return result; } export function getDataApiFromThunk(thunkAPI) { const fileState = thunkAPI.getState().file; const { dataApi } = fileState; return dataApi; }
import './App.scss'; import Navigation from './components/navigation'; import { library } from '@fortawesome/fontawesome-svg-core'; import { faLinkedin } from '@fortawesome/free-brands-svg-icons'; import { faFacebook } from '@fortawesome/free-brands-svg-icons'; import { faTwitter } from '@fortawesome/free-brands-svg-icons'; import { faWhatsapp } from '@fortawesome/free-brands-svg-icons'; import { faShareSquare } from '@fortawesome/free-solid-svg-icons'; import { faCopy } from '@fortawesome/free-regular-svg-icons'; import { BrowserRouter as Router } from "react-router-dom"; library.add(faLinkedin, faFacebook, faTwitter, faWhatsapp, faShareSquare, faCopy); function App() { return ( <Router> <Navigation /> </Router> ); } export default App;
let app = new Vue({ el: '#app', data: { message: 'Hi, Hello Vue World!' } }) let app2 = new Vue({ el: '#app-2', data: { message: '이 페이지는 ' + new Date() + '에 로드 되었습니다.' } }) let app3 = new Vue({ el: '#app-3', data: { seen: true } }) let app4 = new Vue({ el:'#app-4', data: { todos: [ { text: 'JavaScript 배우기' }, { text: 'Vue 배우기' }, { text: '무언가 멋진 것을 만들기' } ] } }) let app5 = new Vue({ el:'#app-5', data: { message: '안녕하세요! Vue.js!' }, methods: { reverseMessage: function () { this.message = this.message.split('').reverse().join('') } } }) new Vue({ methods: { fetchData() { axios.get('www.google.com'); } }, created: function() { this.fetchData(); } }) let app6 = new Vue({ el:'#app-6', data: { show: false } }) Vue.component('app-header', { template: '<h1>Header Component</h1>' }); var appHeader = { template: '<h1>Header Component</h1>' } let app7 = new Vue({ el:'#app-7', components: { 'app-header': appHeader } }) //하위 컴포넌트: childComponent var childComponent = { props: ['propsdata'], template: '<p>{{propsdata}}</p>' } //상위 컴포넌트: root 컴포넌트 let app8 = new Vue({ el:'#app-8', components:{ 'child-component':childComponent }, data:{ message: 'hellooooooooooooooooo vue.js' } }) //하위 컴포넌트: childComponent let childComponent1 = { methods:{ sendEvent: function(){ this.$emit('update'); } } } //상위 컴포넌트: root 컴포넌트 new Vue({ el: '#app-9', components:{ 'child-component': childComponent1 }, methods: { showAlert: function(){ alert('event received'); } } })
const validate = (validation,type, value) => { //debounce ; // let delta = 1000 // let timeoutID = null // clearTimeout(timeoutID) // timeoutID = setTimeout(() => { // return validation[type](value) // },delta) return validation[type](value) } const formValidation = { pwd : (value) => { }, user : (value) => { let reg = /^[a-zA-Z0-9_-]{4,16}$/ return reg.test(value)?'success':'danger' } } export const validateForm = validate.bind(null,formValidation)
/* eslint-disable no-undef */ /* globals Cypress cy */ describe('CI test for blog pages', () => { // refactor with a beforeEach for cy.visit command it('should open the homepage and click on the blog1 link to display the correct url', () => { cy.visit(Cypress.env('HOST')); cy.get('[href="/blog/milestones"] > h2').click({ force: true }); cy.url().should('include', '/blog/'); }); it('should open the homepage and click on the blog1 link to display the correct blog title', () => { cy.visit(Cypress.env('HOST')); cy.get('[href="/blog/milestones"] > h2').click({ force: true }); cy.get('#blog-title').should('have.text', 'milestones'); }); });
/** * Created by samschmid on 23.03.14. */ Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] === obj) { return true; } } return false; } function Database(grunt) { this.grunt = grunt; this.appconfig = grunt.config().appconfig; this.db = this.appconfig.db; } Database.prototype.createSchemes = function(docs) { var appconfig = this.appconfig; var grunt = this.grunt; if(this.db.name === "mongodb") { var lib = []; if(this.db.provider === "mongoose") { grunt.log.write("start writing schemes for database " + this.db.name + " and provider "+this.db.provider + "."); var Provider = require('./providers/mongoose/mongoose-provider.js'); var provider = new Provider(grunt); for(var i=0;i<docs.docs.length;i++) { var doc = docs.docs[i]; if(doc.json.title !== 'api') { //TODO create Scheme for Doc var scheme = provider.createSchemeAndGetLibFile(doc); lib.push(scheme); } } } else { grunt.log.write("cannot create schemes for database " + this.db.name + ", because there we can't use the provider "+this.db.provider+" for it."); } var template = this.grunt.file.read('./grunt/database/providers/mongoose/lib.template'); var libfiles = new Array(); libfiles[0] = undefined; lib.forEach(function(scheme) { if(libfiles[scheme.version]===undefined) { libfiles[scheme.version] = ""; } libfiles[scheme.version] += template.replace("{{{SCHEME}}}", scheme.scheme).replace("{{{PATH}}}", scheme.path); }) libfiles.forEach(function(libfile,index) { if(libfile!==undefined) { grunt.log.debug("libs: " +index + " " +libfile); grunt.file.write("./database/schemes/v"+index+"/schemes.js", libfile); } }) // } else { grunt.log.write("cannot create schemes for database " + this.db.name + ", because there is no provider for it."); } } module.exports = Database;
import React from 'react'; import { Table, Popconfirm, Modal, Form, Input, InputNumber, Select, Button } from 'antd'; import { connect } from 'react-redux'; import dayjs from 'dayjs'; import BlankContent from 'src/layouts/BlankContent'; const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 12 }, }; class CategoryManage extends React.Component { state = { visible: false, current: null, }; componentDidMount() { const { dispatch } = this.props; dispatch({ type: 'category/getList' }); } render() { const { categoryState, form: { getFieldDecorator }, } = this.props; const { visible } = this.state; const { current } = categoryState; return ( <BlankContent> <div> <Button type="primary" onClick={this.handleToAdd}> 添加目录 </Button> </div> <Table rowKey="id" columns={this.getColumns()} pagination={categoryState.pagination} dataSource={categoryState.list} /> <Modal visible={visible} title={current ? '更新目录' : '增加目录'} onCancel={this.handleCancel} onOk={this.handleConfirm} > <Form layout="vertical"> <Form.Item label="名称" {...formItemLayout}> {getFieldDecorator('categoryName', { initialValue: categoryState.current?.categoryName, })(<Input />)} </Form.Item> <Form.Item label="地址" {...formItemLayout}> {getFieldDecorator('url', { initialValue: categoryState.current?.url })(<Input />)} </Form.Item> <Form.Item label="父级目录" {...formItemLayout}> {getFieldDecorator('parentId', { initialValue: categoryState.current?.parentId })( <Select> {categoryState.list.map((c) => ( <Select.Option key={c.id} value={c.id}> {c.categoryName} </Select.Option> ))} </Select> )} </Form.Item> <Form.Item label="优先级" {...formItemLayout}> {getFieldDecorator('priority', { initialValue: categoryState.current?.priority, })(<InputNumber precision={0} />)} </Form.Item> </Form> </Modal> </BlankContent> ); } getColumns = () => { return [ { title: '父节点ID', dataIndex: 'parentId', render: (text, record) => { return text ? record.parent.categoryName : '-'; }, }, { title: '菜单名称', dataIndex: 'categoryName' }, { title: '地址', dataIndex: 'url' }, { title: '优先级', dataIndex: 'priority' }, { title: '更新时间', dataIndex: 'updateTime', render: (text) => <span>{dayjs(text).format('YYYY-MM-DD hh:mm:ss')}</span>, }, { title: '操作', render: (text, record) => ( <div className="anvil-btn"> <a onClick={this.handleToEdit(record)}>修改</a> <Popconfirm title="是否继续?" cancelText="取消" okText="确定" onConfirm={this.handleConfirmDelete(record)} > <a>删除</a> </Popconfirm> </div> ), }, ]; }; handleToAdd = () => { this.setState({ visible: true }); }; handleConfirm = () => { const { form: { validateFields }, dispatch, categoryState, } = this.props; validateFields((err, values) => { if (!err) { if (categoryState.current?.id) values.id = categoryState.current?.id; dispatch({ type: 'category/updateCategory', payload: { category: values, current: null } }); this.setState({ visible: false }); } }); }; handleCancel = () => { this.setState((prevState) => ({ visible: !prevState.visible })); }; handleToEdit = (record) => { return () => { const { dispatch } = this.props; dispatch({ type: 'category/setState', payload: { current: record } }); this.setState({ visible: true }); }; }; handleConfirmDelete = (record) => { return async () => { const { dispatch } = this.props; await dispatch({ type: 'category/deleteCategory', payload: record }); }; }; } export default connect(({ categoryState }) => ({ categoryState }))( Form.create({ mapPropsToFields: (props) => props.current, })(CategoryManage) );
import React, { Component } from "react"; import { Link } from "react-router"; import Sound from "react-sound"; export default class Landing extends Component { constructor(props){ super(props); this.state = { logoHeight: 0, logoWidth: 0, fontSize: 32, x: 650, y: 250, opacity: 0, playSound: false } this.tick = this.tick.bind(this); } componentDidMount(){ this.tick() this.setState({ playSound: true }) } componentWillUnmount(){ this.setState({ playSound: false }) } tick(){ if ( this.state.logoWidth < 400){ this.setState({ logoWidth: this.state.logoWidth + 1, logoHeight: this.state.logoHeight + 1, x: this.state.x - .5, y: this.state.y - .5 }); }else{ this.setState({ opacity: this.state.opacity + .01 }); if (this.state.opacity == 1){ window.cancelAnimationFrame(this.tick) } } window.requestAnimationFrame(this.tick); } render(){ const style={ height: this.state.logoHeight, width: this.state.logoWidth, position: "absolute", left: this.state.x, top: this.state.y } const playLinkStyle = { color: "black", position: "absolute", fontSize: this.state.fontSize, left: 515, top: 500, width: "110px", height: "50px", backgroundColor: "yellow", textAlign: "center", textDecoration: "none", borderRadius: "10px", border: "5px solid white", opacity: this.state.opacity } const controlsLinkStyle = { color: "black", position: "absolute", fontSize: this.state.fontSize, left: 675, top: 500, width: "110px", height: "50px", backgroundColor: "yellow", textAlign: "center", textDecoration: "none", borderRadius: "10px", border: "5px solid white", opacity: this.state.opacity } const contStyle = { position: "relative", width: "1200px", height: "500px" } return ( <div style={contStyle}> {this.state.playSound ? <Sound url="../public/assets/sounds/intro.mp3" playStatus={Sound.status.PLAYING}/> : null} <svg style={style} id="SVGRoot" version="1.1" viewBox="0 0 30 30"> <defs id="defs815"/> <g id="layer1"> <path id="path1384" style={{"fill":"#ffff00","fillOpacity":"1","stroke":"#ffffff","strokeWidth":"1px","strokeLinecap":"butt","strokeLinejoin":"miter","strokeOpacity":"1"}} d="M 0.67545402,13.249152 V 0.90488052 H 18.61289 V 4.3497935 H 7.5744677 V 7.866476 h 5.2892433 v 3.014298 H 7.9194183 V 22.435587 H 0.90542108 Z"/> <path id="path1384-6" style={{"fill":"#ffff00","fillOpacity":"1","stroke":"#ffffff","strokeWidth":"1px","strokeLinecap":"butt","strokeLinejoin":"miter","strokeOpacity":"1"}} d="M 28.929161,10.112166 V 22.363818 H 10.991727 v -3.419066 h 11.038421 v -3.490295 h -5.289244 v -2.991683 h 4.944294 V 0.99465742 h 7.013997 z"/> <text id="text1403" style={{"fontStyle":"normal","fontWeight":"normal","fontSize":"6.31260252px","lineHeight":"1.25","fontFamily":"sans-serif","letterSpacing":"0px","wordSpacing":"0px","fill":"#ffffff","fillOpacity":"1","stroke":"#ffff00","strokeWidth":"0.24566929","strokeMiterlimit":"4","strokeDasharray":"none","strokeOpacity":"1"}} transform="scale(0.89338853,1.1193338)" x="-0.024256159" y="25.705894" xmlSpace="preserve"> <tspan id="tspan1401" style={{"fontSize":"5.1px","fill":"#ffffff","fillOpacity":"1","stroke":"#ffff00","strokeWidth":"0.24566929","strokeMiterlimit":"4","strokeDasharray":"none","strokeOpacity":"1"}} x="-0.024256159" y="25.705894">Falcon Fighter</tspan> </text> </g> </svg> <Link to="/Game" style={playLinkStyle}>Play</Link> <Link to="/Controls" style={controlsLinkStyle}>Controls</Link> </div> ); } }
const path = require('path'); const webpack = require('webpack'); const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); const CleanPlugin = require('clean-webpack-plugin'); const CompressionPlugin = require('compression-webpack-plugin'); const HtmlPlugin = require('html-webpack-plugin'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const { name: NAME, version: VERSION } = require('./package.json'); const environment = process.env.NODE_ENV || 'development'; const getDevTools = () => ( environment === 'development' ? 'cheap-module-eval-source-map' : 'source-map' ); const getPlugins = () => { const plugins = [ new CleanPlugin([ './dist' ], { root: path.resolve('./'), verbose: true, }), new HtmlPlugin({ filename: environment === 'development' ? './index.html' : `${NAME}-${VERSION}.html`, template: path.resolve('./index.html'), title: NAME, }), new BundleAnalyzerPlugin({ analyzerMode: 'static', defaultSizes: 'gzip', openAnalyzer: process.env.NODE_ENV === 'production', }), new webpack.EnvironmentPlugin({ NODE_ENV: 'development', }), new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // all options are optional // chunkFilename: process.env.NODE_ENV === 'production' ? '[id].[hash].css' : '[id].css', // filename: process.env.NODE_ENV === 'production' ? '[name].[hash].css' : '[name].css', chunkFilename: `${NAME}-${VERSION}.css`, filename: `${NAME}-${VERSION}.css`, ignoreOrder: false, }), ]; if (process.env.NODE_ENV === 'production') { plugins.push( new CompressionPlugin(), new UglifyJsPlugin({ parallel: true, sourceMap: true, uglifyOptions: { compress: { inline: false } }, }), ); } return plugins; }; module.exports = { devtool: getDevTools(), entry: [ 'babel-polyfill', './src/index.js', './style/styles.css', ], module: { rules: [ { exclude: /node_modules/, test: /\.(js|jsx)$/i, use: [ { loader: 'babel-loader', options: { cacheDirectory: true, }, } ], }, { test: /\.(sa|sc|c)ss$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { hmr: process.env.NODE_ENV === 'development', // if hmr does not work, this is a forceful method. reloadAll: true, }, }, 'css-loader', ], }, { loader: 'url-loader?limit=100000', test: /\.(png|woff|woff2|eot|ttf|svg)$/, }, ], }, output: { filename: `${NAME}-${VERSION}.js`, path: path.resolve(__dirname, 'dist'), publicPath: '', }, plugins: getPlugins(), profile: true, };
const submitBtn = document.querySelector('.container.left .search-action'); const form = document.querySelector('.container.left form'); const emailInput = document.querySelector('.container.left #email'); const roleInput = document.querySelector('.container.left select[name=role]'); MicroModal.init({ awaitCloseAnimation: false, // set to false, to remove close animation }); document.querySelector('.container.right form').addEventListener('submit', function (e) { e.preventDefault(); document.querySelector('.modal__content ul').innerHTML = ` <li>Owner: <strong style="margin-left: 10px;">${document.querySelector('#owner').value}</strong></li> <li> Pet Name: <strong style="margin-left: 10px;">${document.querySelector('#petName').value}</strong> </li> <li> Breed: <strong style="margin-left: 10px;">${document.querySelector('#breed').value}</strong> </li> <li>Type: <strong style="margin-left: 10px;">${document.querySelector('#type')[document.querySelector('#type').selectedIndex].innerText}</strong>.</li> <li> Size: <strong style="margin-left: 10px;">${document.querySelector('#size')[document.querySelector('#size').selectedIndex].innerText}</strong>. </li> <li> Avatar: <img style="width: 100%;margin-top: 10px;" src="${document.querySelector('.image--preview').getAttribute('src')}"/> </li> `; MicroModal.show('modal-1'); document.querySelector('.modal__footer button.ui.primary').addEventListener('click', () => { this.submit(); }) }) if (submitBtn) { submitBtn.addEventListener('click', function () { let role = roleInput.options[roleInput.selectedIndex] ? roleInput.options[roleInput.selectedIndex].value : ""; fetch(`http://localhost:3000/PRJ321_REST/users/search`, { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: "include", body: JSON.stringify({ "owner": emailInput.value, "role": role }), headers: { "Content-Type": 'application/json' // 'Content-Type': 'application/x-www-form-urlencoded', } }) .then(response => { return response.json(); }) .then(data => { console.log(data); if (data.length > 0) { let temp = `<select id="users" name="users">`; data.map(user => temp += `<option value=${user.email}>${user.email}</option>`); temp += "</select>"; iziToast.question({ timeout: 20000, close: false, drag: false, overlay: true, displayMode: 'once', id: 'question', zindex: 999, title: 'Hey', message: 'Please Choose One User: ', position: 'center', inputs: [ [ temp, 'change', function (instance, toast, select, e) { } ] ], buttons: [ ['<button><b>Confirm</b></button>', function (instance, toast, button, e, inputs) { document.querySelector('.container.right #owner').value = inputs[0].options[inputs[0].selectedIndex].value; instance.hide({transitionOut: 'fadeOut'}, toast, 'button'); }, false], // true to focus ['<button>NO</button>', function (instance, toast, button, e) { instance.hide({transitionOut: 'fadeOut'}, toast, 'button'); }] ] }); } else { setTimeout(() => { iziToast.error({ title: 'error', message: 'Can\'t Find Any User(s) !', }); }, 50); } }) .catch(err => { setTimeout(() => { iziToast.success({ title: 'error', message: 'There is some error when searching user !', }); }, 50); }); }) }
export { removeRequests, removedToFalse, addRequest, addBudget, fetchRequests, fetchApproveRequests, fetchRejectRequests, removedToFalseRequest, fetchApproveBudget, fetchRejectBudget, fetchDriver, assingDriver, updateItems, onDismissAlert } from './requestActions'; export { logout, login, loginCheckState } from './loginActions'; export { fetchUsers, addUser, deleteUser, updateAssingApprover } from './userActions' export { fetchCompanies, addCompany, deleteCompany, fetchBuildings, addBuilding, deleteBuilding } from './buildingActions'
var j = replace; var i = j; console.log(i);
import React, { Component } from "react"; import coins from 'assets/coins.png'; import "./index.css"; export default class CoinFlip extends Component { constructor(props){ super(props) } render() { return ( <img src={coins} styleName={'coinflip-icon'}/> ); } }
const SERVER_URL= "http://unitechno.xyz:3000" module.exports= { SERVER_URL };
module.exports = app => { const { STRING, INTEGER, DATE } = app.Sequelize; const Invitation = app.model.define('invitations', { id: { type: INTEGER, primaryKey: true, autoIncrement: true }, code: STRING(10), user_id:STRING(100), use_user_id:STRING(100) },{ timestamps: false, //去除createAt updateAt freezeTableName: true, //使用自定义表名 }); Invitation.exist = async code=>{ return await Invitation.findOne({ where:{ code } }) } return Invitation; };
import styled from 'styled-components'; const TitleEl = styled.h2` font-size: 2em; `; export { TitleEl };
const getTodoDetails = function () { return fetch('api/getTodoDetails') .then((res) => res.json()) .then((details) => JSON.parse(details)); }; const sendPostReq = function (url, body) { return fetch(url, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body), }); }; const addTask = (task) => sendPostReq('api/addTask', {task}).then(getTodoDetails); const removeTask = (id) => sendPostReq('api/removeTask', {id}).then(getTodoDetails); const updateStatus = (id) => sendPostReq('api/updateStatus', {id}).then(getTodoDetails); const updateTitle = (title) => sendPostReq('api/updateTitle', {title}).then(getTodoDetails); const resetTodoDetails = () => sendPostReq('api/resetTodoDetails').then(getTodoDetails); module.exports = { addTask, removeTask, updateTitle, updateStatus, resetTodoDetails, getTodoDetails, };
var wins = 0; var loses = 0; var guessesLeft = 10; var guessesSoFar = []; var computerGuess = randomChar();; function randomChar() { var chosen = ""; var letter = "abcdefghijklmnopqrstuvwxyz"; for (var i = 0; i < 5; i++) { chosen += letter.charAt(Math.floor(Math.random() * letter.length)); return chosen; } } console.log(computerGuess); document.onkeyup = function(event) { var userGuess = event.key; guessesSoFar.push(userGuess); console.log(guessesSoFar); match(userGuess); } function match(userGuess) { while (guessesLeft > 0) { if (userGuess === computerGuess) { wins++; } else { guessesLeft--; } } loses++; } document.getElementById("lettersGuessed").innerHTML = "<p>" + guessesSoFar + "<p>"; document.getElementById("guessesLeft").innerHTML = "<p>" + guessesLeft + "<p>"; document.getElementById("wins").innerHTML = "<p>" + wins + "<p>"; document.getElementById("loses").innerHTML = "<p>" + loses + "<p>";
export default class Response { status (status) { this.status = status return this } json (data) { return data } }
const express = require('express'); const router = express.Router(); const ProductController = require("../controllers/ProductController"); router.get("/", (req,res) => ProductController.index(req,res)); router.get("/add", (req,res) => ProductController.add(req,res)); router.get("/edit", (req,res) => ProductController.edit(req,res)); router.post("/add", (req,res) => ProductController.create(req,res)); module.exports = router;
'use strict'; var lineCount = 7; // Write a program that draws a // diamond like this: // // // * // *** // ***** // ******* // ***** // *** // * // // The diamond should have as many lines as lineCount is for (var i = 1; i <= lineCount; i++) { var j = lineCount-i; if (i >= lineCount/2+1) { console.log(' '.repeat(i-1) + '*'.repeat(2*j+1) + ' '.repeat(i-1)); } else { console.log(' '.repeat(j) + '*'.repeat(2*i-1) + ' '.repeat(j)); } }
const express = require('express'); const app = express(); const morgan = require('morgan'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const expressValidator = require('express-validator'); require('dotenv').config(); // import mongoose const mongoose = require('mongoose'); // import router const authRouter = require('./routes/auth'); const userRouter = require('./routes/user'); //db connection mongoose .connect(process.env.MONGO_URI, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true }) .then(() => console.log('DB Connected')); mongoose.connection.on('error', err => { console.log(`DB connection error: ${err.message}`); }); // route middleware app.use(morgan('dev')); app.use(bodyParser.json()); app.use(cookieParser()); app.use(expressValidator()); app.use('/api', authRouter); app.use('/api', userRouter); const PORT = process.env.PORT || 8000; app.listen(PORT, () => console.log(`app listen to ${PORT} `));
'use strict'; var parseUrl = require('url').parse; var merge = require('lodash.merge'); module.exports = function assertUrl(url) { if (typeof url === 'string') { url = parseUrl(url); ['protocol', 'hostname'].forEach(function(param) { if (!url[param]) { throw new Error('Invalid connection string given. No ' + param + ' given.'); } }); } if (!url.vhost) { if (url.pathname && url.pathname.length > 1) { url.vhost = url.pathname.substr(1); } else { url.vhost = '/'; } } if (typeof url !== 'object') { throw new TypeError('`options.url` must be a valid AMQP connection URL or an object of connection details'); } if (url.host && !url.hostname) { url = merge({}, url); url.hostname = url.host; delete url.host; } var uri = merge({ hostname: 'localhost' }, url, { port: parseInt(url.port || (url.protocol === 'amqps:' ? 5671 : 5672), 10) }); if (uri.auth) { var auth = uri.auth.split(':', 2); uri.username = auth[0]; uri.password = auth[1]; } uri.protocol = uri.protocol.replace(/:$/, ''); return uri; };
const mongoose = require('mongoose'); const createSchema = mongoose.Schema({ image: { type: String, }, // file:{ data: Buffer, contentType: String }, link: { type: String, required: false, }, application_date: { type: String, required: false, }, batch_id: { type: String, required: false, }, instruction: { type: String, required: false }, created_at: { type: Date, default: Date.now } }); const create = module.exports = mongoose.model('create', createSchema);
import React from "react"; import TaskCard from './TaskCard'; import {Droppable} from 'react-beautiful-dnd'; function List(props) { let tasks=props.tasks; let renderTasks = (tasks) => { let index=-1; return tasks.map((e) => { index=index+1; return ( <TaskCard index={index} id={e.id} taskName={e.taskname} time={e.time} taskType={e.tasktype} taskDescription={e.taskdescription} /> ); }); }; return( <Droppable droppableId={props.columnId}> {provided=>( <div className="list__wrapper" ref={provided.innerRef} {...provided.droppableProps} > {renderTasks(tasks)} {provided.placeholder} </div> )} </Droppable> ); }; export default List;
const https = require('https'); const agent = new https.Agent({ rejectUnauthorized: false }); module.exports = class RestfulAPI { constructor(clientID) { if (!clientID) throw new Error( 'Client ID Required for this Class to Properly Function. Please Visit: https://trovo.live/policy/apis-developer-doc.html', ); this.clientID = clientID; } post(path, headers, data) { return new Promise((resolve, reject) => { headers['Content-Type'] = 'application/json'; const options = { method: 'POST', hostname: 'open-api.trovo.live', port: 443, path: `/openplatform/${path}`, // agent: agent, headers, }; const req = https.request( options, (res) => { const chunks = []; res.on('data', (resData) => chunks.push(resData)); res.on('end', () => { let body = Buffer.concat(chunks); switch (res.headers['content-type']) { case 'application/json': body = JSON.parse(body); break; default: break; } resolve(body); }); }, ); req.on('error', reject); req.write(JSON.stringify(data)); req.end(); }); } get(path, headers) { return new Promise((resolve, reject) => { headers['Content-Type'] = 'application/json'; const options = { method: 'GET', hostname: 'open-api.trovo.live', port: 443, path: `/openplatform/${path}`, // agent: agent, headers, }; const req = https.request( options, (res) => { const chunks = []; res.on('data', (data) => chunks.push(data)); res.on('end', () => { let body = Buffer.concat(chunks); switch (res.headers['content-type']) { case 'application/json': body = JSON.parse(body); break; default: break; } resolve(body); }); }, ); req.on('error', reject); req.end(); }); } ValidateAccessToken(oauth) { return new Promise((resolve, reject) => { const headers = { 'Client-ID': this.clientID, Authorization: `OAuth ${oauth}`, }; this.get('validate', headers) .then((data) => { if (data.error) { reject(data); } else { resolve(data); } }) .catch((err) => { reject(err); }); }); } RevokeAccessToken(oauth, token) { return new Promise((resolve, reject) => { const headers = { 'Client-ID': this.clientID, Authorization: `OAuth ${oauth}`, }; const input = { access_token: token, }; this.post('revoke', headers, input) .then((data) => { if (data.error) { reject(data); } else { resolve(data); } }) .catch((err) => { reject(err); }); }); } GetGameCategory() { return new Promise((resolve, reject) => { const headers = { 'Client-ID': this.clientID, }; this.get('categorys/top', headers) .then((data) => { if (data.error) { reject(data); } else { resolve(data); } }) .catch((err) => { reject(err); }); }); } GetUsers(userList) { return new Promise((resolve, reject) => { const headers = { 'Client-ID': this.clientID, }; const input = { user: userList }; this.post('getusers', headers, input) .then((data) => { if (data.error) { reject(data); } else { resolve(data); } }) .catch((err) => { reject(err); }); }); } GetChannelInfoByID(channelID) { return new Promise((resolve, reject) => { const headers = { 'Client-ID': this.clientID, }; const input = { channel_id: channelID, }; this.post('channels/id', headers, input) .then((data) => { if (data.error) { reject(data); } else { resolve(data); } }) .catch((err) => { reject(err); }); }); } ReadChannelInfo(oauth) { return new Promise((resolve, reject) => { const headers = { 'Client-ID': this.clientID, Authorization: `OAuth ${oauth}`, }; this.get('channel', headers) .then((data) => { if (data.error) { reject(data); } else { resolve(data); } }) .catch((err) => { reject(err); }); }); } EditChannelInformation(channelID, title, languageCode, audiType, oauth) { return new Promise((resolve, reject) => { const headers = { 'Client-ID': this.clientID, Authorization: `OAuth ${oauth}`, }; const input = { channel_id: channelID, live_title: title, language_code: languageCode, audi_type: audiType, }; this.post('channels/update', headers, input) .then((data) => { if (data.error) { reject(data); } else { resolve(data); } }) .catch((err) => { reject(err); }); }); } GetUserInfo(oauth) { return new Promise((resolve, reject) => { const headers = { 'Client-ID': this.clientID, Authorization: `OAuth ${oauth}`, }; this.get('getuserinfo', headers) .then((data) => { if (data.error) { reject(data); } else { resolve(data); } }) .catch((err) => { reject(err); }); }); } GetTopChannels(limit, categoryID, token, cursor) { if ((limit && limit > 100) || limit < 0) throw new Error('Maximum number of objects to return. Maximum: 100. Default: 20.'); return new Promise((resolve, reject) => { const headers = { 'Client-ID': this.clientID, }; const input = { limit: limit || 20, after: true, token: '', cursor: 0, }; if (categoryID) input.category_id = categoryID.toString(); if (token) input.token = token; if (cursor) input.cursor = cursor; this.post('gettopchannels', headers, input) .then((data) => { if (data.error) { reject(data); } else { resolve(data); } }) .catch((err) => { reject(err); }); }); } };
//REQUIRED FUNCTIONS IMPORT import React from 'react'; //COMPONENTS IMPORT import NavbarRouter from './NavbarRouter'; //STYLES IMPORT import './styles/App.scss'; import './styles/NavbarRouter.scss'; function App() { return ( <div className="App"> <NavbarRouter /> </div> ); } export default App;
const Transaction = require('../SharedCode/models/transaction'); const Blocks = require('../SharedCode/blockchain/blocks'); const transactionService = require('../SharedCode/service/transaction.service'); const queueService = require('../SharedCode/service/queue.service'); const { StatusTypes, TransactionStatus } = require('../SharedCode/misc/enum'); module.exports = async function (context, myTimer) { var timeStamp = new Date().toISOString(); if (myTimer.IsPastDue) { context.log('JavaScript is running late!'); } context.log('JavaScript timer trigger function ran!', timeStamp); const transactions = await Transaction.findAll({ where: { status: TransactionStatus.Submitted } }); if (transactions) { for (const transaction of transactions) { const { id, queueId, transactionHash } = transaction; try { const receipt = await Blocks().getTransactionReceipt(transactionHash); if(receipt) { context.log('Transaction:', queueId, JSON.stringify(receipt)); if (receipt.status == true) { transactionService().updateStatus(id, TransactionStatus.Sucess) queueService().updateStatus(queueId, StatusTypes.Completed); } else { transactionService().updateStatus(id, TransactionStatus.Fail) queueService().updateStatus(queueId, StatusTypes.Error); } } } catch (error) { context.log.error('Transaction:', id, error); queueService().updateStatus(id, StatusTypes.Error); transactionService().updateStatus(id, TransactionStatus.Error); } } } };
export const ENV = { BASE_URL: 'http://localhost:3500/v1/', AUTH_KEY: 'id_token', APP_KEY: '1234567WE1WEW', USER_DATA: 'user_data', };
import React from 'react'; import womanImg from '../images/svg/pick-woman.svg'; import manImg from '../images/svg/pick-man.svg'; import babyImg from '../images/svg/pick-baby.svg'; import SectionTitle1 from './SectionTitle1'; import Tiles from './Tiles'; const OfferSection = ({ offerList }) => { const images = [womanImg, manImg, babyImg] return ( <section className="offer"> <div className="tiles-h1"> <SectionTitle1 title={offerList.title} /> </div> <Tiles tiles={offerList.tiles} images={images} /> </section> ); } export default OfferSection;
let t = 'When' let m = 'Mickey Mouse gets punished by Mini Mouse and is vigalent just in case' let sound; function setup() { createCanvas(400, 400); sound = loadSound('assets/track 10.mp3'); } function mousePressed() { if (sound.isPlaying()) { sound.stop(); background(255, 0, 0); } else { sound.play(); background(0, 100, 54); } } function draw() { motion = constrain(map(mouseX, 0, width, -2.6, 2.6), -2.6, 2.6); //BOTH EARS\\ push(); fill(0); ellipse(160, 80, 70, 70); ellipse(240, 80, 70, 70); pop(); push(); fill(255); textSize(25); text(t, 165, 15, 155, 155); pop(); //HEAD\\ push(); fill(240, 170, 50); ellipse(200, 150, 120, 140); pop(); //BOTH EYES\\ push(); translate(motion, 0); fill(255); ellipse(180, 130, 30, 50); ellipse(220, 130, 30, 50); pop(); push(); fill(0); ellipse(180, 135, 20, 40); ellipse(220, 135, 20, 40); noFill(); arc(200, 187, 100, 70, 5*PI/ 4, 7*PI/ 4); fill(0); ellipse(200, 169, 35, 26); pop(); push(); fill(200, 0 , 40); arc(200, 196, 70, 25, 0, PI); arc(200, 230, 140, 80, 5*PI/ 4, 7*PI/ 4); pop(); push(); fill(255); textSize(12); textStyle(BOLD); text(m, 75, 250 , 260, 200); pop(); }
const nodemailer = require('nodemailer') const crypto = require('crypto') require('dotenv').config() const Email = process.env.Email const Password = process.env.Password const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: Email, pass: Password, }, }) const ProgContest = require('../models/ProgContest.model') const getPC = (req, res) => { res.render('prog-contest/register.ejs', { error: req.flash('error') }) } const postPC = (req, res) => { const { teamName, institute, coachName, coachContact, coachEmail, coachTshirt, TLName, TLContact, TLEmail, TLtshirt, TM1Name, TM1Contact, TM1Email, TM1tshirt, TM2Name, TM2Contact, TM2Email, TM2tshirt, } = req.body //console.log(teamName) const total = 800 const paid = 0 const selected = false const hashValue = crypto.randomBytes(20).toString('hex') const confirmationCode = Math.floor(1000 + Math.random() * 9000) const verified = false let error = '' ProgContest.findOne({ teamName: teamName, institute: institute }).then( (team) => { if (team) { error = 'Team with same name and institution exists' req.flash('error', error) res.redirect('/progContest/register') } else { const participant = new ProgContest({ teamName, institute, coachName, coachContact, coachEmail, coachTshirt, TLName, TLContact, TLEmail, TLtshirt, TM1Name, TM1Contact, TM1Email, TM1tshirt, TM2Name, TM2Contact, TM2Email, TM2tshirt, total, paid, selected, hashValue: hashValue, confirmationCode: confirmationCode, verified: verified, }) participant .save() .then(() => { error = 'Team for Programming Contest has been registered successfully!!' const emails = [ { email: coachEmail, name: coachName }, { email: TLEmail, name: TLName }, { email: TM1Email, name: TM1Name }, { email: TM2Email, name: TM2Name }, ] emails.forEach((member) => { const options = { to: member.email, from: Email, subject: 'Registration is Successful!', text: `Hello ${member.name}, You have successfully registered to programming contest as Team ${teamName} and your confirmation code is ${confirmationCode}`, } transporter.sendMail(options, function (err, info) { if (err) { console.log(err) return } console.log('Sent: ' + info.response) }) }) console.log('save ', error) req.flash('error', error) res.redirect('/progContest/register') }) .catch((err) => { console.log(err) error = 'Unexpected error' console.log('error ', error) req.flash('error', error) res.redirect('/progContest/register') }) } } ) } const getPCList = (req, res) => { let all_participant = [] let error = '' ProgContest.find() .then((data) => { all_participant = data res.render('prog-contest/list.ejs', { error: req.flash('error'), participants: all_participant, }) }) .catch(() => { error = 'Failed to fetch participants' res.render('prog-contest/list.ejs', { error: req.flash('error', error), participants: all_participant, }) }) // res.render("math-olympiad/list.ejs"); } const paymentDonePC = (req, res) => { const id = req.params.id ProgContest.findOne({ _id: id }) .then((participant) => { participant.paid = participant.total participant .save() .then(() => { let error = 'Payment completed succesfully' req.flash('error', error) res.redirect('/ProgContest/list') }) .catch(() => { let error = 'Data could not be updated' req.flash('error', error) res.redirect('/ProgContest/list') }) }) .catch(() => { let error = 'Data could not be updated' req.flash('error', error) res.redirect('/ProgContest/list') }) } const selectPC = (req, res) => { const id = req.params.id ProgContest.findOne({ _id: id }) .then((participant) => { participant.selected = true participant .save() .then(() => { let error = 'Participant has been selected succesfully' const options = { to: participant.TLEmail, from: Email, subject: 'You have been Selected!', text: `Hello ${participant.TLName}, You have successfully registered to programming contest as Team ${participant.teamName}`, } transporter.sendMail(options, function (err, info) { if (err) { console.log(err) return } console.log('Sent: ' + info.response) }) req.flash('error', error) res.redirect('/ProgContest/list') }) .catch(() => { let error = 'Data could not be updated' req.flash('error', error) res.redirect('/ProgContest/list') }) }) .catch(() => { let error = 'Data could not be updated' req.flash('error', error) res.redirect('/ProgContest/list') }) } const getEditPC = (req, res) => { const id = req.params.id //console.log('wd ', id, ' ') let info = [] ProgContest.findOne({ _id: id }) .then((data) => { info = data res.render('prog-contest/edit-team.ejs', { error: req.flash('error'), participant: info, }) }) .catch((e) => { console.log(e) error = 'Failed to fetch participants' res.render('prog-contest/edit-team.ejs', { error: req.flash('error', error), participant: info, }) }) } const postEditPC = async (req, res) => { const { teamName, institute, coachName, coachContact, coachEmail, coachTshirt, TLName, TLContact, TLEmail, TLtshirt, TM1Name, TM1Contact, TM1Email, TM1tshirt, TM2Name, TM2Contact, TM2Email, TM2tshirt, } = req.body // console.log( // teamName, // institute, // coachName, // coachContact, // coachEmail, // coachTshirt, // TLName, // TLContact, // TLEmail, // TLtshirt, // TM1Name, // TM1Contact, // TM1Email, // TM1tshirt, // TM2Name, // TM2Contact, // TM2Email, // TM2tshirt // ) const data = await ProgContest.findOneAndUpdate( { teamName: teamName, institute: institute }, { coachName, coachContact, coachEmail, coachTshirt, TLName, TLContact, TLEmail, TLtshirt, TM1Name, TM1Contact, TM1Email, TM1tshirt, TM2Name, TM2Contact, TM2Email, TM2tshirt, }, { useFindAndModify: false } ) if (data) { //console.log('findOneAndUpdate prog contest ', data) res.redirect('/progContest/list') } } const deletePC = (req, res) => { const id = req.params.id //console.log('id ', id) let error = '' ProgContest.deleteOne({ _id: req.params.id }) .then(() => { error = '' req.flash('error', error) res.redirect('/progContest/list') }) .catch(() => { error = 'Failed to delete data!' req.flash('error', error) res.redirect('/progContest/list') }) } const getVerifyPC = (req, res) => { const id = req.params.id let info = [] ProgContest.findOne({ _id: id }) .then((data) => { info = data // console.log('info ', info) res.render('prog-contest/verification.ejs', { error: req.flash('error'), participant: info, }) }) .catch((e) => { console.log(e) error = 'Failed to fetch participants' res.render('prog-contest/verification.ejs', { error: req.flash('error', error), participant: info, }) }) } const postVerifyPC = (req, res) => { const id = req.params.id let error = '' //console.log(id) ProgContest.findOne({ _id: id }).then((participant) => { if (participant) { const { verification } = req.body if (participant.confirmationCode == verification) { participant.verified = true participant .save() .then(() => { error = 'Team is verified successfully.' req.flash('error', error) console.log(error) res.redirect('/progContest/list') }) .catch(() => { error = 'Unknown Error occured and participant was not verified.' req.flash('error', error) console.log(error) res.redirect('/progContest/verify/:id') }) } else { error = 'Verification code does not match' req.flash('error', 'Verification code doesnot match') console.log(error) res.redirect('back') } } else { error = 'Unknown Error occured and Data was not Edited.' req.flash('error', error) console.log(error) res.redirect('/progContest/list') } }) } module.exports = { getPC, postPC, getPCList, paymentDonePC, selectPC, getEditPC, postEditPC, deletePC, getVerifyPC, postVerifyPC, }
export { default as BooksList } from './BooksList' export { default as CategoriesList } from './CategoriesList'
var mongoose = require('../mongoose') var Comment = mongoose.model('Comment') var Article = mongoose.model('Article') var moment = require('moment') /** * 发布评论 * @method * @param {[type]} req [description] * @param {[type]} res [description] * @return {[type]} [description] */ exports.postComment = (req, res) => { var content = req.body.content, creat_date = moment().format('YYYY-MM-DD HH:MM:SS'), id = req.body.id, timestamp = moment().format('X'), username = req.body.username || '匿名' if (!content) { res.json({ code: -200, message: '请输入评论内容' }) } var data = { article_id: id, username, email: '', content, reply_id: 0, reply_user: '', creat_date, is_delete: 0, timestamp } Comment.createAsync(data) .then(result => { return Article.updateAsync({ _id: id }, { '$inc':{ 'comment_count': 1 } }).then(() => { res.json({ code: 200, data: { _id: result._id, article_id: id, username, content, creat_date, is_delete: 0 }, message: '发布成功' }) }) }).catch(err => { res.json({ code: -200, message: err.toString() }) }) } /** * 前台浏览时, 读取评论列表 * @method * @param {[type]} req [description] * @param {[type]} res [description] * @return {[type]} [description] */ exports.getComment = (req, res) => { var id = req.query.id, limit = req.query.limit, page = req.query.page page = parseInt(page, 10) limit = parseInt(limit, 10) if (!page) page = 1 if (!limit) limit = 10 var data = { is_delete: 0, article_id: id }, skip = (page - 1) * limit Promise.all([ Comment.find(data).sort('-_id').skip(skip).limit(limit).exec(), Comment.countAsync(data) ]).then(result => { var total = result[1] var totalPage = Math.ceil(total / limit) var json = { code: 200, data: { list: result[0], total, hasNext: totalPage > page ? 1 : 0 } } res.json(json) }).catch(err => { res.json({ code: -200, message: err.toString() }) }) }
// @flow import * as React from 'react'; import { Translation } from '@kiwicom/mobile-localization'; import IconWithText from './IconWithText'; import { type InsuranceType } from './variantButtons/__generated__/VariantButtons.graphql'; type Props = {| +selectedVariant: InsuranceType, |}; const InsuranceSummary = (props: Props) => { switch (props.selectedVariant) { case 'TRAVEL_PLUS': return <TravelPlusSummary />; case 'TRAVEL_BASIC': return <TravelBasicSummary />; default: return null; } }; const TravelBasicSummary = () => ( <React.Fragment> <IconWithText textIconCode="V" text={ <Translation id="mmb.trip_services.insurance.selection.insurance_summary.medical" /> } /> <IconWithText textIconCode="V" text={ <Translation id="mmb.trip_services.insurance.selection.insurance_summary.cancellation" /> } /> <IconWithText textIconCode="V" text={ <Translation id="mmb.trip_services.insurance.selection.insurance_summary.assistance" /> } /> </React.Fragment> ); const TravelPlusSummary = () => ( <React.Fragment> <IconWithText textIconCode="V" text={ <Translation id="mmb.trip_services.insurance.selection.insurance_summary.medical" /> } /> <IconWithText textIconCode="V" text={ <Translation id="mmb.trip_services.insurance.selection.insurance_summary.cancellation" /> } /> <IconWithText textIconCode="V" text={ <Translation id="mmb.trip_services.insurance.selection.insurance_summary.assistance" /> } /> <IconWithText textIconCode="V" text={ <Translation id="mmb.trip_services.insurance.selection.insurance_summary.bags" /> } /> <IconWithText textIconCode="V" text={ <Translation id="mmb.trip_services.insurance.selection.insurance_summary.travel" /> } /> <IconWithText textIconCode="V" text={ <Translation id="mmb.trip_services.insurance.selection.insurance_summary.liability" /> } /> </React.Fragment> ); export default InsuranceSummary;
import Ember from 'ember'; export default Ember.Controller.extend({ position: 'current', });
var mongo = require('mongodb'); var Server = mongo.Server, Db = mongo.Db, BSON = mongo.BSONPure; var server = new Server('localhost', 27017, {auto_reconnect: true}); db = new Db('viddb', server, {safe: true}); db.open(function(err, db) { if(!err) { console.log("Connected to 'viddb' database"); db.collection('videos', {safe:true}, function(err, collection) { if (err) { console.log("The 'videos' collection doesn't exist. Creating it with sample data..."); populateDB(); } }); } }); exports.findById = function(req, res) { var id = req.params.id; console.log('Retrieving video: ' + id); db.collection('videos', function(err, collection) { collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) { res.send(item); }); }); }; exports.findAll = function(req, res) { db.collection('videos', function(err, collection) { collection.find().sort('name').toArray(function(err, items) { res.send(items); }); }); }; exports.addVideo = function(req, res) { var video = req.body; console.log('Adding video: ' + JSON.stringify(video)); db.collection('videos', function(err, collection) { collection.insert(video, {safe:true}, function(err, result) { if (err) { res.send({'error':'An error has occurred'}); } else { console.log('Success: ' + JSON.stringify(result[0])); res.send(result[0]); } }); }); } exports.updateVideo = function(req, res) { var id = req.params.id; var video = req.body; delete video._id; console.log('Updating video: ' + id); console.log(JSON.stringify(video)); db.collection('videos', function(err, collection) { collection.update({'_id':new BSON.ObjectID(id)}, video, {safe:true}, function(err, result) { if (err) { console.log('Error updating video: ' + err); res.send({'error':'An error has occurred'}); } else { console.log('' + result + ' document(s) updated'); res.send(video); } }); }); } exports.deleteVideo = function(req, res) { var id = req.params.id; console.log('Deleting video: ' + id); db.collection('videos', function(err, collection) { collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) { if (err) { res.send({'error':'An error has occurred - ' + err}); } else { console.log('' + result + ' document(s) deleted'); res.send(req.body); } }); }); } var populateDB = function() { var videos = [ { name: "Camera 1", description: "Camera 1", alphabetLetter: "a", piip: "", cameraip: "10.5.5.9", password: "", isRecording: false, isOn: false, memoryLeft: 0, batteryLeft: 0 }]; db.collection('videos', function(err, collection) { collection.insert(videos, {safe:true}, function(err, result) {}); }); };
// // for pro : built version, use node to start // let config = require('./bin/config.js') // config.FileDir.root = __dirname || '/' // // let server = require('./bin/main.js') // server.start() // for dev : srouce version, use babel-node to start let config = require('./src/config/appconfig.js') config.FileDir.root = __dirname || '/' let server = require('./src/main.js') server.start()
import Api from '@/services/Api' export default { getInstructionGuides(search){ return Api().get('instructionGuides', { params: { search:search } }) }, postInstructionGuides(instructionGuides){ return Api().post('instructionGuides', instructionGuides) }, getInstructionGuideById(instructionGuidesId){ return Api().get(`instructionGuides/${instructionGuidesId}`) }, putInstructionGuideById(instructionGuidesId, instructionGuides){ return Api().put(`instructionGuides/${instructionGuidesId}`, instructionGuides) // eslint-disable-next-line //console.log("Test send to server"); } }