text
stringlengths 7
3.69M
|
|---|
const config = require('../../project.config')
const proPlayers = require('../data/pro-players.json')
const heroes = require('../data/heroes.json')
export function mapAccountToPlayer(playerObject) {
const heroData = heroes.heroes.find(hero => hero.id === playerObject.hero_id)
const heroName = heroData ? heroData.name.replace('npc_dota_hero_', '') : ''
return Object.assign(
playerObject,
proPlayers.find(player => player.account_id === playerObject.account_id),
{
hero_name: heroName,
hero_image: heroData ? `${config.dotaImageCdn}/heroes/${heroName}_sb.png` : '/images/heroes/unknown-hero.jpeg',
hero_id: playerObject.hero_id
}
)
}
export function matchToPlayers(match) {
if (!match || !match.players) {
return match
}
match.players.map(player => mapAccountToPlayer(player))
return match
}
export function getKnownPlayers(players) {
if (!players) {
return []
}
return players.filter(player => player.is_pro || (player.stream && player.stream.id))
}
export function gameTime(time: number) {
const minutes = Math.floor(time / 60)
const seconds = time - (minutes * 60)
const formattedSeconds = seconds < 10 ? `0${seconds}` : seconds
const formattedMinutes = minutes < 10 && minutes >= 0 ? `0${minutes}` : minutes
return `${formattedMinutes}:${formattedSeconds}`
}
|
import React from 'react';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import {Typography} from '@material-ui/core';
import AddIcon from '@material-ui/icons/Add';
import IconButton from '@material-ui/core/IconButton';
import Chip from '@material-ui/core/Chip';
import Grid from '@material-ui/core/Grid';
const listStyle = {
overflow: 'auto',
//float: 'left',
height: '90vh',
}
class DynamicForm extends React.Component {
constructor(props) {
super(props);
}
getChips() {
let chips = [];
for (let i = 0; i < this.props.value.length; i++) {
chips.push(
<Chip
key={i}
label={this.props.value[i]}
onDelete={() => this.props.onRemove(i, this.props.name)}
color="primary"
variant="outlined"
/>
)
}
return chips;
}
render() {
return (
<div className="DynamicForm">
<div style={{ display: 'inline-flex' }}>
<TextField
id="outlined-name"
label={this.props.label}
name={this.props.name + "Field"}
value={this.props.fieldValue}
onChange={this.props.onChange}
margin="normal"
variant="outlined"
style={{marginLeft: '2vw', display: 'inline-block'}}
/>
</div>
<div style={{ display: 'inline-flex' }}>
<Button
variant="contained"
color="primary"
name={this.props.name}
onClick={this.props.onAdd}
size='small'
style={{display: 'inline-block'}}
>
<AddIcon/>
</Button>
</div >
<div style={{ display: 'inline-flex', alignSelf: 'right', overflow: 'auto', maxWidth:'85vh', marginLeft:'5vh'}}>
<Grid justify="right">
<Grid item>
{this.getChips()}
</Grid>
</Grid>
</div>
</div>
)
}
}
export default (DynamicForm);
|
const templateCreateCells = require('../createCells.pug');
const eventEmitter = require('events');
class View extends eventEmitter {
constructor() {
super();
this._startButtonBind();
this._pauseButtonBind();
this._changeCellStateBind();
this._unfocusInputsBind();
}
drawField(modelFieldHeight, modelFieldWidth, cells) {
const $gameField = $('.js-game-field');
const locals = {
fieldHeight: modelFieldHeight,
fieldWidth: modelFieldWidth,
cellsStates: cells,
};
$gameField.html(templateCreateCells(locals));
return $gameField.html();
}
_changeCellStateBind() {
$('.js-game-field').on('click', 'td', (event) => {
$(event.currentTarget).toggleClass('alive dead');
const cellPosition = $(event.currentTarget).attr('data-position');
this.emit('changeCell', cellPosition);
});
return this;
}
_unfocusInputsBind() {
const $heightInput = $('.js-control__height');
$heightInput.focusout(() => {
const newFieldHeight = $heightInput.val();
if (View.isPositiveNumber(newFieldHeight)) {
this.emit('changeFieldHeight', newFieldHeight);
}
});
const $widthInput = $('.js-control__width');
$widthInput.focusout(() => {
const newFieldWidth = $widthInput.val();
if (View.isPositiveNumber(newFieldWidth)) {
this.emit('changeFieldWidth', newFieldWidth);
}
});
return this;
}
_startButtonBind() {
$('.js-start-button').click((event) => {
$(event.currentTarget).attr('disabled', 'true');
const $pauseButton = $('.js-pause-button');
$pauseButton.removeAttr('disabled');
this.emit('startGame');
});
return this;
}
_pauseButtonBind() {
$('.js-pause-button').click((event) => {
$(event.currentTarget).attr('disabled', 'true');
const $startButton = $('.js-start-button');
$startButton.removeAttr('disabled');
this.emit('pauseGame');
});
return this;
}
static isPositiveNumber(num) {
return (!isNaN(num) && num > 0);
}
}
export default View;
|
const MegaClient = require("simple-discord");
module.exports = new MegaClient.Comando({
nombre: "dragono",
alias: ["dragono"],
descripcion: "Easter-egg2",
cooldown: 3,
permiso_cooldown: "ADMINISTRATOR",
ejecutar: (client, message, args) => {
if(client.comandos.size <= 0) return message.channel.send("No hay comandos") //de todos modos por si ocurre algo.
message.channel.send("Pinche otako qliao, dúchate >:(, es broma, mejor ya mando a Dasod a que te vaya a mamar la verga :/")
}
})
|
import { connect } from 'react-redux';
import Profile from './profile';
import { fetchSummoner } from '../../actions/summoner_actions';
import { fetchMatches } from '../../actions/match_actions';
import { summonerSoloQueue, summonerQueues } from '../../reducers/selectors';
const mapStateToProps = (state, {params}) => {
let queues = {
soloQueue: state.summoner.solo_5x5,
flexSr: state.summoner.flex_sr,
teamFive: state.summoner.team_5x5,
teamThree: state.summoner.team_3x3
};
return {
summoner: state.summoner,
matches: state.matches,
queues
};};
const mapDispatchToProps = dispatch => ({
fetchSummoner: summoner => dispatch(fetchSummoner(summoner)),
fetchMatches: (name, offset, limit) =>
dispatch(fetchMatches(name, offset, limit))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Profile);
|
import React from 'react';
import ShowUserNames from './showusernames'
import ChatBox from './chatbox'
import ShowMessages from './showmessages'
import {connect} from 'react-redux'
class Messages extends React.Component {
state={
otherUser : null,
messageBox:null,
messages:[]
}
showUserNames = () => {
return this.props.allusers.map(user => <ShowUserNames
user={user}
userToChatWith={this.userToChatWith}
/>)
}
userToChatWith = (otherUser) => {
this.setState({otherUser})
let abc;
let messageContainer;
abc = [this.props.currentUser.username,otherUser.username,this.props.currentUser.id,otherUser.id].sort().join()
fetch("https://handy-dandy-app.herokuapp.com/messages",{
headers:{
'Authorization': `${localStorage.token}`
}
}).then(res => res.json())
.then(messageBoxes => {
messageContainer = messageBoxes.filter(messageBox => messageBox.name === abc )
if(messageContainer.length === 0){
fetch("https://handy-dandy-app.herokuapp.com/messages",{
method: 'POST',
headers:{
'Content-Type':'application/json',
'Accept':'application/json',
'Authorization': `${localStorage.token}`
},
body: JSON.stringify({
name: abc
})
}).then(res=> res.json())
.then(messageBox => {
this.setState({messageBox})
}
)
}
else(
this.setState({messageBox:messageContainer[0]}))
})
}
abc = () => {
fetch(`https://handy-dandy-app.herokuapp.com/user_messages/${this.state.messageBox.id}`,{
headers: {
"Authorization":`${localStorage.token}`
}
})
.then(res => res.json())
.then(messages=>this.setState({messages}))
}
render() {
return (
<div >
<div className="messagePeopleName">
please click on any user you want to chat with
<h2>{this.showUserNames()}</h2>
</div>
<div className="chatroom" >
{this.state.messageBox?
<div><div className="chattingWithUserMsg">You are chatting with: {this.state.otherUser.first_name}</div>
<ShowMessages
messageBox={this.state.messageBox}
messages={this.state.messages}/></div>
:
null
}
</div>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
allusers: state.allUsers,
currentUser: state.currentUser
}
}
export default connect(mapStateToProps)(Messages);
|
export default class IdentityTransmutter {
construct(source, property, response) {
// if (response !== undefined) {
// throw new Error('IdentityTransmutter must be the first middleware to be executed');
// }
return Reflect.get(source, property);
}
// instance(source, args, response) {
// proxy[property] = Reflect.construct(source, args);
// }
get(source, property, response) {
return Reflect.get(source, property);
}
}
|
process.env.NODE_ENV = 'test';
let mongoose = require("mongoose");
let models = require('../models/models');
let Menu = models.Menu;
let chai = require('chai');
let chaiHttp = require('chai-http');
let app = require('../app');
let should = chai.should();
chai.use(chaiHttp);
describe('Menu', () => {
beforeEach((done) => {
Menu.remove({}, (err) => {
done();
});
});
describe('/GET menu', () => {
it('it should GET all the menus', (done) => {
chai.request(app)
.get('/menu')
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('array');
res.body.length.should.be.eql(0);
done();
});
});
});
describe('/POST menu', () => {
it('it should Create a new menu', (done) => {
let menu = {
rest: '2'
}
chai.request(app).post('/menu')
.send(menu)
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('content').eql(menu.content);
done();
});
});
});
});
|
/*eslint-env browser */
var startTime, timeOut,
SPACE_CODE = 32,
E_CODE = 101,
THOUSAND = 1000;
let circle,
times,
result,
arrayOfTimes = [];
function init(){
let startButton = document.querySelector(".button");
startButton.addEventListener("click", startExperiment);
document.addEventListener("keypress", onKeyPressed);
result = document.getElementById("results");
times = document.getElementById("times");
}
function startExperiment(){
resetTest();
timeOut = setTimeout(changeColor, getRandomTime());
}
function getRandomTime(){
var min = 3,
max = 10,
rand = Math.floor(Math.random() * (max - min + 1) + min);
return rand * THOUSAND;
}
function changeColor(){
circle = document.getElementById("circle");
circle.style.background = "orange";
startTime = new Date();
}
function onKeyPressed(e){
var neededTime;
if(e.keyCode === SPACE_CODE){
let endtime = new Date();
neededTime = endtime - startTime;
arrayOfTimes.push(neededTime);
result.classList.remove("hidden");
result.innerHTML = neededTime + "ms";
resetBackground();
timeOut = setTimeout(changeColor, getRandomTime());
}
if(e.keyCode === E_CODE){
result.innerHTML = "Mittelwert: " + countMean() + "ms";
resetBackground();
clearTimeout(timeOut);
showResults();
}
}
function countMean(){
var i, mean = 0;
for(i = 0; i < arrayOfTimes.length; i++){
mean += parseInt(arrayOfTimes[i], 10);
}
mean /= arrayOfTimes.length;
return mean;
}
function resetTest(){
arrayOfTimes = [];
times.innerHTML = "";
result.classList.add("hidden");
}
function resetBackground(){
circle.style.background = "#0D5047";
}
function showResults(){
let finalTimes = "", i;
for (i = 0; i < arrayOfTimes.length; i++){
if(i === arrayOfTimes.length - 1){
finalTimes += arrayOfTimes[i] + "ms";
}else{
finalTimes += arrayOfTimes[i] + "ms, ";}
}
times.innerHTML = "gemessene Zeiten: " + finalTimes;
saveToCsv();
arrayOfTimes = [];
}
function saveToCsv(){
var encodedUri, link;
let csvContent = "data:text/csv;charset=utf-8,milli seconds\n";
arrayOfTimes.forEach(function (infoArray) {
let row = infoArray + ",";
csvContent += row + "\r\n";
});
encodedUri = encodeURI(csvContent);
link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "results.csv");
document.body.appendChild(link);
link.click();
}
init();
|
let option=document.getElementById("options");
let closed=document.getElementById("close");
option.addEventListener("click",(e)=>{
let el=document.getElementById("active");
let el2=document.getElementById("activelg")
el.classList.toggle("hidden");
el2.classList.toggle("lg:hidden");
})
closed.addEventListener("click",(e)=>{
let el=document.getElementById("active");
el.classList.toggle("hidden");
})
|
const { Router } = require('express')
const {createUser} = require('../../controllers/users')
const route = Router()
route.post('/', async (req ,res) => {
try {
const user = await createUser(
req.body.user.username,
req.body.user.email,
req.body.user.password
)
res.status(201).send({user})
} catch (e) {
res.status(500).json({
message: e.message
})
}
})
route.post('/login', (req ,res) => {
// TODO
})
module.exports = route
|
/**
* Followers Widget
*/
import React, { Component } from 'react';
import { Card, CardBody } from 'reactstrap';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import Button from '@material-ui/core/Button';
// intl messages
import IntlMessages from 'Util/IntlMessages';
export default class FollowersWidget extends Component {
render() {
return (
<Card className="rct-block">
<CardBody className="pb-0 d-flex justify-content-between">
<h4 className="mb-5"><IntlMessages id="components.followers" /></h4>
<p className="fs-14 mb-0"><IntlMessages id="components.trending" />: 29% <i className="ti-arrow-up text-success ml-1"></i></p>
</CardBody>
<List className="p-0">
<ListItem className="d-flex justify-content-between border-bottom py-5 fs-14 px-20">
<span><IntlMessages id="widgets.lastWeek" /></span>
<span>5400</span>
<span><i className="ti-arrow-up text-success mr-5"></i>20%</span>
</ListItem>
<ListItem className="d-flex justify-content-between border-bottom py-5 fs-14 px-20">
<span><IntlMessages id="widgets.thisWeek" /></span>
<span>2400</span>
<span><i className="ti-arrow-down text-danger mr-5"></i>-5%</span>
</ListItem>
</List>
<div className="px-20 py-10 d-flex justify-content-end">
<Button className="btn-xs" variant="raised" size="small" className="text-white" color="primary">
<IntlMessages id="button.seeInsights" />
</Button>
</div>
</Card>
);
}
}
|
/*
* ext-connector.js
*
* Licensed under the Apache License, Version 2
*
* Copyright(c) 2010 Alexis Deveria
*
*/
methodDraw.addExtension("Connector", function(S) {
var svgcontent = S.svgcontent,
svgroot = S.svgroot,
getNextId = S.getNextId,
getElem = S.getElem,
addElem = S.addSvgElementFromJson,
selManager = S.selectorManager,
curConfig = methodDraw.curConfig,
started = false,
start_x,
start_y,
cur_line,
start_elem,
end_elem,
connections = [],
conn_sel = ".se_connector",
se_ns,
// connect_str = "-SE_CONNECT-",
selElems = [];
elData = $.data;
var lang_list = {
"en":[
{"id": "mode_connect", "title": "Connect two objects" }
],
"fr":[
{"id": "mode_connect", "title": "Connecter deux objets"}
]
};
function getOffset(side, line) {
var give_offset = !!line.getAttribute('marker-' + side);
// var give_offset = $(line).data(side+'_off');
// TODO: Make this number (5) be based on marker width/height
var size = line.getAttribute('stroke-width') * 5;
return give_offset ? size : 0;
}
function showPanel(on) {
var conn_rules = $('#connector_rules');
if(!conn_rules.length) {
conn_rules = $('<style id="connector_rules"><\/style>').appendTo('head');
}
conn_rules.text(!on?"":"#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }");
$('#connector_panel').toggle(on);
}
function setPoint(elem, pos, x, y, setMid) {
var pts = elem.points;
var pt = svgroot.createSVGPoint();
pt.x = x;
pt.y = y;
if(pos === 'end') pos = pts.numberOfItems-1;
// TODO: Test for this on init, then use alt only if needed
try {
pts.replaceItem(pt, pos);
} catch(err) {
// Should only occur in FF which formats points attr as "n,n n,n", so just split
var pt_arr = elem.getAttribute("points").split(" ");
for(var i=0; i< pt_arr.length; i++) {
if(i == pos) {
pt_arr[i] = x + ',' + y;
}
}
elem.setAttribute("points",pt_arr.join(" "));
}
if(setMid) {
// Add center point
var pt_start = pts.getItem(0);
var pt_end = pts.getItem(pts.numberOfItems-1);
setPoint(elem, 1, (pt_end.x + pt_start.x)/2, (pt_end.y + pt_start.y)/2);
}
}
function updateLine(diff_x, diff_y) {
// Update line with element
var i = connections.length;
while(i--) {
var conn = connections[i];
var line = conn.connector;
var elem = conn.elem;
var pre = conn.is_start?'start':'end';
// var sw = line.getAttribute('stroke-width') * 5;
// Update bbox for this element
var bb = elData(line, pre+'_bb');
bb.x = conn.start_x + diff_x;
bb.y = conn.start_y + diff_y;
elData(line, pre+'_bb', bb);
var alt_pre = conn.is_start?'end':'start';
// Get center pt of connected element
var bb2 = elData(line, alt_pre+'_bb');
var src_x = bb2.x + bb2.width/2;
var src_y = bb2.y + bb2.height/2;
// Set point of element being moved
var pt = getBBintersect(src_x, src_y, bb, getOffset(pre, line)); // $(line).data(pre+'_off')?sw:0
setPoint(line, conn.is_start?0:'end', pt.x, pt.y, true);
// Set point of connected element
var pt2 = getBBintersect(pt.x, pt.y, elData(line, alt_pre + '_bb'), getOffset(alt_pre, line));
setPoint(line, conn.is_start?'end':0, pt2.x, pt2.y, true);
}
}
function findConnectors(elems) {
if(!elems) elems = selElems;
var connectors = $(svgcontent).find(conn_sel);
connections = [];
// Loop through connectors to see if one is connected to the element
connectors.each(function() {
var start = elData(this, "c_start");
var end = elData(this, "c_end");
var parts = [getElem(start), getElem(end)];
for(var i=0; i<2; i++) {
var c_elem = parts[i];
var add_this = false;
// The connected element might be part of a selected group
$(c_elem).parents().each(function() {
if($.inArray(this, elems) !== -1) {
// Pretend this element is selected
add_this = true;
}
});
if(!c_elem || !c_elem.parentNode) {
$(this).remove();
continue;
}
if($.inArray(c_elem, elems) !== -1 || add_this) {
var bb = svgCanvas.getStrokedBBox([c_elem]);
connections.push({
elem: c_elem,
connector: this,
is_start: (i === 0),
start_x: bb.x,
start_y: bb.y
});
}
}
});
}
function updateConnectors(elems) {
// Updates connector lines based on selected elements
// Is not used on mousemove, as it runs getStrokedBBox every time,
// which isn't necessary there.
findConnectors(elems);
if(connections.length) {
// Update line with element
var i = connections.length;
while(i--) {
var conn = connections[i];
var line = conn.connector;
var elem = conn.elem;
var sw = line.getAttribute('stroke-width') * 5;
var pre = conn.is_start?'start':'end';
// Update bbox for this element
var bb = svgCanvas.getStrokedBBox([elem]);
bb.x = conn.start_x;
bb.y = conn.start_y;
elData(line, pre+'_bb', bb);
var add_offset = elData(line, pre+'_off');
var alt_pre = conn.is_start?'end':'start';
// Get center pt of connected element
var bb2 = elData(line, alt_pre+'_bb');
var src_x = bb2.x + bb2.width/2;
var src_y = bb2.y + bb2.height/2;
// Set point of element being moved
var pt = getBBintersect(src_x, src_y, bb, getOffset(pre, line));
setPoint(line, conn.is_start?0:'end', pt.x, pt.y, true);
// Set point of connected element
var pt2 = getBBintersect(pt.x, pt.y, elData(line, alt_pre + '_bb'), getOffset(alt_pre, line));
setPoint(line, conn.is_start?'end':0, pt2.x, pt2.y, true);
// Update points attribute manually for webkit
if(navigator.userAgent.indexOf('AppleWebKit') != -1) {
var pts = line.points;
var len = pts.numberOfItems;
var pt_arr = Array(len);
for(var j=0; j< len; j++) {
var pt = pts.getItem(j);
pt_arr[j] = pt.x + ',' + pt.y;
}
line.setAttribute("points",pt_arr.join(" "));
}
}
}
}
function getBBintersect(x, y, bb, offset) {
if(offset) {
offset -= 0;
bb = $.extend({}, bb);
bb.width += offset;
bb.height += offset;
bb.x -= offset/2;
bb.y -= offset/2;
}
var mid_x = bb.x + bb.width/2;
var mid_y = bb.y + bb.height/2;
var len_x = x - mid_x;
var len_y = y - mid_y;
var slope = Math.abs(len_y/len_x);
var ratio;
if(slope < bb.height/bb.width) {
ratio = (bb.width/2) / Math.abs(len_x);
} else {
ratio = (bb.height/2) / Math.abs(len_y);
}
return {
x: mid_x + len_x * ratio,
y: mid_y + len_y * ratio
}
}
// Do once
(function() {
var gse = svgCanvas.groupSelectedElements;
svgCanvas.groupSelectedElements = function() {
svgCanvas.removeFromSelection($(conn_sel).toArray());
return gse.apply(this, arguments);
}
var mse = svgCanvas.moveSelectedElements;
svgCanvas.moveSelectedElements = function() {
svgCanvas.removeFromSelection($(conn_sel).toArray());
var cmd = mse.apply(this, arguments);
updateConnectors();
return cmd;
}
se_ns = svgCanvas.getEditorNS();
}());
// Do on reset
function init() {
// Make sure all connectors have data set
$(svgcontent).find('*').each(function() {
var conn = this.getAttributeNS(se_ns, "connector");
if(conn) {
this.setAttribute('class', conn_sel.substr(1));
var conn_data = conn.split(' ');
var sbb = svgCanvas.getStrokedBBox([getElem(conn_data[0])]);
var ebb = svgCanvas.getStrokedBBox([getElem(conn_data[1])]);
$(this).data('c_start',conn_data[0])
.data('c_end',conn_data[1])
.data('start_bb', sbb)
.data('end_bb', ebb);
svgCanvas.getEditorNS(true);
}
});
// updateConnectors();
}
// $(svgroot).parent().mousemove(function(e) {
// // if(started
// // || svgCanvas.getMode() != "connector"
// // || e.target.parentNode.parentNode != svgcontent) return;
//
// console.log('y')
// // if(e.target.parentNode.parentNode === svgcontent) {
// //
// // }
// });
return {
name: "Connector",
svgicons: "images/conn.svg",
buttons: [{
id: "mode_connect",
type: "mode",
icon: "images/cut.png",
title: "Connect two objects",
includeWith: {
button: '#tool_line',
isDefault: false,
position: 1
},
events: {
'click': function() {
svgCanvas.setMode("connector");
}
}
}],
addLangData: function(lang) {
return {
data: lang_list[lang]
};
},
mouseDown: function(opts) {
var e = opts.event;
start_x = opts.start_x,
start_y = opts.start_y;
var mode = svgCanvas.getMode();
if(mode == "connector") {
if(started) return;
var mouse_target = e.target;
var parents = $(mouse_target).parents();
if($.inArray(svgcontent, parents) != -1) {
// Connectable element
// If child of foreignObject, use parent
var fo = $(mouse_target).closest("foreignObject");
start_elem = fo.length ? fo[0] : mouse_target;
// Get center of source element
var bb = svgCanvas.getStrokedBBox([start_elem]);
var x = bb.x + bb.width/2;
var y = bb.y + bb.height/2;
started = true;
cur_line = addElem({
"element": "polyline",
"attr": {
"id": getNextId(),
"points": (x+','+y+' '+x+','+y+' '+start_x+','+start_y),
"stroke": '#' + curConfig.initStroke.color,
"stroke-width": (!start_elem.stroke_width || start_elem.stroke_width == 0) ? curConfig.initStroke.width : start_elem.stroke_width,
"fill": "none",
"opacity": curConfig.initStroke.opacity,
"style": "pointer-events:none"
}
});
elData(cur_line, 'start_bb', bb);
}
return {
started: true
};
} else if(mode == "select") {
findConnectors();
}
},
mouseMove: function(opts) {
var zoom = svgCanvas.getZoom();
var e = opts.event;
var x = opts.mouse_x/zoom;
var y = opts.mouse_y/zoom;
var diff_x = x - start_x,
diff_y = y - start_y;
var mode = svgCanvas.getMode();
if(mode == "connector" && started) {
var sw = cur_line.getAttribute('stroke-width') * 3;
// Set start point (adjusts based on bb)
var pt = getBBintersect(x, y, elData(cur_line, 'start_bb'), getOffset('start', cur_line));
start_x = pt.x;
start_y = pt.y;
setPoint(cur_line, 0, pt.x, pt.y, true);
// Set end point
setPoint(cur_line, 'end', x, y, true);
} else if(mode == "select") {
var slen = selElems.length;
while(slen--) {
var elem = selElems[slen];
// Look for selected connector elements
if(elem && elData(elem, 'c_start')) {
// Remove the "translate" transform given to move
svgCanvas.removeFromSelection([elem]);
svgCanvas.getTransformList(elem).clear();
}
}
if(connections.length) {
updateLine(diff_x, diff_y);
}
}
},
mouseUp: function(opts) {
var zoom = svgCanvas.getZoom();
var e = opts.event,
x = opts.mouse_x/zoom,
y = opts.mouse_y/zoom,
mouse_target = e.target;
if(svgCanvas.getMode() == "connector") {
var fo = $(mouse_target).closest("foreignObject");
if(fo.length) mouse_target = fo[0];
var parents = $(mouse_target).parents();
if(mouse_target == start_elem) {
// Start line through click
started = true;
return {
keep: true,
element: null,
started: started
}
} else if($.inArray(svgcontent, parents) === -1) {
// Not a valid target element, so remove line
$(cur_line).remove();
started = false;
return {
keep: false,
element: null,
started: started
}
} else {
// Valid end element
end_elem = mouse_target;
var start_id = start_elem.id, end_id = end_elem.id;
var conn_str = start_id + " " + end_id;
var alt_str = end_id + " " + start_id;
// Don't create connector if one already exists
var dupe = $(svgcontent).find(conn_sel).filter(function() {
var conn = this.getAttributeNS(se_ns, "connector");
if(conn == conn_str || conn == alt_str) return true;
});
if(dupe.length) {
$(cur_line).remove();
return {
keep: false,
element: null,
started: false
}
}
var bb = svgCanvas.getStrokedBBox([end_elem]);
var pt = getBBintersect(start_x, start_y, bb, getOffset('start', cur_line));
setPoint(cur_line, 'end', pt.x, pt.y, true);
$(cur_line)
.data("c_start", start_id)
.data("c_end", end_id)
.data("end_bb", bb);
se_ns = svgCanvas.getEditorNS(true);
cur_line.setAttributeNS(se_ns, "se:connector", conn_str);
cur_line.setAttribute('class', conn_sel.substr(1));
cur_line.setAttribute('opacity', 1);
svgCanvas.addToSelection([cur_line]);
svgCanvas.moveToBottomSelectedElement();
selManager.requestSelector(cur_line).showGrips(false);
started = false;
return {
keep: true,
element: cur_line,
started: started
}
}
}
},
selectedChanged: function(opts) {
// TODO: Find better way to skip operations if no connectors are in use
if(!$(svgcontent).find(conn_sel).length) return;
if(svgCanvas.getMode() == 'connector') {
svgCanvas.setMode('select');
}
// Use this to update the current selected elements
selElems = opts.elems;
var i = selElems.length;
while(i--) {
var elem = selElems[i];
if(elem && elData(elem, 'c_start')) {
selManager.requestSelector(elem).showGrips(false);
if(opts.selectedElement && !opts.multiselected) {
// TODO: Set up context tools and hide most regular line tools
showPanel(true);
} else {
showPanel(false);
}
} else {
showPanel(false);
}
}
updateConnectors();
},
elementChanged: function(opts) {
var elem = opts.elems[0];
if (elem && elem.tagName == 'svg' && elem.id == "svgcontent") {
// Update svgcontent (can change on import)
svgcontent = elem;
init();
}
// Has marker, so change offset
if(elem && (
elem.getAttribute("marker-start") ||
elem.getAttribute("marker-mid") ||
elem.getAttribute("marker-end")
)) {
var start = elem.getAttribute("marker-start");
var mid = elem.getAttribute("marker-mid");
var end = elem.getAttribute("marker-end");
cur_line = elem;
$(elem)
.data("start_off", !!start)
.data("end_off", !!end);
if(elem.tagName == "line" && mid) {
// Convert to polyline to accept mid-arrow
var x1 = elem.getAttribute('x1')-0;
var x2 = elem.getAttribute('x2')-0;
var y1 = elem.getAttribute('y1')-0;
var y2 = elem.getAttribute('y2')-0;
var id = elem.id;
var mid_pt = (' '+((x1+x2)/2)+','+((y1+y2)/2) + ' ');
var pline = addElem({
"element": "polyline",
"attr": {
"points": (x1+','+y1+ mid_pt +x2+','+y2),
"stroke": elem.getAttribute('stroke'),
"stroke-width": elem.getAttribute('stroke-width'),
"marker-mid": mid,
"fill": "none",
"opacity": elem.getAttribute('opacity') || 1
}
});
$(elem).after(pline).remove();
svgCanvas.clearSelection();
pline.id = id;
svgCanvas.addToSelection([pline]);
elem = pline;
}
}
// Update line if it's a connector
if(elem.getAttribute('class') == conn_sel.substr(1)) {
var start = getElem(elData(elem, 'c_start'));
updateConnectors([start]);
} else {
updateConnectors();
}
},
toolButtonStateUpdate: function(opts) {
if(opts.nostroke) {
if ($('#mode_connect').hasClass('tool_button_current')) {
clickSelect();
}
}
$('#mode_connect')
.toggleClass('disabled',opts.nostroke);
}
};
});
|
import React from 'react';
import PropTypes from 'prop-types';
import {
Layer,
Text,
} from 'react-konva';
// this component takes in charge all related to the square
// names witch are: ABCD anf A'B'C'D'.
const Annotation = ({
blackStroke,
fontSize,
squareNodeA,
squareNodeB,
}) => (
<Layer>
<Text
x={160}
y={180}
text={squareNodeA.A}
fontSize={fontSize}
fill={blackStroke}
/>
<Text
x={160}
y={350}
text={squareNodeA.B}
fontSize={fontSize}
fill={blackStroke}
/>
<Text
x={370}
y={350}
text={squareNodeA.C}
fontSize={fontSize}
fill={blackStroke}
/>
<Text
x={370}
y={180}
text={squareNodeA.D}
fontSize={fontSize}
fill={blackStroke}
/>
<Text
x={770}
y={370}
text={squareNodeB.A}
fontSize={fontSize}
fill={blackStroke}
/>
<Text
x={770}
y={180}
text={squareNodeB.B}
fontSize={fontSize}
fill={blackStroke}
/>
<Text
x={560}
y={180}
text={squareNodeB.C}
fontSize={fontSize}
fill={blackStroke}
/>
<Text
x={560}
y={370}
text={squareNodeB.D}
fontSize={fontSize}
fill={blackStroke}
/>
</Layer>
);
Annotation.propTypes = {
blackStroke: PropTypes.string.isRequired,
fontSize: PropTypes.number.isRequired,
squareNodeA: PropTypes.shape({
A: PropTypes.string.isRequired,
B: PropTypes.string.isRequired,
C: PropTypes.string.isRequired,
D: PropTypes.string.isRequired,
}).isRequired,
squareNodeB: PropTypes.shape({
A: PropTypes.string.isRequired,
B: PropTypes.string.isRequired,
C: PropTypes.string.isRequired,
D: PropTypes.string.isRequired,
}).isRequired,
};
export default Annotation;
|
OC.L10N.register(
"settings",
{
"Couldn't send reset email. Please contact your administrator." : "Die E-Mail zum Zurücksetzen konnte nicht versendet werden. Bitte kontaktiere Deinen Administrator.",
"Email sent" : "E-Mail wurde verschickt",
"Delete" : "Löschen",
"Share" : "Teilen",
"Invalid request" : "Fehlerhafte Anfrage",
"Very weak password" : "Sehr schwaches Passwort",
"Weak password" : "Schwaches Passwort",
"So-so password" : "Durchschnittliches Passwort",
"Good password" : "Gutes Passwort",
"Strong password" : "Starkes Passwort",
"never" : "niemals",
"Cheers!" : "Noch einen schönen Tag!",
"Save" : "Speichern",
"Server address" : "Adresse des Servers",
"Port" : "Port",
"Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "Insbesondere bei Nutzung des Desktop Clients zur Dateisynchronisierung wird vom Einsatz von SQLite abgeraten.",
"Add" : "Hinzufügen",
"Cancel" : "Abbrechen",
"Email" : "E-Mail",
"Password" : "Passwort",
"New password" : "Neues Passwort",
"Change password" : "Passwort ändern",
"Name" : "Name",
"Username" : "Benutzername",
"New Password" : "Neues Passwort",
"Personal" : "Persönlich",
"Admin" : "Administration",
"Settings" : "Einstellungen",
"Group" : "Gruppe",
"Other" : "Anderes"
},
"nplurals=2; plural=(n != 1);");
|
$(document).ready(function () {
var leftSidebar = $('#leftSidebar');
leftSidebar.hide();
// Set handler for Left Sidebar
$('#toggleSidebar').on('click', function () {
leftSidebar.toggle();
});
//Set tooltip
$('[data-toggle="tooltip"]').tooltip();
// Call print
$("#callPrint").on("click", function (e) {
e.preventDefault();
window.print();
});
});
|
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
import Slider from '@react-native-community/slider';
import TrackPlayer,{useProgress} from 'react-native-track-player'
const formatTime = (secs) =>{
let minutes = Math.floor(secs / 60)
let seconds = Math.ceil(secs - minutes * 60);
if (seconds < 10) seconds = `0${seconds}`
return `${minutes}:${seconds}`
}
export default function SliderComp() {
const {position,duration} = useProgress()
const handleChange = (val)=>{
TrackPlayer.seekTo(val)
}
return (
<View style={styles.container}>
<Slider
style={{width: 350, height: 40}}
minimumValue={0}
maximumValue={duration}
value={position}
minimumTrackTintColor="#FFFFFF"
maximumTrackTintColor="rgba(255, 255, 255, .5)"
thumbTintColor="#fff"
onSlidingComplete={handleChange}
/>
<View style={styles.timerContainer}>
<Text style={styles.timer}>{formatTime(position)}</Text>
<Text style={styles.timer}>{formatTime(duration)}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container:{
height:70
},
timerContainer:{
flexDirection: 'row',
justifyContent: "space-between",
},
timer:{
color:'#fff',
fontSize:16,
paddingLeft:15,
paddingRight:15
}
});
|
import { filterCourses } from '../mongodb/courses';
export default {
description: 'Filter courses API',
notes: 'Return details of courses on a particular filter',
tags: ['api', 'courses'],
cors: true,
async handler(request, h) {
try {
if (!request.auth.isAuthenticated) {
return h.redirect('/sign-in');
}
const {
isPaid, level, minRating, maxRating,
} = request.payload;
const res = await filterCourses({
isPaid, level, minRating, maxRating,
});
return h.response(res).headers('Access-Control-Allow-Origin').code(200);
} catch (error) {
return h
.response({
statusCode: 500,
error: 'Server Error',
}).headers('Access-Control-Allow-Origin')
.code(500);
}
},
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function loadAsset(player, entry, callback) {
player.getAssetData(`assets/${entry.storagePath}/shader.json`, "json", (err, data) => {
player.getAssetData(`assets/${entry.storagePath}/vertexShader.txt`, "text", (err, vertexShader) => {
data.vertexShader = { text: vertexShader };
player.getAssetData(`assets/${entry.storagePath}/fragmentShader.txt`, "text", (err, fragmentShader) => {
data.fragmentShader = { text: fragmentShader };
callback(null, data);
});
});
});
}
exports.loadAsset = loadAsset;
function createOuterAsset(player, asset) { return new window.Sup.Shader(asset); }
exports.createOuterAsset = createOuterAsset;
|
// super messy code oops
// the actual diffusion part is pretty simple
/**
* Converts tensors to viewable blob images (much easier to deal with than base64)
* @param {Tensor} tensor - RGB, CHW, float32 tensor to convert to image blob
* @returns Promised Blob
*/
function tensorToBlobAsync(tensor) {
const canvas = document.createElement("canvas");
[canvas.height, canvas.width] = [tensor.dims[2], tensor.dims[3]];
const ctx = canvas.getContext("2d");
let outputImage = new ImageData(new Uint8ClampedArray(canvas.width * canvas.height * 4), canvas.width, canvas.height);
for (let i = 0; i < outputImage.data.length; i++) {
outputImage.data[i] = 255 * ((i&3) == 3 || tensor.data[(i&3) * canvas.height * canvas.width + (i>>2)]);
}
ctx.putImageData(outputImage, 0, 0);
return new Promise((resolve, reject)=> {
canvas.toBlob(resolve);
});
}
/**
* Clamp float to be within range
* @param {float} x - value to clamp
* @param {float} a - minimum value
* @param {float} b - maximum value
* @returns clamped value
*/
function clamp(x, a, b) {
return Math.max(a, Math.min(x, b));
}
/**
* Convert a linear index in a CHW, RGB patch to {y, x, c} coordinates in output image
* @param {int} i - index into patch
* @param {Task} task - task used to create patch
* @param {int} h - height of patch
* @param {int} w - width of patch
* @returns Floating-point, unclamped coordinates into output image
*/
function patchIndexToImageCoords(i, task, h, w) {
const c = Math.floor(i / (h * w));
const y = (Math.floor(i / w) % h + 0.5) / h * task.hwIn + task.yIn - 0.5;
const x = (i % w + 0.5) / w * task.hwIn + task.xIn - 0.5;
return {y, x, c};
}
/**
* Convert a linear index in a CHW, RGB patch to nearest linear index in the larger HWC, RGBA output image.
* @param {int} i - index into patch
* @param {Task} task - task used to create patch
* @param {int} h - height of patch
* @param {int} w - width of patch
* @param {int} oh - height of output image
* @param {int} ow - width of output image
* @returns Index into HWC RGBA output image
*/
function patchIndexToImageIndex(i, task, h, w, oh, ow) {
const coords = patchIndexToImageCoords(i, task, h, w);
const outY = clamp(Math.round(coords.y), 0, oh - 1);
const outX = clamp(Math.round(coords.x), 0, ow - 1);
return (outY * ow + outX) * 4 + coords.c;
}
/**
* Splat a given patch into the given output image, based on patch task description.
* Patch overlap is handled, so that overlapping patches are alpha-blended together.
* (Dynamic input sizes make ORT very sad so it's easier to handle patches manually)
* @param {Tensor} patch - RGB, CHW float32 patch to write
* @param {Task} task - Task describing the location of the patch
* @param {ImageData} outputImage - Image to write patch into.
*/
function writePatchToImageWithFancyOverlapHandling(patch, task, outputImage) {
const [h, w] = [patch.dims[2], patch.dims[3]];
const overlap = ((task.hwIn - task.hwOut) + 1);
for (let y = task.yIn; y < task.yIn + task.hwIn && y < outputImage.height; y++) {
for (let x = task.xIn; x < task.xIn + task.hwIn && x < outputImage.width; x++) {
const py = clamp(Math.round((y - task.yIn + 0.5) / task.hwIn * h - 0.5), 0, h - 1);
const px = clamp(Math.round((x - task.xIn + 0.5) / task.hwIn * w - 0.5), 0, w - 1);
// alpha follows an overlap-length linear ramp on the top-left of each patch,
// except for the patches on the top or left edges of the entire image.
let alphaX = clamp((y - task.yIn) / overlap + (task.yIn == 0), 0, 1);
let alphaY = clamp((x - task.xIn) / overlap + (task.xIn == 0), 0, 1)
let alpha = Math.min(alphaX, alphaY);
for (let c = 0; c < 3; c++) {
let v = 255 * patch.data[c * (h * w) + py * w + px];
v = alpha * v + (1 - alpha) * outputImage.data[(y * outputImage.width + x) * 4 + c];
outputImage.data[(y * outputImage.width + x) * 4 + c] = v;
}
}
}
}
/**
* Schedule that spends more time at high noise levels.
* (Needed for reasonably vibrant results at small stepcounts)
* @param {float} x - Noisiness under default linspace(1, 0) schedule.
* @returns Adjusted noise level under the modified schedule.
*/
function noiseLevelSchedule(x) {
const k = 0.2;
return x * (1 + k) / (x + k);
}
function makeGenerator(network, patch, patchNoise, patchNoiseLevel, patchLowRes, patchCoords, patchGuidance, outputImage, renderResult) {
// single step of denoising
async function generatePatch(task) {
// useful stuff
const [nlIn, nlOut] = [noiseLevelSchedule(1 - task.step / task.steps), noiseLevelSchedule(1 - (task.step + 1) / task.steps)];
const [h, w] = [patch.dims[2], patch.dims[3]];
// fill input information
patchNoiseLevel.data[0] = nlIn;
if (task.step == 0) {
// fill working image
for (let i = 0; i < patch.data.length; i++) {
patch.data[i] = patchNoise.data[i];
}
// fill lowres image
for (let i = 0; i < patchLowRes.data.length; i++) {
patchLowRes.data[i] = (task.stage == 0) ? -1 : outputImage.data[patchIndexToImageIndex(i, task, h, w, outputImage.height, outputImage.width)] / 255.0;
}
// fill coords
for (let i = 0; i < patchCoords.data.length; i++) {
const coords = patchIndexToImageCoords(i, task, h, w);
patchCoords.data[i] = coords.c == 0 ? (coords.x / outputImage.width) : (coords.c == 1 ? (coords.y / outputImage.height) : 1);
}
// fill guidance
if (task.stage > 0) {
for (let i = 0; i < patchGuidance.data.length; i++) {
patchGuidance.data[i] = 1;
}
}
}
// perform denoising step
const tickModel = Date.now();
const denoised = (await network.run({"x": patch, "noise_level": patchNoiseLevel, "x_lowres": patchLowRes, "x_coords": patchCoords, "x_cond": patchGuidance})).denoised;
const tockModel = Date.now();
// start making timeline images
const noisedImage = task.stage == 0 ? tensorToBlobAsync(patch) : null;
const denoisedImage = task.stage == 0 ? tensorToBlobAsync(denoised) : null;
// update working image
const alpha = nlOut / nlIn;
for (let i = 0; i < patch.data.length; i++) {
patch.data[i] = alpha * patch.data[i] + (1 - alpha) * denoised.data[i];
}
// update rendering
writePatchToImageWithFancyOverlapHandling(denoised, task, outputImage);
renderResult({"done": false, "nlIn": nlIn, "nlOut": nlOut, "task": task, "modelTime_ms": tockModel - tickModel, "noised": noisedImage, "denoised": denoisedImage});
}
let generationHandle = null;
function generate(stepsPerResolution) {
// plan out the work we'll need for this image generation
let patchTaskQueue = [];
for (let i = 0; i < stepsPerResolution.length; i++) {
const steps = stepsPerResolution[i];
// extra patch here (the + 1) so we get some patch overlap and no ugly edges
const patchesPerSide = i == 0 ? 1 : ((1 << i) + 1);
const patchSidePx = Math.round(patch.dims[2] / patchesPerSide) * Math.round(outputImage.width / patch.dims[2]);
const tasksInStage = patchesPerSide * patchesPerSide * steps;
for (let t = 0; t < tasksInStage; t++) {
const [patchY, patchX, step] = [Math.floor(t / patchesPerSide / steps), Math.floor(t / steps) % patchesPerSide, t % steps];
patchTaskQueue.push({
"stage": i, "step": step, "steps": steps,
"xIn": patchX * patchSidePx, "yIn": patchY * patchSidePx, "hwIn": Math.round(outputImage.width / (1 << i)),
"xOut": patchX * patchSidePx, "yOut": patchY * patchSidePx, "hwOut": patchSidePx,
"progress": (t + 1) / tasksInStage
});
}
}
// if we're already generating something, stop doing that
if (generationHandle) window.clearTimeout(generationHandle);
// start generating the new thing
const minFrameTime_ms = 10;
function generateNextPatchInQueue() {
if (patchTaskQueue.length == 0) return renderResult({"done": true});
generatePatch(patchTaskQueue.shift()).then(() => {
generationHandle = window.setTimeout(generateNextPatchInQueue, minFrameTime_ms);
});
}
generationHandle = window.setTimeout(generateNextPatchInQueue, minFrameTime_ms);
}
return generate;
}
window.addEventListener("load", async () => {
const [CHANNELS_IN, HEIGHT, WIDTH, UPSAMPLE] = [3, 64, 64, 8];
// complicated image / progress rendering & hover preview stuff
const canvasEl = document.querySelector("#output");
const sketchPadEl = document.querySelector("#sketchpad");
const previewEl = document.querySelector("#preview");
const ctx = canvasEl.getContext("2d");
const sketchCtx = sketchPadEl.getContext("2d");
const previewCtx = previewEl.getContext("2d");
const outputImage = new ImageData(new Uint8ClampedArray(HEIGHT * WIDTH * 4 * UPSAMPLE * UPSAMPLE), WIDTH * UPSAMPLE, HEIGHT * UPSAMPLE);
outputImage.data.fill(255);
[canvasEl.height, canvasEl.width] = [outputImage.height, outputImage.width];
[previewEl.height, previewEl.width] = [outputImage.height, outputImage.width];
[sketchPadEl.height, sketchPadEl.width] = [HEIGHT, WIDTH];
let hoverPreview = false;
let releaseHover = null;
function renderResult(result) {
ctx.putImageData(outputImage, 0, 0);
if (!hoverPreview) {
previewEl.style.opacity = 0;
}
result.task = result.task || {"progress": 0, "stage": -1};
if (result.task.stage == 0) {
const momentContainer = document.querySelector("#timeline");
const moment = document.createElement("div");
if (result.task.step == 0) {
momentContainer.innerHTML = "";
}
momentContainer.append(moment);
result.noised.then((blob) => {
let image = document.createElement("img");
image.src = URL.createObjectURL(blob);
moment.prepend(image);
});
result.denoised.then((blob) => {
let text = document.createElement("span");
text.innerHTML = " → 🦖 → "; // rawr
let image = document.createElement("img");
image.src = URL.createObjectURL(blob);
moment.onmouseenter = moment.ontouchstart = () => {
if (releaseHover) releaseHover();
hoverPreview = true;
moment.classList.add("pressed");
previewEl.style.opacity = 1;
previewCtx.drawImage(image, 0, 0, canvasEl.width, canvasEl.height);
};
let releaseHover = () => {
moment.classList.remove("pressed");
if (momentContainer.querySelector(".pressed") == null) {
// none selected
previewEl.style.opacity = 0;
}
hoverPreview = false;
releaseHover = null;
}
moment.onmouseleave = moment.ontouchcancel = moment.ontouchend = releaseHover;
moment.append(text, image);
});
}
if (result.task.step == 0) {
for (let i = 0; i < 10; i++) document.querySelector("#progress").classList.remove(`stage${i}`);
document.querySelector("#progress").classList.add(`stage${result.task.stage}`);
}
if (result.done) {
canvasEl.toBlob((blob) => {
document.querySelector("#c-d").href = URL.createObjectURL(blob);
document.querySelector("#c-d").target = "_blank";
document.querySelector("#c-d").classList.remove("inactive");
});
}
document.querySelector("#progress").style.opacity = 1 - result.done;
document.querySelector("#progress #bar").style.width = `${100 * result.task.progress}%`;
if (result.modelTime_ms) document.querySelector("#stats").textContent = `${Math.round(result.modelTime_ms)} ms`;
}
// fill with blank image to start
renderResult({});
// load actual neural network stuff, log any errors
ctx.textAlign = "center";
ctx.fillStyle = "black";
ctx.font = "bold 32px sans-serif";
var network = null;
try {
ctx.fillText("Loading neural network...", outputImage.width / 2, outputImage.height / 2, outputImage.width);
network = await ort.InferenceSession.create("./network.onnx", { executionProviders: ["webgl"] });
// once it worked, show the controls
renderResult({});
ctx.font = "bold 24px sans-serif";
ctx.fillText("Network loaded. Preparing generator...", outputImage.width / 2, outputImage.height / 2, outputImage.width);
document.querySelector("#controls").style.visibility = "visible";
} catch (error) {
renderResult({});
ctx.fillText("The neural network didn't load :(", outputImage.width / 2, outputImage.height / 2, outputImage.width);
ctx.font = "16px sans-serif";
ctx.fillText("Try a different computer / phone?", outputImage.width / 2, outputImage.height / 2 + 16, outputImage.width);
ctx.fillStyle = "pink";
ctx.font = "14px monospace";
ctx.fillText(error, outputImage.width / 2, outputImage.height / 2 + 32, outputImage.width * 0.8);
console.error(error);
}
const patch = new ort.Tensor("float32", new Float32Array(CHANNELS_IN * HEIGHT * WIDTH), [1, CHANNELS_IN, HEIGHT, WIDTH]);
const patchNoise = new ort.Tensor("float32", new Float32Array(CHANNELS_IN * HEIGHT * WIDTH), [1, CHANNELS_IN, HEIGHT, WIDTH]);
const patchNoiseLevel = new ort.Tensor("float32", new Float32Array(1), [1, 1, 1, 1]);
const patchLowRes = new ort.Tensor("float32", new Float32Array(CHANNELS_IN * HEIGHT * WIDTH), [1, CHANNELS_IN, HEIGHT, WIDTH]);
const patchCoords = new ort.Tensor("float32", new Float32Array(CHANNELS_IN * HEIGHT * WIDTH), [1, CHANNELS_IN, HEIGHT, WIDTH]);
const patchGuidance = new ort.Tensor("float32", new Float32Array(CHANNELS_IN * HEIGHT * WIDTH), [1, CHANNELS_IN, HEIGHT, WIDTH]);
// initial noise
function resample() {
for (let i = 0; i < patchNoise.data.length; i++) patchNoise.data[i] = Math.random();
}
resample();
// set up image generator
const generator = makeGenerator(network, patch, patchNoise, patchNoiseLevel, patchLowRes, patchCoords, patchGuidance, outputImage, renderResult);
function regenerate() {
const steps = parseInt(document.querySelector("#steps input").value);
const guidanceImage = sketchCtx.getImageData(0, 0, sketchPadEl.width, sketchPadEl.height);
for (let c = 0; c < CHANNELS_IN; c++) {
for (let i = 0; i < sketchPadEl.width * sketchPadEl.height; i++) {
patchGuidance.data[c * HEIGHT * WIDTH + i] = guidanceImage.data[4 * i] / 255;
}
}
generator([steps, Math.max(1, Math.floor(steps / 10)), Math.max(1, Math.floor(steps / 20)), Math.max(1, Math.floor(steps / 25))]);
}
// set up sketchpad
sketchCtx.fill()
sketchCtx.fillStyle = 'white';
sketchCtx.fillRect(0, 0, sketchPadEl.width, sketchPadEl.height);
let pencil = { pressed: false, x: 0, y: 0, side: "nib", drew: false };
function sketchCoords(ev) {
if (!ev) return {x: null, y: null};
const c = sketchPadEl.getBoundingClientRect();
const x = (ev.clientX - c.x + 0.5) / sketchPadEl.clientWidth * sketchPadEl.width - 0.5;
const y = (ev.clientY - c.y + 0.5) / sketchPadEl.clientHeight * sketchPadEl.height - 0.5;
return {x, y};
}
function sketchLine(x0f, y0f, x1f, y1f, side) {
let [x0, y0, x1, y1] = [x0f, y0f, x1f, y1f].map(Math.floor);
const [dx, dy] = [Math.abs(x1 - x0), -Math.abs(y1 - y0)];
const sx = x0 < x1 ? 1 : -1;
const sy = y0 < y1 ? 1 : -1;
let error = dx + dy;
for (let i = 0; i < 128; i++) {
if (side == "nib") {
sketchCtx.fillRect(x0, y0, 1, 1);
} else {
sketchCtx.fillRect(x0 - 3, y0 - 3, 7, 7);
}
if (x0 == x1 && y0 == y1) break;
let e2 = 2 * error;
if (e2 >= dy) {
if (x0 == x1) break;
error = error + dy;
x0 = x0 + sx;
}
if (e2 <= dx) {
if (y0 == y1) break;
error = error + dx;
y0 = y0 + sy;
}
}
}
function updateLine(ev) {
if (ev.touches) { ev = ev.touches[0]; }
const coords = sketchCoords(ev);
if (pencil.pressed) {
sketchCtx.fillStyle = pencil.side == "nib" ? "black" : "white";
sketchLine(pencil.x, pencil.y, coords.x, coords.y, pencil.side);
pencil.drew = true;
}
[pencil.x, pencil.y] = [coords.x, coords.y];
}
sketchPadEl.onmousedown = sketchPadEl.ontouchstart = (ev) => {
pencil.pressed = false;
updateLine(ev);
pencil.pressed = true;
updateLine(ev);
};
sketchPadEl.parentElement.addEventListener("touchstart", (ev) => ev.preventDefault());
sketchPadEl.parentElement.addEventListener("touchmove", (ev) => ev.preventDefault());
document.body.onmousemove = document.body.ontouchmove = (ev) => {
updateLine(ev);
};
document.body.onmouseup = document.body.ontouchend = document.body.ontouchcancel = document.body.onmouseleave = (ev) => {
pencil.pressed = false;
updateLine(ev);
hideOrShowSketchpad();
};
function hideOrShowSketchpad() {
if (Array.from(document.querySelectorAll(".c.tool")).some((el) => el.classList.contains("pressed"))) {
sketchPadEl.classList.add("pressed");
} else {
sketchPadEl.classList.remove("pressed");
// reset pencil
pencil.side = "nib";
if (pencil.drew) {
regenerate();
pencil.drew = false;
}
}
}
function hideSketchpad() {
Array.from(document.querySelectorAll(".c.tool")).forEach((el) => el.classList.remove("pressed"));
hideOrShowSketchpad();
}
// allow drawing even if no tool is selected...
sketchPadEl.addEventListener("mousedown", (ev) => {
sketchPadEl.classList.add("pressed");
if (pencil.side == "nib") document.querySelector("#c-s").classList.add("pressed");
});
sketchPadEl.addEventListener("touchstart", (ev) => {
sketchPadEl.classList.add("pressed");
if (pencil.side == "nib") document.querySelector("#c-s").classList.add("pressed");
});
document.querySelector("#c-s").onclick = (ev) => {
if (ev.target.classList.contains("pressed")) {
ev.target.classList.remove("pressed");
} else {
pencil.side = "nib";
ev.target.classList.add("pressed");
document.querySelector("#c-e").classList.remove("pressed");
}
hideOrShowSketchpad();
}
document.querySelector("#c-e").onclick = (ev) => {
if (ev.target.classList.contains("pressed")) {
ev.target.classList.remove("pressed");
} else {
pencil.side = "eraser";
ev.target.classList.add("pressed");
document.querySelector("#c-s").classList.remove("pressed");
}
hideOrShowSketchpad();
}
// reset button creates new latents
document.querySelector("#c-r").onmousedown = document.querySelector("#c-r").ontouchstart = ev => ev.target.classList.add("pressed");
document.querySelector("#c-r").onclick = ev => {
ev.target.classList.remove("pressed");
hideSketchpad();
resample();
regenerate();
}
// help button toggles help text
document.querySelector("#c-h").onclick = () => {
hideSketchpad();
["#c-h", "#help"].map(q=>document.querySelector(q).classList.toggle("pressed"));
const helpButton = document.querySelector("#c-h")
// ugh
for (let cs of ["c-s", "c-e", "c-r", "c-d", "steps", "stats", "easel", "progress", "timeline"]) {
c = document.querySelector(`#${cs}`);
if (helpButton.classList.contains("pressed")) {
c.style.display = "none";
} else {
c.style.display = null;
}
}
}
document.querySelector("#c-d").onclick = (ev) => {
if (!ev.target.classList.contains("inactive")) {
ev.target.classList.add("pressed")
window.setTimeout(() => ev.target.classList.remove("pressed"), 50);
}
}
// keys are shortcuts for buttons
document.addEventListener("keydown", ev => {
if (ev.key == "Escape" || ev.key == " ") document.querySelector("#c-r").click();
if (ev.key == "Escape" && document.querySelector("#c-h").classList.contains("pressed")) document.querySelector("#c-h").click();
if (ev.key == "?") document.querySelector("#c-h").click();
if (ev.key == "b" || ev.key == "c") document.querySelector("#c-s").click();
if (ev.key == "e" || ev.key == "s") document.querySelector("#c-e").click();
});
// slider controls a label
function makeStepsLabelMatchSlider() {
document.querySelector("#steps span").textContent = document.querySelector("#steps input").value;;
}
document.querySelector("#steps input").oninput = makeStepsLabelMatchSlider;
document.querySelector("#steps input").onchange = regenerate;
makeStepsLabelMatchSlider();
// hide sketchpad whenever you click anywhere else
document.body.addEventListener("mousedown", (ev) => {
if (ev.target == document.body) {
hideSketchpad();
}
});
// generate an image when the page loads
document.querySelector("#c-r").click();
});
|
import React, { Component } from 'react'
import telescope from '../assets/telescope.jpg'
export class Navbar extends Component {
render() {
return (
<div className='navbar'>
<h1 id='navbarTitle'>Job Explorer <img src={telescope} alt='telescope' /> </h1>
</div>
)
}
}
export default Navbar
|
// Flint Tool Maker
// for DanIdle version 4
// Produces more advanced (aka less primitive) tools out of flint, sticks and twine
import {
blockOutputsItems,
blockHasWorkerPriority,
blockDeletesClean
} from "./activeBlock.js";
import { blockHasSelectableCrafting } from "./blockAddon_HasSelectableCrafting.js";
import { game } from "./game.js";
import $ from "jquery";
export const flintToolMaker = mapSquare => {
let state = {
name: "flintToolMaker",
tile: mapSquare,
id: game.getNextBlockId(),
counter: 0,
allowOutput: true,
maxOutput: 5,
outputItems: [
{ name: "None", needs: [] }, // 'none' is included so we can simply list all the items later
{
name: "Flint Hatchet",
info: "Better at cutting than Stabbers",
prereq: [],
parts: [
{ name: "Short Stick", qty: 1 },
{ name: "Twine", qty: 1 },
{ name: "Flint Hatchet Head", qty: 1 }
],
craftTime: 20,
isTool: true,
endurance: 100,
enduranceGain: 2,
enduranceTaper: 0.05,
efficiency: 2,
efficiencyGain: 0.05,
efficiencyTaper: 0.001
},
{
name: "Flint Hoe",
info: "Opens up farming",
prereq: [],
parts: [
{ name: "Long Stick", qty: 1 },
{ name: "Twine", qty: 1 },
{ name: "Flint Hoe Head", qty: 1 }
],
craftTime: 20,
isTool: true,
endurance: 100,
enduranceGain: 1.8,
enduranceTaper: 0.05,
efficiency: 1,
efficiencyGain: 0.05,
efficencyTaper: 0.001
},
{
name: "Flint Spear",
info: "Opens up hunting",
prereq: [],
parts: [
{ name: "Long Stick", qty: 1 },
{ name: "Twine", qty: 1 },
{ name: "Flint Spear Head", qty: 1 }
],
craftTime: 20,
isTool: true,
endurance: 100,
enduranceGain: 1.6,
enduranceTaper: 0.05,
efficiency: 1,
efficiencyGain: 0.05,
efficiencyTaper: 0.01
},
{
name: "Twine Table",
info: "Elevate your working tasks",
prereq: [],
parts: [
{ name: "Long Stick", qty: 5 },
{ name: "Short Stick", qty: 16 },
{ name: "Twine", qty: 5 }
],
craftTime: 20,
isTool: true,
endurance: 100,
enduranceGain: 1,
enduranceTaper: 0.001,
efficiency: 1,
efficiencyGain: 0,
efficiencyTaper: 0
},
{
name: "Twine Sled",
info: "Move things more easily",
prereq: [],
parts: [
{ name: "Long Stick", qty: 8 },
{ name: "Short Stick", qty: 8 },
{ name: "Twine", qty: 5 }
],
craftTime: 20,
isTool: true,
endurance: 100,
enduranceGain: 1,
enduranceTaper: 0.0001,
efficiency: 1,
efficiencyGain: 0,
efficiencyTaper: 0
},
{
name: "Twine Raft",
info: "Move things over water",
prereq: [],
parts: [
{ name: "Long Stick", qty: 6 },
{ name: "Short Stick", qty: 3 },
{ name: "Twine", qty: 3 }
],
craftTime: 20,
isTool: true,
endurance: 100,
enduranceGain: 1,
enduranceTaper: 0.0001,
efficiency: 1,
efficiencyGain: 0,
efficiencyTaper: 0
},
{
name: "Thatch Shingle",
info: "Create a roof",
prereq: ["Wheat Stalks"],
parts: [
{ name: "Wheat Stalks", qty: 10 },
{ name: "Twine", qty: 1 }
],
craftTime: 10,
isTool: false
}
],
// possibleOutputs() is already defined in blockHasSelectableCrafting
// inputsAccepted() is already defined in blockHasSelectableCrafting
// willOutput() is already defined in blockOutputsItems
// willAccept() is already defined in blockHasSelectableCrafting
// receiveItem() is already defined in blockHasSelectableCrafting
update() {
// Handles updating the stats of this block
if (!state.readyToCraft()) {
return state.searchForItems(true);
}
state.processCraft(1);
},
drawPanel() {
$("#sidepanel").html(`
<b>Flint Tool Maker</b><br />
<br />
Flint tools might get you started, but before long you're going to need better tools. Crafting wooden handles onto
your flint blades gives you a few better tools.<br />
<br />
Provide with twine, sticks and flint tool heads to produce a new variety of tools<br />
<br />
`);
state.showPriority();
$("#sidepanel").append(`
<br />
<b>Items Needed</b><br />
<div id="sidepanelparts">${state.drawStocks()}</div>
Progress: <span id="sidepanelprogress">${state.drawProgressPercent()}</span></br>
Finished tools on hand: <span id="sidepanelonhand">${
state.onhand.length
}</span><br />
`);
state.showDeleteLink();
$("#sidepanel").append("<br /><br />");
state.drawOutputChoices();
},
updatePanel() {
$("#sidepanelparts").html(state.drawStocks());
state.updateOutputChoices();
$("#sidepanelprogress").html(state.drawProgressPercent());
},
// pickcraft used to be here, but it is already defined in HasSelectableCrafting
deleteBlock() {
state.finishDelete();
}
};
const genHandle = game.blockDemands.find(ele => ele.name === state.name);
if (genHandle.hasNewOptions === undefined) {
genHandle.hasNewOptions = itemName => {
return itemName === "Wheat Stalks";
};
}
game.blockList.push(state);
mapSquare.structure = state;
$("#" + state.tile.id + "imageholder").html(
'<img src="img/flintToolMaker.png" />'
);
return Object.assign(
state,
blockOutputsItems(state),
blockHasWorkerPriority(state),
blockDeletesClean(state),
blockHasSelectableCrafting(state)
);
};
|
/**
* Created by Mac on 1/30/2016.
*/
doStuff = function(){
numPpl = getInt("txtNumPpl")
numPizzas = getInt("txtNumPizzas")
addHtml("txtOutput", "Numppl="+numPpl + " NumPizzas="+numPizzas+"<br><br>")
remainder = numPizzas % numPpl
html = "Num slices per person = " + Math.floor(numPizzas / numPpl) + "<br>" + "Remaining slices: " + remainder
addHtml("txtOutput", html)
}
|
'use strict';
const faker = require('faker')
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('Characters', [{
name: faker.name.findName(),
money: faker.random.number(),
admin: true,
createdAt: faker.date.past(),
updatedAt: faker.date.past()
}], {});
},
down: (queryInterface, Sequelize) => queryInterface.bulkDelete('Characters', null, {})
};
|
import React from 'react';
import './Contact.css';
import contactImg from './contact.jpg';
import github from '../../../src/icons/github-brands.svg';
import fcc from '../../../src/icons/free-code-camp-brands.svg';
import stack from '../../../src/icons/stack-overflow-brands.svg';
import linkedin from '../../../src/icons/linkedin-in-brands.svg';
import email from '../../../src/icons/envelope-regular.svg';
import phone from '../../../src/icons/phone-solid.svg';
function Contact() {
return (
<div className="container">
<img src={contactImg} alt="Contact" style={{backgroundSize: "cover", width:"100%", height:"100%"}}/>;
<div className="text">
<img className="icons" src={github} alt="GitHub" />
<a className="contact" href="github.com/roydaly" target="_blank" rel="noopener noreferrer"> - GitHub</a>
<br></br>
<img className="icons" src={fcc} alt="freeCodeCamp" />
<a className="contact" href="https://www.freecodecamp.org/roydaly" target="_blank" rel="noopener noreferrer"> - freeCodeCamp</a>
<br></br>
<img className="icons" src={stack} alt="StackOverflow" />
<a className="contact" href="https://stackoverflow.com/users/12032022/roydaly" target="_blank" rel="noopener noreferrer"> - Stack Overflow</a>
<br></br>
<img className="icons" src={linkedin} alt="LinkedIn" />
<a className="contact" href="https://www.linkedin.com/in/roy-daly/" target="_blank" rel="noopener noreferrer"> - LinkedIn</a>
<br></br>
<img className="icons" src={email} alt="Email" />
<a className="contact" href="mailto:roy@roydaly.com" target="_blank" rel="noopener noreferrer"> - Email Me</a>
<br></br>
<img className="icons" src={phone} alt="Email" />
<a className="contact" href="tel:425-306-7299" target="_blank" rel="noopener noreferrer"> - 425.306.7299</a>
</div>
</div>
)
}
export default Contact;
|
function Bullet (x=0,y=-1,vx,vy,color="yellow",ctx,width=10,height=10,ay) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.color = color;
this.ctx = ctx;
this.width = width;
this.height = height;
this.ay = ay;
}
Bullet.prototype.draw = function () {
this.ctx.save();
this.ctx.beginPath();
this.ctx.rect(this.x,this.y,this.width,this.height);
this.ctx.fillStyle = this.color;
this.ctx.fill();
this.ctx.closePath();
this.ctx.restore();
}
Bullet.prototype.changePosition = function () {
this.x += this.vx;
this.y += (this.vy + this.ay);
}
|
//jshint esversion:6
const express = require('express'),
app = express(),
path = require('path'),
cors = require('cors'),
request = require('request'),
fs = require('fs'),
jsonfile = require('jsonfile'),
router = express.Router(),
config = require('../client/src/config.json'),
DIST_DIR = path.join(__dirname, '../client/public/'),
HTML_FILE = path.join(DIST_DIR, 'index.html');
const port = process.env.PORT || 3001;
app.use(cors());
app.use(express.static(DIST_DIR));
app.get("/login", (req, res) => {
res.redirect("https://auth.monzo.com/?client_id=" + config.client_id + "&redirect_uri=" +
config.redirect_uri + "&response_type=" + config.response_type + "&state=" + config.state_token);
});
app.get("/oauth/callback", (req, res) => {
global.code = req.query.code; //store the code in a global variable
var client_id = config.client_id,
client_secret = config.client_secret,
redirect_uri = config.redirect_uri,
grant_type = config.grant_type;
request.post(
{
url: "https://api.monzo.com/oauth2/token",
form: {
grant_type,
client_id,
client_secret,
redirect_uri,
code
}
},
(err, response, body) => {
global.access_token = JSON.parse(body).access_token; //get the access token from response
console.log("oauth callback response: ", body);
console.log("access token: ", access_token);
res.redirect("/pending");
}
);
});
app.get("/pending", (req, res) => {
res.redirect("http://localhost:3000/pending");
})
app.get("/accounts", (req, res) => {
var account_type = config.account_type,
access_token = global.access_token;
request.get("https://api.monzo.com/accounts?account_type=" + account_type,
{
headers: {
Authorization: "Bearer " + access_token
}
},
(error, response, body) => {
var json = JSON.parse(body);
console.log("accounts json: ", json);
var account_desc = json.accounts[0].description,
account_type = json.accounts[0].type,
account_currency = json.accounts[0].currency,
account_num = json.accounts[0].account_number,
sort_code = json.accounts[0].sort_code,
owner_name = json.accounts[0].owners[0].preferred_name;
global.account_id = json.accounts[0].id; //account ID stored in global variable
sort_code = sort_code.slice(0,2)+"-"+sort_code.slice(2,4)+"-"+sort_code.slice(4,6);
res.json({
account_id: account_id,
account_desc: account_desc,
account_type: account_type,
account_currency: account_currency,
account_num: account_num,
sort_code: sort_code,
owner_name: owner_name
});
}
);
});
app.get("/balance", (req, res) => {
var account_id = global.account_id;
request.get(
{
url: "https://api.monzo.com/balance?account_id=" + account_id,
headers: {
Authorization: "Bearer " + global.access_token
}
},
(error, response, body) => {
var json = JSON.parse(body);
console.log("balances: ", json);
var balance = json.balance,
total_balance = json.total_balance,
spend_today = json.spend_today;
balance = (balance/100).toFixed(2); //add decimal pt
total_balance = (total_balance/100).toFixed(2);
if (spend_today<0) {
spend_today = (spend_today/100).toFixed(2);
spend_today = spend_today.substr(1); //removes the leading "-"
}
else spend_today = 0;
res.json({
balance: balance,
total_balance: total_balance,
spend_today: spend_today
});
}
);
});
app.get("/transactions", (req, res) => {
var account_id = global.account_id;
request.get(
{
url: "https://api.monzo.com/transactions?expand[]=merchant&account_id=" + account_id,
headers: {
Authorization: "Bearer " + global.access_token
}
},
(error, response, body) => {
const file = '../client/src/views/Dashboard/components/RecentTransactions/transactions.json';
var json = JSON.parse(body);
console.log("transactions: ", json);
const transactions = json.transactions;
const obj = JSON.stringify(transactions);
jsonfile.writeFile(file, obj) //save all transactions, access expires after 5min
.then(res => console.log('Transactions data written to transactions.json.'))
.catch(err => console.log(err));
res.json({
transactions: transactions //return transactions obj just in case
});
}
);
});
app.get('/', (req, res) => {
res.sendFile(HTML_FILE);
});
app.listen(port, function () {
console.log('App listening on port: ' + port);
});
module.exports = router;
|
import User from "../../src/model/User.js";
import UserRepository from "../../src/repository/UserRepository";
import { PrismaClient } from '@prisma/client';
describe('UserRepository', () => {
const prisma = new PrismaClient();
beforeAll(async () => {
await prisma.$connect();
});
afterEach(async () => {
await prisma.user.deleteMany();
});
afterAll( async () => {
await prisma.$disconnect();
})
test('save method saves a user', async () => {
const user = new User('Jonilson', 'jonilson@host.com', 2332, ['monitor']);
const result = await UserRepository.save(user);
expect(result.id).toBeDefined();
});
test('list method list all users', async () => {
const user = new User('Jonilson', 'jonilson@host.com', 2332, ['monitor']);
await UserRepository.save(user);
const users = await UserRepository.findAll();
expect(users).toHaveLength(1);
expect(users.pop()).toMatchObject({
name: user.name,
email: user.email,
roles: user.roles,
aluraId: user.aluraId
})
});
});
|
import React from 'react'
import { connect } from 'react-redux'
import { Desktop, Tablet, Mobile } from '../components/footer'
const Container = ({ viewport: { type } = {}, ...props }) => {
if (type === 'Mobile') {
return (
<Mobile {...props} />
)
} else if (type === 'Tablet') {
return (
<Tablet {...props} />
)
}
return (
<Desktop {...props} />
)
}
export default connect(
state => ({
viewport: state.viewport,
update: state.config.update,
checkers: state.config.checkers,
support: state.config.support,
providers: state.config.provider,
supportSystem: state.config.settings.support_system,
}),
)(Container)
|
window.onscroll = function() {myFunction()};
function myFunction() {
var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var element = document.getElementById("header");
if (winScroll > 100) {
element.classList.add("shadow-bottom");
} else {
element.classList.remove("shadow-bottom");
}
}
|
$(document).ready(function () {
//Toggle menu
$('.menu-btn').click(function () {
$('.menu ul').slideToggle();
//Button-menu
$('.line-btn:nth-child(2)').toggle();
$('.line-btn:nth-child(1)').toggleClass('line-rotate-1');
$('.line-btn:nth-child(3)').toggleClass('line-rotate-2');
});
});
|
request.symbol
request.companyName
request.marketcap //needs formatting
request.beta
request.week52high
request.week52low
request.dividendRate
request.dividenYield
request.exDividendDate
request.returnOnEquity
request.EBITDA
request.returnOnAssets
request.profitMargin
request.quote.latestPrice
request.quote.peRatio
|
'use strict';
var gulp = require('gulp'),
sass = require('gulp-sass'),
cleanCSS = require('gulp-clean-css'),
autoprefixer = require('gulp-autoprefixer'),
webserver = require('gulp-webserver'),
concat = require('gulp-concat'),
uglify = require('gulp-uglifyjs'),
babel = require('gulp-babel'),
sourcemaps = require('gulp-sourcemaps'),
tslint = require('gulp-tslint'),
ts = require('gulp-typescript'),
tsProject = ts.createProject('tsconfig.json', {
typescript: require('typescript')
}),
paths = {
scripts : [
'./node_modules/jquery/dist/jquery.js',
'./src/scripts/tmp/*.js'
]
};
gulp.task('compile-scss', function() {
gulp.src('src/styles/style.scss')
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 5 versions'],
cascade: false
}))
.pipe(cleanCSS({advanced : false}))
.pipe(gulp.dest('./app/dist/css/'));
});
gulp.task('watch-scss', function() {
gulp.watch('src/styles/*.scss', ['compile-scss']);
});
gulp.task('tslint', () => {
return gulp.src("src/**/*.ts")
.pipe(tslint({
formatter: 'prose'
}))
.pipe(tslint.report());
});
gulp.task("compile-ts", ["tslint"], () => {
let tsResult = gulp.src("src/**/*.ts").pipe(tsProject());
return tsResult.pipe(gulp.dest("./src/scripts"));
});
gulp.task('compile-js', ["compile-ts"], function() {
gulp.src(paths.scripts)
.pipe(concat('main.js'))
// .pipe(babel({
// presets: ['es2015']
// }))
// .pipe(uglify())
.pipe(gulp.dest('./app/dist/js/'));
});
gulp.task('watch-js', function() {
gulp.watch('./src/scripts/*.ts', ['compile-js']);
});
gulp.task('webserver', function() {
gulp.src('app')
.pipe(webserver({
livereload: true,
fallback: "index.html",
port: 8080,
open: true
}));
});
gulp.task('default', ['webserver', 'compile-scss', 'watch-scss', 'compile-js', 'watch-js'] );
|
import React from 'react'
import PropTypes from 'prop-types'
const LanguageItem = ({lang, selectedLanguage, onItemClick}) => (
<li
style={selectedLanguage === lang ? {color: '#d0021b'} : null}
onClick={() => onItemClick(lang)}>
{lang}
</li>
)
// LanguageItem.propTypes = {
// lang: PropTypes.string.isRequired,
// selectedLanguage: PropTypes.string.isRequired,
// onSelect: PropTypes.func.isRequired
// }
console.log('EXPORT')
console.log(LanguageItem)
export default LanguageItem
|
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var WorkoutSchema = new Schema({
created: Date,
duration: Number
});
module.exports = mongoose.model('Workout', WorkoutSchema);
|
// Same functionality with /api/pairs/[chainId].js
// Having issue on passing the list of records.
// vercel discuttion: https://github.com/vercel/next.js/discussions/27555
import dbConnect from "../util/dbConnect";
import Token from "../models/Token";
export default async function getPairList(_chainId) {
await dbConnect();
try {
const list = await Token.find({ chainId: _chainId }).lean();
// Getting error when passing the list directly (consumed by /pages/chains/[chainId])
// https://github.com/vercel/next.js/issues/11993
return JSON.parse(JSON.stringify(list));
} catch (error) {
return [];
}
}
|
var express = require('express');
var router = express.Router();
var isAdmin = require("../middleware/isAdmin");
const Controller = require('../controllers/brandsController');
router.get('/', Controller.getAllBrands);
router.get('/:id', Controller.getBrand);
router.post('/', isAdmin, Controller.addBrand);
router.delete('/', isAdmin, Controller.deleteAllBrands);
router.delete('/:id', isAdmin, Controller.deleteBrand);
router.put('/:id', isAdmin, Controller.updateBrand);
//Add Product
router.post('/:id/products', isAdmin, Controller.addProduct);
//Delete Product
router.delete('/:id/products/:product_id', isAdmin, Controller.deleteProduct);
//Get All Products
router.get('/:id/products', Controller.getAllProducts);
module.exports = router;
|
import React, { useReducer } from 'react';
import UserContext from './userContext';
import userReducer from './userReducer';
import { SHOW_USER_INFO, GET_USERS_INFO, UPDATE_USER_INFO, DELETE_USER, USER_ACTIVE, } from '../../types/index';
import axios from '../../config/axios';
const UserState = props => {
const initialState = {
userInfo: [],
newUserInfo: false,
getFirstName: {
firstName: ''
},
message: null
}
const [state, dispatch] = useReducer(userReducer, initialState)
//CRUD fuctions ADMIN.
const showUserInfo = () => {
dispatch({
type: SHOW_USER_INFO
})
}
//get USERS INFO
const getUserInfo = async () => {
try {
const reply = await axios.get('/users')
dispatch({
type: GET_USERS_INFO,
payload: reply.data.user
})
} catch (error) {
console.log(error)
}
}
const getUserByFirstName = async userFirstName => {
console.log(userFirstName)
try {
const reply = await axios.get(`/users/${userFirstName.firstName}`)
console.log(reply)
dispatch({
type: GET_USERS_INFO,
payload: reply.data.user
})
} catch (error) {
console.log(error)
}
}
const updateUserInfo = async userId => {
console.log(userId._id)
try {
const reply = await axios.put(`/users/${userId._id}`, userId);
console.log(reply)
dispatch({
type: UPDATE_USER_INFO,
payload: reply.data.userId
})
} catch (error) {
console.log(error);
}
}
const deleteUserById = async userId => {
try {
const reply = await axios.delete(`/users/${userId}`);
dispatch({
type: DELETE_USER,
payload: reply.data.user
})
} catch (error) {
console.log(error)
}
}
const userActive = async user => {
try {
const reply = await axios.put(`/users/${user._id}`, user);
console.log(reply)
dispatch({
type: USER_ACTIVE,
payload: reply.data.user
})
} catch (error) {
console.log(error);
}
}
return (
<UserContext.Provider
value={{
userInfo: state.userInfo,
message: state.message,
// newuserInfo: state.newUserInfo,
showUserInfo,
// getUserInfoById,
getUserByFirstName,
getUserInfo,
getFirstName: state.getFirstName,
updateUserInfo,
deleteUserById,
userActive
}}
>
{props.children}
</UserContext.Provider>
)
}
export default UserState;
|
import {Template} from 'meteor/templating';
import {AutoForm} from 'meteor/aldeed:autoform';
import {alertify} from 'meteor/ovcharik:alertifyjs';
import {fa} from 'meteor/theara:fa-helpers';
import {lightbox} from 'meteor/theara:lightbox-helpers';
import fx from 'money';
// Lib
import {createNewAlertify} from '../../../../core/client/libs/create-new-alertify.js';
import {renderTemplate} from '../../../../core/client/libs/render-template.js';
import {destroyAction} from '../../../../core/client/libs/destroy-action.js';
import {displaySuccess, displayError} from '../../../../core/client/libs/display-alert.js';
import {__} from '../../../../core/common/libs/tapi18n-callback-helper.js';
// Component
import '../../../../core/client/components/loading.js';
import '../../../../core/client/components/column-action.js';
import '../../../../core/client/components/form-footer.js';
import '../../../../core/client/components/add-new-button.js';
// Collection
import {Client} from '../../api/collections/client.js';
import {LoanAcc} from '../../api/collections/loan-acc.js';
// Method
import {lookupProduct} from '../../../common/methods/lookup-product.js';
import {lookupLoanAcc} from '../../../common/methods/lookup-loan-acc.js';
// Tabular
import {LoanAccTabular} from '../../../common/tabulars/loan-acc.js';
// Page
import './loan-acc.html';
// Declare template
let indexTmpl = Template.Microfis_loanAcc,
actionTmpl = Template.Microfis_loanAccAction,
productFormTmpl = Template.Microfis_loanAccProductForm,
formTmpl = Template.Microfis_loanAccForm,
showTmpl = Template.Microfis_loanAccShow;
// Index
indexTmpl.onCreated(function () {
// Create new alertify
createNewAlertify('loanAccProduct');
createNewAlertify('loanAcc', {size: 'lg'});
createNewAlertify('loanAccShow');
});
indexTmpl.helpers({
tabularTable(){
return LoanAccTabular;
},
tabularSelector(){
return {clientId: FlowRouter.getParam('clientId')};
},
});
indexTmpl.events({
'click .js-create-loan-acc' (event, instance) {
alertify.loanAccProduct(fa('plus', 'LoanAcc Product'), renderTemplate(productFormTmpl));
},
'click .js-update' (event, instance) {
// $.blockUI();
let self = this;
lookupProduct.callPromise({
_id: self.productId
}).then(function (result) {
Session.set('productDoc', result);
// Meteor.setTimeout(function () {
alertify.loanAcc(fa('pencil', 'LoanAcc'), renderTemplate(formTmpl, {loanAccId: self._id})).maximize();
// $.unblockUI();
// }, 100);
}).catch(function (err) {
console.log(err.message);
});
},
'click .js-destroy' (event, instance) {
destroyAction(
LoanAcc,
{_id: this._id},
{title: 'LoanAcc', itemTitle: this._id}
);
},
'click .js-display' (event, instance) {
alertify.loanAccShow(fa('eye', 'LoanAcc'), renderTemplate(showTmpl, this));
},
'dblclick tbody > tr': function (event) {
var dataTable = $(event.target).closest('table').DataTable();
var rowData = dataTable.row(event.currentTarget).data();
let params = {
clientId: FlowRouter.getParam('clientId'),
loanAccId: rowData._id
};
FlowRouter.go('microfis.repayment', params);
}
});
// Product Form
productFormTmpl.helpers({
productSchema(){
return LoanAcc.productSchema;
},
});
productFormTmpl.events({
'change [name="productId"]'(event, instance){
let productId = event.currentTarget.value;
Session.set('productDoc', null);
if (productId) {
$.blockUI();
lookupProduct.callPromise({
_id: productId
}).then(function (result) {
Session.set('productDoc', result);
Meteor.setTimeout(function () {
$.unblockUI();
}, 100);
}).catch(function (err) {
console.log(err.message);
});
}
},
'click .btn-default'(event, instance){
alertify.loanAccProduct().close();
}
});
productFormTmpl.onDestroyed(function () {
Session.set('productDoc', null);
});
AutoForm.hooks({
Microfis_loanAccProductForm: {
onSubmit: function (insertDoc, updateDoc, currentDoc) {
this.event.preventDefault();
this.done();
},
onSuccess: function (formType, result) {
alertify.loanAcc(fa('plus', 'LoanAcc'), renderTemplate(formTmpl)).maximize();
},
onError: function (formType, error) {
displayError(error.message);
}
}
});
// Form
formTmpl.onCreated(function () {
this.autorun(()=> {
let currentData = Template.currentData();
if (currentData) {
this.subscribe('microfis.loanAccById', currentData.loanAccId);
}
});
});
formTmpl.onRendered(function () {
let $submitDate = $('[name="submitDate"]');
let $disbursementDate = $('[name="disbursementDate"]');
let $firstRepaymentDate = $('[name="firstRepaymentDate"]');
let productDoc = Session.get('productDoc');
$disbursementDate.data("DateTimePicker").minDate(moment(productDoc.startDate).startOf('day'));
$disbursementDate.data("DateTimePicker").maxDate(moment(productDoc.endDate).endOf('day'));
// LoanAcc date change
$disbursementDate.on("dp.change", function (e) {
$submitDate.data("DateTimePicker").maxDate(moment(e.date).startOf('day'));
$firstRepaymentDate.data("DateTimePicker").minDate(moment(e.date).add(1, 'days').startOf('day'));
});
});
formTmpl.helpers({
dataHeader(){
return Session.get('productDoc');
},
collection(){
return LoanAcc;
},
data(){
let doc = {}, formType = 'insert';
let currentData = Template.currentData();
if (currentData) {
doc = LoanAcc.findOne({_id: currentData.loanAccId});
formType = 'update';
}
return {doc, formType};
},
});
formTmpl.onDestroyed(function () {
AutoForm.resetForm("Microfis_loanAccForm");
});
// Hook
let hooksObject = {
onSuccess (formType, result) {
alertify.loanAcc().close();
alertify.loanAccProduct().close();
displaySuccess();
},
onError (formType, error) {
displayError(error.message);
}
};
AutoForm.addHooks([
'Microfis_loanAccForm'
], hooksObject);
// Show
showTmpl.onCreated(function () {
let self = this;
self.dataLookup = new ReactiveVar(false);
self.autorun(function () {
let currentData = Template.currentData();
lookupLoanAcc.callPromise({
_id: currentData._id
}).then(function (result) {
self.dataLookup.set(result);
}).catch(function (err) {
console.log(err.message);
});
});
});
showTmpl.helpers({
data: function () {
let data = Template.instance().dataLookup.get();
// data.attachFileUrl = null;
// if (data.photo) {
// let file = Files.findOne(data.attachFile);
// data.attachFileUrl = file.url();
// }
return data;
}
});
|
const resEl = document.getElementById("res");
const x1 = prompt("Enter first number");
const x2 = prompt("Enter second number");
const res = x1 + x2;
resEl.innerHTML = res;
/* ============= Example 2 */
// Что не так с этой функцией
/*
function trimLower(text) {
return text.trim().toUpperCase();
}
trimLower("Hello");
trimLower(null);
*/
|
/*
* 判断终端设备类型
*/
function IsPC() {
var userAgentInfo = navigator.userAgent;
var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
var flag = "";
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag = Agents[v];
break;
}
}
//console.log(flag);
if (flag != "" && (flag == "Android" || flag == "iPhone" || flag == "SymbianOS" || flag == "Windows Phone")) {
//手机
//alert("手机");
} else if (flag != "" && (flag == "iPad" || flag == "iPod")) {
//ipad
//alert("ipad");
//window.location.href = "http://www.baidu.com";
} else {
//PC
//alert("电脑");
//window.location.href = "http://www.baidu.com";
}
}
IsPC();
|
/* eslint-disable import/extensions */
/**
* @description And gate is one of three many fundamental gate available in the simulator.
* The following class handles the logic and functioning of the AndGate simulator component
* @module AndGate
* @requires Scopes
* @requires Node
* @requires helpers
* @see helpers
* @see Node
* @summary the fundamental and gate
*/
import CircuitElement from './circuitElement.js';
import globalScope from './scopes.js';
import Node from './Node.js';
import { changeInputSize } from './helpers.js';
/**
* Class represent the AndGate
*/
class AndGate extends CircuitElement {
/**
* the and gate component
* @constructor
* @extends CircuitElement
* @param {number} x x coordinate of element
* @param {number} y y coordinate of element
* @param {object} scope is an instance of newCircuit which represents the current element scope
* @param {string} dir the default direction of the element
* @param {number} inputLength the number of nodes attached to element (or input)
* @param {number} bitWidth the number of bits transmitted through input line
*/
constructor(
x,
y,
scope = globalScope,
dir = 'RIGHT',
inputLength = 2,
bitWidth = 1,
) {
/** call the parent class circuitElement's constructor */
super(x, y, scope, dir, bitWidth);
/*
* this sets the width and height of the element if its rectangular
* and the reference point is at the center of the object.
* width and height define the X and Y distance from the center
*/
this.rectangleObject = false;
this.setDimensions(15, 20);
// array containing input nodes
this.inp = [];
this.inputSize = inputLength;
// if odd number of inputs in element
let yIndex;
if (inputLength % 2 === 1) {
// add one half of inputs
for (let i = 0; i < inputLength; i += 1) {
if (i < inputLength / 2 - 1) {
// add the first half of inputs
yIndex = -10 * (i + 1);
} else if (i === inputLength / 2 - 1) {
// add the middle input
yIndex = 0;
} else {
// the the remaining half of inputs
yIndex = 10 * (i + 1 - inputLength / 2 - 1);
}
// push items into input array
this.inp.push(new Node(-10, yIndex, 0, this));
}
} else {
// symmetrically add elements as no mid element
for (let i = 0; i < inputLength; i += 1) {
if (i < inputLength / 2) {
yIndex = -10 * (i + 1);
} else {
yIndex = 10 * (i + 1 - inputLength / 2);
}
// push item into input array
this.inp.push(new Node(-10, yIndex, 0, this));
}
}
// link the output with the component
this.output1 = new Node(20, 0, 1, this);
this.alwaysResolve = true;
this.verilogType = 'and';
this.tooltipText = 'And Gate Tooltip : Implements logical conjunction';
this.changeInputSize = changeInputSize;
}
}
export { AndGate };
|
import React, { Component } from "react";
import { Navbar, Nav } from "react-bootstrap";
class Menu extends Component {
render() {
return (
<>
<Navbar expand="lg" className="w-100 p-0 m-0 navbar transparent ">
<Navbar.Toggle className="navbar-toggler-menu" aria-controls="here" />
<Navbar.Collapse
className="collapse-menu"
id=" navbar transparent w-100 d-inline-flex "
>
<Nav className="justify-content-around navbar-menu transparent p-0 m-0 w-100">
<Nav.Link href="#home">
<a className="nav-link text-white">
<b>Choclates</b>
</a>
</Nav.Link>
<Nav.Link href="#home">
<a className="nav-link text-white">
<b>Cakes</b>
</a>
</Nav.Link>
<Nav.Link href="#home">
<a className="nav-link text-white">
<b>delicasies</b>
</a>
</Nav.Link>
<Nav.Link href="#home">
<a className="nav-link text-white">
<b>Smoor</b>
</a>
</Nav.Link>
<Nav.Link href="#home">
<a className="nav-link text-white">
<b>Cookies</b>
</a>
</Nav.Link>
<Nav.Link href="#link">
<a className="nav-link text-white">
<b>Crisps</b>
</a>
</Nav.Link>
<Nav.Link href="#home">
<a className="nav-link text-white">
<b>Cooking</b>
</a>
</Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
</>
);
}
}
export default Menu;
|
// FOR > data awal ke akhir
const cars = ['Honda', 'Toyota', 'Suzuki', 'Daihatsu', 'Ford']
for(let i = 0; i < cars.length; i++){
console.log(`${[i]} - ${cars[i]}`);
}
// FOREACH
cars.forEach(function(r, i, a) { // (variabel/isi, index, array)
console.log(`${i} - ${r}`);
console.log(a);
})
// MAP object
const users = [
{id: 1, name: 'Alex'},
{id: 2, name: 'Bella'},
{id: 3, name: 'Carl'},
{id: 4, name: 'Daniel'},
]
const ids = users.map(function(user) {
return user.id
})
console.log(ids);
// for > cari key dan value
const user = {
firstName: 'Alex',
lastName: 'Gordon',
age: 20
}
for(let x in user){
console.log(`${x} : ${user[x]}`);
}
|
import * as R from "ramda";
import uuidv1 from "uuid/v1";
import { createServices } from "./services";
import { transforms } from "./transforms";
export const pages = {
home: {
id: "HomePage",
tab: "Home"
},
beerList: {
id: "BeerListPage",
tab: "Beer"
},
beerDetails: {
id: "BeerDetailsPage",
tab: "Beer"
},
breweryList: {
id: "BreweryListPage",
tab: "Brewery"
},
breweryDetails: {
id: "BreweryDetailsPage",
tab: "Brewery"
},
breweryBeerList: {
id: "BreweryBeerListPage",
tab: "Brewery"
},
breweryBeerDetails: {
id: "BreweryBeerDetailsPage",
tab: "Brewery"
}
};
export const createNavigation = (update, withLatestModel) => {
const services = createServices();
const navigateToBeerList = () => withLatestModel(model => {
if (model.beerList) {
update(
transforms.navigate(pages.beerList)
);
}
else {
const uuid = uuidv1();
update(
R.pipe(
transforms.uuid(uuid),
transforms.pleaseWaitBegin
)
);
services.loadBeerList().then(beerList => withLatestModel(model => {
if (model.uuid === uuid) {
update(
R.pipe(
transforms.beerList(beerList),
transforms.navigate(pages.beerList),
transforms.pleaseWaitEnd
)
)
}
}));
}
});
const navigateToBreweryList = params => withLatestModel(model => {
if (model.breweryList) {
update(
transforms.navigate(pages.breweryList, params)
);
}
else {
const uuid = uuidv1();
update(
R.pipe(
transforms.uuid(uuid),
transforms.pleaseWaitBegin
)
);
services.loadBreweryList().then(breweryList => withLatestModel(model => {
if (model.uuid === uuid) {
update(
R.pipe(
transforms.breweryList(breweryList),
transforms.navigate(pages.breweryList, params),
transforms.pleaseWaitEnd
)
)
}
}));
}
});
const trBreweryList = breweryList =>
R.pipe(
transforms.breweryList(breweryList),
transforms.pleaseWaitEnd
);
const trBrewery = params =>
R.pipe(
transforms.brewery(params),
transforms.navigate(pages.breweryDetails, params)
);
const navigateToBreweryDetails = params => withLatestModel(model => {
R.applyTo(
model,
R.ifElse(
R.has("breweryList"),
R.partial(update, [trBrewery(params)]),
() => {
update(transforms.pleaseWaitBegin);
services.loadBreweryList().then(
R.pipe(
trBreweryList,
R.o(trBrewery(params)),
update
)
);
}
)
);
});
const navigateToBreweryBeerList = params => withLatestModel(model => {
if (model.breweryList && model.brewery.id === params.breweryId && model.brewery.beerList) {
update(
transforms.navigate(pages.breweryBeerList, params)
);
}
else {
update(transforms.pleaseWaitBegin);
Promise.all([services.loadBreweryList(), services.loadBeerList(params.breweryId)]).then(values => {
const breweryList = values[0];
const beerList = values[1];
update(
R.pipe(
transforms.breweryList(breweryList),
transforms.brewery(params),
transforms.breweryBeerList(params, beerList),
transforms.navigate(pages.breweryBeerList, params),
transforms.pleaseWaitEnd
)
);
});
}
});
const navigateToBreweryBeerDetails = params => withLatestModel(model => {
if (model.breweryList && model.brewery.id === params.breweryId && model.brewery.beerList) {
update(
transforms.navigate(pages.breweryBeerDetails, params)
);
}
else {
update(transforms.pleaseWaitBegin);
Promise.all([services.loadBreweryList(), services.loadBeerList(params.breweryId)]).then(values => {
const breweryList = values[0];
const beerList = values[1];
update(
R.pipe(
transforms.breweryList(breweryList),
transforms.brewery(params),
transforms.breweryBeerList(params, beerList),
transforms.navigate(pages.breweryBeerDetails, params),
transforms.pleaseWaitEnd
)
);
});
}
});
const navigateTo = page => params => update(transforms.navigate(page, params));
return {
navigateToHome: navigateTo(pages.home),
navigateToBeerList,
navigateToBeerDetails: navigateTo(pages.beerDetails),
navigateToBreweryList,
navigateToBreweryDetails,
navigateToBreweryBeerList,
navigateToBreweryBeerDetails
};
};
|
import React, { Component } from 'react';
import {Link} from 'react-router-dom';
import 'react-bootstrap';
import {loginUser} from './server/Server.js'
class Login extends Component{
constructor(props) {
super(props);
this.state={
email:"",
pass:"",
resp:"",
authText:""
}
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePassChange = this.handlePassChange.bind(this);
}
handleLoginUser(e){
e.preventDefault();
loginUser(this.state.email,this.state.pass,
(text,resp)=>this.setState({resp:[text,resp]}))
debugger;
}
handleEmailChange(event) {
event.preventDefault();
this.setState({email: event.target.value});
}
handlePassChange(event) {
event.preventDefault();
this.setState({pass: event.target.value});
}
render() {
if(this.state.resp!==""){
if(this.state.resp.code=="UserNotConfirmedException"){
authText="User is not confirmed"
}
}
if(this.state.resp[0]){
if(this.state.resp[0][0]=="logged-in"){
var data = this.state.resp[0];
this.props.setUser(this.state.resp[0]);
return(
<div>
<section className="mbr-section mbr-after-navbar register-after-navbar" id="form1-4">
<div className="mbr-section mbr-section__container mbr-section__container--middle">
<div className="container">
<div className="row">
<div className="col-xs-12 text-xs-center">
<Link to={{pathname:'/',state:{user:data}}} className="btn link">Successfully Logged In!</Link>
</div>
</div>
</div>
</div>
</section>
</div>
)
}
}
return (
<div>
<section className="engine"><a rel="external" href="#">Mobirise</a></section>
<section className="mbr-section mbr-after-navbar register-after-navbar" id="form1-4">
<div className="mbr-section mbr-section__container mbr-section__container--middle">
<div className="container">
<div className="row">
<div className="col-xs-12 text-xs-center">
<h3 className="mbr-section-title display-2">LOGIN</h3>
<small className="mbr-section-subtitle">comment on art, buy art, view orders, sign up for events...</small>
</div>
</div>
</div>
</div>
<div className="mbr-section mbr-section-nopadding">
<div className="container">
<Link to="/authenticate" className="btn btn-white btn-white-outline">Authenticate User</Link>
<div className="row">
<div className="col-xs-12 col-lg-10 col-lg-offset-1" data-form-type="formoid">
<form action="#" method="post" data-form-title="CONTACT FORM">
<div className="row row-sm-offset">
<div className="col-xs-12 col-md-4">
<div className="form-group">
<label className="form-control-label">Email<span className="form-asterisk">*</span></label>
<input className="form-control" value={this.state.email} onChange={this.handleEmailChange}/>
</div>
</div>
<div className="col-xs-12 col-md-4">
<div className="form-group">
<label className="form-control-label">Password<span className="form-asterisk">*</span></label>
<input className="form-control" value={this.state.pass} onChange={this.handlePassChange}/>
</div>
</div>
</div>
<div><button type="submit" className="btn btn-primary" onClick={(e) => this.handleLoginUser(e)}>LOGIN</button></div>
</form>
</div>
</div>
</div>
</div>
</section>
<footer className="mbr-small-footer mbr-section mbr-section-nopadding register-footer-custom" id="footer1-2">
<div className="container">
<p className="text-xs-center">Copyright (c) 2016 Artworking</p>
</div>
</footer>
</div>
)
}
}
export default Login
|
import PrismService from "../../services/prism.servise";
export const UI_CHANGE_THEME = 'UI_CHANGE_THEME'
export const UI_PRISM_SHOW_LOADER = 'UI_PRISM_SHOW_LOADER'
export const UI_PRISM_HIDE_LOADER = 'UI_PRISM_HIDE_LOADER'
export const uiChangeTheme = (theme) => ({
type: UI_CHANGE_THEME,
payload: {
theme
}
})
export const uiPrismShowLoader = (payload) => ({
type: UI_PRISM_SHOW_LOADER,
payload
})
export const uiPrismHideLoader = (payload) => ({
type: UI_PRISM_HIDE_LOADER,
payload
})
export const uiChangeThemeInDome = (theme) => {
return (dispatch) => {
dispatch(uiPrismShowLoader())
PrismService.changeTheme(theme)
.then(theme => {
dispatch(uiChangeTheme(theme));
})
.catch(console.error)
.finally(() => dispatch(uiPrismHideLoader()))
};
}
|
import React, { Component } from 'react';
import Expo, { DangerZone } from 'expo';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as ExpoPixi from 'expo-pixi';
import {
StyleSheet,
View,
Dimensions,
TouchableOpacity,
} from 'react-native';
import { Button } from '../../components/button';
import { SuccessModal } from '../../components/success-modal';
import { Container, ButtonContainer, Label } from './styles';
import { Actions } from './actions';
const { Lottie } = DangerZone;
class Signature extends Component {
static navigationOptions = {
title: 'Firma digital',
headerTitleStyle: { color: '#454F63' },
headerStyle: {
backgroundColor: '#fff',
elevation: 6,
borderBottomWidth: 0,
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 3,
},
shadowOpacity: 0.27,
shadowRadius: 4.65
}
};
constructor(props) {
super(props);
this.state = {
animation: true
};
}
componentDidMount() {
this.playAnimation();
}
playAnimation = () => {
if (this.a) {
this.a.play();
}
};
onReady = () => {
console.log('ready!');
};
successModal = () => {
const { navigation, reducer } = this.props;
return (
<SuccessModal
visible={reducer.isSignatureSuccess}
onAcceptPress={() => { actions.closeModalSignatureSuccess(); navigation.goBack(); }}
onRequestClose={() => { actions.closeModalSignatureSuccess(); navigation.goBack(); }}
title="¡Pedido entregado!"
subtitle="Gracias por utilizar nuestro servicio"
/>
);
};
showAnimation = () => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<TouchableOpacity
style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}
onPress={() => this.setState({ animation: false })}
>
<Lottie
ref={a => this.a = a }
style={{
flex: 1,
width: Dimensions.get('window').width,
backgroundColor: 'transparent',
alignItems: 'center',
justifyContent: 'center'
}}
source={require('../../assets/pencil-animation.json')}
/>
<Label>
Necesitamos la firma de tu cliente para saber que recibió
correctamente su pedido, toca la pantalla para empezar.
</Label>
</TouchableOpacity>
</View>
);
saveCanvas = async () => {
const result = await this.sketch.takeSnapshotAsync({
format: 'jpeg',
quality: 0.1,
});
console.log(result.uri);
};
render() {
const { animation } = this.state;
const { reducer } = this.props;
return animation ? (
this.showAnimation()
) : (
<Container>
<Container>
<View style={styles.sketchContainer}>
<ExpoPixi.Signature
ref={ref => (this.sketch = ref)}
style={styles.sketch}
strokeAlpha={1}
onReady={this.onReady}
/>
</View>
</Container>
<ButtonContainer>
<Button
width={Dimensions.get('window').width / 2 - 30}
color="#444F63"
radius
title="DESHACER"
onPress={() => {
this.sketch.clear();
}}
/>
<Button
width={Dimensions.get('window').width / 2 - 30}
color="#ff7043"
radius
onPress={this.saveCanvas}
title="FIRMAR ENTREGA"
loading={reducer.isFetching}
/>
</ButtonContainer>
</Container>
);
}
}
const styles = StyleSheet.create({
sketch: {
flex: 1
},
sketchContainer: {
height: '100%'
},
});
function mapStateToProps(state) {
return {
reducer: state.signatureReducer,
global: state.globalReducer
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({ ...Actions }, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Signature);
|
NameIDBuilder = Java.type("org.opensaml.saml.saml2.core.impl.NameIDBuilder");
XMLObjectAttributeValue = Java.type("net.shibboleth.idp.attribute.XMLObjectAttributeValue");
AuthnRequest = Java.type("org.opensaml.saml.saml2.core.AuthnRequest");
logger = Java.type("org.slf4j.LoggerFactory").getLogger("net.shibboleth.idp.attribute");
inboundMessage = profileContext.getInboundMessageContext().getMessage();
if (inboundMessage instanceof AuthnRequest
&& inboundMessage.getNameIDPolicy() != null
&& inboundMessage.getNameIDPolicy().getSPNameQualifier() != null) {
recipientId = inboundMessage.getNameIDPolicy().getSPNameQualifier();
} else {
recipientId = resolutionContext.getAttributeRecipientID();
}
persistentIds = persistentId.getValues().iterator();
while (persistentIds.hasNext()) {
pai = persistentIds.next();
if (pai.startsWith(recipientId + "|")) {
logger.info("Found a persistentId attribute value for {}", recipientId);
matches = pai.match(/^([^\|]+)\|([^\|]+)\|(.*)$/);
logger.info("Creating a NameID for {}", matches[1]);
nameIdBuilder = new NameIDBuilder();
nameIdObject = nameIdBuilder.buildObject();
nameIdObject.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
nameIdObject.setNameQualifier(matches[2]);
nameIdObject.setSPNameQualifier(matches[1]);
nameIdObject.setValue(matches[3]);
nameIdAttributeValue = new XMLObjectAttributeValue(nameIdObject);
nameId.addValue(nameIdAttributeValue);
break;
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ContainerFactory_1 = require("../utilities/ContainerFactory");
const ArtWork_1 = require("./ArtWork");
/**
* html上のページごとの漫画情報を管理する
*/
class Manga extends ArtWork_1.ArtWork {
constructor(pixivJson) {
super();
this.mangaContainerID = 'popup-manga';
this.pageNum = 0;
//elementのcss
this.mangaContainerCSS = ` background-color:black;
overflow-x:auto;
white-space:nowrap;
width: 100%;
height:auto;
top:0;
left:0;
`;
this.pixivJson = pixivJson;
this.pageNum = this.getPageNum(pixivJson);
this.imgArray = new Array(this.pageNum);
const factory = new ContainerFactory_1.ContainerFactory();
this.mangaContainer = factory.setId(this.mangaContainerID)
.setClass(this.className)
.setCSS(this.mangaContainerCSS)
.createDiv();
this.DELTASCALE = ('mozInnerScreenX' in window) ? 70 : 4;
}
adjustScreenSize(scale) {
const innerScreen = this.innerScreen;
innerScreen.style.width = `${window.innerWidth * scale}px`;
innerScreen.style.height = `${window.innerHeight * scale}px`;
}
/**
* 漫画をポップアップする
* @param innerContainer
* @param hrefElem
* @param json
* @param count
*/
popup(hasClass) {
this.innerScreen.style.display = 'block';
this.innerScreen.style.width = `${Number(this.innerScreen.style.maxWidth) * this.imgScale}px`;
this.innerScreen.style.height = `${Number(this.innerScreen.style.maxHeight) * this.imgScale}px`;
this.innerScreen.innerHTML = '';
this.innerScreen.style.backgroundColor = (hasClass) ? "rgb(255, 64, 96)" : "rgb(34, 34, 34)";
const firstPageURL = this.getImgUrl();
//各ページをセット
this.initImgArray(this.mangaContainer, firstPageURL);
this.innerScreen.appendChild(this.mangaContainer);
this.setScrool(this.mangaContainer, this.innerScreen, this.DELTASCALE);
}
/**
* imgエレメントの配列を作成し漫画の各ページを格納
* @param innerContainer
* @param mangaContainer
* @param manga
* @param primaryLink
* @param pageNum
*/
initImgArray(mangaContainer, firstPageURL) {
for (let i = 0; i < this.pageNum; i++) {
const imgElem = document.createElement('img');
imgElem.src = firstPageURL.replace('p0', 'p' + i);
imgElem.style.maxWidth = this.innerScreen.style.width;
imgElem.style.maxHeight = this.innerScreen.style.height;
imgElem.style.height = this.innerScreen.style.height;
imgElem.style.width = 'auto';
this.imgArray.push(imgElem);
mangaContainer.appendChild(imgElem);
}
}
/**
* mangaコンテナ上でスクロール機能を実現
* @param innerContainer
* @param mangaContainer
* @param manga
*/
setScrool(mangaContainer, innerContainer, deltaScale) {
this.mangaContainer.onwheel = function (e) {
if (e.deltaY < 0 && (innerContainer.getBoundingClientRect().top < 0)) {
innerContainer.scrollIntoView({ block: "start", behavior: "smooth" }); //aligning to top screen side on scrollUp if needed
}
else if (e.deltaY > 0 && (innerContainer.getBoundingClientRect().bottom > document.documentElement.clientHeight)) {
innerContainer.scrollIntoView({ block: "end", behavior: "smooth" }); //aligning to bottom screen side on scrollDown if needed
}
let scrlLft = mangaContainer.scrollLeft;
if ((scrlLft > 0 && e.deltaY < 0) || ((scrlLft < (mangaContainer.scrollWidth - mangaContainer.clientWidth)) && e.deltaY > 0)) {
e.preventDefault();
mangaContainer.scrollLeft += e.deltaY * deltaScale; // TODO - find better value for opera/chrome
}
};
}
/**
* 画像のURLを取得
* @param json
*/
getImgUrl() {
//url = url.replace(/\/...x...\//, '/600x600/'); //both feed and artist works case | TODO: '1200x1200' variant
return this.pixivJson.body.urls.regular.replace(/\/...x...\//, '/600x600/');
}
getPageNum(pixivJson) {
return Number(pixivJson.body.pageCount);
}
}
exports.Manga = Manga;
|
let progress = document.querySelector('.progress');
function showProgress(message, percent) {
console.log(message + ' (' + (percent * 100).toFixed(0) + '%)');
if (percent === 0) {
progress.style.display = 'block';
progress.classList.remove('progress_hidden');
}
progress.querySelector('.progress--message').innerHTML = message;
progress.querySelector('.progress--bar-container--bar').style.width = (percent * 100).toFixed(0) + '%';
if (percent === 1) {
progress.classList.add('progress_hidden');
setTimeout(function () {
progress.style.display = 'none';
}, 600);
}
}
|
(function(window, _, angular, undefined) {
'use strict';
/**
* @name OnhanhOrder
* @description OrderModule
*/
var orderModule = angular.module("app.order", []);
'use strict';
/**
* @name OnhanhOrder
* @description OrderConfig
*/
orderModule
.config(['$stateProvider',
function($stateProvider) {
// Use $stateProvider to configure your states.
$stateProvider
.state("order", {
title: "Order",
// Use a url of "/" to set a states as the "index".
url: "/order",
// Example of an inline template string. By default, templates
// will populate the ui-view within the parent state's template.
// For top level states, like this one, the parent template is
// the index.html file. So this template will be inserted into the
// ui-view within index.html.
controller: 'orderController',
templateUrl: '/web/order/list.html',
})
.state("order.detail", {
title: "Order Detail",
// Use a url of "/" to set a states as the "index".
url: "/:id",
// Example of an inline template string. By default, templates
// will populate the ui-view within the parent state's template.
// For top level states, like this one, the parent template is
// the index.html file. So this template will be inserted into the
// ui-view within index.html.
controller: 'orderDetailController',
templateUrl: '/web/order/detail.html',
});
}
]);
'use strict';
/**
* @name OnhanhOrder
* @description OrderServiceController
*/
orderModule
.service('Orders', [ 'resourceService',
function(resourceService) {
return resourceService('order');
}
]);
'use strict';
/**
* @name OnhanhOrder
* @description OrderDetailController
*/
orderModule
.controller('orderDetailController', [ '$scope', 'order',
function($scope, order) {
$scope.resource = order;
}
]);
'use strict';
/**
* @name OnhanhOrder
* @description OrderController
*/
orderModule
.controller('orderController', [ '$scope', 'orderGrid',
function($scope, orderGrid) {
$scope.gridOptions = orderGrid.gridOptions($scope);
$scope.load = function() {
$scope.gridOptions.load();
}
$scope.load();
}
]);
'use strict';
/**
* @name OnhanhOrder
* @description OrderServiceController
*/
orderModule
.service("orderGrid", ['Orders', function(Orders) {
return {
columns: [{
name: "action",
width: '23',
displayName: "",
enableSorting: false,
cellTemplate: [
'<div class="ui-grid-cell-contents" title="TOOLTIP"> ',
'<a ui-sref="order.detail({id: row.entity.id})"><i class="fa fa-pencil-square-o"></i></a>',
'</div>'
].join('')
},{
name: "id",
width: '150',
displayName: "Order ID",
cellTemplate: '<div class="ui-grid-cell-contents" title="TOOLTIP"><a ui-sref="order.detail({id: row.entity.id})">{{COL_FIELD}}</a> </div>'
},,{
name: "created_at",
displayName: "Date",
cellTemplate: '<div class="ui-grid-cell-contents" title="TOOLTIP"><span date-interval="{{COL_FIELD}}"></span></div>'
},{
name: "payment_status",
displayName: "Payment status",
},{
name: "fulfillment_status",
displayName: "Fulfillment status",
},{
name: "price",
displayName: "Total",
cellTemplate: '<div class="ui-grid-cell-contents" title="TOOLTIP">{{COL_FIELD | currency:"đ ":0}}</div>'
}],
gridOptions: function($scope) {
var options = $scope.options || {};
var defaults = {
selectionRowHeaderWidth: 35,
rowHeight: 35,
showGridFooter: false,
enableFiltering: false,
enableSorting: true,
exporterMenuCsv: false,
enableGridMenu: false,
useExternalFiltering: false,
columnDefs: this.columns,
enableCellEdit: false,
enableColumnMenus: false,
enableScrollbars: false,
enableHorizontalScrollbar: 1,
enableVerticalScrollbar: 0,
load: function(params, fn) {
var res = Orders.get(params, function() {
this.data= res.data;
this.totalItems = res.total;
fn ? fn : "";
}.bind(this));
},
onRegisterApi: function(gridApi) {
this.api = gridApi;
if($scope.saveRow) {
gridApi.rowEdit.on.saveRow($scope, $scope.saveRow);
}
}
}
return angular.extend(defaults, options);
}
}
}]);
})(window, _, window.angular);
|
var { defineSupportCode } = require('cucumber');
const reportLogger = require('../../../../codeceptCommon/reportLogger');
const BrowserWaits = require('../../../support/customWaits');
const SoftAssert = require('../../../../ngIntegration/util/softAssert');
const allWorkPage = require('../../pageObjects/workAllocation/allWorkPage');
const ArrayUtil = require('../../../utils/ArrayUtil');
const { DataTableArgument } = require('codeceptjs');
const filtersToIgnore = {
'Priority': 'Is out of scope and will be removed as part of https://tools.hmcts.net/jira/browse/EUI-4809',
'Task type':'Is to be includes only in 2.1 till the it will be ignored in test' ,
'Person':'Change in component, test needs update to validate new component'
}
Then('I see filter {string} is displayed in all work page', async function(filterItem){
if (Object.keys(filtersToIgnore).includes(filterItem)){
reportLogger.AddMessage(`${filterItem} in test ignored for reason : ${filtersToIgnore[filterItem]}`);
return;
}
expect(await allWorkPage.isFilterItemDisplayed(filterItem) ).to.be.true
});
Then('I see filter {string} is not displayed in all work page', async function (filterItem) {
if (Object.keys(filtersToIgnore).includes(filterItem)) {
reportLogger.AddMessage(`${filterItem} in test ignored for reason : ${filtersToIgnore[filterItem]}`);
return;
}
expect(await allWorkPage.isFilterItemDisplayed(filterItem)).to.be.false
});
Then('I see filter {string} is enabled in all work page', async function (filterItem) {
if (Object.keys(filtersToIgnore).includes(filterItem)) {
reportLogger.AddMessage(`${filterItem} in test ignored for reason : ${filtersToIgnore[filterItem]}`);
return;
}
expect(await allWorkPage.isFilterItemEnbled(filterItem)).to.be.true
});
Then('I see filter {string} is disabled in all work page', async function (filterItem) {
if (Object.keys(filtersToIgnore).includes(filterItem)) {
reportLogger.AddMessage(`${filterItem} in test ignored for reason : ${filtersToIgnore[filterItem]}`);
return;
}
expect(await allWorkPage.isFilterItemEnbled(filterItem)).to.be.false
});
Then('I validate filter item {string} select or radio options present in all work page', async function (filterItem, datatable){
reportLogger.reportDatatable(datatable)
const actualOption = await allWorkPage.getFilterSelectOrRadioOptions(filterItem);
const hashes = datatable.parse().hashes();
for (const hash of hashes){
expect(actualOption).to.includes(hash.option)
}
});
Then('I validate filter item {string} select or radio has option {string} in all work page', async function (filterItem, filterOptions) {
const actualOption = await allWorkPage.getFilterSelectOrRadioOptions(filterItem);
reportLogger.AddMessage(`${filterItem} options displayed : ${JSON.stringify(actualOption)}`);
for (const option of filterOptions.split(',')) {
expect(actualOption).to.includes(option)
}
});
When('I select filter item {string} select or radio option {string} in all work page', async function (filterItem, option) {
if (Object.keys(filtersToIgnore).includes(filterItem)) {
reportLogger.AddMessage(`${filterItem} in test ignored for reason : ${filtersToIgnore[filterItem]}`);
return;
}
const optionElement = await allWorkPage.setFilterSelectOrRadioOptions(filterItem, option);
});
When('I input filter item {string} input text {string} in all work page', async function (filterItem, inputText) {
if (Object.keys(filtersToIgnore).includes(filterItem)) {
reportLogger.AddMessage(`${filterItem} in test ignored for reason : ${filtersToIgnore[filterItem]}`);
return;
}
await allWorkPage.inputFilterItem(filterItem, inputText);
});
When('I click Apply filter button in all work page', async function(){
await allWorkPage.filterApplyBtn.click();
});
Then('I validate Apply filter button in enabled in all work page', async function () {
expect(await allWorkPage.filterApplyBtn.isEnabled()).to.be.true;
});
Then('I validate Apply filter button in disabled in all work page', async function () {
expect(await allWorkPage.filterApplyBtn.isEnabled()).to.be.false;
});
When('I click Reset filter button in all work page', async function () {
await allWorkPage.filterResetBtn.click();
});
Then('I see location search input is enabled in all work filters', async function () {
expect(await allWorkPage.FILTER_ITEMS['Location search'].isPresent(),'Search input not present').to.be.true;
expect(await allWorkPage.FILTER_ITEMS['Location search'].isDisplayed(),'Search input not displayed').to.be.true;
expect(await allWorkPage.FILTER_ITEMS['Location search'].isEnabled(),'Search input not enabled').to.be.true;
});
Then('I see location search input is disabled in all work filters', async function () {
expect(await allWorkPage.FILTER_ITEMS['Location search'].isPresent(), 'Search input not present').to.be.true;
expect(await allWorkPage.FILTER_ITEMS['Location search'].isDisplayed(), 'Search input not displayed').to.be.true;
expect(await allWorkPage.FILTER_ITEMS['Location search'].isEnabled(), 'Search input not disabled').to.be.false;
});
When('I enter location search {string} in all work filter', async function (searchTerm) {
await allWorkPage.FILTER_ITEMS['Location search'].clear();
await allWorkPage.FILTER_ITEMS['Location search'].sendKeys(searchTerm);
});
Then('I see location search results in all work filter', async function (dataTable) {
reportLogger.reportDatatable(dataTable)
const locationsHashes = dataTable.parse().hashes();
const expectdLocations = [];
for (const locationsHash of locationsHashes){
expectdLocations.push(locationsHash.location);
}
await BrowserWaits.retryWithActionCallback(async () => {
const actualResults = await allWorkPage.getSearchResults();
for (const expectedLoc of expectdLocations) {
expect(await allWorkPage.isSearchResultPresent(expectedLoc), `Search result ${expectedLoc} not found in actual results "${actualResults}"`).to.be.true
}
});
});
When('I select location search result {string} in all work filter', async function (location) {
await allWorkPage.selectSearchResult(location);
});
Then('I see location {string} selected in all work filter', async function (expectedValue) {
const inputValue = await allWorkPage.FILTER_ITEMS['Location search'].getAttribute('value');
expect(inputValue).to.includes(expectedValue)
});
|
import db from '../../../db/index.js'
import { getUserFromLoginSession } from '../user'
export const readEatRows = async (userId) => {
return new Promise((resolve, reject) => {
db.query(`
SELECT * FROM eat
WHERE user_id = $1 AND time > current_date - interval '6 day'
ORDER BY time DESC
`
, [userId]
, (err, dbRes) => {
if (err) {
console.log('readEatRows err:', err)
reject(err)
} else {
resolve(dbRes)
}
})
})
}
export default async function read(req, res) {
try {
const user = await getUserFromLoginSession(req)
const dbRes = await readEatRows(user.user_id)
res.status(200).send(dbRes.rows)
} catch (error) {
console.log('api/eat/read error:', error)
res.status(500).end(error)
}
}
|
import React from 'react';
import Amplify, { API, Storage, Predictions, PubSub } from 'aws-amplify';
import ModuleCanvas from './canvas';
import ModuleLoading from './loading';
import ModuleWinner from './winner';
import {DRAWTIME, DOODLES} from '../../../constants';
import {getImageByteData} from '../../../helper';
import {PubSubEvents} from '../../../events';
import * as mutations from '../../../graphql/mutations';
import { AmazonAIPredictionsProvider } from '@aws-amplify/predictions';
import './index.css';
Amplify.addPluggable(new AmazonAIPredictionsProvider());
export default class App extends React.Component {
constructor(props) {
super(props);
//this.finishRound = this.finishRound.bind(this);
this.myCanvas = React.createRef();
this.state = {
time:DRAWTIME,
};
}
componentDidMount(){
console.log("Game: Comp did mount");
this.startTimer();
//Hub.listen(EVENTS.FINISHED_DRAWING, this.finishRound);
}
componentDidUpdate(prevProps) {
if(prevProps.doodle && this.props.doodle && prevProps.doodle.object !== this.props.doodle.object){
this.startTimer();
}
}
startTimer(){
if(this.timer){
clearInterval(this.timer);
}
this.timer = setInterval(() => this.countDown(),1000);
}
countDown(){
let myRemaining = this.state.time-1;
if(myRemaining === 0){
this.finishRound();
}else{
this.setState({ time: myRemaining });
}
}
finishRound(){
console.log("finished Round");
clearInterval(this.timer);
let imageBytes = getImageByteData("canvas", 0.5); //this.myCanvas.current.getImageByteData(0.5);
let file = "doodles/"+this.props.doodle.object.toLocaleLowerCase()+"/"+this.props.player.room+'_'+this.props.player.uuid+'.jpg';
this.uploadToS3(file,imageBytes);
//this.uploadToAPI(imageBytes);
}
// async uploadToAPI(data){
// let myDoodle = DOODLES[this.props.round].object.toLocaleLowerCase();
// let drawing = await API.graphql({query:mutations.createDrawing, variables:{name:myDoodle, imageData:data}, authMode: 'AWS_IAM'});
// console.log("I've called the new API");
// console.log(drawing);
// //this.props.addedPlayer(player.data.createPlayer);
// }
uploadToS3(file,data){
Storage.put(file, data)
.then (result => {
this.props.handleFinishedDrawing();
this.setState({time:DRAWTIME});
//this.getScore({bytes:data}, result.key);
}) // {key: "gameid/playerindex.txt"}
.catch(err => {
window.alert("Failed to upload doodle: ", err);
console.log(err)
});
}
render(){
let view;
if(this.props.winner){
view = <ModuleWinner player={this.props.winner}/>;
}else if(this.props.roundEnded){
view = <ModuleLoading/>;
}else{
view = <ModuleCanvas ref={this.myCanvas} finishRound={this.finishRound.bind(this)} time={this.state.time} player={this.props.player} doodle={this.props.doodle}/>
}
return(
<div>
{view}
</div>
)
}
}
|
/**
sb2musicxml.js Convert scratch project to MusicXML for singing voice synthesis
MIT License
Copyright (c) 2018 Hiroaki Kawashima
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.
*/
const divisions = 24;
const mapNoteDuration = {
'4' : divisions * 4,
'3' : divisions * 3,
'2' : divisions * 2,
'1+1\/2' : divisions * 3 / 2,
'1' : divisions,
'23\/24' : divisions * 23 / 24,
'11\/12' : divisions * 11 / 12,
'7\/8' : divisions * 7 / 8,
'5\/6' : divisions * 5 / 6,
'3\/4' : divisions * 3 / 4,
'2\/3' : divisions * 2 / 3,
'1\/2' : divisions / 2,
'3\/8' : divisions * 3 / 8,
'1\/3' : divisions / 3,
'1\/4' : divisions / 4,
'1\/6' : divisions / 6,
'1\/8' : divisions / 8,
'1\/12' : divisions / 12,
'1\/24' : divisions / 24
}
const chromaticStep = ['C', 'C', 'D', 'D', 'E', 'F', 'F', 'G', 'G', 'A', 'A', 'B'];
const chromaticAlter = [0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0];
const resultSuffix = 'song';
const restSymbolForLyric = '_'; // Symbol used for 'rest (pause)' in lyric
const mouth2soundMapJP = {
a: ['あ', 'か', 'さ', 'た', 'な', 'は', 'や', 'ら', 'が', 'ざ', 'だ', 'ゃ', 'ぁ'],
ma: ['ま', 'ば', 'ぱ'],
ua: ['わ'],
i: ['い', 'き', 'し', 'ち', 'に', 'ひ', 'り', 'ぎ', 'じ', 'ぢ', 'ぃ'],
mi: ['み', 'び', 'ぴ'],
u: ['う', 'く', 'す', 'つ', 'ぬ', 'ふ', 'ゆ', 'る', 'ぐ', 'ず', 'づ', 'ゅ', 'ぅ'],
mu: ['む', 'ぶ', 'ぷ'],
e: ['え', 'け', 'せ', 'て', 'ね', 'へ', 'れ', 'げ', 'ぜ', 'で', 'ぇ'],
me: ['め', 'べ', 'ぺ'],
o: ['お', 'こ', 'そ', 'と', 'の', 'ほ', 'よ', 'ろ', 'ご', 'ぞ', 'ど', 'ょ', 'ぉ'],
mo: ['も', 'ぼ', 'ぽ'],
uo: ['を'],
n: ['ん']
};
// Manage mapping from lyric to mouth shape symbol
// Constructor (arg: mouth2sound map)
Lyric2Mouth = function (m2sMap) {
this.mouth2sound = m2sMap;
// Create sound2mouth mapping
this.sound2mouth = {};
this.sound2mouth[restSymbolForLyric] = restSymbolForLyric;
Object.keys(this.mouth2sound).forEach(function (key) {
this.mouth2sound[key].forEach(function (val) {
this.sound2mouth[val] = key;
}.bind(this)); // or use var _this = this;
}.bind(this));
this.prevMouthChar = restSymbolForLyric;
}
// Convert lyric to mouth shape symbol
Lyric2Mouth.prototype.convert = function (lyric) {
var mouthChar = '';
var tmpArray = [];
lyric.split('').forEach(function (mchar) {
if (mchar == 'ー' || mchar == 'っ') {
// if prev is consonant + vowel (such as 'ma'), extract only the vowel ('a')
mouthChar = prevMouthChar.split('').slice(-1)[0];
} else {
if (this.sound2mouth[mchar] === undefined) {
mouthChar = restSymbolForLyric;
} else {
mouthChar = this.sound2mouth[mchar];
}
}
if (mchar == 'ゃ' || mchar == 'ゅ' || mchar == 'ょ'
|| mchar == 'ぁ' || mchar =='ぃ' || mchar == 'ぅ' || mchar == 'ぇ' || mchar == 'ぉ') {
// console.log('overwrite ' + tmpArray.slice(-1)[0]); // this is only a view
tmpArray[tmpArray.length - 1] = mouthChar; // overwrite the previousMouthChar
} else {
tmpArray.push(mouthChar);
}
prevMouthChar = mouthChar;
}.bind(this));
return tmpArray.join('-');
}
// -----------------------------------------------------------------------
function handleFileSelect(evt) {
var files = evt.target.files;
var f = files[0];
filenameElm = document.getElementById('filename');
if (filenameElm != null) {
if (f == null) {
filenameElm.value = 'File is not selected';
return;
} else {
filenameElm.value = f.name;
}
}
JSZip.loadAsync(f) // Load zip file and extract json file
.then(function (loadfile) {
console.log('Loaded ZIP file. Extract JSON...');
return loadfile.file('project.json').async('string');
}).then(function (json) {
console.log('Loaded JSON. Extract scratch script...');
var obj = JSON.parse(json);
scriptArray = extractScratchScript(obj); // Find script part
if (scriptArray.length > 1) {
return convertSongScript2XML(scriptArray); // Convert to MusicXML
} else if (scriptArray.length == 0) {
throw new Error('Cannot find valid sprite. Sprite name needs to be "song".');
} else {
throw new Error('Cannot find valid sprite. Sprite needs to start with "when Green Flag clicked" followed by song data.');
}
}).then(function (xml) { // Convert xml object and output results
// Show the result area
var resultElm = document.getElementById('result');
if (resultElm == null) {
throw new Error('Cannot find div#result');
}
resultElm.style.display = 'block';
// Prepare xml file for download
var xmlString = (new XMLSerializer()).serializeToString(xml);
console.log(xmlString); // for debug
var dlXmlElm = document.getElementById('dl-xml');
if (dlXmlElm == null) {
throw new Error('Cannot find a#dl');
}
createXMLDownloadLink(dlXmlElm, xmlString, resultSuffix + '.xml');
// Prepare text files for download (timing, lyrics, mouth shape)
var typeList = ['timing', 'lyric', 'mouth'];
var dlElm = {};
var retJson = {};
for (var i in typeList) {
type = typeList[i];
dlElm[type] = document.getElementById('dl-' + type);
if (dlElm[type] != null) {
console.log('list type: ' + type);
if (Object.keys(retJson).length==0) { // create a list when required first time
retJson = convertXML2TimingList(xml);
console.log(retJson);
}
createTextDownloadLink(dlElm[type], retJson[type].join('\n'), resultSuffix + '-' + type + '.txt');
}
}
}).catch(function (error) {
alert(error);
});
}
//-----------------------------------------------------------------
// Create download link for XML
function createXMLDownloadLink(dlXmlElm, xmlString, resultFilename) {
if (window.navigator && window.navigator.msSaveBlob) { // for IE and Edge
dlXmlElm.addEventListener('click', function(e) {
e.preventDefault();
navigator.msSaveBlob( new Blob(['<?xml version="1.0" encoding="UTF-8"?>' + xmlString], {type:'text/xml'}), resultFilename );
}, false);
} else {
dlXmlElm.href = 'data:text/xml;charset=utf-8,' + encodeURIComponent(xmlString);
dlXmlElm.download = resultFilename;
}
}
// Create download link for text
function createTextDownloadLink(dlTextElm, textString, resultFilename) {
if (window.navigator && window.navigator.msSaveBlob) { // for IE and Edge
dlTextElm.addEventListener('click', function(e) {
e.preventDefault();
navigator.msSaveBlob( new Blob([textString], {type:'text/plain'}), resultFilename );
}, false);
} else {
dlTextElm.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(textString);
dlTextElm.download = resultFilename;
}
}
// Extract scratch script array
function extractScratchScript(obj) {
var scriptArray = [];
// for (var child of obj.children) { // cannot use for-of in IE
for (var i in obj.children) { //
child = obj.children[i];
if (child.objName === undefined || child.objName !== 'song') {
continue;
}
console.log(child.objName);
scriptArray = ['invalid song data']; // invalid array data with length 1
// for (var script of child.scripts) { // cannot use for-of in IE
for (var j in child.scripts) {
script = child.scripts[j];
if (script[2][0][0] !== 'whenGreenFlag') {
continue;
}
console.log(script[2][0][0]);
scriptArray = script[2];
}
}
return scriptArray;
}
// convert song data to xml
function convertSongScript2XML(scriptArray) {
var xmlSource = '<?xml version="1.0" encoding="UTF-8"?>'
+ '<!DOCTYPE score-partwise PUBLIC "-//Recordare//DTD MusicXML 2.0 Partwise//EN"'
+ ' "http://www.musicxml.org/dtds/partwise.dtd">'
+ '<score-partwise>'
+ ' <identification>'
+ ' <encoding>'
+ ' <software>Scratch - sb2musicxml</software>'
+ ' <encoding-date></encoding-date>'
+ ' </encoding>'
+ ' </identification>'
+ ' <part-list>'
+ ' <score-part id="P1">'
+ ' <part-name>MusicXML Part</part-name>'
+ ' </score-part>'
+ ' </part-list>'
+ ' <part id="P1">'
+ ' <measure number="1">'
+ ' <attributes>'
+ ' <divisions></divisions>'
+ ' <time>'
+ ' <beats></beats>'
+ ' <beat-type></beat-type>'
+ ' </time>'
+ ' </attributes>'
+ ' <sound/>'
+ ' </measure>'
+ ' </part>'
+ '</score-partwise>'
var xml = (new DOMParser()).parseFromString(xmlSource, 'text/xml');
// Insert date
var date = new Date();
//xml.getElementsByTagName('encoding-date')[0].textContent = date.toLocaleDateString().split('/').join('-');
xml.querySelector('encoding-date').textContent = [date.getFullYear(), ('0' + (date.getMonth() + 1)).slice(-2), ('0' + date.getDate()).slice(-2)].join('-');
// Default values (may be overwritten later)
var tempo = 110;
var beats = 2;
var beatType = 4;
var durationPerMeasure; // duration of a measure
xml.querySelector('divisions').textContent = divisions; // default divisions
xml.querySelector('sound').setAttribute('tempo', tempo); // default tempo
xml.querySelector('beats').textContent = beats; // default beats
xml.querySelector('beat-type').textContent = beatType; // default beat-type
// Start parsing
var measureNumber = 1;
var initialNoteFlag = true;
var cumSumDuration = 0 ; // cumulative duration to check whether a new measure needs to be created or not
var curMeasureElm = xml.querySelector('measure[number="1"]'); // current measure
var syllabicState = 'single'; // for English lyric
var reservedElmForNextMeasure = null;
// Create a note with sound
function _createSoundNote(step, alter, octave, duration, lyricText, syllabicState) {
var pitchElm = xml.createElement('pitch'); // pitch {step, alter, octave}
var stepElm = xml.createElement('step');
stepElm.textContent = step;
pitchElm.appendChild(stepElm);
if (alter != 0) {
var alterElm = xml.createElement('alter');
alterElm.textContent = alter;
pitchElm.appendChild(alterElm);
}
var octaveElm = xml.createElement('octave');
octaveElm.textContent = octave;
pitchElm.appendChild(octaveElm);
var durationElm = xml.createElement('duration'); // duration
durationElm.textContent = duration;
var lyricElm = xml.createElement('lyric'); // lyric {text, syllabic}
var textElm = xml.createElement('text');
textElm.textContent = lyricText;
lyricElm.appendChild(textElm);
var syllabicElm = xml.createElement('syllabic');
syllabicElm.textContent = syllabicState;
lyricElm.appendChild(syllabicElm);
var noteElm = xml.createElement('note'); // note {pitch, duration, lyric}
noteElm.appendChild(pitchElm);
noteElm.appendChild(durationElm);
noteElm.appendChild(lyricElm);
return noteElm;
}
// Create a new 'rest' note
function _createRestNote(duration) {
var durationElm = xml.createElement('duration'); // duration
durationElm.textContent = duration;
var noteElm = xml.createElement('note'); // note {rest, duration}
noteElm.appendChild(xml.createElement('rest'));
noteElm.appendChild(durationElm);
return noteElm;
}
// Create sound
function _createTempo(tempo) {
var soundElm = xml.createElement('sound');
soundElm.setAttribute('tempo', tempo);
return soundElm;
}
// Overwrite duration-related variables (this needs to be called when 'beatType' or 'beats' is updated)
function _updateDurationSettings() {
durationPerMeasure = divisions * (4 / beatType) * beats;
}
// Check the duration of current measure, and create new measure if necessary
// Also, add one empty measure with 'rest' if the initial note is NOT 'rest'
function _createNewMeasureIfNecessary(duration, restFlag) {
if (initialNoteFlag) {
if (restFlag) { // if initial note is 'rest'
cumSumDuration = 0; // reset cumSumDuration
} else { // if initial note is sound (not 'rest'), add one empty measure
curMeasureElm.appendChild(_createRestNote(durationPerMeasure));
cumSumDuration = durationPerMeasure; // enforce to create measure=2 immediately after this
}
initialNoteFlag = false;
}
cumSumDuration += duration;
if (cumSumDuration > durationPerMeasure) { // create new measure
curMeasureElm = xml.createElement('measure');
curMeasureElm.setAttribute('number', ++measureNumber); // increment number
if (reservedElmForNextMeasure !== null) {
curMeasureElm.appendChild(reservedElmForNextMeasure);
console.log('append reserved tempo')
reservedElmForNextMeasure = null;
}
xml.querySelector('part').appendChild(curMeasureElm);
cumSumDuration = duration;
}
}
// Find duration: variable or value
function _extractDuration(arrayOrValue) {
var duration = 0;
if (Array.isArray(arrayOrValue) && arrayOrValue.length > 0 && arrayOrValue[0] === 'readVariable') { // variable
duration = mapNoteDuration[arrayOrValue[1]];
} else if (arrayOrValue > 0) { // value
duration = arrayOrValue * divisions;
}
return duration;
}
_updateDurationSettings(); // update duration settings using default values
for (var i=0; i < scriptArray.length; i++) { // for (var i in scriptArray) {
if (i==0) continue; // skip
// Tempo and beat settings
if (scriptArray[i][0] === 'setTempoTo:') {
tempo = scriptArray[i][1];
console.log('tempo: ' + tempo);
if (cumSumDuration == durationPerMeasure) {
reservedElmForNextMeasure = _createTempo(tempo); // will add to the next measure
} else {
var soundElm = curMeasureElm.querySelector('sound');
if (soundElm) {
soundElm.setAttribute('tempo', tempo); // add or overwrite
} else {
curMeasureElm.appendChild(_createTempo(tempo)); // add immediately
}
console.log('add tempo immediately')
}
}
if (scriptArray[i][0] === 'setVar:to:' && scriptArray[i][1] === 'beats') {
beats = scriptArray[i][2];
console.log('beats: ' + beats);
xml.querySelector('beats').textContent = beats; // overwrite default beats
_updateDurationSettings();
}
if (scriptArray[i][0] === 'setVar:to:' && scriptArray[i][1] === 'beat-type') {
beatType = scriptArray[i][2];
console.log('beat-type: ' + beatType);
xml.querySelector('beat-type').textContent = beatType; // overwrite default beat-type
_updateDurationSettings();
}
// Add sound note
if (scriptArray[i][0] === 'noteOn:duration:elapsed:from:'){
var duration = _extractDuration(scriptArray[i][2]);
if (duration > 0) {
if (scriptArray[i-1][0] === 'say:') { // if lyric exists
try {
var midiPitch = scriptArray[i][1];
var step = chromaticStep[midiPitch % 12]; // chromatic step name ('C', etc.)
var alter = chromaticAlter[midiPitch % 12]; // -1, 0, 1
var octave = Math.floor(midiPitch / 12) - 1;
var lyricText = scriptArray[i-1][1];
if (lyricText.split('').slice(-1)[0] == '-') {
lyricText = lyricText.replace(/-$/, ''); // remove the last char '-'
if (syllabicState == 'single' || syllabicState == 'end') {
syllabicState = 'begin';
} else if (syllabicState == 'begin' || syllabicState == 'middle') {
syllabicState = 'middle';
}
} else {
if (syllabicState == 'single' || syllabicState == 'end') {
syllabicState = 'single';
} else if (syllabicState == 'begin' || syllabicState == 'middle') {
syllabicState = 'end';
}
}
console.log('midiPitch: ' + midiPitch + ', duration: ' + duration + ', ' + lyricText, ',' + syllabicState);
// --- Append node ---
var noteElm = _createSoundNote(step, alter, octave, duration, lyricText, syllabicState);
_createNewMeasureIfNecessary(duration, false);
curMeasureElm.appendChild(noteElm);
} catch (e) {
alert(e);
}
} else {
console.log('No "say" block at i= ' + i);
}
} else {
console.log('No variable at i= ' + i);
}
}
// Add rest
if (scriptArray[i][0] === 'rest:elapsed:from:') {
var duration = _extractDuration(scriptArray[i][1]);
if (duration > 0) {
try {
console.log('rest, duration: ' + duration);
// --- Append node ---
var noteElm = _createRestNote(duration);
_createNewMeasureIfNecessary(duration, true);
curMeasureElm.appendChild(noteElm);
} catch (e) {
alert(e);
}
} else {
console.log('No variable at i= ' + i);
}
}
}
return xml;
}
// Convert MusicXML to timing, lyric, and mouth shape data
function convertXML2TimingList(xml) {
var timingList = [];
var lyricList = [];
var mouthList = [];
var curTimeSec = 0; // physical time in sec
var tempo = 110; // default tempo
var secPerDivision;
var durationDiv; // duration of a note in division unit
var durationSec; // duration of a note in sec unit
console.log('lyric2mouth');
var lyric2mouth = new Lyric2Mouth(mouth2soundMapJP);
try {
// Parse measures in a document
var measureList = xml.getElementsByTagName('measure'); // querySelectorAll... which is faster?
for (var i=0; i < measureList.length; i++) {
var measureElm = measureList[i];
var soundElm = measureElm.querySelector('sound');
if (soundElm != null) {
var tempoAttr = soundElm.getAttribute('tempo');
if (tempoAttr != null) {
tempo = tempoAttr;
secPerDivision = 60 / tempo / divisions; // physical sec per tick (division)
console.log('tempo: ' + tempo + ', secPerDivision: ' + secPerDivision);
}
}
// Parse notes in a measure
var noteList = measureElm.getElementsByTagName('note');
for (var j=0; j < noteList.length; j++) {
var noteElm = noteList[j];
var durationElm = noteElm.querySelector('duration');
if (durationElm != null) {
// Duration
durationDiv = durationElm.textContent;
durationSec = secPerDivision * durationDiv;
timingList.push(curTimeSec); // start time of this note
// Lyrics
var textElm = noteElm.querySelector('lyric > text');
var lyric = (textElm != null ? textElm.textContent : restSymbolForLyric);
lyricList.push(lyric);
// Mouth shape
mouthList.push(lyric2mouth.convert(lyric));
curTimeSec += durationSec;
}
}
}
} catch (e){
alert(e);
}
return {timing: timingList, lyric: lyricList, mouth: mouthList};
}
document.getElementById('infile').addEventListener('change', handleFileSelect, false);
|
//angular.module('sharedServices').service('ServerErrorService', function ($uibModal, $scope) {
// var that = this;
// //$rootScope.$on('ServerErrorOccurred', function (data) {
// // var modalInstance = $uibModal.open({
// // animation: true,
// // templateUrl: 'App.views/errormodal.html',
// // controller: 'errorcontroller',
// // resolve: {
// // errorcontent: function () {
// // return data;
// // }
// // }
// // });
// // modalInstance.result.then(function () {
// // }, function () {
// // console.log('Modal dismissed at: ' + new Date());
// // });
// //});
//});
|
import QueryString from 'querystring';
import { isEmpty } from 'lodash';
import QueryDispatcher from './QueryDispatcher';
// Global Constants
const TTL = Infinity;
/**
* @typedef {Object} DocumentRecord
*
* @property {Record} data - immutable record
* @property {MetaObject} meta - meta object
*/
/**
* @typedef {Object} CollectionRecord
*
* @property {Record[]} data - array of immutable record
* @property {MetaObject} meta - meta object
*/
/**
* @typedef {Object} MetaObject
*
* @property {Object|Null} error error object
* @property {Boolean} isLoading - loading state flag
* @property {String} hashCode - unique hashcode for unique url resource
* @property {Number} updatedAt - last updated at unix timestamp
*/
/**
* @member QueryBuilder.props.options
*
* @typedef {Object} QueryOptions
*
* @property {Boolean} skipLoad skip loading state if previous data exists
*/
/**
* QueryBuilder is a class to construct a query dispatcher object. It can call to dispatch the object
*/
class QueryBuilder {
/**
* Constructor
* @param body {Object} request body
* @param dispatch {Function} dispatch
* @param hashCode {String} custom unique hashcode
* @param method {String} HTTP method
* @param mock {Function} mock resource function
* @param onError {Function} on error callback(error)
* @param onSuccess {Function} on success callback(data)
* @param options {QueryOptions} query options
* @param queryParams {Object} query params
* @param record {Record} immutable record
* @param state {Object} redux state
* @param transformer {Function} transformer function
* @param ttl {Number} ttl
* @param type {String} document or collection
* @param url {String} URL string
*/
constructor({
body,
dispatch,
hashCode,
method,
mock,
onError = () => {},
onSuccess = () => {},
options = { skipLoad: true },
queryParams,
record,
state,
transformer,
ttl = TTL,
type,
url,
} = {}) {
this.props = {
body,
dispatch,
hashCode,
method,
mock,
onError,
onSuccess,
options,
queryParams,
record,
state,
transformer,
ttl,
type,
url,
};
}
/**
* this method is fetch a request with body parameter
* @param body {Object}
* @returns {QueryBuilder}
*
* **Note: not valid for GET request
*/
body(body) {
this.props.body = body;
return this;
}
/**
* this method is to set a custom hashcode for the resource
* @param hashCode {String} custom hashcode
* @returns {QueryBuilder}
*/
hashCode(hashCode) {
if (typeof hashCode !== 'string' || hashCode.length < 5) {
throw new Error('hashCode must be a string and longer than 5 chars');
}
this.props.hashCode = hashCode;
return this;
}
/**
* This method is called before dispatching a failed action
* @param callback {Function} (data) will supply transformed data
* @returns {QueryBuilder}
*/
onError(callback) {
if (typeof callback !== 'function') {
throw new Error('callback must be a function');
}
this.props.onError = callback;
return this;
}
/**
* This method is called before dispatching a succeed action
* @param callback {Function} (data) will supply transformed data
* @returns {QueryBuilder}
*/
onSuccess(callback) {
if (typeof callback !== 'function') {
throw new Error('callback must be a function');
}
this.props.onSuccess = callback;
return this;
}
options(options) {
this.props.options = { ...this.props.options, ...options };
return this;
}
/**
* This method is transform object to query string parameters
* @param queryParams {Object}
* @returns {QueryBuilder}
*/
queryParams(queryParams) {
if (typeof queryParams !== 'object') {
throw new Error('queryParams must be an object');
}
this.props.queryParams = queryParams;
return this;
}
/**
* This method is execute query builder and default to mock for test environment
* @param test {Boolean} if true, mock resource instead
* @returns {DocumentRecord|CollectionRecord}
*/
run(test = false) {
const {
dispatch,
hashCode,
method,
mock,
onError,
onSuccess,
options,
queryParams,
record,
state,
transformer,
ttl,
type,
url,
} = this.props;
/* Use Mock data */
if (process.env.NODE_ENV === 'test') {
test = true; // eslint-disable-line no-param-reassign
}
return new QueryDispatcher({
dispatch,
hashCode,
method,
mock,
onError,
onSuccess,
options,
record,
state,
transformer,
ttl,
type,
url: (!isEmpty(queryParams)) ? `${url}?${QueryString.stringify(queryParams)}` : url,
}).query(test);
}
/**
* This method is to set TTL for query
* @param ttl {Number} - in milliseconds
* @returns {QueryBuilder}
*/
ttl(ttl) {
if (typeof ttl !== 'number') {
throw new Error('ttl must be a number');
}
this.props.ttl = ttl;
return this;
}
}
export default QueryBuilder;
|
#!/usr/bin/env node
const fs = require("fs");
const os = require("os");
const opn = require("opn");
const path = require("path");
const underscore = require("underscore");
const folders = require("platform-folders");
const settings = require("./settings");
const processor = require("./scripts/processor");
const config_utils = require("./scripts/config_utils");
const AUTH_DIR = path.join(folders.getDataHome(), settings.app_name);
const TOKEN_PATH = path.join(AUTH_DIR, settings.token_name);
const CREDENTIALS_PATH = path.join(AUTH_DIR, settings.credentials_name);
const DEFAULT_CONFIG_PATH = path.join(process.cwd(), settings.default_config_path, settings.default_config_name);
// List all files in a directory in Node.js recursively in a synchronous fashion
function walk_sync(dir, filelist) {
let files = fs.readdirSync(dir);
filelist = filelist || [];
files.forEach(function(file) {
let filepath = path.join(dir, file);
if (fs.statSync(filepath).isDirectory()) {
filelist = walk_sync(filepath, filelist);
} else {
filelist.push(file);
}
});
return filelist;
};
function move_file(from, to) {
fs.mkdirSync(path.dirname(to), { recursive: true });
fs.copyFileSync(from, to);
fs.unlinkSync(from);
};
function setup_token() {
let setup_config_path = path.join(__dirname, settings.setup_config_path);
console.log("Need to auth to create the " + settings.token_name);
console.log("Please restart the export to process all config");
console.log("Process setup config for check token is correct...");
return setup_config_path;
};
async function load_config(config_path, sheet_name, rule_name) {
let config = JSON.parse(fs.readFileSync(config_path));
settings.runtime.config_dir = path.dirname(config_path);
if (sheet_name) {
config.sheets = config.sheets.filter((sheet) => {
return sheet.name == sheet_name;
})
}
// Post-process config
for (let i in config.sheets) {
let sheet = config.sheets[i];
let rule_path = path.join(settings.runtime.config_dir, sheet.rule);
sheet.rule = JSON.parse(fs.readFileSync(rule_path));
if (rule_name) {
let single_rule = {};
single_rule[rule_name] = sheet.rule.rules[rule_name];
sheet.rule.rules = single_rule;
}
for (let j in sheet.save) {
sheet.save[j].temp_dist = sheet.save[j].dist.replace(/\.\./g, ".");
sheet.save[j].temp_dir = fs.mkdtempSync(os.tmpdir());
}
}
console.log("Start export data");
console.log("Config path:", config_path);
console.log("Sheet:", sheet_name || "All sheets");
console.log("Rule:", rule_name || "All rules");
console.log("");
return config
}
async function download_export(config) {
let promise = new Promise((resolve) => {
let part_resolve = underscore.after(config.sheets.length, resolve);
for (let i in config.sheets) {
processor.process_sheet(config.sheets[i], part_resolve);
}
})
await promise;
return config;
}
async function validate_export(config) {
return config;
}
async function apply_data(config) {
for (let i in config.sheets) {
for (let j in config.sheets[i].save) {
let save_param = config.sheets[i].save[j];
let files = walk_sync(save_param.temp_dir);
for (let k in files) {
let from_path = path.join(save_param.temp_dir, save_param.temp_dist, files[k]);
let to_path = path.join(settings.runtime.config_dir, save_param.dist, files[k]);
move_file(from_path, to_path);
console.log("Upload file", to_path);
}
}
}
}
function start_pipeline(config_path, sheet, rule_name) {
load_config(config_path, sheet, rule_name)
.then(download_export)
.then(validate_export)
.then(apply_data)
};
function setup_credentials() {
console.log("Check setup instructions here: https://github.com/Insality/sheets-exporter/blob/master/docs/01_installation.md");
console.log("Place credentials in " + CREDENTIALS_PATH);
};
function credentials_folder() {
console.log("Credentials path:", CREDENTIALS_PATH);
}
function help() {
console.log("");
console.log("This information")
console.log("\tsheets-exporter help");
console.log()
console.log("Init default sheets-exporter configs")
console.log("\tsheets-exporter init");
console.log()
console.log("Go to the setup credentials instruction site")
console.log("\tsheets-exporter setup_credentials");
console.log()
console.log("Show the credentials folder")
console.log("\tsheets-exporter credentials_folder");
console.log()
console.log("Add default sheet config to current config")
console.log("\tsheets-exporter add_sheet sheet_name sheet_id {config_path}");
console.log()
console.log("Add default rule config for specific Google list")
console.log("\tsheets-exporter add_rule sheet_name list_name {config_path}");
console.log()
console.log("Start export pipeline. Use default config_path by default and export all sheets and rules")
console.log("\tsheets-exporter export {config_path} {sheet_name} {rule_name}");
};
function init_configs() {
if (fs.existsSync(DEFAULT_CONFIG_PATH)) {
console.log("Found config file:", DEFAULT_CONFIG_PATH);
console.log("The config file is already exists, abort initing...");
return;
}
fs.mkdirSync(DEFAULT_CONFIG_PATH, { recursive: true });
};
function export_configs() {
let config_path = process.argv[3] || DEFAULT_CONFIG_PATH;
if (!fs.existsSync(TOKEN_PATH)) {
config_path = setup_token()
}
if (!fs.existsSync(config_path)) {
console.log("ERROR: No sheets exporter config found");
console.log("Use `sheets-exporter init` for default config init");
console.log("Use `sheets-exporter add_sheet` to add Google document configs");
console.log("Use `sheets-exporter add_rule` to add specific Google list configs");
return;
}
let sheet = process.argv[4];
let rule_name = process.argv[5];
start_pipeline(config_path, sheet, rule_name);
};
let COMMANDS = {
// ({config_path})
"init": config_utils.init_configs,
"setup_credentials": setup_credentials,
// (sheet_name, sheet_id, {config_path})
"add_sheet": config_utils.add_sheet,
// ()
"credentials_folder": credentials_folder,
// (sheet_name, list_name, {config_path})
"add_rule": config_utils.add_rule,
"help": help,
// ({config_path}, {sheet_name}, {list_name})
"export": export_configs,
}
function start() {
fs.mkdirSync(AUTH_DIR, {recursive: true})
if (!fs.existsSync(CREDENTIALS_PATH)) {
setup_credentials()
return
}
let command = process.argv[2];
if (command && COMMANDS[command]) {
COMMANDS[command]();
} else {
help()
}
}
start()
|
export const config = {
username: "jumboFED",
password: "jumbofrontendcodeproject",
api_base_url: "https://api.themoviedb.org/3",
api_key: "6ed12e064b90ae1290fa326ce9e790ff",
card_image_base: "https://image.tmdb.org/t/p/w300_and_h450_bestv2/",
backdrop_base: "https://image.tmdb.org/t/p/w1000_and_h563_face/",
mobile_card_base: "https://image.tmdb.org/t/p/w185_and_h278_bestv2",
mobile_backdrop_base: "https://image.tmdb.org/t/p/w500_and_h282_face",
// Below was hard coded data from the request used for development
// in order to avoid making unnecessary requests or hitting rate limits
popular_example: {
"page": 1,
"total_results": 10000,
"total_pages": 500,
"results": [
{
"popularity": 403.525,
"vote_count": 4936,
"video": false,
"poster_path": "/udDclJoHjfjb8Ekgsd4FDteOkCU.jpg",
"id": 475557,
"adult": false,
"backdrop_path": "/n6bUvigpRFqSwmPp1m2YADdbRBc.jpg",
"original_language": "en",
"original_title": "Joker",
"genre_ids": [
80,
18,
53
],
"title": "Joker",
"vote_average": 8.5,
"overview": "During the 1980s, a failed stand-up comedian is driven insane and turns to a life of crime and chaos in Gotham City while becoming an infamous psychopathic crime figure.",
"release_date": "2019-10-04"
}
]
},
details_examlpe: {
"adult": false,
"backdrop_path": "/n6bUvigpRFqSwmPp1m2YADdbRBc.jpg",
"belongs_to_collection": null,
"budget": 55000000,
"genres": [
{
"id": 80,
"name": "Crime"
},
{
"id": 53,
"name": "Thriller"
},
{
"id": 18,
"name": "Drama"
}
],
"homepage": "http://www.jokermovie.net/",
"id": 475557,
"imdb_id": "tt7286456",
"original_language": "en",
"original_title": "Joker",
"overview": "During the 1980s, a failed stand-up comedian is driven insane and turns to a life of crime and chaos in Gotham City while becoming an infamous psychopathic crime figure.",
"popularity": 394.256,
"poster_path": "/udDclJoHjfjb8Ekgsd4FDteOkCU.jpg",
"production_companies": [
{
"id": 9993,
"logo_path": "/2Tc1P3Ac8M479naPp1kYT3izLS5.png",
"name": "DC Entertainment",
"origin_country": "US"
},
{
"id": 174,
"logo_path": "/ky0xOc5OrhzkZ1N6KyUxacfQsCk.png",
"name": "Warner Bros. Pictures",
"origin_country": "US"
},
{
"id": 429,
"logo_path": "/2Tc1P3Ac8M479naPp1kYT3izLS5.png",
"name": "DC Comics",
"origin_country": "US"
},
{
"id": 83036,
"logo_path": null,
"name": "Joint Effort",
"origin_country": "US"
},
{
"id": 79,
"logo_path": "/tpFpsqbleCzEE2p5EgvUq6ozfCA.png",
"name": "Village Roadshow Pictures",
"origin_country": "US"
},
{
"id": 13240,
"logo_path": "/aTc07YaNHo8WNgkQSnvLmG6w4nW.png",
"name": "Bron Studios",
"origin_country": "CA"
}
],
"production_countries": [
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "2019-10-02",
"revenue": 936887108,
"runtime": 122,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "Put on a happy face.",
"title": "Joker",
"video": false,
"vote_average": 8.5,
"vote_count": 4991
},
search_example: {
"page": 1,
"total_results": 7,
"total_pages": 1,
"results": [
{
"popularity": 7.952,
"vote_count": 7340,
"video": false,
"poster_path": "/z4x0Bp48ar3Mda8KiPD1vwSY3D8.jpg",
"id": 277834,
"adult": false,
"backdrop_path": "/oWU6dgu3RgdSZElkhbZuoPtkWAJ.jpg",
"original_language": "en",
"original_title": "Moana",
"genre_ids": [
12,
16,
35,
10751
],
"title": "Moana",
"vote_average": 7.5,
"overview": "In Ancient Polynesia, when a terrible curse incurred by Maui reaches an impetuous Chieftain's daughter's island, she answers the Ocean's call to seek out the demigod to set things right.",
"release_date": "2016-11-23"
},
{
"popularity": 3.895,
"id": 94727,
"video": false,
"vote_count": 17,
"vote_average": 6.5,
"title": "Moana",
"release_date": "2015-11-13",
"original_language": "en",
"original_title": "Moana",
"genre_ids": [
99
],
"backdrop_path": "/5qZFIH4NMqCKglcTW0zZKiiBIQS.jpg",
"adult": false,
"overview": "Robert J. Flaherty's South Seas follow-up to Nanook of the North is a Gauguin idyll moved by \"pride of beauty... pride of strength.\"",
"poster_path": "/dkSM2bfwYaqY0k6cEFwej1LRWAk.jpg"
},
{
"popularity": 1.349,
"id": 45890,
"video": false,
"vote_count": 12,
"vote_average": 7.2,
"title": "Moana",
"release_date": "2009-11-01",
"original_language": "it",
"original_title": "Moana",
"genre_ids": [
18,
10770
],
"backdrop_path": "/r6AAwtnGKKgBmryMkioAXj9krHN.jpg",
"adult": false,
"overview": "The life story of Italian iconic pornographic actress Moana Pozzi. The actress Ilona Staller sued the production of the film for the unauthorized use of the character \"Cicciolina\", of which she owned the rights.",
"poster_path": "/tQYW0qsdm7iri3svsnrordmdb0A.jpg"
},
{
"popularity": 0.6,
"id": 268516,
"video": false,
"vote_count": 0,
"vote_average": 0,
"title": "Moana",
"release_date": "1959-01-01",
"original_language": "en",
"original_title": "Moana",
"genre_ids": [
99
],
"backdrop_path": null,
"adult": false,
"overview": "Documentary focused on underwater shootings and hawaiian dances.",
"poster_path": "/w6ObwrtxkVOmrPQaoTq7z0cN8gj.jpg"
},
{
"popularity": 0.6,
"id": 534297,
"video": true,
"vote_count": 0,
"vote_average": 0,
"title": "Moana",
"release_date": "",
"original_language": "en",
"original_title": "Moana",
"genre_ids": [],
"backdrop_path": null,
"adult": false,
"overview": "In Ancient Polynesia, when a terrible curse incurred by the Demigod Maui reaches Moana's island, she answers the Ocean's call to seek out the Demigod to set things right.",
"poster_path": null
},
{
"popularity": 1.948,
"id": 327317,
"video": false,
"vote_count": 9,
"vote_average": 5.6,
"title": "Summer Temptations",
"release_date": "1988-11-25",
"original_language": "it",
"original_title": "Provocazione",
"genre_ids": [
18
],
"backdrop_path": "/gOjhdgIFobrYry4WdH10yGuptlo.jpg",
"adult": false,
"overview": "In a villa on an island (St. Peter) a little out of season, inhabit Vanessa, a young widow, and stepdaughters Kikki and alive. Vanessa had married their father above all because it was very rich. After her husband's death, Vanessa decided to keep him Alive and Kikki and also call Roberto, her former lover, now a professor with the aim of preparing the two girls to the maturity examination. Shortly after his arrival, he establishes an atmosphere heavy with half-empty Island the villa that seems almost a luxury prison do understand immediately that the stepmother and stepdaughters will hate and despise each other.",
"poster_path": "/9ugI7lGDCa7CyEPda4fFC3geBr4.jpg"
},
{
"popularity": 0.6,
"id": 631526,
"video": false,
"vote_count": 0,
"vote_average": 0,
"title": "Moananuiakea: One Ocean, One People, One Canoe",
"release_date": "",
"original_language": "en",
"original_title": "Moananuiakea: One Ocean, One People, One Canoe",
"genre_ids": [],
"backdrop_path": null,
"adult": false,
"overview": "From 2019 Maui Film Festival This powerful documentary celebrates the historic Malama Honua Worldwide Voyage that connected countless individuals and communities from around the globe. A voyage that also represented the fulfillment of the vision of Nainoa Thompson and his contemporaries, the passing of the mantle to the next generation of kanaka maoli who will retain the skills of their ancestors and perpetuate this tradition for generations to come so the legacy of Hokulea can last for 1,000 generations.",
"poster_path": null
}
]
}
};
|
const qs = require('qs')
const Mock = require('mockjs')
let usersListData = Mock.mock({
'data|100': [
{
'id|+1': 1,
name: '@cname',
nickName: '@last',
phone: /^1[34578]\d{9}$/,
'age|11-99': 1,
address: '@county(true)',
isMale: '@boolean',
email: '@email',
createTime: '@datetime',
avatar () {
return Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', this.nickName.substr(0, 1))
},
},
],
page: {
total: 100,
current: 1,
},
})
const userPermission = {
DEFAULT: [
'dashboard', 'chart',
],
ADMIN: [
'dashboard', 'users', 'UIElement', 'UIElementIconfont', 'chart',
],
DEVELOPER: ['dashboard', 'users', 'UIElement', 'UIElementIconfont', 'chart'],
}
const adminUsers = [
{
id: 0,
username: 'admin',
password: 'admin',
permissions: userPermission.ADMIN,
}, {
id: 1,
username: 'guest',
password: 'guest',
permissions: userPermission.DEFAULT,
}, {
id: 2,
username: '吴彦祖',
password: '123456',
permissions: userPermission.DEVELOPER,
},
]
exports.usersListData = usersListData
exports.adminUsers = adminUsers
exports.userPermission = userPermission
|
$(document).ready(function(){
//If guest is true, hide the profile icon
var guest = window.localStorage.getItem('guest');
console.log(guest);
if (guest == 'true'){
console.log("Guest is true");
//hide the profile icon
$('#profileBtn').hide();
}
else {
console.log("Guest is false");
}
var room_expanded = false;
var building_expanded = false;
var toast = document.getElementById("snackbar");
var nearMe = false;
//If guest is true, hide the profile icon
var guest = window.localStorage.getItem('guest');
console.log(guest);
if (guest == 'true'){
console.log("Guest is true");
//hide the profile icon
$('#profileBtn').hide();
}
else {
console.log("Guest is false");
}
$("#otherrooms").click(function(){
if (!room_expanded){
$("#otherplace").slideToggle();
room_expanded = true;
$("#otherrooms").text("Other Places -");
}
else {
$("#otherplace").slideToggle();
room_expanded = false;
$("#otherrooms").text("Other Places +");
}
});
$("#building").click(function(){
if (!building_expanded){
$("#buildingPreference").slideToggle();
building_expanded = true;
$('#building').text("Building -");
}
else {
$("#buildingPreference").slideToggle();
building_expanded = false;
$('#building').text("Building +");
}
});
$("#searchBtn").click(function() {
var places = [];
$('input[name=option]:checked').map(function() {
places.push($(this).val());
});
var locations = [];
$('input[name=location]:checked').map(function() {
locations.push($(this).val());
});
console.log(places);
console.log(locations);
if (places.length == 0 && locations.length == 0 && nearMe == false){
$('#snackbar').text("Please select a type and building.");
toast.className = "show";
// After 3 seconds, remove the show class from DIV
setTimeout(function(){ toast.className = toast.className.replace("show", ""); }, 3000);
return;
} else if (places.length == 0){
$('#snackbar').text("Please select a type.");
toast.className = "show";
// After 3 seconds, remove the show class from DIV
setTimeout(function(){ toast.className = toast.className.replace("show", ""); }, 3000);
return;
} else if (locations.length == 0 && nearMe == false){
$('#snackbar').text("Please select a building.");
toast.className = "show";
// After 3 seconds, remove the show class from DIV
setTimeout(function(){ toast.className = toast.className.replace("show", ""); }, 3000);
return;
}
if (nearMe){
console.log("Near me switch");
console.log(places);
console.log(places[0]);
switch(places[0]){
case 'foodplaces':
window.localStorage.setItem('place', 'audreys');
window.location.href='map.html';
break;
case 'studyroom':
window.localStorage.setItem('place', 'geisel_study');
window.location.href='map.html';
break;
case 'nursingroom':
window.localStorage.setItem('place', 'nursing');
window.location.href='map.html';
break;
}
}
else {
if (places == 'foodplaces' && locations == 'geisel'){
window.localStorage.setItem('place', 'audreys');
window.location.href='map.html';
}
else if (places == 'studyroom' && locations == 'geisel'){
window.localStorage.setItem('place', 'geisel_study');
window.location.href='map.html';
}
else if (places == 'nursingroom' && locations == 'geisel'){
window.localStorage.setItem('place', 'nursing');
window.location.href='map.html';
}
else {
$('#snackbar').text("Building coming soon. Sorry!");
toast.className = "show";
// After 3 seconds, remove the show class from DIV
setTimeout(function(){ toast.className = toast.className.replace("show", ""); }, 3000);
return;
}
}
});
// $('input[name=nearme]:checkbox').change(function(){
// if(this.checked){
// //hide building
// $('#buildingDiv').fadeOut();
// $('#building').fadeOut();
// }
// else
// //show building selection when nearme is unchecked
// $('#buildingDiv').show();
// $('#building').show();
// });
$('#myForm input[type="checkbox"]').change(function() {
if(this.checked){
//hide building
//alert("Test checked");
$('#buildingDiv').fadeOut();
$('#building').fadeOut();
nearMe = true;
}
else{
//show building selection when nearme is unchecked
//alert("Test not checked");
$('#buildingDiv').show();
$('#building').show();
nearMe = false;
}
});
/* $("#dropdown").on("change", function() {
if (this.value == "classroom"){
window.location.href='classroom.html';
}
else if (this.value == "restroom"){
window.location.href='restroom.html';
}
});*/
$("#dropdown").on("change", function() {
if (this.value == "restroom"){
window.location.href='restroom.html';
}
else if (this.value == "classroom"){
window.location.href='classroom.html';
}
else if (this.value == "search"){
window.location.href='search.html';
}
});
});
|
import React from 'react';
import { useSelector } from 'react-redux';
import styled from 'styled-components';
const Container = styled.div`
width: 100%;
text-align: right;
color: ${({ theme }) => theme.primaryRed};
padding: 1rem 1rem 0 1rem;
`;
const ValidationErrors = () => {
const location = useSelector(state => state.currentLocation.location);
const formData = useSelector(state => state.createPostForm);
return (
<Container>
{!formData.title && formData.title !== '' && <div>*Title Required</div>}
{isNaN(formData.price) && <div>*Price Required</div>}
{(!location.lat || !location.lng) && <div>*Location Required</div>}
</Container>
);
};
export default ValidationErrors;
|
import _ from 'lodash';
import assrt from 'assert';
import { Handler } from './handler';
import { getLogger } from './logger';
class Router {
constructor () {
this.routes = new Map();
this.logger = getLogger();
}
route (url, handler, errHandler, handlerClass = Handler) {
assrt(url instanceof RegExp);
let wrappedHandler = new handlerClass(handler, errHandler);
this.routes.set(url, wrappedHandler);
}
async handleRoute (handler, req, res) {
try {
let opts = {code: 200, type: 'text/plain'};
let resp = await handler.handle(req, res);
if (resp instanceof Array) {
let newOpts = null;
[resp, newOpts] = resp;
_.extend(opts, newOpts);
}
res.writeHead(opts.code, {'Content-Type': opts.type});
this.logger.info("OK: " + opts.code);
this.logger.debug("Replying with: " + resp);
res.end(resp);
} catch (e) {
this.logger.error("Got error handling route:");
this.logger.error(e);
this.logger.error(e.stack);
res.writeHead(500);
res.end(e.message);
}
}
async serverHandler (req, res) {
this.logger.info('Handling ' + req.url);
for (let [url, handler] of this.routes) {
if (url.test(req.url)) {
await this.handleRoute(handler, req, res);
return;
}
}
this.logger.error("No route to handle url: " + req.url);
res.writeHead(404);
res.end('Not Found');
}
}
export { Router };
|
import Vuex from 'vuex'
import api from '../api/index'
import slugify from './slugify'
const store = () => {
return new Vuex.Store({
state: {
menuIsActive: false,
posts: [],
currentPost: {},
categories: []
},
actions: {
async nuxtServerInit ({ commit }, {store, isClient, isServer, route, params}) {
if (isServer && (route.name === 'index' || route.name === 'category-slug')) {
const data = await api.getPosts()
commit('SET_POSTS', data)
}
if (isServer && params.slug && route.name === 'slug') {
const post = await api.getPostBySlug(params.slug)
commit('SET_POST', post)
}
const categories = await api.getCategories()
commit('SET_CATEGORIES', categories)
},
async getPosts ({commit, state}) {
if (state.posts.length === 0) {
const posts = await api.getPosts()
commit('SET_POSTS', posts)
}
},
async getPost ({commit, store}, slug) {
const post = await api.getPostBySlug(slug)
commit('SET_POST', post)
}
},
getters: {
getPostsByCategorySlug: (state, getters) => (slug) => {
return state.posts.filter(post => {
return post.categories.find(category => slugify(category.fields.title) === slug) !== undefined
})
},
getCategoryBySlug: (state, getters) => (slug) => {
return state.categories.find(category => category.slug === slug)
}
},
mutations: {
TOGGLE_MENU (state) {
state.menuIsActive = !state.menuIsActive
},
SET_POSTS: (state, posts) => {
state.posts = []
posts.forEach(item => {
if (item) {
let entry = {
title: item.fields.title,
slug: item.fields.slug,
body: item.fields.body,
date: item.fields.date,
featuredImage: item.fields.featuredImage,
categories: item.fields.category
}
state.posts.push(entry)
}
})
},
SET_CATEGORIES: (state, categories) => {
categories.forEach(item => {
if (item) {
let entry = {
id: item.sys.id,
title: item.fields.title,
slug: slugify(item.fields.title)
}
state.categories.push(entry)
}
})
},
SET_POST: (state, post) => {
state.currentPost = {
id: post.sys.id,
title: post.fields.title,
slug: post.fields.slug,
body: post.fields.body,
date: post.fields.date,
featuredImage: post.fields.featuredImage,
categories: post.fields.category
}
}
}
})
}
export default store
|
//console.log("aventador");
const createError = err => {
return {
error: err
};
};
module.exports = createError;
|
angular.module('app')
.factory('AuthenticationService', function($q, appConfig, $ionicPlatform) {
var self = {};
console.log('appConfig', appConfig);
self.currentUser = null;
crud.configure({
base: appConfig.apiURL,
protocol: appConfig.apiProtocol
});
self.checkStatus = function() {
var deferred = $q.defer();
$ionicPlatform.ready(function() {
var user = Ionic.User.current(),
authToken = user.get('authToken');
// already know it
if (self.currentUser) {
return setTimeout(function() {
deferred.resolve(self.currentUser);
});
}
// for local testing on browser or Ionic View
if (!_.get(window, 'cordova.InAppBrowser') ||
/NoCloud/.test(location.href)) {
authToken = authToken || localStorage.getItem('browserAuthToken') ||
appConfig.browserAuthToken;
} else if (!user.isAuthenticated()) authToken = null;
// get user info
if (!authToken) setTimeout(function() { deferred.reject(); });
else {
crud.configure({
defaultQuery: { turnkeyAuth: authToken }
});
crud('/api/users/me').read(function(e, user) {
if (e || !user) deferred.reject();
else deferred.resolve(self.currentUser = user);
});
}
});
return deferred.promise;
};
return self;
});
|
function solve(lostFights, helmetPrice, swordPrice, shieldPrice, armorPrice){
let helmetBrokenCounter = 0;
let swordBrokenCounter = 0;
let shieldBrokenCounter = 0;
let finalHelmetCounter = 0;
let finalSwordCounter = 0;
let finalShieldCounter = 0;
let finalArmorCounter = 0;
while (lostFights > 0) {
helmetBrokenCounter++;
swordBrokenCounter++;
shieldBrokenCounter++;
if (helmetBrokenCounter === 2) {
finalHelmetCounter++;
helmetBrokenCounter = 0;
}if (swordBrokenCounter === 3) {
finalSwordCounter++;
swordBrokenCounter = 0;
}if (shieldBrokenCounter === 6){
finalShieldCounter++;
}if (shieldBrokenCounter === 12) {
finalShieldCounter++;
finalArmorCounter++;
shieldBrokenCounter = 0;
}
lostFights--;
}
let result = finalHelmetCounter * helmetPrice + finalSwordCounter * swordPrice + finalShieldCounter * shieldPrice + finalArmorCounter * armorPrice;
console.log(`Gladiator expenses: ${result.toFixed(2)} aureus`);
}
solve(23,12.50,21.50,40,200);
|
import { html, css, LitElement } from 'lit-element';
class Main extends LitElement {
static get styles() {
return [
css`
:host {
flex: 1;
display: block;
box-sizing: border-box;
}
:host div {
border: 1px dashed cyan;
}
`
];
}
render() {
return html`
<div>
<section>
<h2>This is OAE!!</h2>
</section>
</div>
`;
}
}
window.customElements.define('oae-main', Main);
|
import React from 'react';
const withTest = Component => props => {
if (window.location.href.includes('localhost')) {
console.log(props);
}
return <Component>{props.children}</Component>;
};
export default withTest;
|
import React, { useState } from 'react'
import '../css/header.css'
import AccountCircleIcon from '@material-ui/icons/AccountCircle';
import SearchIcon from '@material-ui/icons/Search';
import ShopIcon from '@material-ui/icons/Shop';
import Drawer from '@material-ui/core/Drawer';
import { useSelector } from 'react-redux';
import { auth } from './firebase';
import Cart from './Cart'
import {
Link, useHistory
} from "react-router-dom";
import Search from './Search';
function Header() {
const [state, setState] = React.useState({
top: false,
left: false,
bottom: false,
right: false,
});
const productList = useSelector((state) => state)
const [status, setStatus] = useState([]);
const login = () => {
if (productList.userReducer.user) {
auth.signOut();
}
}
const history = useHistory();
const signIn = () => {
history.push('/login')
}
const toggleDrawer = (anchor, open, name) => (event) => {
if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
return;
}
setState({ ...state, [anchor]: open });
setStatus(name)
console.log(name)
};
const right = 'right'
return (
<div className='header'>
<p className='left'></p>
<div className="header__logo">
<Link to='/'><img className='header__logo__img' src='http://theme.hstatic.net/1000341789/1000533258/14/logo.png?v=259'></img></Link>
</div>
<div className='header__icon'>
<div>
<Link style={{ color: 'black' }} to='/login'> <AccountCircleIcon style={{ fontSize: 30 }}></AccountCircleIcon></Link>
<div className="header__option">
<p className='header__optionOne'>{productList.userReducer.user?.email ? (<div>{productList.userReducer.user?.email.slice(0, productList.userReducer.user?.email.search('@'))}</div>) : (<div>Hello</div>)}</p>
<p className='header__optionTwo'>{productList.userReducer.user?.email ? (<div onClick={login}>Sign Out</div>) : (<div onClick={signIn}>Sign In</div>)}</p>
</div>
</div>
<SearchIcon style={{ fontSize: 30 }} onClick={toggleDrawer(right, true, 'search')}></SearchIcon>
<ShopIcon style={{ fontSize: 30 }} onClick={toggleDrawer(right, true, 'shop')}></ShopIcon>
{productList.rootReducer.length ? (<p className='header__quantity'>{productList.rootReducer.length}</p>) : (<div></div>)}
<Drawer anchor={right} open={state[right]} onClose={toggleDrawer(right, false)}>
{status == 'shop' ? (<Cart close={() => toggleDrawer(right, false)}></Cart>) : (<Search close={() => toggleDrawer(right, false)}></Search>)}
</Drawer>
</div>
</div>
)
}
export default Header
|
import EventPreview from '../Common/Event/EventPreview';
import React from 'react';
const EventList = props => {
if (!props.events) {
return (
<div className="article-preview">Loading...</div>
);
}
if (props.events.length === 0) {
return (
<div className="article-preview">
No upcoming events. Sorry.
</div>
);
}
return (
<div>
{
props.events.map(event => {
return (
<EventPreview event={event} />
);
})
}
</div>
);
};
export default EventList;
|
import { decorate, observable, action } from 'mobx';
import { api } from '../services';
class PostList {
posts = [];
loadAll = async () => {
const posts = await api.Posts.all();
this.posts = posts;
}
add = async (post) => {
try {
const response = await api.Posts.add(post);
this.posts = [response, ...this.posts];
} catch (e) {
console.error(e);
}
}
}
export default decorate(PostList, {
loadAll: action,
add: action,
posts: observable,
});
|
'use strict';
module.exports = {
apiKey: "AIzaSyCQirXTGX-g2_rTK179gUsRgV9lKsQ9ZXk",
authDomain: "thunder-sharks-movies.firebaseapp.com",
};
|
import Blog from "./Blog";
const BlogList = ({ posts }) => {
let i = 0;
return (
<div className="blog-list">
{posts.map(post => (
<Blog post={post} caller={"bloglist"} key={i++}></Blog>
))}
</div>
);
};
export default BlogList;
|
$( "#goButton" ).click(function() {
var groupName = document.getElementById("group").value;
$.get( "./create.php", { group: groupName } )
.done(function( data ) {
if (data == 'exists' || data == 'Success!') window.location.href = "./go.php?group=" + groupName;
else alert('Something went wrong. :( Reload the page.');
});
});
|
import _ from 'lodash';
const projectRoles = roles => (
_.map(roles, ({ name, todo }) => `
> - *${name}*: ${todo}\n
`)
);
const renderProjects = (slackId, projects) => ({
fallback: 'Po\'s Projects',
author_name: 'Projects',
author_icon: ':beers:',
color: 'warning',
text: !projects.length ? `Here are projects that <@${slackId}>'s involved` : 'None',
fields: _.map(projects, ({ name, roles }) => ({
title: name,
value: projectRoles(roles),
short: false,
})),
});
export default (user) => {
const {
name,
slackId,
projects,
team,
bio,
avatarUrl,
email,
role,
} = user;
const teamInfo = team.split(' - ');
return {
text: 'Here you go',
attachments: [
{
fallback: `<@${slackId}> Profile`,
author_name: name,
author_icon: 'https://i0.wp.com/www.flyhoneystars.com/wp-content/uploads/2015/11/shopbacklogo.jpg?resize=300%2C300',
thumb_url: avatarUrl,
// thumb_url: 'https://theme.zdassets.com/theme_assets/716754/44f2c2d2c8c3daad077843549f93561a9bdd3f43.png',
text: bio,
fields: [
{
title: 'Team',
value: teamInfo[1],
short: true,
},
{
title: 'Located',
value: teamInfo[0],
short: true,
},
{
title: 'Email',
value: email,
short: false,
},
{
title: 'Role',
value: role,
short: false,
},
],
},
{ ...renderProjects(slackId, projects) },
{
fallback: 'Call to actions',
text: 'Something you can do',
callback_id: `shopbacker_actions-${slackId}`,
color: '#FF4445',
attachment_type: 'default',
actions: [
{
name: 'profile-action',
text: 'Edit',
type: 'button',
value: 'edit',
},
{
name: 'profile-action',
text: 'Join project',
type: 'button',
value: 'join',
},
{
name: 'profile-action',
text: 'Leave project',
type: 'button',
value: 'leave-project',
},
],
},
],
};
};
|
/*1) Crear una función que recorrar el arreglo alumnos e indique cuantos están aprobados, cuantos están desaprobandos teniendo en cuenta
que la nota mínima aprobatoria es 13. Saca el promedio de las notas aprobadas, promedio de notas desaprobadas y el promedio total de notas.
Indicar el nombre y la carrera en un console.log de los que su indice sea multiplo de 2 ejemplo: "Mi nombre es Juan y mi carrera es Biología".
2) Crear una función que filtre en un nuevo arreglo a los alumnos que tengan de nota menor a 13.
3) Crear una función que retorne un nuevo arreglo en donde se multiplique por 3 la nota de los alumnos y luego la divida entre 2 para devolver
la nueva nota de los alumnos.
*/
const alumnos = [
{
nombre: 'Juan',
carrera: 'Biología',
nota: 16
},
{
nombre: 'Jose',
carrera: 'Enfermero',
nota: 10
},
{
nombre: 'Luis',
carrera: 'Policía',
nota: 07
}
,
{
nombre: 'Maria',
carrera: 'Secretariado',
nota: 10
},
{
nombre: 'Hugo',
carrera: 'Enfermero',
nota: 15
},
{
nombre: 'Rosa',
carrera: 'Enfermero',
nota: 12
}
,
{
nombre: 'Luisa',
carrera: 'Biología',
nota: 18
}
]
console.log(alumnos);
const aprobados = alumnos.filter((alumno) => alumno.nota >= 13);
console.log(aprobados);
SnotA = 0;
CnotA = 0;
aprobados.forEach((p) => {
const {nombre, carrera, nota} = p;
SnotA += p.nota
CnotA ++
})
console.log('El promedio de notas aprobados es: ' + (SnotA/CnotA));
const desaprobados = alumnos.filter((alumno) => alumno.nota <= 12);
console.log(desaprobados);
SnotD = 0;
CnotD = 0;
desaprobados.forEach((p) => {
const {nombre, carrera, nota} = p;
SnotD += p.nota // SnotD = SnotD + p.nota
CnotD ++ // CnotD +1
})
console.log('El promedio de notas desaprobadas es: ' + (SnotD/CnotD));
const notax2 = aprobados.map((p) => {
p.nota = p.nota *3;
});
|
const express = require("express");
require('./connection')
// require('./crud')
const app = express();
app.listen(5000, () => {
console.log(`Server is listening on port 5000`);
});
|
const ec2 = require('@aws-cdk/aws-ec2')
const ecs = require('@aws-cdk/aws-ecs')
const elbv2 = require('@aws-cdk/aws-elasticloadbalancingv2')
const ecr = require('@aws-cdk/aws-ecr')
const cdk = require('@aws-cdk/core')
class EcsFargateSingleServiceStack extends cdk.Stack {
/**
*
* @param {cdk.Construct} scope
* @param {string} id
* @param {cdk.StackProps=} props
*/
constructor(scope, id, props) {
super(scope, id, props);
// base infrastucture
const vpc = new ec2.Vpc(this, 'VPC', { maxAzs: 2 })
const cluster = new ecs.Cluster(this, 'Cluster', {
clusterName: 'Services',
vpc: vpc
})
const alb = new elbv2.ApplicationLoadBalancer(this, 'ALB', {
vpc: vpc,
internetFacing: true,
loadBalancerName: 'ServicesLB'
})
// get our image, replace REGION and ACCOUNTID with yours
const repo = ecr.Repository.fromRepositoryArn(
this,
'Servic1Repo',
`arn:aws:ecr:us-west-2:${props.env.account}:repository/service3`
)
const image = ecs.ContainerImage.fromEcrRepository(repo, 'latest')
// task definition
const taskDef = new ecs.FargateTaskDefinition(
this,
'taskDef',
{
compatibility: ecs.Compatibility.EC2_AND_FARGATE,
cpu: '256',
memoryMiB: '512',
networkMode: ecs.NetworkMode.AWS_VPC
}
)
const container = taskDef.addContainer('Container', {
image: image,
memoryLimitMiB: 512
})
container.addPortMappings({
containerPort: 7073,
protocol: ecs.Protocol.TCP
})
// create service
const service = new ecs.FargateService(
this,
'service',
{
cluster: cluster,
taskDefinition: taskDef,
serviceName: 'service3'
}
)
// network the service with the load balancer
const listener = alb.addListener('listener', {
open: true,
port: 80
}
)
// add target group to container
listener.addTargets('service3', {
targetGroupName: 'Service3Target',
port: 80,
targets: [service]
})
}
}
module.exports = { EcsFargateSingleServiceStack }
|
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyB7avU0P9YGoQSJbphC-lH3SclS180CT-c",
authDomain: "chat-ddf84.firebaseapp.com",
databaseURL: "https://chat-ddf84-default-rtdb.firebaseio.com",
projectId: "chat-ddf84",
storageBucket: "chat-ddf84.appspot.com",
messagingSenderId: "37012775311",
appId: "1:37012775311:web:464151272fd69177852bfa"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//obtener datos del html
var txtUsuario = document.getElementById("usuario");
var txtMensaje = document.getElementById("mensaje");
var btnEnviar = document.getElementById("btnenviar");
var chatlista = document.getElementById("chatlista");
var fechahora = new Date();
var fecha = fechahora.toString();
fecha = fecha.substring(0,24);
//Ejecutar accion en el boton
btnEnviar.addEventListener("click",function(){
var usuario = txtUsuario.value;
var mensaje = txtMensaje.value;
var html = "<li>"+usuario+" dice: "+mensaje+" "+fecha+"</li>";
chatlista.innerHTML += html;
firebase.database().ref('chat').push({
user: usuario,
message: mensaje,
datetime: fecha
})
});
/*Mostrar datos*/
firebase.database().ref('chat').on('value', (snapshot) => {
var html1 = '';
//console.log(snapshot.val());
snapshot.forEach(function (e){
var elemento = e.val();
var usuario1 = elemento.user;
var mensaje1 = elemento.message;
var fecha1 = elemento.datetime;
html1 += "<li><div class='txt'><img id='profile-photo' src='man.png' class='rounded-circle' width='30px'/>"
+usuario1+" dice: <div class='chat ml-6 p-3'>"+mensaje1+"</li></div></div><div class='peque'>"+fecha1+"</div>";
//html1 += "<li><div class='txt'><img id='profile-photo' src='http://nicesnippets.com/demo/man01.png' class='rounded-circle' width='30px'/>"
//+usuario1+" dice: </br><div class='chat ml-6 p-3'>"+mensaje1+"</li></div></div>";
});
chatlista.innerHTML = html1;
})
|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*/
'use strict';
// external libs
const _ = require('lodash');
const PUBLIC_FIELDS = ['type', 'targetType', 'targetName'];
const TYPES = {
READ: 'read',
WRITE: 'write', // read + edit + delete
EDIT: 'edit',
NONE: 'none',
DO: 'do'
};
const TARGET_TYPES = {
NODE_CATEGORY: 'nodeCategory',
EDGE_TYPE: 'edgeType',
ACTION: 'action',
ALERT: 'alert'
};
/**@type {Map<string, string[]>}*/
const LEGAL_RIGHTS_BY_TARGET_TYPE = new Map();
LEGAL_RIGHTS_BY_TARGET_TYPE.set('nodeCategory', ['read', 'write', 'edit', 'none']);
LEGAL_RIGHTS_BY_TARGET_TYPE.set('edgeType', ['read', 'write', 'edit', 'none']);
LEGAL_RIGHTS_BY_TARGET_TYPE.set('action', ['do', 'none']);
LEGAL_RIGHTS_BY_TARGET_TYPE.set('alert', ['read', 'none']);
/**@type {Map<string, string[]>}*/
const IMPLICIT_RIGHTS = new Map();
// you can read if you can read, edit or write
IMPLICIT_RIGHTS.set('read', ['read', 'edit', 'write']);
// you can edit if you can edit or write
IMPLICIT_RIGHTS.set('edit', ['edit', 'write']);
module.exports = function(sequelize, DataTypes) {
const accessRightModel = sequelize.define('accessRight', {
type: {
allowNull: false,
type: DataTypes.STRING
},
targetType: {
allowNull: false,
type: DataTypes.STRING
},
targetName: {
allowNull: false,
type: DataTypes.STRING
},
sourceKey: {
type: DataTypes.STRING(8),
allowNull: false
}
}, {
charset: 'utf8',
classMethods: {
associate: models => {
models.group.hasMany(accessRightModel);
},
instanceToPublicAttributes: instanceToPublicAttributes
}
});
accessRightModel.TYPES = TYPES;
accessRightModel.TARGET_TYPES = TARGET_TYPES;
accessRightModel.PUBLIC_FIELDS = PUBLIC_FIELDS;
accessRightModel.LEGAL_RIGHTS_BY_TARGET_TYPE = LEGAL_RIGHTS_BY_TARGET_TYPE;
accessRightModel.IMPLICIT_RIGHTS = IMPLICIT_RIGHTS;
return accessRightModel;
};
/**
* @param {AccessRightInstance} accessRightInstance
* @param {boolean} [withSourceKey]
* @returns {PublicAccessRight}
*/
function instanceToPublicAttributes(accessRightInstance, withSourceKey) {
let fields = PUBLIC_FIELDS;
if (withSourceKey) {
fields = fields.concat(['sourceKey']);
}
return /**@type {PublicAccessRight}*/ (_.pick(accessRightInstance, fields));
}
|
describe('Home', () => {
beforeEach(() => {
cy.visit('http://localhost:3000')
})
it('has the correct title', () => {
cy.title().should('equal', 'React App')
})
it('has links', () => {
cy.contains('EIMSBÜTTELER TV').click()
cy.contains('Teams')
})
})
|
const router = require('express').Router();
const faker = require('faker');
const Product = require('../models/product');
const Review = require('../models/review');
const Category = require('../models/category');
//batch of existing Product ids
const prodIds = [
"5d3a08492a420740584cad50",
"5d3a08492a420740584cad51",
"5d3a08492a420740584cad52",
"5d3a08492a420740584cad53",
"5d3a08492a420740584cad54",
"5d3a08492a420740584cad55",
"5d3a08492a420740584cad56",
"5d3a08492a420740584cad57",
"5d3a08492a420740584cad58"
];
//Faker Product Data, attempt to override images
router.get('/generate-fake-data', (req, res, next) => {
for (let i = 0; i < 90; i++) {
let product = new Product();
product.category = faker.commerce.department();
product.name = faker.commerce.productName();
product.price = faker.commerce.price();
product.image= 'https://cdn.shopify.com/s/files/1/1430/0320/products/ridf-mrsau_1024x1024.png?v=1476045480';
product.reviews = [];
for (let i = 0; i < 3; i++) {
const review = new Review();
review.author = faker.name.firstName() + ' ' + faker.name.lastName();
review.reviewText = faker.lorem.sentences();
review.product = product;
review.save()
product.reviews.push(review);
}
product.save((err) => {
if (err) throw err
})
}
res.status(200).end()
});
//fake reviews
router.get('/generate-fake-reviews', (req, res, next) => {
for (let i = 0; i < 5; i++) {
let review = new Review();
review.reviewText = faker.lorem.sentences();
review.author = faker.name.firstName() + ' ' + faker.name.lastName();
review.product = prodIds[Math.floor((Math.random() * prodIds.length))];
review.save((err) => {
if (err) throw err
})
}
res.status(200).end()
});
//fake categories
router.get('/generate-fake-categories', (req, res, next) => {
for (let i = 0; i < 5; i++) {
let category = new Category();
category.name = faker.lorem.word();
category.save((err) => {
if (err) throw err
})
}
res.status(200).end()
});
module.exports = router;
|
var qs = require('q-stream');
var assert = require('assert');
var seq = require('../sequence-stream');
describe("sequence-stream", function() {
it("should combine a sequence of streams", function() {
var results = [];
var a = qs();
var b = qs();
var c = qs();
var p = seq([a, b, c])
.pipe(qs(function(d) { results.push(d); }))
.promise()
.then(function() {
assert.deepEqual(results, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
});
a.push(1);
b.push(4);
c.push(7);
a.push(2);
b.push(5);
c.push(8);
a.push(3);
b.push(6);
c.push(9);
a.push(null);
b.push(null);
c.push(null);
return p;
});
it("should act as an ended stream if no streams are given", function() {
assert(seq()._readableState.ended);
});
it("should emit errors occuring when the streams fail to push", function(done) {
var s = qs();
var t = seq([s])
.on('error', function(e) {
assert(e instanceof Error);
assert.equal(e.message, ':(');
done();
});
t.push = function() {
throw new Error(':(');
};
s.push(1);
});
});
|
import dbConnection from "./msSqlWrapper";
import {getTimestamp, toBasicString} from "../utils";
async function registerUserInDB(email, password, privateKey, publicKey, authorityLevel, forename, surname, companyName, creationDate, blocked) {
const queryString = `INSERT INTO users (email, password, privateKey, publicKey, authorityLevel, forename, surname, companyName,
creationDate, blocked) VALUES ('${email}', '${password}', '${toBasicString(privateKey)}', '${toBasicString(publicKey)}', '${authorityLevel}', '${forename}', '${surname}', '${companyName}', '${creationDate}', '${blocked}');`;
return await dbConnection.query(queryString);
}
async function registerCarInDB(vin, privateKey, publicKey, creationDate) {
const queryString = `INSERT INTO kfz (vin, privateKey, publicKey, creationDate) VALUES ('${vin}', '${toBasicString(privateKey)}', '${toBasicString(publicKey)}', '${creationDate}')`;
return await dbConnection.query(queryString);
}
async function doesUserExist(email) {
const queryString = `SELECT * FROM users WHERE email = '${email}'`;
const results = await dbConnection.query(queryString);
return results.length !== 0;
}
async function blockUserInDB(email) {
const query = `
BEGIN TRANSACTION
IF EXISTS (SELECT * FROM bearer_tokens WITH (updlock,serializable)
WHERE user_id LIKE (SELECT id FROM users WHERE email LIKE '${email}'))
BEGIN
DELETE FROM bearer_tokens WHERE user_id LIKE (SELECT id FROM users WHERE email LIKE '${email}')
END
UPDATE users SET blocked = 1 WHERE email = '${email}'
COMMIT TRANSACTION
`;
return await dbConnection.query(query);
}
async function getCarAddressFromVin(vin) {
const queryString = `SELECT publicKey FROM kfz WHERE vin = '${vin}'`;
const result = await dbConnection.query(queryString);
if (result != null && result.length > 0) {
return result[0];
}
return null;
}
async function getAllUsers() {
const queryString = `SELECT * FROM users WHERE users.blocked = 'false'`;
const results = await dbConnection.query(queryString);
if (results == null) {
return null;
}
// Cut array into right size
let users = [];
for (let i = 0; i < results.length; i += 11) {
users.push(results.slice(i, i + 11));
}
return users.map(element => {
return {
date: element[8],
forename: element[5],
surname: element[6],
authorityLevel: element[4],
email: element[1],
company: element[7]
};
});
}
async function getUserFromCredentials(email, password) {
const queryString = `SELECT * FROM users WHERE email = '${email}' AND password = '${password}';`;
const result = await dbConnection.query(queryString);
if (result == null || result.length === 0) {
console.log("Invalid credentials");
return null;
}
return {
"id": result[0],
"email": result[1],
"password": result[2]
};
}
async function getUserFromToken(token) {
const queryString = `SELECT * FROM users WHERE id = (SELECT user_id FROM bearer_tokens WHERE token = '${token}')`;
const result = await dbConnection.query(queryString);
if (result == null || result.length === 0) {
return null;
}
return {
"id": result[0],
"email": result[1],
"privateKey": result[3],
"authorityLevel": result[4],
"forename": result[5],
"surname": result[6],
"companyName": result[7],
"creationDate": result[8],
"blocked": result[9],
"publicKey": result[10]
}
}
async function getUserFromUserId(userId) {
const queryString = `SELECT * FROM users WHERE id = ${userId}`;
const result = await dbConnection.query(queryString);
if (result == null || result.length === 0) {
return null;
}
return {
"id": result[0],
"email": result[1],
"privateKey": result[3],
"authorityLevel": result[4],
"forename": result[5],
"surname": result[6],
"companyName": result[7],
"creationDate": result[8],
"blocked": result[9],
"publicKey": result[10]
}
}
async function updatePassword(email, passwordHash) {
const queryString = `UPDATE users SET password = '${passwordHash}' WHERE email = '${email}'`;
return await dbConnection.query(queryString);
}
async function checkUserAuthorization(token) {
const queryString = `SELECT users.blocked, users.id, users.authorityLevel, tokens.expiration FROM users, bearer_tokens as tokens WHERE users.id = tokens.user_id AND tokens.token = '${token}'`;
return await dbConnection.query(queryString);
}
async function getHeadTransactionHash(publicKeyCar) {
const queryString = `SELECT headTx FROM kfz WHERE publicKey = '${toBasicString(publicKeyCar)}'`;
const result = await dbConnection.query(queryString);
if (result == null || result.length === 0) {
return null;
}
return result[0];
}
async function updateHeadTransactionHash(publicKeyCar, headTxHash) {
const queryString = `UPDATE kfz SET headTx = '${toBasicString(headTxHash)}' WHERE publicKey = '${toBasicString(publicKeyCar)}';`;
return await dbConnection.query(queryString);
}
async function getAllAnnulmentTransactions() {
// Selects all information from annulment_transactions plus the email address which belongs to the user_id
const queryString = `SELECT at.transactionHash, at.pending, at.creationDate, at.vin, at.applicant, users.email FROM annulment_transactions AS at, users WHERE at.user_id = users.id`;
const result = await dbConnection.query(queryString);
if (result == null || result.length === 0) {
return null;
}
let allAnnulments = [];
for (let i = 0; i < result.length; i += 6) {
allAnnulments.push({
"transactionHash": result[i],
"pending": result[i + 1],
"creationDate": result[i + 2],
"vin": result[i + 3],
"applicant": result[i + 4],
"creator": result[i + 5]
});
}
return allAnnulments;
}
async function getAnnulment(hash) {
// Selects all information from annulment_transactions plus the email address which belongs to the user_id for a specific transactionHash
const queryString = `SELECT at.transactionHash, at.pending, at.creationDate, at.vin, at.applicant, users.email FROM annulment_transactions AS at, users WHERE at.user_id = users.id AND transactionHash = '${toBasicString(hash)}'`;
const result = await dbConnection.query(queryString);
if (result == null || result.length === 0) {
return null;
}
return {
"transactionHash": result[0],
"pending": result[1],
"creationDate": result[2],
"vin": result[3],
"applicant": result[4],
"creator": result[5]
}
}
async function insertAnnulment(hash, user_id, vin) {
const queryString = `INSERT INTO annulment_transactions (transactionHash, pending, creationDate, user_id, vin, applicant) VALUES ('${toBasicString(hash)}', 1, '${getTimestamp()}', ${user_id}, '${vin}', NULL)`;
return await dbConnection.query(queryString);
}
async function rejectAnnulment(hash) {
const queryString = `DELETE FROM annulment_transactions WHERE transactionHash = '${hash}'`;
return await dbConnection.query(queryString);
}
async function acceptAnnulment(hash, applicant) {
const queryString = `UPDATE annulment_transactions SET pending = 0, applicant = '${applicant}' WHERE transactionHash = '${toBasicString(hash)}'`;
return await dbConnection.query(queryString)
}
module.exports = {
"registerUserInDB": registerUserInDB,
"registerCarInDB": registerCarInDB,
"getUserFromCredentials": getUserFromCredentials,
"doesUserExist": doesUserExist,
"blockUserInDB": blockUserInDB,
"getCarAddressFromVin": getCarAddressFromVin,
"getUserFromToken": getUserFromToken,
"getUserFromUserId": getUserFromUserId,
"checkUserAuthorization": checkUserAuthorization,
"getAllUsers": getAllUsers,
"getAllAnnulmentTransactions": getAllAnnulmentTransactions,
"getHeadTransactionHash": getHeadTransactionHash,
"updateHeadTransactionHash": updateHeadTransactionHash,
"getAnnulment": getAnnulment,
"insertAnnulment": insertAnnulment,
"rejectAnnulment": rejectAnnulment,
"acceptAnnulment": acceptAnnulment,
"updatePassword": updatePassword
};
|
/*
* @Author: cash
* @Date: 2021-11-05 17:07:07
* @LastEditors: cash
* @LastEditTime: 2021-11-05 17:08:18
* @Description: file content
* @FilePath: \hdl-try\src\views\productCenter\productCategory\hook\initTable.js
*/
import {t} from "@/common/i18n.js";
const columns = [
{
title: t('productCenter.sortingCode'),
// title: '分类编码',
dataIndex: 'categoryCode',
key: 'categoryCode',
slots: { customRender: 'noData' }
},
{
// title: '分类名称',
title: t('productCenter.listsortname'),
dataIndex: 'categoryName',
key: 'categoryName',
slots: { customRender: 'noData' }
},
{
// title: '启用禁用',
title: t('productCenter.enableDisable'),
key: 'status',
dataIndex: 'status',
slots: { customRender: 'status' }
},
{
// title: '排序',
title: t('productCenter.rank'),
key: 'sort',
dataIndex: 'sort',
slots: { customRender: 'noData' }
},
{
// title: '描述',
title: t('projuct.houseDesc'),
key: 'categoryDesc',
dataIndex: 'categoryDesc',
slots: { customRender: 'categoryDesc' }
},
{
// title: '创建时间',
title: t('productCenter.creationTime'),
key: 'createTime',
dataIndex: 'createTime',
slots: { customRender: 'createTime' }
},
{
// title: '操作',
title: t('hdl.operation'),
dataIndex: 'action',
key: 'action',
slots: { customRender: 'action' }
}
];
export default columns
|
/*
* productSearchCriteriaService.js
*
* Copyright (c) 2016 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*/
'use strict';
/**
* Creates the service used to interact with the product search box.
*/
(function() {
angular.module('productMaintenanceUiApp').service('ProductSearchCriteriaService', productSearchCriteriaService);
function productSearchCriteriaService() {
var self = this;
self.searchCallback = null;
self.complexSearchCallback = null;
self.searchType = null;
self.selectionType = null;
self.searchSelection = null;
self.itemStatus = null;
self.byosObject = null;
self.byosObjects = [];
self.showFullPanelProperty = false;
self.productSearchCriteria = {};
/**
* Wheter the user has selected to search by product description.
* @type {boolean}
*/
self.searchByProductDescription = true;
/**
* Whether the user has selected to search by customer friendly description.
* @type {boolean}
*/
self.searchByCustomerFriendlyDescription = false;
/**
* Wheter the user has selected to search by display name.
* @type {boolean}
*/
self.searchByDisplayName = false;
/**
* Whether the user has selected to search by all extended attributes.
* @type {boolean}
*/
self.searchAllExtendedAttributes = false;
return {
// Constants for the search types.
BASIC_SEARCH:"basicSearch",
HIERARCHY_SEARCH:"hierarchySearch",
BDM_SEARCH:"bdmSearch",
BYOS_SEARCH:"byosSearch",
MRT_SEARCH:"mrtSearch",
VENDOR_SEARCH:"vendorSearch",
CUSTOM_HIERARCHY_SEARCH:"customHierarchySearch",
DESCRIPTION_SEARCH: "descriptionSearch",
// Constants for the list types.
UPC:"UPC",
ITEM_CODE:"Item Code",
PRODUCT_ID:"Product ID",
PRODUCT_DESCRIPTION: "Product Description",
BDM: "BDM",
SUB_DEPARTMENT:"Sub Department",
CLASS:"Class",
COMMODITY:"Commodity",
SUB_COMMODITY:"Sub Commodity",
CASE_UPC:"Case UPC",
/**
* Initializes the controller.
*
* @param showFullPanel Whether or not to show the full panel (excludes item status filter). This will add
* things like the MRT tab, the add button for complex search, product description search, etc.
* @param showStatusFilter Whether or not to show the item status filter options.
* @param basicSearchCallback The callback for when the user clicks on a basic search button. Basic
* searches only have one set of criteria.
* @param complexSearchCallback The callback for when the user clicks on the complex search button. Complex
* searches can contain multiple sets of criteria.
*/
init:function(showFullPanel, showStatusFilter, basicSearchCallback, complexSearchCallback) {
self.productSearchCriteria = {};
self.showFullPanelProperty = showFullPanel;
self.searchCallback = basicSearchCallback;
self.complexSearchCallback = complexSearchCallback;
},
/**
* Wheter or not all of the search options should be available.
*
* @returns {boolean|*}
*/
showFullPanel:function() {
return self.showFullPanelProperty;
},
/**
* Returns item status the user has selected.
*
* @returns itemStatus
*/
getItemStatus:function(){
return self.itemStatus;
},
/**
* Sets item status the user has selected.
*
* @param itemStatus
*/
setItemStatus:function(itemStatus){
self.itemStatus = itemStatus;
},
/**
* Returns the callback for when the user clicks on the search button.
*
* @returns {null|*}
*/
getSearchCallback:function() {
if (self.searchCallback == null) {
console.log('returning null search callback');
}
return self.searchCallback;
},
/**
* Returns the callback to use when the user clicks on the complex search button.
* @returns {null|*}
*/
getComplexSearchCallback:function() {
return self.complexSearchCallback;
},
/**
* Returns the type of search the user has chosen (basic, hierarchy, bdm, etc.).
*
* @returns {null|*} The type of search the user has chosen.
*/
getSearchType:function() {
return self.searchType;
},
/**
* Sets the type of search the user has chosen.
*
* @param searchType The type of search the user has chosen.
*/
setSearchType:function(searchType) {
self.searchType = searchType;
},
/**
* Returns the type of data in the search list. For basic, this will be UPC, product ID, or item code. For
* BDM searches, this will be BDM. For hierarchy searches, this will be the level of the hierarchy.
*
* @returns {null|*} The type of data in the search list.
*/
getSelectionType:function() {
return self.selectionType;
},
/**
* Sets the type of data in the search list.
*
* @param selectionType The type of data in the search list.
*/
setSelectionType:function(selectionType) {
self.selectionType = selectionType;
},
/**
* Returns the values the user has chosen to search on. This will be the actual list of UPCs, etc., or an
* object representing a BDM or a level of a hierarchy.
*
* @returns {null|*}
*/
getSearchSelection:function() {
return self.searchSelection;
},
/**
* Sets the values the user has chosen to search on.
*
* @param searchSelection
*/
setSearchSelection:function(searchSelection) {
self.searchSelection = searchSelection;
},
setSearchByProductDescription:function(searchByProductDescription) {
self.searchByProductDescription = searchByProductDescription;
},
setSearchByCustomerFriendlyDescription:function(searchByCustomerFriendlyDescription) {
self.searchByCustomerFriendlyDescription = searchByCustomerFriendlyDescription;
},
setSearchByDisplayName:function(searchByDisplayName) {
self.searchByDisplayName = searchByDisplayName;
},
setSearchAllExtendedAttributes:function(searchAllExtendedAttributes) {
self.searchAllExtendedAttributes = searchAllExtendedAttributes;
},
/**
* Add a list of product IDs to the complex search criteria.
*
* @param productIds The product IDs to add.
*/
addProductIds:function(productIds) {
self.productSearchCriteria.productIds = productIds;
},
/**
* Add a list of item codes to the complex search criteria.
*
* @param itemCodes The item codes to add.
*/
addItemCodes:function(itemCodes) {
self.productSearchCriteria.itemCodes = itemCodes;
},
/**
* Add a list of item classes to the complex search criteria.
*
* @param classCodes The case UPCs to add.
*/
addClasses:function(classCodes) {
self.productSearchCriteria.classCodes = classCodes;
},
/**
* Add a list of commodities to the complex search criteria.
*
* @param commodityCodes The case UPCs to add.
*/
addCommodities:function(commodityCodes) {
self.productSearchCriteria.commodityCodes = commodityCodes;
},
/**
* Add a list of sub-commodities the complex search criteria.
*
* @param subCommodityCodes The case UPCs to add.
*/
addSubCommodities:function(subCommodityCodes) {
self.productSearchCriteria.subCommodityCodes = subCommodityCodes;
},
/**
* Add a list of case UPCs to the complex search criteria.
*
* @param caseUpcs The case UPCs to add.
*/
addCaseUpcs:function(caseUpcs) {
self.productSearchCriteria.caseUpcs = caseUpcs;
},
/**
* Adds a sub-department to the complex search criteria.
*
* @param subDepartment The sub-department to add.
*/
addSubDepartment:function(subDepartment) {
self.productSearchCriteria.subDepartment = subDepartment;
},
/**
* Adds an item class to the complex search criteria.
*
* @param itemClass The item class to add.
*/
addClass:function(itemClass) {
self.productSearchCriteria.itemClass = itemClass;
},
/**
* Adds a commodity to the complex search criteria.
*
* @param classCommodity The commodity to add.
*/
addCommodity:function(classCommodity) {
self.productSearchCriteria.classCommodity = classCommodity;
},
/**
* Adds a sub-commodity to the complex search criteria.
*
* @param subCommodity The sub-commodity to add.
*/
addSubCommodity:function(subCommodity) {
self.productSearchCriteria.subCommodity = subCommodity;
},
/**
* Adds a BDM to the complex search criteria.
*
* @param bdm The BDM to add.
*/
addBdm:function(bdm) {
self.productSearchCriteria.bdm = bdm;
},
/**
* Adds a vendor to the complex search criteria.
*
* @param vendor The vendor to add.
*/
addVendor:function(vendor) {
self.productSearchCriteria.vendor = vendor;
},
/**
* Add a list of UPCs to the complex search criteria.
*
* @param upcs The list of UPC to add.
*/
addUpcs:function(upcs) {
self.productSearchCriteria.upcs = upcs;
},
/**
* Adds a description search to the complex search.
*
* @param description The description the user entered to search for.
* @param searchByProductDescription Whether or not to search for product descriptions (product_master).
* @param searchByCustomerFriendlyDescription Whether or no to search for customer friendly descriptions.
* @param searchByDisplayName Whether or not to search by display name.
* @param searchAllExtendedAttributes Whether or not to searc all extended attribtues.
*/
addDescription:function(description, searchByProductDescription, searchByCustomerFriendlyDescription,
searchByDisplayName, searchAllExtendedAttributes) {
self.productSearchCriteria.description = description;
self.productSearchCriteria.searchByProductDescription = searchByProductDescription;
self.productSearchCriteria.searchByCustomerFriendlyDescription = searchByCustomerFriendlyDescription;
self.productSearchCriteria.searchByDisplayName = searchByDisplayName;
self.productSearchCriteria.searchAllExtendedAttributes = searchAllExtendedAttributes;
},
/**
* Returns the complex search criteria.
*
* @returns {{}|*}
*/
getProductSearchCriteria:function() {
var searchCriteria = angular.copy(self.productSearchCriteria);
// Add the byos objects to the search criteria.
if (self.byosObjects.length > 0) {
searchCriteria.customSearchEntries = self.byosObjects;
}
return searchCriteria;
},
/**
* Empties out the complex search criteria.
*/
clearProductSearchCriteria:function() {
self.productSearchCriteria = {};
self.byosObjects = [];
},
/**
* Sets the build your own search object the user has constructed.
*
* @param objectToSet The BYOS object to store.
*/
setByosObject:function(objectToSet) {
self.byosObject = objectToSet;
},
/**
* Adds a build your own search object to the complex search criteria.
*
* @param objectToAdd The object to add.
*/
addByosObject:function(objectToAdd) {
self.byosObjects.push(objectToAdd);
},
/**
* Removes a build your own search object to the complex search criteria.
*
* @param objectToRemove The object to remove.
*/
removeByosObject:function(objectToRemove) {
var index = -1;
for (var i = 0; i < self.byosObjects.length; i++) {
if (self.byosObjects[i] == objectToRemove) {
index = i;
break;
}
}
if (index >= 0) {
self.byosObjects.splice(index, 1);
}
},
getByosObjects:function() {
return self.byosObjects;
},
/**
* This will return an object with the same structure as the complex
* search but with only one attribute populated. This should be called
* when the user clicks on the search button on the top part of the screen.
*
* @returns {*}
*/
getBasicSearchObject:function() {
if (self.searchType == this.BASIC_SEARCH) {
if (self.selectionType == this.PRODUCT_ID) {
return {productIds: self.searchSelection};
}
if (self.selectionType == this.UPC) {
return {upcs: self.searchSelection};
}
if (self.selectionType == this.ITEM_CODE) {
return {itemCodes: self.searchSelection};
}
if (self.selectionType == this.CASE_UPC) {
return {caseUpcs: self.searchSelection};
}
if (self.selectionType == this.CLASS) {
return {classCodes: self.searchSelection};
}
if (self.selectionType == this.COMMODITY) {
return {commodityCodes: self.searchSelection};
}
if (self.selectionType == this.SUB_COMMODITY) {
return {subCommodityCodes: self.searchSelection};
}
}
if (self.searchType == this.HIERARCHY_SEARCH) {
if (self.selectionType == this.SUB_DEPARTMENT) {
return {subDepartment: self.searchSelection};
}
if (self.selectionType == this.CLASS) {
return {itemClass: self.searchSelection};
}
if (self.selectionType == this.COMMODITY) {
return {classCommodity: self.searchSelection};
}
if (self.selectionType == this.SUB_COMMODITY) {
return {subCommodity: self.searchSelection};
}
}
if (self.selectionType == this.BDM) {
return {bdm: self.searchSelection};
}
if (self.searchType == this.VENDOR_SEARCH) {
return {vendor: self.searchSelection};
}
if (self.searchType == this.BYOS_SEARCH) {
return {customSearchEntries: [self.byosObject]};
}
if (self.searchType == this.DESCRIPTION_SEARCH) {
return {
description: self.searchSelection,
searchByProductDescription: self.searchByProductDescription,
searchByCustomerFriendlyDescription: self.searchByCustomerFriendlyDescription,
searchByDisplayName: self.searchByDisplayName,
searchAllExtendedAttributes: self.searchAllExtendedAttributes
};
}
return null;
}
}
}
})();
|
const Scope = require("./Scope");
var EnqueueSymbol = function(ctx, enclosingScope, defaultPackageName){
this.setNameWithPackage(ctx, ctx.model_type().getText(), defaultPackageName);
this.enclosingScope = enclosingScope;
this.definitions = {};
};
EnqueueSymbol.prototype = Object.create(Scope.prototype);
EnqueueSymbol.prototype.constructor = EnqueueSymbol;
module.exports = EnqueueSymbol;
|
/**
* @file A jQuery wrapper for ColdFusion websockets. The plugin function is {@link jQuery.ws}. The configuration object is {@link jQuery.ws.config}. This plugin is written in ES6, but the package includes a build command that transpiles (and minifies) it to ES5 using {@link https://babeljs.io/|Babel}.
* @author afurey
* @version 1.5.4
* @see {@link jQuery.ws}
*
* @example <caption>Configuring the plugin.</caption>
* $.ws.config.url = 'ws://myserver:1234/cfusion';
* $.ws.config.messageDefaults.app = 'myApplicationName';
*
* @example <caption>Initializing a websocket connection to a ColdFusion websocket channel and listening for incoming data.</caption>
* $.ws('mychannel', function(event, data) {
* console.log(data);
* });
*/
/**
* @typedef WebSocket
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket}
*/
/**
* @typedef MessageEvent
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}
*/
/**
* @typedef EventListener
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/EventListener}
*/
/**
* @typedef DOMException
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMException}
*/
/**
* @callback MessageEventListener
* @description A callback for handling message.
* @param {MessageEvent} event - The event received
* @param {object} message - The message received
*/
/**
* @callback DataEventListener
* @description A callback for handling data messages.
* @param {MessageEvent} event - The event received
* @param {object} data - The message data
* @param {object} message - The entire message
*/
/**
* @namespace jQuery
* @see {@link https://api.jquery.com/}
* @description This is a jQuery plugin that extends jQuery by adding a static method ({@link jQuery.ws}). The plugin uses a configuration object to define defaults and other settings ({@link jQuery.ws.config}).
*/
/**
* @namespace CFWebSocket
* @description This namespace is enclosed in an anonymous scope and cannot be accessed directly.
*/
($ => {
/**
* @private
* @name CFWebSocket.CFWebSocket.config
* @description Global configuration settings for the class. Set directly in the js source file for site-wide settings. Can also be accessed with {@link jQuery.ws.config}.
* @property {!string} url - The URL to connect to with {@link jQuery.ws}
* @property {!object} messageDefaults - Defaults for the control messages sent to ColdFusion
* @property {!string} messageDefaults.appName - The name of your ColdFusion application
* @property {!object} messageDefaults.customOptions - Custom options to pass to the server with every message
*/
let config = {
url: (window.location.protocol === 'https' ? 'wss://' : 'ws://') + window.location.hostname + ':8579/cfusion/cfusion',
messageDefaults: {
ns: 'coldfusion.websocket.channels',
appName: '',
customOptions: {}
}
};
/**
* @public
* @class CFWebSocket.CFWebSocket
* @summary A WebSocket wrapper meant to be used with ColdFusion.
* @description This wrapper implements interfaces for both the standard JavaScript {@link WebSocket} and ColdFusion's WebSocket object (created by the <code>cfwebsocket</code> tag). Supports chaining by returning the called object with each method. Includes an {@link CFWebSocket.CFWebSocket#on|on} method that provides a familiar event-attachment interface.
* @param {!string} url - The url to connect to.
* @param {!(string|object<string,DataEventListener>)} [channels] - One or more channels to subscribe to whenever the connection opens. Specify multiple channels with a comma-delimited string. You can also specify channels as an object whose keys are channel names and values are {@link DataEventListener}s. Channels (and data listeners) can also be added with the {@link CFWebSocket.CFWebSocket#subscribe|subscribe} method. DataEventListeners can also be added with the {@link CFWebSocket.CFWebSocket#on|on} method by using the <code>data</code> event.
* @param {!string|array<string>} [protocol] - A protocol string or array of protocol strings. See {@link WebSocket}.
* @param {!object} [customOptions] - Custom options to pass to the server when subscribing to the channels supplied as the channels argument. These options will only be used for the initial subscribe request.
*/
class CFWebSocket {
constructor(url, channels, protocol, customOptions) {
let complexChannels = (typeof channels === 'object' && channels.constructor === Object);
this.channelHandlers = (complexChannels ? channels : {});
this.eventHandlers = {};
this.oneHandlers = {};
this.w = this.i(url, complexChannels ? Object.keys(channels).join(',') : channels, customOptions);
}
/**
* @public
* @member {!string} CFWebSocket.CFWebSocket#binaryType
* @summary Included for compatibility with JavaScript WebSockets.
*/
get binaryType() {
return this.w.binaryType;
}
set binaryType(v) {
this.w.binaryType = v;
}
/**
* @public
* @member {!number} CFWebSocket.CFWebSocket#bufferedAmount
* @summary Included for compatibility with JavaScript WebSockets. Readonly.
* @see {@link WebSocket}
*/
get bufferedAmount() {
return this.w.bufferedAmount;
}
/**
* @public
* @member {!string} CFWebSocket.CFWebSocket#extensions
* @summary Included for compatibility with JavaScript WebSockets.
*/
get extensions() {
return this.w.extensions;
}
set extensions(v) {
this.w.extensions = v;
}
/**
* @public
* @member {!string} CFWebSocket.CFWebSocket#onclose
* @summary Included for compatibility with JavaScript WebSockets.
*/
get onclose() {
return this.eventHandlers.close;
}
set onclose(v) {
this.eventHandlers.close = v;
}
/**
* @public
* @member {!string} CFWebSocket.CFWebSocket#onerror
* @summary Included for compatibility with JavaScript WebSockets.
*/
get onerror() {
return this.eventHandlers.error;
}
set onerror(v) {
this.eventHandlers.error = v;
}
/**
* @public
* @member {!string} CFWebSocket.CFWebSocket#onmessage
* @summary Included for compatibility with JavaScript WebSockets.
*/
get onmessage() {
return this.eventHandlers.message;
}
set onmessage(v) {
this.eventHandlers.message = v;
}
/**
* @public
* @member {!string} CFWebSocket.CFWebSocket#onopen
* @summary Included for compatibility with JavaScript WebSockets.
*/
get onopen() {
return this.eventHandlers.open;
}
set onopen(v) {
this.eventHandlers.open = v;
}
/**
* @public
* @member {!string} CFWebSocket.CFWebSocket#protocol
* @summary Included for compatibility with JavaScript WebSockets.
*/
get protocol() {
return this.w.protocol;
}
set protocol(v) {
this.w.protocol = v;
}
/**
* @public
* @member {!number} CFWebSocket.CFWebSocket#readyState
* @summary Included for compatibility with JavaScript WebSockets. Readonly.
* @see {@link WebSocket}
*/
get readyState() {
return this.w.readyState;
}
/**
* @public
* @member {!string} CFWebSocket.CFWebSocket#url
* @summary Included for compatibility with JavaScript WebSockets. Readonly.
* @see {@link WebSocket}
*/
get url() {
return this.w.url;
}
/**
* @private
* @method CFWebSocket.CFWebSocket#c
* @summary A private method used internally.
* @description If the event is open or closed and the websocket is in the corresponding state: if a handler is given, calls the given handler; otherwise, fires and removes the last-added one-time handler for the given event.
* @param {!string} event
* @param {!EventListener} [handler]
*/
c(event, handler) {
var args = (event === 'open' && this.readyState === WebSocket.OPEN ? this.o : (event === 'close' && this.readyState === WebSocket.CLOSED ? this.c : undefined));
if (args) {
if (handler) {
handler.apply(this, args);
} else {
this.oneHandlers[event].pop().apply(this, args);
}
}
}
/**
* @private
* @method CFWebSocket.CFWebSocket#i
* @summary A private method used internally.
* @description Creates a new JavaScript WebSocket object and attaches special event handlers used to fire CFWebSocket events.
* @param {!string} subscribeTo - Channel to initially subscribe to. Use a comma-delimited list for multiple channels.
* @return {WebSocket}
*/
i(url, subscribeTo, customOptions) {
let ws = new WebSocket(url);
ws.onopen = (event) => { //note: arrow functions use a fixed this based on the context it in which they were defined
this.s('welcome', undefined, undefined, {
subscribeTo,
customOptions
});
this.o = arguments;
this.f('open', arguments);
};
ws.onclose = (event) => {
this.c = arguments;
this.f('close', arguments);
};
ws.onmessage = event => {
let message = event.data ? JSON.parse(event.data) : {};
if (message.data) {
try {
message.data = JSON.parse(message.data);
} catch (e) {}
}
if (message.code) { //non-zero non-undefined codes are errors
this.f('error', [event, message]);
} else if (message.type === 'data') {
this.f('data', (message.channelname && message.channelname in this.channelHandlers ? message.channelname : undefined), [event, ('data' in message && message.data ? message.data : {}), message]);
} else if (message.reqType === 'subscribeTo') {
if (message.channelssubscribedto) {
this.f('subscribe', [event, message]);
} else {
this.f('error', [event, message]);
}
} else if (message.reqType) {
this.f(message.reqType, [event, message]);
} else {
this.f('error', [event, message]);
}
this.f('message', [event, message]);
};
ws.onerror = () => {
this.f('error', arguments);
};
return ws;
}
/**
* @private
* @method CFWebSocket.CFWebSocket#f
* @summary A private method used internally.
* @description Runs the most appropriate event handler. Will only run one handler at the most. Precedence is channel-specific handlers, one-time handlers, all other handlers. One-time handlers will be removed after firing.
* @param {!string} name - The name of the event
* @param {!string} [channel] - The name of the channel, if applicable
* @param {!array} args - Arguments to pass to the handler
*/
f(name, channel, args) {
if (args === undefined) {
args = channel;
channel = undefined;
}
if (channel && name === 'data') {
this.channelHandlers[channel].apply(this, args);
} else if (name in this.oneHandlers && this.oneHandlers[name].length > 0) {
this.oneHandlers[name].shift().apply(this, args);
} else if (name in this.eventHandlers) {
this.eventHandlers[name].apply(this, args);
}
}
/**
* @private
* @method CFWebSocket.CFWebSocket#s
* @summary A private method used internally.
* @description Sends a ColdFusion websocket control message.
* @param {!string} type - The type of message
* @param {!string} [channel] - The channel
* @param {!object} [customOptions] - Extra custom options to send
* @param {!object} [extras] - Extra parameters to send
*/
s(type, channel, customOptions, extras) {
this.w.send(JSON.stringify($.extend(true, {}, config.messageDefaults, {
type,
channel,
customOptions
}, extras)));
}
/**
* @public
* @method CFWebSocket.CFWebSocket#send
* @summary Included for compatibility with JavaScript WebSockets.
* @description Sends data to the server using the websocket connection. Note that this is not the same as publishing on a channel (see the {@link CFWebSocket.CFWebSocket#publish|publish} method).
* @param {!(string|object|array)} data - The data to send to the server
* @returns {CFWebSocket.CFWebSocket}
* @throws {DOMException} If the connection is not currently OPEN
* @throws {DOMException} If the data is a string that has unpaired surrogates
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#send()}
*/
send(data) {
if ((typeof data === 'object' && channels.constructor === Object) || Array.isArray(data)) {
this.w.send(JSON.stringify(data));
} else {
this.w.send(data);
}
return this;
}
/**
* @public
* @method CFWebSocket.CFWebSocket#close
* @summary Included for compatibility with JavaScript WebSockets.
* @description Closes the websocket connection.
* @param {!number} [code] - A code to send to the server. See {@link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes}.
* @param {!string} [reason] - A human-readable message. No longer than 123 bytes of UTF-8 text.
* @returns {CFWebSocket.CFWebSocket}
* @throws {DOMException} If an invalid code was specified
* @throws {DOMException} If the reason string is too long or contains unpaired surrogates
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#close()}
*/
close(code, reason) {
this.w.close(code, reason);
return this;
}
/**
* @public
* @method CFWebSocket.CFWebSocket#getSubscriberCount
* @summary Included for compatibility with ColdFusion WebSockets.
* @description Retreives the subscriber count from the ColdFusion server.
* @param {!string} channel - The name of the channel to check
* @param {MessageEventListener} callback - A callback to run once the response is received from the server
* @returns {CFWebSocket.CFWebSocket}
*/
getSubscriberCount(channel, callback) {
this.s('getSubscriberCount', channel);
if (callback) {
this.one('getSubscriberCount', callback);
}
return this;
}
/**
* @public
* @method CFWebSocket.CFWebSocket#getSubscriptions
* @summary Included for compatibility with ColdFusion WebSockets.
* @description Retreives the channels that the client is subscribed to.
* @param {MessageEventListener} callback - A callback to run once the response is received from the server
* @return {CFWebSocket.CFWebSocket}
*/
getSubscriptions(callback) {
this.s('getSubscriptions');
if (callback) {
this.one('getSubscriptions', callback);
}
return this;
}
/**
* @public
* @method CFWebSocket.CFWebSocket#isConnectionOpen
* @summary Included for compatibility with ColdFusion WebSockets.
* @description Checks if the connection is open.
* @return {boolean}
* @deprecated Use {@link CFWebSocket.CFWebSocket#readyState|readyState} instead.
*/
isConnectionOpen() {
return this.w.readyState === 1;
}
/**
* @public
* @method CFWebSocket.CFWebSocket#openConnection
* @summary Included for compatibility with ColdFusion WebSockets.
* @description Opens the connection if it was closed. If the connection is already open, does nothing.
* @param {!string} [url] - If provided, a new URL to connect to, else uses the last provided URL
* @returns {CFWebSocket.CFWebSocket}
* @deprecated It is recommended that you create a new CFWebSocket object when you want to open a connection. The current specification for JavaScript WebSockets does not include an open method.
*/
openConnection(url=this.url) {
if (!this.isConnectionOpen()) {
this.w = this.i(url);
}
return this;
}
/**
* @public
* @method CFWebSocket.CFWebSocket#closeConnection
* @summary Included for compatibility with ColdFusion WebSockets.
* @description An alias of {@link CFWebSocket.CFWebSocket#close}.
* @see {@link CFWebSocket.CFWebSocket#close}
* @deprecated You should use the {@link CFWebSocket.CFWebSocket#close|close} method instead.
*/
closeConnection() {
return this.close();
}
/**
* @public
* @method CFWebSocket.CFWebSocket#subscribe
* @summary Included for compatibility with ColdFusion WebSockets.
* @description Subscribes to a single ColdFusion websocket channel.
* @param {!string} channel - The channel to subscribe to
* @param {!object} [data] - The custom options to pass to the server; can be used by the server to filter messages
* @param {DataEventListener} [callback] - A data handler to use for the subscribed channel only
* @returns {CFWebSocket.CFWebSocket}
*/
subscribe(channel, data, callback) {
this.s('subscribe', channel, data);
if (callback) {
this.channelHandlers[channel] = callback;
}
return this;
}
/**
* @public
* @method CFWebSocket.CFWebSocket#unsubscribe
* @summary Included for compatibility with ColdFusion WebSockets.
* @description Unsubscribes from a single ColdFusion websocket channel.
* @param {!string} channel - The channel to unsubscribe from
* @returns {CFWebSocket.CFWebSocket}
*/
unsubscribe(channel) {
this.s('unsubscribe', channel);
return this;
}
/**
* @public
* @method CFWebSocket.CFWebSocket#publish
* @summary Included for compatibility with ColdFusion WebSockets.
* @description Publishes data on a ColdFusion websocket channel.
* @param {!string} channel - The channel to publish on
* @param {!object} data - The data to publish
* @param {object} options - Extra data to send to the server, such as data used for a filter/selector
* @returns {CFWebSocket.CFWebSocket}
*/
publish(channel, data, options) {
try {
data = JSON.stringify(data);
} catch (e) {}
this.s('publish', channel, options, {
data
});
return this;
}
/**
* @public
* @method CFWebSocket.CFWebSocket#authenticate
* @summary Included for compatibility with ColdFusion WebSockets.
* @description Sends an authentication message to the ColdFusion server. This will trigger your ColdFusion application's {@link https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-m-r/onwsauthenticate.html|onWSAuthenticate} callback. Note that you could send data other than an actual username/password (e.g. an auth key) and configure your onWSAuthenticate function to handle it.
* @param {!string} username - A username to supply to the server
* @param {!string} password - A password to supply to the server
* @param {EventListener} callback - A callback to run when the authentication confirmation message is received
* @returns {CFWebSocket.CFWebSocket}
*
* @example
* $.ws().authenticate('foo', 'bar').subscribe('mychannel');
*/
authenticate(username, password, callback) {
this.s('authenticate', undefined, undefined, {
username,
password
});
if (callback) {
this.one('authenticate', callback);
}
return this;
}
/**
* @public
* @method CFWebSocket.CFWebSocket#on
* @summary Provides a familiar event-attachment interface.
* @description Sets an event handler for the CFWebSocket. Each event can have only one handler. Adding a second handler to an event that already has one overwrites the original handler.
* @param {!string} event - Supported events: open, subscribe, welcome, data, unsubscribe, close, error. Using any other event names results in undefined behavior. Adding an open or close event handler after the connection has already been opened will immediately fire the newly-added handler.
* @param {!string} [channel] - Specify a channel. Only works with the data event.
* @param {!(MessageEventListener|DataEventListener)} handler - The callback to use for the event
* @returns {CFWebSocket.CFWebSocket}
*
* @example <caption>The below example shows how you can use this method to attach event handlers.</caption>
* $.ws('mychannel').on('open', function(event, full) {
* console.log('Connected!');
* });
*/
on(event, ...args) {
if (event === 'data' && args.length > 1) {
this.channelHandlers[args[0]] = args[1];
} else if (args.length > 0) {
this.eventHandlers[event] = args[args.length - 1];
}
this.c(event, args[args.length - 1]);
return this;
}
/**
* @public
* @method CFWebSocket.CFWebSocket#one
* @summary Provides a familiar event-attachment interface.
* @description Adds a one-time event handler for the CFWebSocket. Each event can have multiple handlers. Only one handler runs for each firing of an event, event if there are multiple handlers. One-time handlers take precedence over regular handlers.
* @param {!string} event - Supported events: open, subscribe, welcome, data, unsubscribe, close, error. Using any other event names results in undefined behavior. Adding an open or close event handler after the connection has already been opened will immediately fire the newly-added handler.
* @param {!(MessageEventListener|DataEventListener)} handler - The callback to use for the event
* @return {CFWebSocket.CFWebSocket}
*/
one(event, handler) {
if (this.oneHandlers[event]) {
this.oneHandlers[event].push(handler);
} else {
this.oneHandlers[event] = [handler];
}
this.c(event);
return this;
}
}
//JQUERY
/**
* @public
* @function jQuery.ws
* @description Creates a CFWebSocket object, which is a wrapper for JavaScript's own {@link WebSocket} object with added methods for use with ColdFusion's websocket channels.
* @param {string|object<string,DataEventListener>} [channels] - Channel(s) to initially subscribe to. For multiple channels use a comma-delimited list. Use an object whose keys are channels and values are DataEventListeners to specify a separate data listener for each channel.
* @param {object} [customOptions] - Custom options to pass when performing the initial channel subscriptions.
* @param {DataEventListener} [dataHandler] - Either a handler to use for incoming data messages.
* @returns {CFWebSocket.CFWebSocket}
*
* @example <caption>The below examples connects to <code>mychannel</code> and logs any incoming data messages.</caption>
* $.ws('mychannel', function(event, data, message) {
* console.log(data);
* });
*
* @example <caption>In this example we subscribe to multiple channels. Here the same data handler will be used for both channels. To use different handlers, you must call the function separately for each channel.</caption>
* $.ws('mychannel1,mychannel2', function(event, data, message) {
* console.log(data);
* });
*
* @example <caption>Setting a unique data handler for each channel. Here we subscribe to <code>channel1</code> and <code>channel2</code>.</caption>
* $.ws('channel1,channel2', {
* channel1: function(event, data, message) {
* console.log(1);
* },
* channel2: function(event, data, message) {
* console.log(2);
* }
* });
*
* @example <caption>Passing custom data on the initial channel subscription.</caption>
* $.ws('mychannel', {
* recordId: 42,
* authKey: 'blahblahblahsecurekey'
* }, function(event, data, message) {
* //...
* });
*
* @example <caption>You can also save a reference to the CFWebSocket object. This can be useful if you want to be able to add/remove channels, publish on the channel, or send data. Warning: make sure you wait until the WebSocket is connected before trying to use it this way.</caption>
* var myWebSocket = $.ws(...);
* ...
* myWebSocket.publish('somechannel', { message: 'Hello, World!' });
*/
$.ws = (channels, ...args) => {
let hasFunc = (typeof args[0] === 'function');
let ws = new CFWebSocket($.ws.config.url, channels, undefined, hasFunc ? args[1] : args[0]);
if (hasFunc) {
ws.eventHandlers.data = args[0];
}
return ws;
};
/**
* @public
* @name jQuery.ws.config
* @namespace jQuery.ws.config
* @description Global configuration settings for the plugin.
* @property {!string} url - The URL to connect to with {@link jQuery.ws}
* @property {!object} messageDefaults - Defaults for the control messages sent to ColdFusion
* @property {!string} messageDefaults.appName - The name of your ColdFusion application
* @property {!object} messageDefaults.customOptions - Custom options to pass to the server with every message
*
* @example <caption>Passing an auth token with every message to automatically authenticate. This example uses js-cookie.</caption>
* $.ws.config.messageDefaults.customOptions.authkey = Cookies.get('authkey');
*
* @example <caption>Validating an authkey sent in custom options in the channel listener's allowSubscribe callback. The authKeyIsActive function is a stand-in for your own auth key validation logic.</caption>
* component extends="CFIDE.websocket.ChannelListener" {
* ...
* public boolean function allowSubscribe(required struct subscriberInfo) {
* if (authKeyIsActive(arguments.subscriberInfo.authkey)) {
* return true;
* }
* return false;
* }
* ...
* }
*/
$.ws.config = config;
})(jQuery);
|
import React, { useState } from 'react';
import { Button, Paper, TextField, useTheme } from '@material-ui/core';
import { useDispatch } from 'react-redux';
import { MAKE_POST } from '../app/actions';
import { EDIT_POST } from '../app/actions';
function PostForm({ id, onClose, defaultTitle, defaultDescription }) {
const [ title, setTitle ] = useState(defaultTitle || '');
const [ description, setDescription ] = useState(defaultDescription || '');
const dispatch = useDispatch();
const theme = useTheme();
return (
<Paper style={{ padding: theme.spacing(2), display: 'flex', flexDirection: 'column' }}>
<TextField
variant="outlined"
label="Title"
value={title}
onChange={(event) => setTitle(event.currentTarget.value)}
/>
<TextField
multiline
rows={ description.length ? 7 : 3}
variant="outlined"
placeholder="Share some stuff with the world..."
value={description}
onChange={(event) => setDescription(event.currentTarget.value)}
helperText={`${description.length}/400`}
FormHelperTextProps={{ style: { marginLeft: 'auto', marginTop: '-2em', flexBasis: '2em' } }}
/>
<Button
variant="contained"
color="primary"
disabled={!(title.trim().length && description.trim().length) || description.length > 400}
onClick={(event) => {
if (id) {
dispatch({ type: EDIT_POST, payload: { id, title, description }});
onClose();
} else {
dispatch({ type: MAKE_POST, payload: { title, description } });
}
setTitle('');
setDescription('');
}}
>
Submit
</Button>
</Paper>
);
}
export default PostForm;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { connect } from 'react-redux';
import { getBooks } from 'Actions/bookActions';
import { getAuthors } from 'Actions/authorActions';
import { fetchGenres } from 'Actions/genreActions';
import { loadPage, showPage, hidePage } from 'Actions/centerPage';
import pageTypes from '../CenterPage/pageTypes';
const {
BOOKS_FETCHED_PAGE,
AUTHORS_FETCHED_PAGE,
GENRES_FETCHED_PAGE
} = pageTypes;
/**
* @class SidebarView
* @extends { React.Component }
* @description Renders various view options on sidebar
* @param { object } props
* @returns { JSX }
*/
class SidebarViews extends Component {
constructor(props){
super(props);
this.state = {
isLoading: false
}
this.viewCategories = this.viewCategories.bind(this);
this.viewBooks = this.viewBooks.bind(this);
this.viewAuthors = this.viewAuthors.bind(this);
}
/**
* @method viewCategories
* @memberof SidebarViews
* @description Handles click events to view boook categories
* @param { event } event handler
* @returns { void }
*/
viewCategories(event){
event.preventDefault();
this.props.showPage(GENRES_FETCHED_PAGE)
this.setState({ isLoading: true });
this.props.fetchGenres()
.then((data)=>{
if(data.response && data.response.status >= 400){
this.setState({
isLoading:false
});
}else{
this.props.showPage(GENRES_FETCHED_PAGE)
}
})
}
/**
* @method viewBooks
* @memberof SidebarViews
* @description Handles click events to view boooks
* @param { event } event handler
* @returns { void }
*/
viewBooks(event){
event.preventDefault();
this.props.showPage(BOOKS_FETCHED_PAGE) //test purpose
this.setState({ isLoading: true });
this.props.getBooks()
.then((data)=>{
if(data.response && data.response.status >= 400){
this.setState({
isLoading:false
});
}else{
this.props.showPage(BOOKS_FETCHED_PAGE)
}
})
}
/**
* @method viewCategories
* @memberof SidebarViews
* @description Handles click events to view authors
* @param { event } event handler
* @returns { void }
*/
viewAuthors(event){
event.preventDefault();
this.props.showPage(AUTHORS_FETCHED_PAGE) //test purpose
this.setState({ isLoading: true });
this.props.getAuthors()
.then((data)=>{
if(data.response && data.response.status >= 400){
this.setState({
isLoading:false
});
}else{
this.props.showPage(AUTHORS_FETCHED_PAGE)
}
})
}
render(){
const View = ({id, icon, name, onClick, disabled}) => (
<span
id = { id }
className={classnames(`glyphicon glyphicon-${ icon }`)}
onClick={ onClick }
disabled ={ disabled }>
<p>{ name }</p>
</span>
)
return(
<div id="sidebar-views">
<View
id = "view-genres"
icon={'th-list'}
name={'Book categories'}
onClick={this.viewCategories}
disabled={this.state.isLoading}/>
<View
id = "view-books"
icon={'book'}
name={'Books'}
onClick={this.viewBooks}
disabled={this.state.isLoading}/>
<View
id = "view-authors"
icon={'user'}
name={'Authors'}
onClick={this.viewAuthors}
disabled={this.state.isLoading}/>
</div>
)
}
}
const actionCreators = {
getBooks,
getAuthors,
fetchGenres,
showPage,
loadPage,
hidePage
}
export { SidebarViews }
export default connect(null, actionCreators)(SidebarViews);
|
import React from 'react';
import Item from './item.js';
const List = (props) => {
return (
<ul>
{props.list.map((item, i) =>
<Item
key={item.id}
link={item.volumeInfo.infoLink}
image={item.volumeInfo.imageLinks ? item.volumeInfo.imageLinks.thumbnail : '#'}
title={item.volumeInfo.title}
author={item.volumeInfo.authors ? item.volumeInfo.authors[0] : 'Unknown'}
description={item.volumeInfo.description}
/>
)}
</ul>
);
};
export default List;
|
'use strict';
var debug = require('debug')('plugin:ldap');
var ldap = require('ldapjs');
function sendError(res,code,msg) {
var errorInfo = {
"code": code,
"message": msg
};
res.writeHead(code, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(errorInfo));
res.end();
}
module.exports.init = function(config, logger, stats) {
return {
onrequest: function(req, res, next) {
var ldapurl = 'ldap://'+config.host+':'+config.port;
var client = ldap.createClient({
url: ldapurl
});
var auth=req.headers['authorization'];
if (auth===undefined) {
sendError(res,401,"Missing authorization header");
}
console.log(auth);
var tmp = auth.split(' ');
var buf = new Buffer(tmp[1], 'base64');
var plain_auth = buf.toString();
var creds = plain_auth.split(':');
if (creds[1]===undefined) {
sendError(res,403,"Bad authorization header");
}
var username = creds[0];
var password = creds[1].trim();
console.log(username);
console.log(password);
var dn='cn='+username+','+config.base;
client.bind(dn, password, function(err) {
if (err) {
sendError(res,403,"LDAP bind failed");
} else {
console.log("Bind Successfull");
next();
}
});
}
};
}
|
function deleteRows() {
document.Form1.action = "/delete";
document.Form1.submit(); // Submit the page
}
function edit() {
if (document.querySelectorAll('input[type="checkbox"]:checked').length <= 1) {
document.Form1.action = "/edit";
document.Form1.submit(); // Submit the page
} else {
alert("Please select just one row to be edited");
}
}
function getTable() {
microAjax("datagrid", function (msg) {
//msg is the HTML received from server
document.getElementById('datagrid').innerHTML = msg;
});
}
|
const { resolve } = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const { root, src, dist } = require('../config');
const CopyPlugin = require('copy-webpack-plugin');
module.exports = merge.smart(require('./webpack.base'), {
target: 'electron-main',
entry: {
main: [`${src}/index.ts`],
},
output: {
path: resolve(root, dist)
},
externals: [
(context, request, callback) => {
if (request && request.indexOf('node_modules') > 0) {
return callback(null, 'commonjs ' + request);
}
callback();
}
],
plugins: [
new webpack.IgnorePlugin(/^(spawn-sync|bufferutil|utf-8-validate)$/),
// Electron uses package.json to find name and version
new CopyPlugin([{
from: resolve(root, './package.json')
}])
]
});
|
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchUser } from '../redux/actions/index';
export class Main extends Component {
componentDidMount() {
this.props.fetchUser();
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center' }}>
<Text>User is logged in</Text>
</View>
)
}
}
const mapDispatchToProps = (dispatch) => bindActionCreators({fetchUser}, dispatch);
export default connect(null, mapDispatchToProps)(Main);
|
/**
* Created by Aniket
*/
var app = angular.module("app", ['angular-md5', 'ngRoute', 'angularUUID2', 'ngCookies' , 'angularUtils.directives.dirPagination' , 'ngCart'])
app.config(['$routeProvider','$sceProvider',
function ($routeProvider, $sceProvider) {
$sceProvider.enabled(false);
$routeProvider.
when('/login', {
title: 'Login',
templateUrl: 'htmlPages/login.html',
controller: 'loginCtrl'
})
.when('/', {
title: 'Login',
templateUrl: 'htmlPages/login.html',
controller: 'loginCtrl'
})
.when('/userPage', {
title: 'userPage',
templateUrl: 'htmlPages/userPage1.html',
controller: 'userPageCtrl1'
})
.when('/userInfo', {
title: 'userPage',
templateUrl: 'htmlPages/userInfo.html',
controller: 'userPageCtrl1'
})
.when('/showUsers', {
title: 'showUsers',
templateUrl: 'htmlPages/showUsers.html',
controller: 'adminPageCtrl'
})
.when('/returnPage', {
title: 'userPage',
templateUrl: 'htmlPages/returnPage.html',
controller: 'userPageCtrl1'
})
.when('/recommendation', {
title: 'userPage',
templateUrl: 'htmlPages/recommendation.html',
controller: 'userPageCtrl1'
})
.when('/orderPage', {
title: 'orderPage',
templateUrl: 'htmlPages/userPage.html',
controller: 'userPageCtrl1'
})
.when('/addOrder', {
title: 'orderPage',
templateUrl: 'htmlPages/addItems.html',
controller: 'managerPageCtrl'
})
.when('/managerPage', {
title: 'managerPage',
templateUrl: 'htmlPages/managerPage.html',
controller: 'managerPageCtrl'
})
.when('/adminPage', {
title: 'adminPage',
templateUrl: 'htmlPages/admin.html',
controller: 'adminPageCtrl'
})
.when('/makeAdmin', {
title: 'adminPage',
templateUrl: 'htmlPages/makeAdmin.html',
controller: 'adminPageCtrl'
})
.when('/authorizeManager', {
title: 'adminPage',
templateUrl: 'htmlPages/AuthorizeManager.html',
controller: 'adminPageCtrl'
})
.when('/create_account', {
title: 'create_account',
templateUrl: 'htmlPages/create_account.html',
controller: 'loginCtrl'
})
.when('/cart', {
title: 'cart',
templateUrl: 'htmlPages/cart.html',
controller: 'userPageCtrl'
})
.otherwise({
redirectTo: '/login'
});
}])
|
var path = require("path");
module.exports = function(app){
app.get("/survey", function(req, res){
res.sendFile(path.join(__dirname, "/../public/survey.html"))
});
// this routes to "home" if anything other than "/survey" is entered in URL
app.get("*", function(req, res){
res.sendFile(path.join(__dirname, "/../public/home.html"))
})
}
|
'use strict';
module.exports = function (app) {
function ExpressUtils() {
this.backupBody = function (req, res, next) {
req.oldBody = req.body;
next();
};
this.normalizeBody = function (req, res, next) {
var body = req.body,
i;
for (i in body) {
if (body[i] === 'undefined') {
body[i] = undefined;
} else if (body[i] === 'null') {
body[i] = null;
} else if (body[i] === 'true') {
body[i] = true;
} else if (body[i] === 'false') {
body[i] = false;
}
}
next();
};
}
var expressUtils = new ExpressUtils();
app.set('ExpressUtils', expressUtils);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.