text
stringlengths 7
3.69M
|
|---|
/**
* Tabs Component
* @author yan
*/
import React,{ PureComponent, cloneElement, Children } from 'react';
import PropTypes from 'prop-types';
import Tab from './Tab';
import Icon from '../icon';
import CSSModules from 'react-css-modules';
import classNames from 'classnames';
import { allowMultiple } from '../../constants';
import styles from './Tabs.css';
@CSSModules(styles, { allowMultiple })
export default class Tabs extends PureComponent {
static displayName = 'Tabs'
static defaultProps = {
defaultActiveKey: 0,
type:'line',
size:'default',
tabPosition:'top',
}
static propTypes = {
type:PropTypes.oneOf([
'line',
'card',
'button'
]),
size:PropTypes.oneOf([
'default',
'small',
]),
tabPosition:PropTypes.oneOf([
'top',
'left',
]),
activeKey: PropTypes.number,
defaultActiveKey: PropTypes.number,
}
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.deleteButton = this.deleteButton.bind(this);
this.getPanel = this.getPanel.bind(this);
this.state = {
activeKey: props.activeKey || props.defaultActiveKey,
children: props.children,
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.activeKey !== this.state.activeKey) {
this.setState({
activeKey: nextProps.activeKey
})
}
if (nextProps.children !== this.state.children) {
this.setState({
children: nextProps.children
})
}
}
onClick=(activeKey)=> {
const props = this.props;
if(props.children[activeKey].props.disabled){
return
}
if (props.onClick) {
props.onClick(activeKey);
}
this.setState({
activeKey: activeKey,
panelUpdateKey: -1
})
}
deleteButton = (key)=> {
this.props.deleteButton();
this.setState({
panelUpdateKey: key
})
}
getPanel = () => {
var that = this;
let tab = [];
let panel = [];
Children.forEach(this.state.children, function(children, index) {
// add tabs
let status, className;
status = index === that.state.activeKey ? 'active' : 'inactive';
var props = {
key: 'tab'+index,
tabKey: index,
title: children.props.title,
status: status,
disabled:children.props.disabled,
closable:children.props.closable,
style: that.state.style,
onClick: that.onClick,
tabDeleteButton: that.props.tabDeleteButton,
deleteButton: that.deleteButton,
}
tab.push(<Tab {...props}/>);
if (index === that.state.activeKey) {
var props = {className: classNames('tabs__panel', status), status: status, key: index};
if (that.state.panelUpdateKey === index) {
props.update = true;
}
panel.push(cloneElement(children, props));
}
})
return {tab: tab, panel: panel};
}
render() {
var opt = this.getPanel();
const props = this.props;
const{type,size,tabPosition, ...otherProps} = props;
const cls = classNames({
['tabs__card'] : type === 'card',
['tabs__button'] : type === 'button',
['tabs__small'] : size === 'small',
['tabs__left clearfix'] : tabPosition === 'left',
['tabs__wrap'] : true,
})
return(
<div styleName={cls}>
<div styleName={'tabs__bar'}>
{opt.tab}
</div>
<div styleName={'tabs__con'}>
{opt.panel}
</div>
</div>
);
}
}
|
//New in ES6: Object destructuring. Take an attribute of an obj and turn its name value
//pair into a variable.
// var user = { name: 'Jeroen', age: 28};
// var {name} = user; (name:name , value: Jeroen)
//real example:
// const MongoClient = require('mongodb').MongoClient;
const {MongoClient, ObjectID} = require('mongodb');
MongoClient.connect('mongodb://localhost:27017/TodoApp',(err, db) => {
if(err) {
return console.log('Unable to connnect to MongoDB server');
}
console.log('Connected to MongoDB server');
// db.collection('Todos').insertOne({
// text: 'Something to do',
// completed: false
// },(err, result) => {
// if(err) {
// return console.log('Unable to insert new Todo');
// }
// //res.ops: ops attribute is an array of all inserted docs
// console.log(JSON.stringify(result.ops, undefined, 2))
// })
db.collection('Users').insertOne({
name: 'John',
age: 28,
location: 'Brisbane'
}, (err, result) => {
if(err) {
return console.log('Unable to insert new doc');
}
console.log(JSON.stringify(result.ops[0]._id.getTimestamp(),undefined,2))
});
db.close();
});
|
var mexerBracoEsquerdo = 0;
var mexerBracoDireito = 0;
var kanoHead
var kanoBody
var kanoBracoEsquerdo
var kanoBracoDireito
var kanoPernaEsquerda
var kanoPernaDireita
function setup() {
createCanvas(500, 500);
kanoHead = loadImage('assets/head.png');
kanoBody = loadImage('assets/kano-body.png');
kanoBracoEsquerdo = loadImage('assets/kano-braco-esquerdo.png');
kanoBracoDireito = loadImage('assets/kano-braco-direito.png')
kanoPernaEsquerda = loadImage('assets/kano-perna-esquerdo.png')
kanoPernaDireita = loadImage('assets/kano-perna-direita.png')
}
function draw() {
background(255);
push();
translate(225, 10);
image(kanoHead, -55, 0);
fill(255);
circle(0,0,4);
pop();
push();
translate(225, 100);
image(kanoBody, -55, 10);
fill(255);
pop();
push();
translate(205, 255);
image(kanoPernaEsquerda, -55, 0)
fill(255);
circle(0,0,4);
pop();
push();
translate(258, 255);
image(kanoPernaDireita, -18, 0)
fill(255);
circle(0,0,4);
pop();
push();
translate(160, 130);
rotate(radians(mexerBracoEsquerdo))
image(kanoBracoEsquerdo, -65, -17, 66, 175)
fill(255);
circle(0,0,4);
pop();
push();
translate(290, 130);
rotate(radians(mexerBracoDireito))
image(kanoBracoDireito, 0, -20)
fill(255);
circle(0,0,4);
pop();
}
function keyPressed() {
if (keyCode === 68 & mexerBracoDireito == 0) {
mexerBracoDireito = -30;
} else if (keyCode === 68 & mexerBracoDireito == -30) {
mexerBracoDireito = 0;
}
if (keyCode === 69 & mexerBracoEsquerdo == 0) {
mexerBracoEsquerdo = 30;
} else if (keyCode === 69 & mexerBracoEsquerdo == 30) {
mexerBracoEsquerdo = 0;
}
}
|
const { hot } = require("react-hot-loader/root")
// prefer default export if available
const preferDefault = m => (m && m.default) || m
exports.components = {
"component---cache-dev-404-page-js": hot(preferDefault(require("/home/student/Coding/projects/gatsby/gatsby-portfolio/.cache/dev-404-page.js"))),
"component---src-pages-404-js": hot(preferDefault(require("/home/student/Coding/projects/gatsby/gatsby-portfolio/src/pages/404.js"))),
"component---src-pages-about-js": hot(preferDefault(require("/home/student/Coding/projects/gatsby/gatsby-portfolio/src/pages/about.js"))),
"component---src-pages-blog-js": hot(preferDefault(require("/home/student/Coding/projects/gatsby/gatsby-portfolio/src/pages/blog.js"))),
"component---src-pages-contact-js": hot(preferDefault(require("/home/student/Coding/projects/gatsby/gatsby-portfolio/src/pages/contact.js"))),
"component---src-pages-index-js": hot(preferDefault(require("/home/student/Coding/projects/gatsby/gatsby-portfolio/src/pages/index.js"))),
"component---src-templates-page-js": hot(preferDefault(require("/home/student/Coding/projects/gatsby/gatsby-portfolio/src/templates/page.js"))),
"component---src-templates-tags-js": hot(preferDefault(require("/home/student/Coding/projects/gatsby/gatsby-portfolio/src/templates/tags.js")))
}
|
import { makeStyles } from '@material-ui/core'
import React from 'react'
const useStyle = makeStyles((theme) => ({
paperStyle: {
backgroundColor:
}
}))
function Style() {
return (
<div>
</div>
)
}
export default Style
|
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
let hash = {};
let builder = [];
let results = [];
resolve(nums, hash, builder);
for (let key in hash) {
results.push(hash[key]);
}
return results;
};
function tryAddToResults(builder, results) {
let sum = null;
let key = "";
let builder2 = builder.slice(0).sort();
for (let i = 0; i < builder.length; i++) {
sum += builder2[i];
key += builder2[i].toString();
}
if (sum == 0) {
results[key] = builder.slice(0);
}
}
function resolve(nums, hash, builder) {
if (builder.length === 3) {
tryAddToResults(builder, hash);
return;
}
for (let i = 0; i < nums.length; i++) {
builder.push(nums[i]);
let nums2 = nums.slice(i + 1);
resolve(nums2, hash, builder);
builder.pop();
}
}
console.log(JSON.stringify(threeSum([1, -1, -1, 0])));
// console.log(JSON.stringify(threeSum([1, -1, -1, 0])));
// console.log(JSON.stringify(threeSum([-1, 1, 0])));
// console.log(JSON.stringify(threeSum([-1, 0, 1, 2, -1, -4])));
|
const _ = require('lodash')
//Compose middleware package can be used here later on to compose multiple middlewares into a single array
const middleware = {
// VERIFY USER LOGGED IN
isLoggedIn: function (req, res, next) {
var incomingToken = req.body.token || req.query.token || req.headers['x-fake-token']
if (incomingToken) {
const preDefinedToken =process.env.FAKE_TOKEN
if (_.toString(incomingToken) === _.toString(preDefinedToken)) {
req.decoded = incomingToken
return next()
}
return res.status(401).json('Not Authorized..please try to login again')
}
return res.status(401).json('You cannot perform this action unless you are logged in')
}
}
module.exports = middleware
|
/*
var firstElement = '';
var formElements;
var currentElement = '';
var currentElementIndex = 0
var highlightElement;
Event.observe(
window,
'load',
function(e) {
// Get the form elements
formElements = Form.getElements('movieForm');
// Find the first element on the form
firstElement = formElements.find(function(element) {
return element.type != 'hidden' && !element.disabled &&
['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
});
if (highlightElement != 'undefined') {
Field.focus(highlightElement);
currentElement = highlightElement;
}
else {
// Focus on the first element on the form
Field.focus(firstElement);
highlightElement = firstElement;
// Set the current element and current element index to the first element
currentElement = firstElement;
currentElementIndex = formElements.indexOf(firstElement);
}
// 'Highlight' the first element
Element.classNames(highlightElement).add('selectedField');
}
);
Event.observe(document, 'keyup', processKeys);
Event.observe(document, 'click', processKeys);
function processKeys(evt) {
// Get the element that triggered the event
var htmlElement = Event.element(evt);
// If this is indeed an html element
if (htmlElement.id != '') {
if (currentElement != '') {
if (formElements[currentElementIndex].type == 'checkbox') {
Element.classNames(currentElement.parentNode).remove('selectedField');
}
else {
// Remove the 'Highlight' from the current element
Element.classNames(currentElement).remove('selectedField');
}
//if (t != '') {Element.remove("test")};
}
// Get the index of the element as it falls in the form elements array
currentElementIndex = formElements.indexOf(htmlElement);
if (currentElementIndex != -1) {
// Also get the actual form element
currentElement = formElements[currentElementIndex];
if (formElements[currentElementIndex].type == 'checkbox') {
Element.classNames(currentElement.parentNode).add('selectedField');
}
else {
// 'Highlight' the form element
Element.classNames(currentElement).add('selectedField');
}
}
}
}
/*Event.observe(
'movieForm',
'submit',
function(e) {
//if (CheckForEnterKey(e)) {
var tempVar = $F('Name');
tempVar = tempVar.capitalize();
$('Name').value = tempVar;
//}
}
);
function CheckForEnterKey(e)
{
var characterCode;
var characterCode = e.keyCode;
//if generated character code is equal to ascii 13 (if enter key)
if (characterCode == Event.KEY_RETURN) {
return true;
}
else {
return false;
}
}
*/
|
const logger = require('../../../services/loggerService');
const utilService = require('../../../services/utilService');
const collectorService = require('../../../services/collectorService');
Page({
data: {
id: '',
telephone: ''
},
onLoad: function (options) {
this.setData({
id: options.id
})
},
inputTyping: function (e) {
this.setData({
telephone: e.detail.value
});
},
bind: function () {
if (!this.data.telephone) {
utilService.showToast('请输入手机号');
} else {
collectorService.bindTelephone.call(this, this.data.id, this.data.telephone).then(data => {
utilService.toPage({
url: '/pages/index/index'
}, true);
}).catch(err => {
utilService.showToast(err);
})
}
}
})
|
/**
* Internal dependencies
*/
import composeWithContainer from './composeWithContainer';
const composeWithContainerFrontend = composeWithContainer;
export default composeWithContainerFrontend;
|
const { series, parallel, src, dest } = require("gulp");
const gulp = require("gulp"),
less = require("gulp-less"),
autoprefixer = require("gulp-autoprefixer"),
browserSync = require("browser-sync").create();
gulp.task("less", function () {
return src("./src/assets/styles/main.less")
.pipe(less())
.pipe(
autoprefixer({
cascade: false,
})
)
.pipe(dest("./dist"));
});
gulp.task("html", function () {
return gulp.src("./src/views/*.html").pipe(gulp.dest("./dist"));
});
gulp.task("js", function () {
return gulp.src("./src/assets/scripts/*.js").pipe(gulp.dest("./dist"));
});
gulp.task("images", function () {
return gulp.src("./src/assets/images/*").pipe(gulp.dest("./dist/images"));
});
gulp.task("serve", function () {
browserSync.init({
server: {
baseDir: "dist",
},
});
gulp.watch("./src/assets/scripts/*.js").on("change", series("js"));
gulp.watch("./src/assets/styles/**/*.less").on("change", series("less"));
gulp.watch("./src/views/index.html").on("change", series("html"));
gulp.watch("./dist/*.js").on("change", series("js"));
gulp.watch("./dist/main.css").on("change", browserSync.reload);
gulp.watch("./dist/*.html").on("change", browserSync.reload);
});
gulp.task("build", series("less", "js", "images", "html"));
gulp.task("default", series(parallel("html", "less", "js", "images"), "serve"));
|
const express = require('express')
const fs = require('fs')
const { EOL } = require('os')
const app = express()
const logsPath = '../../logs/' + Date.now() + '.log'
/**
* 5000条200长度字符串:3.0s
*/
app.get('/writeFile', (req, res) => {
const content = req.query.content
fs.writeFile(logsPath, content + EOL, { flag: 'a', encoding: 'utf-8' }, (err) => {
res.send('ok')
})
})
/**
* 5000条200长度字符串:2.8s
* 10000条200长度字符串:炸
*/
app.get('/appendFile', (req, res) => {
const content = req.query.content
fs.appendFile(logsPath, content + EOL, 'utf8', (err) => {
res.send('ok')
})
})
/**
* 10000条200长度字符串:8.061s
*/
app.get('/appendFileSync', (req, res) => {
const content = req.query.content
fs.appendFileSync(logsPath, content + EOL, 'utf8')
res.send('ok')
})
/**
* 10000条200长度字符串:10.238s
*/
const stream = fs.createWriteStream(logsPath, { flags: 'a' })
app.get('/writeStream', (req, res) => {
stream.write(req.query.content + EOL, (err) => {
res.send('ok')
})
})
const server = app.listen(6000)
server.setTimeout(0)
|
// Field instance:
//
// - `__isField__: true`
//
// - `getName(): String`, returns field name
// - `setName(String)`, sets field name (only once!)
//
// - `getType(): Type`, returns field type
//
// - `id: Field`, sets field `id` property to `true`
// - `getId(): boolean`, returns field `id` property
// - `setId(boolean): Field`, sets field `id` property
//
// - `calc(function): Field`, sets field `calc` property (only once!)
// - `getCalc(): function`, returns field `calc` property
//
// - `validate(function): Field`, adds validation to the field
// - `getValidators(): Array[function]`, returns field validators
// - builtin validators: `presence`, `inclusion`, `greaterThan`, etc.
import { setValidateMethods } from './validate'
import inclusion from './validators/inclusion'
import presence from './validators/presence'
import { greaterThan, greaterOrEqualTo, lessThan, lessOrEqualTo } from './validators/numeric'
const nameRegex = /^[a-z][a-z0-9_]*$/i
export function createField(type) {
if (type == null || !type.__isType__) {
throw new Error(`Field type is not a valid Reforma type: ${type}`)
}
const privateData = {
name: null,
id: false,
calc: null,
validators: []
}
const field = {}
setFieldness(field)
setFieldType(field, type)
setNameMethods(field, privateData)
setIdMethods(field, privateData)
setCalcMethods(field, privateData)
setValidateMethods(field, privateData)
setBuiltInValidatorMethods(field, type)
return field
}
// -- PRIVATE
function setFieldness(field) {
Object.defineProperty(field, '__isField__', { value: true })
}
function setFieldType(field, type) {
function getType() {
return type
}
Object.defineProperty(field, 'getType', { value: getType })
}
function setNameMethods(field, data) {
function getName() {
return data.name
}
function setName(name) {
const isValidName = typeof name === 'string' && nameRegex.test(name)
if (!isValidName) {
throw new Error(`Illegal field name: ${name}`)
}
if (data.name != null && data.name !== name) {
throw new Error('Field name is already defined')
}
data.name = name
}
Object.defineProperty(field, 'getName', { value: getName })
Object.defineProperty(field, 'setName', { value: setName })
}
function setIdMethods(field, data) {
function getter() {
data.id = true
return field
}
function getId() {
return data.id
}
function setId(newValue) {
data.id = !!newValue
}
// `id=true` is valid state only for primitive types
// therefore, changind `id` is only allowed for primitive types
if (field.getType().__isPrimitiveType__) {
Object.defineProperty(field, 'id', { get: getter })
Object.defineProperty(field, 'setId', { value: setId })
}
Object.defineProperty(field, 'getId', { value: getId })
}
function setCalcMethods(field, data) {
function getCalc() {
return data.calc
}
function isCalculable() {
return data.calc != null
}
function calc(calcFn) {
if (typeof calcFn !== 'function') {
throw new Error('Specify function in `calc`')
}
if (data.calc != null) {
throw new Error('Only single assignment permitted in `calc`')
}
data.calc = calcFn
return field
}
Object.defineProperty(field, 'getCalc', { value: getCalc })
Object.defineProperty(field, 'calc', { value: calc })
Object.defineProperty(field, 'isCalculable', { get: isCalculable })
}
function setBuiltInValidatorMethods(field, type) {
function defineValidator(name, validatorFn) {
Object.defineProperty(field, name, {
value: function () {
field.validate(validatorFn.apply(null, arguments))
return field
}
})
}
if (type.name === 'integer' || type.name === 'float') {
defineValidator('greaterThan', greaterThan)
defineValidator('greaterOrEqualTo', greaterOrEqualTo)
defineValidator('lessThan', lessThan)
defineValidator('lessOrEqualTo', lessOrEqualTo)
}
defineValidator('presence', presence)
defineValidator('inclusion', inclusion)
}
|
const commands = {
summon(entity) {
console.log(`Summoning ${entity}...`)
},
tp(x, y, z) {
console.log("Teleporting to", x, y, z)
},
test() {
console.log("test")
}
}
console.log("-------------------------")
// using variables
let input = "test"
commands[input]()
// is the same as:
commands.test()
console.log("-------------------------")
// How to parse array of commands:
input = "summon cow"
input = input.split(" ") // turn string into array of strings
commands[input[0]](input.slice(1))
// "summon" "cow"
console.log("-------------------------")
// Multiple arguments:
input = "tp ~ ~1 ~"
input = input.split(" ") // turn string into array of strings
// use array destructuring to pass as arguments instead of the raw array
commands[input[0]](...input.slice(1))
// Note what happens without the dots.
commands[input[0]](input.slice(1))
console.log("-------------------------")
|
import React from 'react';
import socialSvg from '../images/sprite.svg';
const Footer = () => {
return(
<footer className="footer">
<svg className="footer__logo">
<use xlinkHref={socialSvg + "#icon-portfolio-logo2"}></use>
</svg>
<p className=" footer__text">
2018 ©
Made by yours truly using <svg className="social__icon"><use xlinkHref={socialSvg + "#icon-brand2"}></use></svg> with
<svg className="social__icon"><use xlinkHref={socialSvg + "#icon-brand4"}></use></svg>
and styled using
<svg className="social__icon"><use xlinkHref={socialSvg + "#icon-brand5"}></use></svg>
</p>
</footer>
)
}
export default Footer;
|
$(function () {
var currentPage = 1;
var pageSize = 20;
function render() {
$.ajax({
type: "get",
url: "/category/queryTopCategoryPaging",
data: {
page: currentPage,
pagesize: pageSize
},
success: function (data) {
// console.log(data);
//调用artTemplate方法,第一个参数是id号,第二个参数是数据
var html = template('tpl', data);
$('.lt_content tbody').html(html);
$('#paginator').bootstrapPaginator({
bootstrapMajorVersion: 3,//指定版本,默认版本是2,只有div,如果指定3,div中要放ul
currentPage: currentPage,//当前的页码
size: "small",
totalPages: Math.ceil(data.total / pageSize),
numberOfPages: 5, //总共显示几个页数在上边
onPageClicked: function (event, originalEvent, type, page) {
currentPage = page;
render();
}
});
}
});
}
render();
$('.myaddBtn').on('click', function () {
$('#myModal2').modal('show');
});
//先进行表单验证
var $form = $('#form');
$form.bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
categoryName: {
validators: {
notEmpty: {
message: "一级分类名不能为空",
}
}
}
}
}).on('success.form.bv', function (e) {
e.preventDefault();
var bv = $form.data('bootstrapValidator');
//这个提交按钮不用点击事件,在上边表单验证的时候,其实已经进行了点击验证,下面再去验证就会重叠
// $('.addCate').on('click', function () {
//获取表单里的内容
// var val = $('#myModal2 input').val();
// console.log(val);
$.ajax({
type: "POST",
url: "/category/addTopCategory",
data: $form.serialize(),
success: function (data) {
// console.log(data);
$('#myModal2').modal('hide');
render();
//重置表单
bv.resetForm();
//表单有一个reset方法,会把表单中所有的值都清空,这是js对象的方法
$form[0].reset();
}
});
//重置表单不能用 设置为空,这样的话,如果表单很多的话,就会很坑
// val = "";
// });
});
})
|
/* eslint-disable react/no-unescaped-entities */
import React from "react";
/* import { connect } from "react-redux";
import * as courseActions from "../../../redux/actions/courseActions";
import PropTypes from "prop-types";
import { bindActionCreators } from "redux"; */
import "bootstrap/dist/css/bootstrap.min.css";
import Jumbotron from "react-bootstrap/Jumbotron";
import Accordion from "react-bootstrap/Accordion";
import Card from "react-bootstrap/Card";
import Image from "react-bootstrap/Image";
import store1 from "./store1.jpg";
class Week5 extends React.Component {
render() {
return (
<Jumbotron>
<h2> Week 5: Local Storage</h2>
<Accordion defaultActiveKey="0">
<Card>
<Accordion.Toggle as={Card.Header} eventKey="1">
API
</Accordion.Toggle>
<Accordion.Collapse eventKey="0">
<Card.Body>
<Card.Title>Local Storage: API</Card.Title>
<Card.Text>
{""}
LocalStorage object stores the data with no expiration data.
The data will not be deleted when the browser is closed, and
will be available the next day, week, or year. localStorage
does this with no expiration data. sessionStorage stores data
for only one session, when the browser tab is closed.
<br />
<br />
<Image src={store1} fluid />
<br />
As seen above the information is localStorage.setItem() into
the localStorage. Then if it is ever needing to be requested
use the localStorage.getItem().
<br />
<br />
<i>
Source: https://www.w3schools.com/html/html5_webstorage.asp
</i>
</Card.Text>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</Jumbotron>
);
}
}
export default Week5;
|
import React, { useState, useContext } from "react";
import NavBar from "./components/NavBar";
import List from "./components/List";
import User from "./components/User";
import PostId from "./components/PostId";
import { HashRouter, Route, Switch, Redirect } from "react-router-dom";
import "./App.css";
import JavascriptTimeAgo from "javascript-time-ago";
import es from "javascript-time-ago/locale/es";
import NoPage from "./components/NoPage";
import CommentsPost from "./components/CommentsPost";
import MobileNotif from "./components/MobileNotif";
import ViewFollows from "components/ViewFollows";
import Directs from "components/Directs/index";
import AddPost from "components/AddPost";
import Login from "components/Login";
import { useUser } from "reactfire";
import firebase from "firebase/app";
import getUserMail from "components/services/getUserMail";
import SignUp from "components/SignUp";
import Loading from "components/Loading";
import Context from 'components/Context/AppContext';
import getImgUser from "components/services/getImgUser";
import EditProfile from "components/EditProfile";
/* import syncronicUsers from "components/services/syncronicUsers"; */
import 'react-notifications/lib/notifications.css';
JavascriptTimeAgo.locale(es);
function App() {
const [mode, setMode] = useState(
(window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches) ||
false
);
const handleChangeMode = () => setMode(!mode);
const {profile, setProfile} = useContext(Context);
/* syncronicUsers(); */
const [newPost, setNewPost] = useState(null);
const handleSetImgNewPost = (img) => setNewPost(img);
const [user, setUser] = useState(useUser());
const handleSetUser = (u) => {
setProfile(null);
setUser(u);
}
const handleLogoutUser = () => {
firebase.auth().signOut();
setUser(null);
setProfile(null);
};
const getAccount = async () => {
setLoading(true);
const account = await getUserMail(user.email);
if (!account) {
setLoading(false);
setProfile("none");
} else {
const img = await getImgUser(account.user);
setProfile({
...account.data,
user: account.user,
picture: img
});
setLoading(false);
}
};
const [loading, setLoading] = useState(false);
if (loading) return <Loading allpage dark={mode} />;
if (!user || !profile || profile === "none") {
if (user && !profile) getAccount();
return (
<HashRouter basename="/">
<Switch>
<Route exact path="/login">
<Login user={user} setUser={handleSetUser} setProfile={setProfile} />
</Route>
<Route exact path="/signup">
<SignUp user={user} setUser={handleSetUser} setProfile={setProfile} />
</Route>
<Redirect to="/login" />
</Switch>
</HashRouter>
);
}
return (
<div className={mode ? "dark" : "light"}>
<HashRouter basename="/">
{newPost !== null ? (
<div className="content-app">
<div className="app">
<AddPost setImg={handleSetImgNewPost} img={newPost} />
</div>
</div>
) : (
<React.Fragment>
<NavBar
setImg={handleSetImgNewPost}
setMode={handleChangeMode}
/>
<div className="content-app">
<div className="app">
<Switch>
<Route exact path="/addPost" component={AddPost} />
<Route
exact
path="/notifications"
component={MobileNotif}
/>
<Route
exact
path="/comments/:id"
component={CommentsPost}
/>
<Route exact path="/search">
<NoPage construction />
</Route>
<Route exact path="/explore">
<NoPage construction />
</Route>
<Route exact path="/directs">
<Directs />
</Route>
<Route exact path="/likes/:id">
<ViewFollows likes />
</Route>
<Route exact path="/posts/:id" component={PostId} />
<Route exact path="/follows/:user">
<ViewFollows follows />
</Route>
<Route exact path="/followers/:user">
<ViewFollows followers />
</Route>
<Route exact path="/login">
<Redirect to="/" />
</Route>
<Route exact path="/signup">
<Redirect to="/" />
</Route>
<Route exact path="/account/edit">
<EditProfile />
</Route>
<Route exact path="/:user">
<User handleLogoutUser={handleLogoutUser}/>
</Route>
<Route exact path="/" component={List} />
</Switch>
<p className="footer">
© 2020 PUPIGRAM DESARROLLADO POR{" "}
<a
href="https://www.linkedin.com/in/pupimarti/"
target="_blank"
rel="noopener noreferrer"
>
JUAN A. MARTÍ
</a>
</p>
</div>
</div>
</React.Fragment>
)}
</HashRouter>
</div>
);
}
export default App;
|
// Breaking down the Pager Component
// TODO Constructor => would like to turn this into a closure that returns the prototyped object
var Pager = (function(data, root) {
var app;
var Mod = function(data, root) {
app = this;
app.pages;
app.currentPage;
app.currentBackground;
app.root = root;
app.data = $(data);
app.disabled = false;
app.div = app.buildEmptyMarkup();
// Collections
app.bgs = [];
app.events = [];
app.pageCache = [];
app.accordions = [];
app.pages = app.data.find('page');
app.init();
}
Mod.prototype = {
/**
* Sets up the pages and adds backgrounds,
* also delegates click events
*/
init: function() {
app.setBackgrounds();
app.delegateEvents();
// Show first page
TweenMax.delayedCall(1, function() {
app.showPage(0, true);
});
},
setBackgrounds: function() {
// Loop through the page nodes
for (var i = 0; i < app.pages.length; i++) {
var $p = $(app.pages[i]), bgCollection;
// Look for background attribute
var backgroundAttribute = $p.attr('background');
if (backgroundAttribute.toUpperCase() !== 'SAME') {
var bg = $('<img class="bg" src="'+ app.root + backgroundAttribute +'">');
app.div.find('.backgrounds').append(bg);
bgCollection = { div: bg, options: $p.find('background') }
} else {
bgCollection = { div: null, options: $p.find('background') }
}
// Add collection to the global backgrounds container
app.bgs.push(bgCollection);
// Check page HTML
if ($p.attr('html') !== undefined) {
app.pageCache[$p.attr('html')] = new PagerExternalPage($p.attr('html'), app.root, app, i);
// console.log('PageCache...', app.pageCache);
}
}
},
delegateEvents: function() {
// Next button
app.div.find('.contentBlock .next').on('click', function(e) {
// Check if the buttons is disabled or not
if (!$(this).hasClass('disabled')) {
app.nextPage();
}
});
// Try Again button
app.div.delegate('.contentBlock .tryagain', 'click', function(e) {
app.dispatchEvent('TryAgain');
});
// TODO Hide TryAgain by default => this should probably be done in CSS
TweenMax.set('.contentBlock .btn.tryagain', { autoAlpha: 0 });
},
setButtonText: function(txt) {
// Not sure where this function is being called
$('.pagerWidget .contentBlack .next').html(txt);
},
/**
* Create the HTML for the page
*/
buildEmptyMarkup: function() {
var markup = [
'<div class="pagerWidget">',
' <div class="backgrounds"></div>',
' <div class="contentBlock">',
' <div class="text">',
' <div class="header"></div>',
' <div class="body"></div>',
' </div>',
' <div class="btn next" id="thenextbutton"></div>',
' </div>',
'</div>'
].join('');
return $(markup);
},
/**
* Create the page and check animate all the things
*/
showPage: function(n, snap) {
// Check for completion
if (n == app.pages.length) {
app.dispatchEvent('Complete');
return false;
}
// Get the current page and page elements
app.currentPage = n;
// Transition background
app.showBackground(n);
var pg = $(this.pages[n]),
contentBlock = {
inner: $('.contentBlock'),
header: $('.contentBlock .header'),
text: $('.contentBlock .text'),
body: $('.contentBlock .body'),
next: $('.contentBlock .next'),
contents: $('.contentBlock #contents')
};
contentBlock.body.attr('id', 'page-'+ n);
// console.log('ContentBlock', contentBlock);
// Check for snap, even though I can't remember what that means
if (snap) {
app.contentSnap(pg, contentBlock);
} else {
app.contentDefault(pg, contentBlock);
}
// Gate the page if there are accordions
app.pageGate();
},
showBackground: function(n) {
var bg = app.bgs[n];
if (bg.div != null) {
if (app.currentBackground != null) {
// Fade out initial
TweenMax.to(app.currentBackground, 0.5, { autoAlpha: 0 });
}
app.currentBackground = bg.div;
}
// If there are options like x and y, animate the image
if (bg.options.length > 0) {
app.animateBackground(bg.options);
}
// Fade new bg image in
TweenMax.to(app.currentBackground, 0.5, { overwrite: false, alpha: 1 });
},
animateBackground: function(options) {
var args = {};
args.x = options.attr('x');
args.y = options.attr('y');
args.scale = options.attr('scale');
if (options.attr('animate') == 'true') {
args.ease = 'Cubic.easeOut';
TweenMax.to(app.currentBackground, 13, args);
} else {
TweenMax.set(app.currentBackground, args);
TweenMax.to(app.currentBackground, 0.5, { autoAlpha: 1 });
}
},
contentSnap: function(pg, contentBlock) {
// console.log('ContentSNAP');
// Add CSS to contentBlock
contentBlock.inner.css({
top: pg.attr('y') +'px',
left: pg.attr('x') +'px',
width: pg.attr('width') - 144
});
contentBlock.text.css({ width: pg.attr('width') - 144});
contentBlock.header.html(pg.find('header').text());
contentBlock.next.html('Next');
// Check the page HTML and see if
// we are getting external HTML
if (pg.attr('html') === undefined) {
contentBlock.body.html(pg.find('body').text());
} else {
contentBlock.body.html(app.pageCache[pg.attr('html')].html);
}
// Change the contentBlocks height
app.setContentHeight(contentBlock);
// TODO Set CTA position, this should probably be done with CSS
app.setCTAPosition(contentBlock.contents.height() + 80);
if (pg.attr('nextX') === undefined) {
contentBlock.next.css('left', (contentBlock.inner.width() - contentBlock.next.width()) / 2 + 42);
} else {
contentBlock.next.css('left', pg.attr('nextX') +'px');
}
},
contentDefault: function(pg, contentBlock) {
// console.log('COntentDEFAULT');
// I don't know why we are changing the width defined in the XML
var newWidth = pg.attr('width') - 144;
// Disable the next button
contentBlock.next.addClass('disabled');
// Animate text off and update content before animating back in
TweenMax.to(contentBlock.text, 0.3, {
autoAlpha: 0,
onComplete: function() {
getContents();
}
});
var getContents = function() {
// console.log('Get CONTENTS ------');
contentBlock.text.css('width', newWidth +'px');
contentBlock.header.html(pg.find('header').text());
if (pg.attr('html') === undefined) {
contentBlock.body.html(pg.find('body').text());
} else {
contentBlock.body.html(app.pageCache[pg.attr('html')].html);
}
var h = app.setContentHeight(contentBlock);
// console.log('WHAT THE EVER LOVING HECKFIRE?', h);
// Animate some more
TweenMax.to(contentBlock.inner, 0.5, {
left: pg.attr('x'),
top: pg.attr('y'),
width: newWidth,
height: h,
onComplete: function() {
showContents();
}
});
// Set next position
var leftPos = (pg.attr('nextX') === undefined)
? (newWidth - contentBlock.next.width()) / 2 + 42
: pg.attr('nextX') +'px';
TweenMax.to(contentBlock.next, 0.5, { left: leftPos });
};
var showContents = function() {
TweenMax.to(contentBlock.text, 0.5, { autoAlpha: 1 });
if (!app.disabled) contentBlock.next.removeClass('disabled');
app.setCTAPosition(contentBlock.contents.height() + 80);
}
},
setContentHeight: function(contentBlock) {
if (!contentBlock.contents.is('div')) {
contentBlock.inner.css('height', contentBlock.text.height());
} else {
contentBlock.inner.css('height', contentBlock.contents.height());
}
return contentBlock.inner.outerHeight();
},
setCTAPosition: function(pos) {
$('.green').attr('style', 'top:'+ pos +'px');
},
pageGate: function() {
// console.log('Gated progress based on accordions.');
// console.log(' Captured Accordions: ', app.accordions);
var count = app.accordions['page'+ app.currentPage];
// console.log(' Count: ', count);
// Check if count is defined
if (count !== undefined && count > 0) {
app.disable();
// Delegate accordion click events
$('.contentBlock').delegate('.accordion-head', 'click', function(e) {
var target = $(e.currentTarget);
// console.log(' Current Accordion Target: ', target);
target.addClass('clicked');
var clickedCount = $('.contentBlock .accordion-head.clicked').length;
if (Number(count) === Number(clickedCount)) {
app.enable();
}
});
}
},
disable: function() {
$('.contentBlock .next').addClass('disabled');
app.disabled = true;
},
enable: function() {
$('.contentBlock .next').removeClass('disabled');
app.disabled = false;
},
nextPage: function() {
app.showPage(app.currentPage+1);
},
prevPage: function() { return false },
updateCounter: function() { return false },
noBack: function() { return false },
noNext: function() { return false },
updateJira: function() {
try {
_shell.jiraLocation('Page '+ (Number(app.currentPage)+1));
} catch(e) {
// throw error
}
},
attach: function(div) {
div.append(app.div);
app.dispatchEvent('Init');
},
addEventListener: function(evt, fn) {
app.events[evt] = fn;
},
dispatchEvent: function(evt) {
if (app.events[evt] !== undefined) {
app.events[evt]();
}
},
setAccordionCount: function(n, idx) {
app.accordions['page'+ idx] = n;
}
};
var PagerExternalPage = function(url, root, _pager, idx) {
this.loaded = false;
this.callback = null;
this.html = null;
var _pagerExternalPage = this;
$.get(root + url, function(html) {
_pagerExternalPage.html = html;
_pagerExternalPage.loaded = true;
if (_pagerExternalPage.callback != null) {
_pagerExternalPage.callback();
}
_pager.setAccordionCount($(html).find('.accordion:visible').length, idx);
});
}
return Mod;
})()
|
let width = document.querySelector(".width input");
let height = document.querySelector(".height input");
let axeX = document.querySelector(".axeX input");
let axeY = document.querySelector(".axeY input");
let color = document.querySelector("[type=color]");
let porportion = document.querySelector("[type=checkbox]");
let image = document.querySelector("img");
const modify = () => {
if (porportion.checked == true) {
image.style.width = width.value + "px"
image.style.height = width.value + "px"
image.style.backgroundColor = color.value;
image.style.bottom = axeY.value + "px"
image.style.left = axeX.value + "px"
} else {
image.style.bottom = axeY.value + "px"
image.style.left = axeX.value + "px"
image.style.height = height.value + "px"
image.style.width = width.value + "px"
image.style.backgroundColor = color.value;
}
}
document.addEventListener('input', modify)
|
var express = require('express');
var router = express.Router();
var logsFunc = require('../../controllers/logs');
router
.get('/', logsFunc.getAllLogs)
.delete('/:id', logsFunc.deleteLogById);
module.exports = router;
|
import Vue from 'vue'
import Router from 'vue-router'
import Home from './components/home'
import Form from './components/formulario'
import Usuario from './components/usuario'
import Listagem from './components/orgao/listagem'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/cadastro/usuario',
name: 'usuario',
component: Usuario,
},
{
path: '/cadastro/orgao',
name: 'orgao',
component: Listagem,
},
{
path: '/formulario',
name: 'formulario',
component: Form,
}
]
})
|
module.exports = {
rules: {
'non-offensive-terms': require('./non-offensive-terms'),
},
configs: {
js: {
plugins: ['prettier'],
extends: ['prettier'],
rules: {
'non-offensive-terms': 'error',
},
},
react: {
extends: [
'airbnb',
'plugin:fs-react-sample/js',
'plugin:react-hooks/recommended',
],
plugins: ['fs-react-sample', 'react-hooks'],
overrides: {
'import/prefer-default-export': 0,
}
}
}
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsAspectRatio = {
name: 'aspect_ratio',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 12h-2v3h-3v2h5v-5zM7 9h3V7H5v5h2V9zm14-6H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02z"/></svg>`
};
|
let userScore = 0;
let computerScore = 0;
const userScore_span = document.getElementById("user-score");
const computerScore_span = document.getElementById("computer-score");
const result_p = document.querySelector(".result p");
const rock_section = document.getElementById("rock");
const paper_section = document.getElementById("paper");
const scissors_section = document.getElementById("scissors");
function getComputerChoice() {
const choices = ['rock','paper','scissors'];
const randomNumber = Math.floor(Math.random() * 3);
return choices[randomNumber];
}
function win(userChoice,computerChoice) {
const smallUserWord = "user".fontsize(3).sub();
const smallComputerWord = "comp".fontsize(3).sub();
const userChoice_div = document.getElementById(userChoice);
userScore++;
userScore_span.innerHTML = userScore;
computerScore_span.innerHTML = computerScore;
result_p.innerHTML = userChoice+smallUserWord+" beats "+computerChoice+smallComputerWord+". You win!!!";
userChoice_div.classList.add('green-shine');
setTimeout(() => userChoice_div.classList.remove('green-shine'), 500);
document.getElementById('user-label').classList.add('green-shine');
setTimeout(() => document.getElementById('user-label').classList.remove('green-shine'), 500);
document.getElementById('computer-label').classList.add('red-shine');
setTimeout(() => document.getElementById('computer-label').classList.remove('red-shine'), 500);
}
function lose(userChoice,computerChoice) {
const smallUserWord = "user".fontsize(3).sub();
const smallComputerWord = "comp".fontsize(3).sub();
const userChoice_div = document.getElementById(userChoice);
computerScore++;
userScore_span.innerHTML = userScore;
computerScore_span.innerHTML = computerScore;
result_p.innerHTML = userChoice+smallUserWord+" loses to "+computerChoice+smallComputerWord+". You lost!!!";
userChoice_div.classList.add('red-shine');
setTimeout(() => userChoice_div.classList.remove('red-shine'), 500);
document.getElementById('computer-label').classList.add('green-shine');
setTimeout(() => document.getElementById('computer-label').classList.remove('green-shine'), 500);
document.getElementById('user-label').classList.add('red-shine');
setTimeout(() => document.getElementById('user-label').classList.remove('red-shine'), 500);
}
function draw(userChoice,computerChoice) {
const smallUserWord = "user".fontsize(3).sub();
const smallComputerWord = "comp".fontsize(3).sub();
const userChoice_div = document.getElementById(userChoice);
result_p.innerHTML = userChoice+smallUserWord+" equals "+computerChoice+smallComputerWord+". It's a draw!!!";
userChoice_div.classList.add('gray-shine');
setTimeout(() => userChoice_div.classList.remove('gray-shine'), 500);
document.getElementById('user-label').classList.add('gray-shine');
setTimeout(() => document.getElementById('user-label').classList.remove('gray-shine'), 500);
document.getElementById('computer-label').classList.add('gray-shine');
setTimeout(() => document.getElementById('computer-label').classList.remove('gray-shine'), 500);
}
function game(userChoice) {
const computerChoice = getComputerChoice();
switch (userChoice + computerChoice) {
case "rockscissors":
case "paperrock":
case "scissorspaper":
win(userChoice,computerChoice);
break;
case "rockpaper":
case "paperscissors":
case "scissorsrock":
lose(userChoice,computerChoice);
break;
case "rockrock":
case "paperpaper":
case "scissorsscissors":
draw(userChoice,computerChoice);
break;
}
}
function main() {
rock_section.addEventListener("click", () => game("rock"));
paper_section.addEventListener("click", () => game("paper"));
scissors_section.addEventListener("click", () => game("scissors"));
}
main();
|
app.directive('map', function(){
return {
scope: {},
templateUrl: "templates/map.html",
controller: "MapCtrl",
}
})
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
require("./testData.css");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TestData = [{
data: _react.default.createElement("div", {
className: "test_data",
key: "1"
}, "Test 1"),
DragNotAllowed: false
}, {
data: _react.default.createElement("div", {
className: "test_data",
key: "1"
}, "Test 2"),
DragNotAllowed: false
}, {
data: _react.default.createElement("div", {
className: "test_data",
key: "1"
}, "Test 3")
}, {
data: _react.default.createElement("div", {
className: "test_data",
key: "1"
}, "Test 4"),
DragNotAllowed: true
}, {
data: _react.default.createElement("div", {
className: "test_data",
key: "1"
}, "Test 5"),
DragNotAllowed: true
}, {
data: _react.default.createElement("div", {
className: "test_data",
key: "1"
}, "Test 6"),
DragNotAllowed: false
}];
var _default = TestData;
exports.default = _default;
|
import React from "react";
const Doctor = ({ doctor, users, doctor_name }) => {
const { id } = doctor;
return (
<>
<h1>{doctor_name}</h1>
<hr />
<h6>Users</h6>
<ul>
{ users.map((user) => (
<li>
<a href={`/users/${user.id}`}>{user.first_name}{user.last_name}</a>
</li>
))}
</ul>
<a href={`/doctors/${id}/appointments`}>
Doctor Appointments
</a>
<br />
<a href={`/doctors/${id}/edit`}>
Doctor update
</a>
<br />
<a href={`/doctors/${id}`} data-method="delete">
Doctor delete
</a>
</>
);
}
export default Doctor;
|
if (Drupal.jsEnabled) {
$(document).ready(function() {
$('#node-form').attr('action', location.href);
$('.drupal-tabs').find('ul.anchors').find('a').click( function() {
var hrefExt = $(this).attr('href');
var form = $('#node-form');
var formAction = form.attr('action');
var index = formAction.indexOf('#');
if (index > 0) {
formAction = formAction.substr(0,index) + hrefExt;
} else {
formAction = formAction + hrefExt;
}
form.attr('action', formAction);
});
$('#edit-save, #edit-delete, #edit-cancel').click( function() {
cleanFormAction();
});
$('#edit-save-top, #edit-delete-top, #edit-cancel-top').click( function() {
cleanFormAction();
});
$('#edit-partial-save-template, #edit-partial-save-css, #edit-partial-save-php, #edit-partial-save-js').click( function() {
return confirm('Are you sure you want to save this to a file? If file exists it will be overwritten.');
});
$('#edit-partial-load-template, #edit-partial-load-css, #edit-partial-load-php, #edit-partial-load-js').click( function() {
return confirm('Are you sure you want to load from a file?');
});
});
}
function cleanFormAction() {
var form = $('#node-form');
var formAction = form.attr('action');
var index = formAction.indexOf('#');
if (index > 0) {
formAction = formAction.substr(0,index);
} else {
formAction = formAction;
}
form.attr('action', formAction);
}
|
/**
* Copyright (c) 2013 Oculus Info Inc.
* http://www.oculusinfo.com/
*
* Released under the MIT License.
*
* 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.
*/
/*
* Aperture
*/
aperture = (function(aperture){
/**
* Source: AjaxAppender.js
* Copyright (c) 2013 Oculus Info Inc.
* @fileOverview Aperture Logging AJAX Appender Implementation
*/
/**
* @namespace
* @ignore
* Ensure namespace exists
*/
aperture.log = (function(ns) {
var AjaxAppender = aperture.log.Appender.extend(
{
init : function( spec ) {
spec = spec || {};
aperture.log.Appender.prototype.init.call(this, spec.level || aperture.log.LEVEL.WARN);
this.url = spec.url;
this.buffer = [];
// Force the scope of postData to this, no matter
// how it's usually called.
this.postData = aperture.util.bind(this.postData, this);
// Post data at requested interval
setInterval(this.postData, spec.timeout || 3000 );
// Also post if navigating away from the page
$(window).unload( this.postData );
},
/** @private */
logString : function( level, message ) {
// Push a log record onto the stack
this.buffer.push( {
level: level,
message: message,
when: new Date()
} );
},
/** @private */
logObjects : function( level, objs ) {
// Push a log record onto the stack
this.buffer.push( {
level: level,
data: objs,
when: new Date()
} );
},
/**
* @private
* Causes the appender to post any queued log messages to the server
*/
postData : function() {
if( buffer.length ) {
// Simple fire and forget POST of the data
$.ajax( {
url: this.url,
type: 'POST',
data: this.buffer
});
// Clear buffer
this.buffer = [];
}
}
});
/**
* @name aperture.log.addAjaxAppender
* @function
* @description
* <p>Creates and adds an AJAX appender object.
* The AJAX Appender POSTs log messages to a provided end-point URI
* using a JSON format. Log messages are buffered on the client side
* and only sent to the server once every N seconds where N is settable
* upon construction.</p>
* <p>The data will be posted with the following format:</p>
* <pre>
* [
* { level:"warn", message:"A log message", when:"2011-09-02T17:57:33.692Z" },
* { level:"error", data:{some:"data"}, when:"2011-09-02T17:57:34.120Z" }
* ]
* </pre>
*
* @param {Object} spec specification object describing the properties of
* the ajax appender to build
* @param {String} spec.url the server endpoint to which log messages will be
* POSTed.
* @param {Number} [spec.timeout] period in milliseconds between when collected
* log messages are sent to the server. Defaults to 3000
* @param {aperture.log.LEVEL} [spec.level] initial appender logging threshold level, defaults to WARN
*
* @returns {aperture.log.Appender} a new AJAX appender object that has been added
* to the logging system
*/
ns.addAjaxAppender = function(spec) {
return ns.addAppender( new AjaxAppender(spec) );
};
return ns;
}(aperture.log || {}));
/**
* Source: AlertBoxAppender.js
* Copyright (c) 2013 Oculus Info Inc.
* @fileOverview Aperture Logging Alert Box Appender Implementation
*/
/**
* @namespace
* @ignore
* Ensure namespace exists
*/
aperture.log = (function(ns) {
var AlertBoxAppender = aperture.log.Appender.extend(
{
init : function(spec) {
spec = spec || {};
// Default to only popping up an alertbox for errors
aperture.log.Appender.prototype.init.call(this, spec.level || aperture.log.LEVEL.ERROR);
},
logString : function( level, message ) {
// Simply
alert( level.toUpperCase() + ':\n' + message );
}
});
/**
* @name aperture.log.addAlertBoxAppender
* @function
* @description Creates and adds an alert box implementation of a logging Appender to
* the logging system. Pops up an alert box for every log message that passes the
* appender's threshold. By default the threshold is set to ERROR to ensure alert boxes
* rarely appear.
*
* @param {Object} [spec] specification object describing the properties of the appender
* @param {aperture.log.LEVEL} [spec.level] initial appender logging threshold level, defaults to ERROR
*
* @return {aperture.log.Appender} a new alert box appender instance
*/
ns.addAlertBoxAppender = function(spec) {
return ns.addAppender( new AlertBoxAppender(spec) );
};
return ns;
}(aperture.log || {}));
/**
* Source: BufferingAppender.js
* Copyright (c) 2013 Oculus Info Inc.
* @fileOverview Aperture Logging Buffering Appender Implementation
*/
/**
* @namespace
* @ignore
* Ensure namespace exists
*/
aperture.log = (function(ns) {
/*
* TODO A buffering appender may be much more useful if it decorates another
* appender. A call to flush the buffer will log all buffered messages to
* the decorated appender.
*/
var BufferingAppender = aperture.log.Appender.extend(
{
init : function(spec) {
spec = spec || {};
aperture.log.Appender.prototype.init.call(this, spec.level || aperture.log.LEVEL.INFO);
this.depth = spec.bufferDepth || 100;
this.buffer = [];
},
logString : function( level, message ) {
this.buffer.push( {level:level, message:message, when:new Date()} );
if( this.buffer.length > this.depth ) {
this.buffer.shift();
}
},
logObjects : function( level, objs ) {
this.buffer.push( {level:level, objects:objs, when:new Date()} );
if( this.buffer.length > this.depth ) {
this.buffer.shift();
}
},
getBuffer : function( keepBuffer ) {
var returnValue = this.buffer;
if( !keepBuffer ) {
this.buffer = [];
}
return returnValue;
}
});
/**
* @name aperture.log.addBufferingAppender
* @function
*
* @description Creates and adds a buffering appender to the logging system.
* This appender stores most recent N log messages internally
* and provides a list of them on demand via a 'getBuffer' function.
*
* @param {Object} [spec] specification object describing how this appender
* should be constructed.
* @param {Number} [spec.bufferDepth] maximum number of log records to keep in
* the buffer, defaults to 100
* @param {aperture.log.LEVEL} [spec.level] initial appender logging threshold level, defaults to INFO
*
* @returns {aperture.log.Appender} a new buffering appender instance
*/
ns.addBufferingAppender = function(spec) {
return ns.addAppender( new BufferingAppender(spec) );
};
return ns;
}(aperture.log || {}));
/**
* Source: ConsoleAppender.js
* Copyright (c) 2013 Oculus Info Inc.
* @fileOverview Aperture Logging Console Appender Implementation
*/
/*
* console is a tricky thing to get working cross browser. Potential
* problems:
* <ul>
* <li>IE 7: No console object</li>
* <li>IE 8: 'console' only exists after dev tools are open. console.log functions
* are not true JS Function functions and do not support 'call' or 'apply'. A work
* around using Function.prototype.bind to make an applyable version of the functions
* (http://whattheheadsaid.com/2011/04/internet-explorer-9s-problematic-console-object)
* is not possible due to missing Function.prototype.bind.</li>
* <li>IE 9: 'console' only exists after dev tools are open. console.log functions
* are not true JS Function functions and do not support 'call' or 'apply'.
* Function.prototype.bind does exist.</li>
* </ul>
*
* Ben Alman / Paul Irish (see attribution below) wrote a nice bit of code that will
* gracefully fallback if console.error, etc are not found. Craig Patik addressed issues
* in IE where the console is not available until the dev tools are opened as well as
* calling the native console functions using .apply. .apply calls are more desirable than
* Alman/Irish solution since the browser may nicely format the passed in data instead of
* logging everything as an array (like Alman/Irish do).
*
* @see Bits and pieces of Paul Irish and Ben Alman's
* <a href="http://benalman.com/projects/javascript-debug-console-log/">console wrapper</a>
* code was copied and modified below.
* Original copyright message:
* JavaScript Debug - v0.4 - 6/22/2010
* http://benalman.com/projects/javascript-debug-console-log/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*
* With lots of help from Paul Irish!
* http://paulirish.com/
*
* @see Craig Patik's <a href="http://patik.com/blog/complete-cross-browser-console-log/">original post</a>
* inspired a number of the tweaks included below.
*/
/**
* @namespace
* @ignore
* Ensure namespace exists
*/
aperture.log = (function(ns) {
var ConsoleAppender = aperture.log.Appender.extend(
{
init : function(spec) {
spec = spec || {};
aperture.log.Appender.prototype.init.call(this, spec.level || aperture.log.LEVEL.INFO);
this.map = [];
// create a map of log level to console function to invoke
// if console doesn't have the function, use log
// level values actually map to console methods (conveniently enough)
aperture.util.forEach(aperture.log.LEVEL, function(level, key) {
this.map[level] = function() {
var con = window.console;
if ( typeof con == 'undefined' ) {
return;
}
if (typeof con.log == 'object') {
// IE 8/9, use Andy E/Craig Patik/@kangax call.call workaround
// since the console.x functions will not support .apply directly
// Note: Could call F.p.apply.call to truly emulate calling console.log(a,b,c,...)
// but IE concatenates the params with no space, no ',' so kind of ugly
if (con[ level ]) {
Function.prototype.apply.call(con[level], con, arguments);
} else {
Function.prototype.apply.call(con.log, con, arguments);
}
} else {
// Modern browser
if (con.firebug) {
con[ level ].apply( window, arguments );
} else if (con[ level ]) {
con[ level ].apply( con, arguments );
} else {
con.log.apply( con, arguments );
}
}
};
},
this );
},
logString : function( level, message ) {
// Simply log the string to the appropriate logger
this.map[level]( message );
},
logObjects : function( level, objArray ) {
// Call the appropriate logger function with all the arguments
this.map[level].apply( null, objArray );
}
});
/**
* @name aperture.log.addConsoleAppender
* @function
* @description Creates and adds a console implementation of a logging Appender to
* the logging system. This appender works as follows:
* <ol>
* <li>If firebug exists, it will be used</li>
* <li>If console.error, console.warn, console.info and console.debug exist, they will
* be called as appropriate</li>
* <li>If they do not exist console.log will be called</li>
* <li>If console.log or console do not exist, this appender does nothing</li>
* </ol>
*
* @param {Object} [spec] specification object describing the properties of the appender
* @param {aperture.log.LEVEL} [spec.level] initial appender logging threshold level, defaults to INFO
*
* @returns {aperture.log.Appender} a new console appender instance
*/
ns.addConsoleAppender = function(spec) {
return ns.addAppender( new ConsoleAppender(spec) );
};
return ns;
}(aperture.log || {}));
/**
* Source: DOMAppender.js
* Copyright (c) 2013 Oculus Info Inc.
* @fileOverview Aperture Logging DOM Appender Implementation
*/
/**
* @namespace
* @ignore
* Ensure namespace exists
*/
aperture.log = (function(ns) {
var DOMAppender = aperture.log.Appender.extend(
{
init : function(spec) {
spec = spec || {};
aperture.log.Appender.prototype.init.call(this, spec.level || aperture.log.LEVEL.INFO);
// Add the list
var list = this.list = $('<ol class="aperture-log-display"></ol>')
.appendTo( spec.container );
// Add a clear button
$('<button class="aperture-log-clear" type="button">Clear</button>')
.click( function() { list.empty(); } )
.appendTo( spec.container );
},
logString : function( level, message ) {
// Append a list item styled by the log level to the list
$('<li></li>')
.text('[' + level + '] ' + message)
.addClass('aperture-log-'+level)
.appendTo(this.list);
}
});
/**
* @name aperture.log.addDomAppender
* @function
*
* @description Creates and adds a DOM appender to the logging system. The DOM Appender
* logs all messages to a given dom element. The given DOM
* element will have an ordered list of log messages and a "Clear" button added to it.
* Log messages will be styled 'li' tags with the class 'aperture-log-#' where # is the
* log level, one of 'error', 'warn', 'info', 'debug', or 'log'. The list itself
* will have the class 'aperture-log-display' and the button will have the class
* 'aperture-log-clear'.
*
* @param {Object} spec specification object describing the properties of the appender
* @param {Element} spec.container the DOM element or selector string to the DOM element
* that should be used to log all messages.
* @param {aperture.log.LEVEL} [spec.level] initial appender logging threshold level, defaults to INFO
*
* @returns {aperture.log.Appender} a new DOM appender instance
*/
ns.addDomAppender = function(spec) {
return ns.addAppender( new DOMAppender(spec) );
};
return ns;
}(aperture.log || {}));
return aperture;
}(aperture || {}));
|
// ** React Imports
import { useEffect, useRef } from 'react'
import { useParams, Link } from 'react-router-dom'
import {getSSmallImageUser } from '@utils'
import Avatar from '@components/avatar'
import Moment from 'react-moment'
import 'moment-timezone'
import 'moment/locale/es'
import { store } from '@store/storeConfig/store'
// ** stores & Actions
import { getItem, setEditOn } from '../store/action'
import { useSelector, useDispatch } from 'react-redux'
import ReactToPrint from 'react-to-print'
// ** Reactstrap
import { Row, Col, Alert, Card, FormGroup, CardBody, CardTitle, Button, CardSubtitle, CardText } from 'reactstrap'
// ** Styles
import '@styles/react/apps/app-users.scss'
const ItemView = props => {
// ** Vars
const stores = useSelector(state => state.users),
dispatch = useDispatch(),
{ id } = useParams()
const componentRef = useRef()
// ** Get suer on mount
useEffect(() => {
dispatch(getItem(id))
}, [dispatch])
return stores.selectedItem !== null && stores.selectedItem !== undefined ? (
<div className='app-user-view'>
<div ref={componentRef} >
<Row>
<Col xl='12' lg='12' md='12'>
<Card>
<CardBody>
<CardTitle tag="h5" className="mb-2">
<Row>
<Col xl='1' lg='1' md='1' className="text-center">
{!!stores.selectedItem.image && <Avatar img={getSSmallImageUser(stores.selectedItem.image)} width='32' height='32' />}
</Col>
<Col xl='6' lg='6' md='6'>
<br className=" print-only"/>
{!!stores.selectedItem.name && <span>{stores.selectedItem.name}</span>} {!!stores.selectedItem.lastName && <span >{stores.selectedItem.lastName}</span>}
</Col>
</Row>
</CardTitle>
<CardSubtitle tag="h6" className="mb-2 text-muted">
<Row>
<Col className="mb-1" xs='12' lg='4' md='4'>{!!stores.selectedItem.dni && <span ><strong>Dni:</strong> {stores.selectedItem.dni}</span>}</Col>
<Col className="mb-1" xs='12' lg='4' md='4'>{!!stores.selectedItem.title && <span><strong>Título Universitario:</strong> {stores.selectedItem.title}</span>}</Col>
<Col xs='12' lg='4' md='4'> {!!stores.selectedItem.university && <span ><strong>Universidad:</strong> {stores.selectedItem.university}</span>}</Col>
</Row>
</CardSubtitle>
{!!stores.selectedItem.birthday &&
<Row className="mb-1">
<Col>
<span> <strong>Fecha de nacimiento: </strong> <Moment locale="es">{stores.selectedItem.birthday}</Moment> </span>
</Col>
<Col>
<strong>Ubicación: </strong> {!!stores.selectedItem.city}<span> {stores.selectedItem.city} - </span> {!!stores.selectedItem.state}<span> {stores.selectedItem.state} - </span> {!!stores.selectedItem.country}<span> {stores.selectedItem.country.name} </span> {!!stores.selectedItem.zipCode}<span> {stores.selectedItem.zipCode} </span>
</Col>
</Row>
}
{!!stores.selectedItem.gender &&
<CardText>
<strong>Género: </strong> {stores.selectedItem.gender === 'femenine' && <span>Femenino</span>} {stores.selectedItem.gender === 'masculine' && <span>Masculino</span>}
</CardText>
}
<Row>
<Col>{!!stores.selectedItem.addressHome && <span className="mr-2"><strong>Dirección de domicilio: </strong> {stores.selectedItem.addressHome} </span>}</Col>
<Col>{!!stores.selectedItem.addressOffice && <span><strong>Dirección de Oficina: </strong> {stores.selectedItem.addressOffice} </span>}</Col>
</Row>
</CardBody>
</Card>
<Card>
<CardBody>
<CardTitle tag="h5">
Información complementaria y contacto
</CardTitle>
<CardSubtitle tag="h6" className="mb-2 text-muted">
<Row>
<Col className="mb-1" xs='12' lg='4' md='4'>{!!stores.selectedItem.principalEmail && <span ><strong>Email principal:</strong> {stores.selectedItem.principalEmail}</span>}</Col>
{!!stores.selectedItem.secundaryEmail && <Col className="mb-1" xs='12' lg='4' md='4'> <span ><strong>Email Segundario:</strong> {stores.selectedItem.secundaryEmail}</span></Col>}
{!!stores.selectedItem.phone && <Col className="mb-1" xs='12' lg='4' md='4'> <span ><strong>Teléfono:</strong> {stores.selectedItem.phone}</span></Col>}
{!!stores.selectedItem.mobile && <Col className="mb-1" xs='12' lg='4' md='4'> <span ><strong>Móvil:</strong> {stores.selectedItem.mobile}</span></Col>}
</Row>
</CardSubtitle>
<Row>
<Col className="mb-2" xs='12' lg='12' md='12'>{!!stores.selectedItem.curriculum && <span className="mr-2"><h3>Curriculum: </h3> {stores.selectedItem.commentary} </span>}</Col>
<Col xs='12' lg='12' md='12'>{!!stores.selectedItem.commentary && <span className="mr-2"><h3>Comentarios: </h3> {stores.selectedItem.curriculum} </span>}</Col>
</Row>
</CardBody>
</Card>
</Col>
</Row>
</div>
<Row>
<Col>
<Link
to='/apps/user/list'
className='user-name text-truncate mb-0'
onClick={() => store.dispatch(setEditOn(0, {}))}
>
Volver
</Link>
</Col>
<Col className="text-right">
<ReactToPrint
trigger={() => <Button >Imprimir</Button>}
content={() => componentRef.current}
/>
</Col>
</Row>
</div>
) : (
<Alert color='danger'>
<h4 className='alert-heading'>Item not found</h4>
<div className='alert-body'>
El item con el id : {id} no existe, por favor buscalo en : <Link to='/apps/user/list'>la lista de items</Link>
</div>
</Alert>
)
}
export default ItemView
|
// Define Device
Framer.Device = new Framer.DeviceComponent();
Framer.Device.setupContext();
var allCards, card, eachCard, i, j, k, label, len, main;
// Define animation Defaults
Framer.Defaults.Animation = {
curve: "spring",
time: ".2"
};
// Define container
main = new Layer({
height: Screen.height,
width: Screen.width
});
// Array for cards
allCards = [];
for (i = j = 0; j < 8; i = ++j) {
card = new Layer({
parent: main,
name: "card" + i,
height: Screen.height - (Screen.height * (i / 8)),
width: Screen.width,
backgroundColor: "white",
shadowY: 3,
shadowBlur: 40
});
label = new Layer({
name: "label",
height: 30,
width: 300,
y: Align.bottom(-30),
x: Align.center,
superLayer: card,
backgroundColor: 'transparent',
html: "<p style='font-size:30px; color: #333; text-align: center;''>MENU ITEM #" + (i + 1) + "</p>"
});
allCards.push(card);
card.states.add({
"default": {
height: Screen.height - (Screen.height * (i / 8)),
opacity: 1
},
open: {
height: Screen.height,
opacity: 1
},
closed: {
height: 0,
opacity: 0
}
});
card.onTapEnd(function() {
var k, len, ref, results, sib;
this.states.next("open", "default");
ref = this.siblings;
results = [];
for (k = 0, len = ref.length; k < len; k++) {
sib = ref[k];
if (sib.index > this.index) {
results.push(sib.states.next("closed", "default"));
} else {
results.push(void 0);
}
}
return results;
});
}
for (k = 0, len = allCards.length; k < len; k++) {
eachCard = allCards[k];
eachCard.on("change:frame", function(event, layer) {
return layer.childrenWithName("label")[0].y = Align.bottom(-30);
});
}
|
import React from 'react';
import { StyleSheet, Text, View, TextInput, FlatList, Button } from 'react-native';
import Modal from 'react-native-modal';
import Card from './Card';
import Crowdsource from './Crowdsource';
import Authorization from './Authorization';
import * as APIs from '../APIkeys'
export default function Main(props) {
//this also contains information for crowdsource fields
const [companies, setCompanies] = React.useState({});
//this is a common state for all cards that resiricts only one company to be queued at a given time
//NA means no one
//queued will be set to the specific company name when that company is queued, back to NA when dequeued
const [queued, setQueued] = React.useState("NA");
const [popup, setPopup] = React.useState(false);
const [company, setCompany] = React.useState("");
const [notAuthorized, setAuthorize] = React.useState(true);
const [search, setSearch] = React.useState("");
const [keys, setKeys] = React.useState([]);
const [incorrect, setIncorrect] = React.useState(false);
//only updates a single card that was given from the server
let receiveMessage = () => {
props.socket.onmessage = (event) => {
let data = JSON.parse(event.data);
let companyName = data.company_name.S;
let line_size = parseInt(data.line_size.N);
let totalDifference = data.totalDifference === undefined ? 0 : parseInt(data.totalDifference.N);
let count_dequeued = data.countDequeued === undefined ? 1 : parseInt(data.countDequeued.N);
let newCompanies = {...companies};
newCompanies[companyName].line_size = line_size;
newCompanies[companyName].totalDifference = totalDifference;
newCompanies[companyName].countDequeued = count_dequeued;
let notInclude = ["countDequeued", "description", "line_size", "positions", "totalDifference"];
Object.keys(data).forEach((key) => {
if(key !== "company_name"){
if(!notInclude.includes(key)){
newCompanies[companyName][key] = data[key].S;
}
}
});
setCompanies(newCompanies);
setKeys(Object.keys(newCompanies).sort());
}
}
let getCompanies = async () => {
try {
let response = await fetch(APIs.GET_ALL_DATA);
if(!response.ok) {
}
let data = await response.json();
setCompanies(data);
setKeys(Object.keys(data).sort());
} catch(e) {
console.log(e);
}
}
React.useEffect(() => {
getCompanies();
}, [receiveMessage()]);
let authenticateData = async (password) => {
try {
let url = APIs.AUTH;
url += password;
console.log(url);
let response = await fetch(url);
if(!response.ok) {
}
let data = await response.json();
console.log(data);
if(data === "passed"){
setIncorrect(false);
setAuthorize(false);
}else{
setIncorrect(true);
}
} catch(e) {
console.log(e);
}
}
let changeSearch = (text) => {
setSearch(text);
let tempKeys = [];
Object.keys(companies).map((val) => {
if (val.toLowerCase().includes(text.toLowerCase())) {
tempKeys.push(val);
}
})
setKeys(tempKeys.sort());
}
return (
<View style={styles.container}>
<Modal
isVisible={notAuthorized}
backdropOpacity={0.9}
>
<Authorization incorrect={incorrect} authenticateData={authenticateData}/>
</Modal>
<TextInput
style={styles.search}
placeholder="search"
placeholderTextColor="white"
value={search}
onChangeText={changeSearch}
>
</TextInput>
<Modal
style={styles.modal}
isVisible={popup}
backdropOpacity={0.9}
>
<Crowdsource
setPopup={setPopup}
company={company}
allData={companies}
/>
</Modal>
<FlatList
data={keys}
renderItem={( key ) => (
<Card
setPopup={setPopup}
setCompany={setCompany}
queued={queued}
setQueued={setQueued}
socket={props.socket}
key={key.item}
name={key.item}
positions={companies[key.item].positions}
description={companies[key.item].description}
people={companies[key.item].line_size}
totalDifference={companies[key.item].totalDifference}
countDequeued={companies[key.item].countDequeued}
allData={companies}
/>
)}
keyExtractor={key => key}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
height: "90%",
width: "100%",
},
search: {
color: 'white',
fontSize: 36,
margin: 5,
marginLeft: 20,
fontWeight: "bold"
}
});
|
// DO NOT MODIFY. Generated by build task.
// Contribute here: https://www.transifex.com/projects/p/gridfieldbulkeditingtools/
if(typeof(ss) == 'undefined' || typeof(ss.i18n) == 'undefined') {
if(typeof(console) != 'undefined') console.error('Class ss.i18n not defined');
} else {
ss.i18n.addDictionary('fr', {
"GridFieldBulkTools.FINISH_CONFIRM": "Vous avez des changements non enregistrés. En continuant vous allez perdre toutes vos données non enregistrées.\n\nVoulez-vous vraiment continuer?",
"GridFieldBulkTools.EDIT_CHANGED": "Changé",
"GridFieldBulkTools.EDIT_UPDATED": "Enregisté",
"GridFieldBulkManager.BULKACTION_EMPTY_SELECT": "Vous devez séléctionner au moins un élément.",
"GridFieldBulkManager.CONFIRM_DESTRUCTIVE_ACTION": "Vos données seront perdues définitivement. Voulez-vous continuer?"
});
}
|
import Login from 'pages/login';
import Dashboard from 'pages/dashboard';
import BoardShow from 'pages/boards/show';
export const privateRoutes = [
{ path: '/', page: Dashboard },
{ path: '/b/:boardID', page: BoardShow }
];
export const publicRoutes = [
{ path: '/login', page: Login }
];
export const loginPath = () => '/login';
export const dashboardPath = () => '/';
export const boardPath = (id) => `/b/${id}`;
|
const ALPHABET= "AG8FOLE2WVTCPY5ZH3NIUDBXSMQK7946";
module.exports = {
couponCode: (number) => {
let ret = '';
for (var i=0; i<6; ++i) {
ret += ALPHABET[number&((1 << 5)-1)];
number = number >> 5;
}
return ret;
},
codeFromCoupon: (coupon) => {
let n = 0;
for (var i = 0; i < 6; ++i)
n = n | ((ALPHABET.indexOf(coupon[i])) << (5 * i));
return n;
},
decimal_expand: 1000000000000000000,
web3_provider: 'https://mainnet.infura.io/aaaaaaaaaaaaaaaaa'
}
|
(function (angular) {
"use strict";
angular.module("bookVenueControllers", [,'venueService','courtPicker'])
.controller('searchController', function ($scope, $state, $stateParams, venueService, venueObj) {
$scope.cityId = $stateParams.cityid;
$scope.courtTypeId = $stateParams.courttypeid;
$scope.searchedDate = $stateParams.bookingdate;
$scope.searchedVenues = venueObj;
$scope.getCourtDetails = function (venueid, venuename) {
$state.go('searchresults.courtpicker', { 'venueid': venueid, 'venuename': venuename });
}
$scope.getVenueDetails = function () {
$scope.venuedetails = venueService.getVenueDetails($scope.venueId);
}
$scope.searchedCourtType = $stateParams.courttypename;
})
.controller('bookingController', function ($scope, $stateParams, reservation) {
$scope.reservationId = reservation;
$scope.basePrice = $stateParams.price;
$scope.serviceTax = (Number($scope.basePrice) * 0.14).toFixed(0);
$scope.totalPrice = Number($scope.basePrice) + Number($scope.serviceTax);
$scope.venueName = $stateParams.venuename;
$scope.courtTypeName = $stateParams.courttypename;
$scope.bookingDate = $stateParams.date;
$scope.courtName = $stateParams.courtname;
$scope.slotIds = $stateParams.slots;
})
.controller('bookingReceiptController', function ($scope, $stateParams, booking) {
$scope.bookingId = booking;
});
}(angular));
|
// Initialize Phaser
var game = new Phaser.Game(1000,750, Phaser.AUTO, 'canvas'); // Define our global variable
game.global = { score: 0 , level: 1 , win: 0, littleHelper: 0, sound: 1, reset:1};
// Add all the states
game.state.add('boot', bootState);
game.state.add('load', loadState);
game.state.add('menu', menuState);
game.state.add('play', playState);
game.state.add('quit', quitState);
// Start the 'boot' state
game.state.start('boot');
|
// JavaScript Document
/*搜索框部分脚本*/
(function()
{
var p=$("#wrap_absolute>p");
var popUp=$("#wrap_absolute");
var dropDownList=$("#search_b");
var input=$(".search_a .search_a_input");
popUp.hover(function(){popUp.css("display","block");},function(){popUp.css("display","none");});
p.hover(function(){popUp.css("display","block");$(this).css("background-color","#F5E8D8");},function(){$(this).css("background-color","#fff");})
dropDownList.click(function(){popUp.css("display","block");})
dropDownList.mouseout(function(){popUp.css("display","none");})
p.click(function()
{
var text=$(this).text();
oldValue=dropDownList.text();
dropDownList.text(text);
if(text=="全部")
{
if($.trim(input.val()).length==0 || input.val()=="输入关键词,在我的CNKI素材库内搜索"|| input.val()=="输入关键词,在我的原创素材库内搜索")
{
input.val("输入关键词,在1.2亿篇文献中搜索素材").addClass("colorGrey");
}
}
if(text=="我的CNKI素材库")
{
if($.trim(input.val()).length==0 || input.val()=="输入关键词,在1.2亿篇文献中搜索素材"|| input.val()=="输入关键词,在我的原创素材库内搜索")
{
input.val("输入关键词,在我的CNKI素材库内搜索").addClass("colorGrey");
}
}
if(text=="我的原创素材库")
{
if($.trim(input.val()).length==0 || input.val()=="输入关键词,在1.2亿篇文献中搜索素材"|| input.val()=="输入关键词,在我的CNKI素材库内搜索")
{
input.val("输入关键词,在我的原创素材库内搜索").addClass("colorGrey");
}
}
$(this).text(oldValue);
popUp.css("display","none");
})
/*文本框内的信息根据选中的类别变化*/
input.focus(function()
{
if(dropDownList.html()=="全部")
{
if($(this).val()=="输入关键词,在1.2亿篇文献中搜索素材")
{
$(this).val("").removeClass("colorGrey");
}
}
else if(dropDownList.html()=="我的CNKI素材库")
{
if($(this).val()=="输入关键词,在我的CNKI素材库内搜索")
{
$(this).val("").removeClass("colorGrey");
}
}
else
{
if(dropDownList.html()=="我的原创素材库")
{
if($(this).val()=="输入关键词,在我的原创素材库内搜索")
{
$(this).val("").removeClass("colorGrey");
}
}
}
})
/*文本框内的信息根据选中的类别变化*/
input.blur(function()
{
if(dropDownList.html()=="全部")
{
if($(this).val()=="")
{
$(this).val("输入关键词,在1.2亿篇文献中搜索素材").addClass("colorGrey");
}
}
else if(dropDownList.html()=="我的CNKI素材库")
{
if($(this).val()=="")
{
$(this).val("输入关键词,在我的CNKI素材库内搜索").addClass("colorGrey");
}
}
else
{
if(dropDownList.html()=="我的原创素材库")
{
if($(this).val()=="")
{
$(this).val("输入关键词,在我的原创素材库内搜索").addClass("colorGrey");
}
}
}
})
})()
|
import RIPEMD160 from 'ripemd160';
export const getVerifyHash = text =>
new RIPEMD160().update(text).digest('hex');
export default { getVerifyHash };
|
import { configureStore } from '@reduxjs/toolkit';
// import { setupListeners } from '@reduxjs/toolkit/query';
import modalSlice from './slices/modalSlice';
import productDetailsSlice from './slices/productDetailsSlice';
import productsSlice from './slices/productsSlice';
import userSlice from './slices/userSlice';
export const store = configureStore({
reducer: {
modal: modalSlice,
user: userSlice,
products: productsSlice,
productDetails: productDetailsSlice,
},
});
// setupListeners(store.dispatch);
|
import React from 'react'
import { HashRouter } from 'react-router-dom'
import { renderRoutes } from 'react-router-config'
import routers from './routers'
import StoreProvider from '@/providers/StoreProvider'
import ThemeProvider from '@/providers/ThemeProvider'
function App() {
return (
<HashRouter>
<ThemeProvider>
<StoreProvider>
{renderRoutes(routers)}
</StoreProvider>
</ThemeProvider>
</HashRouter>
)
}
export default App
|
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Constraint = Matter.Constraint;
var engine, world;
var canvas;
var computerBase, playerBase;
var player, computerPlayer;
function setup() {
canvas = createCanvas(1200, 600);
//Initialising Engine
engine = Engine.create();
world = engine.world;
//Create Player Base and Computer Base Object
computerBase = new ComputerBase(280, 400, 500, 200)
playerBase = new PlayerBase(920, 400, 500, 200)
player = new Player(920, 253, 50,180)
computerPlayer = new ComputerPlayer(280,50,180)
}
function draw() {
background(180);
Engine.update(engine);
// Title
fill("#FFFF");
textAlign("center");
textSize(40);
text("EPIC ARCHERY", width / 2, 100);
//Display Playerbase and computer base
computerBase.display();
playerBase.display();
//display Player and computerplayer
player.display();
computerPlayer.display();
}
|
var assert = require('assert');
module.exports = class Queue extends Array {
constructor(limit=5) {
super();
console.log('costruttoreCoda')
if (limit) {
this._limit = limit;
} else {
this._limit = 5;
}
this._indexOfFirst = -1;
this._indexOfLast = -1;
this._howMany = 0;
}
get limit() {
return this._limit;
}
set limit(value) {
this._limit = value;
}
moveIndex(index) {
assert(index>=-1 && index <=this._limit)
console.log((index + 1) % this._limit);
return (index + 1) % this._limit;
}
enqueue(item) {
// ogni volta che inserisco modifico indece dell'ultimo, quello appena inswerito
if (!this.isfull()) {
// se la coda è vuota devo anche
if (this.isempty()) {
this._indexOfFirst = 0;
}
this._indexOfLast = this.moveIndex(this._indexOfLast);
super[this._indexOfLast] = item;
console.log('messo ' + item);
this._howMany++;
} else {
console.log('la coda è piena')
}
}
dequeue() {
// ogni volta che tolgo modifico l'indice del primo, cioè il prossimo da prelevare
if (!this.isempty()) {
var r = this[this._indexOfFirst];
if (--this._howMany==0) {
this._indexOfFirst = -1;
this._indexOfLast = -1;
console.log('svuotata....' );
} else {
this._indexOfFirst = this.moveIndex(this._indexOfFirst);
}
console.log('preso ' + r);
return r;
} else {
console.log('la coda è vuota')
}
}
isfull() {
return this._howMany == this._limit
}
isempty() {
return (!this._howMany)
}
}
// q = new Queue;
// console.log('---vuota= ' + q.isempty());
// console.log('----piena= ' + q.isfull());
// q.enqueue(0);
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.enqueue(1);
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.enqueue(2);
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.enqueue(3);
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.enqueue(4);
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// console.log('primo dequeue ' + q.dequeue());
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.dequeue();
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.dequeue();
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.dequeue();
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.dequeue();
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.dequeue();
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.dequeue();
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.dequeue();
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
// q.dequeue();
// console.log('vuota= ' + q.isempty());
// console.log('piena= ' + q.isfull());
|
import React from "react";
import {Button, Card, Switch} from "antd";
class SwitchDisabled extends React.Component {
state = {
disabled: true,
};
toggle = () => {
this.setState({
disabled: !this.state.disabled,
});
};
render() {
return (
<Card className="gx-card" title="SwitchDisabled">
<div className="gx-mb-3"><Switch disabled={this.state.disabled} defaultChecked/></div>
<div className="gx-mb-0"><Button type="primary" onClick={this.toggle}>Toggle disabled</Button></div>
</Card>
);
}
}
export default SwitchDisabled;
|
Router.route('/', function () {
this.render('list');
});
Router.route('/create', function () {
this.render('create');
});
|
import React from 'react'
import { storiesOf } from '@storybook/react'
import Message from './index'
const styles = {
container: {
marginBottom: '16px',
},
}
storiesOf('core|UI Feedback/Message', module)
.add('with defaults', () => <Message>This is a default message</Message>, {
info: `Demonstrates default rendering of Message component`,
})
.add(
'with different types',
() => (
<div>
<div style={styles.container}>
<Message type="info">This is an 'info' message</Message>
</div>
<div style={styles.container}>
<Message type="warning">This is a 'warning' message</Message>
</div>
<div style={styles.container}>
<Message type="error">This is an 'error' message</Message>
</div>
</div>
),
{
info: `Demonstrates 'info', 'warning', and 'error' Message types`,
}
)
.add(
'with different alignment',
() => (
<div>
<div style={styles.container}>
<Message align="left">This message is aligned left</Message>
</div>
<div style={styles.container}>
<Message align="center">This message is aligned center</Message>
</div>
<div style={styles.container}>
<Message align="right">This message is aligned right</Message>
</div>
</div>
),
{
info: `Demonstrates alignment options of Message component`,
}
)
|
import {post, get, put, remove} from './crud';
class PostsService {
constructor() {
this.baseUrl = 'http://localhost:5000/post';
this.createUrl = `${this.baseUrl}/create`;
this.editUrl = `${this.baseUrl}/edit`;
this.getUrl = `${this.baseUrl}/all`;
this.searchUrl = `${this.baseUrl}/search`;
this.deleteUrl = `${this.baseUrl}/delete`;
}
createPost(data) {
return post(this.createUrl,data);
}
editPost(data) {
let id = data.id;
return put(`${this.editUrl}/${id}`,data);
}
deletePost(id) {
return remove(`${this.deleteUrl}/${id}`);
}
getPosts() {
return get(this.getUrl);
}
getPost(id) {
return get(`${this.baseUrl}/${id}`);
}
getPostsByName(name) {
return get(`${this.searchUrl}/${name}`)
}
}
export default PostsService
|
define({
"root": {
"SIGNIN" : "Welcome, Please login",
"NEEDREGISTER" : "Register",
"ENTEREMAIL" : "User Name",
"PASSWORD" : "Password",
"REMEMBERME" : "Remember Me",
"FORGOTPWD" : "Forgot password?",
"LOGIN" : "Sign in",
"SIGNINFACEBOOK": "Facebook",
"SIGNINTWITTER" : "Twitter",
"SIGNINGOOGLE" : "Google",
"SIGNINLINKEDIN": "Linkedin",
"COPYRIGHT" : "Copyright © OneTeam. All Rights Reserved.",
"REGISTER" : "Register",
"FIRSTNAME" : "First Name",
"LASTNAME" : "Last Name",
"EMAILADDRESS" : "Email Address",
"CONFIRMPWD" : "Confirm Password",
"ACCOUNTEXISTS" : "Already have an Account?",
"RESETPWD" : "Reset Password",
"ENTRY_EXISTS" : "User found.",
"USER_ENTRY_PASSWORD_REQUIRES_RESET" : "Requires Password Reset.",
"INVALID_CREDENTIALS" : "Invalid Credentials."
},
"en-us": "true"
});
// EOF
|
/**
* @Copyright (c) 2019-present, Zabo & Modular, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict'
const utils = require('../utils')
const { SDKError } = require('../err')
/**
* @typedef {{
* id?: String
* base_currency?: String
* quote_currency?: String
* base_amount?: String
* buy_or_sell?: 'buy' | 'sell'
* quote_amount?: String
* price?: String
* time_in_force?: String
* ttl?: Number
* provide_liquidity_only?: Boolean
* type?: 'limit' | 'market'
* status?: String
* created_at?: Number
* done_at?: Number
* done_reason?: String
* filled_size?: String
* fill_fees?: String
* settled?: Boolean
* request_id?: String
* }} Order
*
* @typedef {{
* data?: [{
* base_currency?: String
* quote_currency?: String
* }]
* request_id?: String
* }} GetSymbolsResp
*
* @typedef {{
* last_price?: String
* last_size?: String
* ask?: String
* ask_size?: String
* bid?: String
* bid_size?: String
* volume?: String
* timestamp?: Number
* request_id?: String
* }} GetTickerInfoResp
*
* @typedef {{
* data?: [Order]
* request_id?: String
* }} GetOrdersResp
*
* @typedef {{
* data?: Order
* request_id?: String
* }} GetOrderResp
*
* @typedef {Pick<Order, 'id' | 'base_currency' | 'quote_currency' | 'buy_or_sell' | 'type' | 'provide_liquidity_only' | 'created_at' | 'status'>} CreateOrderResp
*
* @typedef {{
* data?: [String]
* request_id?: String
* }} CancelOrdersResp
*
* @typedef {CancelOrdersResp} CancelOrderResp
*/
/**
* Trading API.
*/
class Trading {
constructor (api) {
/** @private */
this.api = api
this.account = null
}
/**
* @private
*/
_setAccount (account) {
this.account = account
}
/**
* This function returns the trading tickers available at the given account's provider.
* These pairs can be used in the remaining calls to the Zabo Trading API.
* @returns {Promise<GetSymbolsResp>} API response.
*/
async getSymbols () {
if (!this.account || !this.account.id) {
throw new SDKError(400, '[Zabo] Not connected. See: https://zabo.com/docs#connecting-a-user')
}
try {
return this.api.request('GET', `/accounts/${this.account.id}/trading-symbols`)
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
/**
* This function returns the current market information available for the currency pair,
* at the provider, for the given account.
* @param {{
* baseCurrency: String
* quoteCurrency: String
* }} param0 Request parameters.
* @returns {Promise<GetTickerInfoResp>} API response.
*/
async getTickerInfo ({ baseCurrency, quoteCurrency } = {}) {
if (!this.account || !this.account.id) {
throw new SDKError(400, '[Zabo] Not connected. See: https://zabo.com/docs#connecting-a-user')
} else if (!baseCurrency) {
throw new SDKError(400, '[Zabo] Missing `baseCurrency` parameter. See: https://zabo.com/docs/#get-ticker-info')
} else if (!quoteCurrency) {
throw new SDKError(400, '[Zabo] Missing `quoteCurrency` parameter. See: https://zabo.com/docs/#get-ticker-info')
}
try {
return this.api.request('GET', `/accounts/${this.account.id}/tickers/${baseCurrency}-${quoteCurrency}`)
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
/**
* This function returns all active orders for the given account.
* @returns {Promise<GetOrdersResp>} API response.
*/
async getOrders () {
if (!this.account || !this.account.id) {
throw new SDKError(400, '[Zabo] Not connected. See: https://zabo.com/docs#connecting-a-user')
}
try {
return this.api.request('GET', `/accounts/${this.account.id}/orders`)
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
/**
* This function returns the specific order for the given order id.
* @param {{
* orderId: String
* }} param0 Request parameters.
* @returns {Promise<GetOrderResp>} API response.
*/
async getOrder ({ orderId } = {}) {
if (!this.account || !this.account.id) {
throw new SDKError(400, '[Zabo] Not connected. See: https://zabo.com/docs#connecting-a-user')
} else if (!orderId) {
throw new SDKError(400, '[Zabo] Missing `orderId` parameter. See: https://zabo.com/docs/#get-an-order')
} else if (!utils.uuidValidate(orderId)) {
throw new SDKError(400, '[Zabo] `orderId` must be a valid UUID v4. See: https://zabo.com/docs/#get-an-order')
}
try {
return this.api.request('GET', `/accounts/${this.account.id}/orders/${orderId}`)
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
/**
* This function creates a new trade order.
* @param {{
* baseCurrency: String
* baseAmount?: String
* quoteCurrency: String
* quoteAmount?: String
* buyOrSell: 'buy' | 'sell'
* priceLimit?: String
* timeInForce?: String
* ttl?: Number
* provideLiquidityOnly?: Boolean
* }} param0 Request parameters.
* @returns {Promise<CreateOrderResp>} API response.
*/
async createOrder ({ baseCurrency, quoteCurrency, buyOrSell, priceLimit, baseAmount, quoteAmount, provideLiquidityOnly, timeInForce, ttl } = {}) {
if (!this.account || !this.account.id) {
throw new SDKError(400, '[Zabo] Not connected. See: https://zabo.com/docs#connecting-a-user')
} else if (!baseCurrency) {
throw new SDKError(400, '[Zabo] Missing `baseCurrency` parameter. See: https://zabo.com/docs/#place-new-order')
} else if (!quoteCurrency) {
throw new SDKError(400, '[Zabo] Missing `quoteCurrency` parameter. See: https://zabo.com/docs/#place-new-order')
} else if (typeof baseAmount !== 'undefined' && baseAmount <= 0) {
throw new SDKError(400, '[Zabo] `baseAmount` must be greater than 0. See: https://zabo.com/docs/#place-new-order')
} else if (typeof quoteAmount !== 'undefined' && quoteAmount <= 0) {
throw new SDKError(400, '[Zabo] `quoteAmount` must be greater than 0. See: https://zabo.com/docs/#place-new-order')
} else if (typeof priceLimit !== 'undefined' && priceLimit <= 0) {
throw new SDKError(400, '[Zabo] `priceLimit` must be greater than 0. See: https://zabo.com/docs/#place-new-order')
}
utils.validateEnumParameter('buyOrSell', buyOrSell, ['buy', 'sell'])
utils.validateEnumParameter('timeInForce', timeInForce, ['GTC', 'GTT', 'IOC', 'FOK'], true)
try {
return this.api.request('POST', `/accounts/${this.account.id}/orders`, {
base_currency: baseCurrency,
quote_currency: quoteCurrency,
buy_or_sell: buyOrSell,
price_limit: priceLimit,
base_amount: baseAmount,
quote_amount: quoteAmount,
provide_liquidity_only: provideLiquidityOnly,
time_in_force: timeInForce,
ttl: ttl
})
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
/**
* This function cancels all open orders.
* @returns {Promise<CancelOrdersResp>} API response.
*/
async cancelOrders () {
if (!this.account || !this.account.id) {
throw new SDKError(400, '[Zabo] Not connected. See: https://zabo.com/docs#connecting-a-user')
}
try {
return this.api.request('DELETE', `/accounts/${this.account.id}/orders`)
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
/**
* This function cancels the order with the given order id.
* @param {{
* orderId: String
* }} param0 Request parameters.
* @returns {Promise<CancelOrderResp>} API response.
*/
async cancelOrder ({ orderId } = {}) {
if (!this.account || !this.account.id) {
throw new SDKError(400, '[Zabo] Not connected. See: https://zabo.com/docs#connecting-a-user')
} else if (!orderId) {
throw new SDKError(400, '[Zabo] Missing `orderId` parameter. See: https://zabo.com/docs/#cancel-an-order')
} else if (!utils.uuidValidate(orderId)) {
throw new SDKError(400, '[Zabo] `orderId` must be a valid UUID v4. See: https://zabo.com/docs/#cancel-an-order')
}
try {
return this.api.request('DELETE', `/accounts/${this.account.id}/orders/${orderId}`)
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
}
/**
* @typedef {Trading} TradingAPI
* @type {(api) => TradingAPI}
*/
module.exports = (api) => {
return new Trading(api)
}
|
var exception_manager_8h =
[
[ "CLASS_DIFFER_FILE_NAME", "exception_manager_8h.html#a4c0e3ce2843ba84506b8245e5817aa2d", null ],
[ "CLASS_DIFFER_FILE_NAME_MSG", "exception_manager_8h.html#a6f2290b6f292939c4edb966b920269af", null ],
[ "EXTERN", "exception_manager_8h.html#a77366c1bd428629dc898e188bfd182a3", null ],
[ "INSUFFICIENT_MEMORY", "exception_manager_8h.html#a4921f9a186627faaebc505056ab7ed6e", null ],
[ "INSUFFICIENT_MEMORY_MSG", "exception_manager_8h.html#aae40cf1a4e4697592bb4a6840c84dc77", null ],
[ "MAIN_NOT_FOUND", "exception_manager_8h.html#a29ac845cfb3267ecbd6d4c7fc8e61c0f", null ],
[ "MAIN_NOT_FOUND_MSG", "exception_manager_8h.html#a542bc2de649b402110fab7b2a1d32c41", null ],
[ "NOT_BYTECODE_JAVA", "exception_manager_8h.html#a63b7662e3ceb875e83b384145372395e", null ],
[ "NOT_BYTECODE_JAVA_MSG", "exception_manager_8h.html#a2ef8c9bf0f6adaa3a0af6d07886eb85a", null ],
[ "NOT_JAVA_2_VERSION", "exception_manager_8h.html#afc829e1dbd9da36dcf2174ca2f44b83a", null ],
[ "NOT_JAVA_2_VERSION_MSG", "exception_manager_8h.html#aa76f9d350b78b95ed44adf6471c782f8", null ],
[ "OPEN_FILE_ERROR", "exception_manager_8h.html#af2403da382c35cbe6d8523a905c7cbf5", null ],
[ "OPEN_FILE_ERROR_MSG", "exception_manager_8h.html#a590db159e50280c2234a767d8dc1af52", null ],
[ "POP_IN_A_EMPTY_STACK", "exception_manager_8h.html#a67e4b213a18f3916811719fea63440fe", null ],
[ "POP_IN_A_EMPTY_STACK_MSG", "exception_manager_8h.html#a467452d299a4eb41e8b17d9235968ca6", null ],
[ "throwException", "exception_manager_8h.html#a5049a305044a7c74e4e9b14385d92ea6", null ]
];
|
(function() {
var DepositView, _bank, _query, _table, _page;
var _menu = BackendAdminPayDee._menu;
var _datepicker = BackendAdminPayDee._datepicker;
var _notifyForUser = BackendAdminPayDee._notifyForUser;
var _currency = BackendAdminPayDee._currency;
var _pageCommon = BackendAdminPayDee._page;
var _partner = BackendAdminPayDee._partner;
var _status = TransactionCommon._status;
_menu.activeMenu('deposit-menu');
_datepicker.init('fromDate');
_datepicker.init('toDate');
_partner.init();
_status.init();
DepositView = window.DepositView = {};
DepositView.Bank = (function() {
function Bank() {
this.current = undefined;
this.bankNameEl = $('select[name="bankName"]');
this.bankNameEl.on("select2:select", function () {
_bank.current = _bank.bankNameEl.val();
console.log(_bank);
});
this.init();
}
Bank.prototype.init = function() {
var url = BASE_URL + "/json/listBankApplied.json";
var self = this;
$.ajax({
async: true,
url: url,
method: "GET",
dataType: "json"
}).done(function(data) {
console.log(JSON.stringify(data));
$.each(data, function(idx, obj) {
var option = $('<option>', {"value": obj.shortName, "text": obj.shortName});
self.bankNameEl.append(option);
});
self.bankNameEl.select2();
self.current = self.bankNameEl.select2('data')[0].id;
}).fail(function() {
console.log("Đã xảy ra lỗi khi lấy danh sách ngân hàng!");
_notifyForUser.error('Đã xảy ra lỗi khi lấy danh sách ngân hàng!');
_notifyForUser.show();
}).always(function() {
console.log("Complete Call Ajax: Get list banks!" );
});
};
return Bank;
})();
DepositView.Query = (function() {
function Query() {
this.fromDate = $('input[name="fromDate"]');
this.toDate = $('input[name="toDate"]');
this.transactionIdEl = $('input[name="transactionId"]');
this.paydAccountNoEl = $('input[name="paydAccountNo"]');
this.bankAccountNoEl = $('input[name="bankAccountNo"]');
this.btnSearch = $('button[name="search-deposit"]');
this.btnExcel = $('button[name="to-excel-deposit"]');
this.btnReset = $('button[name="reset-deposit"]');
this.btnSearch.on('click', { context: this }, function(e) {
_pageCommon.resetNumber();
e.data.context.search();
});
this.btnExcel.on('click', { context: this }, function(e) {
e.data.context.exportData();
});
this.btnReset.bind('click', { context: this}, function (e) {
_pageCommon.resetNumber();
e.data.context.reset();
})
}
Query.prototype.makeRequest = function () {
_query.request = {
fromdate: _query.fromDate.val(),
toDate: _query.toDate.val(),
transactionId: _query.transactionIdEl.val(),
partnerId: _partner.current < 0 ? null : _partner.current,
paydAccountNo: _query.paydAccountNoEl.val(),
bankName: _bank.current < 0 ? null : _bank.current,
bankAccountNo: _query.bankAccountNoEl.val(),
status: _status.current < 0 ? null : _status.current,
pageNumber: (_pageCommon.number < 1) ? 1 : (_pageCommon.number + 1),
pageSize: _pageCommon.defaultSize
}
};
Query.prototype.validateRequest = function() {
return _datepicker.validateDuration(_query.fromDate.val(), _query.toDate.val());
};
Query.prototype.search = function() {
if(!_query.validateRequest()) return;
_query.makeRequest();
_page.loadData(_query.request);
};
Query.prototype.reset = function() {
this.fromDate.val('');
this.toDate.val('');
this.transactionIdEl.val('');
this.paydAccountNoEl.val('');
this.bankAccountNoEl.val('');
_status.statusEl.val("-1").trigger('change.select2');
_partner.partnerEl.val("-1").trigger('change.select2');
_bank.bankNameEl.val("-1").trigger('change.select2');
_status.current = -1;
_partner.current = -1;
_bank.current = -1;
};
Query.prototype.exportData = function() {
if(!_query.validateRequest()) return;
_query.makeRequest();
var url = BASE_URL + "/transaction/export-deposit";
console.log("export deposit with url: " + url);
$.ajax({
url: url,
type: 'POST',
contentType : 'application/json',
async: true,
data : JSON.stringify(request)
}).done(function(data) {
console.log(JSON.stringify(data));
if(data === null || data === '' || data !== 'done') {
_notifyForUser.error("Thực hiên xuất giao dịch nạp tiền ngân hàng thất bại!");
} else {
_notifyForUser.ok("Thực hiên xuất giao dịch nạp tiền ngân hàng thành công!");
}
_notifyForUser.show();
}).fail(function(data) {
console.log(data);
console.log("Đã xảy ra lỗi khi thực hiện xuất giao dịch nạp tiền ngân hàng!");
_notifyForUser.error('Đã xảy ra lỗi khi thực hiện xuất giao dịch nạp tiền ngân hàng!');
_notifyForUser.show();
}).always(function() {
console.log("Complete Call Ajax: Export Deposit Telco!" );
});
};
return Query;
})();
DepositView.Table = (function() {
function Table() {
this.el = $('#search-deposit-table');
this.data = [];
this.tableEl = this.el.find('table');
}
Table.prototype.makeTable = function() {
this.tableEl.children('tbody').remove();
this.tableEl.append(this.makeBody());
};
Table.prototype.makeBody = function() {
var tbody = $('<tbody>');
$.each(this.data, function(idx, obj) {
var _actionMenu = new BackendAdminPayDee.ActionMenu(); // Phải khởi tạo đối tượng mới.
_actionMenu.addMenu('fa-bar-chart', "Chi tiết", '#', 'alert("Đã click chi tiết!")');
var tooltip = "<b>- To Partner:</b> " + obj.responseToPartner;
var accountDetail = "<strong>" + obj.fullName + "</strong><br/>" + obj.phoneNumber + "<br/><strong>" + obj.paydAccountNo + "</strong>";
tbody.append($('<tr>')
// .append($('<td>', {"class": "text-nowrap"}).append(idx + 1 + _pageCommon.number * _pageCommon.defaultSize))
.append($('<td>', {"class": "text-nowrap"}).append(obj.transactionId))
.append($('<td>', {"class": "text-nowrap"}).append($('<span>', {"data-toggle": "tooltip", "data-html": "true", "data-original-title": tooltip}).append(obj.depositTime)))
.append($('<td>', {"class": "text-nowrap"}).append(obj.partnerName))
.append($('<td>', {"class": "text-nowrap"}).append(accountDetail))
.append($('<td>', {"class": "text-nowrap"}).append(obj.bankTransRef))
.append($('<td>', {"class": "text-nowrap"}).append(obj.bankName))
// .append($('<td>', {"class": "text-nowrap"}).append(obj.bankAccountNo))
.append($('<td>', {"class": "text-nowrap"}).append(obj.bankAccountHolder))
.append($('<td align=\'right\'>', {"class": "text-nowrap"}).append(_currency.formatCurrency(obj.amount)))
.append($('<td>', {"class": "text-nowrap"}).append($('<span>', {"data-toggle": "tooltip", "data-html": "true", "data-original-title": tooltip}).append(_status.toText(obj.status))))
/*.append($('<td>').append(_actionMenu.toHtml()))*/);
});
return tbody;
};
return Table;
})();
DepositView.Page = (function() {
function Page() {
this.paginationEl = _table.el.find('ul.pagination');
}
Page.prototype.loadData = function() {
var url = BASE_URL + "/transaction/deposit";
var self = this;
$.ajax({
async: true,
url: url,
method: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(_query.request),
dataType: "json"
}).done(function(data) {
console.log(data);
_pageCommon.number = data.pageNumber;
_pageCommon.total = data.pagesAvailable;
_pageCommon.list = _pageCommon.calculatePage(data.pageNumber, data.pagesAvailable);
_table.data = data.pageItems;
_table.makeTable();
_pageCommon.pagination(self.paginationEl, DepositView._query);
}).fail(function() {
console.log("Đã xảy ra lỗi khi thực hiện tìm kiếm Giao dịch Nạp tiền từ bank!");
_notifyForUser.error('Đã xảy ra lỗi khi thực hiện tìm kiếm Giao dịch Nạp tiền từ bank!');
_notifyForUser.show();
}).always(function() {
console.log("Complete Call Ajax: Search Deposit!" );
});
};
return Page;
})();
_bank = new DepositView.Bank();
_query = new DepositView.Query();
_table = new DepositView.Table();
_page = new DepositView.Page();
DepositView._query = _query;
_query.search();
}).call(this);
|
export const CONTACT_US = "/contact-us";
export const COOKIE_POLICY = "/cookie-policy";
export const PRIVACY_POLICY = "/privacy-policy";
export const TERMS_AND_CONDITIONS = "/terms-and-conditions";
export const FAQ = "/faq";
export const SIGN_UP = "/sign-up";
export const SIGN_IN = "/sign-in";
export const FORGOT_PASSWORD = "/forgot-password";
export const SUCCESS = "/success";
export const VERIFICATION = "/verification";
export const CHECK_MAIL_BOX = "/check-mailbox";
export const CHANGE_PASSWORD = "/change-password";
export const CREATE_PROFILE = "/profile/create";
export const EDIT_PROFILE = "/profile/edit";
export const LISTINGS = "/listings";
export const MATCHES = "/matches";
export const SETTINGS = "/settings";
export const MESSAGES = "/messages";
export const CREATE_NEW_POST = "/new-post";
export const EDIT_POST = "/edit-post";
export const NO_MATCHES = "/no-matches";
export const NOTIFICATIONS = "/notifications";
export const SETTINGS_LISTINGS = "/settings/listings";
export const SETTINGS_MATCHES = "/settings/matches";
export const SETTINGS_PROFILES = "/settings/profiles";
export const SETTINGS_NOTIFICATIONS = "/settings/notifications";
export const SETTINGS_ACCOUNT = "/settings/account";
export const SETTINGS_LEGAL = "/settings/legal";
export const SERVER_ERROR = "/server-error";
|
export { default as PersonPhoto} from './PersonPhoto';
|
import '../css/Card-view.css';
import {useHistory} from 'react-router-dom';
function CardView(props){
var hist=useHistory();
const Al=(caty)=>{
hist.push('list/'+caty)
}
const Categories=props.data;
return(
<div>
{Categories.map((items,index)=>(
<section className="card-container" key={index} onClick={()=>{Al(items.category)}}>
<section className="card-title">
{items.category}
</section>
<section className="card-image">
<img src={items.image} alt="card-img"/>
</section>
<section className="card-button">
<button onClick={()=>Al(items.category)}>view</button>
</section>
</section>
))}
</div>
);
}
export default CardView
|
'use strict';
const path = require('path');
const anticaptcha = require('../index');
const fs = require('fs');
const main = async () => {
const client = anticaptcha(process.env.ANTICAPTCHA_KEY);
const file_path = path.join(__dirname, 'captcha_ms.jpeg');
const result = await client.getImage(fs.createReadStream(file_path), {
restriction: {
minLength: 5,
maxLength: 5,
},
});
return result.getValue();
};
module.exports = main;
|
const express = require('express');
const router = express.Router();
/*GET users listing. */
router.get('/', function(req, res, next) {
//res.send('respond with a resource');
res.json([
{
"id": 1,
"name": "Jet_1",
"category": "plane",
"price": 10,
"imagePath": "/images/ethan-mcarthur-1BRYdVhFnqc-unsplash.jpg"
},
{
"id": 2,
"name": "Jet_2",
"category": "plane",
"price": 12,
"imagePath": "/images/ethan-mcarthur-1BRYdVhFnqc-unsplash.jpg"
},
{
"id": 3,
"name": "Yacht_1",
"category": "yacht",
"price": 6,
"imagePath": "/images/ethan-mcarthur-1BRYdVhFnqc-unsplash.jpg"
},
{
"id": 4,
"name": "Yacht_2",
"category": "yacht",
"price": 9,
"imagePath": "/images/ethan-mcarthur-1BRYdVhFnqc-unsplash.jpg"
},
{
"id": 5,
"name": "Car_1",
"category": "car",
"price": 2,
"imagePath": "/images/ethan-mcarthur-1BRYdVhFnqc-unsplash.jpg"
},
{
"id": 6,
"name": "Car_2",
"category": "car",
"price": 3,
"imagePath": "/images/ethan-mcarthur-1BRYdVhFnqc-unsplash.jpg"
}]);
});
module.exports = router;
|
const block_id = 'TY-approval-4YT';
const approval_msg = (message, yes_value, no_value) => {
return [
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': message
}
},
{
'type': 'actions',
'block_id': block_id,
'elements': [
{
'type': 'button',
'text': {
'type': 'plain_text',
'text': 'Yes',
'emoji': true
},
'value': JSON.stringify(yes_value),
'style': 'primary'
},
{
'type': 'button',
'text': {
'type': 'plain_text',
'text': 'No',
'emoji': true
},
'value': JSON.stringify(no_value),
'style': 'danger'
}
]
}
]
}
module.exports = {
msg: approval_msg,
block_id: block_id
}
|
import { getAllPosts } from '../api/posts-RestClient';
import { getPostsByCategory } from '../api/posts-RestClient';
export const LOAD_POSTS = 'LOAD_POSTS';
export const SELECT_CATEGORY = 'SELECT_CATEGORY';
export const fetchPosts = () => dispatch => (
getAllPosts()
.then(posts => dispatch({
type: LOAD_POSTS,
posts
}))
);
export const fetchPostsByCategory = (category) => dispatch => (
getPostsByCategory()
.then(posts => dispatch({
type: SELECT_CATEGORY,
category,
posts
}))
);
|
$(function () {
var h = $(".container-fluid-full").height();
var h1 = $("#content .breadcrumb").height();
$("#tree").height(h - h1 - 27);
$.ajax({
url: "static/page/designcoordination/designplan/designplan.json",
type: "get",
dataType:"json",
success: function (data) {
var zTreeObj;
var setting = {
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId: "0"
}
}
};
zTreeObj = $.fn.zTree.init( $("#tree"), setting, data);
zTreeObj.expandAll(true);
var node = zTreeObj.getNodeByParam("id", 1, null);
zTreeObj.selectNode(node);
}
});
$("tbody tr td:last-of-type button").each(function () {
$(this).click(function () {
console.log($(this).index());
})
});
$(".check").eq(0).click(function () {
$(".different").eq(2).show();
return false;
});
$(".check").eq(1).click(function () {
$(".different").eq(1).show();
return false;
});
$(".check").eq(2).click(function () {
$(".different").eq(0).show();
return false;
});
$(".check").eq(3).click(function () {
$(".different").eq(2).show();
return false;
});
$(".gb").eq(0).click(function () {
$(".different").eq(0).hide();
});
$(".gb").eq(1).click(function () {
$(".different").eq(1).hide();
});
$(".gb").eq(2).click(function () {
$(".different").eq(2).hide();
});
$(".gb").eq(3).click(function () {
$(".different").eq(2).hide();
});
});
|
// Thanks to @maximegris!!!
// Digs into @angular/cli packaged configuration and replaces the renderer target for electron to allow native module usage.
const angularCliWebpack = './node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/browser.js';
const fs = require('fs');
fs.readFile(angularCliWebpack, 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
var res = data.replace(/target: "electron-renderer",/g, '');
var res = res.replace(/target: "web",/g, '');
var res = res.replace(/return \{/g, 'return {target: "electron-renderer",');
fs.writeFile(angularCliWebpack, res, 'utf8', function (err) {
if (err) return console.log(err);
});
});
|
'use strict';
let db;
exports.booksDbSetup = function(database) {
db = database;
return database.schema.hasTable("books").then(exists => {
console.log("Checking if books table exists...");
if (!exists) {
console.log("It doesn't!");
} else {
console.log('Ok.');
}
});
}
/**
* Books available in the inventory
* List of books available in the inventory
*
* offset Integer Pagination offset. Default is 0. (optional)
* limit Integer Maximum number of items per page. Default is 20 and cannot exceed 500. (optional)
* returns List
**/
exports.booksGET = function(offset,limit) {
return db.raw("SELECT b.*, a1.name as name, a2.name as name2, a3.name as name3, a4.name as name4 " +
"FROM books as b "+
"LEFT JOIN authors as a1 ON b.author = a1.id " +
"LEFT JOIN authors as a2 ON b.author2 = a2.id " +
"LEFT JOIN authors as a3 ON b.author3 = a3.id " +
"LEFT JOIN authors as a4 ON b.author4 = a4.id " +
"LIMIT " + limit + " OFFSET " + offset +";")
}
/**
* Finds book by ID
* Returns a book
*
* bookId Long ID of book to return
* returns Book
**/
exports.getBookById = function(bookId) {
return db.raw("SELECT b.*, a1.name as name, a2.name as name2, a3.name as name3, a4.name as name4 " +
"FROM books as b "+
"LEFT JOIN authors as a1 ON b.author = a1.id " +
"LEFT JOIN authors as a2 ON b.author2 = a2.id " +
"LEFT JOIN authors as a3 ON b.author3 = a3.id " +
"LEFT JOIN authors as a4 ON b.author4 = a4.id " +
"WHERE b.id = " + bookId)
}
/**
* Find books by number of sold copies
* Returns a list of books ordered by sold copies
*
* offset Integer Pagination offset. Default is 0. (optional)
* limit Integer Maximum number of items per page. Default is 20 and cannot exceed 500. (optional)
* returns Book
**/
exports.getBookBySoldCopies = function(offset,limit) {
return db.raw("SELECT b.*, a1.name as name, a2.name as name2, a3.name as name3, a4.name as name4 " +
"FROM books as b "+
"LEFT JOIN authors as a1 ON b.author = a1.id " +
"LEFT JOIN authors as a2 ON b.author2 = a2.id " +
"LEFT JOIN authors as a3 ON b.author3 = a3.id " +
"LEFT JOIN authors as a4 ON b.author4 = a4.id " +
"ORDER BY soldqty desc " +
"LIMIT " + limit + " OFFSET " + offset +";")
}
/**
* Find book(s) by author
* Returns a book (or more) with specified author
*
* author String author of book(s) to return
* offset Integer Pagination offset. Default is 0. (optional)
* limit Integer Maximum number of items per page. Default is 20 and cannot exceed 500. (optional)
* returns Book
**/
exports.getBooksByAuthor = function(author,offset,limit) {
return db.raw("SELECT b.*, a1.name as name, a2.name as name2, a3.name as name3, a4.name as name4 " +
"FROM books as b "+
"LEFT JOIN authors as a1 ON b.author = a1.id " +
"LEFT JOIN authors as a2 ON b.author2 = a2.id " +
"LEFT JOIN authors as a3 ON b.author3 = a3.id " +
"LEFT JOIN authors as a4 ON b.author4 = a4.id " +
"WHERE b.author = "+author+" OR b.author2="+author+" OR b.author3="+author+" OR b.author4="+author+" "+
"LIMIT " + limit + " OFFSET " + offset +";")
}
/**
* Find book(s) by genre
* Returns a book (or more) with specified genre
*
* genre String genre of book(s) to return
* offset Integer Pagination offset. Default is 0. (optional)
* limit Integer Maximum number of items per page. Default is 20 and cannot exceed 500. (optional)
* returns Book
**/
exports.getBooksByGenre = function(genre,offset,limit) {
return db.raw("SELECT b.*, a1.name as name, a2.name as name2, a3.name as name3, a4.name as name4 " +
"FROM books as b "+
"LEFT JOIN authors as a1 ON b.author = a1.id " +
"LEFT JOIN authors as a2 ON b.author2 = a2.id " +
"LEFT JOIN authors as a3 ON b.author3 = a3.id " +
"LEFT JOIN authors as a4 ON b.author4 = a4.id " +
"WHERE b.genre = '"+genre+"' "+
"LIMIT " + limit + " OFFSET " + offset +";")
}
/**
* Find book(s) by publication date
* Returns a book (or more) with specified date
*
* date String publication date of book(s) to return
* offset Integer Pagination offset. Default is 0. (optional)
* limit Integer Maximum number of items per page. Default is 20 and cannot exceed 500. (optional)
* returns Book
**/
exports.getBooksByPublicationDate = function(date,offset,limit) {
return db.raw("SELECT b.*, a1.name as name, a2.name as name2, a3.name as name3, a4.name as name4 " +
"FROM books as b "+
"LEFT JOIN authors as a1 ON b.author = a1.id " +
"LEFT JOIN authors as a2 ON b.author2 = a2.id " +
"LEFT JOIN authors as a3 ON b.author3 = a3.id " +
"LEFT JOIN authors as a4 ON b.author4 = a4.id " +
"WHERE b.publicationDate = "+date+" "+
"LIMIT " + limit + " OFFSET " + offset +";")
}
/**
* Find book(s) by theme
* Returns a list of books with specified theme
*
* theme String theme of books to return
* offset Integer Pagination offset. Default is 0. (optional)
* limit Integer Maximum number of items per page. Default is 20 and cannot exceed 500. (optional)
* returns Book
**/
exports.getBooksByTheme = function(theme,offset,limit) {
return db.raw("SELECT b.*, a1.name as name, a2.name as name2, a3.name as name3, a4.name as name4 " +
"FROM books as b "+
"LEFT JOIN authors as a1 ON b.author = a1.id " +
"LEFT JOIN authors as a2 ON b.author2 = a2.id " +
"LEFT JOIN authors as a3 ON b.author3 = a3.id " +
"LEFT JOIN authors as a4 ON b.author4 = a4.id " +
"WHERE b.theme1 = '"+theme+"' OR b.theme2='"+theme+"' OR b.theme3='"+theme+"' "+
"LIMIT " + limit + " OFFSET " + offset +";")
}
/**
* Find book(s) by Title
* Returns a book (or more) with specified title
*
* title String title of book(s) to return
* offset Integer Pagination offset. Default is 0. (optional)
* limit Integer Maximum number of items per page. Default is 20 and cannot exceed 500. (optional)
* returns Book
**/
exports.getBooksByTitle = function(title,offset,limit) {
title = title.toLowerCase()
title = "'%"+title+"%'"
return db.raw("SELECT b.*, a1.name as name, a2.name as name2, a3.name as name3, a4.name as name4 " +
"FROM books as b "+
"LEFT JOIN authors as a1 ON b.author = a1.id " +
"LEFT JOIN authors as a2 ON b.author2 = a2.id " +
"LEFT JOIN authors as a3 ON b.author3 = a3.id " +
"LEFT JOIN authors as a4 ON b.author4 = a4.id " +
"WHERE lower(title) like "+title+" "+
"LIMIT " + limit + " OFFSET " + offset +";")
}
/**
* Find sponsored books
* Returns a list of sponsored books
*
* offset Integer Pagination offset. Default is 0. (optional)
* limit Integer Maximum number of items per page. Default is 20 and cannot exceed 500. (optional)
* returns Book
**/
exports.getSponsoredBooks = function(offset,limit) {
return db.raw("SELECT b.*, a1.name as name, a2.name as name2, a3.name as name3, a4.name as name4 " +
"FROM books as b "+
"LEFT JOIN authors as a1 ON b.author = a1.id " +
"LEFT JOIN authors as a2 ON b.author2 = a2.id " +
"LEFT JOIN authors as a3 ON b.author3 = a3.id " +
"LEFT JOIN authors as a4 ON b.author4 = a4.id " +
"WHERE b.issponsored " +
"LIMIT " + limit + " OFFSET " + offset +";")
}
//get books ordered by sold copies in the specified month (and year)
exports.getBooksBySoldCopiesInMonth = function(month, year, offset, limit) {
return db.raw("SELECT b.*, s.*, a1.name as name, a2.name as name2, a3.name as name3, a4.name as name4 " +
"FROM sales as s "+
"LEFT JOIN books as b ON s.bookid = b.id " +
"LEFT JOIN authors as a1 ON b.author = a1.id " +
"LEFT JOIN authors as a2 ON b.author2 = a2.id " +
"LEFT JOIN authors as a3 ON b.author3 = a3.id " +
"LEFT JOIN authors as a4 ON b.author4 = a4.id " +
"WHERE s.month = "+month+" AND s.year="+year+" "+
"ORDER BY totalsold DESC " +
"LIMIT " + limit + " OFFSET " + offset +";")
}
|
import App from "./work6"
export default App;
|
global.ROUTER.web.Member.sign_up = function( req, res ){
global.api.HTML.render_html( req, res )
}
|
/**
* Created by aaronendsley on 2/19/16.
*/
'use strict'
var app = angular.module('BillsApp', [])
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import utils from 'common/utils';
import http from 'common/http';
import moment from 'moment';
import G6 from '@antv/g6';
import Plugins from '@antv/g6-plugins';
import flowIamge from './images/configure_b.png';
import startIamge from './images/start.png';
import endIamge from './images/end.png';
import tacheIamge from './images/tache.png';
import controlIamge from './images/controlNode.png';
import mergeIamge from './images/mergeNode.png';
import parallelIamge from './images/parallelNode.png';
import abnormalIamge from './images/abnormal.png';
import G6Styles from './G6Styles.scss';
const PREFIX = 'flow-G6component';
const cx = utils.classnames(PREFIX, G6Styles);
let stateConfig = {
"FFF": ["开始", "#5dbe16", false],
"10I": ["未开始", "#cbcbcb", false],
"10D": ["正在处理", "#51c6f7", false],
"10F": ["按时完成", "#94e15a", false],
"10O": ["超时完成", "#f6db56", false],
"10E": ["超时未完成", "#f99847", false],
"10X": ["执行异常", "#ff5453", false],
"10A": ["作废", "#5c5c5c", false]
}
class FlowExhibitionG6 extends Component {
constructor(props) {
super(props);
this.state={
data:{}
}
}
stateColorShow=()=>{
var stateArr = [];
for (var Key in stateConfig){
var obj = {};
obj.text = stateConfig[Key][0];
obj.col = stateConfig[Key][1];
stateArr.push(obj)
}
return (
<ul className={`${cx('list')}`} >
{stateArr.map((item,index) =>
<li key={index}>
<div style={{backgroundColor:item.col}} className={item.text=="正在处理"?`${cx('breathe_btn')}`:null}></div>
<div >
{item.text}
</div>
</li>
)}
</ul>
);
}
//解析xml字符串为DOM
parseXML=(xmlString)=>{
var xmlDoc = null;
//判断浏览器的类型
//支持IE浏览器
if(!window.DOMParser && window.ActiveXObject) { //window.DOMParser 判断是否是非ie浏览器
var xmlDomVersions = ['MSXML.2.DOMDocument.6.0', 'MSXML.2.DOMDocument.3.0', 'Microsoft.XMLDOM'];
for(var i = 0; i < xmlDomVersions.length; i++) {
try {
xmlDoc = new ActiveXObject(xmlDomVersions[i]);
xmlDoc.async = false;
xmlDoc.loadXML(xmlString); //loadXML方法载入xml字符串
break;
} catch(e) {}
}
}
//支持Mozilla浏览器
else if(window.DOMParser && document.implementation && document.implementation.createDocument) {
try {
/* DOMParser 对象解析 XML 文本并返回一个 XML Document 对象。
* 要使用 DOMParser,使用不带参数的构造函数来实例化它,然后调用其 parseFromString() 方法
* parseFromString(text, contentType) 参数text:要解析的 XML 标记 参数contentType文本的内容类型
* 可能是 "text/xml" 、"application/xml" 或 "application/xhtml+xml" 中的一个。注意,不支持 "text/html"。
*/
var domParser = new DOMParser();
xmlDoc = domParser.parseFromString(xmlString, 'text/xml');
} catch(e) {}
} else {
return null;
}
return xmlDoc;
}
loaderG6=(xmlData)=>{
G6.registerNode('circle', {
draw(cfg, group){
let imgType;
switch(cfg.label){
case "开始节点":
imgType = startIamge
break;
case "结束节点":
imgType = endIamge
break;
case "控制节点":
imgType = controlIamge
break;
case "合并节点":
imgType = mergeIamge
break;
case "并行节点":
imgType = parallelIamge
break;
case "未处理":
imgType = abnormalIamge
break;
default:
imgType = tacheIamge
}
group.addShape('text', {
attrs: {
x:0,
y: 40,
fill: '#333333',
text: cfg.label,
fontSize: 14,
textAlign: 'center',
}
});
if(cfg.origin.colorState== "10D"){
let an = group.addShape('circle', {
attrs: {
x: 0,
y: 0,
r: 20,
stroke:"#51C4F8 ",
shadowColor:"#51C4F8",
shadowBlur:10,
fill:cfg.color
}
}).animate({
stroke:"#45bff6",
shadowColor:"#45bff6",
shadowBlur:10,
repeat: true,
},800, 'easeOutBack')
}else{
group.addShape('circle', {
attrs: {
x: 0,
y: 0,
r: 20,
fill:cfg.color
}
})
}
group.addShape('image', {
attrs: {
x: -13,
y: -13,
width:26,
height:26,
img:imgType
}
});
return group.addShape('circle', {
attrs: {
x: 0,
y: 0,
r: 24,
fill:'transparent'
}
});
}
});
const dagre = new Plugins['layout.dagre']({
rankdir: 'LR',
nodesep: 40,
ranksep: 100,
useEdgeControlPoint:false
});
const net = new G6.Net({
id: 'flowExhibitionG6',
height: 350,
grid: null,
useAnchor:true,
fitView: 'lc',
mode: 'drag',
plugins: [dagre]
});
net.clear();
net.tooltip(true);
net.source(xmlData.nodes, xmlData.edges);
net.node().tooltip('id');
net.render();
}
loadData=()=>{
const param = {
processDefineCode:this.props.processDefineCode
};
http.post('/call/call.do',{
bean: 'FlowServ',
method: 'qryProcessDefineByCode',
param: param
},{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}).then(res => {
const xmlCode = JSON.parse(res);
// console.log(parseXML(xmlCode).getElementsByTagName('Transition'));
console.log(xmlCode)
const xmlDomNodes = this.parseXML(xmlCode).getElementsByTagName('Activity');
const xmlDomEdges = this.parseXML(xmlCode).getElementsByTagName('Transition');
const arrNodes =[];
const arrEdges =[];
for(let i =0;i<xmlDomNodes.length;i++){
// console.log(xmlDomNodes[i].getAttribute("state"))
let nodeColor;
switch(xmlDomNodes[i].getAttribute("name")){
case "开始节点":
nodeColor = "#5dbe16"
break;
case "结束节点":
nodeColor = "#fe0200"
break;
case "控制节点":
nodeColor = "#349bff"
break;
case "合并节点":
nodeColor = "#349bff"
break;
case "并行节点":
nodeColor = "#349bff"
break;
default:
nodeColor = stateConfig[!xmlDomNodes[i].getAttribute("state")?'10I':xmlDomNodes[i].getAttribute("state")][1]
}
const nodesObj ={
"shape":"circle",
"label":xmlDomNodes[i].getAttribute("name"),
"id":xmlDomNodes[i].getAttribute("id"),
"colorState":!xmlDomNodes[i].getAttribute("state")?'10I':xmlDomNodes[i].getAttribute("state"),
"color": nodeColor,
// "color":"red"
}
arrNodes.push(nodesObj)
}
for(let i =0;i<xmlDomEdges.length;i++){
const edgesObj = {
"shape": "thisEdge",
"source": xmlDomEdges[i].getAttribute("from"),
"target": xmlDomEdges[i].getAttribute("to"),
"id": xmlDomEdges[i].getAttribute("id"),
"size": 1,
"color":"#333333"
}
arrEdges.push(edgesObj)
}
const xmlData ={
"nodes":arrNodes,
"edges":arrEdges
}
xmlData.nodes.map(function(e){
console.log(e.colorState)
if(e.colorState=="10D"){
console.log(e.id)
xmlData.edges.map(function(a){
if(e.id == a.source){
a.color =stateConfig['10I'][1]
}
})
}
})
this.loaderG6(xmlData)
},res => {
});
}
componentDidMount() {
this.loadData();
}
render(){
//this.props.flowInstance为当前选择的流程实例
return (
<div id="flowExhibitionG6" >
{this.stateColorShow()}
</div>
);
}
}
export default FlowExhibitionG6;
|
//---->>> UPDATE AVS <<<------
const avToMongo = function (av, model, clientsIO) {
var query = { title: av.title };
var update = {
'$set': {
value: av.value
}
};
// When true returns the updated document
var options = {
new: true
};
model.findOneAndUpdate(query, update, options, function(err,res) {
if (err) {
throw err;
}
//console.log(` ${query.title} updeted to value: ${av.itemValue}`)
//console.log(` mongo Responce: ${res}`)
//console.log('AV update emmit for Socket IO !!!');
clientsIO.emit('newAV');
})
};
module.exports = avToMongo;
|
describe('Test File Processor', function () {
var fileProc = require('../../../lib/io/file-processor');
var TestError = require('error-factory')('beyo.testing.TestError');
var createFiles = fileProc.createFiles;
var tmpDir;
before(function (done) {
var path = require('path');
var tmp = require('tmp');
var beyo = new BeyoMock();
tmp.setGracefulCleanup();
tmp.dir({ dir: beyo.rootPath, prefix: 'beyoTest_', unsafeCleanup: true }, function _tempDirCreated(err, tmpPath) {
if (err) throw err;
tmpDir = path.relative(beyo.rootPath, tmpPath);
done();
});
});
it('should fail when no options specified', function * () {
try {
yield createFiles();
throw TestError(this.runnable().fullTitle());
} catch (e) {
if (e instanceof TestError) {
throw e;
} else {
e.should.be.an.Error
.and.have.property('message')
.equal('No options specified');
}
}
});
it('should fail with invalid options value', function * () {
var invalidOptions = [
null, true, false, 0, 1, '', 'abc', [], /./, function () {}
];
var beyo = new BeyoMock();
for (var i = 0, iLen = invalidOptions.length; i < iLen; ++i) {
try {
yield createFiles(beyo, invalidOptions[i]);
throw TestError(this.runnable().fullTitle());
} catch (e) {
if (e instanceof TestError) {
throw e;
} else {
e.should.be.an.Error
.and.have.property('message')
.equal('Invalid options value: ' + String(invalidOptions[i]));
}
}
}
});
it('should fail with no path specified', function * () {
var beyo = new BeyoMock();
try {
yield createFiles(beyo, {});
throw TestError(this.runnable().fullTitle());
} catch (e) {
if (e instanceof TestError) {
throw e;
} else {
e.should.be.an.Error
.and.have.property('message')
.equal('Path not specified');
}
}
});
it('should fail with invalid path value', function * () {
var invalidPaths = [
undefined, null, true, false, void 0, 0, 1, {}, [], /./, function () {}
];
var beyo = new BeyoMock();
for (var i = 0, iLen = invalidPaths.length; i < iLen; ++i) {
try {
yield createFiles(beyo, { path: invalidPaths[i]});
throw TestError(this.runnable().fullTitle());
} catch (e) {
if (e instanceof TestError) {
throw e;
} else {
e.should.be.an.Error
.and.have.property('message')
.equal('Invalid path value: ' + String(invalidPaths[i]));
}
}
}
});
it('should fail with invalid resource path value', function * () {
var invalidPaths = [
undefined, null, true, false, void 0, 0, 1, {}, [], /./, function () {}
];
var beyo = new BeyoMock();
for (var i = 0, iLen = invalidPaths.length; i < iLen; ++i) {
try {
yield createFiles(beyo, { path: tmpDir, files: {}, resourcePath: invalidPaths[i]});
throw TestError(this.runnable().fullTitle());
} catch (e) {
if (e instanceof TestError) {
throw e;
} else {
e.should.be.an.Error
.and.have.property('message')
.equal('Invalid resource path value: ' + String(invalidPaths[i]));
}
}
}
});
it('should fail with no files specified', function * () {
var beyo = new BeyoMock();
try {
yield createFiles(beyo, { path: 'some/path' });
throw TestError(this.runnable().fullTitle());
} catch (e) {
if (e instanceof TestError) {
throw e;
} else {
e.should.be.an.Error
.and.have.property('message')
.equal('Files not specified');
}
}
});
it('should fail with invalid files value', function * () {
var invalidFiles = [
undefined, null, true, false, void 0, 0, 1, [], /./, function () {}, '', 'abc'
];
var beyo = new BeyoMock();
for (var i = 0, iLen = invalidFiles.length; i < iLen; ++i) {
try {
yield createFiles(beyo, { path: 'some/path', files: invalidFiles[i]});
throw TestError(this.runnable().fullTitle());
} catch (e) {
if (e instanceof TestError) {
throw e;
} else {
e.should.be.an.Error
.and.have.property('message')
.equal('Invalid files value: ' + String(invalidFiles[i]));
}
}
}
});
it('should fail with invalid tokens value', function * () {
var invalidTokens = [
undefined, null, true, false, void 0, 0, 1, [], /./, function () {}, '', 'abc'
];
var beyo = new BeyoMock();
for (var i = 0, iLen = invalidTokens.length; i < iLen; ++i) {
try {
yield createFiles(beyo, { path: 'some/path', files: {}, tokens: invalidTokens[i] });
throw TestError(this.runnable().fullTitle());
} catch (e) {
if (e instanceof TestError) {
throw e;
} else {
e.should.be.an.Error
.and.have.property('message')
.equal('Invalid tokens value: ' + String(invalidTokens[i]));
}
}
}
});
it('should create basic structure', function * () {
var path = require('path');
var beyo = new BeyoMock();
var completeEvent = false;
var content;
beyo.on('installFileComplete', function (evt) {
evt.should.have.ownProperty('file').equal('foo/bar.js');
evt.should.have.ownProperty('fileIndex').equal(0);
evt.should.have.ownProperty('files').be.an.Array.with.lengthOf(1);
evt.should.have.ownProperty('options').be.an.Object; // almost equal to the one sent to createFiles...
completeEvent = true;
});
beyo.on('installFileError', function (err, evt) {
console.error(err);
});
yield createFiles(beyo, {
path: tmpDir,
files: {
'foo/bar.js': 'module.exports = "Hello World!";'
}
});
completeEvent.should.be.true;
content = require(path.join(beyo.rootPath, tmpDir, 'foo/bar.js'));
content.should.equal('Hello World!');
});
it('should fail with file path outside base path', function * () {
var beyo = new BeyoMock();
try {
yield createFiles(beyo, {
path: tmpDir,
files: {
'foo/../../bar.txt': 'SHOULD NOT SEE THIS'
}
});
throw TestError(this.runnable().fullTitle());
} catch (e) {
if (e instanceof TestError) {
throw e;
} else {
e.should.be.an.Error
.and.have.property('message')
.equal('Invalid path: foo/../../bar.txt');
}
}
});
it('should fail streaming external file without resource path', function * () {
var beyo = new BeyoMock();
try {
yield createFiles(beyo, {
path: tmpDir,
files: {
'foo.json': '@install/test-tokens.json'
}
});
throw TestError(this.runnable().fullTitle());
} catch (e) {
if (e instanceof TestError) {
throw e;
} else {
e.should.be.an.Error
.and.have.property('message')
.equal('Resource path not specified: install/test-tokens.json');
}
}
});
it('should stream external files', function * () {
var path = require('path');
var beyo = new BeyoMock();
var originalContent;
var content;
yield createFiles(beyo, {
path: tmpDir,
resourcePath: beyo.rootPath,
files: {
'foo.json': '@install/test-tokens.json'
},
tokens: {
key: 'foobar',
key1: 1,
key2: 2,
key3: 3,
key4: 4
}
});
originalContent = beyo.require(path.join('install', 'test-tokens.json'));
content = beyo.require(path.join(tmpDir, 'foo.json'));
originalContent.should.not.eql(content);
originalContent.should.have.ownProperty('%key');
content.should.not.have.ownProperty('%key');
originalContent.should.not.have.ownProperty('foobar');
content.should.have.ownProperty('foobar');
originalContent['%key'].should.equal(content['foobar']);
originalContent['test'].should.not.equal(content['test']);
originalContent['test'].should.equal('Lorem ipsum dolor sit amet, %key1%key2 %key3-%key4 consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus %NOKEY sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosq.');
content['test'].should.equal('Lorem ipsum dolor sit amet, 12 3-4 consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus %NOKEY sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosq.');
});
it('should stream external files (no tokens)', function * () {
var path = require('path');
var beyo = new BeyoMock();
var originalContent;
var content;
beyo.on('installFileError', function (err, evt) {
console.error(err);
});
yield createFiles(beyo, {
path: tmpDir,
resourcePath: beyo.rootPath,
files: {
'foo.json': '@install/test-tokens.json'
}
});
originalContent = beyo.require(path.join('install', 'test-tokens.json'));
content = beyo.require(path.join(tmpDir, 'foo.json'));
content.should.eql(originalContent);
});
it('should emit error', function * () {
var path = require('path');
var beyo = new BeyoMock();
var errorEvent = 0;
beyo.on('installFileError', function (err, evt) {
err.should.be.an.Error;
errorEvent = errorEvent + 1;
});
beyo.on('installFileComplete', function (evt) {
console.log("** INSTALL FILE", evt);
});
yield createFiles(beyo, {
path: tmpDir,
resourcePath: beyo.rootPath,
files: {
'invalid': '@invalid/resource/path/__unknown/file',
'abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789': '@install/test-tokens.json'
}
});
errorEvent.should.be.equal(2);
});
describe('Test Token Replacement', function () {
it('should replace tokens', function * () {
var path = require('path');
var beyo = new BeyoMock();
var content;
yield createFiles(beyo, {
path: tmpDir,
files: {
'tokens/hello.json': '{ "greetings": "Hello %title %name! 100%abc" }'
},
tokens: {
title: 'Mr.',
name: 'Smith'
}
});
content = require(path.join(beyo.rootPath, tmpDir, 'tokens/hello.json'));
content.should.eql({ 'greetings': 'Hello Mr. Smith! 100%abc' });
});
});
});
|
// @flow
/* global window */
import * as React from 'react'
import RelayProvider from './RelayProvider'
import Router from 'next/router'
import createRelayEnvironment from '../lib/createRelayEnvironment'
import type { AppError } from '../lib/appError'
import type { Href } from '../lib/sitemap'
import type { IntlShape } from 'react-intl'
import { IntlProvider, addLocaleData, injectIntl } from 'react-intl'
import { fetchQuery } from 'react-relay'
import { getCookie, type Cookie } from '../lib/cookie'
import { LocaleProvider } from './Locale'
import { AppErrorProvider } from './AppError'
import { IsAuthenticatedProvider } from './IsAuthenticated'
// import { installRelayDevTools } from 'relay-devtools';
// installRelayDevTools();
// Polyfill browser stuff.
if (process.browser === true) {
// eslint-disable-next-line global-require
require('smoothscroll-polyfill').polyfill()
// Add locale data injected in pages/_document.js
Object.keys(window.ReactIntlLocaleData).forEach(lang => {
addLocaleData(window.ReactIntlLocaleData[lang])
})
}
// https://github.com/zeit/next.js#fetching-data-and-component-lifecycle
type NextContext = {
pathname: string,
query: Object,
asPath: string,
req: ?{
...http$IncomingMessage,
locale: string,
localeDataScript: string,
messages: Object,
supportedLocales: Array<string>,
},
res: ?http$ServerResponse,
jsonPageRes: Object,
err: Object,
}
type NextProps = {
url: {
pathname: string,
query: { [key: string]: ?string },
},
}
type InitialAppProps = {|
cookie: ?Cookie,
data: Object,
initialNow: number,
locale: string,
messages: Object,
records: Object,
supportedLocales: Array<string>,
|}
type AppProps = NextProps & InitialAppProps
type AppState = {|
appError: ?AppError,
|}
type Page = React.ComponentType<
{
data: Object,
intl: IntlShape,
} & NextProps,
>
export type QueryVariables<Query> = {|
isAuthenticated: boolean,
query: Query,
userId: ?string,
|}
const app = (
Page: Page,
options?: {|
query?: Object,
queryVariables?: (variables: QueryVariables<Object>) => Object,
requireAuth?: boolean,
|},
) => {
const { query, queryVariables, requireAuth } = options || {}
const PageWithHigherOrderComponents = injectIntl(Page)
class App extends React.PureComponent<AppProps, AppState> {
static redirectToSignIn = (context: NextContext) => {
const { asPath, res } = context
const redirectUrlKey = 'redirectUrl'
const redirectUrl = encodeURIComponent(asPath)
const href: Href = {
pathname: '/sign-in',
query: { [redirectUrlKey]: redirectUrl },
}
if (res) {
res.writeHead(303, {
Location: `${href.pathname}?${redirectUrlKey}=${redirectUrl}`,
})
res.end()
} else {
Router.replace(href)
}
}
static getInitialProps = async (context: NextContext) => {
const cookie = getCookie(context.req)
const isAuthenticated = !!cookie
if (requireAuth === true && !isAuthenticated) {
App.redirectToSignIn(context)
// Return nothing because component will not be rendered on redirect.
return {}
}
let data = {}
let records = {}
// Note we call fetchQuery for client page transitions as well to enable
// pending navigations. Finally possible with Next.js and Relay.
// https://writing.pupius.co.uk/beyond-pushstate-building-single-page-applications-4353246f4480
if (query) {
const environment = createRelayEnvironment(cookie && cookie.token)
const variables = queryVariables
? queryVariables({
isAuthenticated,
query: context.query,
userId: cookie && cookie.userId,
})
: {}
// It can throw "Failed to fetch" error when offline, but it should be
// solved with service workers I believe.
// It does not throw on payload errors like insufficient permissions etc.,
// because payload errors are not real errors. They are expected when the
// schema is updated and an app is not yet updated. That's why Relay
// generated Flow types are optional. Don't crash, just don't show data.
// Another mechanism should invoke app update.
data = await fetchQuery(environment, query, variables)
records = environment
.getStore()
.getSource()
.toJSON()
}
// Always update the current time on page load/transition because the
// <IntlProvider> will be a new instance even with pushState routing.
const initialNow = Date.now()
const { locale, messages, supportedLocales } =
context.req || window.__NEXT_DATA__.props
return ({
cookie,
data,
initialNow,
locale,
messages,
records,
supportedLocales,
}: InitialAppProps)
}
state = {
appError: null,
}
componentWillUnmount() {
if (this.setAppErrorToNullAfterAWhileTimeoutID)
clearTimeout(this.setAppErrorToNullAfterAWhileTimeoutID)
}
setAppErrorToNullAfterAWhileTimeoutID: ?TimeoutID
setAppErrorToNullAfterAWhile() {
const fiveSecs = 5000
if (this.setAppErrorToNullAfterAWhileTimeoutID)
clearTimeout(this.setAppErrorToNullAfterAWhileTimeoutID)
this.setAppErrorToNullAfterAWhileTimeoutID = setTimeout(() => {
this.setState({ appError: null })
}, fiveSecs)
}
dispatchAppError = (appError: AppError) => {
this.setAppErrorToNullAfterAWhile()
this.setState({ appError })
}
render() {
const {
cookie,
data,
initialNow,
locale,
messages,
records,
supportedLocales,
url,
} = this.props
const token = cookie && cookie.token
const environment = createRelayEnvironment(token, records)
const userId = cookie && cookie.userId
const isAuthenticated = !!cookie
const variables = queryVariables
? queryVariables({
isAuthenticated,
query: url.query,
userId,
})
: {}
return (
<IntlProvider
locale={locale}
messages={messages}
initialNow={initialNow}
// https://github.com/yahoo/react-intl/issues/999#issuecomment-335799491
textComponent={({ children }) => children}
>
<LocaleProvider value={{ locale, supportedLocales }}>
<RelayProvider environment={environment} variables={variables}>
<AppErrorProvider
value={{
appError: this.state.appError,
dispatchAppError: this.dispatchAppError,
}}
>
<IsAuthenticatedProvider value={{ isAuthenticated, userId }}>
<PageWithHigherOrderComponents data={data} url={url} />
</IsAuthenticatedProvider>
</AppErrorProvider>
</RelayProvider>
</LocaleProvider>
</IntlProvider>
)
}
}
return App
}
export default app
|
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
/**
* @param {TreeNode} root
* @return {number[]}
*/
var averageOfLevels = function(root) {
var q = [], result = [];
q.push({level: 0, node: root});
var count = 0, sum = 0, level = 0;
while (q.length !== 0) {
var n = q.shift();
var node = n.node;
var nlevel = n.level;
if (n.level === level) {
count++;
sum += n.node.val;
} else {
result.push(sum / count);
level = n.level;
count = 1;
sum = n.node.val;
}
if (node.left) q.push({level: nlevel+1, node: node.left});
if (node.right) q.push({level: nlevel+1, node: node.right});
}
result.push(sum / count);
return result;
};
var a = new TreeNode(3);
a.left = new TreeNode(9);
a.right = new TreeNode(20);
a.right.left = new TreeNode(15);
a.right.right = new TreeNode(7);
console.log(averageOfLevels(a));
|
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var path = require('path');
var session = require('express-session');
var bigInt = require('big-integer');
var fs = require('fs');
var Hashes = require('jshashes');
//EXTERNAL JS
eval(fs.readFileSync('./../public/proof.js').toString());
eval(fs.readFileSync('./../public/rsa.js').toString());
eval(fs.readFileSync('./../public/blind.js').toString());
var KEYSIZE = bigInt(2e128);
var keys=generateKeys(KEYSIZE);
var app = express();
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
var key = null;
app.post('/receiveKey', function(req,res){
var unsignedProofHex = bigInt(applyKeys(req.body.proof,req.body.e,req.body.n)).toString(16);
if(checkProof(unsignedProofHex,req.body.destination,req.body.origin,req.body.value)){
key = req.body.value;
res.sendStatus(200);
}
else{
res.sendStatus(400);
}
});
app.get('/sendKey', function(req,res){
var destination=req.connection.remoteAddress+":"+req.connection.remotePort;
var proof = generateProof(destination,'TTP',key);
proof = bigInt(proof,16).toString();
if(key==null){
res.sendStatus(403);
}
else{
proof = bigInt(proof);
proof = proof.modPow(keys.d,keys.n).toString();
res.send("handle({'origin':'TTP','destination':'"+destination+"','value':'"+key+"','proof':'"+proof+"','e':'"+keys.e.toString()+"','n':'"+keys.n.toString()+"'});");
}
});
var server = app.listen(8080);
console.log('TTP RUNNING ON PORT 8080');
|
/*******************************************************************
*
* File : JSFX_Mouse.js � JavaScript-FX.com
*
* Created : 2000/07/15
*
* Author : Roy Whittle (Roy@Whittle.com) www.Roy.Whittle.com
*
* Purpose : To create a cross browser "Mouse" object.
* This library will allow scripts to query the current x,y
* coordinates of the mouse.
*
* History
* Date Version Description
* 2000-06-08 2.0 Converted for javascript-fx
* 2001-08-26 2.1 Corrected a bug where IE6 was not detected.
***********************************************************************/
if(!window.JSFX)
JSFX=new Object();
if(!JSFX.Browser)
JSFX.Browser = new Object();
JSFX.Browser.mouseX = 0;
JSFX.Browser.mouseY = 0;
if(navigator.appName.indexOf("Netscape") != -1)
{
JSFX.Browser.captureMouseXY = function (evnt)
{
JSFX.Browser.mouseX=evnt.pageX;
JSFX.Browser.mouseY=evnt.pageY;
}
window.captureEvents(Event.MOUSEMOVE);
window.onmousemove = JSFX.Browser.captureMouseXY;
}
else if(document.all)
{
if(document.getElementById)
JSFX.Browser.captureMouseXY = function ()
{
JSFX.Browser.mouseX = event.x + document.body.scrollLeft;
JSFX.Browser.mouseY = event.y + document.body.scrollTop;
}
else
JSFX.Browser.captureMouseXY = function ()
{
JSFX.Browser.mouseX = event.x;
JSFX.Browser.mouseY = event.y;
}
document.onmousemove = JSFX.Browser.captureMouseXY;
}
/*** End ***/
|
const mysql = require('mysql');
const crypto = require('crypto');
const md5 = require('md5');
const db = require('../db');
// var Schema = mongoose.Schema;
// userSchema = new Schema({
// username: {
// type: String,
// required: [true, 'Username is required!'],
// unique: true
// },
// password: {
// type: String,
// required: [true, 'Password is required!']
// },
// role: {
// type: String,
// default: 'user'
// },
// remember_token: {
// type: String,
// default: null
// },
// salt: String
// }, {
// timestamps: {
// createdAt: 'created_at',
// updatedAt: 'updated_at'
// }
// });
//
// userSchema.pre('save', function(next) {
// // Handle new/update passwords
// if (!this.isModified('password')) {
// return next();
// }
// var obj = this;
// // Make salt with a callback
// this.makeSalt(function(saltErr, salt) {
// if (saltErr) {
// return next(saltErr);
// }
// obj.salt = salt;
// obj.encryptPassword(obj.password, function(encryptErr, hashedPassword){
// if (encryptErr) {
// return next(encryptErr);
// }
// obj.password = hashedPassword;
// next();
// });
// });
// });
//
// userSchema.methods = {
// /**
// * Authenticate - check if the passwords are the same
// *
// * @param {String} password
// * @param {Function} callback
// * @return {Boolean}
// * @api public
// */
// authenticate: function(password, callback) {
// if (!callback) {
// return this.password === this.encryptPassword(password);
// }
// this.encryptPassword(password, function(err, pwdGen) {
// if (err) {
// return callback(err);
// }
// if (this.password === pwdGen) {
// callback(null, true);
// } else {
// callback(null, false);
// }
// });
// },
// /**
// * Make salt
// *
// * @param {Number} byteSize Optional salt byte size, default to 16
// * @param {Function} callback
// * @return {String}
// * @api public
// */
// makeSalt: function(byteSize, callback) {
// var defaultByteSize = 16;
// if (typeof arguments[0] === 'function') {
// callback = arguments[0];
// byteSize = defaultByteSize;
// }
// else if (typeof arguments[1] === 'function') {
// callback = arguments[1];
// }
// if (!byteSize) {
// byteSize = defaultByteSize;
// }
// if (!callback) {
// return crypto.randomBytes(byteSize).toString('base64');
// }
// return crypto.randomBytes(byteSize, function(err, salt) {
// if (err) {
// callback(err);
// } else {
// callback(null, salt.toString('base64'));
// }
// });
// },
// /**
// * Encrypt password
// *
// * @param {String} password
// * @param {Function} callback
// * @return {String}
// * @api public
// */
// encryptPassword: function(password, callback) {
// if (!password || !this.salt) {
// return null;
// }
// var defaultIterations = 10000;
// var defaultKeyLength = 64;
// var salt = new Buffer(this.salt, 'base64');
// var digest = 'sha512';
// if (!callback) {
// return crypto.pbkdf2Sync(password, salt, defaultIterations, defaultKeyLength, digest)
// .toString('base64');
// }
// return crypto.pbkdf2(password, salt, defaultIterations, defaultKeyLength, digest, function(err, key){
// if (err) {
// callback(err);
// } else {
// callback(null, key.toString('base64'));
// }
// });
// }
// };
//
//
// var User = mongoose.model('user', userSchema);
//
// var exports = {};
// exports.register = function(username, password) {
// return new Promise(function(resolve, reject) {
// newUser = new User({
// username: username,
// password: password
// });
// newUser.save()
// .then(function(data) {
// if (data) {
// resolve(data);
// }else {
// reject({message: 'There was an error.'});
// }
// })
// .catch(function(err) {
// reject(err);
// });
// });
// }
//
// exports.login = function(username, password) {
// return new Promise(function(resolve, reject) {
// User.findOne({ username })
// .then(function(data) {
// if (data) {
// if (data.authenticate(password)) {
// // generate token with md5
// var timeCreateToken = Date.now()
// var md5String = crypto.createHash("md5").update(username + timeCreateToken).digest("binary");
// var token = new Buffer(md5String, 'binary').toString('base64');
// data.remember_token = token.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
//
// // then save in remember_token
// return data.save();
// }else {
// reject({ message: 'Invalid login' });
// }
// }else {
// reject({ message: 'Invalid login' });
// }
// })
// .then(function(response) {
// if (response) {
// resolve(response);
// }else {
// reject({message: 'Invalid login'});
// }
// })
// .catch(function(err) {
// reject(err);
// });
// });
// }
//
// exports.logout = function(token) {
// return new Promise(function(resolve, reject) {
// if (token) {
// User.findOneAndUpdate(
// { remember_token: token },
// { remember_token: null }
// ).then(function(user) {
// if (user) {
// resolve({ message: 'Logout success' });
// }else {
// reject({ message: 'Unauthorized user' });
// }
// })
// .catch(function(err) {
// reject(err);
// })
// }else {
// reject({ message: 'Unauthorized user' })
// }
// });
// }
//
// exports.checkAuthenticate = function(token) {
// return new Promise(function(resolve, reject) {
// if (token) {
// User.findOne({ remember_token: token })
// .then(function(user) {
// if (user) {
// resolve(user);
// }else {
// reject({ message: 'Unauthorized user' });
// }
// })
// .catch(function(err) {
// reject(err);
// })
// }else {
// reject({ message: 'Unauthorized user' })
// }
// });
// }
db.connect(function(err) {
if (err) {
throw err;
}else {
var sql = `CREATE TABLE IF NOT EXISTS user (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255),
password VARCHAR(255),
role VARCHAR(10),
remember_token VARCHAR(255)
)`;
db.get().query(sql, function(err, result) {
if (err) throw err;
});
}
});
var exports = {};
exports.login = function(username, password) {
return new Promise(function(resolve, reject) {
let queryCmd = 'SELECT * FROM user WHERE username = ' + mysql.escape(username);
db.get().query(queryCmd, function(err, user) {
if (err) {
reject(err);
}else {
if (user && user[0].password === password) {
// generate token with md5
let timeCreateToken = Date.now()
let md5String = crypto.createHash("md5").update(username + timeCreateToken).digest("binary");
let token = new Buffer(md5String, 'binary').toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
// save remember_token
let updateCmd = `UPDATE user SET remember_token = ? WHERE id = ?`;
db.get().query(updateCmd, [token, user[0].id], function(err, result) {
if (result) {
resolve({
remember_token: token,
role: user[0].role
});
}else {
reject(err);
}
});
}else {
reject({
error_code: 401,
message: 'Invalid login'
});
}
}
});
});
}
exports.logout = function(token) {
return new Promise(function(resolve, reject) {
let updateCmd = 'UPDATE user SET remember_token = ? WHERE remember_token = ?';
db.get().query(updateCmd, [null, token], function(err, result) {
if (err) {
reject(err);
}else if (result) {
resolve({message: 'Logout success'});
}else {
reject({
error_code: 401,
message: 'Unauthorized user'
});
}
})
});
}
exports.checkAuthenticate = function(token) {
return new Promise(function(resolve, reject) {
if (!token) {
reject({
error_code: 401,
message: 'Unauthorized user'
});
}else {
let queryCmd = 'SELECT * FROM user WHERE remember_token = ' + mysql.escape(token);
db.get().query(queryCmd, function(err, result) {
if (err) {
reject(err);
}else if (result) {
resolve(result[0]);
}else {
reject({
error_code: 401,
message: 'Unauthorized user'
});
}
});
}
});
}
module.exports = exports;
|
module.exports = exports = require('./lib/co_async')
|
module.exports = (to, from, next) => {
if( csApp.config.get('hasuser') == 0)
{
csApp.Noty.error('Access interzis. Trebuie să vă autentificați.')
let t = setTimeout( () => {
location.href = csApp.config.get('baseurl') + '/login'
}, 10)
}
else
{
next()
}
}
|
import ClinicalSection1 from "./components/clinical-section1";
import ClinicalBanner from "./components/clinicalBanner";
import Layout from "./layout/layout";
export default function ClinicalTrials() {
return (
<Layout>
<ClinicalBanner />
<ClinicalSection1 />
</Layout>
);
}
|
import React from 'react'
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import MovieDetails from './MovieDetails'
describe('<MovieDetails />', () => {
describe('@renders', () => {
it('in default state', () => {
const wrapper = shallow(<MovieDetails />)
expect(toJson(wrapper))
.toMatchSnapshot()
})
it('in with movies state', () => {
const props = {
movie: {
genres: ['action', 'drama'],
poster_path: 'myPath',
title: 'myTitle',
vote_average: '10'
},
director: { name: 'aDirector' },
cast: [{ name: 'name', profile_path: 'test' }]
}
const wrapper = shallow(<MovieDetails {...props}/>)
expect(toJson(wrapper))
.toMatchSnapshot()
})
})
})
|
$(document).ready(function () {
$('#menus_table').DataTable({
// "ordering": false
"order": [[0, "desc"]],
"columns": [
{ "orderDataType": "date-dd-MMM-yyyy" },
null,
null,
null,
null
]
});
console.log('loaded');
}
);
|
import React, { Component } from 'react'
export default class Nav extends Component {
constructor(){
super()
}
render(){
return(
<div className="ui tabular menu">
<div style={{padding:10}}>
<a href="/" className="item">About</a>
</div>
<div style={{padding:10}}>
<a href="/resume" className="item">Resume</a>
</div>
<div style={{padding:10}}>
<a href="/projects" className="item">Projects</a>
</div>
<div style={{padding:10}}>
<a href="/fun" className="item">For Fun</a>
</div>
</div>
)
}
}
|
var cordova = require('cordova/exec/proxy');
module.exports = {
pushNotifications: Windows.Networking.PushNotifications,
channelinstance: null,
notificatoinProcessor: null,
background: Windows.ApplicationModel.Background,
pushNotifications: Windows.Networking.PushNotifications,
notifications: Windows.UI.Notifications,
TaskName: "PushTask",
TaskEntryPoint: "js\\BackgroundPush.js",
/*
* This function will create a push channel and the channel uri will be updated based on teh implemenation of sap.PushModule.updateDeviceToken method (if provided)
* This function should not be called directly.
* Private
*/
registerForNotificationTypes: function (successCB, errorCB, processNotification) {
// backgroundTaskComplete();
sap.PushModule.background.BackgroundExecutionManager.requestAccessAsync().done(function (result) {
// Make sure the app can even receive raw notifications
if (result !== sap.PushModule.background.BackgroundAccessStatus.denied && result !== sap.PushModule.background.BackgroundAccessStatus.unspecified) {
var channelOperation = sap.PushModule.pushNotifications.PushNotificationChannelManager.createPushNotificationChannelForApplicationAsync();
//console.log(channelOperation.done);
channelOperation.done(
function complete(newChannel) {
//console.log("Registration completed");
sap.PushModule.channelinstance = newChannel;
sap.PushModule.channelinstance.addEventListener("pushnotificationreceived", sap.PushModule.pushNotificationReceivedHandler);
sap.PushModule.notificatoinProcessor = sap.Push.ProcessNotificationForUser;
if ((sap.PushModule.updateDeviceToken != undefined) && (sap.PushModule.updateDeviceToken != null) && (typeof sap.PushModule.updateDeviceToken === "function"))
{
sap.PushModule.updateDeviceToken(sap.PushModule.channelinstance.uri, successCB, errorCB);
} else {
console.log("sap.PushModule.updateDeviceToken is not defined");
}
sap.PushModule.RegisterBackgroundTask();
sap.Push.RegisterSuccess("registration success");
},
function error(msg) {
console.log("Registration error");
errorCB("Failed to register with message: " + msg);
sap.Push.RegisterFailed("Failed to register with message: " + msg);
},
function progress() {
console.log("Registration is in progress");
}
)
} else {
errorCB("Raw notification access denied");
};
})
},
/*
* This function closes any open registration channel. This will be called when unregister for notification is triggered.
* @private
*/
unregisterForNotification: function (successCB) {
// sap.PushModule.pushNotifications.PushNotificationChannelManager.closeNotificationChannel();
sap.PushModule.closeNotificationChannel(successCB, successCB);
},
/*
* This function is called when a background prush notificatieon is arrived.
* @private
*/
RegisterBackgroundTask: function () {
sap.PushModule.background.BackgroundExecutionManager.requestAccessAsync().done(function (result) {
// Make sure the app can even receive raw notifications
if (result !== sap.PushModule.background.BackgroundAccessStatus.denied && result !== sap.PushModule.background.BackgroundAccessStatus.unspecified) {
// Clean up the registered task just
sap.PushModule.unregisterBackgroundTask();
// Only open a new channel if you haven't already done so
if (!sap.PushModule.channelinstance) {
sap.PushModule.openNotificationsChannel().done(sap.PushModule.registerBackgroundTask);
} else {
sap.PushModule.registerBackgroundTask();
}
} else {
console.log && console.log("Lock screen access is denied", "sample", "status");
}
}, function (e) {
console.log && console.log("An error occurred while requesting lock screen access.", "sample", "error");
});
},
closeNotificationChannel: function (successCB, errorCB) {
if (sap.PushModule.channelinstance == null) {
errorCB("The channel is not opened or invalid");
} else {
sap.PushModule.channelinstance.close();
successCB("The registration channel closed successfully");
}
},
/*
* This is a default implementation for updating the SMP server with the registration uri recieved from the WNS notfication server.
* If the push plugin is not working with SMP server, this fuction should be custom defined.
* @public
* @param urri {string} the channel uri recieved form the the openchannel call.
* @param successCB {function} the success callback function
* @param errorCB {function} the error callback function.
*/
updateDeviceToken: function (uri, successCB, errorCB) {
sap.Settings.setConfigProperty({ "WnsChannelURI": uri, "WnsPushEnable": true },
function (m) {
successCB("Registration Successful");
},
function (mesg) {
errorCB("Failed to register channel uri with server");
});
},
/*
* @private
* This funciton process the notificaitn recieved.
*/
pushNotificationReceivedHandler: function (e) {
var notificationTypeName = "";
var notificationPayload = null;
switch (e.notificationType) {
// You can get the toast, tile, or badge notification object.
// In this example, we take the XML from the notification.
case sap.PushModule.pushNotifications.PushNotificationType.toast:
notificationTypeName = "Toast";
notificationPayload = e.toastNotification.content.getXml();
break;
case sap.PushModule.pushNotifications.PushNotificationType.tile:
notificationTypeName = "Tile";
notificationPayload = e.tileNotification.content.getXml();
break;
case sap.PushModule.pushNotifications.PushNotificationType.badge:
notificationTypeName = "Badge";
notificationPayload = e.badgeNotification.content.getXml();
var Notifications = Windows.UI.Notifications;
var badgeAttributes = e.badgeNotification.content.getElementsByTagName("badge");
var count = badgeAttributes[0].getAttribute("value");
break;
case sap.PushModule.pushNotifications.PushNotificationType.raw:
notificationTypeName = "raw";
notificationPayload = e.rawNotification.content;
}
if (notificationPayload != null) {
if (sap.PushModule.notificatoinProcessor != null) {
sap.PushModule.notificatoinProcessor(notificationPayload);
} else {
console.log("Notification process funciton is not provided");
}
}
e.cancel = true;
},
/*
* This function will be called as part of the backgroudn notification.
* @private
*/
onActivatedHandler: function (e) {
e.setPromise(WinJS.UI.processAll().then(function () {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch && e.detail.arguments !== "") {
// If there is some payload sent by the toast, go to Scenario 5
var settings = Windows.Storage.ApplicationData.current.localSettings;
settings.values["PushTask"] = e.detail.arguments;
} else {
var settings = Windows.Storage.ApplicationData.current.localSettings;
settings.values["PushTask"] = "{Payload is empty}";
}
}));
},
/*
* This function is called to registere backgroudn task
* @private
*/
registerBackgroundTask: function () {
// Register the background task for raw notifications
var taskBuilder = new sap.PushModule.background.BackgroundTaskBuilder();
var trigger = new sap.PushModule.background.PushNotificationTrigger();
taskBuilder.setTrigger(trigger);
taskBuilder.taskEntryPoint = sap.PushModule.TaskEntryPoint;
taskBuilder.name = sap.PushModule.TaskName;
try {
var task = taskBuilder.register();
//task.oncompleted = backgroundTaskComplete;
task.addEventListener("completed", sap.PushModule.backgroundTaskComplete);
console.log && console.log("Background task registered", "sample", "status");
} catch (e) {
console.log && console.log("Registration error: " + e.message, "sample", "error");
sap.PushModule.unregisterBackgroundTask();
}
},
/*
* This function unregister application frm the background task
* @private
*/
unregisterBackgroundTask: function () {
var iter = sap.PushModule.background.BackgroundTaskRegistration.allTasks.first();
while (iter.hasCurrent) {
var task = iter.current.value;
if (task.name === sap.PushModule.TaskName) {
task.unregister(true);
return true;
}
iter.moveNext();
}
return false;
},
/*
* This function reset the notification after it has recieved and processed.
* @private
*/
resetBadge: function (callback) {
var notifications = Windows.UI.Notifications;
notifications.BadgeUpdateManager.createBadgeUpdaterForApplication().clear();
notifications.TileUpdateManager.createTileUpdaterForApplication().clear();
//notifications.ToastNotificationManager.createToastUpdaterForApplication().clear();
callback("Cleared notification");
},
/*
* This function is used to get the background notification recieved afer applicatoin is started up. This funciton is not directly called. It is called bu push.js
* @private
*/
checkForNotification: function (callback) {
var settings = Windows.Storage.ApplicationData.current.localSettings;
callback(settings.values["PushTask"]);
},
/*
* This is background task complete routine. Not called directly.
* @private
*/
backgroundTaskComplete: function () {
// Retrieve state that is set when a raw notification is received
try {
// This sample assumes the payload is a string, but it can be of any type.
var settings = Windows.Storage.ApplicationData.current.localSettings;
console.log("Background task triggered by raw notification with payload = " + settings.values["PushTask"] + " has completed!", "sample", "status");
if (sap.PushModule.notificatoinProcessor != null) {
sap.PushModule.notificatoinProcessor(settings.values["PushTask"]);
} else {
console.log("Notification process funciton is not provided");
}
} catch (e) {
console.log("Error while processing background task: " + e.message, "", "error");
}
}
}
require("cordova/windows8/commandProxy").add("SMPPushPlugin", module.exports);
|
import api from '../api/index.js';
module.exports = {
taskTimer: null,
startTimer(sign = '', taskTime = 60) {
this.taskTimer = setTimeout(() => {
api.stepReport({
sign,
}, res => {
this.clearTimer();
}, err => {
this.clearTimer();
return true;
});
}, taskTime * 1000);
},
clearTimer() {
this.taskTimer && clearTimeout(this.taskTimer);
this.taskTimer = null;
},
};
|
import React from 'react'
import "./css/api.css"
import { Row, Col, CustomInput, Collapse, Button, Form, FormGroup,CardBody, Card, Input} from 'reactstrap';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import firebase from 'firebase';
import DoughnutExample from './doughnut';
import Drawer from '@material-ui/core/Drawer';
import List from '@material-ui/core/List';
import Divider from '@material-ui/core/Divider';
import {MailFolderListItems, OtherMailFolderListItems } from './tileData';
import squaduplogo from './images/squadlogowhite.png';
import Switch from '@material-ui/core/Switch';
import FormControlLabel from '@material-ui/core/FormControlLabel';
// styles for the page layout
const styles = {
root: {
flexGrow: 1,
},
flex: {
flexGrow: 1,
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
};
const loginStyles = {
width: "100%",
maxWidth: "500px",
margin: "20px auto",
borderRadius: "5%",
padding: "5%",
background: "white",
color: "black",
boxshadow: "10px 10px gray",
}
var prefString= "restaurants"
// class for preferences page that keeps track of the states of preferences, writes them to the database, and returns the preferences page
export class Preferences extends React.Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.toggle2 = this.toggle2.bind(this);
this.state= { //parameters in the nearby search request
radius: "Distance 0 - 5 mile",
restaurants: false,
bakery : false,
cafe: false,
price: "Price $",
collapse: false,
collapse2: false,
afghani: false,
african: false,
newamerican: false,
caribbean: false,
chinese: false,
japanese: false,
italian: false,
indpak: false,
korean: false,
mexian: false,
asianfusion: false,
pizza: false,
bbq: false,
vegetarian: false,
gluten_free: false,
delis: false,
diners: false,
burgers: false,
salad: false,
wraps: false,
noodles: false,
hotpot: false,
top: false,
left: false,
bottom: false,
right: false,
prefStats:{}
}
}
// side panel that is toggled on and off
toggleDrawer = (side, open) => () => {
this.setState({
[side]: open,
});
};
// toggles for extending the group pie chart and extra preferences
toggle() {
this.setState({ collapse: !this.state.collapse });
}
toggle2() {
this.setState({ collapse2: !this.state.collapse2 });
}
donotcare= event => {
if(this.props.userInGroup!=="admin"){
this.props.DisplayResults()
this.props.doneWithPref()
this.onSubmit()}
};
onSubmit(){
const currentComponent= this
var results= []
this.firebasePref()
const request = require('request');
request({
url: 'https://squad-up-gmaps.herokuapp.com/yelp/location/?groupCode='+this.props.groupCode+"&username="+this.props.userInGroup
}, function(err, res, body) {
if (err) {
console.error(err);
}else{
if(res.statusCode==400){
alert("These preferences generated no results")
}
else{
results= JSON.parse(body)
console.log(results)
currentComponent.props.doneWithPref(results)}
}
})
console.log("result is: ",results)
}
// function for if the restuarant option is checked (default is just true)
restaurantChecked(){
this.setState({
restaurants: !this.state.restaurants
})
}
// function for if bakery preference is selected, preference state changed and group chart adjusted
bakeryChecked(){
console.log(this.state.prefStats)
this.setState({
bakery: !this.state.bakery
})
if(!this.state.bakery){
prefString= prefString+", bakery"
}
else{
prefString= prefString.replace(", bakery", "")
}
console.log(prefString)
if(this.state.prefStats.hasOwnProperty('bakery')){
var count= this.state.prefStats.bakery
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.bakery){
prefStats.bakery= 1+ count}
else {
prefStats.bakery= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.bakery){
prefStats.bakery= 1}
this.setState({prefStats})
}
}
// function for if cafe preference is selected, preference state changed and group chart adjusted
cafeChecked(){
this.setState({
cafe: !this.state.cafe
})
if(!this.state.cafe){
prefString= prefString+", cafe"
}
else{
prefString= prefString.replace(", cafe", "")
}
console.log(prefString)
if(this.state.prefStats.hasOwnProperty('cafe')){
var count= this.state.prefStats.cafe
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.cafe){
prefStats.cafe= 1+ count}
else {
prefStats.cafe= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.cafe){
prefStats.cafe= 1}
this.setState({prefStats})
}
}
// function for if afghan preference is selected, preference state changed and group chart adjusted
afghanChecked(){
this.setState({
afghani: !this.state.afghani
})
if(!this.state.afghani){
prefString= prefString+", afghani"
}
else{
prefString= prefString.replace(", afghani", "")
}
if(this.state.prefStats.hasOwnProperty('afghani')){
console.log("exists")
var count= this.state.prefStats.afghani
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.afghani){
prefStats.afghani= 1+ count}
else {
console.log("subtract 1")
prefStats.afghani= count-1
}
this.setState({prefStats})
}
else{
console.log("does not exists")
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.afghani){
prefStats.afghani= 1}
this.setState({prefStats})
}
}
// function for if african preference is selected, preference state changed and group chart adjusted
africanChecked(){
this.setState({
african: !this.state.african
})
if(!this.state.african){
prefString= prefString+", african"
}
else{
prefString= prefString.replace(", african", "")
}
if(this.state.prefStats.hasOwnProperty('african')){
var count= this.state.prefStats.african
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.african){
prefStats.african= 1+ count}
else {
prefStats.african= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.african){
prefStats.african= 1}
this.setState({prefStats})
}
}
// function for if american preference is selected, preference state changed and group chart adjusted
newamericanChecked(){
this.setState({
newamerican: !this.state.newamerican
})
if(!this.state.newamerican){
prefString= prefString+", newamerican"
}
else{
prefString= prefString.replace(", newamerican", "")
}
if(this.state.prefStats.hasOwnProperty('newamerican')){
var count= this.state.prefStats.newamerican
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.newamerican){
prefStats.newamerican= 1+ count}
else {
prefStats.newamerican= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.newamerican){
prefStats.newamerican= 1}
this.setState({prefStats})
}
}
// function for if caribbean preference is selected, preference state changed and group chart adjusted
caribbeanChecked(){
this.setState({
caribbean: !this.state.caribbean
})
if(!this.state.caribbean){
prefString= prefString+", caribbean"
}
else{
prefString= prefString.replace(", caribbean", "")
}
if(this.state.prefStats.hasOwnProperty('caribbean')){
var count= this.state.prefStats.caribbean
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.caribbean){
prefStats.caribbean= 1+ count}
else {
prefStats.caribbean= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.caribbean){
prefStats.caribbean= 1}
this.setState({prefStats})
}
}
// function for if chinese preference is selected, preference state changed and group chart adjusted
chineseChecked(){
this.setState({
chinese: !this.state.chinese
})
if(!this.state.chinese){
prefString= prefString+", chinese"
}
else{
prefString= prefString.replace(", chinese", "")
}
if(this.state.prefStats.hasOwnProperty('chinese')){
var count= this.state.prefStats.chinese
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.chinese){
prefStats.chinese= 1+ count}
else {
prefStats.chinese= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.chinese){
prefStats.chinese= 1}
this.setState({prefStats})
}
}
// function for if japanese preference is selected, preference state changed and group chart adjusted
japaneseChecked(){
this.setState({
japanese: !this.state.japanese
})
if(!this.state.japanese){
prefString= prefString+", japanese"
}
else{
prefString= prefString.replace(", japanese", "")
}
if(this.state.prefStats.hasOwnProperty('japanese')){
var count= this.state.prefStats.japanese
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.japanese){
prefStats.japanese= 1+ count}
else {
prefStats.japanese= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.japanese){
prefStats.japanese= 1}
this.setState({prefStats})
}
}
// function for if italian preference is selected, preference state changed and group chart adjusted
italianChecked(){
this.setState({
italian: !this.state.italian
})
if(!this.state.italian){
prefString= prefString+", italian"
}
else{
prefString= prefString.replace(", italian", "")
}
if(this.state.prefStats.hasOwnProperty('italian')){
var count= this.state.prefStats.italian
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.italian){
prefStats.italian= 1+ count}
else {
prefStats.italian= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.italian){
prefStats.italian= 1}
this.setState({prefStats})
}
}
// function for if indian preference is selected, preference state changed and group chart adjusted
indpakChecked(){
this.setState({
indpak: !this.state.indpak
})
if(!this.state.indpak){
prefString= prefString+", indpak"
}
else{
prefString= prefString.replace(", indpak", "")
}
if(this.state.prefStats.hasOwnProperty('indpak')){
var count= this.state.prefStats.indpak
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.indpak){
prefStats.indpak= 1+ count}
else {
prefStats.indpak= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.indpak){
prefStats.indpak= 1}
this.setState({prefStats})
}
}
// function for if korean preference is selected, preference state changed and group chart adjusted
koreanChecked(){
this.setState({
korean: !this.state.korean
})
if(!this.state.korean){
prefString= prefString+", korean"
}
else{
prefString= prefString.replace(", korean", "")
}
if(this.state.prefStats.hasOwnProperty('korean')){
var count= this.state.prefStats.korean
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.korean){
prefStats.korean= 1+ count}
else {
prefStats.korean= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.korean){
prefStats.korean= 1}
this.setState({prefStats})
}
}
// function for if mexican preference is selected, preference state changed and group chart adjusted
mexicanChecked(){
this.setState({
mexican: !this.state.mexican
})
if(!this.state.mexican){
prefString= prefString+", mexican"
}
else{
prefString= prefString.replace(", mexican", "")
}
if(this.state.prefStats.hasOwnProperty('mexican')){
var count= this.state.prefStats.mexican
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.mexican){
prefStats.mexican= 1+ count}
else {
prefStats.mexican= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.mexican){
prefStats.mexican= 1}
this.setState({prefStats})
}
}
// function for if asianfusion preference is selected, preference state changed and group chart adjusted
asianfusionChecked(){
this.setState({
asianfusion: !this.state.asianfusion
})
if(!this.state.asianfusion){
prefString= prefString+", asianfusion"
}
else{
prefString= prefString.replace(", asianfusion", "")
}
if(this.state.prefStats.hasOwnProperty('asianfusion')){
var count= this.state.prefStats.asianfusion
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.asianfusion){
prefStats.asianfusion= 1+ count}
else {
prefStats.asianfusion= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.asianfusion){
prefStats.asianfusion= 1}
this.setState({prefStats})
}
}
// function for if pizza preference is selected, preference state changed and group chart adjusted
pizzaChecked(){
this.setState({
pizza: !this.state.pizza
})
if(!this.state.pizza){
prefString= prefString+", pizza"
}
else{
prefString= prefString.replace(", pizza", "")
}
if(this.state.prefStats.hasOwnProperty('pizza')){
var count= this.state.prefStats.pizza
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.pizza){
prefStats.pizza= 1+ count}
else {
prefStats.pizza= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.pizza){
prefStats.pizza= 1}
this.setState({prefStats})
}
}
// function for if bbq preference is selected, preference state changed and group chart adjusted
bbqChecked(){
this.setState({
bbq: !this.state.bbq
})
if(!this.state.bbq){
prefString= prefString+", bbq"
}
else{
prefString= prefString.replace(", bbq", "")
}
if(this.state.prefStats.hasOwnProperty('bbq')){
var count= this.state.prefStats.bbq
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.bbq){
prefStats.bbq= 1+ count}
else {
prefStats.bbq= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.bbq){
prefStats.bbq= 1}
this.setState({prefStats})
}
}
// function for if vegetarian preference is selected, preference state changed and group chart adjusted
vegetarianChecked(){
this.setState({
vegetarian: !this.state.vegetarian
})
if(!this.state.vegetarian){
prefString= prefString+", vegetarian"
}
else{
prefString= prefString.replace(", vegetarian", "")
}
if(this.state.prefStats.hasOwnProperty('vegetarian')){
var count= this.state.prefStats.vegetarian
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.vegetarian){
prefStats.vegetarian= 1+ count}
else {
prefStats.vegetarian= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.vegetarian){
prefStats.vegetarian= 1}
this.setState({prefStats})
}
}
// function for if glutenfree preference is selected, preference state changed and group chart adjusted
glutenfreeChecked(){
this.setState({
gluten_free: !this.state.gluten_free
})
if(!this.state.gluten_free){
prefString= prefString+", gluten_free"
}
else{
prefString= prefString.replace(", gluten_free", "")
}
if(this.state.prefStats.hasOwnProperty('gluten_free')){
var count= this.state.prefStats.gluten_free
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.gluten_free){
prefStats.gluten_free= 1+ count}
else {
prefStats.gluten_free= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.gluten_free){
prefStats.gluten_free= 1}
this.setState({prefStats})
}
}
// function for if delis preference is selected, preference state changed and group chart adjusted
delisChecked(){
this.setState({
delis: !this.state.delis
})
if(!this.state.delis){
prefString= prefString+", delis"
}
else{
prefString= prefString.replace(", delis", "")
}
if(this.state.prefStats.hasOwnProperty('delis')){
var count= this.state.prefStats.delis
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.delis){
prefStats.delis= 1+ count}
else {
prefStats.delis= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.delis){
prefStats.delis= 1}
this.setState({prefStats})
}
}
// function for if diners preference is selected, preference state changed and group chart adjusted
dinersChecked(){
this.setState({
diners: !this.state.diners
})
if(!this.state.diners){
prefString= prefString+", diners"
}
else{
prefString= prefString.replace(", diners", "")
}
if(this.state.prefStats.hasOwnProperty('diners')){
var count= this.state.prefStats.diners
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.diners){
prefStats.diners= 1+ count}
else {
prefStats.diners= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.diners){
prefStats.diners= 1}
this.setState({prefStats})
}
}
// function for if burgers preference is selected, preference state changed and group chart adjusted
burgersChecked(){
this.setState({
burgers: !this.state.burgers
})
if(!this.state.burgers){
prefString= prefString+", burgers"
}
else{
prefString= prefString.replace(", burgers", "")
}
if(this.state.prefStats.hasOwnProperty('burgers')){
var count= this.state.prefStats.burgers
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.burgers){
prefStats.burgers= 1+ count}
else {
prefStats.burgers= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.burgers){
prefStats.burgers= 1}
this.setState({prefStats})
}
}
// function for if salad preference is selected, preference state changed and group chart adjusted
saladChecked(){
this.setState({
salad: !this.state.salad
})
if(!this.state.salad){
prefString= prefString+", salad"
}
else{
prefString= prefString.replace(", salad", "")
}
if(this.state.prefStats.hasOwnProperty('salad')){
var count= this.state.prefStats.salad
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.salad){
prefStats.salad= 1+ count}
else {
prefStats.salad= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.salad){
prefStats.salad= 1}
this.setState({prefStats})
}
}
// function for if wraps preference is selected, preference state changed and group chart adjusted
wrapsChecked(){
this.setState({
wraps: !this.state.wraps
})
if(!this.state.wraps){
prefString= prefString+", wraps"
}
else{
prefString= prefString.replace(", wraps", "")
}
if(this.state.prefStats.hasOwnProperty('wraps')){
var count= this.state.prefStats.wraps
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.wraps){
prefStats.wraps= 1+ count}
else {
prefStats.wraps= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.wraps){
prefStats.wraps= 1}
this.setState({prefStats})
}
}
// function for if noodles preference is selected, preference state changed and group chart adjusted
noodlesChecked(){
this.setState({
noodles: !this.state.noodles
})
if(!this.state.noodles){
prefString= prefString+", noodles"
}
else{
prefString= prefString.replace(", noodles", "")
}
if(this.state.prefStats.hasOwnProperty('noodles')){
var count= this.state.prefStats.noodles
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.noodles){
prefStats.noodles= 1+ count}
else {
prefStats.noodles= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.noodles){
prefStats.noodles= 1}
this.setState({prefStats})
}
}
// function for if hotpot preference is selected, preference state changed and group chart adjusted
hotpotChecked(){
this.setState({
hotpot: !this.state.hotpot
})
if(!this.state.hotpot){
prefString= prefString+", hotpot"
}
else{
prefString= prefString.replace(", hotpot", "")
}
if(this.state.prefStats.hasOwnProperty('hotpot')){
var count= this.state.prefStats.hotpot
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.hotpot){
prefStats.hotpot= 1+ count}
else {
prefStats.hotpot= count-1
}
this.setState({prefStats})
}
else{
let prefStats= Object.assign({}, this.state.prefStats)
if(!this.state.hotpot){
prefStats.hotpot= 1}
this.setState({prefStats})
}
}
componentDidMount(){
var currentComponent = this
var ref=firebase.database().ref(this.props.groupCode)
ref.on("value",function(snapshot){
if(snapshot.hasChild("Preferences")){
var resultStats=snapshot.val().Preferences
currentComponent.setState({
prefStats: resultStats
})
}
})
}
// selections for price and radius changes
handleChangePrice(event){
this.setState({price: event.target.value})
}
handleChangeRadius(event){
this.setState({radius: event.target.value})
}
// communicating with firebase and backend
firebasePref(){
if(prefString!="restaurants"){
prefString= prefString.replace("restaurants, ","")
}
console.log(prefString)
const ResultsRef = firebase.database().ref(this.props.groupCode).child("users")
const branch = {
restaurant: this.state.restaurants,
bakery : this.state.bakery,
cafe: this.state.cafe,
price: this.state.price,
afghani: this.state.afghani,
african: this.state.african,
newamerican: this.state.newamerican,
caribbean: this.state.caribbean,
chinese: this.state.chinese,
japanese: this.state.japanese,
italian: this.state.italian,
indpak: this.state.indpak,
korean: this.state.korean,
mexian: this.state.mexian,
asianfusion: this.state.asianfusion,
pizza: this.state.pizza,
bbq: this.state.bbq,
vegetarian: this.state.vegetarian,
gluten_free: this.state.gluten_free,
delis: this.state.delis,
diners: this.state.diners,
burgers: this.state.burgers,
salad: this.state.salad,
wraps: this.state.wraps,
noodles: this.state.noodles,
hotpot: this.state.hotpot,
radius: this.state.radius,
prefString: prefString
}
ResultsRef.child(this.props.userInGroup).child("Preferences").set(branch)
const request = require('request');
request({
url: 'https://squad-up-gmaps.herokuapp.com/updatePrefs/?groupCode='+this.props.groupCode+"&username="+this.props.userInGroup
}, function(err, res, body) {
if (err) {
console.error(err);
}})
}
render(){
console.log(prefString)
const { classes } = this.props;
// side panel from tileData.js
const sideList = (
<div className={classes.list}>
<List>
<MailFolderListItems groupCode={this.props.groupCode} userInGroup={this.props.userInGroup} allUsers = {this.props.allUsers} logout={this.props.logout}/>
</List>
<Divider />
<List>
<OtherMailFolderListItems logout={this.props.logout} />
</List>
</div>
);
const fullList = (
<div className={classes.fullList}>
<List>
<MailFolderListItems logout={this.props.logout} groupCode={this.props.groupCode} userInGroup={this.props.userInGroup} allUsers = {this.props.allUsers}/>
</List>
<Divider />
<List>
<OtherMailFolderListItems logout={this.props.logout} />
</List>
</div>
);
return (
// displaying page with app bar, preference selection, and side panel
<div>
<AppBar position="static" className="tab" style={{maxHeight:"80px"}}>
<Toolbar className="tab">
<IconButton
aria-haspopup="true"
onClick={this.toggleDrawer('left', true)} className={classes.menuButton} color="inherit" aria-label="Menu">
<MenuIcon />
</IconButton>
<img src={squaduplogo} style={{width:"80%", maxWidth:"150px", margin:"5%", float:"center"}} />
</Toolbar>
</AppBar>
<Drawer open={this.state.left} onClose={this.toggleDrawer('left', false)}>
<div
tabIndex={0}
role="button"
onClick={this.toggleDrawer('left', false)}
onKeyDown={this.toggleDrawer('left', false)}
>
{sideList}
</div>
</Drawer>
<div className="App-background">
<div style={loginStyles}>
<div style={{textAlign: "center"}} className="pt-callout pt-icon-info-sign">
<h4> Select Preferences </h4>
<hr style={{marginTop: "10px", marginBottom: "10px", color: "#38abb4"}} />
{/* <React.Fragment>
<FormControlLabel
control={
<Switch
checked={this.state.color === 'blue'}
onChange={this.donotcare}
color="primary"
value="dynamic-class-name"
/>
}
label="Show me the group selection. I do not care."
/>
</React.Fragment> */}
<div>
{/*price and distance selection options*/}
<Form>
<FormGroup>
<FormGroup>
<Input type="select" name="select" id="exampleSelect" price={this.state.value} onChange={this.handleChangePrice.bind(this)}>
<option>Price $ </option>
<option>Price $$ </option>
<option>Price $$$ </option>
<option>Price $$$$ </option>
</Input>
</FormGroup>
<FormGroup>
<Input type="select" name="select" id="exampleSelect" radius={this.state.value} onChange={this.handleChangeRadius.bind(this)}>
<option>Distance 0 - 5 mile</option>
<option>Distance 0 - 10 miles</option>
<option>Distance 0 - 15 miles</option>
<option>Distance 15 + miles</option>
</Input>
</FormGroup>
</FormGroup>
</Form>
<Button color="primary" onClick={this.toggle2} style={{width: "100%", backgroundColor:"white", borderColor:"#0077B5", marginTop: "2%", color:"#0077B5"}} type="submit" className="btn btn-primary" >View Group Preferences</Button>
<Collapse isOpen={this.state.collapse2}>
<Card style={{borderColor:"white"}} >
<CardBody>
<DoughnutExample prefStats={this.state.prefStats} />
</CardBody>
</Card>
</Collapse>
<Button color="primary" onClick={this.toggle} style={{width: "100%", backgroundColor:"white", borderColor:"#0077B5", marginTop: "2%", color:"#0077B5"}} type="submit" className="btn btn-primary" >View All Filters</Button>
<Collapse isOpen={this.state.collapse}>
<Card style={{borderColor:"white"}} >
<CardBody>
<FormGroup>
<div>
<Row>
{/*types of food selection options*/}
<Col className="text-left" xs="6">
<CustomInput type="checkbox" onChange={this.afghanChecked.bind(this)} id="exampleCustomCheckbox" label="Afghan" />
<CustomInput type="checkbox" onChange={this.africanChecked.bind(this)} id="exampleCustomCheckbox2" label="African" />
<CustomInput type="checkbox" onChange={this.newamericanChecked.bind(this)} id="exampleCustomCheckbox3" label="American" />
<CustomInput type="checkbox" onChange={this.caribbeanChecked.bind(this)} id="exampleCustomCheckbox4" label="Caribbean" />
<CustomInput type="checkbox" onChange={this.chineseChecked.bind(this)} id="exampleCustomCheckbox5" label="Chinese" />
<CustomInput type="checkbox" onChange={this.japaneseChecked.bind(this)} id="exampleCustomCheckbox6" label="Japanese" />
<CustomInput type="checkbox" onChange={this.italianChecked.bind(this)} id="exampleCustomCheckbox7" label="Italian" />
<CustomInput type="checkbox" onChange={this.indpakChecked.bind(this)} id="exampleCustomCheckbox8" label="Indian" />
<CustomInput type="checkbox" onChange={this.koreanChecked.bind(this)} id="exampleCustomCheckbox9" label="Korean" />
<CustomInput type="checkbox" onChange={this.mexicanChecked.bind(this)} id="exampleCustomCheckbox10" label="Mexican" />
<CustomInput type="checkbox" onChange={this.asianfusionChecked.bind(this)} id="exampleCustomCheckbox11" label="Asian Fusion" />
<CustomInput type="checkbox" onChange={this.bakeryChecked.bind(this)} id="exampleCustomCheckbox23" label="Bakery" /> </Col>
<Col className="text-left" xs="6">
<CustomInput type="checkbox" onChange={this.pizzaChecked.bind(this)} id="exampleCustomCheckbox22" label="Pizza" />
<CustomInput type="checkbox" onChange={this.bbqChecked.bind(this)} id="exampleCustomCheckbox12" label="Barbeque" />
<CustomInput type="checkbox" onChange={this.vegetarianChecked.bind(this)} id="exampleCustomCheckbox13" label="Vegetarian" />
<CustomInput type="checkbox" onChange={this.glutenfreeChecked.bind(this)} id="exampleCustomCheckbox14" label="Gluten-Free" />
<CustomInput type="checkbox" onChange={this.delisChecked.bind(this)} id="exampleCustomCheckbox15" label="Delis" />
<CustomInput type="checkbox" onChange={this.dinersChecked.bind(this)} id="exampleCustomCheckbox16" label="Diners" />
<CustomInput type="checkbox" onChange={this.burgersChecked.bind(this)} id="exampleCustomCheckbox17" label="Burgers" />
<CustomInput type="checkbox" onChange={this.saladChecked.bind(this)} id="exampleCustomCheckbox18" label="Salad" />
<CustomInput type="checkbox" onChange={this.wrapsChecked.bind(this)} id="exampleCustomCheckbox19" label="Wraps" />
<CustomInput type="checkbox" onChange={this.noodlesChecked.bind(this)} id="exampleCustomCheckbox20" label="Noodles" />
<CustomInput type="checkbox" onChange={this.hotpotChecked.bind(this)} id="exampleCustomCheckbox21" label="Hot Pot" />
<CustomInput type="checkbox" onChange={this.cafeChecked.bind(this)} id="exampleCustomCheckbox24" label="Cafe"/></Col>
</Row>
</div>
</FormGroup>
</CardBody>
</Card>
</Collapse>
</div>
<Button style={{width: "100%", backgroundColor:"#0077B5", borderColor:"#0077B5", marginTop: "2%"}} type="submit" className="btn btn-primary" onClick= {this.onSubmit.bind(this)}>Submit</Button>
{this.props.userInGroup==="admin"?<div/>:
<section className='add-item'>
<form>
<hr style={{marginTop: "10px", marginBottom: "10px", color: "#38abb4"}} />
<h5> Or</h5>
<Button style={{width: "100%", backgroundColor:"#0077B5", borderColor:"#0077B5", marginTop: "2%"}} type="submit" className="btn btn-primary" onClick= {this.donotcare}>I'll go with the flow</Button>
</form>
</section>}
</div>
</div>
</div>
</div>
)}
}
Preferences.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(Preferences)
|
class Notification {
/**
* Constructor method om notification bars aan te kunnen maken.
* @param containerClass (String): ID of Class van het html element
* @param showTime (int): hoelang blijft een notification bar open in ms
* @constructor
*/
constructor(containerClass, showTime = 3000) {
this.container = document.querySelector(containerClass);
this.showTime = showTime;
}
/**
* Trigger de notification bar om een bericht te laten zien
* @param message (String): de tekst die moet worden weergegeven
*/
showMessage(message) {
if ( this.timeoutID ){
clearTimeout(this.timeoutID);
}
this.show();
this.container.innerHTML = message;
this.timeoutID = setTimeout(() => this.hide(), this.showTime);
}
/**
* Functie om de bar in beeld te laten komen
*/
show() {
this.container.classList.add("enabled");
}
/**
* Functie om de balk weer weg te laten gaan
*/
hide() {
this.container.classList.remove("enabled");
}
}
export default Notification;
|
function StatsCtrl($scope, $http, $routeParams) {
$scope.user = 'milan';
//$scope.param = null;
$scope.userId = $routeParams.userId;
$scope.lessons = [];
console.log('StatsCtrl', $scope.userId, $routeParams);
loadStats();
/*$scope.$on('$locationChangeSuccess', function () {
parseLocation($location.path());
console.log('$locationChangeSuccess changed!', $location.path());
if($scope.param='stat' && $scope.usr){
}
loadStats();
});
function parseLocation(location){
if(location.indexOf('/') == 0){
location = location.substring(1);
}
var lp = location.split('/');
$scope.param = lp[0];
$scope.userId = lp[1];
$scope.extra = lp[2];
}*/
function loadStats(){
$scope.loading = true;
$http({method: 'GET', url: '/stats/' + $scope.userId }).
success(function(data, status, headers, config) {
console.log(data)
$scope.lessons = {};
data.forEach(function(val, idx){
val.detail = {show: false, data:[]};
$scope.lessons[val.lesson] = val;
});
$scope.userName = $scope.user = {name : $scope.userId};
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.loading = false;
});
}
$scope.showDetail = function(lesson){
var lessonDetail = $scope.lessons[lesson].detail;
if(lessonDetail.show){
lessonDetail.show = false;
return ;
}
$http({method: 'GET', url: '/stats/' + $scope.userId + '/' + lesson }).
success(function(data, status, headers, config) {
console.log(data[0])
lessonDetail.data = parseDetailData(data[0]);
lessonDetail.show = true;
console.log(lessonDetail.data)
$scope.userName = $scope.user = {name : $scope.userId};
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
//alert(lesson);
}
function parseDetailData(data){
var details = {};
data.forEach(function(obj, idx){
var detail;
// change vs. orig
var co;
if(details[obj.link]){
detail = details[obj.link];
} else {
detail = {
link : obj.link
, change : {}
, orig : {}
};
}
// get is my change or before
if(obj.usr == $scope.userId){
co = detail.change;
} else {
co = detail.orig;
}
if(obj.word && obj.lang){
co['word'] = obj.word;
co['lang'] = obj.lang;
}
if(obj.image){
co['image'] = '/assets/img/orig/' + obj.image;
}
//if(obj.lang){
//}
if(obj.record){
co['record'] = obj.record;
}
details[obj.link] = detail;
});
return details;
}
$scope.haveChangedImage = function(detail){
//console.log('have' + detail);
if(detail.link == 1179){
console.log(detail);
}
return detail.orig.image != detail.change.image;
}
}
|
import initialState from './initialState';
import * as types from '../actions/actionTypes';
export default function subgroupReducer(state = initialState.subgroup, action){
switch (action.types){
case types.LOAD_SUBGROUPS_SUCCESS:
return action.subgroup;
default:
return state;
}
}
|
$(document).ready(function(){
$(".hello").click(function(){
$(this).toggleClass("goodbye");
});
$(".hello").draggable();
});
|
const fs = require('fs');
const glob = require('glob');
const Handlebars = require('handlebars');
// TODO make this configurable through env vars...
const BASE_URL = 'https://simonprickett.dev'
const getKeyValue = (key, arr) => {
const toFind = `${key}:`;
for (const line of arr) {
if (line.startsWith(toFind)) {
return line.substring(toFind.length).trim().split('"').join('');
}
}
};
const getExcerpt = (arr) => {
for (let n = 1; n < arr.length -2; n++) {
if (arr[n].startsWith('---')) {
return arr[n + 1];
}
}
};
const getUrlFromFileName = (fileName) => {
return `${fileName.substring(21, fileName.length - 3)}`;
};
try {
const postFileNames = glob.sync("../_posts/*.md");
const latestPostFileName = postFileNames[postFileNames.length - 1];
const latestPostData = fs.readFileSync(latestPostFileName, 'UTF-8');
const latestPostLines = latestPostData.split(/\r?\n/);
const title = getKeyValue('title', latestPostLines);
const imageUrl = `${BASE_URL}/${getKeyValue('image', latestPostLines)}`;
const excerpt = getExcerpt(latestPostLines);
const url = `${BASE_URL}/${getUrlFromFileName(latestPostFileName)}/`;
console.log(title);
console.log(imageUrl);
console.log(url);
console.log(excerpt);
// TODO get template README and update it...
} catch (err) {
console.error(err);
}
|
/**
* JavaScript에는 정수와 같은 것이 존재하지 않으므로, C 나 Java 에서 수학 계산을 한 경험이 있다면 산술할 때 약간 조심할 필요가 있습니다.
다음과 같은 경우를 주의해야 합니다:
* */
console.log(0.1 + 0.2)
// => 0.30000000000000004
// 문자열을 정수로 변환
console.log(parseInt('123', 10))
console.log(parseInt('010', 10))
// 2진수로 변환하고 싶다면
console.log(parseInt('11', 2))
// => 3
//단항 연산자 '+'를 사용하여 숫자로 변환 할 수도 있습니다.
console.log(typeof '42')
console.log(typeof +'42')
// => string, number
//문자열이 수가아닌 경우 NaN을 반환합니다.
console.log(parseInt('hello', 10))
// => NaN
// NaN은 독성을 가지고 있으므로 어떤 수학연산이 와도 NaN을 반환합니다.
console.log(NaN + 5)
// => NaN
// 값이 NaN인지 판별하는 isNaN함수를 제공합니다.
console.log(isNaN(NaN))
// => true
// 특별한값 Infinity와 -Infinity를 가지고 있습니다.
console.log(1 / 0);
console.log(-1 / 0)
// => Infinity , -Infinity
//내장 함수 isFinite를 사용하여 Infinity, -Infinity, NaN의 값을 검사 할 수 있습니다.
console.log(isFinite(1 / 0))
console.log(isFinite(-Infinity))
console.log(isFinite(Infinity))
console.log(isFinite(NaN) )
console.log(isFinite(1))
// => false, false, false, false, true
|
import React, { Component } from 'react';
import { GoogleApiWrapper } from 'google-maps-react';
import MapContainer from './MapContainer';
class MapsRenderer extends Component {
constructor(props) {
super(props);
this.state = {
list: ''
};
}
fetchStops() {
fetch("/stops/").then(res =>res.json()).then((result)=>{
this.setState({list: result})
});
}
componentWillReceiveProps(nextProps) {
//loading stops from the database
this.fetchStops();
}
callback = (marker, result) => {
this.props.callback(marker, result);
}
render() {
return (
<div>
<MapContainer google={this.props.google} stopsList={this.state.list} callback={this.callback}/>
</div>
);
}
}
export default GoogleApiWrapper({
apiKey: 'AIzaSyBWhKVQtFGxlTcrO3idYsuix-RljyDyenk',
})(MapsRenderer)
|
// function checkStorage(available, ordered) {
// // Пиши код ниже этой строки
// let message;
// if (ordered === 0) {
// message = "В заказе еще нет товаров";
// } else if (ordered > available) {
// message = "Слишком большой заказ, на складе недостаточно товаров!";
// } else {
// message = "Заказ оформлен, с вами свяжется менеджер";
// }
// return message;
// // Пиши код выше этой строки
// }
const checkStorage = function (available, ordered) {
if (ordered === 0) {
return "В заказе еще нет товаров";
}
if (ordered > available) {
return "Слишком большой заказ, на складе недостаточно товаров!";
}
return "Заказ оформлен, с вами свяжется менеджер";
};
console.log(checkStorage(100, 50));
console.log(checkStorage(100, 130));
console.log(checkStorage(70, 0));
console.log(checkStorage(200, 20));
console.log(checkStorage(200, 250));
console.log(checkStorage(150, 0));
// test5
// const fruits = ["яблоко", "слива", "груша", "апельсин"];
// const firstElement = fruits[0];
// const secondElement = fruits[1];
// const lastElement = fruits[3];
// console.log(firstElement);
// console.log(lastElement);
// test6
const fruits = ["яблоко", "персик", "груша", "банан"];
// Пиши код ниже этой строки
const lastElementIndex = fruits.length - 1;
const lastElement = fruits[lastElementIndex];
console.log(lastElement);
|
const express = require('express')
router = express.Router()
const authConfig = require('../configs/config.json')
const jwt = require('jsonwebtoken')
const { v4: uuidv4 } = require('uuid')
const dateUtil = require("../utils/date-utils")
router.get('/me', (req, res) => {
const token = jwt.sign({ id: uuidv4() }, authConfig.secret, { expiresIn: authConfig.token_expires })
res.status(200).json({
httpcode: '200',
status: 'success',
message: 'Logged with Success.',
data: token,
responsetime: dateUtil.LocalDateTime()
})
})
module.exports = router
|
/*global doSweep */
$(document).ready(function() {
"use strict";
var arr = [13, 30, 12, 54, 55, 11, 78, 14, 20, 79, 44, 98];
doSweep("shellsortCON5", arr, 4);
});
|
var dir_1400e81283d4b1101690b94762852a2d =
[
[ "MiniJSON", "dir_1afc8a4af5e72a4e4d000db98e51f84a.html", "dir_1afc8a4af5e72a4e4d000db98e51f84a" ],
[ "ArrayPrefs2.js", "_array_prefs2_8js.html", null ],
[ "AtlasManager.cs", "_atlas_manager_8cs.html", [
[ "AtlasManager", "class_atlas_manager.html", "class_atlas_manager" ]
] ],
[ "ColliderSleeper.cs", "_collider_sleeper_8cs.html", [
[ "ColliderSleeper", "class_collider_sleeper.html", "class_collider_sleeper" ]
] ],
[ "DebugKeyLogger.cs", "_debug_key_logger_8cs.html", [
[ "DebugKeyLogger", "class_debug_key_logger.html", "class_debug_key_logger" ]
] ],
[ "HSBColor.cs", "_h_s_b_color_8cs.html", [
[ "HSBColor", "struct_h_s_b_color.html", "struct_h_s_b_color" ]
] ],
[ "MikkeoUtils.cs", "_mikkeo_utils_8cs.html", null ],
[ "MonoSingleton.cs", "_mono_singleton_8cs.html", [
[ "MonoSingleton", "class_mono_singleton.html", "class_mono_singleton" ]
] ],
[ "ObjectPool.cs", "_object_pool_8cs.html", [
[ "ObjectPool", "class_object_pool.html", "class_object_pool" ],
[ "StartupPool", "class_object_pool_1_1_startup_pool.html", "class_object_pool_1_1_startup_pool" ]
] ],
[ "PlayerPrefs.cs", "_player_prefs_8cs.html", null ],
[ "SelectionBaseObject.cs", "_selection_base_object_8cs.html", [
[ "SelectionBaseObject", "class_selection_base_object.html", null ]
] ],
[ "SetTextureFromURL.cs", "_set_texture_from_u_r_l_8cs.html", [
[ "SetTextureFromURL", "class_set_texture_from_u_r_l.html", "class_set_texture_from_u_r_l" ]
] ],
[ "Singleton.cs", "_singleton_8cs.html", [
[ "PrefabAttribute", "class_prefab_attribute.html", "class_prefab_attribute" ],
[ "Singleton", "class_singleton.html", "class_singleton" ]
] ],
[ "SphereCreator.cs", "_sphere_creator_8cs.html", [
[ "SphereCreator", "class_sphere_creator.html", "class_sphere_creator" ]
] ]
];
|
var trank = angular.module("trankApp");
trank.controller("MenuController", function ($rootScope, $timeout, $scope, lugaresApi, $location) {
$scope.categorias = lugaresApi.listarCategorias();
$scope.usuario = false;
$rootScope.num = 0;
$scope.busca_termo = "";
(function init() {
initMenu(lugaresApi.autoComplete());
})();
$rootScope.$watch('usuario', function( u ){
$scope.usuario = u;
});
$scope.sair = function()
{
$rootScope.usuario = false;
$scope.usuario = false;
}
$scope.login = function(){
if (!$scope.usuario){
$location.search('next',$location.path());
$location.path('/entrar');
}
}
$scope.buscaSubmit = function (){
$location.search('termo',$scope.busca_termo);
$location.path("/busca/");
}
$rootScope.trocaBkg = function (){
$rootScope.num = Math.floor(Math.random()*4) + 1;
$('body').css("background-image",'url("media/bkg_'+($rootScope.num+1)+'.jpg")');
}
});
function initMenu(autoComplete){
$( "#search" ).autocomplete({
source: autoComplete
});
}
|
import { SliderBox } from "./dist/SliderBox";
export { SliderBox };
|
const express = require('express');
const app = express();
const server = require('./server/server');
const config = require('config');
server({
app,
port: config.get('server')
});
|
$(() => {
const sendMsg = (payload, clb) => {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.tabs.sendMessage(tabs[0].id, payload, response => {
if (clb) {
clb(response);
}
});
});
};
$("#expand-thangs-btn").on("click", () => {
sendMsg({ action: "expandComments" });
});
setTimeout(() => {
sendMsg({ action: "getPendingIssues" }, data => {
$('#issues-container').html('');
if (!data) {
$('#issues-container').append(`<div class="issues-container-inner">Something went borken.</div>`);
return;
}
if (data.length === 0) {
$('#issues-container').append(`<div class="issues-container-inner">I couldn't find nothing, yo.</div>`);
return;
}
data.forEach(item => {
const $html = $(`<a class="issue issues-container-inner" data-id="${item.elemId}"></a>`);
$html.append($.parseHTML(item.comment));
$('#issues-container').append($html);
});
});
}, 500);
$("#issues-container").on("click", "a.issue", ev => {
const commentId = $(ev.currentTarget).attr("data-id");
sendMsg({ action: "gotoComment", commentId });
});
});
|
import { StyleSheet } from 'react-native';
import variables, { scale } from '../../../styles/variables';
import {
WHITE_COLOR,
ORANGE,
} from '../../../styles/constants';
const {large} = variables.fontSize;
export const styles = StyleSheet.create({
container: {
width: '100%',
height: scale(50),
backgroundColor: ORANGE,
paddingHorizontal: scale(15),
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
},
text: {
fontSize: large,
color: WHITE_COLOR
}
});
|
'use strict';
const AWS = require('aws-sdk');
var rp = require('request-promise');
var config = require('./config');
module.exports.handler = (event, context, callback) => {
const s3 = new AWS.S3();
const sqs = new AWS.SQS();
event.Records.forEach(record => {
const params = { Bucket: record.s3.bucket.name, Key: record.s3.object.key };
var response = {};
s3.getObject(params, (err, data) => {
rp.post({
url: config.uploadEndpoint,
formData: { file: data.Body },
headers: { apikey: config.apikey, filename: params.Key }
})
.then((data) => {
response.statusCode = 200;
const ctx = context.invokedFunctionArn.split(':');
const queueUrl = `https://sqs.${ctx[3]}.amazonaws.com/${+ctx[4]}/${process.env.sqs}`;
const dataId = JSON.parse(data).data_id;
console.log(dataId)
return sqs.sendMessage({ QueueUrl: queueUrl, MessageBody: dataId }).promise();
})
.catch((e) => {
response = {
statusCode: 404,
body: e,
};
console.log(e);
})
.finally(() => callback(null, response));
});
});
};
|
export const CHANNEL = 'channel';
export const CHANNEL_WAS_SUCCESSFULLY_CREATED = 'Channel was successfully created!';
export const CHANNEL_WAS_SUCCESSFULLY_DELETED = 'Channel was successfully deleted!';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.