text
stringlengths 7
3.69M
|
|---|
// A reducer is a function that gets 2 properties:
// 1. initial this.state
// 2. action - a string telling us what specific action this is
// {
// type: // a defined action type
// payload: // payload attached to out action that can be anything.
// }
const INITIAL_STATE = {
currentUser: null
}
const userReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case 'SET_CURRENT_USER':
return {
...state,
currentUser: action.payload
}
default:
return state
}
}
export default userReducer;
|
import React, { Component } from 'react';
import './../style/gayaku.css';
import { Link } from 'react-router-dom';
import Header from './Header';
import Footer from './Footer';
class Coffees extends Component
{
render()
{
return (
<div>
<Header/>
{/* bikin gambar dan deskripsi */}
<div className="container-fluid text-center">
<div className="row text-center">
<div className="col-sm-4">
<div className="thumbnail item border">
<a href="./Deskripsicoffeesa">
<img src="images/produk kopi/produka.jpg" alt="produka" style={{maxHeight: 450}} />
</a>
<figcaption className="info-wrap">
<h3>Velo 100% Arabica Coffee Bean</h3>
<p>Medium Roast, 100gr</p>
<div className="label-rating">132 reviews</div>
<div className="label-rating">154 orders </div>
</figcaption>
<div className="bottom-wrap">
<a href="./Deskripsicoffeesa" className="btn btncart">Detail</a>
<div className="h5">
Rp 150.000 <del className="price-old">Rp 200.000</del>
</div>
</div>
</div>
</div>
<div className="col-sm-4">
<div className="thumbnail item border">
<a href="./Deskripsicoffeesb">
<img src="images/produk kopi/produkb.jpg" alt="produkb" style={{maxHeight: 450}} />
</a>
<figcaption className="info-wrap">
<h3>Caffe Espresso</h3>
<p>Coffee Beans/Ground, Light Roast,200gr</p>
<div className="label-rating">142 reviews</div>
<div className="label-rating">174 orders </div>
</figcaption>
<div className="bottom-wrap">
<a href="./Deskripsicoffeesb" className="btn btncart">Detail</a>
<div className="h5">
Rp 200.000 <del className="price-old">Rp 250.000</del>
</div>
</div>
</div>
</div>
<div className="col-sm-4">
<div className="thumbnail item border">
<a href="./Deskripsicoffeesc">
<img src="images/produk kopi/produkc.jpg" alt="produkc" style={{maxHeight: 450}} />
</a>
<figcaption className="info-wrap">
<h3>Rose Pank</h3>
<p>Coffee Beans/Ground, Medium Roast, 100gr</p>
<div className="label-rating">132 reviews</div>
<div className="label-rating">154 orders </div>
</figcaption>
<div className="bottom-wrap">
<a href="./Deskripsicoffeesc" className="btn btncart">Detail</a>
<div className="h5">
Rp 150.000 <del className="price-old">Rp 200.000</del>
</div>
</div>
</div>
</div>
</div>
</div>
<Footer/>
</div>
);
}
} export default Coffees;
|
//引入套件及伺服器變數設定
const express = require('express')
const app = express()
const exphbs = require('express-handlebars')
const bodyParser = require('body-parser')
const generatePhrase = require('./generate_phrase')
const port = 8080
//設定樣版引擎
app.engine('handlebars', exphbs({ defaultLayout: 'main' }))
app.set('view engine', 'handlebars')
//路由設定
//bodyParser先放第一個
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static('public'))
app.get('/', (req, res) => {
res.render('index')
})
app.post('/', (req, res) => {
const stupidphrase = generatePhrase(req.body)
res.render('index', { stupidphrase: stupidphrase })
})
//開始express伺服器及監聽
app.listen(process.env.PORT || 8080, () => {
console.log(`express app listening on port ${port} .`)
})
|
import React from 'react';
import { InputGroup, FormControl } from 'react-bootstrap';
import '../App.css';
const Sidebar = () => {
return (
<div className="sidebar">
<h3>FILTER BY:</h3>
<InputGroup className="mb-3">
<InputGroup.Prepend>
<InputGroup.Checkbox aria-label="Checkbox for following text input" />
</InputGroup.Prepend>
<FormControl aria-label="Text input with checkbox" />
</InputGroup>
<InputGroup>
<InputGroup.Prepend>
<InputGroup.Radio aria-label="Radio button for following text input" />
</InputGroup.Prepend>
<FormControl aria-label="Text input with radio button" />
</InputGroup>
</div>
);
};
export default Sidebar;
|
'use strict';
// IMPORTS
let fs = require('fs');
// Reads file from
exports.read = (cb) => {
fs.readFile('./data/calendar.json', (err, d) => {
if (err) throw err;
cb(d);
});
}
|
<<<<<<< HEAD
function subtrair(num1, num2) {
return num1 - num2;
}
=======
function subtrair(num1, num2) {
return num1 - num2;
}
>>>>>>> master
|
'use strict';
/**
* @ngdoc function
* @name sampleApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the sampleApp
*/
angular.module('sampleApp').controller('MainController',[ '$scope', function ($scope) {
$scope.test = 'Hello';
//add active class for menu
$( "ul.page-sidebar-menu li" ).click(function() {
$( "ul.page-sidebar-menu li" ).removeClass("active");
if (window.location.hash==$(this).find('a').attr('href')){
$(this).addClass("active");
}
});
}]);
|
window.onload = function () {
var servers = {};
var selected ='';
var scriptsText ='';
var scriptsResult ='';
var scripts = new Vue({
el: "#serverList",
data: {
selected:selected,
options:servers,
scriptsText:scriptsText,
scriptsResult:scriptsResult
},
methods:{
//run the script
run:function (evnet) {
window.parent.client.request('scripts', {
command: 'run',
serverId: this.selected,
script: this.scriptsText
}, function (err, msg) {
if (err) {
scripts.$data.scriptsResult = err;
return;
}else{
// alert('msg'+msg);
scripts.$data.scriptsResult = msg;
}
});
}
}
});
var list = function () {
window.parent.client.request('scripts', {
command: 'list'
}, function (err, msg) {
if (err) {
alert(err);
return;
}else{
var obj = msg.servers;
scripts.$data.options = obj;
}
})
};
setInterval(list.bind(this),2000);
};
|
const jwt = require('jsonwebtoken');
const TOKEN_SECRET = 'hubizict';
const tokenGenerator = (data, callback) => {
let token = jwt.sign(data, TOKEN_SECRET, {
algorithm: 'HS256',
expiresIn: '8h'
});
callback(token)
}
const isValid = (token, callback) => {
jwt.verify(token, TOKEN_SECRET, (err, decode) => {
if (err) {
// console.log("=========Token Helper: Can't decode token")
callback({isValid: false})
} else {
const exp = new Date(decode.exp * 1000)
const now = Date.now()
const day = (60 * 60 * 24 * 1000)
if (exp < now) {
// console.log("=========Token Helper: Expired Token")
callback({isValid: false})
} else if (exp < now + (5 * day)) {
// console.log("=========Token Helper: Generate New Token")
const newToken = module.exports.generateToken(decode.user.id)
callback({isValid: true, token: newToken, userInfo:decode})
} else {
// console.log("=========Token Helper: Token is valid")
callback({isValid: true, token: token, userInfo:decode})
}
}
});
}
const tokenHandler = (req, res, next) => {
const { token } = req.query
if(token) {
module.exports.isValid(token, (result) => {
req.userInfo = result;
next()
})
} else {
req.userInfo = {isValid: false}
next()
}
}
const tokenDestroy = (req, res, next) => {
res.clearCookie('userInfo');
next();
}
const getDecoded = (token, callback) => {
jwt.verify(token, TOKEN_SECRET, (err, decode) => {
if(token == undefined) { callback(undefined); return; }
if(err) {
callback(undefined);
return;
}
callback(decode);
});
}
const decodedNext = async (req, res, next) => {
let token = req.cookies.userInfo;
await jwt.verify(token, TOKEN_SECRET, (err, decode) => {
if(token == undefined || err) { return next(); }
req.body.token = decode;
next();
});
}
/**
* token 값을 체크 하여 값이 없거나 잘못 되었다면 로그인 화면으로 보낸다.
* @param {*} req
* @param {*} res
*/
const tokenCheckWithoutPage = (req, res, next) => {
let token = req.cookies.userInfo;
jwt.verify(token, TOKEN_SECRET, (err, decode) => {
// 토큰이 expires 된경우 메인화면으로 이동
if(token == undefined || err) {
// 로그인 화면으로 보낸다.
res.redirect('/auth/login');
return;
}
next();
});
}
module.exports = {
tokenGenerator,
isValid,
getDecoded,
decodedNext,
tokenDestroy,
tokenHandler,
tokenCheckWithoutPage
}
|
const {Quotes,SellerQuote,Product} = require('../models');
const { quoteEmailSeller } = require('../utils/quoteEmailSeller');
const { quoteEmailBuyer } = require('../utils/quoteEmailBuyer');
const { notificationEmailSellerUpdate } = require('../utils/notificationEmailSellerUpdate');
const { notificacionEmailBuyerUpdate } = require('../utils//notificacionEmailBuyerUpdate');
exports.add = async (req, res, next) => {
try {
// validar que vengan los productos
if (!req.body) {
res.status(400).json({ error: true, message: 'Los productos a cotizar son obligatorios.' });
next();
}
const product = await Product.findAll({where: { status: true, } });
for (let index = 0; index < dat.length; index++) {
const element = dat[index];
const data = req.body;
UserId= req.user.id,
ProductId= data.ProductId,
quantity= data.quantity,
price_u= data.quantity >= products.quantity_PPS
(datos.quantity * products.price_S),
total_products= data.length,
summary= `En tu cotización tienes un total de: ${total_products}, y el total a pagar por estos productos es: ${total_amount}.` ,
total_amount= price_U*quantity,
date= new date(),
date_expiration= new date()+1728000
};
await Quotes.create(data);
//enviar el email
const resultadoEmailC = await quoteEmailBuyer(
productId,quantity,price_u, total_products, summary, total_amount, date, date_expirantion,
req.user.email,
);
if (resultadoEmailC) {
res.staus(200).json({ message: 'A message has been sent to the email provided.'});
}
const quote = await Quotes.findAll({where: { UserId: req.user.id } });
const user = await User.findAll({where: {UserId: product.UserId}});
const datas = product.UserId;
datas.QuotesId = quote.id;
await SellerQuote.create(datas);
//enviar el email
const resultadoEmailV = await quoteEmailSeller(
productId,quantity,price_u, total_products, summary, total_amount, date, date_expirantion,
user.email,
);
if (resultadoEmailV) {
res.staus(200).json({ message: 'A message has been sent to the email provided.'});
}
next();
} catch (error) {
console.log(error);
let errores = [];
if (error.errors) {
errores = error.errors.map( errorItem => ({
campo: errorItem.path,
error: errorItem.message,
}));
}
res.status(400).json({ error: true, message: 'Quote register error.' , errores });
}
};
// listar
exports.listQuotesBuyer = async (req, res, next) => {
try {
const quote = await Quote.findall({
where: {UserId: req.quote.id},
});
res.json(quote);
} catch (error) {
console.error(error);
res.status(400).json({ message: 'Error reading quotes' });
next();
}
};
exports.updateQuotesBuyer = async(req, res, next) => {
try {
// obtener el registro del usuario desde la bd
const quote = await Quote.findByPk(req.params.id);
if(quote-date <= quote.date_expiration){
// actualizar en la bd
let newQuote = req.body;
// procesar las propiedades que viene en body
Object.keys(newQuote).forEach((propiedad) => {
quote[propiedad] = newQuote[propiedad];
});
// guaradar cambios
await quote.save();
res.json({ message: 'The record was updated.' });
//enviar el email
const resultadoEmailC = await notificationEmailSellerUpdate(
productId,quantity,price_u, total_products, summary, total_amount, date, date_expirantion,
req.user.email,
);
if (resultadoEmailC) {
res.staus(200).json({ message: 'A message has been sent to the email provided.'});
}
const product = await Product.findAll({where: { status: true, } });
const quote = await Quote.findAll({where: { UserId: req.user.id } });
const user = await User.findAll({where: {UserId : product.UserId}});
const datas = product.UserId;
datas.QuotesId = quote.id;
await SellerQuote.create(datas);
//enviar el email
const resultadoEmailV = await notificationEmailSellerUpdate(
productId,quantity,price_u, total_products, summary, total_amount, date, date_expirantion,
user.email,
);
if (resultadoEmailCV) {
res.staus(200).json({ message: 'A message has been sent to the email provided.'});
}
next();
}
else {
res.status(404).json({ error: true, message: 'The time for modifying the quote has expired.'});
}
} catch (error) {
res.status(503).json({ message: 'Failed to update quote.' });
}
};
// delete
exports.delete = async (req, res, next) => {
try {
const quote = await Quote.findByPk(req.params.id);
if(quote-date <= quote.date_expiration){
await user.destroy(); // user.destroy({ where: {id: req.params.id }});
res.json({ message: 'Quote was deleted.' });
} else {
res.status(404).json({ error:true, message: 'The Quote was not found.'});
}
} catch (error) {
res.status(503).json({ message: 'Failed to delete quote. ' });
}
};
|
// 音频API
const myaudio = wx.createInnerAudioContext();
Page({
leftMove: 0,
rightMove: 0,
data: {
itemList: [], //showAction提示文字
title: '',
desc: '',
voice: 0, //声音提醒时间
leftAnimationData: '',
rightAnimationData: '',
leftTime: 0,
rightTime: 0
},
// 页面初始化
onLoad: function () {
myaudio.src = "/assets/sound/countdown.mp3"
},
// 页面显示
onShow: function () {
var configs = wx.getStorageSync('configs')
var itemLists = []
// 第一次出现的阶段内容
var first = true
for (var i in configs) {
var config = configs[i]
if (config.state) {
var desc = config.desc.replace(/@/g, config.time + '秒')
if (first) {
this.setData({
title: config.name,
desc: desc,
leftTime: config.time,
rightTime: config.time,
voice: config.voice
})
first = false
}
itemLists.push({
title: config.name,
desc: desc,
time: config.time,
voice: config.voice
})
}
}
this.setData({
itemList: itemLists
})
},
showAction: function () {
var page = this
var itemArr = []
for (var i = 0; i < this.data.itemList.length; i++) {
itemArr[i] = this.data.itemList[i].title
}
wx.showActionSheet({
itemList: itemArr,
success(res) {
page.setData({
title: page.data.itemList[res.tapIndex].title,
desc: page.data.itemList[res.tapIndex].desc,
voice: page.data.itemList[res.tapIndex].voice,
leftTime: page.data.itemList[res.tapIndex].time,
rightTime: page.data.itemList[res.tapIndex].time
})
page.leftStop();
page.rightStop();
},
fail(res) {
console.log(res.errMsg)
}
})
},
leftStart: function () {
this.rightStop();
if (this.leftInterval && this.leftInterval != 0) {
this.leftStop();
return false;
}
var leftAnimation = wx.createAnimation({
duration: 1000,
timingFunction: 'ease'
})
leftAnimation.rotate(this.leftMove += 100).step()
this.setData({
leftAnimationData: leftAnimation.export()
})
// 定义一个定时器
var page = this
var leftInterval = setInterval(function () {
if (page.data.leftTime <= 0) {
page.leftStop();
myaudio.pause();
return false;
}
if (page.data.leftTime <= page.data.voice) {
myaudio.play();
}
leftAnimation.rotate(page.leftMove += 100).step()
page.setData({
leftAnimationData: leftAnimation.export()
})
page.setData({
leftTime: page.data.leftTime - 1
})
}, 1000)
this.leftInterval = leftInterval
},
leftStop: function () {
clearInterval(this.leftInterval)
this.leftInterval = 0
myaudio.pause();
},
rightStart: function () {
this.leftStop();
if (this.rightInterval && this.rightInterval != 0) {
this.rightStop();
return false;
}
var rightAnimation = wx.createAnimation({
duration: 1000,
timingFunction: 'ease'
})
rightAnimation.rotate(this.rightMove += 100).step()
this.setData({
rightAnimationData: rightAnimation.export()
})
// 定义一个定时器
var page = this
var rightInterval = setInterval(function () {
if (page.data.rightTime <= 0) {
page.rightStop();
return false;
}
if (page.data.rightTime <= page.data.voice) {
myaudio.play();
}
rightAnimation.rotate(page.rightMove += 100).step()
page.setData({
rightAnimationData: rightAnimation.export()
})
page.setData({
rightTime: page.data.rightTime - 1
})
}, 1000)
this.rightInterval = rightInterval
},
rightStop: function () {
clearInterval(this.rightInterval)
this.rightInterval = 0
myaudio.pause();
}
})
|
var meanApp = angular.module('meanApp', ['ngRoute', 'ngUpload', 'ngAnimate', 'meanControllers']);
meanApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
controller:'HomeCtrl',
templateUrl:'mod_home.html'
})
.when('/game_log/:index', {
controller:'ListCtrl',
templateUrl:'mod_list.html'
})
.when('/upload/', {
controller:'UploadCtrl',
templateUrl:'mod_upload.html'
})
.when('/detail/:gameId', {
controller:'DetailCtrl',
templateUrl:'mod_detail.html'
})
.when('/play/', {
controller:'PlayCtrl',
templateUrl:'mod_play.html'
})
.when('/playvcpu/', {
controller:'PlayvCPUCtrl',
templateUrl:'mod_play_v_cpu.html'
})
.when('/login/', {
controller:'LogInCtrl',
templateUrl:'mod_login.html'
})
.when('/rules/', {
controller:'RulesCtrl',
templateUrl:'mod_rules.html'
})
.when('/leaderboard/', {
controller:'LeaderboardCtrl',
templateUrl:'mod_leaderboard.html'
})
.when('/createuser/', {
controller:'CreateUserCtrl',
templateUrl:'mod_createuser.html'
})
.when('/statistics/', {
controller:'StatisticsCtrl',
templateUrl:'mod_statistics.html'
})
.otherwise({
redirectTo: '/'
});
}]);
|
(function() {
angular
.module("hungr")
.controller("PaletteController", PaletteController);
PaletteController.$inject = ['$scope'];
function PaletteController($scope) {
}
})();
|
var defaultUrl = "https://mhsprod.jira.com";
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', openIssue);
document.querySelector('input').addEventListener('keydown', keydown);
document.querySelector('#options').addEventListener('click', showOptions);
onload();
});
function onload() {
var projectKey = localStorage.getItem("projectKey");
if(projectKey) document.getElementById("issueId").value = projectKey + '-';
document.getElementById("issueId").focus();
}
function keydown (event) {
if(event.keyCode==13) openIssue();
}
function openIssue(){
var issueId = document.getElementById("issueId").value.trim();
if (issueId.trim() == '') return;
addToStorage(issueId);
openJira(issueId)
}
function addToStorage(issueId) {
var projectKey = issueId.substr(0, issueId.indexOf('-'));
if(projectKey != '') {
localStorage.setItem("projectKey", projectKey);
}
}
function openJira(issueId) {
var url = localStorage.getItem("url") || defaultUrl;
window.open(url+ "/browse/" + issueId);
}
function showOptions() {
chrome.tabs.create({ 'url': 'chrome://extensions/?options=' + chrome.runtime.id });
}
|
(function () {
'use strict';
/**
* @ngdoc object
* @name panel1.controller:Panel1Ctrl
*
* @description
*
*/
angular
.module('panel1')
.controller('Panel1Ctrl', Panel1Ctrl);
function Panel1Ctrl($timeout) {
var vm = this;
vm.controlsVisible = false;
vm.timeoutPromise = null;
vm.handleMouseMove = function () {
vm.controlsVisible = true;
$timeout.cancel(vm.timeoutPromise);
vm.timeoutPromise = $timeout(function () {
vm.controlsVisible = false;
}, 2000);
};
}
}());
|
window.onload = function() {
var oLink = document.getElementsByTagName("link")[0];
var oSkin = document.getElementById("skin");
var aLi = oSkin.getElementsByTagName("li");
for (var i = 0; i < aLi.length; i++) {
aLi[i].onclick = function() {
for (var i = 0; i < aLi.length; i++) {
aLi[i].className = " "
};
this.className = "current";
oLink.href = this.id+".css";
}
};
}
|
const express = require('express');
const router = express.Router();
const Genre = require('../model/genres');
const passport = require('passport');
router.get('/', passport.authenticate('jwt', { session: false }), async (req, res) => {
var pageNo = parseInt(req.query.pageNo)
var size = parseInt(5)
const genre = await Genre.find()
.skip((pageNo - 1) * size)
.limit(size)
.then(result => {
res.status(200).json(result);
})
return genre;
});
router.get('/:id', passport.authenticate('jwt', { session: false }), async (req, res) => {
const genre = await Genre.findById(req.params.id)
.then(result => {
res.status(200).json(result);
})
return genre;
});
router.post('/', passport.authenticate('jwt', { session: false }), (req,res,next) => {
async function AddGenre(){
try{
const genre = await new Genre({
name : req.body.name
})
genre.save().then(result => res.json(result))
return { genre }
}
catch(err){
throw err;
}
}
AddGenre();
})
router.put('/:id', passport.authenticate('jwt', { session: false }), async (req,res) => {
const genre = await Genre.findByIdAndUpdate(req.params.id,{ name : req.body.name},{new: true})
.then(result => {
if(!result){
return res.status(404).send('the genre with the given ID')
}
return res.status(200).json(result);
})
return genre
})
router.delete("/:id", passport.authenticate('jwt', { session: false }), async (req,res) => {
const genre = await Genre.findByIdAndRemove(req.params.id)
.then(result => {
if(!result){
res.json({mesage: "data not found"})
}
res.status(200).json({message : 'sukses'});
})
return genre
})
module.exports = router;
|
//
// ScriptWidget
// https://scriptwidget.app
//
// Usage for component rect
//
$render(
<vstack frame="max">
<rect frame="50,30" color="blue"></rect>
<rect frame="50,30" color="blue" corner="5"></rect>
</vstack>
);
|
// Given a sorted array and a target value, return the index if the target is found.If not, return the index where it would be if it were inserted in order.
// You may assume no duplicates in the array.
// Example 1:
// Input: [1, 3, 5, 6], 5
// Output: 2
// Example 2:
// Input: [1, 3, 5, 6], 2
// Output: 1
// Example 3:
// Input: [1, 3, 5, 6], 7
// Output: 4
// Example 1:
// Input: [1, 3, 5, 6], 0
// Output: 0
// 一个排序后的数组,一个target,如果数组中包含target就返回在数组中的索引,如果不包含就向数组中插入target,返回新数组target的索引
// 因为看到是排序后的数组,所以直接循环数组对比了。。。。感觉想提高性能就得从如何快速找到一个比target大的数字,看到75ms的算法果然用了二分法
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var searchInsert = function (nums, target) {
if (nums.indexOf(target) !== -1 ) {
return nums.indexOf(target)
}
for (var i = 0; i < nums.length;i++) {
if (nums[i]> target) {
nums.splice(i, 0, target)
return i
}
if (i == nums.length -1) {
nums.push(target)
return i + 1
}
}
};
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var searchInsert = function (nums, target) {
var l = 0;
var u = nums.length - 1;
var mid;
while (l <= u) {
mid = parseInt((u + l) / 2);
if (target === nums[mid]) {
return mid;
} else if (target < nums[mid]) {
u = mid - 1;
} else {
l = mid + 1;
}
}
return l;
};
|
import React from 'react';
import { Link } from 'react-router-dom';
import logoHeader from '../assets/images/logo.jpg'
const Menu = () => {
return(
<div className="content header">
<figure>
<img src={logoHeader} className="logo" alt="Supermercado" />
</figure>
<nav>
<Link to='/'>Home</Link>
<Link to='/receitas'>Receitas</Link>
<Link to='/contato'>Contato</Link>
</nav>
</div>
)
}
export default Menu;
|
function catchErrors(error, displayError) {
let errorMsg;
if (error.response) {
// The request was made and the server responsed with a status code that is not in the range of 2XX
errorMsg = error.response.data;
console.error('Error response', errorMsg);
// For Cloudinary image uploads
if (error.response.data.error) {
errorMsg = error.response.data.error.message;
}
} else if (error.request) {
// The request was made, but no response was received
errorMsg = error.request;
console.error('Error request', errorMsg);
} else {
// Something else happened in making the request that triggered an error
errorMsg = error.message;
console.error('Error message', errorMsg);
}
displayError(errorMsg);
}
export default catchErrors;
|
import React,{Component} from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import * as tool from '../../utils/tool';
import { Tabs,Spin } from 'antd';
import MyTable from '../../components/MyTable';
import jQuery from 'jquery';
import styles from './css/Block.css';
import NotFound from '../../components/NotFound';
import TradeRow from '../../components/TradeRow';
const TabPane = Tabs.TabPane;
class Block extends Component{
constructor(props){
super(props);
this.state = {
detail: {},
dataSource: [],
loading: true,
count: 0,
};
this.domLoadFlag = false;
this.mypre = null;
this.columns = [{
title: '交易',
className:'myCol',
dataIndex: 'id',
key: 'id',
render: (text,record,index) => {
return TradeRow(record,()=>{this.toTradePage(text)});
}
}];
}
toTradePage = (id)=>{
this.props.dispatch(routerRedux.push(tool.getUri('/tx/'+id)));
};
componentWillReceiveProps(nextProps){
console.log('》》》props变化', nextProps);
if(this.props.match.params.id != nextProps.match.params.id){
console.log('重新请求');
this.init(nextProps.match.params.id);
}
}
init = (id)=>{
let params = {};
//hash值
if(id.length == 64){
params.block_hash = id;
}else{
params.block_num = parseInt(id);
}
this.props.dispatch({
type: 'eos/getBlockDetail',
params,
callback: (data)=>{
this.setState({
loading: false,
detail: data
});
if(data.raw_data){
console.log('》》》》》已经加载');
let s = data.raw_data;
s = s.replace(/\r\n/g,"");
s = s.replace(/\n/g,"");
jQuery(this.mypre).html(this.syntaxHighlight(JSON.parse(s)));
}
},
errCallback: ()=>{
this.setState({
loading: false,
});
}
});
};
componentDidMount(){
}
componentWillMount(){
this.init(this.props.match.params.id);
}
getBlockTrade = (page_num,page_size)=>{
let id = this.props.match.params.id;
let params = {
page_num: page_num,
page_size: page_size,
};
//hash值
if(id.length == 64){
params.block_hash = id;
}else{
params.block_num = parseInt(id);
}
this.props.dispatch({
type: 'eos/getBlockTrade',
params,
callback: (data)=>{
data.transaction_info.map((item,index)=>{
item.key = index;
});
this.setState({
dataSource: data.transaction_info,
count: data.total
})
}
});
};
syntaxHighlight = (json) => {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
};
toBlockProducerPage = (id)=>{
this.props.dispatch(routerRedux.push(tool.getUri('/bp/'+id)));
};
render(){
let {detail,loading} = this.state;
if(loading){
return (
<div className={styles.spinWrapper}>
<Spin />
</div>
);
} else if(detail.block_num){
return this.renderDetail();
}else{
return this.renderNotFound();
}
}
renderNotFound = ()=>{
return (
<NotFound/>
);
};
toBlockPage = (id)=>{
let s = tool.getUri('/block/'+id);
window.location = window.location.origin + s;
};
toIndex = ()=>{
window.location = window.location.origin + tool.getUri('/');
};
renderDetail = ()=>{
let {detail,dataSource} = this.state;
let tab1 = `交易(${this.state.count})`;
return (
<div>
<div className={styles.bread}>
<a href="javascript:void(0)" style={{color:'rgba(0, 0, 0, 0.65)'}} onClick={this.toIndex}>首页</a> / 区块#{detail.block_num}
</div>
<div className={styles.basic}>
<div className={styles.title}>区块#{detail.block_num}</div>
<div style={{overflow:'hidden'}}>
<div className={styles.leftWrapper}>
<div className={styles.item}>
<div className={styles.itemLabel}>出块时间:</div>
<div className={styles.itemValue}>{detail.timestamp}</div>
</div>
<div className={styles.item}>
<div className={styles.itemLabel}>出块节点:</div>
<div className={styles.itemValue}><a href="javascript:void(0);" onClick={()=>{this.toBlockProducerPage(detail.producer)}}>{detail.producer}</a></div>
</div>
<div className={styles.item}>
<div className={styles.itemLabel}>前一个区块:</div>
<div className={styles.itemValue}><a href="javascript:void(0)" onClick={()=>this.toBlockPage(detail.block_num-1)}>#{detail.block_num-1}</a></div>
</div>
<div className={styles.item}>
<div className={styles.itemLabel}>后一个区块:</div>
<div className={styles.itemValue}><a href="javascript:void(0)" onClick={()=>this.toBlockPage(detail.block_num+1)}>#{detail.block_num+1}</a></div>
</div>
</div>
<div className={styles.rightWrapper}>
<div className={styles.item}>
<div className={styles.itemLabel2}>block_id:</div>
<div className={styles.itemValue2}>{detail.id}</div>
</div>
<div className={styles.item}>
<div className={styles.itemLabel2}>transaction_mroot:</div>
<div className={styles.itemValue2}>{detail.transaction_mroot}</div>
</div>
<div className={styles.item}>
<div className={styles.itemLabel2}>出块节点签名:</div>
<div className={styles.itemValue2}>{detail.producer_signature}</div>
</div>
</div>
</div>
</div>
<div className={styles.detail}>
<Tabs defaultActiveKey="1" onChange={()=>{}}>
<TabPane tab={tab1} key="1">
<MyTable
showHeader={false}
dataSource={dataSource}
columns={this.columns}
count={this.state.count}
getTableData={this.getBlockTrade}
/>
</TabPane>
<TabPane tab="RAW数据" key="2" forceRender={true}>
<pre ref={(r) => { this.mypre = r; }} >
</pre>
</TabPane>
</Tabs>
</div>
</div>
);
}
}
export default connect()(Block);
|
import PositionalExample from "./positional";
export {
PositionalExample
};
|
$("#submit")
.click(
function() {
var request = {
brand: $("#brand").val(),
province: $("#province").val(),
city: $("#city").val(),
appsku: $("#appsku").val(),
channel: $("#channel").val(),
zt: $("#zt").val(),
key: $("#keyword").val(),
start_time: $("#start_time").val(),
end_time: $("#end_time").val(),
page_type: $("#pageype").val()
};
$
.ajax({
url: "api/car/search",
type: "POST",
dataType: "json",
data: JSON.stringify(request),
contentType: 'application/json',
success: function(data) {
var emptyLine = "<tr><td id=\"no_record\" style=\"display:true\" colspan=\"14\" align=\"center\">NO RECORD FOUND</td></tr>";
if (data == "") {
$("#no_record").remove();
$("#request_list_tbl").remove();
$("#request_list")
.append(
"<tbody id = \"request_list_tbl\"></tbody>")
$("#request_list_tbl")
.append(emptyLine);
} else {
$("#no_record").remove();
$("#request_list_tbl").remove();
$("#request_list")
.append(
"<tbody id = \"request_list_tbl\"></tbody>")
var length = data.list.length;
if (length > 0) {
$.each(data.list, function(index,
item) {
var line = "<tr>" + "<td>" + item.id + "</td>" + "<td>" + item.name + "</td>" + "<td>" + item.phone + "</td>" + "<td>" + item.province + " " + item.city + "</td>" + "<td>" + item.brand + "</td>" + "<td>" + item.carName + "</td>" + "<td>" + item.serialName + "</td>" + "<td>" + item.dealer + "</td>" + "<td>" + item.appsku + "</td>" + "<td>" + item.channel + "</td>" + "<td>" + item.zt + "</td>" + "<td> </td>" + "<td>" + item.pagetype + "</td>" + "<td>" + item.requestTime + "</td>" + "</tr>";
$("#request_list_tbl").append(
line);
});
} else {
$("#request_list_tbl").append(
emptyLine);
}
}
}
});
});
// 根据车型id和城市获取经销商
function showTip(text) {
$("#models_balloon").text(text).show();
setTimeout('$("#models_balloon").hide();', 2000);
}
function showSuccess() {
$(".popup-succes").show();
setTimeout('$(".popup-succes").hide();', 2000);
}
function loadSMSConfig() {
$.ajax({
url: "api/car/config/sms",
type: "GET",
dataType: "text",
data: "",
success: function(data) {
if (data == "OFF") {
$(":radio[name='sms_switch'][value='OFF']").attr("checked", true);
} else {
$(":radio[name='sms_switch'][value='ON']").attr("checked", true);
}
}
});
}
function loadMailList() {
$.ajax({
url: "api/car/config/maillist",
type: "GET",
dataType: "json",
data: "",
success: function(data) {
$("#mail_list").remove();
$("#mail_tbl").append("<tbody id = \"mail_list\"></tbody>");
var length = data.length;
if (length > 0) {
$.each(data, function(index,
item) {
var line = "<tr>" + "<td style=\"width: 20%\"><input type=\"checkbox\" name=\"mailid\" value= \"" + item.id + "\" ></td>" + "<td style=\"width: 40%\">" + item.name + "</td>" + "<td style=\"width: 40%\">" + item.mail + "</td>" + "</tr>";
$("#mail_list").append(
line);
});
} else {
$("#mail_list").remove();
$("#mail_tbl").append("<tbody id = \"mail_list\"></tbody>");
}
}
});
}
$("#save_sms_switch").click(
function() {
var value = $("input[name='sms_switch']:checked").val();
$.ajax({
url: "api/car/config/sms",
type: "PUT",
dataType: "text",
data: {
value: value
},
success: function(data) {
}
});
}
);
$("#delete").click(
function() {
var chk_ids = []; //定义一个数组
var cnt = 0;
$('input[name="mailid"]:checked').each(function() {
chk_ids.push($(this).val());
cnt = cnt + 1;
});
if (cnt > 0) {
$.ajax({
url: "api/car/config/maillist",
type: "POST",
data: {
"chk_ids": chk_ids
},
traditional: true,
success: function(data) {}
});
loadMailList();
}
}
);
$("#add_mail").click(
function() {
var name = $("#name").val();
var mail = $("#mail").val();
$.ajax({
url: "api/car/config/maillist",
type: "PUT",
dataType: "text",
data: {
name: name,
mail: mail
},
success: function(data) {
}
});
$("#name").val("");
$("#mail").val("");
loadMailList();
}
);
|
// Copyright (c) 2016-2018, BuckyCloud, Inc. and other BDT contributors.
// The BDT project is supported by the GeekChain Foundation.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the BDT nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'use strict';
const Base = require('../../base/base.js');
const {Result: DHTResult, Config} = require('../util.js');
const BaseUtil = require('../../base/util.js');
const TimeHelper = BaseUtil.TimeHelper;
const LOG_INFO = Base.BX_INFO;
const LOG_WARN = Base.BX_WARN;
const LOG_DEBUG = Base.BX_DEBUG;
const LOG_CHECK = Base.BX_CHECK;
const LOG_ASSERT = Base.BX_ASSERT;
const LOG_ERROR = Base.BX_ERROR;
const TaskConfig = Config.Task;
class Task {
constructor(owner, {timeout = TaskConfig.TimeoutMS, maxIdleTime = TaskConfig.MaxIdleTimeMS} = {}) {
if (new.target === Task) {
throw new Error('Task is a base class, it must be extended.');
}
if (!timeout) {
timeout = TaskConfig.TimeoutMS;
}
let now = TimeHelper.uptimeMS();
this.m_owner = owner;
this.m_id = owner.genTaskID();
this.m_startTime = now;
this.m_timeout = timeout || TaskConfig.TimeoutMS;
this.m_lastActiveTime = now;
this.m_maxIdleTime = maxIdleTime;
this.m_callbackList = [];
}
get id() {
return this.m_id
}
get type() {
return this.constructor.name;
}
get isComplete() {
return this.m_isComplete;
}
get deadline() {
return this.m_startTime + this.m_timeout;
}
get consum() {
return TimeHelper.uptimeMS() - this.m_startTime;
}
start() {
this._startImpl();
}
process(cmd, ...args) {
this.m_lastActiveTime = TimeHelper.uptimeMS();
this._processImpl(cmd, ...args);
}
wakeUp() {
let now = TimeHelper.uptimeMS();
if (now - this.m_startTime > this.m_timeout) {
this._onComplete(DHTResult.TIMEOUT);
return;
}
if (now - this.m_lastActiveTime > this.m_maxIdleTime) {
this.m_lastActiveTime = now;
this._retry();
}
}
stop() {
this._stopImpl();
this._onComplete(DHTResult.STOPPED);
}
get bucket() {
return this.m_owner.bucket;
}
get packageFactory() {
return this.m_owner.packageFactory;
}
get packageSender() {
return this.m_owner.packageSender;
}
get distributedValueTable() {
return this.m_owner.distributedValueTable;
}
get servicePath() {
return this.m_owner.servicePath;
}
addCallback(callback) {
this.m_callbackList.push(callback);
}
static genGlobalTaskID(peerid, taskid) {
return `@pid:${peerid}@tid:${taskid}`;
}
_retry() {
this._retryImpl();
}
_onComplete(result) {
this.m_isComplete = true;
this.m_owner.onTaskComplete(this);
this._onCompleteImpl(result);
setImmediate(() => this.m_callbackList = []);
}
_callback(...args) {
this.m_callbackList.forEach(callback => setImmediate(() => callback(...args)));
}
// override 子类必须明确重载下列函数以明确行为
_startImpl() {
throw new Error('Task._startImpl it must be override.');
}
_stopImpl() {
throw new Error('Task._stopImpl it must be override.');
}
_processImpl() {
throw new Error('Task._processImpl it must be override.');
}
_retryImpl() {
throw new Error('Task._retryImpl it must be override.');
}
_onCompleteImpl(result) {
throw new Error('Task._onCompleteImpl it must be override.');
}
}
module.exports = Task;
|
//This utility makes a video element "responsive"
//by manipulating it´s source elements based on the screen size
class ResponsiveVideo {
constructor(id, sources) {
//Getting native video element
this.videoEl = document.getElementById(id);
//Sorting each source sizes array descendingly by size maxWidth
for (const source of sources) {
source.sizes.sort((prevSize, thisSize) => thisSize.maxWidth - prevSize.maxWidth);
}
//Keeping track of video sources
this.sources = sources;
//Whenever window is resized, source elements of the video will get updated
window.addEventListener('resize', () => {
this.update();
})
//Initializing the source elements by calling the update function on page load
this.update();
}
update() {
//Getting current screen width
const currentWidth = document.documentElement.clientWidth;
//Strings representing each source element will be pushed into this array
let currentSources = [];
//For each source in source config of the video
for (const source of this.sources) {
//Getting sorted array of all suported sizes (f.e [INFINITY, 1200, 800, 500])
// -> 1st size (index 0): 1200 - INFINITY, 2nd size (index 1): 800 - 1200, etc
const sourceSizes = source.sizes.map(size => size.maxWidth);
//Getting first index for which the current window size is greater than specified size
let currentSizeId = sourceSizes.findIndex((size, id) => (size <= currentWidth));
//If the current window size is smaller than the smallest specified size, using size array length (so the last element gets used after subtracting 1)
if (currentSizeId === -1) {
currentSizeId = sourceSizes.length;
}
//Creating source string for adequate size
//Subtracting currentSizeId by 1 because of transformation (when source size index 1 fullfills relation size <= currentWidth, the source size index 0 (first size) must be used)
currentSources.push(this.createSource(source, currentSizeId - 1));
}
//Adding fallback text
currentSources.push('Your browser does not support HTML5 video')
//Joining all sources into a string
const videoElInner = currentSources.join('');
//If the source string did not change this update cycle, returning
if (this.lastSourceString === videoElInner) {
return;
}
//Cloning video element
const newVideo = this.videoEl.cloneNode(true);
//Setting sources for the video clone
newVideo.innerHTML = videoElInner;
//Replacing native video element with its clone
this.videoEl.parentElement.appendChild(newVideo);
this.videoEl.parentElement.removeChild(this.videoEl);
//Updating video element hook
this.videoEl = newVideo;
//Saving this source string, so it can be used for optimalization next update cycle
this.lastSourceString = videoElInner;
}
//Creates string source for given source and its size id
//f.e <source src="img/movie.mov" type="video/quicktime">
createSource(source, id) {
return `<source src="${source.filePath}${source.sizes[id].name}.${source.extension}" type="${source.type}">`
}
}
export default ResponsiveVideo;
|
/**
* Main route definitions
*/
var path = require('path')
var image = require('../controllers/image')
module.exports = function(app) {
// Index route
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, '../src/index.html'))
})
// Image processing endpoints
app.get('/images', image.get)
app.post('/images', image.post)
app.get('/music/:song', function(req, res) {
var song = req.params.song
if (!song) {
return res.send(404)
}
res.sendFile(path.join(__dirname, '../music/' + song + '.mp3'))
})
}
|
/**
* Created by Milos on 31.1.2015..
*/
var mongoose = require("mongoose");
var systemModel = mongoose.model("system", {
flag: String,
time: String,
data: String,
created: {
type: Date,
default: Date.now
}
}, "system");
module.exports = systemModel;
|
// @flow
import React from 'react'
import { withState } from 'recompose'
import { storiesOf } from '@kadira/storybook'
import Tabs from './'
const items = [
{
icon: 'fa-th-large',
label: 'Grid',
},
{
icon: 'fa-table',
label: 'Table',
},
{
icon: 'fa-list',
label: 'List',
},
]
const MyTabs = withState('selected', 'select', 0)(
({
className,
selected,
select,
}: {
className?: string,
selected: number,
select: (selected: number) => void,
}) => (
<Tabs
className={className}
selected={selected}
select={select}
items={items}
/>
),
)
storiesOf('Tabs', module)
.add('default', () => (
<div>
<div className="heading">Default</div>
<MyTabs />
<div className="heading">Small & center</div>
<MyTabs className="is-small is-centered" />
<div className="heading">Toggled</div>
<MyTabs className="is-toggle" />
</div>
))
|
var express = require('express');
var router = express.Router();
var items = [];
for(i = 0; i < 10; i++) {
items[i] = {"id" : i,
"mensaje": "Hola esta es la descripcion: " + i}
}
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/api/', function(req, res, next) {
res.json(items);
});
module.exports = router;
|
import React, { useCallback, useContext } from "react";
import { withRouter, Redirect } from "react-router";
import app from "./firebaseapp.js";
import { AuthContext } from "./Auth.js";
import { makeStyles } from '@material-ui/core/styles';
import { Link } from 'react-router-dom'
import 'antd/dist/antd.css';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import { Form, Input, Button, Checkbox } from 'antd';
import 'antd/dist/antd.css';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
},
}));
const RemoveUsers = ({ history, users }) => {
const classes = useStyles();
const layout = {
labelCol: {
span: 8,
},
wrapperCol: {
span: 40,
},
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 50,
},
};
const handleRemoveUsers = useCallback(
//TO IMPLEMENT; users is a prop which is a list of emails that should be removed
async event => {
},
[history]
);
const { currentUser } = useContext(AuthContext);
return (
<div>
<br></br>
<Grid container spacing={3}>
<Grid item xs>
</Grid>
<Grid item xs={8} sm={8} style={{height: "200px"}}>
<br></br>
<h2 style={{
display: "flex",
justifyContent: "center",
alignItems: "center", textAlign: "center"}}> Are you sure you want to remove these users? </h2>
<Form {...layout}
name="basic"
initialValues={{
remember: true,
}}
onFinish={handleRemoveUsers}
>
<Grid container spacing={0}>
<Grid item xs={1}> </Grid>
<Grid item xs={10}>
<Form.Item style = {{width: "100%", borderRadius: "5px"}} >
<Button type="primary" htmlType="submit" style = {{width: "100%", borderRadius: "5px"}}>
Yes
</Button>
</Form.Item>
</Grid>
</Grid>
</Form>
</Grid>
<Grid item xs>
</Grid>
</Grid>
</div>
);
};
export default RemoveUsers
|
import React, { Component } from 'react';
import { Button } from 'reactstrap';
import './App.css';
import './Numbers/Numbers.css'
import Number from './Numbers/Numbers.js'
import 'bootstrap/dist/css/bootstrap.min.css';
class App extends Component {
state = {
number: []
};
getRandomNumbers = () => {
let arr = [];
while (arr.length < 5) {
const number = Math.floor(Math.random() * (36 - 5) + 5);
console.log(number);
if(arr.indexOf(number) === -1){
arr.push(number);
}
}
arr.sort((a, b) => a - b);
this.setState({
number: arr
});
};
onClickNum =() => {
this.getRandomNumbers();
};
render() {
return (
<div className={'Container'}>
<Button onClick={this.onClickNum} className="btn" color="warning">Click... New numbers!</Button>
<div className={'NumberDiv'}>
{
this.state.number.map((numbers, index) => {
return(
<Number
key={index}
number={numbers}
/>
)
})
}
</div>
</div>
);
}
}
export default App;
|
import Dice1 from "./images/Dice-1.png";
import Dice2 from "./images/Dice-2.png";
import Dice3 from "./images/Dice-3.png";
import Dice4 from "./images/Dice-4.png";
import Dice5 from "./images/Dice-5.png";
import Dice6 from "./images/Dice-6.png";
import Dice7 from "./images/Dice-7.png";
import Dice8 from "./images/Dice-8.png";
export default function Status() {
// const [useColor, setUseColor] = useState();
function changeNFT(color) {
const rows = ["row1", "row2", "row3", "row4"];
for (var i = 0; i < 4; i++) {
var list = document
.getElementById(rows[i])
.getElementsByClassName("element");
var listLength = list.length;
for (var j = 0; j < listLength; j++) {
list[j].classList.add(color);
}
}
}
return (
<div className="board-screen-child" id="status">
<div className="element">
<h2>My Assets </h2>
<div className="userNFT">
<img onClick={() => changeNFT("platinum")} src={Dice1} />
<img onClick={() => changeNFT("sapphire")} src={Dice2} />
<img onClick={() => changeNFT("ruby")} src={Dice3} />
<img onClick={() => changeNFT("emerald")} src={Dice4} />
<img onClick={() => changeNFT("amethyst")} src={Dice5} />
<img onClick={() => changeNFT("obsidian")} src={Dice6} />
<img onClick={() => changeNFT("citrine")} src={Dice7} />
<img onClick={() => changeNFT("diamond")} src={Dice8} />
</div>
</div>
</div>
);
}
|
import React from 'react'
import { View, StyleSheet, Text, TouchableOpacity } from 'react-native'
const ListItem = ({ record }) => {
return (
<TouchableOpacity>
<View style={styles.entry} >
<Text style={styles.col}>{record.created_at}</Text>
<Text style={styles.col}>{record.description}</Text>
<Text style={styles.col}>{record.amount}pts</Text>
</View>
</TouchableOpacity>
)
}
const styles = StyleSheet.create({
entry: {
flexDirection: 'row',
width: 300,
backgroundColor: '#fcfcfc',
paddingVertical: 10,
paddingHorizontal: 15,
justifyContent: 'space-between',
alignItems: 'center',
borderRadius: 15,
marginBottom: 20
},
col: {
fontSize: 15
}
});
export default ListItem
|
const Particle = require('particle-api-js');
const path = require('path');
class ControlDeckParticleToggle {
constructor(streamDeck, buttonId, options) {
this.particle = new Particle();
this.statusVariable = options.status_variable;
this.status = null;
this.buttonId = buttonId;
this.streamDeck = streamDeck;
this.particleId = options.particle_id;
this.onFunction = options.on_function;
this.offFunction = options.off_function;
if (options.on_icon) {
this.onIconPath = path.resolve(
path.dirname(require.main.filename),
options.on_icon
);
}
if (options.off_icon) {
this.offIconPath = path.resolve(
path.dirname(require.main.filename),
options.off_icon
);
}
this._getStatus();
setInterval(() => {
this._getStatus();
}, 5000);
this.streamDeck.on('up', keyIndex => {
if (keyIndex === this.buttonId) {
this._setStatus(!this.status);
}
});
}
_getStatus() {
this.particle
.getVariable({
name: this.statusVariable,
deviceId: this.particleId,
auth: process.env.PARTICLE_LOGIN_TOKEN
})
.then(data => {
this._setStatus(data.body.result);
});
}
_setStatus(newStatus) {
if (this.status !== null && this.status !== newStatus) {
const functionToCall = newStatus ? this.onFunction : this.offFunction;
this.particle.callFunction({
name: functionToCall,
deviceId: this.particleId,
auth: process.env.PARTICLE_LOGIN_TOKEN
});
}
this.status = newStatus;
this._updateStreamDeck();
}
_updateStreamDeck() {
if (this.status) {
this.onIconPath
? this.streamDeck.fillImageFromFile(this.buttonId, this.onIconPath)
: this.streamDeck.fillColor(this.buttonId, 0, 255, 0);
} else {
this.offIconPath
? this.streamDeck.fillImageFromFile(this.buttonId, this.offIconPath)
: this.streamDeck.fillColor(this.buttonId, 200, 200, 200);
}
}
}
module.exports = ControlDeckParticleToggle;
|
module.exports = {
getQuotation: 'https://doulaig.oss-cn-hangzhou.aliyuncs.com/boboswap/assetInfo.json',//行情
getRiseFall:'https://api.coingecko.com/api/v3/coins/markets?',//行情24H涨跌幅
}
|
// import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import * as CONSTANTS from './constants'
export function getWidth (spriteId) {
return ReactDOM.findDOMNode(
document.getElementById(spriteId)
).getBoundingClientRect().width
}
export function getHeight (spriteId) {
return ReactDOM.findDOMNode(
document.getElementById(spriteId)
).getBoundingClientRect().height
}
export function getStyle (spriteId) {
return ReactDOM.findDOMNode(document.getElementById(spriteId)).style
}
export function handleKeyDown (e, ...movementQueue) {
let [...queue] = movementQueue
let keyIndex = Object.values(CONSTANTS.KEY_VALUES).indexOf(e.keyCode)
if (e.keyCode === CONSTANTS.UP_ARROW || e.keyCode === CONSTANTS.DOWN_ARROW) {
e.preventDefault()
}
if (keyIndex > -1) {
e.preventDefault()
let movement = Object.keys(CONSTANTS.KEY_VALUES)[keyIndex]
let ableToPushToQueue = true
for (let i in queue) {
if (queue[i] === movement) {
ableToPushToQueue = false
}
}
if (ableToPushToQueue) {
if (movement === 'SPACE_BAR') {
queue.unshift(movement)
} else {
queue.push(movement)
}
}
return queue
}
}
export function handleKeyUp (e, ...movementQueue) {
let [...queue] = movementQueue
let keyIndex = Object.values(CONSTANTS.KEY_VALUES).indexOf(e.keyCode)
if (keyIndex > -1) {
e.preventDefault()
let movement = Object.keys(CONSTANTS.KEY_VALUES)[keyIndex]
for (let i in queue) {
if (queue[i] === movement) {
queue.splice(i, 1)
}
}
return queue
}
}
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Signup from '../views/Signup.vue'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'
import Immobile from '../views/Immobile.vue'
import NewProperty from '../views/PropertyRegistration.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/signup',
name: 'Signup',
component: Signup
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/meus-imoveis',
name: 'Dashboard',
component: Dashboard
},
{
path: '/immobile/:id',
name: 'Immobile',
component: Immobile
},
{
path: '/new-property',
name: 'NewProperty',
component: NewProperty
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
|
var bcache_8c =
[
[ "BodyCache", "structBodyCache.html", "structBodyCache" ],
[ "bcache_path", "bcache_8c.html#a5a6da9a92e635c11bf3af21611c6ea5f", null ],
[ "mutt_bcache_move", "bcache_8c.html#affefecb14cd62cc08faf0a6ba19b52c0", null ],
[ "mutt_bcache_open", "bcache_8c.html#a3eba1237cb1746acad5efa0a123a892c", null ],
[ "mutt_bcache_close", "bcache_8c.html#af3a22202fb2135dfb1081cb6e6c5fecb", null ],
[ "mutt_bcache_get", "bcache_8c.html#aecd453abbb62e97d92f9b39a469c8324", null ],
[ "mutt_bcache_put", "bcache_8c.html#acf998afceb34defdd8d6be4b652ce729", null ],
[ "mutt_bcache_commit", "bcache_8c.html#a5125c4a660fa9267a94153695c44a4f0", null ],
[ "mutt_bcache_del", "bcache_8c.html#a81a73e04de0e74abec304abb57f9a21a", null ],
[ "mutt_bcache_exists", "bcache_8c.html#a0fd8cd0e88c27788e6268674c71c7879", null ],
[ "mutt_bcache_list", "bcache_8c.html#a61b6432fa4ef33ea232dad524cf907bb", null ],
[ "C_MessageCacheClean", "bcache_8c.html#a0bf86733ff0fefb7879f1d75bb44415a", null ],
[ "C_MessageCachedir", "bcache_8c.html#a747ba79497d0a085ea36885146f187f4", null ]
];
|
/* Chain filter and map to collect the ids of videos that have a rating of 5.0 */
var newReleasesMov = [
{
"id": 1,
"title": "Hard",
"boxart": "Hard.jpg",
"uri": "http://vikask/movies/1",
"rating": [4.0],
"bookmark": []
},
{
"id": 2,
"title": "Bad",
"boxart": "Bad.jpg",
"uri": "http://vikask/movies/2",
"rating": [5.0],
"bookmark": [{ id: 1, time: 2 }]
},
{
"id": 3,
"title": "Cham",
"boxart": "Cham.jpg",
"uri": "http://vikask/movies/3",
"rating": [4.0],
"bookmark": []
},
{
"id": 4,
"title": "Fra",
"boxart": "Fra.jpg",
"uri": "http://vikask/movies/4",
"rating": [5.0],
"bookmark": [{ id: 4, time: 6 }]
}
];
newReleases.filter(video => {
return video.rating === 5
}).map(video=>{
console.log(video.id);
})
|
import Vue from 'vue'
import VueRouter from 'vue-router' // eslint-disable-line import/no-extraneous-dependencies
import VueModal from 'vue-js-modal'
import VueI18n from 'vue-i18n'
import SubscribeModal from './SubscribeModal.vue'
import notificationsService from '../../services/services/notifications'
import subscriptionsApi from '../../services/api/subscriptions'
jest.mock('../../services/utils/screen/screen-utils', () => ({ screenWidth: 200, PHONE_PORTRAIT_TO_LANDSCAPE: 600 }))
describe.skip('Component | SubscribeModal.vue', () => {
let wrapper
const email = 'pierre@recontact.me'
let localVue
beforeEach(() => {
console.warn = jest.fn()
localVue = createLocalVue()
localVue.use(VueModal)
localVue.use(VueI18n)
localVue.use(VueRouter)
wrapper = shallowMount(SubscribeModal, {
localVue,
data() {
return {
email,
error: 'error message',
}
},
})
})
describe('template', () => {
it('should match snapshot', () => {
expect(wrapper).toMatchSnapshot()
})
})
/* xdescribe('rendering', () => {
it('should display the modal', () => {
wrapper.$modal.show('subscribe-modal')
return Vue.nextTick().then(() => {
expect(wrapper.find('.subscribe-modal')).toBeDefined()
})
})
}) */
describe('#beforeOpen', () => {
it('should reset email', () => {
wrapper.vm.email = 'Coucou@contact.me'
wrapper.vm.beforeOpen()
expect(wrapper.vm.email).toBeNull()
})
it('should remove error', () => {
wrapper.vm.error = 'C\'est un problème'
wrapper.vm.beforeOpen()
expect(wrapper.vm.error).toBeNull()
})
})
describe('#opened', () => {
beforeEach(() => {
wrapper.vm._focusOnInput = jest.fn()
wrapper.vm._closeModal = jest.fn()
})
it('should focusOnInput', () => {
wrapper.vm.opened()
expect(wrapper.vm._focusOnInput).toHaveBeenCalledWith()
})
it('should close on escape key', () => {
wrapper.vm.opened()
const e = document.createEvent('Events')
e.initEvent('keydown', true, true)
e.keyCode = 27
document.dispatchEvent(e)
return Vue.nextTick().then(() => {
expect(wrapper.vm._closeModal).toHaveBeenCalledWith()
})
})
it('should not close on any other key than space', () => {
wrapper.vm.opened()
const e = document.createEvent('Events')
e.initEvent('keydown', true, true)
e.keyCode = 13
document.dispatchEvent(e)
return Vue.nextTick().then(() => {
expect(wrapper.vm._closeModal).not.toHaveBeenCalled()
})
})
})
/* xdescribe('#_focusOnInput', () => {
it.skip('should focus on input subscribe content', done => {
wrapper.$modal.show('subscribe-modal')
setTimeout(() => {
const inputSubscribe = wrapper.find('input#subscribe-content')
// expect(inputSubscribe).to.have.focus()
done()
}, 100)
})
}) */
describe('#sendSubscription', () => {
beforeEach(() => {
subscriptionsApi.subscribe = jest.fn()
notificationsService.information = jest.fn()
subscriptionsApi.subscribe.mockResolvedValue({})
})
it('should remove error', () => {
wrapper.vm.error = 'C\'est un problème'
wrapper.vm.sendSubscription()
expect(wrapper.vm.error).toBeNull()
})
describe('when email is empty', () => {
it('should set error', () => {
wrapper.vm.email = ''
wrapper.vm.sendSubscription()
expect(wrapper.vm.error).toBe('emailError')
})
it('should not call sendSubscription', () => {
wrapper.vm.email = ''
wrapper.vm.sendSubscription()
expect(subscriptionsApi.subscribe).not.toHaveBeenCalled()
})
})
describe('when email does not follow good pattern', () => {
it('should set error', () => {
wrapper.vm.email = 'pierrerecontact'
wrapper.vm.sendSubscription()
expect(wrapper.vm.error).toBe('emailError')
})
it('should not call sendSubscription', () => {
wrapper.vm.email = 'pierre@recontact.m'
wrapper.vm.sendSubscription()
expect(subscriptionsApi.subscribe).not.toHaveBeenCalled()
})
})
it('should call the API with good params', () => {
wrapper.vm.sendSubscription(email)
expect(subscriptionsApi.subscribe).toHaveBeenCalledWith(email)
})
it('should display success notification', () => {
notificationsService.information.mockResolvedValue({})
wrapper.vm.sendSubscription()
return Vue.nextTick().then(() => {
const message = 'subscriptionSuccess'
expect(notificationsService.information).toHaveBeenCalledWith(message)
})
})
/* xit('should close modal', () => {
wrapper.$modal.show('subscribe-modal')
wrapper.vm.email = 'email@recontact.me'
wrapper.vm.sendSubscription()
return Vue.nextTick().then(() => {
expect(wrapper.find('.subscribe-modal')).not.to.exist
})
}) */
// describe('when sendSubscription fails', () => {
// beforeEach(() => {
// // wrapper.$modal.show('subscribe-modal');
// wrapper.vm.email = 'email@recontact.me'
// subscriptionsApi.subscribe.mockRejectedValue(new Error('e'))
// })
//
// // xit('should not close modal', () => {
// // wrapper.vm.sendSubscription()
// //
// // return Vue.nextTick().then(() => {
// // expect(wrapper.find('.subscribe-modal')).to.exist
// // })
// // })
// //
// // xit('should set error', () => {
// // wrapper.vm.sendSubscription()
// //
// // return Vue.nextTick().then(() => {
// // expect(wrapper.vm.error).toEqual('subscriptionError')
// // })
// // })
// })
})
/* xdescribe('#cancelSubscription', () => {
it('should close modal', () => {
wrapper.$modal.show('subscribe-modal')
wrapper.cancelSubscription()
return Vue.nextTick().then(() => {
expect(wrapper.find('.subscribe-modal')).not.to.exist
})
})
}) */
/* it.skip('should sendSubscription on click on "send" button', () => {
wrapper.$modal.show('subscribe-modal')
sinon.stub(component, 'sendSubscription')
return Vue.nextTick().then(() => {
const myButton = wrapper.find('.subscribe-modal__action--send')
myButton.click()
expect(wrapper.sendSubscription).toHaveBeenCalled
})
}) */
/* it.skip('should cancelSubscription on click on "cancel" button', () => {
wrapper.$modal.show('subscribe-modal')
sinon.stub(component, 'cancelSubscription')
return Vue.nextTick().then(() => {
const myButton = wrapper.find('.subscribe-modal__action--cancel')
myButton.click()
expect(wrapper.cancelSubscription).toHaveBeenCalled
})
}) */
describe('locales', () => {
const languages = Object.keys(SubscribeModal.i18n.messages)
it('contains 2 languages', () => {
expect(languages).toHaveLength(2)
expect(languages).toEqual(['fr', 'en'])
})
describe('each language', () => {
describe('fr', () => {
const locales = Object.keys(SubscribeModal.i18n.messages.fr)
it('contains 8 locales', () => {
expect(locales).toHaveLength(8)
expect(locales).toEqual([
'subscribe',
'modalText',
'email',
'confirm',
'cancel',
'emailError',
'subscriptionError',
'subscriptionSuccess',
])
})
})
describe('en', () => {
const locales = Object.keys(SubscribeModal.i18n.messages.en)
it('contains 8 locales', () => {
expect(locales).toHaveLength(8)
expect(locales).toEqual([
'subscribe',
'modalText',
'email',
'confirm',
'cancel',
'emailError',
'subscriptionError',
'subscriptionSuccess',
])
})
})
})
})
})
|
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// Actions
import * as gridActions from '../actions/grid.actions';
// Components
import Grid from '../components/Grid';
import Header from '../components/Header';
import Footer from '../components/Footer';
// Component (containers)
import Controllers from './Controllers';
import Shapes from './Shapes';
class Home extends React.PureComponent {
componentDidMount() {
this.props.actions.grid.init();
}
render() {
const { grid } = this.props.data;
const { toggleCell } = this.props.actions.grid;
return (
<div>
<Header />
<div className={'gf-panel-container'} >
<div>
<p>Game's Controllers</p>
<Controllers />
</div>
<div>
<p>Game's Shapes</p>
<Shapes />
</div>
</div>
<div className={'gf-grid-container'} >
<Grid rows={grid} toggleCell={toggleCell} />
</div>
<Footer />
</div>
);
}
}
Home.propTypes = {
data: React.PropTypes.shape({
grid: React.PropTypes.array,
}).isRequired,
actions: React.PropTypes.shape({
grid: React.PropTypes.object,
}).isRequired,
};
function mapDispatchToProps(dispatch) {
return {
actions: {
grid: bindActionCreators(gridActions, dispatch),
},
};
}
function mapStateToProps(state) {
return { data: { grid: state.grid } };
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);
|
export class AbstractView {
/** @type {HTMLElement} */
rootElement;
/** @type {Map<string, HTMLElement>} */
DOM;
/**
*
* @param {HTMLElement} rootElement
*
*/
constructor(rootElement) {
this.rootElement = rootElement;
this.DOM = new Map();
}
async init() {
throw Error("Not implemented.");
}
/**
*
* @param {string} key
*
*/
findDOMById(key) {
if (!this.DOM.has(key)) return;
return this.DOM.get(key);
}
/**
*
* @param {string} key
* @param {HTMLElement} element
*
*/
setToDom(key, element) {
this.DOM.set(key, element);
}
/**
*
* @param {{[key: string]: HTMLElement}} arg
*/
setAllToDom(arg) {
Object.entries(arg).forEach(([key, val]) => this.setToDom(key, val));
}
}
|
import {
LOGIN_TYPE,
REGISTER_TYPE,
CURRENT_USER,
LOGOUT
} from '../action-type';
import axios from '../../utils/middleware';
export const loginUser = payloads => dispatch => axios.post('/login',
{ payloads }).then((res) => {
if (res.data['success']) {
dispatch({ type: LOGIN_TYPE, payload:res.data });
}
return res.data;
}).catch((error) => {
console.log('catch login err',error)
const res = { success:false, message: 'Something went wrong,please try again' };
return res;
});
export const register = payloads => dispatch => axios.post('/register',
{ payloads }).then((res) => {
if (res['data'].code==200) {
dispatch({type: REGISTER_TYPE, payload:res.data });
}
return res.data
}).catch((error) => {
const res = { message: error.response.data };
return res;
});
export const logout = payloads => dispatch => new Promise((resolve, reject)=>{
dispatch({type: LOGOUT })
resolve()
})
export const checkauth = payloads => dispatch => axios.get('/checkauth',
{ payloads }).then((res) => {
if (res['data'].success) {
dispatch({type: CURRENT_USER, payload:res['data']['data'] });
}
return res;
}).catch((error) => {
const res = { success : false, message: 'Something went wrong,please try again' };
return res;
});
export const getmetaData = payloads => dispatch => axios.get('/metas',
{ payloads }).then((res) => {
return res;
}).catch((error) => {
const res = { success : false, message: 'Something went wrong,please try again' };
return res;
});
export const forgot_password = payloads => dispatch => axios.post('/forgotpassword?mobile=true',
{ payloads }).then((res) => {
console.log('forgot password re',res.data)
return res.data;
}).catch((error) => {
const res = { message: 'Something went wrong,please try again' };
return res;
});
|
export const celToFahr = (arg) => {
if (typeof arg !== "number") {
throw new Error("Input must be a number");
}
const result = (arg * 9) / 5 + 32;
return result;
};
export const fahrToCel = (arg) => {
if (typeof arg !== "number") {
throw new Error("Input must be a number");
}
const result = (arg - 32) * (5 / 9);
return result;
};
export const kelToCel = (arg) => {
if (typeof arg !== "number") {
throw new Error("Input must be a number");
}
const result = arg - 273.15;
return result;
};
export const celToKel = (arg) => {
if (typeof arg !== "number") {
throw new Error("Input must be a number");
}
const result = arg + 273.15;
return result;
};
export const fahrToKel = (arg) => {
if (typeof arg !== "number") {
throw new Error("Input must be a number");
}
const result = (arg - 32) * (5 / 9) + 273.15;
return result;
};
export const kelToFahr = (arg) => {
if (typeof arg !== "number") {
throw new Error("Input must be a number");
}
const result = (arg - 273.15) * (9 / 5) + 32;
return result;
};
|
var bunyan = require('bunyan');
var log = bunyan.createLogger({name: 'kga-web/db-updater'});
var endpoint = process.env.ENDPOINTS_DBUPDATER_SOCKET;
var maximum_message_size = process.env.ENDPOINTS_DBUPDATER_MAXMESSAGESIZE;
var zmq = require('zmq');
log.info('ZMQ', zmq.version);
log.info('Starting db-updater configured to provide endpoint',endpoint);
log.info('Maximum message size', maximum_message_size);
var responder = zmq.socket('rep', { ZMQ_MAXMSGSIZE: maximum_message_size });
responder.on('message', function(request) {
try {
var messageData = JSON.parse(request.toString());
log.info("Message received", messageData);
//responder.send("{}");
responder.send(JSON.stringify({text: 'World', counter: messageData.counter }));
} catch (syntaxError){
log.error("Parsing of message failed", { message: request.toString(), error: syntaxError });
responder.send(JSON.stringify({
status: "Error",
message: syntaxError.toString()
}));
}
});
responder.bind(endpoint, function(err){
if (err) {
log.error("Failed initializing message receiver", { error: err });
process.exit(1);
} else {
log.info("Listening on", endpoint);
}
});
process.on('SIGINT', function() {
log.info('Received SIGINT, closing socket', endpoint);
responder.close();
process.exit(0);
})
|
import $ from 'jquery';
/**
* Base64 加密函数
* @param string
*/
export const Base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function (e) {
var t = "";
var n, r, i, s, o, u, a;
var f = 0;
e = Base64._utf8_encode(e);
while (f < e.length) {
n = e.charCodeAt(f++);
r = e.charCodeAt(f++);
i = e.charCodeAt(f++);
s = n >> 2;
o = (n & 3) << 4 | r >> 4;
u = (r & 15) << 2 | i >> 6;
a = i & 63;
if (isNaN(r)) {
u = a = 64
} else if (isNaN(i)) {
a = 64
}
t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
}
return t
},
decode: function (e) {
var t = "";
var n, r, i;
var s, o, u, a;
var f = 0;
if (e) {
e = e.replace(/[^A-Za-z0-9+/=]/g, "");
while (f < e.length) {
s = this._keyStr.indexOf(e.charAt(f++));
o = this._keyStr.indexOf(e.charAt(f++));
u = this._keyStr.indexOf(e.charAt(f++));
a = this._keyStr.indexOf(e.charAt(f++));
n = s << 2 | o >> 4;
r = (o & 15) << 4 | u >> 2;
i = (u & 3) << 6 | a;
t = t + String.fromCharCode(n);
if (u != 64) {
t = t + String.fromCharCode(r)
}
if (a != 64) {
t = t + String.fromCharCode(i)
}
}
t = Base64._utf8_decode(t);
}
return t
}, _utf8_encode: function (e) {
e = e.replace(/rn/g, "n");
var t = "";
for (var n = 0; n < e.length; n++) {
var r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r)
} else if (r > 127 && r < 2048) {
t += String.fromCharCode(r >> 6 | 192);
t += String.fromCharCode(r & 63 | 128)
} else {
t += String.fromCharCode(r >> 12 | 224);
t += String.fromCharCode(r >> 6 & 63 | 128);
t += String.fromCharCode(r & 63 | 128)
}
}
return t
}, _utf8_decode: function (e) {
var t = "";
var n = 0;
var c2 = 0;
var c3 = 0;
var r = 0;
// var r = c1 = c2 = 0;
while (n < e.length) {
r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r);
n++
} else if (r > 191 && r < 224) {
c2 = e.charCodeAt(n + 1);
t += String.fromCharCode((r & 31) << 6 | c2 & 63);
n += 2
} else {
c2 = e.charCodeAt(n + 1);
c3 = e.charCodeAt(n + 2);
t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
n += 3
}
}
return t
}
}
/**
* 附件下载
*/
export const downloadFile = (url, downloadFileName) => {
const fileName = typeof downloadFile === 'undefined' ? 'file.txt' : downloadFileName;
const form = $('<form></form>')
.attr('action', url)
.attr('method', 'POST')
form.append(
$('<input/>')
.attr('type', 'hidden')
.attr('name', 'fileName')
.attr('value', fileName)
);
form.appendTo('body')
.submit()
.remove();
}
|
'use strict';
/**
* @ngdoc service
* @name dssiFrontApp.KeyCondition
* @description
* # KeyCondition
* Factory in the dssiFrontApp.
*/
angular.module('dssiFrontApp')
.factory('KeyCondition', function ($resource, urls) {
var service = $resource(urls.BASE_API + '/key-conditions/:id', null,
{
'update': { method:'PUT' }
});
return service;
});
|
const BaseModel = require('./BaseModel');
const db = require('../dbConfig');
class UserModel extends BaseModel {
constructor(table) {
super(table)
}
findBy(email) {
return db('users_organizations')
.where({ user_email: email })
.select('organizations.*')
.join('organizations', 'organizations.id', 'users_organizations.organization_id')
.then(organizations => {
if (!organizations.length) {
return null;
}
return super._findBy({ email })
.first()
.then(user => {
return db('roles')
.where({ id: user.role_id })
.first()
.then(role => {
delete user.role_id;
user.organizations = organizations;
user.role = role
return user;
})
})
})
}
add(data) {
const { organization_id, invite_token, ...userData } = data;
const user_org = { user_email: userData.email, organization_id };
return db('users')
.insert(userData, 'email')
.then(user_emails => {
const [user_email] = user_emails;
return db('invite_tokens')
.insert({ id: invite_token }, 'id')
.then(() => {
return db('users_organizations')
.insert(user_org)
.then(() => {
return this.findBy(user_email);
})
})
})
}
}
module.exports = UserModel;
|
// Here a theme is defined. This theme is passed to the entire site (via layout.js) so the individual parts of the theme object
// can be accessed in each styled component.
export const theme = {
colors: {
main: 'thistle', //used in header
primaryAccent: 'linen', //used for thumbnails on homepage and as price background
secondaryAccent: 'gainsboro', //used for header border and item buttons
}
};
|
import React from 'react'
import '../css/drawerheader.css'
function DrawerHeader({ close }) {
return (
<div className='drawer'>
<div className="drawer__header">
<p>GIỎ HÀNG</p>
<CloseIcon className='drawer__buttonclose' onClick={close()}></CloseIcon>
</div>
</div>
)
}
export default DrawerHeader
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const config_1 = require("../config/config");
// =================================================================
//-- Verificar token
// =================================================================
exports.verificarToken = function (req, resp, next) {
var token = req.query.token;
jsonwebtoken_1.default.verify(token, config_1.SEED, (error, decoded) => {
if (error) {
return resp.status(401).json({
ok: false,
mensaje: 'Token incorrecto',
errors: error,
token: token,
decoded: decoded
});
}
req.usuario = decoded.usuario;
next();
});
};
// =================================================================
//-- Verificar si usuario es maestro o administrador
// =================================================================
exports.verificarUsuario = function (req, resp, next) {
var usuario = req.usuario;
if (usuario.role === 'maestro' || usuario.role === 'administrador') {
next();
return;
}
else {
return resp.status(401).json({
mensaje: 'No puede realizar el movimiento, debido a que no es un maestro o administrador de la plataforma'
});
}
};
// =================================================================
//-- Verificar si usuario es exactemente administrador
// =================================================================
exports.verificarAdmin = function (req, resp, next) {
var usuario = req.usuario;
if (usuario.role === 'administrador') {
next();
return;
}
else {
return resp.status(401).json({
mensaje: 'No puede realizar el movimiento, debido a que no es un administrador de la plataforma'
});
}
};
// =================================================================
//-- Verificar si es el mismo usuario que esta editando los datos
// =================================================================
exports.MismoUsuario = function (req, resp, next) {
var usuario = req.usuario;
var id = req.params.id;
if (usuario._id === id) {
next();
}
else {
return resp.status(401).json({
mensaje: 'No puedes editar la informacion de otro usuario'
});
}
};
|
// see: http://bl.ocks.org/ameyms/9184728
var D3WRAP = { REVISION: '1' };
var colorGenerator = d3.scale.category20();
// Bar Chart Object
D3WRAP.SimpleBarChart = function(container, dataset, params) {
this.container = container;
this.dataset = dataset;
this.params = params;
var self = this;
// Provide parameter defaults if they are missing
this.barConfig = {
width : params.width || 760,
height : params.height ||340,
leftMargin : params.leftMargin || 40,
topMargin : params.topMargin || 20,
yScale : params.yScale || 150.0,
xScale : params.xScale || 20.0,
barWidth : params.barWidth || 35.0,
chartWidth: params.chartWidth || 700,
chartHeight : params.chartHeight || 300
}
// Function to adjust scales
this.adjustScales = function() {
self.yScale = d3.scale.linear()
.domain([0, d3.max(self.dataset, function(d){return d.target.count;})+10])
.range([self.barConfig.chartHeight, 0])
;
self.xScale = d3.scale.linear()
.domain([0, self.dataset.length])
.range([0, self.barConfig.chartWidth])
;
}
// Select the DOM element into which we will insert the chart
this.c1 = d3.select(container);
// Append an SVG to the DOM element with an offset from the upper left corner
this.svg1 = this.c1.append("svg")
.attr("width", this.barConfig.width)
.attr("height", this.barConfig.height)
.append("g")
.attr("transform", "translate(" + this.barConfig.leftMargin + "," + this.barConfig.topMargin + ")")
;
this.adjustScales();
// Create axes and append to SVG
this.xAxis = d3.svg.axis().scale(this.xScale).orient("bottom");
this.yAxis = d3.svg.axis().scale(this.yScale).orient("left");
this.svg1.append("g").attr("class", "xaxis axis")
.attr("transform", "translate(0," + this.barConfig.chartHeight + ")")
.call(this.xAxis)
;
this.svg1.append("g").attr("class", "yaxis axis").call(this.yAxis);
// Creation of DOM elements in SVG from initial data
this.svg1.selectAll("rect")
.data(this.dataset,function(d){return d.target.iata;})
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d,i){return self.xScale(i);})
.attr("y", function(d,i){return self.yScale(d.target.count);})
.attr("width", function(d,i){return self.barConfig.chartWidth/self.dataset.length-4;})
.attr("height", function(d,i) {return self.barConfig.chartHeight-self.yScale(d.target.count);})
.attr("fill", function(d) {return colorGenerator(d.target.count);})
;
this.svg1.selectAll("text.btext")
.data(this.dataset,function(d){return d.target.iata;})
.enter().append("text")
.attr("class", "btext")
.attr("x", function(d,i){return self.xScale(i)+5;})
.attr("y", function(d,i){return self.yScale(d.target.count)-20;})
.text(function(d,i){return d.target.iata;})
;
}
D3WRAP.SimpleBarChart.prototype = Object.create(Object.prototype);
D3WRAP.SimpleBarChart.prototype.constructor = D3WRAP.SimpleBarChart;
D3WRAP.NeedleGauge = function(container, params) {
this.container = container;
this.params = params;
this.el = d3.select(container);
}
D3WRAP.NeedleGauge.prototype = Object.create(Object.prototype);
D3WRAP.NeedleGauge.prototype.constructor = D3WRAP.NeedleGauge;
D3WRAP.NeedleGauge.prototype.setvalue = function (value) {
this.value = value;
}
|
import "../../../js/index";
import $ from "jquery";
import PartitialAjax from "django-partitialajax"
import setupCrud from "../../../js/crud";
$(function () {
PartitialAjax.initialize();
setupCrud(
PartitialAjax.getPartitialFromElement(document.getElementById("host-list-partitial")),
PartitialAjax.getPartitialFromElement(document.getElementById("host-create-button")),
".host-delete-button"
);
});
|
/* ================================================
*
* Copyright (c) 2016 Oracle and/or its affiliates. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ================================================
*/
var serverAssignedKeys = true;
function rowToJson(target) {
var jsonObject = new Object();
// Find the 'table' element
var inputCollection = target.getElementsByTagName("INPUT");
for (var i = 0; i < inputCollection.length; i++) {
var inputItem = inputCollection[i];
jsonObject[inputItem.name] = inputItem.value;
}
return jsonObject
}
function createIcon(src,alt) {
var IMG = document.createElement("IMG");
IMG.src = src
IMG.alt = alt
IMG.border = 0;
IMG.align = "absmiddle"
IMG.width = 16;
IMG.heigh = 16;
return IMG
}
function createButton(src,title) {
/*
<button id="btn.saveNewDocument" type="button" class="btn btn-default btn-med" onclick="doCreateCollection();return false;">
<img src="/XFILES/lib/icons/json_create_collection.png" alt="New Collection" border="0" align="absmiddle" width="16" height="16"/>
</button>
*/
var BUTTON = document.createElement("button");
BUTTON.className="btn btn-default btn-med"
BUTTON.type="button"
BUTTON.appendChild(createIcon(src,title));
return BUTTON
}
function createSpacer() {
SPAN = document.createElement("SPAN")
SPAN.style.width = "10px";
SPAN.style.display="inline-block";
return SPAN;
}
function createTable() {
var table = document.createElement("SPAN");
table.style.display = "table";
return table;
}
function createTableHeader() {
var header = document.createElement("SPAN");
header.style.display = "table-row"
return header;
}
function createTableRow() {
var row = document.createElement("SPAN");
row.style.display = "table-row"
return row
}
function createCell() {
var cell = document.createElement("SPAN");
cell.style.display = "table-cell";
cell.style.paddingRight = "10px";
return cell;
}
function createHeadingCell(name) {
var newHeadingCell = createCell();
newHeadingCell.appendChild(document.createTextNode(name));
return newHeadingCell;
}
function addFieldMenu(INPUT) {
/*
<div class="input-group">
<input type="text" class="form-control">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-left" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="x#">Separated link</a></li>
</ul>
</div><!-- /btn-group -->
</div><!-- /input-group -->
*/
var DIV1 = document.createElement("DIV");
DIV1.className = "input-group";
var DIV2 = document.createElement("DIV");
DIV2.className = "input-group-btn"
DIV1.appendChild(DIV2);
var BUTTON = document.createElement("BUTTON");
DIV2.appendChild(BUTTON);
BUTTON.type="button";
BUTTON.className = "btn btn-default dropdown-toggle";
BUTTON.dataset.toggle="dropdown"
var SPAN = document.createElement("SPAN");
BUTTON.appendChild(SPAN);
SPAN.className="caret";
var UL = document.createElement("UL");
DIV2.appendChild(UL);
UL.className = "dropdown-menu"
UL.role="menu"
var LI = document.createElement("LI");
UL.appendChild(LI);
var A=document.createElement("A");
LI.appendChild(A);
A.textContent="Add Field";
A.onclick = function(target) { return function() { doInsertField(target); return false }; }(INPUT);
A.href="#"
var LI = document.createElement("LI");
UL.appendChild(LI);
var A=document.createElement("A");
LI.appendChild(A);
A.textContent="Remove Field";
A.onclick = function(target) { return function() { removeField(target); return false }; }(INPUT);
A.href="#"
DIV1.appendChild(INPUT);
return DIV1;
}
function createInputCell(name) {
var INPUT = document.createElement("INPUT")
INPUT.type = "text"
INPUT.className = "form-control"
INPUT.placeholder = name;
INPUT.name = name;
var newContentCell = createCell();
newContentCell.appendChild(addFieldMenu(INPUT));
return newContentCell
}
function getCollectionName() {
var collectionList = document.getElementById("collectionList");
var collectionName = collectionList.value;
return collectionName;
}
function appendField(name) {
closeModalDialog("newFieldDialog")
var table = document.getElementById("editDocument").firstChild;
var contentRow = table.lastChild;
var headingRow = contentRow.previousSibling;
if (contentRow.childNodes.length > 3) {
contentRow.parentNode.appendChild(createTableHeader());
contentRow.parentNode.appendChild(createTableRow());
var newHeadingRow = contentRow.nextSibling;
var newContentRow = newHeadingRow.nextSibling;
headingRow = newHeadingRow;
contentRow = newContentRow;
}
headingRow.appendChild(createHeadingCell(name));
var contentCell = createInputCell(name);
contentRow.appendChild(contentCell);
contentCell.firstChild.focus();
}
function getFieldLocator(target) {
var fl = new Object();
// Find the table-cell and table-row (SPAN) containing the target element (SPAN-DIV->INPUT)
fl.contentCell = target.parentNode.parentNode;
fl.contentRow = fl.contentCell.parentNode;
fl.headingRow = fl.contentRow.previousSibling;
// Find cell's position within row.
var counter = 0;
var cell = fl.contentCell
while (cell.previousSibling != null) {
counter ++;
cell = cell.previousSibling;
}
// Find the corresponding Heading Cell
cell = fl.headingRow.firstChild
for (var i = 0; i < counter; i++) {
cell = cell.nextSibling;
}
fl.headingCell = cell;
return fl;
}
function insertField(target,name) {
// target is the 'IMG' element that was clicked on to open the field menu.
closeModalDialog("newFieldDialog");
var fl = getFieldLocator(target);
fl.headingRow.insertBefore(createHeadingCell(name),fl.headingCell);
fl.contentRow.insertBefore(createInputCell(name),fl.contentCell);
// Shuffle the remaining Content Cells forwards one position
while (fl.contentRow.childNodes.length > 4) {
if (fl.contentRow.nextSibling == null) {
fl.contentRow.parentNode.appendChild(createTableHeader());
fl.contentRow.parentNode.appendChild(createTableRow());
}
var newHeadingRow = fl.contentRow.nextSibling;
var newContentRow = newHeadingRow.nextSibling;
if (newHeadingRow.childNodes.length == 0) {
newHeadingRow.appendChild(headingRow.removeChild(fl.headingRow.lastChild));
newContentRow.appendChild(contentRow.removeChild(fl.contentRow.lastChild));
}
else {
newHeadingRow.insertBefore(fl.headingRow.removeChild(fl.headingRow.lastChild),newHeadingRow.firstChild);
newContentRow.insertBefore(fl.contentRow.removeChild(fl.contentRow.lastChild),newContentRow.firstChild);
}
fl.headingRow = newHeadingRow;
fl.contentRow = newContentRow;
}
}
function removeField(target) {
// Get the Field Locator for the target.
// target is the 'INPUT' element associated with the Menu.
var fl = getFieldLocator(target);
// Remove the Heading Cell from the Heading Row
// Remove the Conent Cell from the Content Row.
fl.headingRow.removeChild(fl.headingCell);
fl.contentRow.removeChild(fl.contentCell);
// Shuffle the remaining Content Cells backwards one position
while (fl.contentRow.nextSibling != null) {
var nextHeadingRow = fl.contentRow.nextSibling
var nextContentRow = nextHeadingRow.nextSibling;
fl.headingRow.appendChild(nextHeadingRow.removeChild(nextHeadingRow.firstChild));
fl.contentRow.appendChild(nextContentRow.removeChild(nextContentRow.firstChild));
fl.headingRow = nextHeadingRow;
fl.contentRow = nextContentRow;
}
if ((fl.headingRow.children.length == 0) && (fl.headingRow.parentNode.children.length > 2)) {
fl.headingRow.parentNode.removeChild(fl.headingRow);
fl.contentRow.parentNode.removeChild(fl.contentRow);
}
}
function resetEditDocumentForm() {
target = document.getElementById("editDocument");
target.innerHTML = "";
return target;
}
function openNewFieldDialog() {
try {
var field = document.getElementById("newFieldName");
field.value = "";
$('#newFieldDialog').modal('show')
field.focus();
}
catch (e) {
handleException('schemalessDevelopmentUI.openEditDocumentDialog',e,null);
}
}
function doInsertField(target) {
/*
**
** Prepare the New Field Dialog for an Insert Field operation.
**
*/
var createFieldButton = document.getElementById("btn.saveNewField");
createFieldButton.onclick = function(target) { return function() { insertField(target, document.getElementById("newFieldName").value); return false }; }(target);
$('#newFieldDialog').modal('show')
}
function doAppendField() {
/*
**
** Prepare the New Field Dialog for an Append Field operation.
**
*/
try {
var target = document.getElementById("editDocument");
if (target.childNodes.length == 0) {
var table = createTable();
target.appendChild(table);
table.appendChild(createTableHeader());
table.appendChild(createTableRow());
}
var createFieldButton = document.getElementById("btn.saveNewField");
createFieldButton.onclick = function(target) { return function() { appendField(document.getElementById("newFieldName").value); return false }; }(target);
$('#newFieldDialog').modal('show')
}
catch (e) {
handleException('schemalessDevelopmentUI.openEditDocumentDialog',e,null);
}
}
function clearData() {
// closeAllDialogs();
var keyList = document.getElementById("keyList");
keyList.innerHTML = "";
var documentList = document.getElementById("showDocumentList");
documentList.innerHTML = "";
}
function makeEditableDocument(target) {
// This code needs to manage Nested Objects
var inputCollection = target.getElementsByTagName("INPUT");
for (var i=0; i<inputCollection.length; i++) {
var INPUT = inputCollection[i];
INPUT.className = "form-control"
INPUT.placeholder = INPUT.name;
var cell = INPUT.parentNode;
cell.removeChild(INPUT);
cell.appendChild(addFieldMenu(INPUT));
}
var table = target.firstChild;
var header = table.firstChild
var row = table.firstChild.nextSibling
// Split input fields into rows each with at most 4 columns.
while (row.childNodes.length > 4) {
var newHeader = createTableHeader();
var newRow = createTableRow();
// At first glance this appears to be bassackwards
// Create a New Header and Content rows.
// Copy 4 elements from the front of current row
// to the newly created row. Rinse and Repeat as
// necessary.
table.insertBefore(newHeader,header)
table.insertBefore(newRow,header)
for (var i=0; i<4; i++) {
newHeader.appendChild(header.removeChild(header.firstChild));
newRow.appendChild(row.removeChild(row.firstChild));
}
}
}
function resetForm() {
clearData()
doListCollections();
}
function checkCollectionName(collectionName) {
var optionList = document.getElementById("collectionList")
for (var i=0;i < optionList.options.length; i++) {
if (optionList.options[i].value == collectionName) {
return optionList.options[i];
}
}
return null;
}
function checkNewCollection() {
var collectionList = document.getElementById("collectionList");
var newCollection = document.getElementById("newCollection");
var existingActions = document.getElementById("existingActions");
if (collectionList.value == "(new)") {
newCollection.style.display="inline-block"
existingActions.style.display="none";
}
else {
newCollection.style.display="none"
existingActions.style.display="inline-block";
}
clearData();
}
function doCreateCollection() {
var collectionName = document.getElementById("newCollectionName").value;
if ((typeof collectionName == "undefined") || (collectionName == "")) {
showErrorMessage("Please enter collection name");
return;
}
if (checkCollectionName(collectionName) != null) {
showErrorMessage("Collection Exists");
return;
}
var postCreateAction = function(XHR,URL) {
showInformationMessage ("Create Collection Complete. Status = " + XHR.status + " (" + XHR.statusText + ")");
document.getElementById("newCollectionName").value = "";
doListCollections();
}
restAPI.createCollection(collectionName,null,postCreateAction);
}
function doDeleteCollection() {
var callback = function(XHR,URL) {
var collectionName = getCollectionName();
if (XHR.status == 200) {
showInformationMessage("Collection " + collectionName + " deleted");
resetForm();
}
else {
if (XHR.status == 412) {
showErrorMessage("Delete Collection Prohibited on Non-Empty Collection");
}
else {
showErrorMessage ("doDeleteCollection[" + URL + "]: Operation failed. Status = " + XHR.status + " (" + XHR.statusText + ")");
}
}
}
restAPI.setCollectionName(getCollectionName());
restAPI.dropCollection(callback);
}
function doListCollections() {
var callback = function(XHR,URL) {
jsonDocument = restAPI.processGetResponse(XHR,URL);
if (jsonDocument != null) {
var optionList = document.getElementById("collectionList")
optionList.innerHTML = "";
var newOption = new Object();
newOption.name = "(new)"
jsonDocument.items.unshift(newOption);
populateOptionList(optionList,jsonDocument.items,"name");
checkNewCollection();
}
}
restAPI.getCollectionList(callback)
}
function renderKeyList(keyList,collectionName) {
var container = document.getElementById("keyList");
container.innerHTML = "";
var SPAN = document.createElement("SPAN");
container.appendChild(SPAN);
SPAN.className = "h5";
SPAN.textContent = "Key List for \"" + collectionName + "\"";
var BR = document.createElement("BR");
container.appendChild(BR);
BR = document.createElement("BR");
container.appendChild(BR);
var TABLE = document.createElement("TABLE")
container.appendChild(TABLE);
TABLE.className = "table table-striped table-bordered";
var SPAN = document.createElement("SPAN");
container.appendChild(SPAN);
SPAN.className = "h5";
var results = "Result : ";
if (keyList.length > 0) {
results += keyList.length + " Rows selected.";
}
else {
results += "No Rows selected.";
}
SPAN.textContent =results;
for (var i=0; i<keyList.length;i++) {
var keyValue = keyList[i].id
var TR = TABLE.insertRow(0);
TR.id = keyValue;
var TD = TR.insertCell()
/*
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
<li role="presentation" class="divider"></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
</ul>
</div>
*/
var DIV = document.createElement("DIV");
TD.appendChild(DIV)
DIV.className = "dropdown";
var BUTTON = document.createElement("BUTTON");
DIV.appendChild(BUTTON);
BUTTON.className = "btn btn-default dropdown-toggle"
BUTTON.type = "button";
BUTTON.dataset.toggle = "dropdown";
BUTTON.appendChild(document.createTextNode("Action "));
var SPAN = document.createElement("SPAN");
BUTTON.appendChild(SPAN);
SPAN.className = "caret";
var UL = document.createElement("UL");
DIV.appendChild(UL);
UL.className = "dropdown-menu";
UL.role = "menu"
var LI = document.createElement("LI");
LI.role="presentation";
UL.appendChild(LI);
var A = document.createElement("A");
LI.appendChild(A);
A.role="menuitem"
A.onclick = function(collection,key) { return function() { doUpdateDocument(collection,key); }; }(collectionName,keyValue);
A.tabindex="-1"
A.href="#"
var ICON = createIcon("/XFILES/lib/icons/json_update_document.png","Edit Document");
A.appendChild(ICON)
A.appendChild(document.createTextNode(" Update Document"))
var LI = document.createElement("LI");
LI.role="presentation";
UL.appendChild(LI);
var A = document.createElement("A");
LI.appendChild(A);
A.role="menuitem"
A.onclick = function(collection,key) { return function() { doDuplicateDocument(collection,key); }; }(collectionName, keyValue);
A.tabindex="-1"
A.href="#"
var ICON = createIcon("/XFILES/lib/icons/json_create_document.png","Clone Document");
A.appendChild(ICON)
A.appendChild(document.createTextNode(" Duplicate Document"));
var LI = document.createElement("LI");
LI.role="presentation";
UL.appendChild(LI);
var A = document.createElement("A");
LI.appendChild(A);
A.role="menuitem"
A.onclick = function(collection,key) { return function() { doDeleteDocument(collection,key); }; }(collectionName,keyValue);
A.tabindex="-1"
A.href="#"
var ICON = createIcon("/XFILES/lib/icons/json_delete_document.png","Delete Document");
A.appendChild(ICON)
A.appendChild(document.createTextNode(" Delete Document"))
var LI = document.createElement("LI");
LI.role="presentation";
UL.appendChild(LI);
var A = document.createElement("A");
LI.appendChild(A);
A.role="menuitem"
A.onclick = function(collection,key) { return function() { doCreateTemplate(collection,key); }; }(collectionName,keyValue);
A.tabindex="-1"
A.href="#"
var ICON = createIcon("/XFILES/lib/icons/json_create_collection.png","Create Template");
A.appendChild(ICON)
A.appendChild(document.createTextNode(" Save Template"));
var TD = TR.insertCell()
var A = document.createElement("A")
TD.appendChild(A);
A.title = "Fetch Document"
A.href = '#';
A.onclick = function(collection,key) { return function() { doUpdateDocument(collection,key); }; }(collectionName,keyValue);
TXT = document.createTextNode(keyValue);
A.appendChild(TXT);
}
container.style.display="block";
}
function doGetKeys() {
var callback = function(XHR,URL) {
jsonDocument = restAPI.processGetResponse(XHR,URL);
if (jsonDocument != null) {
if (jsonDocument.items.length == 0) {
showInformationMessage("No documents found");
clearData();
}
else {
renderKeyList(jsonDocument.items,getCollectionName());
}
}
}
restAPI.setCollectionName(getCollectionName());
restAPI.getCollection("fields=id",callback);
}
function renderDocuments(jsonObject) {
var target = document.getElementById("showDocumentList")
target.style.display="block";
target.innerHTML = "";
var table = jRenderer.addTable(target);
var header = jRenderer.addHeader(table);
var hcell = jRenderer.addCell(header);
hcell.appendChild(document.createTextNode("ID"))
for (var i=0; i < jsonObject.length; i++) {
var row = jRenderer.addRow(table);
var cell1 = jRenderer.addCell(row);
cell1.appendChild(document.createTextNode(jsonObject[i].id))
var cell2 = jRenderer.addCell(row);
jRenderer.renderJsonObject(cell2,jsonObject[i].value);
}
}
function doGetDocuments() {
var callback = function(XHR,URL) {
jsonDocument = restAPI.processGetResponse(XHR,URL);
if (jsonDocument != null) {
if (jsonDocument.items.length == 0) {
showInformationMessage("No documents found");
}
else {
renderDocuments(jsonDocument.items);
}
}
}
restAPI.setCollectionName(getCollectionName());
restAPI.getCollection(null,callback);
}
function doCreateTemplate(collectionName,keyValue) {
var ICON = document.getElementById("btn.SaveNewTemplate");
ICON.onclick = function(collection,keyValue) { return function() { doSaveTemplate(collection,keyValue); }; }(collectionName, keyValue);
var field = document.getElementById("newTemplateName");
field.value = "";
$('#newTemplateDialog').modal('show')
field.focus();
}
function doSaveTemplate(collectionName,keyValue) {
closeModalDialog("newTemplateDialog");
var callback = function(XHR,URL) {
jsonDocument = restAPI.processGetResponse(XHR,URL);
if (jsonDocument != null) {
var name = document.getElementById("newTemplateName").value;
saveTemplate(name,jsonDocument)
}
}
restAPI.setCollectionName(collectionName);
restAPI.getDocument(keyValue,callback)
}
function doCreateDocument() {
/*
**
** Set the 'Save' action on the Edit Document form to createDocument()
**
*/
var target = resetEditDocumentForm();
var ICON = document.getElementById("btn.saveEditDocument");
ICON.onclick = function(inputContainer,collection) { return function() { createDocument(inputContainer,collection); }; }(target, getCollectionName());
getTemplateList();
$('#editDocumentDialog').modal('show');
}
function queryCollection(inputContainer,collectionName) {
var jsonObject = rowToJson(inputContainer);
var callback = function(XHR,URL) {
$('#editDocumentDialog').modal('hide')
jsonDocument = restAPI.processGetResponse(XHR,URL);
if (jsonDocument != null) {
if (jsonDocument.items.length == 0) {
showInfromation("No documents found");
}
else {
renderDocuments(jsonDocument.items);
}
}
};
restAPI.setCollectionName(collectionName)
restAPI.postDocument("action=query",jsonObject,callback)
}
function doQueryCollection(collection) {
/*
**
** Set the 'Save' action on the Edit Document form to createDocument()
**
*/
var target = resetEditDocumentForm();
var ICON = document.getElementById("btn.saveEditDocument");
ICON.onclick = function(inputContainer,collection) { return function() { queryCollection(inputContainer,collection); }; }(target, getCollectionName());
getTemplateList();
$('#editDocumentDialog').modal('show')
;
}
function doUpdateDocument(collection, key) {
/*
**
** Set the 'Save' action on the Edit Document form to updateDocument()
**
*/
var target = document.getElementById("editDocument");
var ICON = document.getElementById("btn.saveEditDocument");
ICON.onclick = function(inputContainer,collection,key) { return function() { updateDocument(inputContainer,collection,key); }; }(target, collection, key);
var templateList = document.getElementById("templateList");
templateList.style.display = "NONE";
var callback = function(XHR,URL) {
jsonDocument = restAPI.processGetResponse(XHR,URL);
if (jsonDocument != null) {
target = resetEditDocumentForm()
jRenderer.renderJsonInput(target,jsonDocument);
makeEditableDocument(target);
$('#editDocumentDialog').modal('show')
var inputCollection = target.getElementsByTagName("INPUT");
inputCollection[0].focus();
}
}
/*
**
** Get the document to be updated and open the Edit Document Dialog
**
*/
restAPI.setCollectionName(collection);
restAPI.getDocument(key,callback)
}
/*
**
** Delete Document
**
*/
function doDeleteDocument(collection,key) {
var callback = function(XHR,URL) {
var row = document.getElementById(key);
row.parentNode.removeChild(row);
showInformationMessage ("Delete Complete. Status = " + XHR.status + " (" + XHR.statusText + ")");
}
restAPI.setCollectionName(collection)
restAPI.deleteDocument(key,callback)
}
/*
**
** Duplicate Document
**
*/
function doDuplicateDocument(collection, key) {
/*
**
** Set the 'Save' action on the Edit Document form to createDocument()
**
*/
var target = document.getElementById("editDocument");
var ICON = document.getElementById("btn.saveEditDocument");
ICON.onclick = function(inputContainer,collection) { return function() { createDocument(inputContainer,collection); }; }(target, collection);
/*
**
** Get the document to be duplicated and open the Edit Document Dialog
**
*/
var callback = function(XHR,URL) {
jsonDocument = restAPI.processGetResponse(XHR,URL);
if (jsonDocument != null) {
target = resetEditDocumentForm()
jRenderer.renderJsonInput(target,jsonDocument);
makeEditableDocument(target);
$('#editDocumentDialog').modal('show');
var inputCollection = target.getElementsByTagName("INPUT");
inputCollection[0].focus();
}
}
restAPI.setCollectionName(collection);
restAPI.getDocument(key,callback)
}
function onDragStart(ev) {
ev.dataTransfer.setData("Text",ev.target.id);
console.log(ev.target.id);
}
function enableDrop(ev) {
// ev.preventDefault();
}
function onDrop(ev) {
if (ev.preventDefault) {
ev.preventDefault();
}
var data=ev.dataTransfer.getData("Text");
if (data == 'removeField') {
deleteField(ev.srcElement);
}
return false;
}
function onPageLoaded() {
doListCollections();
}
/*
**
** Create Document
**
*/
function createDocument(inputContainer,collectionName) {
var jsonObject = rowToJson(inputContainer);
var callback = function(XHR,URL) {
status = restAPI.processPutResponse(XHR,URL);
$('#editDocumentDialog').modal('hide')
};
restAPI.setCollectionName(collectionName);
if (serverAssignedKeys) {
restAPI.postDocument(null,jsonObject,callback)
}
else {
var newGuid = guid();
restAPI.putDocument(newGuid,jsonObject,callback)
}
}
/*
**
** Update Document
**
*/
function updateDocument(inputContainer,collectionName,key) {
var jsonObject = rowToJson(inputContainer);
var callback = function(XHR,URL) {
status = restAPI.processPutResponse(XHR,URL);
$('#editDocumentDialog').modal('hide')
};
restAPI.setCollectionName(collectionName);
restAPI.putDocument(key,jsonObject,callback)
}
function generateTemplate(object) {
var template = new Object();
for (var key in object) {
var item = object[key]
if ((typeof item == "string") || (typeof item == "number") || (typeof item == "boolean")) {
template[key] = null;
}
else {
if (typeof jsonItem == "object") {
if (jsonItem instanceof Array) {
template[key] = new Array();
for (var i = 0; i < jsonItem.length; i++) {
var item = jsonItem[i]
if ((typeof item == "string") || (typeof item == "number") || (typeof item == "boolean")) {
template[key][i] = null;
}
else {
template[key][i] = generateTemplate(item)
}
}
}
else {
template[key] = generateTemplate(item);
}
}
}
}
return template
}
function createTemplateCollection(name,object) {
var collectionName = "TEMPLATES";
var postCreateAction = function(name,object) {
return function(XHR,URL) {
if (XHR.status == 201) {
// Template Collection successfully created
saveTemplate(name,object);
}
else {
showErrorMessage("Unable to save Template. Status : " + XHR.status + " (" + XHR.statusText + ")");
}
};
} (name,object);
var collectionSpec = new Object();
collectionSpec.tableName = collectionName
collectionSpec.contentColumn = new Object();
collectionSpec.contentColumn.name = 'JSON_CONTENT';
collectionSpec.contentColumn.sqlType = "CLOB";
if ((collectionSpec.contentColumn.sqlType == 'CLOB') || (collectionSpec.contentColumn.sqlType == 'BLOB')) {
collectionSpec.contentColumn.compress = "MEDIUM";
collectionSpec.contentColumn.cache = true;
}
collectionSpec.keyColumn = new Object();
collectionSpec.keyColumn.name = 'ID'
collectionSpec.keyColumn.sqlType = 'VARCHAR2';
collectionSpec.keyColumn.maxLength = 64;
collectionSpec.keyColumn.assignmentMethod = "CLIENT"
collectionSpec.creationTimeColumn = new Object();
collectionSpec.creationTimeColumn.name = "CREATED_ON";
collectionSpec.lastModifiedColumn = new Object();
collectionSpec.lastModifiedColumn.name = "LAST_MODIFIED";
collectionSpec.versionColumn = new Object();
collectionSpec.versionColumn.name = "VERSION";
collectionSpec.versionColumn.method = "SHA256";
collectionSpec.readOnly = false;
restAPI.createCollection("TEMPLATES",collectionSpec,postCreateAction);
}
function saveTemplate(name, object) {
var checkTemplateStatus = function(name,object) {
return function(XHR,URL) {
if (XHR.status == 404) {
// Template Collection not found..
createTemplateCollection(name,object);
}
else {
if (XHR.status != 200) {
showErrorMessage("Unable to save Template. Status : " + XHR.status + " (" + XHR.statusText + ")");
}
else {
showInformationMessage("Template \"" + name + "\" added to TEMPLATES collection");
}
}
};
} (name,object);
var template = generateTemplate(object);
restAPI.setCollectionName("TEMPLATES");
restAPI.putDocument(name,template,checkTemplateStatus)
}
function getTemplateList() {
var callback = function(XHR,URL) {
var templateList = document.getElementById("templateList");
templateList.style.display = "none";
if (XHR.status == 200) {
var jsonDocument;
try {
jsonDocument = JSON.parse(XHR.responseText);
if (jsonDocument.items.length > 0) {
templateList.style.display = "inline-block";
var noTemplate = new Object();
noTemplate.id = "(none)";
jsonDocument.items.unshift(noTemplate);
populateOptionList(templateList,jsonDocument.items,"id");
}
}
catch (e) {
self.showErrorMessage("getTemplateList: Error parsing JSON response. (" + e.message + ")",URL);
return null;
}
}
else if (XHR.status == 404) {
}
else {
self.showErrorMessage("getTemplateList: Operation failed. Status = " + XHR.status + " (" + XHR.statusText + ")",URL);
return null;
}
}
restAPI.setCollectionName("TEMPLATES");
restAPI.getCollection("fields=id", callback);
}
function useTemplate() {
var collectionName = getCollectionName();
closeModalDialog("useTemplateDialog");
/*
**
** Set the 'Save' action on the Edit Document form to createDocument()
**
*/
var target = document.getElementById("editDocument");
var ICON = document.getElementById("btn.saveEditDocument");
ICON.onclick = function(inputContainer,collection) { return function() { createDocument(inputContainer,collection); }; }(target, collectionName);
var templateList = document.getElementById("templateList");
var templateName = templateList.value;
if (templateName != "(none)") {
/*
**
** Get the Template and open the Edit Document Dialog
**
*/
var callback = function(XHR,URL) {
jsonDocument = restAPI.processGetResponse(XHR,URL);
if (jsonDocument != null) {
target = resetEditDocumentForm()
jRenderer.renderJsonInput(target,jsonDocument);
makeEditableDocument(target);
$('#editDocumentDialog').modal('show');
}
}
restAPI.setCollectionName("TEMPLATES");
restAPI.getDocument(templateName, callback);
}
else {
resetEditDocumentForm();
$('#editDocumentDialog').modal('show');
}
}
function init() {
try {
initCommon();
initRestLogin();
if (isORDS) {
restAPI.setORDS();
restAPI.setSchema("scott");
var pwd = document.getElementById("sqlPassword");
pwd.parentNode.removeChild(pwd);
}
else {
restAPI.setServletRoot('/DBJSON');
}
doListCollections();
}
catch (e) {
handleException('schemalessDevelopmentUI.init',e,null);
}
}
|
import React from 'react';
import Logo from '../../images/fortuneScution.png';
import Button from '../UI/button';
import Image from '../UI/image';
let Navigation = props => {
return (
<React.Fragment>
<div className="homeNav">
<div>
<a href="https://www.youtube.com/watch?v=FteTrkjdb-0" target="_blank" className="btn blue darken-2 hideSmall">Watch Demo</a>
<Button
clicked={props.click2}
style="loginBtn2"
text="Join Now"
info={{
type: "submit",
name: "action",
}}
/>
</div>
<div>
<Image
info={{
class: "logo", // image
src: Logo
}}
/>
</div>
<div className="gridTwo2">
<Button
clicked={props.click2}
style="loginBtn hideSmal"
text="Join Now"
info={{
type: "submit",
name: "action",
}}
/>
<Button
clicked={props.click1}
style="loginBtn"
text="Login"
info={{
type: "submit",
name: "action",
}}
/>
</div>
</div>
</React.Fragment>
)
}
export default Navigation;
|
const officerOptions = [
{
position: "Show Coordinator",
name: "Xochitl Luna",
photoUrl: "/officer_images/Xochitl.jpg",
},
{
position: "President",
name: "Amber Zheng",
photoUrl: "/officer_images/Amber.jpg",
},
{
position: "Vice President",
name: "Sage Simhon",
photoUrl: "/officer_images/Sage.jpg",
},
{
position: "Treasurer",
name: "Maya Redden",
photoUrl: "/officer_images/Maya.jpg",
},
{
position: "Pub Chair",
name: "Jade Ishii",
photoUrl: "/officer_images/Jade.jpg",
},
{
position: "Pub Chair",
name: "Irene Terpstra",
photoUrl: "/officer_images/Irene.jpg",
},
{
position: "Secretary",
name: "Maryann Chidume",
photoUrl: "/officer_images/Maryann.jpg",
},
{
position: "Webmaster",
name: "Donald Liu",
photoUrl: "/officer_images/Donald.jpg",
},
{
position: "Social Chair",
name: "Quentin Thernize",
photoUrl: "/officer_images/Quentin.jpg",
},
{
position: "Media Historian",
name: "Eva Smerekanych",
photoUrl: "/officer_images/Eva.jpg",
},
{
position: "Tech Coordinator",
name: "Montse Garza",
photoUrl: "/officer_images/Montse.jpg",
},
{
position: "Costume Coordinator",
name: "Maria Fedyk",
photoUrl: "/officer_images/Maria.jpg",
},
];
module.exports = {
officerOptions,
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ModelAnimations extends SupCore.Data.Base.ListById {
constructor(pub) {
super(pub, ModelAnimations.schema);
}
}
ModelAnimations.schema = {
name: { type: "string", minLength: 1, maxLength: 80, mutable: true },
duration: { type: "number" },
keyFrames: {
type: "hash",
keys: { minLength: 1, maxLength: 80 },
values: {
type: "hash",
properties: {
translation: {
type: "array?",
items: {
type: "hash",
properties: {
time: { type: "number", min: 0 },
value: { type: "array", items: { type: "number", length: 3 } }
}
}
},
rotation: {
type: "array?",
items: {
type: "hash",
properties: {
time: { type: "number", min: 0 },
value: { type: "array", items: { type: "number", length: 4 } }
}
}
},
scale: {
type: "array?",
items: {
type: "hash",
properties: {
time: { type: "number", min: 0 },
value: { type: "array", items: { type: "number", length: 3 } }
}
}
}
}
}
}
};
exports.default = ModelAnimations;
|
var webpack = require('webpack');
var Ex = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var getHtmlConfig=function(name){
return {
template: './src/view/'+name+'.html',
filename: 'view/'+name+'.html',
inject: true,
hash: true,
chunks: ['common', name]
}
}
//环境变量 dev/online
var WEB
var config = {
entry: {
'common': ['./src/page/common/index.js'],
'index': ['./src/page/index/index.js'],
'login': ['./src/page/login/index.js'],
},
output: {
path: './dist',
publicPath:'/dist',
filename: 'js/[name].js'
},
externals: {
'jquery': 'window.jQuery'
},
plugins: [
//获取公共js
new webpack.optimize.CommonsChunkPlugin({
names: 'common',
filename: 'js/base.js'
}),
//把css单独打包到文件里
new Ex("css/[name].css"),
//html模板的处理
new HtmlWebpackPlugin(getHtmlConfig('index')),
new HtmlWebpackPlugin(getHtmlConfig('login'))
],
module: {
loaders: [
// 编译css并自动添加css前缀
{
test: /\.css$/,
loader: Ex.extract('style-loader', 'css-loader') // 单独打包出CSS,这里配置注意下
},
{
test: /\.(gif|png|jpg|woff|svg|eot|ttf)\??.*$/,
loader: Ex.extract('url-loader?limit=100&name=resource/[name].[ext]') // 图片处理
}
]
}
}
if('dev' === WEBPACK_ENV){
config.entry.common.push('webpack-dev-server/client?http://localhost:8088/');
}
module.exports = config;
|
import React from 'react'
import { StyleSheet } from 'quantum'
const getMessage = (count, limit) =>
__i18n('SEARCH.PAGEINFO')
.replace('${count}', count)
.replace('${limit}', limit)
const styles = StyleSheet.create({
self: {
fontSize: '14px',
width: '100%',
},
})
const Info = ({ count, limit }) => (
<div
className={styles()}
dangerouslySetInnerHTML={{ __html: getMessage(count, limit) }}
/>
)
export default Info
|
// @flow
import React from 'react';
import LocalForm from '../LocalForm';
export default function Root() {
return <LocalForm />;
}
|
import React, { Component } from 'react';
import { Route } from 'react-router';
import {connect} from 'react-redux';
import selector from './state/selector';
import dispatcher from './state/dispatcher';
import './styles';
class Game extends Component {
handleStartClick = event => {
this.props.startGame();
}
handleSquareClick = square => {
this.props.squareSelected(square);
}
render() {
const {
state,
squares,
} = this.props;
if(state === 'pre') {
return (
<section className="game" onClick={this.handleStartClick} role="button">
Play
</section>
)
}
return (
<section className="game">
<ul className="game__board">
{squares.map((square, index) => {
const liProps = {};
if(!square && state === 'active') {
liProps.onClick = e => this.handleSquareClick(index, e);
liProps.role = 'button';
}
return (
<li key={index} {...liProps}>
{square === 1 ? 'X' : (square === 2 ? 'O' : '')}
</li>
);
})}
</ul>
{state === 'post' && (
<div className="game__over" onClick={this.handleStartClick} role="button">Game Over!</div>
)}
</section>
)
}
}
export default connect(selector, dispatcher)(Game);
|
// 'use strict';
require('es6-promise').polyfill();
require('isomorphic-fetch');
const GITHUB = require('githubot')
const _ = require('lodash');
const Q = require('q');
const featureIds = require('../lib/featureIds');
let agm = require('../lib/agmLogin.js').agm;
let agmLogin = require('../lib/agmLogin.js').agmLogin;
module.exports = (robot) => {
//convert github issue state to agm syntax
function convertState(state) {
return (state === 'closed' ? 'Done' : 'New');
}
//find github issue story points and return integer
function findStoryPoints(labels) {
let obj = _.find(labels, l => l.name.includes('story points'));
return (obj === undefined ? null : obj.name.split(': ')[1]);
}
//convert github issue priority to agm syntax
function findPriority(labels) {
for(label of labels) {
if (label.name.includes("priority")) {
switch (label.name) {
case 'high priority':
return '1-High';
break;
case 'medium priority':
return '2-Medium';
break;
case 'low priority':
return '3-Low'
break;
}
}
}
return null;
}
//use issue feature label to find appropriate feature id
function findFeatureId(i) {
let feature = _.find(i.labels, l => l.name.includes('Feature'));
if (feature === undefined) {
return null;
}
//find featureIds object via issue's feature name
let obj = _.find(featureIds, f => f.gh_label === feature.name)
//if no assigned sprint, use 'no sprint' feature id
if (i.milestone === null) {
return obj['No Sprint'];
}
//use sprint # to find feature id
let sprint = i.milestone.title.split('- ')[1];
return obj[sprint];
}
function findReleaseId(i) {
if (i.milestone === null) {
return null;
}
let releases = {
'Sprint 1' : '1073',
'Sprint 2' : '1073',
'Sprint 3' : '1074',
'Sprint 4' : '1074',
'Sprint 5' : '1075',
'Sprint 6' : '1075'
}
let sprint = i.milestone.title.split('- ')[1];
return releases[sprint];
}
function getIssueComments(issueUrl) {
return new Promise(function(resolve, reject) {
GITHUB.get(`${issueUrl}/comments`, comments => {
// need if else for success/fail
resolve(comments);
});
});
}
robot.respond(/link issues/i, res => {
let issuesUrl = "https://github.hpe.com/api/v3/repos/Centers-of-Excellence/EA-Marketplace-Design-Artifacts/issues?state=all&per_page=100";
let commentsUrl = "https://github.hpe.com/api/v3/repos/Centers-of-Excellence/EA-Marketplace-Design-Artifacts/issues/comments?state=all&per_page=100";
let linkedIssues = [];
let allIssueIds = [];
let allIssueObjects = [];
let issuesPromises = [];
let commentsPromises = [];
//let agmLogin = require('../lib/agmLogin.js').agmLogin;
//get page count of github issues (max 100 issues per page)
let issuesPageCount = new Promise((resolve, reject) => {
GITHUB.get(`${issuesUrl}&page=1`, issues => {
let pageCount = Math.ceil(issues[0].number / 100);
// need if else for success/fail
resolve(pageCount);
});
});
//use page count to build array of 'getIssues' promises
function buildIssuesPromises(num) {
while (num > 0) {
issuesPromises.push(get100Issues(num));
num -= 1;
}
return issuesPromises;
}
function get100Issues(num) {
return new Promise((resolve, reject) => {
GITHUB.get(`${issuesUrl}&page=${num}`, issues => {
// need if else for success/fail
resolve(issues);
});
});
}
function buildIssueObjects(arr) {
arr.map(issues => {
//issues = array of objects
//filter out pull requests and invalid issues
let filtered = _.filter(issues, i => !i.hasOwnProperty('pull_request') && isValid(i.labels));
filtered.map(issue => {
buildIssueObject(issue);
allIssueIds.push(issue.number);
})
})
}
function isValid(labels) {
let obj = _.find(labels, l => l.name.includes('invalid'));
return (obj === undefined ? true : false);
}
function buildIssueObject(i) {
let issueObject = {};
issueObject.number = i.number;
issueObject.title = i.title;
issueObject.url = i.url;
issueObject.storyPoints = findStoryPoints(i.labels);
issueObject.state = convertState(i.state);
issueObject.priority = findPriority(i.labels);
issueObject.featureId = findFeatureId(i);
issueObject.releaseId = findReleaseId(i);
allIssueObjects.push(issueObject);
}
//get page count of all issues' comments, max 100 comments per page.
//github api includes "Link" in header which specifies last page #.
//link does not appear if results fit on single page, so this
//function will need to be edited to account for single page.
let commentsPageCount = fetch(`${commentsUrl}&page=1`).then(res => {
let url = res.headers.get('Link').split(" ")[2];
return url.split("&page=")[1].charAt(0);
}).catch(err => {
res.reply(err);
});
//use page count to build array of 'scanComments' promises
function buildCommentsPromises(num) {
while (num > 0) {
commentsPromises.push(scan100Comments(num));
num -= 1;
}
return commentsPromises;
}
function scan100Comments(num) {
return new Promise((resolve, reject) => {
GITHUB.get(`${commentsUrl}&page=${num}`, comments => {
for(comment of comments) {
if (comment.body.includes("Linked to Agile Manager ID #")) {
let id = comment.issue_url.split('/issues/');
linkedIssues.push(parseInt(id[1]));
}
}
// need if else for success/fail
resolve(linkedIssues);
});
});
}
function createAgmItem(match) {
let resourceOptions = createResourceOptions(match);
return new Promise((resolve, reject) => {
agm.resource(resourceOptions, function(err, body) {
if (err) {
reject(err);
} else {
let agmDetails = [
body.data[0].item_id,
body.data[0].id,
match.url,
`Item Created. AGM Client ID: ${body.data[0].item_id}; API ID: ${body.data[0].id}. Github Issue: ${match.number}`,
match.number
]
resolve(agmDetails);
};
});
});
}
function createResourceOptions(obj){
return {
workspaceId: '1003',
resource: 'backlog_items',
method: 'POST',
data: [{
name: obj.title,
subtype: 'user_story',
story_points: obj.storyPoints,
application_id: '53',
team_id: '159',
// theme_id: '6209',
story_priority: obj.priority,
status: obj.state, //New, In Progress, In Testing, or Done
feature_id: obj.featureId,
release_id: obj.releaseId
}]
};
}
//if no unlinked issues, return msg. Otherwise continue
//promise chain, creating agm user stories and posting github
//comments containing agm info for respective user story
function createAgmItems(unlinkedIssues){
if (unlinkedIssues.length === 0) {
res.reply('All Issues Linked.')
} else {
return Q.all(unlinkedIssues.map(i => {
let match = matchIssueObject(i, allIssueObjects);
return createAgmItem(match);
})).then(result => {
result.forEach(arr => {
console.log(arr[3]);
})
return Q.all(result.map(i => {
return postGithubComment(i);
}))
}).then(result => {
result.forEach(msg => {
console.log(msg);
})
})
}
}
function matchIssueObject(num, issues){
let match = issues.filter(function(obj) {
return obj.number == num;
});
return match[0];
}
function postGithubComment(data) {
let comment = {"body": `Linked to Agile Manager ID #${data[0]} (API ID #${data[1]})`}
// let commentSuccess = `Github Issue #${data[4]} Comment Created`
return new Promise((resolve, reject) => {
GITHUB.post (`${data[2]}/comments`, comment, reply => {
let issue = reply.issue_url.split('issues/')
resolve(`Github Issue #${issue[1]} Comment Created`);
});
});
}
agmLogin(agm).then(() => {
return issuesPageCount;
}).then(num => {
return buildIssuesPromises(num);
}).then(promises => {
return Promise.all(promises);
}).then(data => {
buildIssueObjects(data);
}).then(() => {
return commentsPageCount;
}).then(num => {
return buildCommentsPromises(num);
}).then(promises => {
return Promise.all(promises);
}).then(() => {
return _.difference(allIssueIds, linkedIssues);
}).then(unlinkedIssues => {
return createAgmItems(unlinkedIssues);
}).catch(err => {
console.error(err);
})
});
robot.respond(/update issue #?([0-9]+)/i, res => {
//user enters github issue number in command
let num = res.match[1];
let issueUrl = `https://github.hpe.com/api/v3/repos/Centers-of-Excellence/EA-Marketplace-Design-Artifacts/issues/${num}`;
let issueObject = {};
let apiId;
function getAgmId(comments) {
for (c of comments) {
if (c.body.includes('Linked to Agile Manager')) {
return c.body.split('API ID #')[1].slice(0, -1);
}
}
}
function getIssue() {
return new Promise((resolve, reject) => {
GITHUB.get(issueUrl, issue => {
// need if else for success/fail
buildIssueObject(issue);
resolve(issueObject);
});
});
}
function buildIssueObject(i) {
issueObject.title = i.title;
issueObject.storyPoints = findStoryPoints(i.labels);
issueObject.state = convertState(i.state);
issueObject.priority = findPriority(i.labels);
issueObject.featureId = findFeatureId(i);
issueObject.releaseId = findReleaseId(i);
}
function updateAgmItem(id, obj) {
let resourceOptions = createResourceOptions(id, obj);
return new Promise((resolve, reject) => {
agm.resource(resourceOptions, function(err, body) {
if (err) {
reject(err);
} else {
resolve(`AGM Item #${apiId} Updated.`);
};
});
});
}
function createResourceOptions(id, obj){
return {
workspaceId: '1003',
resource: 'backlog_items',
entityId: id,
method: 'PUT',
data: {
name: obj.title,
story_points: obj.storyPoints,
story_priority: obj.priority,
status: obj.state, //New, In Progress, In Testing, or Done
feature_id: obj.featureId,
release_id: obj.releaseId
}
};
}
agmLogin(agm).then(() => {
return getIssueComments(issueUrl);
}).then(data => {
apiId = getAgmId(data);
}).then(() => {
return getIssue();
}).then(obj => {
return updateAgmItem(apiId, obj);
}).then(msg => {
res.reply(msg);
}).catch(err => {
res.reply(err);
})
});
robot.router.post('/hubot/gitbot/issues', (req, res) => {
let action = req.body.action;
let issue = req.body.issue;
let issueUrl = issue.url;
let issueObject = {};
let apiId;
res.end('Successfully obtained issue info');
//build object with issue attributes
function buildIssueObject(i) {
issueObject.number = i.number;
issueObject.title = i.title;
issueObject.storyPoints = findStoryPoints(i.labels);
issueObject.state = convertState(i.state);
issueObject.priority = findPriority(i.labels);
issueObject.featureId = findFeatureId(i);
issueObject.releaseId = findReleaseId(i);
}
function createAgmItem(obj) {
let resourceOptions = postOptions(obj);
return new Promise((resolve, reject) => {
agm.resource(resourceOptions, function(err, body) {
if (err) {
reject(err);
} else {
let agmDetails = [
body.data[0].item_id,
body.data[0].id,
`Item Created. AGM Client ID: ${body.data[0].item_id}; API ID: ${body.data[0].id}. Github Issue: ${obj.number}`
]
resolve(agmDetails);
};
});
});
}
function postOptions(obj){
return {
workspaceId: '1003',
resource: 'backlog_items',
method: 'POST',
data: [{
name: obj.title,
subtype: 'user_story',
story_points: obj.storyPoints,
application_id: '53',
team_id: '159',
story_priority: obj.priority,
status: obj.state,
feature_id: obj.featureId,
release_id: obj.releaseId
}]
};
}
function postGithubComment(data) {
let comment = {"body": `Linked to Agile Manager ID #${data[0]} (API ID #${data[1]})`}
return new Promise((resolve, reject) => {
GITHUB.post (`${issueUrl}/comments`, comment, reply => {
let issue = reply.issue_url.split('issues/')[1];
resolve(`Github Issue #${issue} Comment Created`);
});
});
}
//scan comments for agm api id
function getAgmId(comments) {
for (c of comments) {
if (c.body.includes('Linked to Agile Manager')) {
return c.body.split('API ID #')[1].slice(0, -1);
}
}
}
function updateAgmItem(obj, id) {
let resourceOptions = putOptions(obj, id);
return new Promise((resolve, reject) => {
agm.resource(resourceOptions, function(err, body) {
if (err) {
reject(err);
} else {
resolve(`AGM Item #${apiId} Updated.`);
};
});
});
}
function putOptions(obj, id){
return {
workspaceId: '1003',
resource: 'backlog_items',
entityId: id,
method: 'PUT',
data: {
name: obj.title,
story_points: obj.storyPoints,
story_priority: obj.priority,
status: obj.state, //New, In Progress, In Testing, or Done
feature_id: obj.featureId
}
};
}
//start script
buildIssueObject(issue);
if (action === 'opened') {
//screen for pull request?
agmLogin(agm).then(() => {
return createAgmItem(issueObject);
}).then(data => {
console.log(data[2]);
return postGithubComment(data);
}).then(msg => {
console.log(msg);
}).catch(err => {
console.log(err);
})
} else {
//what if issue comments more than one page?
agmLogin(agm).then(() => {
return getIssueComments(issueUrl);
}).then(data => {
apiId = getAgmId(data);
}).then(() => {
return updateAgmItem(issueObject, apiId);
}).then(msg => {
console.log(msg);
}).catch(err => {
console.error(err);
})
}
});
};
|
const readlineSync = require("readline-sync");
function calcSurface(h, l){/* calcule le h x le l*/
return h* l;
}
console.log(calcSurface(2,3));
let a = Number(readlineSync.question('donnes une longueur'));
let b = Number(readlineSync.question('donnes une largeur'));
console.log(calcSurface(a,b));
|
const express = require('express');
const userController = require('../controller/userController');
const roou = express.Router();
app.post('/users', userController.addUser);
app.get('/users', userController.getAllUser);
app.get('/users/:id', userController.getUserById);
app.put('/users/:id', userController.updateUser);
app.delete('/users/:id', userController.deleteUser);
module.exports = app
|
function create_deal_document(doc_type_name, deal_id) {
var result = "";
webix.ajax().sync().get("documents/deals/" + deal_id + "?dtName=" + doc_type_name, null,
{
success: function (data, text, request) {
result = JSON.parse(data);
}, error: function (d,t,r) {
webix.alert("Произошла ошибка, повторите попытку позже");
}
});
return result;
}
function create_user_document(doc_type_name, user_id) {
var result = "";
webix.ajax().sync().get("documents/users/" + user_id + "?dtName=" + doc_type_name, null,
{
success: function (data, text, request) {
result = JSON.parse(data);
}, error: function (d,t,r) {
webix.alert("Произошла ошибка, повторите попытку позже");
}
});
return result;
}
function confirm_deal_document(doc_id, confirm_code) {
var result = "";
webix.ajax().sync().post("documents/deal_documents/" + doc_id, {code: confirm_code},
{
success: function (data, text, request) {
result = JSON.parse(data);
}, error: function (d,t,r) {
webix.alert("Произошла ошибка, повторите попытку позже");
}
});
return result;
}
function confirm_user_document(doc_id, confirm_code) {
var result = "";
webix.ajax().sync().post("documents/user_documents/" + doc_id, {code: confirm_code},
{
success: function (data, text, request) {
result = JSON.parse(data);
}, error: function (d,t,r) {
webix.alert("Произошла ошибка, повторите попытку позже");
}
});
return result;
}
function create_personal_data_agreement() {
var userData = users_update_prepare_data();
var docData = "";
webix.ajax().headers({"Content-type": "application/json"}).sync().post("documents/users/personal_data_agreement", userData,
{
success: function (data, text, request) {
docData = JSON.parse(data);
}, error: function (d,t,r) {
webix.alert("Произошла ошибка, повторите попытку позже");
}
});
if (docData.state !== "OK") {
webix.alert(docData.message);
return;
}
$$("doc_obj_type").setValue("user_document");
$$("doc_type_name").setValue("personal_data_agreement");
$$("doc_obj_id").setValue(docData.object.userDocId);
$$("doc_text_place").setHTML(docData.object.userDocText);
$$("doc_text_view").resize();
$$("docs_window").isPersonalAgreement = true;
$$("docs_window").show();
$$("index_page").disable();
}
function create_deal_agreement(deal_id, doc_type) {
var result = "";
webix.ajax().sync().get("documents/deals/" + deal_id + "?dtName=" + doc_type, null,
{
success: function (data, text, request) {
result = JSON.parse(data);
}, error: function (d,t,r) {
webix.alert("Произошла ошибка, повторите попытку позже");
}
});
if (result.state !== "OK") {
webix.alert(result.message);
return;
}
if(current_role == 'ROLE_INVESTOR' && doc_type == 'borrower_agreement'){
showPayingWarning();
}
$$("doc_obj_type").setValue("deal_document");
$$("doc_type_name").setValue(doc_type);
$$("parent_obj_id").setValue(deal_id);
$$("doc_obj_id").setValue(result.object.dealDocId);
$$("doc_text_place").setHTML(result.object.dealDocText);
$$("doc_text_view").resize();
$$("docs_window").show();
$$("index_page").disable();
}
function start_user_personal_agreement_confirmation() {
var result = confirm_user_document($$("doc_obj_id").getValue(), $$("confirm_code").getValue());
if (result.state !== "OK") {
webix.alert(result.message);
return;
}
$$("confirmCheckbox").setValue(1);
$$("confirmCheckbox").disable();
$$("userPersonalDataAgreementConfirmed").setValue(1);
if($$("docs_window").isPersonalAgreement){
var data = users_update_prepare_data();
users_update_request_send("users", $$("userId").getValue(), data);
}
webix.confirm({
ok: "Скачать"
, cancel: "Закрыть"
, text: "Документ успешно подтвержден, для скачивания версии в формате PDF нажмите \"Скачать\". "+
"Вы также можете скачать его позже в разделе \"Документы\""
, callback: function (result) {
if (result) {
window.open("documents/user_documents/" + $$("doc_obj_id").getValue());
}
close_docs_window();
}
});
}
function start_deal_document_confirmation(hasNext) {
var result = confirm_deal_document($$("doc_obj_id").getValue(), $$("confirm_code").getValue());
if (result.state !== "OK") {
webix.alert(result.message);
return;
}
webix.confirm({
ok: "Скачать"
, cancel: "Закрыть"
, text: "Документ успешно подтвержден, для скачивания версии в формате PDF нажмите \"Скачать\". "+
"Вы также можете скачать его позже в разделе \"Документы\""
, callback: function (result) {
if (result)
window.open("documents/deal_documents/" + $$("doc_obj_id").getValue());
close_docs_window();
if (hasNext)
nextAction($$("parent_obj_id").getValue());
else
lastAction($$("parent_obj_id").getValue())
}
});
}
function nextAction(deal_id) {
create_deal_agreement(deal_id, "borrower_agreement");
}
function lastAction(deal_id) {
if (current_role === 'ROLE_BORROWER') {
deals_set_borrower_user_request(deal_id, "-1");
} else if (current_role === 'ROLE_INVESTOR') {
deals_confirm(deal_id);
}
}
|
import React, { Component } from 'react';
import { StyleSheet, Text, TextInput, TouchableOpacity,KeyBoardAvoidingView } from 'react-native';
export default class WriterScreen extends Component{
constructor(){
super();
this.state={
title:'',
author:'',
story:''
}
}
render(){
return(
<KeyBoardAvoidingView>
<TouchableOpacity style={styles.header}>
<Text style={styles.headerText}>Writer's Corner</Text>
</TouchableOpacity>
<TextInput
style={styles.input}
placeholder="Title"
onChangeText={(text)=>this.setState({title:text})}
value={this.state.title}
/>
<TextInput
style={styles.input}
placeholder="Author's name"
onChangeText={(text)=>this.setState({author:text})}
value={this.state.author}
/>
<TextInput
style={styles.input}
placeholder="Start writing here"
multiline={true}
onChangeText={(text)=>this.setState({story:text})}
value={this.state.story}
/>
<TouchableOpacity style={styles.submitButton}>
<Text style={styles.submitButtonText}>Submit</Text>
</TouchableOpacity>
</KeyBoardAvoidingView>
)
}
}
const styles=StyleSheet.create({
header:{
backgroundColor:"black",
width:"50%",
height: 50,
alignSelf:'center',
alignItems:'center'
},
headerText:{
color:'white',
textAlign:'center',
fontWeight:'bold',
fontSize:30
},
input:{
width:150,
height:50,
borderColor:"black",
borderWidth:1
},
submitButton:{
backgroundColor:"red",
width:75,
height:25
},
submitButtonText:{
color:"white",
fontSize:15,
textAlign:'center'
}
})
|
$(document).ready(function(){
$(".img").click(function(){
$("#slider").show();
$(".img").hide();
});
$("#slider").mouseenter(function(){
$(".btn").show();
});
$("#slider").mouseleave(function(){
$(".btn").hide();
});
});
|
// @flow
import { Platform } from 'react-native';
import TONEnvironment from './TONEnvironment';
export default class TONWorkerThread {
// constructor
workerThread: Worker;
constructor(workerName: string) {
if (TONEnvironment.isProduction() && Platform.OS !== 'web') { // iOS, Android in production
this.workerThread = new Worker(`${workerName}.thread.js`);
} else {
const rootFolder = Platform.OS === 'web' ? '.' : './web';
this.workerThread = new Worker(`${rootFolder}/workers/${workerName}.thread.js`);
}
}
dispatch(params: *): Promise<*> {
return new Promise((resolve, reject) => {
this.workerThread.onmessage = (message: any) => {
this.workerThread.terminate();
let response = message;
if (Platform.OS === 'web') { // web (instanceof MessageEvent)
response = message.data;
} else { // mobile (instanceof String)
try {
response = JSON.parse(message); // trying to parse an Object from String
} catch (error) {
//
}
}
resolve(response);
};
this.workerThread.onerror = (error) => { // N.B. not supported on react native!!!
this.workerThread.terminate();
reject(error);
};
let message = params;
if (Platform.OS === 'web') { // web (will be wrapped with MessageEvent)
// nothing
} else { // mobile (only String is supported to post)
message = params instanceof Object ? JSON.stringify(params) : message;
}
this.workerThread.postMessage(message);
});
}
}
|
import reducer, {defaultValue, SET_USER_LIST, SET_PAGE} from '../reducer'
describe('Testing some functions in search reducer', () => {
let state
it('Check if reducer is started with default value', () => {
expect(reducer(undefined, {})).toEqual(defaultValue)
})
it('Check if set user list saves correctly new users and keep old users', () => {
state = reducer(state, {
type: SET_USER_LIST,
value: [
{name: 'User 1'},
{name: 'User 2'}
]
})
expect(state).toHaveProperty('users')
expect(state.users).toHaveLength(2)
})
it('Check if set page works correctly', () => {
state = reducer(state, {
type: SET_PAGE,
value: 2
})
expect(state).toHaveProperty('page')
expect(state.page).toBe(2)
})
})
|
( function () {
'use strict';
angular
.module( 'app', [ 'app.config', 'app.home', 'app.add', 'app.edit' ] );
})();
|
/*使用Node.js创建一个静态Web服务器
1)创建一个HTTP Server
2)为Server指定处理请求消息的过程
2.1)解析请求URL中的资源名称, 如 /login.html
2.2)读取指定文件中的内容,如 htdocs/login.html
2.3)构建响应消息,把读取到的文件内容输出客户端
3)让Server开始监听特定端口
提示:上述程序需要用到http、url、fs模块*/
/**
* 使用Node.js创建一个静态Web服务器
* 根据客户端请求的页面名称,输出对应的文件内容
*/
/*Url {
protocol: 'http:',
slashes: true, // 斜杠语法
auth: null,
host: 'tmooc.cn:8000',
port: '8000',
hostname: 'tmooc.cn',
hash: '#chapter3',
search: '?uname=mary&age=20',
query: { uname: 'mary', age: '20' },
pathname: '/s.do',
path: '/s.do?uname=mary&age=20',
href: 'http://tmooc.cn:8000/s.do?uname=mary&age=20#chapter3'
}*/
var http = require('http');
var url = require('url');
var fs = require('fs');
//1 创建一个HTTP Server
var server = http.createServer();
//2 为Server指定处理请求消息的过程
server.on('request', function(request, response) {
//2.1)解析请求URL中的资源名称, 如 /login.html
var urlObj = url.parse( request.url , true);
var fileName = urlObj.pathname; //请求的文件名称
if(fileName=='/favicon.ico'){
console.log(" pathname: '/favicon.ico")
response.end(); //结束输出
return; //不处理图标文件的请求
}
fileName = 'htdocs'+fileName; //请求文件的实际路径 如 htdocs/login.html
//2.2)读取指定文件中的内容,如 htdocs/login.html
var buf = fs.readFileSync(fileName);
//2.3)构建响应消息,把读取到的文件内容输出客户端
response.writeHead(200, {'Content-Type':'text/html;charset=UTF-8'});
response.write(buf); //输出响应主体
response.end(); //结束输出
});
//3 让Server开始监听特定端口
server.listen(3000, function(){
console.log('静态Web服务器开始监听3000端口');
});
//测试输出: http://localhost:3000/login.html http://localhost:3000/favicon.ico
|
// $( function() {
// var dateFormat = "mm/dd/yy",
// leaving = $( "#leaving" )
// .datepicker({
// defaultDate: "+1w",
// changeMonth: true,
// numberOfMonths: 3
// })
// .on( "change", function() {
// returning.datepicker( "option", "minDate", getDate( this ) );
// }),
// to = $( "#returning" ).datepicker({
// defaultDate: "+1w",
// changeMonth: true,
// numberOfMonths: 3
// })
// .on( "change", function() {
// leaving.datepicker( "option", "maxDate", getDate( this ) );
// });
// function getDate( element ) {
// var date;
// try {
// date = $.datepicker.parseDate( dateFormat, element.value );
// } catch( error ) {
// date = null;
// }
// return date;
// }
// } );
// $(function () {
// $("#slider-range").slider({
// range: true,
// min: 0,
// max: 2000,
// values: [75, 300],
// slide: function (event, ui) {
// $("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
// },
// });
// $("#amount").val(
// "$" +
// $("#slider-range").slider("values", 0) +
// " - $" +
// $("#slider-range").slider("values", 1)
// );
// });
// let startDate;
// let returnDate;
// let cityName;
// let budget;
// function getResponse() {
// const responsePage = {
// method: "GET",
// url: "/response",
// params: {
// cityName: cityName,
// budget: budget,
// startDate: startDate,
// returnDate: returnDate,
// },
// headers: {
// "Content-Type": "application/json",
// },
// };
// axios.request(responsePage)
// .then( )
// }
// const resultSect = document.querySelector(".results-section")
// const saveFlights = document.querySelector(".save-flight")
// const resultFlight = document.querySelector(".results")
var endCity = "Tokyo"; // later input used in case we are switching cities or building out the end point
var endCitySymbol = "TYOA";
var travelId = "298184";
var citySymbol = "";
var cityName = "New York";
var resultSect = document.querySelector(".results");
var resultSect = document.querySelector(".results")
$("#api-inputs").submit(function (event) {
event.preventDefault();
startDate = document.querySelector("#leaving").value;
returnDate = document.querySelector("#returning").value;
cityName = document.querySelector("#start-city").value.trim();
budget = document.querySelector("#amount").value.trim();
$("#api-inputs").modal("hide");
return;
// show buttons
});
$("#get-flights").click(gettingTheCityCode);
$("");
// skyscanner api
// request for the city code
function gettingTheCityCode() {
const skyscannerCityName = {
method: "GET",
url: "/api/destination/cities/" + cityName,
headers: {
"Content-Type": "application/json",
},
};
axios
.request(skyscannerCityName)
.then(function (response) {
// console.log(response.data.Places[0].CityId);
citySymbol = response.data.Places[0].CityId;
gettingFlightData(citySymbol);
})
.catch(function (error) {
console.error(error);
});
}
function gettingFlightData() {
let flightoptions = {
method: "GET",
url: "api/destination/flights",
params: {
citySymbol: citySymbol,
endCity: endCitySymbol,
startDate: startDate,
returnDate: returnDate,
},
// we can send a post request (bad practice)
// query string
// ?symbol=SYM&endSymbol=END&startDate=whatever&returnDate=anotherDate
// req.query.symbol = SYM
// req.query.endSymbol = END
headers: {
"Content-Type": "application/json",
},
};
axios.request(flightoptions).then(function (response) {
// console.log(response.data);
// data.quotes & data.carriers
generateFlightList(response);
});
}
function generateFlightList(response) {
// flightPrice = response.data.Quotes[1].minPrice; //this is added to show what the lowest price option is in the list
// console.log(response.data.Carriers[0].Name);
let response1 = response.data
console.log(response1)
for (let i = 0; i <= response.data.Quotes.length; i++) {
// generate the list from the options given
// try to give no more than 10 options
let flightCells = `
<div class="card-body results" data-marker='${i}'>
<h5 class="card-title">Flight Option #${i + 1}</h5>
<p class="card-text">Carrier: <span data-marker='${i}' id="carrier${i}">${
response.data.Carriers[i].Name
}</span></p>
<p class="card-text">Airport: <span data-marker='${i}' id="airport${i}">${
response.data.Places[i].IataCode
}</span></p>
<p class="card-text">Min Price: $<span data-marker='${i}' id="price${i}">${
response.data.Quotes[i].MinPrice
}</span></p>
<button class="save-flight btn btn-primary" id='${i}' onClick='saveFlights(this.id)'>Save Flight</button>
</div>
`;
resultSect.innerHTML = flightCells;
}
}
function saveFlights(ID) {
console.log(ID)
let carrier = document.querySelector(`#carrier${ID}`).textContent
let price = document.querySelector(`#price${ID}`).textContent
let budgetLeft = budget - price
let savedTrip = {
method:"POST",
url:"/apis/trips",
params: {
budget: budgetLeft,
carrier: carrier,
},
headers: {
"Content-Type": "application/json",
},
}
axios.request(savedTrip)
.then(function () {
res.json();
console.log(carrier,price, budgetLeft)
}
|
//Import Modules
import React, {useState, useEffect} from 'react';
import Axios from 'axios';
//Import Stylesheets
import './Styles/App.css';
//Import Components
import Form from './Components/Form';
import CouponList from './Components/CouponList';
import Header from './Components/Header';
import Footer from './Components/Footer';
import Infobox from './Components/Infobox';
//Main Component
function App() {
//State Hooks
//Data Hooks
const [shopName, setShopName] = useState('');
const [couponValue, setCouponValue] = useState('');
const [couponCode, setCouponCode] = useState('');
const [description, setDescription] = useState('');
const [multipleTimes, setMultipleTimes] = useState(false);
const [couponList, setCouponList] = useState([]);
const [date, setDate] = useState(new Date(9999,1,1));
//UI Hooks
const [couponLink, setLink] = useState('');
const [isActive, setActive] = useState(false);
const [infoActive, setInfoActive] = useState(false);
const [flipActive, setFlipActive] = useState(false);
const [darkMode, setDarkMode] = useState(false);
const [listHeading, setListHeading] = useState("Finde dein Schnäppchen...");
//Show and Hide the Form and flip the Button
const handleToggle = () => {
setActive(!isActive);
setFlipActive(!flipActive);
};
//Effect Hook which is executed at page load
useEffect(()=>{
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
setDarkMode(true); //If Users System Color is in "Dark Mode", set Dark Mode true
}
Axios.get("https://skimp-coupons.herokuapp.com/read").then((response)=>{ //Send request to route in backend
let allCoupons = response.data;
allCoupons.sort((a,b) => a.shopName.localeCompare(b.shopName)); //Sort alphabetacally
setCouponList(allCoupons); //Handle data from the response
});
},[]); //Start useEffect Hook as soon as page loads
return (
<div className="App" data-theme={darkMode ? "dark" : "light"}>
<Header infoActive={infoActive} setInfoActive={setInfoActive} isActive={isActive} darkMode={darkMode} setDarkMode={setDarkMode}/>
<Infobox infoActive={infoActive} setInfoActive={setInfoActive}/>
<Form isActive={isActive} setActive={setActive} flipActive={flipActive} setFlipActive={setFlipActive}
shopName={shopName} setShopName={setShopName} couponCode={couponCode} setCouponCode={setCouponCode}
description={description} setDescription={setDescription} multipleTimes={multipleTimes} setMultipleTimes={setMultipleTimes}
couponList={couponList} setCouponList={setCouponList} setCouponValue={setCouponValue}
couponValue={couponValue} setLink={setLink} couponLink={couponLink} date={date} setDate={setDate} setListHeading={setListHeading}
/>
<CouponList infoActive={infoActive} isActive={isActive} couponList={couponList} setCouponList={setCouponList} listHeading={listHeading}/>
<button className={`openFormButton ${infoActive ? "blur" : ""}`} onClick={handleToggle}>
<div id="flip-button-inner" className={flipActive? "flip" : ""}>
<div className="flip-button-front"><ion-icon name="add-outline"></ion-icon></div>
<div className="flip-button-back"><ion-icon name="close-outline"></ion-icon></div>
</div>
</button>
<Footer isActive={isActive} infoActive={infoActive}/>
</div>
);
}
export default App; //Export Component
|
const { google } = require('googleapis')
const GithubAPI = require('./github-integration')
// Authenticate with Google Analytics
const jwt = new google.auth.JWT(
process.env.GA_EMAIL,
null,
process.env.GA_PRIVATE_KEY,
'https://www.googleapis.com/auth/analytics.readonly'
)
const view_id = process.env.GA_VIEW_ID
async function createPullRequestWithViews() {
let api = new GithubAPI()
// Get all the articles stored as markdown inside the 'src/posts' directory
const gaViews = await getPagesAndViews()
const markdownFiles = await api.getRepoFiles('src/posts')
const fileViews = matchViewsWithFiles(gaViews, markdownFiles.data)
// Now we need to take each file and get its original contents
const fileContents = fileViews.map(async fileViews => {
const { data: file } = await api.getRepoFile(`src/posts/${fileViews.file}`)
const buff = Buffer.from(
file.content,
file.encoding // most likely base64
)
return {
name: fileViews.file,
contents: buff.toString('ascii'),
sha: file.sha,
}
})
const markdownContents = await Promise.all(fileContents)
const filesWithViews = markdownContents.map((file, index) =>
updateFileContents(file, fileViews[index].views)
)
api.setBranch('view/update-08122018').then(() => {
api.pushFiles('test push with github-api', filesWithViews).then(function() {
console.log('Files committed!')
})
})
}
/**
* Get the frontmatter from a string
*
* TODO: Would this be easier to consume if it was returned as an object?
*
* @param {string} str string to look for frontmatter in
* @returns {string} frontmatter contents
*/
const getFrontmatter = str =>
str.substring(str.indexOf('---') + 3, str.lastIndexOf('---'))
/**
* Match the google analytics data with the post files from the github repo
* and match which files revieved what number of views.
*
* Returns an array of objects of the following type:
* { file: 'file-in-repository', views: numViews, }
*
* @param {*} views
* @param {*} files
*/
const matchViewsWithFiles = (views, files) => {
const dateRegex = /[0-9]{2}\-[0-9]{2}\-[0-9]{4}\-/g
return (
files
.map(file => {
const cleanedFileName = file.name
.replace('.md', '')
.replace(dateRegex, '')
const gaMatches = views.filter(item =>
item.page.includes(cleanedFileName)
)
return gaMatches.length
? {
file: file.name,
views: gaMatches[0].views,
}
: {}
})
// Filter out any empty objects
.filter(item => item.hasOwnProperty('file'))
)
}
/**
* Take the existing file contents and update the view frontmatter
*
* @param {*} file
* @param {*} views
*/
const updateFileContents = (file, views) => {
const frontmatter = getFrontmatter(file.contents)
let fileToWrite = ''
if (frontmatter.includes('pageViews')) {
// we already have saved page views before, so just update the value
// TODO: Implement this part
fileToWrite = file.contents
} else {
// page views was never added to this file
const frontmatterEnd = file.contents.lastIndexOf('---')
fileToWrite =
file.contents.slice(0, frontmatterEnd) +
`pageViews: ${views}\n` +
file.contents.slice(frontmatterEnd)
}
return {
path: `src/posts/${file.name}`,
content: fileToWrite,
sha: file.sha,
}
}
/**
* Get all the pages and their respective views that Google Analytics is tracking
*/
async function getPagesAndViews() {
const response = await jwt.authorize()
const { data } = await google.analytics('v3').data.ga.get({
auth: jwt,
ids: view_id,
'start-date': '2018-10-01', // Date when analytics was set up
'end-date': 'today',
dimensions: 'ga:pagePath',
metrics: 'ga:pageviews',
})
// Create and return an array of objects {page, views} for simple consuming
return (pagesAndViews = data.rows.map(row => {
return { page: row[0], views: row[1] }
}))
}
exports.handler = async (event, context) => {
createPullRequestWithViews()
}
|
import axios from 'axios';
import storage from './jas-storage';
import Vue from 'vue';
const ajax = function (type, url, oParam, isnoToken) {
if (!isnoToken) {
let token = storage.get('token', 1000 * 60 * 60 * 24); // 按照过期时间取token
if (!token) { // 未取到token,重新加载
location.reload();
return;
}
url = url + '?token=' + token;
}
var _type = type == 'post' ? 'post' : 'get';
let params = type == 'post' ? oParam : {
params: {
...oParam
}
};
url = '/jasproxy' + url;
return new Promise((resolve, reject) => {
axios[_type](url, params)
.then(res => {
let data = res.data;
// console.log(data)
if (data.status == -1 && data.code == "402") { // token失效或者过期,会返回-1
Vue.prototype.$confirm('登录信息失效,请重新登录', '提示', {
type: 'warning',
callback: function (action) {
if (action === 'confirm') {
// window.top.location.href = jasTools.base.rootPath + "/jasmvvm/pages/page-login/login.html";
}
}
});
return;
}
if (data.status == -1 && data.code == "excel-400") { // token失效或者过期,会返回-1
Vue.prototype.$message({
message: '当前查询条件下无数据',
type: 'error'
});
return;
}
if (data.status == 1 || data.status == 'ok') {
resolve(data);
} else if (!data.status && data) {
if (data.success == -1) {
Vue.prototype.$message({
message: data.msg || data.message || '服务器连接失败,请稍后再试',
type: 'error'
});
reject(data);
} else {
resolve(data);
}
} else {
Vue.prototype.$message({
message: data.msg || data.message || '服务器连接失败,请稍后再试',
type: 'error'
});
reject(data);
}
})
.catch(res => {
Vue.prototype.$message({
message: '服务器连接失败,请稍后再试...',
type: 'error'
});
reject(res);
});
});
};
export default {
get: ajax.bind(null, 'get'),
post: ajax.bind(null, 'post'),
axios
};
|
import React, { Component } from 'react';
import Comment from './Comment';
import { getComments } from '../../api/httpcalls'
class PostComments extends Component{
constructor(){
super();
this.state={
comments:[],
postId:null
}
}
updateComments = (commentData) => {
this.setState({
comments: [...this.state.comments, ...commentData],
postId: this.props.postId
})
}
componentDidMount() {
getComments(this.props.postId, this.updateComments)
}
render(){
if(this.state.postId==null){
return <h3>Loading Comments...</h3>
}else{
return(
<div>
<h3 className="mb-4" align="center" style={{color: "#DB3327" }}>Post No. {parseInt(this.state.postId) % 10} Comments</h3>
{
this.state.comments.map(comment =>{
return(
<Comment key={comment.commentId} name={comment.commentName} body={comment.commentBody} id={comment.id} PostId={this.state.postId} />
)})
}
</div>
);
}
}
}
export default PostComments;
|
import React from 'react';
import Main from './components/layout/Main';
import Home from './components/Pages/Home';
function App() {
return (
<div className="App">
<Main>
<Home />
</Main>
</div>
);
}
export default App;
|
'use strict'
const express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
app = express();
require('dotenv').config()
const PORT = process.env.PORT || 3000,
LOOKUP = require('./js/lookup'),
api = require('./routes/api');
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(cookieParser());
app.set('view engine', 'pug')
app.set('views', './views');
app.get('/', (req, res) => {
res.render('index', {
message: 'Look up social posts by user handle'
});
});
app.get('(?:/api)?/lookup/:username', (req, res) => {
// TODO respond json on api
let username = req.params.username;
LOOKUP.userLookup(username, (err, userPosts) => {
if ( err ) { return res.status(500).send(err) }
res.render('lookup', {
username: username,
reddit: userPosts.reddit,
twitter: userPosts.twitter,
instagram: userPosts.instagram
})
});
});
app.listen(PORT, () => {
console.log(`App listening on ${PORT}`)
});
|
'use strict';
require('dotenv').config();
const awsConfig = {
accessKeyId: process.env.accessKeyId,
secretAccessKey: process.env.secretAccessKey,
region: process.env.region
};
const ELB = require('aws-sdk/clients/elb');
const classic_elb = new ELB(awsConfig);
const _ = require('underscore');
const assert = require('assert');
// Return a list of all load balancers and their Instances. Each entry will be of the form:
// {LoadBalancerName: 'cda-consu-ElasticL-BK5LOE3X0J1A',
// Instances: [...] }
const describeELBs = () =>
classic_elb.describeLoadBalancers().promise().then(elbs => {
const descs = _.map(elbs.LoadBalancerDescriptions, function (elb) {
return {
LoadBalancerName: elb.LoadBalancerName,
Instances: elb.Instances
}
});
return _.sortBy(descs, desc => desc.LoadBalancerName)
});
const describeTags = (elb_names) =>
classic_elb.describeTags({
LoadBalancerNames: elb_names
}).promise().then(desc =>
_.sortBy(desc.TagDescriptions, desc => desc.LoadBalancerName));
/*
Strategy: Call describeELBs, then create an array of ELB names for the params to the describeTags call. Then join
the tags with the matching ELB.
*/
const elbsWithTags = () => {
const elbs = describeELBs();
const names = elbs.then(elbs => _.map(elbs, elb => elb.LoadBalancerName));
const tags = names.then(describeTags).then(tags => _.pluck(tags, 'Tags'));
return elbs.then(elbs =>
tags.then(tags => _.zip(elbs, tags)).then(elems => _.map(elems, elem => {
elem[0].Tags = elem[1];
return elem[0];
})))
};
// Returns ELB names, their instances, & tags for all production ELBs.
const prodELBs = () => {
const elbs = elbsWithTags();
return elbs.then(elbs => _.filter(elbs, elb =>
_.findWhere(elb.Tags, {
Key: 'Environment',
Value: 'prod'
})))
};
// Swaps property between two similar instances
const swapProperty = (left, right, propertyName) => {
const tmp = right[propertyName];
right[propertyName] = left[propertyName];
left[propertyName] = tmp;
};
const swapInstances = () => {
// Group by app type, then swap the instances.
const grouped = prodELBs().then(elbs => _.groupBy(elbs, elb =>
_.find(elb.Tags, tag => tag.Key === 'AppType').Value
));
grouped.then(group => swapProperty(group.consumer[0], group.consumer[1], 'Instances'));
grouped.then(group => swapProperty(group.dispenser[0], group.dispenser[1], 'Instances'));
// Extract the parameters to the setInstances call
const consumers = grouped.then(group => _.map(group.consumer, el => _.omit(el, 'Tags')));
const dispensers = grouped.then(group => _.map(group.dispenser, el => _.omit(el, 'Tags')));
const params = consumers.then(consumers => dispensers.then(dispensers => consumers.concat(dispensers)));
params.then(params => params.forEach(setInstances));
};
/*
Deregister & register instances. Params is obtained using makeParams below.
*/
const deRegisterInstances = (classic_elb, params) =>
classic_elb.deregisterInstancesFromLoadBalancer(params).promise();
const registerInstances = (classic_elb, params) =>
classic_elb.registerInstancesWithLoadBalancer(params).promise();
/* Return a Promise containing an array of the instance ids currently registered with this ELB.
This is an example of the return value from 'describeInstanceHealth'
data = {
InstanceStates: [
{
Description: "N/A",
InstanceId: "i-207d9717",
ReasonCode: "N/A",
State: "InService"
},
{
Description: "N/A",
InstanceId: "i-afefb49b",
ReasonCode: "N/A",
State: "InService"
}
]
}
*/
const getInstances = (classic_elb, elb_name) =>
classic_elb.describeInstanceHealth({LoadBalancerName: elb_name}).promise().then(data =>
_.map(data.InstanceStates, state => state.InstanceId));
// Set the registered instances of a classic ELB.
/* The parameter to this method is an object argument like below:
{
"LoadBalancerName": "cda-consu-ElasticL-1JCJFBRJ4YIVL",
"Instances": [
{
"InstanceId": "i-0de8bbc7c8ddf2e10"
}
]
}
*/
// todo Wrong name to prevent accidental invocation!
const setInstances2 = (elbAndInstances) => {
const elb_name = elbAndInstances.LoadBalancerName;
const instances = _.pluck(elbAndInstances.Instances, 'InstanceId');
const current = getInstances(classic_elb, elb_name);
return current.then(curr => {
console.log(`current: ${curr}`);
console.log(`passed: ${instances}`);
// If current instances are equal to our target then nothing to do.
if (_.isEqual(_.sortBy(curr, v => v), _.sortBy(instances, v => v))) return Promise.resolve(); else
// If not empty, then deregister current instances
if (_.isEmpty(curr)) return Promise.resolve(); else
return deRegisterInstances(classic_elb, makeParams(elb_name, curr));
}).then(() => registerInstances(classic_elb, makeParams(elb_name, instances)));
};
const makeParams = (elb_name, instances) => {
return {
LoadBalancerName: elb_name,
Instances: _.map(instances, id => {
return {
InstanceId: id
}
})
}
};
module.exports = {
prodELBs,
swapInstances
};
|
const options = {
root: null,
rootMargin: '-30% 0px',
threshold: 0
};
const obs = new IntersectionObserver(showIntersect, options);
const slideIn = document.querySelectorAll('.slide_in');
slideIn.forEach(sa => obs.observe(sa));
function showIntersect(changes,observer) {
changes.forEach(change => {
if (change.isIntersecting) {
change.target.classList.add('active');
observer.unobserve(change.target);
} else {
change.target.classList.remove('active');
}
});
}
|
//@flow
import React from 'react';
import PropTypes from 'prop-types';
import {withStyles} from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Typography from '@material-ui/core/Typography';
import Dialog from './Dialog';
type Photo = {
albumId: string,
id: string,
title: string,
url: string,
thumbnailUrl: string,
};
type Props = {
photos: Array<Photo>,
classes: Object,
};
const styles = {
card: {
width: 200,
maxHeight: 400,
margin: 20,
},
media: {
objectFit: 'cover',
},
};
function ImgMediaCard(props: Props) {
const {classes, photos} = props;
return (
<div
style={{
display: 'flex',
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
}}
>
{photos.map((photo) => {
return (
<Card className={classes.card}>
<CardMedia
component="img"
alt="Contemplative Reptile"
className={classes.media}
height="150"
width="150"
image="https://via.placeholder.com/150/92c952"
title="Contemplative Reptile"
/>
<CardContent>
<Typography
style={{height: 70}}
gutterBottom
variant="p"
component="p"
>
{photo.title}
</Typography>
</CardContent>
<CardActions>
<Dialog />
</CardActions>
</Card>
);
})}
</div>
);
}
ImgMediaCard.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(ImgMediaCard);
|
import {createMuiTheme} from '@material-ui/core/styles';
export const theme = createMuiTheme({
direction: 'rtl',
palette: {
primary: {main: '#34347D'},
secondary: {main: '#FFCC0F'},
},
overrides: {
MuiGrid: {
container: {
textAlign: 'left',
},
},
},
});
|
import styled from 'styled-components';
const InnerSection = styled.div`
padding: 5px;
`;
export default InnerSection;
|
// objekte für personen profil erstellen
var Persons = [
{
name: 'John',
surname: 'Doe',
favoritePerformers: ["Justin Timberlake", "Ed Sheeran", "Emma Watson"],
age: 25,
myPhoto: 'img/image1.jpg',
likes: 1
},
{
name: 'Jane',
surname: 'Doe',
favoritePerformers: ["Justin Timberlake", "Ed Sheeran", "Emma Watson"],
age: 23,
myPhoto: 'img/image2.jpg',
likes: 2
},
{
name: 'Max',
surname: 'Mustermann',
favoritePerformers: ["Justin Timberlake", "Ed Sheeran", "Emma Watson"],
age: 28,
myPhoto: 'img/image3.jpg',
likes: 4
},
{
name: 'Maxina',
surname: 'Mustermann',
favoritePerformers: ["Justin Timberlake", "Ed Sheeran", "Emma Watson"],
age: 25,
myPhoto: 'img/image4.jpg',
likes: 3
},
{
name: 'Andrea',
surname: 'Mustermann',
favoritePerformers: ["Justin Timberlake", "Ed Sheeran", "Emma Watson"],
age: 25,
myPhoto: 'img/image4.jpg',
likes: 3
}
];
// create profiles
function createProfiles(){
likebtns = [];
for (var i = 0; i < Persons.length; i++) {
// create profile div
cont = document.getElementById("content");
var persdiv = document.createElement("div");
persdiv.setAttribute("class", "profile");
persdiv.setAttribute("id", ("person" + i));
cont.appendChild(persdiv);
var left = document.createElement("div");
left.setAttribute("class", ("left"));
persdiv.appendChild(left);
var right = document.createElement("div");
right.setAttribute("class", ("right"));
persdiv.appendChild(right);
var likes = document.createElement("div");
likes.setAttribute("class", ("likes"));
persdiv.appendChild(likes);
// add image to profile
var prfpc = document.createElement("img");
prfpc.setAttribute("src", Persons[i].myPhoto);
prfpc.setAttribute("class", "persimg");
left.appendChild(prfpc)
// add description
// add firstname
var firstname = document.createElement("span");
firstname.setAttribute("class", "name");
var firstnameinhalt = document.createTextNode("Name: " + (Persons[i].name));
firstname.appendChild(firstnameinhalt);
right.appendChild(firstname);
// add surname
var surname = document.createElement("span");
surname.setAttribute("class", "surname")
var surnameinhalt = document.createTextNode("Surname: " + (Persons[i].surname));
surname.appendChild(surnameinhalt);
right.appendChild(surname);
// add age
var age = document.createElement("span");
age.setAttribute("class", "age");
var ageinhalt = document.createTextNode("Age: " + (Persons[i].age));
age.appendChild(ageinhalt);
right.appendChild(age);
// add likebutton + counter
var like = document.createElement("button");
var likeinhalt = document.createTextNode("Like");
like.appendChild(likeinhalt);
like.setAttribute("id", "likebtn" + i);
like.setAttribute("class", "likebtn" );
likes.appendChild(like)
likebtns += like;
var likecount = document.createElement("span");
likecount.setAttribute("id", "likecount" + (i));
var likecountinhalt = document.createTextNode((Persons[i].likes));
likecount.appendChild(likecountinhalt);
likes.appendChild(likecount);
}
}
createProfiles();
for (var i = 0; i < Persons.length; i++) {
var elem = document.getElementById("likebtn" + i);
elem.addEventListener('click', function(){updateLikes(Number(i))});
}
var parEv = document.querySelector("#content");
parEv.addEventListener('click', updateLikes, false);
// var likebtn1 = document.getElementById("likebtn0");
// likebtn1.addEventListener('click', function(){updateLikes(0)});
// var likebtn2 = document.getElementById("likebtn1");
// likebtn2.addEventListener('click', function(){updateLikes(1)});
// var likebtn3 = document.getElementById("likebtn2");
// likebtn3.addEventListener('click', function(){updateLikes(2)});
// var likebtn4 = document.getElementById("likebtn3");
// likebtn4.addEventListener('click', function(){updateLikes(3)});
function updateLikes(e) {
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id
var clickedIDNR = Number(e.target.id.slice(-1));
console.log(e);
Persons[clickedIDNR].likes += 1;
var counterupdate = document.getElementById("likecount" + clickedIDNR).innerHTML = Persons[clickedIDNR].likes;
}
e.stopPropagation();
}
// sortierung
var sortLikesBtn = document.createElement("button");
sortLikesBtn.appendChild(document.createTextNode("likes!"));
sortLikesBtn.setAttribute('id', 'sortlikebtn');
sortLikesBtn.setAttribute('class', 'close');
document.getElementById("sortnav").appendChild(sortLikesBtn);
sortLikesBtn.addEventListener('click', sortLikes);
function sortLikes() {
Persons.sort(function(a, b) {return b.likes-a.likes});
while (cont.firstChild) {
cont.innerHTML = "";}
createProfiles();
console.log(Persons);
// json ??
}
var sortNameBtn = document.createElement("button");
sortNameBtn.appendChild(document.createTextNode("Name"));
sortNameBtn.setAttribute('id', 'sortnamebtn');
sortNameBtn.setAttribute('class', 'close');
document.getElementById("sortnav").appendChild(sortNameBtn);
sortNameBtn.addEventListener('click', sortName);
function sortName() {
console.log(Persons);
Persons.sort(function(a, b) {
return (a.name).localeCompare(b.name);
})
while (cont.firstChild) {
cont.innerHTML = "";}
createProfiles();
console.log(Persons);
}
var sortSurnameBtn = document.createElement("button");
sortSurnameBtn.appendChild(document.createTextNode("Surname"));
sortSurnameBtn.setAttribute('id', 'sortsurnamebtn');
sortSurnameBtn.setAttribute('class', 'close');
document.getElementById("sortnav").appendChild(sortSurnameBtn);
sortSurnameBtn.addEventListener('click', sortSurname);
function sortSurname() {
console.log(Persons);
Persons.sort(function(a, b) {
return (a.surname).localeCompare(b.surname);
})
while (cont.firstChild) {
cont.innerHTML = "";}
createProfiles();
console.log(Persons);
}
var sortAgeBtn = document.createElement("button");
sortAgeBtn.appendChild(document.createTextNode("Age"));
sortAgeBtn.setAttribute('id', 'sortagebtn');
sortAgeBtn.setAttribute('class', 'close');
document.getElementById("sortnav").appendChild(sortAgeBtn);
sortAgeBtn.addEventListener('click', sortAge);
function sortAge() {
console.log(Persons);
Persons.sort(function(a, b) {
return a.age-b.age;
})
while (cont.firstChild) {
cont.innerHTML = "";}
createProfiles();
console.log(Persons);
}
// link liste sortierung öffnen
var arrow = document.getElementById("arrow");
arrow.addEventListener('click', openSortlist)
var navi = document.getElementById('sortnav');
var navbtn = navi.getElementsByTagName('button');
function openSortlist() {
if (document.querySelector("#sortnav > button").className == 'open') {
for (var i = 0; i < navbtn.length; i++) {
navbtn[i].setAttribute("class", "close");
}
}
else {
for (var i = 0; i < navbtn.length; i++) {
navbtn[i].setAttribute("class", "open");
};
};
}
// registrierung öffnen onpage
var reglink = document.querySelector("#register");
reglink.addEventListener('click', regPage)
function regPage() {
cont.innerHTML = ""
// add form
var regform = document.createElement("form");
cont.appendChild(regform);
// sur namefield
var surname = document.createElement("p");
var sntxt = document.createTextNode("Surname");
surname.setAttribute("id", "sntxt");
surname.appendChild(sntxt);
regform.appendChild(surname);
var surnamein = document.createElement("input");
surnamein.setAttribute("id", "snfield");
regform.appendChild(surnamein);
// namefield
var name = document.createElement("p");
var nmtxt = document.createTextNode("Name");
name.setAttribute("id", "nametxt");
name.appendChild(nmtxt);
regform.appendChild(name);
var namein = document.createElement("input");
namein.setAttribute("id", "namefield");
regform.appendChild(namein);
// agefield
var age = document.createElement("p");
var agetxt = document.createTextNode("Age");
age.setAttribute("id", "agetxt");
age.appendChild(agetxt);
regform.appendChild(age);
var agein = document.createElement("input");
agein.setAttribute("id", "agefield");
regform.appendChild(agein);
// picture
var pic = document.createElement("p");
var pictxt = document.createTextNode("Upload Picture");
pic.setAttribute("id", "pictxt");
pic.appendChild(pictxt);
regform.appendChild(pic);
var picturelink = document.createElement("input");
picturelink.setAttribute("id", "picfield");
regform.appendChild(picturelink);
// submit button
var submit = document.createElement("input");
submit.setAttribute("type", "submit");
submit.setAttribute("id", "regbtn");
regform.appendChild(submit);
}
// registrierung
// make eventlistener for submit button
var regbtn = document.querySelector("#regbtn");
if (regbtn !== null) {
regbtn.addEventListener('click', submitForm);
}
// check if all fields are filled out
function submitForm() {
alert("hello world")
sn = document.querySelector("#snfield");
nm = document.querySelector("#namefield");
age = document.querySelector("#agefield");
pic = document.querySelector("#picturelink")
if (sn !== "") {
document.querySelector("#sntxt").innerText += " Please fill out this field";
}
else {}
}
// print error message if not
//
|
import React from 'react';
import {Modal,ModalBody,ModalHeader,ModalFooter,
Form,FormGroup,Label,
Input,Button,Table} from 'reactstrap'
import Spinner from '../../components/UI/Spinner';
const ListBuilding = (props) => {
return (
<div>
<Modal isOpen={props.open} toggle={props.toggle} >
<ModalHeader
toggle={props.toggle}>
Lista de Obras
</ModalHeader>
<ModalBody>
{props.loading ?
<Spinner/>
:
<Table>
<thead>
<tr>
<th>#</th>
<th>Nombre</th>
<th>Direccion</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
{props.buildings.map((building,i)=>(
<tr key={i}>
<th scope="row">{building.idBuilding}</th>
<td>{building.name}</td>
<td>{building.address}</td>
<td>
<button className="btn btn-sm btn-info">Editar</button>{' '}
<button onClick={(e)=>props.onDelete(building.idBuilding)} className="btn btn-sm btn-danger">Borrar</button>{' '}
</td>
</tr>
))}
</tbody>
</Table>
}
</ModalBody>
<ModalFooter>
{/* <Button color="primary" onClick={props.onAddUser}>
Agregar</Button>{' '} */}
<Button color="secondary" onClick={props.toggle}>Volver</Button>
</ModalFooter>
</Modal>
</div>
);
};
export default ListBuilding;
|
/**
* Traffic Sales Widget
*/
import React from 'react';
import Button from '@material-ui/core/Button';
// card component
import { RctCardFooter } from 'Components/RctCard';
// chart
import HorizontalBarChart from 'Components/Charts/HorizontalBarChart';
// intl messages
import IntlMessages from 'Util/IntlMessages';
const TrafficChannel = ({ label, chartdata, labels }) => (
<div className="sales-chart-wrap">
<div className="p-15">
<HorizontalBarChart
label={label}
chartdata={chartdata}
labels={labels}
height={168}
/>
</div>
<RctCardFooter customClasses="d-flex justify-content-between align-items-center">
<Button size="small" variant="raised" color="primary" className="text-white"> <IntlMessages id="button.goToCampaign" /></Button>
<p className="fs-12 mb-0 text-base">
<span><i className="mr-5 zmdi zmdi-refresh"></i></span>
<IntlMessages id="widgets.updated10Minago" />
</p>
</RctCardFooter >
</div >
);
export default TrafficChannel;
|
import styled from "styled-components";
const Button = styled.button`
padding: 0.2em 0.5em;
background-color: #0e375d;
color: #FFF;
border-radius: 0.2em;
border: none;
opacity: 0.6;
&:hover {
opacity: 1;
}
&:disabled {
opacity: 0.1;
}
`;
export default Button;
|
function Cone() {
var radius;
var _height;
this.setBase = function(base) {
this.radius = base;
};
this.setHeight = function(height) {
this._height = height;
};
this.getBase = function() {
return this.radius;
};
this.getHeight = function() {
return this._height;
};
this.getVolume = function() {
return this.radius * this.radius * Math.PI * this._height / 3;
};
}
|
import React from 'react';
import styled from 'styled-components';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
const Toast = styled(ToastContainer)`
.Toastify__toast--info {
background: 'rgb(51, 102, 255)';
}
.Toastify__toast--success {
background: 'rgb(51, 187, 102)';
}
.Toastify__toast--warning {
background: 'rgb(254, 255, 20)';
}
.Toastify__toast--error {
background: 'rgb(255, 102, 102)';
}
`;
export const showToast = ({ type, message }) => {
switch (type) {
case 'success':
toast.success(message);
break;
case 'warn':
toast.warn(message);
break;
case 'error':
toast.error(message);
break;
default:
toast.info(message);
}
};
export default function ToastAnimated() {
return <Toast />;
}
|
var idb = ["samples.json"]
d3.json(idb[0]).then((data) => {
var samples=data;
console.log(samples)
console.log(samples[0])
console.log(samples[0].names)
console.log(samples[0].metadata)
console.log(samples[0].samples)
//Bar Chart for id=940 as default plot
function init() {
var isamples0 = samples[0].samples[0];
//console.log(isamples0)
isamples0.otu_ids2 = isamples0.otu_ids.map(function(otu){
return "otu " + otu
});
var trace1 = {
x: isamples0.sample_values.slice(0,10).reverse(),
y: isamples0.otu_ids2.slice(0,10).reverse(),
text: isamples0.otu_labels.slice(0,10).reverse(),
name: "Data",
type: "bar",
orientation: "h"
};
var chartData = [trace1];
//console.log(chartData)
var layoutch = {
title: "Top OTUs of Subject ID: " + "940",
margin: {
l: 100,
r: 100,
t: 50,
b: 100
}
};
Plotly.newPlot("bar", chartData, layoutch);
//console.log(isamples0.id)
//Demographic Info
var imetadata0 = samples[0].metadata[0]
//console.log(imetadata0)
var demogr = d3.select("#sample-metadata");
demogr.append("tr").text("id: " + imetadata0["id"]);
demogr.append("tr").text("ethnicity: " + imetadata0["ethnicity"]);
demogr.append("tr").text("gender: " + imetadata0["gender"]);
demogr.append("tr").text("age: " + imetadata0["age"]);
demogr.append("tr").text("location: " + imetadata0["location"]);
demogr.append("tr").text("bbtype: " + imetadata0["bbtype"]);
demogr.append("tr").text("wfreq: " + imetadata0["wfreq"]);
//Bubble Chart
var traceb = {
x: isamples0.otu_ids,
y: isamples0.sample_values,
text: isamples0.otu_labels,
mode: 'markers',
marker: {
color: isamples0.otu_ids,
size: isamples0.sample_values
}
};
var bubbleData = [traceb];
//console.log(bubbleData)
//console.log(d3.max(isamples0.otu_ids))
var layoutb = {
title: "Subject ID: " + 940,
showlegend: false,
height: 1000,
width: 1000,
xaxis:{title:{text: 'OTU ID'}},
yaxis:{title:{text: 'Sample Values'}}
}
Plotly.newPlot('bubble', bubbleData, layoutb);
//Gauge Chart
var gdata = [
{
domain: { x: [0, 1], y: [0, 1] },
value: imetadata0.wfreq,
title: { text: "Scrubs per Week, Subject ID: " + 940, font: {size: 18} },
type: "indicator",
gauge: {
axis: { range: [0, 9], dtick: 1},
steps:[
{ range: [0,1], color: "rgb(237,246,228)" },
{ range: [1,2], color: "rgb(211,233,191)" },
{ range: [2,3], color: "rgb(189,223,159)" },
{ range: [3,4], color: "rgb(164,210,122)" },
{ range: [4,5], color: "rgb(123,188,64)" },
{ range: [5,6], color: "rgb(108,166,56)" },
{ range: [6,7], color: "rgb(86,134,54)" },
{ range: [7,8], color: "rgb(65,101,41)" },
{ range: [8,9], color: "rgb(56,87,85)" }
]},
mode: "gauge+number"
}
];
var layoutg = { width: 400, height: 300, margin: { l:10, r:50, t: 10, b: 10 }};
Plotly.newPlot('gauge', gdata, layoutg);
//pie chart
var piechart = [{
values: isamples0.sample_values.slice(0,10).reverse(),
labels: isamples0.otu_ids2.slice(0,10).reverse(),
//text: isamples0.otu_labels.slice(0,10).reverse(),
title: {text: "Top OTUs Proportion", font: {size: 18} },
type: "pie"
}]
var layoutp = {
height: 500,
width: 500,
showlegend: false,
margin: { l:80, r:50, t: 0, b: 0 }
};
Plotly.newPlot('pie', piechart, layoutp);
};
//Default items above completed
d3.select("#sample-metadata").html("");
//Test Subject ID List
var samplesallid = samples[0].names;
//var samplesallid = samples[0].samples.map(sid => sid.id);
console.log(samplesallid)
var idli = document.getElementById("selDataset");
for (var i = 0; i<samplesallid.length; i++) {
var opt = samplesallid[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
idli.appendChild(el);
}
document.getElementById("selDataset").onchange = function(){getData()};
function getData(){
var dsid = document.getElementById("selDataset").value;
//console.log(dsid)
//Bar Chart
var isamples01 = samples[0].samples.filter(ssid => ssid.id === dsid)
var isamples0 = isamples01[0];
//console.log(isamples01)
isamples0.otu_ids2 = isamples0.otu_ids.map(function(otu){
return "otu " + otu
});
var trace1 = {
x: isamples0.sample_values.slice(0,10).reverse(),
y: isamples0.otu_ids2.slice(0,10).reverse(),
text: isamples0.otu_labels.slice(0,10).reverse(),
name: "Data",
type: "bar",
orientation: "h"
};
var chartData = [trace1];
var layoutch = {
title: "Top OTUs of Subject ID: " + dsid,
margin: {
l: 100,
r: 100,
t: 50,
b: 100
}
};
Plotly.newPlot("bar", chartData, layoutch);
//Demographic Info
var imetadata01 = samples[0].metadata.filter(ssid => ssid.id === parseInt(dsid));
var imetadata0 = imetadata01[0];
//console.log(imetadata0)
var demogr = d3.select("#sample-metadata");
d3.select("#sample-metadata").html("");
demogr.append("tr").text("id: " + imetadata0["id"]);
demogr.append("tr").text("ethnicity: " + imetadata0["ethnicity"]);
demogr.append("tr").text( "gender: " + imetadata0["gender"]);
demogr.append("tr").text("age: " + imetadata0["age"]);
demogr.append("tr").text( "location: " + imetadata0["location"]);
demogr.append("tr").text("bbtype: " + imetadata0["bbtype"]);
demogr.append("tr").text( "wfreq: " + imetadata0["wfreq"]);
//Bubble Chart
var traceb = {
x: isamples0.otu_ids,
y: isamples0.sample_values,
text: isamples0.otu_labels,
mode: 'markers',
marker: {
color: isamples0.otu_ids,
size: isamples0.sample_values
}
};
var bubbleData = [traceb];
//console.log(bubbleData)
var layoutb = {
title: "Subject ID: " + dsid,
showlegend: false,
height: 1000,
width: 1000,
xaxis:{title:{text: 'OTU ID'}},
yaxis:{title:{text: 'Sample Values'}}
}
Plotly.newPlot('bubble', bubbleData, layoutb);
//Gauge Chart
var gdata = [
{
domain: { x: [0, 1], y: [0, 1] },
value: imetadata0.wfreq,
title: { text: "Scrubs per Week, Subject ID: " + dsid, font: {size: 18} },
type: "indicator",
gauge: {
axis: { range: [0, 9], dtick: 1},
steps:[
{ range: [0,1], color: "rgb(237,246,228)" },
{ range: [1,2], color: "rgb(211,233,191)" },
{ range: [2,3], color: "rgb(189,223,159)" },
{ range: [3,4], color: "rgb(164,210,122)" },
{ range: [4,5], color: "rgb(123,188,64)" },
{ range: [5,6], color: "rgb(108,166,56)" },
{ range: [6,7], color: "rgb(86,134,54)" },
{ range: [7,8], color: "rgb(65,101,41)" },
{ range: [8,9], color: "rgb(56,87,85)" }
]},
mode: "gauge+number"
}
];
//var layout = { width: 400, height: 300, margin: { l:100, r:50, t: 0, b: 0 } };
//var layoutg = { width: 400, height: 300, margin: { l:60, r:0, t: 10, b: 10 }};
var layoutg = { width: 400, height: 300, margin: { l:10, r:50, t: 10, b: 10 }};
Plotly.newPlot('gauge', gdata, layoutg);
//pie chart
var piechart = [{
values: isamples0.sample_values.slice(0,10).reverse(),
labels: isamples0.otu_ids2.slice(0,10).reverse(),
//text: isamples0.otu_labels.slice(0,10).reverse(),
title: {text: "Top OTUs Proportion", font: {size: 18} },
type: "pie"
}]
var layoutp = {
height: 500,
width: 500,
showlegend: false,
margin: { l:80, r:50, t: 0, b: 0 }
};
Plotly.newPlot('pie', piechart, layoutp);
}
init();
});
|
module.exports = function (app) {
app.directive('quizMenu', [quizMenu]);
function quizMenu() {
return {
template: require('./menu.template.html'),
scope: {
user: "="
},
controller: function ($scope) {
}
};
}
};
|
var Qapp = Qapp || { Models: {}, Collections: {}, Views: {} };
Qapp.initialize = function() {
var questionCollection = new Qapp.Collections.QuestionCollection();
var questionListView = new Qapp.Views.QuestionListView({
collection: questionCollection,
el: $('#trending')
});
questionCollection.fetch();
// var answersCollection = new Qapp.Collections.AnswerCollection();
// answersCollection.fetch({data: $.param({ }) ,success:function(data){
// console.log("Answers collection fetch working", data);
// }});
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
}
$('#question_form').on('submit', function(e){
e.preventDefault();
var newQuestionInput = $(this).serializeArray();
console.log({content: newQuestionInput[0].value, option_1: newQuestionInput[1].value, option_2: newQuestionInput[2].value, user_id: newQuestionInput[3].value});
questionCollection.create({content: newQuestionInput[0].value, option_1: newQuestionInput[1].value, option_2: newQuestionInput[2].value, user_id: newQuestionInput[3].value});
resetForm($('#question_form'));
});
$('#question_form_this').on('submit', function(e){
e.preventDefault();
var newQuestionInput = $(this).serializeArray();
console.log({content: newQuestionInput[0].value, option_1: newQuestionInput[1].value, option_2: newQuestionInput[2].value, user_id: newQuestionInput[3].value});
questionCollection.create({content: newQuestionInput[0].value, option_1: newQuestionInput[1].value, option_2: newQuestionInput[2].value, user_id: newQuestionInput[3].value});
resetForm($('#question_form_this'));
});
$('#question_form_rank').on('submit', function(e){
e.preventDefault();
var newQuestionInput = $(this).serializeArray();
console.log({content: newQuestionInput[0].value, range_min: newQuestionInput[1].value, range_max: newQuestionInput[2].value, user_id: newQuestionInput[3].value});
questionCollection.create({content: newQuestionInput[0].value, range_min: newQuestionInput[1].value, range_max: newQuestionInput[2].value, user_id: newQuestionInput[3].value});
resetForm($('#question_form_rank'));
});
setTimeout(function(){
$('.answer_form').on('submit', function(e){
console.log("answer form event", e);
console.log("answer form submit working");
e.preventDefault();
var newAnswerInput = $(this).serializeArray();
var self = this;
console.log("answerform this", this, "this.attributes", this.attributes);
if ( $("#useless").attr("class") !== "" ){
console.log({question_id: $('.answer_form').parent().attr('id'), user_id: newAnswerInput[2].value, option_answer: newAnswerInput[0].value, comment: newAnswerInput[1].value});
answersCollection.create({question_id: $('.answer_form').parent().attr('id'), user_id: newAnswerInput[2].value, option_answer: newAnswerInput[0].value, comment: newAnswerInput[1].value});
}
else {
console.log({question_id: $('.answer_form').parent().attr('id'), user_id: newAnswerInput[2].value, range_answer: newAnswerInput[0].value, comment: newAnswerInput[1].value});
answersCollection.create({question_id: $('.answer_form').parent().attr('id'), user_id: newAnswerInput[2].value, range_answer: newAnswerInput[0].value, comment: newAnswerInput[1].value});
}
// **** NEWER **** This will fix the reset form, as well as the nexQuestion issue.
resetForm($(self));
// We will eventually use this to go to the next question, once we include the function for it?
// questionCollection.nextQuestion();
});
}, 2000);
$('.answer_display').on('click', function(){
var questionGraphListView = new Qapp.Views.QuestionListView({
collection: questionCollection,
el: $('#container')
});
questionGraphListView.renderGraphs();
})
$('.answer').on('click', function(){
console.log("answer click working");
var questionAnswerListView = new Qapp.Views.QuestionListView({
collection: questionCollection,
el: $('#answer_container')
});
questionAnswerListView.renderQuestionAnswer();
})
}
$(function() {
Qapp.initialize();
})
|
import './styles/root.scss';
import React, { Component } from 'react';
import { render } from 'react-dom';
import { observer } from 'mobx-react';
import { env } from './store/index';
import { Commands } from './commands';
import { Auth } from './auth';
@observer
export class Root extends Component {
render() {
return do {
if (!env.connected) {
<span>Connecting...</span>
}
else {
<main>
<nav className="flex">
<div className="w-50">
<h1>nibblr</h1>
</div>
<div className="w-50 tr">
<Auth />
</div>
</nav>
<Commands />
<img
className="absolute right-0 bottom-0 nibblr"
src="/nibblr.gif"
/>
</main>
}
}
}
}
render(<Root/>, document.body.appendChild(document.createElement('div')));
|
import React, { useState } from 'react';
import CertificateIconApproved from '../../assets/certificate-icon-approved.svg';
import CertificateIconPending from '../../assets/certificate-icon-pending.svg';
import CertificateIconDeclined from '../../assets/certificate-icon-declined.svg';
const Certificate = props => {
// const immunityStatus = 1; // 0: pending, 1: approved, -1: declined
const determineImmunityStatus = (val) => {
if (val === 1) {
return <img src={CertificateIconApproved} alt=":)" />
}
else if (val === 0) {
return <img src={CertificateIconPending} alt=":|" />
}
else {
return <img src={CertificateIconDeclined} alt=":(" />
}
}
const determineCertificateText = (val) => {
if (val === 1) {
let certificateText1 = 'You have tested positive for antibodies by ';
let hospital = 'vestre sykehus at 06.04.2020'
let certificateText2 = '. This will most likely give immunity.';
let certificateText3 = 'Immunity is issued on the background of completed blood samples and adequate time in quarantine. ';
let certificateText4 = 'Get more info.'
return <span>{certificateText1}<a href={'http://google.com/search?q='+hospital}>{hospital}</a>{certificateText2}<br/><br/>{certificateText3}<a href={'http://google.com/search?q='+certificateText4}>{certificateText4}</a></span>
}
else if (val === 0) {
let certificateText1 = 'You are pending immunity by ';
let hospital = 'vestre sykehus'
let certificateText2 = 'Immunity is issued on the background of completed blood samples and adequate time in quarantine. ';
let certificateText3 = 'Get more info.'
return <span>{certificateText1}<a href={'http://google.com/search?q='+hospital}>{hospital}</a><br/><br/>{certificateText2}<a href={'http://google.com/search?q='+certificateText3}>{certificateText3}</a></span>
}
else {
let certificateText1 = 'You have been labeled not immune.';
let certificateText2 = 'How can I become immune?';
return <span>{certificateText1}<br/><br/><a href={'http://google.com/search?q=how to become immune covid-19'}>{certificateText2}</a></span>
}
}
const [ expandBox, setExpandBox ] = useState(false);
const handleExpandBox = () => {
setExpandBox(!expandBox);
const button = document.getElementById('expandbutton');
const content = document.getElementById('content');
console.log(content);
if (expandBox) {
button.style.transform = 'rotate(90deg)'
content.style.maxHeight = '0';
content.style.opacity = '0';
content.style.padding = '0 0';
}
else {
button.style.transform = 'rotate(270deg)';
content.style.maxHeight = '300px';
content.style.opacity = '1';
content.style.padding = '25px 0';
}
}
return (
<div className="certificate">
<div className="certificate__wrapper">
<div className="certificate__top">
{ determineImmunityStatus(props.immunityStatus) }
<div className="certificate__text">
<div className="certificate__text-title">Certificate of immunity</div>
<div className="certificate__text-name">Farao Frisk</div>
</div>
</div>
<div id={"content"} className="certificate__content">
{ determineCertificateText(props.immunityStatus) }
</div>
<div onClick={handleExpandBox} id="expandbutton" className="certificate__expand-button"></div>
</div>
</div>
);
};
export default Certificate;
|
(function() {
$(function() {
$('a[href="#fakelink"]').click(function(e) {
return e.preventDefault()
});
$('a.droplink').click(function(e) {
var $drop, $link;
$link = $(e.currentTarget);
$drop = $link.siblings('.dropdown');
if ($link.is('.active') || $drop.is('.active')) {
$link.removeClass('active');
$drop.removeClass('active');
} else {
$link.addClass('active');
$drop.addClass('active');
}
return false;
});
$('.js-clipboard').each(function() {
var $btn = $(this)
if (!$btn.data('zeroclipboard-bound')) {
$btn.attr('data-clipboard-text', $('#' + $btn.data('ref-id')).text().trim())
$btn.data('zeroclipboard-bound', true)
var clip = new ZeroClipboard(this)
clip.on('aftercopy', function(e) {
$this = $(e.target)
var html = $this.html()
$this.html('<i class="icon icon-clipboard pad0r"></i>' + 'Copied to clipboard!')
setTimeout(function() {
$this.html(html)
}, 1000);
});
}
});
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;
matches = [];
substrRegex = new RegExp(q, 'i');
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push({ value: str });
}
});
cb(matches);
};
};
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];
$('.typeahead').typeahead({
hint: true,
highlight: true,
},
{
name: 'states',
displayKey: 'value',
source: substringMatcher(states)
});
$('#tags-green').tagsinput({
tagClass: 'fill-green'
});
$('#tags-typeahead').tagsinput({
typeaheadjs: {
name: 'states',
displayKey: 'value',
valueKey: 'value',
source: substringMatcher(states)
}
});
$('[data-toggle="tooltip"]').tooltip()
$('.datepicker').each(function(index, value) {
new Pikaday({ field: value });
});
document.body.className += ' animate'
window.prettyPrint && prettyPrint()
});
}).call(this);
|
import FireService from './FireService';
import SettingsService from './SettingsService';
import UserService from './UserService';
import storageFactory from "./StorageFactory";
const localStore = storageFactory(localStorage);
const sessionStore = storageFactory(sessionStorage);
export {
FireService,
SettingsService,
UserService,
localStore,
sessionStore
};
|
'use strict';
var envvar = require('envvar');
var express = require('express');
var bodyParser = require('body-parser');
var moment = require('moment');
var plaid = require('plaid');
var Req = require('request');
var APP_PORT = envvar.number('APP_PORT', 8000);
var PLAID_CLIENT_ID = envvar.string('PLAID_CLIENT_ID');
var PLAID_SECRET = envvar.string('PLAID_SECRET');
var PLAID_PUBLIC_KEY = envvar.string('PLAID_PUBLIC_KEY');
var PLAID_ENV = envvar.string('PLAID_ENV', 'sandbox');
// We store the access_token in memory - in production, store it in a secure
// persistent data store
var ACCESS_TOKEN = null;
var PUBLIC_TOKEN = null;
var ITEM_ID = null;
// Initialize the Plaid client
var client = new plaid.Client(
PLAID_CLIENT_ID,
PLAID_SECRET,
PLAID_PUBLIC_KEY,
plaid.environments[PLAID_ENV]
);
var app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: false
}));
app.disable('x-powered-by');
app.use(bodyParser.json());
app.get('/', function(request, response, next) {
response.render('index.ejs', {
PLAID_PUBLIC_KEY: PLAID_PUBLIC_KEY,
PLAID_ENV: PLAID_ENV,
});
});
app.post('/get_access_token', function(request, response, next) {
PUBLIC_TOKEN = request.body.public_token;
/*
** ONLY FOR TESTING PURPOSES, you can change userid to
** any of the users available in the database.
*/
console.log("sending request");
Req.post(
'http://localhost:8000/createaccounts',
{ json: { public_token: PUBLIC_TOKEN, userid: 2}},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
else {
console.log("User Account succesfully processed in database")
}
}
);
});
app.get('/accounts', function(request, response, next) {
// Retrieve high-level account information and account and routing numbers
// for each account associated with the Item.
client.getAuth(ACCESS_TOKEN, function(error, authResponse) {
if (error != null) {
var msg = 'Unable to pull accounts from the Plaid API.';
console.log(msg + '\n' + JSON.stringify(error));
return response.json({
error: msg
});
}
console.log(authResponse.accounts);
response.json({
error: false,
accounts: authResponse.accounts,
numbers: authResponse.numbers,
});
});
});
app.post('/transactions', function(request, response, next) {
// Pull transactions for the Item for the last 30 days
var startDate = moment().subtract(30, 'days').format('YYYY-MM-DD');
var endDate = moment().format('YYYY-MM-DD');
client.getTransactions(ACCESS_TOKEN, startDate, endDate, {
count: 250,
offset: 0,
}, function(error, transactionsResponse) {
if (error != null) {
console.log(JSON.stringify(error));
return response.json({
error: error
});
}
console.log('pulled ' + transactionsResponse.transactions.length + ' transactions');
response.json(transactionsResponse);
});
});
var server = app.listen(3000, function() {
console.log('plaid-walkthrough server listening on port 3000');
});
|
'use strict'
import nodeDebug from 'debug'
import express from 'express'
import TweetsService from './../services/TweetsService'
import TweetsWorker from './../services/TweetsWorker'
import {
prepareWebsocketResponse
} from './../utils'
const debug = nodeDebug('tweetwall:routes')
export default () => {
const router = express.Router()
router.get('/', (req, res) => {
debug('GET: /')
res.render('index')
})
router.get('/tweets.json', (req, res) => {
debug('GET: /tweets.json')
TweetsService.getTweets()
.then((tweetsList) => {
res.json(tweetsList)
})
.catch((err) => {
debug(err)
res.status(500).json({message: 'Internal Server Error!'})
})
})
router.get('/leads.json', (req, res) => {
debug('GET: /leads.json')
TweetsService.getLeads()
.then((leadsList) => {
res.json(leadsList)
})
.catch((err) => {
debug(err)
res.status(500).json({message: 'Internal Server Error!'})
})
})
router.ws('/timeline.io', (ws, req) => {
debug('WS: /timeline.io')
ws.on('connected', () => {
TweetsWorker.on('error', (err) => {
ws.send(prepareWebsocketResponse(err))
})
})
})
return router
}
|
import { contactAdded, contactUpdated, contactDeleted } from "./events.js";
import { domCache } from './domCache.js';
export let contactAPI;
(function() {
const ContactAPI = (function() {
const URI = 'http://localhost:3000/api/contacts';
let xhRequest = new XMLHttpRequest(),
currentMethod,
activeCallback;
// remove activeCallback to prevent redundant actions
xhRequest.addEventListener("loadend", () => {
xhRequest.removeEventListener("load", activeCallback);
});
// encode form into uri components
const encode = function encodeForm(form) {
let encodedStrings = [];
for (let keyPair of form.entries()) {
encodedStrings
.push(keyPair
.map(val => encodeURIComponent(val))
.join("="));
}
return encodedStrings.join("&");
};
// send request based on method and parameters
const request = function requestWithParams(method, params) {
currentMethod = method.toLowerCase();
let id = params.id,
contactForm = params.contactForm,
url = URI;
activeCallback = params.callback;
if (id) url += `/${id}`;
xhRequest.open(method, url);
xhRequest.responseType = 'json';
xhRequest.addEventListener("load", activeCallback);
if (contactForm) {
xhRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhRequest.send(encode(contactForm));
} else {
xhRequest.send();
}
};
return {
method() {
return currentMethod;
},
allContacts(callback) {
request('GET', {callback});
},
oneContact(id, callback) {
request('GET', {id, callback});
},
addContact(contactForm) {
const callback = function addContactCallback(event) {
contactAdded.detail.contact = event.target.response;
document.dispatchEvent(contactAdded);
};
request('POST', {contactForm, callback});
},
editContact(id, contactForm) {
const callback = function updateContactCallback(event) {
contactUpdated.detail.contact = event.target.response;
document.dispatchEvent(contactUpdated);
};
request('PUT', {id, contactForm, callback});
},
delContact(id) {
const callback = function delContactCallback(event) {
let status = event.target.status,
contactId = event.target.responseURL.split('/').pop();
if (status === 204) {
contactDeleted.detail.success = true;
contactDeleted.detail.contact = domCache.spliceContact(contactId)[0];
} else {
contactDeleted.detail.success = false;
}
document.dispatchEvent(contactDeleted);
};
request('DELETE', {id, callback});
},
init() {
return this;
}
}
})();
contactAPI = Object.create(ContactAPI).init();
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.