text
stringlengths
7
3.69M
const db = require('../utils/db'); const bankParser = require('../utils/bankparser'); const transaction = require('../utils/transaction'); const redeemCredits = (req, res, next) => { // TODO check last access to prevent too many requests // TODO cycle pages until no entry is left bankParser.getPayIns() .then(async (entries) => { console.log(entries); res.json(entries); let transactions = []; for (const entry of entries) { const foundTransaction = await db.query('find', 'transactions', { timestamp: entry.timestamp, sender: entry.sender, receiver: entry.receiver, amount: entry.amount }).catch(() => null); if (!foundTransaction[0]) transactions.push(transaction.createTransactionFromSystem(entry).catch(() => null)); } return Promise.all(transactions).catch(next); }) .catch(next) }; module.exports = { redeemCredits };
var $ = require('./js/lib/jquery'); var Carousel = require('./js/app/Carousel'); var GoTop = require('./js/app/Gotop'); var Exposure = require('./js/app/Exposure'); Carousel.init($('.carousel')); new GoTop; Exposure.init($('img, .about li'), function($node) { showImg($node) }); function showImg($img) { var imgUrl = $img.attr('data-src'); $img.attr('src', imgUrl); }
$(function() { var postAt = ""; var oldValue = "NEW"; $("input#postId").blur(function() { var val = $(this).val(); if(val == oldValue) return; oldValue = val; if(val == "" || val == "NEW" || !Number.isInteger(parseInt(val))) { $("input, textarea").val(""); $(this).val("NEW"); return; } $.post("scripts/getPost.php", {postId: val}, function(data) { $("input[name=username]").val(data.author); $("input#title").val(data.title); $("input#image").val(data.image); $("select[name=type]").val(data.type); $("textarea#body").val(data.content); postAt = data.at; $("input").change(); }, "json"); }); function insertAtCaret(e,t){var a=document.getElementById(e),c=a.scrollTop,l=0,n=a.selectionStart||"0"==a.selectionStart?"ff":document.selection?"ie":!1;if("ie"==n){a.focus();var r=document.selection.createRange();r.moveStart("character",-a.value.length),l=r.text.length}else"ff"==n&&(l=a.selectionStart);var o=a.value.substring(0,l),s=a.value.substring(l,a.value.length);if(a.value=o+t+s,l+=t.length,"ie"==n){a.focus();var r=document.selection.createRange();r.moveStart("character",-a.value.length),r.moveStart("character",l),r.moveEnd("character",0),r.select()}else"ff"==n&&(a.selectionStart=l,a.selectionEnd=l,a.focus());a.scrollTop=c} // courtesy of http://stackoverflow.com/questions/1064089/inserting-a-text-where-cursor-is-using-javascript-jquery var title, author, content, at, image, type, json; $("input,textarea,select").change(function() { var now = new Date(); var newBody = $("#body").val() .replace(/\n/g,"\\n") .replace(/\t/g,"\\t") .replace(/'/g, "\\'"); while(/<pre class="brush:[^"]+">[^<]*<(?!\/pre).*<\/pre>/g.test(newBody)) newBody = newBody.replace(/(<pre class="brush:[^"]+">[^<]*)<(?!\/pre)(.*<\/pre>)/g, "$1&lt;$2"); while(/<pre class="brush:[^"]+">[^>]*(?!pre)>.*<\/pre>/g.test(newBody)) { var reachedEnd = false; newBody = newBody.replace(/(<pre class="brush:[^"]+">[^>]*)(pre)?>(.*<\/pre>)/g, function(m1, m2, m3) { if(m2) { reachedEnd = true; return m1; } else { return m1 + "&gt;" + m3; } }); if(reachedEnd) { break; } } $("textarea#newBody").val(newBody); title = $("#title").val(); content = newBody .replace(/\\n/g, "\n") .replace(/\\t/g, "\t"); author = $("input[name=username]").val(); at = ($("#postId").val() != "NEW") ? postAt : (now.getMonth() + 1) + "/" + (now.getDate()) + "/" + (now.getFullYear() - 2000) + " @ " + (now.getHours() == 0 ? 12 : now.getHours() > 12 ? now.getHours() - 12 : now.getHours()) + ":" + (now.getMinutes().toString().length == 1 ? "0" : "") + now.getMinutes() + (now.getHours() < 12 ? "AM" : "PM"); image = $("input#image").val(); type = $("select[name=type]").val(); json = { title: title, content: content, author: author, at: at, image: image, type: type }; var newElement = $("<div>"); newElement.addClass("post"); newElement.append("<span class='details'>By " + json.author + "<br />On " + json.at + "</span>"); newElement.append("<span class='title'><a href='http://www.thehomeworklife.co.nf/index.html?post=" + -1 + "'>" + json.title + "</a></span>"); newElement.append("<span class='shareContainer'></span>"); newElement.append("<blockquote class='content'><div class='postImageContainer'><img class='postImageLarge' src='" + json.image + "' title='Click to expand' /></div>" + json.content + "</blockquote>"); newElement.append("<span class='share'><input class='shareUrl' type='text' value='" + /*$("base").attr("href") + "post/"*/ "http://www.thehomeworklife.co.nf/index.html?post=" + -1 + "' readonly onclick='this.select();this.setSelectionRange(0, this.value.length)' /><span class='type " + json.type + "' title='Click to search others of tag [" + json.type + "]'>" + json.type + "</span></span>"); $("blockquote#preview").html(newElement); }); $("textarea#body").keydown(function(event) { if(event.which == 9) { event.preventDefault(); insertAtCaret("body","\t"); } }); $("button#submit").click(function() { json.password = $("input[name=password]").val(); json.newPost = $("input#postId").val() == "NEW" ? "TRUE" : $("input#postId").val(); $.ajax({ url: "scripts/addPost.php", data: json, method: "post", success: function(response) { alert("Success: " + response); $.get("scripts/generateRss.php"); }, error: function(test, test2, error) { alert("ERROR: " + test + " " + test2 + " " + error); }, dataType: "text" }); }); });
$(function(){ //get the caller tabId var tabId = parseInt(window.location.search.substring(1)); var tamperStarted = false; chrome.webRequest.onBeforeSendHeaders.addListener( function(details) { $('#logs').append("<li>request made on tab: "+details.requestId + "</li>"); //if tampering is started, ask to tamper request. if(tamperStarted == true) { if(confirm("Tamper url: "+ details.url)) { var r = window.showModalDialog('tamper.html', details, "dialogwidth: 450; dialogheight: 300; resizable: yes"); } } return; //{requestHeaders: details.requestHeaders}; }, {urls: ["<all_urls>"], tabId : tabId}, ["blocking", "requestHeaders"] ); //UI interactions $('#btnTamperToggle').click(function(){ tamperStarted = !tamperStarted; if(tamperStarted) { $(this).html('Stop'); } else { $(this).html('Start'); } }); });
const router = require('express').Router() const path = require('path') const fs = require('fs') // @ ~/.well-known/acme-challenge/{hash} router.get(process.env.SSL_PATH, (req, res, next) => { res.sendFile(path.join(__dirname, 'ssl-cert')) }) module.exports = router
import React, { Component } from "react"; import ActivateAccount from "../../components/auth/ActivateAccount"; import { activateAccount } from "../../apiCalls/auth/activateAccountActions"; import { ACTIVATEACCOUNT_SUCCES_MESSAGE } from "../../constants"; class ActivateAccountContainer extends Component { constructor(props) { super(props); this.state = { err: null, success_message: "" }; this.handleActivateAccount = this.handleActivateAccount.bind(this); } componentDidMount() { this.handleActivateAccount( this.props.match.params.uid, this.props.match.params.token ); } async handleActivateAccount(uid, token) { if (this.state.err !== null || this.state.success_message !== "") { this.setState({ err: null, success_message: "" }); } try { await activateAccount(uid, token); return this.setState({ success_message: ACTIVATEACCOUNT_SUCCES_MESSAGE, err: null }); } catch (err) { return this.setState({ success_message: "", err }); } } render() { const { success_message, err } = this.state; return <ActivateAccount success_message={success_message} err={err} />; } } export default ActivateAccountContainer;
var searchData= [ ['sf_5fbroadcast_5finfo_5fvar',['SF_BROADCAST_INFO_VAR',['../sndfile_8h.html#ac029684516383fab298a406c625a7d8d',1,'sndfile.h']]], ['sf_5fcart_5finfo_5fvar',['SF_CART_INFO_VAR',['../sndfile_8h.html#a502df5fca6cdcd9f5b076c2b989bc125',1,'sndfile.h']]], ['sf_5fcount_5fmax',['SF_COUNT_MAX',['../sndfile_8h.html#a2a594c90b41e9b0140f28724f80b763a',1,'sndfile.h']]], ['sf_5fcues_5fvar',['SF_CUES_VAR',['../sndfile_8h.html#a01418c0b27e026aee7b718533bb4f7f9',1,'sndfile.h']]], ['sf_5fstr_5ffirst',['SF_STR_FIRST',['../sndfile_8h.html#a4e4fb6e7419fa77d21641397c5afd702',1,'sndfile.h']]], ['sf_5fstr_5flast',['SF_STR_LAST',['../sndfile_8h.html#a8c6c81346fe61df488dd3231d4c90110',1,'sndfile.h']]], ['size_5fof_5ffatal',['SIZE_OF_FATAL',['../server_8c.html#a72aed21dd91ceea26ffe09ce4391933a',1,'server.c']]], ['sndfile_5f1',['SNDFILE_1',['../sndfile_8h.html#a01907163d623742301e6475255653414',1,'sndfile.h']]], ['system',['SYSTEM',['../util_8c.html#a21b97df85e65556468b28a576311271c',1,'util.c']]] ];
editBannerImageFunction = function (row, store) { var status = 0; if (row != null) { status = row.data.banner_status; } Ext.apply(Ext.form.VTypes, { daterange: function (val, field) { var date = field.parseDate(val); if (!date) { return; } if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) { var start = Ext.getCmp(field.startDateField); start.setMaxValue(date); start.validate(); this.dateRangeMax = date; } else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) { var end = Ext.getCmp(field.endDateField); end.setMinValue(date); end.validate(); this.dateRangeMin = date; } return true; } }); var editBannerImageFrm = Ext.create('Ext.form.Panel', { id: 'editBannerImageFrm', frame: true, plain: true, constrain: true, defaultType: 'textfield', autoScroll: true, layout: 'anchor', url: '/Website/BannerImageEdit', defaults: { anchor: "95%", msgTarget: "side", labelWidth: 60 }, items: [ { xtype: 'displayfield', fieldLabel: '圖片位置', id: 'site_name', name: 'site_name', value: document.getElementById('sname').value }, { xtype: 'displayfield', fieldLabel: '流水號', id: 'banner_content_id', name: 'banner_content_id', hidden: row == null ? true : false, submitValue: true }, { xtype: 'textfield', fieldLabel: '文字', id: 'banner_title', name: 'banner_title', submitValue: true }, { xtype: 'textfield', fieldLabel: '連結', id: 'banner_link_url', name: 'banner_link_url', submitValue: true, vtype: 'url' }, { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', width: 500, items: [ { xtype: 'displayfield', fieldLabel: '開啟模式' }, { xtype: 'radiogroup', allowBlank: false, columns: 2, width: 300, //margin: '0 0 0 10', items: [{ boxLabel: '母視窗連接', name: 'banner_link_mode', id: 'oldw', checked: true, inputValue: 1 }, { boxLabel: '新視窗開啟', name: 'banner_link_mode', id: 'neww', inputValue: 2 }] } ] }, { xtype: 'numberfield', fieldLabel: '排序', id: 'banner_sort', name: 'banner_sort', maxValue: 65536, minValue: 0 }, { xtype: 'datefield', fieldLabel: '上線日期', id: 'banner_start', name: 'banner_start', allowBlank: false, editable: false, vtype: 'daterange', endDateField: 'banner_end' }, { xtype: 'datefield', fieldLabel: '下線日期', id: 'banner_end', name: 'banner_end', allowBlank: false, editable: false, vtype: 'daterange', startDateField: 'banner_start' }, { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', items: [ { xtype: 'displayfield', fieldLabel: '狀態' }, { xtype: 'radiogroup', allowBlank: false, width: 300, columns: 4, id: 'banner_statuses', //margin: '0 0 0 10', items: [{ boxLabel: '新建', name: 'banner_status', checked: true, id: 's1', inputValue: 0, hidden:status== 0 ? false : true }, { boxLabel: '顯示', name: 'banner_status', id: 's2', inputValue: 1 }, { boxLabel: '隱藏', name: 'banner_status', id: 's3', inputValue: 2 }, { boxLabel: '下線/刪除', name: 'banner_status', id: 's4', inputValue: 3 }] } ] }, { xtype: 'filefield', name: 'banner_image', id: 'banner_image', fieldLabel: '圖檔', msgTarget: 'side', buttonText: '瀏覽..', submitValue: true, validator: function (value) { var type = value.split('.'); if (type[type.length - 1] == 'gif' || type[type.length - 1] == 'png' || type[type.length - 1] == 'jpg') { return true; } else { return '上傳文件類型不正確!'; } }, width: 300, allowBlank: false, fileUpload: true }, { xtype: 'displayfield', fieldLabel: '建立時間', id: 'banner_createdate', name: 'banner_createdate', hidden: row == null ? true : false }, { xtype: 'displayfield', fieldLabel: '修改時間', id: 'banner_updatedate', name: 'banner_updatedate', hidden: row == null ? true : false }, { xtype: 'displayfield', fieldLabel: '來源IP', id: 'banner_ipfrom', name: 'banner_ipfrom', hidden: row == null ? true : false }], buttons: [{ formBind: true, disabled: true, text: SAVE, handler: function () { var status = 0; if (Ext.getCmp('s1').getValue()) { status = 0; } if (Ext.getCmp('s2').getValue()) { status = 1; } if (Ext.getCmp('s3').getValue()) { status = 2; } if (Ext.getCmp('s4').getValue()) { status = 3; } var form = this.up('form').getForm(); if (form.isValid()) { form.submit({ params: { banner_content_id: Ext.htmlEncode(Ext.getCmp('banner_content_id').getValue()), banner_site_id: document.getElementById('sid').value, banner_title: Ext.htmlEncode(Ext.getCmp('banner_title').getValue()), banner_link_url: Ext.htmlEncode(Ext.getCmp('banner_link_url').getValue()), banner_sort: Ext.htmlEncode(Ext.getCmp('banner_sort').getValue()), banner_start: Ext.htmlEncode(Ext.getCmp('banner_start').getValue()), banner_end: Ext.htmlEncode(Ext.getCmp('banner_end').getValue()), neww: Ext.htmlEncode(Ext.getCmp('neww').getValue()), oldw: Ext.htmlEncode(Ext.getCmp('oldw').getValue()), banner_statuses:status, banner_image: Ext.htmlEncode(Ext.getCmp('banner_image').getValue()) }, success: function (form, action) { var result = Ext.JSON.decode(action.response.responseText); if (result.success) { Ext.Msg.alert(INFORMATION, result.msg); store.load(); editBannerImageWin.close(); } }, failure: function (form, action) { var result = Ext.JSON.decode(action.response.responseText); Ext.Msg.alert(INFORMATION, result.msg); } }); } } }] }); var editBannerImageWin = Ext.create('Ext.window.Window', { iconCls: 'icon-user-edit', id: 'editBannerImageWin', width: 500, layout: 'fit', items: [editBannerImageFrm], constrain: true, closeAction: 'destroy', modal: true, resizable: false, labelWidth: 60, bodyStyle: 'padding:5px 5px 5px 5px', closable: false, tools: [ { type: 'close', qtip: '是否關閉', handler: function (event, toolEl, panel) { Ext.MessageBox.confirm(CONFIRM, IS_CLOSEFORM, function (btn) { if (btn == "yes") { Ext.getCmp('editBannerImageWin').destroy(); } else { return false; } }); } } ], listeners: { 'show': function () { if (row != null) { editBannerImageFrm.getForm().loadRecord(row); Ext.getCmp('banner_start').setValue(row.data.banner_start.substring(0, 10)); Ext.getCmp('banner_end').setValue(row.data.banner_end.substring(0, 10)); } } } }); editBannerImageWin.show(); initForm(row); } function initForm(row) { var img = row.data.banner_image.toString(); //var imgUrl = img.substring(img.lastIndexOf("\/") + 1); var url = img.split("\/"); var imgUrl = url[url.length - 1]; Ext.getCmp('banner_image').setRawValue(imgUrl); }
export default { props: [ 'reloadMethod' ], data() { return { netError_tip: '数据都丢了...' } }, methods: { _netError_reload() { let reloadMethod = this.reloadMethod; this.$parent[reloadMethod](); } } }
var express = require("express"); var bodyParser = require("body-parser"); var session = require("express-session"); var util = require("./utils/utility"); var db = require("./db/index.js"); var morgan = require("morgan"); var app = express(); app.set('views', __dirname + '/../views'); app.set('view engine', 'jade'); app.use(morgan("dev")); // logs GET and POST requests app.use(bodyParser.json()); // parses request's bodies req.body app.use(bodyParser.urlencoded({ extended:true })); // tells express where to look for client files to serve app.use(express.static(__dirname + "/../client")); app.use(session({ secret: "notsosecret", resave: false, })); app.get("/", util.checkUser, function(req, res) { res.redirect("/boards"); }); app.get("/signup", function(req, res) { res.render('signup'); }); app.post("/signup", function(req, res) { var username = req.body.username; var password = req.body.password; // check if username exists // if yes alert user // if not create new user entry and create new session // and redirect to /boards db.User.count({ where: {username: username} }).then(function(count) { if (count > 0) { alert('Username already taken'); } else { db.User.create({ username: username, password: password }).then(function(user) { user.hashPassword(); util.createSession(req, res, user); }); } }); }); app.get("/signin", function(req, res) { // serve signin page res.render('signin'); }); app.post("/signin", function(req, res) { var username = req.body.username; var password = req.body.password; // check if username exists in table // if not alert client // if yes check comparePassword with getter // if matches // creates session and redirect to /boards // if not alert user db.User.findOne({ where: {username: username} }).then(function(user) { if (!user) { console.log('unregistered account'); res.redirect('/signup'); } else { user.comparePassword(password, function(match) { if (match) { console.log('matched!'); util.createSession(req, res, user); } else { console.log('incorrect password'); } }); } }); }); app.get('/boards', function(req, res) { res.render('boards'); }); app.get("/api/boards", function(req, res) { db.Board.findAll().then(function(boards) { res.json(boards); }); }); app.post("/api/boards", function(req, res) { console.log('called'); var newBoard = req.body.boardname; // interact with db // if already exists alert user and redirect user to that board // create new board if doesn't already exists and redirect to new board db.Board.findOne({ where: {boardname: newBoard} }).then(function(board) { if (board) { console.log('Board already exists'); // redirect to that board } else { db.Board.create({boardname: newBoard}) .then(function(board) { console.log(board + " created"); // redirect to board }); } }); res.send(201); }); app.get("/board/msgs/*", function(req, res) { // parse req.url console.log('getting msgs'); var boardname = req.url.split('/').pop().split('?')[0]; console.log(boardname); db.Board.findOne({where: {boardname: boardname}}) .then(function(board) { db.Message.findAll({where: {BoardId: board.id}, include: [db.User]}) .then(function(boards) { console.log(boards); res.json(boards); }) }); }); app.get("/board/*", function(req, res) { // parse req.url var boardname = req.url.split('/').pop(); res.render('board', {boardname: boardname}); }); app.post("/board/*", function(req, res) { var boardname = req.url.split('/').pop(); var message = req.body.message; var username = req.session.user.username; db.User.findOne({ where: {username: username}}) .then(function(user) { db.Board.findOne({where: {boardname: boardname}}) .then(function(board) { db.Message.create({ UserId: user.id, BoardId: board.id, text: message }) }) }) }); // app.get("/boards/*", util.checkUser, function(req, res) { // // get board name // // check with db see if it exists // // if yes display all msg from that board // // if not redirect to all boards // }); // app.post("/boards/*", util.checkUser, function(req, res) { // // get board name // // check with db to see if board exists // // if not redirect to board // // if yes make a new entry to db // }) console.log("ChronoChat is listening on 8080"); app.listen(8080);
/** * Contoh Callback sederhana */ // function tampilkan(callback) { // var txt = callback('erdi'); // console.log(txt); // } // tampilkan((res) => { // return "Halo " + res // }); /** * Contoh asynchronous/ Promise */ storage = { get: function() { // tertunda return new Promise((resolve, reject) => { setTimeout(() => { resolve('ini adalah hasil promise'); }, 5000); }); } } console.log('start di sini'); storage.get().then((res) => { console.log(res); }); console.log('selesai');
import H1 from './H1.svelte'; export { H1 };
// new Object -> Object.prototype function Product(name, price) { this.name = name; this.price = price; } Product.prototype.discount = function(percentual) { this.price = this.price - (this.price * (percentual / 100)); }; Product.prototype.increase = function(percentual) { this.price = this.price + (this.price * (percentual / 100)); }; const productOne = new Product('Camiseta', 50); const productTwo = { name: 'Caneca', price: 15 }; Object.setPrototypeOf(productTwo, Product.prototype); productTwo.increase(10); const productThree = Object.create(Product.prototype, { price: { writable: true, configurable: true, enumerable: true, value: 42 }, size: { writable: true, configurable: true, enumerable: true, value: 43 }, }); productThree.increase(10); console.log(productOne); console.log(productTwo); console.log(productThree); // productOne.discount(100); // productOne.increase(100); /* const objA = { keyA: 'A' // __proto__: Object.prototype } const objB = { keyB: 'B' } const objC = new Object(); objC.keyC = 'C' Object.setPrototypeOf(objB, objA); Object.setPrototypeOf(objC, objB); console.log(objC.keyB); */
import React, { Component } from 'react'; import {getData} from './data'; import ExperienceItem from './experience-item'; import Skill from './skill-item'; class ExperienceAchievementContainer extends Component{ constructor(props){ super(props); this.state = { data: getData().experience, skills: getData().skills, tools: getData().tools, interests: getData().interests, achievements: getData().achievements } } render(){ const {data, skills, tools, interests, achievements} = this.state; return ( <div> <div className="page-header"> <h1>Experience</h1> </div> <div className="row"> { data.map((item, i) => ( <ExperienceItem key={i} company={item.company} image={item.image} from={item.from} to={item.to} position={item.position} facebook={item.facebook} /> )) } </div> <br/><br/> <div className="page-header"> <h1>Achievement</h1> </div> <div className="row" style={{margin:'0.2rem'}}> { achievements.map((item,i) => ( <div key={i} className="achievement"> <h3>{item.about}</h3> <div className="col-md-6"> <div> <h5> <b>Title:</b> {item.topic} {/*<ul> { item.authors.map((author, j) => ( <li key={j}>{author.name}</li> )) } </ul> */} </h5> <h5><b>Data Source:</b> {item.dataSource}</h5> <h5><b>Classifier Used:</b> { item.classifiers.map((classifier, j) => ( <span className="tags" key={j}> {classifier+", "} </span> )) } </h5> <h5><b>ML Technique</b></h5> <ul> { item.machineLearning.map((ml,j) => ( <li key={j}>{ml}</li> )) } </ul> <h5><b>Models</b></h5> <ul> { item.testModel.map((model,j) => ( <li key={j}>{model}</li> )) } </ul> </div> </div> <div className="col-md-6"> <h5><b>Authors</b></h5> <ul> { item.authors.map((author,j) => ( <li key={j}> {author.name}<br/> <i>{author.subject} at {author.institute}</i> </li> )) } </ul> <h5><b>Supervisors</b></h5> <ul> { item.supervisors.map((author,j) => ( <li key={j}> {author.name}<br/> <i>{author.post}, {author.subject} at {author.institute}</i> </li> )) } </ul> </div> </div> )) } </div> <br/><br/> <div className="page-header"> <h1>Skills</h1> </div> <div className="row" style={{margin:'0.2rem'}}> { skills.map((item, i) => ( <Skill key={i} name={item.name} level={item.level} /> )) } </div> <br/><br/> <div className="row" style={{margin:'0.2rem'}}> <div className="col-md-6"> <h4>Tools</h4><hr/> <ul className="tools"> { tools.map((item, i) => ( <li key={i}> <h5><p>{item}</p></h5> </li> )) } </ul> </div> <div className="col-md-6"> <h4>Interests</h4><hr/> <ul className="tools"> { interests.map((item, i) => ( <li key={i}> <h5><p>{item}</p></h5> </li> )) } </ul> </div> </div> </div> ); } } export default ExperienceAchievementContainer;
const Title = (props) => { const {title,description}=props return ( <div className="row"> <div className="col-lg-6 mx-auto"> <div className="title-area text-center"> <h2 className="title">{title}</h2> <p className="title-description">{description}</p> </div> </div> </div> ) } export default Title
import { Router } from 'express'; import Queue from '../lib/Queue'; const usersRouter = Router(); usersRouter.post('/', async (request, response) => { const { name, email, password } = request.body; const user = { name, email, password } await Queue.add('RegistrationMail', { user }) return response.json(user); }); export default usersRouter;
'use strict'; import dom from 'metal-dom'; import globals from '../../src/globals/globals'; import HtmlScreen from '../../src/screen/HtmlScreen'; import Surface from '../../src/surface/Surface'; import UA from 'metal-useragent'; describe('HtmlScreen', function() { beforeEach(() => { var requests = this.requests = []; this.xhr = sinon.useFakeXMLHttpRequest(); this.xhr.onCreate = (xhr) => { requests.push(xhr); }; // Prevent log messages from showing up in test output. sinon.stub(console, 'log'); }); afterEach(() => { this.xhr.restore(); console.log.restore(); }); it('should get title selector', () => { var screen = new HtmlScreen(); assert.strictEqual('title', screen.getTitleSelector()); screen.setTitleSelector('div.title'); assert.strictEqual('div.title', screen.getTitleSelector()); }); it('should returns loaded content', (done) => { var screen = new HtmlScreen(); screen.load('/url').then((content) => { assert.strictEqual('content', content); done(); }); this.requests[0].respond(200, null, 'content'); }); it('should set title from response content', (done) => { var screen = new HtmlScreen(); screen.load('/url').then(() => { assert.strictEqual('new', screen.getTitle()); done(); }); this.requests[0].respond(200, null, '<title>new</title>'); }); it('should not set title from response content if not present', (done) => { var screen = new HtmlScreen(); screen.load('/url').then(() => { assert.strictEqual(null, screen.getTitle()); done(); }); this.requests[0].respond(200, null, ''); }); it('should cancel load request to an url', (done) => { var screen = new HtmlScreen(); screen.load('/url') .catch(reason => { assert.ok(reason instanceof Error); done(); }).cancel(); }); it('should copy surface root node attributes from response content', (done) => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent('<html attributeA="valueA"><div id="surfaceId">surface</div></html>'); screen.flip([]).then(() => { assert.strictEqual('valueA', document.documentElement.getAttribute('attributeA')); done(); }); }); it('should extract surface content from response content', () => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent('<div id="surfaceId">surface</div>'); assert.strictEqual('surface', screen.getSurfaceContent('surfaceId')); screen.allocateVirtualDocumentForContent('<div id="surfaceId">surface</div>'); assert.strictEqual(undefined, screen.getSurfaceContent('surfaceIdInvalid')); }); it('should extract surface content from response content default child if present', () => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent('<div id="surfaceId">static<div id="surfaceId-default">surface</div></div>'); assert.strictEqual('surface', screen.getSurfaceContent('surfaceId')); screen.allocateVirtualDocumentForContent('<div id="surfaceId">static<div id="surfaceId-default">surface</div></div>'); assert.strictEqual(undefined, screen.getSurfaceContent('surfaceIdInvalid')); }); it('should release virtual document after activate', () => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent(''); assert.ok(screen.virtualDocument); screen.activate(); assert.ok(!screen.virtualDocument); }); it('should set body id in virtual document to page body id', () => { var screen = new HtmlScreen(); globals.document.body.id = 'bodyAsSurface'; screen.allocateVirtualDocumentForContent('<body>body</body>'); screen.assertSameBodyIdInVirtualDocument(); assert.strictEqual('bodyAsSurface', screen.virtualDocument.querySelector('body').id); }); it('should set body id in virtual document to page body id even when it was already set', () => { var screen = new HtmlScreen(); globals.document.body.id = 'bodyAsSurface'; screen.allocateVirtualDocumentForContent('<body id="serverId">body</body>'); screen.assertSameBodyIdInVirtualDocument(); assert.strictEqual('bodyAsSurface', screen.virtualDocument.querySelector('body').id); }); it('should set body id in document and use the same in virtual document', () => { var screen = new HtmlScreen(); globals.document.body.id = ''; screen.allocateVirtualDocumentForContent('<body>body</body>'); screen.assertSameBodyIdInVirtualDocument(); assert.ok(globals.document.body.id); assert.strictEqual(globals.document.body.id, screen.virtualDocument.querySelector('body').id); }); it('should evaluate surface scripts', (done) => { enterDocumentSurfaceElement('surfaceId', '<script>window.sentinel=true;</script>'); var surface = new Surface('surfaceId'); var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent(''); assert.ok(!window.sentinel); screen.evaluateScripts({ surfaceId: surface }).then(() => { assert.ok(window.sentinel); delete window.sentinel; exitDocumentElement('surfaceId'); done(); }); }); it('should evaluate surface styles', (done) => { enterDocumentSurfaceElement('surfaceId', '<style id="temporaryStyle">body{background-color:rgb(0, 255, 0);}</style>'); var surface = new Surface('surfaceId'); var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent(''); screen.evaluateStyles({ surfaceId: surface }).then(() => { assertComputedStyle('backgroundColor', 'rgb(0, 255, 0)'); exitDocumentElement('surfaceId'); done(); }); }); it('should always evaluate tracked temporary scripts', (done) => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent('<script data-senna-track="temporary">window.sentinel=true;</script>'); assert.ok(!window.sentinel); screen.evaluateScripts({}) .then(() => { assert.ok(window.sentinel); delete window.sentinel; screen.allocateVirtualDocumentForContent('<script data-senna-track="temporary">window.sentinel=true;</script>'); screen.evaluateScripts({}) .then(() => { assert.ok(window.sentinel); delete window.sentinel; done(); }); }); }); it('should always evaluate tracked temporary styles', (done) => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent('<style id="temporaryStyle" data-senna-track="temporary">body{background-color:rgb(0, 255, 0);}</style>'); screen.evaluateStyles({}) .then(() => { assertComputedStyle('backgroundColor', 'rgb(0, 255, 0)'); screen.allocateVirtualDocumentForContent('<style id="temporaryStyle" data-senna-track="temporary">body{background-color:rgb(255, 0, 0);}</style>'); screen.evaluateStyles({}) .then(() => { assertComputedStyle('backgroundColor', 'rgb(255, 0, 0)'); exitDocumentElement('temporaryStyle'); done(); }); }); }); it('should append existing teporary styles with id in the same place as the reference', (done) => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent('<style id="temporaryStyle" data-senna-track="temporary">body{background-color:rgb(0, 255, 0);}</style>'); screen.evaluateStyles({}) .then(() => { document.head.appendChild(dom.buildFragment('<style id="mainStyle">body{background-color:rgb(255, 255, 255);}</style>')); assertComputedStyle('backgroundColor', 'rgb(255, 255, 255)'); screen.allocateVirtualDocumentForContent('<style id="temporaryStyle" data-senna-track="temporary">body{background-color:rgb(255, 0, 0);}</style>'); screen.evaluateStyles({}) .then(() => { assertComputedStyle('backgroundColor', 'rgb(255, 255, 255)'); exitDocumentElement('mainStyle'); exitDocumentElement('temporaryStyle'); done(); }); }); }); it('should evaluate tracked permanent scripts only once', (done) => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent('<script id="permanentScriptKey" data-senna-track="permanent">window.sentinel=true;</script>'); assert.ok(!window.sentinel); screen.evaluateScripts({}) .then(() => { assert.ok(window.sentinel); delete window.sentinel; screen.allocateVirtualDocumentForContent('<script id="permanentScriptKey" data-senna-track="permanent">window.sentinel=true;</script>'); screen.evaluateScripts({}) .then(() => { assert.ok(!window.sentinel); done(); }); }); }); it('should evaluate tracked permanent styles only once', (done) => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent('<style id="permanentStyle" data-senna-track="permanent">body{background-color:rgb(0, 255, 0);}</style>'); screen.evaluateStyles({}) .then(() => { assertComputedStyle('backgroundColor', 'rgb(0, 255, 0)'); screen.allocateVirtualDocumentForContent('<style id="permanentStyle" data-senna-track="permanent">body{background-color:rgb(255, 0, 0);}</style>'); screen.evaluateStyles({}) .then(() => { assertComputedStyle('backgroundColor', 'rgb(0, 255, 0)'); exitDocumentElement('permanentStyle'); done(); }); }); }); it('should remove from document tracked pending styles on screen dispose', (done) => { var screen = new HtmlScreen(); document.head.appendChild(dom.buildFragment('<style id="mainStyle">body{background-color:rgb(255, 255, 255);}</style>')); screen.allocateVirtualDocumentForContent('<style id="temporaryStyle" data-senna-track="temporary">body{background-color:rgb(0, 255, 0);}</style>'); screen.evaluateStyles({}) .then(() => { assertComputedStyle('backgroundColor', 'rgb(255, 255, 255)'); exitDocumentElement('mainStyle'); done(); }); screen.dispose(); }); it('should clear pendingStyles after screen activates', (done) => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent('<style id="temporaryStyle" data-senna-track="temporary"></style>'); screen.evaluateStyles({}) .then(() => { assert.ok(!screen.pendingStyles); exitDocumentElement('temporaryStyle'); done(); }); assert.ok(screen.pendingStyles); screen.activate(); }); it('should mutate temporary style hrefs to be unique on ie browsers', (done) => { UA.testUserAgent('MSIE'); // Simulates ie user agent var screen = new HtmlScreen(); screen.load('/url').then(() => { screen.evaluateStyles({}) .then(() => { assert.ok(document.getElementById('testIEStlye').href.indexOf('?zx=') > -1); done(); }); screen.activate(); }); this.requests[0].respond(200, null, '<link id="testIEStlye" data-senna-track="temporary" rel="stylesheet" href="testIEStlye.css">'); }); it('link elements should only be loaded once in IE', (done) => { UA.testUserAgent('MSIE'); // Simulates ie user agent var screen = new HtmlScreen(); window.sentinelLoadCount = 0; screen.load('/url').then(() => { var style = screen.virtualQuerySelectorAll_('#style')[0]; style.addEventListener('load', () => { window.sentinelLoadCount++; }); style.addEventListener('error', () => { window.sentinelLoadCount++; }); screen.evaluateStyles({}) .then(() => { assert.strictEqual(1, window.sentinelLoadCount); delete window.sentinelLoadCount; done(); }); screen.activate(); }); this.requests[0].respond(200, null, '<link id="style" data-senna-track="temporary" rel="stylesheet" href="/base/src/senna.js">'); }); it('should have correct title', (done) => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent('<title>left</title>'); screen.resolveTitleFromVirtualDocument(); screen.flip([]).then(() => { assert.strictEqual('left', screen.getTitle()); done(); }); }); it('should have correct title when the title contains html entities', (done) => { var screen = new HtmlScreen(); screen.allocateVirtualDocumentForContent('<title>left &amp; right</title>'); screen.resolveTitleFromVirtualDocument(); screen.flip([]).then(() => { assert.strictEqual('left & right', screen.getTitle()); done(); }); }); }); function enterDocumentSurfaceElement(surfaceId, opt_content) { dom.enterDocument('<div id="' + surfaceId + '">' + (opt_content ? opt_content : '') + '</div>'); return document.getElementById(surfaceId); } function exitDocumentElement(surfaceId) { return dom.exitDocument(document.getElementById(surfaceId)); } function assertComputedStyle(property, value) { assert.strictEqual(value, window.getComputedStyle(document.body, null)[property]); }
SB.Examples.LayerTest = function() { SB.Game.call(this); } goog.inherits(SB.Examples.LayerTest, SB.Game); SB.Examples.LayerTest.prototype.initialize = function(param) { param.backgroundColor = '#000000'; SB.Game.prototype.initialize.call(this, param); var root = new SB.Entity; /* var GLOWMAP = THREE.ImageUtils.loadTexture("./images/green_glow_512.png"); var NOISEMAP = THREE.ImageUtils.loadTexture("./images/cloud.png"); var uniforms = { time: { type: "f", value: 1.0 }, opacity: { type: "f", value: 1.0 }, texture1: { type: "t", value: 0, texture: NOISEMAP }, texture2: { type: "t", value: 1, texture: GLOWMAP } }; uniforms.texture1.texture.wrapS = uniforms.texture1.texture.wrapT = THREE.Repeat; uniforms.texture2.texture.wrapS = uniforms.texture2.texture.wrapT = THREE.Repeat; var material = new THREE.ShaderMaterial( { uniforms: uniforms, vertexShader: document.getElementById( 'sbGlowVertexShader' ).textContent, fragmentShader: document.getElementById( 'sbGlowFragmentShader' ).textContent, transparent:true, } ); */ var e = new SB.Entity; var transform = new SB.Transform; e.addComponent(transform); var map = THREE.ImageUtils.loadTexture('./images/duckCM.png'); var cube = new SB.CubeVisual({map:map}); e.addComponent(cube); root.addChild(e); var b1 = new SB.Examples.LayerObject(); //b1.transform.position.x = 2; var headlight = new SB.DirectionalLight({ /*layer:SB.Graphics.instance.backgroundLayer,*/ color : 0xFFFFFF, intensity : 1}); root.addComponent(headlight); var headlight = new SB.DirectionalLight({layer:SB.Graphics.instance.backgroundLayer, color : 0xFFFFFF, intensity : 1}); root.addComponent(headlight); root.addChild(b1); var glowEffect = GlowEffect({viewer:this}); this.addEntity(glowEffect); glowEffect.realize(); this.addEntity(root); root.realize(); }
import React from 'react' import { Link } from 'gatsby' import styled from 'styled-components' import { useSiteMetadata } from '../hooks/use-site-metadata' const Title = styled.h1` font-size: 3.5rem; line-height: 0.9; padding: 1rem 1rem 2rem; border-bottom: ${({ theme }) => theme.border}; span { display: block; margin-bottom: 1rem; font-size: 0.75em; } ` const Header = () => { const { title } = useSiteMetadata() return ( <header> <Title> <Link to="/"> <span>{'</>'}</span> {title} </Link> </Title> </header> ) } export default Header
/** * A pile of cards. A card deck is a Pile of cards. * Indexes: * Positive index: Starts from the top of the deck, when the deck is face DOWN. 0 = top card. * Starts from the bottom of the deck, when the deck is face UP. 0 = bottom card. * Negative index: Starts from the bottom of the the deck, when the deck is face DOWN. -1 = bottom card. * Starts from the top of the deck, when the deck is face UP. -1 = top card. * @author Rajitha Wannigama */ var Pile = { /** * The list of cards in this pile, using cards.Card objects to represent a card. * @private * @type {Array} */ cards: undefined, /** * The list of cards in this pile, using the string representation rather than using * cards.Card objects. * @private * @type {Array} */ cards_str: undefined, // UI stuff /** * If this Pile is selectable as a whole, this is set to true. * @private * @type {Boolean} */ is_selectable: false, /** * The function to execute when the pile is selected. * @private * @type {Function} */ on_select: undefined, // methods /** * Create a new Pile of cards. * @constructor * @this {Pile} * @param {...Pile} a list of Pile objects used to create this new Pile, in the order * needed. * @returns {Pile} * @throws {Error} */ create: function() { if ( arguments.length == 0 ) { // Create an empty Pile var obj = Object.create(this); obj.cards = []; return obj; } else { // Create a new Pile from a bunch of piles. var i, j; var pile = Object.create(this); pile.cards = []; for (i = 0; i < arguments.length; i++) { if ( !this.isPile(arguments[i]) ) { // Error, this is not a Pile object! throw Error('cards.Pile.create: Argument ' + i + ' is not a cards.Pile object. arguments[' + i + '] = ' + arguments[i]); } // Add the cards from this pile (arguments[i]) to the end of our new pile pile.cards = pile.cards.concat(arguments[i].cards); } return pile; } }, /** * Add a Card or an array of Cards. * @param {cards.Card|Array} c * @returns {cards.Pile} this Pile object for method chaining. */ add: function(c) { if ( Array.isArray(c) ) { } else if ( this.isPile(c) ) { } else { this.cards.push(c); return this; } }, /** * Check if an object is a Pile object. * @param {Object} the object to check * @returns {Boolean} true if the parameter is a cards.Pile object. */ isPile: function(obj) { return (typeof obj === 'object') && (Array.isArray(obj.cards)); }, /** * * @param {Object} [options] * @returns {Object #<HTMLDivElement>} * @throws {Error} */ html: function(options) { // Default options var def_options = { faceup: true, // or false for facedown display: 'stack', // or 'spread' or 'fan' (spread in an arc) direction: 'LR', // LR = left to right, RL = right to left /* * For display: 'spread': * 'normal' - normal spread with just the card rank and suit shown * 'full' - show each card in full * 'half' - show half of each card * <css-unit> - space each card using the CSS measurement. e.g. '10px' applies 10px * of spacing between each card. */ spacing: 'normal' }; if ( typeof options !== 'undefined' ) { // Parse options if ( typeof options.faceup !== 'undefined' ) { // Using !! to make sure its a boolean value def_options.faceup = !!options.faceup; } if ( typeof options.display !== 'undefined' ) { if ( /^(stack|spread)$/.test(options.display) ) { def_options.display = options.display; } else { throw new Error('cards.Pile.html: invalid value for option "display": ' + options.display); } } if ( typeof options.direction !== 'undefined' ) { if ( /^(LR|RL)$/.test(options.direction) ) { def_options.direction = options.direction; } else { throw new Error('cards.Pile.html: invalid value for option "direction": ' + options.direction); } } if ( typeof options.spacing !== 'undefined' ) { // @TODO Add support for CSS units if ( /^(normal|full|half)$/.test(options.direction) ) { def_options.direction = options.direction; } else { throw new Error('cards.Pile.html: invalid value for option "direction": ' + options.direction); } } } var div = document.createElement('div'); var c; var c_width = parseInt((this.cards[0].html()).style.width, 10); var c_height = parseInt((this.cards[0].html()).style.height, 10); var spacing = 34; for (var i = 0; i < this.cards.length; i++) { c = this.cards[i].html({faceup: def_options.faceup}); c.style.position = 'absolute'; c.style.left = (i*spacing) + 'px'; div.appendChild(c); } c_width += 2; div.style.position = 'relative'; div.style.width = '' + ( ( spacing * (this.cards.length-1) ) + c_width ) + 'px'; div.style.height = c_height + 'px'; div.style.zIndex = '2'; return div; }, /** * Deal cards from this pile, one at a time, into different piles. * @this {cards.Pile} * @param {Number} n the number of cards to deal * @param {Number} [piles=1] the number of piles to deal. Default is 1. -1 = all cards. * @returns {cards.Pile|Array} if piles=1 or undefined, a cards.Pile object is returned. Otherwise an * array of cards.Pile objects is returned. * @throws {Error} */ deal: function(n, piles) { // If n is given, it must be a number. if ( (typeof n != 'undefined') && (typeof n != 'number') ) { throw new Error('cards.Pile.deal: n must be a number. n = ' + n); } // If piles is given, it must be a number. if ( (typeof piles != 'undefined') && (typeof piles != 'number') ) { throw new Error('cards.Pile.deal: piles must be a number. piles = ' + piles); } n = (typeof n === 'undefined') ? 1 : n; n = (n == -1) ? this.cards.length : n; // n must be valid - less than (or equal to) the total number of cards in this pile and higher than 1. if ( (n > this.cards.length) || (n < 1) ) { throw new Error('cards.Pile.deal: n is out of range. n = ' + n); } // The number of piles we need to deal. piles = (typeof piles === 'undefined') ? 1 : piles; piles = (piles < 1) ? 1 : piles; // The cards.Pile objects. var obj_piles = []; var i; // Create the number of piles we need. for ( i = 0; i < piles; i++ ) { obj_piles.push( this.create() ); } // Deal out the cards var j = 0; for ( i = 0; i < n; i++ ) { obj_piles[j].cards.push( this.cards[i] ); // Increment second loop counter j++; j = (j == piles) ? 0 : j; } return obj_piles.length == 1 ? obj_piles[0] : obj_piles; /* if ( arguments.length < 1 ) { // Must contain at least one argument return false; } // By default, we want to deal out ALL cards in this pile var num = -1; if ( (typeof arguments[0]) == 'number' ) { // We want to deal out a specific number of cards num = arguments[0]; } var j = 1; for (var i = 0; i < this.cards.length; i++) { arguments[j].add(this.cards[i]); j++; j = j == arguments.length ? 1 : j; } for (i = 0; i < arguments.length; i++) { } */ }, /** * Find a card at the given index. This function does NOT remove the card from this Pile. It simply * returns a reference to the {cards.Card} object. * @this {cards.Pile} * @param {Number} n the index of the card * @returns {cards.Card|undefined} undefined is returned if the index does not exist. */ find: function(n) { return this.cards[n]; }, /** * pile.shuffle({f:cards.Shuffle.overhand, n:[6,8]}); * pile.shuffle(cards.Shuffle.riffle); * pile.shuffle(cards.Shuffle.riffle, 2); * pile.shuffle(cards.Shuffle.riffle, 2, 10); * @param {Function} [func=cards.Shuffle.overhand] can be a user defined function * @param {Number} [a=1] the number of times to perform the shuffle. If "b" is not given, then the * shuffle is performed exactly "a" times. * @param {Number} [b] if "b" is given, the shuffle is performed a random * number of times between "a" and "b". * @returns {cards.Pile} this Pile object for method chaining. * @throws {Error} */ shuffle: function(options) { if ( typeof options === 'undefined' ) { options = Pile.shuffle.options(); } else if ( !Pile.shuffle.isValidOptions(options) ) { // Options passed in is not valid. throw new Error('cards.Pile.shuffle: invalid options given. options = ' + options); } var i, n; if ( Array.isArray(options.n) ) { // n is a random number between the range given by options.n n = Math.floor(Math.random() * (options.n[1] - options.n[0] + 1)) + options.n[0] } else { n = options.n; } var range = []; // Generate initial range for ( i = 0; i < this.cards.length; i++ ) { range.push(i); } for ( i = 0; i < n; i++ ) { range = options.f(range); } // @TODO Validate output from the shuffling function -- check there are no duplicates /* Use code: // Make sure we create a copy s_range = range.concat([]); // Sort using numerical comparisons, not dictionary order range.sort(function(a,b) { return (a < b) ? -1 : (a > b ? 1 : 0 ); }); */ var cards_new = []; for ( i = 0; i < range.length; i++ ) { cards_new.push( this.cards[ range[i] ] ); } this.cards = cards_new; return this; }, /** * Cut the cards. The function cuts the card at a random position around the middle of the pile. * @returns {cards.Pile} this Pile object. * @throws {Error} */ cut: function(options) { var len = this.cards.length; if ( len < 0 ) { throw new Error('cards.Pile.cut: Unexpected array length of ' + len); } switch (len) { case 0: case 1: // Do nothing break; case 2: // Swap the cards var t = this.cards[0]; this.cards[0] = this.cards[1]; this.cards[1] = t; break; default: // If its even, cuts exactly in half // If its odd, puts smaller portion in bottom var half = Math.floor(len/2); var bottom = this.cards.slice(0,half); var top = this.cards.slice(half); this.cards = top.concat(bottom); break; } return this; } }; /** * Check if the shuffling options given is valid. * @param {*} options * @returns {Boolean} true if the options given is valid. */ Pile.shuffle.isValidOptions = function(options) { // options must be an object and contain two properties "f" and "n". // options.f must be a function. if ( (typeof options === 'object') && (typeof options.f === 'function') ) { var type = typeof options.n; // options.n can be a number > 0 or an array with length 2. if ( type === 'number' ) { return options.n > 0; } else if ( Array.isArray(options.n) ) { return (options.n.length == 2) && (options.n[0] > 0) && (options.n[1] >= options.n[0]); } else { // Invalid "n" property. return false; } } else { // Not an object, so not valid options. return false; } } /** * Set or get the options. * @param {Object|String} [options] use the string 'reset' to reset the options back to factory default. * @returns {Object} a reference to the current options object (if changed, the updated one is returned). * @throws {Error} if the options given are invalid. */ Pile.shuffle.options = function(options) { var type = typeof options; switch (type) { case 'undefined': // Just return the options break; case 'string': // Reset the options if ( options == 'reset' ) { Pile.shuffle.CurrentOptions = Pile.shuffle.DefaultOptions; } else { throw new Error('cards.Pile.shuffle.options: invalid options given. options = ' + options); } break; default: if ( Pile.shuffle.isValidOptions(options) ) { // Set the options Pile.shuffle.CurrentOptions = options; } else { throw new Error('cards.Pile.shuffle.options: invalid options given. options = ' + options); } break; } return Pile.shuffle.CurrentOptions; }
import {authTypes} from './actionTypes'; import axios from 'axios'; const ROOT_URL = "http://localhost/api"; export const loginUser = data => { return { type: authTypes.AUTH_USER, user: data } } export const checkAuth = () => dispatch => { const token = localStorage.getItem('token'); if (token) { axios.get(`${ROOT_URL}/auth?token=${token}`) .then(res => { dispatch({ type: authTypes.AUTH_USER, user: res.data.data.user }) }) } } export const logout = () => dispatch => { localStorage.removeItem('token'); dispatch ({ type: authTypes.LOGOUT }); };
import { Vector2 } from "../geom/Vector2.js"; import { CreateMat3 } from "../geom/Matrix3.js"; export class Transform2D { constructor() { this.position = new Vector2(); this.scale = new Vector2(1, 1); this.pivot = new Vector2(); this._rotation = 0; this._rotationComponents = new Vector2(); this.alpha = 1; this.parent = null; this.children = []; this.worldTransform = CreateMat3(); this.localTransform = CreateMat3(); } updateTransform() { const positionx = Math.floor(this.position.x); const positiony = Math.floor(this.position.y); const sinR = this._rotationComponents.y; const cosR = this._rotationComponents.x; this.localTransform[0] = cosR * this.scale.x; this.localTransform[1] = -sinR * this.scale.y; this.localTransform[3] = sinR * this.scale.x; this.localTransform[4] = cosR * this.scale.y; const parentTransform = this.parent.worldTransform; const a00 = this.localTransform[0]; const a01 = this.localTransform[1]; const a02 = positionx - (this.localTransform[0] * this.pivot.x - this.pivot.y * this.localTransform[1]); const a10 = this.localTransform[3]; const a11 = this.localTransform[4]; const a12 = positiony - (this.localTransform[4] * this.pivot.y - this.pivot.x * this.localTransform[3]); const b00 = parentTransform[0]; const b01 = parentTransform[1]; const b02 = parentTransform[2]; const b10 = parentTransform[3]; const b11 = parentTransform[4]; const b12 = parentTransform[5]; this.localTransform[2] = a02; this.localTransform[5] = a12; this.worldTransform[0] = b00 * a00 + b01 * a10; this.worldTransform[1] = b00 * a01 + b01 * a11; this.worldTransform[2] = b00 * a02 + b01 * a12 + b02; this.worldTransform[3] = b10 * a00 + b11 * a10; this.worldTransform[4] = b10 * a01 + b11 * a11; this.worldTransform[5] = b10 * a02 + b11 * a12 + b12; this.worldAlpha = this.alpha * this.parent.worldAlpha; for (const child of this.children) { child.updateTransform(); } } addChild(child, updateParent = true) { if (!~this.children.indexOf(child)) { this.children.push(child); } if (updateParent) child.setParent(this, false); } removeChild(child, updateParent = true) { if (!!~this.children.indexOf(child)) this.children.splice(this.children.indexOf(child), 1); if (updateParent) child.setParent(null, false); } setParent(parent, updateParent = true) { if (this.parent && parent !== this.parent) this.parent.removeChild(this, false); this.parent = parent; if (updateParent && parent) parent.addChild(this, false); } get rotation() { return this._rotation; } set rotation(v) { this._rotation = v; this._rotationComponents.x = Math.cos(this._rotation); this._rotationComponents.y = Math.sin(this._rotation); } }
import { merge, withStatus } from "litera"; import { withJson } from "litera-response-body"; // TODO: handle errors from graphql instead export default atom => async (req, data) => { try { return await atom(req, data); } catch (err) { // if (err instanceof GitHubError) { // return merge(withStatus(err.status), withJson(err.data)); // } throw err; } };
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsRoomService = { name: 'room_service', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M2 17h20v2H2zm11.84-9.21A2.006 2.006 0 0012 5a2.006 2.006 0 00-1.84 2.79C6.25 8.6 3.27 11.93 3 16h18c-.27-4.07-3.25-7.4-7.16-8.21z"/></svg>` };
var propaneDivOne = document.getElementById("propaneDiv1"); var propaneDivTwo = document.getElementById("propaneDiv2"); window.onscroll = function(){ if(window.scrollY>20){ propaneDivOne.classList.replace("hideDiv1","showDiv1"); } if(window.scrollY>450){ propaneDivTwo.classList.replace("hideDiv2","showDiv2"); } }
import {put, call, takeLatest} from 'redux-saga/effects'; import {cinema} from '../service'; import {CinemaState} from '../state'; import DispatchConstants from './DispatchConstants'; export function* cinemaApiCall(action) { yield put(CinemaState.updateLoader(true)); yield put(CinemaState.updateError(false)) const filmApiResponse = yield call(cinema.callApi, 'filmworld'); // console.log('API REsponse for ', action.payload, apiResponse); if (filmApiResponse.response_type === 'success') { yield put(CinemaState.updateFilm(filmApiResponse.response)); const cinemaApiReponse = yield call(cinema.callApi, 'cinemaworld'); if (cinemaApiReponse.response_type === 'success') { yield put(CinemaState.updateCinema(cinemaApiReponse.response)); yield put(CinemaState.updateLoader(false)); } else { yield put(CinemaState.updateError(true)); yield put(CinemaState.updateCinema(null)); yield put(CinemaState.updateLoader(false)); } } else { yield put(CinemaState.updateError(true)); yield put(CinemaState.updateFilm(null)); yield put(CinemaState.updateLoader(false)); } } export function* watchCinema() { yield takeLatest(DispatchConstants.CINEMA_API, cinemaApiCall); }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /* global mat4, WGLUProgram */ /* Like CubeSea, but designed around a users physical space. One central platform that maps to the users play area and several floating cubes that sit just those boundries (just to add visual interest) */ window.VRUI = (function () { "use strict"; var VRUIVS = [ "uniform mat4 projectionMat;", "uniform mat4 modelViewMat;", "attribute vec3 position;", "attribute vec2 texCoord;", "varying vec2 vTexCoord;", "void main() {", " vTexCoord = texCoord;", " gl_Position = projectionMat * modelViewMat * vec4( position, 1.0 );", "}" ].join("\n"); var VRUIFS = [ "precision mediump float;", "uniform sampler2D diffuse;", "varying vec2 vTexCoord;", "void main() {", " gl_FragColor = texture2D(diffuse, vTexCoord);", "}" ].join("\n"); var VRUI = function (gl, spriteURL, spriteColumnCount, spriteRowCount) { this.gl = gl; this.statsMat = mat4.create(); var textureLoader = new WGLUTextureLoader(gl); this.texture = textureLoader.loadTexture(spriteURL); this.program = new WGLUProgram(gl); this.program.attachShaderSource(VRUIVS, gl.VERTEX_SHADER); this.program.attachShaderSource(VRUIFS, gl.FRAGMENT_SHADER); this.program.bindAttribLocation({ position: 0, texCoord: 1 }); this.program.link(); this.vertBuffer = gl.createBuffer(); this.indexBuffer = gl.createBuffer(); this.spriteColumnCount = spriteColumnCount || 4; this.spriteRowCount = spriteRowCount || 4; }; var UISprites = {}; VRUI.prototype.addSprite = function (name, colX, rowY) { UISprites[name] = new VRUI.UISprite(colX, rowY, this.spriteRowCount, this.spriteColumnCount); }; // onePixel = 1.0 / textureSize. var UIList = []; VRUI.prototype.addUI = function (spriteName, ax, ay, callback) { if(typeof UISprites[spriteName] == 'undefined') throw new Error("Sprite name not found: " + spriteName); if(!callback) callback = spriteName; if(typeof callback == 'string') callback = function() { document.dispatchEvent(new CustomEvent(callback)); }; var UIElm = new VRUI.UIElement(spriteName); UIElm.getPosition().set(ax, ay, 0, 0.5); UIList.push(UIElm); return UIElm; }; VRUI.prototype.render = function (projectionMat, modelViewMat, orientation) { var gl = this.gl; var program = this.program; program.use(); gl.uniformMatrix4fv(program.uniform.projectionMat, false, projectionMat); gl.uniformMatrix4fv(program.uniform.modelViewMat, false, modelViewMat); // Update positions var uiVerts = []; var uiIndicies = []; // Update all ui element positions for (var j = 0; j < UIList.length; j++) { var UpdateUIElm = UIList[j]; UpdateUIElm.update(orientation); } // Create array of positions and texture maps for (var i = 0; i < UIList.length; i++) { var UIElm = UIList[i]; // Get immediate position var IP = UIElm.getImmediatePosition(); var halfSize = IP.getSize()/2; var x = IP.getX(); var y = IP.getY(); var z = IP.getZ(); var pos = [0, 0, -5]; pos = rotY(pos, -x); pos = rotX(pos, y); x = pos[0]; y = pos[1]; z = pos[2]; var angleX = orientation[0]*2; var angleY = orientation[1]*2; //pos = rotY(pos, angleY); //pos = rotX(pos, -angleX); var lbz = [-halfSize, -halfSize, 0]; var rbz = [halfSize, -halfSize, 0]; var rtz = [halfSize, halfSize, 0]; var ltz = [-halfSize, halfSize, 0]; lbz = rotY(lbz, -angleY); rbz = rotY(rbz, -angleY); rtz = rotY(rtz, -angleY); ltz = rotY(ltz, -angleY); lbz = rotX(lbz, angleX); rbz = rotX(rbz, angleX); rtz = rotX(rtz, angleX); ltz = rotX(ltz, angleX); // Set up 2d indicies var idx = uiVerts.length / 5.0; uiIndicies.push(idx, idx + 1, idx + 2); // Add 3 points to make a triangle uiIndicies.push(idx, idx + 2, idx + 3); // Add 3 more points to make a complete square // Calculate sprite map box var sLeft = UIElm.getTextureLeft(); var sRight = UIElm.getTextureRight(); var sTop = UIElm.getTextureTop(); var sBottom = UIElm.getTextureBottom(); // Set up XYZ position coordinates and XY sprite map coordinates for a 2d sprite uiVerts.push(x + lbz[0], y + lbz[1], z + lbz[2], sLeft, sBottom); uiVerts.push(x + rbz[0], y + rbz[1], z + rbz[2], sRight, sBottom); uiVerts.push(x + rtz[0], y + rtz[1], z + rtz[2], sRight, sTop); uiVerts.push(x + ltz[0], y + ltz[1], z + ltz[2], sLeft, sTop); } // Bind the positions and texture maps to the buffers gl.bindBuffer(gl.ARRAY_BUFFER, this.vertBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(uiVerts), gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(uiIndicies), gl.STATIC_DRAW); var indexCount = uiIndicies.length; uiIndicies = null; uiVerts = null; // Render everything // gl.bindBuffer(gl.ARRAY_BUFFER, this.vertBuffer); // Only necessary if not bound earlier // gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); // Only necessary if not bound earlier gl.enableVertexAttribArray(program.attrib.position); gl.enableVertexAttribArray(program.attrib.texCoord); // Enable 2 extra parameters for vertex attributes, I think? gl.vertexAttribPointer(program.attrib.position, 3, gl.FLOAT, false, 20, 0); // Enable position vertex (X,Y,Z) gl.vertexAttribPointer(program.attrib.texCoord, 2, gl.FLOAT, false, 20, 12);// Enable texture coordinates (X,Y) gl.activeTexture(gl.TEXTURE0); // Select texture 0 gl.bindTexture(gl.TEXTURE_2D, this.texture); // Bind sprite map to texture 0 gl.uniform1i(this.program.uniform.diffuse, 0); gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0); //if (stats) { // // To ensure that the FPS counter is visible in VR mode we have to // // render it as part of the scene. // mat4.fromTranslation(this.statsMat, [0, 1.5, -this.depth * 0.5]); // mat4.scale(this.statsMat, this.statsMat, [0.5, 0.5, 0.5]); // mat4.rotateX(this.statsMat, this.statsMat, -0.75); // mat4.multiply(this.statsMat, modelViewMat, this.statsMat); // stats.render(projectionMat, this.statsMat); //} }; VRUI.UISprite = function (colX, rowY, totalRows, totalColumns) { var tLeft = 0.0; var tRight = 1.0; var tTop = 0.0; var tBottom = 1.0; if(colX !== null && rowY !== null && totalRows !== null && totalColumns !== null) { tLeft = ((colX) / totalColumns); // Left side of box tRight = ((colX+1) / totalColumns); // Right side of box tTop = ((rowY) / totalRows); // Top side of box tBottom = ((rowY+1) / totalRows); // Bottom side of box } this.getTextureLeft = function() { return tLeft; }; this.getTextureRight = function() { return tRight; }; this.getTextureTop = function() { return tTop; }; this.getTextureBottom = function() { return tBottom; }; }; VRUI.UIPosition = function (x, y, z, size) { this.ACCURACY = 0.01; this.getX = function() { return x;}; this.getY = function() { return y;}; this.getZ = function() { return z;}; this.getSize = function () { return size; }; this.set = function (newX, newY, newZ, newSize, accuracy) { if(!accuracy) accuracy = this.ACCURACY; if (typeof newX == 'number') x = Math.round(newX / accuracy) * accuracy; if (typeof newY == 'number') y = Math.round(newY / accuracy) * accuracy; if (typeof newZ == 'number') z = Math.round(newZ / accuracy) * accuracy; if (typeof newSize == 'number') size = Math.round(newSize / accuracy) * accuracy; }; this.getLeft = function() { return x - size/2; }; this.getRight = function() { return x + size/2; }; this.getTop = function() { return y + size/2; }; this.getBottom = function() { return y - size/2; }; this.updateTowards = function(position, fraction) { if(x > position.getX()) x -= (x - position.getX()) * fraction; else if(x < position.getX()) x += (position.getX() - x) * fraction; if(y > position.getY()) y -= (y - position.getY()) * fraction; else if(y < position.getY()) y += (position.getY() - y) * fraction; if(z > position.getZ()) z -= (z - position.getZ()) * fraction; else if(z < position.getZ()) z += (position.getZ() - z) * fraction; if(size > position.getSize()) size -= (size - position.getSize()) * fraction; else if(size < position.getSize()) size += (position.getSize() - size) * fraction; } }; VRUI.UIElement = function (spriteName, position) { if(!position) position = new VRUI.UIPosition(0.0, 0.0, 0.0, 1.0); var immediatePosition = new VRUI.UIPosition(0.0, 0.0, 0.0, 0.1); this.getPosition = function() { return position;}; this.setPosition = function(newPosition) { position = newPosition;}; this.getImmediatePosition = function() { return immediatePosition;}; this.setImmediatePosition = function(newPosition) { immediatePosition = newPosition;}; this.getTextureLeft = function() { return UISprites[spriteName].getTextureLeft(); }; this.getTextureRight = function() { return UISprites[spriteName].getTextureRight(); }; this.getTextureTop = function() { return UISprites[spriteName].getTextureTop(); }; this.getTextureBottom = function() { return UISprites[spriteName].getTextureBottom(); }; var THIS = this; this.update = function(orientation) { immediatePosition.updateTowards(position, 0.1); // var xyz = [UIList.length / 2 - this.i, -0.5, -2.0]; var angleX = orientation[1]; var angleY = orientation[0]; var x = immediatePosition.getX(); var y = immediatePosition.getY(); var dist = Math.sqrt(Math.pow(x - angleX, 2) + Math.pow(y - angleY, 2)); if(dist < 0.1) { position.set(null, null, null, 1.5); } else { position.set(null, null, null, 0.5); } // xyz = rotY(xyz, -angleY); // position.set(xyz[0], xyz[1], xyz[2]); } }; function rotX(xyz, angleX) { var x = xyz[0], y = xyz[1], z = xyz[2]; var xx = x; var yy = y*Math.cos(angleX)-z*Math.sin(angleX); var zz = y*Math.sin(angleX)+z*Math.cos(angleX); return [xx, yy, zz]; } function rotY(xyz, angleY) { var x = xyz[0], y = xyz[1], z = xyz[2]; var yy = y; var xx = x*Math.cos(angleY)-z*Math.sin(angleY); var zz = x*Math.sin(angleY)+z*Math.cos(angleY); return [xx, yy, zz]; } function rotZ(xyz, angleY) { var x = xyz[0], y = xyz[1], z = xyz[2]; var yy = x*Math.cos(angleX)-y*Math.sin(angleX); var xx = x*Math.cos(angleY)-y*Math.sin(angleY); var zz = z; return [xx, yy, zz]; } return VRUI; })();
"use strict"; var winston = require('winston'); var _ = require('lodash'); var async = require('async'); var nconf = require('nconf'); var multer = require('multer'); var UploadStorage = require('./uploadStorage'); var logger = require('../logger'); var customerSession = require('../database/customerSession'); module.exports = function (middleware) { var imageUpload = multer({ storage: UploadStorage.imageStorage(), limits: {fileSize: nconf.get('images:fileSize')}, fileFilter: UploadStorage.imageFilter }); middleware.uploadImage = function (req, res, next) { var condition = {cid: req.params.cid}; var who = req.query.f; async.waterfall([ function (next) { customerSession.findOne(condition, next); }, function (customer, next) { checkMonthFileSize(customer, req, next); }, function (next) { imageUpload.single('image')(req, res, function (err) { if (err) return next(new Error('upload-file-has-error')); if (!_.isUndefined(who)) { // only update customer req.monthlyUploadSize = getYearMonth() + ',' + (parseInt(req.file.size) + parseInt(req.lastUploadSize)); updateMonthSize(req); } next(null, { code: 200, msg: { original: req.file.path, resized: req.file.resizePath, w: req.file.resizeWidth, h: req.file.resizeHeight } }); }); } ], function (err, result) { if (!err) return res.json(result); logger.error(err); switch (err.message) { case 'customer-not-found': res.json({code: 5001, msg: err.message}); break; case 'exceed-monthly-max-size': res.json({code: 5002, msg: err.message}); break; case 'upload-file-has-error': res.json({code: 5003, msg: err.message}); break; case 'crypto-name-has-error': logger.error(err); break; case 'resize-file-has-error': res.json({code: 5005, msg: err.message}); break; case 'upload-file-name-undefined': res.json({code: 5006, msg: err.message}); break; default: res.json({code: 5010, msg: err.message}); break; } }); }; var avatarUpload = multer({ storage: UploadStorage.avatarStorage(), limits: {fileSize: nconf.get('images:fileSize')}, fileFilter: UploadStorage.imageFilter }); middleware.uploadAvatar = avatarUpload.single('avatars'); function checkMonthFileSize(customer, req, next) { if (!customer) return next(new Error('customer-not-found')); var yearMonth = getYearMonth(); var monthlyUploadSize = 0; var uploadArray; if (customer.upload) { uploadArray = customer.upload.split(','); monthlyUploadSize = uploadArray[1]; if (uploadArray[0] !== yearMonth) { monthlyUploadSize = 0; } } if (monthlyUploadSize - nconf.get("images:monthlyMaxSize") > 0) { return next(new Error('exceed-monthly-max-size')); } req.lastUploadSize = monthlyUploadSize; req.uploadCacheUUID = customer.uuid; next(); } function updateMonthSize(req) { var monthlyUploadSize = req.monthlyUploadSize; var upload = {upload: monthlyUploadSize}; var condition = {uuid: req.uploadCacheUUID}; setImmediate(function () { customerSession.update(upload, condition, function (err, data) { if (err) logger.error(err); }); }); } function getYearMonth() { var now = new Date(); var mm = now.getMonth() + 1; return [now.getFullYear(), (mm > 9 ? '' : '0') + mm].join(''); } };
const mongoose = require("mongoose"); const Schema = mongoose.Schema; // Create Schema const DogSchema = new Schema({ owner: { type: Schema.Types.ObjectId, ref: "users" }, name: { type: String, required: true }, sex: { type: String, required: true }, dateofbirth: { type: Date, required: true }, primarycolor: { type: String, required: true }, secondarycolor: { type: String, required: true }, breed: { type: String, required: true }, vaccination: [ { name: { type: String }, age: { type: String }, date: { type: Date }, next: { type: Date } } ] }); module.exports = Dog = mongoose.model("dogs", DogSchema);
const ua = require('universal-analytics'); const uuid = require('uuid/v4'); const { TrackingIdStore: store } = require('./ElectronStore'); const packageVersion = require('../../package.json'); let visitor; let appName = 'app.ssh-git'; let appVersion = packageVersion.version; function initAnalytics() { const userId = store.get('userId') || uuid(); visitor = ua('UA-155290096-1', userId); } function trackEvent(category, action) { visitor .event(category, action, error => { if (error) console.error('error tracking event: ', error.message); }) .send(); } function trackScreen(screenName) { visitor .pageview(screenName, appName, appVersion, error => { if (error) { console.error('error tracking pageview: ', error.message); } }) .send(); } module.exports = { initAnalytics, trackEvent, trackScreen };
import React, { Component, PropTypes } from 'react'; import d3 from 'd3'; import _ from 'underscore'; import './SplineChart.css'; class SplineChart extends Component { componentWillMount() { let { xScale, yScale, radius } = this.props; this.dot = d3.svg.symbol().type('circle').size(radius); this.line = d3.svg.line() .interpolate('cardinal') .x((d) => { return xScale(d.x); }) .y((d) => { return yScale(d.y); }); } render() { let { xScale, yScale, data } = this.props, circles = _.map(data, (d, i) => { let translate = `translate(${xScale(d.x)}, ${yScale(d.y)})`, className = d.significant ? 'dot significant' : 'dot'; return ( <path key={`circle${i}`} className={className} d={this.dot()} transform={translate} /> ); }); return ( <g className="splineChart"> <path className="line" d={this.line(this.props.data)} /> {circles} </g> ); } } SplineChart.propTypes = { data: PropTypes.arrayOf( PropTypes.shape({ x: PropTypes.number.isRequired, y: PropTypes.number.isRequired, significant: PropTypes.bool, }) ).isRequired, xScale: PropTypes.func.isRequired, yScale: PropTypes.func.isRequired, radius: PropTypes.number.isRequired, }; export default SplineChart;
import React from "react"; import { PanelHeader } from "components"; import NotificationAlert from "react-notification-alert"; import Cookies from 'universal-cookie'; import Member from "../Member/Member"; import { Query } from "react-apollo"; import gql from "graphql-tag"; import Loading from "../../components/Loading/Loading"; class Dashboard extends React.Component { constructor(props) { super(props); let cookies = new Cookies(); this.state = { username: cookies.get("VOILK_USERNAME"), privatekey: cookies.get("VOILK_POSTING"), posting_pubkey: cookies.get("VOILK_POSTINGPUB") }; this.onDismiss = this.onDismiss.bind(this); this.notify = this.notify.bind(this); } isLoggedIn = () => { // let cookies = new Cookies(); // this.setState({ // username: cookies.get("VOILK_USERNAME"), // privatekey: cookies.get("VOILK_POSTING"), // posting_pubkey: cookies.get("VOILK_POSTINGPUB") // }); console.log(this.state.username); if (this.state.username == "null" || this.state.privatekey == "null" || this.state.posting_pubkey == "null"|| this.state.username == undefined || this.state.posting_pubkey == undefined|| this.state.privatekey == undefined ) { window.location.href = "/login" } } onDismiss() { } notify(place, msg) { var color = Math.floor(Math.random() * 5 + 1); var type; switch (color) { case 1: type = "primary"; break; case 2: type = "success"; break; case 3: type = "danger"; break; case 4: type = "warning"; break; case 5: type = "info"; break; default: break; } type = "info"; var options = {}; options = { place: place, message: ( <div> {msg} </div> ), type: type, icon: "now-ui-icons ui-1_bell-53", autoDismiss: 10 }; this.refs.notificationAlert.notificationAlert(options); } render() { return ( <React.Fragment> {this.isLoggedIn()} <PanelHeader size="sm" /> <div className="content"> <NotificationAlert ref="notificationAlert" /> <Query query={gql` { get_ads_profile( username: "${this.state.username}", private_posting_key: "${this.state.privatekey}" ) { _id name username credit ads { _id ad_type ad_link ad_target ad_width ad_height ad_status ad_active ad_clicks{ ad_browser ad_platform created_at geoplugin_areaCode geoplugin_city geoplugin_continentCode geoplugin_continentName geoplugin_countryCode geoplugin_countryName geoplugin_currencyCode geoplugin_currencyConverter geoplugin_currencySymbol geoplugin_currencySymbol_UTF8 geoplugin_delay geoplugin_dmaCode geoplugin_euVATrate geoplugin_inEU geoplugin_latitude geoplugin_locationAccuracyRadius geoplugin_timezone geoplugin_status geoplugin_request geoplugin_regionName geoplugin_regionCode geoplugin_region geoplugin_longitude } ad_impressions{ ad_browser ad_platform created_at geoplugin_areaCode geoplugin_city geoplugin_continentCode geoplugin_continentName geoplugin_countryCode geoplugin_countryName geoplugin_currencyCode geoplugin_currencyConverter geoplugin_currencySymbol geoplugin_currencySymbol_UTF8 geoplugin_delay geoplugin_dmaCode geoplugin_euVATrate geoplugin_inEU geoplugin_latitude geoplugin_locationAccuracyRadius geoplugin_timezone geoplugin_status geoplugin_request geoplugin_regionName geoplugin_regionCode geoplugin_region geoplugin_longitude } created_at updated_at ad_status } created_at updated_at error } } `} > {({ loading, error, data }) => { if (loading) return <Loading message={"Loading Transactions..."} color={"info"} />; if (error) return <p>Error :(</p>; return( <Member info={data.get_ads_profile}/> ) }} </Query> </div> </React.Fragment> ); } } export default Dashboard;
import React from 'react'; import {Modal, Icon, Form, TextArea, Popup, Button} from 'semantic-ui-react'; import bg from '../../assets/background.jpg' const FormularioComentarios = ({ guardar, comentario, setComentario, modalComentarios, setModalComentarios, }) => { const onChangeComentario = e => { setComentario({ ...comentario, [e.target.name]:e.target.value }) } return ( <Modal open={modalComentarios} > <Modal.Header style={{backgroundImage: `url(${bg})`, color: 'white'}} > <Icon name="clipboard check"/> Nuevo Comentario </Modal.Header> <Modal.Content> <Form> <h3> Comentario </h3> <Form.Group widths="equal"> <Form.Input label="Asunto" name="asunto" value={comentario.asunto} onChange={onChangeComentario} /> <Form.Input label={ <Popup content="Ponlo para dar formalidad >:3" trigger={ <label> <Icon name="info circle"/> Correo Electronico </label> } /> } value={comentario.email} name="email" onChange={onChangeComentario} /> </Form.Group> <Form.Group widths="equal"> <Form.Input label="Nombres" name="nombres" value={comentario.nombres} onChange={onChangeComentario} /> <Form.Input label="Apellido" name="curso" value={comentario.curso} onChange={onChangeComentario} /> </Form.Group> <Form.Group widths="equal"> <Form.Field> <label>Contenido del Comentario</label> <TextArea name="contenido" value={comentario.contenido} onChange={onChangeComentario} /> </Form.Field> </Form.Group> </Form> </Modal.Content> <Modal.Actions > <Button content="CANCELAR" onClick={() => setModalComentarios(false)} style={{ fontWeight: 'bold', color:"black", borderRadius:25, }} /> <Button content="CREAR" onClick={() => guardar()} style={{ fontWeight: 'bold', color:"black", borderRadius:25, }} /> </Modal.Actions> </Modal> ); } export default FormularioComentarios;
exports.command = 'lint [type]'; exports.desc = 'Lint'; exports.builder = { type: { default: 'all' } }; exports.handler = (argv) => { const chalk = require('chalk'); console.log(chalk.yellow('[COMMAND: AngularX CLI] Lint:')); };
// let redir = function (params) { // document.getElementById("abt").scrollTo({behavior:"smooth"}); // }
export { get as getRoomType } from './get';
app.get('/usermeeage',function(req,res){ var username = req.query.username; var password = req.query.password; var ret = {}; ret.username =username; ret.password =password; ret = JSON.stringify(ret); res.send(ret); })
import React, {Component} from 'react' import Footer from '../widget/footer.jsx' import {Segment, Message} from 'semantic-ui-react' import BrowserLink from '../widget/browser-link.jsx' import api from '../../connect/api.jsx' import {render} from 'react-dom' export default class Invalid extends Component { render() { return <div className="page invalid"> <Segment> <h1>Ошибка привязки приложения</h1> <Message error icon="warning sign" content="Ваш аккаунт был привязан к другому компьютеру, для того чтобы привьязать к этому компьютеру перейдите по ссылке ниже"/> <BrowserLink href={'http://mlbot.inbisoft.com/conflict/' + api.hashToken}> Запрос на сброс привьязки </BrowserLink> </Segment> <Footer/> </div> } static render() { render(<Invalid/>, document.getElementById('app')) } }
import styled from '@kuba/styled' export default styled` :root { --border-radius-none: 0; --border-radius-sm: 8px; --border-radius-md: 16px; --border-radius-lg: 24px; --border-radius-pill: 500px; --border-radius-circular: 50%; } `
import React, { Component } from "react" import SearchBar from "./SearchBar" import Table from "./Table" import Api from "../utils/Api" // table export default class Main extends Component { constructor(props) { super(props) this.state = { users: [], filteredUsers: [], sortedUsers: [] }; this.sortByAsc = this.sortByAsc.bind(this); this.sortByDesc = this.sortByDesc.bind(this); } sortByAsc() { this.setState(prevState => { this.state.users.sort((a, b) => (a.name - b.name)) }); } sortByDesc() { this.setState(prevState => { this.state.users.sort((a, b) => (b.name - a.name)) }); } // state = { // users: [{}], // order: "descend", // filteredUsers: [{}], // sortedUsers: [{}] // } handleSearchChange = event => { console.log(event.target.value) const filter = event.target.value console.log(filter) const filteredList = this.state.users.filter( item => { let values = Object.values(item.name).join("").toLowerCase() console.log(values, item) return values.indexOf(filter.toLowerCase()) !== -1 }) console.log(filteredList) this.setState({ filteredUsers: filteredList }) } componentDidMount() { Api.getUsers().then(results => { console.log(results) this.setState({ users: results.data.results, filteredUsers: results.data.results, sortedUsers: (a, b) => { a = a.name || ''; b = b.name || ''; return a.localeCompare(b); } }) }).catch(err => { console.log(err) }) } // sort, button, onClick handle sort, that would be in the table, handle sort lives in the main, if ascend flip to descend. const sortedUsers = this.state.filteredUsers.sort() render() { return ( <div> <SearchBar handleSearchChange= {this.handleSearchChange} /> <div> <Table users= {this.state.filteredUsers} /> </div> </div> ) } }
import benchPic from "../images/bench.jpeg"; function Bench() { return ( <div> <h2> Нажмите на скамейку, чтобы скачать эскиз <br /> Please click the bench to download the sketch </h2> <a href={benchPic} download> <img className="bench-pic" src={benchPic} /> </a> </div> ); } export default Bench;
var MyMethods = require('./http-functions'); var getHTML = MyMethods.get; var printHTML = MyMethods.print; var printHTMLlower = MyMethods.printLower; var printHTMLupper = MyMethods.printUpper; var printHTMLreverse = MyMethods.printReverse; var printHTMLl33t = MyMethods.printL33t; var options = { host: 'sytantris.github.io', path: '/http-examples/step6/1337.html' }; getHTML(options, printHTMLl33t);
function validateUser(userId, password, serverPath,redirectUrl){ var url = serverPath + "ajaxpage/login-validate.od?userId=" + userId +"&passKey="+password+"&r=" + Math.random(); $.get(url, function(result) { result = result.replace(/\r\n/g, ""); if (result == "SUCCESS") { window.location.href = redirectUrl; }else{ alert("登录失败!"+result); } }); }
define( [ "jquery", 'mage/url', "Magento_Checkout/js/view/payment/default", "Magento_Checkout/js/action/place-order", "Magento_Checkout/js/model/payment/additional-validators", "Magento_Checkout/js/model/quote", "Magento_Checkout/js/model/full-screen-loader", "Magento_Checkout/js/action/redirect-on-success", ], function ( $, mageUrl, Component, placeOrderAction, additionalValidators, quote, fullScreenLoader, redirectOnSuccessAction ) { 'use strict'; return Component.extend({ defaults: { template: 'Payflexi_Checkout/payment/payflexi_checkout' }, redirectAfterPlaceOrder: false, isActive: function () { return true; }, /** * Provide redirect to page */ redirectToCustomAction: function (url) { fullScreenLoader.startLoader(); window.location.replace(mageUrl.build(url)); }, /** * @override */ afterPlaceOrder: function () { var checkoutConfig = window.checkoutConfig; var paymentData = quote.billingAddress(); var payflexiConfiguration = checkoutConfig.payment.payflexi_checkout; if (payflexiConfiguration.integration_type == 'standard') { this.redirectToCustomAction(payflexiConfiguration.integration_type_standard_url); } else { if (checkoutConfig.isCustomerLoggedIn) { var customerData = checkoutConfig.customerData; paymentData.email = customerData.email; } else { paymentData.email = quote.guestEmail; } var visibleItems = checkoutConfig.quoteItemData; var products = ''; visibleItems.forEach((item, index) => { var orderedItem = item.name + ", Qty:" + item.qty + ", Sku:" + item.product.sku; if (item.options && item.options.length >= 1) { item.options.forEach((option, i) => { orderedItem = orderedItem + ", " + option.label + ":" + option.value; }) } if (index < visibleItems.length - 1) { orderedItem = orderedItem + " | "; } products += orderedItem; }); var quoteId = checkoutConfig.quoteItemData[0].quote_id; var _this = this; _this.isPlaceOrderActionAllowed(false); var handler = PayFlexi.checkout({ key: payflexiConfiguration.public_key, gateway: payflexiConfiguration.enabled_gateway, name: paymentData.firstname + ' ' + paymentData.lastname, email: paymentData.email, amount: Math.ceil(quote.totals().grand_total), // get order total from quote for an accurate... quote currency: checkoutConfig.totalsData.quote_currency_code, meta: { title: products, quoteId: quoteId, billing_address: paymentData.street[0] + ", " + paymentData.street[1], phone: paymentData.telephone, city: paymentData.city + ", " + paymentData.countryId }, onSuccess: function (response) { fullScreenLoader.startLoader(); $.ajax({ method: "GET", url: payflexiConfiguration.api_url + "V1/payflexi/verify/" + response.reference + "_-~-_" + quoteId }).success(function (data) { data = JSON.parse(data); if (data.status) { if (data.status === "approved") { // redirect to success page after redirectOnSuccessAction.execute(); return; } } fullScreenLoader.stopLoader(); _this.isPlaceOrderActionAllowed(true); _this.messageContainer.addErrorMessage({ message: "Error, please try again" }); }); }, onDecline: function(response){ fullScreenLoader.startLoader(); $.ajax({ method: "GET", url: payflexiConfiguration.api_url + "V1/payflexi/verify/" + response.reference + "_-~-_" + quoteId }).success(function (data) { data = JSON.parse(data); _this.redirectToCustomAction(payflexiConfiguration.recreate_quote_url); }); }, onExit: function(){ _this.redirectToCustomAction(payflexiConfiguration.recreate_quote_url); } }); handler.renderCheckout(); } }, }); } );
import React, { PropTypes } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Freight.less'; import {Indent, SuperToolbar, SuperTable, SuperPagination} from '../../../../../components'; class Freight extends React.Component { toToolbar = () => { const {buttons, onClick} = this.props; const props = {buttons, onClick}; return <SuperToolbar {...props}/> } toTable = () => { const {cols, tableItems=[], onCheck, onDoubleClick} = this.props; const tableProps = { cols, items: tableItems, callback: {onCheck, onDoubleClick} }; return <div className={s.table}> <SuperTable {...tableProps}/> <div className={s.page}><SuperPagination {...this.props}/></div> </div> } render() { return ( <Indent className={s.root}> {this.toToolbar()} {this.toTable()} </Indent> ); } } export default withStyles(s)(Freight);
import React, { useState } from "react"; import Grid from "@material-ui/core/Grid"; import TextField from "@material-ui/core/TextField"; import Button from "@material-ui/core/Button"; import { Paper } from "@material-ui/core"; import Dropdown from "./dropdown"; import { style } from "./../styles"; function CreateForm(props) { const [one, setOne] = useState(""); const [two, setTwo] = useState(""); const [three, setThree] = useState(""); const [four, setFour] = useState(""); const [answer, setAnswer] = useState(""); const [answers, setAnswers] = useState([]); const [question, setQuestion] = useState(""); const inputWidth = "50vw"; const handleAnswer = (answer) => { setAnswer(answer); }; const addQuestion = () => { const questionObj = { question: question, answers: answers, answer: answer, }; // console.log(questionObj); props.addQuestion(questionObj); }; const saveTest = () => { props.saveTest(); }; return ( <Paper elevation={10} style={{ padding: "20x 20x 20x 20x", backgroundColor: style.colors.yellow, }} > <form noValidate autoComplete="off"> <Grid container spacing={3} direction="column" justify="center" alignItems="center" style={{ padding: "20px 20px 20px 20px" }} > <Grid item> <TextField id="0" variant="outlined" label="Question" style={{ width: inputWidth }} onChange={(event) => { setQuestion(event.target.value); }} inputProps={{ style: { color: style.colors.pink } }} />{" "} <br /> </Grid> <Grid item> <TextField id="1" variant="outlined" label="first answer" style={{ width: inputWidth }} onChange={(event) => { setOne(event.target.value); setAnswers([event.target.value, two, three, four]); }} inputProps={{ style: { color: style.colors.pink } }} />{" "} <br /> </Grid> <Grid item> <TextField id="2" variant="outlined" label="second answer" style={{ width: inputWidth }} onChange={(event) => { setTwo(event.target.value); setAnswers([one, event.target.value, three, four]); }} inputProps={{ style: { color: style.colors.pink } }} />{" "} <br /> </Grid> <Grid item> <TextField id="3" variant="outlined" label="third answer" style={{ width: inputWidth }} onChange={(event) => { setThree(event.target.value); setAnswers([one, two, event.target.value, four]); }} inputProps={{ style: { color: style.colors.pink } }} />{" "} <br /> </Grid> <Grid item> <TextField id="4" variant="outlined" label="fourth answer" style={{ width: inputWidth }} onChange={(event) => { setFour(event.target.value); setAnswers([one, two, three, event.target.value]); }} inputProps={{ style: { color: style.colors.pink } }} />{" "} <br /> </Grid> </Grid> </form> <Grid container spacing={3} direction="column" justify="center" alignItems="center" style={{ padding: "20px 20px 20px 20px" }} > <Grid item> <Dropdown questions={answers} handleAnswer={handleAnswer} /> <br /> </Grid> <Grid item> <Button variant="contained" color="primary" onClick={addQuestion} style={{ backgroundColor: style.colors.pink, fontFamily: style.button.fontFamily, }} > Add Question </Button> </Grid> <Grid item> <Button variant="contained" color="primary" onClick={saveTest} style={{ backgroundColor: style.colors.pink, fontFamily: style.button.fontFamily, }} > Save Game </Button> </Grid> </Grid> </Paper> ); } export default CreateForm;
const mongoose = require('mongoose'); const schema = mongoose.Schema; const roomSchema = new schema({ name:{type:String , required:true}, }) module.exports = mongoose.model('room', roomSchema);
import { fork, take, call, put, all } from 'redux-saga/effects'; import { eventChannel } from 'redux-saga'; import { FireService } from '../../services'; import * as actions from './actions'; import * as constants from './constants'; import * as parse from './parse'; export function makeTopStoriesObserver(emitter) { return (snapshot) => { const value = snapshot.val(); emitter(actions.topStoriesUpdates(value)); }; } export function topStoriesChannel() { return eventChannel((emitter) => { const topStoriesObserver = makeTopStoriesObserver(emitter); FireService.addObserver('topstories', 'value', topStoriesObserver); // the subscriber must return an unsubscribe function return () => { FireService.removeObserver('topstories', 'value', topStoriesObserver); }; }); } export function* loadStories(ids) { try { const data = []; for (let i = 0; i < ids.length; i++) { const id = ids[i]; const path = `item/${id}`; const snapshot = yield call( FireService.readOnce, path, ); data.push(snapshot.val()); } const formatted = parse.stories(data); yield put(actions.loadStoriesSuccess(formatted)); } catch (err) { yield put(actions.loadStoriesFailure(err.message, err)); } } /** * Generator function to listen for redux actions * * Handles any action api requests as non-blocking calls and * returns the appropriate action responses * @returns {SagaIterator} */ export function* watch() { while (true) { const { type, payload = {} } = yield take([ constants.TOP_STORIES_REQUEST, constants.LOAD_STORIES_REQUEST, ]); switch (type) { case constants.LOAD_STORIES_REQUEST: yield fork( loadStories, payload.ids, ); break; default: yield null; } } } /** * Generator function to listen for saga event channel emissions */ export function* eventWatch() { const channel = yield call(topStoriesChannel); try { while (true) { const { type, payload = {} } = yield take(channel); switch (type) { case constants.TOP_STORIES_UPDATES: yield put(actions.topStoriesSuccess(payload.ids)); break; default: yield null; break; } } } catch (error) { // nothing } } export default function* rootSaga() { yield all([watch(), eventWatch()]); }
(function(){ angular .module('myApp') .controller('MarketController', ['Market', MarketController ]); function MarketController(Market, FormDataService) { var vm = this; } })();
// app.counterController.js (function() { "use strict"; angular.module("CounterApp") .controller("CounterController", CounterController); CounterController.$inject = ["$scope"]; function CounterController($scope) { $scope.onceCount = 0; $scope.counter = 0; $scope.showNumberOfWatchers = showNumberOfWatchers; $scope.countOnce = countOnce; $scope.increment = increment; function showNumberOfWatchers() { console.log("# of Watchers", $scope.$$watchersCount); } function countOnce() { $scope.onceCount = 1; } function increment() { $scope.counter++; } $scope.$watch("onceCount", (newValue, oldValue) => { console.log("onceCount newValue: ", newValue); console.log("onceCount oldValue: ", oldValue); }); $scope.$watch("counter", (newValue, oldValue) => { console.log("counter newValue: ", newValue); console.log("counter oldValue: ", oldValue); }); } })();
var searchData= [ ['modelchanged',['modelChanged',['../class_branch_controller.html#afc4446fcb492d4471d7d54a25aa986c1',1,'BranchController::modelChanged()'],['../class_commit_controller.html#ac3e01f65e4003edc6b2f08a454568bcc',1,'CommitController::modelChanged()']]], ['msleep',['msleep',['../class_sleep.html#a402902c10de37debf16043c236897a0c',1,'Sleep']]] ];
export { default as NotFound } from "./NotFound"; export { default as Home } from "./Home"; export { default as PageProjet } from "./PageProjet"; export { default as Categorie } from "./Categorie"; export { default as Actualites } from "./Actualites"; export { default as ContactCV } from "./ContactCV";
import * as httpUtil from './httpUtil'; const baseUrl="https://todo-simple-api.herokuapp.com"; const todoUrl=`${baseUrl}/todos`; function createList(){ let container=document.createElement('div'); container.style.width=500; container.innerHTML='TO-DO List<hr>'; container.id="container"; let title=document.createElement('input'); title.type='text'; title.placeholder='title'; let description=document.createElement('input'); description.type='text'; description.placeholder='description'; let add=document.createElement('input'); add.type='submit'; add.value='Add to List'; document.getElementsByTagName('body')[0].appendChild(container); container.appendChild(title); container.appendChild(description); container.appendChild(add); add.addEventListener("click",(e) =>{ e.preventDefault(); let data={ "title":title.value, "description":description.value, "isComplete":false } addList(todoUrl,data); }); } function addList(todoUrl,data){ httpUtil.post(todoUrl,data).then(response=>{ todoList(response.data.data.title,response.data.data.description,response.data.data.id); }); } function todoList(title,description,id){ let div= document.createElement('div'); let titleNew=document.createElement('label'); titleNew.innerHTML=title+' '; let descriptionNew=document.createElement('label'); descriptionNew.innerHTML=description+' '; let delButtonNew=document.createElement('input'); delButtonNew.type='submit'; delButtonNew.value='delete'; let upButtonNew=document.createElement('input'); upButtonNew.type='submit'; upButtonNew.value='update'; let container=document.getElementById('container'); container.appendChild(div); div.appendChild(titleNew); div.appendChild(descriptionNew); div.appendChild(delButtonNew); div.appendChild(upButtonNew); delButtonNew.addEventListener('click',(e)=>{ let delId=id; let delUrl=`${todoUrl}/${delId}`; deleteList(delUrl); container.removeChild(div); }); upButtonNew.addEventListener('click',(e)=>{ let upId=id; let upUrl=`${todoUrl}/${upId}`; div.removeChild(titleNew); div.removeChild(descriptionNew); div.removeChild(delButtonNew); div.removeChild(upButtonNew); updateForm(upUrl,div,title,description); }); } function updateForm(upUrl,div,title,description){ let upForm=document.createElement('form'); let titleUp=document.createElement('input'); titleUp.type='text'; titleUp.value=title; let descriptionUp=document.createElement('input'); descriptionUp.type='text'; descriptionUp.value=description; let ButtonUp=document.createElement('input'); ButtonUp.type='submit'; ButtonUp.value='Save'; upForm.appendChild(titleUp); upForm.appendChild(descriptionUp); upForm.appendChild(ButtonUp); div.appendChild(upForm); ButtonUp.addEventListener('click',(e)=>{ e.preventDefault(); let data={ "title":titleUp.value, "description":descriptionUp.value, "isComplete":false }; div.removeChild(upForm); console.log(data,upUrl); updateList(upUrl,data); }); } httpUtil.get(todoUrl).then(response => { response.data.data.forEach((todo) => { todoList(todo.title,todo.description,todo.id); }) }) function deleteList(delUrl){ httpUtil.remove(delUrl).then(response => { alert('deleted'); }) } function updateList(upUrl,data){ httpUtil.put(upUrl,data).then(response=>{ todoList(response.data.data.title,response.data.data.description,response.data.data.id); }) } createList();
// console.log('Hello World!'); // var language = 'JavaScript'; // var status = 'Awesome'; // var ourThoughts = language + ' is ' + status; // console.log(ourThoughts); // var greeting = 'Hello'; // greeting += ' World!'; // console.log('greeting:', greeting); // var capitalGreet = greeting.toUpperCase(); // var lowerCaseGreet = greeting.toLowerCase(); // console.log('capitalGreet:', capitalGreet); // console.log('lowerCaseGreet:', lowerCaseGreet); // var sentence = 'the quick brown fox jumped over the lazy dog'; // var words = sentence.split(' '); // console.log(words); // var firstName = 'Brendan'; // var lastName = 'Eich'; // console.log('firstName:', firstName); // console.log('lastName:', lastName); // var fullName = ` // Full Name // --- // First Name: ${firstName} // Last Name: ${lastName}`; // console.log(fullName); // var price = 23.09; // var tax = 0.07 // var total = price * (1 + tax); // console.log(total); // var age = 11; // age++; // console.log(age); // age--; // console.log(age); // Undefined is implicit emptiness // noVal is never given a value, so it is undefined // var noVal; // console.log(noVal); // undefined // Null is explicit emptiness // Values must be assigned null // var nullVal = null; // console.log(nullVal); // null // var favoriteThings = ['dogs', 'nature', 'friends']; // var firstThing = favoriteThings[0]; // var secondThing = favoriteThings[1]; // var thirdThing = favoriteThings[2]; // console.log(`I like ${firstThing}, ${secondThing}, and ${thirdThing}`); // var car = { // make: 'Tesla', // model: 'Model 3', // color: 'red' // }; // var key = 'color'; // Values are most commonly accessed using dot notation // console.log(`Car Make: ${car.make}`); // Tesla // Values can also be accessed using bracket notation // similar to ruby hashes // console.log(`Car Model: ${car['model']}`); // Model 3 // Bracket notation is useful for dynamically accessing properties using a variable string // console.log(`Car Color: ${car[key]}`); // Car Color: red // objects in JavaScript can have keys and values assigned dynamically after creation // car.engineSound = 'Vroom!!!'; // console.log(`Car Engine Sound: ${car.engineSound}`); // Car Engine Sound: "Vroom!!!" // var willLearnJavaScript = false; // willLearnJavaScript = !willLearnJavaScript; // console.log(willLearnJavaScript); // var areSame = 'Hello World!' === 'Hello World!'; // console.log('areSame:', areSame); // var areSame = 10 == '10'; // console.log('areSame:', areSame); // var areSame = 10 === '10'; // console.log('areSame:', areSame); // var areSame1 = false == 0; // console.log('false == 0:', areSame1); // var areSame2 = false == ''; // console.log('false == "":', areSame2); // var areSame3 = true == '1'; // console.log('true == "1":', areSame3); // var areSame4 = null == undefined; // console.log('null == undefined', areSame4); // var areSame1 = 10 !== 10; // console.log('areSame1:', areSame1); // var areSame2 = 6 !== '6'; // console.log('areSame2:', areSame2); // var shouldExecute = true; // if (shouldExecute === true) { // console.log('Hazaaaa! This code ran!'); // } // var num = 9; // if (num > 10) { // console.log('num is more than 10!'); // } else if (num < 8) { // console.log('num is less than 8!'); // } else { // console.log('num is somewhere between 8 and 10!'); // } // var num = 6; // BOTH conditionals must be true // if (num > 3 && num < 10) { // console.log('The number is larger than 3 AND smaller than 10'); // } // EITHER condition must be true // if (num === 6 || num > 10) { // console.log('The number is equal to six or larger than 10'); // } // for (var i = 1; i <= 10; i++) { // console.log(i); // } // var counter = 1; // while (counter <= 10) { // console.log(counter); // counter++ // } // var count = 1; // while (count < 10 ) { // console.log(count); // count += 2; // } // var strangeKids = ['Will', 'Mike', 'Lucas', 'Dustin', 'Max', 'Eleven']; // strangeKids.forEach(function(kid, index) { // console.log(`${index + 1}, ${kid}`); // }); // var movies = ['I Robot', 'Interstellar', 'I am Legend', 'Armaggedon'] // movies.forEach(function(movie) { // console.log(movie); // }); // function sayHello(name) { // console.log(`Hello ${name}!`); // } // function fullName(first, last) { // return `${first} ${last}!`; // } // var name = fullName('John', 'Smith'); // sayHello(name); // function subtract(num1, num2) { // var difference = num1 - num2; // return difference; // } // var difference = subtract(12, 4); // console.log(difference); var sum = add(6, 7) console.log(sum); function add(num1, num2) { var sum = num1 + num2; return sum; }
/** * login.js */ $(document).ready(function(){ $('label').css({marginTop:"3px", marginBottom:"5px"}); $('#login').focus(); }); /** * This function requires entry of username and password on the login form. */ function loginValidate() { var errcode = 0; if ($('#login').attr('value') == "") { errcode = 10; } if ($('#password').attr('value') == "") { errcode++; } if (errcode == 0) { return true; } if (errcode == 10) { alert('{lang_enter_user}'); $('#login').focus(); } else if (errcode == 11) { alert('{lang_enter_user_password}'); $('#login').focus(); } else { alert('{lang_enter_password}'); $('#password').focus(); } return false; } // eof
sample(); function sample() { console.log("WRite to console"); }
var Videos = function (PostGre) { "use strict"; var TABLES = require('../constants/tables'); var CONSTANTS = require('../constants/constants'); var VideoModel = PostGre.Models[TABLES.VIDEOS]; var badRequests = require('../helpers/badRequests')(); this.saveVideo = function (videoName, keyId, callback) { var saveData; var arr = videoName.split('_'); var err; if (arr.length < 5) { if (callback && ( typeof callback === 'function' )) { err = new Error('Incorrect video name'); err.status = 400; return callback(err); } } saveData = { key_id: keyId, datetime: arr[0], uuid: arr[1], longitude: arr[2], latitude: arr[3], ext: arr[4], project: CONSTANTS.PROJECT_NAME }; VideoModel .insert(saveData) .then(function (savedVideo) { if (callback && ( typeof callback === 'function' )) { callback(null, savedVideo); } }) .otherwise(function (err) { if (callback && ( typeof callback === 'function')) { return callback(err); } }); }; this.getVideosByEmail = function (req, res, next) { var email = req.param('email'); var start = req.param('start'); var end = req.param('end'); var endDate; var startString; var endString; var sql; var err; if (!email || !start || !end) { err = badRequests.notEnParams(); //logWriter.log( destination + ".getVideosByEmail()", "Not enough incoming parameters" ); return next(err); } endDate = new Date(end); // add 1 day to endDate; endDate.setDate(endDate.getDate() + 1); startString = new Date(start).toISOString(); endString = endDate.toISOString(); sql = "SELECT " + " keys.key, " + " CONCAT ( " + " TO_CHAR( videos.datetime, 'YYYY-MM-DD HH24:MI:SS' ), '_', " + " videos.uuid, '_', " + " longitude, '_', " + " latitude, '_', " + " ext " + " ) AS name, " + " videos.created_at " + "FROM users " + " INNER JOIN keys ON users.id=keys.user_id " + " INNER JOIN videos ON videos.key_id=keys.id " + "WHERE users.email='" + email + "' " + " AND users.project='" + CONSTANTS.PROJECT_NAME + "' " + " AND datetime BETWEEN '" + startString + "' AND '" + endString + "' " + "ORDER BY videos.datetime"; PostGre.knex .raw(sql) .then(function (queryResult) { var result = ( queryResult && queryResult.rows ) ? queryResult.rows : []; res.status(200).send(result); }) .otherwise(next); } }; module.exports = Videos;
var config = require('./config.json') , timerServer = require('./timerServer'); var express = require('express') , app = express(); /** Settings */ app.set('view engine', 'ejs'); /** Middleware */ app.use(express.static(__dirname + '/public')); /** Routes */ app.get('/', function(req, res) { res.render('index', { config : config, page : { title: 'Feidippes the Marathon timer', header: 'Feidippes the Marathon timer' } }); }); app.get('/control/reset/', function (req, res) { timerServer.resetTime(req, res); }); app.get('/control/', function (req, res) { res.render('admin', { config : config, page : { title: 'Feidippes the Marathon timer | Admin', header: 'Feidippes - Timer controller' } }); }); app.get('/time/', function (req, res) { timerServer.getTimes(req, res); }); /** Redirect unknown routes to home */ app.get('*', function (req, res) { res.redirect(config.baseUrl); }) app.listen(config.port, config.host); console.log('Server running on http://' + config.host + ((config.port !== 80) ? (':' + config.port) : '') + '/');
import React, {Component, PropTypes} from 'react'; import config from '../../../config'; import SideBar from './components/Sidebar'; import Header from './components/Header'; import styles from './MyCabinet.scss'; export default class MyCabinet extends Component { render() { return ( <div className={styles.myCabinetMainContainer}> <SideBar appHeading={config.app.name}/> <div className={styles.myCabinetContent}> <Header/> </div> </div> ); } }
import React from "react"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; import { Divider, } from "semantic-ui-react"; import TopSlideBox from "../TopSlideBox"; import ModelTable from "../ModelTable"; import ModelSearchBox from "../ModelSearchBox"; import { WEBSITE_PATH, TABLE_TYPE, CONTENTS_TYPE, } from "../../config/constants" import styles from "./styles.module.scss"; const ModelNew = (props, context) => ( <div className={styles.RootDivision}> <TopSlideBox slideType={CONTENTS_TYPE.MODEL} /> <ModelSearchBox /> <RenderModelScreen {...props} /> </div> ) const RenderModelScreen = (props, context) => { const NEW_TITLE = `${context.t("최신등록.")}` const NEW_DISCRIPTION = `${context.t("최근에 등록한 모델의 순서대로 보여집니다.")}` return ( <div className={styles.ModelListDivision}> <RenerTopDivision title={NEW_TITLE} description={NEW_DISCRIPTION} /> <Divider className={styles.Divider}/> <RenerModelFilter modelFilterList={props.modelFilterList} /> <ModelTable model_list={props.model_list} tableType={TABLE_TYPE.TYPE_B} /> <RenderGoBack linkPath={WEBSITE_PATH.MODEL} /> </div> ) } const RenerTopDivision = (props, context) => { return ( <div className={styles.TitleDivision}> <div className={styles.TitleText}> <p>{props.title}</p> </div> <div className={styles.DescriptionText}> <p>{props.description}</p> </div> </div> ) } const RenerModelFilter = (props, context) => { return ( <div className={styles.FilterDivision}> <div className={styles.FilterTitleText}> <p>{context.t("RESULTS FOR :")}</p> </div> <div className={styles.FilterDescriptionText}> { (props.modelFilterList === undefined || props.modelFilterList === null) ? <p>{context.t("ALL")}</p> : <p>{props.modelFilterList.toString()}</p> } </div> </div> ) } const RenderGoBack = (props, context) => { return ( <div className={styles.GoBackDivision}> <div className={styles.Text}> <Link to={props.linkPath} > {context.t("GO BACK")} </Link> </div> </div> ) } ModelNew.propTypes = { model_list: PropTypes.array, } ModelNew.contextTypes = { t: PropTypes.func.isRequired }; RenderModelScreen.contextTypes = { t: PropTypes.func.isRequired }; RenerModelFilter.contextTypes = { t: PropTypes.func.isRequired }; RenerTopDivision.contextTypes = { t: PropTypes.func.isRequired }; RenderGoBack.contextTypes = { t: PropTypes.func.isRequired }; export default ModelNew;
function runTest() { FBTest.openNewTab(basePath + "search/4603/issue4603.html", function() { FBTest.openFirebug(function() { FBTest.selectPanel("html"); var win = FW.Firebug.chrome.window; var doc = win.document; var searchField = doc.getElementById("fbSearchBox"); var searchFieldIcon = doc.getAnonymousElementByAttribute(searchField, "class", "fbsearch-icon"); var normalSearchFieldIcon = win.getComputedStyle(searchFieldIcon, null). backgroundImage; searchField.value = "search"; FBTest.ok(normalSearchFieldIcon != win.getComputedStyle(searchFieldIcon, null).backgroundImage, "Search Field icon must be changed"); FBTest.click(searchFieldIcon); FBTest.compare("", searchField.value, "Search Field must be cleared"); FBTest.compare(normalSearchFieldIcon, win.getComputedStyle(searchFieldIcon, null).backgroundImage, "Search Field icon must be normal again"); FBTest.testDone(); }); }); }
var User = require('../models/user') , Badge = require('../models/badge') , ObjectID = require('mongoose').mongo.BSONPure.ObjectID , reverse = require('../lib/router').reverse , configuration = require('../lib/configuration') , url = require('url') exports.param = {} exports.param['groupId'] = function(req, res, next, id) { var objId, badgeIds; if (req.url.match(/.js$/)) { req.query.js = true; id = id.replace(/.js$/, ''); } try { objId = ObjectID(id) } catch(err) { return res.send('could not find group', 404) } badgeIds = [] User.findOne({'groups': {'$elemMatch' : { _id : objId }}}, function(err, doc) { if (!doc) return res.send('could not find group', 404); badgeIds = doc.groups.id(objId).badges Badge.find({'_id': {'$in' : badgeIds}}, function(err, docs) { if (!docs.length) return res.send('could not find group', 404); req.badges = docs; req.groupId = id; return next(); }) }) } exports.group = function(req, res) { if (req.query && req.query.js) { var iframeurl = url.parse(reverse('share.group', {groupId: req.groupId})) iframeurl.hostname = configuration.get('hostname'); iframeurl.protocol = configuration.get('protocol'); iframeurl.port = configuration.get('external_port'); res.setHeader('Content-Type', 'text/javascript'); return res.send('document.write("<iframe frameborder=0 src=\''+ url.format(iframeurl) +'\'></iframe>")') } res.render('share-frame', { layout: false, badges: req.badges }); } exports.badge = function(req, res) { var badge = req.badge; res.render('badge-details', { layout: 'mini-details', recipient: badge.recipient, image: badge.meta.imagePath, type: badge.badge }) }
import React, { Component } from "react"; import { Provider } from "react-redux"; import store from "./src/reducers/index"; import CounterAction from "./src/actions/CounterAction"; /** * Store - holds the state the is only one state * Action - state can be modify using actions - simple object * Dispatcher - Action needs to be sent by someone - this is the dispatcher action * Reducer - receives the action modify the state id need and return new state * - pure action * - only mandatory filed is the type * Subscriber - listen for the state change to update the ui using connect * **/ export default class App extends Component { constructor(props) { super(props); } render() { return ( <Provider store={store}> <CounterAction /> </Provider> ); } }
// To run with lodash enabled type the following command: // node -r esm arrayswork import get from "lodash/get"; const acquisitions = [ { acquiringCompany: { id: 1, companyName: "Alex", }, acquiredCompany: { id: 2, companyName: "Zalex", }, }, ]; const sortedData = acquisitions .map((i) => ({ id: i.acquiredCompany.id, acquiredCompany: get(i.acquiredCompany, "companyName", "-"), acquiringCompany: get(i.acquiringCompany, "companyName", "-"), })) .slice(); console.log(acquisitions); console.log(sortedData);
export default { 'all': true, };
'use strict' let today = new Date() let formatDate = today.toDateString() let selectElement = document.getElementById('date') selectElement.innerHTML = formatDate function firstFunction() { alert("The first function executed successfully!"); } function secondFunction() { alert("The second function executed successfully"); } // Selecting button element let btn = document.getElementById("Knap1"); // Assigning event handlers to the button btn.onclick = secondFunction; let x = document.getElementById("Knap2"); x.addEventListener("mouseover", myFunction); x.addEventListener("click", mySecondFunction); x.addEventListener("mouseout", myThirdFunction); function myFunction() { document.getElementById("demo").innerHTML += "Moused over!<br>"; } function mySecondFunction() { document.getElementById("demo").innerHTML += "Clicked!<br>"; } function myThirdFunction() { document.getElementById("demo").innerHTML += "Moused out!<br>"; }
var numberOfchildren = prompt("Enter the number of chidren"); var partnersName = prompt("Enter the parents name"); var jobTitle = prompt("Enter a job title"); var geolocation = prompt("Enter location"); console.log("You will be come a" + jobTile + "in" + geolocation + ", and married to" + partnersName + "with" + numberOfchildren+ "kids" ); // var year = prompt("enter you year of birth"); // var futureyear = prompt("Enter your future year");
 /* Dropdown jQuery Plugin 1.0 http://nasa8x.com Copyright (c) 2011 Nasa8x Dual licensed under the MIT and GPL licenses: http://www.opensource.org/licenses/mit-license.php http://www.gnu.org/licenses/gpl.html */ (function ($) { $.DropDownMenu = function (e, t, o) { this.menu = e; this.options = o; this.target = t; this.init(); }; $.DropDownMenu.prototype = { showTimeout: null, hideTimeout: null, viewport: function (e) { if (e) { return $.extend({ height: e.outerHeight(), width: e.outerWidth(), top: e.position().top, left: e.position().left }); } else { return $.extend({ height: $(window).height(), width: $(window).width(), top: $(window).scrollTop(), left: $(window).scrollLeft() }); } }, init: function () { var m = this.menu; var o = this.options; switch (o.when) { default: case 'hover': m.hover($.proxy(function (e) { this.resetTimeOut(); this.event = e; this.show(1); e.preventDefault(); }, this), $.proxy(function () { this.hide(1); }, this)); break; case 'click': m.unbind('click.dropdown').bind('click.dropdown', $.proxy(function (e) { e.preventDefault(); this.show(1); }, this)).bind('mouseout.mvcforum', $.proxy(function() { this.hide(1); }, this)); break; } this.addEvents(); }, addEvents: function () { /* $(document).bind('click.dropdown', $.proxy(function (e) { if (e.target != this.target[0]) { this.hide(); } }, this));*/ this.target.hover( $.proxy(function () { this.resetTimeOut(); }, this), $.proxy(function () { this.hide(1); }, this)); /* this.target.unbind('.dropdown').bind('mouseover.dropdown', $.proxy(function () { this.clearTimeout(); }, this)) .bind('mouseout.dropdown', $.proxy(function () { this.hide(1); }, this));*/ }, resetTimeOut: function () { if (this.showTimeout) { clearTimeout(this.showTimeout); } if (this.hideTimeout) { clearTimeout(this.hideTimeout); } }, show: function (f) { if (this.visibled) return; var o = this.options; if ((f == 1 || f == true) && o.timeout.show > 0) { this.resetTimeOut(); this.showTimeout = setTimeout($.proxy(function () { this.show(); }, this), o.timeout.show); return; } this.visibled = true; if ($.isFunction(o.onShow)) { o.onShow.apply(); } var v = this.viewport(this.menu); var m = this.target; var h = m.outerHeight(); var w = m.outerWidth(); var p = o.position; var winW = $(window).width(); if (w + v.left + o.offsetY > winW) { p = 'bottom-right'; } var t, l; switch (p) { default: case 'bottom-left': l = v.left + o.offsetY; t = v.top + v.height + o.offsetX; break; case 'bottom-right': l = v.left - w + v.width - o.offsetY; t = v.top + v.height - o.offsetX; break; } this.menu.addClass(o.activeClass); m.css({ top: t, left: l }).slideDown(o.duration.show); }, hide: function (f) { if (!this.visibled) return; var o = this.options; if ((f == 1 || f == true) && o.timeout.hide > 0) { this.resetTimeOut(); this.hideTimeout = setTimeout($.proxy(function () { this.hide(); }, this), o.timeout.hide); return; } else { this.visibled = false; this.target.slideUp(o.duration.hide, $.proxy(function () { this.menu.removeClass(o.activeClass); // close callback if ($.isFunction(o.onHide)) { o.onHide.apply(); } }, this)); } } }; $.fn.dropdown = function (options) { var defaults = { when: 'hover', //'hover', 'click' activeClass: 'selected', position: 'bottom-left', meta: 'dropdown', offsetX: 0, offsetY: 0, duration: { show: 500, hide: 500 }, timeout: { show: 0, hide: 500 }, onShow: null, onHide: null }; return this.each(function () { var e = $(this); if ($.data(e, 'dropdown')) return; $.data(e, 'dropdown', true); var o = $.extend(true, {}, defaults, options || {}); if (o.meta && $.metadata) { var md = e.metadata(); $.extend(true, o, md[o.meta] || {}); } var t = o.target ? $(o.target) : $('ul', e); new $.DropDownMenu(e, t, o); }); }; })(jQuery);
import data from './data'; const byName = Object.create(null); const byAbbr = Object.create(null); for (let i = 0, il = data.length; i < il; i++) { const item = data[i]; const {name, abbr} = item; byName[name] = item; byAbbr[abbr] = item; } export { data, byName, byAbbr, }; export default { data, byName, byAbbr, };
const KoaRouter = require('koa-router'); const { Op } = require('sequelize'); const AWS = require('aws-sdk'); const fs = require('fs'); const { sendOwnerEmail, sendGetFitEmail, sendBuyerEmail } = require('../mailers/storeMailer'); const router = new KoaRouter(); const BUCKET_NAME = process.env.BUCKET_NAME_AWS; const IAM_USER_KEY = process.env.ACCESS_KEY_ID_AWS_STORAGE; const IAM_USER_SSKEY = process.env.SECRET_ACCESS_KEY_AWS_STORAGE; async function products(ctx, next) { ctx.state.allProduct = await ctx.orm.products.findAll(); return next(); } async function loadProduct(ctx, next) { try { ctx.state.product = await ctx.orm.products.findByPk(ctx.params.id); } catch (e) { ctx.state.product = { name: 'Inexistente', id: -1 }; } return next(); } async function loadUser(ctx, next) { ctx.state.userInfo = await ctx.orm.users.findByPk(ctx.state.product.userId); return next(); } async function checkProduct(ctx, next) { console.log('inicio'); if (ctx.session.currentUser) { const productIds = []; ctx.state.currentUser.cart.forEach((id) => { productIds.push(id); }); if (productIds.length > 0) { ctx.state.availableProducts = await ctx.orm.products.findAll({ where: { id: { [Op.or]: productIds, }, }, }); } else { ctx.state.availableProducts = null; } if (ctx.state.availableProducts) { ctx.state.currentUser.cart = []; ctx.state.availableProducts.forEach((product) => { ctx.state.currentUser.cart.push(Number(product.id)); }); } ctx.session.currentUser.cart = ctx.state.currentUser.cart; } console.log('final'); return next(); } async function discardProduct(ctx, next) { const productIds = []; ctx.state.currentUser.cart.forEach((id) => { if (!(id === Number(ctx.params.id))) { productIds.push(id); } }); ctx.state.currentUser.cart = productIds; return next(); } async function calculateCart(ctx, next) { console.log('checkproduct'); if (ctx.session.currentUser) { ctx.state.priceCart = 0; ctx.state.availableProducts.forEach((product) => { ctx.state.priceCart += Number(product.precio); }); } return next(); } async function loadSaleData(ctx, next) { const productsOwners = await ctx.orm.products.findAll({ where: { id: { [Op.or]: ctx.session.currentUser.cart, }, }, include: { association: ctx.orm.products.users, as: 'owners', }, }); if (productsOwners) { if (productsOwners.length > 0) { ctx.state.saleData = productsOwners; } } return next(); } async function sendEmailSoldOwners(ctx, next) { if (ctx.state.saleData) { try { ctx.state.saleData.forEach((product) => { sendOwnerEmail(ctx, { product, user: product.user, }); }); } catch (e) { console.log(e); } } return next(); } async function sendEmailBuyer(ctx, next) { if (ctx.state.saleData) { try { const user = await ctx.orm.users.findByPk(ctx.session.currentUser.id); await sendBuyerEmail(ctx, { products: ctx.state.saleData, priceCart: ctx.state.priceCart, user, }); } catch (e) { console.log(e); } } return next(); } async function sendEmailGetFit(ctx, next) { if (ctx.state.saleData) { try { await sendGetFitEmail(ctx, { products: ctx.state.saleData, }); } catch (e) { console.log(e); } } return next(); } async function deleteProducts(ctx, next) { ctx.session.currentUser.cart = []; for (let index = 0; index < ctx.state.saleData.length; index++) { // eslint-disable-next-line no-await-in-loop await ctx.state.saleData[index].destroy(); } return next(); } async function uploadFileStore(ctx, next) { const files = ctx.request.files.foto; const myFiles = Array.isArray(files) ? files : typeof files === "object" ? [files] : null; if (myFiles) { try { const filePromises = myFiles.map((file) => { const s3 = new AWS.S3({ accessKeyId: IAM_USER_KEY, secretAccessKey: IAM_USER_SSKEY, Bucket: BUCKET_NAME, }); const { path, name, type } = file; const body = fs.createReadStream(path); const params = { Bucket: 'getfit-storage/store', Key: name, Body: body, ContentType: type, ACL: 'public-read', }; return new Promise((resolve, reject) => { s3.upload(params, (error, data) => { if (error) { reject(error); return next(); } console.log(data); resolve(data); }); }); }); const results = await Promise.all(filePromises); console.log('Results:', results); ctx.request.body.foto = results[0].Location; } catch (error) { console.error(error); ctx.state.error = error; } } return next(); } router.get('store', '/', products, async (ctx) => { if (ctx.session.currentUser) { await ctx.render('store/index', { allProducts: ctx.state.allProduct, productPath: (id) => ctx.router.url('product', id), createProductPath: ctx.router.url('createProduct'), shoppingCartPath: ctx.router.url('shoppingCart'), }); } else { ctx.redirect(ctx.router.url('index')); } }); router.get('product', '/:id/info', loadProduct, loadUser, async (ctx) => { if (ctx.session.currentUser) { const { product, userInfo } = ctx.state; await ctx.render('store/product', { product, userInfo, addCartPath: ctx.router.url('addCart', product.id), storePath: ctx.router.url('store'), }); } else { ctx.redirect(ctx.router.url('index')); } }); router.get('shoppingCart', '/cart', checkProduct, async (ctx) => { if (ctx.session.currentUser) { const { availableProducts } = ctx.state; await ctx.render('store/shoppingCart', { availableProducts, storePath: ctx.router.url('store'), discardProductCartPath: (id) => ctx.router.url('discardProductCart', id), endShopping: ctx.router.url('payProducts'), }); } else { ctx.redirect(ctx.router.url('index')); } }); router.get('payProducts', '/pay', checkProduct, calculateCart, async (ctx) => { console.log('here'); if (ctx.session.currentUser) { const { priceCart, availableProducts } = ctx.state; await ctx.render('store/submitShop', { priceCart, availableProducts, shoppingCartPath: ctx.router.url('shoppingCart'), endShopping: ctx.router.url('payingProducts'), }); } else { ctx.redirect(ctx.router.url('index')); } }); router.post('payingProducts', '/paying', checkProduct, calculateCart, loadSaleData, sendEmailSoldOwners, sendEmailBuyer, sendEmailGetFit, deleteProducts, async (ctx) => { console.log('here'); ctx.redirect(ctx.router.url('store')); }); router.get('createProduct', '/create', async (ctx) => { if (ctx.session.currentUser) { const newProduct = await ctx.orm.products.build(); await ctx.render('store/new', { newProduct, storePath: ctx.router.url('store'), createRequestPath: ctx.router.url('creatingProduct'), }); } else { ctx.redirect(ctx.router.url('index')); } }); router.post('creatingProduct', '/creating', uploadFileStore, async (ctx) => { if (!(ctx.state.error)) { const newProduct = await ctx.orm.products.build({ userId: ctx.session.currentUser.id, name: ctx.request.body.name, precio: ctx.request.body.precio, tipo: ctx.request.body.tipo, estado: ctx.request.body.estado, foto: ctx.request.body.foto, descripcion: ctx.request.body.descripcion, }); console.log('Body:', ctx.request.body); try { await newProduct.save(); ctx.redirect(ctx.router.url('store')); } catch (e) { await ctx.render('store/new', { errors: e.errors, newProduct, storePath: ctx.router.url('store'), createRequestPath: ctx.router.url('creatingProduct'), }); } } else { const newProduct = await ctx.orm.products.build({ userId: ctx.session.currentUser.id, name: ctx.request.body.name, precio: ctx.request.body.precio, tipo: ctx.request.body.tipo, estado: ctx.request.body.estado, foto: null, descripcion: ctx.request.body.descripcion, }); await ctx.render('store/new', { errors: ctx.state.error, newProduct, storePath: ctx.router.url('store'), createRequestPath: ctx.router.url('creatingProduct'), }); } }); router.post('deleteProduct', '/:id/delete', loadProduct, async (ctx) => { const { product } = ctx.state; await product.destroy(); ctx.redirect(ctx.router.url('userProfile')); }); router.post('addCart', '/:id/add/product/cart', async (ctx) => { ctx.session.currentUser.cart.push(Number(ctx.params.id)); ctx.redirect(ctx.router.url('store')); }); router.post('discardProductCart', '/:id/discard/producto', discardProduct, async (ctx) => { ctx.redirect(ctx.router.url('shoppingCart')); }); module.exports = router;
import { createApp } from 'vue' import App from './App.vue' import router from "./router"; import store from "./store" import 'assets/css/resets.css' import 'assets/css/border.css' import 'assets/js/common.js' import MyPlugin from "./components/common"; import '../vue.config.js' createApp(App).use(router).use(store).use(MyPlugin).mount('#app')
import React from 'react' import { BrowserRouter, Route, Link } from 'react-router-dom' import routeResourceDetectorHOC from '../../src' function School () { return <h2>School</h2> } function Classs () { return <h2>Class</h2> } function Student () { return <h2>Student</h2> } function Teacher () { return <h2>Teacher</h2> } const RoutesComp = () => { RoutesComp.resourceConfigurations = { 'class/:classId/teacher/:teacherId': { handler: async () => { return new Promise((resolve, reject) => { setTimeout(() => { console.log('path teacher resource') reject(new Error('teacher resource error')) }, 2000) }) } }, 'class/:classId': { handler: async () => { return new Promise((resolve, reject) => { setTimeout(() => { console.log('path class resource') resolve() }, 1000) }) } }, 'class/(\\w)+': { handler: () => { console.log('regexp class resource') } }, 'class/:classId/student/:studentId': { handler: () => { console.log('path student resource') } } } RoutesComp.routeConfigurations = { '/school/class/:classId/student/:studentId': { handler: () => { console.log('student route') }, deselect: () => { console.log('deselect student route') }, blackList: ['class/:classId'] }, '/school/class/:classId/teacher/:teacherId': { handler: () => { console.log('teacher route') }, deselect: () => { console.log('deselect teacher route') } } } // Teacher: 开启 detectResourceInSequence 后,某个resource报错后,不会继续往下执行 return ( <React.Fragment> <Link to='/school'>School</Link><br/> <Link to='/school/class/1'>Class 1</Link><br/> <Link to='/school/class/1/student/1'>Class 1 Student 1</Link><br/> <Link to='/school/class/1/teacher/1'>Class 1 Teacher 1</Link><br/> <Route exact path='/school' component={School} /> <Route exact path='/school/class/1' component={Classs} /> <Route exact path='/school/class/1/student/1' component={Student} /> <Route exact path='/school/class/1/teacher/1' component={Teacher} /> </React.Fragment> ) } class App extends React.PureComponent { render () { const Detector = routeResourceDetectorHOC(RoutesComp, { detectResourceInSequence: true, deselectResources: true }) return ( <BrowserRouter> <Detector /> </BrowserRouter> ) } } export default App
import React, { Component } from 'react'; import styled from 'styled-components'; import { FormattedMessage, intlShape, injectIntl } from 'react-intl'; import NavLinkStyled from '../../components/NavLinkStyled'; import { PAGE_URLS } from '../../constants/constants'; import Lang from '../../components/Lang'; const HeaderWrapper = styled.header` background-color: ${props => props.theme.colorDark}; color: ${props => props.theme.colorMain}; padding: 20px; position: relative; text-align: left; `; const H1 = styled.h1` border: 1px solid ${props => props.theme.colorMain}; color: ${props => props.theme.colorHeader}; font-size: 2rem; padding: 20px; text-align: center; word-break: break-word; `; const Nav = styled.nav` border: 1px solid ${props => props.theme.colorMain}; margin-top:20px; `; class Header extends Component { render() { const intl = this.props.intl; const homeValue = intl.formatMessage({id: "PAGE_HOME_VALUE"}); const homeTitle = intl.formatMessage({id: "PAGE_HOME_TITLE"}); const roomsValue = intl.formatMessage({id: "PAGE_ROOMS_VALUE"}); const roomsTitle = intl.formatMessage({id: "PAGE_ROOMS_TITLE"}); return ( <HeaderWrapper> {/* <Lang /> */} <H1> <FormattedMessage id="HEADER_CAPTION" /> </H1> <Nav> <NavLinkStyled to={PAGE_URLS.home} value={homeValue} title={homeTitle} /> <NavLinkStyled to={PAGE_URLS.rooms} value={roomsValue} title={roomsTitle} /> </Nav> </HeaderWrapper> ); } } Header.propTypes = { intl: intlShape.isRequired }; export default injectIntl(Header);
import React from "react"; import {Button, Card, Icon} from "antd"; const ButtonGroup = Button.Group; const ButtonGroups = () => { return ( <Card className="gx-card" title="Button Groups"> <h4>Basic</h4> <ButtonGroup> <Button>Cancel</Button> <Button>OK</Button> </ButtonGroup> <ButtonGroup> <Button disabled>L</Button> <Button disabled>M</Button> <Button disabled>R</Button> </ButtonGroup> <ButtonGroup> <Button>L</Button> <Button>M</Button> <Button>R</Button> </ButtonGroup> <h4>With Icon</h4> <ButtonGroup> <Button type="primary"> <Icon type="left"/>Go back </Button> <Button type="primary"> Go forward<Icon type="right"/> </Button> </ButtonGroup> <ButtonGroup> <Button type="primary" icon="cloud"/> <Button type="primary" icon="cloud-download"/> </ButtonGroup> </Card> ); }; export default ButtonGroups;
import React from 'react'; import {Link} from 'react-router'; export default class About extends React.Component { render() { return ( <div id="about" className="aboutUs"> <div className = "container"> <h2><b>About us</b></h2> <hr /> <p>We are San Francisco, California based team who loves to travel and believe that the best adventures are those shared with family andn friends.</p> </div> </div> ) } }
module.exports = { "extends": "google", "rules": { "no-unused-expressions": [ 2, { allowShortCircuit: true, allowTernary: true } ], "space-before-function-paren": [2, "always"] } };
const mongoose = require("mongoose"); const freqSchema = new mongoose.Schema({ name: { type: String, }, freq: { type: mongoose.Decimal128, } }) const Stations = mongoose.model("Stations", freqSchema) module.exports = Stations
define(['jquery', 'underscore', 'backbone', 'text!template/contacts.html' ], function($, _, Backbone,commentTemp){ var CommentList = Backbone.View.extend({ tagName: 'li', templ: _.template(commentTemp), initialize: function() { _.bindAll(this, 'render'); this.model.bind('change', this.render); this.model.view = this; }, render: function(){ $(this.el).html(this.template(this.model.toJSON())); this.setContent(); return this; }, setContent:function(){ var content = this.model.get('message'); this.$('.post').text(content); } }); console.log('CommentList',CommentList.prototype); return CommentList; } );
import React,{Component} from 'react'; import swal from 'sweetalert'; export default class Success extends Component { componentDidMount() { swal("Thank you for choosing us,we will call you to confirm shortly!","ETA:30 Minutes","success"); swal({ title: "Get ready to dig in!", text: "Order placed successfully!", icon: "success", }) .then((willDelete) => { if (willDelete) { swal("Thank you for choosing us,we will call you to confirm shortly!", { icon: "success", }); } else { swal("Thank you for choosing us,we will call you to confirm shortly!!"," ","http://classroomclipart.com/images/gallery/Animations/phone.gif"); } }); } render() { return(<div style={{}}> cdmkl </div>); } }
/*事件绑定 * obj 要绑定的事件源 * event 要绑定的事件 * fn 要处理的事件处理程序 * */ function addEvent(obj, event, fn) { if (obj.addEventListener) { obj.addEventListener(event, fn, false) } else { obj.attachEvent("on" + event, fn); } } /*解除事件绑定 * obj 要解除绑定的事件源 * event 要解除绑定的事件 * fn 要解除绑定的事件处理程序 * */ function removeEvent(obj, event, fn) { if (obj.removeEventListener) { obj.removeEventListener(event, fn, false) } else { obj.detachEvent("on" + event, fn); } } /*获取对象的样式的属性值*/ function getStyle(obj, attr) { if (window.getComputedStyle) { return getComputedStyle(obj, null)[attr]; } else { return obj.currentStyle[attr]; } } /*获得相对于body左上角的位置 * * obj 要获取的对象 * */ function offset(obj) { var arr = [obj]; var parent = obj.parentNode; var result = {left: 0, top: 0}; while (parent.nodeName !== "BODY") { var val = getStyle(parent, "position"); if (val == "absolute" || val == "relative" || val == "fixed") { arr.push(parent); } parent = parent.parentNode; } for (var i = 0; i < arr.length; i++) { var borderL = 0, borderT = 0; if (i > 0) { borderL = parseInt(getStyle(arr[i], "borderLeftWidth")) || 0; borderT = parseInt(getStyle(arr[i], "borderTopWidth")) || 0; } result.left += borderL + arr[i].offsetLeft; result.top += borderT + arr[i].offsetTop; } return result; } /*工厂模式 * obj 要拖拽的对象 * options 拖拽的选项 * * */ function drag(obj, options, callback) { //创建工厂 return new drags(obj, options, callback); //实例化对象 } function drags(obj, options,callback) { //构造函数 this.obj = obj; var options=options==undefined?{} :options; //初始化事件源 this.callback=callback?callback:null; this.dragx = options.dragx == undefined ? true : options.dragx; //初始化拖拽方向(x) this.dragy = options.dragy == undefined ? true : options.dragy; //初始化拖拽方向(y) this.sidex = options.sidex == undefined ? false : options.sidex; //初始化范围(x) this.sidey = options.sidey == undefined ? false : options.sidey; //初始化范围(y) this.animate = options.animate == undefined ? true : options.animate; //初始化动画效果 this.speed = 0.7; //设置速度因子 this.start(); //调用开始方法 } drags.prototype = { //原型方法 start: function () { //开始方法 this.mousedown(); //调用鼠标按下方法 }, stop:function(e){ if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue=false; } }, mousedown: function () { //构造鼠标按下方法 var that = this; //保存指向 this.obj.onmousedown = function (e) { //鼠标按下方法 var ev = that.getEv(e); //鼠标事件对象 that.ox = that.getOx(ev); //获取鼠标到事件源的位置(x) that.oy = that.getOy(ev); //获取鼠标到事件源的位置(y) that.startx = that.ox; //获取开始位置(x) that.starty = that.oy; //获取开始位置(y) that.mousemove(); //调用鼠标移动方法 that.mouseup(); //调用鼠标抬起方法 that.stop(ev); } }, mousemove: function () { //构造鼠标移动方法 var that = this; //保存this指针 document.onmousemove = function (e) { //鼠标移动方法(设置在document上:调节问题) var ev = that.getEv(e); //获取鼠标移动事件 that.cx = ev.clientX; //获取鼠标到浏览器窗口的位置(x) that.cy = ev.clientY; //获取鼠标到浏览器窗口的位置(y) that.endx = that.cx; //获取当前结束位置(x) that.endy = that.cy; //获取当前结束位置(y) var lefts = that.cx - (offset(that.obj).left - that.obj.offsetLeft) - that.ox; //获取事件源横向移动位置 var tops = that.cy - (offset(that.obj).top - that.obj.offsetTop) - that.oy; //获取事件源纵向移动位置 if (that.sidex) { //判断是否设置了x方向的区间 if (lefts < that.sidex[0]) { //如果lefts值小于指定的区间 lefts = that.sidex[0]//让lefts始终等于最小值 } if (lefts > that.sidex[1]) {//如果lefts值大于指定的区间 lefts = that.sidex[1]//让lefts始终等于最大值 } } if (that.sidey) {//和以上判断x方向区间同理 if (tops < that.sidey[0]) { tops = that.sidey[0] } if (tops > that.sidey[1]) { tops = that.sidey[1] } } if (that.dragx) {//判断是否让事件源在x方向拖拽 that.obj.style.left = lefts + "px"; } if (that.dragy) {//判断是否让事件源在y方向拖拽 that.obj.style.top = tops + "px"; } that.left=lefts; that.top=tops; if(that.callback){ that.callback(that.left,that.top); } that.chax = that.endx - that.startx;//计算出当前鼠标移动速度的快慢(通过前后两个点得差值计算) that.chay = that.endy - that.starty;//计算出当前鼠标移动速度的快慢(通过前后两个点得差值计算) that.startx = that.endx;//让前后点调换位置 that.starty = that.endy; that.stop(ev); } }, mouseup: function () { //鼠标抬起的方法 var that = this; //用that保存this的指针 document.onmouseup = function () {//注册document的鼠标抬起的方法 document.onmousemove = null;//当鼠标抬起时注销鼠标移动事件 document.onmouseup = null;//当鼠标抬起时注销本身事件 if (!that.animate) {//判断当鼠标抬起时是否执行动画 return; } that.animation();//如果 animate属性值为真,那么开始运行动画 } }, animation: function () { //动画的方法 var that = this;//用that保存this的指针 var t = setInterval(function () {//用定时器开启动画 if (Math.abs(that.chax) > Math.abs(that.chay)) {//如果x方向的动画后运行完,要依照x的值来停止动画 if (Math.abs(that.chax) < 1) { clearInterval(t); } } else {//如果y方向的动画后运行完,要依照x的值来停止动画 if (Math.abs(that.chay) < 1) { clearInterval(t); } } //让x的差值 不断的乘以 速度因子 that.chax *= that.speed; //让y的差值 不断的乘以 速度因子 that.chay *= that.speed; //让事件源当前的位置+差值的速度=当前事件源应该在的位置 var lefts = that.obj.offsetLeft + that.chax; var tops = that.obj.offsetTop + that.chay; /*以下的代码和mousemove里面的代码同理,都是对参数的判断*/ if (that.sidex) { if (lefts < that.sidex[0]) { lefts = that.sidex[0] } if (lefts > that.sidex[1]) { lefts = that.sidex[1] } } if (that.sidey) { if (tops < that.sidey[0]) { tops = that.sidey[0] } if (tops > that.sidey[1]) { tops = that.sidey[1] } } if (that.dragx) { that.obj.style.left = lefts + "px"; } if (that.dragy) { that.obj.style.top = tops + "px"; } }, 50) }, getEv: function (e) {//解决事件对象兼容性的问题 return e || window.event; }, getOx: function (e) {//解决获取相对于事件源位置兼容性的问题 return e.layerX || e.offsetX || 0; }, getOy: function (e) {//解决获取相对于事件源位置兼容性的问题 return e.layerY || e.offsetY || 0; } }
;(function(angular) { var myApp = angular.module('myAngularModule', []) .controller('MyAngularModuleController', function($scope) { // Empty controllers should work $scope.domain = 'backpacks'; $scope.backpacks = [ { "brand": "Jansport", "model": "the normal" }, { "brand": "boreas", "model": "Bolinas", "category": "Super Tramp", "colors": [ "Eclipse Black", "Marina Blue", "Monterey Grey", "Truckee Green" ] } ]; }) .directive('staticText', function() { return { restrict: "AEC", templateUrl: "static.html", transclude: true } }); console.log('myApp: ', myApp); })(window.angular);
'use strict'; const http = require('http'); var assert = require('assert'); const express= require('express'); const app = express(); const mustache = require('mustache'); const filesystem = require('fs'); const url = require('url'); const port = Number(process.argv[2]); const hbase = require('hbase') // host:'localhost', port:8070 var hclient = hbase({ host: process.argv[3], port: Number(process.argv[4])}) // function rowToMap(row) { // var stats = {} // row.forEach(function (item) { // stats[item['column']] = Number(item['$']) // }); // return stats; // } // hclient.table('yson_street_by_seg').row('W Washington950').get((error, value) => { // console.info(rowToMap(value)) // console.info(value) // }) // // hclient.table('spertus_carriers').scan({ maxVersions: 1}, (err,rows) => { // console.info(rows) // }) // // hclient.table('spertus_ontime_by_year').scan({ // filter: {type : "PrefixFilter", // value: "AA"}, // maxVersions: 1}, // (err, value) => { // console.info(value) // }) app.use(express.static('public')); app.get('/traffic.html', function (req, res) { hclient.table('yson_streets').scan({ maxVersions: 1}, (err,rows) => { var template = filesystem.readFileSync("submit.mustache").toString(); var html = mustache.render(template, { streets : rows }); res.send(html) }) }); function removePrefix(text, prefix) { return text.substr(prefix.length) } function byteToInt(x){ let val=0; for (let i=0; i<x.length; ++i) { val+=x[i]; if(i<x.length-1) val = val << 8; } return val; } function counterToNumber(c) { return Number(Buffer.from(c).readInt32BE()); } app.get('/street-results.html',function (req, res) { const street = req.query['street']; console.log(street); // print street name function processSegmentIdRecord(segmentIdRecord) { var result = { segment_id : segmentIdRecord['segment_id']}; ["from_street", "to_street", "traffic_direction", "speed_month", "speed_week", "speed_day", "speed_hour", "speed_now"].forEach(val => { if (val == "speed_now") { if (counterToNumber(segmentIdRecord[val]) != 0) { result[val] = counterToNumber(segmentIdRecord[val]); } else { result[val] = "-" } } else { result[val] = segmentIdRecord[val]; } }) return result; } function SpeedInfo(cells) { var result = []; var segmentIdRecord; cells.forEach(function(cell) { var segment_id = Number(removePrefix(cell['key'], street)) if(segmentIdRecord === undefined) { segmentIdRecord = { segment_id: segment_id } } else if (segmentIdRecord['segment_id'] != segment_id ) { result.push(processSegmentIdRecord(segmentIdRecord)) segmentIdRecord = { segment_id: segment_id } } segmentIdRecord[removePrefix(cell['column'],'stats:')] = cell['$'] }) result.push(processSegmentIdRecord(segmentIdRecord)) return result; } function processRedlightSpeedRecord(streetRecord) { var result = { street : streetRecord['street_name']}; ["redlight_year", "redlight_months", "speed_year", "speed_months"].forEach(val => { if (streetRecord[val] === undefined) { result[val] = "-" } else { result[val] = streetRecord[val]; } }) return result; } function RedlightSpeedInfo(cells) { var result = []; var streetRecord; // console.log(streetRecord) cells.forEach(function(cell) { var street_name = cell['key'] if(streetRecord === undefined) { streetRecord = { street_name: street_name } // console.log(streetRecord) } else if (streetRecord['street_name'] != street_name ) { result.push(processRedlightSpeedRecord(streetRecord)) streetRecord = {street_name: street_name} } streetRecord[removePrefix(cell['column'],'stats:')] = cell['$'] }) result.push(processRedlightSpeedRecord(streetRecord)) return result; } function processCrashRecord(crashIdRecord) { var result = { crash_record_id : crashIdRecord['crash_record_id']}; ["crash_date", "street", "address", "first_crash_type", "crash_type", "prim_cause", "damage"].forEach(val => { result[val] = crashIdRecord[val]; }) return result; } function CrashInfo(cells) { var result = []; var crashIdRecord cells.forEach(function(cell) { var crash_record_id = removePrefix(cell['key'], street) // console.log(crash_record_id) if(crashIdRecord === undefined) { crashIdRecord = { crash_record_id: crash_record_id } } else if (crashIdRecord['crash_record_id'] != crash_record_id) { result.push(processCrashRecord(crashIdRecord)) crashIdRecord = { crash_record_id: crash_record_id } } crashIdRecord[removePrefix(cell['column'],'stats:')] = cell['$'] }) result.push(processCrashRecord(crashIdRecord)) return result; } hclient.table('yson_street_by_seg').scan({ filter: {type : "PrefixFilter", value: street}, maxVersions: 1}, (err, cells) => { var si = SpeedInfo(cells); // console.log(si); hclient.table('yson_redlight_speed').scan({ filter: {type : "PrefixFilter", value: street}, maxVersions: 12}, (err, cells) => { if (cells.length > 0) { var rsi = RedlightSpeedInfo(cells); } else { var rsi = undefined; } console.log(rsi); hclient.table('yson_crashes_month').scan({ filter: {type : "PrefixFilter", value: street}, maxVersions: 1}, (err, cells) => { if (cells.length > 0) { var ci = CrashInfo(cells); } else { var ci = undefined; } // var ci = CrashInfo(cells); // console.log(ci); var template = filesystem.readFileSync("result-table.mustache").toString(); var html = mustache.render(template, { SpeedInfo: si, street: street, RedlightSpeedInfo: rsi, CrashInfo: ci }); res.send(html) }) }) }) }); app.listen(port);
import { Item, ColorContainer, Container } from './CardItem.style'; const CardItem = ({ product }) => { const { amount, price, color } = product; return ( <Item> <Container> <ColorContainer color={color} /> <div>* {amount}</div> </Container> <div>{price}$</div> </Item> ); }; export default CardItem;
// createCoupon(couponInput:CouponInput!):Coupon! // editCoupon(couponInput:CouponInput!):Coupon! // deleteCoupon(id:String!):String! const Coupon = require('../../models/coupon') module.exports = { Query: { coupons: async(_, args, context) => { console.log('coupons') try { const coupons = await Coupon.find({ isActive: true }).sort({ createdAt: -1 }) return coupons.map(coupon => ({ ...coupon._doc, _id: coupon.id })) } catch (err) { console.log(err) throw err } } }, Mutation: { coupon: async(_, args, context) => { console.log('coupon') try { const coupon = await Coupon.findOne({ isActive: true, code: args.coupon }) if (coupon) { return { ...coupon._doc, _id: coupon.id } } else { throw new Error('Coupon code not found') } } catch (err) { console.log(err) throw err } }, createCoupon: async(_, args, context) => { console.log('createCoupon') try { const count = await Coupon.countDocuments({ code: args.couponInput.code, isActive: true }) if (count > 0) throw new Error('Coupon Code already exists') const coupon = new Coupon({ code: args.couponInput.code, discount: args.couponInput.discount, enabled: args.couponInput.enabled }) const result = await coupon.save() return { ...result._doc, _id: result.id } } catch (err) { console.log(err) throw err } }, editCoupon: async(_, args, context) => { console.log('editCoupon') try { const count = await Coupon.countDocuments({ _id: args.couponInput._id }) if (count > 1) throw new Error('Coupon code already used') const coupon = await Coupon.findById(args.couponInput._id) if (!coupon) { throw new Error('Coupon does not exist') } coupon.code = args.couponInput.code coupon.discount = args.couponInput.discount coupon.enabled = args.couponInput.enabled const result = await coupon.save() return { ...result._doc, _id: result.id } } catch (err) { console.log(err) throw err } }, deleteCoupon: async(_, args, context) => { console.log('deleteCoupon') try { const coupon = await Coupon.findById(args.id) coupon.isActive = false const result = await coupon.save() return result.id } catch (err) { console.log(err) throw err } } } }
/** * Created by hehua on 2016/4/7. */
module.exports = { extends: ["stylelint-config-standard"], rules: { "at-rule-no-unknown": [ true, { ignoreAtRules: ["mixin", "extend", "content", "include"] }, ], indentation: 4, "no-descending-specificity": null, // 禁止特异性较低的选择器在特异性较高的选择器之后重写 }, };
importScripts("https://www.gstatic.com/firebasejs/5.0.3/firebase-app.js"); importScripts("https://www.gstatic.com/firebasejs/5.0.3/firebase-messaging.js"); var config = { apiKey: "AIzaSyBZUz6V1Mkmwxpe781P8X6ZC7fPTUyiBIg", authDomain: "it-love1.firebaseapp.com", databaseURL: "https://it-love1.firebaseio.com", projectId: "it-love1", storageBucket: "it-love1.appspot.com", messagingSenderId: "782043275132" }; firebase.initializeApp(config); const messaging = firebase.messaging();
var x=100, y=150; function pos(dx,dy) { if(!document.getElementById) return; x += 30*dx; y += 30*dy; obj = document.getElementById("kotak"); obj.style.top = y + "px"; obj.style.left = x + "px"; } function getNama() { document.write("<b><i>Jarvis Andriano</i></b>"); } function showHide() { var x = document.getElementById("kotak"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }
import api from "./api"; /** * @param {String} endpoint relative endpoint * @param {object} body request body * @param {String} method method can be ["GET","POST","PUT", "DELETE"] | Default GET * @param {boolean} transformBody whether to transform the request body from JSON to FormData | Default false */ export async function queryApi(endpoint,body = null,method = "GET",transformBody = false) { let error = null; let result = null; try { //Create our config, with the method as the method passed and the new endpoint let config = { method, url: `${process.env.REACT_APP_API_URL}/${endpoint}`, }; if (body) { // If we have a body and the method is GET, the config is the following if (method.toUpperCase() === "GET") config = { ...config, headers: { "Content-Type":"appliation/json", Authorization: `Bearer ${localStorage.getItem("authToken")}`}, data: body, }; if (["POST", "PUT","OPTIONS", "PATCH"].includes(method.toUpperCase())) { if (transformBody) { // If our method is POST, PUT or PATCH, and we have to transform our body to Form Data (for files upload for example) // transform body object to form data entries let bodyFormData = new FormData(); for (let [key, value] of Object.entries(body)) { if (value) { if (Array.isArray(value)) value.forEach((v) => bodyFormData.append(key, v)); else bodyFormData.append(key, value); } } // Change the config to the following config = { ...config, headers: { Authorization: `Bearer ${localStorage.getItem("authToken")}` , "Content-Type": "multipart/form-data" }, data: bodyFormData, }; } else { // If not keep the content type json and the body will be parsed automatically to json config = { ...config, headers: {Authorization: `Bearer ${localStorage.getItem("authToken")}` , "Content-Type": "application/json" }, data: body, }; } } } else { if (method.toUpperCase() === "GET") config = { ...config, headers: { "Content-Type":"appliation/json", Authorization: `Bearer ${localStorage.getItem("authToken")}`} }; } // Setting authorization token if available with each request // This example uses localStorage, feel free to change it to cookie storage or something else. // const token = localStorage.getItem("token"); // if (token) // config.headers = { ...config.headers, Authorization: `Bearer ${token}` }; // console.log(`Requesting : ${config.url}`) // console.log(config) const res = await api(config); result = res.data; } catch (e) { // To differentiate between validation errors and response errors, // check whether the "errors" key is defined or not in the returned error from this function. if (e.response) { // The request was made and the server responded with a status code that falls out of the range of 2xx error = e.response.data; // console.log(e.message); // console.log(error); } else { // 1) The request was made but no response was received // OR // 2) Something went wrong in setting up the request that triggered an Error // console.log(e.request); // console.log(e.message); error = e.message; } } return [result, error]; }
'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller } = app; const webhdfsRouter = router.namespace('/webhdfs'); webhdfsRouter.post('/download', controller.webhdfs.download); webhdfsRouter.get('/downloadFromHdfs', controller.webhdfs.downloadFromHdfs); webhdfsRouter.get('/downloadFromNode', controller.webhdfs.downloadFromNode); webhdfsRouter.get('/getJson', controller.webhdfs.getJson); webhdfsRouter.post('/upload', controller.webhdfs.upload); };
import React from 'react' import PropTypes from 'prop-types' import ShopItem from './ShopItem' function ListView({items}) { return ( <div className="flex-container items"> { items.map((item, i) => <ShopItem item={item} key={i}/>) } </div> ) } ListView.propTypes = { items: PropTypes.array.isRequired } export default ListView
Images = new orion.collection('images', { pluralName: 'imagenes', singularName: 'imagen', title: 'Imagenes', link: { title: 'Imagenes', }, tabular: { columns: [ { data: 'index', title: 'Lugar' }, { data: 'description', title: 'Descripción' }, orion.attributeColumn('image', 'image', 'Imagen'), orion.attributeColumn('hasOne', 'categoryId', 'Categoría'), ], }, }); Images.attachSchema(new SimpleSchema({ index: { type: Number, label: 'Lugar', }, description: { type: String, label: 'Descripción', }, image: orion.attribute('image', { label: 'Imagen', }), thumb: orion.attribute('image', { label: 'Fotito Chiquitita', }), categoryId: orion.attribute('hasOne', { label: 'Categoría', }, { collection: Categories, titleField: 'name', publicationName: 'images_categoryId_schema', }), createdAt: orion.attribute('createdAt'), }));
$(document).ready(function(){ // delete plant modal function $("#delete-modal").on("show.bs.modal", function(event){ //Get the button that triggered the modal var button = $(event.relatedTarget); // Extract value from the custom data-* attribute to link the plant_id var url = button.data("url"); $(this).find('#confirm-delete').attr('href', url); }); // checkbox validation function $( '.checkbox-validation' ).on('submit', function(e) { // checks if any inputs for suitable_for are checked if($('input[name="suitable_for"]:checked').length === 0) { // prevents the submiting of the form e.preventDefault(); // adds an * to label so users know it is required $('.suitable-for').text("Suitable For *"); } }); });
import styled from 'styled-components'; const Titulo = styled.h1` grid-column: 1 / -1; color: #39b2d6; `; export default Titulo;
const config = require('../../config.json') const sqlCmds = require('../sql/commands.js') const moment = require('moment-timezone') const defaultConfigs = require('../../util/configCheck.js').defaultConfigs function getArticleId (articleList, article) { let equalGuids = (articleList.length > 1) // default to true for most feeds if (equalGuids && articleList[0].guid) { for (var x in articleList) { if (parseInt(x, 10) > 0 && articleList[x].guid !== articleList[x - 1].guid) equalGuids = false } } if ((!article.guid || equalGuids) && article.title) return article.title if ((!article.guid || equalGuids) && !article.title && article.pubdate && article.pubdate.toString() !== 'Invalid Date') return article.pubdate return article.guid } module.exports = function (con, rssList, articleList, debugFeeds, link, callback) { let sourcesCompleted = 0 function processSource (rssName) { const channelId = rssList[rssName].channel let processedArticles = 0 let totalArticles = 0 checkTableExists() function checkTableExists () { sqlCmds.selectTable(con, rssName, function (err, results) { if (err) { return callback(new Error(`Unable to select table ${rssName}, skipping source.\n`, err), {status: 'success', link: link}) } else if (results.length === 0) { // When no error, but the table does not exist and was not a feed that was deleted during this cycle return callback(new Error(`Unable to select table ${rssName}, may be a deleted source. Skipping.`), {status: 'success', link: link}) } if (debugFeeds.includes(rssName)) console.log(`DEBUG ${rssName}: Table has been selected. Size of articleList: ${articleList.length}`) const feedLength = articleList.length - 1 const cycleMaxAge = config.feedSettings.cycleMaxAge && !isNaN(parseInt(config.feedSettings.cycleMaxAge, 10)) ? parseInt(config.feedSettings.cycleMaxAge, 10) : 1 for (var x = feedLength; x >= 0; x--) { // if (debugFeeds.includes(rssName)) console.log(`DEBUG ${rssName}: Checking table for (ID: ${getArticleId(articleList, articleList[x])}, TITLE: ${articleList[x].title})`) if (articleList[x].pubdate && articleList[x].pubdate > moment().subtract(cycleMaxAge, 'days')) checkTable(articleList[x], getArticleId(articleList, articleList[x])) else { // Invalid dates are pubdate.toString() === 'Invalid Date' let checkDate = false const globalSetting = config.feedSettings.checkDates != null ? config.feedSettings.checkDates : defaultConfigs.feedSettings.checkDates.default checkDate = globalSetting const specificSetting = rssList[rssName].checkDates checkDate = typeof specificSetting !== 'boolean' ? checkDate : specificSetting if (checkDate) checkTable(articleList[x], getArticleId(articleList, articleList[x]), true) // Mark as old if date checking is enabled else checkTable(articleList[x], getArticleId(articleList, articleList[x])) // Otherwise mark as new } totalArticles++ } }) } function checkTable (article, articleId, isOldArticle) { sqlCmds.selectId(con, rssName, articleId, function (err, idMatches, fields) { if (err) { callback(new Error(`Database Error: Unable to select ID ${articleId} in table ${rssName} (${err})`)) return incrementProgress() } if (idMatches.length > 0) { // if (debugFeeds.includes(rssName)) console.log(`DEBUG ${rssName}: Matched ID in table for (ID: ${articleId}, TITLE: ${article.title}).`) return seenArticle(true) } let check = false const globalSetting = config.feedSettings.checkTitles != null ? config.feedSettings.checkTitles : defaultConfigs.feedSettings.checkTitles.default check = globalSetting const specificSetting = rssList[rssName].checkTitles check = typeof specificSetting !== 'boolean' ? check : specificSetting if (!check) return seenArticle(false) sqlCmds.selectTitle(con, rssName, article.title, function (err, titleMatches) { if (err) { callback(new Error(`Database Error: Unable to select title ${articleId} in table ${rssName} (${err})`)) return incrementProgress() } if (titleMatches.length > 0) { if (debugFeeds.includes(rssName)) console.log(`DEBUG ${rssName}: Matched TITLE in table for (ID: ${articleId}, TITLE: ${article.title}).`) return seenArticle(false, true) // Still mark as unseen because its articleId was different, and thus needs to be inserted to table } seenArticle(false) }) }) function seenArticle (seen, doNotSend) { if (seen) return incrementProgress() if (debugFeeds.includes(rssName)) { if (!isOldArticle) console.log(`DEBUG ${rssName}: Never seen article (ID: ${articleId}, TITLE: ${article.title}), sending now`) else console.log(`DEBUG ${rssName}: Never seen article, but declared old - not sending (ID: ${articleId}, TITLE: ${article.title})`) } article.rssName = rssName article.discordChannelId = channelId if (!isOldArticle && !doNotSend) callback(null, {status: 'article', article: article}) insertIntoTable({ id: articleId, title: article.title }) } } function insertIntoTable (articleInfo) { sqlCmds.insert(con, rssName, articleInfo, function (err, res) { // inserting the feed into the table marks it as "seen" if (err) { callback(new Error(`Database Error: Unable to insert ${articleInfo.id} in table ${rssName} (${err})`)) return incrementProgress() } if (debugFeeds.includes(rssName)) console.log(`DEBUG ${rssName}: Article (ID: ${articleInfo.id}, TITLE: ${articleInfo.title}) should have been sent, and now added into table`) incrementProgress() }) } function incrementProgress () { processedArticles++ if (processedArticles === totalArticles) return finishSource() } } for (var rssName in rssList) processSource(rssName) // Per source in one link function finishSource () { sourcesCompleted++ if (sourcesCompleted === rssList.size()) return callback(null, {status: 'success', link: link}) } }
const { query } = require('../config') const instruments = [ "", 'piano', 'guitar', 'violin', 'cello', 'ukulele', 'flute', 'saxophone', 'bass guitar', 'viola', 'voice', 'trumpet', 'drums', 'bassoon', 'trombone', 'upright bass', 'music theory', 'composition', 'french horn' ] const bookingALesson = ({ teacher_profile_id, lessonType, instrument, level, price, description, student_profile_id }) => { return new Promise((resolve, reject) => { query( `INSERT INTO public.booking(teacher_profile_id, lesson_type, instrument_id, level, price_id, description, student_profile_id, approve) VALUES($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *`, [teacher_profile_id, lessonType, instrument, level, price, description, student_profile_id, false], (error, results) => { if (error) { reject(error) } else { resolve(results.rows[0]) } } ) }) } const getTeacherPendingBooking = ({ teacher_profile_id }) => { return new Promise((resolve, reject) => { query( `SELECT b.*, p.first_name, p.last_name, p.phone_number, p.avatar, pr.duration FROM public.booking AS b INNER JOIN public.profile AS p ON b.student_profile_id = p.id INNER JOIN public.pricing AS pr ON pr.id = b.price_id WHERE teacher_profile_id = $1 and approve = $2 `, [teacher_profile_id, false], (error, results) => { if (error) { reject(error) } else { const responseData = results.rows.map(booking => { return { id: booking.id, teacher_profile_id: booking.teacher_profile_id, student_profile_id: booking.student_profile_id, instrument_id: booking.instrument_id, instrument: instruments[booking.instrument_id], level: booking.level, approve: false, duration: booking.duration, student: { first_name: booking.first_name, last_name: booking.last_name, avatar: booking.avatar, age: 18, phone: booking.phone_number || "0905030698" } } }) resolve(responseData) } } ) }) } const getBookingInformation = (id, teacher_profile_id) => { return new Promise((resolve, reject) => { query( `SELECT * FROM public.booking WHERE id = $1 and teacher_profile_id = $2`, [id, teacher_profile_id], (error, results) => { if (error) { reject(error) } else { resolve(results.rows[0]) } } ) }) } const approveBooking = (id) => { return new Promise((resolve, reject) => { query( `UPDATE public.booking set approve = $1 WHERE id = $2 RETURNING *`, [true, id], (error, results) => { if (error) { reject(error) } else { resolve(results.rows[0]) } } ) }) } const getListStudentFromBooking = ({ booking_ids }) => { return new Promise((resolve, reject) => { query( `SELECT p.* FROM public.booking as b INNER JOIN profile as p ON b.student_profile_id = p.id WHERE b.id = ANY ($1)`, [booking_ids], (error, results) => { if (error) { reject(error) } else { resolve(results.rows) } } ) }) } const getListTeacherForStudentFromBooking = (student_profile_id) => { return new Promise((resolve, reject) => { query( `SELECT p.*, ARRAY_AGG(s.instrument_id) as instrument_ids, ARRAY_AGG(s.level) as levels FROM public.booking as b INNER JOIN profile as p ON b.teacher_profile_id = p.id INNER JOIN skill as s ON s.profile_id = b.teacher_profile_id WHERE b.student_profile_id = $1 AND b.approve = $2 GROUP BY p.id`, [student_profile_id, true], (error, results) => { if (error) { reject(error) } else { const responseData = results.rows.map(item => { const skills = item.instrument_ids.map((id, index) => { return { level: item.levels[index], instrument: instruments[id] } }) return { avatar: item.avatar, city: item.city, first_name: item.first_name, id: item.id, last_name: item.last_name, phone: item.phone_number, skills: skills } }) resolve(responseData) } } ) }) } const getListActiveBookingForTeacher = (teacher_profile_id) => { return new Promise((resolve, reject) => { query( `SELECT * FROM public.booking WHERE teacher_profile_id = $1 and approve = $2`, [teacher_profile_id, true], (error, results) => { if (error) { reject(error) } else { resolve(results.rows) } } ) }) } const getListActiveBookingForStudent = (student_profile_id) => { return new Promise((resolve, reject) => { query( `SELECT * FROM public.booking WHERE student_profile_id = $1 and approve = $2`, [student_profile_id, true], (error, results) => { if (error) { reject(error) } else { resolve(results.rows) } } ) }) } const getSetupBooking = (lesson_id) => { return new Promise((resolve, reject) => { query( `SELECT b.*, p.first_name, p.last_name, p.avatar, p.phone_number, p.id FROM public.lesson as l INNER JOIN public.booking as b ON l.booking_id = b.id INNER JOIN public.profile as p ON b.student_profile_id = p.id WHERE l.id = $1`, [lesson_id], (error, results) => { if (error) { reject(error) } else { resolve(results.rows[0]) } } ) }) } module.exports = { bookingALesson, getTeacherPendingBooking, getBookingInformation, approveBooking, getListStudentFromBooking, getListTeacherForStudentFromBooking, getListActiveBookingForTeacher, getListActiveBookingForStudent, getSetupBooking }
import TodoList from './js/Classes/TodoList'; import UI from './js/Classes/UI'; import { validarForm } from './js/functiones/functions'; import { formTodo, todos } from './js/Variables'; import './styles.css'; export const ui = new UI(); export const todosArr = new TodoList(); loadListeners(); function loadListeners() { formTodo.addEventListener('click', validarForm); document.addEventListener('DOMContentLoaded', () => { if(todos !== []) { ui.loadHTML(todos); } }); }
import React, { Component } from 'react' import capture1 from './images/InGameCaptures/capture1.png' import GameDev from './GameDev.js' import './Projects.css' export class Projects extends Component { render() { return ( <div id='project' className='project scrollMark'> <h1 className='scrollFadeBottom' data-delay='0.0s'>Projects</h1> <img src={capture1} className='scrollFadeTop projectIcon' alt='gameDevPic' data-toggle="modal" data-target="#gameDevDetail" data-delay='0.1s'></img> <GameDev/> <h2 className='scrollFadeTop moreText' data-delay='0.2s'>More Wait To Be Added</h2> </div> ) } } export default Projects
require('mocha'); var should = require('should'); var _ = require('lodash'); var app = require(__dirname + '/../lib/application'); var actors = require(__dirname + '/../lib/actors'); var cache = require(__dirname + '/../lib/cache'); var properties = require(__dirname + '/../lib/properties'); describe('actors & cache modules', function () { beforeEach(function (done) { app.start(done); }); afterEach(function (done) { app.removeActor('sample'); app.removeActor('fake'); app.stop(done); }); it('should add actor to actors and to cache', function (done) { var actorAdded = 0; var cacheActorAdded = 0; function cacheActorAddedListener(aid, cid) { cacheActorAdded++; should.exist(aid); aid.should.have.type('string', 'aid should be a string'); should.exist(cid); aid.should.have.type('string', 'cid should be a string'); cid.should.be.eql(properties.container.id); } function actorAddedListener(aid) { actorAdded++; should.exist(aid); aid.should.have.type('string', 'aid should be a string'); cacheActorAdded.should.be.eql(1); actorAdded.should.be.eql(1); cache.removeListener('actor added', cacheActorAddedListener); actors.removeListener('actor added', actorAddedListener); done(); } cache.on('actor added', cacheActorAddedListener); actors.on('actor added', actorAddedListener); actors.add({id: 'sample'}); }); it('should remove actor from actors and from cache', function (done) { var actorRemoved = 0; var cacheActorRemoved = 0; function cacheActorRemovedListener(aid, cid) { cacheActorRemoved++; should.exist(aid); aid.should.have.type('string', 'aid should be a string'); should.exist(cid); aid.should.have.type('string', 'cid should be a string'); cid.should.be.eql(properties.container.id); } function actorRemovedListener(aid) { actorRemoved++; should.exist(aid); aid.should.have.type('string', 'aid should be a string'); cacheActorRemoved.should.be.eql(1); actorRemoved.should.be.eql(1); cache.removeListener('actor removed', cacheActorRemovedListener); actors.removeListener('actor removed', actorRemovedListener); done(); } cache.on('actor removed', cacheActorRemovedListener); actors.on('actor removed', actorRemovedListener); actors.add({id: 'sample'}); actors.remove('sample'); }); it('should ensure an actor exists', function (done) { actors.add({id: 'sample'}); var result = actors.exists('sample'); should.exist(result); result.should.be.eql(true); done(); }); it('should get an actor from actors', function (done) { var actor = {id: 'sample'}; actors.add(actor); var retreivedActor = actors.get('sample'); should.exist(retreivedActor); retreivedActor.should.be.eql(actor); done(); }); it('should get all added actors id', function (done) { actors.add({id: 'sample'}); actors.add({id: 'fake'}); var aids = actors.all(actors); should.exist(aids); aids.should.be.instanceOf(Array); aids.should.containEql('sample'); aids.should.containEql('fake'); done(); }); it('should pick an container from cache', function (done) { actors.add({id: 'sample'}); // local actor var fakeContainer = {id: 'fakeContainerid'}; cache.add('sample', fakeContainer); var next = null; for (var i = 0; i < 10; i++) { var cid = cache.pick('sample'); should.exist(cid); cid.should.have.type('string'); if (next === null) { [properties.container.id, fakeContainer.id].should.containEql(cid); next = cid; } else { cid.should.be.eql(next); } next = (next === properties.container.id) ? fakeContainer.id : properties.container.id; } done(); }); it('should get a container from cache', function (done) { actors.add({id: 'sample'}); var container = cache.getContainer(properties.container.id); should.exist(container); container.should.be.eql(properties.container); done(); }); it('should disable then enable container', function (done) { var oldContainerDisableTime = properties.containerDisableTime; properties.containerDisableTime = 50; actors.add({id: 'sample'}); cache.disableContainer(properties.container.id); var container = cache.getContainer(properties.container.id); should.exist(container.disabled); container.disabled.should.be.eql(true); setTimeout(function () { var container = cache.getContainer(properties.container.id); should.not.exist(container.disabled); properties.containerDisableTime = oldContainerDisableTime; done(); }, 75); }); it('should get all cache actors ids', function (done) { actors.add({id: 'sample'}); cache.add('fake', {id: 'fakeContainerid'}); var aids = cache.actors(); should.exist(aids); aids.should.be.instanceOf(Array); aids.should.containEql('sample'); aids.should.containEql('fake'); done(); }); it('should get all cache containers ids', function (done) { actors.add({id: 'sample'}); var fakeContainer = {id: 'fakeContainerid', name: 'fakeContainer'}; cache.add({id: 'fake'}, fakeContainer); var cids = cache.containers(); should.exist(cids); cids.should.be.instanceOf(Array); cids.should.containEql(_.pick(properties.container, ['id', 'name'])); cids.should.containEql(fakeContainer); done(); }); it('should clear cache and sync local actors', function (done) { actors.add({id: 'sample'}); var fakeContainer = {id: 'fakeContainerid', name: 'fakeContainer'}; cache.add({id: 'fake'}, fakeContainer); function cacheClearedListener() { var aids = cache.actors(); aids.should.containEql('sample'); aids.should.not.containEql('fake'); var cids = cache.containers(); cids.should.containEql(_.pick(properties.container, ['id', 'name'])); cids.should.not.containEql(fakeContainer); cache.removeListener('cleared', cacheClearedListener); done(); } cache.on('cleared', cacheClearedListener); cache.clear(); }); });
import React from 'react' import './nav.css'; import {Link} from 'react-router-dom' export default class Nav extends React.Component { render() { return ( <div> <nav class="navbar-light bg-light nav-flex"> <div> <a class="navbar-brand" href="#">Travelism</a> </div> <div> <ul class="navbar-custom mr-auto mt-2 mt-lg-0"> <li class="nav-item active"> <Link class="nav-link" to="/">Home <span class="sr-only">(current)</span></Link> </li> <li class="nav-item"> <a class="nav-link" href="#">Challenge</a> </li> <li class="nav-item"> <a class="nav-link" href="#">{this.props.account}</a> </li> <li class="nav-item"> <p>{this.props.point}</p> </li> </ul> </div> </nav> </div> ) } }