text
stringlengths
7
3.69M
//somehow this was actually working var counter = 0; var counterAc = 0; $(document).ready(function () { var html1 = '<div class="col-lg-4 col-sm-6 portfolio-item"><div class="card h-100"><img id="video_uri" name="'; var html2 = '" info="'; var html3 = '" vn="'; var html4 = '" infoWater="'; var html5 = '" infouid="'; var html6 = '" infomid="'; var html7 = '" piccomp="'; var html8 = '"class="card-img-top" src="'; var html9 = '" onerror="imageComp(this);"/><div class="card-body"><p class="card-text">'; var html10 = "</p></div></div></div>"; var sep = "</br>"; var videoUris = ""; var videoIds = ""; var user_id = $("#info_userId").text(); var iid = Cookies.get("iid"); if (iid != undefined) { $.post("php/user_control.php", { mode: "5", uid: iid }, function (data) { //console.log(data); if (data != "not found") { $("#iid").html( '<a class="nav-link" href="user/panel.php">' + data + "</a>" ); $("#btn_follow").css("display", "block"); $(document).on("click", "#btn_follow", function () { console.log("lmao"); $.post( "php/user_control.php", { mode: "7", uid: iid, userid: user_id }, function (data) { if (data != "") { if (data == "added") { $("#btn_follow").css("display", "none"); alert("Added to your dashboard."); } if (data == "already added") { $("#btn_follow").css("display", "none"); alert("You are already following this user."); } } else { alert("Something went wrong, Try Again..."); } } ); }); } else { $("#iid").html('<a class="nav-link" href="user/login.php">Login</a>'); } }); } else { $("#iid").html('<a class="nav-link" href="user/login.php">Login</a>'); } var max_offset = 0; var max_offset2 = 0; var postCount = $("#info_postCount").text(); var count = 0; var count2 = 0; var has_more = 0; var has_more2 = 0; var user_id = user_id.replace(/ /g, ""); var infoSet = false; var room_id = ""; $("#tab_likes").trigger("click"); $("#tab_videos").trigger("click"); $("#tab_videos").on("click", function () { $("#likes").css("visibility", "hidden"); $("#videos").css("visibility", "visible"); }); $("#tab_likes").on("click", function () { $("#videos").css("visibility", "hidden"); $("#likes").css("visibility", "visible"); }); $(document).on("click", "#btn_goStream", function () { //console.log(room_id); var win = window.open("live/live.php?room_id=" + room_id, "_blank"); win.focus(); }); document.onkeydown = function (evt) { evt = evt || window.event; if (evt.keyCode == 27) { } }; $(document).on("click", "#btn_more", function () { if ((has_more = 1)) { getJsonOC(); } else { alert("Dude, calm down... There is no more videos."); $("#btn_more").css("display", "none"); } }); $(document).on("click", "#btn_saveLinks", function () { var completeUris = videoUris + videoIds; //var dataSend = {videoUrl: videoUris, videoId: videoIds, uid: user_id}; var html = "php/savevuriLogs.php"; /*$.post(html, dataSend, function(data){ console.log(data); var blob = new Blob([completeUris], {type: "text/plain;charset=utf-8"}); saveAs(blob, "uris_" + user_id + ".txt"); });*/ var fd = new FormData(); fd.append("videoUrl", videoUris); fd.append("videoId", videoIds); fd.append("uid", user_id); navigator.sendBeacon(html, fd); var blob = new Blob([completeUris], { type: "text/plain;charset=utf-8" }); saveAs(blob, "uris_" + user_id + ".txt"); }); $(window).on("unload", function () { var completeUris = videoUris + videoIds; //var dataSend = {videoUrl: videoUris, videoId: videoIds, uid: user_id}; var html = "php/savevuriLogs.php"; /*console.log(dataSend); console.log(html); $.post(html, dataSend, function(data){ console.log("done"); });*/ var fd = new FormData(); fd.append("videoUrl", videoUris); fd.append("videoId", videoIds); fd.append("uid", user_id); navigator.sendBeacon(html, fd); }); $(document).on("click", "#video_uri", function () { var videoUri = $(this).attr("name"); var video2Down = $(this).attr("info"); var video2DownWater = $(this).attr("infoWater"); var videoUid = $(this).attr("infouid"); var videoMID = $(this).attr("infomid"); //console.log(addressValue); counterAc = parseInt($(this).attr("vn")); $("#body_content").css("filter", "blur(5px)"); $("#player_buttons").css("visibility", "visible"); $("#btn_downRaw").attr("onclick", 'location.href="' + video2Down + '";'); $("#btn_downWhater").attr( "onclick", 'location.href="' + video2DownWater + '";' ); if (videoMID != "") { $("#btn_goMusic").attr("href", "user_music.php?mid=" + videoMID); } /*if (video2DownWater != "") { $("#btn_downWhater").attr('onclick', "location.href=\"" + video2DownWater + "\";"); }else{ $("#btn_downWhater").attr('onclick', "alert('Video with watermark not available')"); }*/ $("#video_player_tag").attr("src", videoUri); $("#video_player").css("visibility", "visible"); }); $(document).keydown(function (e) { switch (e.which) { case 37: // left if ($("#video_player").css("visibility") == "visible") { if (counterAc > 1) { counterAc = counterAc - 1; setPlayerKeys($("[vn=" + counterAc + "]")); } else { alert("There is no more videos in that direction!"); } } break; case 39: // right if ($("#video_player").css("visibility") == "visible") { if (counterAc < counter) { counterAc = counterAc + 1; setPlayerKeys($("[vn=" + counterAc + "]")); } else { getJsonOC(); alert("There is no more videos in that direction! Loding more..."); } } break; case 77: if ($("#player_buttons").css("visibility") != "hidden") { //console.log("test1"); $("#btn_goMusic").click(); } break; case 87: if ($("#player_buttons").css("visibility") != "hidden") { $("#btn_downWhater").click(); } break; case 82: if ($("#player_buttons").css("visibility") != "hidden") { $("#btn_downRaw").click(); } break; case 27: if ($("#player_buttons").css("visibility") != "hidden") { $("#btn_closePlayer").click(); } break; case 85: if ($("#btn_saveLinks").css("display") != "none") { $("#btn_saveLinks").click(); } break; default: return; // exit this handler for other keys } e.preventDefault(); // prevent the default action (scroll / move caret) }); function setPlayerKeys(obj) { var videoUri = $(obj).attr("name"); var video2Down = $(obj).attr("info"); var video2DownWater = $(obj).attr("infoWater"); var videoUid = $(obj).attr("infouid"); var videoMID = $(obj).attr("infomid"); //console.log(addressValue); $("#body_content").css("filter", "blur(5px)"); $("#player_buttons").css("visibility", "visible"); $("#btn_downRaw").attr("onclick", 'location.href="' + video2Down + '";'); $("#btn_downWhater").attr( "onclick", 'location.href="' + video2DownWater + '";' ); if (videoMID != "") { $("#btn_goMusic").attr( "onclick", 'location.href="user_music.php?mid=' + videoMID + '";' ); } else { alert("There is no users with this music."); } if (videoUid != "") { $("#btn_goUser").attr( "onclick", 'location.href="user_posts.php?user_id=' + videoUid + '";' ); } else { $("#btn_goUser").attr( "onclick", "alert('You are already on that profile.')" ); } /*if (video2DownWater != "") { $("#btn_downWhater").attr('onclick', "location.href=\"" + video2DownWater + "\";"); }else{ $("#btn_downWhater").attr('onclick', "alert('Video with watermark not available')"); }*/ $("#video_player_tag").attr("src", videoUri); $("#video_player").css("visibility", "visible"); } $("#btn_closePlayer").on("click", function () { $("#body_content").css("filter", ""); $("#player_buttons").css("visibility", "hidden"); $("#btn_downRaw").attr("onclick", ""); $("#video_player_tag").attr("src", ""); $("#video_player").css("visibility", "hidden"); }); //getea de a 8 getJsonOC(); //getJsonLikes(); /*while(has_more == 1){ console.log("yes"); }*/ function whileDelay() {} /*$(window).on("scroll", function() { var scrollHeight = $(document).height(); var scrollPosition = $(window).height() + $(window).scrollTop(); if ((scrollHeight - scrollPosition) / scrollHeight === 0) { getJson(max_offset, user_id); } });*/ function getJsonOC() { var html = "php/jsonpst.php?uid=" + user_id + "&cursor=" + max_offset; //console.log(html); $.ajax({ url: html, success: videoAdapt, error: function () { console.log("Error videos Fetch"); }, }); } function getJsonLikes() { var html = "php/jsonpst.php?uid=" + user_id + "&cursor=" + max_offset2 + "&mode=1"; console.log(html); $.ajax({ url: html, success: videoAdapt2, error: function () { console.log("Error videos Fetch"); }, }); } function videoAdapt(data) { /*data = JSON.stringify(data); console.log(data);*/ //console.log(data); var userVids = JSON.parse(data); //console.log(data); //console.log(has_more); if (userVids.status_code == 4) { alert( "User not found. Or User with no Videos. Or profile is private. Error P" ); location.replace("index.html"); //console.log(data); } else { if (infoSet != true) { infoSet = true; setUserInfo(data); } var arrayLenght = userVids.aweme_list; var arrayL = Object.keys(arrayLenght).length; var videoUrl = ""; var videoPic = ""; var videoTitle = ""; var videoUrlWater = ""; if (arrayL > 0) { for (var i = 0; i < arrayL; i++) { //videoUrlWater = userVids.aweme_list[i].video.download_addr.url_list[0]; videoUrlWater = "https://api2.musical.ly/aweme/v1/play/?video_id=" + userVids.aweme_list[i].video.play_addr.uri + "&line=0&ratio=540p&watermark=1&media_type=4&vr_type=0&test_cdn=None&improve_bitrate=0&logo_name=tiktok_m"; videoUrl = userVids.aweme_list[i].video.play_addr.url_list[0]; videoPic = userVids.aweme_list[i].video.dynamic_cover.url_list[0]; var videoPicComp = userVids.aweme_list[i].video.cover.url_list[0]; //videoPic = insert(videoPic, 4 , "s"); videoTitle = userVids.aweme_list[i].desc; var videouid = ""; var videoMusic = ""; var videoId = userVids.aweme_list[i].aweme_id; counter = counter + 1; if (userVids.aweme_list[i].hasOwnProperty("music")) { videoMusic = userVids.aweme_list[i].music.mid; } max_offset = userVids.max_cursor; videoUris = videoUris + videoUrl + "\n"; videoUris = videoUris.replace(/\n/g, "\r\n"); videoIds = videoIds + videoId + "\n"; videoIds = videoIds.replace(/\n/g, "\r\n"); var videoUrlToDown = "php/downloader.php?file=" + videoUrl + "&name=" + videoTitle.replace(/#/g, "_").replace(/ /g, "_") + "_" + user_id; var videoWaterToDown = "php/downloader.php?file=" + encodeURIComponent(videoUrlWater) + "&name=" + videoTitle.replace(/#/g, "_").replace(/ /g, "_") + "_" + user_id; $("#tbl_vids").append( html1 + videoUrl + html2 + videoUrlToDown + html3 + counter + html4 + videoWaterToDown + html5 + videouid + html6 + videoMusic + html7 + videoPicComp + html8 + videoPic + html9 + videoTitle + sep + "<hr>" + '<p style="font-size: 10px">' + "Video Id: " + videoId + "</p>" + html10 ); $("#btn_more").css("display", "block"); $("#btn_saveLinks").css("display", "block"); //console.log("1"); } } else { console.log("error for"); } } } function videoAdapt2(data) { //console.log("jsonpst.php?uid=" + user_id + "&cursor=" + max_offset2 + "&mode=1") console.log(data); var userVids = JSON.parse(data); if (userVids.msg == "Unknow") { alert( "User not found. Or User with no Videos. Or profile is private. Error L" ); //console.log(max_offset2); //location.replace("index.html"); //console.log(data); } else { var arrayLenght = userVids.aweme_list; var arrayL = Object.keys(arrayLenght).length; var videoUrl = ""; var videoPic = ""; var videoTitle = ""; var videoUrlWater = ""; var videoMusic = ""; if (arrayL > 0) { for (var i = 0; i < arrayL; i++) { videoUrl = userVids.aweme_list[i].video.download_addr.url_list[0]; videoPic = userVids.aweme_list[i].video.dynamic_cover.url_list[0]; videoTitle = userVids.aweme_list[i].desc; max_offset2 = userVids.max_cursor; var videouid = userVids.aweme_list[i].author.uid; if ("mid" in userVids.aweme_list[i].music) { videoMusic = userVids.aweme_list[i].music.mid; } else { videoMusic = ""; } has_more2 = userVids.has_more; //console.log("2: " + has_more2); var videoUrlToDown = "php/downloader.php?file=" + videoUrl + "&name=" + videoTitle.replace(/#/g, "_").replace(/ /g, "_").replace(/,/g, "_"); $("#tbl_likes").html( $("#tbl_likes").html() + html1 + videoUrl + html2 + videoUrlToDown + html3 + videoUrlWater + html4 + videouid + html5 + videoMusic + html6 + videoPic + html7 + videoTitle + html8 ); /*if (userVids.aweme_list[i].video.hasOwnProperty('download_suffix_logo_addr')){ videoUrlWater = userVids.aweme_list[i].video.download_suffix_logo_addr.url_list[0]; var videoUrlToDownWater = "php/down_water.php?file=" + videoUrlWater + "&name=" + videoTitle.replace(/#/g,"_").replace(/ /g,"_");; $("#tbl_likes").html($("#tbl_likes").html() + html1 + videoUrl + html2 + videoUrlToDown + html3 + videoUrlToDownWater + html4 + videoPic + html5 + videoTitle + html6); //console.log("1"); }else{ }*/ //console.log("1"); } } else { console.log("error for"); } } } function setUserInfo(data) { var userInfo = JSON.parse(data); var nick = userInfo.aweme_list[0].author.nickname; //done var at = userInfo.aweme_list[0].author.unique_id; //done var followingCount = userInfo.aweme_list[0].author.following_count; //done var avatarImg = userInfo.aweme_list[0].author.avatar_thumb.url_list[0]; //done avatarImg = insert(avatarImg, 4, "s"); var region = userInfo.aweme_list[0].author.region; //done var bio = userInfo.aweme_list[0].author.signature; //done has_more = userInfo.has_more; room_id = userInfo[0]; console.log(room_id); //console.log(room_id); if (room_id != "0") { $("#btn_goStream").css("visibility", "visible"); } $("#lbl_nick").html( '<img id="user_avatar" src="' + avatarImg + '" class="img-rounded" style="width: 100px; height: 100px;" alt="' + nick + '">' + " " + nick ); $("#lbl_info").html( "@" + at + sep + "Bio: " + bio + sep + "Region: " + region + $("#lbl_info").html() ); //$("#con_tabs").css('visibility', 'visible'); } function insert(str, index, value) { return str.substr(0, index) + value + str.substr(index); } });
const express = require("express"); const CategoryModel = require('../models/Category.js'); const ArticleModel = require('../models/article.js'); const pagination = require('../util/pagination.js'); const router = express.Router(); //权限验证 router.use((req,res,next)=>{ if(req.userInfo.isAdmin){ next() }else{ res.send('<h1>请用管理员账号登录</h1>'); } }) //显示文章列表 router.get('/',(req,res)=>{ const options = { page:req.query.page, model:ArticleModel, query:{}, projection:'-__v', sort:{_id:-1} //populates:[{path:"user",select:'username'},{path:'category',select:'name'}] }; pagination(options) .then(data=>{ res.render('admin/article_list',{ userInfo:req.userInfo, articles:data.docs, page:data.page, list:data.list, pages:data.pages, url:'/article' }) }) }) //显示添加文章页面 router.get("/add",(req,res)=>{ CategoryModel.find({},'name') .sort({order:-1}) .then(categories=>{ res.render('admin/article_add',{ userInfo:req.userInfo, categories }) }) }) //处理添加文章 router.post("/add",(req,res)=>{ const { category,title,intro,content } = req.body; console.log(req.body.title); ArticleModel.insertMany({ title, category, intro, content, user:req.userInfo._id }) .then(article=>{ res.render('admin/success',{ userInfo:req.userInfo, message:'添加文章成功', url:'/article' }) }) .catch(err=>{ res.render('admin/error',{ userInfo:req.userInfo, message:"添加文章失败,操作数据库错误,稍后再试一试" }) }) }) //处理编辑 router.post('/edit',(req,res)=>{ const { id,name,order } = req.body; CategoryModel.findById(id) .then(category=>{ if(category.name == name && category.order == order){ res.render("admin/error",{ userInfo:req.userInfo, message:'请修改后在提交' }) }else{ CategoryModel.findOne({name:name,_id:{$ne:id}}) .then(newCategory=>{ if(newCategory){ res.render("admin/error",{ userInfo:req.userInfo, message:'修改分类失败,分类已存在' }) }else{ CategoryModel.update({_id:id},{name,order}) .then(result=>{ res.render('admin/success',{ userInfo:req.userInfo, message:'修改分类成功', url:'/category' }) }) .catch(err=>{ throw err; }) } }) .catch(err=>{ throw err; }) } }) .catch(err=>{ res.render("admin/error",{ userInfo:req.userInfo, message:'修改分类失败,数据库错误,请稍后再试' }) }) }) //删除 router.get('/delete/:id',(req,res)=>{ const { id } = req.params CategoryModel.deleteOne({_id:id}) .then(result=>{ res.render('admin/success',{ userInfo:req.userInfo, message:'删除分类成功', url:'/category' }) }) .catch(err=>{ res.render("admin/error",{ userInfo:req.userInfo, message:'删除分类失败,数据库错误,请稍后再试' }) }) }) module.exports = router;
"use strict"; var async = require('async'); module.exports = function (sequelize, DataTypes) { var Game = sequelize.define('Game', { id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, datetime: DataTypes.DATE, away_id: DataTypes.INTEGER, home_id: DataTypes.INTEGER, away_score: DataTypes.INTEGER, home_score: DataTypes.INTEGER, winner_id: DataTypes.INTEGER, source_url: DataTypes.STRING(200), box_score_url: DataTypes.STRING(200), espn_id: DataTypes.INTEGER, season_id: DataTypes.INTEGER, sport_id: DataTypes.INTEGER, week_no: DataTypes.INTEGER }, { indexes: [ { unique: true, fields: ['id'] }, { name: 'get_current_season_games', fields: ['home_id', 'away_id', 'datetime',{attribute: 'datetime', order: 'ASC'}] }, { unique: true, name: 'espn_id_index', fields: ['espn_id'] } ], timestamps: true, freezeTableName: true, tableName: 'game', classMethods: { saveGame: function(game) { return Game.findOrCreate({ where: { espn_id: game.espn_id }, defaults: game }) .spread(function (gameDBRecord, isCreated) { function updateScores(game, dbRecord, periods) { return new Promise(function (resolve, reject) { var scores = []; game.scores.away.forEach(function (score, index) { if (!isNaN(game.scores.away[index]) && !isNaN(game.scores.home[index]) || game.scores.home[index] === '-' || game.scores.away[index] === '-') { scores.push({ game_id: dbRecord.id, period_id: periods[index].id, period: index + 1, away_id: game.away_id, home_id: game.home_id, away_score: game.scores.away[index], home_score: game.scores.home[index] }); } }); async.waterfall([ function (cb) { sequelize.models.Score.destroy({ where: { game_id: dbRecord.id } }) .then(function (affectedRows) { cb(); }) .catch(cb); }, function (cb) { sequelize.models.Score.bulkCreate(scores) .then(function () { cb(null, scores); }) .catch(cb); } ], function (err, scores) { if (err) { reject(err); } else { resolve(scores); } }); }); } var sportId = game.sport_id; return sequelize.models.Period.findAll({ where: { sport_id: sportId }, order: 'index ASC' }) .then(function (periods) { if (isCreated) { // Add scores to newly created game return updateScores(game, gameDBRecord, periods); } else { // Update already present game scores gameDBRecord.away_score = game.away_score; gameDBRecord.home_score = game.home_score; gameDBRecord.away_id = game.away_id; gameDBRecord.home_id = game.home_id; gameDBRecord.winner_id = game.winner_id; gameDBRecord.box_score_url = game.box_score_url; gameDBRecord.espn_id = game.espn_id; gameDBRecord.datetime = game.datetime; gameDBRecord.season_id = game.season_id; gameDBRecord.week_no = game.week_no; return gameDBRecord.save() .then(function () { return updateScores(game, gameDBRecord, periods); }); } }); }); }, resolveGame: function(sportId, gameDate, awayTeam, homeTeam) { return sequelize.query('SELECT \ g.id AS "game_id", \ g.espn_id AS "espn_id", \ g.box_score_url AS "score_link", \ at.id AS "away_team_id", \ ht.id AS "home_team_id", \ at.full_name, \ ht.full_name \ FROM game g \ LEFT JOIN sport_team at ON g.away_id = at.id \ LEFT JOIN sport_team ht ON g.home_id = ht.id \ WHERE \ (g.datetime AT TIME ZONE \'America/New_York\') :: DATE = :gameDate :: DATE \ AND g.sport_id = :sportId \ AND (at.full_name LIKE regexp_replace(:awayTeam, \'[^a-zA-Z\%\ ]\', \'%\', \'g\') \ OR ht.full_name LIKE regexp_replace(:homeTeam, \'[^a-zA-Z\%\ ]\', \'%\', \'g\')) \ LIMIT 1;', { type: sequelize.QueryTypes.SELECT, replacements: { awayTeam: '%' + awayTeam + '%', homeTeam: '%' + homeTeam + '%', gameDate: '%' + gameDate + '%', sportId: sportId } }) .then(function(result) { if(!result || result.length === 0) { return null; } return { gameId: result[0].game_id, espnId: result[0].espn_id, scoreLink: result[0].score_link, awayTeamId: result[0].away_team_id, homeTeamId: result[0].home_team_id } }); }, getOldGames: function (date) { return sequelize.query("SELECT id FROM game WHERE (SELECT COUNT(*) FROM score WHERE game_id = game.id) = 0 AND datetime <= :date", { type: sequelize.QueryTypes.SELECT, replacements: { date: date } }) } } }); return Game; };
import firebase from 'firebase'; const firebaseConfig = { apiKey: 'AIzaSyDXZEOi_czeNROEjfR9aWzEtVPEKec7rag', authDomain: 'exhale-project-ff168.firebaseapp.com', databaseURL: 'https://exhale-project-ff168.firebaseio.com', projectId: 'exhale-project-ff168', storageBucket: 'exhale-project-ff168.appspot.com', messagingSenderId: '1059533838634', appId: '1:1059533838634:web:126b010b6e4bffd8a02653', measurementId: 'G-B3QBECYKQ2', }; const fire = firebase.initializeApp(firebaseConfig); export const uiConfig = { signInFlow: 'popup', signInOptions: [ firebase.auth.GoogleAuthProvider.PROVIDER_ID, firebase.auth.FacebookAuthProvider.PROVIDER_ID, ], }; export default fire;
var tanya = true while(tanya) { var player = prompt('gunting, batu, kertas'); var comp = Math.random(); var hasil = ''; if (comp < 0.34) { comp = 'gunting'; } else if (comp >= 0.34 && comp <= 0.67) { comp = 'batu'; } else { comp = 'kertas'; } if (player === comp) { hasil += 'SERI!'; } else if (player == 'gunting') { hasil += (comp == 'kertas') ? 'MENANG!' : 'KALAH' } else if (player == 'batu') { hasil += (comp == 'gunting') ? 'MENANG!' : 'KALAH' } else if (player == 'kertas') { hasil += (comp == 'batu') ? 'MENANG!' : 'KALAH' } else { hasil += 'SALAH INPUT'; } // tampilan hasilnya console.log(player); console.log(comp); console.log(hasil) alert('KAMU memilih: ' + player + '\nKOMPUTER memilih: ' + comp + '\nhasilnya = KAMU ' + hasil) tanya = confirm('lagi?') } alert('terima kasih')
// @see https://eslint.org/docs/developer-guide/working-with-custom-formatters module.exports = (results, data) => { const meta = data ? data.rulesMeta : null; const docs = ruleId => { if (meta && meta[ruleId] && meta[ruleId].docs) { const { recommended, url } = meta[ruleId].docs; return { recommended, url }; } else { return null; } }; const newResults = results.map(({ filePath, messages }) => ({ filePath, messages: messages.map( ({ ruleId, severity, message, line, column, endLine, endColumn }) => ({ ruleId, severity, message, line, column, endLine, endColumn, docs: docs(ruleId) }) ) })); return JSON.stringify(newResults); };
import { DrawerNavigator, StackNavigator } from 'react-navigation'; import React from 'react'; import { TouchableOpacity } from 'react-native'; import Home from '../components/Home'; import Bubble from '../components/Bubble'; import Tweets from '../components/Tweets'; import Market from '../components/Market'; import Calendar from '../components/Calendar'; import Communities from '../components/Communities'; import Donate from '../components/Donate'; import Icon from 'react-native-vector-icons/FontAwesome'; export const Drawer = DrawerNavigator({ Home: { screen: Home, navigationOptions: { title: '홈', } }, Bubble: { screen: Bubble, navigationOptions: { title: '가치평가', } }, Market: { screen: Market, navigationOptions: { title: '코인 시세', } }, Tweets: { screen: Tweets, navigationOptions: { title: '트윗', } }, Calendar: { screen: Calendar, navigationOptions: { title: 'ICO|호재', } }, Communities: { screen: Communities, navigationOptions: { title: '모아보기', } }, Donate: { screen: Donate, } }); let handleDrawer = ['DrawerOpen', 'DrawerClose']; export const Stacks = StackNavigator({ Home: { screen: Drawer }, }, { initialRouteName: 'Home', navigationOptions: ({navigation}) => ({ headerLeft: <TouchableOpacity onPress={() => { navigation.navigate(handleDrawer[0]) handleDrawer.push(handleDrawer.shift()) }} > <Icon style={{margin:10}} name='bars' size={20} color='white' /> </TouchableOpacity>, headerStyle: { backgroundColor: 'rgb(36,36,36)', marginTop: 24 }, title: 'InvesCoin', headerTintColor: 'white', }) });
/* Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false */ s = "A man, a plan, a canal: Panama" function validPalindrome(s) { s = s.replace(/[^0-9a-zA-Z]+/gmi, ""); console.log(s) asdafd } validPalindrome(s);
var keystone = require('keystone'); var handlebars = require('handlebars'); handlebars.registerHelper('splitDesc', function(description) { var description = description.split("\r\n"); var final = ''; for (var i= 0 ; i < description.length ; i++){ final = final + "<p>" + description[i] + "</p>"; } return (final); //return handlebars.SafeString("test", description[0] + " <br/> " + description[1]); //return description; }); exports = module.exports = function(req,res){ var view = new keystone.View(req,res); var locals = res.locals; locals.section = 'faqlist'; view.query('faqlist', keystone.list('faqlist').model.find()); view.render('faqlist'); }
let routes = require("express").Router(); let mongo = require("../common/mongo"); routes.get("/",(req,res)=>{ rule = req.query.rule ? req.query.rule : 'time'; count = req.query.count ? req.query.count : 3; q = req.query.q ? req.query.q : ''; start = req.query.start ? req.query.start:1; let commonDate = { slides:req.session, crumb:"首页", active:"user", columnName:"user", 'api_name':"user", q, time:req.query.time, start, rule, count } mongo({ collection:"user", callback:(collection,client,)=>{ collection.countDocuments({},(err,result)=>{ commonDate.pageCount=Math.ceil(result/(count-0)) ? Math.ceil(result/(count-0)) : 1; collection.find( q ? { title: eval('/' + q + '/g') } : {}, { sort: rule ? { [rule]: -1 } : { 'time': -1 }, limit:count ? count-0: 3, skip:start?(start-1)*count:0 }).toArray((err,result)=>{ client.close(); commonDate.pageData = {data:result}; res.render("user",commonDate); }); }) } }); }); module.exports = routes;
'use strict'; (function () { var filterButton = document.querySelector('.catalog-form__filter-button'); if (filterButton) { var body = document.querySelector('.page-body'); var header = body.querySelector('.page-header'); var filterMenu = document.querySelector('.catalog-filter'); var filterMenuClose = document.querySelector('.catalog-filter__close'); var rangeFilter = filterMenu.querySelector('.range-filter'); var rangeBar = rangeFilter.querySelector('.range-filter__bar'); var minPrice = rangeFilter.querySelector('.range-filter__price--min'); var maxPrice = rangeFilter.querySelector('.range-filter__price--max'); filterMenu.classList.remove('catalog-filter--nojs'); rangeFilter.classList.remove('range-filter--nojs'); rangeBar.classList.remove('range-filter__bar--nojs'); minPrice.textContent = '$ 55'; maxPrice.textContent = '$ 155'; filterButton.addEventListener('click', function (evt) { evt.preventDefault(); body.classList.add('page-body--fixed-filter'); header.classList.add('page-header--hide'); filterMenu.classList.add('catalog-filter--open'); }); filterMenuClose.addEventListener('click', function (evt) { evt.preventDefault(); body.classList.remove('page-body--fixed-filter'); header.classList.remove('page-header--hide'); filterMenu.classList.remove('catalog-filter--open'); }); window.addEventListener('keydown', function (evt) { if (evt.key === 'Escape') { evt.preventDefault(); body.classList.remove('page-body--fixed-filter'); header.classList.remove('page-header--hide'); filterMenu.classList.remove('catalog-filter--open'); } }); } }());
const User = require('../models/user') const isAdmin = async user => { const userWithLastestUpdated = await new User().getById(user._id) if (userWithLastestUpdated.role === 'ADMIN') { return true } return false } module.exports = isAdmin
appControllers.controller('NavCtrl', [ '$scope', '$location', function($scope, $location) { $scope.isActive = function(route) { $scope.path = $location.path(); return $location.path() === route; }; } ]); appControllers.controller("ExpandCtrl", [ '$scope', function($scope) { $scope.toggleDetail = function(id) { if ($scope.activeId == id) $scope.activeId = -1; else $scope.activeId = id; }; } ]); appControllers.controller('SurveyListCtrl', ['$scope', '$interval', '$window', '$location', 'SurveyService', 'AuthenticationService', function SurveyListCtrl($scope, $interval, $window, $location, SurveyService, AuthenticationService) { if (AuthenticationService.isAuthenticated) { $scope.surveys = []; $scope.exportData = []; $scope.currentUser = $window.sessionStorage._id; SurveyService.findAll().success(function(data) { $scope.surveys = data; for(var i = 0; i < data.length; i++) { var createDate = new Date(data[i].created); $scope.exportData.push({ name: data[i].name, gender: data[i].gender, city: data[i].city, kids: data[i].kids.toString(), creator: data[i].creator.username, created: createDate }); } }).error(function(data, status) { console.log(status); console.log(data); }); var timerSurveyList = $interval(function () { $scope.exportData = []; SurveyService.findAll().success(function(data) { $scope.surveys = data; for(var i = 0; i < data.length; i++) { var createDate = new Date(data[i].created); $scope.exportData.push({ name: data[i].name, gender: data[i].gender, city: data[i].city, kids: data[i].kids.toString(), creator: data[i].creator.username, created: createDate }); } }).error(function(data, status) { console.log(status); console.log(data); }); }, 60000); $scope.$on('$destroy', function() { $interval.cancel(timerSurveyList); }); } else { $location.path("/"); } } ]); appControllers.controller('SurveyCreateCtrl', ['$scope', '$location', '$window', 'SurveyService', 'AuthenticationService', function SurveyCreateCtrl($scope, $location, $window, SurveyService, AuthenticationService) { if (AuthenticationService.isAuthenticated) { $scope.save = function save(survey) { if (survey.name != undefined && survey.city != undefined && survey.gender != undefined && survey.kids != undefined) { SurveyService.create(survey, $window.sessionStorage.username).success(function(data) { $location.path("/survey/list"); }).error(function(data, status) { console.log(status); console.log(data); }); } } } } ]); appControllers.controller('SurveyEditCtrl', ['$scope', '$routeParams', '$location', 'SurveyService', 'AuthenticationService', function SurveyEditCtrl($scope, $routeParams, $location, SurveyService, AuthenticationService) { if (AuthenticationService.isAuthenticated) { $scope.survey = {}; var id = $routeParams.id; SurveyService.findOne(id).success(function(data) { $scope.survey = data; }).error(function(data, status) { $location.path("/survey/list"); }); $scope.save = function save(survey) { if (survey.name != undefined && survey.city != undefined && survey.gender != undefined && survey.kids != undefined) { SurveyService.update(survey).success(function(data) { $location.path("/survey/list"); }).error(function(data, status) { console.log(status); console.log(data); }); } } } } ]); appControllers.controller('ModalCtrl', ['$scope', '$location', '$route', 'SurveyService', function ModalCtrl($scope, $location, $route, SurveyService) { $scope.modalShown = false; $scope.surveyToDeleteId = ''; $scope.openModal = function(id) { $scope.modalShown = !$scope.modalShown; $scope.surveyToDeleteId = id; } $scope.closeModal = function() { $scope.modalShown = !$scope.modalShown; $scope.surveyToDeleteId = ''; } $scope.deleteSurvey = function deleteSurvey() { if ($scope.surveyToDeleteId != '') { var id = $scope.surveyToDeleteId; $scope.surveyToDeleteId= ''; SurveyService.delete(id).success(function(data) { if($location.path() != "/survey/list") { $location.path("/survey/list"); } else { $route.reload(); } }).error(function(data, status) { console.log(status); console.log(data); }); } } } ]); appControllers.controller('ChartCtrl', [ '$scope', '$location', '$interval', 'SurveyService', 'AuthenticationService', function ChartCtrl($scope, $location, $interval, SurveyService, AuthenticationService) { if (AuthenticationService.isAuthenticated) { $scope.pieConfig = { tooltips: true, labels: false, colors: ['red', 'blue'], legend: { display: true, position: 'right' } }; SurveyService.getPie().success(function(data) { $scope.pieData = { data: [{ x: "Male", y: [data.male], }, { x: "Female", y: [data.female] }] }; }) .error(function(data, status) { console.log(status); console.log(data); }); var timerSurveyChart = $interval(function () { SurveyService.getPie().success(function(data) { $scope.pieData = { data: [{ x: "Male", y: [data.male], }, { x: "Female", y: [data.female] }] }; }) .error(function(data, status) { console.log(status); console.log(data); }); }, 60000); $scope.$on('$destroy', function() { $interval.cancel(timerSurveyChart); }); } else { $location.path("/"); } } ]); appControllers.controller('UserCtrl', ['$scope', '$location', '$window', '$interval', 'UserService', 'AuthenticationService', function UserCtrl($scope, $location, $window, $interval, UserService, AuthenticationService) { if (AuthenticationService.isAuthenticated && $location.path() == '/') { $location.path('/survey/list'); } if (AuthenticationService.role != 'admin' && $location.path() == '/admin/register') { $location.path('/survey/list'); } //Admin User Controller (signIn, logOut, register) $scope.signIn = function signIn(username, password) { if (username != null && password != null) { UserService.signIn(username, password).success(function(data) { AuthenticationService.isAuthenticated = true; $window.sessionStorage._id = data._id; $window.sessionStorage.username = data.username; $window.sessionStorage.role = data.role; $window.sessionStorage.token = data.token; $location.path("/survey/list"); }).error(function(data, status) { $scope.error = data.error; console.log(status); console.log(data); }); } } $scope.logOut = function logOut() { if (AuthenticationService.isAuthenticated) { UserService.logOut().success(function(data) { AuthenticationService.isAuthenticated = false; AuthenticationService.role = ''; delete $window.sessionStorage._id; delete $window.sessionStorage.username; delete $window.sessionStorage.role; delete $window.sessionStorage.token; //$interval.cancel(timerSurveyList); //$interval.cancel(timerSurveyChart); $location.path("/"); }).error(function(data, status) { console.log(status); console.log(data); }); } else { $location.path("/"); } } $scope.register = function register(username, password, passwordConfirm, role) { if (AuthenticationService.isAuthenticated) { UserService.register(username, password, passwordConfirm, role).success(function(data) { $location.path("/admin/users"); }).error(function(data, status) { $scope.error = data.error; console.log(status); console.log(data); }); } else { $location.path("/"); } } } ]); appControllers.controller('UserListCtrl', [ '$scope', '$location', 'UserService', 'AuthenticationService', function UserListCtrl($scope, $location, UserService, AuthenticationService) { if (AuthenticationService.role != 'admin' && $location.path() == '/admin/users') { $location.path('/survey/list'); } else if (AuthenticationService.isAuthenticated) { $scope.users = []; UserService.list().success(function(data) { $scope.users = data; }).error(function(data, status) { console.log(status); console.log(data); }); } else { $location.path("/"); } } ]);
var base_url = document.getElementById('base_url').innerHTML; function show_message($icon, $title, $message){ Swal.fire({ icon: $icon, html: '<div class="col-12">'+ '<center>'+ '<strong>'+$title+'</strong><br>'+ '<small>'+$message+'</small>'+ '</center>'+ '</div>', showCloseButton: false, showCancelButton: false, showConfirmButton: true }); } function update_status_order(act){ $('.loader').attr('hidden', false); var action = act; var id = document.getElementById('order_id').innerHTML; $.ajax({ url: document.getElementById('base_url').innerHTML + 'api/update_status_order', type: 'post', data: {'action':action, 'id':id}, success: function(result){ $('.loader').attr('hidden', true); var data = JSON.parse(result); show_message('success', data.response['message']['english'], ''); location.reload(); }, error: function(error, x, y){ $('.loader').attr('hidden', true); show_message('error', 'Oops! sepertinya ada kesalahan', 'kesalahan tidak diketahui'); var msg = JSON.parse(error.responseText); show_message('error', 'Oops! sepertinya ada kesalahan', msg.response.message['english']); } }) } function update_status_order_upgrade(status){ $('.loader').attr('hidden', false); var vStatus = status; var order_id = document.getElementById('order_id').innerHTML; var lisensi_id = document.getElementById('lisensi_id').innerHTML; var user_id = document.getElementById('user_id').innerHTML; $.ajax({ url: document.getElementById('base_url').innerHTML + 'api/upgrade_licence_update_status', type: 'post', data: {'order_id': order_id,'status': vStatus,'lisensi_id': lisensi_id,'user_id': user_id}, success: function(result){ $('.loader').attr('hidden', true); var d = JSON.parse(result); show_message('success', d.response.message['english'], ''); location.reload(); }, error: function(error, x, y){ $('.loader').attr('hidden', true); show_message('error', 'Oops! sepertinya ada kesalahan', 'kesalahan tidak diketahui'); var msg = JSON.parse(error.responseText); show_message('error', 'Oops! sepertinya ada kesalahan', msg.response.message['english']); } }) } function upgrade_licence_with_balance(){ $('.loader').attr('hidden', false); var lisensi_id = document.getElementById('lisensi_id').innerHTML; var user_id = document.getElementById('user_id').innerHTML; $.ajax({ url: document.getElementById('base_url').innerHTML + 'api/upgrade_licence_with_balance', type: 'post', data: {'lisensi_id': lisensi_id,'id': user_id}, success: function(result){ $('.loader').attr('hidden', true); var d = JSON.parse(result); show_message('success', d.response.message['english'], ''); location.reload(); }, error: function(error, x, y){ $('.loader').attr('hidden', true); show_message('error', 'Oops! sepertinya ada kesalahan', 'kesalahan tidak diketahui'); var msg = JSON.parse(error.responseText); show_message('error', 'Oops! sepertinya ada kesalahan', msg.response.message['english']); } }) } function update_status_order_pin(act){ $('.loader').attr('hidden', false); var action = act; var id = document.getElementById('order_id').innerHTML; $.ajax({ url: document.getElementById('base_url').innerHTML + 'api/update_status_order_pin', type: 'post', data: {'action':action, 'id':id}, success: function(result){ $('.loader').attr('hidden', true); var data = JSON.parse(result); show_message('success', data.response['message']['english'], ''); location.reload(); }, error: function(error, x, y){ $('.loader').attr('hidden', true); show_message('error', 'Oops! sepertinya ada kesalahan', 'kesalahan tidak diketahui'); var msg = JSON.parse(error.responseText); show_message('error', 'Oops! sepertinya ada kesalahan', msg.response.message['english']); } }) } function update_profile_company(){ var sistem_name = document.getElementById('sistem_name').value var phone_number = document.getElementById('phone_number').value var email = document.getElementById('email').value var address = document.getElementById('address').value if(sistem_name != ''){ if(phone_number != ''){ if(email != ''){ if(address != ''){ $.ajax({ url: document.getElementById('base_url').innerHTML + 'api/update_status_company_profile', type: 'post', data: {'sistem_name':sistem_name, 'phone_number':phone_number, 'email':email, 'address':address}, success: function(result){ $('.loader').attr('hidden', true); var data = JSON.parse(result); show_message('success', data.response['message']['english'], ''); location.reload(); }, error: function(error, x, y){ $('.loader').attr('hidden', true); show_message('error', 'Oops! sepertinya ada kesalahan', 'kesalahan tidak diketahui'); var msg = JSON.parse(error.responseText); show_message('error', 'Oops! sepertinya ada kesalahan', msg.response.message['english']); } }) }else{ show_message('warning', 'Address is Empty', ''); } }else{ show_message('warning', 'Email is Empty', ''); } }else{ show_message('warning', 'Phone Number is Empty', ''); } }else{ show_message('warning', 'Sistem Name is Empty', ''); } } function update_pin_register_settings(){ var price = document.getElementById('price').value var currency = document.getElementById('currency').value if(price != ''){ if(currency != ''){ $.ajax({ url: document.getElementById('base_url').innerHTML + 'api/update_pin_register', type: 'post', data: {'price':price, 'currency':currency}, success: function(result){ $('.loader').attr('hidden', true); var data = JSON.parse(result); show_message('success', data.response['message']['english'], ''); location.reload(); }, error: function(error, x, y){ $('.loader').attr('hidden', true); show_message('error', 'Oops! sepertinya ada kesalahan', 'kesalahan tidak diketahui'); var msg = JSON.parse(error.responseText); show_message('error', 'Oops! sepertinya ada kesalahan', msg.response.message['english']); } }) }else{ show_message('warning', 'Currency is Empty', ''); } }else{ show_message('warning', 'Price is Empty', ''); } } function update_licence_setting(){ var name = document.getElementById('name').value var price = document.getElementById('price').value var percentage = document.getElementById('percentage').value var id = document.getElementById('id_licence').value // console.log(id); if(name != ''){ if(price != ''){ if(percentage != ''){ $.ajax({ url: document.getElementById('base_url').innerHTML + 'api/update_licence_setting', type: 'post', data: {'price':price, 'percentage':percentage, 'name':name, 'id':id}, success: function(result){ $('.loader').attr('hidden', true); var data = JSON.parse(result); show_message('success', data.response['message']['english'], ''); location.reload(); }, error: function(error, x, y){ $('.loader').attr('hidden', true); show_message('error', 'Oops! sepertinya ada kesalahan', 'kesalahan tidak diketahui'); var msg = JSON.parse(error.responseText); show_message('error', 'Oops! sepertinya ada kesalahan', msg.response.message['english']); } }) }else{ show_message('warning', 'Percentage is Empty', ''); } }else{ show_message('warning', 'Price is Empty', ''); } }else{ show_message('warning', 'Name is Empty', ''); } } function update_instruction(){ var instruction = document.getElementById('instruction').value // console.log(id); if(instruction != ''){ $.ajax({ url: document.getElementById('base_url').innerHTML + 'api/update_instruction', type: 'post', data: {'instruction':instruction}, success: function(result){ $('.loader').attr('hidden', true); var data = JSON.parse(result); show_message('success', data.response['message']['english'], ''); location.reload(); }, error: function(error, x, y){ $('.loader').attr('hidden', true); show_message('error', 'Oops! sepertinya ada kesalahan', 'kesalahan tidak diketahui'); var msg = JSON.parse(error.responseText); show_message('error', 'Oops! sepertinya ada kesalahan', msg.response.message['english']); } }) }else{ show_message('warning', 'Instruction is Empty', ''); } } function change_logo(){ var fd = new FormData(); var files = $('#file')[0].files; if(files.length > 0 ){ fd.append('file',files[0]); $.ajax({ url: document.getElementById('base_url').innerHTML + 'api/update_logo', type: 'post', data: fd, contentType: false, processData: false, success: function(response){ if(response != 0){ show_message('success', 'Logo has been changed', ''); location.reload(); }else{ Swal.fire( 'File not upload', '', 'error' ) } }, error: function(error, x, y){ console.log(error); } }); }else{ show_message('warning', 'Logo is Empty', ''); } }
import React, { PropTypes } from 'react'; import { Link } from 'react-router'; const propTypes = { children: PropTypes.element.isRequired, routes: PropTypes.array.isRequired, }; /* <header> <h1>When should I leave for the airport?</h1> </header> */ function App({ children, routes }) { return ( <div> <header> <h1>When should I leave for the airport?</h1> </header> {children} <div style={{ color: '#A0A0A0', fontSize: '14px', marginTop: '50px', textAlign: 'center'}}> </div> </div> ); } App.propTypes = propTypes; export default App;
const Regencies = require(model + "support/regencies.model") const Districts = require(model + "support/districts.model") async function index(req,res){ let data = await this.DB('SELECT * FROM support.regencies r INNER JOIN support.districts d ON r.id_regency=d.regency_id ORDER BY r.id_regency ASC') this.responseSuccess({ code:200, status: true, values: data.get(), message: 'Data Kecamatan Berhasil di Dapatkan' }) } async function ddlRegencies(req,res){ let data = await Regencies.query() this.responseSuccess({ code:200, status: true, values: data, message: 'Data Kota/Kabupaten Berhasil di Dapatkan' }) } async function store(req, res){ let request = req.body await this.validation(request, { kabupaten: 'required', kecamatan: 'required' }) await Districts.query().insert({ regency_id: request.kabupaten, district: request.kecamatan.toUpperCase() }) this.responseSuccess({ code:201, status: true, values:{}, message: 'Data Kecamatan Berhasil di Tambahkan' }) } async function update(req,res){ let request = req.body await this.validation(request, { kabupaten: 'required', kecamatan: 'required' }) let update = await Districts.query().update({ regency_id: request.kabupaten, district: request.kecamatan.toUpperCase() }) .where('id_district', request.id) if(update){ this.responseSuccess({ code:200, status: true, values:{}, message: 'Data Kecamatan Berhasil di Update' }) }else{ this.responseError({ code:400, status: false, values:{}, message: 'Data Kecamatan Gagal di Update' }) } } async function destroy(req,res){ let hapus = await Districts.query().deleteById(req.params.id) if(hapus){ this.responseSuccess({ code:200, status: true, values: {}, message: 'Data Kecamatan Berhasil di Hapus' }) }else{ this.responseError({ code:400, status: false, values: {}, message: 'Data Kecamatan Gagal di Hapus' }) } } module.exports = { index, ddlRegencies, store, destroy, update }
import React from "react"; import { Input, Form as AntForm, Button, message } from "antd"; import { Formik, Field, Form as FormikForm } from "formik"; import http from "axios"; import * as Yup from "yup"; import { API_URL } from "../config"; import { getAuthHeaders } from "../utils"; const Search = Input.Search; const FormItem = AntForm.Item; class BiddingForm extends React.Component { bid = async (auctionId, amount, submitting) => { const bidMessage = message.loading("Submitting bid", 0); try { const { data } = await http.post( `${API_URL}/auction/${auctionId}/bid`, amount, { headers: getAuthHeaders() } ); submitting(false); bidMessage(); } catch (error) { submitting(false); bidMessage(); console.log(error.response.data.message); } }; render() { return ( <Formik initialValues={{ amount: "" }} validationSchema={Yup.object().shape({ amount: Yup.number() .integer("The amount must be an integer") .min(this.props.currentBid + 1, "Your bid is not valid") .required("Bid cannot be empty") })} onSubmit={(values, { setSubmitting }) => { this.bid(this.props.auction, values, setSubmitting); }}> {({ handleSubmit, isSubmitting }) => ( <FormikForm onSubmit={handleSubmit}> <Field name='amount' render={({ field, form: { errors, touched } }) => ( <FormItem validateStatus={ touched.amount && errors.amount ? "error" : touched.amount && !errors.amount ? "success" : "" } help={touched.amount && errors.amount}> <Input {...field} type='number' placeholder='Your bid' addonAfter={ <Button htmlType='submit' type='primary' block disabled={isSubmitting}> Bid </Button> } style={{ maxWidth: "200px" }} disabled={isSubmitting} /> </FormItem> )} /> </FormikForm> )} </Formik> ); } } export default BiddingForm;
"use strict"; const { run, hyphenToUpperCase, getWebpackCliArguments } = require("../../utils/test-utils"); const watchFlags = getWebpackCliArguments("watch"); describe("watch config related flag", () => { for (const [name, value] of Object.entries(watchFlags)) { // extract property name from flag name const property = name.split("watch-options-")[1]; const propName = hyphenToUpperCase(property); if (propName === "stdin") { return; } if ( value.configs.filter((config) => config.type === "boolean").length > 0 && name !== "watch" ) { it(`should config --${name} correctly`, async () => { const { exitCode, stderr, stdout } = await run(__dirname, [`--${name}`]); expect(exitCode).toBe(0); expect(stderr).toBeFalsy(); if (name.includes("reset")) { expect(stdout).toContain(`watchOptions: { ignored: [] }`); } else { expect(stdout).toContain(`watchOptions: { ${propName}: true }`); } }); if (!name.endsWith("-reset")) { it(`should config --no-${name} correctly`, async () => { const { exitCode, stderr, stdout } = await run(__dirname, [`--no-${name}`]); expect(exitCode).toBe(0); expect(stderr).toBeFalsy(); expect(stdout).toContain(`watchOptions: { ${propName}: false }`); }); } } if (value.configs.filter((config) => config.type === "number").length > 0) { it(`should config --${name} correctly`, async () => { const { exitCode, stderr, stdout } = await run(__dirname, [`--${name}`, "10"]); expect(exitCode).toBe(0); expect(stderr).toBeFalsy(); expect(stdout).toContain(`watchOptions: { ${propName}: 10 }`); }); } if (value.configs.filter((config) => config.type === "string").length > 0) { it(`should config --${name} correctly`, async () => { if (propName === "poll") { const { exitCode, stderr, stdout } = await run(__dirname, [`--${name}`, "200"]); expect(exitCode).toBe(0); expect(stderr).toBeFalsy(); expect(stdout).toContain(`watchOptions: { ${propName}: 200 }`); } else { const { exitCode, stderr, stdout } = await run(__dirname, [ `--${name}`, "ignore.js", ]); expect(exitCode).toBe(0); expect(stderr).toBeFalsy(); expect(stdout).toContain(`watchOptions: { ${propName}: [ 'ignore.js' ] }`); } }); } } });
import React, { Component } from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import Icons from "../helpers/icons"; Icons(); class Quantity extends Component { render() { const { className, quantity } = this.props; return ( <div className={`${className} quantity`}> <div className="quantity-count">{quantity}</div> <div className="quantity-plus"> <FontAwesomeIcon icon="chevron-up" /> </div> <div className="quantity-minus"> <FontAwesomeIcon icon="chevron-down" /> </div> </div> ); } } export default Quantity;
'use strict'; var proxyquire = require('proxyquire').noPreserveCache(); var motherSensorClientCtrlStub = { index: 'motherSensorClientCtrl.index', show: 'motherSensorClientCtrl.show', create: 'motherSensorClientCtrl.create', update: 'motherSensorClientCtrl.update', destroy: 'motherSensorClientCtrl.destroy' }; var routerStub = { get: sinon.spy(), put: sinon.spy(), patch: sinon.spy(), post: sinon.spy(), delete: sinon.spy() }; // require the index with our stubbed out modules var motherSensorClientIndex = proxyquire('./index.js', { 'express': { Router: function() { return routerStub; } }, './mother-sensor-client.controller': motherSensorClientCtrlStub }); describe('MotherSensorClient API Router:', function() { it('should return an express router instance', function() { motherSensorClientIndex.should.equal(routerStub); }); describe('GET /api/mother-sensor-clients', function() { it('should route to motherSensorClient.controller.index', function() { routerStub.get .withArgs('/', 'motherSensorClientCtrl.index') .should.have.been.calledOnce; }); }); describe('GET /api/mother-sensor-clients/:id', function() { it('should route to motherSensorClient.controller.show', function() { routerStub.get .withArgs('/:id', 'motherSensorClientCtrl.show') .should.have.been.calledOnce; }); }); describe('POST /api/mother-sensor-clients', function() { it('should route to motherSensorClient.controller.create', function() { routerStub.post .withArgs('/', 'motherSensorClientCtrl.create') .should.have.been.calledOnce; }); }); describe('PUT /api/mother-sensor-clients/:id', function() { it('should route to motherSensorClient.controller.update', function() { routerStub.put .withArgs('/:id', 'motherSensorClientCtrl.update') .should.have.been.calledOnce; }); }); describe('PATCH /api/mother-sensor-clients/:id', function() { it('should route to motherSensorClient.controller.update', function() { routerStub.patch .withArgs('/:id', 'motherSensorClientCtrl.update') .should.have.been.calledOnce; }); }); describe('DELETE /api/mother-sensor-clients/:id', function() { it('should route to motherSensorClient.controller.destroy', function() { routerStub.delete .withArgs('/:id', 'motherSensorClientCtrl.destroy') .should.have.been.calledOnce; }); }); });
const express = require('express'); //gerencia requesições, rotas e urls... const { Op } = require('sequelize') //facilita o gerenciamento de um banco de dados const cors = require('cors'); // responsvel por fazer a comunicação com o frontend const app = express(); // app ficou responsavel por deter o express const Lancamentos = require('./models/Lancamentos') app.use(express.json()); app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE"); res.header("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"); app.use(cors()); next(); }); // configurando a API para receber e passar informações app.get('/listar/:mes/:ano', async (req, res) => { let mes = new Number(req.params.mes); let ano = new Number(req.params.ano); const date = new Date(ano + "-" + mes); let primeiroDia = new Date(date.getFullYear(), date.getMonth(), 1); let ultimoDia = new Date(date.getFullYear(), date.getMonth() + 1, 0) const lancamentos = await Lancamentos.findAll({ order: [['dataPagamento', 'ASC']], where: { "dataPagamento": { [Op.between]: [primeiroDia, ultimoDia] } } }); const valorRecebido = await Lancamentos.sum('valor', { where: { tipo: '2', "dataPagamento": { [Op.between]: [primeiroDia, ultimoDia] } } }); const valorPago = await Lancamentos.sum('valor', { where: { tipo: '1', situacao: '1', "dataPagamento": { [Op.between]: [primeiroDia, ultimoDia] } } }); const valorPendente = await Lancamentos.sum('valor', { where: { tipo: '1', situacao: '2', "dataPagamento": { [Op.between]: [primeiroDia, ultimoDia] } } }); const saldo = new Number(valorRecebido) - new Number(valorPago); return res.json({ erro: false, lancamentos, valorRecebido, valorPago, valorPendente, saldo }) }); app.get('/visualizar/:id', async (req, res) => { await Lancamentos.findByPk(req.params.id).then(lancamento => { return res.json({ erro: false, lancamento }) }).catch(function () { return res.status(400).json({ erro: true, msg: "Erro: Lançamento não encontrado!" }); }); }); app.post('/cadastrar', async (req, res) => { await Lancamentos.create(req.body).then(function () { return res.json({ erro: false, msg: "Lançamento cadastrado com Sucesso!" }) }).catch(function () { return res.status(400).json({ erro: true, msg: "Erro: Lançamento não cadastrado com Sucesso!" }); }); }); app.put('/editar', async (req, res) => { let dados = req.body; await Lancamentos.update(dados, { where: { id: dados.id } }).then(function () { return res.json({ erro: false, msg: "Lançamento editado com sucesso!" }); }).catch(function () { return res.status(400).json({ erro: true, msg: "Erro: Falha na edição do lançamento!" }) }); }); app.delete('/apagar/:id', async (req, res) => { await Lancamentos.destroy({where: {id: req.params.id}}).then(function() { return res.json({ erro: false, msg: "Lançamento deletado com sucesso!" }); }).catch(function () { return res.status(400).json({ erro: true, msg: "Erro: Lançamento não foi deletado!!" }); }) }); app.listen(8080, function () { console.log("Servidor iniciado na porta 8080: http://localhost:8080"); })
const App = (children) => ( <React.Fragment> <h1>Magic 8 Ball</h1> <Magic8Ball/> </React.Fragment> ) class Magic8Ball extends React.Component { state = { status: "none", message: "Shake me!" } getMessage = async () => { const req = await fetch("/magic"); const res = await req.json(); this.setState(res); } render() { const { status, message } = this.state; return ( <div className={`ball ${status}`}> <div className="message">{message}</div> <button onClick={this.getMessage}>Shake</button> </div> ) } } const app = document.getElementById("app"); ReactDOM.render(<App/>, app);
$(function () { $(window).resize(function () { //console.log($(window).width()); $("newrow1") .css({ "width": $(window).width() - 100 }); $("north") .css({ "width": $(window).width() - 100 }); $("south") .css({ "width": $(window).width() - 100 }); $(".west") .css({ "width": $(window).width() - 50 }); $("#googlemap") .css({ "width": $(window).width() - 100 }); }); });
var intervalId; var port; var portList = new Array(); var numberOfPort = 0; onconnect = function (event) { port = event.ports[0]; numberOfPort++; portList[ numberOfPort - 1 ] = port; port.onmessage = function(e) { if ( e.data == "start" ) { intervalId = setInterval( envoyerDate, 1000); } else if ( e.data == "pause" ) { clearInterval( intervalId ); envoyerChaine( "WORKER SUSPENDU "+port ) } else if ( e.data == "stop" ) { clearInterval( intervalId ); port.postMessage("WORKER STOPPE"); port.close(); } }; // port.start(); }; var envoyerDate = function() { for (var p=0; p<portList.length; p++) { portList[ p ].postMessage( new Date() + '<br>Nb connexions = ' + numberOfPort ); } } var envoyerChaine = function( chaine ) { for (var p=0; p<portList.length; p++) { portList[ p ].postMessage( new Date() + " " + chaine + '<br>Nb connexions = ' + numberOfPort ); } }
module.exports = function countAllFromTown(string,startString){ var newString = string.split(","); var newerString = []; for(var i = 0 ; i < newString.length ; i++){ var loopString = newString[i].trim(); if(loopString.startsWith(startString)){ newerString.push(loopString); } } return newerString.length; }
import './ModalWindow.css'; import React, { PureComponent } from "react"; export default class ModalWindow extends PureComponent { constructor(props) { super(props); this.state = { close: false }; } modalClose = e => { if ( (this.node && !this.node.contains(e.target)) || e.target.id === "modalClose" ) { this.setState({ close: true }); setTimeout(() => { const layer = document.querySelector('.layer'); this.props.onModalClose(); document.body.style.overflowY = 'scroll'; layer.parentNode.removeChild(layer); }, 500); document.removeEventListener("click", this.modalClose); } }; componentDidMount() { document.addEventListener("click", this.modalClose); } render() { const { close } = this.state; return ( <div ref={node => (this.node = node)} className={"modal-window" + (close ? " modal-hide" : "")} > <div className="button-group"> <button className="btn btn-secondary" id="modalClose" onClick={this.modalClose}> close </button> </div> <div className="text"> <h1>Hello!</h1> </div> </div> ); } }
import React from 'react'; import { Polygon } from 'react-leaflet'; import { ForbiddenAreaMarker } from './Markers'; /** * Composant ForbiddenArea : * Affiche les points d'une zone interdite * * props : * - area : La zone interdite */ function ForbiddenArea({ area }) { return ( <> <Polygon color="red" positions={area.coordinates[0]}></Polygon> {area.coordinates[0].map((point, index) => ( <ForbiddenAreaMarker key={index} position={point} areaId={area.id} /> ))} </> ); } export default ForbiddenArea;
import React, { useState,useEffect } from "react" import Facade from "./apiFacade"; import { BrowserRouter as Router, Switch, Route,} from "react-router-dom"; import Company from "./Components/Company" import Header from "./Components/Header" import Home from "./Components/Home" import Products from "./Components/Products" import './App.css' import { Container} from 'react-bootstrap'; import 'bootstrap/dist/css/bootstrap.min.css' function App() { const [loggedIn, setLoggedIn] = useState(false) const logout = () => { Facade.logout() setLoggedIn(false)} const login = (user, pass) => { Facade.login(user,pass) .then(res =>setLoggedIn(true)); } return ( <Container> <Router> <Header facade={Facade} loggedIn={loggedIn}/> <Switch> <Route exact path="/"> <Home loggedIn={loggedIn} login={login} facade={Facade} logout={logout} /> </Route> <Route exact path="/Company"> {Facade.hasUserAccess('user', loggedIn) && <Company facade={Facade} // props for company />} </Route> <Route exact path="/Products"> {Facade.hasUserAccess('admin', loggedIn) && <Products facade={Facade} // props for company />} </Route> </Switch> </Router> </Container> ) } export default App;
// This is where project configuration and plugin options are located. // Learn more: https://gridsome.org/docs/config // Changes here require a server restart. // To restart press CTRL + C in terminal and run `gridsome develop` module.exports = { siteName: 'Quarry Lakes Demonstration Garden', siteDescription: 'Outstanding Plants of Alameda County', plugins: [ { use: 'gridsome-source-google-sheets-v2', options: { //sheetId: process.env.GOOGLE_SHEET_ID, //'GOOGLE_SHEET_ID', apiKey: process.env.GOOGLE_API_KEY, //'GOOGLE_API_KEY', spreadsheets: [ { spreadsheetId: process.env.GOOGLE_SHEET_ID, sheets: [ { sheetName: 'Sheet1', // Example: "Sheet1" "QL_Plants" collectionName: 'googleSheet', // Example: "Projects" (Must be unique) }, //{ // sheetName: 'Natives', // Example: "Sheet2" // collectionName: "googleSheet", // Example: "Users" (Must be Unique) //}, ], }, ], }, }, { use: '@gridsome/source-filesystem', options: { path: 'articles/**/*.md', typeName: 'Article', resolveAbsolutePaths: true, remark: { externalLinksTarget: '_blank', externalLinksRel: ['nofollow', 'noopener', 'noreferrer'], }, }, }, ], templates: { googleSheet: [ { path: '/:ID', component: './src/templates/googleSheet.vue', }, ], }, transformers: { remark: { plugins: ['@gridsome/remark-prismjs'], }, }, }
import React from "react"; import { TouchableOpacity, Text, StyleSheet } from "react-native"; import Color from "../styles/Color"; function LogFeed(props) { return ( <TouchableOpacity style={styles.container}> <Text style={styles.log}>김민재 3 : 진문화 0</Text> </TouchableOpacity> ); } const styles = StyleSheet.create({ container: { width: "80%", alignSelf: "center", margin: 10, backgroundColor: Color.themeOpacity, height: 40, justifyContent: "center", borderRadius: 10, }, log: { color: Color.themeColor, alignSelf: "center", }, }); export default LogFeed;
// @flow import React from 'react'; import { View, StyleSheet } from 'react-native'; import { UIConstant, UIComponent, UIStyle, UIColor, UILink, } from '../services/UIKit'; import TONLocalized from '../helpers/TONLocalized'; const styles = StyleSheet.create({ fixHeight: { height: UIConstant.bigCellHeight(), }, borderTop: { borderTopWidth: 1, borderTopColor: UIColor.whiteLight(), }, }); const footerTextStyle = [ UIStyle.Color.textTertiary(), UIStyle.Text.tinyMedium(), UIStyle.Padding.default(), ]; const fixHeightCenterContainer = [ styles.fixHeight, UIStyle.Common.centerLeftContainer(), ]; type Props = {}; type State = {}; export default class Bottom extends UIComponent<Props, State> { renderLeft() { return ( <View style={fixHeightCenterContainer}> { TONLocalized.BottomLinksLeft.map((item, rank) => ( <UILink key={`link-${rank}`} title={this.props.isNarrow ? null : item.linkText} href={item.link} icon={item.icon} iconStyle={item.disableIconTint ? { tintColor: '' } : null} iconHoverStyle={item.disableIconTint ? { tintColor: '' } : null} target="_blank" /> )) } </View> ); } renderRight() { return ( <View style={fixHeightCenterContainer}> { TONLocalized.BottomLinksRight.map((item, rank) => ( <UILink key={`link-${rank}`} title={this.props.isNarrow ? null : item.linkText} href={item.link} iconR={item.icon} target="_blank" /> )) } </View> ); } render() { return ( <View style={[UIStyle.Common.rowSpaceContainer(), styles.fixHeight, styles.borderTop]}> {this.renderLeft()} {this.renderRight()} </View> ); } }
var dec = 42, oct = 0o52, hex = 0x2a, bin = 0b101010 Number("42"); Number("0o52"); Number("0x2a"); Number("0b101010"); dec.toString(); dec.toString(8); dec.toString(16); dec.toString(2);
const { ApolloServer, gql, ApolloError, MockList } = require('apollo-server-express'); const ProfileAPI = require('./datasources/profiles'); const express = require('express'); const typeDefs = require('./schema'); const resolvers = require('./resolver'); /* To fetch schema using introspection const {buildClientSchema} = require('graphql'); const results = require('introspectionResults.json'); const schema = buildClientSchema(results.data); //pass this schema to Apollo server. */ const { createRateLimitTypeDef, createRateLimitDirective, defaultKeyGenerator } = require('graphql-rate-limit-directive'); const depthLimit = require('graphql-depth-limit'); const { createComplexityLimitRule } = require('graphql-validation-complexity'); //TODO:custom,skip and include directive //TODO:convert to typescript //TODO:Test const mocks = { String: () => 'hello', Query: () => { profiles: () => new MockList(1000) } } async function startApolloServer() { const dataSources = () => ({ profileAPI: new ProfileAPI() }); const server = new ApolloServer({ introspection: true, playground: true, apiKey: process.env.ENGINE_API_KEY, typeDefs: [createRateLimitTypeDef(), typeDefs], resolvers, dataSources, /*mocks:true, mocks, mockEntireSchema:true,*/ schemaDirectives: { //TODO:restrict based on user rateLimit: createRateLimitDirective(), }, validationRules: [ //depthLimit(1) ], formatError: (err) => { console.log(err) if (err.extensions.code === 'INTERNAL_SERVER_ERROR') { return new ApolloError("We are having trouble", "ERROR", { token: Math.random, err: err.message }); //TODO:store and can be referred later when user raises ticket. } return err; } }); //await server.start(); const app = express(); server.applyMiddleware({ app, path: '/graphql' }); app.listen({ port: process.env.PORT || 4000 },(url)=>{ console.log(process.env.PORT || 4000); console.log(`Go to http://localhost:${process.env.PORT}/graphiql to run queries!`); }); } startApolloServer();
var body = document.querySelector('.mainBody') const aboutLink = document.querySelector('#about') const projectsLink = document.querySelector('#projects') const resumeLink = document.querySelector('#resume') const mattLink = document.querySelector('#name') function buttonShow() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; } } function buttonTrans(x) { x.classList.toggle("change"); } function displayProjects() { let newBody = document.createElement('div') newBody.classList.add('mainBody') newBody.innerHTML = `<div class="projectsHeader"> <div> <h1>Projects</h1> <h2>Some projects I've worked on.</h2> </div> </div> <div class="projects3col"> <div class="projectpane"> <h2>AHAbot</h2> <br> <a href="https://github.com/mattspeidel/aha-bot-brain"> <img src="ahabot.png"></a> <p>AHAbot is an interactive, natural language chatbot within Slack that provides a unified, familiar interface for disruptive home control. It interacts directly with each user's personal instance of <a href="https://www.home-assistant.io/hassio/">Home Assistant</a> running on their Raspberry Pi and allows you to control many supported devices as well as receive status from all your supported smart devices.</p> <br> <p>It is built in Node.js using Node Slack SDK, Natural.js, and axios. The registration site is built in Django. </p> <br> <p>This was my final project at <a href="https://www.momentumlearn.com">Momentum Learning</a> for the 12-week immersive program. My team included <a href="https://github.com/dbarnes87">David Barnes</a>, <a href="https://github.com/christopherwburke">Chris Burke</a>, and <a href="https://github.com/ZekeHart">Zeke Hart</a>.</p> <a class="bottomline" href="https://github.com/mattspeidel/aha-bot-brain">See it on <img id="gh-small" src="GitHub-Mark-32px.png"></a> </div> <div class="projectpane"> <h2>SnipManager</h2> <br> <a href="https://github.com/mattspeidel/snipmanager"> <img src="snip.png"></a> <p>SnipManager is a web app that lets you upload, edit, search for, and copy code snippets.</p> <br> <p>This was built with Django and implements Django REST Framework. It uses a lot of javascript on the front end to provide fast results and display. The front end also includes prism.js and code mirror to provide syntax highlighting.</p> <br> <p>This project was a group project at <a href="https://www.momentumlearn.com">Momentum Learning</a>. The team included myself, <a href="https://github.com/ZekeHart">Zeke Hart</a>, and <a href="https://github.com/dzordich">David Zordich</a>.</p> <a class="bottomline" href="https://github.com/mattspeidel/snipmanager">See it on <img id="gh-small" src="GitHub-Mark-32px.png"></a> </div> <div class="projectpane"> <h2>MusicSite</h2> <br> <a href="https://github.com/mattspeidel/itunes-search"> <img src="itunes.png"></a> <p>This is a website that provides for the ability to search iTunes' music library and return a listing of song clips you can listen to. It can be filtered by Artist, Song Title, or Album Title.</p> <br> <p>It was built using javascript tapping into the iTunes API. The CSS styling accomodates both mobile and desktop layouts.</p> <a class="bottomline" href="https://github.com/mattspeidel/itunes-search">See it on <img id="gh-small" src="GitHub-Mark-32px.png"></a> </div> </div>` body.parentNode.replaceChild(newBody, body) body = document.querySelector('.mainBody') } function displayAbout() { let newBody = document.createElement('div') newBody.classList.add('mainBody') newBody.innerHTML = `<div class="aboutHeader"> <div class="contentColumn"> <h1>Matthew Speidel</h1> <img class="headshot" src="ms_hs.JPG" /> <h2>Hi, I'm a software developer based in the Raleigh-Durham, North Carolina area.</h2> </div> </div> <div class="about2col"> <div class="aboutme"> <h2>About Me</h2> <br> <p>As a lifelong techie and researcher, I dream of working on solutions for the projects of the future we have yet to imagine.</p> <br> <p>I've recently graduated <a href="https://www.momentumlearn.com">Momentum Learning's</a> 12-week immersive program in Durham, NC and am looking for great opportunities.</p> <br> <p>My technical skills include Python, Django, javascript, node.js, vue.js, HTML, CSS, Docker, working with REST APIs, SQL, and Git. I'm a passionate, dedicated problem-solver and love this career.</p> </div> <div class="contactme"> <h2>Contact Me</h2> <br> <a href="https://www.linkedin.com/in/matthew-speidel/"> <img id="li-big" src="LI-Logo.png"></a> <br> <a href="https://github.com/mattspeidel"> <img id="gh-big" src="GitHub_Logo.png"></a> <br> <a class="nounder" href="mailto:mattspeidel@gmail.com"> <img id="gmail" src="gmail.png"> Email</a> </div> </div>` body.parentNode.replaceChild(newBody, body) body = document.querySelector('.mainBody') } function displayResume() { let newBody = document.createElement('div') newBody.classList.add('mainBody') newBody.innerHTML = `<div class="resumeheader"> <div> <h1>Résumé</h1> <h2>Please review my résumé below or visit my <a href="https://www.linkedin.com/in/matthew-speidel/"">LinkedIn.</a></h2> </div> </div> <div class="resume2col"> <div class="resumeleft"> <h2>WORK EXPERIENCE</h2> <h3>Full Stack Software Developer</h3> <h3>Momentum Learning (May 2019 > Present)</h3> <p>Dedicated 12 weeks to learning Full-Stack Engineering practices for building and maintaining websites and web applications in an immersive coding program. </p> <p>Completed daily and weekly technical projects solo, in pair programming and in group setting to learn and gain knowledge around current development tools, techniques and best practices.</p> <br> <h3>Premises/Wire Technician</h3> <h3>AT&T (October 2016 > December 2017)</h3> <p>Conducted client installations and repairs of internet, VOIP, and television services in both residential and business environments.</p> <p>Utilized diagnostic equipment and tools to troubleshoot telecom facilities as well as aerial and buried communication lines.</p> <p>Exceeded performance metrics in all areas, including quality, efficiency, and safety while receiving customer service accolades.</p> <br> <h3>Center Consultant</h3> <h3>FedEx Office (August 2012 > October 2016)</h3> <p>Quickly assumed a direct role in all aspects of the business including printing, shipping, and retail merchandising.</p> <p>Directly assisted in helping the store reach the highest success levels, earning the #5 position in our store tier nationwide and President's Club status.</p> <br> <h3>Store Manager/Assistant Store Manager</h3> <h3>Gamestop (November 2004 > November 2011)</h3> <p>Captained the sales team to consistently excellent ranking regionally, first place in district three years straight, including top performance in reserves, sales comp and trade comps.</p> <p>Maintained operational excellence including scheduling, recruitment, and loss prevention.</p> <p>Developed sales into strong repeat customers.</p> <br> <h2>EDUCATION</h2> <h3>Momentum Learning (May 2019 > Present)</h3> <p>Dedicated 12 weeks to learning Full-Stack Engineering practices for building and maintaining websites and web applications in an immersive coding program. </p> <p>Completed daily and weekly technical projects solo, in pair programming and in group setting to learn and gain knowledge around current development tools, techniques and best practices.</p> <br> <h3>Newbury High School</h3> <p>High School Diploma</p> </div> <div class="resumeright"> <div class="rrbox"> <div class="rrtext"> <h1>MATTHEW</h1> <h1>SPEIDEL</h1> </div> </div> <br> <h3>1213 Links Drive</h3> <h3>Morrisville, NC 27560</h3> <h3 id="desktopemail">mattspeidel@gmail.com</h3> <a id="mobileemail" href="mailto:mattspeidel@gmail.com">Email</a> <br> <h2>SKILLS</h2> <br> <h3>Python</h3> <br> <h3>JavaScript</h3> <br> <h3>Django</h3> <br> <h3>HTML</h3> <br> <h3>CSS</h3> <br> <h3>node.js</h3> <br> <h3>vue.js</h3> <br> <h3>Docker</h3> <br> <h3>Git</h3> <br> <h3>Rest API</h3> <br> <h3>SQL</h3> <br> <h3>Agile</h3> </div> </div>` body.parentNode.replaceChild(newBody, body) body = document.querySelector('.mainBody') } aboutLink.addEventListener('click', function () { displayAbout() } ) mattLink.addEventListener('click', function () { displayAbout() } ) projectsLink.addEventListener('click', function () { displayProjects() } ) resumeLink.addEventListener('click', function () { displayResume() } )
import $ from '../../core/renderer'; import { extend } from '../../core/utils/extend'; import messageLocalization from '../../localization/message'; import { getMapFromObject } from './ui.file_manager.common'; import FileManagerDialogBase from './ui.file_manager.dialog.js'; import FileManagerFilesTreeView from './ui.file_manager.files_tree_view'; var FILE_MANAGER_DIALOG_FOLDER_CHOOSER = 'dx-filemanager-dialog-folder-chooser'; var FILE_MANAGER_DIALOG_FOLDER_CHOOSER_POPUP = 'dx-filemanager-dialog-folder-chooser-popup'; class FileManagerFolderChooserDialog extends FileManagerDialogBase { show() { var _this$_filesTreeView; this._resetDialogSelectedDirectory(); (_this$_filesTreeView = this._filesTreeView) === null || _this$_filesTreeView === void 0 ? void 0 : _this$_filesTreeView.refresh(); super.show(); } switchToCopyDialog(targetItemInfos) { this._targetItemInfos = targetItemInfos; this._setTitle(messageLocalization.format('dxFileManager-dialogDirectoryChooserCopyTitle')); this._setButtonText(messageLocalization.format('dxFileManager-dialogDirectoryChooserCopyButtonText')); } switchToMoveDialog(targetItemInfos) { this._targetItemInfos = targetItemInfos; this._setTitle(messageLocalization.format('dxFileManager-dialogDirectoryChooserMoveTitle')); this._setButtonText(messageLocalization.format('dxFileManager-dialogDirectoryChooserMoveButtonText')); } _getDialogOptions() { return extend(super._getDialogOptions(), { contentCssClass: FILE_MANAGER_DIALOG_FOLDER_CHOOSER, popupCssClass: FILE_MANAGER_DIALOG_FOLDER_CHOOSER_POPUP }); } _createContentTemplate(element) { super._createContentTemplate(element); this._filesTreeView = this._createComponent($('<div>'), FileManagerFilesTreeView, { getDirectories: this.option('getDirectories'), getCurrentDirectory: () => this._getDialogSelectedDirectory(), onDirectoryClick: e => this._onFilesTreeViewDirectoryClick(e), onFilesTreeViewContentReady: () => this._toggleUnavailableLocationsDisabled(true) }); this._$contentElement.append(this._filesTreeView.$element()); } _getDialogResult() { var result = this._getDialogSelectedDirectory(); return result ? { folder: result } : result; } _getDefaultOptions() { return extend(super._getDefaultOptions(), { getItems: null }); } _getDialogSelectedDirectory() { return this._selectedDirectoryInfo; } _resetDialogSelectedDirectory() { this._selectedDirectoryInfo = null; } _onFilesTreeViewDirectoryClick(_ref) { var { itemData } = _ref; this._selectedDirectoryInfo = itemData; this._filesTreeView.updateCurrentDirectory(); } _onPopupShown() { this._toggleUnavailableLocationsDisabled(true); super._onPopupShown(); } _onPopupHidden() { this._toggleUnavailableLocationsDisabled(false); super._onPopupHidden(); } _toggleUnavailableLocationsDisabled(isDisabled) { if (!this._filesTreeView) { return; } var locations = this._getLocationsToProcess(isDisabled); this._filesTreeView.toggleDirectoryExpandedStateRecursive(locations.locationsToExpand[0], isDisabled).then(() => this._filesTreeView.toggleDirectoryLineExpandedState(locations.locationsToCollapse, !isDisabled).then(() => locations.locationKeysToDisable.forEach(key => this._filesTreeView.toggleNodeDisabledState(key, isDisabled)))); } _getLocationsToProcess(isDisabled) { var expandLocations = {}; var collapseLocations = {}; this._targetItemInfos.forEach(itemInfo => { if (itemInfo.parentDirectory) { expandLocations[itemInfo.parentDirectory.getInternalKey()] = itemInfo.parentDirectory; } if (itemInfo.fileItem.isDirectory) { collapseLocations[itemInfo.getInternalKey()] = itemInfo; } }); var expandMap = getMapFromObject(expandLocations); var collapseMap = getMapFromObject(collapseLocations); return { locationsToExpand: isDisabled ? expandMap.values : [], locationsToCollapse: isDisabled ? collapseMap.values : [], locationKeysToDisable: expandMap.keys.concat(...collapseMap.keys) }; } } export default FileManagerFolderChooserDialog;
var http = require('http'); var fs = require('fs'); http.createServer(function(request, response) { switch (request.url) { case '/' : getStaticFileContent(response, 'public/home.html', 'text/html'); break; case '/aboutus' : getStaticFileContent(response, 'public/aboutus.html', 'text/html'); break; case '/contactus' : getStaticFileContent(response, 'public/contactus.html', 'text/html'); break; default : response.writeHead(404, {'content-type':'text/plain'}); response.end('404 - Page not found'); break; } }).listen('4054'); function getStaticFileContent(response, filepath, contentType) { fs.readFile(filepath, function(err , data) { if(err) { response.writeHead(500, {'content-type':'text/plain'}); response.end('500 - Internal server error'); } if(data) { response.writeHead(200, {'content-type':'text/html'}); response.end(data); } }) }
module.exports = { 'Demo test' : function (browser) { console.log(browser.launch_url); browser .url(browser.launch_url) .waitForElementVisible('body') .assert.attributeContains('input[type="text"]', 'title', 'Search') .end(); } };
var express = require('express'); var router = express.Router(); const db = require('../database'); var { validateQuery } = require('../utils/validation'); var { getAllAvailableFields } = require('../utils/helpers'); const Category = db.models.Category; router.get('/', async (req, res, next) => { await Category.findAll() .then((result) => { res.status(200).send({ success: true, result: result }); return; }) .catch((error) => { res.status(500).send({ success: false, error: error }); return; }); }); router.post('/add_category', validateQuery(Category.rawAttributes), async (req, res, next) => { params = req.body; fields = getAllAvailableFields(Category.rawAttributes, params); await Category.findOrCreate({ where: { name: params.name }, defaults: fields }) .then((result) => { res.status(200).send({ success: true, created: result[1], result: result[0] }); return; }) .catch((error) => { res.status(500).send({ success: false, error: error }); return; }); }); router.post('/update_category', async (req, res, next) => { params = req.body; category = await Category.findOne({ where: { id: params.category_id } }) .catch((error) => { res.status(500).send({ success: false, error: error }); return; }); if(category) { categoryFields = getAllAvailableFields(Category.rawAttributes, params); await category.update(categoryFields) .then((result) => { res.status(200).send({ success: true, result: result }); return; }) .catch((error) => { res.status(500).send({ success: false, error: error }); return; }); } }); router.post('/delete_category', async (req, res, next) => { params = req.body; await Category.destroy({ where: { id: params.category_id } }) .then((result) => { res.status(200).send({ success: true, result: result}); return; }) .catch((error) => { res.status(500).send({ success: false, error: error }); return; }); }); module.exports = router;
const resolve = require('path').resolve; require('babel-register')( { babelrc: resolve('../.babelrc') } ); require('./boot');
'use strict'; /** * Компонент, который реализует сортируемую таблицу * @param {Array} items - данные, которые нужно отобразить * * Пример одного элемента, описывающего строку таблицы * * { * name: 'Ilia', * age: 25, * salary: '1000', * city: 'Petrozavodsk' * }, * * @constructor */ function SortableTable(items) { /** * @property {Element} - обязательно свойство, которое ссылается на элемент <table> */ this.el = document.createElement('table'); let elThead = document.createElement('thead'); let elTbody = document.createElement('tbody'); let arrTitle = []; this.el.appendChild(elThead); this.el.appendChild(elTbody); for (let item in items) { if (+item === 0) { for (let title in items[item]) { arrTitle.push(title); } } } this.renderHead = function() { let thead = this.el.querySelector('thead'); let row = document.createElement('tr'); thead.appendChild(row); for (let title of arrTitle) { let td = document.createElement('td'); td.innerText = title; row.appendChild(td); } }; this.renderBody = function() { let tbody = this.el.querySelector('tbody'); tbody.innerHTML = ''; for (let item of items) { let row = document.createElement('tr'); for (let param in item) { let td = document.createElement('td'); td.innerText = item[param]; row.appendChild(td); } tbody.appendChild(row); } }; this.renderHead(); this.renderBody(); /** * Метод выполняет сортировку таблицы * @param {number} column - номер колонки, по которой нужно выполнить сортировку (отсчет начинается от 0) * @param {boolean} desc - признак того, что сортировка должна идти в обратном порядке */ this.sort = function (column, desc = false) { let param = arrTitle[column]; let order = 1; if (desc) order = order * -1; items.sort(function(a, b) { return a[param] > b[param] ? order : order * -1; }); this.renderBody(); }; }
// Helper methods for swift output var SwiftUtils = { importe: function(framework) { return "import " + framework; }, extension: function(extension) { return "extension " + extension + " {"; }, struct: function(struct) { return "struct " + struct + " {"; }, methodSignature: function(name) { return "static func " + SwiftUtils.camelize(SwiftUtils.cleanSymbol(name)) + "() {"; }, methodSignature: function(name, output) { return "static func " + SwiftUtils.camelize(SwiftUtils.cleanSymbol(name)) + "() -> " + output + " {"; }, uiColor: function(color) { return "UIColor(red: " + color.red() + ", green: " + color.green() + ", blue: " + color.blue() + ", alpha: " + color.alpha() + ")"; }, uiColorWithNSColor: function(nsColor) { return "UIColor(red: " + nsColor.redComponent() + ", green: " + nsColor.greenComponent() + ", blue: " + nsColor.blueComponent() + ", alpha: " + nsColor.alphaComponent() + ")"; }, varColor: function(color, tabIncr) { return tabIncr + "let color = " + SwiftUtils.uiColorWithNSColor(color) + SwiftUtils.newLine(); }, varDefinedColor: function(colorName, tabIncr) { return tabIncr + "let color = UIColor." + SwiftUtils.camelize(SwiftUtils.cleanSymbol(colorName)) + "Color()" + SwiftUtils.newLine(); }, varKern: function(kern, tabIncr) { var nonNullKern = kern == null ? "0" : kern; return tabIncr + "let kern = " + nonNullKern + SwiftUtils.newLine(); }, varFont: function(name, size, tabIncr) { var output = ""; output += tabIncr + "guard let font = UIFont(name: \"" + name + "\", size: " + size + ") else {" + SwiftUtils.newLine(); output += tabIncr + SwiftUtils.tab() + "fatalError(\"Can't load font\")" + SwiftUtils.newLine(); output += tabIncr + "}" + SwiftUtils.newLine(); return output; }, varParagraph: function(paragraph, tabIncr) { var output = ""; output += tabIncr; output += "let paragraph = NSMutableParagraphStyle()"; output += SwiftUtils.newLine(); output += tabIncr; output += "paragraph.minimumLineHeight = " + paragraph.minimumLineHeight(); output += SwiftUtils.newLine(); output += tabIncr; output += "paragraph.alignment = " + SwiftUtils.nsTextAlignment(paragraph.alignment()); output += SwiftUtils.newLine(); output += tabIncr; output += "paragraph.paragraphSpacing = " + paragraph.paragraphSpacing(); output += SwiftUtils.newLine(); return output; }, nsTextAlignment: function(value) { var output = ""; if (value == 0) { output = "Left"; } else if (value == 2) { output = "Center" } else if (value == 1) { output = "Right" } else if (value == 3) { output = "Justified" } else if (value == 4) { output = "Natural" } return "NSTextAlignment." + output; }, returnAttributes: function(tabIncr, needParagraph) { var output = ""; output += tabIncr; output += "return [NSFontAttributeName: font,"; output += SwiftUtils.newLine(); output += tabIncr + SwiftUtils.tab(); output += "NSKernAttributeName: kern,"; output += SwiftUtils.newLine(); output += tabIncr + SwiftUtils.tab(); output += "NSForegroundColorAttributeName: color"; if (needParagraph) { output += ","; output += SwiftUtils.newLine(); output += tabIncr + SwiftUtils.tab(); output += "NSParagraphStyleAttributeName: paragraph," } output += SwiftUtils.newLine(); output += tabIncr; output += "]"; output += SwiftUtils.newLine(); return output; }, camelize: function(name) { return name.replace(/(?:^\w|[A-Z]|\b\w)/g, function(letter, index) { return index == 0 ? letter.toLowerCase() : letter.toUpperCase(); }).replace(/\s+/g, ''); }, cleanSymbol: function(str) { return str.replace(/[^\w\s]/gi, ''); }, tab: function() { return "\t"; }, newLine: function() { return "\r\n"; }, };
$(document).ready(() => { $('.giffy').hide() $('.hideMe').hide() $('.clickMe').click(() => { $('.giffy').fadeIn('slow') $('.clickMe').hide() $('.hideMe').show() }) $('.hideMe').click(() => { $('.giffy').hide() $('.hideMe').hide() $('.clickMe').show() }) })
import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import TextField from "@material-ui/core/TextField"; import Button from "@material-ui/core/Button"; import InputMask from "react-input-mask"; const useStyles = makeStyles((theme) => ({ root: { "& > *": { margin: theme.spacing(1), width: "25ch", }, }, })); export default function BasicTextFields() { const classes = useStyles(); return ( <form className={classes.root} noValidate autoComplete="off"> <TextField id="outlined-basic" label="Имя" variant="outlined" /> <InputMask mask="(+380)99-999-99-99" // value={props.value} // onChange={props.onChange} > {(inputProps) => ( <TextField id="outlined-basic" label="Телефон" type="tel" variant="outlined" /> )} </InputMask> <Button variant="contained" color="primary"> Нужна консультация </Button> </form> ); }
module.exports = (data = {}) => { const { pid, uuid, kv, campaign, creative, } = data; const cid = campaign ? campaign.id : undefined; const cre = creative ? creative.id : undefined; return { uuid, pid, cid, cre, kv, }; };
/** * Created by user on 31.03.15. */ 'use strict'; angular.module('when-scrolled-directive', []).directive('crmWhenScrolled', function() { return function(scope, elm, attr) { var raw = elm[0]; elm.bind('scroll', function() { if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) { scope.$apply(attr.crmWhenScrolled); } }); }; });
define([ './mixins/sync', './mixins/schema', './mixins/getter', './mixins/setter', './mixins/getterCreator', './mixins/lifeCycle', './mixins/validation', './mixins/navigation', './../shared/actions_mixin', './../shared/error_mixin', './../shared/classShared_mixin' ], function ( sync, schema, getter, setter, getterCreator, lifeCycle, validation, navigation, actions_mixin, error_mixin, classShared_mixin ) { 'use strict'; var SagaModel = require('sgc-model').Model; var clazz = _.extend({}, classShared_mixin(SagaModel)); var RemoteModel = SagaModel.extend({ constructor: function(attr, options){ options = _.defaults(options||{}, { parent: null, path: null }); this.configureSchema(); var res = SagaModel.prototype.constructor.apply(this, arguments); this._path = options.path; this._parent = options.parent; return res; }, idAttribute: '_id' }, clazz); _.extend(RemoteModel.prototype, sync(SagaModel)); _.extend(RemoteModel.prototype, schema(SagaModel)); _.extend(RemoteModel.prototype, getter(SagaModel)); _.extend(RemoteModel.prototype, setter(SagaModel)); _.extend(RemoteModel.prototype, getterCreator(SagaModel)); _.extend(RemoteModel.prototype, lifeCycle(SagaModel)); _.extend(RemoteModel.prototype, validation(SagaModel)); _.extend(RemoteModel.prototype, navigation(SagaModel)); _.extend(RemoteModel.prototype, actions_mixin(SagaModel)); _.extend(RemoteModel.prototype, error_mixin(SagaModel)); return RemoteModel; });
$(function(){ var ajax_url = 'http://serv1.dca.tw:3000/API/bootcamp/articles/'; //顯示資料 (read) $.ajax({ url: ajax_url, type: 'GET', error: function(){ console.log('error'); }, success: function(e){ for(var i=0; i<e.length; i++) { $(".result").append( '<div class="full-msg" data-id="'+ e[i]._id +'">' + '<div>姓名:'+ e[i].username +'<span class="del">刪除留言</span></div>' + '<div>網站:'+ e[i].url +'</div>' + '<div>電子郵件:'+ e[i].email +'</div>' + '<div>'+ e[i]. message +'</div>' + '</div>' ); }; } }); //刪除資料(delete) $(".result").on('click', '.del', function(){ var fullMsg = $(this).closest('.full-msg'), delID = fullMsg.data('id'); $.ajax({ url: ajax_url + delID, type: 'DELETE', error: function() { console.log('error'); }, success: function(e){ console.log(e); fullMsg.fadeOut(800, function(){ $(this).html('留言已刪除').fadeIn(800); }); } }); }) });
import React, { Component } from 'react'; import { Page, Navbar, List, ListItem, ListInput, Toggle, BlockTitle, Row, Button, Range, Block, Icon, Fab } from 'framework7-react'; import { dict } from '../../Dict'; import ModelStore from "../../stores/ModelStore"; import * as MyActions from "../../actions/MyActions"; import GroupShow from "../../containers/groups/show" export default class Layout extends Component { constructor() { super(); this.getInstance = this.getInstance.bind(this); this.submit = this.submit.bind(this); this.handleChangeValue = this.handleChangeValue.bind(this); this.state = { token: window.localStorage.getItem('token'), group: null, id: null, user_id: null, } } componentWillMount() { ModelStore.on("got_instance", this.getInstance); ModelStore.on("set_instance", this.getInstance); ModelStore.on("deleted_instance", this.getInstance); } componentWillUnmount() { ModelStore.removeListener("got_instance", this.getInstance); ModelStore.removeListener("set_instance", this.getInstance); ModelStore.removeListener("deleted_instance", this.getInstance); } componentDidMount() { MyActions.getInstance('groups', this.$f7route.params['groupId'], this.state.token); } getInstance() { var group = ModelStore.getIntance() var klass = ModelStore.getKlass() if (group && klass === 'Group') { this.setState({ group: group, id: group.id, }); } this.$$('.btn').show(); } submit() { this.$$('.btn').hide(); this.$$('.btn-notice').text(dict.submitting); var data = { group_id: this.state.id, user_id: this.state.user_id } MyActions.setInstance('users/assignments', data, this.state.token); } handleChangeValue(obj) { this.setState(obj); } fab() { if (this.state.group) { return ( <Fab href={"/groups/" + this.state.group.id + "/edit"} target="#main-view" position="left-bottom" slot="fixed" color="lime"> <Icon ios="f7:edit" aurora="f7:edit" md="material:edit"></Icon> <Icon ios="f7:close" aurora="f7:close" md="material:close"></Icon> </Fab> ) } } render() { const { group } = this.state; return ( <Page> <Navbar title={dict.groups} backLink={dict.back} /> <BlockTitle></BlockTitle> {this.fab()} <GroupShow group={group} submit={this.submit} handleChange={this.handleChangeValue} /> </Page> ); } }
const colors = { aqua: '#1fbba6', aquaDark: '#189786', blue: '#279ddf', blueDark: '#0b3670', green: '#17a84b', greenDark: '#0f692f', red: '#ed1c24', redDarker: '#9612170', yellow: '#f6c92f', yellowDark: '#9b7f1e', orange: '#fbb300', orangeDarker: '#a14400', pink: '#ee3c80', pinkDarkest: '#972651', Violet: '#673189', blueFb: '#3b5998', blueDarker: '#263f70', blueLight: '#00c0ff', blueDarkBtn: '#008fa4', greenLight: '#73bf43', greenDarkBtn: '#5fa235', redLight: '#ee3e36', redDark: '#b32923', orangeLight: '#ff8400', OrangeDark: '#b75f01', pinkDark: '#f21f43', pinkDarker: '#a30f28', base: '#ffffff', whiteGray: '#f5f5f5', grayLighter: '#ececec', grayDark: '#acacac', gray: '#646464', grayBg: '#434851', grayDarker: '#333333', black: '#000000', petroleum: '#3f454e' }; const colorsBase = Object.assign({}, colors, { // fonts fontBrandom: '"Brandon", Helvetica, Arial, sans-serif', fontMikado: '"Mikado Black", Arial, sans-serif;', fontSizeXS: '1rem', fontSizeS: '1.7rem', fontSizeM: '30px', fontSizeL: '3.1rem', // brand primary: colors.blue, accent: colors.orange, success: colors.greenLight, warning: colors.orangeLight, danger: colors.redLight, info: colors.blueLight }); export default colorsBase;
function correo() { console.log("Entre"); var nombre = document.getElementById('username').value; var email = document.getElementById('email').value; var reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var subject = document.getElementById('subject').value; var phone = document.getElementById('phone').value; var message = document.getElementById('message').value; if(nombre == null || nombre.length == 0 || /^\s+$/.test(nombre)){ /*alert("Escribe tu Nombre correctamente");*/ document.getElementById("username").focus(); Swal.fire({ title: '¡Error!', text: 'Escribe tu nombre correctamente', icon: 'error', confirmButtonText: 'Aceptar' }) document.getElementById("username").focus(); return false; } else if(!(reg.test(email))){ // alert("Escribe un correo correcto correctamente"); document.getElementById("email").focus(); Swal.fire({ title: '¡Error!', text: 'Escribe tu email correctamente', icon: 'error', confirmButtonText: 'Aceptar' }) document.getElementById("email").focus(); return false; }else if(subject == null || subject.length == 0 || /^\s+$/.test(subject)){ // alert("Escribe el Asunto"); document.getElementById("subject").focus(); Swal.fire({ title: '¡Error!', text: 'Escribe el nombre de tu empresa correctamente', icon: 'error', confirmButtonText: 'Aceptar' }) document.getElementById("subject").focus(); return false; }else if(!(/^\d{10}$/.test(phone))){ // alert("Escribe un número válido de WhatsApp de 10 caracteres"); document.getElementById("phone").focus(); Swal.fire({ title: '¡Error!', text: 'Escribe un número válido de WhatsApp de 10 caracteres', icon: 'error', confirmButtonText: 'Aceptar' }) document.getElementById("phone").focus(); return false; } if(message == null || message.length == 0 || /^\s+$/.test(message)){ // alert("Escribe tu Mensaje"); document.getElementById("message").focus(); Swal.fire({ title: '¡Error!', text: 'Escribe tu Mensaje correctamente', icon: 'error', confirmButtonText: 'Aceptar' }) document.getElementById("message").focus(); return false; }else Swal.fire({ position: 'top-middle', icon: 'success', title: 'Su mensaje ha sido enviado correctamente', showConfirmButton: false, timer: 1500 }); const data = new URLSearchParams([['nombre', nombre], ['email', email], ['phone', phone], ['subject', subject], ['message', message]]); document.getElementById('username').value = ''; document.getElementById('email').value = ''; document.getElementById('phone').value = ''; document.getElementById('subject').value = ''; document.getElementById('message').value = ''; fetch('https://gruporyc.com.mx:8081/send-email', { method: 'POST', body: data }) .then(function(response) { if(response.ok) { // alert('Su mensaje ha sido enviado. Nos contactaremos con usted por medio de su numero o correo electronico, muchas gracias por la confianza.'); return response.text() } else { throw 'Error en la llamada Ajax'; } }) .catch(function(err) { }); } /*funcion 2*/ function correo2() { console.log("Entre"); var nombre = document.getElementById('username2').value; var email = document.getElementById('email2').value; var reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var subject = document.getElementById('subject2').value; var phone = document.getElementById('phone2').value; var message = document.getElementById('message2').value; if(nombre == null || nombre.length == 0 || /^\s+$/.test(nombre)){ /*alert("Escribe tu Nombre correctamente");*/ document.getElementById("username").focus(); Swal.fire({ title: '¡Error!', text: 'Escribe tu nombre correctamente', icon: 'error', confirmButtonText: 'Aceptar' }) document.getElementById("username").focus(); return false; } else if(!(reg.test(email))){ // alert("Escribe un correo correcto correctamente"); document.getElementById("email").focus(); Swal.fire({ title: '¡Error!', text: 'Escribe tu email correctamente', icon: 'error', confirmButtonText: 'Aceptar' }) document.getElementById("email").focus(); return false; }else if(subject == null || subject.length == 0 || /^\s+$/.test(subject)){ // alert("Escribe el Asunto"); document.getElementById("subject").focus(); Swal.fire({ title: '¡Error!', text: 'Escribe el nombre de tu empresa correctamente', icon: 'error', confirmButtonText: 'Aceptar' }) document.getElementById("subject").focus(); return false; }else if(!(/^\d{10}$/.test(phone))){ // alert("Escribe un número válido de WhatsApp de 10 caracteres"); document.getElementById("phone").focus(); Swal.fire({ title: '¡Error!', text: 'Escribe un número válido de WhatsApp de 10 caracteres', icon: 'error', confirmButtonText: 'Aceptar' }) document.getElementById("phone").focus(); return false; } if(message == null || message.length == 0 || /^\s+$/.test(message)){ // alert("Escribe tu Mensaje"); document.getElementById("message").focus(); Swal.fire({ title: '¡Error!', text: 'Escribe tu Mensaje correctamente', icon: 'error', confirmButtonText: 'Aceptar' }) document.getElementById("message").focus(); return false; }else Swal.fire({ position: 'top-middle', icon: 'success', title: 'Su mensaje ha sido enviado correctamente', showConfirmButton: false, timer: 1500 }); const data = new URLSearchParams([['nombre', nombre], ['email', email], ['phone', phone], ['subject', subject], ['message', message]]); document.getElementById('username').value = ''; document.getElementById('email').value = ''; document.getElementById('phone').value = ''; document.getElementById('subject').value = ''; document.getElementById('message').value = ''; fetch('https://gruporyc.com.mx:8081/send-email', { method: 'POST', body: data }) .then(function(response) { if(response.ok) { // alert('Su mensaje ha sido enviado. Nos contactaremos con usted por medio de su numero o correo electronico, muchas gracias por la confianza.'); return response.text() } else { throw 'Error en la llamada Ajax'; } }) .catch(function(err) { }); }
/** * 初始化快递公司设置详情对话框 */ var MdLogisticsCompanyInfoDlg = { mdLogisticsCompanyInfoData : {} }; /** * 清除数据 */ MdLogisticsCompanyInfoDlg.clearData = function() { this.mdLogisticsCompanyInfoData = {}; } /** * 设置对话框中的数据 * * @param key 数据的名称 * @param val 数据的具体值 */ MdLogisticsCompanyInfoDlg.set = function(key, val) { this.mdLogisticsCompanyInfoData[key] = (typeof val == "undefined") ? $("#" + key).val() : val; return this; } /** * 设置对话框中的数据 * * @param key 数据的名称 * @param val 数据的具体值 */ MdLogisticsCompanyInfoDlg.get = function(key) { return $("#" + key).val(); } /** * 关闭此对话框 */ MdLogisticsCompanyInfoDlg.close = function() { parent.layer.close(window.parent.MdLogisticsCompany.layerIndex); } /** * 收集数据 */ MdLogisticsCompanyInfoDlg.collectData = function() { this .set('id') .set('code') .set('name') .set('createTime') .set('createdBy') .set('updateTime') .set('updatedBy') .set('isDeleted') .set('tenantId') .set('logisticsCodeRule'); } /** * 提交添加 */ MdLogisticsCompanyInfoDlg.addSubmit = function() { this.clearData(); this.collectData(); //提交信息 var ajax = new $ax(Feng.ctxPath + "/mdLogisticsCompany/add", function(data){ Feng.success("添加成功!"); window.parent.MdLogisticsCompany.table.refresh(); MdLogisticsCompanyInfoDlg.close(); },function(data){ Feng.error("添加失败!" + data.responseJSON.message + "!"); }); ajax.set(this.mdLogisticsCompanyInfoData); ajax.start(); } /** * 提交修改 */ MdLogisticsCompanyInfoDlg.editSubmit = function() { this.clearData(); this.collectData(); //提交信息 var ajax = new $ax(Feng.ctxPath + "/mdLogisticsCompany/update", function(data){ Feng.success("修改成功!"); window.parent.MdLogisticsCompany.table.refresh(); MdLogisticsCompanyInfoDlg.close(); },function(data){ Feng.error("修改失败!" + data.responseJSON.message + "!"); }); ajax.set(this.mdLogisticsCompanyInfoData); ajax.start(); } $(function() { });
const findLast = (arr, fn) => arr.filter(fn).slice(-1)[0]; module.exports = findLast;
function Pool() { var setting = { width: 12, height: 20, cellSize: 20 }; var $pool; var grid = []; var cellStatus = { empty: 0, block: 1, ice: 2 }; var clearCounter = 0; var clear100 = 10 var clearLines = function() { var lines = 0; for (var i = 0; i < grid.length; i++) { for (var j = 0; j < grid[i].length; j++) { if (grid[i][j].status !== cellStatus.ice) { break; } } if (j === grid[i].length) { if (++clearCounter % clear100 === 0) { msgCenter.postMsg('pool.clear100'); } lines++; var line = []; for (var j = 0; j < game.poolWidth; j++) { $('#' + grid[i][j].id).hide(400, function() { $(this).remove(); }); line.push({ status: cellStatus.empty }); } grid.splice(i, 1); grid.unshift(line); for (var j = 0; j <= i; j++) { for (var k = 0; k < grid[j].length; k++) { if (grid[j][k].id) { $('#' + grid[j][k].id).css({ top: j * game.cellSize, left: k * game.cellSize }); } } } } } msgCenter.postMsg('score.clbonus', lines); }; var checkFull = function() { for (var i = 0; i < game.poolWidth; i++) { if (grid[0][i].status === cellStatus.ice) { return true; } } return false; }; var init = function() { for (var i = 0; i < game.poolHeight; i++) { var line = []; for (var j = 0; j < game.poolWidth; j++) { line.push({ status: cellStatus.empty }); } grid.push(line); } $pool = $('#pool'); $pool.width(game.poolWidth * game.cellSize).height(game.poolHeight * game.cellSize); }; var reset = function() { for (var i = 0; i < grid.length; i++) { for (var j = 0; j < grid[i].length; j++) { grid[i][j].status = cellStatus.empty; grid[i][j].id = null; } } clearCounter = 0; $pool.empty(); }; var checkCell = function(pos, cells, cb) { for (var i = 0; i < cells.length; i++) { if (cells[i][0] + pos[0] >= game.poolHeight || cells[i][1] + pos[1] < 0 || cells[i][1] + pos[1] >= game.poolWidth || (cells[i][0] + pos[0] >= 0 && grid[cells[i][0] + pos[0]][cells[i][1] + pos[1]].status !== cellStatus.empty)) { return cb(false); } } cb(true); }; var putIn = function(id, pos, cells) { var $block = $('<div class="block"></div>').attr('id', id).css({ top: pos[0] * game.cellSize, left: pos[1] * game.cellSize }).appendTo($pool); for (var i = 0; i < cells.length; i++) { $('<div class="cell"></div>').attr('id', id + '_' + i).width(game.cellSize).height(game.cellSize).css({ top: cells[i][0] * game.cellSize, left: cells[i][1] * game.cellSize }).appendTo($block); } }; var setPosition = function(blockId, pos) { $('#' + blockId).css({ top: pos[0] * game.cellSize, left: pos[1] * game.cellSize }); }; var setDirection = function(blockId, cells) { var $block = $('#' + blockId); for (var i = 0; i < cells.length; i++) { $block.find('.cell:eq(' + i + ')').css({ top: cells[i][0] * game.cellSize, left: cells[i][1] * game.cellSize }); } }; var freezeBlock = function(blockId, pos, cells) { var $block = $('#' + blockId); var $cells = $($block.remove().html()).appendTo($pool); for (var i = 0; i < $cells.length; i++) { var r = pos[0] + cells[i][0]; var c = pos[1] + cells[i][1]; var id = $($cells[i]).css({ 'top': r * game.cellSize, 'left': c * game.cellSize }).addClass('ice').attr('id'); if (r >= 0) { grid[r][c].status = cellStatus.ice; grid[r][c].id = id; } } clearLines(); if (!checkFull()) { msgCenter.postMsg('block.neednew'); } else { msgCenter.postMsg('game.over'); } }; init(); msgCenter.regHandler('pool.reset', null, reset) .regHandler('pool.checkcell', null, function(params) { checkCell(params.pos, params.cells, params.cb); }).regHandler('block.created', null, function(params) { putIn(params.id, params.pos, params.cells); }).regHandler('block.freeze', null, function(params) { freezeBlock(params.id, params.pos, params.cells); }).regHandler('block.setpos', null, function(params) { setPosition(params.id, params.pos); }).regHandler('block.setdir', null, function(params) { setDirection(params.id, params.cells); }); }
$(document).ready(function() { jQuery('input[default]') .focus(function() { if ($(this).val()==$(this).attr("default")) { $(this).val(""); $(this).removeClass('empty'); } }) .blur( function() { if ($(this).val()=="") { $(this).val($(this).attr("default")); $(this).addClass('empty'); } }).blur(); }); function category_hoverrow_item(groupid,itemid,imagehtml,title) { var photofade = .50; jQuery('<div/>', { id: 'item_'+itemid, class: 'item', html: '<div class="itemimage">'+imagehtml+'</div><div class="itemtitle">'+title+'</div>', css: { 'float': 'left','cursor':'pointer','position':'relative' } }) .mouseover(function() { if(jQuery('#items_'+groupid).data('selected')!=itemid) { jQuery('#items_'+groupid+' .item').removeClass('selected'); jQuery('#items_'+groupid+' .item .itemtitle').show(); jQuery(this).addClass('selected'); jQuery('#items_'+groupid+' #item_'+itemid+' .itemtitle').hide(); jQuery('#descs_'+groupid+' .desc').hide(); jQuery('#desc_'+itemid).fadeToggle(300,'swing'); jQuery('#items_'+groupid).data('selected',itemid); } }) .appendTo('#items_'+groupid); } function category_hoverrow_desc(groupid,itemid,html,title) { jQuery('<div/>', { id: 'desc_'+itemid, html: '<h2>'+title+'</h2><br />'+html, class: 'desc', css: { 'display': 'none' } }) .appendTo('#descs_'+groupid); }
/**@jsx jsx */ import { jsx} from 'theme-ui' import Img from 'gatsby-image'; import { graphql, StaticQuery } from 'gatsby'; const FloatingHead = () => ( <StaticQuery query={graphql` query { site { siteMetadata { minibio } } author: file(relativePath: { regex: "/raphadeluca-avatar.png/" }) { childImageSharp { fluid(maxWidth: 690) { ...GatsbyImageSharpFluid } } } } `} render={data => ( <div sx={{ display: ['none', 'block'], fontSize: 1, textAlign: 'center', }}> <Img alt="Raphaël De Luca." fluid={data.author.childImageSharp.fluid} sx={{ display: 'block', borderRadius: '50%', mx: 'auto', maxWidth: '120px', border: '2px solid #ff7f00', }} /> <p dangerouslySetInnerHTML={{ __html: data.site.siteMetadata.minibio, }} /> </div> )} /> ); export default FloatingHead;
// @flow import { NativeModules } from 'react-native'; const noop: (x: *) => void = () => {}; const { addPass = noop } = NativeModules.RNKiwiAppleWalletManager || {}; export default { addPass };
import React, { Component, useState, useEffect, } from 'react' import { View, Text, StyleSheet, FlatList, TouchableOpacity, } from 'react-native' import { Divider, FAB, Appbar, } from 'react-native-paper' import firebase from './../../services/FirebaseConection' export default function Entresafra({ route, navigation }) { const [entresafra, setEntresafra] = useState() var uid = route.params useEffect(() => { firebase.database().ref(`users/${uid}/entresafra`).on('value', (snapshot) => { const entresafras = snapshot.val() const entresafrasList = [] for (let id in entresafras) { entresafrasList.push(entresafras[id]) } console.log(entresafrasList) setEntresafra(entresafrasList) }) }, []) function Entresafra({ descriptionEntresafra, descriptionCulture, dateStartEntresafra, dateEndEntresafra, observationEntresafra, dateStartCulture, observationCulture, coordinates }) { return ( <TouchableOpacity style={styles.item} onPress={() => navigation.navigate('InfoEntresafra', { uid, descriptionEntresafra, descriptionCulture, dateStartEntresafra, dateEndEntresafra, observationEntresafra, dateStartCulture, observationCulture, coordinates })}> <Text style={styles.textName}> {descriptionEntresafra}</Text> <Text style={styles.textDescription}> Cultura: {descriptionCulture}</Text> <Divider style={{ backgroundColor: '#c2c6ca' }} /> </TouchableOpacity> ) } return ( <View style={styles.background}> <View style={styles.appBar}> <Appbar.Header style={styles.appBarStyle}> <Appbar.BackAction color="#ffff" onPress={() => navigation.navigate('Home')} /> <Appbar.Content title="Minhas entresafras" color='#ffff' /> </Appbar.Header> </View> <View style={{ flex: 1, backgroundColor: '#fff' }}> <FlatList data={entresafra} keyExtractor={(item) => item.key} renderItem={({ item }) => <Entresafra descriptionEntresafra={item.descriptionEntresafra} descriptionCulture={item.descriptionCulture} dateStartEntresafra={item.dateStartEntresafra} dateEndEntresafra={item.dateEndEntresafra} observationEntresafra={item.observationEntresafra} dateStartCulture={item.dateStartCulture} observationCulture={item.observationCulture} coordinates={item.polygon} />} > </FlatList> <FAB style={styles.fab} icon='plus' color='#ffff' onPress={() => navigation.navigate('NewEntresafra')} /> </View> </View> ) } const styles = StyleSheet.create({ background: { flex: 1, width: '100%', justifyContent: 'center', backgroundColor: '#FFFF' }, fab: { position: 'absolute', margin: 16, right: 0, bottom: 0, backgroundColor: '#7ed957' }, formContainer: { flex: 1, backgroundColor: '#FFFF', width: '87%', height: '90%', }, appBar: { backgroundColor: "#FFFF", height: '10%', }, appBarStyle: { backgroundColor: "#7ed957", }, item: { paddingBottom: 15, marginVertical: 2, marginHorizontal: 18, backgroundColor: '#ffff', }, textName: { color: '#3d3935', fontSize: 22, marginTop: 8, fontFamily: 'sans-serif' }, textDescription: { color: '#3d3935', fontSize: 18, fontFamily: 'sans-serif', marginTop: 5, marginLeft: 3, marginBottom: 15 }, viewInfo: { backgroundColor: '#FFFF', width: '95%', height: '100%', }, })
//var root_url = "http://demo9239551.mockable.io" var root_url = "." $("a[href='#wifisettings']").on("shown.bs.tab",function(){ $.get(root_url+"/wifi","").done(callback_get_wifi_settings).fail(function(data){alert('GetWiFiFailed: '+JSON.stringify(data))}); }); $("#form_mqtt_settings#mqtt_showpassword").click(function(){ alert ("TODO show password"); }) $('a[href="#seedata"]').on("shown.bs.tab",fillDataTab()) $("#form_wifi_settings").submit(function(e){ //e.PreventDefault(); var url = root_url+'/wifi' // if ($("#wifi_ssid").val() == "-1"){ // $("#group-ssid").removeClass("success").removeClass("warning").addClass("error"); // return; // } $.post(url, $(this).serialize()) .done(function(data){ alert("Set wifi settings OK. " + JSON.stringify(data)); }) .fail(function(data){ alert("Set wifi settings Failed. " + JSON.stringify(data)); }) }); $("#form_mqtt_settings").submit(function(e){ var url = root_url+'/mqtt' $.post(url,$(this).serialize()) .done(function(data){ alert("Set mqtt settings OK. " + JSON.stringify(data)); }) .fail(function(data){ alert("Set mqtt settings Failed. " + JSON.stringify(data)); }) //e.PreventDefaults(); }); function saveDS18Name(e) { alert(e.parentNode.parentNode.parentNode.parentNode.childNodes[2].textContent); var url = root_url+'/ds18b20/alias' var params = { "id":e.parentNode.parentNode.parentNode.parentNode.childNodes[2].textContent, "name": e.parentNode.parentNode.childNodes[1].value } //alert(JSON.stringify(params)) $.get(url,params) .done(function(data){ alert("Set Alias settings OK. " + JSON.stringify(data)); }) .fail(function(data){ alert("Set Alias settings Failed. " + JSON.stringify(data)); }) } $("#form_ds18b20_setname").submit(function(e){ var url = root_url+'/ds18b20/alias' var params = $(this).serialize() alert(JSON.stringify(params)) $.get(url,params) .done(function(data){ alert("Set mqtt settings OK. " + JSON.stringify(data)); }) .fail(function(data){ alert("Set mqtt settings Failed. " + JSON.stringify(data)); }) //e.PreventDefaults(); }); function callback_get_wifi_settings(data) { if (typeof(data) == "string"){ data = JSON.parse(data) } //alert(JSON.stringify(data)); var selSSID = $("#wifi_ssid"); $.each(data.networks, function (index, name){selSSID.append('<option value="'+name+'">'+name+'</option>')}); } function getDS18B20Alias(id) { return "todo" } function fillDataTab() { var dataTab = $("#seedata") var datajson; $.get(root_url+"/data").done(function (data){ //dataTab.text(JSON.stringify(data)); //alert(data); if (typeof(data) == "string"){ data = JSON.parse(data) } var table = $('#seedata #tblData'); table.children("tr").remove(); table.append('<tr><th>Name</th><th>Celsuim</th><th>ID</th></tr>') ds = data['DS18B20']; for (var id in ds) { var tr = $("<tr>"); tr.append("<td>") var td = tr.find("td") td.append('<div class="input-group mb-3">\ <input type="text" id="name" class="form-control" placeholder="No name yet" aria-label="Name" aria-describedby="basic-addon2">\ <div class="input-group-append">\ <button class="save btn btn-outline-secondary" type="button">Save</button>\ </div>\ </div>'); var input = td.find("#name") input.val( ds[id].name?ds[id].name:""); input.id = id; var btnSave = td.find(":button"); btnSave.removeAttr("onclick") btnSave.attr("onclick","saveDS18Name(this)"); var td_celsium = $("<td>",{"text": ds[id].celsium}); tr.append(td_celsium) var td_id = $("<td>",{"text":id}) tr.append(td_id) table.append(tr); } }).fail(function(a,b,c){alert ("fail " + b)}) //dataTab.append(); } // Example starter JavaScript for disabling form submissions if there are invalid fields (function() { 'use strict'; window.addEventListener('load', function() { // Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.getElementsByClassName('needs-validation'); // Loop over them and prevent submission var validation = Array.prototype.filter.call(forms, function(form) { form.addEventListener('submit', function(event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add('was-validated'); }, false); }); }, false); })();
const path = require("path"); const resolve = dir => path.join(__dirname, dir); // const name = require("./package.json").name; module.exports = { publicPath: process.env.NODE_ENV === "production" ? process.env.VUE_APP_CONTEXT_PATH : "/", outputDir: `dist/${process.env.VUE_APP_MODENAME}`, assetsDir: "assets", productionSourceMap: false, lintOnSave: true, css: { extract: true, // 是否使用css分離外掛 ExtractTextPlugin sourceMap: false, // 開啟 CSS source maps?是否在構建樣式地圖,false將提高構建速度 loaderOptions: { // css預設器配置項 scss: { prependData: ` @import "~@/assets/helpers/_var.scss"; @import "~@/assets/helpers/_mixins.scss"; ` } } }, devServer: { port: 8002, open: true }, configureWebpack: config => { // if (IS_PROD) { config.optimization = { splitChunks: { // 表示選擇哪些 chunks 進行分割,可選值有:async,initial和all chunks: "all", // 表示新分離開出的chunk必須大於等於minSize,默認為30000,約30kb。 minSize: 30000, // 表示一個模塊至少應被minChunks個chunk所包含才能分割。默認為1。 minChunks: 1, // 表示按需加載文件時,並行請求的最大數目。默認為5。 maxAsyncRequests: 5, // 表示加載入口文件時,並行請求的最大數目。默認為3。 maxInitialRequests: 3, // 表示拆分出的chunk的名稱連接符,默認為~ automaticNameDelimiter: "-", cacheGroups: { bootstrap: { name: "bootstrap", test: /[\\/]node_modules[\\/]bootstrap[\\/]/, priority: 10 }, jquery: { name: "jquery", test: /[\\/]node_modules[\\/]jquery[\\/]/, priority: 10 } } } }; // } }, chainWebpack: config => { config.resolve.alias .set("@", resolve("src")) .set("@assets", resolve("src/assets")) .set("@components", resolve("src/components")) .set("@layout", resolve("src/components/layout")) .set("@views", resolve("src/components/views")) .set("@static", resolve("src/static")); config.module.rule("eslint").use("eslint-loader"); } };
'use strict'; var should = require('should'), request = require('supertest'), app = require('../../server'), mongoose = require('mongoose'), User = mongoose.model('User'), Film = mongoose.model('Film'), agent = request.agent(app); /** * Globals */ var credentials, user, film; /** * Film routes tests */ xdescribe('Film CRUD tests', function() { beforeEach(function(done) { // Create user credentials credentials = { username: 'username', password: 'password' }; // Create a new user user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: credentials.username, password: credentials.password, provider: 'local' }); // Save a user to the test db and create new Film user.save(function() { film = { name: 'Film Name' }; done(); }); }); it('should be able to save Film instance if logged in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Film agent.post('/films') .send(film) .expect(200) .end(function(filmSaveErr, filmSaveRes) { // Handle Film save error if (filmSaveErr) done(filmSaveErr); // Get a list of Films agent.get('/films') .end(function(filmsGetErr, filmsGetRes) { // Handle Film save error if (filmsGetErr) done(filmsGetErr); // Get Films list var films = filmsGetRes.body; // Set assertions (films[0].user._id).should.equal(userId); (films[0].name).should.match('Film Name'); // Call the assertion callback done(); }); }); }); }); it('should not be able to save Film instance if not logged in', function(done) { agent.post('/films') .send(film) .expect(401) .end(function(filmSaveErr, filmSaveRes) { // Call the assertion callback done(filmSaveErr); }); }); it('should not be able to save Film instance if no name is provided', function(done) { // Invalidate name field film.name = ''; agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Film agent.post('/films') .send(film) .expect(400) .end(function(filmSaveErr, filmSaveRes) { // Set message assertion (filmSaveRes.body.message).should.match('Please fill Film name'); // Handle Film save error done(filmSaveErr); }); }); }); it('should be able to update Film instance if signed in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Film agent.post('/films') .send(film) .expect(200) .end(function(filmSaveErr, filmSaveRes) { // Handle Film save error if (filmSaveErr) done(filmSaveErr); // Update Film name film.name = 'WHY YOU GOTTA BE SO MEAN?'; // Update existing Film agent.put('/films/' + filmSaveRes.body._id) .send(film) .expect(200) .end(function(filmUpdateErr, filmUpdateRes) { // Handle Film update error if (filmUpdateErr) done(filmUpdateErr); // Set assertions (filmUpdateRes.body._id).should.equal(filmSaveRes.body._id); (filmUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback done(); }); }); }); }); it('should be able to get a list of Films if not signed in', function(done) { // Create new Film model instance var filmObj = new Film(film); // Save the Film filmObj.save(function() { // Request Films request(app).get('/films') .end(function(req, res) { // Set assertion res.body.should.be.an.Array.with.lengthOf(1); // Call the assertion callback done(); }); }); }); it('should be able to get a single Film if not signed in', function(done) { // Create new Film model instance var filmObj = new Film(film); // Save the Film filmObj.save(function() { request(app).get('/films/' + filmObj._id) .end(function(req, res) { // Set assertion res.body.should.be.an.Object.with.property('name', film.name); // Call the assertion callback done(); }); }); }); it('should be able to delete Film instance if signed in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Film agent.post('/films') .send(film) .expect(200) .end(function(filmSaveErr, filmSaveRes) { // Handle Film save error if (filmSaveErr) done(filmSaveErr); // Delete existing Film agent.delete('/films/' + filmSaveRes.body._id) .send(film) .expect(200) .end(function(filmDeleteErr, filmDeleteRes) { // Handle Film error error if (filmDeleteErr) done(filmDeleteErr); // Set assertions (filmDeleteRes.body._id).should.equal(filmSaveRes.body._id); // Call the assertion callback done(); }); }); }); }); it('should not be able to delete Film instance if not signed in', function(done) { // Set Film user film.user = user; // Create new Film model instance var filmObj = new Film(film); // Save the Film filmObj.save(function() { // Try deleting Film request(app).delete('/films/' + filmObj._id) .expect(401) .end(function(filmDeleteErr, filmDeleteRes) { // Set message assertion (filmDeleteRes.body.message).should.match('User is not logged in'); // Handle Film error error done(filmDeleteErr); }); }); }); afterEach(function(done) { User.remove().exec(); Film.remove().exec(); done(); }); });
'use strict'; /** * Created by Indexyz on 2016/7/5. */ const fs = require('fs'); const lib = require('../Lib.js'); const assert = require('assert'); const launch = require('./Launch.js'); class Version { constructor(name, path, options, callback) { this.vName = name; this.pPath = path + name + "/"; this.cOptions = options; this.loadObject(callback); return this } getLibraries() { return lib.transAllLib(JSON.stringify(this.thisObject["libraries"])); } toString() { return this.vName } loadObject(callback) { let self = this; fs.readFile(self.pPath + self.vName + ".json", {flag: "r"}, function (err, data) { if (err) { console.log(err) } let thisObject = JSON.parse(data.toString()); assert.equal(self.vName, thisObject["id"]); self.thisObject = thisObject; //noinspection JSUnresolvedVariable let requireVersion = thisObject.inheritsFrom; (function (thisObject) { if (requireVersion != undefined){ new Version(requireVersion, self.cOptions.path + "/" + self.cOptions.version, self.cOptions, function (newVersion) { process.nextTick(function () { self.requireVersion = newVersion; callback(thisObject) }) }) } else { callback(thisObject) } })(self) }); } isOK() { fs.exists(self.pPath + self.vName + ".json", function (err, state) { return state }) } getLaunch(Options) { const launcher = new launch(this, Options); return launcher; } hasRequire(){ return (this.thisObject.inheritsFrom != undefined) } getRequire(){ return (this.hasRequire() ? this.version.thisObject.inheritsFrom : null) } } class ClassicVersion extends Version { loadObject(callback) { callback(this) } getLibraries() { return null } } module.exports = Version; module.exports.ClassicVersion = ClassicVersion;
/* author Vlad Yakymenko Dp-P05 JS Core */ 'use strict'; window.onload = function () { let server = (function () { let info = document.getElementById('info') /*get names from server and show it on a page*/ function getNames () { let $div = $('<div>').addClass('info').appendTo(info), $span = $('<span>').text(''), output = []; $('<button>', { 'class': 'btnInfo', 'text': 'NAMES' }).appendTo($div).on('click', function() { let xhr = new XMLHttpRequest(), names = ''; xhr.open('GET', 'get-names'); xhr.send(); xhr.addEventListener('readystatechange', function() { if (xhr.readyState === 4 && xhr.status === 200) { showNames(); } }); function showNames () { xhr = xhr.responseText.split(''); for (let i = 9; i < xhr.length - 2; i++) { names += xhr[i]; } names = names.split(','); next: for (let i = 0; i < names.length; i++) { for (let j = 0; j < output.length; j++) { if (output[j] === names[i]) { continue next; } } output.push(names[i]); } $span.text(output).appendTo($div); } }); } /*get time from server and show it on a page*/ function getTime () { let $time = $('<span>').text(''), $div = $('<div>').addClass('info').appendTo(info), $btnTime = $('<button>').addClass('btnInfo').text('TIME').appendTo($div); $btnTime.on('click', function () { let xhr = new XMLHttpRequest(), out = ''; xhr.open('GET', 'get-time'); xhr.send(); xhr.addEventListener('readystatechange', function() { if (xhr.readyState === 4 && xhr.status === 200) { xhr = xhr.responseText.split(''); for (let i = 15; i < xhr.length - 1; i++) { out += xhr[i]; } $time.text(out).appendTo($div); } }); }); } return { getNames: getNames, getTime: getTime } })(), btn = document.getElementById('btnStartGame'); server.getTime(); server.getNames(); $(btn).on('click', startGame); function startGame () { setInterval(function() { let battle = new Battle(); battle.fight(); }, 3000); } }
// @Description : the standard template to use when instantiating a SharedKrake Object var SharedKrake = function() { var self = this; self.origin_url = null; self.destinationUrl = null; self.columns = []; }; SharedKrake.prototype.reset = function() { var self = this; self.origin_url = null; self.destinationUrl = null; self.columns = []; };
module.exports = { publicPath: '/stockage/', }
import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { configure } from 'mobx'; import { Provider } from 'mobx-react'; import router from './router'; import AppStore from './stores/AppStore'; configure({ enforceActions: true }); const stores = { // appStore: new AppStore({ list: [1] }) // 塞入初始数据,可用于服务端渲染 appStore: new AppStore({}) }; render(<Provider {...stores}>{ router }</Provider>, document.getElementById('root'));
const { performance } = require('perf_hooks'); // Suppose we want to write a function // that calculates the sum of all numbers from 1 up to // (and including) some number n. function addUpToA(n) { let total = 0; for (let i = 0; i <= n; i++) { total += i; } return total; } var t1 = performance.now(); addUpToA(1000000000); var t2 = performance.now(); console.log(`Time Elapsed: ${(t2 - t1) / 1000} seconds.`) console.log(addUpToA(6)) function addUpToB(n) { return n * (n + 1) / 2; } var t3 = performance.now(); addUpToB(1000000000); var t4 = performance.now(); console.log(`Time Elapsed: ${(t4 - t3) / 1000} seconds.`) console.log(addUpToB(6))
export let fakeFood = [ { "id": "1", "title": "Healthy Meal Plan", "shortDescription": "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", "img": "https://lh3.googleusercontent.com/sk8cuOLm9KdT4vptADQu_TRXKYVz0A5EvAH1rI6CtHdzQQ5W33L_GYfUCJvsBDshaMFO-juwV-RX16usLcxHTd2n2XemNDHRs36zY7HPEz7obX0AjAzwpk3_rHBO6w324styeqh3sg=w2400", "price": 23.99, "category": "lunch", }, { id: "2", title: "Fried Chicken Bento", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", shortDescription: "How We Dream About Our Future", img: "https://lh3.googleusercontent.com/v85Ulb4YLOt6APu_cDIIWF2hMZ77hjxJtpnG_ocXGuEGnfgfIaEZ_c6ZG91BpJy5jJ_Fr3LupF8LFvRj-UYChaYzni3H9Yp00FiinAgTfyEHLFF-tgDuLE_vYjDfTEvzvphSDdCcyw=w2400", price: 9.99, category: "lunch", }, { id: "3", title: "Tarragon-Rubbed-Salmon", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", shortDescription: "How We Dream About Our Future", img: "https://lh3.googleusercontent.com/0O4LmfNYAkrRqM8dU4ANYhvNQhFEoWN_2872eNDCwCspL4fjRX0l_AdZeb4z3bAJwxyfvyreFkYg2mHcDlm-E6hQEtSmY1UQjo6u9j2v0P6OZ1JsGPBINldlhdY_LhiiU7oZ9IuO0w=w2400", price: 6.99, category: "lunch", }, { id: "4", title: "Beef Steak", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", shortDescription: "How We Dream About Our Future", img: "https://lh3.googleusercontent.com/Ar1zAHz73Nmj_IsyeEA-ul6oPM5AalhY7YeNF57519Xn-R31nh_yO2nI_jyIRlTJIo7vCVFOa3eR7M-j8c5pITtga9T_DAO_Vcm_Sq22BsVJH7rdlD-XME5gZQ4Fy_9guoomOhRPVw=w2400", price: 15.99, category: "lunch", }, { id: "5", title: "Honey-Soy-Glazed Salmon With Pepp ", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", shortDescription: "How We Dream About Our Future", img: "https://lh3.googleusercontent.com/5tVceF9bXvCRho78xYLc_3LrJtZ8vPNC_upTpFAL0WBfG4hn4jfCc-n0MdRtoohs9yTfTqf37GTfcC0LcpS573Chq1JLDF8JUcvnYBluf2NLsABfpfFHkeEJ1nKYx8PxX2eNeFNEiA=w2400", price: 15.99, category: "lunch", }, { id: "6", title: "Indian Lunch", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/uKGhaflDr_xIgtbkmXuc6wKLkHBcp861HLSh4pjoAN2b9WE3-SjXoSSWbBa8cqx_W9bTFzxTDg13qFmAxSPZy_1add8IU6jG7ztomrkT-QIoruzFz13UNVcN2ay_ABc66OQLb8pA2Q=w2400", price: 8.99, category: "lunch", }, { id: "7", title: "Bagel and Cream Cheese", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/ch-LMMuqTjOcM9ySg_-iTXUlfVGa4NlHrJ_rvyNnEJ2ngpixjKnpxdXsWv8jvkZ718Kbpkn5Ho4zLP3nnl_nes6OOwR72JT9ryoQZ7AA5-M5Vi6zAr7H8P_1gwiNBp09E5Yk3YIdBw=w2400", price: 6.99, category: "breakfast", }, { id: "8", title: "Breakfast Sandwich", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/QHsgzvVLXm2lheCtXFcYxn4bcwIob4ien3XUEf9m_h5tYiyPpEFjBPQnZIBuC1cC-QMiNMcrsMOdGr5syfE_fgyiZq0zJjOM1vlu8gIUVmEJA8CDs2ndDn95GoxWYSGUczgu_JaZOA=w2400", price: 9.99, category: "breakfast", }, { id: "9", title: "Eggs Benedict", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/oN0_Ex4wN-_t07J7glRHj9yYkIjtVn7I4qN2RF76xrQV2kx4lrrUlfpDZwvc0JgEVJltlDbnyIIGuUIThNhqSK05ky9Ak0o8tpBouhALQtyUhb6NAP75EtlCZwlL533SICJpgN1S0w=w2400", price: 8.99, category: "breakfast", }, { id: "10", title: "Toast Croissant Fried Egg ", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/UbpIcbBsQw0KZM3rAZScC_URlFeKhnJkc84k1VFSOG1rP1j087PaevW6d6oWRKseBDSzEweC8Hut1fkTu7gal6MOT7SMmkgWJglBkbJJ7XJ2Lb3xEHvgljrS7tTCs9z5Fi9-oIyDsg=w2400", price: 6.99, category: "breakfast", }, { id: "11", title: "Baked Chicken", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/Sr0RuoKj6q4L-3ggsr9FgY02H1E6nL_wGr90dIoEB82wZ62THx2jzH1xhj5jOWIsw0b5VUi3aoNNtTDfUylOqBo42qUINik6a5Kubi5aWyEApbJR4RvE7-WZbZ0GR7Qn-XPxKaT6iA=w2400", price: 10.99, category: "breakfast", }, { id: "12", title: "Full Breakfast Fried Egg Toast Brunch", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/Dx7QataL8nayOKGEw7mZXFCmsulO3wQM9w9uoSBLoBOf3Dg6MMnbVp0Y3xTenmYs5qsvRT3MVf1Sbz88yeLAtmYimnSNmG71t6geltYgJXQYFm4hay___wnkzKnLG9ohordKA1s3RQ=w2400", price: 3.99, category: "breakfast", }, { id: "13", title: "Salmon With Grapefruit And lenti Salad", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/BnYXl3IiCtJRy7TbLuxL5vzCnQiMkZZX_i1erEXzTwXUFYG45aHaLAAYgFSj0rB6tucw-4Eje8Xq-aBZCNdOvLXOWymDvHs3uDeh9LizxkOfwIv5sytSVEX-TsDzhW0K34sni3ghpg=w2400", price: 9.99, category: "dinner", }, { id: "14", title: "French fries with cheese", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/uFsSqKdoiK7BAXB8Rv_Qz4SJliw_SvP8o2fDPtCMeP1DWCeM-mvFeTAgdlrRGBHgfT_-zwlWg05fnmk2vU1wkCMufTkwMyo8lmP9NBQGZk5qEBzFTBQ1jxkrWady4ndpZuygbgswgw=w2400", price: 8.99, category: "dinner", }, { id: "15", title: "Lemony Salmon Piccata", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/2r9CWxkIub8Po4UcokcAQBt1pSzmFgChGYo1lZpMIR-a4Klg5-qSzGDs7bxcwZSjQv0vZ68K5ynjnUweMw94iqg9FmJ3kj-w59BohQ1fxsbKjz2uLiewXogLHZuMJiGHdnUzSZ0ZfQ=w2400", price: 10.99, category: "dinner", }, { id: "16", title: "Garlic Butter Baked Salmon", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/CpsraaqbIoqB0oBlzRt_CPqhSZsX7abcZFrpVMB7cTsSx-C75Ih8B7W7Fj5yDpuS25if-55zzKs7o2eJH6-_64NvCAX1Zb4Tc1_5escVmY0PS3fd3KyieKcF8twcvh36B2gHCHMpNQ=w2400", price: 6.99, category: "dinner", }, { id: "17", title: "pork Tenderloin With Quinoa Pilaf", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/tr3TYpaMHvrLt_IUQTTTC--lI5M17obZRWCSLSTOZZWakJuD6TlLE9iQGnjlKVOYqE9qRHRZUyligQt5Bg45kLykl-fveBT31uDsT_HwEXf9oCPbVHF5buwLZxl6fNGu6aqKRdkqig=w2400", price: 12.99, category: "dinner", }, { id: "18", title: "Baked Chicken", shortDescription: "How We Dream About Our Future", "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo maxime, officia tempore modi deleniti porro non debitis quis optio adipisci accusamus atque totam mollitia architecto. Recusandae officia illo non est.", img: "https://lh3.googleusercontent.com/xIKYQ7_hwNXLiAKVKsfPtg-aaNS-vGsDRLwHWfRIOEKFxBH3qStLP_zhChSh-4JJHC9s21qqzRUkZoI38Uz9Xy6MHV5A8sbenH6jyLk9vqc45iRqNSWKPloww9J33mwDQ6B2UTCljg=w2400", price: 9.99, category: "dinner", }, ]
angular .module('service.group', ['ui.bootstrap', 'ui.xxt']) .service('tkGroupTeam', [ '$q', 'http2', function ($q, http2) { this.list = function (oApp, teamType) { var defer = $q.defer(), url url = '/rest/pl/fe/matter/group/team/list?app=' + oApp.id if (!teamType) { url += '&teamType=' } else if (/T|R/.test(teamType)) { url += '&teamType=' + teamType } http2.get(url).then(function (rsp) { var teams = rsp.data teams.forEach(function (oTeam) { oTeam.extattrs = oTeam.extattrs && oTeam.extattrs.length ? JSON.parse(oTeam.extattrs) : {} oTeam.targets = !oTeam.targets || oTeam.targets.length === 0 ? [] : JSON.parse(oTeam.targets) }) defer.resolve(teams) }) return defer.promise } }, ]) .provider('srvGroupApp', function () { var _siteId, _appId, _oApp this.config = function (siteId, appId) { _siteId = siteId _appId = appId } this.$get = [ '$q', '$uibModal', 'http2', 'noticebox', 'srvSite', 'tkGroupTeam', function ($q, $uibModal, http2, noticebox, srvSite, tkGroupTeam) { return { cached: function () { return _oApp }, get: function () { var defer = $q.defer(), url if (_oApp) { defer.resolve(_oApp) } else { url = '/rest/pl/fe/matter/group/get?site=' + _siteId + '&app=' + _appId http2.get(url).then(function (rsp) { var schemasById = {} _oApp = rsp.data _oApp.tags = !_oApp.tags || _oApp.tags.length === 0 ? [] : _oApp.tags.split(',') try { _oApp.group_rule = _oApp.group_rule && _oApp.group_rule.length ? JSON.parse(_oApp.group_rule) : {} _oApp.dataSchemas.forEach(function (oSchema) { if (oSchema.type !== 'html') { schemasById[oSchema.id] = oSchema } }) _oApp._schemasById = schemasById } catch (e) { console.error('error', e) } tkGroupTeam.list(_oApp).then(function (teams) { var teamsById = {} teams.forEach(function (round) { teamsById[round.team_id] = round }) _oApp._teamsById = teamsById defer.resolve(_oApp) }) }) } return defer.promise }, update: function (names) { var defer = $q.defer(), modifiedData = {} angular.isString(names) && (names = [names]) names.forEach(function (name) { if (name === 'tags') { modifiedData.tags = _oApp.tags.join(',') } else { modifiedData[name] = _oApp[name] } }) http2 .post( '/rest/pl/fe/matter/group/update?app=' + _appId, modifiedData ) .then(function (rsp) { defer.resolve(rsp.data) }) return defer.promise }, assocWithApp: function (sourceTypes, oMission, notSync) { var defer = $q.defer() $uibModal .open({ templateUrl: '/views/default/pl/fe/matter/group/component/sourceApp.html?_=1', controller: [ '$scope', '$uibModalInstance', function ($scope2, $mi) { $scope2.data = { app: '', appType: 'registration', onlySpeaker: 'N', keepExistent: 'N', } if (!oMission && _oApp && _oApp.mission) { oMission = _oApp.mission } if (oMission) { $scope2.data.sameMission = 'Y' } $scope2.sourceTypes = sourceTypes $scope2.cancel = function () { $mi.dismiss() } $scope2.ok = function () { $mi.close($scope2.data) } $scope2.$watch('data.appType', function (appType) { var url if (!appType) return if (appType === 'mschema') { srvSite .memberSchemaList(oMission, !!oMission) .then(function (aMschemas) { $scope2.apps = aMschemas }) delete $scope2.data.includeEnroll } else { if (appType === 'registration') { url = '/rest/pl/fe/matter/enroll/list?site=' + _siteId + '&size=999' url += '&scenario=registration' delete $scope2.data.includeEnroll } else if (appType === 'signin') { url = '/rest/pl/fe/matter/signin/list?site=' + _siteId + '&size=999' $scope2.data.includeEnroll = 'Y' } oMission && (url += '&mission=' + oMission.id) http2.get(url).then(function (rsp) { $scope2.apps = rsp.data.apps }) } }) }, ], backdrop: 'static', }) .result.then(function (data) { var url, params if (data.app) { params = { app: data.app.id, appType: data.appType, } data.appType === 'signin' && (params.includeEnroll = data.includeEnroll) if (notSync) { params.appTitle = data.app.title defer.resolve(params) } else { url = '/rest/pl/fe/matter/group/record/assocWithApp?app=' + _appId url += '&keepExistent=' + data.keepExistent http2.post(url, params).then(function (rsp) { var schemasById = {} _oApp.sourceApp = data.app _oApp.dataSchemas = rsp.data.dataSchemas _oApp.dataSchemas.forEach(function (schema) { if (schema.type !== 'html') { schemasById[schema.id] = schema } }) _oApp._schemasById = schemasById defer.resolve(_oApp) }) } } }) return defer.promise }, syncByApp: function () { var defer = $q.defer() if (_oApp.sourceApp) { var url = '/rest/pl/fe/matter/group/record/syncByApp?app=' + _appId http2.get(url).then(function (rsp) { noticebox.success('同步' + rsp.data + '个用户') defer.resolve(rsp.data) }) } return defer.promise }, cancelSourceApp: function () { _oApp.sourceApp = null _oApp.source_app = null _oApp.dataSchemas = null _oApp.data_schemas = null _oApp.assigned_nickname = '' delete _oApp.sourceApp return this.update([ 'source_app', 'data_schemas', 'assigned_nickname', ]) }, setSyncFilter: function () { if (!_oApp.sourceApp) noticebox.warn('没有指定分组用户来源活动') if (_oApp.sourceApp.type !== 'mschema') noticebox.warn('只支持对通讯录活动设置用户同步筛选条件') var optSchemas // 作为筛选条件的单选题 if (_oApp.sourceApp.extAttrs && _oApp.sourceApp.extAttrs.length) { optSchemas = _oApp.sourceApp.extAttrs.filter((ea) => /single|multiple/.test(ea.type) ) } if (!optSchemas || optSchemas.length === 0) noticebox.warn( '通讯录中没有包含可用于筛选条件的题目(仅限单选题和多选题)' ) var defer = $q.defer() http2 .post('/rest/script/time', { html: { filter: '/views/default/pl/fe/matter/group/component/syncFilter', }, }) .then(function (rsp) { $uibModal .open({ templateUrl: '/views/default/pl/fe/matter/group/component/syncFilter.html?_' + rsp.data.html.filter.time, controller: [ '$scope', '$uibModalInstance', function ($scope2, $mi) { var syncRule = _oApp.syncRule var _rules = [] $scope2.data = { logicOR: false, } if (syncRule) { if (syncRule.rules && syncRule.rules.length) { syncRule.rules.forEach((r) => { let schema, op schema = optSchemas.find((s) => s.id === r.schema) if (schema && Array.isArray(schema.ops)) { op = schema.ops.find((op) => op.v === r.op) } _rules.push({ schema, op }) }) } if (syncRule.logicOR === true) $scope2.data.logicOR = true } $scope2.optSchemas = optSchemas $scope2.rules = _rules $scope2.addRule = function () { _rules.push({}) } $scope2.removeRule = function (oRule) { _rules.splice(_rules.indexOf(oRule), 1) } $scope2.cleanRule = function () { _rules.splice(0, _rules.length) } $scope2.ok = function () { var oConfig = { rules: [], logicOR: $scope2.data.logicOR, } _rules.forEach((oRule) => { oConfig.rules.push({ schema: oRule.schema.id, op: oRule.op.v, }) }) $mi.close(oConfig) } $scope2.cancel = function () { $mi.dismiss() } }, ], backdrop: 'static', }) .result.then((newSyncRule) => defer.resolve(newSyncRule)) }) return defer.promise }, export: function () { var url = '/rest/pl/fe/matter/group/record/export?app=' + _appId window.open(url) }, dealData: function (oUser) { this.get().then(function (oApp) { var role_team_titles = [] if ( oUser.role_teams && oUser.role_teams.length && oApp._teamsById ) { oUser.role_teams.forEach(function (teamId) { if (oApp._teamsById[teamId]) { role_team_titles.push(oApp._teamsById[teamId].title) } }) } oUser.role_team_titles = role_team_titles }) }, } }, ] }) .provider('srvGroupTeam', function () { var _teams, _siteId, _appId this.config = function (siteId, appId) { _siteId = siteId _appId = appId } this.$get = [ '$q', '$uibModal', 'http2', 'noticebox', 'srvGroupApp', 'tkGroupTeam', function ($q, $uibModal, http2, noticebox, srvGroupApp, tkGroupTeam) { return { cached: function () { return _teams }, list: function () { var defer = $q.defer(), url if (_teams) { defer.resolve(_teams) } else { _teams = [] tkGroupTeam .list({ id: _appId, }) .then(function (teams) { _teams = teams defer.resolve(_teams) }) } return defer.promise }, config: function () { var defer = $q.defer() srvGroupApp.get().then(function (oApp) { $uibModal .open({ templateUrl: 'configRule.html', controller: [ '$uibModalInstance', '$scope', 'http2', function ($mi, $scope, http2) { var groupRule, rule, schemas groupRule = oApp.groupRule rule = { count: groupRule.count, times: groupRule.times, schemas: [], } schemas = angular.copy(oApp.dataSchemas) $scope.schemas = [] http2 .get( '/rest/pl/fe/matter/group/record/count?app=' + _appId ) .then(function (rsp) { $scope.countOfPlayers = rsp.data $scope.$watch('rule.count', function (countOfGroups) { if (countOfGroups) { rule.times = Math.ceil( $scope.countOfPlayers / countOfGroups ) } }) }) schemas.forEach(function (oSchema) { if (oSchema.type === 'single') { if ( groupRule.schemas && groupRule.schemas.indexOf(oSchema.id) !== -1 ) { oSchema._selected = true } $scope.schemas.push(oSchema) } }) $scope.rule = rule $scope.cancel = function () { $mi.dismiss() } $scope.ok = function () { if ($scope.schemas.length) { $scope.rule.schemas = [] $scope.schemas.forEach(function (oSchema) { if (oSchema._selected) { $scope.rule.schemas.push(oSchema.id) } }) } $mi.close($scope.rule) } }, ], backdrop: 'static', }) .result.then(function (oRule) { var url = '/rest/pl/fe/matter/group/configRule?app=' + _appId _teams.splice(0, _teams.length) http2.post(url, oRule).then(function (rsp) { rsp.data.forEach(function (oTeam) { _teams.push(oTeam) }) defer.resolve(_teams) }) }) }) return defer.promise }, empty: function () { var defer = $q.defer() if (window.confirm('本操作将清除已有分组数据,确定执行?')) { var url = '/rest/pl/fe/matter/group/configRule?app=' + _appId http2.post(url, {}).then(function (rsp) { _teams.splice(0, _teams.length) defer.resolve(rsp.data) }) } return defer.promise }, add: function () { var defer = $q.defer(), oProto = { title: '分组' + (_teams.length + 1), } http2 .post('/rest/pl/fe/matter/group/team/add?app=' + _appId, oProto) .then(function (rsp) { var oNewTeam = rsp.data oNewTeam._before = angular.copy(oNewTeam) _teams.push(oNewTeam) defer.resolve(oNewTeam) }) return defer.promise }, update: function (oTeam, name) { var defer = $q.defer(), oUpdated = {} oUpdated[name] = oTeam[name] http2 .post( '/rest/pl/fe/matter/group/team/update?tid=' + oTeam.team_id, oUpdated ) .then( function (rsp) { if (rsp.err_code === 0) { oTeam._before = angular.copy(oTeam) defer.resolve(oTeam) noticebox.success('完成保存') } else { oTeam[name] = oTeam._before[name] } }, { autoBreak: false, } ) return defer.promise }, remove: function (oTeam) { var defer = $q.defer() http2 .get('/rest/pl/fe/matter/group/team/remove?tid=' + oTeam.team_id) .then(function (rsp) { _teams.splice(_teams.indexOf(oTeam), 1) defer.resolve() }) return defer.promise }, } }, ] }) .provider('srvGroupRec', function () { let _oApp, _siteId, _appId, _oCriteria this.$get = [ '$q', '$uibModal', 'noticebox', 'http2', 'cstApp', 'pushnotify', 'tmsSchema', 'srvGroupApp', function ( $q, $uibModal, noticebox, http2, cstApp, pushnotify, tmsSchema, srvGroupApp ) { return { init: function (aCachedUsers) { let defer = $q.defer() srvGroupApp.get().then((oApp) => { _oApp = oApp _siteId = oApp.siteid _appId = oApp.id _aGrpRecords = aCachedUsers this.criteria = _oCriteria = { data: {} } defer.resolve() }) return defer.promise }, execute: function () { var _self = this if (window.confirm('本操作将清除已有分组数据,确定执行?')) { http2 .get(`/rest/pl/fe/matter/group/execute?app=${_appId}`) .then(() => _self.list()) } }, list: function (oTeam, arg, filterByKeyword) { let defer, filter, teamTypeId, url defer = $q.defer() filter = filterByKeyword || {} if (oTeam) { teamTypeId = arg === 'team' ? 'teamId' : 'roleTeamId' filter[teamTypeId] = oTeam === false ? 'pending' : oTeam.team_id } url = `/rest/pl/fe/matter/group/record/list?app=${_appId}` _aGrpRecords.splice(0, _aGrpRecords.length) http2.post(url, filter).then((rsp) => { if (rsp.data.total) { rsp.data.records.forEach((oRec) => { tmsSchema.forTable(oRec, _oApp._schemasById) srvGroupApp.dealData(oRec) _aGrpRecords.push(oRec) }) } defer.resolve(rsp.data.records) }) return defer.promise }, filter: function () { let defer, that defer = $q.defer() that = this http2 .post('/rest/script/time', { html: { filter: '/views/default/pl/fe/matter/group/component/recordFilter', }, }) .then((rsp) => { $uibModal .open({ templateUrl: `/views/default/pl/fe/matter/group/component/recordFilter.html?_=${rsp.data.html.filter.time}`, controller: 'ctrlRecordFilter', windowClass: 'auto-height', backdrop: 'static', resolve: { app: function () { return _oApp }, dataSchemas: function () { return _oApp.dataSchemas }, criteria: function () { return angular.copy(_oCriteria) }, }, }) .result.then(function (oCriteria) { defer.resolve() angular.extend(_oCriteria, oCriteria) that.list(null, null, _oCriteria).then(() => { defer.resolve() }) }) }) return defer.promise }, quitTeam: function (users, type) { let defer, url, eks defer = $q.defer() url = `/rest/pl/fe/matter/group/record/quitTeam?app=${_appId}&type=${type}` eks = users.reduce((a, oRec) => { a.push(oRec.enroll_key) return a }, []) http2.post(url, eks).then((rsp) => { let oResult = rsp.data users.forEach((oRec) => { if (oResult[oRec.enroll_key] !== false) { if (type === 'T') { oRec.team_id = '' oRec.team_title = '' } else { oRec.role_teams = [] oRec.role_team_titles = '' } tmsSchema.forTable(oRec, _oApp._schemasById) } }) defer.resolve() }) return defer.promise }, joinGroup: function (oTeam, users) { var defer = $q.defer(), url, eks = [] url = '/rest/pl/fe/matter/group/record/joinGroup?app=' + _appId url += '&team=' + oTeam.team_id users.forEach(function (oRec) { eks.push(oRec.enroll_key) }) http2.post(url, eks).then(function (rsp) { var oResult = rsp.data users.forEach(function (oRec) { if (oResult[oRec.enroll_key] !== false) { switch (oTeam.team_type) { case 'T': oRec.team_id = oTeam.team_id oRec.team_title = oTeam.title break case 'R': oRec.role_teams === undefined && (oRec.role_teams = []) oRec.role_teams.push(oTeam.team_id) srvGroupApp.dealData(oRec) break } tmsSchema.forTable(oRec, _oApp._schemasById) } }) defer.resolve() }) return defer.promise }, setIsLeader: function (isLeader, users) { let defer, url, eks defer = $q.defer() url = `/rest/pl/fe/matter/group/record/setIsLeader?app=${_appId}&isLeader=${isLeader}` eks = users.map((oRec) => oRec.enroll_key) http2.post(url, eks).then((rsp) => { var oResult = rsp.data users.forEach((oRec) => { if (oResult[oRec.enroll_key] !== false) { oRec.is_leader = isLeader } }) defer.resolve() }) return defer.promise }, add: function (oRec) { var defer = $q.defer(), url url = '/rest/pl/fe/matter/group/record/add?app=' + _appId http2.post(url, oRec).then(function (rsp) { tmsSchema.forTable(rsp.data, _oApp._schemasById) srvGroupApp.dealData(rsp.data) _aGrpRecords.splice(0, 0, rsp.data) defer.resolve() }) return defer.promise }, update: function (oBeforeRec, oNewRec) { var defer = $q.defer(), url url = '/rest/pl/fe/matter/group/record/update?app=' + _appId url += '&ek=' + oBeforeRec.enroll_key http2.post(url, oNewRec).then(function (rsp) { http2.merge(oBeforeRec, rsp.data) tmsSchema.forTable(oBeforeRec, _oApp._schemasById) srvGroupApp.dealData(oBeforeRec) defer.resolve() }) return defer.promise }, remove: function (oBeforeRec) { var defer = $q.defer() http2 .get( '/rest/pl/fe/matter/group/record/remove?app=' + _appId + '&ek=' + oBeforeRec.enroll_key ) .then(function (rsp) { _aGrpRecords.splice(_aGrpRecords.indexOf(oBeforeRec), 1) defer.resolve() }) return defer.promise }, empty: function () { var defer = $q.defer(), vcode vcode = prompt( '是否要从【' + _oApp.title + '】删除所有用户?,若是,请输入活动名称。' ) if (vcode === _oApp.title) { http2 .get('/rest/pl/fe/matter/group/record/empty?app=' + _appId) .then(function (rsp) { _aGrpRecords.splice(0, _aGrpRecords.length) defer.resolve() }) } else { defer.resolve() } return defer.promise }, edit: function (oRecord) { var defer = $q.defer() http2 .post('/rest/script/time', { html: { editor: '/views/default/pl/fe/matter/group/component/recordEditor', }, }) .then(function (rsp) { $uibModal .open({ templateUrl: '/views/default/pl/fe/matter/group/component/recordEditor.html?_=' + rsp.data.html.editor.time, controller: 'ctrlGrpRecEditor', windowClass: 'auto-height', resolve: { record: function () { return angular.copy(oRecord) }, }, }) .result.then(function (data) { defer.resolve(data) }) }) return defer.promise }, notify: function (rows) { var options = { matterTypes: cstApp.notifyMatter, sender: 'group:' + _appId, } _oApp.mission && (options.missionId = _oApp.mission.id) pushnotify.open( _siteId, function (notify) { var url, targetAndMsg = {} if (notify.matters.length) { if (rows) { targetAndMsg.users = [] Object.keys(rows.selected).forEach(function (key) { if (rows.selected[key] === true) { var rec = _aGrpRecords[key] targetAndMsg.users.push({ userid: rec.userid, enroll_key: rec.enroll_key, }) } }) } targetAndMsg.message = notify.message url = '/rest/pl/fe/matter/group/notice/send' url += '?site=' + _siteId targetAndMsg.app = _appId targetAndMsg.tmplmsg = notify.tmplmsg.id http2.post(url, targetAndMsg).then(function (data) { noticebox.success('发送完成') }) } }, options ) }, } }, ] }) .provider('srvGroupNotice', function () { this.$get = [ '$q', 'http2', 'srvGroupApp', function ($q, http2, srvGroupApp) { return { detail: function (batch) { var defer = $q.defer(), url srvGroupApp.get().then(function (oApp) { url = '/rest/pl/fe/matter/group/notice/logList?batch=' + batch.id + '&app=' + oApp.id http2.get(url).then(function (rsp) { defer.resolve(rsp.data) }) }) return defer.promise }, } }, ] }) /** * filter */ .controller('ctrlRecordFilter', [ '$scope', '$uibModalInstance', 'dataSchemas', 'criteria', function ($scope, $mi, dataSchemas, lastCriteria) { var canFilteredSchemas = [] dataSchemas.forEach(function (schema) { if ( false === /image|file|score|html/.test(schema.type) && schema.id.indexOf('member') !== 0 ) { canFilteredSchemas.push(schema) } if (/multiple/.test(schema.type)) { let options = {} if (lastCriteria.data[schema.id]) { lastCriteria.data[schema.id].split(',').forEach(function (key) { options[key] = true }) lastCriteria.data[schema.id] = options } } $scope.schemas = canFilteredSchemas $scope.criteria = lastCriteria }) $scope.checkedRounds = {} $scope.clean = function () { var oCriteria = $scope.criteria if (oCriteria.data) { angular.forEach(oCriteria.data, function (val, key) { oCriteria.data[key] = null }) } } $scope.ok = function () { let oCriteria = $scope.criteria, optionCriteria /* 将单选题/多选题的结果拼成字符串 */ canFilteredSchemas.forEach((schema) => { let result if (/multiple/.test(schema.type)) { if ((optionCriteria = oCriteria.data[schema.id])) { result = [] Object.keys(optionCriteria).forEach(function (key) { optionCriteria[key] && result.push(key) }) if (result.length) oCriteria.data[schema.id] = result.join(',') } } }) $mi.close(oCriteria) } $scope.cancel = function () { $mi.dismiss('cancel') } }, ]) .controller('ctrlGrpRecEditor', [ '$scope', '$uibModalInstance', 'cstApp', 'record', 'tmsSchema', 'srvGroupApp', 'tkGroupTeam', function ( $scope, $mi, cstApp, oRecord, tmsSchema, srvGroupApp, tkGroupTeam ) { srvGroupApp.get().then(function (oApp) { $scope.app = oApp tkGroupTeam.list(oApp).then(function (teams) { $scope.teamRounds = [] $scope.roleTeams = [] teams.forEach(function (oTeam) { switch (oTeam.team_type) { case 'T': $scope.teamRounds.push(oTeam) break case 'R': $scope.roleTeams.push(oTeam) break } }) var obj = {} if (oRecord.role_teams && oRecord.role_teams.length) { oRecord.role_teams.forEach(function (teamId) { obj[teamId] = true }) oRecord._role_teams = obj } }) if (oRecord.data) { oApp.dataSchemas.forEach(function (schema) { if (oRecord.data[schema.id]) { tmsSchema.forEdit(schema, oRecord.data) } }) } $scope.cstApp = cstApp $scope.aTags = oApp.tags oRecord.aTags = !oRecord.tags || oRecord.tags.length === 0 ? [] : oRecord.tags.split(',') $scope.record = oRecord }) $scope.scoreRangeArray = function (schema) { var arr = [] if (schema.range && schema.range.length === 2) { for (var i = schema.range[0]; i <= schema.range[1]; i++) { arr.push('' + i) } } return arr } $scope.ok = function () { var oNewRecord, oScopeRecord if ($scope.record._role_teams) { for (var i in $scope.record._role_teams) { if ( $scope.record._role_teams[i] && $scope.record.role_teams.indexOf(i) === -1 ) { $scope.record.role_teams.push(i) } if ( !$scope.record._role_teams[i] && $scope.record.role_teams.indexOf(i) !== -1 ) { $scope.record.role_teams.splice(i, 1) } } } oScopeRecord = $scope.record oNewRecord = { data: {}, is_leader: oScopeRecord.is_leader, comment: oScopeRecord.comment, tags: oScopeRecord.aTags.join(','), team_id: oScopeRecord.team_id, role_teams: oScopeRecord.role_teams, } if (oScopeRecord.data) { $scope.app.dataSchemas.forEach(function (oSchema) { if (oScopeRecord.data[oSchema.id]) { oNewRecord.data[oSchema.id] = oScopeRecord.data[oSchema.id] } }) if (oScopeRecord.data.member) { oNewRecord.data.member = oScopeRecord.data.member } } $mi.close({ record: oNewRecord, tags: $scope.aTags, }) } $scope.cancel = function () { $mi.dismiss() } $scope.$on('tag.xxt.combox.done', function (event, aSelected) { var aNewTags = [] for (var i in aSelected) { var existing = false for (var j in $scope.record.aTags) { if (aSelected[i] === $scope.record.aTags[j]) { existing = true break } } !existing && aNewTags.push(aSelected[i]) } $scope.record.aTags = $scope.record.aTags.concat(aNewTags) }) $scope.$on('tag.xxt.combox.add', function (event, newTag) { $scope.record.aTags.push(newTag) $scope.aTags.indexOf(newTag) === -1 && $scope.aTags.push(newTag) }) $scope.$on('tag.xxt.combox.del', function (event, removed) { $scope.record.aTags.splice($scope.record.aTags.indexOf(removed), 1) }) }, ])
// public/articles/services/articles.client.service.js // Invoke 'strict' JavaScript mode //'use strict'; /* $resource is from angular-resource $resource has three arguments: 1: Url: The base URL for the resource endpoints 2: ParamDefaults: a routing parameter assignment using the article's document _id field 3: Actions: an actions argument extending the resource methods with an update() method that uses the PUT http method. 4: Options: objects that represent custom options to extend the default behavior of $resourceProvider The returned ngResource object will have several methods to handle the default RESTful resource routes, and it can optionally be extended by custom methods. The default resource methods are as follows: • get(): This method uses a GET HTTP method and expects a JSON object response • save(): This method uses a POST HTTP method and expects a JSON object response • query(): This method uses a GET HTTP method and expects a JSON array response • remove(): This method uses a DELETE HTTP method and expects a JSON object response • delete(): This method uses a DELETE HTTP method and expects a JSON object response Calling each of these methods will use the $http service and invoke an HTTP request with the specified HTTP method, URL, and parameters. The $resource instance method will then return an empty reference object that will be populated once the data is returned from the server. You can also pass a callback function that will get called once the reference object is populated. A basic usage of the $resource factory method would be as follows: var Users = $resource('/users/:userId', { userId: '@id' }); var user = Users.get({ userId: 123 }, function () { user.abc = true; user.$save(); }); In order for your CRUD module to easily communicate with the API endpoints, it is recommended that you use a single AngularJS service that will utilize the $resource factory method. Notice how the service uses the $resource factory with three arguments: the base URL for the resource endpoints, a routing parameter assignment using the article's document _id field, and an actions argument extending the resource methods with an update() method that uses the PUT HTTP method. This simple service provides you with everything you need to communicate with your server endpoints. */ // Create the 'articles' service angular.module('articles').factory('Articles', ['$resource', function ($resource) { // Use the '$resource' service to return an article '$resource' object return $resource('api/articles/:articleId', { articleId: '@_id' }, { update: { method: 'PUT' } }); }]);
const path = require("path"); const webpack = require("webpack"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const VENDOR_LIBS = [ "axios", "bootstrap", // "font-awesome", "jquery", "popper.js", "react", "react-router-dom", "react-dom", "redux-thunk", "redux", ]; const devServer = { port: 4000, open: true, disableHostCheck: true, historyApiFallback: true, overlay: true, inline: true, compress: true, contentBase: "/", }; module.exports = { entry: { bundle: "./src/index.js", vendor: VENDOR_LIBS, }, output: { path: path.join(__dirname, "dist"), filename: "[name].[chunkhash].js", }, mode: "development", resolve: { extensions: ["*", ".js", ".jsx"], }, module: { // loaders: [ // { // loader: "babel-loader", // query: { // presets: ["@babel/preset-react"], // // plugins: ["transform-class-properties"], // }, // test: /\.jsx?$/, // exclude: "/node_modules", // }, // ], rules: [ { use: "babel-loader", test: /\.js$|jsx/, // khong cho no tim trong day exclude: "/node_modules", }, { use: ["style-loader", "css-loader"], test: /\.css$/, }, { loader: "file-loader", test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.woff2$|\.eot$|\.wav$|\.ttf$|\.ttf$|\.mp3$|\.ico$/, }, ], }, devtool: "eval-source-map", plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "windown.$": "jquery", "windown.jQuery": "jquery", }), new HtmlWebpackPlugin({ template: "src/index.html", }), ], devServer, optimization: { splitChunks: { cacheGroups: { // In dev mode, we want all vendor (node_modules) to go into a chunk, // so building main.js is faster. vendors: { test: /[\\/]node_modules[\\/]/, name: "vendor", // Exclude pre-main dependencies going into vendors, as doing so // will result in webpack only loading pre-main once vendors loaded. // But pre-main is the one loading vendors. // Currently undocument feature: https://github.com/webpack/webpack/pull/6791 // chunks: chunk => chunk.name !== "pre-main.min" }, }, }, runtimeChunk: { name: "manifest", }, }, };
function playJeopardy(){ //jepq= jeopardy header1 display question there //next = button to net question to appear var $jepq = $("#jepq"); var $answerhide = $("#answerhide"); //when button is clicked make ajax call to api/random $('#next').on('click',function(){ $.ajax({ url: 'http://jservice.io/api/clues?category=2', dataType: 'json' }) .done(function(data){ var nextQuestionID=Math.floor(Math.random() *45) ; $jepq.text(data[nextQuestionID].question); $answerhide.text(data[nextQuestionID].answer); }) .fail(function(jqXHR, textStatus, errorThrown){ }); }); } $(function(){ playJeopardy(); }); /* $("#answer").keypress(function(e) { if (e.which == 13) //Entere keypress { if (answer == answerhide) { alert("Correct!!! 5 points have been added to your score") } else { alert("Sorry you are incorrect 1 point has been deducted from your score...") } } }); */
import Link from 'next/link' import moment from 'moment' import GameModeTag from './GameModeTag' const Card = ({story}) => { const showStoryTags = story => ( story.tags.map((t, i) => ( <Link key={i} href={`/tags/${t.slug}`}> <a className="paper-btn btn-small mr-1 ml-1">{t.name}</a> </Link> )) ) return ( <div className="card"> <div className="card-body"> <Link href={`/stories/${story.slug}`}> <a className="text-primary"> { story.is_finished && <span className="badge success finished-card-badge">finished</span> } { story.tags.find(tag => tag.name === 'dev-Update') && <span className="badge danger dev-update-card-badge">dev Update</span> } <header className="card-title"> <h4>{story.title}</h4> </header> <section> <p className="article-meta"> Written by <Link href={`/profile/${story.postedBy.username}`}> <a>{story.postedBy.name}</a> </Link> | Published {moment(story.createdAt).fromNow()} </p> </section> <div> <section> <p className="card-text"> {story.excerpt} </p> </section> </div> </a> </Link> </div> <div className="card-footer"> <section> <GameModeTag game_mode={story.game_mode} /> {showStoryTags(story)} </section> </div> </div> ) } export default Card
/* eslint-disable indent */ module.exports = { friendlyName: 'Get list of possible partners', description: 'Get list of possible partners for a person of which PersonsId is givven.', inputs: { PersonId: { description: 'The id of the person to lookup possible partners.', type: 'number', required: true }, }, exits: { success: { description: 'Possible partners were found', responseType: '' }, notFound: { description: 'No possible partners were found.', responseType: 'notFound' } }, fn: async function(inputs, exits) { var possiblePartnersList = await sails.sendNativeQuery('call GetPossiblePartners($1)', [inputs.PersonId]); if (possiblePartnersList.rows[0].length === 0) { return exits.notFound({ message: 'Found no possible partners for person with id:' + inputs.PersonId, }); } else { return exits.success({ message: 'Possible partners were found for person with id: ' + inputs.PersonId, data: possiblePartnersList.rows[0] }); } } };
/** * Created by 724291943 on 2017/6/3. */ var express = require('express') var api = express.Router() var classification = require('../models/classification') var blog = require('../models/blog') var tag = require('../models/tag') api.get('/getSiteBar', function (req, res) { var json = {} getBlogNum() .then(function (data) { json.blogNum = data return getTagNum() }) .then(function (data) { json.tagNum = data return getClassificationNum() }) .then(function (data) { json.classificationNum = data res.json(json) }) }) function getTagNum() { return new Promise(function (resolve, reject) { tag.count({},function (err, count) { if(err){ reject('find tag err') }else { resolve(count) } }) }) } function getClassificationNum() { return new Promise(function (resolve, reject) { classification.count({},function (err, count) { if(err){ reject('find classification err') }else { resolve(count) } }) }) } function getBlogNum() { return new Promise(function (resolve, reject) { blog.count({},function (err, count) { if(err){ reject('find blog err') }else { resolve(count) } }) }) } module.exports = api
'use strict' const mongoose = require('mongoose'); const Schema = mongoose.Schema; const schema = new Schema({ id: { type: Number, required: true, trim: true }, pessoa: { id: { type: Number, required: true, trim: true }, nome: { type: String, required: true, trim: true }, sobrenome: { type: String, required: true, trim: true }, cpf: { type: String, required: true, trim: true }, telefone: { type: String, required: true, trim: true }, sexo: { type: String, required: true, trim: true }, email: { type: String, required: true, trim: true }, enderecos: [ { id: { type: Number, required: true, trim: true }, estado: { type: String, required: true, trim: true }, cidade: { type: String, required: true, trim: true }, bairro: { type: String, required: true, trim: true }, logradouro: { type: String, required: true, trim: true }, numero: { type: String, required: true, trim: true }, complemento: { type: String, required: true, trim: true } } ], dataNasc: { type: String, required: true, trim: true } } }); module.exports = mongoose.model('Cliente', schema);
$(function () { /* *思路大概是先为每一个required添加必填的标记,用each()方法来实现。 *在each()方法中先是创建一个元素。然后通过append()方法将创建的元素加入到父元素后面。 *这里面的this用的很精髓,每一次的this都对应着相应的input元素,然后获取相应的父元素。 *然后为input元素添加失去焦点事件。然后进行用户名、邮件的验证。 *这里用了一个判断is(),如果是用户名,做相应的处理,如果是邮件做相应的验证。 *在jQuery框架中,也可以适当的穿插一写原汁原味的javascript代码。比如验证用户名中就有this.value,和this.value.length。对内容进行判断。 *然后进行的是邮件的验证,貌似用到了正则表达式。 *然后为input元素添加keyup事件与focus事件。就是在keyup时也要做一下验证,调用blur事件就行了。用triggerHandler()触发器,触发相应的事件。 *最后提交表单时做统一验证 *做好整体与细节的处理 */ //文本框失去焦点后 $('form :input').blur(function () { var $parent = $(this).parent(); $parent.find(".prompt").remove(); $parent.removeClass("onFocus"); var el = null;//声明正则表达式 if ($(this).is('.email')) { var el = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/; } if (el != null) { if (el.test(this.value)) { var promptText = ""; } else if (this.value == "") { var promptText = $(this).attr("promptNull"); var promptClass = "error"; } else { var promptText = $(this).attr("promptError"); var promptClass = "error"; } $parent.append('<span class="prompt ' + promptClass + '"><em></em><span></span>' + promptText + '</span>'); } }).focus(function () { $(this).parent().addClass("onFocus"); });//end blur //提交,最终验证。 $('#sub').click(function () { $("form :input").trigger('blur'); var numError = $('form .error,form .warning').length; if (numError) { return false; } var email = $(".email").val(); var password = $("input[type=password]").val(); $.ajax({ url:"../../teacherLogin.do", type:"get", data:"email="+email+"&password="+password, dataType:"json", success:function(data){ //alert(11111); if(data.resultcode=="101"){ alert(data.resultmsg); }else{ if(data.register.tea_status=="1"){ alert("您尚未完善个人信息!"); location.href = "tch_teacherPerfect01.html?email="+data.register.tea_email+","+data.register.tea_name+","+data.register.tea_idcard; }else if(data.register.tea_status=="2"){ location.href = "tch_registerPerfectWait.html"; }else if(data.register.tea_status=="3"||data.register.tea_status=="0"){ location.href = "index.html"; }else if(data.register.tea_status=="4"){ location.href = "tch_perfectInformation.html"; } } } }) }); //重置 $('#res').click(function () { $(".prompt").remove(); }); }) //]]>
import React from 'react' import Grid from "@material-ui/core/Grid"; import Typography from "../components/Typography"; import withStyles from "@material-ui/core/es/styles/withStyles"; import Link from "@material-ui/core/Link"; import Button from "../components/Button"; import withRouter from "react-router/es/withRouter"; import LinkRouter from 'react-router-dom/Link' import API from "../../../services/API"; const styles = theme => ({ button: { marginTop: theme.spacing.unit, } }); class DonationStepDemo extends React.Component { classes = this.props.classes; state = { questionnaire: null }; constructor(props) { super(props); props.changeNextBtn(true) } componentDidMount() { API.getQuestionnaire(this.props.donationInformation.product.questionnaireId) .then(questionnaire => { this.setState({ questionnaire: questionnaire }) }) } getGift = () => { let donationInformation = this.props.donationInformation; return ({ donorName: donationInformation.donorName, videoUrl: donationInformation.videoUrl, amount: donationInformation.amount, charityProject: donationInformation.product, questionnaire: this.state.questionnaire }) }; handleBtn = () => { localStorage.setItem('gift', JSON.stringify(this.getGift())) }; render() { return ( <> <Grid item sm={12} xs={12}> <Typography variant="h5" align="center" component='h2' gutterBottom> See what your friend will receive! </Typography> </Grid> <Grid item sm={12} container justify='center'> <Button onClick={this.handleBtn} color="secondary" size="large" variant="contained" className={this.classes.button} component={linkProps => ( <Link {...linkProps} variant="button" component={linkRouterProps => ( <LinkRouter {...linkRouterProps} to="/gifts-demo" target="_blank" /> )} /> )} > OPEN DEMO </Button> </Grid> </> ); } } export default withStyles(styles)(withRouter(DonationStepDemo));
import React from 'react' import styled, { ThemeProvider } from 'styled-components' import ThemeChildren from '../Components/ThemeChildren' import { Button } from '../Theme/widgets' // @9 theme const theme = { main: "red" }; function Theme() { return ( <> <div> <Button>Normal</Button> <ThemeProvider theme={theme}> <Button>Themed</Button> <ThemeChildren>123</ThemeChildren> </ThemeProvider> </div> </> ) } export default Theme
class IAM { /** * IAM constructor * @constructor * @param {object} aws - AWS SDK * @param {object} options - {apiVersion} */ constructor(aws, options) { this._AWS = aws; this._apiVersion = options.apiVersion; this._iam = new this._AWS.IAM({ apiVersion: this._apiVersion }); } /** * Create IAM Group * @create * @param {object} params */ createGroup(params) { // Create a new IAM Group return new Promise((resolve, reject) => { if (!params) reject(new Error('Provide params to create IAM Group')); this._iam.createGroup(params, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }); } /** * Delete IAM Group * @delete * @param {object} params */ deleteGroup(params) { return new Promise((resolve, reject) => { if (!params) reject(new Error('Provide params to delete IAM group')); this._iam.deleteGroup(params, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }); } /** * Attach policy to a given groups * @attachGroupPolicy * @param {object} params */ attachGroupPolicy(params) { return new Promise((resolve, reject) => { if (!params) reject(new Error('Provde params to attach policy to a group')); this._iam.attachGroupPolicy(params, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }); } /** * Detach policy to a given groups * @detachGroupPolicy * @param {object} params */ detachGroupPolicy(params) { return new Promise((resolve, reject) => { if (!params) reject(new Error('Provide params for detachGroupPolicy')); this._iam.detachGroupPolicy(params, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }) } } module.exports = IAM
import * as actionTypes from '../actions/actionTypes'; import { updateObject } from '../utility'; const initState = { editableMovie: null, loading: false, editingMode: false, error: null } const changeMovieStart = (state, action) => { return updateObject(state, { loading: true }); } const changeMovieSuccess = (state, action) => { return updateObject(state, { editableMovie: action.movie[0], loading: false, editingMode: false }); } const changeMovieFail = (state, action) => { return updateObject(state, { loading: false, error: action.error }); } const cancelMovie = (state, action) => { return updateObject(state, { editingMode: false }); } const changeMovieInit = (state, action) => { return updateObject(state, { editingMode: true }); } const selectedMovie = (state, action) => { return updateObject(state, { editableMovie: action.selectedMovie }); } const fetchSelectedMovieStart = (state, action) => { return updateObject(state, { loading: true } ); } const fetchSelectedMovieFail = (state, action) => { return updateObject(state, { loading: false, error: action.error } ); } const fetchSelectedMovieSuccess = (state, action) => { return updateObject(state, { editableMovie: action.movie, loading: false, editingMode: false }); } const reducer = (state = initState, action) => { switch (action.type) { case actionTypes.CHANGE_MOVIE_START: return changeMovieStart(state, action); case actionTypes.CHANGE_MOVIE_SUCCESS: return changeMovieSuccess(state, action); case actionTypes.CHANGE_MOVIE_FAIL: return changeMovieFail(state, action); case actionTypes.CHANGE_MOVIE_CANCEL: return cancelMovie(state, action); case actionTypes.CHANGE_MOVIE_INIT: return changeMovieInit(state, action); case actionTypes.SELECTED_MOVIE: return selectedMovie(state, action); case actionTypes.FETCH_MOVIE_START: return fetchSelectedMovieStart(state, action); case actionTypes.FETCH_MOVIE_SUCCESS: return fetchSelectedMovieSuccess(state, action); case actionTypes.FETCH_MOVIE_FAIL: return fetchSelectedMovieFail(state, action); default: return state } } export default reducer;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ArcadeBody2DUpdater_1 = require("./ArcadeBody2DUpdater"); const THREE = SupEngine.THREE; const tmpVector3 = new THREE.Vector3(); class ArcadeBody2DMarker extends SupEngine.ActorComponent { constructor(actor) { super(actor, "ArcadeBody2DMarker"); this.offset = new THREE.Vector3(0, 0, 0); this.markerActor = new SupEngine.Actor(this.actor.gameInstance, `Marker`, null, { layer: -1 }); } setIsLayerActive(active) { if (this.line != null) this.line.visible = active; } update() { super.update(); this.markerActor.setGlobalPosition(this.actor.getGlobalPosition(tmpVector3)); } setBox(width, height) { if (this.line != null) this._clearRenderer(); const geometry = new THREE.Geometry(); geometry.vertices.push(new THREE.Vector3(-width / 2, -height / 2, 0.01), new THREE.Vector3(width / 2, -height / 2, 0.01), new THREE.Vector3(width / 2, height / 2, 0.01), new THREE.Vector3(-width / 2, height / 2, 0.01), new THREE.Vector3(-width / 2, -height / 2, 0.01)); const material = new THREE.LineBasicMaterial({ color: 0xf459e4 }); this.line = new THREE.Line(geometry, material); this.markerActor.threeObject.add(this.line); this.setOffset(); } setOffset(x, y) { if (x != null && y != null) this.offset.set(x, y, 0); this.line.position.set(this.offset.x, this.offset.y, 0); this.line.updateMatrixWorld(false); } setTileMap() { if (this.line != null) this._clearRenderer(); // TODO ? } _clearRenderer() { this.markerActor.threeObject.remove(this.line); this.line.geometry.dispose(); this.line.material.dispose(); this.line = null; } _destroy() { if (this.line != null) this._clearRenderer(); this.actor.gameInstance.destroyActor(this.markerActor); this.markerActor = null; super._destroy(); } } /* tslint:disable:variable-name */ ArcadeBody2DMarker.Updater = ArcadeBody2DUpdater_1.default; exports.default = ArcadeBody2DMarker;
 jwplayer("mediaplayer").setup({ flashplayer: "jwplayer/jwplayer.swf", playlist: [{ file: "Media/wheelchairrace.flv", image: "Media/example.jpg", title: "Wheel Chair Race", duration: 5}, { file: "Media/wheelchairrace.flv", image: "Media/example.jpg", title: "Wheel Chair Race", duration: 15 }], controlbar: "none", autostart: "true", icons: "false", stretch: "fill", width: 518, height: 296 // events: { // onComplete: function() { alert("the video is finished!"); } // } }); function addVideo(videoUrl, videoThumb, videoTitle) { var playlist = jwplayer().getPlaylist(); var newItem = { file: videoUrl, image: videoThumb, title: videoTitle }; playlist.push(newItem); jwplayer().load(playlist); }
import styled from 'styled-components'; export const Container = styled.div` width: 100%; height: 110px; display: flex; flex-direction: column; background-image: linear-gradient(to right, #e2f3ff 50%, #9dd8ff); justify-content: space-between; align-items: flex-start; padding: 5px; border-radius: 5px; margin-top: 15px; box-shadow: inset 0 0 10px #000000; `;
const express = require('express'); const router = express.Router(); const mongo = require('mongodb').MongoClient; const createID = require('./services/create-id.js'); const handleHashing = require('./services/handle-hashing.js'); const dbURL = `mongodb://${process.env.DBUSER}:${process.env.DBPASSWORD}@${process.env.DBURL}/${process.env.DBNAME}`; router.get('/polls', async (req, res, next) => { let client = await mongo.connect(dbURL); let db = await client.db(process.env.DBNAME); let collectionPolls = await db.collection('build-a-voting-app-polls'); let findPoll = await collectionPolls.find({}, { projection: { _id: 0 } }).toArray(); client.close(); res.json({ get: true, polls: findPoll }); }); router.post('/poll/id', async (req, res, next) => { if(req.cookies.id) { let client = await mongo.connect(dbURL); let db = await client.db(process.env.DBNAME); let collectionIDs = await db.collection('build-a-voting-app-ids'); let findID = await collectionIDs.findOne({ type: 'polls' }, { projection: { _id: 0, type: 0 } }); let id = createID(findID.list); let query = `list.${id}`; let updateID = await collectionIDs.findOneAndUpdate({ type: 'polls' }, { $set: { [query]: new Date() } }); client.close(); res.json({ create: true, id: id }); } else { // res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true }); res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true, secure: true }); res.json({ create: false, id: null }); } }); router.post('/poll/create', async (req, res, next) => { if(req.cookies.id) { let query = `list.${req.body.id}`; let client = await mongo.connect(dbURL); let db = await client.db(process.env.DBNAME); let collectionPolls = await db.collection('build-a-voting-app-polls'); let insertPoll = await collectionPolls.insertOne(req.body); let collectionIDs = await db.collection('build-a-voting-app-ids'); let updateID = await collectionIDs.findOneAndUpdate({ type: 'polls' }, { $set: { [query]: 'created' } }); client.close(); res.json({ create: true }); } else { // res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true }); res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true, secure: true }); res.json({ create: false }); } }); router.post('/poll/cancel', async (req, res, next) => { if(req.cookies.id) { let query = `list.${req.body.id}`; let client = await mongo.connect(dbURL); let db = await client.db(process.env.DBNAME); let collectionIDs = await db.collection('build-a-voting-app-ids'); let deleteId = await collectionIDs.updateOne({ type: 'polls' }, { $unset: { [query]: '' } }); client.close(); res.json({ delete: true }); } else { res.json({ delete: false }); } }); router.put('/poll/update/:id', async (req, res, next) => { if(req.cookies.id) { let operations = []; if(req.body.changes.editedChoices.length) { req.body.changes.editedChoices.forEach((v, i, a) => { operations.push( { updateOne: { filter: { $and: [{ id: req.params.id }, { owner: req.body.owner }, { 'choices.id': v }] }, update: { $set: { 'choices.$.name': (req.body.poll.choices.find(fv => fv.id === v)).name } } } } ); }); } if(req.body.changes.newChoices.length) { let newChoicesList = []; req.body.changes.newChoices.forEach((v, i, a) => { newChoicesList.push(req.body.poll.choices.find(fv => fv.id === v)); }); operations.push( { updateOne: { filter: { $and: [{ id: req.params.id }, { owner: req.body.owner }] }, update: { $push: { choices: { $each: newChoicesList } } } } } ); } if(req.body.changes.deletedChoices.length) { let deletedChoicesList = req.body.changes.deletedChoices.map((v, i, a) => v); operations.push( { updateOne: { filter: { $and: [{ id: req.params.id }, { owner: req.body.owner }] }, update: { $pull: { choices: { id: { $in: deletedChoicesList } } } } } } ); } if(req.body.changes.pollItems.length) { let pollItemsList = {}; req.body.changes.pollItems.forEach((v, i, a) => { pollItemsList[v] = req.body.poll[v]; }); operations.push( { updateOne: { filter: { $and: [{ id: req.params.id }, { owner: req.body.owner }] }, update: { $set: pollItemsList } } } ); } let client = await mongo.connect(dbURL); let db = await client.db(process.env.DBNAME); let collectionPolls = await db.collection('build-a-voting-app-polls'); let bulkUpdatePoll = await collectionPolls.bulkWrite(operations, { ordered: false }); client.close(); res.json({ update: true }); } else { res.json({ update: false }); } }); router.delete('/poll/delete/:id', async (req, res, next) => { if(req.cookies.id) { let query = `list.${req.params.id}`; let client = await mongo.connect(dbURL); let db = await client.db(process.env.DBNAME); let collectionPolls = await db.collection('build-a-voting-app-polls'); let deletePoll = await collectionPolls.findOneAndDelete({ $and: [{ id: req.params.id }, { owner: req.body.owner }] }); let collectionIDs = await db.collection('build-a-voting-app-ids'); let deleteId = await collectionIDs.updateOne({ type: 'polls' }, { $unset: { [query]: '' } }); client.close(); res.json({ delete: true }); } else { res.json({ delete: false }); } }); router.put('/poll/vote/:id', async (req, res, next) => { let operations = []; if(req.body.username !== null) { let query = `voters.${req.body.username}`; operations.push( { updateOne: { filter: { id: req.params.id }, update: { $set: { [query]: req.body.votes[0] } } } } ); if(req.body.votes[1]) { operations.push( { updateOne: { filter: { $and: [{ id: req.params.id }, { 'choices.id': req.body.votes[1] }] }, update: { $inc: { 'choices.$.votes': -1 } } } } ); } } operations.push( { updateOne: { filter: { $and: [{ id: req.params.id }, { 'choices.id': req.body.votes[0] }] }, update: { $inc: { 'choices.$.votes': 1 } } } } ); let client = await mongo.connect(dbURL); let db = await client.db(process.env.DBNAME); let collectionPolls = await db.collection('build-a-voting-app-polls'); let bulkUpdatePoll = await collectionPolls.bulkWrite(operations, { ordered: false }); client.close(); res.json({ update: true }); }); router.post('/user/checkname', async (req, res, next) => { let client = await mongo.connect(dbURL); let db = await client.db(process.env.DBNAME); let collectionIDs = await db.collection('build-a-voting-app-ids'); let findID = await collectionIDs.findOne({ type: 'users' }, { projection: { _id: 0, type: 0 } }); client.close(); let takenUsernames = Object.entries(findID).map((v, i, a) => v[1]); if(takenUsernames.indexOf(req.body.username) === -1) { res.json({ taken: false }); } else { res.json({ taken: true }); } }); router.post('/user/create', async (req, res, next) => { if(!req.cookies.id) { let data = {}; data.username = req.body.username; data.email = handleHashing(req.body.email); data.password = handleHashing(req.body.password); let client = await mongo.connect(dbURL); let db = await client.db(process.env.DBNAME); let collectionIDs = await db.collection('build-a-voting-app-ids'); let findID = await collectionIDs.findOne({ type: 'users' }, { projection: { _id: 0, type: 0 } }); let id = createID(findID.list); data.id = id; let query = `list.${id}`; let insertID = await collectionIDs.findOneAndUpdate({ type: 'users' }, { $set: { [query]: req.body.username } }); let collectionUsers = await db.collection('build-a-voting-app-users'); let insertUser = await collectionUsers.insertOne(data); client.close(); let date = new Date(); date.setDate(date.getDate() + 1); // res.cookie('id', id, { expires: date, path: '/', httpOnly: true }); res.cookie('id', id, { expires: date, path: '/', httpOnly: true, secure: true }); res.json({ create: true, expire: date.getTime() }); } else { // res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true }); res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true, secure: true }); res.json({ create: false }); } }); router.post('/user/login', async (req, res, next) => { if(!req.cookies.id) { let client = await mongo.connect(dbURL); let db = await client.db(process.env.DBNAME); let collectionUsers = await db.collection('build-a-voting-app-users'); let findUser = await collectionUsers.findOne({ username: req.body.username }); client.close(); if(!findUser) { res.json({ get: false }); } else { let password = await handleHashing(req.body.password, findUser.password.salt); if(password.hash !== findUser.password.hash) { res.json({ get: false }); } else { let date = new Date(); date.setDate(date.getDate() + 1); // res.cookie('id', findUser.id, { expires: date, path: '/', httpOnly: true }); res.cookie('id', findUser.id, { expires: date, path: '/', httpOnly: true, secure: true }); res.json({ get: true, expire: date.getTime() }); } } } else { // res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true }); res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true, secure: true }); res.json({ get: false }); } }); router.post('/user/logout', async (req, res, next) => { // res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true }); res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true, secure: true }); res.json({ logout: true }); }); router.post('/user/edit', async (req, res, next) => { if(!req.cookies.id) { let client = await mongo.connect(dbURL); let db = await client.db(process.env.DBNAME); let collectionUsers = await db.collection('build-a-voting-app-users'); let findUser = await collectionUsers.findOne({ username: req.body.username }); let email = await handleHashing(req.body.email, findUser.email.salt); if(!findUser || email.hash !== findUser.email.hash) { client.close(); res.json({ update: false }); } else { let password = await handleHashing(req.body.password); let updateUser = await collectionUsers.updateOne({ username: req.body.username }, { $set: { password: { hash: password.hash, salt: password.salt } } }); client.close(); let date = new Date(); date.setDate(date.getDate() + 1); // res.cookie('id', findUser.id, { expires: date, path: '/', httpOnly: true }); res.cookie('id', findUser.id, { expires: date, path: '/', httpOnly: true, secure: true }); res.json({ update: true, expire: date.getTime() }); } } else { // res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true }); res.cookie('id', '', { expires: new Date(), path: '/', httpOnly: true, secure: true }); res.json({ update: false }); } }); module.exports = router;
/* * productCategoryComponent.js * * Copyright (c) 2017 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ 'use strict'; /** * Code Table -> generic code table component. * * @author m314029 * @since 2.21.0 */ (function () { var app = angular.module('productMaintenanceUiApp'); app.component('genericCodeTable', { scope: '=', // Inline template which is binded to message variable in the component controller templateUrl: 'src/codeTable/generic/genericCodeTable.html', bindings: { tableSelected: '<' }, // The controller that handles our component logic controller: GenericCodeTableController }); GenericCodeTableController.$inject = ['GenericCodeTableApi', 'ngTableParams']; /** * Generic code table's controller definition. * @constructor */ function GenericCodeTableController(genericCodeTableApi, ngTableParams) { /** All CRUD operation controls of product category page goes here */ var self = this; self.codeTableParams = null; self.newCodes = []; self.isAddingCode = false; const DEFAULT_PAGE = 1; const DEFAULT_PAGE_SIZE = 20; const CODE_TABLE_BUILD_ERROR_PRETEXT = "Error getting code table data: "; /** * Standard AngularJS function ($onChanges) implementation. Used to catch change events of the objects that * bound to this component (bindings can be found listed in the component definition above). */ self.$onChanges = function () { resetDefaults(); fetchDataForCodeTable(); }; /** * Resets defaults for controller. */ function resetDefaults(){ self.error = null; } /** * Gets all data for code table by calling back end. */ function fetchDataForCodeTable(){ var parameters = {}; parameters.tableName = self.tableSelected.codeTableName; self.isWaitingForResponse = true; genericCodeTableApi.findAllByTable( parameters, loadData, function(error){ loadData([]); buildError(CODE_TABLE_BUILD_ERROR_PRETEXT, error); } ) } /** * Create the ngTable with the given results. * * @param results Code table records. */ function loadData(results){ self.isWaitingForResponse = false; self.codeTableParams = new ngTableParams( { page: DEFAULT_PAGE, /* show first page */ count: DEFAULT_PAGE_SIZE /* count per page */ }, { counts: [], debugMode: false, data: results } ) } /** * Builds the error given a pre-text string, and api error message. * * @param errorPreText Pre-text for an error message. * @param error Error message from api. */ function buildError(errorPreText, error){ self.error = errorPreText + getError(error); self.isWaitingForResponse = false; } /** * Gets the error given an api error message. * * @param error Error message from api. * @returns {string} */ function getError(error){ if (error && error.data) { if(error.data.message) { return error.data.message; } else { return error.data.error; } } else { return "An unknown error occurred."; } } /** * Edit current row of code data. * @param code * @param index */ self.editCode = function(code, index){ self.previousEditingIndex = index; self.currentEditingObject = angular.copy(code); self.isEditing = true; }; /** * Set codeToRemove. */ self.setRemoveCode = function(code){ self.codeToRemove = code; }; /** * Reset codeToRemove. */ self.cancelRemove = function(){ self.codeToRemove = null; }; /** * Call back end to remove a code. */ self.removeCode = function () { if(self.codeToRemove) { genericCodeTableApi.deleteCodeByTableNameAndId( {tableName: self.tableSelected.codeTableName, id: self.codeToRemove.id }, self.onSuccess, self.onError ); } }; /** * Call back end to save a code. */ self.saveCode = function (item) { self.isWaitingForResponse = true; var genericCodeTableUpdate = {tableName : self.tableSelected.codeTableName, codeTables: item}; genericCodeTableApi.saveCodeByTableNameAndCodeTable(genericCodeTableUpdate, self.onSuccess, self.onError ); }; /** * Sets up parameters for the new code modal. */ self.addCodeModal = function () { self.isAddingCode = true; self.newCodes = []; self.newCodes.push({id: '', description: ''}); }; /** * Adds a new empty row into the add new code table. */ self.addNewCodeRow = function () { self.newCodes.push({id: '', description: ''}); }; /** * Returns true if the currently editing index is the same as previous editing index. * * @param index * @returns {boolean} */ self.compareEditingIndexToCurrentIndex = function(index) { return self.previousEditingIndex != null && self.previousEditingIndex === index; }; /** * Returns true is there are changes in the current editing object and the description isn't empty. * @param code * @returns {boolean} */ self.isCodeChangesAndNotEmpty = function(code) { return JSON.stringify(self.currentEditingObject) !== JSON.stringify(code) && code.description; }; /** * Cancel edit of row for a code * @param index */ self.cancelEdit = function(item, index) { self.previousEditingIndex = null; item.description = self.currentEditingObject.description; }; /** * Resets parameters when closing the add new code modal. */ self.confirmAddNewCodeModalClose = function() { var isData = false; if(self.newCodes.length >0) { for(var x=0; x<self.newCodes.length; x++){ if(self.newCodes[x].id || self.newCodes.description){ isData = true; break; } } } if(isData) { $('#cancelAddCodeModal').modal("show"); } else { self.newCodesError = ""; self.isAddingCode = false; $('#addCodeModal').modal("hide"); } }; /** * Validates codes and makes a backend call to save the codes to add. */ self.saveNewCodes = function () { $('#cancelAddCodeModal').modal("hide"); var codes = self.validateNewCodes(); if(!self.newCodesError) { self.isWaitingAddingCodes = true; var genericCodeTableUpdate = {tableName : self.tableSelected.codeTableName, codeTables: codes}; genericCodeTableApi.addAllByTableNameAndCodeTables(genericCodeTableUpdate, self.saveNewCodesSuccess, self.saveNewCodesError ); } }; /** * Success callback function that hides the spinner and add code modal. * @param result */ self.saveNewCodesSuccess = function(result) { self.isWaitingAddingCodes = false; self.isAddingCode = false; self.success = result.message; $('#addCodeModal').modal("hide"); fetchDataForCodeTable(); }; /** * Error callback when adding a new code. * * @param error */ self.saveNewCodesError = function(error) { self.isWaitingAddingCodes = false; self.newCodesError = error; }; /** * Validates whether or not a code is available. * * @param index */ self.isCodeAvailable = function(index) { if(self.newCodes[index].id) { genericCodeTableApi.findCodeByTableNameAndId( {tableName: self.tableSelected.codeTableName, id: self.newCodes[index].id }, function(results) { self.newCodes[index].isCodeAvailable = !results.id; }, function(error){ buildError(CODE_TABLE_BUILD_ERROR_PRETEXT, error); } ); } else { self.newCodes[index].isCodeAvailable = undefined; } }; /** * Validates the new codes to see if list is empty, there are duplicates, missing values, etc, and returns the list * if valid. * @returns {*} */ self.validateNewCodes = function () { self.newCodesError = ""; var duplicateCodes = false; var unavailableCodes = false; var missingCode = false; var missingDescription = false; var codes = []; for(var x=0; x< self.newCodes.length; x++) { if(!self.newCodes[x].isCodeAvailable && self.newCodes[x].id) { unavailableCodes = true; } if(self.newCodes[x].id) { if(!self.newCodes[x].description) { missingDescription = true; } else { codes.push(self.newCodes[x]); } for (var y = 0; y < self.newCodes.length; y++) { if (x !== y) { if (self.newCodes[x].id === self.newCodes[y].id) { duplicateCodes = true; } } } } else if (self.newCodes[x].description) { missingCode = true; codes.push(self.newCodes[x]); } } if(unavailableCodes) { self.newCodesError += "ERROR: Some of the chosen codes were unavailable. Please select an available code. "; } if(duplicateCodes) { self.newCodesError += "ERROR: Duplicate codes chosen. Please remove the duplicates and try again. "; } if(missingCode) { self.newCodesError += "ERROR: Some of the codes contain a description that is missing a code ID. "; } if(missingDescription) { self.newCodesError += "ERROR: Some of the codes contain an ID that is missing a description. "; } if(codes.length === 0) { self.newCodesError += "ERROR: Please enter a code and description to save. "; return undefined; } else { return codes; } }; /** * Closes add new code confirmation modal. */ self.closeAddNewCodeConfirmModal = function() { $('#cancelAddCodeModal').modal("hide"); }; /** * Closes add new codes modal. */ self.closeAddNewCodeModals = function() { $('#cancelAddCodeModal').modal("hide"); $('#addCodeModal').modal("hide"); }; /** * Success callback that fetches new data. * @param results */ self.onSuccess = function(results) { self.success = results.message; self.isAddingCode = false; self.isEditing = false; self.previousEditingIndex = null; fetchDataForCodeTable(); }; /** * Error callback. * @param results */ self.onError = function(results) { self.error = results.message; self.isWaitingForResponse = false; }; } })();
var nextGreaterElements = function(nums) { let newArr = []; let max = nums[0]; nums.forEach(num => { max = Math.max(num, max) }) nums.forEach(num => { if (num < max) { newArr.push(max) } else { newArr.push(-1); } }) return newArr }; // var nextGreaterElements = function(nums) { // let newArr = []; // // let max = nums[0]; // // nums.forEach(num => { // // max = Math.max(num, max) // // }) // for (let i = 0; i < nums.length; i++) { // let num = nums[i]; // let j = i+1; // let found = false; // while (j !== i) { // if (j >= nums.length) { // j = 0; // console.log(j, i) // }else if (nums[j] > num) { // found = true; // newArr.push(nums[j]) // j = i; // } else { // j++; // } // } // if (!found) { // newArr.push(-1) // } // } // return newArr // }; console.log(nextGreaterElements([5,4,3,2,1])) console.log(nextGreaterElements([2,3,1,2,1]))
import conTable from './src/conTable'; conTable.install = function(Vue) { Vue.component(conTable.name, conTable); }; export default conTable;
"use string" function done(){ let na = document.getElementById('n').value; if(!na == ""){ var str = na; var n = str.length; if(n > 1){ var st = [a-z]; var m = st.localCompare(str); if(m == 0){ alert(na); } else{ alert('name should contain a-z'); } } else{ alert('name should be atleast 2 words!!'); } } else{ alert('empty'); } }
import React from 'react' import TransportTiny from './TransportTiny' import HotelTiny from './HotelTiny' import PlaceTiny from './PlaceTiny' import EventTiny from './EventTiny' import BagTiny from './BagTiny' import { Button, Card, Grid, Image, Message, List, Icon, Modal, Form } from 'semantic-ui-react' const SingleTripDetails = (props) => { return ( <div> <Button fluid onClick={props.handleBackClick}> Go Back </Button><br/> <Card.Group> <Card fluid> <Card.Content> <Grid> <Grid.Row> <Grid.Column width={3}/> <Grid.Column width={9}> <Card.Header as='h3'>{props.trip.title}</Card.Header> </Grid.Column> <Grid.Column width={4}/> </Grid.Row> <Grid.Row textAlign='left'> <Grid.Column width={11} > <Message size='large' className='trip-details' > {props.trip.description} </Message> </Grid.Column> <Grid.Column width={5}> <Image src={props.trip.photo}/> <List divided relaxed> <List.Item> <div className='padding'> <List.Icon color='black' name='money bill alternate outline' size='large' /> ${props.trip.budget} </div> </List.Item> <List.Item> <div className='padding'> <List.Icon color='black' name='sign in' size='large' /> {props.formatDate(props.trip.start_date)} </div> </List.Item> <List.Item> <div className='padding'> <List.Icon color='black' name='sign out' size='large' /> {props.formatDate(props.trip.end_date)} </div> </List.Item> </List> </Grid.Column> </Grid.Row> <Grid.Row columns={2}> <Grid.Column> <Message> <AddButton trip={props.trip} name='transportations' handleTripUpdatedEvents={props.handleTripUpdatedEvents}/> <Message.Header content='Flights/Transportation'/> {props.trip.transportations.length > 0 ? props.trip.transportations.map(transport => <TransportTiny key={transport.id} transport={transport} transportEdit={props.transportEdit} handleDeletedTransport={props.handleDeletedTransport} formatTime={props.formatTime} formatDate={props.formatDate} />) : <br/> } </Message> </Grid.Column> <Grid.Column > <Message> <AddButton trip={props.trip} name='hotels' handleTripUpdatedEvents={props.handleTripUpdatedEvents} /> <Message.Header content='Hotels'/> {props.trip.hotels.length > 0 ? props.trip.hotels.map(hotel => <HotelTiny key={hotel.id} hotel={hotel} hotelEdit={props.hotelEdit} handleDeletedHotel={props.handleDeletedHotel} formatTime={props.formatTime} formatDate={props.formatDate} />) : <br/> } </Message> </Grid.Column> </Grid.Row> <Grid.Row columns={3}> <Grid.Column > <Message> <AddButton trip={props.trip} name='places' handleTripUpdatedEvents={props.handleTripUpdatedEvents} /> <Message.Header content='Places'/> {props.trip.places.length > 0 ? props.trip.places.map(place => <PlaceTiny key={place.id} place={place} placeEdit={props.placeEdit} handleDeletedPlace={props.handleDeletedPlace} formatTime={props.formatTime} />) : <br/> } </Message> </Grid.Column> <Grid.Column > <Message> <AddButton trip={props.trip} name='events' handleTripUpdatedEvents={props.handleTripUpdatedEvents} /> <Message.Header content='Events'/> {props.trip.events.length > 0 ? props.trip.events.map(event => <EventTiny key={event.id} event={event} eventEdit={props.eventEdit} handleDeletedEvent={props.handleDeletedEvent} formatTime={props.formatTime} />) : <br/> } </Message> </Grid.Column> <Grid.Column > <Message> <AddBagButton trip={props.trip} name='carryons' createCarryOn={props.createCarryOn} handleTripUpdatedEvents={props.handleTripUpdatedEvents} /> <Message.Header content='Bags' /> {props.trip.carryons.length > 0 ? props.trip.carryons.map(bag => <BagTiny key={bag.id} bag={bag} />) : <br/> } </Message> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={16}> <List divided horizontal> <List.Item> <EditModal trip={props.trip} handleTripEditClick={props.handleTripEditClick} /> </List.Item> <List.Item> <a href='' onClick={(e) => {props.handleDeleteClick(e, props.trip)}}> Delete </a> </List.Item> </List> </Grid.Column> </Grid.Row> </Grid> </Card.Content> </Card> </Card.Group> </div> ) } class EditModal extends React.Component { constructor () { super () this.state = { title: '', budget: 0, description: '', start_date: '', end_date: '', photo: '', miles: 0 } } componentDidMount () { let tripCopy = {...this.props.trip} this.setState({ title: tripCopy.title, budget: tripCopy.budget, description: tripCopy.description, start_date: tripCopy.start_date, end_date: tripCopy.end_date, photo: tripCopy.photo, miles: tripCopy.miles }) } changeHandler = (e) => { this.setState({ [e.target.id]: e.target.value }) } submitHandler = (e) => { e.preventDefault() let selectedTrip = {...this.props.trip} this.props.handleTripEditClick(selectedTrip, this.state) } render () { return ( <Modal size='small' dimmer='blurring' trigger={<a href=''>Edit Trip Info</a>} closeIcon closeOnDimmerClick > <Modal.Header> {this.props.trip.title} </Modal.Header> <Modal.Content> <Form onSubmit={(e) => this.submitHandler(e)} onChange={(e) => this.changeHandler(e)} > <Form.Group> <Form.Input width='11' id='title' label='Trip Title' value={this.state.title}/> <Form.Input width='5' id='budget' label='Budget' type='number' value={this.state.budget}/> </Form.Group> <Form.TextArea id='description' label='Description' value={this.state.description}/> <Form.Group> <Form.Input id='start_date' label='Start Date' type='date' value={this.state.start_date}/> <Form.Input id='end_date' label='End Date' type='date' value={this.state.end_date}/> <Form.Input id='photo' label='Photo URL' /> </Form.Group> <Form.Button type='submit' floated='right' >Submit</Form.Button> </Form><br/><br/> </Modal.Content> </Modal> ) } } const AddButton = (props) => { const createNewItem = () => { fetch(`http://localhost:3000/${props.name}`, { method: 'POST', body: JSON.stringify({ trip_id: props.trip.id, name: 'Click to Edit' }), headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }) .then(resp => resp.json()) .then(data => props.handleTripUpdatedEvents(props.name, data)) } return ( <Button onClick={() => createNewItem(props)} icon compact basic floated='left' size='mini'> <Icon name='plus'/> </Button> ) } class AddBagButton extends React.Component { constructor () { super() this.state = { bags: [], bag_id: '' } } options = [] fetchBags = () => { fetch('http://localhost:3000/luggages') .then(resp => resp.json()) .then(data => { let bags = data.filter(bag => bag.user_id === parseInt(localStorage.current_user_id)) bags.forEach(bag => this.options.push({id: bag.id, text: `${bag.name} - ${bag.luggage_type}`, value: bag.name})) }) } handleChange = (e) => { this.setState({ bag_id: e.currentTarget.id }) } render () { this.fetchBags() return ( <Modal size='mini' dimmer='blurring' trigger={<Button icon compact basic floated='left' size='mini'><Icon name='plus'/></Button>} closeIcon closeOnDimmerClick > <Modal.Content> <Form onSubmit={() => this.props.createCarryOn(this.state.bag_id, this.props.trip.id)}> <Form.Select fluid label='Select a Bag' onChange={(e) => this.handleChange(e)} options={this.options} /> <Form.Button type='submit' floated='right' >Submit</Form.Button><br/><br/> </Form> </Modal.Content> </Modal> ) } } export default SingleTripDetails
module.exports = require('./lib/super-object-mapper');
import React from 'react' import PropTypes from 'prop-types' class SimpleComponent extends React.Component { componentDidMount() { const { lifeCycleCallback, todoList } = this.props lifeCycleCallback('didMount', todoList) } componentDidUpdate() { const { lifeCycleCallback, todoList } = this.props lifeCycleCallback('didUpdate', todoList) } render() { const { title } = this.props return ( <div className="simple-normal-component"> <h1>{title}</h1> </div> ) } } SimpleComponent.propTypes = { title: PropTypes.string.isRequired, todoList: PropTypes.array.isRequired, lifeCycleCallback: PropTypes.func.isRequired, } export default SimpleComponent
import styled from 'styled-components'; import Theme from './Theme'; const Select = styled.select` border-radius: 10px; padding: 0.3rem; margin: 1rem 0 1rem 0; border: none; background-color: white; box-shadow: 0px 3px 5px 2px rgba(0, 0, 0, 0.3); &:hover { border: 1px solid ${Theme.fiverrGreen}; } &:focus { outline: none; border: 1px solid ${Theme.fiverrGreen}; } `; export default Select;
/** * Created by MACHENIKE on 2017/2/19. */ export const GET_PRODUCTS = 'GET_PRODUCTS' export const ADD_PRODUCTS = 'ADD_PRODUCTS' export const REMOVE_PRODUCTS = 'REMOVE_PRODUCTS' export const GET_LIST = 'GET_LIST'
const chalk = require('chalk'); module.exports = function(){ console.log(chalk.yellow( `EXERCISE 15: Write a small function called "getSmallest" that takes a parameter called "arr" and returns the smallest of all the numbers in "arr". For example: getSmallest([1,2,3]) should return 1 getSmallest([-5,100,-7]) should return -7 getSmallest([1,0,3,2]) should return 0 ` )); process.exit(); };
import React from 'react'; import { Link } from 'react-router'; import { connect, dispatch } from 'react-redux'; import { Field, reduxForm } from 'redux-form' var AddComment = props => { const { handleSubmit } = props; const fieldStyle = { width: "100%" } const containerStyle = { padding: "5px" } return ( <div style={containerStyle}> <form form={props.form} key={props.id} onSubmit={handleSubmit}> <div className="row"> <div className="col-10"> <Field style={fieldStyle} name="title" placeholder="Subject" component="input" type="text"/> </div> <div className="col-2"> <button className="btn btn-secondary" style={fieldStyle} type="submit"> {props.submitText} </button> </div> </div> <div className="row"> <div className="col-12"> <Field style={fieldStyle} name="description" placeholder="Comment" component="textarea" type="text"/> </div> </div> <div className="row"> </div> </form> </div> ) } AddComment = reduxForm({ form: 'addComment' })(AddComment) export default AddComment;
function PigNose(tx, ty, ts) { this.x = tx; this.y = ty; this.size = ts; this.angle = 0; this.update = function(mx, i,j) { this.x = i; this.y = j; this.angle += mx; //this.angle = atan2(my - this.y, mx - this.x); }; this.display = function() { push(); translate(this.x, this.y); fill(effectColor.r,effectColor.g,effectColor.b,effectColor.a); ellipse(0, 0, this.size, this.size * 0.9); fill(effectColor.r/2,effectColor.g/2,effectColor.b/2,effectColor.a); ellipse(this.size / 4, 0, this.size / 2.4, this.size / 2.4); ellipse(this.size / 4 - 30, 0, this.size / 2.4, this.size / 2.4); pop(); }; }
export const updateDevices = (devices, newValues) => { const newDevices = []; (devices || []).map((device) => { newDevices.push({ ...device, ...newValues }); }); return newDevices; };
import styled from 'styled-components' import {Link} from 'react-router-dom' export const Inner = styled.div` display: flex; align-items: center; justify-content: space-between; flex-direction: ${({direction}) => direction}; max-width: 1100px; margin: auto; width: 100%; @media (max-width: 1000px) { flex-direction: column; } ` export const Pane = styled.div` width: 33%; @media (max-width: 1000px) { width: 100%; padding: 0 45px; text-align: center; } `; export const Category = styled.div` display: flex; border-bottom: 1px solid #eb8c2d; padding: 50px 5%; color: white; overflow: hidden; &:last-child { border:none; } `; export const Container = styled.section` background-color: #1c1c1c; @media (max-width: 1000px) { ${Category}:last-of-type h2 { margin-bottom: 50px; } } `; export const Title = styled.h1` font-size: 50px; line-height: 1.1; margin-bottom: 8px; color: #dedede; @media (max-width: 600px) { font-size: 35px; } `; export const SubTitle = styled.h2` font-size: 22px; font-weight: normal; line-height: normal; color: #dedede; @media (max-width: 600px) { font-size: 18px; } `; export const Image = styled.img` max-width: 100%; height: auto; `; export const Button = styled(Link)` background-color: #eb8c2d; padding: 1em 2em; text-decoration: none; text-transform: uppercase; font-weight: bold; letter-spacing: 1.6; color: #dedede; @media (max-width: 600px){ margin-top: 2em; } &:hover { background-color: #e87909; } `
const { createDB } = require('./../js/create.js') var db = createDB() db.serialize(function() { var stmt = db.prepare("INSERT INTO files (name, full_path, date_added) VALUES (?, ?, datetime())"); for (var i = 0; i < 10; i++) { stmt.run( [ `file_number_${i}`, `~/full/file/path/file_number_${i}.jpg`, ] ); } }); db.close();
export const ADD = 'Added' export const DELETE = 'Deleted' export const UPDATE = 'Updated' export const INITIALIZE = 'Initialized'