text stringlengths 7 3.69M |
|---|
app.factory('chartServ',function(constServ){
var chartCommon = {
reflow: true,
credits: {enabled: false},
legend: {enabled: true},
title: {text: ''},
tooltip: {pointFormat: '<b>{series.name}</b> : {point.y:.2f}'},
navigator: {enabled: false},
scrollbar: {enabled: false},
rangeSelector: {enabled: false},
exporting: {enabled: false},
plotOptions: {
column: {
pointPlacement: 'between',
pointPadding: 0,
groupPadding: 0,
borderWidth: 0.5
}
},
chart: {
alignTicks: true,
pinchType: 'none',
zoomType: 'none'
},
series: [{
type: 'column',
zIndex: 1,
dataGrouping: {enabled: false}
}]
};
var pieCommon = {
chart: {
plotBackgroundColor: null,
plotBorderWidth: 0
},
title : {
userHTML: true,
text: '',
align: 'center',
verticalAlign: 'middle',
style: {
fontWeight: 'bold',
fontSize: '2em',
textShadow: "rgb(255, 255, 255) 0px 0px 10px"
},
y: 0,
floating: true
},
subtitle: {
userHTML: true,
align: 'center',
verticalAlign: 'middle',
style: {
fontWeight: 'bold',
textShadow: "rgb(255, 255, 255) 0px 0px 10px"
},
y: 30,
floating: true
},
options: {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie',
height: 300
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
userHTML: true,
formatter: function(){
var temp = '<div style="text-align:center;"><span style="font-size:2.25em;color:'+this.point.color+'">'+
Highcharts.numberFormat(this.percentage,1)+'%</span><br>'+
this.point.name+'<br>'+Highcharts.numberFormat(this.y,2)+' '+this.point.unit+'</div>';
return temp;
}
},
}
},
tooltip: {pointFormat: '<b>{point.y:.2f} {point.unit}</b> ({point.percentage:.1f}%)'}
},
tooltip: {pointFormat: '<b>{point.y:.2f} {point.unit}</b> ({point.percentage:.1f}%)'},
credits: {enabled: false},
navigator: {enabled: false},
scrollbar: {enabled: false},
rangeSelector: {enabled: false},
exporting: {enabled: false},
series: [{colorByPoint: true}]
};
var pieCommon2 = angular.copy(pieCommon);
delete pieCommon2.options;
pieCommon2.chart = {
height: 250,
plotBackgroundColor: null,
plotBorderWidth: 0,
plotShadow: false,
type: 'pie'
};
pieCommon2.plotOptions = {pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
userHTML: true,
formatter: function(){
var temp = '<div style="text-align:center;"><span style="font-size:1.5em;color:'+this.point.color+'">'+
Highcharts.numberFormat(this.percentage,1)+'%</span><br>'+
this.point.name+'</div>';
return temp;
},
distance: 20
},
innerSize: '60%',
}};
var pieCommon3 = angular.copy(pieCommon);
delete pieCommon3.options;
pieCommon3.chart = {
height: 250,
plotBackgroundColor: null,
plotBorderWidth: 0,
plotShadow: false,
type: 'pie'
};
pieCommon3.plotOptions = {pie: {
allowPointSelect: true,
cursor: 'pointer',
showInLegend: true,
dataLabels: {
enabled: true,
userHTML: true,
formatter: function(){
var temp = '<div style="text-align:center;"><span style="font-size:1.1em;color:'+this.point.color+'">'+
Highcharts.numberFormat(this.percentage,1)+'%</span><br></div>';
return temp;
},
distance: 30
},
innerSize: '60%',
}};
var pieCommon4 = {
chart: {
plotBackgroundColor: null,
plotBorderWidth: 0
},
title : {
userHTML: true,
text: '',
align: 'center',
verticalAlign: 'middle',
style: {
fontWeight: 'bold',
fontSize: '2em',
textShadow: "rgb(255, 255, 255) 0px 0px 10px"
},
y: 0,
floating: true
},
subtitle: {
userHTML: true,
align: 'center',
verticalAlign: 'middle',
style: {
fontWeight: 'bold',
textShadow: "rgb(255, 255, 255) 0px 0px 10px"
},
y: 30,
floating: true
},
options: {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie',
height: 450
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
userHTML: true,
formatter: function(){
var temp = '<div style="text-align:center;"><span style="font-size:2.25em;color:'+this.point.color+'">'+
Highcharts.numberFormat(this.percentage,1)+'%</span><br>'+
this.point.name+'<br>'+Highcharts.numberFormat(this.y,2)+' '+this.point.unit+'</div>';
return temp;
}
},
}
},
tooltip: {pointFormat: '<b>{point.y:.2f} {point.unit}</b> ({point.percentage:.1f}%)'}
},
tooltip: {pointFormat: '<b>{point.y:.2f} {point.unit}</b> ({point.percentage:.1f}%)'},
credits: {enabled: false},
legend: {enabled: false},
navigator: {enabled: false},
scrollbar: {enabled: false},
rangeSelector: {enabled: false},
exporting: {enabled: false},
series: [{colorByPoint: true}]
};
var xAxisPattern = {
type: 'datetime',
ordinal: false,
labels: {style: {fontWeight :'bold'}},
title: {
align: 'high',
text: 'time'
}
};
var yAxisPattern = {
min: 0,
title: {text: ''},
tickPosition: "outside",
tickAmount: 5
};
var dataGrouping = {
approxmation: 'average',
enabled: true,
forced: true,
units: [['minute']]
};
return {
getGroupping : function(val){
var temp = angular.copy(dataGrouping);
temp.units[0].push([val]);
return temp;
},
getYAxis : function(yName,opposite){
var temp = angular.copy(yAxisPattern);
switch(yName){
case 'energy':
temp.title.text = 'Energy (kWh)';
break;
case 'peak':
case 'power':
temp.title.text = 'Power (kW)';
break;
case 'temperature':
temp.title.text = 'Temperature(°C)';
break;
case 'humidity':
temp.title.text = 'Humidity (%)';
break;
case 'illuminance':
temp.title.text = 'Illuminance (lux)';
break;
case 'pm':
temp.title.text = 'PM2.5 (µg/m^3)';
break;
case 'AQI':
temp.title.text = 'AQI';
break;
default:
break;
}
if(opposite) temp.opposite = true;
return temp;
},
getYAxis2 : function(yName,opposite){
var temp = angular.copy(yAxisPattern);
switch(yName){
case 'energy':
temp.title.text = 'Energy (kWh)';
break;
case 'peak':
case 'power':
temp.title.text = 'Power (W)';
break;
case 'temperature':
temp.title.text = 'Temperature(°C)';
break;
case 'humidity':
temp.title.text = 'Humidity (%)';
break;
case 'illuminance':
temp.title.text = 'Illuminance (lux)';
break;
default:
break;
}
if(opposite) temp.opposite = true;
return temp;
},
getXAxis :function(xName){
var temp = angular.copy(xAxisPattern);
temp.labels.formatter = function(){return (new Date(this.value)).getHours();};
temp.tickInterval = 2 * 60 * 60 * 1000;
switch(xName){
case 'month':
temp.labels.formatter = function(){return (new Date(this.value)).getDate();};
temp.tickInterval = 2 * 60 * 60 * 1000 * 24;
temp.title.text = 'time (date)';
break;
case 'year':
temp.labels.formatter = function(){return constServ.getMonth((new Date(this.value)).getMonth());};
temp.tickInterval = 2 * 60 * 60 * 1000 * 12 * (365 / 12);
temp.title.text = 'time (month)';
break;
default:
var now = new Date();
temp.max = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1,0,0,0,0).getTime();
temp.min = new Date(now.getFullYear(), now.getMonth(), now.getDate(),0,0,0,0).getTime();
// console.log(temp.max,temp.min);
delete temp.labels;
delete temp.tickInterval;
break;
}
return temp;
},
getCommon :function(xName,yName){
var chart = angular.copy(chartCommon);
chart.xAxis = this.getXAxis(xName);
chart.yAxis = this.getYAxis(yName);
return chart;
},
getCommon2 :function(xName,yName){
var chart = angular.copy(chartCommon);
chart.xAxis = this.getXAxis(xName);
chart.yAxis = this.getYAxis2(yName);
return chart;
},
getPlotLine: function(name,value,color){return {
value: value,
color: color,
width: 1,
zIndex: 20,
dashStyle: 'solid',
label: {
text: name,
style: {color: color}
}
};},
getPie :function(data){
var pie = angular.copy(pieCommon);
pie.series[0].data = data;
return pie;
},
getPie2: function(data){
var pie = angular.copy(pieCommon2);
pie.series[0].data = data;
return pie;
},
getPie3: function(data){
var pie = angular.copy(pieCommon3);
pie.series[0].data = data;
return pie;
},
getPie4: function(data){
var pie = angular.copy(pieCommon4);
pie.series[0].data = data;
return pie;
},
getOption :function(){return chartOptions;}
};
});
|
import React, { Component, PropTypes } from 'react'
class Content extends Component {
render () {
let side = {
left:this.props.type=="right"?'50%':'10%'
}
let usnClass = this.props.type=='left'?'username-left':'username-right'
let float = this.props.type=='right'?{float:'right'}:{}
return (
<div className='content' style={side}>
<div className='content-title'>
<div className='user-icon' style={float}></div>
<h4 className={usnClass}>{this.props.data.user}</h4>
</div>
<div className="history-content" >
<h4 className='content-text'>{this.props.data.text}</h4>
</div>
</div>
)
}
}
Content.propTypes = {
type:PropTypes.string.isRequired,//决定左或者右
data:PropTypes.object.isRequired,//内容
/*
data:{
text:,
status:
}
*/
}
export default Content |
const fs = require('fs')
function sumOfQuantities(evt) {
var count = 0;
var order = evt.order.order;
var shipmentList = order.shipmentList;
var firstShipment = shipmentList[0];
// console.log('firstShipment keys: ' + Object.keys(firstShipment));
var lineItemList = firstShipment.lineItemList;
for (var i = 0; i < lineItemList.length; i++) {
var item = lineItemList[i];
var qty = item.quantity;
count = count + qty;
}
return count;
}
// function GetQuantity_original(evt) {
// var count = 0;
// var order = evt.order;
// var shipmentList = order.shipmentList;
// var firstShipment = shipmentList[0];
// // console.log('firstShipment keys: ' + Object.keys(firstShipment));
// var lineItemList = firstShipment.lineItemList;
// for (var i = 0; i < lineItemList.length; i++) {
// var item = lineItemList[i];
// var qty = item.quantity;
// count = count + qty;
// }
// return count;
// }
// A very defensive function; ensures the evt is as we expect it.
function GetQuantity(evt) {
var count = 0;
if ('order' in evt) {
var order = evt.order;
if ('shipmentList' in order) {
var shipmentList = order.shipmentList;
if (Array.isArray(shipmentList)) {
if (shipmentList.length > 0) {
var firstShipment = shipmentList[0];
var lineItemList = firstShipment.lineItemList;
if (Array.isArray(lineItemList)) {
if (lineItemList.length > 0) {
for (var i = 0; i < lineItemList.length; i++) {
var item = lineItemList[i];
if ('quantity' in item) {
var qty = item.quantity;
count = count + qty;
}
}
}
}
}
}
}
}
return count;
}
if (false) {
var infile = 'data/test_json_withtime2.json'
var jstr = fs.readFileSync(infile, 'utf-8').toString();
var order = JSON.parse(jstr);
var evt = {};
evt['order'] = order;
var sum = sumOfQuantities(evt);
console.log(sum);
}
if (true) {
var infile = 'data/test_json_withtime2_ok_msg.json'
var jstr = fs.readFileSync(infile, 'utf-8').toString();
var evt = JSON.parse(jstr);
var count = GetQuantity(evt);
console.log(count);
var jstr = '{"something":"unexpected"}';
var evt = JSON.parse(jstr);
var count = GetQuantity(evt);
console.log(count);
}
|
import React from 'react'
const BOLD = {
fontWeight: 'bold'
}
const ITALIC = {
fontStyle: 'italic'
}
const BOLD_ITALIC = {
fontFamily: 'bold-italic'
}
export function renderMark(mark, marks) {
if (
marks.size > 1 &&
marks.some(m => m.type == 'bold') &&
marks.some(m => m.type == 'italic')
) {
return mark.type == 'bold'
? BOLD_ITALIC
: null
}
if (mark.type == 'bold') return BOLD
if (mark.type == 'italic') return ITALIC
}
|
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const assert = chai.assert;
const app = require('../../lib/app');
const mongoose = require('mongoose');
process.env.DB_URI = 'mongodb://localhost:27017/user-api-test';
require('../../lib/connection');
describe('user', () => {
before(() => mongoose.connection.dropDatabase());
const user = {
username: 'user',
password: 'password'
};
const request = chai.request(app);
describe('user management', () => {
const badRequest = (url, data, error) =>
request
.post(url)
.send(data)
.then(
() => { throw new Error('status should not be ok'); },
res => {
assert.equal(res.status, 400);
assert.equal(res.response.body.error, error);
}
);
it('signup requires username', () =>
badRequest('/user/signup', { password: 'password' }, 'username and password must be provided')
);
it('signup requires password', () =>
badRequest('/user/signup', { username: 'username' }, 'username and password must be provided')
);
let token = '';
it('signup', () =>
request
.post('/user/signup')
.send(user)
.then(res => assert.ok(token = res.body.token))
);
it('can\'t use same user name', () =>
request
.post('/user/signup')
.send(user)
.then(
() => { throw new Error('status should not be ok'); },
res => {
assert.equal(res.status, 400);
assert.equal(res.response.body.error, 'username user already exists');
}
)
);
it('signin requires username', () =>
badRequest('/user/signin', { password: 'password' }, 'username and password must be provided')
);
it('signin requires password', () =>
badRequest('/user/signin', { username: 'user' }, 'username and password must be provided')
);
it('signin with wrong user', () =>
request
.post('/user/signin')
.send({ username: 'bad user', password: user.password })
.then(
() => { throw new Error('status should not be ok');},
res => {
assert.equal(res.status, 400);
assert.equal(res.response.body.error, 'invalid username or password');
}
)
);
it('user can delete own account', () => {
let unhappyUser = {
username: 'unhappy',
password: 'abcd'
};
return request
.post('/user/signup')
.send(unhappyUser)
.then(res => res.body.token)
.then((token) => {
return request
.delete('/user/me')
.set('Authorization', token);
})
.then(res => {
assert.isOk(res.body.message);
});
});
it('user can update username', () => {
let changeUser = {
username: 'mrbigglesworth',
password: 'abcd'
};
return request
.post('/user/signup')
.send(changeUser)
.then(res => res.body.token)
.then((token) => {
return request
.patch('/user/me/changeAccountInfo')
.send({username: 'hungrymonkey'})
.set('Authorization', token);
})
.then(res => {
console.log(res.body.username);
assert.equal(res.body.username, 'hungrymonkey');
});
});
it('user can update username and password', () => {
let changeUser = {
username: 'mrbigglesworth',
password: 'abcd'
};
let userHash = '';
let newHash = '';
return request
.post('/user/signup')
.send(changeUser)
.then(res => res.body.token)
.then((token) => {
return request
.get('/user/mrbigglesworth')
.set('Authorization', token)
.then(res => {
userHash = res.body.hash;
return request
.patch('/user/me/changeAccountInfo')
.send({password: 'efgh'})
.set('Authorization', token)
.then(res => newHash = res.body.hash);
});
})
.then(res => {
console.log('NEWHASH', newHash, 'USERHASH', userHash);
assert.notEqual(newHash, userHash);
});
});
});
describe('user during play', () => {
let johnDoe = {
username: 'johnDoe',
password: 'abcd'
};
let johnDoeToken = '';
let testAsset3 = {
asset_type: 'House',
model: 'Tiny Home',
purchase_price: 1000
};
function saveAsset (token, asset) {
return request
.post('/assets')
.send(asset)
.set('Authorization', token)
.then(res => res.body);
}
it('receives properties to user object on signup', () => {
return request
.post('/user/signup')
.send(johnDoe)
.then(res => johnDoeToken = res.body.token)
.then(() => {
return request
.get(`/user/${johnDoe.username}`)
.set('Authorization', johnDoeToken);
})
.then((res) => {
assert.ok(res.body.bank_account);
assert.equal(res.body.retired, false);
});
});
it('can add assets to user object instance', () => {
return request
.post ('/user/signin')
.send(johnDoe)
.then(res => {
johnDoeToken = res.body.token;
return saveAsset(johnDoeToken, testAsset3);
})
.then(savedAsset3 => {
testAsset3._id = savedAsset3._id;
testAsset3.__v = savedAsset3.__v;
return testAsset3;
})
.then((testAsset3) =>
request
.post('/user/johnDoe/assets')
.send({ johnDoeToken, _id: testAsset3._id })
.set('Authorization', johnDoeToken)
.then(res => {
console.log('RESPONSE', res.body);
assert.equal(res.body.assets.length, 1);
assert.ok(res.body.assets[0].asset_name);
})
);
});
});
}); |
const cryptocookies = require('./build/Release/cryptocookies');
module.exports = cryptocookies;
|
import { mathjaxRender } from './latex-to-svg';
function getMathImgSrcList(latexArr) {
const BASE64_MAP = {
ykparallelogram:
'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c3ZnIHdpZHRoPSIxOHB4IiBoZWlnaHQ9IjEycHgiIHZpZXdCb3g9IjAgMCAxOCAxMiIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4gICAgICAgIDx0aXRsZT7lhazlvI8vNy9qaWhlLTE2IGNvcHk8L3RpdGxlPiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4gICAgPGRlZnM+PC9kZWZzPiAgICA8ZyBpZD0i5YWs5byPLzcvamloZS0xNi1jb3B5IiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4gICAgICAgIDxnIGlkPSJHcm91cC00MyIgZmlsbD0iIzAwMDAwMCI+ICAgICAgICAgICAgPHBhdGggZD0iTTQuMjg3ODA3MTEsMS42NTE2ODUzOSBMMi4xMTIzMTQ5NywxMC4zNDgzMTQ2IEwxMy44MTM4MjU3LDEwLjM0ODMxNDYgTDE1Ljk4OTMxNzksMS42NTE2ODUzOSBMNC4yODc4MDcxMSwxLjY1MTY4NTM5IFogTTE1LjAzMzQxOTgsMTIgTDAsMTIgTDIuOTY5MzI3MDMsMCBMMTgsMCBMMTUuMDMzNDE5OCwxMiBaIiBpZD0iRmlsbC0yMyI+PC9wYXRoPiAgICAgICAgPC9nPiAgICA8L2c+PC9zdmc+',
ykrectangle:
'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c3ZnIHdpZHRoPSIyMHB4IiBoZWlnaHQ9IjEycHgiIHZpZXdCb3g9IjAgMCAyMCAxMiIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4gICAgICAgIDx0aXRsZT7lhazlvI8vNy9qaWhlLTE1IGNvcHk8L3RpdGxlPiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4gICAgPGRlZnM+PC9kZWZzPiAgICA8ZyBpZD0i5YWs5byPLzcvamloZS0xNS1jb3B5IiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4gICAgICAgIDxnIGlkPSJHcm91cC00MyIgZmlsbD0iIzAwMDAwMCI+ICAgICAgICAgICAgPHBhdGggZD0iTTEuNzk3NjQ5OTMsMTAuMTYyNTc2NyBMMTguMjA1NDAyMSwxMC4xNjI1NzY3IEwxOC4yMDU0MDIxLDEuODAzNjgwOTggTDEuNzk3NjQ5OTMsMS44MDM2ODA5OCBMMS43OTc2NDk5MywxMC4xNjI1NzY3IFogTTAsMTIgTDIwLDEyIEwyMCwwIEwwLDAgTDAsMTIgWiIgaWQ9IkZpbGwtMjIiPjwvcGF0aD4gICAgICAgIDwvZz4gICAgPC9nPjwvc3ZnPg==',
ykcong:
'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c3ZnIHdpZHRoPSIzMnB4IiBoZWlnaHQ9IjE2cHgiIHZpZXdCb3g9IjAgMCAzMiAxNiIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4gICAgICAgIDx0aXRsZT4xeHVndWFueGktMTIgY29weUAyeDwvdGl0bGU+ICAgIDxkZXNjPkNyZWF0ZWQgd2l0aCBTa2V0Y2guPC9kZXNjPiAgICA8ZGVmcz48L2RlZnM+ICAgIDxnIGlkPSIxeHVndWFueGktMTItY29weSIgc3Ryb2tlPSJub25lIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+ICAgICAgICA8ZyBpZD0iMXh1Z3VhbnhpLTEyIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg4LjAwMDAwMCwgMC4wMDAwMDApIiBmaWxsPSIjMjkyQzMzIj4gICAgICAgICAgICA8cGF0aCBkPSJNMCwxMy44MTU0Mjk3IEwxNiwxMy44MTU0Mjk3IEwxNiwxNS40NzA3MDMxIEwwLDE1LjQ3MDcwMzEgTDAsMTMuODE1NDI5NyBaIE03LjIzNzYwMjY5LDMuNjUyODIwMTggQzguNDM2Njc3MSwwLjk0NDg1MjUzMyAxMC4xNjI3OTU4LDQuOTczNjM3NTZlLTE1IDEyLjExMTU1MTIsMy4xMDg2MjQ0N2UtMTUgQzE0LjI4NTY2MzEsNi44NDg4NTI1OWUtMTUgMTYsMS43NzkwNTAwNSAxNiw0LjAwMDU2NjM2IEMxNiw2LjE4OTI4Mzg0IDE0LjMzNjkzMTgsNy44ODM0MDI1NyAxMi4xNTM5OTM3LDggTDEyLjA2OTEwODcsNi4zMTc4MTY0NiBDMTMuNDAzMzgwMyw2LjI0NjU0ODkxIDE0LjM2Mjc1ODQsNS4yNjkyNTg2OSAxNC4zNjI3NTg0LDQuMDAwNTY2MzYgQzE0LjM2Mjc1ODQsMi43MDYxMDc4OSAxMy4zNzgyNjI1LDEuNjg0NDQ5IDEyLjExMTU1MTIsMS42ODQ0NDkgQzEwLjc1NTg3MjQsMS42ODQ0NDkgOS42Mjg0MTIzLDIuMzAyNDQ5MzIgOC43MTgxNTgxNCw0LjM3MDQ1Mjg4IEw4LjcxNzA4MzI5LDQuMzY5OTUxMzggQzcuNTE4Mjc2MzksNy4wNzcxNjU0MyA1LjgzNzAwNzIyLDggMy44ODg0NDg4Miw4IEMxLjcxNDMzNjg5LDggMCw2LjIyMDk0OTk1IDAsMy45OTk0MzM2NCBDMCwxLjgxMDcxNjE2IDEuNjYzMDY4MjQsMC4xMTY1OTc0MzIgMy44NDYwMDYzNCwxLjMzMjI2NzYzZS0xNSBMMy45MzA4OTEzMSwxLjY4MjE4MzU0IEMyLjU5NjYxOTY3LDEuNzUzNDUxMDkgMS42MzcyNDE2MSwyLjczMDc0MTMxIDEuNjM3MjQxNjEsMy45OTk0MzM2NCBDMS42MzcyNDE2MSw1LjI5Mzg5MjExIDIuNjIxNzM3NTQsNi4zMTU1NTEgMy44ODg0NDg4Miw2LjMxNTU1MSBDNS4yNDQxMjc2Miw2LjMxNTU1MSA2LjMyNTU3ODgyLDUuNzE5OTk5MjIgNy4yMzU4MzI5NywzLjY1MTk5NTY2IEw3LjIzNzYwMjY5LDMuNjUyODIwMTggWiBNMCwxMCBMMTYsMTAgTDE2LDExLjY1NTI3MzQgTDAsMTEuNjU1MjczNCBMMCwxMCBaIiBpZD0iQ29tYmluZWQtU2hhcGUiPjwvcGF0aD4gICAgICAgIDwvZz4gICAgPC9nPjwvc3ZnPg=='
};
// 因为公式编辑器已经在编辑过滤,所有这里不做filter
return new Promise(resolve => {
mathjaxRender(latexArr).then(svgs => {
const list = [];
const promises = Array.from(svgs).map((svg, index) => {
return new Promise(res => {
Array.from(svg.querySelectorAll('image')).forEach(img => {
const href = img.getAttribute('href') || '';
img.setAttribute(
'xlink:href',
BASE64_MAP[
href.slice(href.lastIndexOf('/') + 1, href.lastIndexOf('.'))
] || '',
);
img.removeAttribute('href');
});
const area = document.createElement('canvas');
area.setAttribute('width', '500px');
area.setAttribute('height', '500px');
area.setAttribute('style', 'display: none');
// 转换
if (window.canvg === undefined) {
throw new Error('canvg is needed. Please refer to demo');
}
window.canvg(area, svg.outerHTML, {
ignoreClear: false,
renderCallback: () => {
// 找到自己的位置
list[index] = {
src: area.toDataURL('image/png'),
latex: latexArr[index]
.slice(1, latexArr[index].length - 1)
.replace(/>/g, '>')
.replace(/</g, '<'),
};
res();
},
});
});
});
Promise.all(promises).then(() => {
resolve(list);
});
});
});
}
export default getMathImgSrcList;
|
import { call, put } from 'redux-saga/effects';
import { CADCLI_BUSCA_CLINICA_FALHA, CADCLI_BUSCA_CLINICA_FIM, CADCLI_BUSCA_CLINICA_INICIANDO, CADCLI_SALVAR_INICIANDO, CADCLI_SALVO_FALHA, CADCLI_SALVO_SUCESSO, CADCLI_VINCULAR_CLINICA_LOCAL, CADCLI_VINCULO_DESVINCULO_FALHA, CADCLI_VINCULO_DESVINCULO_SUCESSO, CAD_CLI_BUSCA_CEP_FIM, CAD_CLI_BUSCA_CEP_INICIO } from '../../actions/clinicas/CadastroClinicasAction';
import { MensagemInformativa } from "../../components/mensagens/Mensagens";
import { RETORNO_SUCESSO, RETORNO_SERVER_INDISPONIVEL } from '../../constants/ConstantesInternas';
import ClinicaServico from '../../servicos/ClinicaServico';
import EnderecoServico from '../../servicos/EnderecoServico';
export function* salvarClinica(action){
yield put({type: CADCLI_SALVAR_INICIANDO});
const nomeMetodo = action.clinica.idClinica && action.clinica.idClinica > 0 ? 'alterarClinica': 'salvarClinica';
const retorno = yield call(ClinicaServico[nomeMetodo], action.clinica);
if (retorno.status === RETORNO_SUCESSO){
yield put({type: CADCLI_SALVO_SUCESSO});
MensagemInformativa('Clínica salva com sucesso!');
} else {
yield put({type: CADCLI_SALVO_FALHA, mensagemFalha: retorno.mensagemErro});
if (retorno.status != RETORNO_SERVER_INDISPONIVEL){
MensagemInformativa(retorno.mensagemErro);
}
}
}
export function* vincularClinica(action){
yield put({type: CADCLI_BUSCA_CLINICA_INICIANDO});
try {
const retorno = yield call(ClinicaServico.vincularClinicaMedico, action.clinica.idClinica, action.codMedico);
if (retorno.status === RETORNO_SUCESSO){
yield put({type: CADCLI_VINCULO_DESVINCULO_SUCESSO, clinicaVinculada: action.clinica});
yield put({type: CADCLI_VINCULAR_CLINICA_LOCAL, clinicaVinculada: action.clinica});
MensagemInformativa('Clínica vinculada com sucesso!');
} else {
yield put({type: CADCLI_VINCULO_DESVINCULO_FALHA, mensagemFalha: retorno.mensagemErro});
if (retorno.status != RETORNO_SERVER_INDISPONIVEL){
MensagemInformativa(retorno.mensagemErro);
}
}
} catch(error){
yield put({type: CADCLI_VINCULO_DESVINCULO_FALHA, mensagemFalha: error});
}
}
export function* buscarClinicas(action){
yield put({type: CADCLI_BUSCA_CLINICA_INICIANDO});
try {
const retorno = yield call(ClinicaServico.buscarClinicas, action.nomeClinica, action.codMedico);
if (retorno.status === RETORNO_SUCESSO){
yield put({type: CADCLI_BUSCA_CLINICA_FIM, listaClinicas: retorno.data.retorno});
} else {
yield put({type: CADCLI_BUSCA_CLINICA_FALHA, mensagemFalha: retorno.mensagemErro});
if (retorno.status != RETORNO_SERVER_INDISPONIVEL){
MensagemInformativa(retorno.mensagemErro);
}
}
} catch(error){
yield put({type: CADCLI_BUSCA_CLINICA_FALHA, mensagemFalha: error});
}
}
export function* buscarEnderecoPorCep(action){
yield put({type: CAD_CLI_BUSCA_CEP_INICIO});
const dadosEndereco = yield call(EnderecoServico.buscarCep, action.numCep);
if (dadosEndereco.status === RETORNO_SUCESSO ){
const {retorno} = dadosEndereco.data;
const retornoEndereco = {
numCep: action.numCep,
estado: retorno.bairro.cidade.estado.nomeEstado,
cidade: retorno.bairro.cidade.nomeCidade,
bairro: retorno.bairro.nomeBairro,
idLogradouro: retorno.idLogradouro,
logradouro: retorno.nomeLogradouro + (retorno.descComplemento != null ? ` (${retorno.descComplemento})`: '')
};
yield put({type: CAD_CLI_BUSCA_CEP_FIM, dadosEndereco: retornoEndereco })
} else {
yield put({type: CAD_CLI_BUSCA_CEP_FIM, mensagemFalha: dadosEndereco.mensagemErro })
if (retorno.status != RETORNO_SERVER_INDISPONIVEL){
MensagemInformativa(dadosEndereco.mensagemErro);
}
}
}
|
import React, {Component} from 'react'
import { render } from '@testing-library/react'
class Contador extends Component {
state = {contador: 22};
render() {
return (
<div>
<h2>El contador está a {this.state.contador}.</h2>
</div>
);
}
}
export default Contador; |
import React, { Component } from 'react';
import { View, Text, TouchableOpacity, Alert } from 'react-native';
import { getDeck, removeData } from '../utils/data'
class Deck extends Component {
state = {
deckName: this.props.route.params,
cardNums: null
}
componentDidMount() {
this.getDeckInfo()
}
getDeckInfo = () => {
getDeck(this.state.deckName).then((res) => res.hasOwnProperty('questions') ? this.setState({ cardNums: res['questions'].length }) : null)
}
render() {
/* this.getDeck("React").then((res) => {
console.log(res['questions'])
}) */
/* removeData() */
this.props.navigation.addListener('focus', () => {
this.getDeckInfo()
})
//this.props.route.params.id !== undefined ? this.getDeckInfo() : null
//console.log(this.props.route.params)
const { deckName, cardNums } = this.state
return (
<View style={{ flex: 1, padding: 20 }}>
<View>
<Text>{deckName}</Text>
<Text>{cardNums ? cardNums : 'this Deck has no Cards, tap below to add'}</Text>
</View>
<View>
<TouchableOpacity onPress={() => this.props.navigation.navigate('AddCard', deckName)}><Text>Add Card</Text></TouchableOpacity>
<TouchableOpacity onPress={() => cardNums ? this.props.navigation.navigate('Quiz', deckName) : Alert.alert('this Deck has no Cards')}
><Text>Start Quiz</Text></TouchableOpacity>
</View>
</View>
);
}
}
export default Deck; |
var assert = require('assert');
var Deque = require('../dist/deque.js').Deque;
describe('Testing deque.js', function () {
var deque = new Deque();
it('Add 1 to front and its size should be 1', function () {
deque.addFront(1);
assert.equal(1, deque.getSize());
});
it('Add 2 to rear and its size should be 2', function () {
deque.addRear(2);
assert.equal(2, deque.getSize());
});
it('Call removeFront function and it should return 1', function () {
assert.equal(1, deque.removeFront());
});
it('Call removeRear function and it should return 2', function () {
assert.equal(2, deque.removeRear());
});
it('The deque should be empty now', function () {
assert.equal(true, deque.isEmpty());
});
it('Call removeFront function of an empty deque should throw error', function () {
assert.throws(deque.removeFront, Error);
});
it('Call removeRear function of an empty deque should throw error', function () {
assert.throws(deque.removeRear, Error);
});
}); |
import users from "@/data/users.js";
export const filterUsers = {
data() {
return {
sortCriteria: "",
users,
};
},
methods: {
filter_active_inactive() {
if (this.status != null) {
var status = this.status;
return this.users.filter(function (users) {
return users.status == status;
});
} else {
return this.users;
}
},
sort_by(users, sortProp) {
return users.sort(function (a, b) {
if (a[sortProp] > b[sortProp]) return 1;
if (a[sortProp] < b[sortProp]) return -1;
return 0;
});
}
},
computed: {
sortedUsers() {
if (!this.sortCriteria) {
this.sortCriteria = "created_at";
}
return this.sort_by(this.filter_active_inactive(), this.sortCriteria);
},
userProperties() {
let arr = [];
for (let prop in this.users[0]) {
arr.push(prop);
}
return arr;
}
}
}; |
'use strict';
const _ = require('lodash');
const defaults = {};
function Processor(options, logger) {
const self = this;
options = _.merge(defaults, options);
self.process = function (node) {
let $ = node.$;
let $body = node.$body;
};
}
module.exports = Processor;
|
function SelectedImages(name) {
/**
* local storage is not available when opening a local file on IE
* unless you access it using file://127.0.0.1/c$/pathtofile/file.html
*/
!localStorage && (l = location, p = l.pathname.replace(/(^..)(:)/, "$1$$"), (l.href = l.protocol + "//127.0.0.1" + p));
this.storage_key = 'SelectedImages_' + name;
}
/**
* Adding an image to the list of selected images in local storage
*/
SelectedImages.prototype.add = function(image) {
var list_string = window.localStorage.getItem(this.storage_key) || '';
var list = list_string.split(',');
if (list.indexOf(image) == -1) {
list.push(image);
}
window.localStorage.setItem(this.storage_key, list.join(','));
};
/**
* Removing an image to the list of selected images in local storage
*/
SelectedImages.prototype.remove = function(image) {
var list_string = window.localStorage.getItem(this.storage_key) || '';
var list = list_string.split(',');
var index = list.indexOf(image);
if (index != -1) {
list.splice(index, 1);
}
window.localStorage.setItem(this.storage_key, list.join(','));
};
/**
* Checking if the image was previously selected
*/
SelectedImages.prototype.has = function(image) {
var list_string = window.localStorage.getItem(this.storage_key) || '';
var list = list_string.split(',');
var index = list.indexOf(image);
return index != -1;
};
/**
* return an array of selected images
*/
SelectedImages.prototype.get = function() {
var list_string = window.localStorage.getItem(this.storage_key) || '';
return list_string.split(',');
};
|
module.exports = ({
name: "twitter",
code: `
$image[https://chilledcoders.ml/twitter?text=$message]
$color[RANDOM]
`
}) |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {
import { RestClient } from './RestClient';
let uniqueRequestId = 1;
let worker;
export class RestWorkerClient extends RestClient {
constructor(...args) {
super(...args);
this.promiseMap = new Map();
this.handleResponse = (ev) => {
const r = JSON.parse(ev.data);
if (r.id && this.promiseMap.has(r.id)) {
const handlers = this.promiseMap.get(r.id);
this.promiseMap.delete(r.id);
if (r.success) {
handlers.resolve(r.response);
}
else {
handlers.reject(r.response);
}
}
};
}
construstor() {
if (!worker) {
worker = new Worker('RestClientWorker.js');
}
worker.addEventListener('response', this.handleResponse);
}
get(action) {
return new Promise((_resolve, _reject) => {
const id = ++uniqueRequestId;
this.promiseMap.set(id, {
resolve: _resolve,
reject: _reject
});
const message = {
id,
method: 'get',
action,
};
worker.postMessage(JSON.stringify(message));
});
}
}
export default RestWorkerClient;
/***/ }
/******/ ]); |
const express = require('express');
const bodyParser = require("body-parser");
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.post("/", (req, res) => { let a, data,outp;
a= req.body.data ;
outp= a.slice(0,3)+a.slice(a.indexOf(":"));
console.log(outp);
res.json({out:outp})})
app.listen(port, () => {console.log(`Server running on ${port}`)}); |
import { useState } from 'react'
import { Project } from '../App';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import Box from '@material-ui/core/Box';
import Grid from '@material-ui/core/Grid';
import Slider from '@material-ui/core/Slider';
import Input from '@material-ui/core/Input';
import Checkbox from '@material-ui/core/Checkbox';
import FormControlLabel from '@material-ui/core/FormControlLabel';
export default function ProjectsItem(props) {
const [percentage, setPercentage] = useState(props.projects[props.index].percentage);
const [checked, setChecked] = useState(props.projects[props.index].checked);
const updateProjects = (newValue) => {
if (typeof newValue === 'boolean') {
setChecked(newValue);
}
else {
setPercentage(newValue);
}
let tmpProjects = props.projects;
tmpProjects[props.index] = new Project(tmpProjects[props.index].name, tmpProjects[props.index].xp,
typeof newValue !== 'boolean' ? newValue : tmpProjects[props.index].percentage,
typeof newValue === 'boolean' ? newValue : tmpProjects[props.index].checked,
);
props.setProjects([...tmpProjects]);
};
const marks = [
{
value: 0,
label: '0',
},
{
value: 100,
label: '100',
},
{
value: 125,
label: '125',
},
];
return (
<Grid container spacing={3} alignItems="center" sx={{ margin: 2 }}>
<Grid item>
<Typography id="input-slider" >
{props.project.name}
</Typography>
</Grid>
<Grid item>
%
</Grid>
<Grid item xs>
<Slider
aria-labelledby="input-slider"
value={percentage}
step={1}
min={0}
max={125}
color={percentage >= 100 ? "primary" : "secondary"}
onChange={(e, newPercentage) => {
updateProjects(newPercentage);
}}
marks={marks}
/>
</Grid>
<Grid item>
<Input
value={percentage}
size="small"
onChange={(e) => {
if (e.target.value >= 0 && e.target.value <= 125) {
updateProjects(Number(e.target.value));
}
if (e.target.value > 125) {
updateProjects(125);
}
}}
inputProps={{
step: 1,
min: 0,
max: 125,
type: 'number',
'aria-labelledby': 'input-slider',
}}
/>
</Grid>
<Grid item>
<FormControlLabel control={
<Checkbox color="primary"
value={checked}
onChange={(e) => { updateProjects(!checked) }} />}
label="Is my coa first ?"
/>
</Grid>
<Grid item>
<Button variant="contained" color="primary"
onClick={(e) => {
props.setProjects(props.projects.filter(item => item !== props.project))
}}>
Remove
</Button>
</Grid>
</Grid>
);
} |
/*
* Module code goes here. Use 'module.exports' to export things:
* module.exports.thing = 'a thing';
*
* You can import it from another modules like this:
* var mod = require('role.worker');
* mod.thing == 'a thing'; // true
*/
var logger = require("screeps.logger");
logger = new logger("role.worker");
logger.enabled = false;
var obj = function() {
}
var base = require('role.base');
obj.prototype = new base();
global.utils.extendFunction(obj, "init", function(name, roomManager) {
this.__init(name, roomManager);
this.workerCreepIds = [];
this.requiredCreeps = 5;
this.allowMining = true;
}, "__");
global.utils.extendFunction(obj, "tickInit", function() {
logger.log("num", this.name, this.workerCreepIds.length, this.requiredCreeps, this.roomManager.room.name)
if (this.roomManager.visibility && this.roomManager.room.controller.level > 3) {
this.requiredCreeps = 2;
}
if (this.roomManager.visibility && this.roomManager.room.controller.level > 5 || this.roomManager.room.storage) {
this.requiredCreeps = 1;
}
if (this.roomManager.remoteMode) {
this.requiredCreeps = 1;
}
if (this.workerCreepIds.length < this.requiredCreeps) {
var minBodies = 0;
// if (this.roomManager.room.controller.level > 4) {
// minBodies = 3;
// }
//need some creeps
var priority = 20;
if (this.numCreeps == 0)
priority = 250;
var req = global.utils.makeCreepRequest(this.name, "workerCreepIds", [MOVE, MOVE, CARRY, WORK], [MOVE, CARRY, WORK], priority, false, 5, minBodies)
this.roomManager.requestCreep(req);
return;
}
}, "__");
global.utils.extendFunction(obj, "tick", function() {
for(var i in this.workerCreepIds) {
var creep = Game.creeps[this.workerCreepIds[i]];
if (creep) {
this.runCreep(creep);
} else {
logger.log("mofo died",this.workerCreepIds[i])
delete this.workerCreepIds[i];
}
}
}, "__");
global.utils.extendFunction(obj, "tickEnd", function() {
}, "__");
obj.prototype.runCreep = function(creep) {
//logger.log(creep);
if (creep.flee(5)) {
return;
}
var isHelper = creep.memory.helperCreep && (this.homeOverride && creep.room.name != this.homeOverride);
if (isHelper || creep.pos.roomName != creep.memory.home) {
logger.log(creep.name, creep.memory.home)
var centerOfHomeRoom = new RoomPosition(25, 25, creep.memory.home);
//logger.log("helper creep moving", centerOfHomeRoom, creep.memory.home)
global.utils.moveCreep(creep, centerOfHomeRoom);
return;
} else if (isHelper) {
var centerOfHomeRoom = new RoomPosition(25, 25, creep.memory.home);
//logger.log("helper creep moving", centerOfHomeRoom, creep.memory.home)
global.utils.moveCreep(creep, centerOfHomeRoom);
creep.memory.helperCreep = false;
return;
}
//creep.say(this.allowMining && creep.memory.mining && !creep.full())
if ((this.allowMining && creep.memory.mining && !creep.full()) || creep.empty() || (creep.memory.doneWorking && !creep.full())) {
//creep.memory.mining = false;
if (!this.getEnergy(creep)) {
if (this.allowMining && creep.mineEnergyFromSource()) {
creep.memory.mining = true;
//try mining
//
} else {
logger.log(creep.name, creep.memory.role, "can't find energy")
}
}
} else {
creep.memory.mining = false;
creep.memory.doneWorking = false;
//do work
this.doWork(creep);
}
}
obj.prototype.doWork = function(creep) {
if (!creep.stashEnergyInTowersEmergency()) {
var fillSpawns = false;
if (this.roomManager.creepsInBaseRole("fillers") == 0 || creep.memory.role == "fillers" || this.roomManager.room.energyAvailable < this.roomManager.room.energyCapacityAvailable * 0.5) {
fillSpawns = true;
}
if (!fillSpawns || !creep.stashEnergyInSpawns()) {
if (!creep.stashEnergyInSpawnContainers()) {
if (creep.memory.skipConstruction == undefined) {
creep.memory.skipConstruction = true;
}
if (this.roomManager.room.controller.level < 2 || this.roomManager.room.controller.ticksToDowngrade < 1000) {
creep.memory.skipConstruction = true;
}
if (creep.memory.skipConstruction && this.roomManager.room.controller.ticksToDowngrade > 2000) {
creep.memory.skipConstruction = false;
}
if (creep.memory.skiskipConstruction || (!creep.doConstruction() && !creep.doRepair())) {
if (!creep.stashEnergyInTowers()) {
if (!creep.doUpgrade()) {
logger.log(this.name, 'nothing to do')
}
}
}
}
}
}
}
obj.prototype.getEnergy = function(creep) {
//logger.log(creep);
if (!creep.pickupEnergy()) {
if (!creep.getEnergyFromSourceContainers()) {
return false;
}
}
return true;
}
module.exports = obj; |
import React from 'react';
import { MapLayer } from 'react-leaflet';
import './leaflet-text-icon.js';
class MarkerCluster extends MapLayer {
constructor(props) {
super(props);
this._markers = {};
}
componentWillMount() {
let markers = [];
let self = this;
this.leafletElement = L.markerClusterGroup();
if (!_.isEmpty(this.props.parkingMetadata)) {
markers = _.map(this.props.parkingMetadata, (val,key)=>{
this._markers[Number(val.LotCode)] = L.marker(new L.LatLng(val.Latitude, val.Longitude), {
title: val.Street,
icon: new L.TextIcon({
text: val.BayCount.toString(),
color: 'blue',
id: Number(val.LotCode)
})
});
this._markers[Number(val.LotCode)].bindPopup(
"<b>Street name: </b>"+val.Street+"<br>"+
"<b>Bay type: </b>"+val.BayType+"<br>"+
"<b>Tarrif code:</b>"+val.TariffCode+"<br>"+
"<b>Bay count:</b>"+val.BayCount).on('click', (e) => {self.props.onClickMarker(e.target.options.icon.options.id)});
return this._markers[Number(val.LotCode)];
});
this.leafletElement.addLayers(markers);
}
}
componentWillReceiveProps(nextProps) {
_.forEach(nextProps.realTimeData, (val)=>{
let color = Number(val.currentvalue)?'blue':'red';
this._markers[Number(val.ID)].options.icon.setColor(color);
this._markers[Number(val.ID)].options.icon.setText(val.currentvalue.toString());
});
}
shouldComponentUpdate() {
return false;
}
render() {
return null;
}
}
MarkerCluster.propTypes = {
parkingMetadata: React.PropTypes.object.isRequired,
realTimeData: React.PropTypes.array.isRequired,
onClickMarker: React.PropTypes.func.isRequired
};
export default MarkerCluster; |
$(window).scroll(function () {
if ($(window).scrollTop() > 0) {
$('.fadeInBlock').stop().fadeTo("slow", 0);
console.log('p')
} else {
$('.fadeInBlock').stop().fadeTo("fast", 1);
console.log(box1Top)
}
}); |
class Rook extends ChessPice {
constructor(_name, position) {
super(_name, position);
}
setPosition(_newPosition) {
this.position = _newPosition;
}
//function move return true or false and cotaine position
checkMove(targetPosX, targetPosY, isSelected = false) {
// first two conditions to check it no out of the board
if (targetPosX < 0 && targetPosX > 7 || targetPosY < 0 && targetPosY > 7) {
alert("out of board exception of rook");
return false;
}
else if (targetPosX === this.position.getPosX() && targetPosY === this.position.getPosY()) {
return true;
}
if (isSelected) {
for (let [x, y, rest] of Player.arr) {
if(x==targetPosX && y==targetPosY){
return false;
}
}
}
// this conditions to check the movement of rook pice
if (this.position.getPosY() === targetPosY && targetPosX < this.position.getPosX()) {
return this.checkMove(targetPosX + 1, targetPosY,true);
}
else if (this.position.getPosY() === targetPosY && targetPosX > this.position.getPosX()) {
return this.checkMove(targetPosX - 1, targetPosY,true);
}
else if (this.position.getPosX() === targetPosX && targetPosY < this.position.getPosY()) {
return this.checkMove(targetPosX, targetPosY + 1,true);
}
else if (this.position.getPosX() === targetPosX && targetPosY > this.position.getPosY()) {
return this.checkMove(targetPosX, targetPosY - 1,true);
}
else {
return false; //move as not possiple
}
}
capture(TargetPosX, TargetPosY) {
return this.checkMove(TargetPosX, TargetPosY);
}
shadowMove(TargetPosX, TargetPosY) {
return this.checkMove(TargetPosX, TargetPosY);
}
}
|
import {StyleSheet, Text, TouchableOpacity} from "react-native"
import React from "react"
const Row = props => (
<TouchableOpacity style={styles.row} onPress={() => {
props.onSelectContact(props)
}}>
<Text>{props.name}</Text>
<Text>{props.phone}</Text>
</TouchableOpacity>
)
const styles = StyleSheet.create({
row: {padding: 20},
})
export default Row |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import cs from 'classnames';
class MiniPinDisplay extends Component {
rows = [
[1],
[2, 3],
[4, 5, 6],
[7, 8, 9, 10],
];
render() {
const { frame } = this.props;
return (
<div className="py-px flex flex-col-reverse">
{this.rows.map((row, index) => (
<div key={index} className="my-px flex justify-center">
{row.map((pin) => {
const pinClass = cs(
'rounded-full border w-2 h-2 mx-px',
{ 'bg-blue border-blue': frame.throw_1 && frame.throw_1.includes(pin) },
{ 'border-blue': frame.throw_2 && frame.throw_2.includes(pin) },
{ 'bg-red border-red': frame.throw_1 && !frame.throw_1.includes(pin) && frame.throw_2 && !frame.throw_2.includes(pin) },
);
return (
<div key={pin} className={pinClass} />
);
})}
</div>
))}
</div>
);
}
}
MiniPinDisplay.propTypes = {
frame: PropTypes.object.isRequired,
};
export default MiniPinDisplay;
|
var fs = require('fs')
, os = require('os')
, path = require('path')
, sendData = require('send-data')
, sendError = require('send-data/error');
module.exports = function (request, response) {
var fs = require('fs')
require('fs').readFile(getPath(request), function (err, data) {
if (err) {
sendError(request, response, { body: err })
} else {
sendData(request, response, { statusCode: 200, body: data })
}
})
};
function getPath (request) {
var url = request.url
, re = new RegExp('/file/(.+)')
, file = decodeURI(re.exec(url)[1]);
if (file.indexOf('~/') === 0) file = path.resolve(os.homedir(), file.slice(2));
return file;
}
|
var form = document.querySelector("form");
var output = document.getElementById("output")
form.addEventListener("submit", function(e){
e.preventDefault();
var newItem = {
title: this.title.value,
description: this.description.value,
price: this.price.value
}
addItem(newItem)
form.reset();
})
function addItem(newItem) {
var item = document.createElement("div");
item.classList.add("item")
var title = document.createElement("h3");
title.innerHTML = "<br>" + newItem.title;
var description = document.createElement("p");
description.innerText = newItem.description;
var price = document.createElement("p");
price.innerText = "Price: $" + newItem.price;
var label = document.createElement("label");
label.innerText = "Completed:";
var checkbox = document.createElement("input");
checkbox.type = "checkbox"
checkbox.addEventListener("input", function(e) {
title.classList.toggle("completed")
label.classList.toggle("completed")
price.classList.toggle("completed")
description.classList.toggle("completed")
})
var deleteButton = document.createElement("button");
deleteButton.innerText = "X";
deleteButton.addEventListener("click", function(e) {
output.removeChild(this.parentElement)
})
children = [deleteButton,title,label,checkbox,price,description]
children.forEach( x => item.appendChild(x))
output.appendChild(item);
} |
import React from 'react'
import { Elements } from '@stripe/react-stripe-js'
import { loadStripe } from '@stripe/stripe-js'
import SimpleCartForm from './SimpleCartForm'
const stripePromise = loadStripe(
'pk_test_51JEnJYK5piEEHVoJsZy1UseJjGl4GLrX7rxzcKUyxMoe9YTbu9n8nlOFcNzcI1a9w5QhdwTrjKDsDHIV1MYC0RnV00c59vYIKI'
)
const ProcessPayment = () => {
return (
<>
<Elements stripe={stripePromise}>
<SimpleCartForm/>
</Elements>
</>
)
}
export default ProcessPayment
|
'use strict';
module.exports = {
files: [
'index.html',
'demo/**/*'
],
port: 7501,
ui: {
port: 7502
},
open: false,
host: '0.0.0.0'
};
|
import random from "unique-random-array"
export default function({types: t }) {
return {
visitor: {
BinaryExpression(path) {
switch (path.node.operator) {
case "==":
case "===":
path.node.operator = "!=="
break
case "+":
if (path.node.left.value === 2 && path.node.right.value === 2) {
path.replaceWith(t.numericLiteral(5))
} else {
path.node.operator = "-"
}
break
case "*":
path.node.operator = "%"
break
case "**":
path.node.operator = "*"
break
case "%":
let left = path.node.left
path.node.left = path.node.right
path.node.right = left
break
default:
path.node.operator = random(["+", "-", "*", "/", "==", "===", "!=", "!==", "**", "&&", "||", "^", "%"])()
}
}
}
}
}
|
class SlingShot{
constructor(bodyA, pointB){
var options = {
bodyA: bodyA,
pointB: pointB,
stiffness: 0.04,
length: 10
}
this.pointB = pointB
this.sling = Constraint.create(options);
World.add(world, this.sling);
}
fly(){
this.sling.bodyA = null;
}
display(){
//this gets dispakyed if the sligshot is still there and not null meaning that the user has not pulledthe slingshot yet
//image for the catapult
}
} |
var car = new Car("AW456", new Account("Andres Herrera", "QWE234"))
car.passenger = 4
car.printDataCar()
$uberX = new UberPool("QWE567", new Account("Andrea Ferran", "ANDA765"), "Chevrolet", "Spark");
$uberX.passengers = 4;
$uberX.printDataCar();
|
// primer
function Animal (kind, name) {
this.kind = kind;
this.name = name;
}
var cat = new Animal("cat", "Maca");
console.log(cat);
// zadatak
function Person (name, surname, hobby){
this.name = name;
this.surname = surname;
this.hobi = hobby;
this.sayName = function () {
console.log("Hi I'm " + this.name + "!");
}
this.sayBla = function(){
console.log(this.name + ": bla");
}
this.likeIt = function(){
for (var i = 0; i < this.hobi.length; i++){
console.log(this.name + ' likes ' + this.hobi[i]);
}
}
this.changeSurname = function(newSurname) {
this.surname = newSurname;
}
}
var nenad = new Person("Nenad", "Bugaric");
var milos = new Person("Milos", "Brajevic", ['sports', 'codding', 'reading']);
milos.sayName();
milos.sayBla();
milos.likeIt();
milos.changeSurname('Brajovic');
console.log(milos.surname);
// zadatak 1. Write a function to convert a number from one base (radix) to another. Hint: Use one of the built-in functions and toString method of one of the built-in Object Wrappers;
/*
function convertNumber (input, base) {
var output = input.toString();
output = parseInt(output, base);
return output;
}
console.log(convertNumber('ff', 8));
*/
function convertNumberBase (inputStr, inputBase, outputBase){
var number = parseInt(inputStr, inputBase);
var convertedNumber = number.toString(outputBase);
return convertedNumber;
}
console.log(convertNumberBase("377", 8, 16));
// zadatak 2 Write a JavaScript function that reverses a number. typeof result of the function should be “number”.
function reverseNumber(input) {
var reversed = input.toString().split("").reverse().join("");
reversed = parseInt(reversed);
return reversed;
}
console.log(reverseNumber(123));
console.log(typeof(reverseNumber(123)));
// zadatak 3 Write a JavaScript function that returns a passed string with letters in alphabetical order.
// Note: Assume punctuation, numbers and symbols are not included in the passed string.
function sortString (input){
var result = input.toLowerCase().split("").sort().join("");
return result;
}
console.log(sortString("Webmaster"));
// zadatak 4 Write a function to alphabetize words of a given string. Alphabetizing a string means rearranging the letters so they are sorted from A to Z.
// "Republic Of Serbia" -> "Rbceilpu Of Sabeir"
function alphabetization (inputStr) {
var output = inputStr.split(" ");
for (var i = 0; i < output.length; i++) {
output[i] = output[i].split("").sort().join("");
}
output = output.join(" ");
return output;
}
console.log(alphabetization("Republic Of Serbia"));
//zadatak 5 Write a function to split a string and convert it into an array of words.
// "John Snow" -> [ 'John', 'Snow' ]
function splitString (input){
var output = input.split(" ");
return output;
}
console.log(splitString("John Snow"));
// zadatak 6 Write a function to convert a string to its abbreviated form.
// "John Snow" -> "John S."
function abbreviated (input){
var output = input.split(" ");
output
return
} |
// Compiled by ClojureScript 1.10.238 {:static-fns true, :optimize-constants true}
goog.provide('simplify_debts.core');
goog.require('cljs.core');
goog.require('cljs.core.constants');
goog.require('reagent.core');
goog.require('simplify_debts.views');
simplify_debts.core.mount_root = (function simplify_debts$core$mount_root(){
return reagent.core.render.cljs$core$IFn$_invoke$arity$2(new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [simplify_debts.views.home_page], null),document.getElementById("app"));
});
simplify_debts.core.init_BANG_ = (function simplify_debts$core$init_BANG_(){
return simplify_debts.core.mount_root();
});
|
const state = {
currentNewsId: '',
// curFilmRtype: 0, // 当前电影标记的状态 // 默认0 想看1 看过2
username: '',
currentComment: '', // 我的短评
// watchedFilms: loadWatchedFilms(), // 看过的电影
// wantedFilms: loadWantedFilms() // 想看的电影
}
export default state |
module.controller("footerCtrl", FooterCtrl)
// DI dependency injection - IOC
function FooterCtrl($scope, $rootScope, globalConst, dataService, serviceService) {
$scope.productName = globalConst.name
$scope.productVersion = globalConst.ver
$scope.items = dataService.items
$scope.sayInUpper = function() {
alert(serviceService.getUpper("hello"))
}
}
|
const serviceAccount = {
/* enter keys here */
}
export default serviceAccount |
/* eslint-env node */
'use strict';
var path = require('path');
module.exports = {
buildDir: path.resolve('test'),
themesDir: path.resolve('test'),
theme: 'theme',
content: {
'test-folder-one/': {
type: 'pages',
'index.md': 'testcontent-page-one',
files: ['test-page-1.md'],
'test-page-1.md': {
content: 'test content page 1',
name: 'test-page-1',
parentDir: 'test-folder-one/',
href: 'test-folder-one/test-page-1'
}
},
'test-folder-two/': {
type: 'pages',
'index.md': 'testcontent-page-two',
files: ['test-page-2.md'],
'test-page-2.md': {
content: 'test content page 2',
name: 'test-page-2',
parentDir: 'test-folder-two/',
href: 'test-folder-two/test-page-2'
}
},
'test-folder-three/': {
type: 'pages',
'index.md': 'testcontent-page-three',
files: ['test-page-3.md', 'test-page-4.md', 'test-page-5.md'],
'test-page-3.md': undefined,
'test-page-4.md': {
content: 'test content page 5',
parentDir: 'test-folder-two/',
href: 'test-folder-two/test-page-5'
},
'test-page-5.md': {
content: 'test content page 5',
name: 'test-page-5',
href: 'test-folder-two/test-page-5'
}
},
'test-category-one/': {
type: 'posts',
'index.md': {
posts: ['test content post 1']
},
files: ['index.md', 'test-post-1.md'],
'test-post-1.md': {
content: 'test content post 1',
name: 'test-post-1',
parentDir: 'test-category-one/',
href: 'test-category-one/test-post-1'
}
},
'test-category-two/': {
type: 'posts',
'index.md': {
posts: ['test content post 2']
},
files: ['index.md', 'test-post-2.md'],
'test-post-2.md': {
content: 'test content post 2',
name: 'test-post-2',
parentDir: 'test-category-two/',
href: 'test-category-two/test-post-2'
}
},
'test-category-three/': {
type: 'posts',
files: ['test-post-3.md', 'test-post-4.md', 'test-post-5.md', 'test-post-6.md'],
'test-post-3.md': {
content: 'test content post 3',
name: 'test-post-3',
parentDir: 'test-category-three/',
href: 'test-category-three/test-post-3'
},
'test-post-4.md': undefined,
'test-post-5.md': {
content: 'test content post 5',
parentDir: 'test-category-three/',
href: 'test-category-three/test-post-5'
},
'test-post-6.md': {
content: 'test content post 6',
name: 'test-post-6',
href: 'test-category-three/test-post-6'
}
},
'statics/': {
type: 'statics',
files: ['static-file-1', 'static-file-2', 'static-file-3'],
'static-file-1': {
content: 'bitstream',
name: 'static-file-1',
parentDir: 'statics/',
href: 'statics/static-file-1'
},
'static-file-2': {
content: 'bitstream',
name: 'static-file-2',
parentDir: 'statics/',
href: 'statics/static-file-2'
},
'static-file-3': {
content: 'bitstream',
name: 'static-file-3',
parentDir: 'statics/',
href: 'statics/static-file-3'
}
}
}
};
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Vehicle = /** @class */ (function () {
function Vehicle(year) {
this.year = year;
}
Vehicle.prototype.getYear = function () {
return this.year;
};
Vehicle.prototype.toString = function () {
return this.year.toString();
};
return Vehicle;
}());
var Car = /** @class */ (function (_super) {
__extends(Car, _super);
function Car(year, color) {
var _this = _super.call(this, year) || this;
_this.color = color;
return _this;
}
Car.prototype.getColor = function () {
return this.color;
};
Car.prototype.toString = function () {
return " " + _super.prototype.toString.call(this) + " : " + this.color;
};
return Car;
}(Vehicle));
var printFunc = function (vehicle) { return console.log(" " + vehicle); };
var vehicle = new Vehicle(2018);
var car = new Car(2018, 'Blue');
printFunc(vehicle);
printFunc(car);
|
import * as Yup from 'yup';
import Incident from '../models/Incident';
import Ong from '../models/Ong';
class IncidentController {
async index(req, res) {
const { page = 1 } = req.query;
const { count } = await Incident.findAndCountAll();
const ongs = await Incident.findAll({
limit: 5,
offset: (page - 1) * 5,
include: [
{
model: Ong,
as: 'ong',
attributes: [
'id',
'name',
'email',
'whatsapp',
'city',
'uf',
],
},
],
});
res.header('X-Total-Count', count);
return res.json(ongs);
}
async store(req, res) {
const schema = Yup.object().shape({
title: Yup.string().required(),
description: Yup.string().required(),
value: Yup.number().required(),
});
if (!(await schema.isValid(req.body))) {
return res.status(400).json({ error: 'Validation fails' });
}
const checkOngExists = await Ong.findOne({
where: { id: req.headers.authorization },
});
if (!checkOngExists) {
return res.status(400).json({ error: 'Ong does not exist!' });
}
const { title, description, value } = req.body;
const ong_id = req.headers.authorization;
const { id } = await Incident.create({
title,
description,
value,
ong_id,
});
return res.json({ id, title, description, value, ong_id });
}
async delete(req, res) {
const { id } = req.params;
const ong_id = req.headers.authorization;
const incident = await Incident.findOne({
where: {
id,
},
});
if (incident.ong_id !== ong_id) {
return res.status(401).json({ error: 'Operation not permitted.' });
}
await Incident.destroy({
where: {
id,
},
});
return res.status(204).send();
}
}
export default new IncidentController();
|
//import merge from "lodash/merge";
// The redux reducer function for the logged in state.
export function hasErrored(state = false, action) {
switch (action.type) {
case 'HAS_ERRORED':
return action.hasErrored
default:
return state
}
}
export function isBusy(state = false, action) {
switch (action.type) {
case 'IS_BUSY':
return action.isBusy
default:
return state
}
}
export function listUsers(state = [], action) {
console.log("listUsers>> action.type: " + action.type + " action: " + JSON.stringify(action))
switch (action.type) {
case 'USER_LIST':
return action.userList;
default:
return state
}
}
export function editUser(state = {}, action) {
console.log("user>> action.type: " + action.type + " action: " + JSON.stringify(action))
console.log("Initial state is:"+JSON.stringify(state));
switch (action.type) {
case 'USER_CHANGE':
let user = (state)?{...state.user}:{};
console.log("Before user is:"+JSON.stringify(user));
user[action.id]= action.value;
console.log("After user is:"+JSON.stringify(user));
console.log("State is:"+JSON.stringify(state));
let newState = {
...state,
user
}
console.log("newState:"+JSON.stringify(newState));
return newState;
case 'SET_USER':
return action.user;
default:
return state
}
}
export function setUser(state = {}, action) {
switch (action.type) {
case 'SET_USER':
return action.user;
default:
return state
}
}
export function filterChange(state = null, action) {
console.log("filterChange>> action.type: " + action.type + " action.filter: " + JSON.stringify(action.filter))
switch (action.type) {
case 'FILTER_CHANGE':
return action.filter
default:
return state
}
}
|
import React from "react";
// import './display.css'
const Display = (props) => {
const {displayVal} = props;
return (
<div className={`display`}>
<p>{displayVal}</p>
</div>
)
};
export default Display |
/**
* Created by nisabhar on 11/20/2015.
*/
/**
* Created by nisabhar on 6/30/2015.
*/
define(['jquery', 'knockout', 'ojL10n!pcs/resources/nls/dashboardResource'], function ($, ko, bundle) {
var _columnAlias = function(data) {
if (data.columnsInfo) {
var ret = {};
var i;
for (i = 0; i < data.columnsInfo.length; i++) {
ret[data.columnsInfo[i].columnName.replace("TASK","PROCESS")] = i;
}
return ret;
}
};
var _adfProxyCall = function(url){
// Let the container handle if container is willing to
if (typeof doADFProxyCall == 'function') {
doADFProxyCall(url);
}
// else handle ourself
else{
if(url) {
window.location.assign(url);
}
}
};
var _errorHandler = function (jqXHR, customMsg){
$("#bpm-dsb-error-dialog").ojDialog("open");
var msg = bundle.container.generic_error_msg;
if(customMsg){
msg = customMsg;
}
else if (jqXHR && jqXHR.status === 401){
msg= bundle.container.access_error_msg;
}
$("#bpm-dsb-error-dialog-custom-text").text(msg);
};
var _constants ={
queries : {
//Custom
APPLICATION_LIST : "PROCESS_LABEL_LIST"
},
dataType : {
TIMESTAMP : 'TIMESTAMP',
DATETIME : 'DATETIME',
INT : 'INT'
},
misc : {
ANY : 'ANY',
ALL : 'ALL',
VALUE : 'value',
VISIBLE : 'visible'
},
chartType :{
BAR : 'bar',
LINE:'line',
AREA :'area',
PIE:'pie',
LINEWITHAREA:'lineWithArea',
FUNNEL:'funnel',
COMBO :'combo'
},
columnTypes : {
ATTRIBUTE : 'ATTRIBUTE',
DIMENSION : 'DIMENSION',
MEASURE : 'MEASURE'
},
dataSource :{
PROCESS :'PROCESS',
ACTIVITY:'ACTIVITY',
TASK:'TASK',
ASSIGNMENT:'ASSIGNMENT'
},
functionList :{
SUM:'SUM',
COUNT:'COUNT',
AVG:'AVG',
MIN:'MIN',
MEDIAN:'MEDIAN',
MAX:'MAX',
STDDEV:'STDDEV',
COUNTDISTINCT:'COUNTDISTINCT',
VARIANCE:'VARIANCE'
},
timeGroups : [
'YEAR',
'QUARTER',
'MONTH',
'WEEK',
'DAYOFYEAR',
'DAYOFMONTH',
'DAYOFWEEK',
'HOUR',
'MINUTE',
'SECOND'
],
lastNDays : {
'7': '1WEEK',
'30': '1MONTH',
'60': '2MONTHS',
'90': '3MONTHS',
'180': '6MONTHS',
'270': '9MONTHS',
'365': '1YEAR'
}
};
return {
columnAlias : _columnAlias,
constants : _constants,
drilldown : _adfProxyCall,
errorHandler : _errorHandler,
refreshAll : function(observableArray, fromArray){
//push all the items from a array to an observable array and
//notify the subscribers to the observableArray at the end
observableArray.valueWillMutate();
observableArray.removeAll();
ko.utils.arrayPushAll(observableArray, fromArray);
observableArray.valueHasMutated();
},
addAll : function (observableArray, fromArray){
//Add all the items from a array to an observable array and
//notify the subscribers to the observableArray at the end
observableArray.valueWillMutate();
ko.utils.arrayPushAll(observableArray, fromArray);
observableArray.valueHasMutated();
},
startsWith : function(str, searchString, position){
position = position || 0;
return str.substr(position, searchString.length) === searchString;
}
};
});
|
/*global FB*/
import * as Constants from '../constants/Constants';
const FacebookActionCreators = {
loadSDK: function (appID, appVersion) {
return {
type: Constants.FACEBOOK_LOAD_SDK(),
payload: new Promise(resolve => {
window.fbAsyncInit = function () {
FB.init({
appId: appID,
xfbml: true,
cookie: true,
version: appVersion
});
FB.AppEvents.logPageView();
resolve();
};
(function (d, s, id) {
const fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
const js = d.createElement(s);
js.id = id;
js.src = '//connect.facebook.net/en_US/sdk.js';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
})
}
},
login: function (options) {
return {
type: Constants.FACEBOOK_LOG_IN(),
payload: new Promise(resolve => {
window.FB.login(response => resolve(response), options);
})
}
},
logout: function () {
return {
type: Constants.FACEBOOK_LOG_OUT(),
payload: new Promise(resolve => {
window.FB.logout(response => resolve(response));
})
}
},
checkStatus: function () {
return {
type: Constants.FACEBOOK_CHECK_STATUS(),
payload: new Promise(resolve => {
window.FB.getLoginStatus(response => resolve(response));
})
}
},
loadPicture: function(userId) {
return {
type: Constants.FACEBOOK_LOAD_PICTURE(),
payload: new Promise(resolve => window.FB.api('/' + userId +'/picture?type=small',
response => resolve(response)))
}
},
retrievePersonalInfo : function() {
return {
type: Constants.FACEBOOK_RETRIEVE_PERSONAL_INFO(),
payload: new Promise(resolve => {
window.FB.api('/me?fields=first_name,last_name,gender,birthday,location',
response => resolve(response));
})
}
}
};
export default FacebookActionCreators; |
import _ from "lodash";
export const fetchBusesInfo = async query => {
const url =
"https://sitetrakerrecruiting-developer-edition.na73.force.com/services/apexrest/getBusses";
const rawResponse = await fetch(url);
const response = await rawResponse.text();
const result = JSON.parse(response) || [];
return _.sortBy(result.filter(bus => bus.attributes.type === "Bus__c"), [
"Bus_ID__c"
]);
};
export const getSeatBasedPricing = bus =>
bus.Maximum_Capacity__c <= 24 ? 120000 : 160000;
export const getMilesBasedDiscount = bus =>
bus.Odometer_Reading__c > 100000
? ((bus.Odometer_Reading__c - 100000) * 0.1).toFixed(2)
: 0;
export const getFeatureBasedPricing = bus =>
bus.Has_Air_Conditioning__c ? getSeatBasedPricing(bus) * 3 / 100 : 0;
export const getYearsBasedPricing = bus =>
bus.Year__c <= 1972 ? (getSeatBasedPricing(bus) * 34 / 100).toFixed(2) : 0;
export const calculateResaleValue = bus => {
const priceBasedOnSeats = getSeatBasedPricing(bus);
const pricebasedOnFeature = getFeatureBasedPricing(bus);
const priceBasedOnYear = getYearsBasedPricing(bus);
const discount = getMilesBasedDiscount(bus);
const resaleValue = (
priceBasedOnSeats +
pricebasedOnFeature +
priceBasedOnYear -
discount
).toFixed(2);
return {
resaleValue,
priceBasedOnSeats,
pricebasedOnFeature,
priceBasedOnYear,
discount
};
};
|
const { adminRepository } = require("../repository/adminRepository");
const { createResponse } = require("../response");
const { Customer } = require('../model/Customer');
const { createCustomerMap, createCruiseShipRatingMap } = require('../mapper/Mapper');
const { ErrorHandler } = require("../error");
class adminController {
constructor() {}
async login(req, res, next) {
try {
console.log("IN ADMIN LOGIN")
var adminLogin = {
email: req.body.email,
password: req.body.password
};
console.log(adminLogin);
const admin = await adminRepository.getAdminByIdFromDb(adminLogin.email);
console.log(admin);
if(admin.length == 0){
throw new ErrorHandler(401, 'Not registered');
}
if(admin[0].password != adminLogin.password){
throw new ErrorHandler(401, 'Wrong password');
}
console.log(admin)
//Set session id
req.session.adminId = admin[0].adminId;
//Response:
createResponse(res, 200, `Successfully logged in`, {
adminLogin
});
} catch (exception) {
next(exception);
}
}
//plans
async pushPlan(req, res, next) {
try {
const travelPlan = req.body;
await adminRepository.pushTravelPlanInDb(travelPlan)
createResponse(res, 200, "Successfully created travelPlan", {
travelPlan
});
} catch (exception) {
next(exception);
}
}
async deletePlan(req, res, next) {
try {
var travelPlanId = req.params.travelPlanId;
await adminRepository.deleteTravelPlanInDb(req.params.travelPlanId);
createResponse(res, 200, "Successfully deleted travelPlan", {
travelPlanId
});
} catch (exception) {
next(exception);
}
}
//Stops
async pushStop(req, res, next) {
try {
const stop = req.body;
await adminRepository.pushStopInDb(stop)
createResponse(res, 200, "Successfully created stop", {
stop
});
} catch (exception) {
next(exception);
}
}
async deleteStop(req, res, next) {
try {
var stopId = req.params.stopId;
await adminRepository.deleteStopInDb(req.params.stopId);
createResponse(res, 200, "Successfully deleted stop", {
stopId
});
} catch (exception) {
next(exception);
}
}
//CREW
async pushCrewMember(req, res, next) {
try {
const crewMember = req.body;
await adminRepository.pushCrewMemberInDb(crewMember)
createResponse(res, 200, "Successfully created crewMember", {
crewMember
});
} catch (exception) {
next(exception);
}
}
async deleteCrewMember(req, res, next) {
try {
var crewMemberId = req.params.crewMemberId;
await adminRepository.deleteCrewMemberInDb(req.params.crewMemberId);
createResponse(res, 200, "Successfully deleted crewMember", {
crewMemberId
});
} catch (exception) {
next(exception);
}
}
async linkShipTravelPlan(req, res, next) {
try {
const link = req.body;
await adminRepository.linkShipTravelPlanInDb(req.params.shipId,req.params.travelPlanId,link)
createResponse(res, 200, "Successfully linked travel plan and ship", {
link
});
} catch (exception) {
next(exception);
}
}
async linkTravelPlanStop(req, res, next) {
try {
const link = req.body;
await adminRepository.linkTravelPlanStopInDb(req.params.travelPlanId,req.params.stopId,link)
createResponse(res, 200, "Successfully linked travel plan and stop", {
link
});
} catch (exception) {
next(exception);
}
}
}
module.exports.adminController = adminController;
|
var React = require('react');
var SendForm = require('SendForm');
var TokenMessage = require('TokenMessage');
var ErrorModal = require('./ErrorModal');
var Web3 = require('web3');
const contract = require('truffle-contract');
const MeetupTokenContract = require('../../build/contracts/MeetupToken.json');
var SendToken = React.createClass({
getInitialState: function () {
return {
isLoading: false
}
},
componentWillMount: function() {
var account;
var self = this;
// Get network provider and web3 instance.
if (typeof web3 !== 'undefined') {
// Use Status'/MetaMask's provider.
web3 = new Web3(web3.currentProvider)
} else {
this.setState({
errorMessage: 'Unable to connect to Ethereum. Please check you have MetaMask installed and that you have access to your account.',
})
return
}
web3.eth.getAccounts((error, accounts) => {
account = accounts[0];
self.setState({
account: account
})
})
this.setState({
web3: web3
})
const MeetupToken = contract(MeetupTokenContract)
MeetupToken.setProvider(web3.currentProvider)
MeetupToken.at('0xac55f0311b290118adabe46d9767dbb91aaf3df3').then((instance) => {
instance.balanceOf(account, {from: account, gas: 80000}).then(function(res) {
var balance = res.toNumber();
self.setState({
balance: balance
})
})
})
},
handleSend: function (addressTo, amount) {
var self = this;
this.setState({
isLoading: true,
errorMessage: undefined
});
const MeetupToken = contract(MeetupTokenContract)
MeetupToken.setProvider(this.state.web3.currentProvider)
MeetupToken.at('0xac55f0311b290118adabe46d9767dbb91aaf3df3').then((instance) => {
instance.transfer(addressTo, amount, {from: this.state.account, gas: 80000}).then((res) => {
var txHash = res.tx;
self.setState({
txHash: txHash,
isLoading: false
})
}).catch(function(e) {
self.setState({
isLoading: false,
errorMessage: e.message
});
});
});
},
render: function () {
var {isLoading, txHash, errorMessage, account, balance} = this.state;
function renderMessage() {
if (isLoading) {
return <h3 className="text-center">Sending Transaction...</h3>;
} else if (txHash) {
return <TokenMessage txHash={txHash} />;
}
}
function renderError () {
if (typeof errorMessage === 'string') {
return (
<ErrorModal message={errorMessage}/>
)
}
}
return (
<div className="columns medium-6 large-4 small-centered">
<h1 className="text-center page-title">Share the Love</h1>
<h4 className="text-center page-title">Account</h4>
<p className="text-center">{account}</p>
<p className="text-center">Your MET balance: {balance}</p>
<br/>
<h4 className="text-center sub-title">Send Your Tokens Anywhere!</h4>
<SendForm onSend={this.handleSend}/>
{renderMessage()}
{renderError()}
</div>
);
}
});
module.exports = SendToken;
|
import { lexicographicSortSchema, printSchema } from 'graphql/utilities';
export default function printSchemaOrdered(originalSchema) {
return printSchema(lexicographicSortSchema(originalSchema));
}
|
var express = require("express"); //
var bodyParser = require("body-parser"); // body parameter parser for POST and PUT request body encoading
var url = require('url'); // url parser for GET and DELETE parameter encoading
var fileUpload = require('express-fileupload'); // For POST and PUT multi-part boyd request encoading
var app = express();
// default options
app.use(fileUpload());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var server = app.listen(3000, function () {
console.log("Listening on port %s...", server.address().port);
});
var startLine = endLine = "---------------------------------------------------"
// Handle get request type
app.get("/user", function (req, res) {
console.log(startLine);
console.log("New Request GET received");
// parse url parameters
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query);
if (!req.headers) {
console.log('No headers added');
} else {
console.log('HEADERS are ');
console.log(req.headers);
}
console.log(endLine);
// return query data
res.json(query);
});
// Handle post request type
app.post('/user', function (req, res) {
console.log(startLine);
console.log("New Request POST received");
console.log(req.body);
if (!req.headers) {
console.log('No headers added');
} else {
console.log('HEADERS are ');
console.log(req.headers);
}
if (!req.files) {
console.log('No files were uploaded.');
} else {
console.log(req.files);
}
console.log(endLine)
// return body data
res.json(req.body);
});
// Handle put request type
app.put('/user', function (req, res) {
console.log(startLine);
console.log("New Request PUT received");
console.log(req.body);
if (!req.headers) {
console.log('No headers added');
} else {
console.log('\nHEADERS are ');
console.log(req.headers);
}
if (!req.files) {
console.log('No files were uploaded.');
} else {
console.log(req.files);
}
console.log(endLine)
// return body data
res.json(req.body);
});
// Handle delete request type.
app.delete("/user", function (req, res) {
console.log(startLine);
console.log("New Request DELETE received");
// parse url parameters
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query);
if (!req.headers) {
console.log('No headers added');
} else {
console.log('HEADERS are ');
console.log(req.headers);
}
console.log(endLine)
// return query data
res.json(query);
});
// Anonymous request found.
app.use(function(req, res, next){
res.status(404);
// respond with json
if (req.accepts('json')) {
res.send({ error: '404 not found' , url : req.url });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
}); |
import React from 'react';
const Score = (props) => {
return(
<div>Current Score: {props.currentScore}</div>
)
}
export default Score; |
/* jshint indent: 2 */
module.exports = function(sequelize, DataTypes) {
return sequelize.define('cl_component', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
title: {
type: DataTypes.STRING(255),
allowNull: false
},
description: {
type: DataTypes.TEXT,
allowNull: false
},
category_id: {
type: DataTypes.INTEGER(11),
allowNull: false
},
tags: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: ''
},
preview: {
type: DataTypes.STRING(255),
allowNull: false
},
thumbnails: {
type: DataTypes.STRING(255),
allowNull: false
},
config: {
type: DataTypes.TEXT,
allowNull: false
},
alias: {
type: DataTypes.STRING(255),
allowNull: false
}
}, {
tableName: 'cl_component'
});
};
|
'use strict'
import { NavigationExperimental } from 'react-native'
import * as types from './constant'
const {
StateUtils: NavigationStateUtils
} = NavigationExperimental
export const initialLoginNavigationState = {
index: 0,
routes: [{
key: 'LoginPage',
title: '登录'
}]
}
export const initialRootNavigationState = {
index: 0,
routes: [{
key: 'MainPage'
}]
}
export const initialHomeNavigationState = {
index: 0,
routes: [{
key: 'HomePage',
title: '首页'
}]
}
export const initialUserNavigationState = {
index: 0,
routes: [{
key: 'UserPage',
title: '我的'
}]
}
const initialState = {
navigationStates: {
[types.NAVIGATOR_NAME_ROOT]: initialRootNavigationState,
[types.NAVIGATOR_NAME_LOGIN]: initialLoginNavigationState,
[types.NAVIGATOR_NAME_HOME]: initialHomeNavigationState,
[types.NAVIGATOR_NAME_USER]: initialUserNavigationState
},
tabbarState: {
selectedTab: 'HomeTab'
}
}
export default function navigation (state = initialState, action) {
switch (action.type) {
case types.NAVIGATION_PUSH:
case types.NAVIGATION_POP: {
let originalNavigationState = state.navigationStates[action.navigator]
let navigationState = null
if (action.type === types.NAVIGATION_PUSH) {
navigationState = NavigationStateUtils.push(originalNavigationState, action.route)
} else if (action.type === types.NAVIGATION_POP) {
navigationState = NavigationStateUtils.pop(originalNavigationState)
}
if (navigationState && navigationState !== originalNavigationState) {
return Object.assign({}, state, {
navigationStates: Object.assign({}, state.navigationStates, {[action.navigator]: navigationState})
})
}
break
}
case types.NAVIGATION_LOGIN_RESET: {
return Object.assign({}, state, {
navigationStates: Object.assign({}, state.navigationStates, {[action.navigator]: initialLoginNavigationState})
})
}
case types.TABBAR_SWITCH: {
return Object.assign({}, state, {
tabbarState: {
selectedTab: action.tabProps.key
}
})
}
default:
return state
}
return state
} |
import React, { useState, useEffect } from "react";
import { Route } from "react-router-dom";
import styled from "styled-components";
import PropTypes from "prop-types";
import ReactRouterPropTypes from "react-router-prop-types";
import Avatar from "../BaseComponents/Avatar";
import Text from "../BaseComponents/Text";
import CustomizedButton from "../BaseComponents/CustomizedButton";
import {
LocationIcon,
BirthdayIcon,
CalendarIcon,
SettingIcon
} from "../BaseComponents/SVGIcons";
import BackHeadWithRouter from "../middleComponents/BackHead";
import Tweets from "./Tweets";
import PullDownRefresh from "../middleComponents/PullDownRefresh";
import { getUserByName } from "../Api";
import NavigationList from "../middleComponents/NavigationList";
import LayOut from "../layout/Layout";
import { userType } from "../propTypes";
function WithReplies() {
return <Tweets />;
}
function Media() {
return (
<div style={{ margin: "37px 18px", textAlign: "center" }}>
<div>
<Text xlarge bold>
你还没有发过任何带照片或视频的推文
</Text>
</div>
<div style={{ marginTop: "9px" }}>
<Text large secondary>
当你发送带照片或视频的推文时,它就会出现在这里。
</Text>
</div>
<CustomizedButton large>发照片或视频推文</CustomizedButton>
</div>
);
}
function Likes() {
return <h1>喜欢</h1>;
}
const Container = styled.div`
position: relative;
`;
const UserAvaterBG = styled.div`
padding-bottom: 33.33%;
background-color: rgb(204, 214, 221);
`;
const UserAvaterWrapper = styled.div`
padding: 2px;
background-color: rgb(255, 255, 255);
border-radius: 9999px;
margin-top: -47.5px;
display: inline-block;
margin-bottom: 9px;
`;
const InlineSvgWrapper = styled.div`
margin-right: 9px;
display: flex;
align-items: stretch;
`;
const SvgWrapper = styled.span`
margin-right: 5px;
`;
const SettingButton = styled.button`
border: 1px solid rgb(27, 149, 224);
border-radius: 9999px;
min-height: 37px;
min-width: 37px;
display: flex;
align-items: center;
justify-content: center;
margin-right: 9px;
background-color: transparent;
&:focus {
outline: none;
}
`;
export default function User({
match,
currentUser,
showUserSettingPopupMenu,
setPopupPosition
}) {
const [user, setUser] = useState();
function handleRefresh() {
return new Promise(resolve => {
setTimeout(() => resolve(), 100);
});
}
useEffect(() => {
const { userName } = match.params;
getUserByName(userName)
.then(userData => setUser(userData))
.catch(() => {});
}, []);
const { userName } = match.params;
function handleSettingClick({ target }) {
showUserSettingPopupMenu();
if (window.matchMedia("(min-width: 1000px)").matches) {
const { left, top } = target.getBoundingClientRect();
setPopupPosition({
left,
top,
right: null,
bottom: null
});
}
}
// console.log({ userName });
return (
<LayOut
narrowHead={<BackHeadWithRouter title={user && user.name} />}
main={(
<PullDownRefresh onRefresh={handleRefresh}>
<Container>
<UserAvaterBG />
<div style={{ padding: "9px 9px 0", marginBottom: "14px" }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "flex-start"
}}
>
<UserAvaterWrapper>
{user && user.avatarSrc && <Avatar user={user} large />}
</UserAvaterWrapper>
{currentUser && currentUser.name === userName ? (
<CustomizedButton>编辑个人资料</CustomizedButton>
) : (
<div style={{ display: "flex" }}>
<SettingButton
type="button"
onClick={e => handleSettingClick(e)}
>
<SettingIcon middle primary />
</SettingButton>
<CustomizedButton>关注</CustomizedButton>
</div>
)}
</div>
<div style={{ margin: "5px 0 9px" }}>
<Text bold large>
{user && user.name}
</Text>
<br />
<Text secondary>
@{user && user.nickName}</Text>
</div>
<div style={{ marginBottom: "9px", display: "flex" }}>
<InlineSvgWrapper>
<SvgWrapper>
<LocationIcon xsmall secondary />
</SvgWrapper>
<Text secondary>{user && user.location}</Text>
</InlineSvgWrapper>
<InlineSvgWrapper>
<SvgWrapper>
<BirthdayIcon xsmall secondary />
</SvgWrapper>
<Text secondary>
出生于
{user && user.birthday}
</Text>
</InlineSvgWrapper>
<InlineSvgWrapper>
<SvgWrapper>
<CalendarIcon xsmall secondary />
</SvgWrapper>
<Text secondary>
{user && user.registerTime}
加入
</Text>
</InlineSvgWrapper>
</div>
<div style={{ display: "flex" }}>
<div style={{ marginRight: "18px" }}>
<Text bold>{user && user.following}</Text>
<Text secondary>正在关注</Text>
</div>
<Text bold>{user && user.followers}</Text>
<Text secondary>关注者</Text>
</div>
</div>
<NavigationList
links={[
{
to: match.url,
title: "推文",
exact: true,
ariaLabel: "View all tweets"
},
{
to: `${match.url}/with_replies`,
title: "推文与回复",
ariaLabel: "View all replys"
},
{
to: `${match.url}/media`,
title: "媒体",
ariaLabel: "View all media"
},
{
to: `${match.url}/likes`,
title: "喜欢",
ariaLabel: "View all liked tweets"
}
]}
/>
<Route path={match.url} exact component={Tweets} />
<Route path={`${match.url}/with_replies`} component={WithReplies} />
<Route path={`${match.url}/media`} component={Media} />
<Route path={`${match.url}/likes`} component={Likes} />
</Container>
</PullDownRefresh>
)}
/>
);
}
User.propTypes = {
match: ReactRouterPropTypes.match.isRequired,
showUserSettingPopupMenu: PropTypes.func.isRequired,
setPopupPosition: PropTypes.func.isRequired,
currentUser: userType.isRequired
};
|
import { createNumberMask, createTextMask } from 'redux-form-input-masks'
export const normalizeAll = (normalizers) => {
return (value, previousValue, allValues, previousAllValues) => {
let i = 0
const normalizersLength = normalizers.length
let currentValue = value
while (i < normalizersLength) {
const currentNormalizer = normalizers[i]
if (typeof currentNormalizer === 'function') {
currentValue = currentNormalizer(currentValue, previousValue, allValues, previousAllValues)
}
i++
}
return currentValue
}
}
export const currencyMask = createNumberMask({
prefix: 'R$ ',
decimalPlaces: 2,
locale: 'pt-BR',
})
export const currencyMaskWithoutPrefix = createNumberMask({
decimalPlaces: 2,
locale: 'pt-BR',
})
export const phoneMask = createTextMask({
pattern: '(99) 999 999 999',
guide: false,
})
// TODO: Change to datepicker
export const dateMask = createTextMask({
pattern: '99/99/9999',
guide: false,
stripMask: false,
})
export const cepMask = createTextMask({
pattern: '99999-999',
guide: false,
stripMask: false,
})
export const onlyNumbers = (value) => {
if (value) {
const onlyNums = value.replace(/[^\d]/g, '')
return onlyNums
}
return value
}
export const cepNormalizer = (value) => {
if (value) {
const onlyNums = value.replace(/[^\d]/g, '')
if (onlyNums.length <= 5) {
return onlyNums
}
return `${ onlyNums.slice(0, 5) }-${ onlyNums.slice(5, 8) }`
}
return value
}
export const maxLength = (max) => (value) => {
if (value) {
const onlyNums = value.slice(0, max)
return onlyNums
}
return value
}
export const cpfNormalizer = (value) => {
if (value) {
const onlyNums = value.replace(/[^\d]/g, '')
if (onlyNums.length <= 3) {
return onlyNums
}
if (onlyNums.length <= 6) {
return `${ onlyNums.slice(0, 3) }.${ onlyNums.slice(3, 6) }`
}
if (onlyNums.length <= 9) {
return `${ onlyNums.slice(0, 3) }.${ onlyNums.slice(3, 6) }.${ onlyNums.slice(6, 9) }`
}
return `${ onlyNums.slice(0, 3) }.${ onlyNums.slice(3, 6) }.${ onlyNums.slice(6, 9) }-${ onlyNums.slice(9, 11) }`
}
return value
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import SearchHitachi from './SearchHitachi';
import HS from './HS';
import Hitachivantara from './Hitachivantara';
import Vti from './Vti';
//import '@fortawesome/fontawesome-free/css/all.min.css';
import 'bootstrap-css-only/css/bootstrap.min.css';
import 'mdbreact/dist/css/mdb.css';
import {
BrowserRouter as Router,
Route,
Redirect
} from "react-router-dom";
import SLV1 from './SLV1';
import IBMS from './IBMS';
import ITkt from './ITkt';
import Chart from './Chart';
import IBT from './IBT';
import Contact from './Contact';
import Login from './Login';
import Eticket from './Eticket';
import Helpers from './Helpers';
import FileM from './FileM';
import Upld from './Upld'
ReactDOM.render(
<React.StrictMode>
<Router>
<Route exact path="/" render={() => (
<Redirect to="/login"/>
)} />
<Route path="/App">
<App/>
</Route>
<Route path="/searchHitachi">
<SearchHitachi/>
</Route>
<Route path="/ITkt">
<ITkt/>
</Route>
<Route path="/Upld">
<Upld/>
</Route>
<Route path="/Helpers">
<Helpers/>
</Route>
<Route path="/HS">
<HS/>
</Route>
<Route path="/SLV1">
<SLV1/>
</Route>
<Route path="/Hitachivantara">
<Hitachivantara/>
</Route>
<Route path="/Vti">
<Vti/>
</Route>
<Route path="/IBMS">
<IBMS/>
</Route>
<Route path="/IBT">
<IBT/>
</Route>
<Route path="/Chart">
<Chart/>
</Route>
<Route path="/Contact">
<Contact/>
</Route>
<Route path="/Eticket">
<Eticket/>
</Route>
<Route path="/login">
<Login/>
</Route>
<Route path="/FileM">
<FileM/>
</Route>
</Router>
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
$().ready(function(){
$(validForm())
$("#comp-sub").click(function(){
if(!validForm().form())
return;
$("#company-valid-form").submit();
});
$("#comp-cancel").click(function(){
window.location.href = "/CXZKVIP/usermanage/personal/show";
});
})
jQuery.validator.addMethod("regex", function(value, element, param) {
var r = param;
return r.test(value);
}, "填写不正确");
function validForm(){
return $("#company-valid-form").validate({
rules:{
NICKNAME: {
required:true,
rangelength:[3,8],
},
COMPNAME:{
required:true,
},
COMPNUM:{
required:true
},
REALNAME:{
required:true,
rangelength:[2,8],
regex:/[^\u0000-\u00FF]/,
},
ADDRESS:{
required:true
},
PIC:{
required:true
},
EMAIL:{
email:true
}
},
messages: {
NICKNAME: {
required: "请输入昵称",
rangelength: "长度必须为3-8位字符",
},
COMPNAME:{
required:"请输入公司名称",
},
COMPNUM:{
required:"请输入营业执照"
},
REALNAME:{
required:"请输入真实姓名",
rangelength:"长度不正确",
regex:"格式不正确"
},
ADDRESS:{
required:"请输入公司地址"
},
PIC:{
required:"请选择图片"
},
EMAIL:{
email:"邮箱格式不正确"
}
},
errorElement: "em"
});
} |
import React from 'react'
const FirebaseContext = React.createContext(null)
// FirebaseContext.Provider
// FirebaseContext.Consumer
export default FirebaseContext |
import {submitNamed} from '/lib/xp/task';
import isMaster from '../lib/microsoftGraph/cluster/isMaster.es';
export function run() {
if (!isMaster()) { // Only execute job on master
return;
}
log.info('Starting sync task...');
submitNamed({
name: 'sync',
config: {
userStore: 'graph' // NOTE Hardcode
}
});
} // export function run
|
import axios from 'axios';
export const url = "https://pokeapi.co/api/v2/";
const api = axios.create({
baseURL: url
})
export default api; |
export { get as getPayments } from './get';
|
import React from 'react';
function WordCard(props) {
return (
<div className="col-sm-3 py-2">
<div className="card card-body h-100 d-flex flex-column">
<h5 className="card-title">{props.word}</h5>
<p class="card-text">{props.meaning}</p>
</div>
</div>
)
}
export default WordCard; |
/** @jsxImportSource @emotion/core */
import { css } from "@emotion/core";
const activeInput = css`
background-color: #434a52;
cursor: pointer;
color: #c4c7c9;
font-weight: 600;
`;
const hourInput = css`
display: flex;
justify-content: center;
width: min-content;
flex-flow: column;
align-items: center;
`;
const hourInput__container = css`
display: grid;
grid-template-rows: 100px;
grid-template-columns: repeat(4, 150px);
align-items: center;
`;
const hourInput__day = css`
font-size: 20px;
`;
export { activeInput,hourInput, hourInput__container, hourInput__day };
|
function _(id) {
return document.getElementById(id);
}
function submitForm() {
_('mybtn').disabled = true;
_('status').innerHTML = 'please wait...';
let formdata = new FormData();
formdata.append('name', _('name').value);
formdata.append('email', _('email').value);
formdata.append('message', _('message').value);
let ajax = new XMLHttpRequest();
ajax.open('POST', 'example_parser.php');
ajax.onreadystatechange = function() {
if(ajax.readyState === 4 && ajax.status === 200) {
console.log(ajax);
if(ajax.statusText === 'OK') {
_('myForm').innerHTML = '<h2>Thanks ' + _('name').value + ', your form has been submitted.</h2>';
} else {
('status').innerHTML = ajax.responseText;
_('mybtn').disabled = false;
}
}
}
ajax.send(formdata);
} |
import React from 'react'
import classNames from 'classnames'
import Link from './Link'
import Icon from './Icon'
import MiniNumber from './MiniNumber'
const DocsCard = ({ title, description, url, titlePrefix = '', colorClass, items }) => {
const titleContent = titlePrefix ? `${titlePrefix} - ${title}` : title
return (
<Link
key={title}
to={url}
colorClassName='text-qrigray-400'
>
<div
className='rounded-lg border-solid border border-qrigray-100 hover:border-qripink box-border px-4 py-3 flex h-28 transform transition-all duration-100'
>
<div className="flex-shrink-0">
<Icon icon='docsRing' size='3xs' className={classNames('mb-1 mr-2.5', colorClass)} />
</div>
<div className="flex-grow flex flex-col min-w-0">
<div className='font-bold text-black mb-2 flex items-center tracking-wide'>{titleContent} {items && <MiniNumber className='ml-3'>{items.length}</MiniNumber>}</div>
<div className='text-sm overflow-hidden break-word' style={{
display: '-webkit-box',
WebkitLineClamp: 2,
WebkitBoxOrient: 'vertical'
}}>{description}</div>
</div>
</div>
</Link>
)
}
export default DocsCard
|
updateVaccineStatusData();
function updateVaccineStatusData(){
let lastDate = null;
let vaccineList = null;
$.ajax({
url:"GetVaccStatusLastDate.do",
success:function(resultData){
lastDate = resultData;
if(lastDate < dateToYearVaccine(new Date())){
lastDate = StringToDateVaccine(lastDate);
let sendData = {
baseDate:lastDate,
}
$.ajax({
url:"VaccineStatusApiCall.do",
data:sendData,
success:function(resultData){
let list_length = 0;
if(resultData.data != null) {
vaccineList = resultData.data;
list_length = vaccineList.length;
}
let dataList = "";
for(let i = 0; i < list_length; i++){
let baseDate = vaccineList[i].baseDate;
let area = vaccineList[i].sido;
let firstCnt = vaccineList[i].firstCnt.toString();
let secondCnt = vaccineList[i].secondCnt.toString();
let totalFirstCnt = vaccineList[i].totalFirstCnt.toString();
let totalSecondCnt = vaccineList[i].totalSecondCnt.toString();
dataList += baseDate +"/"+ area +"/"+ firstCnt +"/"+ secondCnt +"/"+ totalFirstCnt + "/" + totalSecondCnt;
dataList += "&";
}
sendData = {
dataList:dataList
}
if(dataList != ""){
$.ajax({
url:"InsertVaccineInfo.do",
data:sendData,
success:function(resultData){
}
})
}
}
})
}
}
})
}
function dateToYearVaccine(_date) {
let year = _date.getFullYear();
let month = _date.getMonth() + 1;
if (month < 10) month = '0' + month;
let date = _date.getDate();
if (date < 10) date = '0' + date;
return year + '' + month + '' + date;
}
function StringToDateVaccine(_str) {
if(typeof _str == "number"){
_str = _str.toString();
}
let str = _str.slice(0,4) +"-"+ _str.slice(4,6) +"-"+ _str.slice(6,8) + " "+"00:00:00";
return str;
}
function prevDataVaccine(amount, _date){
if(typeof _date == "number"){
_date = _date.toString();
}
_date = new Date(Number(_date.substring(0,4)),Number(_date.substring(4,6))-1,Number(_date.substring(6,8)));
let _buf_date = _date;
_buf_date.setDate(_buf_date.getDate() - amount);
_buf_date = dateToYearVaccine(_buf_date);
return _buf_date;
}
function changeVaccineCategory(){
let category1 = ["1주", "2주", "1달", "3달", "전체"];
let category2 = ["1달", "3달", "전체"];
let category3 = ["3달", "전체"];
let target = $("#period");
let _this = $("#type");
let addList = null;
if(_this.val() == "일별") addList = category1;
else if(_this.val() == "주별") addList = category2;
else if(_this.val() == "월별") addList = category3;
$("#period option").remove();
for (x in addList) {
if(x == 0)
target.append("<option selected='selected'>"+ addList[x] +"</option>");
else
target.append("<option>"+ addList[x] +"</option>");
}
} |
window.onload = function(){
var FADE_TIME = 150;
var TYPING_TIMER_LENGTH = 400;
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
]
// Initialize variables
var windowObj = window;
var usernameInput = document.querySelector('.usernameInput');
var messages = document.querySelector('.messages');
var inputMessage = document.querySelector('.inputMessage');
var loginPage = document.querySelector('.login.page');
var chatPage = document.querySelector('.chat.page');
//Prompt for setting a username
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var currentInput = usernameInput.focus();
var socket = io();
const addParticipantsMessage = (data) => {
var message = '';
if(data.numUser === 1 ) {
message += "there's 1 participant";
} else {
message += "there are " + data.numUsers + " participants";
}
log(message);
}
//로그인
socket.on('login', (data) => {
connected = true;
var message = "socket IO 채팅에 오셨네엽!";
log(message, {
prepend: true
});
console.log('data',data);
addParticipantsMessage(data);
});
window.onkeydown = (keycode) => {
if(keycode.key == 'Enter'){
if(username) {
sendMessage();
typing = false;
} else {
console.log('Enter else');
setUsername();
}
}
}
const sendMessage = () => {
//메세지 값
var message = inputMessage.value;
//Prevent markup from being injected into the message
//if there is a non-empty message and a socket connetion
if(message && connected){
inputMessage.value = '';
addChatMessage({
username: username,
message: message
});
//tell server to excute 'new message' and send along one parameter
socket.emit('new message', message);
}
}
const cleanInput = (input) => {
// return `<div>${input}</div>`
return $('<div/>').text(input).html();
};
const setUsername = () => {
//공백같은거 제거해야함
username = usernameInput.value.trim();
if(username) {
loginPage.classList.add('hide');
loginPage.classList.remove('show');
chatPage.style.display = 'block';
// loginPage.removeEventListener('click', currentInput,false);
currentInput = inputMessage.focus();
// inputMessage.style.display = 'block';
// currentInput = inputMessage.focus();
//Tell the server your username
socket.emit('add user', username);
}
}
//타이핑 메시지 얻기
const getTypingMessages = (data) => {
// console.log('겟타이핑메세지',data);
// console.log(document.querySelector('.typing.message'));
// Array.prototpy
}
const getUsernameColor = (username) => {
var hash = 7;
for(var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
//calculate color
var index = Math.abs(hash % COLORS.length);
console.log('색깔은?',COLORS[index]);
return COLORS[index];
}
//Adds the visual chat message to the message list
const addChatMessage = (data, options) => {
// console.log('탸핑', typingMessages);
var hoho = [data];
var typingMessages = document.createElement('div');
hoho.filter( jayeon => {
typingMessages.classList.add('typing');
typingMessages.classList.add('message');
typingMessages.innerText = jayeon.username;
});
console.log('탸핑길이',typingMessages);
options = options || {};
if(document.querySelector('.typing')){
options.fade = false;
document.querySelector('.typing').remove();
}
var usernameDiv = document.createElement('span');
usernameDiv.classList.add('username');
usernameDiv.style.color = getUsernameColor(data.username);
usernameDiv.innerText = data.username+' : ';
var messageBodyDiv = document.createElement('span');
messageBodyDiv.classList.add('messageBody');
messageBodyDiv.innerText = data.message;
// var typingClass = data.typing ? 'typing' : '';
// console.log('typingClass',typingClass);
var messageDiv = document.createElement('li');
// messageDiv.classList.add('message');
// messageDiv.innerText = data.username;
// messageBodyDiv.classList.add(typingClass);
// messageBodyDiv.classList.add(typingClass);
// document.querySelector('.typing').classList.add('hide');
messageDiv.append(usernameDiv, messageBodyDiv);
addMessageElement(messageDiv, options);
}
//로그메시지
const log = (message, options) => {
var el = document.createElement('li');
el.classList.add('log');
el.innerHTML = message;
addMessageElement(el, options);
}
const addChatTyping = (data) => {
data.typing = true;
data.message = 'is typing';
// console.log('addChatTyping', data);
// addChatMessage(data);
aaa(data,'');
}
const aaa = (data,options) => {
// console.log('탸핑', typingMessages);
var hoho = [data];
var typingMessages = document.createElement('div');
hoho.filter( jayeon => {
typingMessages.classList.add('typing');
typingMessages.classList.add('message');
typingMessages.innerText = jayeon.username;
});
options = options || {};
if(typingMessages.length !== 0) {
options.fade = false;
typingMessages.remove();
}
var usernameDiv = document.createElement('span');
usernameDiv.classList.add('username');
usernameDiv.style.color = getUsernameColor(data.username);
usernameDiv.innerText = data.username+' : ';
var messageBodyDiv = document.createElement('span');
messageBodyDiv.classList.add('messageBody');
messageBodyDiv.innerText = data.message;
var typingClass = data.typing ? 'typing' : '';
var messageDiv = document.createElement('li');
// messageDiv.classList.add('message');
// messageDiv.innerText = data.username;
messageDiv.classList.add(typingClass);
// messageBodyDiv.classList.add(typingClass);
messageDiv.append(usernameDiv, messageBodyDiv);
addMessageElement(messageDiv, options);
}
const updateTyping = () => {
if(connected) {
if(!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(() => {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
document.querySelector('.typing').remove();
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
const addMessageElement = (el, options) => {
var elTwo = el;
//기본옵션 셋업
if(!options) {
options= {};
}
if(typeof options.fade === 'undefined'){
options.fade = true;
}
if(typeof options.prepend == 'undefined') {
options.prepend = false;
}
//옵션 적용
if(options.fade) {
elTwo.classList.add('show');
elTwo.classList.remove('hide');
}
if(options.prepend) {
//메세지 나오는거 전에 추가
messages.prepend(elTwo);
} else {
messages.append(elTwo);
console.log('elTwo append',elTwo);
}
messages.scrollTop = messages.scrollHeight;
}
loginPage.onclick = () => {
inputMessage.focus();
}
inputMessage.onclick = () => {
inputMessage.focus();
}
inputMessage.addEventListener('input', () => {
updateTyping();
});
socket.on('new message', (data) => {
addChatMessage(data);
});
socket.on('typing', (data) => {
addChatTyping(data);
});
socket.on('user joined', (data) => {
log(data.username + ' joined');
addParticipantsMessage(data);
})
socket.on('disconnect', () => {
log('you have been disconnected');
});
};
|
'use strict';
UserManager.Models.UserInfo = Backbone.Model.extend({});
|
export default {
otherdatas: '' //断货补单王数据
} |
const express=require('express');
const app=express();
const mongoose=require('mongoose')
const bodyParser=require('body-parser');
const Employee=require('./models/Employee');
const TeaserData=require('./models/TeaserData');
const Images=require('./models/Image');
const imageMimeType=['image/jpg','image/png','image/jpeg']
mongoose.connect("mongodb://localhost:27017/moonraftEmployeeRegistration",{ useNewUrlParser: true });
const db=mongoose.connection;
db.once('error',(err)=>{
console.log(err)
})
db.on('open',()=>{
console.log('db is connected')
})
app.set('view engine','ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',(req,res,next)=>{
res.render('index');
});
app.get("/register",(req,res)=>{
res.render("register");
});
app.get("/login",(req,res)=>{
res.render("login");
})
app.get("/teaserData",async (req,res)=>{
try{
const allImages= await Images.find();
res.render("teaserData",{
allImages
});
}
catch(err){
console.log(err)
}
})
// app.post('/add', async (req,res,next)=>{
// const {firstname,lastname,email,password,img}=req.body;
// const employee=new Employee({
// firstname,
// lastname,
// email,
// password,
// img
// });
// saveImage(employee,img);
// try{
// const newEmployee=await employee.save()
// res.redirect('/')
// }
// catch(err){
// console.log(err)
// }
// console.log(employee);
// });
// app.post("/login",async (req,res)=>{
// try{
// const email=req.body.email;
// const password=req.body.password;
// console.log(password);
// const useremail=await Employee.findOne({email:email})
// if(useremail.password==password){
// res.status(201).render("employeeData",{
// firstname:useremail.firstname,
// lastname:useremail.lastname,
// email:useremail.email,
// imgSrc:`data:${useremail.imgType};charset=utf-8;base64,${useremail.img.toString('base64')}`
// })
// }
// else{
// res.send("password not matching")
// }
// }
// catch(error){
// res.status(400).send("Invalid Email id");
// }
// })
app.post('/teaseradd', async (req,res,next)=>{
const {teasertext,teaserdescription,img}=req.body;
const teaser=new TeaserData({
teasertext,
teaserdescription
});
const image=new Images({
img
});
saveImage(image,img);
try{
const newTeaser=await teaser.save()
const newImage=await image.save()
res.redirect('/')
}
catch(err){
console.log(err)
}
});
// save image as binary file
const saveImage= async (image,imgEncoded)=>{
if(imgEncoded == null) return ;
const img=await JSON.parse(imgEncoded)
if(img!=null && imageMimeType.includes(img.type)){
image.img=new Buffer.from(img.data,'base64');
image.imgType=img.type
}
}
app.listen(3000,()=>console.log('Server is working on port 3000')) |
import React from 'react'
import { useState } from 'react';
import { addCategory } from '../services/category'
export default function Category(props) {
const { category, currentUser } = props;
const [formData, setFormData] = useState({
name: ""
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prevState) => ({
...prevState,
[name]: value,
}));
};
const { name} = formData;
const handleSubmit = async (e) => {
e.preventDefault();
const newCategory = await addCategory(formData)
}
return (
<div>
<h3>Categories </h3>
{
currentUser && category.map(categ => (
<p key={categ.id}>{categ.name}</p>
))
}
<form onSubmit={handleSubmit}>
<input value={name}
name="name"
onChange={handleChange}></input>
<button>add</button>
</form>
</div>
)
}
|
function getCountriesWithMaxCountCities(countries) {
var list = [];
countries.filter(function (country) {
return country.cities.length === getMaxCountCities(countries);
})
.forEach(function (country) {
list.push(country.name);
});
return list;
}
function getMaxCountCities(countries) {
return countries.reduce(function (maxCount, country) {
if (country.cities.length > maxCount) {
maxCount = country.cities.length;
}
return maxCount
}, 0);
}
function getCountriesWithTotalPopulations(countries) {
var countriesTotalPopulation = {};
countries.forEach(function (country) {
countriesTotalPopulation[country.name] = country.cities
.reduce(function (total, city) {
return total + city.population;
}, 0);
});
return countriesTotalPopulation;
}
(function () {
var countries = [
{
name: "Russia",
cities: [
{
name: "Moscow",
population: 12692466
},
{
name: "Saint-Petersburg",
population: 5392992
},
{
name: "Novosibirsk",
population: 1618039
},
{
name: "Yekaterinburg",
population: 1483119
}
]
},
{
name: "China",
cities: [
{
name: "Beijing",
population: 21150000
},
{
name: "Shanghai",
population: 24150000
},
{
name: "Chungking",
population: 30165000
}
]
},
{
name: "Germany",
cities: [
{
name: "Berlin",
population: 3520031
},
{
name: "Hamburg",
population: 1787408
},
{
name: "Munich",
population: 1450381
}
]
}
];
console.log("Страны в массиве с максимальной численностью городов: ", getCountriesWithMaxCountCities(countries));
console.log("Общее количество населения стран из массива: ", getCountriesWithTotalPopulations(countries));
}());
|
/**
* @fileoverview Provides mapbox main namespace.
*/
/**
* Application namespace for collaboration demo.
*/
var mapbox = {};
/**
* Enumeration of events with the server.
*
* @enum {string}
*/
mapbox.Topics = {
FEATURE_CREATED: '//feature/created',
FEATURE_DELETED: '//feature/deleted',
FEATURE_EDITED: '//feature/edited'
};
/**
* Generates a random alpha-numeric hash for use as a temporary identifier.
*
* Not really very securely random, but good enough for this demo.
*
* @return {string} A random alpha-numeric string.
*/
mapbox.generateHash = function() {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
for(var i = 0; i < 15; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text + (new Date()).getTime();
};
try {
module.exports = mapbox;
} catch(e) {}
|
import StyleguideForm from '@/StyleguideForm.js'
import {AjaxHelper} from './../helpers/Helpers.js'
describe('StyleguideForm.js', () => {
let ajaxHelper;
let record;
let form;
beforeEach(() => {
ajaxHelper = new AjaxHelper();
ajaxHelper.install();
record = {id: 15, title: 'Foo', body: 'Bar'};
form = new StyleguideForm(record);
})
afterEach(() => {
ajaxHelper.uninstall();
})
it ('stores the passed object properties as its own properties', () => {
let form = new StyleguideForm({id: 15, title: 'Foo', body: 'Bar'});
expect(form.id).toBe(15);
expect(form.title).toBe('Foo');
expect(form.body).toBe('Bar');
})
it ('allows to constrain the properties to be transferred', () => {
let form = new StyleguideForm({id: 15, title: 'Foo', body: 'Bar'}, ['title']);
expect(form.id).toBe(15);
expect(form.title).toBe('Foo');
expect(form.body).toBe(undefined);
})
it ('caches the original data', () => {
form.id = 18;
form.title = 'Foobar';
form.body = 'Barbaz';
expect(form.id).toBe(18);
expect(form.title).toBe('Foobar');
expect(form.body).toBe('Barbaz');
expect(form.originalData.id).toBe(15);
expect(form.originalData.title).toBe('Foo');
expect(form.originalData.body).toBe('Bar');
})
it ('deep clones the original data', () => {
let form = new StyleguideForm({
weights: [
{title: 'Bold', weight: 700},
{title: 'Regular', weight: 500},
{title: 'Light', weight: 300}
]
});
form.weights[0].title = 'Heavy';
expect(form.weights[0].title).toBe('Heavy');
expect(form.originalData.weights[0].title).toBe('Bold');
})
it ('submits an ajax call', (done) => {
mockSuccessfulRequest();
form.submit('/pages', record);
ajaxHelper.expectAfterRequest(() => {
ajaxHelper.expectRequest('/pages/15', record);
}, done);
})
it ('submits an ajax call using the id of the instance', (done) => {
mockSuccessfulRequest();
form.submit('/pages');
ajaxHelper.expectAfterRequest(() => {
ajaxHelper.expectRequest('/pages/15', record);
}, done);
})
it ('submits an ajax call using the id of the instance even with constraints', (done) => {
mockSuccessfulRequest();
form = new StyleguideForm(record, ['title']);
form.submit('/pages');
ajaxHelper.expectAfterRequest(() => {
ajaxHelper.expectRequest('/pages/15', {title: 'Foo'});
}, done);
})
it ('stores feedback as a property after ajax call', (done) => {
mockSuccessfulRequest();
form.submit('/pages', record);
ajaxHelper.expectAfterRequest(() => {
expect(form.feedback).toEqual(['The page was updated.']);
}, done);
})
it ('emits an event after ajax call', (done) => {
mockSuccessfulRequest();
form.on('success', (data) => {
expect(data).toEqual({
feedback: ['The page was updated.'],
record: {id: 18, title: 'Foobar', body: 'Barbaz'}
});
done();
})
form.submit('/pages', record);
})
it ('stores feedback as a property after ajax call with errors', (done) => {
mockRequestWithErrors();
form.submit('/pages', record);
ajaxHelper.expectAfterRequest(() => {
expect(form.feedback).toEqual(['An error occourred']);
}, done);
})
it ('stores validation errors as a property after ajax call with errors', (done) => {
mockRequestWithValidationErrors();
form.submit('/pages', record);
ajaxHelper.expectAfterRequest(() => {
expect(form.errors).toEqual({title: ['Please provide a title']});
}, done);
})
it ('emits an event after failed ajax call', (done) => {
mockRequestWithErrors();
form.on('fail', (data) => {
done();
})
form.submit('/pages', record);
})
it ('allows to reset the props with the record returned by ajax request', (done) => {
form.shouldReset(true);
mockSuccessfulRequest();
form.submit('/pages', record);
ajaxHelper.expectAfterRequest(() => {
expect(form.id).toBe(18);
expect(form.title).toBe('Foobar');
expect(form.body).toBe('Barbaz');
}, done);
})
it ('caches original data again after an ajax request', (done) => {
form.shouldReset(true);
mockSuccessfulRequest();
expect(form.originalData.id).toBe(15);
expect(form.originalData.title).toBe('Foo');
expect(form.originalData.body).toBe('Bar');
form.submit('/pages', record);
ajaxHelper.expectAfterRequest(() => {
expect(form.originalData.id).toBe(18);
expect(form.originalData.title).toBe('Foobar');
expect(form.originalData.body).toBe('Barbaz');
}, done);
})
it ('resets the errors if a second request is successful', (done) => {
mockRequestWithValidationErrors();
form.submit('/pages', record);
ajaxHelper.expectAfterRequest(
() => {
expect(form.errors).not.toEqual({});
},
() => {
ajaxHelper.stubRequest(/foobar/, ajaxHelper.getSuccessfulResponse());
form.submit('/foobar', record);
ajaxHelper.expectAfterRequest(() => {
expect(form.errors).toEqual({});
}, done);
}
);
})
it ('provides a method to reset the form to its original data', () => {
expect(form.id).toBe(15);
expect(form.title).toBe('Foo');
expect(form.body).toBe('Bar');
form.id = 18;
form.title = 'Foobar';
form.body = 'Barbaz';
expect(form.id).toBe(18);
expect(form.title).toBe('Foobar');
expect(form.body).toBe('Barbaz');
form.reset();
expect(form.id).toBe(15);
expect(form.title).toBe('Foo');
expect(form.body).toBe('Bar');
})
it ('will add properties to an object if they are not set', () => {
let form = new StyleguideForm({contacts: []}, ['contacts', 'title']);
expect(form.contacts).toEqual([]);
expect(form.title).toBe('');
})
it ('will reset the form expect for the id, if the id was set after a successful request', (done) => {
mockSuccessfulRequest();
let form = new StyleguideForm({title: '', body: ''}, ['title', 'body']);
form.shouldReset(true);
expect(form.id).toBeNull();
form.submit('/pages');
ajaxHelper.expectAfterRequest(() => {
expect(form.id).toBe(18);
form.reset();
expect(form.id).toBe(18);
}, done)
})
it ('submits multipart-formdata header if has uploads', (done) => {
mockSuccessfulRequest();
let form = new StyleguideForm({}, []);
form.hasUploads(true);
form.filesChange('file', [new Blob()]);
form.submit('/pages');
ajaxHelper.expectAfterRequest(() => {
ajaxHelper.expectHeaders({'Content-Type': 'multipart/form-data'});
}, done)
})
it ('will not submit multipart-formdata header if has not uploads', (done) => {
mockSuccessfulRequest();
let form = new StyleguideForm({}, []);
form.filesChange('file', [new Blob()]);
form.submit('/pages');
ajaxHelper.expectAfterRequest(() => {
ajaxHelper.expectHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
}, done)
})
let mockSuccessfulRequest = () => {
let newRecord = {id: 18, title: 'Foobar', body: 'Barbaz'};
ajaxHelper.stubRequest(/pages/, ajaxHelper.getSuccessfulResponse(newRecord));
}
let mockRequestWithErrors = () => {
ajaxHelper.stubRequest(/pages/, ajaxHelper.getResponseWithErrors('An error occourred'));
}
let mockRequestWithValidationErrors = () => {
ajaxHelper.stubRequest(/pages/, ajaxHelper.getResponseWithValidationErrors({
title: ['Please provide a title']
}));
}
}) |
/*
* This is written as a self calling function so I don't have to place
* 'use strict' in global scope.
* This prevents problems when concatenating scripts that are not strict.
*/
(function () {
'use strict';
var tl = require('vsts-task-lib');
var util = require('./util.js');
/*
* This file bootstraps the code that does the real work. Using this technique
* makes testing very easy.
*/
// Contains the code for this task. It is put in a separate module to make
// testing the code easier.
var task = require('./task.js');
// Get the parameter values and cache them
let appSlug = tl.getInput('appSlug', true);
util.debug("Getting endpoint details...");
let apiEndpointData = util.getMobileCenterEndpointDetails('serverEndpoint');
let apiToken = apiEndpointData.authToken;
let apiServer = apiEndpointData.apiServer;
let apiVersion = apiEndpointData.apiVersion;
let userAgent = tl.getVariable('MSDEPLOY_HTTP_USER_AGENT');
if (!userAgent) {
userAgent = 'VSTS';
}
userAgent = userAgent + ' (Task:VSMobileCenterBuild)';
// Call the task
task.run(apiServer, appSlug, apiToken, userAgent, apiVersion);
}()); |
import axios from "axios";
import { handleUserRepos, handleUserCommits } from "../redux/actions";
export const fetchReposUser = (user, dispatch) => {
axios
.get(`https://api.github.com/users/${user}/repos`)
.then(response => dispatch(handleUserRepos(response.data)))
.catch(error => console.warn(error));
};
export const fetchUserCommits = (location, dispatch) => {
axios
.get(`https://api.github.com/repos${location}`)
.then(response => dispatch(handleUserCommits(response.data)))
.catch(error => console.warn(error));
};
|
const sequelize = require('sequelize');
const model = require('../../config/model');
const photo = model.define('fiesta_purchase', {
link : { type : sequelize.TEXT, allowNull : false }
});
module.exports = photo;
|
angular.module('Hotel.User', ['Hotel.Common']);
|
const readFile = require('../helpers/readFile');
const input = readFile();
let sum = 0;
const calculateFuelFor = input => {
console.log("calculate fuel for ", input)
const fuel = Math.floor(input / 3) - 2;
console.log('fuel required: ', fuel)
if (fuel < 0) {
console.log("can't have negative fuel ", fuel, ", returning 0 instead")
return 0;
}
return fuel + calculateFuelFor(fuel);
}
const lines = input.split('\n');
for (let line of lines) {
const mass = parseInt(line);
sum += calculateFuelFor(mass);
}
console.log(sum) |
import { Permissions } from "expo";
import React from "react";
import {
StyleSheet,
FlatList,
Dimensions,
CameraRoll,
Image,
TouchableHighlight,
View,
ViewPagerAndroid,
BackHandler
} from "react-native";
export default class App extends React.Component {
state = {
images: [],
isPhotoFullScreen: false,
selectedImage: null,
access: false
};
componentDidMount() {
Permissions.askAsync(Permissions.CAMERA_ROLL)
.then(res => {
console.log("Access: " + res.status);
return CameraRoll.getPhotos({
first: 1000,
assetType: "Photos"
})
.then(r => {
this.setState({ images: r.edges });
})
.catch(err => {
console.log(err);
});
})
.catch(res => console.log("Access: " + res.status));
BackHandler.addEventListener("hardwareBackPress", () => {
if (this.state.isPhotoFullScreen) {
this.onClose();
return true;
}
});
}
onOpen = index => {
this.setState({
isPhotoFullScreen: true,
selectedImage: index
});
};
onClose = () =>
this.setState({ isPhotoFullScreen: false, selectedImage: null });
render() {
return (
<>
{this.state.isPhotoFullScreen ? (
<ViewPagerAndroid
style={styles.background}
initialPage={this.state.selectedImage}
pageMargin={20}
>
{this.state.images.map((item, i) => (
<View key={i}>
<TouchableHighlight
style={styles.container}
onPress={this.onClose}
>
<Image
style={styles.fullSreen}
resizeMode="contain"
source={{ uri: item.node.image.uri }}
/>
</TouchableHighlight>
</View>
))}
</ViewPagerAndroid>
) : (
<FlatList
data={this.state.images}
keyExtractor={(item, i) => i}
style={styles.container}
renderItem={({ item, index }) => (
<TouchableHighlight
style={styles.item}
onPress={() => this.onOpen(index)}
>
<View>
<Image
style={styles.item}
source={{ uri: item.node.image.uri }}
/>
</View>
</TouchableHighlight>
)}
numColumns={3}
/>
)}
</>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
item: {
marginBottom: 1,
marginRight: 1,
height: Dimensions.get("window").width / 3,
width: Dimensions.get("window").width / 3
},
background: {
backgroundColor: "black",
flex: 1
},
fullSreen: {
flex: 1,
height: undefined,
width: undefined
}
});
|
/**
* 自定义modal浮层
* 使用方法:
* <modal show="{{showModal}}" height='60%' bindcancel="modalCancel" bindconfirm='modalConfirm'>
<view>你自己需要展示的内容</view>
</modal>
属性说明:
show: 控制modal显示与隐藏
height:modal的高度
bindcancel:点击取消按钮的回调函数
bindconfirm:点击确定按钮的回调函数
使用模块:
场馆 -> 发布 -> 选择使用物品
*/
Component({
options:{
multipleSlots:true
},
/**
* 组件的属性列表
*/
properties: {
//是否显示modal
show: {
type: Boolean,
value: false,
},
//modal的高度
height: {
type: String,
value: '80%'
},
confirmText:{
type:String,
value:'确定'
},
cancelText:{
type:String,
value:'取消'
}
},
observers:{
cancelText(val){
console.log(val)
}
},
/**
* 组件的初始数据
*/
data: {
animationData: {}
},
ready(){
let animation = wx.createAnimation(
// { duration: 1000,}
)
animation.opacity(0)
this.setData({
animationData:animation.export()
})
},
/**
* 组件的方法列表
*/
methods: {
clickMask() {
// this.setData({show: false})
},
cancel() {
this.triggerEvent('cancel')
},
confirm() {
this.triggerEvent('confirm')
}
}
}) |
import * as actions from './index';
describe('getHouses', () => {
it('should return an action of type GET_HOUSES', () => {
const expected = { type: 'GET_HOUSES' };
expect(actions.getHouses()).toEqual(expected);
});
});
describe('getHousesSuccess', () => {
it('should return an action of type GET_HOUSES_SUCCESS', () => {
const houses = [{ house: 'white' }];
const expected = { type: 'GET_HOUSES_SUCCESS', houses };
expect(actions.getHousesSuccess(houses)).toEqual(expected);
});
});
describe('captureErrorMessage', () => {
it('should return an action of type CAPTURE_ERROR_MESSAGE', () => {
const errorMessage = 'error';
const expected = { type: 'CAPTURE_ERROR_MESSAGE', errorMessage };
expect(actions.captureErrorMessage(errorMessage)).toEqual(expected);
});
});
describe('getMembers', () => {
it('should return an action of type GET_MEMBERS', () => {
const expected = { type: 'GET_MEMBERS' };
expect(actions.getMembers()).toEqual(expected);
});
});
describe('getMembersSuccess', () => {
it('should return an action of type GET_MEMBERS_SUCCESS', () => {
const house = { name: 'white', members: [] };
const expected = { type: 'GET_MEMBERS_SUCCESS', house };
expect(actions.getMembersSuccess(house)).toEqual(expected);
});
});
describe('addMembersDisplay', () => {
it('should return an action of type DISPLAY_MEMBERS', () => {
const houseName = 'white';
const expected = { type: 'DISPLAY_MEMBERS', houseName };
expect(actions.addMembersDisplay(houseName)).toEqual(expected);
});
});
describe('removeMembersDisplay', () => {
it('should return an action of type REMOVE_MEMBERS', () => {
const houseName = 'white';
const expected = { type: 'REMOVE_MEMBERS', houseName };
expect(actions.removeMembersDisplay(houseName)).toEqual(expected);
});
}); |
(function() {
'use strict';
angular.module('app.entidades.controller', [])
.controller('EntidadesCreateCtrl', EntidadesCreateCtrl)
.controller('EntidadesListCtrl', EntidadesListCtrl)
.controller('EntidadesUpdateCtrl', EntidadesUpdateCtrl);
EntidadesCreateCtrl.$inject = ['$location', '$mdToast', 'Entidades'];
function EntidadesCreateCtrl($location, $mdToast, Entidades) {
var vm = this;
vm.create = create;
function create() {
Entidades.save(vm.entidad, function() {
$location.path('/entidades/list');
$mdToast.show(
$mdToast.simple()
.textContent('Registro exitoso')
.position('bottom right'));
}, function(error) {
$mdToast.show(
$mdToast.simple()
.textContent(error.status + ' ' + error.data)
.position('bottom right'));
});
}
}
EntidadesListCtrl.$inject = ['$location', 'Entidades'];
function EntidadesListCtrl($location, Entidades) {
var vm = this;
vm.query = {
order: 'name',
limit: 5,
page: 1
};
vm.entidades = Entidades.query();
}
EntidadesUpdateCtrl.$inject = ['$stateParams', '$location', '$mdToast',
'Entidades'
];
function EntidadesUpdateCtrl($stateParams, $location, $mdToast, Entidades) {
this.id = $stateParams.idEntidad;
this.entidad = Entidades.get({
id: this.id
});
this.update = function() {
Entidades.update({
id: this.entidad.idEntidad
}, this.entidad, function() { //ESTA ES LA FORMA CUANDO LA LLAVE PRIMARIA NO ES AI.
$location.path('/entidades/list');
$mdToast.show(
$mdToast.simple()
.textContent('Se ha actualizado La Entidad')
.position('bottom right'));
});
};
}
})();
|
pay = {
student_id: 301,
experience_id: 2,
slug: 'inicio',
value: true,
//value_num: algun numero
}
//send2api(pay)
var webpage = "http://192.168.0.24:8000/api/metric/post/";
function send2api(payload){
var data = new FormData();
data.append( 'json', JSON.stringify( payload ) );
fetch("http://192.168.0.24:8000/api/metric/post/",
//fetch("http://localhost:8000/api/metric/post/",
{
method: "POST",
body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ console.log("metric sent") })
}
/*************************
VARIABLES
*************************/
// Valores posibles de seleccion
//var velocidades = [18, 12, 6] //velocidades iniciales disponibles
var velocidades = [18] //velocidades iniciales disponibles
var angulos = [30,45,60] //angulos disponibles
var angulos_h = [-1,0,1] //angulos disponibles
var respuestas = []
var cant_respuestas = 8
// para click en cannon
var v_o = 18;
var cannon_angle = 0; // angulo horizontal
var gamma = 30; // angulo vertical
var distanciaTarget;
var yTarget=0;
var xTarget=0;
var gravity = 9.8;
var launching_ball = false; //true: bola es lanzada
//var video = document.querySelector("#tutorial");
//var playTV = document.querySelector("#playTV");
var indicadorcoordenadas = document.querySelector('#indicadorcoordenadas');
var alfa1= document.querySelector("#alfa1");
var alfa2= document.querySelector("#alfa2");
var alfa3= document.querySelector("#alfa3");
var textoPizarraEnBlanco = document.querySelector('#textoPizarraEnBlanco');
var textoPizarra30grados = document.querySelector("#textoPizarra30grados");
var textoPizarra45grados = document.querySelector("#textoPizarra45grados");
var textoPizarra60grados = document.querySelector("#textoPizarra60grados");
var offset_z = 4; //offset de calculos de targets respecto a punto de lanzamiento
var offset_y = 0;
var target0 = document.querySelector('#target0');
var orange = document.querySelector('#orange');
var shoot = document.querySelector(".cannon");
var cannonL1 = document.querySelector("#cannonL1");
var cannonL2 = document.querySelector("#cannonL2");
var cannonL3 = document.querySelector("#cannonL3");
var cannon1 = document.querySelector("#cannon1");
var cannon2 = document.querySelector("#cannon2");
var cannon3 = document.querySelector("#cannon3");
var cannons = document.querySelector("#cannons");
var start = document.querySelector('#start');
//Botones para posicion horizontal de cañon
var angle_1 = document.querySelector('#v1');
var angle0 = document.querySelector('#v2');
var angle1 = document.querySelector('#v3');
// Tutorial - Tooltips
/*STEPS:
0: Usuario inicia experiencia, tiene que apretar emprezar
1: Usuario ya apreto "Empezar"
2: Debe cambiar posicion horizontar par de veces
3: Debe cambiar angulo par de veces
4: Lanza la pelota
5: Debe acertar a un blanco
*/
class Hint {
constructor() {
this.btn_tooltips = document.querySelector('#btn_tooltips');
this.hint_rectangle = document.querySelector("#hint_rectangle");
this.dom = document.querySelector("#hints");
this.active = false;
this.step = 0;
//tengo q cambiar angulo horizontal 2 veces
this.pos_count = 3;
this.angle_count = 3;
this.changeHintText("Hola, bienvenido a la experiencia N°2 de umVRal. Para comenzar, aprieta el botón 'empezar'.");
}
reset() {
this.step = 1;
this.active = false;
this.change_temp = 0;
//tengo q cambiar angulo horizontal 2 veces
this.pos_count = 3;
this.angle_count = 3;
}
changeHintText(text) {
this.dom.setAttribute('text', {'value': text})
}
change_funct() {
let that = this;
if((that.change_temp < 2) && that.active) { that.change_temp++; }
else {
that.changeHintText('Bien!. Continua experimentando en la experiencia, y aprende con nostoros! LH.', that.dom);
that.fade_out();
}
}
//start es equivalente a toStep2()
start(){
let that = this;
if (that.step === 1 && that.pos_count > 0){
that.changeHintText("La experiencia comienza!. Prueba cambiando la posición del cañon "+that.pos_count+" veces en el panel a tu derecha.");
//that.pos_count--;
that.step = 2;
}
}
toStep3(){
let that = this;
if (that.step === 2){
that.changeHintText('Prueba ahora cambiando el angulo del cañon '+that.angle_count+' veces');
that.step = 3;
}
}
change_position() {
let that = this;
//if (that.step === 1 && that.pos_count > 0){
if (that.step === 2){
that.pos_count--;
that.changeHintText("La experiencia comienza!. Prueba cambiando la posición del cañon "+that.pos_count+" veces en el panel a tu derecha.");
if (that.pos_count <= 0){
that.toStep3();
}
}
}
change_angle() {
let that = this;
if (that.step === 3 && that.angle_count > 0){
that.angle_count--;
that.changeHintText('Prueba ahora cambiando el angulo del cañon '+that.angle_count+' veces');
if (that.angle_count <= 0){
that.toStep4();
}
}
}
toStep4(){
let that = this;
if (that.step === 3){
that.changeHintText('Bien!. Ahora llego la hora de lanzar proyectil. Ajusta coordenadas de cañon, y miralo para lanzar proyectil. Apunta a un Blanco.');
that.step = 4;
}
}
launch() {
let that = this;
if (that.step === 4){
that.changeHintText('Bien!. Ahora llego la hora de lanzar proyectil. Ajusta coordenadas de cañon, y miralo para lanzar proyectil. Apunta a un Blanco.');
that.step++;
}
}
target() {
let that = this;
if (that.step === 4 || that.step === 5){
that.changeHintText('Ya tienes tu primer acierto!. Ahora, impacta unos 2 blancos más para poder completar la experiencia');
that.step++;
setTimeout(function(){
that.hint_rectangle.setAttribute('animation',"property: slice9.opacity; dir: alternate; dur: 1000; easing: easeInSine; loop: false; to: 0");
that.dom.setAttribute('animation',"property: text.opacity; dir: alternate; dur: 1000; easing: easeInSine; loop: false; to: 0");
setTimeout(function(){
that.hint_rectangle.setAttribute('visible', false);
that.dom.setAttribute('visible', false);
},1000);
}, 4000);
}
}
fade_out() {
let that = this;
this.active = false;
setTimeout(function(){
that.hint_rectangle.setAttribute('animation',"property: slice9.opacity; dir: alternate; dur: 1000; easing: easeInSine; loop: false; to: 0");
that.dom.setAttribute('animation',"property: text.opacity; dir: alternate; dur: 1000; easing: easeInSine; loop: false; to: 0");
setTimeout(function(){
that.hint_rectangle.setAttribute('visible', 'false');
that.dom.setAttribute('visible', 'false');
}, 1000);
}, 1000);
};
fade_in() {
let that = this;
//that.reset();
that.active = true;
that.dom.setAttribute('visible', true);
setTimeout(function(){
that.hint_rectangle.setAttribute('animation',"property: slice9.opacity; dir: alternate; dur: 1000; easing: easeInSine; loop: false; to: 0.7");
that.dom.setAttribute('animation',"property: text.opacity; dir: alternate; dur: 1000; easing: easeInSine; loop: false; to: 0.8");
//that.step = 1;
}, 500);
}
}
hints = new Hint();
var comenzo=false;
//Generar las respuestas de la experiencia
generateAnswers();
nextTarget();
/*************************
FUNCIONES DE EVENTOS
**************************/
hints.btn_tooltips.addEventListener('click', function(){
hints.fade_in();
if (hints.step === 1) { hints.start() };
pay = {
student_id: 301,
experience_id: 2,
slug: 'tutorial',
value: true,
//value_num: algun numero
}
send2api(pay);
})
start.addEventListener('click', function(){
hints.step = 1;
hints.start()
nextTarget();
//TODO : Tengo que ver el problema si el usuario apreta empezar antes,
// Para saltar el paso
comenzo = true;
target0.setAttribute('visible', 'true');
start.setAttribute('visible', 'false');
indicadorcoordenadas.setAttribute('visible','true');
});
cannon1.addEventListener('click', function(){
orange.setAttribute('material','color: orange; shader: flat');
cannonL1.setAttribute('visible', 'true');
cannonL2.setAttribute('visible', 'false');
cannonL3.setAttribute('visible', 'false');
});
cannon2.addEventListener('click', function(){
orange.setAttribute('material','color: black; shader: flat');
cannonL1.setAttribute('visible', 'false');
cannonL2.setAttribute('visible', 'true');
cannonL3.setAttribute('visible', 'false');
});
cannon3.addEventListener('click', function(){
orange.setAttribute('material','color: blue; shader: flat');
cannonL1.setAttribute('visible', 'false');
cannonL2.setAttribute('visible', 'false');
cannonL3.setAttribute('visible', 'true');
});
alfa1.addEventListener('click', function(){
textoPizarraEnBlanco.setAttribute('visible','false');
textoPizarra45grados.setAttribute('visible','false');
textoPizarra60grados.setAttribute('visible','false');
textoPizarra30grados.setAttribute('visible','true');
gamma=30;
// cambio en angulo del cañon
cannonL1.object3D.rotation.x = degToRad(90+gamma);
cannonL2.object3D.rotation.x = degToRad(90+gamma);
cannonL3.object3D.rotation.x = degToRad(90+gamma);
// cambio de angulo bala
if(comenzo){
document.querySelector("#coordenadastarget").setAttribute('value','coordenadas ( x='+xTarget+'[m] ,y='+yTarget+'[m] ) \n Velocidad disparo= 18[m/s]');
}
});
alfa2.addEventListener('click', function(){
textoPizarraEnBlanco.setAttribute('visible','false');
textoPizarra45grados.setAttribute('visible','true');
textoPizarra60grados.setAttribute('visible','false');
textoPizarra30grados.setAttribute('visible','false');
gamma=45;
// cambio en angulo del cañon
cannonL1.object3D.rotation.x = degToRad(90+gamma);
cannonL2.object3D.rotation.x = degToRad(90+gamma);
cannonL3.object3D.rotation.x = degToRad(90+gamma);
//
if(comenzo){
document.querySelector("#coordenadastarget").setAttribute('value','coordenadas ( x='+xTarget+'[m] ,y='+yTarget+'[m] ) \n Velocidad disparo= 18[m/s]');
}
});
alfa3.addEventListener('click', function(){
textoPizarraEnBlanco.setAttribute('visible','false');
textoPizarra45grados.setAttribute('visible','false');
textoPizarra60grados.setAttribute('visible','true');
textoPizarra30grados.setAttribute('visible','false');
gamma=60;
// cambio en angulo del cañon
cannonL1.object3D.rotation.x = degToRad(90+gamma);
cannonL2.object3D.rotation.x = degToRad(90+gamma);
cannonL3.object3D.rotation.x = degToRad(90+gamma);
// cambio de angulo bala
if(comenzo){
document.querySelector("#coordenadastarget").setAttribute('value','coordenadas ( x='+xTarget+'[m] ,y='+yTarget+'[m] ) \n Velocidad disparo= 18[m/s]');
}
});
var alfa1panel= document.querySelector("#h1");
var alfa2panel= document.querySelector("#h2");
var alfa3panel= document.querySelector("#h3");
alfa1panel.addEventListener('click', function(){
textoPizarraEnBlanco.setAttribute('visible','false');
textoPizarra45grados.setAttribute('visible','false');
textoPizarra60grados.setAttribute('visible','false');
textoPizarra30grados.setAttribute('visible','true');
gamma=30;
hints.change_angle();
// cambio en angulo del cañon
cannonL1.object3D.rotation.x = degToRad(90+gamma);
cannonL2.object3D.rotation.x = degToRad(90+gamma);
cannonL3.object3D.rotation.x = degToRad(90+gamma);
// cambio de angulo bala
if(comenzo){
document.querySelector("#coordenadastarget").setAttribute('value','coordenadas ( x='+xTarget+'[m] ,y='+yTarget+'[m] ) \n Velocidad disparo= 18[m/s]');
}
});
alfa2panel.addEventListener('click', function(){
textoPizarraEnBlanco.setAttribute('visible','false');
textoPizarra45grados.setAttribute('visible','true');
textoPizarra60grados.setAttribute('visible','false');
textoPizarra30grados.setAttribute('visible','false');
gamma=45;
hints.change_angle();
// cambio en angulo del cañon
cannonL1.object3D.rotation.x = degToRad(90+gamma);
cannonL2.object3D.rotation.x = degToRad(90+gamma);
cannonL3.object3D.rotation.x = degToRad(90+gamma);
// cambio de angulo bala
if(comenzo){
document.querySelector("#coordenadastarget").setAttribute('value','coordenadas ( x='+xTarget+'[m] ,y='+yTarget+'[m] ) \n Velocidad disparo= 18[m/s]');
}
});
alfa3panel.addEventListener('click', function(){
textoPizarraEnBlanco.setAttribute('visible','false');
textoPizarra45grados.setAttribute('visible','false');
textoPizarra60grados.setAttribute('visible','true');
textoPizarra30grados.setAttribute('visible','false');
gamma=60;
hints.change_angle();
// cambio en angulo del cañon
cannonL1.object3D.rotation.x = degToRad(90+gamma);
cannonL2.object3D.rotation.x = degToRad(90+gamma);
cannonL3.object3D.rotation.x = degToRad(90+gamma);
// cambio de angulo bala
if(comenzo){
document.querySelector("#coordenadastarget").setAttribute('value','coordenadas ( x='+xTarget+'[m] ,y='+yTarget+'[m] ) \n Velocidad disparo= 18[m/s]');
}
});
/*
playTV.addEventListener('click',function(){
video.play();
playTV.setAttribute('visible','false');
});
video.addEventListener('ended',myHandler,false);
function myHandler(e) {
playTV.setAttribute('visible','true');
}
*/
/* Lanzamiento de Bala */
cannons.addEventListener('click', function(){
if (launching_ball === false || orange.body.position < -1 || orange.body.position.y < 0.8) {
launching_ball = true;
hints.launch();
pay = {
student_id: 301,
experience_id: 2,
slug: 'disparo',
value: true,
//value_num: algun numero
}
send2api(pay);
//Reset de velocidades de la Bala
orange.body.angularVelocity.set(0,0,0);
orange.body.quaternion.set(0,0,0,1);
orange.body.position.set(0, 1.5, -4.5);
velocity = getVelocity(v_o , gamma, cannon_angle)
orange.body.velocity.set(velocity[0], velocity[1], -velocity[2]);
}
});
shoot.addEventListener('click', function(){
if (launching_ball === false || orange.body.position < -1 || orange.body.position.y < 0.8) {
launching_ball = true;
//Reset de velocidades de la Bala
hints.launch();
pay = {
student_id: 301,
experience_id: 2,
slug: 'disparo',
value: true,
//value_num: algun numero
}
send2api(pay);
orange.body.angularVelocity.set(0,0,0);
orange.body.quaternion.set(0,0,0,1);
orange.body.position.set(0, 1.5, -4.5);
velocity = getVelocity(v_o , gamma, cannon_angle)
orange.body.velocity.set(velocity[0], velocity[1], -velocity[2]);
}
});
/* Evento de colision de Raycaster de Bala con Target/Plano */
/* Funcion que se lanza, cuando la bala tiene una colision con un
target o el suelo, para poder reiniciar el disparo
* Variables Offset: sirven cuando el cañon tinee que moverse de posicion, ya
que se asume que el cañon debiese estar en 0.0
*/
orange.addEventListener('raycaster-intersection', function (e) {
launching_ball = false;
if (e.detail.els[0].getAttribute('id') === 'plano'){
orange.body.velocity.set(0, 0, 0);
orange.body.position.set(0, -4, -4.5);
}
else if (e.detail.els[0].getAttribute('id') === 'target0'){
hints.target();
pay = {
student_id: 301,
experience_id: 2,
slug: 'acierto',
value: true,
//value_num: algun numero
}
send2api(pay)
orange.body.velocity.set(0, 0, 0);
orange.body.position.set(0, -4, -4.5);
nextTarget();
}
// OJO: Este if, fija la respuesta para cierto angulo. Si el target tiene dos respuestas,
// entonces no funcionaria, y habria que hacer colisiones con dos versiones
/*
if (parseInt(e.detail.els[0].getAttribute('angle')) == gamma){
}
*/
});
/* Click, para cambiar el cañon de posicion horizontal */
angle_1.addEventListener('click', function(){
changeCanonPosition(-1);
});
angle0.addEventListener('click', function(){
changeCanonPosition(0);
});
angle1.addEventListener('click', function(){
changeCanonPosition(1);
});
/**************************
FUNCIONES DE SOPORTE
**************************/
// Crear posicion no random para los targets
/*
* angle : Angulo horizontal
* v_o : Velocidad inicial del arreglo
* gamma : Angulo vertical del cañon
*/
function targetPos(angle, v_o, gamma){
if (angle === -1) {
position = getTargetPosition(v_o, gamma, -1) //Obtener posicion random para el target
target0.object3D.position.set(position[0],position[1]+offset_y,-(position[2]+offset_z));
target0.object3D.rotation.y = degToRad(20);
}
else if (angle === 1){
position = getTargetPosition(v_o, gamma, 1) //Obtener posicion random para el target
target0.object3D.position.set(position[0],position[1]+offset_y,-(position[2]+offset_z));
target0.object3D.rotation.y = degToRad(-20);
}
else {
position = getTargetPosition(v_o, gamma, 0) //Obtener posicion random para el target
target0.object3D.position.set(0,position[1]+offset_y,-(position[2]+offset_z));
target0.object3D.rotation.y = degToRad(0);
}
}
/* generateAnswers*/
/* Genera las respuestas al inicio de la experiencia, que el estudiante
tiene que responder para poder completar la experiencia
- formato respuesta: [velocidad, angulo_vert, angulo_hor]*/
function generateAnswers(){
for(i=0; i<cant_respuestas; i++){
var aux = {};
aux.vel = velocidades[getRandNumber(velocidades.length)];
aux.vertangl = angulos[getRandNumber(angulos.length)];
aux.horangl = angulos_h[getRandNumber(angulos_h.length)];
respuestas.push(aux);
}
}
/* nextTarget */
/* Saca de la pila de targets a ser apuntados el próximo target */
function nextTarget(){
if(respuestas.length >= 1){
let t = respuestas.pop();
targetPos(t.horangl, t.vel, t.vertangl);
}
else {
target0.setAttribute("visible",false);
indicadorcoordenadas.setAttribute('value','Experiencia Finalizada!');
}
return true;
}
/* getRandNumber*/
/* Devuelve un numero random, de 0 a limit */
function getRandNumber(limit){
return Math.floor(Math.random()*limit);
}
/* Obtener velocidad de la Bala, en el lanzamiento */
function getVelocity(v_o, theta, angulo) {
theta = degToRad(theta)
v_x = 0
v_z = v_o * Math.cos(theta)
if (angulo === +1){
v_x = v_z * Math.cos(70)
v_z = v_z * Math.sin(70)
}
else if (angulo === -1){
v_x = -v_z * Math.cos(70)
v_z = v_z * Math.sin(70)
}
v_y = v_o * Math.sin(theta)
return [v_x, v_y, v_z]
}
/* Obtener posición próxima de un Target */
/*
Obtiene posicion random de un target
input:
v_o: Veloicdad inicial correcta
theta: Angulo correcto de respuesta
grad: Grado Horizontal
*/
function getTargetPosition(v_o, theta, grad) {
theta = degToRad(theta)
v_y = v_o * Math.sin(theta);
v_x = v_o * Math.cos(theta);
time_max = (2 * v_y)/gravity;
interval = (time_max - 0.3 )/ 7;
//Se añade un tiempo pequeño, para que target no aparesca en el mismo lugar
//que el cañon
rand = Math.floor(Math.random()*8)
time = (rand*interval)+0.3;
p_y = (v_y * time) - 0.5*gravity*Math.pow(time, 2);
p_x = 0;
p_z = v_x * time;
if (grad === -1){
p_x = (-p_z * Math.cos(70));
p_z = (p_z * Math.sin(70));
}
else if (grad === 1){
p_x = (p_z * Math.cos(70));
p_z = (p_z * Math.sin(70));
}
yTarget=Math.floor((p_y+1)*100)/100;
xTarget=Math.floor(Math.sqrt(p_x*p_x + p_z*p_z)*100)/100;
indicadorcoordenadas.setAttribute('value','( '+xTarget+'[m] , '+yTarget+'[m] )');
return [p_x, p_y+1, p_z];
}
/* Cambiar Grados por Radianes. Requerida por THREE.JS */
function degToRad(deg){
return deg * Math.PI / 180;
}
grad20 = degToRad(20);
function changeCanonPosition(angle) {
hints.change_position();
if (angle === -1){
cannonL1.object3D.rotation.y = grad20;
cannonL2.object3D.rotation.y = grad20;
cannonL3.object3D.rotation.y = grad20;
cannon_angle = -1;
}
else if (angle === 1){
cannonL1.object3D.rotation.y = -grad20;
cannonL2.object3D.rotation.y = -grad20;
cannonL3.object3D.rotation.y = -grad20;
cannon_angle = 1;
}
else{
cannonL1.object3D.rotation.y = 0;
cannonL2.object3D.rotation.y = 0;
cannonL3.object3D.rotation.y = 0;
cannon_angle = 0;
}
}
|
var express = require('express');
var router = express.Router();
var ruleEngineCon=require('../../connections/mysqlRuleEngineDbCon.js')
router.get('/getAllErrors:dtls', (req, res) => {
try{
var objectToSend={}
var ent_cd=req.params.dtls;
var query="Select * from error_info where ent_cd = '"+ent_cd+"'";
ruleEngineCon.query(query,function(error,results){
if(error){
console.log("Error-->routes-->reject_handling-->errorInfo-->getAllErrors--",error)
objectToSend["error"]=true
objectToSend["data"]="Can't fetch error info at the moment.Please try again later. If problem persists call support"
res.send(objectToSend);
}else{
objectToSend["error"]=false
objectToSend["data"]=results;
res.send(objectToSend);
}
})
}catch(ex){
console.log("Error-->routes-->reject_handling-->errorInfo-->getAllErrors--",ex)
objectToSend["error"]=true
objectToSend["data"]="Can't fetch error info at the moment.Please try again later. If problem persists call support"
res.send(objectToSend);
}
});
router.post('/ignoreError', (req, res) => {
try{
var objectToSend={}
var error_id=req.body.error_id;
var query="delete from error_info where error_id='"+error_id+"'";
ruleEngineCon.query(query,function(error,results){
if(error){
console.log("Error-->routes-->reject_handling-->errorInfo-->ignoreError--",error)
objectToSend["error"]=true
objectToSend["data"]="Can't ignore this error at the moment.Please try again later. If problem persists call support"
res.send(objectToSend);
}else{
objectToSend["error"]=false
objectToSend["data"]="Error Ignored";
res.send(objectToSend);
}
})
}catch(ex){
console.log("Error-->routes-->reject_handling-->errorInfo-->ignoreError--",ex)
objectToSend["error"]=true
objectToSend["data"]="Can't ignore this error at the moment.Please try again later. If problem persists call support"
res.send(objectToSend);
}
});
module.exports = router;
|
(function(){
"use strict";
window.App = Ember.Application.create();
/* model + REST 일 때 prefix 주기 위해 사용 */
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://localhost:10001',
namespace: 'catalog'
});
})(); |
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as ActionCreators from '../../../actions/index';
import AddButton from './add_button';
import EditButton from './edit_button';
import FormModal from './form_modal';
import ConfirmModal from './confirm_modal';
const mapStateToProps = function (state) {
let tableItems = state.wards.map(function(ward) {
let numWardAccounts = state.wardAccounts.filter(wardAccount => {
return ward.id == wardAccount.wardId;
}).length;
return Object.assign({}, ward, {
numWardAccounts: numWardAccounts
});
});
return {
tableItems: tableItems,
wardFocus: state.ui.wardFocus,
formModal: state.ui.formModal,
formValues: state.modalForm.formValues,
channel: state.session.socket ? state.session.socket.channels[0] : undefined
};
};
const mapDispatchToProps = function (dispatch) {
return bindActionCreators(ActionCreators, dispatch);
};
class WardList extends Component {
deleteWard(id) {
this.props.channel.push('delete_ward', {
id: id
});
}
renderResult(ward, key) {
if (this.props.wardFocus == ward.id) {
return (
<tr className="selected" key={key}>
<ConfirmModal
name={'wardList' + ward.id}
body={'Are you sure you want to delete ' + ward.name + '?'}
proceed={() => this.deleteWard(ward.id)}
cancel={() => this.props.closeConfirmModal()}
/>
<td className="text-link" onClick={() => this.props.clearWardFocus()}>{ward.name}</td>
<td className="text-link" onClick={() => this.props.clearWardFocus()}>{ward.numWardAccounts}</td>
<td>
<EditButton
name="editWard"
btnText="Edit"
values={ward}
/>
<button className="btn btn-xs btn-danger" onClick={() => this.props.openConfirmModal('wardList' + ward.id)}>Delete</button>
</td>
</tr>
);
} else {
return (
<tr key={key}>
<ConfirmModal
name={'wardList' + ward.id}
body={'Are you sure you want to delete ' + ward.name + '?'}
proceed={() => this.deleteWard(ward.id)}
cancel={() => this.props.closeConfirmModal()}
/>
<td className="text-link" onClick={() => this.props.setWardFocus(ward.id)}>{ward.name}</td>
<td className="text-link" onClick={() => this.props.setWardFocus(ward.id)}>{ward.numWardAccounts}</td>
<td>
<EditButton
name="editWard"
btnText="Edit"
values={ward}
/>
<button className="btn btn-xs btn-danger" onClick={() => this.props.openConfirmModal('wardList' + ward.id)}>Delete</button>
</td>
</tr>
);
}
}
renderResults() {
if (this.props.tableItems.length != 0) {
return this.props.tableItems.map(this.renderResult.bind(this));
} else {
return (
<tr>
<td colSpan="3"><i>No results</i></td>
</tr>
);
}
}
submitForm(values) {
this.props.clearFormErrors();
let valid = true;
if (!values || !values.name) {
this.props.addFormError('name', 'Cannot be blank');
valid = false;
}
if (!values || !values.relationship) {
this.props.addFormError('relationship', 'Cannot be blank');
valid = false;
}
if (valid) {
switch (this.props.formModal) {
case 'addWard':
this.props.channel.push('create_ward', {ward_params: {
name: values.name,
relationship: values.relationship,
active: values.active || true
}});
break;
case 'editWard':
this.props.channel.push('update_ward', {id: this.props.formValues.id, updated_params: {
name: values.name,
relationship: values.relationship,
active: values.active
}});
break;
default:
console.log('No valid form open, nothing saved');
}
this.props.closeFormModal();
}
}
render() {
return(
<div>
<FormModal
name="addWard"
onSubmit={this.submitForm.bind(this)}
inputs={[
{type: 'text', name: 'name', text: 'Name', focus: true},
{type: 'text', name: 'relationship', text: 'Relationship'},
{type: 'select', name: 'active', text: 'Active', selectObjects: [{text: 'yes', value: true}, {text: 'no', value: false}]}
]}
title="Add Ward"
instructions="Enter a name and a relationship (optional) for your new ward. The name should be unique and does not need to be a handle for a specific social media account. Relationship should reflect the ward's relationship to you. Select if this ward is active or not."
/>
<FormModal
name="editWard"
onSubmit={this.submitForm.bind(this)}
inputs={[
{type: 'text', name: 'name', text: 'Name', focus: true},
{type: 'text', name: 'relationship', text: 'Relationship'},
{type: 'select', name: 'active', text: 'Active', selectObjects: [{text: 'yes', value: true}, {text: 'no', value: false}]}
]}
title="Edit Ward"
instructions="Edit the name and relationship (optional) for this ward. The name should be unique and does not need to be a handle for a specific social media account. Relationship should reflect the ward's relationship to you. Select if this ward is active or not."
/>
<table className="table table-hover">
<thead>
<tr>
<th>Name</th>
<th># Accts</th>
<th>Options</th>
</tr>
</thead>
<tbody>
{this.renderResults()}
</tbody>
</table>
<div className="pull-right">
<AddButton
name="addWard"
btnText="Add Ward..."
/>
</div>
<br />
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(WardList);
|
const Movie = require('../models/movie');
const BadRequestError = require('../errors/bad-request-err');
const NotFoundError = require('../errors/not-found-err');
const ForbiddenError = require('../errors/forbidden-err');
// получение всех сохранённых пользователем фильмов
const getFavoritesMovies = (req, res, next) => {
const owner = req.user._id;
Movie.find({ owner }).select('+owner')
.then((movies) => res.send(movies))
.catch(next);
};
// добавление фильма в избранное
const addMovieToFavorites = (req, res, next) => {
const {
country, director, duration, year,
description, image, trailer, thumbnail,
movieId,
nameRU, nameEN,
} = req.body;
const owner = req.user._id;
Movie.create({
country,
director,
duration,
year,
description,
image,
trailer,
thumbnail,
movieId,
nameRU,
nameEN,
owner,
})
.then((movie) => res.send({ data: movie }))
.catch((err) => {
if (err.name === 'ValidationError') {
next(new BadRequestError('Переданы некорректные данные при создании фильма'));
} else {
next(err);
}
});
};
// удаление сохранённого фильма по ID
const deleteMovieById = (req, res, next) => {
const { _id } = req.params;
const userId = req.user._id;
Movie.findById(_id)
.select('+owner')
.orFail(new NotFoundError('Фильм с заданным ID не найден'))
.then((movie) => {
if (movie.owner.toString() !== userId) {
return next(new ForbiddenError('Нельзя удалить чужой фильм'));
}
return Movie.findByIdAndRemove(_id)
.select('-owner')
.then(() => res.send({ message: 'Фильм успешно удалён' }));
})
.catch((err) => {
if (err.kind === 'ObjectId') {
next(new BadRequestError('Невалидный ID фильма'));
} else {
next(err);
}
});
};
module.exports = {
getFavoritesMovies, addMovieToFavorites, deleteMovieById,
};
|
'use strict';
var assign = require('object-assign');
var co = require('co');
function empty() { return null; }
function UseExtension(view) {
this.tags = ['use'];
this.view = view;
}
// 修改lookup方法,让use tag的变量查找首先查data对象
function generateLookup(data, lookup) {
return function(key) {
if (data.hasOwnProperty(key)) {
return data[key];
}
return lookup.apply(this, arguments);
};
}
assign(UseExtension.prototype, {
parse: function(parser, nodes) {
var tok = parser.nextToken();
var args = new nodes.NodeList(tok.lineno, tok.colno);
var schema = parser.parseExpression();
args.addChild(schema);
if (parser.skipSymbol('as')) {
var name = parser.parseExpression();
var nameTok = new nodes.Literal(name.lineno, name.colno, name.value);
args.addChild(nameTok);
}
parser.advanceAfterBlockEnd(tok.value);
var body = parser.parseUntilBlocks('enduse');
parser.advanceAfterBlockEnd();
var method = this.view.async ? 'CallExtensionAsync' : 'CallExtension';
return new nodes[method](this, 'run', args, [body]);
},
run: function(context, url, alias, body, callback) {
// if there is no `use 'xx' as alias` express
if (typeof alias === 'function') {
callback = body;
body = alias;
alias = undefined;
}
var use = this.view.use || empty;
var self = this;
if (this.view.async && callback) {
co(use(url))
.then(function(data) {
var ret = self._run(context, url, body, data);
callback(null, ret);
})
.catch(callback);
return null;
}
var ctx = use(url);
if (ctx === null) {
return body();
}
return this._run(context, url, body, ctx, alias);
},
_run: function(context, url, body, ctx, alias) {
var frame = this.view.frame;
var lookup = context.lookup;
var frameLookup = frame.lookup;
var wrap = this.view.useWrap;
// 如果获得了数据,首先把context备份
var ret;
// 对于数据,循环执行body函数
if (Array.isArray(ctx) && !alias) {
var loop = { length: ctx.length, first: true, last: false };
ret = ctx.map(function(data, i) {
loop.index = i + 1;
loop.index0 = i;
if (i) { loop.first = false; }
if (i === loop.length - 1) { loop.last = true; }
// 修改context上下文数据
var _data = assign({}, data, { loop: loop });
context.lookup = generateLookup(_data, lookup);
frame.lookup = generateLookup(_data, frameLookup);
return body();
}).join('');
} else {
// use 'a.schema' as alias,
// change ctx data
if (alias) {
var _ctx = ctx;
ctx = {};
ctx[alias] = _ctx;
}
context.lookup = generateLookup(ctx, lookup);
frame.lookup = generateLookup(ctx, frameLookup);
ret = body();
}
// 恢复原来的备份数据
context.lookup = lookup;
frame.lookup = frameLookup;
if (typeof wrap === 'function') {
return wrap(url, ret, alias);
}
return ret;
}
});
module.exports = UseExtension;
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const AdminNotificationSchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
sectionId: {
type: Schema.Types.ObjectId,
ref: 'Section',
required: true
},
showed: {
type: Boolean,
default: false
},
notify: {
type: Schema.Types.ObjectId,
required: true
},
review: {
type: Boolean,
default: false
}
});
const AdminNotification = mongoose.model('AdminNotification', AdminNotificationSchema);
module.exports = AdminNotification; |
import React from 'react';
import PropTypes from 'prop-types';
import style from '../PhoneBook/PhoneBook.module.css';
const Filter = ({ value, onChangeFilter }) => {
return (
<div className={style.form}>
<p>Find contact by name</p>
<input
type="text"
placeholder="Find"
value={value}
onChange={e => onChangeFilter(e.target.value)}
/>
</div>
);
};
Filter.propTypes = {
value: PropTypes.string.isRequired,
onChangeFilter: PropTypes.func.isRequired,
};
export default Filter;
|
import knex from '../config/db';
import { hash } from 'bcryptjs';
class Colaborador {
constructor(nome, bi, photoBi, photoAvatar, idCurso) {
this.nome = nome;
this.bi = bi;
this.idCurso = idCurso;
this.photoAvatar = photoAvatar;
this.photoBi = photoBi;
this.nivelSession = 3;
this.palavraPasse = bi;
}
async save() {
this.palavraPasse = await this.criptPassword();
let dados = await knex.insert(this).into('coordenador');
return dados;
}
criptPassword () {
if(this.palavraPasse){
console.log(this.palavraPasse);
return hash(this.palavraPasse, 8);
}
}
static async showDate() {
let dados = await knex.select().into('coordenador');
return dados;
}
static async show(id) {
let dado = await knex.select().into('coordenador').whereRaw(`id = "${id}"`);
return dado;
}
static async update(id, dado) {
return knex.whereRaw(`id = "${id}"`).update(dado).table('coordenador');
}
static async delete(id) {
return knex.whereRaw(`id = ${1}`).delete().table('coordenador');
}
}
export default Colaborador;
|
import { createSlice } from "@reduxjs/toolkit";
const login = createSlice({
name: "login",
initialState: { name: "", email: "" },
reducers: {
addUser: (state, action) => {
state.name = action.payload.name;
},
updateUser: (state, action) => {
state.name = action.payload;
},
verifyEmail: (state, action) => {
state.email = action.payload;
},
},
});
const { reducer, actions } = login;
export const { addUser, updateUser, verifyEmail } = actions;
export default reducer;
|
const person = {
nome: 'Rob',
surname: 'Soares',
age: 19,
address: {
street: 'Av. Edmilson Rodrigues Marcelino',
number: 44
}
};
// Atribuição via desestruturação
const {nome, surname, ...rest} = person;
console.log(nome, rest);
/*
const {address: {street, number}, address} = person;
console.log(street, number, address); */ |
var Stark = function (name) { this.name = name }
Stark.prototype.Attack = function () { console.log(`使用拳頭攻擊`) }
//IronMan 其實就是TS 版本的class,同時也是裝飾器,裝飾史塔克這個物件
var IronMan = function (stark) { this.stark = stark }
IronMan.prototype.Attack =function (){console.log(`使用空氣砲攻擊`)};
IronMan.prototype.AutoMissile=function (){console.log(`使用自動瞄準飛彈射擊`)};
var HulkBuster = function (stark) { this.stark = stark }
HulkBuster.prototype.Attack = function (){console.log(`對浩克打出強力一擊`)};
var stark = new Stark('東尼史塔克')
stark.Attack();
iron = new IronMan(stark);
iron.Attack();
iron.AutoMissile();
buster = new HulkBuster(iron);
buster.Attack();
|
var images = new Array();
$(document).ready(function() {
loadGallery();
});
function runGallery() {
if (images[0]) {
$("#gallery").fadeOut(500);
setTimeout(
function() {
$("#gallery").html('<img src="' + images[0] + '" />').fadeIn(500);
images.splice(0,1);
setTimeout("runGallery()", 5000);
}, 500);
}
else {
loadGallery();
}
}
function loadGallery() {
$.get(
UrlBuilder.buildUrl(false, "home", "getimage"),
function (data) {
images = data;
runGallery();
},
'json');
} |
'use strict';
/*
* WORKFLOW: MISUNDERSTOOD
* Functions for handling the case when the bot doesn't understand the user's input.
*/
/*
* Sends a message to the user explaining that the bot doesn't know what they meant.
*/
async function sendMisunderstoodMessage (recUser, message) {
const sharedLogger = this.__dep(`sharedLogger`);
// Skip if the bot has been disabled for this user.
if (this.skipIfBotDisabled(`send misunderstood message`, recUser)) {
return false;
}
// Last ditch attempt to match the user's input.
if (this.options.enableNlp) {
const matchedCommand = await this.__findMatchingCommandByIntent(message.text, false);
if (matchedCommand) {
await this.__executeCommand(matchedCommand, message, recUser);
return true;
}
}
if (this.options.misunderstoodFlowUri) {
await this.executeFlow(this.options.misunderstoodFlowUri, recUser, message);
return true;
}
else if (this.options.misunderstoodText) {
// Send the misunderstood text.
const MessageObject = this.__dep(`MessageObject`);
const misunderstoodMessage = MessageObject.outgoing(recUser, {
text: this.options.misunderstoodText,
options: this.options.misunderstoodOptions,
});
await this.sendMessage(recUser, misunderstoodMessage);
// Misunderstood message sent.
return true;
}
else { // We failed to match any commands AND there's no misunderstood text so we just ignore this situation.
sharedLogger.verbose(`The misunderstood text is not configured so we won't send anything to the user.`);
return false;
}
}
/*
* Export.
*/
module.exports = {
sendMisunderstoodMessage,
};
|
var request = require('supertest-as-promised');
var rs = require('randomstring');
var chai = require('chai');
var should = chai.should();
var expect = chai.expect;
var _ = require('lodash');
describe('UserController', function() {
var randomUser = {
"firstName": rs.generate(10),
"lastName": rs.generate(10),
"email": 'mariomoro@icanplay.co.uk',
"password": "p4$$w0Rd"
};
var token = '';
// SIGN UP TEST UNITS
describe('POST /user/signup', function() {
it('can register a new user', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send(randomUser)
.expect(200)
.then(function(res) {
expect('Sent verification link to the specified email account').to.be.ok;
done();
})
.catch(done);
});
it('cannot register the same user twice', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send(randomUser)
.expect(409)
.then(function(res) {
expect('Email address is already taken by another user, please try again.'
|| 'Username is already taken by another user, please try again.').to.be.ok;
done();
})
.catch(done);
});
/* it('cannot register a user with an existing username', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send({firstName: rs.generate(10),
lastName: rs.generate(10),
userName: randomUser.userName,
email: 'kakotamix@yahoo.es',
password: 'p4SSw0Rd'
})
.expect(409)
.then(function(res){
expect('Username is already taken by another user, please try again.').to.be.ok;
done();
})
.catch(done);
});*/
it('cannot register a user with an existing email', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send({firstName: rs.generate(10),
lastName: rs.generate(10),
userName: rs.generate(10),
email: 'mariomoro@icanplay.co.uk',
password: 'p4SSw0Rd'
})
.expect(409)
.then(function(res){
expect('Email address is already taken by another user, please try again.').to.be.ok;
done();
})
.catch(done);
});
it('cannot register a user without first name', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send({lastName: rs.generate(10),
email: 'mariomoro@icanplay.co.uk',
password: 'p4SSw0Rd'
})
.expect(400)
.then(function(res){
expect('A first name is required').to.be.ok;
done();
})
.catch(done);
});
it('cannot register a user without last name', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send({firstName: rs.generate(10),
email: 'mariomoro@icanplay.co.uk',
password: 'p4SSw0Rd'
})
.expect(400)
.then(function(res){
expect('A last name is required').to.be.ok;
done();
})
.catch(done);
});
/* it('cannot register a user without user name', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send({firstName: rs.generate(10),
lastName: randomUser.userName,
email: 'mariomoro@icanplay.co.uk',
password: 'p4SSw0Rd'
})
.expect(400)
.then(function(res){
expect('A user name is required').to.be.ok;
done();
})
.catch(done);
});
it('cannot register a user whose user name has other characters than numbers or letters', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send({firstName: rs.generate(10),
lastName: rs.generate(10),
userName: 'u$3R_n4|\/|£',
email: 'mariomoro@icanplay.co.uk',
password: 'p4SSw0Rd'
})
.expect(400)
.then(function(res){
expect('Invalid username: must consist of numbers and letters only').to.be.ok;
done();
})
.catch(done);
}); */
it('cannot register a user without email', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send({firstName: rs.generate(10),
lastName: rs.generate(10),
password: 'p4SSw0Rd'
})
.expect(400)
.then(function(res){
expect('An email is required').to.be.ok;
done();
})
.catch(done);
});
it('cannot register a user without a valid email address (as defined by RFC 5322)', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send({firstName: rs.generate(10),
lastName: rs.generate(10),
email: 'mariomoro@icanplay',
password: 'p4SSw0Rd'
})
.expect(400)
.then(function(res){
expect('Invalid email').to.be.ok;
done();
})
.catch(done);
});
it('cannot register a user without a password', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send({firstName: rs.generate(10),
lastName: rs.generate(10),
email: 'mariomoro@icanplay.co.uk'
})
.expect(400)
.then(function(res){
expect('A password is required').to.be.ok;
done();
})
.catch(done);
});
it('cannot register a user without a password at least 6 characters long', function (done) {
request(sails.hooks.http.app)
.post('/user/signup')
.send({firstName: rs.generate(10),
lastName: rs.generate(10),
email: 'mariomoro@icanplay.co.uk',
password: 'p4SS'
})
.expect(400)
.then(function(res){
expect('Password must be at least 6 characters').to.be.ok;
done();
})
.catch(done);
});
});
// LOG IN TEST UNITS
describe('POST /login/', function() {
it('cannot log in a user without email', function (done) {
request(sails.hooks.http.app)
.post('/login/')
.send({password: randomUser.password})
.expect(400)
.then(function(res) {
expect('The request was malformed').to.be.ok;
done();
})
.catch(done);
});
it('cannot log in a user without password', function (done) {
request(sails.hooks.http.app)
.post('/login/')
.send({userName: randomUser.userName})
.expect(400)
.then(function(res) {
expect('The request was malformed').to.be.ok;
done();
})
.catch(done);
});
it('cannot log in an unknown user', function (done) {
request(sails.hooks.http.app)
.post('/login/')
.send({email: 'unknownUser@nodomain.no',
password: '123456'})
.expect(404)
.then(function(res) {
expect('The email you entered is unknown.').to.be.ok;
done();
})
.catch(done);
});
it('cannot log in a known user but with wrong password', function (done) {
request(sails.hooks.http.app)
.post('/login/')
.send({email: 'verified@piltrafilla.es',
password: 'W4t73V£r'})
.expect(404)
.then(function(res) {
expect('The password you entered is wrong.').to.be.ok;
done();
})
.catch(done);
});
it('cannot log in a soft-deleted user', function (done) {
request(sails.hooks.http.app)
.post('/login/')
.send({email: 'softdeleted@piltrafilla.es',
password: '123456'})
.expect(403)
.then(function(res) {
expect('Your account has been deleted. Please restore your account.').to.be.ok;
done();
})
.catch(done);
});
it('cannot log in a banned user', function (done) {
request(sails.hooks.http.app)
.post('/login/')
.send({email: 'banned@piltrafilla.es',
password: '123456'})
.expect(403)
.then(function(res) {
expect('Your account has been banned.').to.be.ok;
done();
})
.catch(done);
});
it('cannot log in a signed-up but not-verified user', function (done) {
request(sails.hooks.http.app)
.post('/login/')
.send({email: 'nonverified@piltrafilla.es',
password: '123456'})
.expect(403)
.then(function(res) {
expect('Your account is not verified').to.be.ok;
done();
})
.catch(done);
});
it('can log in a registered and verified user', function (done) {
request(sails.hooks.http.app)
.post('/login/')
.send({email: 'verified@piltrafilla.es',
password: '123456'})
.expect(200)
.then(function(res) {
token = res.body.token;
expect(res.body.token).to.be.ok;
expect(res.body.user).to.be.ok;
done();
})
.catch(done);
});
});
// LOG OUT TEST UNITS
describe('GET /logout/', function() {
it('can log out a logged in user', function (done) {
request(sails.hooks.http.app)
.get('/logout/')
.send({})
.expect(302)
.then(function(res) {
expect('/').to.be.ok;
// If logged out the call /user/profile must return 403 forbidden
request(sails.hooks.http.app)
.get('/user/profile')
.expect(403)
.then(function (res) {
expect('You are not permitted to perform this action.');
done();
})
.catch(done);
})
.catch(done);
});
});
});
/*
describe('PUT /user/login', function(){
it('can successfully login user', function(done){
var user;
User.create({
"firstName": rs.generate(10),
"lastName": rs.generate(10),
"userName": rs.generate(10),
"email": 'mariomoro@icanplay.co.uk',
"password": "p4$$w0Rd"
}).then(function(_user){
var user = _user;
request(sails.hooks.http.app)
.put('/user/login/')
.send({
userName: user.userName,
password: user.password
})
.expect(200)
.then(function(res) {
expect(res.session.userId).to.be.ok;
done();
})
.catch(done);
});
});
});
describe('PUT /user/remove-profile', function() {
it('can successfully set user.deleted to false', function (done) {
var user;
User.create({
"firstName": rs.generate(10),
"lastName": rs.generate(10),
"userName": rs.generate(10),
"password": "p4$$w0Rd"
}).then(function (_user) {
var user = _user;
request(sails.hooks.http.app)
.delete('/user/remove-profile/')
.expect(200)
.then(function (res) {
var data = res.body;
expect(data[0].deleted).to.be.ok;
done();
}).catch(done);
});
});
});
*/
/*describe('DELETE /user/:id', function(){
it('can sucessuflly set user as banned', function(done){
var user;
User.create({
"firstName": rs.generate(10),
"lastName": rs.generate(10),
"userName": rs.generate(10),
"password": "p4$$w0Rd"
}).then(function(_user){
var user = _user;
request(sails.hooks.http.app)
.delete('/user/'+user.id)
.expect(200)
.then(function(res) {
var data = res.body;
expect(data[0].deleted).to.be.ok;
done();
})
.catch(done);
});
});
});*/
//});
|
define([
'apps/system2/docsetting/docsetting',
'apps/system2/docsetting/docsetting.service'], function (app) {
app.module.controller("docsetting.controller.file.op", function ($state,$scope, docsettingService, $uibModal) {
});
});
|
// key = 리액트에서 key는 컴포넌트 배열을 렌더링 했을 때
// 어떤 원소에 변동이 있었는지 알아내려고 사용합니다.
// key 값을 설정할 때는 map 함수의 인자로 전달되는 함수 내부에서
// 컴포넌트 props를 설정하듯이 설정하시면 됩니다.
// key 값은 언제나 유일해야 합니다. 따라서 데이터가 가진 고유값을
// key 값으로 설정해야 합니다.
// 그런데, 앞서 예문에서는 컴포넌트에 고유 번호 식별 key 설정이
// 되어 있지 않았습니다. 그러면, 이번에는 map 함수에 전달되는
// 콜백 함수의 인수인 index 값을 사용해 보겠습니다.
import React from 'react';
const IterationSample = () => {
// 문자열로 구성된 배열을 선언합니다.
const names = ['눈사람', '얼음', '눈', '바람'];
const nameList = names.map((name, index) => <li key = {index}> {name} </li>);
// 여기서는 고유한 값이 없을 때만 index 값을 key로 사용해야 합니다.
// 왜냐하면 index를 key로 사용하면 배열이 변경될 때 효율적으로
// 리렌더링하지 못하기 때문입니다.
return <ul> {nameList} </ul>;
};
export default IterationSample; |
import React from 'react'
import { Link } from 'gatsby'
export default function SiteLogo() {
return (
<Link className="site-brand d-block mb-5" to="/">
<svg width="99" height="85" fill="none" xmlns="http://www.w3.org/2000/svg" className="pixelHeart-logo">
<title>{`Underlost, By Tyler Rilling`}</title>
<circle className="pixelHeart-circle" cx="25" cy="40" r="25" fill="#0FE" />
<g className="pixelHeart-container">
<path
d="M88.392 18.444h5.9v5.847h-5.9v-5.847ZM76.747 13.6h5.814v5.847h-5.814V13.6Zm0 17.375H70.9v-5.78h-5.814v5.78h-5.714v-5.78h-5.83v5.813h-5.765v5.695l-.169.05h-5.78v-5.745h-5.815v-5.814h-5.83v5.781h-5.76v5.694h-5.715v11.542h5.764v5.85h5.83v5.814h5.764v5.747h5.798v5.814h5.83v-5.834h5.814v-5.744h5.797v-5.797h5.798v-5.85h5.814v5.85h5.863v-5.85H70.9V36.786h5.863v5.78h5.814V36.67h-5.83v-5.61h5.814v-5.864h-5.814v5.78ZM53.438 59.669v.137Zm-17.289.137v-.137ZM70.9 36.669h-5.78v-5.611h5.78v5.611Z"
fill="#000"
/>
<path d="M59.203 59.942h5.884v5.863h-5.884v-5.863Z" fill="#000" />
</g>
</svg>
</Link>
)
}
|
const mongoose = require('mongoose'); //导入数据库模块
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useFindAndModify: false
}); //链接数据库
const type = mongoose.Schema;
const blogtype = new type({
name: {
type: String,
required: true
},
desc: {
type: String,
required: true
}
})
const blog = mongoose.model('blog_data', blogtype);
module.exports = blog; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.