text stringlengths 7 3.69M |
|---|
/**
* Created by gxu on 4/9/17.
*/
'use strict';
angular
.module('defenseApp')
.factory('TestTools', TestTools);
TestTools.$inject = ['Session'];
function TestTools(Session) {
var tools = {};
///////////////////---------------利用率热图模拟数据生成------------------///////////////
var generateHeatMapData = function (startDate, endDate) {
var sd = new Date(startDate);
var ed = new Date(endDate);
console.log("simulate weekly util data");
console.log(sd);
console.log(ed);
var curTime = startDate;
var utiliaztionData = [];
while (curTime - endDate <= 0) {
var curTimeObj = new Date(curTime);
var dayOfWeek = curTimeObj.getDay();
var hourOfDay = curTimeObj.getHours();
var runningPercentile = 0;
if (dayOfWeek == 0 || dayOfWeek == 6) {
runningPercentile = Math.floor(Math.random() * 10 + 5);
} else {
if (hourOfDay >= 0 && hourOfDay < 6) {
runningPercentile = Math.floor(Math.random() * 5 + 10);
} else if (hourOfDay >= 6 && hourOfDay < 8) {
runningPercentile = Math.floor(Math.random() * 10 + 15);
}
else if (hourOfDay >= 7 && hourOfDay < 14) {
runningPercentile = Math.floor(Math.random() * 35 + 30);
} else if (hourOfDay >= 14 && hourOfDay < 20) {
runningPercentile = Math.floor(Math.random() * 25 + 25);
} else {
runningPercentile = Math.floor(Math.random() * 15 + 5);
}
}
//var runningPercentile = Math.floor(Math.random() * (100 - idlePercentile));
// 目前要求无停机时间
var idlePercentile = 100 - runningPercentile;
utiliaztionData.push({
hourlyTime: curTime,
runningPercentile: runningPercentile / 100,
idlePercentile: idlePercentile / 100
});
curTime += 3600 * 1000; // plus 1 hour
}
return utiliaztionData;
};
tools.getUtilizationLatestWeek = function (testCurrTime) {
var todayDate = new Date(testCurrTime.getFullYear(), testCurrTime.getMonth(), testCurrTime.getDate(), 0, 0, 0, 0);
console.log(todayDate);
todayDate = todayDate.getTime();
var oneWeekBeforeToday = todayDate - 7 * 24 * 3600 * 1000;
var yesterdayNight23 = todayDate - 3600 * 1000; // tonight is at 23:00:00pm
var testUtilizationData = generateHeatMapData(oneWeekBeforeToday, yesterdayNight23);
// test data for yesterday
var yesterdayBusyHourValue = 0;
var yesterdayBusyHour = 0;
var yesterdayIdleHourValue = 100;
var yesterdayIdleHour = 0;
var yesterdayTotalHour = 0.0;
var yesterdayOffTimeHours = 0.0;
// 用weeklydata 得出昨日的一些数据, 最高使用时段, 等等
var testOffset = testUtilizationData.length - 1 - 23;
for (var i = 0; i < 24; i++) {
var testHourlyData = testUtilizationData[testOffset + i];
if (testHourlyData.runningPercentile > yesterdayBusyHourValue) {
yesterdayBusyHour = i;
yesterdayBusyHourValue = testHourlyData.runningPercentile;
}
if (testHourlyData.runningPercentile < yesterdayIdleHourValue) {
yesterdayIdleHour = i;
yesterdayIdleHourValue = testHourlyData.runningPercentile;
}
yesterdayTotalHour += testHourlyData.runningPercentile;
if (i < 9 || i > 19) {
yesterdayOffTimeHours += testHourlyData.runningPercentile;
}
}
return {
weeklyUtil: {
succeed: true,
data: {
deviceId: 101,
hourlyUtilizations: testUtilizationData
}
},
yesterdayUtil: {
succeed: true,
data: {
deviceId: 101,
totalRunningHours: yesterdayTotalHour,
powerLowerBound: 4.5,
powerUpperBound: 100.02,
totalConsumedEnergy: 1.1 * 3600 * 1000,
totalIdleHours: 24 - yesterdayTotalHour,
mostOftenUsedHour: yesterdayNight23 - (23 - yesterdayBusyHour) * 3600 * 1000, //3pm
leastOftenUsedHour: yesterdayNight23 - (23 - yesterdayIdleHour) * 3600 * 1000, //3am
offTimeHours: yesterdayOffTimeHours
}
}
};
};
var deviceInspectList = [
{
correctionValue: -29.7719,
end: "57.0",
highDown: -35,
highUp: -10,
id: 299,
inspectPurpose: 0,
lowAlter: 10,
lowDown: -33,
lowUp: -15,
name: "温度(PT100)",
originalValue: -29.7719,
standard: -24,
start: "-93.0",
value: "25.0",
zero: 0,
inspectType: {
code: "00",
id: 1,
name: "温度(PT100)",
unit: "度"
}
},
{
correctionValue: 2,
end: "1.0",
highDown: 5,
highUp: 5,
id: 300,
inspectPurpose: 0,
inspectType: {
code: "05",
id: 8,
name: "设备门状态",
unit: "开/关"
},
lowAlter: 10,
lowDown: 1.5,
lowUp: 1.5,
name: "设备门状态",
originalValue: 2,
standard: 1,
start: "1.0",
value: "0.0",
zero: 0
},
{
correctionValue: 0.062,
end: "3.3",
highDown: 0,
highUp: 1,
id: 303,
inspectPurpose: 1,
lowAlter: 10,
lowDown: 0,
lowUp: 0.8,
name: "电流",
originalValue: 0.062,
standard: 0.3,
start: "-2.7",
value: "1.0",
zero: 0,
inspectType: {
code: "0b",
id: 13,
name: "电流",
unit: "A"
},
runningStatus: [
{
deviceInspectId: 303,
deviceRunningStatus: {
id: 1,
description: "",
level: 0,
name: "poweroff"
},
id: 1,
threshold: 0
},
{
deviceInspectId: 303,
deviceRunningStatus: {
id: 2,
description: "",
level: 10,
name: "standby"
},
id: 2,
threshold: 0.01
},
{
deviceInspectId: 303,
deviceRunningStatus: {
id: 3,
description: "",
level: 20,
name: "running"
},
id: 3,
threshold: 0.3
}
]
},
{
correctionValue: 73.5,
end: "365.0",
highDown: 0,
highUp: 120,
id: 304,
inspectPurpose: 0,
inspectType: {
code: "0c",
id: 14,
name: "有功功率",
unit: "W"
},
lowAlter: 10,
lowDown: 0,
lowUp: 115,
name: "有功功率",
originalValue: 73.5,
standard: 5,
start: "-355.5",
value: "120.0",
zero: 0
}
];
// ------------------------- 设备详情页 监控数据 生成------------
var deviceSample = {
alterNum: 0,
code: "fk-冰箱",
photo: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/217/a1e6ebcc-7180-4040-bda1-e6167dc4830d",
createDate: 1488967935000,
creator: "iLabService",
deviceInspects: deviceInspectList,
deviceType: {
id: 138,
logo: "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/138/142f0018-ef0f-43e0-baf2-4f2ababec1c6",
name: "冰箱",
type: false
},
monitorDevice: {
battery: '59.9',
id: 113,
number: "086021060342000027",
online: 0
},
manager: {
bindEmail: 1,
bindMobile: 1,
companyId: "AM",
companyLogo: "https://ilsgxuresource.blob.core.windows.net/company60/company/4e16ef24-e842-425e-a269-3178a36a5440",
companyName: "ilabservice",
createDate: 1489072884000,
department: "运营",
email: "zy.li@ilabservice.com",
id: 136,
job: "管理员",
jobNum: "000",
mobile: "15900751966",
name: "ils",
password: "123",
removeAlert: "2",
role: {
authority: "FIRM_MANAGER",
id: 148,
roleAuthority: {
id: 3,
name: "FIRM_MANAGER"
}
},
roleNames: "企业管理员 ",
userName: "ils",
},
days: 27,
enable: 1,
id: 217,
name: "低温冰箱",
maintain: "180",
model: "iLabService",
purchase: 1488700800000,
pushInterval: 30,
pushType: "禁止推送",
roomName: "科海大楼7层iLabService",
roomId: 232,
score: "47.5",
xpoint: 400,
ypoint: 140
};
var generateInspectData = function (beginTime, count) {
var data = [];
deviceInspectList.forEach(function (inspect) {
var inspectData = [];
for (var i = 0; i < count; i++) {
var picResult = "";
var realValue = "";
var result = "";
if (inspect.id == 300) {
// 设备门
picResult = "2";
realValue = "2000";
result = "关";
}
else if (inspect.id == 303) {
picResult = (Math.random() * (inspect.lowUp - inspect.standard) * 0.2 + inspect.standard).toFixed(2).toString();
realValue = picResult;
result = picResult + "A";
} else if (inspect.id == 304) {
var mid = (inspect.lowUp + inspect.lowDown) / 2;
picResult = (Math.random() * (inspect.lowUp - mid) * 0.2 + mid).toFixed(2).toString();
realValue = picResult;
result = picResult + "W";
} else if (inspect.id == 299) {
picResult = (Math.random() * (inspect.lowUp - inspect.standard) * 0.2 + inspect.standard).toFixed(2).toString();
realValue = picResult;
result = picResult + "度";
}
var monitorTime = beginTime + i * 30 * 1000;
if (monitorTime > Date.now()) {
monitorTime = Date.now();
}
inspectData.push({
createDate: monitorTime,
deviceInspect: inspect,
judge: 0,
picResult: picResult,
realValue: realValue,
result: result
});
}
inspectData.reverse();
data.push(inspectData);
});
return data;
};
tools.getDeviceInspectDataSample = function (beginTime) {
var curTime = new Date();
var count = Math.ceil((curTime.getTime() - beginTime) / 30 / 1000);
console.log("new data " + count);
return {
runningStatus: 20,
score: 20.2,
list: generateInspectData(beginTime, count)
};
};
// ----------------------------------------测试 数据----------------------------
var companyInfoSample = {
address: "上海纳贤路800号",
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/0beb2f42-5719-4f3c-b594-24da14c966c5",
companyId: "AM",
createDate: 1488652660000,
email: "zy.li@ilabservice.com",
enable: 1,
highAlert: 0,
id: 59,
lat: 31.1894,
lng: 121.611,
location: "121.611,31.1894",
login: "http://ilabservice.chinaeast.cloudapp.chinacloudapi.cn/Lab_login.html?company=AM",
logo: "https://ilsgxuresource.blob.core.windows.net/company60/company/4e16ef24-e842-425e-a269-3178a36a5440",
lowAlert: 0,
name: "ilabservice",
offline: 5,
online: 0,
score: 30.8444,
total: 5
};
var user_firm_manager = {
bindEmail: 1,
bindMobile: 1,
companyId: "AM",
companyLogo: "https://ilsgxuresource.blob.core.windows.net/company60/company/4e16ef24-e842-425e-a269-3178a36a5440",
companyName: "ilabservice",
createDate: 1489072884000,
department: "运营",
email: "zy.li@ilabservice.com",
id: 136,
job: "管理员",
jobNum: "000",
mobile: "15900751966",
name: "ils",
password: "123",
removeAlert: "2",
role: {
authority: "FIRM_MANAGER",
id: 148,
roleAuthority: {
id: 3,
name: "FIRM_MANAGER"
}
},
roleNames: "企业管理员 ",
userName: "ils",
verify: "6012"
};
var user_service_manager = {
department: "ilabservice",
email: "gxu@ilabservice.com",
id: 1,
job: "系统管理员",
jobNum: "000",
mobile: "15900751966",
name: "intelab",
password: "123456",
role: {
authority: "SERVICE_MANAGER",
id: 148,
roleAuthority: {
id: 1,
name: "SERVICE_MANAGER"
}
},
roleNames: "系统管理员 ",
userName: "intelab"
};
var deviceScientistsSample = [
{
companyId: "AM",
companyLogo: 'https://ilsgxuresource.blob.core.windows.net/company60/company/4e16ef24-e842-425e-a269-3178a36a5440',
companyName: "ilabservice",
createDate: 1489072884000,
department: "devops",
email: "gxu@ilabservice.com",
id: 153,
job: "devlead",
jobNum: "1234",
mobile: "13258198510",
name: "tobyxu",
password: "123",
removeAlert: "0",
role: {
authority: "FIRM_WORKER",
id: 165,
roleAuthority: {
id: 4,
name: "FIRM_WORKER"
}
},
roleNames: "企业业务员 试验品管理员 ",
userName: "Toby"
},
{
companyId: "AM",
companyLogo: 'https://ilsgxuresource.blob.core.windows.net/company60/company/4e16ef24-e842-425e-a269-3178a36a5440',
companyName: "ilabservice",
createDate: 1489072884000,
department: "研发",
id: 137,
job: "devlead",
jobNum: "1234",
mobile: "13258198510",
name: "k.li",
password: "ilabservice123",
removeAlert: "0",
role: {
authority: "FIRM_SCIENTIST",
id: 149,
roleAuthority: {
id: 5,
name: "FIRM_SCIENTIST"
}
},
roleNames: "试验品管理员 ",
userName: "李康"
}
];
var deviceManagersSample = [
{
bindEmail: 1,
bindMobile: 1,
companyId: "AM",
companyLogo: 'https://ilsgxuresource.blob.core.windows.net/company60/company/4e16ef24-e842-425e-a269-3178a36a5440',
companyName: "ilabservice",
createDate: 1489072884000,
department: "运营",
email: "zy.li@ilabservice.com",
id: 136,
job: "管理员",
jobNum: "000",
mobile: "15900751966",
name: "ils",
password: "123",
removeAlert: "2",
role: {
authority: "FIRM_MANAGER",
id: 148,
roleAuthority: {
id: 3,
name: "FIRM_MANAGER"
}
},
roleNames: "企业管理员 ",
userName: "ils",
verify: "6012"
}
];
var runningStatusSample = [
{
description: "",
id: 1,
level: 0,
localizedName: "停机",
name: "poweroff"
},
{
description: "",
id: 2,
level: 10,
localizedName: "待机",
name: "standby"
},
{
description: "",
id: 3,
level: 20,
localizedName: "运行",
name: "running"
}
];
var deviceParametersSample = {
id: 214,
name: "all",
list: [
{
chosed: true,
highDown: "0.0",
highUp: "40.0",
id: 1,
inspectPurpose: 0,
lowDown: "0.0",
lowUp: "30.0",
name: "温度(PT100)",
standard: "20.0"
},
{
chosed: true,
highDown: "5.0",
highUp: "5.0",
id: 8,
inspectPurpose: 0,
lowDown: "0.0",
lowUp: "0.0",
name: "设备门状态",
standard: "1.0"
},
{
chosed: true,
highDown: "0.0",
highUp: "60.0",
id: 13,
inspectPurpose: 1,
lowDown: "0.0",
lowUp: "60.0",
name: "电流",
runningStatus: [
{
deviceTypeInspectId: 303,
id: 1,
description: "",
level: 0,
name: "poweroff",
runningStatusId: 1,
threshold: 0
},
{
deviceTypeInspectId: 303,
id: 2,
description: "",
level: 10,
name: "standby",
runningStatusId: 2,
threshold: 0.01
},
{
deviceTypeInspectId: 303,
id: 3,
description: "",
level: 20,
name: "poweroff",
runningStatusId: 3,
threshold: 0.3
}
],
standard: "20.0"
},
{
chosed: true,
highDown: "0.0",
highUp: "120.0",
id: 14,
inspectPurpose: 0,
lowDown: "0.0",
lowUp: "115.0",
name: "有功功率",
standard: "5.0"
}
]
};
var roomListSample = [
{
error: 0,
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/rooms/232/bde85aa9-1cf9-4366-87ce-fc96ecd18507",
days: 30,
buildId: 1,
buildName: "科海大楼",
floorId: 1,
floorName: "1-1floor",
highAlert: 0,
id: 1,
lowAlert: 1,
name: "1-1-1room",
offline: 2,
online: 1,
score: 23.2333,
total: 3,
roomId: 1,
deviceList: [
{
alterNum: 0,
code: "001",
photo: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/215/ffd64b95-56cc-4def-8615-745c2aa1c985",
createDate: 1488713590000,
creator: "iLabService",
deviceInspects: [],
deviceType: {
id: 126,
logo: "https://tobypictures.blob.core.windows.net/devicetypes/126/35b518b0-8f32-4eb1-b7e3-2c65f4809a31",
name: "温度+ 门+压差+电表",
type: false
},
monitorDevice: {
battery: '97.3',
id: 1,
number: "086021060342000041",
online: 0
},
days: 29,
enable: 1,
highAlert: 0,
id: 1,
name: "INTELAB演示1",
maintain: "365",
model: "iLabService",
purchase: 1488700800000,
pushInterval: 30,
pushType: "禁止推送",
roomName: "1-1-1room",
score: "0",
xpoint: 270,
ypoint: 160
},
{
alterNum: 0,
code: "002",
photo: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/216/b36de11c-d42d-47f2-a678-32f080263d9a",
createDate: 1488713590000,
creator: "iLabService",
deviceInspects: [],
deviceType: {
id: 127,
logo: "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/127/f38c124a-af01-4659-8747-93a94d0b37a8",
name: "温湿度+甲烷+门",
type: false
},
monitorDevice: {
battery: '95.9',
id: 2,
number: "086021060342000018",
online: 0
},
days: 29,
enable: 1,
id: 2,
name: "INTELAB演示2",
maintain: "180",
model: "iLabService",
purchase: 1488700800000,
pushInterval: 30,
pushType: "禁止推送",
roomName: "1-1-1room",
score: "22.2",
xpoint: 270,
ypoint: 160
},
{
alterNum: 0,
code: "003",
photo: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/217/a1e6ebcc-7180-4040-bda1-e6167dc4830d",
createDate: 1488713590000,
creator: "iLabService",
deviceInspects: [],
deviceType: {
id: 128,
logo: "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/128/2edad111-3039-401e-9616-67d6ca47e885",
name: "pt100+温湿度+门",
type: false
},
monitorDevice: {
battery: '59.9',
id: 3,
number: "086021060342000027",
online: 0
},
days: 26,
enable: 1,
id: 3,
name: "INTELAB DEMO 3",
maintain: "180",
model: "iLabService",
purchase: 1488700800000,
pushInterval: 30,
pushType: "邮箱",
roomName: "1-1-1room",
score: "47.5",
xpoint: 400,
ypoint: 140
}
]
},
{
error: 0,
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/rooms/232/bde85aa9-1cf9-4366-87ce-fc96ecd18507",
days: 30,
buildId: 2,
buildName: "Milburn",
floorId: 2,
floorName: "2-1floor",
highAlert: 0,
id: 2,
lowAlert: 1,
name: "2-1-1room",
offline: 1,
online: 1,
score: 23.2333,
total: 2,
roomId: 2,
deviceList: [
{
alterNum: 0,
code: "001",
photo: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/215/ffd64b95-56cc-4def-8615-745c2aa1c985",
createDate: 1488713590000,
creator: "iLabService",
deviceInspects: [],
deviceType: {
id: 126,
logo: "https://tobypictures.blob.core.windows.net/devicetypes/126/35b518b0-8f32-4eb1-b7e3-2c65f4809a31",
name: "温度+ 门+压差+电表",
type: false
},
monitorDevice: {
battery: '97.3',
id: 4,
number: "086021060342000041",
online: 0
},
days: 29,
enable: 1,
highAlert: 0,
id: 4,
name: "INTELAB演示-4",
maintain: "365",
model: "iLabService",
purchase: 1488700800000,
pushInterval: 30,
pushType: "禁止推送",
roomName: "2-1-1room",
score: "0",
xpoint: 770,
ypoint: 260
},
{
alterNum: 0,
code: "002",
photo: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/216/b36de11c-d42d-47f2-a678-32f080263d9a",
createDate: 1488713590000,
creator: "iLabService",
deviceInspects: [],
deviceType: {
id: 127,
logo: "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/127/f38c124a-af01-4659-8747-93a94d0b37a8",
name: "温湿度+甲烷+门",
type: false
},
monitorDevice: {
battery: '95.9',
id: 5,
number: "086021060342000018",
online: 0
},
days: 29,
enable: 1,
id: 5,
name: "INTELAB演示-5",
maintain: "180",
model: "iLabService",
purchase: 1488700800000,
pushInterval: 30,
pushType: "禁止推送",
roomName: "2-1-1room",
score: "22.2",
xpoint: 270,
ypoint: 560
}
]
},
{
error: 0,
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/rooms/232/bde85aa9-1cf9-4366-87ce-fc96ecd18507",
days: 30,
buildId: 2,
buildName: "Milburn",
floorId: 3,
floorName: "2-2floor",
highAlert: 0,
id: 3,
lowAlert: 1,
name: "2-2-1room",
offline: 1,
online: 1,
score: 23.2333,
total: 2,
roomId: 3,
deviceList: [
{
alterNum: 0,
code: "001",
photo: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/215/ffd64b95-56cc-4def-8615-745c2aa1c985",
createDate: 1488713590000,
creator: "iLabService",
deviceInspects: [],
deviceType: {
id: 126,
logo: "https://tobypictures.blob.core.windows.net/devicetypes/126/35b518b0-8f32-4eb1-b7e3-2c65f4809a31",
name: "温度+ 门+压差+电表",
type: false
},
monitorDevice: {
battery: '97.3',
id: 6,
number: "086021060342000041",
online: 0
},
days: 29,
enable: 1,
highAlert: 0,
id: 6,
name: "INTELAB演示-6",
maintain: "365",
model: "iLabService",
purchase: 1488700800000,
pushInterval: 30,
pushType: "禁止推送",
roomName: "2-2-1room",
score: "0",
xpoint: 270,
ypoint: 160
},
{
alterNum: 0,
code: "002",
photo: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/216/b36de11c-d42d-47f2-a678-32f080263d9a",
createDate: 1488713590000,
creator: "iLabService",
deviceInspects: [],
deviceType: {
id: 127,
logo: "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/127/f38c124a-af01-4659-8747-93a94d0b37a8",
name: "温湿度+甲烷+门",
type: false
},
monitorDevice: {
battery: '95.9',
id: 7,
number: "086021060342000018",
online: 0
},
days: 29,
enable: 1,
id: 7,
name: "INTELAB演示-7",
maintain: "180",
model: "iLabService",
purchase: 1488700800000,
pushInterval: 30,
pushType: "禁止推送",
roomName: "2-2-1room",
score: "22.2",
xpoint: 270,
ypoint: 160
}
]
},
{
error: 0,
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/rooms/232/bde85aa9-1cf9-4366-87ce-fc96ecd18507",
days: 30,
buildId: 3,
buildName: "科海大楼",
floorId: 4,
floorName: "3-1floor",
highAlert: 0,
id: 4,
lowAlert: 1,
name: "3-1-1room",
offline: 1,
online: 0,
score: 23.2333,
total: 1,
roomId: 4,
deviceList: [
{
alterNum: 0,
code: "001",
photo: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/215/ffd64b95-56cc-4def-8615-745c2aa1c985",
createDate: 1488713590000,
creator: "iLabService",
deviceInspects: [],
deviceType: {
id: 126,
logo: "https://tobypictures.blob.core.windows.net/devicetypes/126/35b518b0-8f32-4eb1-b7e3-2c65f4809a31",
name: "温度+ 门+压差+电表",
type: false
},
monitorDevice: {
battery: '97.3',
id: 8,
number: "086021060342000041",
online: 0
},
days: 29,
enable: 1,
highAlert: 0,
id: 8,
name: "INTELAB演示-8",
maintain: "365",
model: "iLabService",
purchase: 1488700800000,
pushInterval: 30,
pushType: "禁止推送",
roomName: "3-1-1room",
score: "0",
xpoint: 370,
ypoint: 760
}
]
}
];
var floorListSample = [
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/floors/439/d959481a-78ab-4c7a-91a9-3e7926c70783",
days: 30,
buildId: 1,
buildName: "科海大楼",
floorId: 1,
highAlert: 0,
id: 1,
lowAlert: 0,
name: "1-1floor",
offline: 3,
online: 1,
score: 23.2333,
total: 4,
roomList: [
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/rooms/232/bde85aa9-1cf9-4366-87ce-fc96ecd18507",
createDate: 1488652889000,
days: 30,
deviceNum: 3,
enable: 1,
highAlert: 0,
id: 1,
lowAlert: 1,
name: "1-1-1room",
offline: 2,
online: 1,
score: 23.2333,
total: 3,
xpoint: 500,
ypoint: 300
}
]
},
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/floors/439/d959481a-78ab-4c7a-91a9-3e7926c70783",
days: 30,
buildId: 2,
buildName: "Milburn",
floorId: 2,
highAlert: 0,
id: 2,
lowAlert: 0,
name: "2-1floor",
offline: 1,
online: 0,
score: 23.2333,
total: 1,
roomList: [
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/rooms/232/bde85aa9-1cf9-4366-87ce-fc96ecd18507",
createDate: 1488652889000,
days: 30,
deviceNum: 2,
enable: 1,
highAlert: 0,
id: 2,
lowAlert: 1,
name: "2-1-1room",
offline: 1,
online: 1,
score: 23.2333,
total: 2,
xpoint: 500,
ypoint: 300
}
]
},
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/floors/439/d959481a-78ab-4c7a-91a9-3e7926c70783",
days: 30,
buildId: 2,
buildName: "Milburn",
floorId: 3,
highAlert: 0,
id: 3,
lowAlert: 0,
name: "2-2floor",
offline: 1,
online: 0,
score: 23.2333,
total: 1,
roomList: [
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/rooms/232/bde85aa9-1cf9-4366-87ce-fc96ecd18507",
createDate: 1488652889000,
days: 30,
deviceNum: 2,
enable: 1,
highAlert: 0,
id: 3,
lowAlert: 1,
name: "2-2-1room",
offline: 1,
online: 1,
score: 23.2333,
total: 2,
xpoint: 500,
ypoint: 300
}
]
},
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/floors/439/d959481a-78ab-4c7a-91a9-3e7926c70783",
days: 30,
buildId: 3,
buildName: "碧云公馆",
floorId: 4,
highAlert: 0,
id: 4,
lowAlert: 0,
name: "3-1floor",
offline: 1,
online: 0,
score: 23.2333,
total: 1,
roomList: [
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/rooms/232/bde85aa9-1cf9-4366-87ce-fc96ecd18507",
createDate: 1488652889000,
days: 30,
deviceNum: 1,
enable: 1,
highAlert: 0,
id: 4,
lowAlert: 1,
name: "3-1-1room",
offline: 1,
online: 0,
score: 23.2333,
total: 1,
xpoint: 500,
ypoint: 300
}
]
}
];
var buildingListSample = [
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/buildings/50/0d5f4363-24a5-43e8-a598-bc447fdb6002",
days: 30,
buildId: 1,
highAlert: 2,
id: 1,
lowAlert: 2,
name: "科海大楼",
offline: 2,
online: 1,
score: 23.2333,
total: 3,
floors: [
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/floors/439/d959481a-78ab-4c7a-91a9-3e7926c70783",
createDate: 1488652879000,
days: 30,
deviceNum: 3,
enable: 1,
highAlert: 0,
id: 1,
lowAlert: 1,
name: "1-1floor",
offline: 2,
online: 1,
score: 23.2333,
total: 3,
xpoint: 610,
ypoint: 255
}
]
},
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/buildings/50/0d5f4363-24a5-43e8-a598-bc447fdb6002",
days: 25,
deviceNum: 4,
enable: 1,
highAlert: 1,
id: 2,
buildId: 2,
lowAlert: 0,
name: "Millburn",
offline: 2,
online: 2,
score: 23.95,
total: 4,
floors: [
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/floors/439/d959481a-78ab-4c7a-91a9-3e7926c70783",
createDate: 1488652879000,
days: 30,
deviceNum: 2,
enable: 1,
highAlert: 0,
id: 2,
lowAlert: 1,
name: "2-1floor",
offline: 1,
online: 1,
score: 23.2333,
total: 2,
xpoint: 610,
ypoint: 255
},
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/floors/439/d959481a-78ab-4c7a-91a9-3e7926c70783",
createDate: 1488652879000,
days: 30,
deviceNum: 2,
enable: 1,
highAlert: 0,
id: 3,
lowAlert: 1,
name: "2-2floor",
offline: 1,
online: 1,
score: 23.2333,
total: 2,
xpoint: 210,
ypoint: 555
}
]
},
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/buildings/50/0d5f4363-24a5-43e8-a598-bc447fdb6002",
createDate: 1488652868000,
days: 22,
deviceNum: 1,
enable: 1,
highAlert: 0,
id: 3,
buildId: 3,
lowAlert: 3,
name: "碧云公馆",
offline: 1,
online: 0,
score: 45,
total: 1,
floors: [
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/floors/439/d959481a-78ab-4c7a-91a9-3e7926c70783",
createDate: 1488652879000,
days: 30,
deviceNum: 1,
enable: 1,
highAlert: 0,
id: 4,
lowAlert: 1,
name: "3-1floor",
offline: 1,
online: 0,
score: 23.2333,
total: 1,
xpoint: 710,
ypoint: 555
}
]
}
];
var campusSample = {
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/0beb2f42-5719-4f3c-b594-24da14c966c5",
days: 29,
highAlert: 3,
id: 1,
logo: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
lowAlert: 6,
name: "ilabservice",
offline: 7,
online: 1,
score: 30.8444,
total: 8,
list: [
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/buildings/50/0d5f4363-24a5-43e8-a598-bc447fdb6002",
createDate: 1488652868000,
days: 29,
deviceNum: 3,
enable: 1,
highAlert: 1,
id: 1,
lowAlert: 2,
name: "科海大楼",
offline: 2,
online: 1,
score: 23.2333,
total: 3,
xpoint: 116.491167,
ypoint: 39.877355
},
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/buildings/50/0d5f4363-24a5-43e8-a598-bc447fdb6002",
createDate: 1489028870000,
days: 25,
deviceNum: 4,
enable: 1,
highAlert: 0,
id: 2,
lowAlert: 0,
name: "Millburn",
offline: 2,
online: 2,
score: 23.95,
total: 4,
xpoint: 116.512152,
ypoint: 39.857419
},
{
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/buildings/50/0d5f4363-24a5-43e8-a598-bc447fdb6002",
createDate: 1488652868000,
days: 22,
deviceNum: 1,
enable: 1,
highAlert: 0,
id: 3,
lowAlert: 0,
name: "碧云公馆",
offline: 1,
online: 0,
score: 45,
total: 1,
xpoint: 116.428789,
ypoint: 39.896622
}
]
};
var deleteUserInitSample = [
{
"id": 136,
"name": "ils",
"password": "iLabService@123",
"userName": "ils",
"mobile": "15900751966",
"createDate": 1489044084000,
"email": "k.li@ilabservice.com",
"department": "运营",
"job": "ils",
"jobNum": "000",
"role": {"id": 148, "authority": "FIRM_MANAGER", "roleAuthority": {"id": 3, "name": "FIRM_MANAGER"}},
"companyName": "ilabservice",
"verify": "7106",
"bindMobile": 1,
"bindEmail": 1,
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业管理员 ",
"companyId": "AM",
"removeAlert": "2"
}, {
"id": 138,
"name": "zy.li",
"password": "iLabService@123",
"userName": "栗志云",
"createDate": 1488643943000,
"department": "工程",
"job": "工程师",
"jobNum": "002",
"role": {"id": 150, "authority": "FIRM_WORKER", "roleAuthority": {"id": 4, "name": "FIRM_WORKER"}},
"companyName": "ilabservice",
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业业务员 ",
"companyId": "AM",
"removeAlert": "2"
}, {
"id": 153,
"name": "tobyxu",
"password": "123",
"userName": "Toby",
"createDate": 1491889850000,
"department": "devops",
"job": "devlead",
"jobNum": "1234",
"role": {"id": 165, "authority": "FIRM_WORKER", "roleAuthority": {"id": 4, "name": "FIRM_WORKER"}},
"companyName": "ilabservice",
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业业务员 试验品管理员 ",
"companyId": "AM",
"removeAlert": "2"
}];
var userListSample = {
"total": "4",
"pages": "1",
"userList": {
"userId": 136,
"userList": [{
"id": 143,
"name": "1234",
"password": "123",
"userName": "小芳",
"createDate": 1490607669000,
"department": "测试",
"job": "测试",
"jobNum": "2423",
"role": {
"id": 155,
"authority": "FIRM_WORKER",
"roleAuthority": {"id": 4, "name": "FIRM_WORKER"}
},
"companyName": "ilabservice",
"companyLogo": "https://ilstestresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业业务员 ",
"companyId": "AM",
"removeAlert": "0"
}, {
"id": 140,
"name": "yc.zheng",
"password": "123",
"userName": "郑一村",
"createDate": 1488806529000,
"department": "研发",
"job": "实习生",
"jobNum": "003",
"role": {
"id": 152,
"authority": "FIRM_WORKER",
"roleAuthority": {"id": 4, "name": "FIRM_WORKER"}
},
"companyName": "ilabservice",
"companyLogo": "https://ilstestresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业业务员 ",
"companyId": "AM",
"removeAlert": "0"
}, {
"id": 138,
"name": "zy.li",
"password": "123",
"userName": "栗志云",
"createDate": 1488643943000,
"department": "工程",
"job": "工程师",
"jobNum": "002",
"role": {
"id": 150,
"authority": "FIRM_WORKER",
"roleAuthority": {"id": 4, "name": "FIRM_WORKER"}
},
"companyName": "ilabservice",
"companyLogo": "https://ilstestresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业业务员 ",
"companyId": "AM",
"removeAlert": "0"
}, {
"id": 137,
"name": "k.li",
"password": "123",
"userName": "李康",
"createDate": 1488643917000,
"department": "研发",
"job": "经理",
"jobNum": "001",
"role": {
"id": 149,
"authority": "FIRM_SCIENTIST",
"roleAuthority": {"id": 5, "name": "FIRM_SCIENTIST"}
},
"companyName": "ilabservice",
"companyLogo": "https://ilstestresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "试验品管理员 ",
"companyId": "AM",
"removeAlert": "0"
}]
},
"thisNum": "4"
};
var userCompanySample = {
"error": 0,
"message": "OK",
"data": {
"id": 136,
"name": "ils",
"password": "123",
"userName": "ils",
"mobile": "15900751966",
"createDate": 1489044084000,
"email": "zy.li@ilabtools.com",
"department": "运营",
"job": "管理员",
"jobNum": "000",
"role": {
"id": 148,
"authority": "FIRM_MANAGER",
"roleAuthority": {"id": 3, "name": "FIRM_MANAGER"}
},
"companyName": "ilabservice",
"verify": "6012",
"bindMobile": 1,
"bindEmail": 1,
"companyLogo": "https://ilstestresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业管理员 ",
"companyId": "AM",
"removeAlert": "1"
}
};
var companyUserListSample = [
{
"id": 136,
"name": "ils",
"password": "iLabService@123",
"userName": "ils",
"mobile": "15900751966",
"createDate": 1489044084000,
"email": "k.li@ilabservice.com",
"department": "运营",
"job": "ils",
"jobNum": "000",
"role": {
"id": 148,
"authority": "FIRM_MANAGER",
"roleAuthority": {"id": 3, "name": "FIRM_MANAGER"}
},
"companyName": "ilabservice",
"verify": "7106",
"bindMobile": 1,
"bindEmail": 1,
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业管理员 ",
"companyId": "AM",
"removeAlert": "2"
}, {
"id": 138,
"name": "zy.li",
"password": "iLabService@123",
"userName": "栗志云",
"createDate": 1488643943000,
"department": "工程",
"job": "工程师",
"jobNum": "002",
"role": {
"id": 150,
"authority": "FIRM_WORKER",
"roleAuthority": {"id": 4, "name": "FIRM_WORKER"}
},
"companyName": "ilabservice",
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业业务员 ",
"companyId": "AM",
"removeAlert": "0"
}];
var deviceTypeSample = [
{
"id": 64,
"name": "环境温度",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/64/7607d45c-7a86-41b2-a0b7-77feeb59087d",
"inspectTypes": [{"id": 4, "name": "温湿度(温度)", "code": "04", "unit": "度"}],
"type": true
}, {
"id": 120,
"name": "pt100+开关",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/120/fcdc009a-4d47-4dd5-bb70-b7c6c29c90cd",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 8,
"name": "设备门状态",
"code": "05",
"unit": "开/关"
}],
"type": true
}, {
"id": 125,
"name": "all",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/125/fbcac7c5-6caf-4a7f-ac57-8dfb3bc3ffb5",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 2,
"name": "温湿度(湿度)",
"code": "01",
"unit": "%"
}, {"id": 3, "name": "二氧化碳", "code": "02", "unit": "ppm"}, {
"id": 4,
"name": "温湿度(温度)",
"code": "04",
"unit": "度"
}, {"id": 6, "name": "房间压差", "code": "06", "unit": "pa"}, {
"id": 7,
"name": "甲烷含量",
"code": "07",
"unit": "LEL%"
}, {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"}, {
"id": 10,
"name": "有功电能",
"code": "08",
"unit": "KWH"
}, {"id": 11, "name": "无功电能", "code": "09", "unit": "KWH"}, {
"id": 12,
"name": "电压",
"code": "0a",
"unit": "V"
}, {"id": 13, "name": "电流", "code": "0b", "unit": "A"}, {
"id": 14,
"name": "有功功率",
"code": "0c",
"unit": "W"
}, {"id": 15, "name": "无功功率", "code": "0d", "unit": "Q"}, {
"id": 18,
"name": "TVOC",
"code": "10",
"unit": "mg/m3"
}],
"type": false
}, {
"id": 126,
"name": "温度+ 门+压差+电表",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/126/550ff778-0ebe-41f6-b3d6-78913d3f55fa",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 6,
"name": "房间压差",
"code": "06",
"unit": "pa"
}, {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"}, {
"id": 10,
"name": "有功电能",
"code": "08",
"unit": "KWH"
}, {"id": 12, "name": "电压", "code": "0a", "unit": "V"}, {
"id": 13,
"name": "电流",
"code": "0b",
"unit": "A"
}, {"id": 14, "name": "有功功率", "code": "0c", "unit": "W"}],
"type": false
}, {
"id": 127,
"name": "温湿度+甲烷+门",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/127/f38c124a-af01-4659-8747-93a94d0b37a8",
"inspectTypes": [{"id": 2, "name": "温湿度(湿度)", "code": "01", "unit": "%"}, {
"id": 4,
"name": "温湿度(温度)",
"code": "04",
"unit": "度"
}, {"id": 7, "name": "甲烷含量", "code": "07", "unit": "LEL%"}, {
"id": 8,
"name": "设备门状态",
"code": "05",
"unit": "开/关"
}],
"type": false
}, {
"id": 128,
"name": "pt100+温湿度+门",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/128/2edad111-3039-401e-9616-67d6ca47e885",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 2,
"name": "温湿度(湿度)",
"code": "01",
"unit": "%"
}, {"id": 4, "name": "温湿度(温度)", "code": "04", "unit": "度"}, {
"id": 8,
"name": "设备门状态",
"code": "05",
"unit": "开/关"
}],
"type": false
}, {
"id": 129,
"name": "pt100+温湿度+门开关+co2",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/129/66321523-8e4e-47bb-9432-5a36fa86aa25",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 2,
"name": "温湿度(湿度)",
"code": "01",
"unit": "%"
}, {"id": 3, "name": "二氧化碳", "code": "02", "unit": "ppm"}, {
"id": 4,
"name": "温湿度(温度)",
"code": "04",
"unit": "度"
}, {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"}],
"type": false
}, {
"id": 132,
"name": "家用冰箱",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/132/8be094e6-eb3b-4410-9bdb-edf8ddde92ff",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 8,
"name": "设备门状态",
"code": "05",
"unit": "开/关"
}, {"id": 10, "name": "有功电能", "code": "08", "unit": "KWH"}, {
"id": 11,
"name": "无功电能",
"code": "09",
"unit": "KWH"
}, {"id": 12, "name": "电压", "code": "0a", "unit": "V"}, {
"id": 13,
"name": "电流",
"code": "0b",
"unit": "A"
}, {"id": 14, "name": "有功功率", "code": "0c", "unit": "W"}, {
"id": 15,
"name": "无功功率",
"code": "0d",
"unit": "Q"
}],
"type": false
}];
var deviceListSample = {
"id": 236,
"name": "休息室",
"days": 37,
"deviceList": [{
"id": 227,
"code": "fk-冰箱",
"name": "低温冰箱",
"deviceType": {
"id": 138,
"name": "冰箱",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/138/142f0018-ef0f-43e0-baf2-4f2ababec1c6",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 8,
"name": "设备门状态",
"code": "05",
"unit": "开/关"
}, {"id": 10, "name": "有功电能", "code": "08", "unit": "KWH"}, {
"id": 12,
"name": "电压",
"code": "0a",
"unit": "V"
}, {"id": 13, "name": "电流", "code": "0b", "unit": "A"}, {
"id": 14,
"name": "有功功率",
"code": "0c",
"unit": "W"
}, {"id": 15, "name": "无功功率", "code": "0d", "unit": "Q"}],
"type": false
},
"createDate": 1489577876000,
"creator": "iLabService",
"purchase": 1475020800000,
"photo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company60/devices/227/540666c7-b99d-40b9-9096-f0427bc1d7a8",
"manager": {
"id": 141,
"name": "kungfu",
"password": "iLabService@123",
"userName": "李康",
"mobile": "15900751966",
"createDate": 1490018889000,
"email": "zycltl@163.com",
"department": "开发",
"job": "kungfu",
"jobNum": "0001",
"role": {
"id": 153,
"authority": "FIRM_MANAGER",
"roleAuthority": {"id": 3, "name": "FIRM_MANAGER"}
},
"companyName": "kungfu",
"verify": "4350",
"bindMobile": 1,
"bindEmail": 1,
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company60/company/8e8df3f5-1c74-44c1-9a36-2691a9a6a6c4",
"roleNames": "企业管理员 ",
"companyId": "BD",
"removeAlert": "2"
},
"alterNum": 0,
"maintain": "365",
"model": "iLabService",
"xPoint": 255.0,
"yPoint": 125.0,
"monitorDevice": {"id": 123, "number": "086021060342000023", "battery": "99.4", "online": 1},
"deviceInspects": [{
"id": 305,
"inspectType": {"id": 15, "name": "无功功率", "code": "0d", "unit": "Q"},
"standard": 30.0,
"lowUp": 50.0,
"lowDown": 0.0,
"highUp": 70.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "无功功率",
"start": "-180.0",
"value": "70.0",
"end": "240.0",
"zero": 0.0,
"originalValue": 80000.0,
"correctionValue": 80000.0,
"inspectPurpose": 0
}],
"pushType": "禁止推送",
"pushInterval": 30,
"roomName": "Kungfu孵化器7层休息室",
"score": "6.3",
"enable": 1,
"days": 35
}],
"roomId": 236,
"floorId": 443,
"floorName": "7层",
"buildId": 53,
"buildName": "Kungfu孵化器",
"lowAlert": 0,
"highAlert": 1,
"online": 1,
"offline": 0,
"total": 1,
"score": 6.3,
"background": "https://ilsdevresource.blob.core.chinacloudapi.cn/company60/rooms/236/d0616b8e-f7d4-4313-a451-c249df59b108"
};
var deviceTypeListSample = [{
"id": 141,
"name": "kungfu",
"password": "iLabService@123",
"userName": "李康",
"mobile": "15900751966",
"createDate": 1490018889000,
"email": "zycltl@163.com",
"department": "开发",
"job": "kungfu",
"jobNum": "0001",
"role": {"id": 153, "authority": "FIRM_MANAGER", "roleAuthority": {"id": 3, "name": "FIRM_MANAGER"}},
"companyName": "kungfu",
"verify": "4350",
"bindMobile": 1,
"bindEmail": 1,
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company60/company/8e8df3f5-1c74-44c1-9a36-2691a9a6a6c4",
"roleNames": "企业管理员 ",
"companyId": "BD",
"removeAlert": "2"
}];
var userDeviceListSample = {
"total": "5",
"devices": [{
"id": 218,
"code": "004",
"name": "INTELAB DEMO - Jing",
"deviceType": {
"id": 129,
"name": "pt100+温湿度+门开关+co2",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/129/66321523-8e4e-47bb-9432-5a36fa86aa25",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 2,
"name": "温湿度(湿度)",
"code": "01",
"unit": "%"
}, {"id": 3, "name": "二氧化碳", "code": "02", "unit": "ppm"}, {
"id": 4,
"name": "温湿度(温度)",
"code": "04",
"unit": "度"
}, {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"}],
"type": false
},
"createDate": 1489030620000,
"creator": "iLabService",
"purchase": 1489017600000,
"photo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/218/c73f9ef5-93da-4ece-b919-d696fbb7d2cb",
"manager": {
"id": 136,
"name": "ils",
"password": "iLabService@123",
"userName": "ils",
"mobile": "15900751966",
"createDate": 1489044084000,
"email": "k.li@ilabservice.com",
"department": "运营",
"job": "ils",
"jobNum": "000",
"role": {
"id": 148,
"authority": "FIRM_MANAGER",
"roleAuthority": {"id": 3, "name": "FIRM_MANAGER"}
},
"companyName": "ilabservice",
"verify": "7106",
"bindMobile": 1,
"bindEmail": 1,
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业管理员 ",
"companyId": "AM",
"removeAlert": "2"
},
"alterNum": 0,
"maintain": "180",
"maintainDate": 1489017600000,
"model": "iLabService",
"xPoint": 90.0,
"yPoint": 100.0,
"monitorDevice": {
"id": 114,
"number": "086021060342000022",
"battery": "97.0",
"online": 0
},
"deviceInspects": [{
"id": 256,
"inspectType": {"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"},
"standard": 20.0,
"lowUp": 40.0,
"lowDown": 0.0,
"highUp": 40.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "温度(PT100)",
"start": "-100.0",
"value": "40.0",
"end": "140.0",
"zero": 0.0,
"originalValue": 19.5116,
"correctionValue": 19.5116,
"inspectPurpose": 0
}, {
"id": 257,
"inspectType": {"id": 2, "name": "温湿度(湿度)", "code": "01", "unit": "%"},
"standard": 30.0,
"lowUp": 40.0,
"lowDown": 10.0,
"highUp": 70.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "温湿度(湿度)",
"start": "-180.0",
"value": "70.0",
"end": "240.0",
"zero": 0.0,
"originalValue": 23.418,
"correctionValue": 23.418,
"inspectPurpose": 0
}, {
"id": 258,
"inspectType": {"id": 3, "name": "二氧化碳", "code": "02", "unit": "ppm"},
"standard": 40.0,
"lowUp": 200.0,
"lowDown": 30.0,
"highUp": 300.0,
"highDown": 10.0,
"lowAlter": 10,
"name": "二氧化碳",
"start": "-830.0",
"value": "290.0",
"end": "910.0",
"zero": 0.0,
"originalValue": 126.0,
"correctionValue": 126.0,
"inspectPurpose": 0
}, {
"id": 259,
"inspectType": {"id": 4, "name": "温湿度(温度)", "code": "04", "unit": "度"},
"standard": 20.0,
"lowUp": 30.0,
"lowDown": 15.0,
"highUp": 40.0,
"highDown": 5.0,
"lowAlter": 10,
"name": "温湿度(温度)",
"start": "-85.0",
"value": "35.0",
"end": "125.0",
"zero": 0.0,
"originalValue": 23.699,
"correctionValue": 23.699,
"inspectPurpose": 0
}, {
"id": 260,
"inspectType": {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"},
"standard": 1.0,
"lowUp": 0.0,
"lowDown": 0.0,
"highUp": 5.0,
"highDown": 5.0,
"lowAlter": 10,
"name": "设备门状态",
"start": "1.0",
"value": "0.0",
"end": "1.0",
"zero": 0.0,
"originalValue": 1.0,
"correctionValue": 1.0,
"inspectPurpose": 0
}],
"files": [{
"id": 31,
"url": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/iLabService INTELAB物联网云监控解决方案_页面_4.jpg",
"createDate": 1489045172000,
"name": "iLabService INTELAB物联网云监控解决方案_页面_4.jpg"
}],
"pushType": "禁止推送",
"pushInterval": 30,
"roomName": "Millburn1309",
"score": "23.95",
"enable": 1,
"days": 32
}, {
"id": 217,
"code": "003",
"name": "INTELAB DEMO - Kenny",
"deviceType": {
"id": 128,
"name": "pt100+温湿度+门",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/128/2edad111-3039-401e-9616-67d6ca47e885",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 2,
"name": "温湿度(湿度)",
"code": "01",
"unit": "%"
}, {"id": 4, "name": "温湿度(温度)", "code": "04", "unit": "度"}, {
"id": 8,
"name": "设备门状态",
"code": "05",
"unit": "开/关"
}],
"type": false
},
"createDate": 1488939135000,
"creator": "iLabService",
"purchase": 1488931200000,
"photo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/217/a1e6ebcc-7180-4040-bda1-e6167dc4830d",
"manager": {
"id": 136,
"name": "ils",
"password": "iLabService@123",
"userName": "ils",
"mobile": "15900751966",
"createDate": 1489044084000,
"email": "k.li@ilabservice.com",
"department": "运营",
"job": "ils",
"jobNum": "000",
"role": {
"id": 148,
"authority": "FIRM_MANAGER",
"roleAuthority": {"id": 3, "name": "FIRM_MANAGER"}
},
"companyName": "ilabservice",
"verify": "7106",
"bindMobile": 1,
"bindEmail": 1,
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业管理员 ",
"companyId": "AM",
"removeAlert": "2"
},
"alterNum": 0,
"maintain": "180",
"model": "iLabService",
"xPoint": 400.0,
"yPoint": 140.0,
"monitorDevice": {
"id": 113,
"number": "086021060342000027",
"battery": "59.9",
"online": 0
},
"deviceInspects": [{
"id": 252,
"inspectType": {"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"},
"standard": 25.0,
"lowUp": 35.0,
"lowDown": 15.0,
"highUp": 40.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "温度(PT100)",
"start": "-95.0",
"value": "40.0",
"end": "145.0",
"zero": 0.0,
"originalValue": 34.5219,
"correctionValue": 34.5219,
"inspectPurpose": 0
}, {
"id": 253,
"inspectType": {"id": 2, "name": "温湿度(湿度)", "code": "01", "unit": "%"},
"standard": 35.0,
"lowUp": 50.0,
"lowDown": 20.0,
"highUp": 80.0,
"highDown": 5.0,
"lowAlter": 10,
"name": "温湿度(湿度)",
"start": "-190.0",
"value": "75.0",
"end": "260.0",
"zero": 0.0,
"originalValue": 35.015,
"correctionValue": 35.015,
"inspectPurpose": 0
}, {
"id": 254,
"inspectType": {"id": 4, "name": "温湿度(温度)", "code": "04", "unit": "度"},
"standard": 20.0,
"lowUp": 30.0,
"lowDown": 0.0,
"highUp": 35.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "温湿度(温度)",
"start": "-85.0",
"value": "35.0",
"end": "125.0",
"zero": 0.0,
"originalValue": 28.483,
"correctionValue": 28.483,
"inspectPurpose": 0
}, {
"id": 255,
"inspectType": {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"},
"standard": 1.0,
"lowUp": 0.0,
"lowDown": 0.0,
"highUp": 5.0,
"highDown": 5.0,
"lowAlter": 10,
"name": "设备门状态",
"start": "1.0",
"value": "0.0",
"end": "1.0",
"zero": 0.0,
"originalValue": 1.0,
"correctionValue": 1.0,
"inspectPurpose": 0
}],
"pushType": "禁止推送",
"pushInterval": 30,
"roomName": "科海大楼7层iLabService",
"score": "47.5",
"enable": 1,
"days": 33
}, {
"id": 216,
"code": "002",
"name": "INTELAB演示2",
"deviceType": {
"id": 127,
"name": "温湿度+甲烷+门",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/127/f38c124a-af01-4659-8747-93a94d0b37a8",
"inspectTypes": [{"id": 2, "name": "温湿度(湿度)", "code": "01", "unit": "%"}, {
"id": 4,
"name": "温湿度(温度)",
"code": "04",
"unit": "度"
}, {"id": 7, "name": "甲烷含量", "code": "07", "unit": "LEL%"}, {
"id": 8,
"name": "设备门状态",
"code": "05",
"unit": "开/关"
}],
"type": false
},
"createDate": 1488686235000,
"creator": "iLabService",
"purchase": 1488585600000,
"photo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/216/b36de11c-d42d-47f2-a678-32f080263d9a",
"manager": {
"id": 136,
"name": "ils",
"password": "iLabService@123",
"userName": "ils",
"mobile": "15900751966",
"createDate": 1489044084000,
"email": "k.li@ilabservice.com",
"department": "运营",
"job": "ils",
"jobNum": "000",
"role": {
"id": 148,
"authority": "FIRM_MANAGER",
"roleAuthority": {"id": 3, "name": "FIRM_MANAGER"}
},
"companyName": "ilabservice",
"verify": "7106",
"bindMobile": 1,
"bindEmail": 1,
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业管理员 ",
"companyId": "AM",
"removeAlert": "2"
},
"alterNum": 0,
"maintain": "180",
"model": "iLabService",
"xPoint": 240.0,
"yPoint": 165.0,
"monitorDevice": {
"id": 112,
"number": "086021060342000018",
"battery": "95.1",
"online": 1
},
"deviceInspects": [{
"id": 248,
"inspectType": {"id": 2, "name": "温湿度(湿度)", "code": "01", "unit": "%"},
"standard": 40.0,
"lowUp": 60.0,
"lowDown": 20.0,
"highUp": 80.0,
"highDown": 10.0,
"lowAlter": 10,
"name": "温湿度(湿度)",
"start": "-170.0",
"value": "70.0",
"end": "250.0",
"zero": 0.0,
"originalValue": 69.897,
"correctionValue": 69.897,
"inspectPurpose": 0
}, {
"id": 249,
"inspectType": {"id": 4, "name": "温湿度(温度)", "code": "04", "unit": "度"},
"standard": 20.0,
"lowUp": 28.0,
"lowDown": 10.0,
"highUp": 35.0,
"highDown": 5.0,
"lowAlter": 10,
"name": "温湿度(温度)",
"start": "-70.0",
"value": "30.0",
"end": "110.0",
"zero": 0.0,
"originalValue": 18.272,
"correctionValue": 18.272,
"inspectPurpose": 0
}, {
"id": 250,
"inspectType": {"id": 7, "name": "甲烷含量", "code": "07", "unit": "LEL%"},
"standard": 0.0,
"lowUp": 15.0,
"lowDown": -1.0,
"highUp": 30.0,
"highDown": -5.0,
"lowAlter": 10,
"name": "甲烷含量",
"start": "-105.0",
"value": "35.0",
"end": "105.0",
"zero": 0.0,
"originalValue": 0.150953,
"correctionValue": 0.150953,
"inspectPurpose": 0
}, {
"id": 251,
"inspectType": {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"},
"standard": 1.0,
"lowUp": 0.0,
"lowDown": 0.0,
"highUp": 5.0,
"highDown": 5.0,
"lowAlter": 10,
"name": "设备门状态",
"start": "1.0",
"value": "0.0",
"end": "1.0",
"zero": 0.0,
"originalValue": 2.0,
"correctionValue": 2.0,
"inspectPurpose": 0
}],
"pushType": "禁止推送",
"pushInterval": 30,
"roomName": "科海大楼7层iLabService",
"score": "0",
"enable": 1,
"days": 36
}, {
"id": 215,
"code": "001",
"name": "INTELAB演示1",
"deviceType": {
"id": 126,
"name": "温度+ 门+压差+电表",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/126/550ff778-0ebe-41f6-b3d6-78913d3f55fa",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 6,
"name": "房间压差",
"code": "06",
"unit": "pa"
}, {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"}, {
"id": 10,
"name": "有功电能",
"code": "08",
"unit": "KWH"
}, {"id": 12, "name": "电压", "code": "0a", "unit": "V"}, {
"id": 13,
"name": "电流",
"code": "0b",
"unit": "A"
}, {"id": 14, "name": "有功功率", "code": "0c", "unit": "W"}],
"type": false
},
"createDate": 1488684790000,
"creator": "iLabService",
"purchase": 1488672000000,
"photo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/215/ffd64b95-56cc-4def-8615-745c2aa1c985",
"manager": {
"id": 136,
"name": "ils",
"password": "iLabService@123",
"userName": "ils",
"mobile": "15900751966",
"createDate": 1489044084000,
"email": "k.li@ilabservice.com",
"department": "运营",
"job": "ils",
"jobNum": "000",
"role": {
"id": 148,
"authority": "FIRM_MANAGER",
"roleAuthority": {"id": 3, "name": "FIRM_MANAGER"}
},
"companyName": "ilabservice",
"verify": "7106",
"bindMobile": 1,
"bindEmail": 1,
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业管理员 ",
"companyId": "AM",
"removeAlert": "2"
},
"alterNum": 0,
"maintain": "365",
"model": "iLabService",
"xPoint": 270.0,
"yPoint": 160.0,
"monitorDevice": {
"id": 111,
"number": "086021060342000041",
"battery": "99.0",
"online": 1
},
"deviceInspects": [{
"id": 241,
"inspectType": {"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"},
"standard": 20.0,
"lowUp": 30.0,
"lowDown": 10.0,
"highUp": 40.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "温度(PT100)",
"start": "-100.0",
"value": "40.0",
"end": "140.0",
"zero": 0.0,
"originalValue": 16.581,
"correctionValue": 16.581,
"inspectPurpose": 0
}, {
"id": 242,
"inspectType": {"id": 6, "name": "房间压差", "code": "06", "unit": "pa"},
"standard": 10.0,
"lowUp": 10.0,
"lowDown": -10.0,
"highUp": 10.0,
"highDown": -10.0,
"lowAlter": 10,
"name": "房间压差",
"start": "-50.0",
"value": "20.0",
"end": "70.0",
"zero": 0.0,
"originalValue": -0.133333,
"correctionValue": -0.138667,
"inspectPurpose": 0
}, {
"id": 243,
"inspectType": {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"},
"standard": 1.0,
"lowUp": 0.0,
"lowDown": 0.0,
"highUp": 5.0,
"highDown": 5.0,
"lowAlter": 10,
"name": "设备门状态",
"start": "1.0",
"value": "0.0",
"end": "1.0",
"zero": 0.0,
"originalValue": 2.0,
"correctionValue": 2.0,
"inspectPurpose": 0
}, {
"id": 244,
"inspectType": {"id": 10, "name": "有功电能", "code": "08", "unit": "KWH"},
"standard": 10.0,
"lowUp": 20.0,
"lowDown": 0.0,
"highUp": 20.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "有功电能",
"start": "-50.0",
"value": "20.0",
"end": "70.0",
"zero": 0.0,
"originalValue": 5.5925,
"correctionValue": 5.5925,
"inspectPurpose": 1
}, {
"id": 245,
"inspectType": {"id": 12, "name": "电压", "code": "0a", "unit": "V"},
"standard": 220.0,
"lowUp": 250.0,
"lowDown": 200.0,
"highUp": 260.0,
"highDown": 190.0,
"lowAlter": 10,
"name": "电压",
"start": "10.0",
"value": "70.0",
"end": "430.0",
"zero": 0.0,
"originalValue": 224.575,
"correctionValue": 224.575,
"inspectPurpose": 1
}, {
"id": 246,
"inspectType": {"id": 13, "name": "电流", "code": "0b", "unit": "A"},
"standard": 0.0,
"lowUp": 3.0,
"lowDown": 0.0,
"highUp": 3.0,
"highDown": -1.0,
"lowAlter": 10,
"name": "电流",
"start": "-12.0",
"value": "4.0",
"end": "12.0",
"zero": 0.0,
"originalValue": 0.062,
"correctionValue": 0.062,
"inspectPurpose": 1
}, {
"id": 247,
"inspectType": {"id": 14, "name": "有功功率", "code": "0c", "unit": "W"},
"standard": 5.0,
"lowUp": 10.0,
"lowDown": 2.0,
"highUp": 50.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "有功功率",
"start": "-145.0",
"value": "50.0",
"end": "155.0",
"zero": 0.0,
"originalValue": 7.0,
"correctionValue": 7.0,
"inspectPurpose": 0
}],
"pushType": "禁止推送",
"pushInterval": 30,
"roomName": "科海大楼7层iLabService",
"score": "0",
"enable": 1,
"days": 36
}, {
"id": 214,
"code": "001",
"name": "INTELAB演示机",
"deviceType": {
"id": 125,
"name": "all",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/125/fbcac7c5-6caf-4a7f-ac57-8dfb3bc3ffb5",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 2,
"name": "温湿度(湿度)",
"code": "01",
"unit": "%"
}, {"id": 3, "name": "二氧化碳", "code": "02", "unit": "ppm"}, {
"id": 4,
"name": "温湿度(温度)",
"code": "04",
"unit": "度"
}, {"id": 6, "name": "房间压差", "code": "06", "unit": "pa"}, {
"id": 7,
"name": "甲烷含量",
"code": "07",
"unit": "LEL%"
}, {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"}, {
"id": 10,
"name": "有功电能",
"code": "08",
"unit": "KWH"
}, {"id": 11, "name": "无功电能", "code": "09", "unit": "KWH"}, {
"id": 12,
"name": "电压",
"code": "0a",
"unit": "V"
}, {"id": 13, "name": "电流", "code": "0b", "unit": "A"}, {
"id": 14,
"name": "有功功率",
"code": "0c",
"unit": "W"
}, {"id": 15, "name": "无功功率", "code": "0d", "unit": "Q"}, {
"id": 18,
"name": "TVOC",
"code": "10",
"unit": "mg/m3"
}],
"type": false
},
"createDate": 1488624231000,
"creator": "iLabService",
"purchase": 1488326400000,
"photo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/214/b6cc30e8-7502-4fe8-bf01-f9ac936c1b77",
"manager": {
"id": 136,
"name": "ils",
"password": "iLabService@123",
"userName": "ils",
"mobile": "15900751966",
"createDate": 1489044084000,
"email": "k.li@ilabservice.com",
"department": "运营",
"job": "ils",
"jobNum": "000",
"role": {
"id": 148,
"authority": "FIRM_MANAGER",
"roleAuthority": {"id": 3, "name": "FIRM_MANAGER"}
},
"companyName": "ilabservice",
"verify": "7106",
"bindMobile": 1,
"bindEmail": 1,
"companyLogo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b",
"roleNames": "企业管理员 ",
"companyId": "AM",
"removeAlert": "2"
},
"alterNum": 0,
"maintain": "365",
"model": "iLabService",
"xPoint": 260.0,
"yPoint": 165.0,
"monitorDevice": {"id": 110, "number": "修改41", "battery": "99.4", "online": 0},
"deviceInspects": [{
"id": 227,
"inspectType": {"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"},
"standard": 20.0,
"lowUp": 30.0,
"lowDown": 0.0,
"highUp": 40.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "温度(PT100)",
"start": "-100.0",
"value": "40.0",
"end": "140.0",
"zero": 0.0,
"originalValue": 20.2578,
"correctionValue": 20.2578,
"inspectPurpose": 0
}, {
"id": 228,
"inspectType": {"id": 2, "name": "温湿度(湿度)", "code": "01", "unit": "%"},
"standard": 50.0,
"lowUp": 70.0,
"lowDown": 0.0,
"highUp": 90.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "温湿度(湿度)",
"start": "-220.0",
"value": "90.0",
"end": "320.0",
"zero": 0.0,
"originalValue": 80.151,
"correctionValue": 80.151,
"inspectPurpose": 0
}, {
"id": 229,
"inspectType": {"id": 3, "name": "二氧化碳", "code": "02", "unit": "ppm"},
"standard": 10.0,
"lowUp": 20.0,
"lowDown": 0.0,
"highUp": 20.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "二氧化碳",
"start": "-50.0",
"value": "20.0",
"end": "70.0",
"zero": 0.0,
"originalValue": 0.0,
"correctionValue": 0.0,
"inspectPurpose": 0
}, {
"id": 230,
"inspectType": {"id": 4, "name": "温湿度(温度)", "code": "04", "unit": "度"},
"standard": 20.0,
"lowUp": 40.0,
"lowDown": 0.0,
"highUp": 40.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "温湿度(温度)",
"start": "-100.0",
"value": "40.0",
"end": "140.0",
"zero": 0.0,
"originalValue": -46.85,
"correctionValue": -46.85,
"inspectPurpose": 0
}, {
"id": 231,
"inspectType": {"id": 6, "name": "房间压差", "code": "06", "unit": "pa"},
"standard": 40.0,
"lowUp": 100.0,
"lowDown": 0.0,
"highUp": 100.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "房间压差",
"start": "-260.0",
"value": "100.0",
"end": "340.0",
"zero": 0.0,
"originalValue": -0.016667,
"correctionValue": -0.017333,
"inspectPurpose": 0
}, {
"id": 232,
"inspectType": {"id": 7, "name": "甲烷含量", "code": "07", "unit": "LEL%"},
"standard": 5.0,
"lowUp": 10.0,
"lowDown": 0.0,
"highUp": 10.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "甲烷含量",
"start": "-25.0",
"value": "10.0",
"end": "35.0",
"zero": 0.0,
"originalValue": 0.0,
"correctionValue": 0.0,
"inspectPurpose": 0
}, {
"id": 233,
"inspectType": {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"},
"standard": 1.0,
"lowUp": 0.0,
"lowDown": 0.0,
"highUp": 5.0,
"highDown": 5.0,
"lowAlter": 10,
"name": "设备门状态",
"start": "1.0",
"value": "0.0",
"end": "1.0",
"zero": 0.0,
"originalValue": 1.0,
"correctionValue": 1.0,
"inspectPurpose": 0
}, {
"id": 234,
"inspectType": {"id": 10, "name": "有功电能", "code": "08", "unit": "KWH"},
"standard": 10.0,
"lowUp": 50.0,
"lowDown": 0.0,
"highUp": 50.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "有功电能",
"start": "-140.0",
"value": "50.0",
"end": "160.0",
"zero": 0.0,
"originalValue": 4.55889,
"correctionValue": 4.55889,
"inspectPurpose": 0
}, {
"id": 235,
"inspectType": {"id": 11, "name": "无功电能", "code": "09", "unit": "KWH"},
"standard": 10.0,
"lowUp": 50.0,
"lowDown": 0.0,
"highUp": 50.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "无功电能",
"start": "-140.0",
"value": "50.0",
"end": "160.0",
"zero": 0.0,
"originalValue": 6.90306,
"correctionValue": 6.90306,
"inspectPurpose": 0
}, {
"id": 236,
"inspectType": {"id": 12, "name": "电压", "code": "0a", "unit": "V"},
"standard": 20.0,
"lowUp": 500.0,
"lowDown": 0.0,
"highUp": 500.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "电压",
"start": "-1480.0",
"value": "500.0",
"end": "1520.0",
"zero": 0.0,
"originalValue": 0.0,
"correctionValue": 0.0,
"inspectPurpose": 0
}, {
"id": 237,
"inspectType": {"id": 13, "name": "电流", "code": "0b", "unit": "A"},
"standard": 40.0,
"lowUp": 60.0,
"lowDown": 0.0,
"highUp": 60.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "电流",
"start": "-140.0",
"value": "60.0",
"end": "220.0",
"zero": 0.0,
"originalValue": 0.0,
"correctionValue": 0.0,
"inspectPurpose": 0
}, {
"id": 238,
"inspectType": {"id": 14, "name": "有功功率", "code": "0c", "unit": "W"},
"standard": 40.0,
"lowUp": 70.0,
"lowDown": 0.0,
"highUp": 70.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "有功功率",
"start": "-170.0",
"value": "70.0",
"end": "250.0",
"zero": 0.0,
"originalValue": 0.0,
"correctionValue": 0.0,
"inspectPurpose": 0
}, {
"id": 239,
"inspectType": {"id": 15, "name": "无功功率", "code": "0d", "unit": "Q"},
"standard": 40.0,
"lowUp": 70.0,
"lowDown": 0.0,
"highUp": 70.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "无功功率",
"start": "-170.0",
"value": "70.0",
"end": "250.0",
"zero": 0.0,
"originalValue": 0.0,
"correctionValue": 0.0,
"inspectPurpose": 0
}, {
"id": 240,
"inspectType": {"id": 18, "name": "TVOC", "code": "10", "unit": "mg/m3"},
"standard": 1.0,
"lowUp": 2.0,
"lowDown": 0.0,
"highUp": 2.0,
"highDown": 0.0,
"lowAlter": 10,
"name": "TVOC",
"start": "-5.0",
"value": "2.0",
"end": "7.0",
"zero": 0.0,
"originalValue": 0.0,
"correctionValue": 0.0,
"inspectPurpose": 0
}],
"files": [{
"id": 25,
"url": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/iLabService INTELAB物联网云监控解决方案_页面_1.jpg",
"createDate": 1488643848000,
"name": "iLabService INTELAB物联网云监控解决方案_页面_1.jpg"
}, {
"id": 26,
"url": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/iLabService INTELAB物联网云监控解决方案_页面_2.jpg",
"createDate": 1488643858000,
"name": "iLabService INTELAB物联网云监控解决方案_页面_2.jpg"
}, {
"id": 27,
"url": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/iLabService INTELAB物联网云监控解决方案_页面_3.jpg",
"createDate": 1488643864000,
"name": "iLabService INTELAB物联网云监控解决方案_页面_3.jpg"
}, {
"id": 28,
"url": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/iLabService INTELAB物联网云监控解决方案_页面_4.jpg",
"createDate": 1488643868000,
"name": "iLabService INTELAB物联网云监控解决方案_页面_4.jpg"
}, {
"id": 29,
"url": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/iLabService INTELAB物联网云监控解决方案_页面_5.jpg",
"createDate": 1488643873000,
"name": "iLabService INTELAB物联网云监控解决方案_页面_5.jpg"
}, {
"id": 30,
"url": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/devices/iLabService INTELAB物联网云监控解决方案_页面_6.jpg",
"createDate": 1488643878000,
"name": "iLabService INTELAB物联网云监控解决方案_页面_6.jpg"
}],
"pushType": "禁止推送",
"pushInterval": 30,
"roomName": "科海大楼7层iLabService",
"score": "83.8",
"enable": 1,
"days": 37
}],
"thisNum": "5"
};
var deviceTypesSample = [
{
"id": 64,
"name": "环境温度",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/64/7607d45c-7a86-41b2-a0b7-77feeb59087d",
"inspectTypes": [{"id": 4, "name": "温湿度(温度)", "code": "04", "unit": "度"}],
"type": true
}, {
"id": 120,
"name": "pt100+开关",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/120/fcdc009a-4d47-4dd5-bb70-b7c6c29c90cd",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 8,
"name": "设备门状态",
"code": "05",
"unit": "开/关"
}],
"type": true
}, {
"id": 125,
"name": "all",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/125/fbcac7c5-6caf-4a7f-ac57-8dfb3bc3ffb5",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 2,
"name": "温湿度(湿度)",
"code": "01",
"unit": "%"
}, {"id": 3, "name": "二氧化碳", "code": "02", "unit": "ppm"}, {
"id": 4,
"name": "温湿度(温度)",
"code": "04",
"unit": "度"
}, {"id": 6, "name": "房间压差", "code": "06", "unit": "pa"}, {
"id": 7,
"name": "甲烷含量",
"code": "07",
"unit": "LEL%"
}, {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"}, {
"id": 10,
"name": "有功电能",
"code": "08",
"unit": "KWH"
}, {"id": 11, "name": "无功电能", "code": "09", "unit": "KWH"}, {
"id": 12,
"name": "电压",
"code": "0a",
"unit": "V"
}, {"id": 13, "name": "电流", "code": "0b", "unit": "A"}, {
"id": 14,
"name": "有功功率",
"code": "0c",
"unit": "W"
}, {"id": 15, "name": "无功功率", "code": "0d", "unit": "Q"}, {
"id": 18,
"name": "TVOC",
"code": "10",
"unit": "mg/m3"
}],
"type": false
}, {
"id": 126,
"name": "温度+ 门+压差+电表",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/126/550ff778-0ebe-41f6-b3d6-78913d3f55fa",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 6,
"name": "房间压差",
"code": "06",
"unit": "pa"
}, {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"}, {
"id": 10,
"name": "有功电能",
"code": "08",
"unit": "KWH"
}, {"id": 12, "name": "电压", "code": "0a", "unit": "V"}, {
"id": 13,
"name": "电流",
"code": "0b",
"unit": "A"
}, {"id": 14, "name": "有功功率", "code": "0c", "unit": "W"}],
"type": false
}, {
"id": 127,
"name": "温湿度+甲烷+门",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/127/f38c124a-af01-4659-8747-93a94d0b37a8",
"inspectTypes": [{"id": 2, "name": "温湿度(湿度)", "code": "01", "unit": "%"}, {
"id": 4,
"name": "温湿度(温度)",
"code": "04",
"unit": "度"
}, {"id": 7, "name": "甲烷含量", "code": "07", "unit": "LEL%"}, {
"id": 8,
"name": "设备门状态",
"code": "05",
"unit": "开/关"
}],
"type": false
}, {
"id": 128,
"name": "pt100+温湿度+门",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/128/2edad111-3039-401e-9616-67d6ca47e885",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 2,
"name": "温湿度(湿度)",
"code": "01",
"unit": "%"
}, {"id": 4, "name": "温湿度(温度)", "code": "04", "unit": "度"}, {
"id": 8,
"name": "设备门状态",
"code": "05",
"unit": "开/关"
}],
"type": false
}, {
"id": 129,
"name": "pt100+温湿度+门开关+co2",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/129/66321523-8e4e-47bb-9432-5a36fa86aa25",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 2,
"name": "温湿度(湿度)",
"code": "01",
"unit": "%"
}, {"id": 3, "name": "二氧化碳", "code": "02", "unit": "ppm"}, {
"id": 4,
"name": "温湿度(温度)",
"code": "04",
"unit": "度"
}, {"id": 8, "name": "设备门状态", "code": "05", "unit": "开/关"}],
"type": false
}, {
"id": 132,
"name": "家用冰箱",
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/devicetypes/132/8be094e6-eb3b-4410-9bdb-edf8ddde92ff",
"inspectTypes": [{"id": 1, "name": "温度(PT100)", "code": "00", "unit": "度"}, {
"id": 8,
"name": "设备门状态",
"code": "05",
"unit": "开/关"
}, {"id": 10, "name": "有功电能", "code": "08", "unit": "KWH"}, {
"id": 11,
"name": "无功电能",
"code": "09",
"unit": "KWH"
}, {"id": 12, "name": "电压", "code": "0a", "unit": "V"}, {
"id": 13,
"name": "电流",
"code": "0b",
"unit": "A"
}, {"id": 14, "name": "有功功率", "code": "0c", "unit": "W"}, {
"id": 15,
"name": "无功功率",
"code": "0d",
"unit": "Q"
}],
"type": false
}];
var inspectDeviceTypeSample = {
"list": [{"id": 1, "name": "温度(PT100)", "chosed": false, "runningStatus": []}, {
"id": 2,
"name": "温湿度(湿度)",
"chosed": false,
"runningStatus": []
}, {"id": 3, "name": "二氧化碳", "chosed": false, "runningStatus": []}, {
"id": 4,
"name": "温湿度(温度)",
"chosed": false,
"runningStatus": []
}, {"id": 6, "name": "房间压差", "chosed": false, "runningStatus": []}, {
"id": 7,
"name": "甲烷含量",
"chosed": false,
"runningStatus": []
}, {"id": 8, "name": "设备门状态", "chosed": false, "runningStatus": []}, {
"id": 9,
"name": "电池电量",
"chosed": false,
"runningStatus": []
}, {"id": 10, "name": "有功电能", "chosed": false, "runningStatus": []}, {
"id": 11,
"name": "无功电能",
"chosed": false,
"runningStatus": []
}, {"id": 12, "name": "电压", "chosed": false, "runningStatus": []}, {
"id": 13,
"name": "电流",
"chosed": false,
"runningStatus": []
}, {"id": 14, "name": "有功功率", "chosed": false, "runningStatus": []}, {
"id": 15,
"name": "无功功率",
"chosed": false,
"runningStatus": []
}, {"id": 16, "name": "温度", "chosed": false, "runningStatus": []}, {
"id": 17,
"name": "湿度",
"chosed": false,
"runningStatus": []
}, {"id": 18, "name": "TVOC", "chosed": false, "runningStatus": []}, {
"id": 19,
"name": "烟雾监控",
"chosed": false,
"runningStatus": []
}, {"id": 20, "name": "pm2.5", "chosed": false, "runningStatus": []}, {
"id": 21,
"name": "pm10",
"chosed": false,
"runningStatus": []
}, {"id": 22, "name": "电能", "chosed": false, "runningStatus": []}, {
"id": 23,
"name": "电压",
"chosed": false,
"runningStatus": []
}, {"id": 24, "name": "电流", "chosed": false, "runningStatus": []}, {
"id": 25,
"name": "功率",
"chosed": false,
"runningStatus": []
}]
};
var currentDeviceTypeSample = {
"id": 129,
"name": "pt100+温湿度+门开关+co2",
"list": [{
"id": 1,
"name": "温度(PT100)",
"lowUp": "40.0",
"lowDown": "0.0",
"highUp": "40.0",
"highDown": "0.0",
"standard": "20.0",
"chosed": true,
"runningStatus": [],
"inspectPurpose": 0
}, {
"id": 2,
"name": "温湿度(湿度)",
"lowUp": "40.0",
"lowDown": "0.0",
"highUp": "40.0",
"highDown": "0.0",
"standard": "30.0",
"chosed": true,
"runningStatus": [],
"inspectPurpose": 0
}, {
"id": 3,
"name": "二氧化碳",
"lowUp": "60.0",
"lowDown": "0.0",
"highUp": "60.0",
"highDown": "0.0",
"standard": "40.0",
"chosed": true,
"runningStatus": [],
"inspectPurpose": 0
}, {
"id": 4,
"name": "温湿度(温度)",
"lowUp": "40.0",
"lowDown": "0.0",
"highUp": "40.0",
"highDown": "0.0",
"standard": "30.0",
"chosed": true,
"runningStatus": [],
"inspectPurpose": 0
}, {
"id": 8,
"name": "设备门状态",
"lowUp": "0.0",
"lowDown": "0.0",
"highUp": "5.0",
"highDown": "5.0",
"standard": "1.0",
"chosed": true,
"runningStatus": [],
"inspectPurpose": 0
}]
};
//------------------------- 测试 函数 api 调用, 返回|修改 以上测试数据 -------------
tools.getUserInfoSample = function () {
if (!Session.user) {
return user_firm_manager;
}
if (!Session.company) {
return user_service_manager;
} else {
return user_firm_manager;
}
};
tools.getCompanyInfoSample = function () {
return companyInfoSample;
};
tools.getDeviceSample = function () {
return deviceSample;
};
tools.getDeviceScientistsSample = function () {
return deviceScientistsSample;
};
tools.getDeviceManagerListSample = function () {
return deviceManagersSample;
};
tools.getDeviceRunningStatusSample = function () {
return runningStatusSample;
};
tools.getDeviceParametersSample = function () {
return deviceParametersSample;
};
//因为这个地方是返回一个交接的用户列表,再删除的时候需要选择
tools.getDeleteUserInitSample = function () {
return deleteUserInitSample;
};
tools.getRoomSample = function (roomId) {
for (var i = 0; i < roomListSample.length; i++) {
if (roomListSample[i].id == roomId) {
return roomListSample[i];
}
}
};
tools.getFloorSample = function (floorId) {
for (var i = 0; i < floorListSample.length; i++) {
if (floorListSample[i].id == floorId) {
return floorListSample[i];
}
}
};
tools.getBuildingSample = function (buildingId) {
for (var i = 0; i < buildingListSample.length; i++) {
if (buildingListSample[i].id == buildingId) {
return buildingListSample[i];
}
}
};
tools.getCampusSample = function () {
return campusSample;
};
// ----------------------------------------dashboard APISample end----------------------------
// ----------------------------------------userList APISample start----------------------------
//这个userlist应该存在一个变量里。 所有相关user的操作都在这个list变量上, 不要再创建其他的, 可以和上面的那个user merge起来
tools.getUserListSample = function () {
return userListSample;
};
// 上面已经有company的sample data了, 这里就不要重复了。
tools.getUserCompanySample = function () {
return userCompanySample;
};
//同上, 只要一个userlist
tools.getCompanyUserListSample = function () {
return companyUserListSample;
};
tools.createUserSample = function () {
return {"error": 0, "message": "创建成功!"}
};
tools.saveDeleteUserHandSample = function () {
return {"error": 0, "message": "创建成功!"}
};
// ----------------------------------------userList APISample end----------------------------
// ----------------------------------------userdevice APISample start----------------------------
tools.getDeviceTypeSample = function () {
return deviceTypeSample;
};
tools.getDeviceListSample = function () {
return deviceListSample;
};
tools.getDeviceTypeListSample = function () {
return deviceTypeListSample;
};
tools.getScientistListSample = function () {
return [{'id': 1, 'name': 'xuge'}, {'id': 2, 'name': 'xieanhuan'}];
};
tools.getUserDeviceListSample = function () {
return userDeviceListSample;
};
tools.saveDeleteDeviceInfoSample = function () {
return {"error": 0, "message": "删除成功!"}
};
// ----------------------------------------settings APISample start----------------------------
tools.updateFloorInfo = function (name, data) {
if (data.floorId) {
//修改
for (var i = 0; i < buildingListSample.length; i++) {
if (buildingListSample.id != data.buildId) {
continue;
}
for (var j = 0; j < buildingListSample[i].floors.length; j++) {
if (buildingListSample[i].floors[j].id == data.floorId) {
buildingListSample[i].floors[j].xpoint = data.ceng_xpoint;
buildingListSample[i].floors[j].ypoint = data.ceng_ypoint;
buildingListSample[i].floors[j].name = name;
return;
}
}
}
} else {
//新增
for (var i = 0; i < buildingListSample.length; i++) {
if (buildingListSample[i].id == data.buildId) {
var newFloor = JSON.parse(JSON.stringify(buildingListSample[i].floors[0]));
newFloor.name = name;
newFloor.xpoint = data.ceng_xpoint;
newFloor.ypoint = data.ceng_ypoint;
buildingListSample.push(newFloor);
}
}
}
};
tools.getDeviceTypesSample = function () {
return deviceTypesSample;
};
tools.getInspectDeviceTypeSample = function () {
return inspectDeviceTypeSample;
};
tools.getCurrentDeviceTypeSample = function () {
return currentDeviceTypeSample;
};
tools.postDeviceTypeSample = function () {
return ''
};
tools.getBuildListSample = function (data) {
/* var xp,yp;
if(build_xpoint){xp=build_xpoint}else{xp=575.0}
if(build_ypoint){yp=build_ypoint}else{yp=575.0}*/
if (data) {
var build_name = data.build_name;
var build_xpoint = data.build_xpoint;
var build_ypoint = data.build_ypoint;
var type = data.type;
}
var listData = [{
"name": "科海大楼",
"xpoint": 116,
"ypoint": 39,
"deviceNum": 4,
"createDate": 1488624068000,
"lowAlert": 0,
"highAlert": 2,
"online": 2,
"offline": 2,
"total": 4,
"score": 32.825,
"enable": 0,
"days": 38
}, {
"name": "科海大楼",
"xpoint": 116,
"ypoint": 39,
"deviceNum": 4,
"createDate": 1488624068000,
"lowAlert": 0,
"highAlert": 2,
"online": 2,
"offline": 2,
"total": 4,
"score": 32.825,
"enable": 1,
"days": 38
}];
var flag = 0;
if (build_name) {
var newBuild = {
"name": build_name,
"xpoint": build_xpoint,
"ypoint": build_ypoint
};
for (var i = 0; i < listData.length; i++) {
if ((listData[i].name == build_name) && build_name) {
listData[i] = newBuild;
}
}
if (type == 0) {
listData.push(newBuild);
}
}
return {
"data": {
"id": 59,
"name": "ilabservice",
"background": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/0beb2f42-5719-4f3c-b594-24da14c966c5",
"days": 38,
"list": listData,
"lowAlert": 0,
"highAlert": 3,
"online": 2,
"offline": 3,
"total": 5,
"score": 18.925,
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b"
}
}
};
tools.deleteBuildSample = function () {
return {"error": 0, "message": "删除成功!"}
};
tools.getFloorsSample = function (data) {
if (data) {
var floor_name = data.floor_name;
var floor_xpoint = data.floor_xpoint;
var floor_ypoint = data.floor_ypoint;
var type = data.type;
}
var listData = [{
"id": 439,
"name": "7层",
"deviceNum": 4,
"createDate": 1488624079000,
"background": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/floors/439/d959481a-78ab-4c7a-91a9-3e7926c70783",
"xpoint": 610.0,
"ypoint": 255.0,
"lowAlert": 0,
"highAlert": 2,
"online": 2,
"offline": 2,
"total": 4,
"score": 32.825,
"enable": 1,
"days": 38
}, {
"id": 439,
"name": "11层",
"deviceNum": 4,
"createDate": 1488624079000,
"background": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/floors/439/d959481a-78ab-4c7a-91a9-3e7926c70783",
"xpoint": 610.0,
"ypoint": 255.0,
"lowAlert": 0,
"highAlert": 2,
"online": 2,
"offline": 2,
"total": 4,
"score": 32.825,
"enable": 1,
"days": 38
}];
var flag = 0;
if (floor_name) {
var newBuild = {
"name": floor_name,
"xpoint": floor_xpoint,
"ypoint": floor_ypoint
};
for (var i = 0; i < listData.length; i++) {
if ((listData[i].name == floor_name) && floor_name) {
listData[i] = newBuild;
}
}
if (type == 0) {
listData.push(newBuild);
}
localStorage.jsonFloor = JSON.stringify(listData);
}
return {
"error": 0,
"message": "OK",
"data": {
"id": 50,
"name": "科海大楼",
"alertNum": 0,
"days": 38,
"floors": listData,
"buildId": 50,
"lowAlert": 0,
"highAlert": 2,
"online": 2,
"offline": 2,
"total": 4,
"score": 32.825,
"background": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/buildings/50/0d5f4363-24a5-43e8-a598-bc447fdb6002"
}
}
};
tools.addFloorSample = function () {
return {
"error": 0,
"message": "OK",
"data": {
"id": 50,
"name": "科海大楼",
"alertNum": 0,
"days": 38,
"floors": [{
"id": 439,
"name": "7层",
"deviceNum": 4,
"createDate": 1488624079000,
"background": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/floors/439/d959481a-78ab-4c7a-91a9-3e7926c70783",
"xpoint": 610.0,
"ypoint": 255.0,
"lowAlert": 0,
"highAlert": 2,
"online": 2,
"offline": 2,
"total": 4,
"score": 32.825,
"enable": 1,
"days": 38
}],
"buildId": 50,
"lowAlert": 0,
"highAlert": 2,
"online": 2,
"offline": 2,
"total": 4,
"score": 32.825,
"background": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/buildings/50/0d5f4363-24a5-43e8-a598-bc447fdb6002"
}
}
};
tools.getRoomListSample = function (xpoint, ypoint) {
var xp, yp;
if (xpoint) {
xp = xpoint
} else {
xp = 575.0
}
if (ypoint) {
yp = ypoint
} else {
yp = 575.0
}
return {
"error": 0,
"message": "OK",
"data": {
"id": 59,
"name": "ilabservice",
"background": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/0beb2f42-5719-4f3c-b594-24da14c966c5",
"days": 38,
"roomList": [{
"id": 50,
"name": "科海大楼",
"xpoint": xp,
"ypoint": yp,
"deviceNum": 4,
"createDate": 1488624068000,
"lowAlert": 0,
"highAlert": 2,
"online": 2,
"offline": 2,
"total": 4,
"score": 32.825,
"enable": 1,
"days": 38
}],
"lowAlert": 0,
"highAlert": 3,
"online": 2,
"offline": 3,
"total": 5,
"score": 18.925,
"logo": "https://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/beb937d0-3378-48c7-bf87-16abe3fee25b"
}
}
};
// ----------------------------------------settings APISample end----------------------------
// ----------------------------------------userDevice APISample end----------------------------
var companyListSample = [
{
address: "上海张江",
background: "https://ilsdevresource.blob.core.chinacloudapi.cn/company60/company/65c511ad-1418-4191-847a-72d2b9b9628f",
companyId: "BD",
createDate: 1489367283000,
email: "107699621@qq.com",
enable: 1,
highAlert: 0,
id: 60,
lat: 31.2108,
lng: 121.592,
location: "121.592,31.2108",
login: "http://bd.intelab.cloud",
lowAlert: 0,
name: "kungfu",
offline: 4,
online: 0,
score: 57.9375,
telephone: "",
total: 4,
manager: {
companyId: "BD",
companyName: "kungfu",
id: 141,
name: "kungfu",
password: "123",
roleNames: "企业管理员 ",
userName: "李",
mobile: "127847264"
}
},
{
address: "上海纳贤路800号",
background: "hhttps://ilsdevresource.blob.core.chinacloudapi.cn/company59/company/0beb2f42-5719-4f3c-b594-24da14c966c5",
companyId: "AM",
createDate: 1489367283000,
email: "zy.li@ilabservice.com",
enable: 1,
highAlert: 0,
id: 59,
lat: 31.1894,
lng: 121.611,
location: "121.592,31.2108",
login: "http://am.intelab.cloud",
lowAlert: 0,
name: "ilabservice",
offline: 4,
online: 0,
score: 57.9375,
telephone: "",
total: 4,
manager: {
companyId: "AM",
companyName: "ilabservice",
id: 136,
name: "ilabservice",
password: "123",
roleNames: "企业管理员 ",
userName: "ils",
mobile: '13787268472'
}
}
];
tools.getCompanyListSample = function () {
return companyListSample;
};
var versionListSample = [{
"id": 20,
"name": "1",
"url": "https://ilsresources.blob.core.chinacloudapi.cn/version/version/20/0_weixiu_5900_20160319134553.jpg",
"firstCode": "1",
"secondCode": "1",
"thirdCode": "11",
"forthCode": "1",
"type": "01",
"createDate": 1482426381000
}];
tools.getVersionListSample = function () {
return versionListSample;
};
return tools;
}
|
import classes from './SelectButton.module.css';
const SelectButton = (props) => {
const selected = props.value === props.currentValue;
return (
<button
className={`${classes.SelectButton} ${selected ? classes.Selected : ''}`}
onClick={props.clicked}
>
{props.value}
</button>
);
};
export const SelectColorButton = (props) => {
const selected = props.color === props.currentColor;
return (
<button className={classes.SelectColorButton} onClick={props.clicked}>
<span
style={{ backgroundColor: props.color }}
className={`${selected ? classes.SelectedColor : ''}`}
></span>
</button>
);
};
export default SelectButton;
|
import React from 'react'
import PropTypes from 'prop-types'
function Button({onMore}) {
return (
<button className="Button" onClick={onMore}>
Load MORE...
</button>
)
}
Button.propTypes = {
onMore: PropTypes.func.isRequired,
}
export default Button
|
$(function(){
var isHiden = true;
var isHiden = true; /*控制切换菜单*/
$('.close').click(function(){
if(isHiden){
$('#popView').animate({left:'+=100%'});//菜单块向右移动
}else{
$('#popView').animate({left:'-=100%'}); //菜单块向左移动
}
isHiden = !isHiden;
});
$('#resume').click(function(){
if(isHiden){
$('#popView').animate({left:'+=100%'});//菜单块向右移动
}else{
$('#popView').animate({left:'-=100%'}); //菜单块向左移动
}
isHiden = !isHiden;
});
});
$(window).scroll(function() {
if ($(this).scrollTop() >= 50) { // If page is scrolled more than 50px
$('#return-to-top').fadeIn(200); // Fade in the arrow
} else {
$('#return-to-top').fadeOut(200); // Else fade out the arrow
}
});
$('#return-to-top').click(function() { // When arrow is clicked
$('body,html').animate({
scrollTop : 0 // Scroll to top of body
}, 500);
});
|
var express = require('express'),
geocoder = require('geocoder'),
request = require('request'),
http = require('http'),
querystring = require('querystring');
var Legislators = require('./controllers/legislators');
var Bills = require('./controllers/bills');
exports.define = function(app){
app.get('/api/legislator*', function(req, res){
var legislator = new Legislators( req, res );
legislator.get();
});
app.get('/api/bill*', function(req, res){
var bill = new Bills( req, res );
bill.get();
});
};
|
import React from 'react';
import {StyleSheet, View} from 'react-native';
import Screen from '../Screen';
import {Colors, Layout, Styles, Fonts} from '@app/constants';
export default function MoreScreen(props) {
return <Screen style={styles.container}></Screen>;
}
const styles = StyleSheet.create({
container: {},
});
|
$(function () {
$('#Mukachevo').on('click', function () {
$('#from').val('Мукачево');
$('#to').val('Ужгород');
$('#date').val(todayFormat());
$('#date').focus();
});
$('#Uzhhorod').on('click', function () {
$('#to').val('Мукачево');
$('#from').val('Ужгород');
$('#date').val(todayFormat());
$('#date').focus();
});
$('#Mouse').on('click', function () {
$('#to').val('Пацканьово');
$('#from').val('Крисовці');
$('#date').val(todayFormat());
$('#date').focus();
});
$('#UzhNU').on('click', function () {
$('#to').val('Армія');
$('#from').val('УжНУ');
$('#date').val(todayFormat());
$('#date').focus();
alert('ТРЕБА БУЛО ЙТИ В АСПІРАНТУРУ!!!');
});
$('#Uzhhorod1').on('click', function () {
$('#from').val('Ужгород');
});
$('#Mukachevo1').on('click', function () {
$('#from').val('Мукачево');
});
$('#Kiev').on('click', function () {
$('#from').val('Київ');
});
$('#Lviv').on('click', function () {
$('#from').val('Львів');
});
$('#Odessa').on('click', function () {
$('#from').val('Одеса');
});
$('#Uzhhorod2').on('click', function () {
$('#to').val('Ужгород');
});
$('#Mukachevo2').on('click', function () {
$('#to').val('Мукачево');
});
$('#Kiev2').on('click', function () {
$('#to').val('Київ');
});
$('#Lviv2').on('click', function () {
$('#to').val('Львів');
});
$('#Odessa2').on('click', function () {
$('#to').val('Одеса');
});
$('.ButtonBuy').on('click', function (e) {
let target = e.target,
parent = target.parentNode;
var count = parent.firstChild.nextElementSibling.innerText;
var number = parseInt(count) - 1;
if (number >= 0) {
parent.firstChild.nextElementSibling.innerText = number;
} else {
alert("Вибачте, вільних місць не залишилось більше. Хіба якщо зайцем проскочите.");
}
});
function todayFormat() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) dd = '0' + dd;
if (mm < 10) mm = '0' + mm;
today = yyyy + '-' + mm + '-' + dd;
return today;
}
}); |
// @flow
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Dimensions,
Text,
View
} from 'react-native';
import MapView, { PROVIDER_GOOGLE } from 'react-native-maps';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
class GoogleMapPlayground extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<View style={{ flex: 1 }}>
<View style={{ backgroundColor: 'green', height: 100, justifyContent: 'center', alignItems: 'center'}}>
<Text>Some div</Text>
</View>
<View style={styles.container}>
<MapView
provider={PROVIDER_GOOGLE}
style={styles.map}
initialRegion={{
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}}
/>
</View>
</View>
);
}
}
GoogleMapPlayground.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
top: 100,
justifyContent: 'flex-end',
alignItems: 'center'
},
map: {
...StyleSheet.absoluteFillObject,
},
});
export default GoogleMapPlayground;
|
/**
* Created by f.putra on 2019-04-09.
*/
import React from 'react';
import {Dimensions, Text, TouchableOpacity, View} from 'react-native';
import {Body, Container, Content, Header, Form, Label, Input, Item, Icon, Left, Right, Picker} from 'native-base'
import styles from '../../utils/Style'
import Divider from '../../utils/Divider'
const {width, height} = Dimensions.get('window')
class Home extends React.Component {
static navigationOptions = {
tabBarIcon: ({tintColor}) => (
<Icon name={'logo-usd'}/>
),
};
constructor(props) {
super(props)
this.state = {
active: false,
selected: undefined,
data: [
{
title: "ABC",
price: 12000
}
],
index: 0,
routes: 'Lead In',
};
}
onSave() {
}
onValueChange(value) {
this.setState({
selected: value
});
}
render() {
const {routes} = this.state
return (
<Container style={styles.container}>
<Header style={styles.header}>
<Left>
<Icon name="arrow-backward" style={[styles.xxlarge, {color: '#fafafa', left: 10}]}/>
</Left>
<Body>
<Text style={[styles.xlarge, {color: '#fafafa'}]}>Add Deal</Text>
</Body>
<Right>
<TouchableOpacity onPress={this.onSave} style={{right: 10}}>
<Text style={[styles.large, {color: '#fafafa'}]}>SAVE</Text>
</TouchableOpacity>
</Right>
</Header>
<Content>
<View style={{height: height, padding : 15}}>
<Text>List Person</Text>
</View>
</Content>
</Container>
);
}
}
export default Home;
|
$(function() {
var $instance = $('.album a').imageLightbox({
onStart: function() {
$('<div id="imagelightbox-overlay"></div>').appendTo('body');
$('<a href="#" id="imagelightbox-close">x</a>').appendTo('body').on('click touchend', function() {
$(this).remove();
$instance.quitImageLightbox();
return false;
});
},
onEnd: function() {
$('#imagelightbox-overlay').remove();
$('#imagelightbox-caption').remove();
$('#imagelightbox-close').remove();
//$('#imagelightbox-loading').remove();
},
onLoadStart: function() {
$('#imagelightbox-caption').remove();
//$('<div id="imagelightbox-loading"><div></div></div>').appendTo('body');
},
onLoadEnd: function() {
var description = $('a[href="' + $('#imagelightbox').attr('src') + '"] img').attr('alt');
if (description.length > 0) {
$('<div id="imagelightbox-caption">' + description + '</div>').appendTo('body');
}
//$('#imagelightbox-loading').remove();
}
});
}); |
const form = document.getElementById("form");
form.addEventListener("submit", function(e) {
let succes = errorCallback();
if(succes){
}
else{
e.preventDefault();
}
});
function errorCallback(){
const fname = document.getElementById("fname");
const lname = document.getElementById("lname");
const mail = document.getElementById("mail");
const password = document.getElementById("password");
if(fname.value == ""){
const imgFname = document.getElementById("imgFname");
const pFname = document.getElementById("pFname");
fname.style.border = "2px solid hsl(0, 100%, 74%)";
imgFname.style.opacity = "1";
pFname.style.opacity = "1";
}else{
fname.style.border = "1px solid hsl(240, 6%, 91%)";
imgFname.style.opacity = "0";
pFname.style.opacity = "0";
}
if(lname.value == ""){
const imgLname = document.getElementById("imgLname");
const pLname = document.getElementById("pLname");
lname.style.border = "2px solid hsl(0, 100%, 74%)";
imgLname.style.opacity = "1";
pLname.style.opacity = "1";
}else{
lname.style.border = "1px solid hsl(240, 6%, 91%)";
imgLname.style.opacity = "0";
pLname.style.opacity = "0";
}
const mailik = mail.value.toString();
if(mail.value == "" || !mailik.includes("@")){
const imgMail = document.getElementById("imgMail");
const pMail = document.getElementById("pMail");
mail.style.border = "2px solid hsl(0, 100%, 74%)";
imgMail.style.opacity = "1";
pMail.style.opacity = "1";
}else{
mail.style.border = "1px solid hsl(240, 6%, 91%)";
imgMail.style.opacity = "0";
pMail.style.opacity = "0";
}
if(password.value == ""){
const imgPassword = document.getElementById("imgPassword");
const pPassword = document.getElementById("pPassword");
password.style.border = "2px solid hsl(0, 100%, 74%)";
imgPassword.style.opacity = "1";
pPassword.style.opacity = "1";
}else{
password.style.border = "1px solid hsl(240, 6%, 91%)";
imgPassword.style.opacity = "0";
pPassword.style.opacity = "0";
}
if(password.value == "" || mail.value == "" || !mailik.includes("@") || lname.value == "" || fname.value == ""){
return false;
}else{
return true;
}
} |
import { createGlobalStyle } from 'styled-components';
const GlobalStyle = createGlobalStyle`
:root {
--primary: #337ab7;
--success: #5cb85c;
--info: #5bc0de;
--warning: #f0ad4e;
--danger: #d9534f;
--gray-darker: #222;
--gray-dark: #333;
--gray: #555;
--gray-light: #777;
--gray-lighter: #eee;
--facebook: #3b5998;
--google: #ea4335;
--github: var(--gray-dark);
--cb-blue: #4285F4;
--cb-green: #00D490;
--cb-yellow: #FFCF50;
--cb-red: #DA5847;
}
html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 80px;
margin: 0;
padding: 0;
font-size: 14px;
line-height: 20px;
}
body.isViewDocument {
padding-top: 20px;
}
body.isViewDocument .navbar {
display: none;
}
.navbar {
border-radius: 0;
border-left: none;
border-right: none;
border-top: none;
}
form label {
display: block;
}
form .control-label {
display: block;
margin-bottom: 7px;
}
form label.error {
display: block;
margin-top: 8px;
font-size: 13px;
font-weight: normal;
color: var(--danger);
}
.page-header {
margin-top: 0;
}
.table tr td {
vertical-align: middle !important;
}
/* Removes unnecessary bottom padding on .container */
body > #react-root > div > .container {
padding-bottom: 0;
}
@media screen and (min-width: 768px) {
body.isViewDocument {
padding-top: 40px;
}
.page-header {
margin-top: 20px;
}
}
`;
export default GlobalStyle;
|
import DataSourceAdapter from '../grid_core/ui.grid_core.data_source_adapter';
var dataSourceAdapterType = DataSourceAdapter;
export default {
extend: function extend(extender) {
dataSourceAdapterType = dataSourceAdapterType.inherit(extender);
},
create: function create(component) {
return new dataSourceAdapterType(component);
}
}; |
module.exports = {
index: -1,
position: [0, 0],
onMessage: function(message) {
this.commands.moveTo.call(this, [message.target[0] + message.shape[this.index][0] * message.scale, message.target[1] + message.shape[this.index][1] * message.scale]);
},
commands: {
moveTo: function(pos) {
console.log(this.index, pos)
}
}
}
|
fetch("./data.json")
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log("error: " + err);
});
function appendData(data) {
obj = data;
console.log(data)
for (var i = 0; i < obj.length; i++) {
var fullName = obj[i]["fullName"]
var userName = obj[i]["userName"]
var email = obj[i]["email"]
var totalPoints = obj[i]["totalPoints"]
var tableRef = document.getElementById("userDataBody")
var row = tableRef.insertRow(i);
row.insertCell(0).innerHTML = fullName;
row.insertCell(1).innerHTML = userName;
row.insertCell(2).innerHTML = email;
row.insertCell(3).innerHTML = totalPoints;
}
}
// console.log(object)
|
const cards = {};
/******************************************************************************/
cards.albums = {};
cards.albums.drag_start =
function drag_start(event)
{
const album_card = event.target.closest(".album_card");
event.dataTransfer.setData("text/plain", album_card.id);
}
cards.albums.drag_end =
function drag_end(event)
{
}
cards.albums.drag_over =
function drag_over(event)
{
event.preventDefault();
}
cards.albums.drag_drop =
function drag_drop(event)
{
const child = document.getElementById(event.dataTransfer.getData("text"));
const child_id = child.dataset.id;
const parent = event.currentTarget;
const parent_id = parent.dataset.id;
event.dataTransfer.clearData();
if (child_id == parent_id)
{
return;
}
let prompt;
if (parent_id === "root")
{
const child_title = child.querySelector('.album_card_title').textContent.trim();
prompt = `Remove child\n${child_title}?`;
}
else
{
const child_title = child.querySelector('.album_card_title').textContent.trim();
const parent_title = parent.querySelector('.album_card_title').textContent.trim();
prompt = `Move\n${child_title}\ninto\n${parent_title}?`;
}
if (! confirm(prompt))
{
return;
}
if (parent_id === "root")
{
api.albums.remove_child(ALBUM_ID, child_id, common.refresh_or_alert);
}
else if (ALBUM_ID)
{
api.albums.add_child(parent_id, child_id, null);
api.albums.remove_child(ALBUM_ID, child_id, common.refresh_or_alert);
}
else
{
api.albums.add_child(parent_id, child_id, common.refresh_or_alert);
}
}
/******************************************************************************/
cards.bookmarks = {};
cards.bookmarks.create =
function create(bookmark, add_author, add_delete_button, add_url_element)
{
const bookmark_card = document.createElement("div");
bookmark_card.className = "bookmark_card"
bookmark_card.dataset.id = bookmark.id;
const h2 = document.createElement("h2");
const bookmark_title = document.createElement("a");
bookmark_title.className = "bookmark_title";
bookmark_title.href = bookmark.url;
bookmark_title.innerText = bookmark.display_name;
h2.appendChild(bookmark_title);
bookmark_card.appendChild(h2);
// The URL element is always display:none, but its presence is useful in
// facilitating the Editor object. If this bookmark will not be editable,
// there is no need for it.
if (add_url_element)
{
const bookmark_url = document.createElement("a");
bookmark_url.className = "bookmark_url";
bookmark_url.href = bookmark.url;
bookmark_url.innerText = bookmark.url;
bookmark_card.appendChild(bookmark_url);
}
// If more tools are added, this will become an `or`.
// I just want to have the structure in place now.
if (add_delete_button)
{
const bookmark_toolbox = document.createElement("div");
bookmark_toolbox.className = "bookmark_toolbox"
bookmark_card.appendChild(bookmark_toolbox);
if (add_delete_button)
{
const delete_button = document.createElement("button");
delete_button.className = "red_button button_with_confirm";
delete_button.dataset.onclick = "return delete_bookmark_form(event);";
delete_button.dataset.prompt = "Delete Bookmark?";
delete_button.dataset.cancelClass = "gray_button";
delete_button.innerText = "Delete";
bookmark_toolbox.appendChild(delete_button);
common.init_button_with_confirm(delete_button);
}
}
return bookmark_card;
}
/******************************************************************************/
cards.photos = {};
cards.photos.MIMETYPE_THUMBNAILS = {
"svg": "svg",
"application/zip": "archive",
"application/x-tar": "archive",
"archive": "archive",
"audio": "audio",
"image": "image",
"video": "video",
"text": "txt",
};
cards.photos.file_link =
function file_link(photo, short)
{
if (short)
{
return `/photo/${photo.id}/download/${photo.id}${photo.dot_extension}`;
}
const basename = escape(photo.filename);
return `/photo/${photo.id}/download/${basename}`;
}
cards.photos.create =
function create(photo, view)
{
if (view !== "list" && view !== "grid")
{
view = "grid";
}
const photo_card = document.createElement("div");
photo_card.id = `photo_card_${photo.id}`;
photo_card.dataset.id = photo.id;
photo_card.className = `photo_card photo_card_${view} photo_card_unselected`
if (photo.searchhidden)
{
photo_card.classList.add("photo_card_searchhidden");
}
photo_card.ondragstart = "return cards.photos.drag_start(event);";
photo_card.ondragend = "return cards.photos.drag_end(event);";
photo_card.ondragover = "return cards.photos.drag_over(event);";
photo_card.ondrop = "return cards.photos.drag_drop(event);";
photo_card.draggable = true;
const photo_card_filename = document.createElement("div");
photo_card_filename.className = "photo_card_filename";
const filename_link = document.createElement("a");
filename_link.href = `/photo/${photo.id}`;
filename_link.draggable = false;
filename_link.innerText = photo.filename;
photo_card_filename.appendChild(filename_link);
photo_card.appendChild(photo_card_filename);
const photo_card_metadata = document.createElement("span");
photo_card_metadata.className = "photo_card_metadata";
const metadatas = [];
if (photo.width)
{
metadatas.push(`${photo.width}×${photo.height}`);
}
if (photo.duration)
{
metadatas.push(`${photo.duration_string}`);
}
photo_card_metadata.innerHTML = common.join_and_trail(metadatas, ", ");
const filesize_file_link = document.createElement("a");
filesize_file_link.href = cards.photos.file_link(photo);
filesize_file_link.target = "_blank";
filesize_file_link.draggable = false;
filesize_file_link.innerText = photo.bytes_string;
photo_card_metadata.append(filesize_file_link);
photo_card.appendChild(photo_card_metadata);
if (view == "grid")
{
let thumbnail_src;
if (photo.has_thumbnail)
{
thumbnail_src = `/photo/${photo.id}/thumbnail/${photo.id}.jpg`;
}
else
{
thumbnail_src =
cards.photos.MIMETYPE_THUMBNAILS[photo.extension] ||
cards.photos.MIMETYPE_THUMBNAILS[photo.mimetype] ||
cards.photos.MIMETYPE_THUMBNAILS[photo.simple_mimetype] ||
"other";
thumbnail_src = `/static/basic_thumbnails/${thumbnail_src}.png`;
}
const photo_card_thumbnail = document.createElement("a");
photo_card_thumbnail.className = "photo_card_thumbnail";
photo_card_thumbnail.target = "_blank";
photo_card_thumbnail.href = `/photo/${photo.id}`;
photo_card_thumbnail.draggable = false;
const thumbnail_img = document.createElement("img");
thumbnail_img.loading = "lazy";
thumbnail_img.src = thumbnail_src;
thumbnail_img.draggable = false;
photo_card_thumbnail.appendChild(thumbnail_img);
photo_card.appendChild(photo_card_thumbnail);
}
let tag_names_title = [];
let tag_names_inner = "";
for (const tag of photo.tags)
{
tag_names_title.push(tag.name);
tag_names_inner = "T";
}
const photo_card_tags = document.createElement("span");
photo_card_tags.className = "photo_card_tags";
photo_card_tags.title = tag_names_title.join(",");
photo_card_tags.innerText = tag_names_inner;
photo_card.appendChild(photo_card_tags);
if (window.photo_clipboard !== undefined)
{
const clipboard_checkbox = photo_clipboard.give_checkbox(photo_card);
photo_clipboard.apply_check(clipboard_checkbox);
}
return photo_card;
}
cards.photos.drag_start =
function drag_start(event)
{
}
cards.photos.drag_end =
function drag_end(event)
{
}
cards.photos.drag_over =
function drag_over(event)
{
}
cards.photos.drag_drop =
function drag_drop(event)
{
}
cards.photos.photo_contextmenu = null;
cards.photos.set_contextmenu =
function set_contextmenu(element, build_function)
{
element.classList.add("photo_card_contextmenu");
element.classList.add("contextmenu");
element.onclick = "event.stopPropagation(); return;";
cards.photos.photo_contextmenu = element;
cards.photos.build_photo_contextmenu = build_function;
contextmenus.hide_open_menus();
}
cards.photos.right_clicked_photo = null;
cards.photos.photo_rightclick =
function photo_rightclick(event)
{
if (["A", "IMG"].includes(event.target.tagName))
{
return true;
}
if (cards.photos.photo_contextmenu === null)
{
return true;
}
if (event.ctrlKey || event.shiftKey || event.altKey)
{
return true;
}
const photo_card = event.target.closest(".photo_card");
if (! photo_card)
{
cards.photos.right_clicked_photo = null;
contextmenus.hide_open_menus();
return true;
}
if (contextmenus.menu_is_open())
{
contextmenus.hide_open_menus();
}
cards.photos.right_clicked_photo = photo_card;
const menu = cards.photos.photo_contextmenu;
cards.photos.build_photo_contextmenu(photo_card, menu);
setTimeout(() => {contextmenus.show_menu(event, menu);}, 0);
event.stopPropagation();
event.preventDefault();
return false;
}
/******************************************************************************/
cards.tags = {};
|
var rest = require('../API/RestClient');
exports.displayFavouriteMusic = function getFavouriteMusic(session, username){
var url = 'https://foodchatbotmsa.azurewebsites.net/tables/m_mBot';
rest.getFavouriteMusic(url, session, username, handleFavouriteMusicResponse)
};
function handleFavouriteMusicResponse(message, session, username) {
var favouriteMusicResponse = JSON.parse(message);
var allMusic = [];
for (var index in favouriteMusicResponse) {
var usernameReceived = favouriteMusicResponse[index].username;
var favouriteMusic = favouriteMusicResponse[index].favouriteMusic;
//Convert to lower case whilst doing comparison to ensure the user can type whatever they like
if (username.toLowerCase() === usernameReceived.toLowerCase()) {
//Add a comma after all favourite foods unless last one
if(favouriteMusicResponse.length - 1) {
allMusic.push(favouriteMusic);
}
else {
allMusic.push(favouriteMusic + ', ');
}
}
}
// Print all favourite foods for the user that is currently logged in
session.send("%s, your favourite music are: %s", username, allMusic);
}
exports.deleteFavouriteMusic = function deleteFavouriteMusic(session,username,favouriteMusic){
var url = 'https://foodchatbotmsa.azurewebsites.net/tables/m_mBot';
rest.getFavouriteMusic(url,session, username,function(message,session,username){
var allMusic = JSON.parse(message);
for(var i in allMusic) {
if (allMusic[i].favouriteMusic === favouriteMusic && allMusic[i].username === username) {
console.log(allMusic[i]);
rest.deleteFavouriteMusic(url,session,username,favouriteMusic, allMusic[i].id ,handleDeletedMusicResponse)
}
}
});
};
function handleDeletedMusicResponse(body,session,username, favouriteMusic) {
console.log('Done');
}
exports.sendFavouriteMusic = function postFavouriteMusic(session, username, favouriteMusic){
var url = 'https://foodchatbotmsa.azurewebsites.net/tables/m_mBot';
rest.postFavouriteMusic(url, username, favouriteMusic);
}; |
//PROMISES ARE USED IN THE EXECUTION OF ASYNCHRONOUS CODE TO AVOID CALL BACK HELL.
// I.E THEY ARE USED IN CALLING REQUESTS FROMT HE SERVER
//FOR MORE EXPLANATION SEE THE REGISTER IN WHICH IT IS WRITTEN.
/*
const test = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve('hello')
},2000)
})
test
.then(a_value=>{
console.log(a_value) // AFTER TWO SECS hello IS PRINTED.
})
*/
const recIDs = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve([123,234,23])
},1500)
})// recIDs NOW RETURN [123,234,23]
const recipe = (recID)=>{
return new Promise((resolve,reject)=>{
setTimeout(ID=>{
resolve(`${ID}:Tomatoes and Potatoes`)
},1500,recID)
})
}// recipe IS A FUNCTION WHICH RETURNS A PROMISE
recIDs
.then(id=>{
console.log(id)
return recipe(id[1])
})
.then(rec=>{
console.log(rec)
})
.catch(console.log('ERROR!!')) |
const ApiConstants = {
loginUrl: (hostUri, redirectUri) => {
return `${hostUri}/oauth2/authorize/twitch?redirect_uri=${redirectUri}`;
},
websocketUrl: (hostUri) => {
return `${hostUri}/ws`;
}
};
export default ApiConstants;
|
import axios from 'axios'
// initial state
const state = {
booksList : {books:[], error:null, loading:false},
newBook: {book:null, error:null, loading:false},
activeBook : {book:null, error:null, loading:false, updated:false},
deletedBooks : {books:[], error:null, loading:false},
filterBook : ''
}
// getters
const getters = {}
// actions
const actions = {
getAllBooks ({ commit }) {
commit('FETCH_BOOKS');
axios
.get('book/fetch')
.then(response => commit('FETCH_BOOKS_SUCCESS', response.data))
.catch(error => commit('FETCH_BOOKS_FAILURE', error))
},
getBookByID ({ commit }, book_id) {
commit('FETCH_BOOK');
axios
.get('book/fetch/' + book_id)
.then(response => {
commit('FETCH_BOOK_SUCCESS', response.data);
})
.catch(error => commit('FETCH_BOOK_FAILURE', error))
},
addBook ({ commit, dispatch }, book) {
commit('ADD_BOOK');
axios
.post('book/add', {
book_name : book.book_name,
book_desc : book.book_desc
})
.then(response => {
commit('ADD_BOOK_SUCCESS', response.data);
dispatch('getAllBooks');
})
.catch(error => commit('ADD_BOOK_FAILURE', error))
},
saveBook ({ commit, dispatch }, book) {
commit('SAVE_BOOK');
axios
.post('book/save', {
book_id : book.book_id,
book_name : book.book_name,
book_desc : book.book_desc
})
.then(response => {
commit('SAVE_BOOK_SUCCESS', response.data);
dispatch('getAllBooks')
})
.catch(error => commit('SAVE_BOOK_FAILURE', error))
},
removeBooks ({ commit, dispatch }, book_ids) {
commit('REMOVE_BOOKS')
axios
.post('book/remove', {
book_ids : book_ids
})
.then(response => {
commit('REMOVE_BOOKS_SUCCESS', response.data);
dispatch('getAllBooks')
})
.catch(error => commit('REMOVE_BOOKS_FAILURE', error))
}
}
// mutations
const mutations = {
FETCH_BOOKS(state) {
state.booksList = {books:[], error:null, loading: true}},
FETCH_BOOKS_SUCCESS(state, payload){
state.booksList = {books: payload, error:null, loading: false}},
FETCH_BOOKS_FAILURE(state, payload){
state.booksList = {books: [], error : payload, loading: false}},
RESET_BOOKS(state){
state.booksList = {books:[], error:null, loading: false}},
ADD_BOOK(state){
state.newBook = {book:null, error:null, loading: true}},
ADD_BOOK_SUCCESS(state, payload){
state.newBook = {book:payload, error:null, loading: false}},
ADD_BOOK_FAILURE(state, payload){
state.newBook = {book:null, error:payload, loading: false}},
RESET_ADD_BOOK(state){
state.newBook = {book:null, error:null, loading: false}},
FETCH_BOOK(state){
state.activeBook = {book:null, error:null, loading: true, updated:false}},
FETCH_BOOK_SUCCESS(state, payload){
state.activeBook = {book:payload, error:null, loading: false}},
FETCH_BOOK_FAILURE(state, payload){
state.activeBook = {book:null, error:payload, loading: false}},
RESET_FETCH_BOOK(state){
state.activeBook = {book:null, error:null, loading: false,updated:false}},
SAVE_BOOK(state){
state.activeBook = {book:null, error:null, loading: true, updated:false}},
SAVE_BOOK_SUCCESS(state, payload){
state.activeBook = {book:payload, error:null, loading: false, updated:true}},
SAVE_BOOK_FAILURE(state, payload){
state.activeBook = {book:null, error:payload, loading: false, updated:false}},
RESET_SAVE_BOOK(state){
state.activeBook = {book:null, error:null, loading: false, updated:false}},
REMOVE_BOOKS(state){
state.deletedBooks = {books:[], error:null, loading: true}},
REMOVE_BOOKS_SUCCESS(state, payload){
state.deletedBooks = {books:payload, error:null, loading: false}},
REMOVE_BOOKS_FAILURE(state, payload){
state.deletedBooks = {books:[], error:payload, loading: false}},
RESET_REMOVE_BOOKS(state){
state.deletedBooks = {books:[], error:null, loading: false}},
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
} |
import React, { Component } from "react";
import ArrowDown from "components/Icons/ArrowDown";
import ArrowUp from "components/Icons/ArrowUp";
import { Typography, ArrowDownIcon, ArrowUpIcon } from "components";
import { map } from "lodash";
import { formatCurrency } from '../../utils/numberFormatation';
import { connect } from "react-redux";
import { getApp } from "../../lib/helpers";
import { setCurrencyView } from "../../redux/actions/currency";
import Tooltip from '@material-ui/core/Tooltip';
import { withStyles } from "@material-ui/core/styles";
import { getAppCustomization, getIcon } from "../../lib/helpers";
import _ from 'lodash';
import "./index.css";
const defaultProps = {
currencies : [],
currency : {},
open: false
}
class CurrencySelector extends Component {
constructor(props) {
super(props);
this.state = { ...defaultProps };
}
componentDidMount(){
this.projectData(this.props);
}
componentWillReceiveProps(props){
this.projectData(props);
}
componentDidUpdate() {
const { open } = this.state;
if (open) {
document.addEventListener("mousedown", this.handleClickOutside);
} else {
document.removeEventListener("mousedown", this.handleClickOutside);
}
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
projectData = async (props) => {
const { profile, currency } = props;
const virtual = getApp().virtual;
var currencies = getApp().currencies.filter(c => c.virtual === virtual);
if(!currencies || _.isEmpty(currencies) || currencies.length < 0){return}
currencies = currencies.map(
c => {
const w = profile.getWallet({currency : c});
const wApp = getApp().wallet.find(w => w.currency._id === c._id);
return {
...c,
balance : _.isEmpty(w) ? 0 : w.playBalance,
image : _.isEmpty(wApp.image) ? c.image : wApp.image
}
}
);
this.setState({
currencies,
currency : !_.isEmpty(currency) ? currency : currencies[0]
})
}
getOptions = () => {
const { profile } = this.props;
let { currencies } = this.state;
if(!currencies || _.isEmpty(currencies) || currencies.length < 0){return}
currencies = currencies.map(
c => {
const w = profile.getWallet({currency : c});
return {
value: c._id,
label: _.isEmpty(w) ? 0 : w.bonusAmount > 0 ? formatCurrency(w.playBalance + w.bonusAmount) : formatCurrency(w.playBalance),
icon: c.image,
currency: c
}
}
)
return currencies;
};
handleClickOutside = event => {
const isOutsideClick = !this.optionsRef.contains(event.target);
const isLabelClick = this.labelRef.contains(event.target);
if (isOutsideClick && !isLabelClick) {
this.setState({ open: false });
}
};
handleLabelClick = () => {
const { open } = this.state;
this.setState({ open: !open });
};
renderLabel() {
const { open, currency } = this.state;
const { profile } = this.props;
if (_.isEmpty(currency)) return null;
const w = profile.getWallet({ currency });
const balanceWithBonus = profile.getBalanceWithBonus({ currency });
const wApp = getApp().wallet.find(w => w.currency._id === currency._id);
const icon = _.isEmpty(wApp.image) ? currency.image : wApp.image;
const skin = getAppCustomization().skin.skin_type;
const { colors } = getAppCustomization();
const secondaryColor = colors.find(({ type }) => type == "secondaryColor")
const SecondaryTooltip = withStyles({
tooltip: {
color: "white",
backgroundColor: secondaryColor.hex
}
})(Tooltip);
const arrowUpIcon = getIcon(24);
const arrowDownIcon = getIcon(25);
return (
w.bonusAmount > 0
?
<SecondaryTooltip title={`Bonus: ${formatCurrency(w.bonusAmount)}`}>
<div styleName="label">
<div styleName="currency-icon">
<img src={icon} width={20}/>
</div>
<span>
<Typography color="white" variant={'small-body'}>{formatCurrency(balanceWithBonus)}</Typography>
</span>
{open
?
arrowUpIcon === null ? skin == "digital" ? <ArrowUpIcon /> : <ArrowUp /> : <img src={arrowUpIcon} />
:
arrowDownIcon === null ?skin == "digital" ? <ArrowDownIcon /> : <ArrowDown /> : <img src={arrowDownIcon} />
}
</div>
</SecondaryTooltip>
:
<div styleName="label">
<div styleName="currency-icon">
<img src={icon} width={20}/>
</div>
<span>
<Typography color="white" variant={'small-body'}>{formatCurrency(w.playBalance)}</Typography>
</span>
{open
?
arrowUpIcon === null ? skin == "digital" ? <ArrowUpIcon /> : <ArrowUp /> : <img src={arrowUpIcon} />
:
arrowDownIcon === null ?skin == "digital" ? <ArrowDownIcon /> : <ArrowDown /> : <img src={arrowDownIcon} />
}
</div>
);
}
renderOptionsLines = () => {
return map(this.getOptions(), ({ value, label, icon, currency }) => (
<button
styleName="option"
key={value}
id={value}
onClick={()=>this.changeCurrency(currency)}
type="button"
>
<div styleName="currency-icon">
<img src={icon} width={20}/>
</div>
<Typography variant="small-body" color="white">{label}</Typography>
</button>
));
};
renderOptions() {
const { open } = this.state;
if (!open) return null;
return (
<div styleName="options">
<span styleName="triangle" />
{this.renderOptionsLines()}
</div>
);
}
changeCurrency = async (item) => {
await this.props.dispatch(setCurrencyView(item));
this.setState({...this.state, currency : item, open : false})
}
render() {
return (
<div styleName="root">
<button
ref={el => {
this.labelRef = el;
}}
onClick={this.handleLabelClick}
type="button">
{this.renderLabel()}
</button>
<div
ref={el => {
this.optionsRef = el;
}}>
{this.renderOptions()}
</div>
</div>
);
}
}
function mapStateToProps(state){
return {
profile : state.profile,
ln: state.language,
currency : state.currency
};
}
export default connect(mapStateToProps)(CurrencySelector); |
import domAdapter from '../../core/dom_adapter';
import { isDefined, isFunction } from '../../core/utils/type';
import { Tooltip } from '../core/tooltip';
import { extend } from '../../core/utils/extend';
import { patchFontOptions } from './utils';
import { Plaque } from './plaque';
import pointerEvents from '../../events/pointer';
import { start as dragEventStart, move as dragEventMove, end as dragEventEnd } from '../../events/drag';
import { addNamespace } from '../../events/utils/index';
import eventsEngine from '../../events/core/events_engine';
var getDocument = domAdapter.getDocument;
var EVENT_NS = 'annotations';
var DOT_EVENT_NS = '.' + EVENT_NS;
var POINTER_ACTION = addNamespace([pointerEvents.down, pointerEvents.move], EVENT_NS);
var POINTER_UP_EVENT_NAME = addNamespace(pointerEvents.up, EVENT_NS);
var DRAG_START_EVENT_NAME = dragEventStart + DOT_EVENT_NS;
var DRAG_EVENT_NAME = dragEventMove + DOT_EVENT_NS;
var DRAG_END_EVENT_NAME = dragEventEnd + DOT_EVENT_NS;
function coreAnnotation(options, contentTemplate) {
return {
draw: function draw(widget, group) {
var annotationGroup = widget._renderer.g().append(group).css(patchFontOptions(options.font));
if (this.plaque) {
this.plaque.clear();
}
this.plaque = new Plaque(extend(true, {}, options, {
cornerRadius: (options.border || {}).cornerRadius
}), widget, annotationGroup, contentTemplate, widget._isAnnotationBounded(options));
this.plaque.draw(widget._getAnnotationCoords(this));
if (options.allowDragging) {
annotationGroup.on(DRAG_START_EVENT_NAME, {
immediate: true
}, e => {
this._dragOffsetX = this.plaque.x - e.pageX;
this._dragOffsetY = this.plaque.y - e.pageY;
}).on(DRAG_EVENT_NAME, e => {
this.plaque.move(e.pageX + this._dragOffsetX, e.pageY + this._dragOffsetY);
}).on(DRAG_END_EVENT_NAME, e => {
this.offsetX = (this.offsetX || 0) + e.offset.x;
this.offsetY = (this.offsetY || 0) + e.offset.y;
});
}
},
hitTest(x, y) {
return this.plaque.hitTest(x, y);
},
showTooltip(tooltip, _ref) {
var {
x,
y
} = _ref;
var that = this;
var options = that.options;
if (tooltip.annotation !== that) {
tooltip.setTemplate(options.tooltipTemplate);
var callback = result => {
result && (tooltip.annotation = that);
};
callback(tooltip.show(options, {
x,
y
}, {
target: options
}, options.customizeTooltip, callback));
} else {
if (!tooltip.isCursorOnTooltip(x, y)) {
tooltip.move(x, y);
}
}
}
};
}
function getTemplateFunction(options, widget) {
var template;
if (options.type === 'text') {
template = function template(item, groupElement) {
var text = widget._renderer.text(item.text).attr({
'class': item.cssClass
}).append({
element: groupElement
});
if (item.width > 0 || item.height > 0) {
text.setMaxSize(item.width, item.height, {
wordWrap: item.wordWrap,
textOverflow: item.textOverflow
});
}
};
} else if (options.type === 'image') {
template = function template(item, groupElement) {
var {
width,
height,
url,
location
} = item.image || {};
var {
width: outerWidth,
height: outerHeight
} = item;
var imageWidth = outerWidth > 0 ? Math.min(width, outerWidth) : width;
var imageHeight = outerHeight > 0 ? Math.min(height, outerHeight) : height;
widget._renderer.image(0, 0, imageWidth, imageHeight, url, location || 'center').append({
element: groupElement
});
};
} else if (options.type === 'custom') {
template = options.template;
}
return template;
}
function getImageObject(image) {
return typeof image === 'string' ? {
url: image
} : image;
}
export var createAnnotations = function createAnnotations(widget, items) {
var commonAnnotationSettings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var customizeAnnotation = arguments.length > 3 ? arguments[3] : undefined;
var pullOptions = arguments.length > 4 ? arguments[4] : undefined;
var commonImageOptions = getImageObject(commonAnnotationSettings.image);
return items.reduce((arr, item) => {
var currentImageOptions = getImageObject(item.image);
var customizedItem = isFunction(customizeAnnotation) ? customizeAnnotation(item) : {};
if (customizedItem) {
customizedItem.image = getImageObject(customizedItem.image); // T881143
}
var options = extend(true, {}, commonAnnotationSettings, item, {
image: commonImageOptions
}, {
image: currentImageOptions
}, customizedItem);
var templateFunction = getTemplateFunction(options, widget);
var annotation = templateFunction && extend(true, pullOptions(options), coreAnnotation(options, widget._getTemplate(templateFunction)));
annotation && arr.push(annotation);
return arr;
}, []);
};
var chartPlugin = {
name: 'annotations_chart',
init() {},
dispose() {},
members: {
_getAnnotationCoords(annotation) {
var _axis, _axis2;
var coords = {
offsetX: annotation.offsetX,
offsetY: annotation.offsetY
};
var argCoordName = this._options.silent('rotated') ? 'y' : 'x';
var valCoordName = this._options.silent('rotated') ? 'x' : 'y';
var argAxis = this.getArgumentAxis();
var argument = argAxis.validateUnit(annotation.argument);
var axis = this.getValueAxis(annotation.axis);
var series;
var pane = (_axis = axis) === null || _axis === void 0 ? void 0 : _axis.pane;
if (annotation.series) {
var _series;
series = this.series.filter(s => s.name === annotation.series)[0];
axis = (_series = series) === null || _series === void 0 ? void 0 : _series.getValueAxis();
isDefined(axis) && (pane = axis.pane);
}
if (isDefined(argument)) {
if (series) {
var center = series.getPointCenterByArg(argument);
center && (coords[argCoordName] = center[argCoordName]);
} else {
coords[argCoordName] = argAxis.getTranslator().translate(argument);
}
!isDefined(pane) && (pane = argAxis.pane);
}
var value = (_axis2 = axis) === null || _axis2 === void 0 ? void 0 : _axis2.validateUnit(annotation.value);
if (isDefined(value)) {
var _axis3;
coords[valCoordName] = (_axis3 = axis) === null || _axis3 === void 0 ? void 0 : _axis3.getTranslator().translate(value);
!isDefined(pane) && isDefined(axis) && (pane = axis.pane);
}
coords.canvas = this._getCanvasForPane(pane);
if (isDefined(coords[argCoordName]) && !isDefined(value)) {
var _series2;
if (!isDefined(axis) && !isDefined(series)) {
coords[valCoordName] = argAxis.getAxisPosition();
} else if (isDefined(axis) && !isDefined(series)) {
coords[valCoordName] = this._argumentAxes.filter(a => a.pane === axis.pane)[0].getAxisPosition();
} else if ((_series2 = series) !== null && _series2 !== void 0 && _series2.checkSeriesViewportCoord(argAxis, coords[argCoordName])) {
coords[valCoordName] = series.getSeriesPairCoord(coords[argCoordName], true);
}
}
if (!isDefined(argument) && isDefined(coords[valCoordName])) {
if (isDefined(axis) && !isDefined(series)) {
coords[argCoordName] = axis.getAxisPosition();
} else if (isDefined(series)) {
if (series.checkSeriesViewportCoord(axis, coords[valCoordName])) {
coords[argCoordName] = series.getSeriesPairCoord(coords[valCoordName], false);
}
}
}
return coords;
},
_annotationsPointerEventHandler(event) {
if (this._disposed) {
return;
}
var originalEvent = event.originalEvent || {};
var touch = originalEvent.touches && originalEvent.touches[0] || {};
var rootOffset = this._renderer.getRootOffset();
var coords = {
x: touch.pageX || originalEvent.pageX || event.pageX,
y: touch.pageY || originalEvent.pageY || event.pageY
};
var annotation = this._annotations.items.filter(a => a.hitTest(coords.x - rootOffset.left, coords.y - rootOffset.top))[0];
if (!annotation || !annotation.options.tooltipEnabled) {
this._annotations.hideTooltip();
return;
}
this._clear();
if (annotation.options.allowDragging && event.type === pointerEvents.down) {
this._annotations._hideToolTipForDrag = true;
}
if (!this._annotations._hideToolTipForDrag) {
annotation.showTooltip(this._annotations.tooltip, coords);
event.stopPropagation();
}
},
_isAnnotationBounded(options) {
return isDefined(options.value) || isDefined(options.argument);
},
_pullOptions(options) {
return {
type: options.type,
name: options.name,
x: options.x,
y: options.y,
value: options.value,
argument: options.argument,
axis: options.axis,
series: options.series,
options: options,
offsetX: options.offsetX,
offsetY: options.offsetY
};
},
_forceAnnotationRender() {
this._change(['FORCE_RENDER']);
},
_clear() {
this.hideTooltip();
this.clearHover();
}
}
};
var polarChartPlugin = {
name: 'annotations_polar_chart',
init() {},
dispose() {},
members: {
_getAnnotationCoords(annotation) {
var coords = {
offsetX: annotation.offsetX,
offsetY: annotation.offsetY,
canvas: this._calcCanvas()
};
var argAxis = this.getArgumentAxis();
var argument = argAxis.validateUnit(annotation.argument);
var value = this.getValueAxis().validateUnit(annotation.value);
var radius = annotation.radius;
var angle = annotation.angle;
var pointCoords;
var series;
if (annotation.series) {
series = this.series.filter(s => s.name === annotation.series)[0];
}
extend(true, coords, this.getXYFromPolar(angle, radius, argument, value));
if (isDefined(series)) {
if (isDefined(coords.angle) && !isDefined(value) && !isDefined(radius)) {
if (!isDefined(argument)) {
argument = argAxis.getTranslator().from(isFinite(angle) ? this.getActualAngle(angle) : coords.angle);
}
pointCoords = series.getSeriesPairCoord({
argument,
angle: -coords.angle
}, true);
} else if (isDefined(coords.radius) && !isDefined(argument) && !isDefined(angle)) {
pointCoords = series.getSeriesPairCoord({
radius: coords.radius
}, false);
}
if (isDefined(pointCoords)) {
coords.x = pointCoords.x;
coords.y = pointCoords.y;
}
}
if (annotation.series && !isDefined(pointCoords)) {
coords.x = coords.y = undefined;
}
return coords;
},
_annotationsPointerEventHandler: chartPlugin.members._annotationsPointerEventHandler,
_isAnnotationBounded: chartPlugin.members._isAnnotationBounded,
_pullOptions(options) {
var polarOptions = extend({}, {
radius: options.radius,
angle: options.angle
}, chartPlugin.members._pullOptions(options));
delete polarOptions.axis;
return polarOptions;
},
_forceAnnotationRender: chartPlugin.members._forceAnnotationRender,
_clear: chartPlugin.members._clear
}
};
var vectorMapPlugin = {
name: 'annotations_vector_map',
init() {},
dispose() {
this._annotations._offTracker();
this._annotations._offTracker = null;
},
members: {
_getAnnotationCoords(annotation) {
var coords = {
offsetX: annotation.offsetX,
offsetY: annotation.offsetY
};
coords.canvas = this._projection.getCanvas();
if (annotation.coordinates) {
var data = this._projection.toScreenPoint(annotation.coordinates);
coords.x = data[0];
coords.y = data[1];
}
return coords;
},
_annotationsPointerEventHandler: chartPlugin.members._annotationsPointerEventHandler,
_isAnnotationBounded(options) {
return isDefined(options.coordinates);
},
_pullOptions(options) {
var vectorMapOptions = extend({}, {
coordinates: options.coordinates
}, chartPlugin.members._pullOptions(options));
delete vectorMapOptions.axis;
delete vectorMapOptions.series;
delete vectorMapOptions.argument;
delete vectorMapOptions.value;
return vectorMapOptions;
},
_forceAnnotationRender() {
this._change(['EXTRA_ELEMENTS']);
},
_getAnnotationStyles() {
return {
'text-anchor': 'start'
};
},
_clear() {}
},
extenders: {
_prepareExtraElements() {
var that = this;
var renderElements = () => {
that._renderExtraElements();
};
that._annotations._offTracker = that._tracker.on({
'move': renderElements,
'zoom': renderElements,
'end': renderElements
});
}
}
};
var pieChartPlugin = {
name: 'annotations_pie_chart',
init() {},
dispose() {},
members: {
_getAnnotationCoords(annotation) {
var series;
var coords = {
offsetX: annotation.offsetX,
offsetY: annotation.offsetY,
canvas: this._canvas
};
if (annotation.argument) {
if (annotation.series) {
series = this.getSeriesByName(annotation.series);
} else {
series = this.series[0];
}
var argument = series.getPointsByArg(annotation.argument)[0];
var {
x,
y
} = argument.getAnnotationCoords(annotation.location);
coords.x = x;
coords.y = y;
}
return coords;
},
_isAnnotationBounded(options) {
return options.argument;
},
_annotationsPointerEventHandler: chartPlugin.members._annotationsPointerEventHandler,
_pullOptions(options) {
var pieChartOptions = extend({}, {
location: options.location
}, chartPlugin.members._pullOptions(options));
delete pieChartOptions.axis;
return pieChartOptions;
},
_clear: chartPlugin.members._clear,
_forceAnnotationRender: chartPlugin.members._forceAnnotationRender
}
};
var corePlugin = {
name: 'annotations_core',
init() {
this._annotations = {
items: [],
_hideToolTipForDrag: false,
tooltip: new Tooltip({
cssClass: "".concat(this._rootClassPrefix, "-annotation-tooltip"),
eventTrigger: this._eventTrigger,
widgetRoot: this.element(),
widget: this
}),
hideTooltip() {
this.tooltip.annotation = null;
this.tooltip.hide();
},
clearItems() {
this.items.forEach(i => i.plaque.clear());
this.items = [];
}
};
this._annotations.tooltip.setRendererOptions(this._getRendererOptions());
},
dispose() {
this._annotationsGroup.linkRemove().linkOff();
eventsEngine.off(getDocument(), DOT_EVENT_NS);
this._annotationsGroup.off(DOT_EVENT_NS);
this._annotations.tooltip && this._annotations.tooltip.dispose();
},
extenders: {
_createHtmlStructure() {
this._annotationsGroup = this._renderer.g().attr({
'class': "".concat(this._rootClassPrefix, "-annotations")
}).css(this._getAnnotationStyles()).linkOn(this._renderer.root, 'annotations').linkAppend();
eventsEngine.on(getDocument(), POINTER_ACTION, e => {
if (!this._annotations.tooltip.isCursorOnTooltip(e.pageX, e.pageY)) {
this._annotations.hideTooltip();
}
});
eventsEngine.on(getDocument(), POINTER_UP_EVENT_NAME, event => {
this._annotations._hideToolTipForDrag = false;
this._annotationsPointerEventHandler(event);
});
this._annotationsGroup.on(POINTER_ACTION, this._annotationsPointerEventHandler.bind(this));
},
_renderExtraElements() {
this._annotationsGroup.clear();
this._annotations.items.forEach(item => item.draw(this, this._annotationsGroup));
},
_stopCurrentHandling() {
this._annotations.hideTooltip();
}
},
members: {
_buildAnnotations() {
this._annotations.clearItems();
var items = this._getOption('annotations', true);
if (!(items !== null && items !== void 0 && items.length)) {
return;
}
this._annotations.items = createAnnotations(this, items, this._getOption('commonAnnotationSettings'), this._getOption('customizeAnnotation', true), this._pullOptions);
},
_setAnnotationTooltipOptions() {
var tooltipOptions = extend({}, this._getOption('tooltip'));
tooltipOptions.contentTemplate = tooltipOptions.customizeTooltip = undefined;
this._annotations.tooltip.update(tooltipOptions);
},
_getAnnotationCoords() {
return {};
},
_pullOptions() {
return {};
},
_getAnnotationStyles() {
return {};
}
},
customize(constructor) {
constructor.addChange({
code: 'ANNOTATIONITEMS',
handler() {
this._requestChange(['ANNOTATIONS']);
},
isOptionChange: true,
option: 'annotations'
});
constructor.addChange({
code: 'ANNOTATIONSSETTINGS',
handler() {
this._requestChange(['ANNOTATIONS']);
},
isOptionChange: true,
option: 'commonAnnotationSettings'
});
constructor.addChange({
code: 'ANNOTATIONS',
handler() {
this._buildAnnotations();
this._setAnnotationTooltipOptions();
this._forceAnnotationRender();
},
isThemeDependent: true,
isOptionChange: true
});
},
fontFields: ['commonAnnotationSettings.font']
};
export var plugins = {
core: corePlugin,
chart: chartPlugin,
polarChart: polarChartPlugin,
vectorMap: vectorMapPlugin,
pieChart: pieChartPlugin
}; |
var w;
var h;
var currentplayer
var x = 'x';
var o = 'o';
function setup() {
createCanvas(400, 400);
w = width/3;
h = height/3;
//fillCell ();
// this.cell = ( cell1 || cell2 || cell3 || cell4 || cell5 || cell6 || cell7 || cell8 || cell9 );
}
function draw() {
background(220);
strokeWeight(1);
//row1
cell1 = rect(0,0, w, h);
cell2 = rect(w,0, w, h);
cell3 = rect(w + w, 0, w, h);
//row2
cell4 = rect( 0, h, w, h);
cell5 = rect(w, h, w, h);
cell6 = rect(w +w ,h, w, h);
//row3
cell7 = rect(0, h + h, w, h);
cell8 = rect(w, h + h, w, h);
cell9 = rect(w + w, h + h, w, h);
this.cell = ( cell1 || cell2 || cell3 || cell4 || cell5 || cell6 || cell7 || cell8 || cell9 );
}
function mousecClicked(fillCell) {
if (currentplayer === player1)
{ this.cell == 'X' ;
} else {
this.cell == 'O' ;
}
size (32)
textAlign();
}
function currentplayer() {}
function winstate() {}
function reset() {}
|
const util = require('./../../../utils/util.js');
const http = require("./../../../utils/http.js");
const app = getApp();
Page({
data: {
me: '',
ta: '',
content:'',
privation:false
},
onLoad: function () {
},
getMe: function (event) {
let value = event.detail.value;
console.log(value);
this.setData({
me: value
});
},
getTa: function (event) {
let value = event.detail.value;
console.log(value);
this.setData({
ta: value
});
},
getContent: function (event) {
let value = event.detail.value;
console.log(value);
this.setData({
content: value
});
},
/**
* 设置是否匿名
*/
setPrivate: function (event) {
this.setData({
privation: event.detail.value
});
},
/**
* 提交
*/
post:function(event){
let me = this.data.me;
let ta = this.data.ta;
let content = this.data.content;
let privation = this.data.privation;
if(me == ''){
wx.showLoading({
title: '你的名字不能为空',
})
setTimeout(res => {
wx.hideLoading();
}, 2000);
}
if(ta == ''){
wx.showLoading({
title: 'ta的名字不能为空',
})
setTimeout(res => {
wx.hideLoading();
}, 2000);
}
wx.showLoading({
title: '发送中',
})
http.post('/match_love', {
match_name: ta,
username:me,
content:content,
privation: privation
}, res => {
wx.hideLoading();
if(res.data.data != null){
wx.navigateTo({
url: `/pages/match_result/match_result?id=${res.data.data.id}`
})
}else{
wx.navigateBack({ comeBack: true });
}
});
}
})
|
// ARRAYS Warm-ups
// Declare a variable greeting and assign to it a phrase.
const greeting = 'Sup, brah. How you doing?'
console.log(greeting)
// Split a string into an array of characters (see the .split() method)
console.log(greeting.split())
// Take an array of letters and merge them into a string (see the .join() method)
const charArray = greeting.split('')
console.log(charArray.join(''))
// Select a random item from an array (Read up on Math.random() to figure out how to choose a random item from your array. JavaScript doesn’t have Python’s random.choice() function at the ready, so we get to do it ourselves!)
numArray = [1, 3, 6, 9, 25, 38, 30]
function selectRandom(anyArray) {
min = 0;
max = (anyArray.length - 1);
return anyArray[Math.floor(Math.random() * (max - min)) + min];
}
console.log(selectRandom(numArray))
// Select two random items from an array and swap them
function selectIndex(anyArray) {
min = 0;
max = (anyArray.length - 1);
return Math.floor(Math.random() * (max - min)) + min;
}
const numberIndex = selectRandom(numArray);
function switchNumbers(anyArray) {
const indexOne = selectIndex(anyArray);
const indexTwo = selectIndex(anyArray);
console.log(`[${indexOne}, ${indexTwo}]`)
console.log('BEFORE')
console.log(anyArray)
item = anyArray[indexOne]
item2 = anyArray[indexTwo]
anyArray[indexOne] = item2
anyArray[indexTwo] =item
console.log('AFTER')
console.log(anyArray)
}
switchNumbers(numArray)
// MAPS Warm-ups
// Create an empty map and assign it to the variable candy
const candy = {
}
// Set five colors as keys in the map and flavors as the values, for instance “purple” could be “grape”.
candy['purple'] = 'grape'
candy['yellow'] = 'banana'
candy['green'] = 'lime'
candy['blue'] = 'raspberry'
candy['red'] = 'strawberry'
console.log(candy)
// Iterate over the candy flavors to print “The x flavor is colored y.” for each
for (let key of Object.keys(candy)){
console.log(`The ${candy[key]} flavor is colored ${key}`)
}
// Get the value of a color from the map, and see what happens when you try getting a value of a color that doesn’t exist.
console.log(candy['green'])
console.log(candy['pink'])
//FUNCTIONS Warm-up
// Write a function that takes a color and the candy map. It should return the flavor or if it’s not in the map, console log “Sorry, that color doesn’t have a flavor” and return nothing.
function flavorSearch(color, map){
if (map[color] === undefined){
console.log('Sorry, that color doesn\'t have a flavor');
return null}
else {
return map[color]
}
}
// Write a function that takes an array of colors and returns an array of the corresponding flavors. If the map doesn’t have the color, add null to the array.
const colorfulColors = ['pink','yellow','red','blue','green','purple']
function checkFlavor(color_array, map) {
flavorArray = [
]
for (let color of color_array) {
flavor = flavorSearch(color, map)
flavorArray.push(flavor)
}
return flavorArray
}
console.log(checkFlavor(colorfulColors, candy))
// Create a function that reverses a word
function reverseString(anyString) {
let reversed = "";
for (let char of anyString) {
reversed = char + reversed;
}
return reversed;
}
console.log(reverseString('backwoods'))
// Create a function that takes an array of words and returns a new array of the
// words with each word reversed.
// Create a function that returns a random word from an array
// Create an array of words and save it to a variable. Using your functions create
// a second array of reversed words.
// We could use the two arrays we've created to select a random word to show the user
// and check their guess. How could we do that? Is there a better way?
// ////////////////////////////////////////////////////////////////////////////
// Create a function that takes an array of words and returns a map with the keys
// as the reversed word and the values as the original word.
// Create a function that takes two strings, `guess` and `word` and a map, like
// the one you created above. If the first string is in the map, return the word
// if not, console log "Sorry, incorrect. The word was ..." and include word.
// ////////////////////////////////////////////////////////////////////////////
// FURTHER STUDY
// Create a function that scrambles a word. Use whatever method you like to
// rearrange the letters.
// Create a function that takes an array of words and returns a map with the
// scrambled words as the keys and the original word as the values.
|
import React from "react";
import "../assets/styles/background_animation.css";
const BackgroundComponent = () => {
return (
<div className="background">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
);
};
export default BackgroundComponent;
|
console.log(process.argv.slice(2)
.map(parseFloat)
.reduce((a, b) => a + b, 0)); |
var mySection = document.querySelector('ul#section');
var button = document.querySelectorAll('button');
for(var i = 0; i < button.length; i++){
button[i].addEventListener('click', function (evt) {
if(evt.target.textContent == 'Expand'){
evt.target.nextElementSibling.classList.remove('hidden');
evt.target.textContent = "Collapse";
} else {
evt.target.nextElementSibling.classList.add('hidden');
evt.target.textContent = "Expand";
}
});
}
|
//@flow
import React, {Component} from 'react';
import {HashRouter} from 'react-router-dom';
import MainNav from './screens/MainNav';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
class App extends Component<{}> {
render() {
return (
<Provider store={store}>
<HashRouter>
<MainNav />
</HashRouter>
</Provider>
);
}
}
export default App;
|
import React from 'react'
import { Component } from 'react';
import './App.css';
import Login from './components/login'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Profile from './components/profile'
import {connect} from 'react-redux'
import NavigationBar from './components/reactNavBar'
import {logout} from './actions/users'
import Signup from './components/signup'
import {login} from './actions/users'
import CreateTrip from './components/trips/createTrip';
import TripContainer from './containers/trips'
import TripShow from './components/trips/show';
import trips from './containers/trips';
import UserContainer from './containers/users'
import UserShow from './components/users/show'
class App extends Component {
state = {
currentUser: null,
currentProfile: null
}
// setCurrentUser = data => {
// this.setState({
// currentUser: data.user,
// currentProfile: data.profile
// })
// }
render() {
return (
<div className="App">
<Router>
<NavigationBar currentUser={this.props.currentUser} logout={this.props.logout}/>
<Switch>
<Route exact path='/users/:id' render={(routerProps)=> <UserShow {...routerProps} user={this.props.users.filter(user => user.id == routerProps.match.params.id)[0]}/>}/>
<Route exact path='/' render={(routerProps)=> <UserContainer {...routerProps}/>}/>
<Route exact path='/login' render={()=> <Login login={this.props.login} fetchUser={this.props.fetchUser}/>}/>
<Route exact path='/profile' render={()=> {
return this.props.currentUser ? (
<Profile />
) : (
<Login setCurrentUser={this.setCurrentUser} />
)
}} />
<Route exact path='/signup' render={()=> <Signup />}/>
<Route exact path='/trips' render={(routerProps)=><><h1>My Trips</h1> <TripContainer {...routerProps}/></>}/>
<Route path='/trips/new' render={()=> <CreateTrip/>}/>
<Route exact path='/trips/:id' render={(routerProps)=> <TripShow {...routerProps} trip={this.props.trips.filter(trip => trip.id == routerProps.match.params.id)[0]}/>}/>
</Switch>
</Router>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
currentUser: state.users.currentUser,
trips: state.trips.trips,
users: state.users.allUsers
}
}
// const patchToProps = dispatch => {
// return {
// logout: (user) => {
// dispatch(logout(user))
// },
// login: (user) => {
// dispatch(login(user))
// }
// }
// }
export default connect(mapStateToProps, {logout, login})(App)
|
const { booksResolvers } = require('./booksResolvers');
const { herosResolvers } = require('./herosResolvers');
const resolvers = [booksResolvers, herosResolvers];
module.exports = {
resolvers,
}; |
import { PolymerElement } from "@polymer/polymer/polymer-element.js";
import "./one-square.js";
export class FourSquare extends PolymerElement {
static get is() { return 'four-square'; }
static get properties() {
return {
widthBox: { type: Number, value: 50, },
};
}
//static get observers() {
// return [ 'thingCountChanged' ];
//}
constructor() {
super();
/*
var div = document.createElement('div');
var e1 = document.createElement('one-square');
e1.className = "white";
div.appendChild(e1);
var e2 = document.createElement('one-square');
e2.className = "white";
var e3 = document.createElement('one-square');
e3.className = "white";
var e4 = document.createElement('one-square');
e4.className = "white";
*/
//this.width =
//this.height =
//const upDown = this.bigSquare.height() ;
//const leftRight = this.bigSquare.width() ;
}
connectedCallback() {
super.connectedCallback();
}
disconnectedCallback() {
}
attributeChangedCallback() {
}
ready() {
super.ready();
//this.widthBox = parseInt(this.shadowRoot.querySelector('.white').style.width);
//this.width = FSwidth.width();
//this.$.green.setAttribute("width", "20px");
}
static get template() {
return `
<style>
#green {
background-color: rgb(118,150,86);
}
.white {
background-color:rgb(238,238,210);
}
.orange {
background-color: orange;
}
.pink {
background-color: pink;
}
slot {
}
</style>
<div style="height: 100%;
width: 100%;
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;">
<slot height="100%" width="100%"></slot>
<one-square id="green"> </one-square>
<one-square class="white"> </one-square>
<one-square class="orange"> </one-square>
<one-square class="pink"> </one-square>
</div>
`
}
//_thingCountChanged() {
//}
}
customElements.define('four-square', FourSquare);
//var el1 = document.createElement('one-square');
//var el2 = new OneSquare(); |
import {ReactComponent as Arrow} from './arrow.svg'
import {ReactComponent as Pause} from './pause.svg'
import {ReactComponent as Refresh} from './refresh.svg'
import {ReactComponent as Play} from './play.svg'
export {Arrow} ;
export {Pause} ;
export {Refresh} ;
export {Play} ; |
module.exports = function chiSquareDist(a, b, sd, aColSum, bColSum) {
let sum = 0
let vectorASum
// sum vector a components
for (i = 0; i < a.length; i++) {
vectorASum += a[i]
}
// Vector B sum
for (i = 0; i < b.length; i++) {
vectorBSum += b[i]
}
for (i = 0; )
// for (i = 0; i < a.length; i++) {
// const numerator = Math.pow(a[i] - b[i], 2)
// const denominator = Math.pow(a[i] + b[i], 2)
// const div = numerator / denominator
// sum += div
// }
return sum / 2
} |
const CREATE_FARM_REQUEST = "farms:CREATE_FARM_REQUEST";
const CREATE_FARM_SUCCESS = "farms:CREATE_FARM_SUCCESS";
const CREATE_FARM_FAILURE = "farms:CREATE_FARM_FAILURE";
export default {
CREATE_FARM_REQUEST,
CREATE_FARM_SUCCESS,
CREATE_FARM_FAILURE,
};
|
module.exports = {
up: (queryInterface, Sequelize) => {
queryInterface.sequelize.query('ALTER TABLE urlstores ADD CONSTRAINT urlstore_shorturl_key UNIQUE(shorturl)');
},
down: (queryInterface, Sequelize) => {
queryInterface.sequelize
.query('ALTER TABLE urlstores DROP CONSTRAINT urlstore_shorturl_key;');
},
};
|
export const permissions = Object.freeze({
ADMIN: 'ADMIN',
SHOP: 'SHOP'
}); |
var scripts = document.getElementsByTagName("script"),
src = scripts[scripts.length-1].src;
x = src.split("/_js/");
cc_domainname = x[0]+"/";
function rateover(id,value,size,outof,cat_id,separator)
{
//exit;
if(size == "small"){sizevar = 1;}
else if(size == "medium"){sizevar = 2;}
else if(size == "large"){sizevar = 3;}
s2 = value*2;
str = "hello";
k=0;
for(i=1;i<=10;i++)
{
j=i/2;
starid = "rate"+id+""+j;
// console.log(starid);
k=k+0.5;
docstar = document.getElementById(starid);
// for 5 stars
if(cat_id == "5"){
if(k <= value){
if(i%2 == 1){
docstar.style.backgroundPosition="-8px -"+(36*sizevar)+"px";}
else {docstar.style.backgroundPosition="-"+(9*sizevar)+"px -"+(36*sizevar)+"px";}
} else {
if(i%2 == 1){docstar.style.backgroundPosition="-8px -1px";}
else{docstar.style.backgroundPosition="-"+(9*sizevar)+"px -1px";}
}
}
// for 10 stars
if(cat_id == "10"){
if(k <= value){
if(i%2 == 1){docstar.style.backgroundPosition="-8px -"+(36*sizevar)+"px";}
else {docstar.style.backgroundPosition="-"+(0*sizevar)+"px -"+(36*sizevar)+"px";}
} else {
if(i%2 == 1){docstar.style.backgroundPosition="-8px -1px";}
else{docstar.style.backgroundPosition="-"+(0*sizevar)+"px -1px";}
}
}
}
if(outof == 5){ value = value;}
else if(outof == 10){ value = value*2;}
else if(outof == 100){ value = value*20;}
//document.getElementById("rate_numbers_"+id).innerHTML = value+""+separator+""+outof;
}
function rateout(id,value,blograte,size,outof,cat_id)
{
//exit;
if(size == "small"){sizevar = 1;}
else if(size == "medium"){sizevar = 2;}
else if(size == "large"){sizevar = 3;}
s2 = blograte*2;
str = "hello"+blograte;
k=0;
for(i=1;i<=10;i++)
{
j=i/2;
starid = "rate"+id+""+j;
k=k+0.5;
docstar = document.getElementById(starid);
// out of 5 stars
if(cat_id == "5"){
if(k <= blograte){
if(i%2 == 1){docstar.style.backgroundPosition = "-8px -"+(18*sizevar)+"px";}
else{docstar.style.backgroundPosition = "-"+(9*sizevar)+"px -"+(18*sizevar)+"px";}
}
else {
if(i%2 == 1){docstar.style.backgroundPosition = "-8px -1px";}
else{docstar.style.backgroundPosition = "-"+(9*sizevar)+"px -1px";}
}
}
// out of 10 stars
if(cat_id == "10"){
if(k <= blograte){
if(i%2 == 1){docstar.style.backgroundPosition = "-8px -"+(18*sizevar)+"px";}
else{docstar.style.backgroundPosition = "-"+(0*sizevar)+"px -"+(18*sizevar)+"px";}
}
else {
if(i%2 == 1){docstar.style.backgroundPosition = "-8px -1px";}
else{docstar.style.backgroundPosition = "-"+(0*sizevar)+"px -1px";}
}
}
}
//document.getElementById("rate_numbers_"+id).innerHTML = "";
}
function ratethis(id,value,type,size,color,outof,rateonhover,score,totalcount,shape,cat_id,ratingon,lang_rating,domainname)
{
//alert(type+size+color+outof+rateonhover+score+totalcount);alert(id+""+value);
var linkbox = 'rateboxtable_'+ id;
var countId = 'countrating' ;
var countbox = '._countRating';
var totalbox = '._countTotal';
if(size == "small"){a = 18; b=2; c=21+2;}
else if(size == "medium"){a = 36; b=3; c=25+3;}
else if(size == "large"){a = 54; b=5; c=29+5;}
h1 = a; h2 = c; w1 = a*cat_id+(b * (cat_id - 1));
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
// show on page loading
if (xmlhttp.readyState==1){
document.getElementById(linkbox).innerHTML = "Loading...";
}
// show on successful page return
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// icon after adding review
document.getElementById(linkbox).innerHTML=xmlhttp.responseText;
// change rating counts
var countRating = document.getElementById(countId).value;
jQuery(countbox).html(countRating);
// change total votes
var countTotal = jQuery(totalbox).html();
countTotal = Number(countTotal) + 1 ;
jQuery(totalbox).html(countTotal);
}
}
// send page request
xmlhttp.open("GET",domainname+"?id="+id+"&value="+value+"&type="+type+"&size="+size+"&color="+color+"&outof="+outof+"&rateonhover="+rateonhover+"&score="+score+"&totalcount="+totalcount+"&shape="+shape+"&cat_id="+cat_id+"&ratingon="+ratingon,true);
xmlhttp.send();
}
function ext_ratethis(id,value,type,size,color,outof,rateonhover,score,totalcount,shape,cat_id,ratingon,lang_rating,domainname)
{
linkbox = 'rateboxtable_'+id;
if(size == "small"){a = 18; b=2; c=21+2;}
else if(size == "medium"){a = 36; b=3; c=25+3;}
else if(size == "large"){a = 54; b=5; c=29+5;}
h1 = a; h2 = c; w1 = a*cat_id+(b * (cat_id - 1));
//alert("test");
var request = extrate("get", ""+domainname+"cc_rating_ratethis.php?id="+id+"&value="+value+"&type="+type+"&size="+size+"&color="+color+"&outof="+outof+"&rateonhover="+rateonhover+"&score="+score+"&totalcount="+totalcount+"&shape="+shape+"&cat_id="+cat_id+"&ratingon="+ratingon);
if (request){
request.onload = function(){
document.getElementById(linkbox).innerHTML = request.responseText;
};
request.send();
}
}
function extrate(method, url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
// edit url to var
function rating_module(id)
{
//alert(cc_domainname);
var request = extrate("get", ""+cc_domainname+"cc_rating_external.php?id="+id);
if (request){
request.onload = function(){ //do something with request.responseText
document.getElementById("extrate_"+id).innerHTML = request.responseText;
gapi.plusone.go();
FB.XFBML.parse();
};
request.send();
}
}
function ext_rateover(id,value,size,outof,cat_id,separator)
{
rateover(id,value,size,outof,cat_id,separator);
}
function ext_rateout(id,value,blograte,size,outof,cat_id)
{
rateout(id,value,blograte,size,outof,cat_id);
}
//FB.XFBML.parse(); |
/**
* Utility function to get the current date.
* @param svg {Object} D3 selection of the parent svg element.
*/
function setStartDate(svg){
svg.startDate = (typeof serverDate === "string"?new Date(serverDate):serverDate);
svg.startDate = new Date(svg.startDate.getTime() - (svg.startDate.getTimezoneOffset() + 59 )*60000);
console.log(svg.startDate);
}
/**
* Process the specific case of netTopServices for real time.
* @param jsonData {Object} Json object containing the data.
* @param jsonContent {Array} Content array of jsonData.
* @param svg {Object} D3 selection of the parent svg element.
*/
function processServices(jsonData, jsonContent, svg){
if(svg.typeGraph !== "netTopServicesTraffic" && svg.typeGraph !== "netTopServicesNbFlow"){
return;
}
var indexitem = jsonContent.indexOf("port");
var indexdisplay = jsonContent.indexOf("proto");
jsonContent[indexitem] = "item";
jsonContent[indexdisplay] = "display";
var array, elem, port, proto,protoName;
for(var i = jsonData.length - 1; i >= 0; i --){
array = jsonData[i][1];
for(var j = array.length - 1; j >= 0; j--){
elem = array[j];
port = elem[indexitem];
proto = elem[indexdisplay];
protoName = idToProtocol(proto);
if(port === "" && proto === ""){
continue;
}
elem[indexitem] = proto + "/" + port;
elem[indexdisplay] = (protoName=== ""?elem[indexitem]:protoName + "/" + port);
}
}
}
|
/**
* @Author: cyzeng
* @DateTime: 2017-06-16 23:11:25
* @Description: 登录路由
*/
const login = r => require.ensure( [], () => r(require('@Src/view/login/login')), 'login');
export default [
{
path: '/',
name: 'login',
component: login
}
]
|
/**
* @module transformation-controller
*/
const transformer = require( 'enketo-transformer' );
const communicator = require( '../lib/communicator' );
const surveyModel = require( '../models/survey-model' );
const cacheModel = require( '../models/cache-model' );
const account = require( '../models/account-model' );
const user = require( '../models/user-model' );
const utils = require( '../lib/utils' );
const routerUtils = require( '../lib/router-utils' );
const isArray = require( 'lodash/isArray' );
const express = require( 'express' );
const url = require( 'url' );
const router = express.Router();
// var debug = require( 'debug' )( 'transformation-controller' );
module.exports = app => {
app.use( `${app.get( 'base path' )}/transform`, router );
};
router.param( 'enketo_id', routerUtils.enketoId );
router.param( 'encrypted_enketo_id_single', routerUtils.encryptedEnketoIdSingle );
router.param( 'encrypted_enketo_id_view', routerUtils.encryptedEnketoIdView );
router
.post( '*', ( req, res, next ) => {
// set content-type to json to provide appropriate json Error responses
res.set( 'Content-Type', 'application/json' );
next();
} )
.post( '/xform/:enketo_id', getSurveyParts )
.post( '/xform/:encrypted_enketo_id_single', getSurveyParts )
.post( '/xform/:encrypted_enketo_id_view', getSurveyParts )
.post( '/xform', getSurveyParts )
.post( '/xform/hash/:enketo_id', getSurveyHash );
/**
* Obtains HTML Form, XML model, and existing XML instance
*
* @param {module:api-controller~ExpressRequest} req
* @param {module:api-controller~ExpressResponse} res
* @param {Function} next - Express callback
*/
function getSurveyParts( req, res, next ) {
_getSurveyParams( req )
.then( survey => {
if ( survey.info ) {
// A request with "xformUrl" body parameter was used (unlaunched form)
_getFormDirectly( survey )
.then( survey => {
_respond( res, survey );
} )
.catch( next );
} else {
_authenticate( survey )
.then( _getFormFromCache )
.then( result => {
if ( result ) {
return _updateCache( result );
} else {
return _updateCache( survey );
}
} )
.then( result => {
_respond( res, result );
} )
.catch( next );
}
} )
.catch( next );
}
/**
* Obtains the hash of the cached Survey Parts
*
* @param {module:api-controller~ExpressRequest} req
* @param {module:api-controller~ExpressResponse} res
* @param {Function} next - Express callback
*/
function getSurveyHash( req, res, next ) {
_getSurveyParams( req )
.then( survey => cacheModel.getHashes( survey ) )
.then( _updateCache )
.then( survey => {
if ( Object.prototype.hasOwnProperty.call( survey, 'credentials' ) ) {
delete survey.credentials;
}
res.status( 200 );
res.send( {
hash: _getCombinedHash( survey )
} );
} )
.catch( next );
}
/**
* @param {module:survey-model~SurveyObject} survey
* @return {Promise}
*/
function _getFormDirectly( survey ) {
return communicator.getXForm( survey )
.then( transformer.transform );
}
/**
* @param {module:survey-model~SurveyObject} survey
* @return {Promise}
*/
function _authenticate( survey ) {
return communicator.authenticate( survey );
}
/**
* @param {module:survey-model~SurveyObject} survey
* @return {Promise}
*/
function _getFormFromCache( survey ) {
return cacheModel.get( survey );
}
/**
* Update the Cache if necessary.
*
* @param {module:survey-model~SurveyObject} survey
* @param {Promise}
*/
function _updateCache( survey ) {
return communicator.getXFormInfo( survey )
.then( communicator.getManifest )
.then( cacheModel.check )
.then( upToDate => {
if ( !upToDate ) {
delete survey.xform;
delete survey.form;
delete survey.model;
delete survey.xslHash;
delete survey.mediaHash;
delete survey.mediaUrlHash;
delete survey.formHash;
return _getFormDirectly( survey )
.then( cacheModel.set );
}
return survey;
} )
.then( _addMediaHash )
.catch( error => {
if ( error.status === 401 || error.status === 404 ) {
cacheModel.flush( survey )
.catch( e => {
if ( e.status !== 404 ) {
console.error( e );
}
} );
} else {
console.error( 'Unknown Error occurred during attempt to update cache', error );
}
throw error;
} );
}
/**
* @param {module:survey-model~SurveyObject} survey
* @return {Promise} always resolved promise
*/
function _addMediaHash( survey ) {
survey.mediaHash = utils.getXformsManifestHash( survey.manifest, 'all' );
return Promise.resolve( survey );
}
/**
* Adds a media map, see enketo/enketo-transformer
*
* @param {Array|*} manifest
* @return {object|null} media map object
*/
function _getMediaMap( manifest ) {
let mediaMap = null;
if ( isArray( manifest ) ) {
manifest.forEach( file => {
mediaMap = mediaMap ? mediaMap : {};
if ( file.downloadUrl ) {
mediaMap[ file.filename ] = utils.toLocalMediaUrl( file.downloadUrl );
}
} );
}
return mediaMap;
}
/**
* @param {module:survey-model~SurveyObject} survey
* @return {*} updated survey
*/
function _replaceMediaSources( survey ) {
const media = _getMediaMap( survey.manifest );
if ( media ) {
const JR_URL = /"jr:\/\/[\w-]+\/([^"]+)"/g;
const replacer = ( match, filename ) => {
if ( media[ filename ] ) {
return `"${media[ filename ].replace('&', '&')}"`;
}
return match;
};
survey.form = survey.form.replace( JR_URL, replacer );
survey.model = survey.model.replace( JR_URL, replacer );
if ( media[ 'form_logo.png' ] ) {
survey.form = survey.form.replace( /(class="form-logo"\s*>)/, `$1<img src="${media['form_logo.png']}" alt="form logo">` );
}
}
return survey;
}
/**
* @param {module:survey-model~SurveyObject} survey
* @return {Promise}
*/
function _checkQuota( survey ) {
return surveyModel
.getNumber( survey.account.linkedServer )
.then( quotaUsed => {
if ( quotaUsed <= survey.account.quota ) {
return Promise.resolve( survey );
}
const error = new Error( 'Forbidden. Quota exceeded.' );
error.status = 403;
throw error;
} );
}
/**
* @param {module:api-controller~ExpressResponse} res
* @param {module:survey-model~SurveyObject} survey
*/
function _respond( res, survey ) {
delete survey.credentials;
_replaceMediaSources( survey );
res.status( 200 );
res.send( {
form: survey.form,
// previously this was JSON.stringified, not sure why
model: survey.model,
theme: survey.theme,
branding: survey.account.branding,
// The hash components are converted to deal with a node_redis limitation with storing and retrieving null.
// If a form contains no media this hash is null, which would be an empty string upon first load.
// Subsequent cache checks will however get the string value 'null' causing the form cache to be unnecessarily refreshed
// on the client.
hash: _getCombinedHash( survey ),
languageMap: survey.languageMap
} );
}
/**
* @param {module:survey-model~SurveyObject} survey
*/
function _getCombinedHash( survey ) {
const FORCE_UPDATE = 1;
const brandingHash = ( survey.account.branding && survey.account.branding.source ) ? utils.md5( survey.account.branding.source ) : '';
return [ String( survey.formHash ), String( survey.mediaHash ), String( survey.xslHash ), String( survey.theme ), String( brandingHash ), String( FORCE_UPDATE ) ].join( '-' );
}
/**
* @param {module:survey-model~SurveyObject} survey
* @param {module:api-controller~ExpressRequest} req
* @return {Promise}
*/
function _setCookieAndCredentials( survey, req ) {
// for external authentication, pass the cookie(s)
survey.cookie = req.headers.cookie;
// for OpenRosa authentication, add the credentials
survey.credentials = user.getCredentials( req );
return Promise.resolve( survey );
}
/**
* @param {module:api-controller~ExpressRequest} req
* @return {Promise}
*/
function _getSurveyParams( req ) {
const params = req.body;
const customParamName = req.app.get( 'query parameter to pass to submission' );
const customParam = customParamName ? req.query[ customParamName ] : null;
if ( req.enketoId ) {
return surveyModel.get( req.enketoId )
.then( account.check )
.then( _checkQuota )
.then( survey => {
survey.customParam = customParam;
return _setCookieAndCredentials( survey, req );
} );
} else if ( params.serverUrl && params.xformId ) {
return account.check( {
openRosaServer: params.serverUrl,
openRosaId: params.xformId
} )
.then( _checkQuota )
.then( survey => {
survey.customParam = customParam;
return _setCookieAndCredentials( survey, req );
} );
} else if ( params.xformUrl ) {
const urlObj = url.parse( params.xformUrl );
if ( !urlObj || !urlObj.protocol || !urlObj.host ) {
const error = new Error( 'Bad Request. Form URL is invalid.' );
error.status = 400;
throw error;
}
const xUrl = `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`;
return account.check( {
openRosaServer: xUrl
} )
.then( survey => // no need to check quota
Promise.resolve( {
info: {
downloadUrl: params.xformUrl
},
account: survey.account
} ) )
.then( survey => _setCookieAndCredentials( survey, req ) );
} else {
const error = new Error( 'Bad Request. Survey information not complete.' );
error.status = 400;
throw error;
}
}
|
import {useStaticQuery, graphql} from "gatsby"
const useStore = () => {
const query = graphql`
{
markdownRemark(fileAbsolutePath: {regex: "/content/pages/store/"}) {
html
frontmatter {
image {
childImageSharp {
fluid(maxWidth: 600) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
}
}
`
const data = useStaticQuery(query)
const store = data.markdownRemark
return store
}
export default useStore
|
/**
* Created by StarkX on 08-Apr-18.
*/
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
const AuthScopeSchema = new Schema({
scope: String,
isDefault: Boolean
});
module.exports = AuthScopeSchema; |
viewport = [-2, -2, 6, 2];
var monkey;
var text;
function init() {
// Only one instance is required, so just create it right away.
monkey = please.access('monkey.jta').instance();
graph.add(monkey);
// Create an empty graph node; it can be transformed, but is not shown.
// It is used below to link the text to.
var above = new please.GraphNode();
// Add it to the monkey (not the graph) so it moves with the monkey.
monkey.add(above);
// Its location is 1.2 units above the monkey's location.
above.location = [0, 0, 1.2];
text = please.overlay.new_element();
text.bind_to_node(above);
}
// The update function is called whenever a shared object is changed. In this
// program the only shared object is Public.monkey, so it is called when that
// is changed.
function update() {
// Set the monkey's location and rotation from the info.
monkey.location = [Public.monkey[0], Public.monkey[1], 0];
monkey.rotation_z = Public.monkey[2];
// Simital to AddText, ClearAll is a convenience function that removes
// all child elements and returns the object.
text.ClearAll().AddText(Public.monkey[3]);
}
|
let music = new Howl({
src: ['ld44.mp3'],
loop: true,
})
music.play()
function recoverMusic(time) {
let steps = 100;
let delay = time/2;
for (let i = 0; i <= steps; ++i) {
setTimeout(() => {
let rate = 0.5 + (i/steps/2)
if (music.rate() < rate)
music.rate(rate)
}, delay + time * (i * (1000/steps)))
}
// setTimeout(() => music.rate(1), delay + time * 1000)
}
|
class Players{
constructor(players){ //string array
this.players = players;
this.playerCt = 0;
}
getCurrent(){
return this.players[this.playerCt];
}
next(){
this.playerCt++;
this.playerCt %= this.players.length;
}
getAll(){
return this.players;
}
getCount(){
return this.playerCt;
}
}
module.exports = { Players };
|
var data = {
test: 'abc'
}
var cpn = {
data: function() {
return data;
},
template: '<h1>Ai say:{{ test }} <br><button @click="changeTest">Change it!</button></h1>',
methods: {
changeTest: function() {
this.test = 'vo doi';
console.log(this)
}
}
};
var cpn2 = {
data: function() {
return {
test: 'tu anh'
};
},
template: '<h1>Ai say:{{ test }} <br><button @click="changeTest">Change it!</button></h1>',
methods: {
changeTest: function() {
this.test = 'vo doi';
console.log(this)
}
}
};
// 2 instance can use common component
new Vue({
el: '#app',
components: {
'mycomponent': cpn,
'mycomponent1': cpn2
}
})
new Vue({
el: '#app1',
components: {
'mycomponent': cpn,
'mycomponent1': cpn2
}
}) |
import React from 'react';
import Product from './Store-Product';
export default ({beers}) => (
<section id='warehouse' className="row">
{ beers.map((beer, i) => <Product key={i} item={beer} />) }
</section>
);
|
const Sneakers = require('../parsers/lamoda/model');
async function getFirstSneakers() {
const sneaker = await Sneakers.collection.findOne();
return sneaker;
}
async function getSneakers(params) {
let brand = params.brand ? params.brand.split(',') : false;
let sizeMin = +params.sizeMin || 0;
let sizeMax = +params.sizeMax || 100;
let priceMin = +params.priceMin || 0;
let priceMax = +params.priceMax || 1000000;
let sneakers = await Sneakers.find({
newPrice: { $gte: priceMin, $lte: priceMax },
sizes: { $elemMatch: { $gte: sizeMin, $lte: sizeMax } }
});
if (brand) {
sneakers = sneakers.filter(sneaker => brand.includes(sneaker.brand));
}
sneakers.forEach((sneaker, i) => {
sneakers[i].gallery = sneaker.gallery[0];
sneakers[i].sizes = sneaker.sizes.filter(size => size >= sizeMin && size <= sizeMax);
})
return sneakers;
}
module.exports = { getFirstSneakers, getSneakers } |
const firstName='hasan ali ';
const lastName='sheikh';
const fullName= firstName+' ' +lastName + " is a good boy";
console.log(fullName);
const fullName2= `${firstName} ${lastName} is a good boy`
console.log(fullName2);
const num1=22;
const num2=34;
const numbers = `${num1} ${12+12+14+16+17+18+19+20} `;
console.log(numbers);
const multiline='hello dear \n'+ 'how are you \n'+'i hope that you are well \n' + 'nice to meet you';
console.log(multiline);
const multiline1=`hello my friend
i hope that you are well
i always miss you`;
console.log(multiline1);
|
import React from 'react'
import ReactDOM from 'react-dom'
import Row from '../../node_modules/react-bootstrap/lib/Row'
import Col from '../../node_modules/react-bootstrap/lib/Col'
import Form from '../../node_modules/react-bootstrap/lib/Form'
import Label from '../../node_modules/react-bootstrap/lib/Label'
import FormControl from '../../node_modules/react-bootstrap/lib/FormControl'
import FormGroup from '../../node_modules/react-bootstrap/lib/FormGroup'
import Button from '../../node_modules/react-bootstrap/lib/Button'
// import local storage ---------------------------------
import Lockr from '../../node_modules/lockr/lockr'
class EditForm extends React.Component {
constructor() {
super()
this.state={recipe: [], recipes: []}
}
// setInitialRecipeValues(e) {
// this.setState({recipe: this.props.recipe})
// }
handleEditName(e) {
console.log(this.state.recipe[0])
this.setState({recipe: [e.target.value, this.state.recipe[1], this.state.recipe[2], this.state.recipe[3]]})
console.log(this.state.recipe[0])
}
handleEditIngredients(e) {
console.log(this.state.recipe[1])
this.setState({recipe: [this.state.recipe[0], e.target.value, this.state.recipe[2], this.state.recipe[3]]})
console.log(this.state.recipe[1])
}
handleEditInstructions(e) {
console.log(this.state.recipe[2])
this.setState({recipe: [this.state.recipe[0], this.state.recipe[1], e.target.value, this.state.recipe[3]]})
console.log(this.state.recipe[2])
}
handleEditCategories(e) {
console.log(this.state.recipe[3])
this.setState({recipe: [this.state.recipe[0], this.state.recipe[1], this.state.recipe[2], e.target.value]})
console.log(this.state.recipe[3])
}
handleRecipesChange(e) {
let recipes = Lockr.get('recipes')
recipes[this.props.recipes.indexOf(this.props.recipe)] = this.state.recipe
Lockr.set('recipes', recipes)
}
render() {
return(
<div>
<h4>{this.props.recipe[0]}</h4>
<Form className='recForms'>
<FormGroup>
<span>Name</span>
<FormControl className='edit'onChange={this.handleEditName.bind(this)}value={this.state.recipe[0]}/>
</FormGroup>
<FormGroup>
<Row><Col xs={5}><span>Ingredients separated by a</span></Col><Col className='text-left'xs={1}><div className='syntax'>,</div></Col></Row>
<FormControl className='edit'onChange={this.handleEditIngredients.bind(this)}value={this.state.recipe[1]}/>
</FormGroup>
<FormGroup>
<Row><Col xs={5}><span>Instructions separated by a</span></Col><Col className='text-left'xs={1}><div className='syntax'>|</div></Col></Row>
<FormControl className='edit' onChange={this.handleEditInstructions.bind(this)}value={this.state.recipe[2]}/>
</FormGroup>
<FormGroup>
<Row><Col xs={5}><span>Categories separated by a</span></Col><Col className='text-left'xs={1}><div className='syntax'>,</div></Col></Row>
<FormControl className='edit' onChange={this.handleEditCategories.bind(this)}value={this.state.recipe[3]}/>
</FormGroup>
<div>
<div className='text-center' id='closeEdit' onClick={this.props.close}>
<Button id='confirm' onClick={this.handleRecipesChange.bind(this)}>Confirm changes</Button>
</div>
</div>
</Form>
</div>
)
}
componentDidMount() {
this.setState({recipe: this.props.recipe})
}
}
export default EditForm |
import React from 'react';
const ButtonGroups = () => (
<div>
<div className="header">
<h4 className="title">Button Group</h4>
</div>
<div className="content">
<div className="btn-group">
<button type="button" className="btn btn-default">Left</button>
<button type="button" className="btn btn-default">Middle</button>
<button type="button" className="btn btn-default">Right</button>
</div>
<br /><br />
<div className="btn-group">
<button type="button" className="btn btn-default">1</button>
<button type="button" className="btn btn-default">2</button>
<button type="button" className="btn btn-default">3</button>
<button type="button" className="btn btn-default">4</button>
</div>
<div className="btn-group">
<button type="button" className="btn btn-default">5</button>
<button type="button" className="btn btn-default">6</button>
<button type="button" className="btn btn-default">7</button>
</div>
<div className="btn-group">
<button type="button" className="btn btn-default">8</button>
</div>
</div>
</div>
);
export default ButtonGroups; |
import React from 'react';
import ActionBarComp from './ActionBarComp';
import '../styles/flashcard.css';
import DeckListComp from './DeckListComp';
import AddDeckComp from './AddDeckComp';
import EditDeckComp from './EditDeckComp';
import DeleteDeckComp from './DeleteDeckComp';
import CardListComp from './CardListComp';
import AddCardComp from './AddCardComp';
import EditCardComp from './EditCardComp';
import DeleteCardComp from './DeleteCardComp';
class ManageDecksComp extends React.Component {
constructor() {
super();
this.state = {
showAdd: true,
currentDeck: '',
currentCard: '',
thisDeck: {},
thisCard: {},
headerText: 'Decks',
currentView: 'DeckList',
};
}
setView = (newView = 'DeckList') => {
let showAdd = false;
let headerText = '';
let viewName = newView;
switch (newView) {
case 'DeckList':
headerText = 'Decks';
showAdd = true;
break;
case 'DeckAdd':
headerText = 'Add Deck';
break;
case 'DeckDelete':
headerText = 'Delete Deck';
break;
case 'DeckEdit':
headerText = 'Edit Deck';
break;
case 'CardList':
headerText = 'Cards';
showAdd = true;
break;
case 'CardAdd':
headerText = 'Add Card';
break;
case 'CardEdit':
headerText = 'Edit Card';
break;
case 'CardDelete':
headerText = 'Delete Card';
break;
default:
viewName = 'DeckList';
headerText = 'Decks';
showAdd = true;
}
this.setState({
currentView: viewName,
showAdd,
headerText,
});
}
handleAddClick = () => {
const { currentView } = this.state;
switch (currentView) {
case 'DeckList': {
this.setView('DeckAdd');
break;
}
case 'CardList': {
this.setView('CardAdd');
break;
}
default:
this.setView('DeckList');
}
};
handleBackClick = () => {
const { currentView } = this.state;
switch (currentView) {
case 'DeckList': case 'DeckAdd': case 'DeckDelete': case 'DeckEdit': case 'CardList': {
this.setView('DeckList');
break;
}
case 'CardAdd': case 'CardEdit': case 'CardDelete': {
this.setView('CardList');
break;
}
default:
this.setView('DeckList');
}
}
handleDeckAdded = (deckId) => {
this.setView('CardAdd');
this.setState({ currentDeck: deckId });
};
handleDeckSelect = (deckId) => {
this.setView('CardList');
this.setState({ currentDeck: deckId });
}
handleDeckEdit = (deck) => {
this.setView('DeckEdit');
this.setState({ thisDeck: deck });
}
handleDeckDelete = (deckId) => {
this.setView('DeckDelete');
this.setState({ currentDeck: deckId });
}
handleCardAdded = (cardId) => {
this.setState({ currentCard: cardId });
this.setView('CardList');
}
handleCardSelect = (card) => {
this.setState({ thisCard: card });
this.setView('CardEdit');
}
handleCardEdit = (card) => {
this.setState({ thisCard: card });
this.setView('CardEdit');
}
handleCardDelete = (cardId) => {
this.setState({ currentCard: cardId });
this.setView('CardDelete');
}
handleDeckEdited = (deckId) => {
this.setState({ currentDeck: deckId });
this.setView('DeckList');
};
handleDeckDeleted = () => {
this.setState({ currentDeck: '' });
this.setView('DeckList');
};
handleCardEdited = (cardId) => {
this.setState({ currentCard: cardId });
this.setView('CardList');
};
handleCardDeleted = () => {
this.setState({ currentCard: '' });
this.setView('CardList');
}
render() {
const {
currentView, currentDeck, currentCard, showAdd, headerText, thisCard, thisDeck,
} = this.state;
return (
<div className="ManageDecksComp">
<ActionBarComp
showAdd={showAdd}
showBack
headerText={headerText}
onAdd={this.handleAddClick}
onBack={this.handleBackClick}
/>
{ (currentView === 'DeckList')
? (
<DeckListComp
onDeckSelect={this.handleDeckSelect}
onDeckEdit={this.handleDeckEdit}
onDeckDelete={this.handleDeckDelete}
/>
)
: null
}
{ (currentView === 'DeckAdd')
? (
<div>
<AddDeckComp onDeckAdded={this.handleDeckAdded} />
</div>
)
: null
}
{ (currentView === 'DeckEdit')
? (
<div>
<EditDeckComp deck={thisDeck} onDeckEdited={this.handleDeckEdited} />
</div>
)
: null
}
{ (currentView === 'DeckDelete')
? (
<div>
<DeleteDeckComp
deck={currentDeck}
onDeckDeleted={this.handleCardDeleted}
/>
</div>
)
: null
}
{ (currentView === 'CardList')
? (
<div>
<CardListComp
deck={currentDeck}
onCardSelect={this.handleCardSelect}
onCardEdit={this.handleCardEdit}
onCardDelete={this.handleCardDelete}
/>
</div>
)
: null
}
{ (currentView === 'CardAdd')
? (
<div>
<AddCardComp
deck={currentDeck}
onCardAdded={this.handleCardAdded}
/>
</div>
)
: null
}
{ (currentView === 'CardEdit')
? (
<div>
<EditCardComp
card={thisCard}
onCardEdited={this.handleCardEdited}
/>
</div>
)
: null
}
{ (currentView === 'CardDelete')
? (
<div>
<DeleteCardComp
card={currentCard}
onCardDeleted={this.handleCardDeleted}
/>
</div>
)
: null
}
</div>
);
}
}
export default ManageDecksComp;
|
(function () {
'use strict';
/**
* @ngdoc object
* @name 0908essbar.controller:C0908essbarCtrl
*
* @description
*
*/
angular
.module('0908essbar')
.controller('C0908essbarCtrl', C0908essbarCtrl);
function C0908essbarCtrl() {
var vm = this;
vm.ctrlName = 'C0908essbarCtrl';
}
}());
|
var utils = {}
/**
* log for debugging
*/
utils.log = function () {
if (console) {
console.log.apply(console, arguments)
}
}
/**
* warnings, traces by default
* can be suppressed by `silent` option.
*/
utils.warn = function (msg) {
if (console) {
console.warn(msg)
if (console.trace) {
console.trace()
}
}
}
module.exports = utils
|
export const MODE_LIGHT = 'light'
export const MODE_DARK = 'dark'
export const MODE_DEFAULT = MODE_LIGHT
export const basePallet = {
violet: '#7f00ff',
indigo: '#3f00ff',
blue: '#1a99ff',
cyan: '#17a2b8',
teal: '#009999',
green: '#28a745',
yellow: '#ffc107',
tangerine: '#ffaa00',
mustard: '#aa7700',
orange: '#fd7e14',
red: '#dc3545',
white: '#ffffff',
gray: '#7f7f7f',
black: '#010101',
}
// TODO add an 'action' color to work as a default message/button color
export default {
mode: MODE_DEFAULT,
prominent: 'primary',
pallet: {
primary: basePallet.tangerine,
secondary: basePallet.blue,
tertiary: basePallet.teal,
light: basePallet.white,
neutral: basePallet.gray,
dark: basePallet.black,
success: basePallet.green,
info: basePallet.cyan,
warning: basePallet.yellow,
danger: basePallet.red,
},
factors: {
alpha: 0.3,
darker: {
min: 0.08,
max: 0.155,
},
dark: {
min: 0.2,
max: 0.47,
},
light: {
min: 0.22,
max: 0.55,
},
lighter: {
min: 25,
max: 40,
},
},
}
|
import React from "react";
export default function(props) {
const ad = props.ad;
return (
<div>
<form id="adForm" onSubmit={props.onSubmit}>
<input
type="text"
name="title"
placeholder="type title here"
value={ad.title}
onChange={props.onChange}
/>
<input
type="text"
name="price"
placeholder="type price here"
value={ad.price}
onChange={props.onChange}
/>
<input
type="text"
name="description"
placeholder="type description here"
value={ad.description}
onChange={props.onChange}
/>
<input
type="text"
name="pictureUrl"
placeholder="type picture url here"
value={ad.pictureUrl}
onChange={props.onChange}
/>
<input
type="checkbox"
name="soldStatus"
value={props.soldStatus}
onChange={props.onChange}
/>
Item has been sold
<br />
</form>
<button type="submit" form="adForm" value="Submit">
{" "}
Submit
</button>
</div>
);
}
|
import React from 'react';
//import './services.css';
const ServiceCard=(props)=>{
return(
<div className='container'>
<div className='card'>
<img alt='logo' src={props.imagelink} height="50%" width="100%"/>
<p><b>{props.title}</b></p>
<p>{props.summary}</p>
</div>
</div>
);
}
export default ServiceCard; |
var authService = angular.module('AuthService', []);
authService.service('AuthService', ['$facebook', function ($facebook) {
//'use strict';
this.userLoggedIn = null;
this.setUserLoggedIn = function (user) {
this.userLoggedIn = user;
for (var i in this.onLoginQueue) {
var call = this.onLoginQueue[i];
call(user);
}
};
this.setUserLoggedOut = function () {
this.userLoggedIn = null;
for (var i in this.onLogoutQueue) {
var call = this.onLogoutQueue[i];
call();
}
};
this.getUser = function () {
return this.userLoggedIn;
};
this.getUserFeed = function (callback) {
$facebook.api("/" + this.userLoggedIn.id + "/feed").then(function (userWall) {
callback(userWall)
});
};
this.postToWall = function (callback, message) {
console.log("/" + this.userLoggedIn.id + "/feed")
$facebook.api("/" + this.userLoggedIn.id + "/feed", "post", { "message": message })
.then(function (response) {
if (callback) {
callback();
}
})
.catch(function(error) {
});
};
this.onLoginQueue = [];
this.loginCallbackNames = [];
this.doOnLogin = function (callbackName, callback) {
if (this.userLoggedIn != null) {
callback(this.userLoggedIn);
}
if (this.loginCallbackNames.indexOf(callbackName) == -1) {
this.onLoginQueue.push(callback);
this.loginCallbackNames.push(callbackName);
}
};
this.onLogoutQueue = [];
this.logoutCallbackNames = [];
this.doOnLogout = function (callbackName, callback) {
if (this.userLoggedIn == null) {
callback(this.userLoggedIn);
}
if (this.logoutCallbackNames.indexOf(callbackName) == -1) {
this.onLogoutQueue.push(callback);
this.logoutCallbackNames.push(callbackName);
}
};
}]);
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _a = _interopRequireDefault(require("./a"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var isFn = function isFn(f) {
return typeof f === 'function';
};
console.log('a', _a["default"]);
var _default = isFn;
exports["default"] = _default; |
import React, { useState, useEffect } from "react";
import "./App.css";
import CountryForm from "./components/countryFrom/CountryForm";
import Leaflet from "./components/leaflet/Leaflet";
import Loading from "./components/loading/Loading";
import WeatherInfo from "./components/weatherInfo/WeatherInfo";
import WeatherLayout from "./components/weatherLayout/WeatherLayout";
function App() {
const [lat, setLat] = useState(36.7525);
const [lng, setLng] = useState(3.04197);
const [isNotEmpty, setIsNotEmpty] = useState(false);
const [loading, setLoading] = useState(null);
const [countryInfo, setCountryInfo] = useState();
const [counryLatLng, setCountryLatLng] = useState({
lat: 36.7525,
lon: 3.04197,
});
const [weatherData, setWeatherData] = useState();
const [current, setCurrent] = useState();
const [hideCordsFrom, setHideCordsFrom] = useState(false);
const [hideCountryFrom, setHideCountryFrom] = useState(true);
//Get Weather info via Country Name
const countries = (country) => {
fetch(
`${process.env.REACT_APP_API_CITIES}?q=${country}&appid=${process.env.REACT_APP_API_KEY}`
)
.then(async (res) => {
const data = await res.json();
setCountryInfo(data);
setCountryLatLng(data["coord"]);
})
.catch((err) => console.log("Fetch Error -S:", err));
};
// Get weather info via Lat and Lon
const getWeatherData = (lat, lng) => {
if (lat && lng) {
fetch(
`${process.env.REACT_APP_BASE_URL}?lat=${lat}&lon=${lng}&exclude=minutely,hourly,&appid=${process.env.REACT_APP_API_KEY}`
)
.then(async (res) => {
let data = await res.json();
console.log("data:", data["daily"]);
setWeatherData(data);
setCurrent(data["current"]);
})
.catch(function (err) {
console.log("Fetch Error :-S", err);
});
}
};
const handelCordsFrom = () => {
setHideCordsFrom(!hideCordsFrom);
setHideCountryFrom(!hideCountryFrom);
};
const handelCountryFrom = () => {
setHideCountryFrom(!hideCountryFrom);
setHideCordsFrom(!hideCordsFrom);
};
const addCountryInfo = (e) => {
console.log("E:", e);
countries(e);
};
const addInfo = (e) => {
setLat(e[0].lat);
setLng(e[1].lng);
//call api here and assign value to the state
setTimeout(() => {
setLoading(true);
}, 500);
const timer = setTimeout(() => {
setIsNotEmpty(true);
setLoading(false);
getWeatherData(e[0].lat, e[1].lng);
}, 1000);
return () => {
setLoading(false);
clearTimeout(timer);
};
};
return (
/* addInfo || countryInfo */
<div className="app">
<div className="dashboard">
<button
onClick={handelCordsFrom}
title="Type your coordinates (lat, lng) to get weather info "
>
{" "}
Cords{" "}
</button>
<button
onClick={handelCountryFrom}
title="Type your Country or City to get weather info"
>
{" "}
Country{" "}
</button>
</div>
{hideCountryFrom ? <WeatherLayout addInfo={addInfo} /> : null}
{hideCordsFrom ? <CountryForm addCountryInfo={addCountryInfo} /> : null}
<Leaflet
lat={lat}
lng={lng}
current={current}
countryLatLng={counryLatLng}
countryInfo={countryInfo}
/>
{loading ? <Loading /> : ""}
{isNotEmpty ? (
<WeatherInfo weatherInfo={weatherData} countryInfo={countryInfo} />
) : null}
</div>
);
}
export default App;
|
var userinfo = ddsc.localStorage.get("userinfo");
if(userinfo){
var userCode = userinfo.userCode;
}
$(function () {
$(".product").on("click", "a", function () {
window.location.href = "./goodDetail.html?goodsCode="+goodsCode;
})
$('#del').on('click', function(){
deleteFootinfo()
})
queryFootinfo()
})
function queryFootinfo(){
let params = {
userCode,
}
myAjax.request({
url: basepath + "/footprintinfo/queryFootprintinfo.do",
type: "GET"
}, params)
.then((result) => {
let html = '';
result.data.list.map((item, index) => {
html += `
<li>
<a>
<img src="${item.picUrl}" alt="">
<div class="info f_left">
<p>${item.bookName}</p>
<p class="warm">¥${item.pirce}</p>
<p>
<b class="stared"></b>
<b class="stared"></b>
<b class="stared"></b>
<b class="star-half"></b>
<b class="star"></b>
<i class="conment">(263)</i>
</p>
</div>
</a>
</li>
`
})
$("#product").append(html)
})
.catch((error) => {
/*let layparams = {
message: "报错了:"+error,
}
showToast(layparams)*/
console.error("报错了:"+error);
});
}
//清除
function deleteFootinfo(){
let params = {
userCode,
}
myAjax.request({
url: basepath + "/footprintinfo/deleteFootprintinfo.do",
type: "GET"
}, params)
.then((result) => {
let layparams = {
message: result.msg
}
showToast(layparams)
})
.catch((error) => {
/*let layparams = {
message: "报错了:"+error,
}
showToast(layparams)*/
console.error("报错了:"+error);
});
} |
var SelfPosition = require('./SelfPosition');
var StageInOut = function($dom,option){
// this.target = $dom[0];
this.isIn = false;
$dom.css({backgroundColor:"#ff0000"});
var config = {
offsetIn:0,
offsetOut:0
}
$.extend(config,option);
function setup(){
this.__proto__ = new SelfPosition($dom[0]);
return this;
}
this.update = function(){
this._update();
console.log(this.progress);
// var rect = this.target.getBoundingClientRect();
// console.log(1-(rect.top+rect.height)/(window.innerHeight+rect.height));
if(this.progress > config.offsetIn && this.progress < 1-config.offsetIn){
if(!this.isIn){
this.in(this.direct<0?-1:1);
this.isIn = true;
}
}
if(this.progress < -config.offsetOut || this.progress > 1+config.offsetOut){
if(this.isIn){
this.out(this.direct<0?-1:1);
this.isIn = false;
}
}
}
this.in = function(){
console.log('in');
}
this.out = function(){
console.log('out');
}
setup.call(this);
}
StageInOut.prototype.constructor = StageInOut;
module.exports = StageInOut; |
function getTarget(e){ //宣告函式
if(!e){ //如果不存在event物件
e = window.event //使用舊版IE的event物件
}
return e.target || e.srcElement; //取得事件發生的目標元件
}
function itemDone(e){ //宣告函式
//自清單中移除清單項目
let target, elParent, elGrandparent;//宣告變數
target = getTarget(e); //取得被點擊鏈結的目標元件,及超鏈結元件
elParent = target.parentNode; //取得目標元件的父元件,即清單項目元件
elGrandparent = target.parentNode.parentNode;//取得目標元件的祖父元件,即清單項目元件
elGrandparent.removeChild(elParent);//自清單中移除清單項目
//避免超鏈結將使用者帶離頁面
if(e.preventDefault){//如果preventDefault()可運作
e.preventDefault();//使用preventDefault()
}else{//否則
e.returnValue = false;//使用舊版IE的方式
}
}
//設置事件監聽器,當click事件啟動時便呼叫itemDone()
let el = document.getElementById('shoppingList');//取得id屬性值為shoppingList元件
if(el.addEventListener){//如果事件監聽器可運作
el.addEventListener('click', function(e){//為click事件加入監聽器
itemDone(e);//呼叫itemDone()函式
}, false);//使用事件汽泡模式
}else{//否則
el.attachEvent('onclick', function(e){//使用舊版IE方式:onclick
itemDone(e);//呼叫itemDone()函式
});
} |
import { useDispatch, useSelector } from "react-redux";
import './App.css';
import {loadQuiz} from "./actions/fetchAction";
import Flexbox from "react-flexbox";
import {useState} from "react";
import {Answers} from "./components/Answers/answers";
import {Correct} from "./components/Correct/correct";
function App() {
const dispatch= useDispatch();
const quiz = useSelector(state => state.fetchQuiz.fetchedPosts);
const counter = useSelector(state => state.counterQuiz)
const [color, setColor] = useState(" ")
const [finalCorrect, setFinalCorrect] = useState();
const mark = () => {
}
return (
<div className="App">
<header className="header">
<button
className='LoadButton'
onClick={() => dispatch(loadQuiz())}
>
Download quiz
</button>
<div className="title">Quiz
</div>
<div className="score">Score
<span>{counter}</span>
</div>
</header>
{quiz.map( (q,idx) => (
<div className="quiz-blocks" key={q.id}>
<h5 className="questions" >{q.question}</h5>
<div className="quiz-answers-blocks" >
<Answers quiz={quiz[idx]} color={color} id={q.id}/>
<Correct quiz={quiz[idx]} setColor={setColor} color={color}/>
</div>
</div>
))}
</div>
);
}
export default App;
|
@import "Source/Model/undefinedColor.js"
var ColorAnalyzer = {
// Might need to add options for text or color only
analyze: function(document, colorsDictionary, sharedStyles) {
var undefinedColors = {};
// For pages
for (var i = 0; i < document.pages().count(); i++) {
var page = document.pages().objectAtIndex(i);
// For artboards
for (var j = 0; j < page.artboards().count(); j++) {
var artboard = page.artboards().objectAtIndex(j)
// For layers
for (var k = 0; k < artboard.layers().count(); k++) {
var layer = artboard.layers().objectAtIndex(k)
var style = layer.style()
var path = page.name() + "/" + artboard.name() + "/" + layer.name();
// If style is Color
var undefinedLayer = ColorAnalyzer.setSharedStyle(colorsDictionary, layer, sharedStyles);
if (undefinedLayer != null) {
var undefinedColor = undefinedColors[undefinedLayer.style().fill().color().hexValue()];
if (undefinedColor != null) {
var paths = undefinedColor.paths;
paths.push(path);
undefinedColors[undefinedLayer.style().fill().color().hexValue()].paths = paths;
} else {
var paths = [path];
var newUndefinedColor = new UndefinedColor(undefinedLayer.style().fill().color(), paths);
undefinedColors[undefinedLayer.style().fill().color().hexValue()] = newUndefinedColor;
}
}
}
}
}
return undefinedColors;
},
setSharedStyle: function(dictionary, layer, sharedStyles) {
//Is color -> fillType?
var isSimpleFill = !layer.style().hasMoreThanOneEnabledFill()
var hasNoBorder = !layer.style().hasEnabledBorder()
var hasNoShadow = !layer.style().hasEnabledShadow()
var hasNoInnerShadow = !layer.style().innerShadow() || !layer.style().innerShadow().isEnabled()
//log("has no shadow: " + hasNoShadow + ", has no border: " + hasNoBorder + ", has no inner shadow:" + hasNoInnerShadow);
if (layer.style().fill() && hasNoBorder && hasNoShadow && isSimpleFill && hasNoInnerShadow) {
if (layer.style().fill().fillType() == 0 && layer.style().fill().isEnabled()) {
var hexValue = layer.style().fill().color().hexValue();
if (dictionary[hexValue] == null) {
return layer;
}
}
}
return null;
}
};
|
export default {
SERVER_URL: "http://api.shout.app/"
}
|
$("#add-post").click(function () { addNewPost(); });
$(".progress").hide();
loadCategories();
function loadCategories() {
const options = $("#category-id");
options.html('');
$.get('/api/categories',
function (result) {
$.each(result, function () {
options.append($("<option />").val(this.id).text(this.name));
});
}
);
}
function addNewPost() {
const link = $("#link").val();
const key = $("#security-key").val();
const categoryId = $("#category-id").val();
const comment = $("#post-comment").val();
const tags = $("#tags").val();
const progress = $(".progress");
const data = {
link: link,
key: key,
categoryId: categoryId,
comment: comment,
tags: tags
};
progress.show();
$.post('/api/publications/new', data)
.done(function (response) {
progress.hide();
window.location.replace(response.shareUrl);
}).fail(function (err) {
if (!!err && err.status === 403)
alert('Access denied');
else
console.error(err);
});
} |
class Songs {
constructor(_parent, _item) {
this.parent = _parent;
this.song = _item.title;
this.artist = _item.artist.name;
this.artistimg = _item.artist.picture;
this.album = _item.album.cover;
this.albumbig = _item.album.cover_big;
this.duration = _item.duration;
this.play = _item.preview;
this.rank = _item.rank;
this.link = _item.artist.link;
}
render() {
const secsToTime = (_secs) => {
let mins = Math.floor(_secs / 60);
if (mins < 10) {
mins = "0" + mins;
}
let secs = _secs % 60;
if (secs < 10) {
secs = "0" + secs;
}
return mins + ":" + secs;
}
let newDiv = $(`<div class="menu"></div>`);
$(this.parent).append(newDiv);
$(newDiv).append(`
<div class="content artist">
<img src="${this.artistimg}">
</div>
<div class="content name">${this.song}</div>
<div class="content album">
<img src="${this.album}">
</div>
<div class="content duration">${secsToTime(this.duration)}</div>
<div class="content rank">${this.rank}</div>
`)
$(this.parent).append(`<hr>`);
$(newDiv).on("click", () => {
showDark(this.albumbig, this.song, this.rank, this.play, this.artist, this.link);
})
}
} |
import './validations/auth'
|
const updateSites = () => fetch('https://www.softomate.net/ext/employees/list.json')
.then(res => res.json())
.then(list => {
localStorage.setItem('list', JSON.stringify(list));
localStorage.setItem('lastUpdate', Date.now().toString());
});
const ONE_HOUR = 1000 * 60 * 60;
const lastUpdate = localStorage.getItem('lastUpdate');
if (!lastUpdate || ((Date.now() - parseInt(lastUpdate)) > ONE_HOUR)) {
updateSites();
}
const closeMessage = name => {
const closedList = JSON.parse(localStorage.getItem('closedList')) || [];
closedList.push(name);
localStorage.setItem('closedList', JSON.stringify(closedList));
};
const showMessage = name => {
const shownList = JSON.parse(sessionStorage.getItem('shownList')) || {};
shownList[name] = (shownList.hasOwnProperty(name) ? parseInt(shownList[name]) : 0) + 1;
sessionStorage.setItem('shownList', JSON.stringify(shownList));
};
const checkShowMessage = (name, sendResponse) => {
const shownList = JSON.parse(sessionStorage.getItem('shownList')) || {};
const closedList = JSON.parse(localStorage.getItem('closedList')) || [];
if (shownList.hasOwnProperty(name) && shownList[name] >= 3) {
sendResponse({res: false});
}
if (closedList.indexOf(name) !== -1) {
sendResponse({res: false});
}
sendResponse({res: true});
};
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
switch (request.type) {
case 'list':
sendResponse(JSON.parse(localStorage.getItem('list')));
break;
case 'checkShowMessage':
checkShowMessage(request.data, sendResponse);
break;
case 'showMessage':
showMessage(request.data);
break;
case 'closeMessage':
closeMessage(request.data);
break;
}
});
|
import React from 'react';
import axios from 'axios';
import styled from 'styled-components';
import Followers from './Followers';
const Name = styled.p`
font-weight: bold;
`
class UserCard extends React.Component {
constructor(props) {
super(props);
this.state = {
followers: []
}
}
componentDidMount() {
axios
.get('https://api.github.com/users/janemsuh/followers')
.then(response => {
this.setState({ followers: response.data })
})
.catch(err => console.log(err));
}
render() {
return (
<div className='user-card'>
<div className='img-container'>
<img src={this.props.data.avatar_url} alt='avatar' />
</div>
<div className='profile-data'>
<Name>{this.props.data.name} ({this.props.data.login})</Name>
<p>Lives in {this.props.data.location}</p>
<p>Follows {this.props.data.following} users</p>
<p>Has {this.props.data.followers} followers:</p>
<Followers followers={this.state.followers} />
</div>
</div>
);
}
}
export default UserCard; |
class Movie{
constructor(){
}
setMoviePoster(path){
//Set Moview Poster
if(path != null){
return `https://image.tmdb.org/t/p/w342/${path}`;
}
else{
return "/assets/images/not-found.jpg";
}
}
convertDateFormat(date){
if(date === null || date === ""){
return "";
}
else{
let releaseDay = date.substring(8,10);
let releaseMonth = date.substring(5, 7);
let releaseYear = date.substring(0, 4);
return `${releaseDay}/${releaseMonth}/${releaseYear}`;
}
}
checkForLanguage(movie){
if(movie.spoken_languages.length > 0){
return movie.spoken_languages[0].name
}
else{
return 'Unknown'
}
}
getDirector(credits){
let director;
credits.crew.forEach(crew => {
if(crew.job === "Director"){
director = crew.name;
}
});
return director
}
getTrailer(video){
const videoResults = video.results
let trailer;
if(videoResults.length > 0){
switch(video.results[0].site){
case "YouTube":
trailer = `https://www.youtube.com/watch?v=${videoResults[0].key}`;
break;
case "Vimeo":
trailer = `https://vimeo.com/${videoResults[0].key}`;
break;
default:
tailer = '';
}
}
else{
trailer = '';
}
return trailer
}
getMoviePreview(movie){
const title = movie.original_title,
movieID = movie.id,
poster = this.setMoviePoster(movie.poster_path),
date = this.convertDateFormat(movie.release_date),
rating = movie.vote_average * 10;
ui.createResultCards(title, poster, date, movieID, rating);
}
async getMovieFull(id){
const movieResponse = await fetch(`https://api.themoviedb.org/3/movie/${id}?api_key=${apiKey}`);
const creditResponse = await fetch(`https://api.themoviedb.org/3/movie/${id}/credits?api_key=${apiKey}`);
const videoResponse = await fetch(`https://api.themoviedb.org/3/movie/${id}/videos?api_key=${apiKey}`);
const movie = await movieResponse.json();
const credit = await creditResponse.json();
const video = await videoResponse.json();
return{
title: movie.original_title,
poster: this.setMoviePoster(movie.poster_path),
date: this.convertDateFormat(movie.release_date),
runtime: movie.runtime,
overview: movie.overview,
budget: movie.budget,
language: this.checkForLanguage(movie),
genres: movie.genres,
director: this.getDirector(credit),
trailer: this.getTrailer(video)
}
}
async getRandomMovie(){
//Get ID of most recent movie in database
const movieResponse = await fetch(`https://api.themoviedb.org/3/movie/latest?api_key=${apiKey}`);
const latest = await movieResponse.json();
const latestID = latest.id;
//Find random ID between 1 and ID of most recent movie
const randomID = Math.floor(Math.random() * `${latestID}`) + 1;
return randomID;
}
} |
const constants = require('./constants.js');
const utils = require('./utils.js');
const proj = require('./reproject.js');
function getBboxForTile (tile, projection, buffer) {
if (buffer !== undefined && projection !== 'EPSG:4326') {
return 'NOT SUPPORTED';
}
if (buffer === undefined) {
buffer = 0;
}
const lastChar = tile[tile.length - 1];
const isSplit = lastChar === 'R' || lastChar === 'L';
if (isSplit) tile = tile.slice(0, tile.length - 1);
let x = constants.X0;
let y = constants.Y0;
let ans = [];
let res = '';
y += dyFromChar0(tile[0]);
x += dxFromChar1(tile[1]);
if (tile.length === 2) {
ans = [x, y, x + constants.dx200k, y + constants.dx200k];
res = '200k';
}
const tc2 = dxyFromChar2(tile[2]);
x += tc2[0];
y += tc2[1];
if (tile.length === 3) {
ans = [x, y, x + constants.dx100k, y + constants.dy100k];
res = '100k';
}
const tc3 = dxyFromChar3(tile[3]);
x += tc3[0];
y += tc3[1];
if (tile.length === 4) {
ans = [x, y, x + constants.dx50k, y + constants.dy50k];
res = '50k';
}
const tc4 = dxyFromChar4(tile[4]);
x += tc4[0];
y += tc4[1];
if (tile.length === 5) {
ans = [x, y, x + constants.dx25k, y + constants.dy25k];
res = '25k';
}
const tc5 = dxyFromChar5(tile[5]);
x += tc5[0];
y += tc5[1];
if (tile.length === 6) {
ans = [x, y, x + constants.dx10k, y + constants.dy10k];
res = '10k';
}
const tc6 = dxyFromChar6(tile[6]);
x += tc6[0];
y += tc6[1];
if (tile.length === 7) {
ans = [x, y, x + constants.dx5k, y + constants.dy5k];
res = '5k';
}
const tc7 = dxyFromChar7(tile[7]);
x += tc7[0];
y += tc7[1];
if (tile.length === 8 && !isSplit) {
ans = [x, y, x + constants["dx2.5k"], y + constants["dy2.5k"]];
res = '2.5k';
}
if (isSplit) {
if (lastChar === 'L') {
ans = [ans[0], ans[1], ans[2] - constants['dx' + res] / 2, ans[3]];
} else {
ans = [ans[0] + constants['dx' + res] / 2, ans[1], ans[2], ans[3]];
}
}
if (projection === undefined || projection === 'EPSG:3067') {
return ans;
} else if (projection === 'EPSG:3857') {
return [...proj.from3067to3857([ans[0], ans[1]]), ...proj.from3067to3857([ans[2], ans[3]])];
} else if (projection === 'EPSG:4326') {
const bboxIn4326 = [...proj.from3067to4326([ans[0], ans[1]]), ...proj.from3067to4326([ans[2], ans[3]])];
const bboxWithBuffer = utils.addBufferToBbox(bboxIn4326, buffer);
return bboxWithBuffer;
} else {
return [];
}
}
function dyFromChar0 (c) {
if (!c) return '';
return constants.dy200k * constants.enum0.indexOf(c.toUpperCase());
}
function dxFromChar1 (c) {
if (!c) return '';
return (parseInt(c) - 2) * constants.dx200k;
}
function dxyFromChar2 (c) {
if (!c) return '';
const c0 = constants.enum2[parseInt(c) - 1];
return [c0[0] * constants.dx100k, c0[1] * constants.dy100k];
}
function dxyFromChar3 (c) {
if (!c) return '';
const c0 = constants.enum2[parseInt(c) - 1];
return [c0[0] * constants.dx50k, c0[1] * constants.dy50k];
}
function dxyFromChar4 (c) {
if (!c) return '';
const c0 = constants.enum2[parseInt(c) - 1];
return [c0[0] * constants.dx25k, c0[1] * constants.dy25k];
}
function dxyFromChar5 (c) {
if (!c) return '';
let t0 = 0;
for (let i = 0; i < 4; i++) {
if (constants.enum5[i].indexOf(c) !== -1) {
t0 = i;
break;
}
}
const c0 = constants.enum5[t0];
const c1 = c0.indexOf(c);
return [t0 * constants.dx10k, c1 * constants.dy10k];
}
function dxyFromChar6 (c) {
if (!c) return '';
const c0 = constants.enum2[parseInt(c) - 1];
return [c0[0] * constants.dx5k, c0[1] * constants.dy5k];
}
function dxyFromChar7 (c) {
if (!c) return '';
let t0 = 0;
for (let i = 0; i < 2; i++) {
if (constants.enum6[i].indexOf(c) !== -1) {
t0 = i;
break;
}
}
const c0 = constants.enum6[t0];
const c1 = c0.indexOf(c);
return [t0 * constants["dx2.5k"], c1 * constants["dy2.5k"]];
}
exports.getBboxForTile = getBboxForTile;
|
"use strict";
var fs = require("fs"),
sqlite3 = require("sqlite3").verbose(),
util = require('util'),
moment = require('moment');
// Global Variables
var db;
var repository = "../db/goldennuts.db";
var SQL_LOG_FILE = "../db/goldennuts.sql"
function db_set_db_path(path) {
repository = path;
}
function db_set_logfile_path(path) {
SQL_LOG_FILE = path;
}
// time_now function is used to get the cur_time
function date_time() {
return moment().format('HH-mm-ss');
}
function format_user_date(date) {
return moment(date, 'YYYY-MM-DD').format('YYYY-MM-DD');
}
function date_date() {
return moment().format('YYYY-MM-DD');
}
function build_date(year, month, day) {
var str = util.format("%d-%d-%d", year, month, day);
return str;
}
function db_open(create_new) {
if (typeof db === 'undefined') {
if (fs.existsSync(repository)) {
db = new sqlite3.Database(repository);
return true;
} else if (create_new) {
db = new sqlite3.Database(repository, sqlite3.OPEN_CREATE | sqlite3.OPEN_READWRITE);
return true;
}
} else {
console.error("Trying to open DB file twice");
}
return false;
}
function db_close() {
if (typeof db === 'undefined') {
console.error("trying to close a unopened file");
return;
}
db.close();
}
function db_status() {
if(typeof db === 'undefined') {
return false;
}
return true;
}
function db_execute_query(query, callback) {
if (!(query.indexOf('SELECT') == 0)) {
fs.appendFileSync(SQL_LOG_FILE, query + "\n");
}
//todo: Log the query being Executed here
db.all(query, callback);
return;
}
function db_create_table(query, callback) {
if(!db_status()) {
console.error("trying to create table without opening database");
callbak(true);
return false;
}
db_execute_query(query, function (err, rows) {
if (err) {
console.error("Error Executing stmt '%s' error : %s", query, err);
callback(true);
return;
}
if (rows.length === 0) {
callback(false);
return;
} else {
console.warn("Was not expecting '%d' rows", rows.length);
callback(true);
}
return;
});
}
function db_execute(query, callback) {
if (!db_status()) {
console.error("trying to create table without opening database");
callbak(true, "db not initialized yet");
return;
}
db_execute_query(query, callback);
return;
}
module.exports = {
db_init: db_open,
db_status: db_status,
db_set_path: db_set_db_path,
db_set_logfile_path: db_set_logfile_path,
db_exit: db_close,
db_new_table: db_create_table,
db_time: date_time,
db_date: date_date,
db_execute_query: db_execute,
format_user_date: format_user_date,
};
if(0) {
if (!db_open()) {
console.error("Unable to open database file");
process.exit(1);
}
db_close();
}
|
const Fornecedor = require('../models/fornecedor');
exports.test = (req, res) => res.send('Teste realizado com sucesso!');
exports.fornecedor_create = (req, res, next) => {
const fornecedor = new Fornecedor({
_id: parseInt(req.body.id),
nome: req.body.nome,
telefone: req.body.telefone,
email: req.body.email,
endereco: req.body.endereco
});
fornecedor.save(err => {
if (err)
return next(new Error(`Ocorreu um erro: ${err}`));
res.send('Fornecedor cadastrado com sucesso!!!');
});
}
exports.fornecedor_details = (req, res, next) => {
Fornecedor.findById(req.params.id, (err, fornecedor) => {
if (err)
return next(new Error(`Ocorreu um erro: ${err}`));
res.send(fornecedor);
});
}
exports.fornecedor_update = (req, res, next) => {
Fornecedor.findByIdAndUpdate(req.params.id, {$set: req.body},
(err, fornecedor) => {
if (err)
return next(new Error(`Ocorreu um erro: ${err}`));
res.send('Fornecedor alterado!');
})
}
exports.fornecedor_delete = (req, res, next) => {
Fornecedor.findByIdAndDelete(req.params.id, (err => {
if (err)
return next(new Error(`Ocorreu um erro: ${err}`));
res.send('Fornecedor excluído!');
}))
}
|
export default function filterByKeyWord(imagesArray, filterTerm) {
return imagesArray.filter(imageObject => {
const keywordPasses = !filterTerm.keyword || filterTerm.keyword === imageObject.keyword;
const hornsPasses = !filterTerm.horns || filterTerm.horns === imageObject.horns;
return hornsPasses && keywordPasses;
});
} |
import DS from 'ember-data';
import ApplicationSerializer from './application';
export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
customer: { serialize: 'records' },
basket: { serialize: 'records' }
}
}); |
const axios = require('axios');
const BASE_URL = process.env.BASE_URL
const getKeywordNews = (keyword)=>{
return axios.get(`${BASE_URL}/search?keywords=${keyword}`,{
headers: {
'Authorization' : process.env.CURRENTS_API_TOKEN
}
})
.then(({data})=>{
return data.news
})
.catch(err=>console.log(err))
}
module.exports = getKeywordNews
|
var mn = mn || {};
mn.components = mn.components || {};
mn.components.MnXDCRDelete =
(function (Rx) {
"use strict";
mn.core.extend(MnXDCRDelete, mn.core.MnEventableComponent);
MnXDCRDelete.annotations = [
new ng.core.Component({
templateUrl: "app-new/mn-xdcr-delete.html",
changeDetection: ng.core.ChangeDetectionStrategy.OnPush,
inputs: [
"replication"
]
})
];
MnXDCRDelete.parameters = [
ngb.NgbActiveModal,
mn.services.MnXDCR,
mn.services.MnForm,
mn.services.MnTasks
];
return MnXDCRDelete;
function MnXDCRDelete(activeModal, mnXDCRService, mnFormServices, mnTasksService) {
mn.core.MnEventableComponent.call(this);
this.activeModal = activeModal;
this.form = mnFormServices.create(this)
.setPackPipe(Rx.operators.map(function () {
return this.replication.id;
}.bind(this)))
.setPostRequest(mnXDCRService.stream.deleteCancelXDCR)
.successMessage("Replication deleted successfully!")
.success(function () {
activeModal.close();
mnTasksService.stream.updateTasks.next();
});
}
})(window.rxjs);
|
'use strict';
const AwsEcs = require('../aws-raw-services/AwsEcs');
const _ = require('lodash');
// const BackoffUtils = require('../../util/BackoffUtils');
class Ecs extends AwsEcs {
constructor() {
super();
}
/**
* Retireve the service or reject if not found.
* @param {String} clusterName - The name of the cluster the service to be retrieved belongs to.
* @param {String} serviceName - The name of the service to be retrieved.
*/
_retrieveService(clusterName,serviceName){
return Promise.resolve()
.then(()=>{
return this._describeServices({
services: [ serviceName ],
cluster: clusterName
});
})
.then((response)=>{
if(_.isEmpty(response.failures)){
return response.services[0];
}
else{
return Promise.reject(response.failures[0]);
}
});
}
/**
* Mutates the taskDefinition's containerDefinitions
* @param {TaskDefinition} taskDefinition - the actual taskDefinition object to be mutated
* @param {Object} upgradeDetails = Object where the keys are the container name to alter. If the value is a string that is used as the new container image version. If value is an object it will be merged into the definition.
*/
_mutateTaskDefinitionsContainerDetails(taskDefinition,upgradeDetails){
let containerDefinitions = [];
//Lop through the container definitions and update them
taskDefinition.containerDefinitions.forEach(containerDef => {
if(upgradeDetails.hasOwnProperty(containerDef.name)){//eslint-disable-line
let containerDefinitionUpgradeDetails = upgradeDetails[containerDef.name];
//allows for string (just changing the version) or object changing other settings like cpu/mem
if(_.isString(containerDefinitionUpgradeDetails)){
containerDefinitionUpgradeDetails = {version: containerDefinitionUpgradeDetails};
}
let newContainerDef = _.cloneDeep(containerDef);
//if we are upgrading the version
if(containerDefinitionUpgradeDetails.version){
let image = containerDef.image;
let repo = image.split(':')[0];
let newContainerImageAndVersion = repo + ':' + containerDefinitionUpgradeDetails.version;
newContainerDef.image = newContainerImageAndVersion;
}
//merge any other settings
_.merge(newContainerDef,containerDefinitionUpgradeDetails);
//remove version this is not apart of the
delete newContainerDef.version;
containerDefinitions.push(newContainerDef);
}
else{
containerDefinitions.push(containerDef);
}
});
taskDefinition.containerDefinitions = containerDefinitions;
return taskDefinition;
}
/**
* Mutates the taskDefinition's cpu and mem
* @param {TaskDefinition} taskDefinition - the actual taskDefinition object to be mutated
* @param {integer} cpu - The number of cpu units to use for the task see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#task_size
* @param {integer} mem - The amount of memory in MiB to use for the task, see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#task_size
*/
_mutateTaskDefinitionsCpuMem(taskDefinition,cpu,mem){
taskDefinition.cpu = cpu.toString();
taskDefinition.memory = mem.toString();
return taskDefinition;
}
_retrieveUpdatedTaskDefinition(taskDefinition,updateDetails={}){
let newTaskDef = _.cloneDeep(taskDefinition);
if(updateDetails.containerDetails){
this._mutateTaskDefinitionsContainerDetails(newTaskDef,updateDetails.containerDetails);
}
if(updateDetails.taskCpu || updateDetails.taskMem){
this._mutateTaskDefinitionsCpuMem(newTaskDef,updateDetails.taskCpu,updateDetails.taskMem);
}
return newTaskDef;
}
upgradeService(clusterName,serviceName,upgradeDetails={},opts={}){
let service = null;
return Promise.resolve()
.then(()=>{
return this._retrieveService(clusterName,serviceName);
})
.then((serviceResponse)=>{
service = serviceResponse;
return this._describeTaskDefinition({
taskDefinition: serviceResponse.taskDefinition
});
})
.then((taskDefinitionResponse)=>{
return this._retrieveUpdatedTaskDefinition(taskDefinitionResponse.taskDefinition,upgradeDetails.taskDefinition);
})
.then((newTaskDefinition)=>{
delete newTaskDefinition.taskDefinitionArn;
delete newTaskDefinition.revision;
delete newTaskDefinition.status;
delete newTaskDefinition.requiresAttributes;
delete newTaskDefinition.compatibilities;
return this._registerTaskDefinition(newTaskDefinition);
})
//update service
.then((registrationResults)=>{
//if a new desiredCount is specified use it otherwise use the existing value.
let desiredCount = _.get(upgradeDetails,'desiredTaskCount',service.desiredCount);
return this._updateService({
forceNewDeployment: opts.forceNewDeployment,
cluster: clusterName,
service: serviceName,
taskDefinition: registrationResults.taskDefinition.taskDefinitionArn,
networkConfiguration: service.networkConfiguration,
platformVersion: service.platformVersion,
healthCheckGracePeriodSeconds: service.healthCheckGracePeriodSeconds,
desiredCount: desiredCount
});
});
}
bumpServiceContainerVersions(clusterName,serviceName,containerUpgradeDetails,forceNewDeployment=true){
return this.upgradeService(clusterName,serviceName,{taskDefinition:{containerDetails:containerUpgradeDetails}},{forceNewDeployment});
}
bumpServiceTaskCpuMem(clusterName,serviceName,cpu,mem,forceNewDeployment=true){
return this.upgradeService(clusterName,serviceName,{taskDefinition:{taskCpu:cpu,taskMem:mem}},{forceNewDeployment});
}
bumpServiceDesiredTaskCount(clusterName,serviceName,desiredTaskCount,forceNewDeployment=true){
return this.upgradeService(clusterName,serviceName,{desiredTaskCount},{forceNewDeployment});
}
}
module.exports = Ecs; |
var watson = require('watson-developer-cloud');
var fs = require('fs');
var path = require('path');
var Promise = require('bluebird');
var speech_to_text = watson.speech_to_text({
username: <YOUR CREDS HERE>,
password: <YOUR CREDS HERE>,
version: 'v1',
url: 'https://stream.watsonplatform.net/speech-to-text/api',
});
exports.watsonSpeechToText = function(audioFile) {
return new Promise(function(resolve, reject) {
var params = {
content_type: 'audio/flac',
timestamps: true,
continuous: true
};
var results = [];
// create the stream
var recognizeStream = speech_to_text.createRecognizeStream(params);
// pipe in some audio
fs.createReadStream(audioFile).pipe(recognizeStream);
// listen for 'data' events for just the final text
// listen for 'results' events to get the raw JSON with interim results, timings, etc.
recognizeStream.setEncoding('utf8'); // to get strings instead of Buffers from `data` events
recognizeStream.on('results', function(e) {
if (e.results[0].final) {
results.push(e);
}
});
['data', 'results', 'error', 'connection-close'].forEach(function(eventName) {
recognizeStream.on(eventName, console.log.bind(console, eventName + ' event: '));
});
recognizeStream.on('error', function(err) {
util.handleError('Error writing to transcript.json: ' + err);
});
recognizeStream.on('connection-close', function() {
var transcriptFile = path.join(__dirname, 'transcript.json');
fs.writeFile(transcriptFile, JSON.stringify(results), function(err) {
if (err) {
util.handleError(err);
}
resolve();
});
});
});
}; |
import React, { useState } from "react";
import Header from "./components/Header";
import Home from "./components/Home";
import SideBarMenu from "./components/SideBarMenu";
function App() {
const [openMenu,setOpenMenu] = useState(false);
return (
<div className="app">
<Header setOpenMenu={setOpenMenu} />
<SideBarMenu openMenu={openMenu} setOpenMenu={setOpenMenu}/>
<Home/>
</div>
);
}
export default App;
|
import React, { Component } from "react";
import DisplayAlbum from "../components/DisplayAlbum";
import axios from "axios";
class Display extends Component {
constructor() {
super();
this.state = {
beatlesAlbums: [],
};
}
componentDidMount() {
this.getBeatlesAlbums();
}
getBeatlesAlbums = () => {
axios
.get("/api/albums")
.then((res) => {
this.setState({ beatlesAlbums: res.data });
})
.catch((err) => console.log(err));
};
render() {
const mappedAlbums = this.state.beatlesAlbums.map((album, i) => (
<DisplayAlbum
key={i}
album={album}
selectFavorite={this.props.selectFavorite}
/>
));
return <section className="albums">{mappedAlbums}</section>;
}
}
export default Display;
|
// SMILE_PLEASE //
//////////////////
// Gulp
var gulp = require('gulp');
// Sass/CSS stuff
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var minifycss = require('gulp-minify-css');
// JavaScript
var uglify = require('gulp-uglify');
// Images
var imagemin = require('gulp-imagemin');
// Stats and Things
var size = require('gulp-size');
var src = "./example";
var dest = "./example/public";
// compile all your Sass
gulp.task('sass', function (){
gulp.src([src + '/assets/styles/**/*.scss', '!' + src + '/assets/styles/_variables.scss'])
.pipe(sass({
includePaths: [src + '/assets/styles'],
outputStyle: 'expanded'
}))
.pipe(prefix(
"last 1 version", "> 1%", "ie 8", "ie 7"
))
// .pipe(gulp.dest(dest + '/css'))
// .pipe(minifycss())
.pipe(gulp.dest(dest + '/css'));
});
// Uglify JS
gulp.task('uglify', function(){
gulp.src(src + '/smilePlease.js')
.pipe(uglify())
.pipe(gulp.dest(dest + '/js'));
});
// Images
gulp.task('imagemin', function () {
gulp.src(src + '/assets/img/**/*')
.pipe(imagemin())
.pipe(gulp.dest(dest + '/img'));
});
// Stats and Things
gulp.task('stats', function () {
gulp.src(dest + '/**/*')
.pipe(size())
.pipe(gulp.dest(dest));
});
//
gulp.task('default', ['sass', 'uglify', 'imagemin']);
gulp.task('watch', ['default'], function() {
// watch me getting Sassy
gulp.watch(src + "/assets/styles/*.scss", ["sass"]);
// make my JavaScript ugly
gulp.watch(src + "/smilePlease.js", ["uglify"]);
// images
gulp.watch(src + "/assets/img/**/*", ["imagemin"]);
}); |
$(function () {
let amenityDict = {};
$('input[type=checkbox]').change(function () {
if (this.checked) {
amenityDict[$(this).data('id')] = $(this).data('name');
} else {
delete amenityDict[$(this).data('id')];
}
let amenityValues = Object.values(amenityDict);
if (amenityValues.length > 0) {
$('div.amenities > h4').text(amenityValues.join(', '));
} else {
$('div.amenities > h4').html(' ');
}
});
$.get('http://0.0.0.0:5001/api/v1/status/', function (data, textStatus) {
if (textStatus === 'success') {
$('div#api_status').addClass('available');
} else {
$('div#api_status').removeClass('available');
}
});
});
|
import Employee from '../../../../../models/erp/employee'
export default [
{
prop: 'employeeId',
label: '归属员工',
rule: { required: false, message: '请输入归属员工' },
render(h) {
const defaultOptions = this.$root.defaultOptions
const loadOptions = async value => {
if (!value) return []
const ps = [
Employee.search(1, 20, [{ filterType: 'LIKE', property: 'sn', value: value }, { filterType: 'EQ', property: 'deleted', value: false }], [], true),
Employee.search(1, 20, [{ filterType: 'LIKE', property: 'name', value: value }, { filterType: 'EQ', property: 'deleted', value: false }], [], true)
]
const results = await Promise.all(ps)
const content = _.unionWith(results[0].content, results[1].content, _.isEqual)
return content.map(it => { return { value: it.id, label: `${it.sn}(${it.name})` } })
}
return <remote-select v-model = {this.model} load-options={loadOptions} defaultOptions = {defaultOptions} placeholder='请输入工号和姓名'></remote-select>
}
}
]
|
import React from 'react';
import {
View,
Text,
TouchableOpacity,
Dimensions,
StyleSheet,
StatusBar,
Image,
span,
TextInput,
Button,
ScrollView,
ActivityIndicator,
LogBox,
Linking,
} from 'react-native';
import {
TextField,
FilledTextField,
OutlinedTextField,
} from 'react-native-material-textfield';
import { initialWindowMetrics } from 'react-native-safe-area-context';
import auth from '@react-native-firebase/auth';
import database from '@react-native-firebase/database';
class Signupp extends React.Component {
constructor(props) {
super(props);
this.state = {
check: false,
username: '',
password: '',
email: '',
x: 0,
l: 0,
};
}
signupbuttonclicking = () => {
console.log("trying to sign up")
// this.setState({l:1});
console.log("hiiii", this.state.email, this.state.password)
auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(() => {
console.log('User account created & signed in!');
alert("User account created and please log in")
// console.log("here akso we get uid bro",auth())
// var x=auth()
// console.log("okkk x is",x.uid)
// this.props.navigation.navigate('Login')
})
.catch(error => {
if (error.code === 'auth/email-already-in-use') {
console.log('That email address is already in use!');
alert(error.code)
}
if (error.code === 'auth/invalid-email') {
console.log('That email address is invalid!');
alert(error.code)
}
console.error(error);
});
// this.props.navigation.navigate('Aboutpage')
}
render() {
return (
<ScrollView style={styles.container}>
<View style={styles.header}>
<Image source={require('../images/cover.png')} style={styles.logo} />
<View style={styles.pic1}>
<Image source={require('../images/bs.png')} style={styles.pic} />
</View>
</View>
<View style={styles.footer}>
<View style={{ marginTop: 23 }}>
<OutlinedTextField
label="Username"
keyboardType="default"
labelTextStyle={{
fontWeight: 'bold',
fontFamily: 'poppins',
color: '#B0B0B0',
}}
// onChangeText={(email) => this.setState({email})}
value={this.state.email}
containerStyle={{ height: 46, borderRadius: 15 }}
inputContainerStyle={{ height: 46 }}
baseColor="black"
onChangeText={(userName) => {
this.setState({ userName: userName });
}}
/>
</View>
<View style={{ marginTop: 23 }}>
<OutlinedTextField
label="Email"
keyboardType="default"
labelTextStyle={{
fontWeight: 'bold',
fontFamily: 'poppins',
color: '#B0B0B0',
}}
// onChangeText={(email) => this.setState({email})}
value={this.state.email}
containerStyle={{ height: 46, borderRadius: 15 }}
inputContainerStyle={{ height: 46 }}
baseColor="black"
onChangeText={(emailvalue) => {
this.setState({ email: emailvalue });
}}
/>
</View>
<View style={{ marginTop: 23 }}>
<OutlinedTextField
label="Password"
keyboardType="default"
labelTextStyle={{
fontWeight: 'bold',
fontFamily: 'poppins',
color: 'black',
}}
// onChangeText={(password) => this.setState({password})}
value={this.state.password}
containerStyle={{ height: 46, borderRadius: 15 }}
inputContainerStyle={{ height: 46 }}
secureTextEntry={true}
baseColor="black"
onChangeText={(passvalue) => {
this.setState({ password: passvalue });
}}
/>
</View>
<View style={{ paddingLeft: 38 }}>
<TouchableOpacity
style={styles.button}
onPress={() => {
this.signupbuttonclicking()
this.props.navigation.navigate('Login');
}}>
<Text style={styles.ButtonText}>Signup</Text>
</TouchableOpacity>
</View>
<View style={{ flexDirection: 'row', paddingLeft: 56, marginTop: 30 }}>
<Text style={{ fontWeight: 'bold', color: '#858192' }}>
Already have an Account?
</Text>
<TouchableOpacity
onPress={() => {
console.log('singUp is pressed in login page');
this.props.navigation.navigate('Login');
}}>
<Text style={{ fontWeight: 'bold', color: '#858192' }}> Login</Text>
</TouchableOpacity>
</View>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FFFFFF',
},
header: {
flex: 2,
justifyContent: 'center',
alignItems: 'center',
paddingBottom: 4,
flexDirection: 'row',
paddingRight: 5,
paddingTop: 17,
},
footer: {
flex: 3,
width: '92%',
backgroundColor: '#FFFFFF',
paddingHorizontal: 3,
paddingVertical: 14,
marginLeft: 11,
},
logo: {
height: 295,
width: 295,
},
pic: {
height: 195,
width: 165,
position: 'absolute',
},
pic1: {
paddingRight: 164,
position: 'absolute',
paddingBottom: 150,
},
text: {
color: 'grey',
marginTop: 5,
},
button: {
marginTop: 40,
alignSelf: 'stretch',
alignItems: 'center',
padding: 20,
backgroundColor: 'white',
borderWidth: 1,
borderRadius: 30,
paddingVertical: 10,
paddingHorizontal: 1,
borderColor: '#B0B0B0',
width: 240,
height: 45,
},
ButtonText: {
fontSize: 15,
color: 'black',
borderColor: 'black',
fontWeight: 'bold',
alignSelf: 'center',
},
});
export default Signupp;
|
export default (state, action) =>{
let {type, payload } = action
switch(type){
case 'GET_DATA':
return {
...state,
datas:payload,
loading:false
}
case 'SINGLE_DATA':
return {
...state,
singleData:payload,
loading:false
}
case 'POST_DATA':
case 'EDIT_DATA':
return {
...state,
datas:[payload,...state.datas],
loading:false
}
case 'DEL_DATA':
return{
...state,
datas: state.datas.filter(data => data.id !== payload),
loading:false
}
case 'DATA_ERROR':
return {
...state,
error:payload,
loading:false
}
case 'SET_ALERT':
return{
...state,
alert:[...state.alert,payload],
loading:false
}
case 'REMOVE_ALERT':
return {
...state,
alert:state.alert.filter(alert=> alert.id !== payload),
loading:false
}
default:
return state
}
} |
//https://stackoverflow.com/questions/31174698/unable-to-prevent-an-input-from-submitting-when-press-the-enter-key-on-it
var id = document.URL.split('/');
var socket = io();
var recorder;
var audio_source = null;
/*
//https://stackoverflow.com/questions/43903963/post-html5-audio-data-to-server
var enc = ['ogg', 'webm'];
var mime = "";
enc.forEach(e => {
if (!mime && MediaRecorder.isTypeSupported(`audio/${e};codecs="opus"`)) {
mime = `audio/${e};codecs="opus"`;
}
});
console.log(mime);*/
/*var funcMidiVisualizer = require("func-midi-visualizer");
const viz_config = {
window: window,
root: document.getElementById('#midi_viz'),
width: 300,
height: 300,
midi: {
data: null
},
audio: {
data: null
},
renderer: null
};
initMidiVisualizer(viz_config).then((visualizer) => {
const playingVisualizer = visualizer.play();
}).catch((error) => console.error('Oh man, something bad happened:', error));*/
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
socket.emit('create', id[3], user.displayName);
}
else {
window.open("/login", "_self");
}
});
socket.on('owner', function(owner) {
$('#owner').val(owner.name);
});
socket.on('collabs', function(users) {
var collabs = "";
var names = Object.keys(users);
for (var i = 0; i < names.length; i++) {
if (names[i] != "owner" && (users['owner'].state == 'not recording' || users[names[i]].ready)) {
collabs += users[names[i]].name + ", ";
}
}
$('#collaborators').val(collabs.slice(0, -2));
});
// SHOW USERS ON PAGE
socket.on('update', function(users) {
var names = Object.keys(users);
for (var i = 0; i < names.length; i++) {
$('#users').append('<h4 id=' + names[i] + '>' + users[names[i]].name + '</h4>');
if (users[names[i]].ready == true) {
$('#users').find('#' + names[i]).css('color', 'green');
}
}
});
socket.on('get_access', function(is_owner) {
if (is_owner) {
$('#record').removeClass('hidden');
$('#publish').removeClass('hidden');
$('#song_name').removeClass('disabled');
}
$('#ready').removeClass('disabled');
});
socket.on('alert', function(new_user, id) {
$('#users').append('<h4 id=' + id + '>' + new_user + '</h4>');
});
socket.on('remove', function(users) {
$('#users').empty();
var names = Object.keys(users);
for (var i = 0; i < names.length; i++) {
$('#users').append('<h4 id=' + names[i] + '>' + users[names[i]].name + '</h4>');
if (users[names[i]].ready == true) {
$('#users').find('#' + names[i]).css('color', 'green');
}
}
});
socket.on('leave', function() {
window.open("/", "_self");
});
var piano = SampleLibrary.load({
instruments: "piano"
});
socket.on('send_keynote', function(note) {
// WORK ON VISUALIZER HERE
piano.toMaster();
piano.triggerAttack(note);
});
socket.on('recording', function() {
$('#record').html("Stop");
$('#record').removeClass("btn-danger");
$('#record').addClass("btn-secondary");
$('#ready').html("Recording");
$('#ready').removeClass("btn-warning");
$('#ready').addClass("btn-danger");
});
socket.on('not_ready', function() {
alert("Not everyone is ready!");
});
socket.on('show_finish', function() {
$('#ready').html("Finished!");
$('#ready').removeClass("btn-success");
$('#ready').removeClass("btn-danger");
$('#ready').addClass("btn-primary");
});
socket.on('show_ready', function(id) {
$('#users').find('#' + id).css('color', 'green');
});
socket.on('check', function() {
if ($('#ready').html() == "Finished!") {
var check = confirm("Are you ready to publish?");
socket.emit('send', check, audio_source);
}
else {
alert("You didn't finish recording!");
}
});
socket.on('submit', function(source) {
$('#audio_song').val(source);
$('#song_finish').submit();
});
socket.on('update_name', function(name) {
$('#song_name').val(name);
});
$(document).ready(function() {
$('#song_name').focus(function() {
$(document).off('keydown', playNote);
}).blur(function() {
$(document).on('keydown', playNote);
socket.emit('song_name', $('#song_name').val());
});
$(document).keypress(function(key) {
if (key.keyCode == 13) {
key.preventDefault();
}
});
$('#id').val(id[3]);
$('#ready').click(function() {
if ($('#ready').html() == "Ready") {
$('#ready').html("Waiting");
$('#ready').removeClass("btn-success");
$('#ready').addClass("btn-warning");
socket.emit('ready');
}
});
$('#record').click(function() {
if ($('#record').html() == "Record") {
navigator.mediaDevices.getUserMedia({
audio: true
})
.then(function (stream) {
recorder = new MediaRecorder(stream);
recorder.start();
console.log("recorder started");
recorder.addEventListener('dataavailable', onRecordingReady);
});
socket.emit('record');
}
else {
recorder.stop();
console.log("recorder stopped");
$('#record').hide();
socket.emit('finish');
}
});
$('#publish').click(function() {
socket.emit('publish');
});
});
function onRecordingReady(e) {
socket.emit('finish_song', URL.createObjectURL(e.data));
}
socket.on('play', function(audio_src) {
var audio = document.getElementById('audio');
// e.data contains a blob representing the recording
audio.src = audio_src;
//console.log(audio.src);
audio_source = audio_src;
audio.play();
});
|
/**
* Application logger which logs to console as well as file.
*/
const os = require('os');
const util = require('util');
const moment = require('moment');
const Storage = require('./storage.js');
function log(args, logFunc, level, tag) {
const date = new Date();
const eol = os.EOL;
const message = util.format.apply(util, args);
const logMessage = util.format('[%s @ %s] [%s] %s%s', level, moment(date).format('YYYY-MM-DD HH:mm:ss'), tag, message, eol);
logFunc(logMessage);
Storage.append({ fileName: 'punk.log', value: logMessage }, (error) => {
if(error) {
console.error('Failed to save log message.');
console.error(error);
}
});
}
function Logger(tag) {
this.tag = tag;
};
Logger.prototype.debug = function(/* arguments */) {
log(arguments, console.debug.bind(console), 'DEBUG', this.tag);
};
Logger.prototype.info = function(/* arguments */) {
log(arguments, console.info.bind(console), 'INFO', this.tag);
};
Logger.prototype.warn = function(/* arguments */) {
log(arguments, console.warn.bind(console), 'WARN', this.tag);
};
Logger.prototype.error = function(/* arguments */) {
log(arguments, console.error.bind(console), 'ERROR', this.tag);
};
function loggerFactory(tag) {
return new Logger(tag);
}
module.exports = loggerFactory;
|
controllers.controller('ChatDetailCtrl', function($scope, $stateParams, ChatService) {
ChatService.createOrReplace($scope.user.uid + '-' + $stateParams.recipientUserId);
}) |
module.exports = function(sequelize, DataTypes) {
var Transaction = sequelize.define('transaction', {
transaction: {
type: DataTypes.STRING,
allowNull: false
},
place: {
type: DataTypes.STRING,
allowNull: false
},
total: {
type: DataTypes.DECIMAL(10, 2),
allowNull: false,
defaultValue: 0.00
},
split: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0
},
date: {
type: DataTypes.DATE,
allowNull: false
},
account: {
type: DataTypes.STRING,
allowNull: false
},
placecategory1: {
type: DataTypes.STRING
},
placecategory2: {
type: DataTypes.STRING
},
placecategory3: {
type: DataTypes.STRING
}
}, {
timestamps: false
});
return Transaction;
} |
export default () => (
<svg x="0px" y="0px" viewBox="0 0 280 304" enableBackground="new 0 0 280 304">
<g>
<g>
<g>
<polyline
fill="#EDFCFF"
points="187.8,194.5 187.8,233.8 7.7,233.8 7.7,7.1 187.8,7.1 187.8,40 "
/>
<polyline
fill="none"
stroke="#004C97"
strokeWidth="5.1"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
points="
187.8,194.5 187.8,233.8 7.7,233.8 7.7,7.1 187.8,7.1 187.8,40 "
/>
</g>
<g>
<path
fill="#FFFFFF"
d="M275,117.2c0,42.7-34.6,77.3-77.3,77.3c-16.1,0-31-4.9-43.4-13.3l-40.7,2l14.8-31.8
c-5.1-10.3-8-21.9-8-34.2c0-42.7,34.6-77.2,77.3-77.2C240.4,40,275,74.5,275,117.2z"
/>
<path
fill="none"
stroke="#004C97"
strokeWidth="5.1"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
d="
M275,117.2c0,42.7-34.6,77.3-77.3,77.3c-16.1,0-31-4.9-43.4-13.3l-40.7,2l14.8-31.8c-5.1-10.3-8-21.9-8-34.2
c0-42.7,34.6-77.2,77.3-77.2C240.4,40,275,74.5,275,117.2z"
/>
</g>
<g>
<path fill="#DFF0F7" d="M7.7,233.8v63.6h152.4c15.2,0,27.7-12.5,27.7-27.8v-35.8H7.7z" />
<path
fill="none"
stroke="#004C97"
strokeWidth="5.1"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
d="
M7.7,233.8v63.6h152.4c15.2,0,27.7-12.5,27.7-27.8v-35.8H7.7z"
/>
</g>
<line
fill="none"
stroke="#004C97"
strokeWidth="5.1"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
x1="97.8"
y1="266.8"
x2="97.8"
y2="266.8"
/>
<path
fill="none"
stroke="#004C97"
strokeWidth="5.1"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
d="
M154.5,125.6c24.3,24.3,63.5,24.3,87.7,0"
/>
<path
fill="none"
stroke="#004C97"
strokeWidth="5.1"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
d="
M223.4,99.9c0,1.5-1.2,2.8-2.8,2.8c-1.5,0-2.8-1.2-2.8-2.8c0-1.5,1.2-2.8,2.8-2.8C222.2,97.1,223.4,98.3,223.4,99.9z"
/>
<path
fill="none"
stroke="#004C97"
strokeWidth="5.1"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
d="
M178.9,99.9c0,1.5-1.2,2.8-2.8,2.8c-1.5,0-2.8-1.2-2.8-2.8c0-1.5,1.2-2.8,2.8-2.8C177.7,97.1,178.9,98.3,178.9,99.9z"
/>
</g>
</g>
</svg>
);
|
import Link from 'next/link';
import css from './header.module.css';
export default function Header() {
return (
<Link href="/">
<header className={css.header}>
<h1>Freshy</h1>
</header>
</Link>
);
}
|
Vue.component('letter', {
template: `<div id="frame-letter" style="height: 100%; width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: flex-start;">
<letter-1 v-if="page == 1"></letter-1>
<letter-all v-if="page == 2"></letter-all>
</div>`,
props: {
},
data() {
return {
page: 0
};
},
created(){
},
async mounted () {
if(document.body.clientWidth < 500) {
this.page = 1;
} else {
let page = window.localStorage["japanese-letter"];
this.page = (page == "1") ? 1 : 2;
}
},
destroyed() {
},
methods: {
onChangeIndex() {
},
},
watch: {
},
}); |
// import 'babel-polyfill';
import React from 'react'
import ReactDOM from 'react-dom'
import Posts from './components/posts'
class LiveblogStream {
constructor(element, assetHandler, urls = {getURL, getNextURL}) {
const App = (
<Posts
getURL={urls.getURL}
getNextURL={urls.getNextURL}
assetHandler={assetHandler}
ref={(postsComponent) => this._postComponent = postsComponent}
/>
)
ReactDOM.render(App, element)
}
// TODO: check, if parameter contains all necessary attributes
addPost(post) {
this._postComponent.addPost(post)
}
editPost(post) {
this._postComponent.editPost(post)
}
}
window.LiveblogStream = LiveblogStream |
import React from 'react';
import './index.css';
import {Table, Tooltip, Button, Input, Space, Popconfirm, message, Modal} from 'antd';
import { SearchOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import Getandcopy from '../../components/getandcopy';
import api from '../../http/api.js';
export default class Feedback extends React.Component {
constructor(props) {
super(props);
this.state = {
columns:[],
dataSource:null,
selectedRowKeys:[],
selectedNoResolve:[],
current:1,
total:0,
}
}
componentDidMount(){
this.setState({
columns:this.initColumns()
});
this.serchData({page:1});
};
componentWillUnmount() {
this.setState = (state, callback) => {
return
}
}
resovled = (id)=>{
this.resovledto([id], '已解决');
};
resovledAll = ()=>{
Modal.confirm({
title: '确认已解决?',
icon: <ExclamationCircleOutlined />,
content: '确认将选择的所有标记为已解决?',
okText:'确定',
onOk:() =>{
this.resovledto(this.state.selectedNoResolve, '已解决');
},
cancelText:'取消',
});
};
getcounts = (callback)=>{
let selectCountArray = [];
this.state.selectedRowKeys.forEach(value=>{
let index = this.state.dataSource.findIndex(v=>v.id==value);
if (index === -1)
return;
let aindex = selectCountArray.findIndex(v=>v===this.state.dataSource[index].usercount);
if (aindex === -1){
selectCountArray.push(this.state.dataSource[index].usercount);
}
});
callback(selectCountArray.join(','));
};
//禁止和解禁某些文章
resovledto = (ids, status)=>{
let admin = JSON.parse(sessionStorage.getItem('admin'));
api.resovlefeedback(JSON.stringify({admincount:admin.count, id:ids.join(','), status}))
.then(res=>res.json())
.then(data=>{
if (data.status === 1){
let dataSource = Array.from(this.state.dataSource, value=>{
let index = ids.findIndex(v=>v==value.id);
if (index === -1)
return value;
else
return {...value,status, ...data.data}
});
let selectedNoResolve = [];
if (ids.length===1){
selectedNoResolve = this.state.selectedNoResolve.filter(item=>item !== ids[0]);
}
this.setState({
dataSource,
selectedNoResolve
});
message.destroy();
message.success('操作成功!');
}
else {
message.destroy();
message.warning('操作失败!');
}
})
.catch(error=>{
message.destroy();
message.warning('操作失败!');
});
};
//改变选中
selectChange = (e, data)=>{
let selectedNoResolve = [];
data.forEach(item=>{
if (item.status === '待解决')
selectedNoResolve.push(item.id);
});
this.setState({
selectedRowKeys:e,
selectedNoResolve
});
};
//表的任何地方发生变化
tableChange = (pagination, filters, sorter)=>{
let config = {};
//若是改变的页数,则以改变后的为准;若不是改变的页数,则表示过滤别的,需要将页数调整为1
if (this.state.current === pagination.current)
config.page = 1;
else
config.page = pagination.current;
//看过滤的哪些有值,将有值的作为过滤条件
for (let key in filters) {
if (filters[key]) {
if (key === 'type'){
let valueArray = filters[key][0].replace(/,/g,',').split(',');
valueArray = Array.from(valueArray, v=>this.ctoe(v));
config[key] = valueArray.join(',');
}
else
config[key] = filters[key][0];
}
}
//看是否需要排序
if (sorter.order){
config.orderKey = sorter.columnKey;
config.order = sorter.order==='descend'?'desc':'asc';
}
this.serchData(config);
};
//搜索数据
serchData = (config)=>{
api.getfeedback(config)
.then(res=>res.json())
.then(data=>{
if (data.status === 1){
let dataSource = Array.from(data.data,v=>{
v.key = v.id;
v.sendtime = (new Date(v.sendtime)).format('yyyy-MM-dd hh:mm:ss');
if (v.resovletime)
v.resovletime = (new Date(v.resovletime)).format('yyyy-MM-dd hh:mm:ss');
v.type = this.etoc(v.type);
return v;
});
this.setState({
dataSource,
total:data.total,
current:config.page
});
}
})
.catch(error=>{});
};
//转化类型
etoc = (e)=>{
let c = '';
switch (e) {
case 'problem':
c = '网站问题';
break;
case 'error':
c = '错误禁止';
break;
case 'advise':
c = '发展建议';
break;
default:
c=e;
break;
}
return c;
};
ctoe = (c)=>{
let e = '';
switch (c) {
case '网站问题':
e = 'problem';
break;
case '错误禁止':
e = 'error';
break;
case '发展建议':
e = 'advise';
break;
default:
e=c;
break;
}
return e;
};
//自定义过滤方式和图标等
getColumnSearchProps = title => ({
filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
<div style={{ padding: 8 }}>
<Input
ref={node => {
this.searchInput = node;
}}
placeholder={`搜索 ${title}`}
value={selectedKeys[0]}
onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
style={{ width: 188, marginBottom: 8, display: 'block' }}
/>
<Space>
<Button
type="primary"
onClick={() => this.handleSearch(selectedKeys, confirm)}
icon={<SearchOutlined />}
size="small"
style={{ width: 90 }}
>
搜索
</Button>
<Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
重置
</Button>
</Space>
</div>
),
filterIcon: filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />,
onFilterDropdownVisibleChange: visible => {
if (visible) {
setTimeout(() => this.searchInput.select(), 100);
}
},
});
handleSearch = (selectedKeys, confirm) => {
confirm();
};
handleReset = clearFilters => {
clearFilters();
};
//初始化列名
initColumns = ()=>{
let columns = [
{
title: 'ID',
width: 100,
dataIndex: 'id',
key: 'id',
fixed: 'left',
},
{
title: '发表人',
width: 100,
dataIndex: 'usercount',
key: 'usercount',
...this.getColumnSearchProps('发表人'),
},
{
title: '类型',
width: 100,
dataIndex: 'type',
key: 'type',
...this.getColumnSearchProps('发表人'),
},
{
title: '内容',
width: 150,
dataIndex: 'content',
key: 'content',
ellipsis: {
showTitle: false,
},
render: content => (
<Tooltip placement="topLeft" title={content}>
{content}
</Tooltip>
),
},
{
title: '状态',
width: 100,
dataIndex: 'status',
key: 'status',
...this.getColumnSearchProps('状态'),
},
{
title: '发表时间',
width: 150,
dataIndex: 'sendtime',
key: 'sendtime',
sorter:true,
defaultSortOrder:'descend',
showSorterTooltip:false,
},
{
title: '处理人',
width: 100,
dataIndex: 'admincount',
key: 'admincount',
...this.getColumnSearchProps('处理人'),
},
{
title: '处理时间',
width: 150,
dataIndex: 'resovletime',
key: 'resovletime',
sorter:true,
showSorterTooltip:false,
},
{
title: '操作',
key: 'action',
width: 65,
render: (text, record) => (
record.status==='待解决'&&
<Popconfirm
title="确认标记为已解决?"
onConfirm={() => this.resovled(record.key)}
cancelText='取消'
okText='确定'
>
<Button
size='small'
type='primary'
>已解决</Button>
</Popconfirm>
),
fixed:'right'
},
];
return columns;
};
render() {
return (
<div>
<div className='btn-box'>
<Getandcopy
getcontent={this.getcounts}
disabled={this.state.selectedRowKeys.length===0}
btntext='获取所选账户'
/>
<div>
<Button
onClick={this.resovledAll}
size='small'
type="primary"
disabled={this.state.selectedNoResolve.length===0}
>
标记所选
</Button>
</div>
</div>
{
this.state.dataSource &&
<Table
columns={this.state.columns}
dataSource={this.state.dataSource}
scroll={{ x: 1015 }}
size='small'
rowSelection={{
selectedRowKeys:this.state.selectedRowKeys,
onChange:this.selectChange,
}}
onChange={this.tableChange}
pagination={{
current:this.state.current,
hideOnSinglePage:true,
showSizeChanger:false,
defaultPageSize:15,
total:this.state.total
}}
/>
}
</div>
);
}
} |
var Crawler = require('../../crawler.js').Crawler;
describe('Crawler._onResponse method', function () {
'use strict';
var body;
var crawler;
var crawlPageSpy;
var failureSpy;
var finishCallbackSpy;
var pageInfo;
var processRedirectSpy;
var successSpy;
beforeEach(function () {
body = 'my body';
crawler = new Crawler();
pageInfo = {
page: {
url: 'http://www.google.com/'
}
};
crawlPageSpy = spyOn(crawler, '_crawlPage');
failureSpy = spyOn(crawler, '_responseError');
finishCallbackSpy = jasmine.createSpy('finishCallback');
processRedirectSpy = spyOn(crawler, '_processRedirect');
successSpy = spyOn(crawler, '_responseSuccess');
spyOn(crawler, 'queue');
});
it('exists', function () {
expect(crawler._onResponse instanceof Function).toBe(true);
});
it('always converts response to an object', function () {
// These calls should fail if this is not handled
crawler._onResponse(pageInfo, null, '', '', function () {});
crawler._onResponse(pageInfo, null, null, '', function () {});
crawler._onResponse(pageInfo, null, undefined, '', function () {});
crawler._onResponse(pageInfo, null, [], '', function () {});
});
describe('when killed', function () {
var result;
beforeEach(function () {
crawler._killed = true;
result = crawler._onResponse(pageInfo, null, {}, '', finishCallbackSpy);
});
it('returns false', function () {
expect(result).toBe(false);
});
it('runs finish callback', function () {
expect(finishCallbackSpy).toHaveBeenCalled();
});
it('does not run _processRedirect', function () {
expect(processRedirectSpy).not.toHaveBeenCalled();
});
it('does not run _responseSuccess', function () {
expect(successSpy).not.toHaveBeenCalled();
});
it('does not run _crawlPage', function () {
expect(crawlPageSpy).not.toHaveBeenCalled();
});
});
describe('- on redirect -', function () {
var response;
beforeEach(function () {
pageInfo.page.url = 'http://www.google.com/';
pageInfo.page.isExternal = false;
response = { statusCode: 200, url: 'http://www.alreadycrawled.com/' };
});
it('marks pages as external when final URL is not on the same domain', function () {
crawler._onResponse(pageInfo, null, response, '', finishCallbackSpy);
expect(pageInfo.page.isExternal).toBe(true);
});
it('calls _processRedirect', function () {
crawler._onResponse(pageInfo, null, response, '', finishCallbackSpy);
expect(processRedirectSpy).toHaveBeenCalledWith(pageInfo, response.url, response);
});
describe('when _processRedirect returns null', function () {
beforeEach(function () {
processRedirectSpy.andReturn(null);
crawler._onResponse(pageInfo, null, response, '', finishCallbackSpy);
});
it('executes the finishCallback', function () {
expect(finishCallbackSpy).toHaveBeenCalled();
});
it('does not execute _responseSuccess', function () {
expect(successSpy).not.toHaveBeenCalled();
});
it('does not execute _responseError', function () {
expect(failureSpy).not.toHaveBeenCalled();
});
});
describe('when _processRedirect returns non-null', function () {
beforeEach(function () {
processRedirectSpy.andReturn({ page: { url: 'http://www.alreadycrawled.com/' } });
});
it('executes _responseSuccess if successful', function () {
crawler._onResponse(pageInfo, null, response, '', finishCallbackSpy);
expect(successSpy.calls[0].args[0]).toEqual({ page: { url: 'http://www.alreadycrawled.com/' } });
});
it('executes _responseError if failed', function () {
crawler._onResponse(pageInfo, true, response, '', finishCallbackSpy);
expect(failureSpy.calls[0].args[0]).toEqual({ page: { url: 'http://www.alreadycrawled.com/' } });
});
});
});
describe('on 200 response', function () {
var response;
beforeEach(function () {
response = {
statusCode: 200
};
});
it('executes _responseSuccess method', function () {
crawler._onResponse(pageInfo, null, response, body, finishCallbackSpy);
expect(successSpy).toHaveBeenCalled();
expect(successSpy.calls[0].args[0]).toBe(pageInfo);
expect(successSpy.calls[0].args[1]).toEqual(response);
expect(successSpy.calls[0].args[2]).toEqual(body);
expect(successSpy.calls[0].args[3]).toBe(finishCallbackSpy);
});
it('does not execute _responseError', function () {
crawler._onResponse(pageInfo, null, response, body, finishCallbackSpy);
expect(failureSpy).not.toHaveBeenCalled();
});
it('does not execute _responseSuccess method when errors occur (when error is not null)', function () {
crawler._onResponse(pageInfo, true, response, body, finishCallbackSpy);
expect(successSpy).not.toHaveBeenCalled();
});
});
describe('on non 200 response', function () {
var response;
beforeEach(function () {
response = {
statusCode: 400
};
});
it('executes _responseError method', function () {
crawler._onResponse(pageInfo, null, response, body, finishCallbackSpy);
expect(failureSpy).toHaveBeenCalled();
expect(failureSpy.calls[0].args[0]).toBe(pageInfo);
expect(failureSpy.calls[0].args[1]).toEqual(response);
expect(failureSpy.calls[0].args[2]).toEqual(null);
expect(failureSpy.calls[0].args[3]).toBe(finishCallbackSpy);
});
onErrorSpecs(response, null);
});
describe('on error', function () {
var response;
beforeEach(function () {
response = {
statusCode: 200
};
});
it('executes _responseError method', function () {
crawler._onResponse(pageInfo, true, response, body, finishCallbackSpy);
expect(failureSpy).toHaveBeenCalled();
expect(failureSpy.calls[0].args[0]).toBe(pageInfo);
expect(failureSpy.calls[0].args[1]).toEqual(response);
expect(failureSpy.calls[0].args[2]).toEqual(true);
expect(failureSpy.calls[0].args[3]).toBe(finishCallbackSpy);
});
onErrorSpecs(response, true);
});
describe('on parse errors with external links that return 200 and include a content-length header', function () {
var response;
beforeEach(function () {
pageInfo.page.isExternal = true;
response = { statusCode: 200, headers: { 'content-length': '4' } };
crawler._onResponse(pageInfo, { code: 'HPE_INVALID_CONSTANT' }, response, body, finishCallbackSpy);
});
it('does not execute _responseError method', function () {
expect(failureSpy).not.toHaveBeenCalled();
});
it('executes _responseSuccess method', function () {
expect(successSpy).toHaveBeenCalledWith(pageInfo, response, body, finishCallbackSpy);
});
});
function onErrorSpecs(response, error) {
it('does not execute _responseSuccess', function () {
crawler._onResponse(pageInfo, error, response, body, finishCallbackSpy);
expect(successSpy).not.toHaveBeenCalled();
});
it('sets the page\'s retries to 0 if it does not have the property already', function () {
crawler.retries = 1;
pageInfo.page._retries = undefined;
crawler._onResponse(pageInfo, error, response, body, finishCallbackSpy);
// Information is stored in pageInfo instead of the Page object
expect(pageInfo._retries).toBe(1); // Note: it increments by 1
});
it('increases the number of retries if the page\'s retries is less than the number of retries specified in the crawler', function () {
crawler.retries = 1;
pageInfo.page._retries = 0;
crawler._onResponse(pageInfo, error, response, body, finishCallbackSpy);
// Information is stored in pageInfo instead of the Page object
expect(pageInfo._retries).toBe(1);
});
it('does not increase the number of retries if the page\'s retries is equal to or greater than the number of retries specified in the crawler', function () {
crawler.retries = 1;
pageInfo.page._retries = 1;
crawler._onResponse(pageInfo, error, response, body, finishCallbackSpy);
expect(pageInfo.page._retries).toBe(1);
});
it('does not process retries if the crawlers retries are set to 0', function () {
crawler.retries = 0;
crawler._onResponse(pageInfo, error, response, body, finishCallbackSpy);
expect(pageInfo.page._retries).not.toBeDefined();
});
it('runs _crawlPage method if a retry should occur', function () {
crawler.retries = 1;
crawler._onResponse(pageInfo, error, response, body, finishCallbackSpy);
expect(crawlPageSpy).toHaveBeenCalledWith(pageInfo, finishCallbackSpy);
});
it('does not execute _responseError method if a retry occurs', function () {
crawler.retries = 1;
crawler._onResponse(pageInfo, error, response, body, finishCallbackSpy);
expect(failureSpy).not.toHaveBeenCalled();
});
}
});
|
(function () {
var app = angular.module('services', []);
app.factory('productLoader', ['$http', '$log', function ($http, $log) {
return function(callback) {
callback = callback || function(){};
$http.get('shopItems.json')
.success(callback)
.error(function (data, status) {
$log.error('Error ' + status + ' unable to download the product list.');
});
};
}]);
})();
// (function () {
//
// var app = angular.module('services', []);
//
// app.factory('productLoader', ['$http', '$log', function ($http, $log) {
// return function() {
// $http.get('shopItems.json')
// .success(function (data, status, headers, config) {
//
// $scope.shopOffer = data;
// $log.info('Product list loaded from the server.');
//
// }).error(function (data, status, headers, config) {
//
// $log.error('Error ' + status + ' unable to download the product list.');
//
// });
// };
// }]);
//
// })();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.