text stringlengths 7 3.69M |
|---|
$(function() {
// 初始化加载
loadData();
var status = $("#status").val();
if (status != "未开始") {
$("#addExam").hide();
}
});
function loadData() {
var tbSubject_name = $("#tbSubject_name").textbox('getValue');;// 考试名称
if(tbSubject_name!=null && tbSubject_name!=""){
var regex = new RegExp("^[a-zA-Z0-9\u4e00-\u9fa5]+$");// 不包含“-”
var res = regex.test(tbSubject_name);
if(res!=true){
return $.messager.alert('提示', "您好,课程只允许输入数字、字母和汉字", 'warning');;
}
}
var tbExam_id = $("#tbExam_Id").val();
var tbSubject_addTime = $("#tbSubject_addTime").datebox('getValue');// 创建时间--开始
var tbSubject_endTime = $("#tbSubject_endTime").datebox('getValue');// 创建时间---结束
var date = verificationDate(tbSubject_addTime,tbSubject_endTime);
if (date == false) {
return false;
}
$('#data-list')
.datagrid(
{
url : ctx + '/tbExamSubject/list',
columns : [ [
{
field : 'tci_name',
title : '课程名称',
width : 200,
align : 'center',
resizable : 'false'
},
{
field : 'tec_begin_time',
title : '开始时间',
width : 150,
align : 'center',
sortable : true
},
{
field : 'tesr_end_time',
title : '结束时间',
width : 150,
align : 'center',
sortable : true
},
{
field : 'tesr_add_time',
title : '创建时间',
width : 150,
align : 'center',
sortable : true
},
{
field : 'pay',
title : '操作',
width : 150,
align : 'center',
width : 200,
resizable : 'false',
formatter : function(value, rec) {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth()+1;
if (month <=9) {
month = "0"+month;
}
var day = date.getDate();
if (day <=9) {
day = "0"+day;
}
var hour = date.getHours();
if (hour <= 9) {
hour = "0"+hour;
}
var minute = date.getMinutes();
if (minute <=9) {
minute = "0"+minute;
}
var second = date.getSeconds();
var currentdate = year+'-'+month+'-'+day+'-'+hour+':'+minute+':'+second
var html = "";
html += '<a onclick="info(\''+ rec.tec_id+ '\')" href="javascript:void(0)">详情</a>';
if ($("#tbExam_statusa").val() == 1) {
html += '<a onclick="update(\''+ rec.tec_id+ '\')" href="javascript:void(0)">编辑</a> | ';
html += '<a onclick="del(\''+ rec.tec_id+ '\')" href="javascript:void(0)">删除</a>';
}else if (rec.tesr_end_time < currentdate) {
html += '  | <a onclick="inputScore(\''+ rec.tec_id+ '\')" href="javascript:void(0)">录入成绩</a>';
}
return html;
}
},
] ],
queryParams : {
tbSubjectName : tbSubject_name,
addTime : tbSubject_addTime,
endTime : tbSubject_endTime,
tbExam_id : tbExam_id
},
rownumbers : true,
singleSelect : true,
fit : true,
striped : true,
fitColumns : true,
sortName : 'tesr_add_time',
sortOrder : 'desc',
nowrap : false,
pagination : true,
sortable : true,
remoteSort : true,
rowStyler : function(index, row) {
if ((index % 2) != 0) {
return 'background-color:#FAFAD2;';
}
},
pageSize : 15,
pageList : [ 10, 15, 20, 30, 40, 50 ],
onLoadSuccess : function(data) {
$('.infocls').linkbutton({
text : '详情',
plain : true,
iconCls : 'icon-search'
});
$('.delcls').linkbutton({
text : '删除',
plain : true,
iconCls : 'icon-remove'
});
$('.searchcls').linkbutton({
text : '查询',
plain : true,
iconCls : 'icon-search'
});
$('.updatecls').linkbutton({
text : '修改',
plain : true,
iconCls : 'icon-edit'
});
$('.addcls').linkbutton({
text : '新增',
plain : true,
iconCls : 'icon-add'
});
$('.addScore').linkbutton({
text : '录入成绩',
plain : true,
iconCls : 'icon-add'
});
}
});
}
function tbExamAdd() {
parent.addTabFun({
src : ctx + "/tbExamSubject/index/add?tbExamSubjectId="+$("#tbExam_Id").val(),
title : "新增考试"
});
}
function addSubjects(id) {
parent.addTabFun({
src : ctx + "/tbExamSubject/index/list?tbExamSubjectId="+id,
title : "考试科目"
});
}
function update(id) {
parent.addTabFun({
src : ctx + "/tbExamSubject/index/edit?tbExamSubjectId="+id,
title : "编辑考试"
});
}
function info(id) {
parent.addTabFun({
src : ctx + "/tbExamSubject/index/info?tbExamSubjectId="+id,
title : "考试详情"
});
}
function inputScore(id) {
parent.addTabFun({
src : ctx + "/tbExamSubject/index/inputScore?tbExamSubjectId="+id,
title : "录入成绩"
});
}
function del(TbExamId) {
$.messager.confirm("提示","您确认要删除吗,删除不可恢复哦!",function(r){
if(r){
$.ajax({
type:"POST",
dataType:'JSON',
url:ctx+ '/tbExamSubject/del',
data:{TbExamId:TbExamId},
success:function(data){
if(data=='100'){
$.messager.alert('提示','删除成功!');
$('#data-list').datagrid("load");
}else if(data=='101'){
$.messager.alert("登录超时!");
}else{
$.messager.alert("数据有误,请联系技术人员核查!");
}
}
});
}
});
}
function verificationDate(AddDate,AddDateEnd){
// 如果有结束时间没有开始时间
if ((AddDate == '') && (AddDateEnd != '')) {
// 提醒用户
$.messager.alert("提示", "请选择开始时间", "info");
return false;
}
// 如果有开始时间没有结束时间
// if ((AddDate != '') && (AddDateEnd == '')) {
// AddDateEnd = formatDate(new Date());
// $("#tbSubject_endTime").datebox('setText', AddDateEnd);
// $("#tbSubject_endTime").datebox('setValue', AddDateEnd);
// // 结束时间设为现在
// }
// 开始时间和技术时间都不为空
if ((AddDate != '') && (AddDateEnd != '')) {
// 结束时间大于开始时间
if (AddDateEnd < AddDate) {
$.messager.alert("提示", "结束时间不能小于开始时间", "info");
$("#AddDateEnd").datebox('setText', '');
$("#AddDateEnd").datebox('setValue', '');
return false;
}
// 时间跨度不能超过1年
var start = new Date(AddDate.replace(/-/g, "/")).getTime();
var end = new Date(AddDateEnd.replace(/-/g, "/")).getTime();
if (end - start > 12 * 24 * 30.416666 * 60 * 60 * 1000) {
$.messager.alert("提示", "时间跨度不能超过一年", "info");
// 不合格把结束日期设置为空
$("#tbSubject_addTime").datebox('setText', '');
$("#tbSubject_addTime").datebox('setValue', '');
$("#tbSubject_endTime").datebox('setText', '');
$("#tbSubject_endTime").datebox('setValue', '');
return false;
}
}
} |
describe('VglAxesHelper:', function suite() {
const { VglAxesHelper, VglNamespace } = VueGL;
it('without properties', function test(done) {
const vm = new Vue({
template: '<vgl-namespace><vgl-axes-helper ref="h" /></vgl-namespace>',
components: { VglAxesHelper, VglNamespace },
}).$mount();
vm.$nextTick(() => {
try {
const actual = new THREE.LineSegments().copy(vm.$refs.h.inst);
actual.geometry = vm.$refs.h.inst.geometry;
actual.material = vm.$refs.h.inst.material;
actual.updateMatrixWorld();
const expected = new THREE.AxesHelper();
expected.updateMatrixWorld();
expected.uuid = actual.uuid;
expected.geometry.uuid = actual.geometry.uuid;
expected.material.uuid = actual.material.uuid;
expect(actual.toJSON()).to.deep.equal(expected.toJSON());
done();
} catch (e) {
done(e);
}
});
});
it('with properties', function test(done) {
const vm = new Vue({
template: '<vgl-namespace><vgl-axes-helper size="88.73" position="3 3.5 0.2" rotation="0.3 0.3 0.2 XYZ" scale="1.1 1.2 0.9" ref="h" /></vgl-namespace>',
components: { VglAxesHelper, VglNamespace },
}).$mount();
vm.$nextTick(() => {
try {
const actual = new THREE.LineSegments().copy(vm.$refs.h.inst);
actual.geometry = vm.$refs.h.inst.geometry;
actual.material = vm.$refs.h.inst.material;
actual.updateMatrixWorld();
const expected = new THREE.AxesHelper(88.73);
expected.position.set(3, 3.5, 0.2);
expected.rotation.set(0.3, 0.3, 0.2, 'XYZ');
expected.scale.set(1.1, 1.2, 0.9);
expected.updateMatrixWorld();
expected.uuid = actual.uuid;
expected.geometry.uuid = actual.geometry.uuid;
expected.material.uuid = actual.material.uuid;
expect(actual.toJSON()).to.deep.equal(expected.toJSON());
done();
} catch (e) {
done(e);
}
});
});
it('after properties are changed', function test(done) {
const vm = new Vue({
template: '<vgl-namespace><vgl-axes-helper :size="sz" :position="p" :rotation="r" :scale="sc" ref="h" /></vgl-namespace>',
components: { VglAxesHelper, VglNamespace },
data: {
sz: '1.1',
p: '3 3.5 0.2',
r: '0.3 0.3 0.2 XYZ',
sc: '1.1 1.2 0.9',
},
}).$mount();
vm.$nextTick(() => {
vm.sz = '12';
vm.p = '3.5 4 0.5';
vm.r = '0.4 0.4 0.3 XYZ';
vm.sc = '1 1 1.1';
vm.$nextTick(() => {
try {
const actual = new THREE.LineSegments().copy(vm.$refs.h.inst);
actual.geometry = vm.$refs.h.inst.geometry;
actual.material = vm.$refs.h.inst.material;
actual.updateMatrixWorld();
const expected = new THREE.AxesHelper(12);
expected.position.set(3.5, 4, 0.5);
expected.rotation.set(0.4, 0.4, 0.3, 'XYZ');
expected.scale.set(1, 1, 1.1);
expected.updateMatrixWorld();
expected.uuid = actual.uuid;
expected.geometry.uuid = actual.geometry.uuid;
expected.material.uuid = actual.material.uuid;
expect(actual.toJSON()).to.deep.equal(expected.toJSON());
done();
} catch (e) {
done(e);
}
});
});
});
});
|
const EmployeePayRoll = require('F:\employeepay-roll-app\employee-payroll-app\employeePayroll.js');
const EmployeePayrollForm = require('F:\employeepay-roll-app\employee-payroll-app\employeePayRollApp.html');
window.addEventListener('DOMContentLoaded', (event) => {
const name = document.querySelector('#name');
const nameError = document.querySelector('.name-error');
name.addEventListener('input', function(){
if (name.value.length == 0) {
nameError.textContent = "";
return;
}
try {
(new EmployeePayrollApp()).name = name.value;;
nameError.textContent = "";
}
catch (e) {
nameError.textContent = e;
}
const salary = document.querySelector('#salary');
const output = document.querySelector('.salary-output');
output.textContent = salary.value;
salary.addEventListener('input', function () {
output.textContent = salary.value;
});
});
}); |
var api = require("../../utils/api.js");
var util = require("../../utils/util.js");
var app = getApp();
Page({
data: {
questions: {},
id: 0,
translate: "",
focus: false
},
onLoad: function(options) {
wx.setNavigationBarTitle({
title: "文本任务"
});
var that = this;
wx.request({
url: api.getProject() + "/" + options.id + api.getTask(),
data: {},
method: "get",
header: {
"Content-Type": "application/json;charset=utf-8",
Cookie: app.getSid()
},
success: function(res) {
that.setData({
questions: res.data.questions
});
}
});
},
bindTextCon: function(e) {
this.setData({
focus: true
});
},
bindFormSubmit: function(e) {
if (e.detail.value.translate !== "") {
wx.showModal({
content: "保存成功",
showCancel: false,
success: function(res) {
wx.switchTab({
url: "../index/index",
success: function() {}
});
}
});
} else {
wx.showModal({
content: "请输入内容",
showCancel: false
});
}
}
}); |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/* ServerHello message layout:
* 00: Version_Major (MSB)
* 01: Version_Minor (LSB)
* 02: UTC + random offset (MSB)
* 03: UTC + random offset (continued)
* 04: UTC + random offset (continued)
* 05: UTC + random offset (LSB)
* 06...33: Random (28 bytes)
* 34: Session ID Length
* .......: Session ID (if a session ID is present)
* .......: Cipher Suite (2 bytes)
* .......: Compression Method (1 byte)
*/
let enums = require('../../enums.js');
// constants
const RANDOM_LENGTH = 32; // NOTE: the first four bytes are the Utc value (with a random offset which should be set by the server)
const MIN_LENGTH = 40;
//
const MAX_SESSION_ID_LENGTH = (1 << 8) - 1;
function ServerHelloMessage() {
this.dtlsVersion = null;
this.random = null;
this.sessionId = null;
this.cipherSuite = null;
this.compressionMethod = null;
}
// NOTE: this function returns null if a complete message could not be parsed (and does not validate any data in the returned message)
// NOTE: offset is optional (default: 0)
exports.fromBuffer = function(buffer, offset) {
// use currentOffset to track the current offset while reading from the buffer
let initialOffset;
let currentOffset;
// validate inputs
//
// offset
if (typeof offset === "undefined") {
initialOffset = 0;
} else if (typeof offset !== "number") {
// if the offset is provided, but is not a number, then return an error
throw new TypeError();
} else if (offset >= buffer.length) {
throw new RangeError();
} else {
initialOffset = offset;
}
currentOffset = initialOffset;
// buffer
if (typeof buffer === "undefined") {
throw new TypeError();
} else if (buffer === null) {
// null buffer is NOT acceptable
} else if (Object.prototype.toString.call(buffer) != "[object Uint8Array]") {
throw new TypeError();
} else if (buffer.length - currentOffset < MIN_LENGTH) {
// buffer is not long enough for a full message; return null.
return null;
}
// create the new ServerHelloMessage object
let result = new ServerHelloMessage();
// parse buffer
//
// dtlsVersion (octets 0-1)
result.dtlsVersion = buffer.readUInt16BE(currentOffset);
currentOffset += 2;
// random (octets 2-33)
result.random = new Buffer.alloc(RANDOM_LENGTH);
buffer.copy(result.random, 0, currentOffset, currentOffset + result.random.length);
currentOffset += RANDOM_LENGTH;
// sessionId length (octet 34)
let sessionIdLength = buffer[currentOffset];
currentOffset += 1;
// verify that the buffer length is long enough to fit the session
if (buffer.length - offset - MIN_LENGTH < sessionIdLength) {
// if the buffer is not big enough, return null
return null;
}
// sessionId
result.sessionId = Buffer.alloc(sessionIdLength);
buffer.copy(result.sessionId, 0, currentOffset, currentOffset + sessionIdLength);
currentOffset += sessionIdLength;
// cipherSuite (two octets)
result.cipherSuite = buffer.readUInt16BE(currentOffset);
currentOffset += 2;
// compressionMethod (one octet)
result.compressionMethod = buffer[currentOffset];
currentOffset += 1;
// return the new ServerHelloMessage object
return {message: result, bytesConsumed: currentOffset - initialOffset};
} |
import React, {useState} from 'react'
import {useSelector, useDispatch} from 'react-redux'
import {Form, FormGroup, Label, Input, Button, Col, Progress} from 'reactstrap'
import { CKEditor } from '@ckeditor/ckeditor5-react'
import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor'
import {editorConfiguration} from '../../components/editor/EditorConfig'
import Myinit from '../../components/editor/UploadAdapter'
import {set} from 'mongoose'
const PostWrite = () => {
const {isAuthenticated} = useSelector((state) => state.auth)
const [form, setValues] = useState({title: '', contents:'', fileUrl: ''})
const dispatch = useDispatch()
const onChange = (e) => {
setValues({
...form,
[e.target.name]: e.target.value
})
}
const onSubmit = async(e) => {
await e.preventDefault()
const {title, contents, fileUrl, category} = form
}
const getDataFromCKEditor = (event, editor) => {
const data = editor.getData()
if(data && data.match('<img src=')) {
const whereImg_start = data.indexOf('<img src=')
let whereImg_end = ''
let ext_name_find = ''
let result_Img_Url = ''
const ext_name = ['jpeg', 'png', 'jpg', 'gif']
for(let i = 0; i<ext_name.length; i++) {
if (data.match(ext_name[i])) {
console.log(data.indexOf(`${ext_name[i]}`))
ext_name_find = ext_name[i]
whereImg_end = data.indexOf(`${ext_name[i]}`)
}
}
if(ext_name_find === 'jpeg') {
result_Img_Url = data.substring(whereImg_start+10,whereImg_end+4)
} else {
result_Img_Url = data.substring(whereImg_start+10, whereImg_end+3)
}
console.log(result_Img_Url, 'result img url')
setValues({
...form,
fileUrl : result_Img_Url,
contents : data
})
} else {
setValues({
...form,
fileUrl: 'http://source.unsplash.com/random/301x201',
contents: data
})
}
}
return (
<div>
{isAuthenticated ? (
<Form>
<FormGroup className='mb-3'>
<Label for='title'>title</Label>
<Input
type='text'
name='title'
id='title'
className='form-control'
onChange={onChange}
/>
</FormGroup>
<FormGroup className='mb-3'>
<Label for='category'>category</Label>
<Input
type='text'
name='category'
id='category'
className='form-control'
onChange={onChange}
/>
</FormGroup>
<FormGroup className='mb-3'>
<Label for='contents'>contents</Label>
<CKEditor
editor={ClassicEditor}
config={editorConfiguration}
onReady={Myinit}
onBlur={getDataFromCKEditor}
/>
<Button color='success' block className='mt-3 col-md-2 offset-md-10 mb-3'>
제출하기
</Button>
</FormGroup>
</Form>
) : (
<Col width={50} className='p-5 m-5'>
<Progress animated color='info' value={100}/>
</Col>
)}
</div>
)
}
export default PostWrite |
let path = require('path');
const rimraf = require('mz-modules/rimraf');
const mkdirp = require('mz-modules/mkdirp');
let ncp = require('ncp').ncp;
const dist_path = './dist/';
function init() {
clear_create_dist().then(copy_files);
}
function clear_create_dist() {
return rimraf(dist_path).then(function() {
return mkdirp(dist_path);
});
}
function copy_files() {
let files = ['./marscss.scss', './scss/'];
files.forEach(function(value) {
let destination = path.join(dist_path, value);
ncp(value, destination);
});
}
init();
|
export default /* glsl */`
// convert clip space position into texture coordinates to sample scene grab textures
vec2 getGrabScreenPos(vec4 clipPos) {
vec2 uv = (clipPos.xy / clipPos.w) * 0.5 + 0.5;
#ifdef WEBGPU
uv.y = 1.0 - uv.y;
#endif
return uv;
}
// convert uv coordinates to sample image effect texture (render target texture rendered without
// forward renderer which does the flip in the projection matrix)
vec2 getImageEffectUV(vec2 uv) {
#ifdef WEBGPU
uv.y = 1.0 - uv.y;
#endif
return uv;
}
`;
|
import ReadLaterList from './ReadLaterList';
export{ReadLaterList}; |
import React from 'react';
export default class Seat extends React.Component {
render() {
const { hands = [], who, dealersTurn, currentHand = 0 } = this.props;
var seatClassName = `pocket ${who}`;
return (
<div className={seatClassName}>
{hands.map((hand, index) => {
var active;
currentHand == index && who == 'player' ? active = 'active' : null;
var handClassName = `hand ${active}`;
return <div className={handClassName} key={index}>{hand.cards.map((card, index) => {
return (dealersTurn || who != 'dealer' || index != 1) ? <img key={index} src={require(`../cardImages/${card.name}_of_${card.suit}.svg`)} /> : <img key={index} className='cardImage' src={require(`../cardImages/Card_back.svg`)} alt='card back' />
})}
<div className='resultPanel' >{hand.result}</div>
</div>
})}
</div>
);
};
}
|
import React from 'react';
import './App.css';
import Navbar from './Navbar';
import Explore from './component/Explore';
import {
BrowserRouter as Router,
Route,
} from 'react-router-dom';
import Tag from './component/Tag';
import Photo from './component/Photo';
import axios from 'axios';
import {api_key} from './config';
const url = (page) => (`https://api.flickr.com/services/rest/?method=flickr.interestingness.getList&api_key=${api_key}&extras=url_m%2C+url_c%2C+owner_name%2C+views%2C+tags%2C+description%2C+date_taken&per_page=20&page=${page}&format=json&nojsoncallback=1`);
const captionStyle = {
backgroundColor: "rgba(0, 0, 0, 0.7)",
maxHeight: "240px",
overflow: "hidden",
position: "absolute",
bottom: "0",
width: "100%",
color: "white",
padding: "10px",
fontSize: "90%"
};
class App extends React.Component {
constructor(props){
super(props);
this.state = {
listPhotos: [],
curPage: 0,
pages: 0
}
}
loadFunc(page){
axios.get(url(page))
.then(res => {
this.setState({
listPhotos: [...this.state.listPhotos,...res.data.photos.photo],
curPage: page,
pages: res.data.photos.pages
})
})
.catch(err => {
})
}
loadGridPhoto(){
return this.state.listPhotos.map((photo, index) => {
return {
id: photo.id,
src: photo.url_m,
thumbnail: photo.url_m,
thumbnailWidth: parseInt(photo.width_m,10),
thumbnailHeight: parseInt(photo.height_m,10),
customOverlay: (
<div style={captionStyle}>
<b>{photo.title}</b>
<div>Owner: {photo.ownername}</div>
<div>Views: {photo.views}</div>
</div>)}
})
}
searchTag(tag){
let photoInTag=[];
this.state.listPhotos.map((photo,index)=>{
if(photo.tags.search(tag) !== -1){
photoInTag.push({
id: photo.id,
src: photo.url_m,
thumbnail: photo.url_m,
thumbnailWidth: parseInt(photo.width_m,10),
thumbnailHeight: parseInt(photo.height_m,10),
customOverlay: (
<div style={captionStyle}>
<b>{photo.title}</b>
<div>Owner: {photo.ownername}</div>
<div>Views: {photo.views}</div>
</div>)});
}
return '';
});
return photoInTag;
}
render() {
return (
<Router>
<div>
<Route render={(props)=><Navbar {...props}/>}/>
<Route exact path="/" render={(props)=><Explore {...props} photo={this.state}
loadFunc={()=>this.loadFunc(this.state.curPage+1)}
loadGridPhoto={()=>{return this.loadGridPhoto()}}/>}/>
<Route path="/photo" render={(props)=><Photo {...props} photo={this.state}
loadFunc={()=>this.loadFunc(this.state.curPage+1)}/>}/>
<Route path="/tag" render={(props)=><Tag {...props} photo={this.state}
loadFunc={()=>this.loadFunc(this.state.curPage+1)}
loadGridPhoto={(tag)=>{return this.searchTag(tag)}}/>}/>
</div>
</Router>
);
}
}
export default App;
|
import { connectDB } from './connect'
export const addNewTask = async task => {
let db = await connectDB();
let collection = db.collection(`tasks`);
await collection.insertOne(task);
};
export const updateTask = async task => {
let { id, group, isComplete, name } = task;
let db = await connectDB();
let collection = db.collection(`tasks`);
if (group) {
await collection.updateOne({ id }, { $set: { group } }); //find props (id), whatver is "set" to the group find it
}
if (name) {
await collection.updateOne({ id }, { $set: { name } }); //find props (id), whatver is "set" to the name find it
}
if (isComplete !== undefined) {
await collection.updateOne({ id }, { $set: { isComplete } }); //find props (id), whatver is "set" to the isComplete find it
}
}; |
/* eslint-disable react/prop-types */
import React from 'react';
import styled from 'styled-components';
import { palette, font } from 'styled-theme';
import Header from '../Header';
import Footer from '../Footer';
const LayoutWrapper = styled.div`
display: flex;
height: 100%;
flex-direction: column;
font-family: ${font('primary')};
background: ${palette('grayscale', 0, true)};
main {
flex-grow: 1;
}
`;
const Layout = ({ children }) => (
<LayoutWrapper>
<Header />
<main>{children}</main>
<Footer />
</LayoutWrapper>
);
export default Layout;
|
const request = require('supertest')
const app = require('../app')
// Setup a Test Database
const { setupDB } = require('./test-setup')
setupDB('endpoint-testing')
const Customer = require('../models/customer')
describe('POST /customers', () => {
/**
* testing /GET endpoints on Customer resource
*/
const customer = {
name: "David",
email: "email@email.com",
password: "password"
}
it("should save user to database", async () => {
const response = await request(app).post('/customers').send(customer)
expect(response.body.id).toBeTruthy()
expect(response.body.name).toBeTruthy()
})
it("should have valid data", async () => {
await request(app).post('/customers').send(customer)
const _customer = await Customer.findOne({ email: customer.email });
expect(_customer.name).toBe(customer.name)
expect(_customer.email).toBe(customer.email)
})
it('should respond with a 200 status code', async () => {
const response = await request(app).post('/customers').send(customer)
expect(response.statusCode).toEqual(200)
})
it('should return 400 if request is sent twice', async () => {
await request(app).post('/customers').send(customer)
const response = await request(app).post('/customers').send(customer)
expect(response.statusCode).toEqual(400)
})
})
|
'use strict';
let request = require('request');
let express = require('express');
let router = express.Router();
let User = require('../../models/user');
router.post('/', (req, res) => {
let accessTokenUrl = 'https://graph.facebook.com/v2.5/oauth/access_token';
let graphApiUrl = 'https://graph.facebook.com/v2.5/me?fields=id,email,first_name,last_name,link,name';
let params = {
code: req.body.code,
client_id: req.body.clientId,
client_secret: process.env.FACEBOOK_SECRET,
redirect_uri: req.body.redirectUri
};
// Step 1. Exchange authorization code for access token.
request.get({
url: accessTokenUrl,
qs: params,
json: true
}, (err, response, accessToken) => {
if (response.statusCode !== 200) {
return res.status(500).send({
message: accessToken.error.message
});
}
// Step 2. Retrieve profile information about the current user.
request.get({
url: graphApiUrl,
qs: accessToken,
json: true
}, (err, response, profile) => {
console.log('facebook profile:', profile);
if (response.statusCode !== 200) {
return res.status(500).send({
message: profile.error.message
});
}
if (req.headers.authorization) {
User.findOne({
facebook: profile.id
})
.populate('cart')
.exec((err, existingUser) => {
if (existingUser) {
return res.status(409).send({
message: 'There is already a Facebook account that belongs to you'
});
}
let token = req.headers.authorization.split(' ')[1];
let payload = jwt.decode(token, process.env.JWT_SECRET);
User.findById(payload.sub)
.populate('cart')
.exec((err, user) => {
if (!user) {
return res.status(400).send({
message: 'User not found'
});
}
user.facebook = profile.id;
user.picture = user.picture || 'https://graph.facebook.com/v2.3/' + profile.id + '/picture?type=large';
user.displayName = user.displayName || profile.name;
user.save((err, doc) => {
if (err) {
console.log('err: ', err);
}
let token = user.token();
console.log('2 ', token);
res.send({
token: token,
user: user
});
});
});
});
}
else {
// Step 3b. Create a new user account or return an existing one.
User.findOne({
facebook: profile.id
})
.populate('cart')
.exec((err, existingUser) => {
if (existingUser) {
let token = existingUser.token();
console.log('3 ', token);
return res.send({
token: token,
user: existingUser
});
}
let user = new User();
user.facebook = profile.id;
user.email = profile.email;
user.firstName = profile.first_name;
user.lastName = profile.last_name;
user.avatar = 'https://graph.facebook.com/' + profile.id + '/picture?type=large';
user.save((err, doc) => {
if (err) {
console.log('err: ', err);
}
let token = user.token();
console.log('1 ', token);
res.send({
token: token,
user: user
});
});
});
}
});
});
});
module.exports = router;
|
"use strict";
module.exports = {
extends: [
"reverentgeek/browser",
"reverentgeek/blog",
"plugin:react/recommended"
],
rules: {
"no-var": [ "error" ]
}
};
|
const express = require("express");
const mongoose = require("mongoose");
const customers = require("./routes/customers");
const retailers = require("./routes/retailers");
const medicines = require("./routes/medicines");
const app = express();
mongoose
.connect("mongodb://localhost/hackathon", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => console.log("Connected to Mongo DB"))
.catch((err) => console.error("Could not connect to Mongo DB ...", err));
app.use(express.json());
app.use("/api/customers", customers);
app.use("/api/retailers", retailers);
app.use("/api/medicines", medicines);
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Listening on port ${port}...`);
});
|
const fs = require('fs');
const parse = require('csv-parse');
const transform = require('stream-transform')
const hashTags = {};
const posts = [];
const topHashTags = (measure, count = 10) => Object.entries(hashTags)
.sort(([tagA, dataA], [tagB, dataB]) => dataB[measure]/dataB.tweets.length - dataA[measure]/dataA.tweets.length)
.slice(0, count);
const topHashTagRates = (measure, count = 10) => {
Object.entries(hashTags)
.map(([tag, metadata]) => [tag, metadata[measure] / metadata.impressions])
.sort(([tagA, rateA], [tagB, rateB]) => rateB - rateA)
.slice(0, count)
}
const getHashTags = (tweet) => {
const tags = tweet['Tweet text'].split(' ').filter(word => word.startsWith('#'));
const { impressions, engagements } = tweet;
const clicks = tweet['url clicks'];
tags.forEach(tag => {
const sanitisedTag = tag.toLowerCase().replace(/[^a-z#]/g, '');
if (!hashTags[sanitisedTag]) {
hashTags[sanitisedTag] = {
tag: sanitisedTag,
impressions,
engagements,
clicks,
tweets: [tweet['Tweet permalink']],
}
} else {
hashTags[sanitisedTag].impressions += impressions;
hashTags[sanitisedTag].engagements += engagements;
hashTags[sanitisedTag].clicks += clicks;
hashTags[sanitisedTag].tweets.push(tweet['Tweet permalink']);
}
})
}
const topPosts = (measure, count = 10) => posts
.sort((postA, postB) => postB[measure] - postA[measure])
.map(post => ({ id: post['Tweet id'], text: post['Tweet text'], [measure]: post[measure] }))
.slice(0, count);
if (fs.existsSync('all_tweets.csv'))
fs.unlinkSync('all_tweets.csv');
const csvFiles = fs.readdirSync('.');
const allTweets = [];
let columns;
csvFiles
.filter(fileName => fileName.endsWith('.csv'))
.forEach(fileName => {
const buffer = fs.readFileSync(fileName, 'utf8');
const lines = buffer.split('\n');
columns = lines[0];
lines.splice(0, 1);
allTweets.push(lines.join('\n'));
});
allTweets.unshift(columns);
fs.writeFileSync('all_tweets.csv', allTweets.join('\n'));
const stream = fs.createReadStream('all_tweets.csv')
.pipe(parse({ columns: true, auto_parse: true }))
.pipe(transform((tweet) => {
if (tweet['Tweet id']) {
posts.push(tweet);
getHashTags(tweet);
}
}));
const printHashTag = (tag, measure) => `${tag[0]}: ${tag[1][measure]/tag[1].tweets.length} ${tag[1].tweets.join(', ')}`;
stream.on('finish', () => {
const topTenImpressions = topPosts('impressions');
const topTenEngagements = topPosts('engagements');
const topTenClicks = topPosts('url clicks');
const lines = [];
lines.push('Top 10 Impressions');
lines.push(...topTenImpressions.map(tweet => tweet.text));
lines.push('\n');
lines.push('Top ten engagements');
lines.push(...topTenEngagements.map(tweet => tweet.text));
lines.push('\n');
lines.push('Top ten clicks');
lines.push(...topTenClicks.map(tweet => tweet.text));
const topHashtagImpressions = topHashTags('impressions');
const topHashtagEngagements = topHashTags('engagements');
const topHashTagClicks = topHashTags('clicks');
lines.push('\n\nTop hashtag impressions');
lines.push(...topHashtagImpressions.map(tag => printHashTag(tag, 'impressions')));
lines.push('\n');
lines.push('Top hashtag engagements');
lines.push(...topHashtagEngagements.map(tag => printHashTag(tag, 'engagements')));
lines.push('\n');
lines.push('Top hashtag clicks');
lines.push(...topHashTagClicks.map(tag => printHashTag(tag, 'clicks')));
fs.writeFileSync('top_ten_tweets', lines.join('\n'));
});
|
"use strict";
var _createClass = (function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
);
}
return call && (typeof call === "object" || typeof call === "function")
? call
: self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError(
"Super expression must either be null or a function, not " +
typeof superClass
);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass)
Object.setPrototypeOf
? Object.setPrototypeOf(subClass, superClass)
: (subClass.__proto__ = superClass);
}
var Login = (function(_React$Component) {
_inherits(Login, _React$Component);
function Login() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Login);
for (
var _len = arguments.length, args = Array(_len), _key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
return (
(_ret = ((_temp = ((_this = _possibleConstructorReturn(
this,
(_ref = Login.__proto__ || Object.getPrototypeOf(Login)).call.apply(
_ref,
[this].concat(args)
)
)),
_this)),
(_this.state = {
username: "",
password: ""
}),
(_this.handleChange = function(event) {
var _event$target = event.target,
name = _event$target.name,
value = _event$target.value; //Destructure the current fields name and value
_this.setState(_defineProperty({}, name, value));
// alert(this.setState({ [name]: value })); //Sets state
}),
(_this.handleSubmit = function(event) {
event.preventDefault();
//Alter your request like below
$.ajax({
method: "post",
url: "https://nodedeveloper.azurewebsites.net/users/login",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
data: {
username: _this.state.username,
password: _this.state.password
}
}).then(function(res) {
console.log(res);
console.log(res.data);
});
}),
_temp)),
_possibleConstructorReturn(_this, _ret)
);
}
_createClass(Login, [
{
key: "render",
value: function render() {
return React.createElement(
"div",
{ className: "container-fluid" },
React.createElement(
"div",
{ className: "row" },
React.createElement(
"div",
{ className: "col-sm-10 col-md-10 col-md-offset-1" },
React.createElement(
"div",
{ className: "account-wall" },
React.createElement("br", null),
React.createElement("br", null),
React.createElement("br", null),
React.createElement(
"div",
{ className: "row" },
React.createElement(
"div",
{ className: "col-md-6" },
React.createElement("br", null),
React.createElement(
"div",
{ className: "col-md-10 col-md-offset-3" },
React.createElement("img", {
src: "images/logo.png",
width: "70%",
className: "center"
})
),
React.createElement(
"div",
{ className: "col-md-10 col-md-offset-2" },
React.createElement("br", null),
React.createElement("img", {
src: "images/layer.png",
width: "100%",
className: "center"
}),
React.createElement("br", null),
" ",
React.createElement("br", null),
" ",
React.createElement("br", null)
)
),
React.createElement(
"div",
{ className: "col-md-6 vl" },
React.createElement(
"form",
{ className: "form-signin", onSubmit: this.handleSubmit },
React.createElement(
"label",
null,
React.createElement("b", null, "Username")
),
React.createElement("input", {
type: "text",
className: "form-control",
placeholder: "Username",
id: "username",
name: "username",
autoFocus: true,
onChange: this.handleChange
}),
React.createElement("br", null),
React.createElement(
"label",
null,
React.createElement("b", null, "Password")
),
React.createElement("input", {
type: "password",
className: "form-control",
id: "password",
name: "password",
placeholder: "Password",
onChange: this.handleChange,
required: true
}),
React.createElement(
"label",
{ className: "checkbox pull-left" },
React.createElement("input", {
type: "checkbox",
defaultValue: "remember-me"
}),
"Remember me"
),
React.createElement(
"a",
{ href: "#", className: "pull-right need-help" },
"Forget Password? "
),
React.createElement("span", { className: "clearfix" }),
React.createElement(
"button",
{
className:
"btn btn-lg btn-primary btn-block center-block",
align: "center",
type: "submit"
},
"Login"
)
),
React.createElement("br", null),
React.createElement(
"a",
{ href: "#", className: "text-right new-account" },
"Sign Up "
)
)
)
)
)
)
);
}
}
]);
return Login;
})(React.Component);
ReactDOM.render(
React.createElement(Login, null),
document.getElementById("root")
);
|
import React from 'react';
import './SearchBar.css';
import { makeStyles } from '@material-ui/core';
import styled from 'styled-components';
//Material UI components
import Card from '@material-ui/core/Card';
const ButtonGroup = styled.div`
margin-top: calc(var(--size-bezel) * 2.5);
display: flex;
`;
const MoneyMaker = styled.button`
color: currentColor;
padding: var(--size-bezel) calc(var(--size-bezel) * 2);
background: var(--color-accent);
border: none;
border-radius: var(--size-radius);
font-weight: 900;
justify-content: space-around;
`;
const useStyles = makeStyles((theme) => ({
positioning: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
'@media (max-width: 375px)': {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}
},
card: {
boxShadow: '0 3px 5px 2px rgba(0, 0, 0, 0.2)',
height: '300px',
width: '100%',
},
boxOne: {
width: '5px',
height: '5px',
border: '10px solid green',
backgroundColor: 'green',
borderRadius: '90%',
position: 'relative',
top: '110px',
left: '47px',
[theme.breakpoints.down('xs')]: {
display: 'none'
}
},
boxTwo: {
width: '5px',
height: '5px',
border: '10px solid royalblue',
backgroundColor: 'royalblue',
borderRadius: '10px',
position: 'relative',
top: '127px',
left: '47px',
[theme.breakpoints.down('xs')]: {
display: 'none'
}
}
}))
export default function HeroDashboard() {
const classes = useStyles();
return (
<div>
<Card className= { `${classes.positioning} ${classes.card}` }>
<label>
<label>
<input class='input__field' type='text' placeholder='Website URL' />
</label>
<ButtonGroup>
<MoneyMaker style={{ marginRight: '15px', cursor: 'pointer' }}>Analyze</MoneyMaker>
<MoneyMaker type='reset' style={{ cursor: 'pointer' }}>Reset</MoneyMaker>
</ButtonGroup>
</label>
</Card>
</div>
)
} |
var win = window;
var doc = document;
var nav = navigator;
var ua = nav.userAgent.toLowerCase();
var key = {
ie: 'msie',
sf: 'safari',
tt: 'tencenttraveler'
};
// 正则列表
var reg = {
browser: '(' + key.ie + '|' + key.sf + '|firefox|chrome|opera)',
shell: '(maxthon|360se|360chrome|theworld|se|theworld|greenbrowser|qqbrowser|lbbrowser|bidubrowser|17173)',
tt: '(tencenttraveler)',
os: '(windows nt|macintosh|solaris|linux)',
kernel: '(webkit|gecko|like gecko)'
};
var System = {
'5.0': 'Win2000',
'5.1': 'WinXP',
'5.2': 'Win2003',
'6.0': 'WinVista',
'6.1': 'Win7',
'6.2': 'Win8',
'6.3': 'Win8.1'
};
var chrome = null;
// 360浏览器
var is360Chrome = null;
// 360级速浏览器
var is360se = null;
// 特殊浏览器检测
var is360 = (function () {
// 高速模式
var result = ua.indexOf('360chrome') > -1 ? !!1 : !1;
var s;
// 普通模式
try {
if (win.external && win.external.twGetRunPath) {
s = win.external.twGetRunPath;
if (s && s.indexOf('360se') > -1) {
result = !!1;
}
}
} catch (e) {
result = !1;
}
return result;
})();
// 判断百度浏览器
var isBaidu = (function () {
return ua.indexOf('bidubrowser') > -1 ? !!1 : !1;
})();
// 判断百度影音浏览器
var isBaiduPlayer = (function () {
return ua.indexOf('biduplayer') > -1 ? !!1 : !1;
})();
// 判断爱帆avant浏览器
var isAvant = (function () {
return ua.indexOf('爱帆') > -1 ? !!1 : !1;
})();
var isLiebao = (function () {
return ua.indexOf('lbbrowser') > -1 ? !!1 : !1;
})();
// 特殊检测maxthon返回版本号
var maxthonVer = (function () {
try {
if (/(\d+\.\d)/.test(win.external.max_version)) {
return parseFloat(RegExp['\x241']);
}
} catch (e) {
}
})();
var browser = getBrowser();
var shell = uaMatch(reg.shell);
var os = uaMatch(reg.os);
var kernel = uaMatch(reg.kernel);
// ie11
function getBrowser() {
if (isIE11()) {
return ['msie', ua.match(/rv:(\w+\.\w+)/gi)[0].split(':')[1]];
}
return uaMatch(reg.browser);
}
function isIE11() {
// 检测是否是ie内核 是否是ie11 标识
if ((!!win.ActiveXObject || 'ActiveXObject' in win) && (ua.match(/.net/gi) && ua.match(/rv:(\w+\.\w+)/gi))) {
// return ['msie',ua.match(/rv:(\w+\.\w+)/gi)[0].split(':')[1]];
return !0;
}
}
/**
* 对ua字符串进行匹配处理
* @param {string} str 要处理的字符串
* @return {Array} 返回处理后的数组
*/
function uaMatch(str) {
var reg = new RegExp(str + '\\b[ \\/]?([\\w\\.]*)', 'i');
var result = ua.match(reg);
return result ? result.slice(1) : ['', ''];
}
function detect360chrome() {
return 'track' in document.createElement('track') && 'scoped' in document.createElement('style');
}
/* eslint-disable */
function isHao123() {
return !!(window.external && window.external.ExtGetAppPath && window.external.ExtGetAppPath());
}
/* eslint-enable */
function isIpad() {
return ua.indexOf('ipad') > -1 || ua.indexOf('iphone') > -1;
}
function canvasSupport() {
return !!document.createElement('canvas').getContext;
}
// 保存浏览器信息
if (browser[0] === key.ie) {
if (is360) {
shell = ['360se', ''];
} else if (maxthonVer) {
shell = ['maxthon', maxthonVer];
} else if (shell === ',') {
shell = uaMatch(reg.tt);
}
} else if (browser[0] === key.sf) {
browser[1] = uaMatch('version') + '.' + browser[1];
}
chrome = (browser[0] === 'chrome') && browser[1];
// 如果是chrome浏览器,进一步判断是否是360浏览器
if (chrome) {
if (detect360chrome()) {
if ('v8Locale' in window) {
is360Chrome = true;
} else {
is360se = true;
}
}
}
// 获取操作系统
function getSystem() {
var plat = navigator.platform;
var isWin = (plat === 'Win32') || (plat === 'Win64') || (plat === 'Windows');
var isMac = (plat === 'Mac68K') || (plat === 'MacPPC') || (plat === 'Macintosh') || (plat === 'MacIntel');
if (isMac) {
return 'Mac';
}
var isUnix = (plat === 'X11') && !isWin && !isMac;
if (isUnix) {
return 'Unix';
}
var isLinux = (String(plat).indexOf('Linux') > -1);
if (isLinux) {
return 'Linux';
}
if (isWin) {
return System[os[1]] || 'other';
}
return 'other';
}
// 遵循cmd规范,输出浏览器、系统等响应参数
module.exports = {
cookieEnabled: navigator.cookieEnabled,
isStrict: (doc.compatMode === 'CSS1Compat'),
isShell: !!shell[0],
shell: shell,
kernel: kernel,
platform: os,
types: browser,
chrome: chrome,
system: getSystem(),
firefox: (browser[0] === 'firefox') && browser[1],
ie: (browser[0] === 'msie') && browser[1],
opera: (browser[0] === 'opera') && browser[1],
safari: (browser[0] === 'safari') && browser[1],
maxthon: (shell[0] === 'maxthon') && shell[1],
isTT: (shell[0] === 'tencenttraveler') && shell[1],
is360: is360,
// 是否是chrome内核的360浏览器
is360Chrome: is360Chrome,
// 是否是chrome内核的360极速浏览器
is360se: is360se,
isBaidu: isBaidu,
// 判断hao123浏览器
isHao123: isHao123,
isLiebao: isLiebao,
isIE11: isIE11(),
isSougou: (shell[0] === 'se'),
isQQ: shell[0] === 'qqbrowser',
isIpad: isIpad,
version: '',
// 浏览器下载入口需排除的浏览器
noDl: isBaidu || isAvant || isBaiduPlayer,
// 是否支持canvas
canvasSupport: canvasSupport()
};
|
const Collection = require('../models/Collection')
const createCollection = async (req, res) => {
try{
const {name} = req.body
const user_id = req.user.userId
const exists = await Collection.exists({name, user_id})
if(exists){
return res.status(500).json({message: "Collection with the same name is already exists"})
}
const candidate = new Collection({user_id, name})
const collection = await candidate.save()
return res.status(201).json({collection})
}catch (e) {
return res.status(500).json({message: e.message | 'Something went wrong... Please, try again.'})
}
}
const getCollections = async (req, res) => {
try{
const user_id = req.user.userId
const collections = await Collection.find({user_id})
return res.status(201).json({collections})
}catch (e) {
return res.status(500).json({message: 'Something went wrong... Please, try again.'})
}
}
const deleteCollection = async (req, res) => {
try{
const collection = await Collection.delete({id: req.params.id})
return res.status(201).json({id: collection.id})
}catch (e) {
return res.status(500).json({message: e.message})
}
}
const getCollectionsToReview = async (req, res) => {
try{
const user_id = req.user.userId
const collections = await Collection.getCollectionsToReview({user_id})
return res.status(201).json(collections)
}catch (e) {
return res.status(500).json({message: e.message})
}
}
module.exports = {
createCollection,
getCollections,
deleteCollection,
getCollectionsToReview
}
|
var sys = require('sys')
var exec = require('child_process').exec;
var APPLICATIONKEY = "934fe58a111a44624f2ebd6ff5371a042fe26021992a68f83bcd193756502bbe"
var CLIENTKEY = "beb657fa101077abcb7934f3e7e39e071f5ae92788a400d52a17b1601b775a83"
//1. mobile backendのSDKの読み込み
var NCMB = require("/home/pi/node_modules/ncmb/lib/ncmb");
// 2. mobile backendアプリとの連携
var ncmb = new NCMB(APPLICATIONKEY,CLIENTKEY);
//setInterval(function() {
exec("python /home/pi/161029sensar/light.py", function (error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
return
}
date = new Date();
year = date.getFullYear();
month = date.getMonth()+1;
day = date.getDate();
hour = date.getHours();
min = date.getMinutes();
sec = date.getSeconds();
datas = stdout.split(",")
// Compose records
var record = {
"deviceid": "pi_01",
"timestamp": year + "/"+ month + "/" + day + " " + hour + ":" + min + ":" + sec,
"lux": datas[0],
};
console.log("deviceid:" +record.deviceid);
console.log("timestamp:" +record.timestamp);
console.log("lux:" +record.lux);
var TemperatureClass = ncmb.DataStore("Illuminance");
var temperatureClass = new TemperatureClass();
temperatureClass.set("illuminance",record.lux);
temperatureClass.set("date",date);
temperatureClass.save()
.then(function(){
console.log("message is saved.");
})
.catch(function(err){
console.log(err.text);
});
});
//},60000);
|
const d = [5, 4, 3, 2, 1];
const budget = 10;
function solution(d, budget) {
var answer = 0;
d.sort((a, b) => a - b);
while (budget >= d[0] && d.length >= 1) {
budget -= d[0];
d.splice(0, 1);
answer++;
}
return answer;
}
console.log(solution(d, budget));
|
import React from 'react'
import Home from './containers/Home/Home'
import './App.css'
const App = () => <Home />
export default App
|
import React, { useRef, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { isEmpty } from 'underscore';
import { circlePointPaint, heatMapPaint } from './paints';
import { getFirstDuration } from 'utils/dateTime';
import Filter from '../Dashboard/components/Map/Filter';
import Divider from '@material-ui/core/Divider';
import { loadPM25HeatMapData, loadMapEventsData } from 'redux/MapData/operations';
import { usePM25HeatMapData, useEventsMapData } from 'redux/MapData/selectors';
import SettingsIcon from '@material-ui/icons/Settings';
import RichTooltip from '../../containers/RichToolTip';
import { MenuItem } from '@material-ui/core';
import Checkbox from '@material-ui/core/Checkbox';
import { useInitScrollTop } from 'utils/customHooks';
import { ErrorBoundary } from '../../ErrorBoundary';
import { useDashboardSitesData } from 'redux/Dashboard/selectors';
import { loadSites } from 'redux/Dashboard/operations';
import { useOrgData } from 'redux/Join/selectors';
// css
import 'assets/css/overlay-map.css';
import 'mapbox-gl/dist/mapbox-gl.css';
import mapboxgl from 'mapbox-gl';
import { ErrorEvent } from 'mapbox-gl';
import BoundaryAlert from '../../ErrorBoundary/Alert';
import CircularLoader from '../../components/Loader/CircularLoader';
import { darkMapStyle, lightMapStyle, satelliteMapStyle, streetMapStyle } from './utils';
import MapIcon from '@material-ui/icons/Map';
import LightModeIcon from '@material-ui/icons/Highlight';
import SatelliteIcon from '@material-ui/icons/Satellite';
import DarkModeIcon from '@material-ui/icons/NightsStay';
import StreetModeIcon from '@material-ui/icons/Traffic';
// prettier-ignore
// eslint-disable-next-line import/no-webpack-loader-syntax
mapboxgl.workerClass = require("worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker").default;
const markerDetailsPM2_5 = {
0.0: ['marker-good', 'Good'],
12.1: ['marker-moderate', 'Moderate'],
35.5: ['marker-uhfsg', 'Unhealthy for sensitive groups'],
55.5: ['marker-unhealthy', 'Unhealthy'],
150.5: ['marker-v-unhealthy', 'VeryUnhealthy'],
250.5: ['marker-hazardous', 'Hazardous'],
500.5: ['marker-unknown', 'Invalid']
};
const markerDetailsPM10 = {
0.0: ['marker-good', 'Good'],
54.1: ['marker-moderate', 'Moderate'],
154.1: ['marker-uhfsg', 'Unhealthy for sensitive groups'],
254.1: ['marker-unhealthy', 'Unhealthy'],
354.1: ['marker-v-unhealthy', 'VeryUnhealthy'],
424.1: ['marker-hazardous', 'Hazardous'],
604.1: ['marker-unknown', 'Invalid']
};
const markerDetailsNO2 = {
0.0: ['marker-good', 'Good'],
53.1: ['marker-moderate', 'Moderate'],
100.1: ['marker-uhfsg', 'Unhealthy for sensitive groups'],
360.1: ['marker-unhealthy', 'Unhealthy'],
649.1: ['marker-v-unhealthy', 'VeryUnhealthy'],
1249.1: ['marker-hazardous', 'Hazardous'],
2049.1: ['marker-unknown', 'Invalid']
};
const markerDetailsMapper = {
pm2_5: markerDetailsPM2_5,
pm10: markerDetailsPM10,
no2: markerDetailsNO2
};
const getMarkerDetail = (markerValue, markerKey) => {
if (markerValue === null || markerValue === undefined) return ['marker-unknown', 'uncategorised'];
const markerDetails = markerDetailsMapper[markerKey] || markerDetailsPM2_5;
let keys = Object.keys(markerDetails);
// in-place reverse sorting
keys.sort((key1, key2) => -(key1 - key2));
for (let i = 0; i < keys.length; i++) {
if (markerValue >= keys[i]) {
return markerDetails[keys[i]];
}
}
return ['marker-unknown', 'uncategorised'];
};
mapboxgl.accessToken = process.env.REACT_APP_MAPBOX_TOKEN;
const MapControllerPosition = ({ className, children, position }) => {
const positions = {
topLeft: { top: 0, left: 0 },
bottomLeft: { bottom: 0, left: 0 },
topRight: { top: 0, right: 0 },
bottomRight: { bottom: 0, right: 0 }
};
const style = {
display: 'flex',
flexWrap: 'wrap',
position: 'absolute',
cursor: 'pointer',
margin: '10px',
padding: '10px',
...(positions[position] || positions.topLeft)
};
return (
<span className={className} style={style}>
{children}
</span>
);
};
const PollutantSelector = ({ className, onChange, showHeatMap }) => {
useInitScrollTop();
const orgData = useOrgData();
const [open, setOpen] = useState(false);
let pollutant = localStorage.pollutant;
const pollutantMapper = {
pm2_5: (
<span>
PM<sub>2.5</sub>
</span>
),
pm10: (
<span>
PM<sub>10</sub>
</span>
),
no2: (
<span>
NO<sub>2</sub>
</span>
)
};
const onHandleClick = () => {
setOpen(!open);
};
const handleMenuItemChange = (pollutant, state) => () => {
localStorage.pollutant = pollutant;
setOpen(!open);
onChange(state);
window.location.reload();
};
useEffect(() => {
if (!localStorage.pollutant) {
localStorage.pollutant = 'pm2_5';
}
}, []);
return (
<RichTooltip
content={
<div>
<MenuItem
onClick={handleMenuItemChange('pm2_5', {
pm2_5: true,
no2: false,
pm10: false
})}
>
PM<sub>2.5</sub>
</MenuItem>
<MenuItem
onClick={handleMenuItemChange('pm10', {
pm2_5: false,
no2: false,
pm10: true
})}
>
PM<sub>10</sub>
</MenuItem>
{orgData.name !== 'airqo' && (
<MenuItem
onClick={handleMenuItemChange('no2', {
pm2_5: false,
no2: true,
pm10: false
})}
>
NO<sub>2</sub>
</MenuItem>
)}
</div>
}
open={open}
placement="left"
onClose={() => setOpen(false)}
>
<div style={{ padding: '10px' }}>
<span className={className} onClick={onHandleClick}>
{pollutantMapper[pollutant]}
</span>
</div>
</RichTooltip>
);
};
const MapStyleSelectorPlaceholder = () => {
const [isOpen, setIsOpen] = useState(false);
const [isHovered, setIsHovered] = useState(false);
const dropdownRef = useRef(null);
const handleClick = () => {
setIsOpen(!isOpen);
};
useEffect(() => {
const handleClickOutside = (event) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
setIsOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);
const handleHover = (isHovered) => {
setIsHovered(isHovered);
};
return (
<div
ref={dropdownRef}
className="map-style-placeholder"
onClick={handleClick}
onMouseEnter={() => handleHover(true)}
onMouseLeave={() => handleHover(false)}
>
<div className={`map-icon-container${isHovered ? ' map-icon-hovered' : ''}`}>
<MapIcon className="map-icon" />
</div>
{isOpen && <MapStyleSelector />}
</div>
);
};
const MapStyleSelector = () => {
const styleSet = [
{
name: 'light',
icon: <LightModeIcon />,
mapStyle: lightMapStyle
},
{
name: 'dark',
icon: <DarkModeIcon />,
mapStyle: darkMapStyle
},
{
name: 'street',
icon: <StreetModeIcon />,
mapStyle: streetMapStyle
},
{
name: 'satellite',
icon: <SatelliteIcon />,
mapStyle: satelliteMapStyle
}
];
const [mapMode, setMapMode] = useState('');
useEffect(() => {
if (localStorage.mapMode) {
setMapMode(localStorage.mapMode);
} else {
setMapMode('light');
}
}, []);
return (
<>
<div className="map-style">
<div className="map-style-cards">
{styleSet.map((style) => {
return (
<div
key={style.name}
onClick={() => {
localStorage.mapStyle = style.mapStyle;
localStorage.mapMode = style.name;
window.location.reload();
}}
>
<span>{style.icon}</span>
<span>{style.name} map</span>
</div>
);
})}
</div>
</div>
</>
);
};
const MapSettings = ({
showSensors,
showHeatmap,
showCalibratedValues,
onSensorChange,
onHeatmapChange,
onCalibratedChange
}) => {
const [open, setOpen] = useState(false);
return (
<RichTooltip
content={
<div>
<MenuItem onClick={() => onSensorChange(!showSensors)}>
<Checkbox checked={showSensors} color="default" /> Monitors
</MenuItem>
<MenuItem onClick={() => onHeatmapChange(!showHeatmap)}>
<Checkbox checked={showHeatmap} color="default" /> Heatmap
</MenuItem>
<Divider />
{showSensors ? (
<MenuItem onClick={() => onCalibratedChange(!showCalibratedValues)}>
<Checkbox checked={showCalibratedValues} color="default" /> Calibrated values
</MenuItem>
) : (
<MenuItem onClick={() => onCalibratedChange(!showCalibratedValues)} disabled>
<Checkbox checked={showCalibratedValues} color="default" /> Calibrated values
</MenuItem>
)}
</div>
}
open={open}
placement="left"
onClose={() => setOpen(false)}
>
<div style={{ padding: '10px' }}>
<div className="map-settings" onClick={() => setOpen(!open)}>
<SettingsIcon />
</div>
</div>
</RichTooltip>
);
};
const CustomMapControl = ({
className,
onPollutantChange,
showSensors,
showHeatmap,
showCalibratedValues,
onSensorChange,
onHeatmapChange,
onCalibratedChange
}) => {
return (
<MapControllerPosition className={'custom-map-control'} position={'topRight'}>
<MapSettings
showSensors={showSensors}
showHeatmap={showHeatmap}
showCalibratedValues={showCalibratedValues}
onSensorChange={onSensorChange}
onHeatmapChange={onHeatmapChange}
onCalibratedChange={onCalibratedChange}
/>
<PollutantSelector
className={className}
onChange={onPollutantChange}
showHeatMap={showHeatmap}
/>
<MapStyleSelectorPlaceholder />
</MapControllerPosition>
);
};
export const OverlayMap = ({ center, zoom, heatMapData, monitoringSiteData }) => {
const dispatch = useDispatch();
const sitesData = useDashboardSitesData();
const MAX_OFFLINE_DURATION = 86400; // 24 HOURS
const mapContainerRef = useRef(null);
const [map, setMap] = useState();
const [showSensors, setShowSensors] = useState(true);
const [showHeatMap, setShowHeatMap] = useState(false);
const [showCalibratedValues, setShowCalibratedValues] = useState(false);
const [showPollutant, setShowPollutant] = useState({
pm2_5: localStorage.pollutant === 'pm2_5',
no2: localStorage.pollutant === 'no2',
pm10: localStorage.pollutant === 'pm10'
});
const popup = new mapboxgl.Popup({
closeButton: false,
offset: 25
});
useEffect(() => {
setShowPollutant({
pm2_5: localStorage.pollutant === 'pm2_5',
no2: localStorage.pollutant === 'no2',
pm10: localStorage.pollutant === 'pm10'
});
}, [localStorage.pollutant]);
useEffect(() => {
if (isEmpty(sitesData)) {
dispatch(loadSites());
}
}, [sitesData]);
useEffect(() => {
const map = new mapboxgl.Map({
container: mapContainerRef.current,
style: localStorage.mapStyle ? localStorage.mapStyle : lightMapStyle,
center,
zoom,
maxZoom: 20
});
if (heatMapData) {
map.on('load', () => {
map.addSource('heatmap-data', {
type: 'geojson',
data: heatMapData
});
map.addLayer({
id: 'sensor-heat',
type: 'heatmap',
source: 'heatmap-data',
paint: heatMapPaint
});
map.addLayer({
id: 'sensor-point',
source: 'heatmap-data',
type: 'circle',
paint: circlePointPaint
});
map.setLayoutProperty('sensor-heat', 'visibility', showHeatMap ? 'visible' : 'none');
map.setLayoutProperty('sensor-point', 'visibility', showHeatMap ? 'visible' : 'none');
map.on('mousemove', (e) => {
const features = map.queryRenderedFeatures(e.point, {
layers: ['sensor-point']
});
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = features.length > 0 ? 'pointer' : '';
if (map.getZoom() < 9) {
popup.remove();
return;
}
if (!features.length) {
popup.remove();
return;
}
const reducerFactory = (key) => (accumulator, feature) =>
accumulator + parseFloat(feature.properties[key]);
let average_predicted_value =
features.reduce(reducerFactory('pm2_5'), 0) / features.length;
let average_confidence_int =
features.reduce(reducerFactory('interval'), 0) / features.length;
popup
.setLngLat(e.lngLat)
.setHTML(
`<table class="popup-table">
<tr>
<td><b>Predicted AQI</b></td>
<td>${average_predicted_value.toFixed(4)}</td>
</tr>
<tr>
<td><b>Confidence Level</b></td>
<td>± ${average_confidence_int.toFixed(4)}</td>
</tr>
</table>`
)
.addTo(map);
});
});
}
map.addControl(
new mapboxgl.FullscreenControl({
container: mapContainerRef.current
}),
'bottom-right'
);
map.addControl(new mapboxgl.NavigationControl(), 'bottom-right');
setMap(map);
// clean up on unmount
// return () => map.remove();
}, []);
useEffect(() => {
if (map) {
map.getSource('heatmap-data') && map.getSource('heatmap-data').setData(heatMapData);
}
// if (map) {
// map.getLayer("sensor-point") && map.removeLayer("sensor-point");
// }
// if (map) {
// map.getLayer("sensor-heat") && map.removeLayer("sensor-heat");
// }
});
const toggleSensors = () => {
try {
const markers = document.getElementsByClassName('marker');
for (let i = 0; i < markers.length; i++) {
markers[i].style.visibility = !showSensors ? 'visible' : 'hidden';
}
setShowSensors(!showSensors);
// eslint-disable-next-line no-empty
} catch (err) {}
};
const toggleHeatMap = () => {
setShowHeatMap(!showHeatMap);
try {
map.setLayoutProperty('sensor-heat', 'visibility', showHeatMap ? 'none' : 'visible');
map.setLayoutProperty('sensor-point', 'visibility', showHeatMap ? 'none' : 'visible');
// eslint-disable-next-line no-empty
} catch (err) {
console.log('Heatmap Load error:', err);
}
};
return (
<div className="overlay-map-container" ref={mapContainerRef}>
{showSensors &&
map &&
monitoringSiteData.features.length > 0 &&
monitoringSiteData.features.forEach((feature) => {
const [seconds, duration] = getFirstDuration(feature.properties.time);
let pollutantValue =
(showPollutant.pm2_5 && feature.properties.pm2_5 && feature.properties.pm2_5.value) ||
(showPollutant.pm10 && feature.properties.pm10 && feature.properties.pm10.value) ||
(showPollutant.no2 && feature.properties.no2 && feature.properties.no2.value) ||
null;
if (showCalibratedValues) {
pollutantValue =
(showPollutant.pm2_5 &&
feature.properties.pm2_5 &&
feature.properties.pm2_5.calibratedValue &&
feature.properties.pm2_5.calibratedValue) ||
(showPollutant.pm10 &&
feature.properties.pm10 &&
feature.properties.pm10.calibratedValue &&
feature.properties.pm10.calibratedValue) ||
(showPollutant.no2 &&
feature.properties.no2 &&
feature.properties.no2.calibratedValue &&
feature.properties.no2.calibratedValue) ||
null;
}
let markerKey = '';
for (const property in showPollutant) {
if (showPollutant[property]) markerKey = property;
}
const [markerClass, desc] = getMarkerDetail(pollutantValue, markerKey);
const el = document.createElement('div');
el.className = `marker ${seconds >= MAX_OFFLINE_DURATION ? 'marker-grey' : markerClass}`;
// el.innerText = (pollutantValue && pollutantValue.toFixed(0)) || "--";
if (
feature.geometry.coordinates.length >= 2 &&
feature.geometry.coordinates[0] &&
feature.geometry.coordinates[1]
) {
new mapboxgl.Marker(el, { rotation: -45, scale: 0.4 })
.setLngLat(feature.geometry.coordinates)
.setPopup(
new mapboxgl.Popup({
offset: 25,
className: 'map-popup'
}).setHTML(
`<div class="popup-body">
<div>
<span class="popup-title">
<b>${
(sitesData[feature.properties.site_id] &&
sitesData[feature.properties.site_id].name) ||
(sitesData[feature.properties.site_id] &&
sitesData[feature.properties.site_id].description) ||
feature.properties.device ||
feature.properties._id
}</b>
</span>
</div>
<div class="${`popup-aqi ${markerClass}`}">
<span>
${
(showPollutant.pm2_5 && 'PM<sub>2.5<sub>') ||
(showPollutant.pm10 && 'PM<sub>10<sub>')
}
</span> </hr>
<div class="pollutant-info">
<div class="pollutant-info-row">
<div class="pollutant-number">${
(pollutantValue && pollutantValue.toFixed(2)) || '--'
}</div>
<div class="popup-measurement">µg/m<sup>3</sup></div>
</div>
<div class="pollutant-desc">${desc}</div>
</div>
</div>
<span>Last Refreshed: <b>${duration}</b> ago</span>
</div>`
)
)
.addTo(map);
}
})}
<Filter pollutants={showPollutant} />
{map && (
<CustomMapControl
showSensors={showSensors}
showHeatmap={showHeatMap}
showCalibratedValues={showCalibratedValues}
onSensorChange={toggleSensors}
onHeatmapChange={toggleHeatMap}
onCalibratedChange={setShowCalibratedValues}
onPollutantChange={setShowPollutant}
className={'pollutant-selector'}
/>
)}
</div>
);
};
const MapContainer = () => {
const dispatch = useDispatch();
const heatMapData = usePM25HeatMapData();
const monitoringSiteData = useEventsMapData();
// useEffect(() => {
// if (isEmpty(heatMapData.features)) {
// dispatch(loadPM25HeatMapData());
// }
// }, [heatMapData]);
useEffect(() => {
if (isEmpty(monitoringSiteData.features)) {
dispatch(
loadMapEventsData({
recent: 'yes',
external: 'no',
metadata: 'site_id',
frequency: 'hourly',
active: 'yes'
})
);
}
}, [monitoringSiteData]);
return (
<div>
<ErrorBoundary>
{monitoringSiteData ? (
<OverlayMap
center={[22.5600613, 0.8341424]}
zoom={2.4}
// heatMapData={heatMapData}
monitoringSiteData={monitoringSiteData}
/>
) : (
<CircularLoader loading={true} />
)}
</ErrorBoundary>
</div>
);
};
export default MapContainer;
|
import React, { useState } from "react";
import { Button, makeStyles, TextField } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
loginform: {
display: "flex",
flexFlow: "column wrap",
width: "50%",
maxHeight: "45vh",
justifyContent: "space-evenly",
"@media (max-width: 600px)": { width: "80%" },
"@media (max-width: 400px)": { width: "100%" },
},
names: {
display: "flex",
justifyContent: "space-between",
width: "100%",
},
firstNameInput: {
color: "white",
background: "white",
width: "50%",
},
lastNameInput: {
color: "white",
background: "white",
width: "50%",
marginLeft: "1vw",
},
input: {
color: "white",
background: "white",
marginTop: "1vh",
// width: "100%",
},
button: {
background: theme.palette.primary.main,
color: "white",
margin: "1vh auto",
fontSize: "1rem",
boxShadow: "2px 2px 5px black",
"&:hover": {
backgroundColor: theme.palette.primary.light,
color: "#FFF",
},
},
}));
export default function LoginForm({ loginGuest }) {
const [formData, setFormData] = useState({
firstname: "",
lastname: "",
email: "",
});
const classes = useStyles();
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prev) => ({
...prev,
[name]: value,
}));
};
const handleSubmit = () => {
// e.preventDefault();
const guest = {
...formData,
};
loginGuest(guest);
};
return (
<>
<form className={classes.loginform}>
<div className={classes.names}>
<TextField
className={classes.firstNameInput}
variant="filled"
label="First Name"
name="firstname"
value={formData.firstname}
onChange={(e) => handleChange(e)}
required
/>
<TextField
className={classes.lastNameInput}
variant="filled"
label="Last Name"
name="lastname"
onChange={(e) => handleChange(e)}
required
/>
</div>
<TextField
className={classes.input}
variant="filled"
label="Email"
name="email"
type="email"
onChange={(e) => handleChange(e)}
required
/>
</form>
<Button
className={classes.button}
variant="outlined"
onClick={handleSubmit}
>
Enter!
</Button>
</>
);
}
|
function solve(face, suit) {
let validCardFaces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
let validSuits = {
S: 'S',
H: 'H',
D: 'D',
C: 'C'
};
if (!validCardFaces.includes(face)) {
throw new Error(`Invalid ${face}`);
}
let suits = Object.keys(validSuits);
if (!suits.includes(suit)) {
throw new Error(`Invalid ${suit}`);
}
suit = suit.replace('S', '\u2660');
suit = suit.replace('H', '\u2665');
suit = suit.replace('D', '\u2666');
suit = suit.replace('C', '\u2663');
return face + suit;
}
let checkCard = solve;
console.log(solve('A', 'S'));
|
var increasingBST = function(root) {
let head = root;
let node = root;
let prev = null;
while (node) {
if (node.left)
}
}; |
import { extendTheme } from '@chakra-ui/react';
import fonts from './fonts';
import colors from './colors';
import sizes from './sizes';
const overrides = {
fonts,
colors,
sizes,
};
const theme = extendTheme(overrides);
export default theme;
|
import React, {useState} from 'react'
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import styled, {css} from "styled-components"
// import {} from "../style/DataBox"
const DataBox = ({item}) => {
const [showMore, setShowMore] = useState(false)
const {dt_txt, main, weather, wind} = item
const month = dt_txt.split(" ")[0].split("-")
const hours = dt_txt.split(" ")[1].split(":")
return (
<Container>
<Info showMore={showMore}>
<p className="dataBox__time">{month[1]}/{month[2]} - {hours[0]}:{hours[1]}</p>
<p className="dataBox__temp">{Math.round(main.temp)}°C</p>
<img className="dataBox__icon" src={`http://openweathermap.org/img/wn/${weather[0].icon}@2x.png`} alt="icon"/>
<div onClick={() => setShowMore(!showMore)} className="dataBox__iconBox">
<ExpandMoreIcon fontSize="large" className={`dataBox__arrow`}/>
</div>
</Info>
{
showMore ? (
<MoreInfo>
<p>Wind speed: {wind.speed} km/h</p>
<p>Weather: {weather[0].description}</p>
<p>Humidity: {main.humidity}%</p>
<p>Pressure : {main.pressure} Pa</p>
</MoreInfo>
) : null
}
</Container>
)
}
export default DataBox
// ------------------------------style---------------------------
const Container = styled.section`
max-width: 600px;
margin: 0 auto;
&:not(:last-child){
margin-bottom: 6px;
}
`
const Info = styled.div`
display: flex;
background: #262732;
align-items: center;
justify-content: space-between;
p{
padding: 0 20px;
}
.dataBox__iconBox{
cursor: pointer;
background: #1A1B23;
transition: transform .4s;
padding: 30px;
}
.dataBox__iconBox:hover{
background: #111218;
}
.dataBox__arrow{
transform: rotate(0deg);
transition: transform .2s ease-out;
${props => props.showMore && css`
transform:rotate(180deg);
`}
}
@media (max-width:375px) {
.dataBox__icon{
display: none;
}
}
`
const MoreInfo = styled.div`
display: grid;
grid-template-columns: repeat(2, 50%);
background: #3F404B;
padding: 20px;
p{
padding: 10px 0;
}
@media (max-width:375px) {
display: flex;
flex-direction: column;
}
`
// ------------------------------style---------------------------
|
import React from 'react';
import OutputRows from './OutputscreenRow';
const OutputScreens = (props) => {
return(
<div className="Opscreen">
<OutputRows value = {props.question}/>
<OutputRows value= {props.answer}/>
</div>
)
}
export default OutputScreens; |
import React from "react";
import Card from "./Card";
import Stretch from "../assets/pics/stretch.jpg";
import Toxins from "../assets/pics/toxins.jpeg";
import CardioDog from "../assets/pics/cardio-dog.jpeg";
import Lean from "../assets/pics/lean.jpeg";
import Balance2 from "../assets/pics/balance2.jpeg";
import Sports from "../assets/pics/basketball.jpeg";
import KetteleBell from "../assets/pics/kettle-bell-shoe.jpeg";
import SwimTurtle from "../assets/pics/swim-turtle.jpeg";
import Forest from "../assets/pics/strecthing-out-forest.jpeg";
const CardList = ({ props }) => {
const datas = [
{
id: 1,
name: "Flexability",
cardinfo: "Flexibility is very important in 2020",
image: Stretch,
homePakButton: "INFO"
},
{
id: 2,
name: "Chems & Preserves",
cardinfo: "There are chemicals and presevatives everywhere",
image: Toxins,
homePakButton: "INFO"
},
{
id: 3,
name: "Cardio",
cardinfo: "Using a heartrate moniter to get optimal results",
image: CardioDog,
homePakButton: "INFO"
},
{
id: 4,
name: "Lean Muscle",
cardinfo: "Build lean muscle using plant protien for healthier gains",
image: Lean,
homePakButton: "INFO"
},
{
id: 5,
name: "Balance & Rehab",
cardinfo:
"Maintainin balance and stability is important for preventing thos unwanted slips and falls",
image: Balance2,
homePakButton: "INFO"
},
{
id: 6,
name: "Sports Training",
cardinfo:
"You play sports so did I lets find the optimal workout for your specific sport goals",
image: Sports,
homePakButton: "INFO"
},
{
id: 7,
name: "Home Training",
cardinfo: "Yes we will come to you!",
image: KetteleBell,
homePakButton: "INFO"
},
{
id: 8,
name: "Swimming Classes",
cardinfo: "Never too late to learn to swim",
image: SwimTurtle,
homePakButton: "INFO"
},
{
id: 9,
name: "Personal PT Videos",
cardinfo:
"Let's create videos based on your goals so if were not working out or if your allways busy we can always stay connected online.",
image: Forest,
homePakButton: "INFO"
}
];
const renderedList = datas.map(datasClone => {
return (
<div className="">
<Card
key={datasClone.id}
image={datasClone.image}
name={datasClone.name}
cardinfo={datasClone.cardinfo}
homePakButton={datasClone.homePakButton}
/>
</div>
);
});
return <div className="">{renderedList}</div>;
};
export default CardList;
|
// export const AssociateHTMLConverter = (associateObj) => {
// return `
// <div class="associate card">
// <p class="associate__name">Name : ${associateObj.name}</p>
// <p class="associate__alibi">Alibi: ${associateObj.alibi}</p>
// </div>
// `
// }
|
import axios from 'axios'
import Vue from 'vue'
Vue.prototype.$http = axios
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
axios.defaults.xsrfCookieName = 'csrftoken'
axios.withCredentials = true
const urlprefix='http://192.168.1.43:8000/api/student/online/'
export default {
getpiedata() {
return online_get('kindcollect')
},
getstuonlinetime(stuid = undefined) {
let params = {}
params['stuid'] = stuid
return online_get('stuonlinetime', { params: params })
},
getsturoute(stuid = undefined, data = undefined) {
let params = {
stuid,
data
}
return online_get('sturoute', { params, params })
},
getstuonlinesort(stuid = undefined, term = undefined) {
let params = {
stuid,
term
}
return online_get('stuonlinesort', { params: params })
},
getbuildingcoord() {
return online_get('buildingcoord')
},
getheatmap(date = undefined) {
let params = { date }
return online_get('heatmap', { params: params })
},
getcollegefreq() {
return online_get('collegefreq')
},
filterstudents(college=undefined,grade=undefined,keyword=undefined) {
let params={
college,
grade,
keyword
}
return online_get('filterstudents',{params:params})
},
makerandomid(){
return online_get('makerandomid')
},
getstudentstatus(stuid=undefined){
let params={
stuid
}
return online_get('getstudentstatus',{params: params})
}
}
function online_get(url, options) {
if (options !== undefined) {
var { params = {} } = options
} else {
params = {}
}
return new Promise((resolve, reject) => {
// console.log({params})
axios.get(urlprefix+url, { params })
.then(res => {
// if (res.data.error !== null) {
// // Vue.prototype.$message({
// // type:'error',
// // message:res.data.data
// // })
// reject(res)
// }
resolve(res.data);
}, err => {
reject(err);
})
})
} |
/**
* Created by supervlad on 23.04.16.
*/
const initial = [];
const boardReducer = (state = initial, action) => {
let columns = [...state],
sourceCard = null,
column = null;
switch(action.type) {
case 'ADD_COLUMN':
return [...state, action.columnData];
case 'ADD_CARD':
column = columns[action.columnIdx];
column.cards.push({text: action.text, color: action.color});
return columns;
case 'REMOVE_CARD':
column = columns[action.columnIdx];
column.cards.splice(action.cardIdx, 1);
return columns;
case 'REMOVE_COLUMN':
columns.splice(action.columnIdx, 1);
return columns;
case 'CHANGE_CARD_COLOR':
column = columns[action.columnIdx];
column.cards[action.cardIdx].color = action.color;
return columns;
case 'REPLACE_COLUMNS':
if(action.source == action.target) return columns;
sourceCard = columns[action.source];
columns[action.source] = columns[action.target];
columns[action.target] = sourceCard;
return columns;
case 'MOVE_CARD_TO_COLUMN':
if(action.source.cardIdx == action.target.cardIdx) return columns;
sourceCard = columns[action.source.parentIdx].cards.splice(action.source.cardIdx, 1)[0];
columns[action.target.parentIdx].cards.push(sourceCard);
return columns;
case 'REPLACE_CARDS':
let sourceCards = columns[action.source.parentIdx].cards;
let targetCards = columns[action.target.parentIdx].cards;
sourceCard = sourceCards[action.source.cardIdx];
sourceCards[action.source.cardIdx] = targetCards[action.target.cardIdx];
targetCards[action.target.cardIdx] = sourceCard;
return columns;
default:
return state;
}
};
export default boardReducer; |
// Complex i
var complexi = math.complex('i');
// Pauli matrices & gates
var gateX = [[0,1],[1,0]];
var gateY = [[0,math.complex('-i')],[math.complex('i'),0]];
var gateZ = [[1,0],[0,-1]];
// More gates
var gateH = math.multiply(1/math.sqrt(2),[[1,1],[1,-1]]);
var gateSWAP = [[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]];
var gateCNOT = [[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]];
// Standard states
var statePlus = math.multiply(1/math.sqrt(2),[[1],[1]]);
var stateMin = math.multiply(1/math.sqrt(2),[[1],[-1]]);
var stateOne = [[0],[1]];
var stateZero = [[1],[0]];
var stateY = [[math.sqrt(0.5)], [math.multiply(math.sqrt(0.5),complexi)]];
var stateY_min = [[math.sqrt(0.5)], [math.multiply(math.sqrt(0.5),math.complex('-i'))]];
// Standard density matrices
var maxMixed = [[0.5, 0],[0, 0.5]];
var identity = [[1,0],[0,1]];
/**
* #getVector
*
* Computes vector representation of density matrix in Bloch Sphere
* Returns three.vector with x,y,z coordinates
*
* @param {Density matrix}
* @return {vector}
*/
function getVector(densMatrix){
// Compute projections of state onto all axes
var xCoor = trace(math.multiply(densMatrix,gateX));
var yCoor = trace(math.multiply(densMatrix,gateY));
var zCoor = trace(math.multiply(densMatrix,gateZ));
xCoor = getRealValue(xCoor);
yCoor = getRealValue(yCoor);
zCoor = getRealValue(zCoor);
var vector = new THREE.Vector3( xCoor, yCoor, zCoor );
return vector;
}
/**
* #getRealValue
*
* Returns real part of complex number
* @param {num}
* @return {num}
*/
function getRealValue(num) {
return math.complex(num).re;
}
// uses two noise matrices to compute new shape of Bloch sphere,
// returns two vectors, first is scaling of each axis, second is position of new center
/**
* #computeNewBlochSphere
*
* Uses two noise matrices to compute new shape of Bloch sphere,
* returns two vectors, first is scaling of each axis, second is position of new center
* @param {E1}
* @param {E2}
* @return {[[scaleX, scaleY, scaleZ], center_X]}
*/
function computeNewBlochSphere(E1, E2) {
// compute new positions of +/x,y,z
var newX_p = getVector(channelNoise(stateToDens(statePlus),E1,E2));
var newY_p = getVector(channelNoise(stateToDens(stateY),E1,E2));
var newZ_p = getVector(channelNoise(stateToDens(stateZero),E1,E2));
var newX_m = getVector(channelNoise(stateToDens(stateMin),E1,E2));
var newY_m = getVector(channelNoise(stateToDens(stateY_min),E1,E2));
var newZ_m = getVector(channelNoise(stateToDens(stateOne),E1,E2));
// now compute center of ellipsoid in three different ways,
// and check whether they give the same result
var center_X = (newX_p.clone().add(newX_m)).divideScalar(2);
var center_Y = (newY_p.clone().add(newY_m)).divideScalar(2);
var center_Z = (newZ_p.clone().add(newZ_m)).divideScalar(2);
// checks:
var dif_XY = center_X.distanceTo(center_Y);
var dif_XZ = center_X.distanceTo(center_Z);
var dif_YZ = center_Y.distanceTo(center_Z);
var newXAxis = newX_p.clone().sub(center_X);
var newYAxis = newY_p.clone().sub(center_Y);
var newZAxis = newZ_p.clone().sub(center_Z);
var scaleX = newXAxis.x;
var scaleY = newYAxis.y;
var scaleZ = newZAxis.z;
return [[scaleX, scaleY, scaleZ], center_X];
} // computeNewBlochSphere
// Returns trace of 2x2 matrix
/**
* #trace
*
* Returns trace of 2x2 matrix
* @param {matrix}
* @return {trace}
*/
function trace(matrix){
return math.add(matrix[0][0],matrix[1][1]);
}
/**
* getStateFromAngle
*
* Computes state of qubit from polar coordinates in BlochSphere
* Returns vector with alpha and beta for qubit in normal basis
*
* @param {theta}
* @param {phi}
* @return {[[alpha],[beta]]}
*/
function getStateFromAngle(theta, phi) {
var alpha = math.cos(theta/2);
var beta = math.multiply(math.sin(theta/2),math.exp(math.complex(0,phi)));
return [[alpha],[beta]];
}
/**
* #getEigenvalues
*
* Computes eigenvalues of 2x2 matrix
* returns array of the 2 eigenvalues of 2x2 matrix
* @param {matrix}
* @return {[lambda1, lambda2]}
*/
function getEigenvalues(matrix) {
var T = trace(matrix);
var D = math.det(matrix);
var part = math.chain(T)
.pow(2)
.divide(4)
.subtract(D)
.sqrt()
.done();
var lambda1 = math.chain(T).divide(2).add(part).done();
var lambda2 = math.chain(T).divide(2).subtract(part).done();
// a = matrix[0][0];
// b = matrix[0][1];
// c = matrix[1][0];
// d = matrix[1][1];
// partA = 1;
// partB = math.chain(a).add(d).multiply(-1).done();
// partC = math.subtract(math.multiply(a,d),math.multiply(c,d));
// partsqrt = math.chain(partC)
// .multiply(partA)
// .multiply(-4)
// .add(math.pow(partB,2))
// .sqrt()
// .done();
// lambda1 = math.chain(-1)
// .multiply(partB)
// .add(partsqrt)
// .multiply(0.5)
// .done();
// lambda2 = math.chain(-1)
// .multiply(partB)
// .subtract(partsqrt)
// .multiply(0.5)
// .done();
return [lambda1, lambda2];
}
/**
* #getEigenVectors
*
* Computes eigenvectors of 2x2 matrix
* returns matrix of the 2 eigenvectors of 2x2 matrix
* @param {matrix}
* @return {[eigvec1, eigvec2]}
*/
function getEigenVectors(matrix) {
var a = matrix[0][0];
var b = matrix[0][1];
var c = matrix[1][0];
var d = matrix[1][1];
var eigval = getEigenvalues(matrix);
var l1 = eigval[0];
var l2 = eigval[1];
var eigvec;
if (c != 0) {
eigvec = [[math.subtract(l1,d), math.subtract(l2,d)],[c,c]]
} else if (b != 0) {
eigvec = [[b,b],[math.subtract(l1,a), math.subtract(l2,a)]]
} else {
eigvec = identity;
}
return eigvec;
}
/**
* #conjugateTranspose
*
* Returns conjugate transpose of matrix
*
* @param {matrix}
* @return {conjugate transposed matrix}
*/
function conjugateTranspose(matrix) {
return math.conj(math.transpose(matrix));
}
/**
* #stateToDens
*
* Returns density matrix from qubit state
*
* @param {state}
* @return {density matrix}
*/
function stateToDens(state) {
return math.multiply(state, conjugateTranspose(state));
}
/**
* #tensorProduct
*
* Returns tensorProduct of two states
*
* @param {state1}
* @param {state2}
* @return {result}
*/
function tensorProduct(state1, state2) {
return [math.multiply(state1[0],state2[0]),
math.multiply(state1[0],state2[1]),
math.multiply(state1[1],state2[0]),
math.multiply(state1[1],state2[1])]
}
/**
* #controlledGate
*
* Returns controlled version of specified gate
*
* @param {gate}
* @return {controlled gate}
*/
function controlledGate(gate) {
return [[1,0,0,0],[0,1,0,0],[0,0,gate[0][0],gate[0][1]],[0,0,gate[1][0],gate[1][1]]];
}
/**
* #getPhaseShiftGate
*
* Returns phase shift gate with given angle shift
*
* @param {angle shift}
* @return {phase shift gate}
*/
function getPhaseShiftGate(shift) {
return [[1,0],[0,Math.exp(math.multiply(complexi,shift))]];
}
/**
* #applyGateToState
*
* Applies gate to state, returns resulting state
*
* @param {state}
* @param {gate}
* @return {state after gate}
*/
function applyGateToState(state, gate) {
return math.multiply(gate,state);
}
/**
* #applyGateToDensMat
*
* Applies gate to density matrix of state, returns resulting density matrix
*
* @param {density matrix}
* @param {gate}
* @return {density matrix after gate}
*/
function applyGateToDensMat(densMatrix, gate) {
return math.chain(gate)
.multiply(densMatrix)
.multiply(conjugateTranspose(gate))
.done();
}
/**
* #channelNoise
*
* Computes the transformation of the density matrix of a state when applying noise matrices E1 and E2
* Returns resulting density matrix
*
* @param {density matrix}
* @param {E1}
* @param {E2}
* @return {density matrix after noise}
*/
function channelNoise(densMatrix, E1, E2) {
return math.add(math.chain(E1)
.multiply(densMatrix)
.multiply(conjugateTranspose(E1))
.done(),
math.chain(E2)
.multiply(densMatrix)
.multiply(conjugateTranspose(E2))
.done());
}
/**
* #depolNoise
*
* Applies depolarization noise to density matrix with parameter r
*
* @param {density matrix}
* @param {r}
* @return {density matrix after depol}
*/
function depolNoise(densMatrix, r) {
return math.add(math.multiply(r,densMatrix), math.multiply((1-r),maxMixed));
}
/**
* #dephaseNoiseX
*
* Applies dephasing noise with probability r for bit flip (X-gate) to density matrix
*
* @param {density matrix}
* @param {r}
* @return {density matrix after dephase}
*/
function dephaseNoiseX(densMatrix, r) {
var E1 = math.sqrt(r);
var E2 = math.multiply(math.sqrt(1-r),gateX);
return channelNoise(densMatrix, E1, E2);
}
/**
* #dephaseNoiseZ
*
* Applies dephasing noise with probability r for phase flip (Z-gate) to density matrix
* @param {density matrix}
* @param {r}
* @return {density matrix after dephase}
*/
function dephaseNoiseZ(densMatrix, r) {
var E1 = math.sqrt(r);
var E2 = math.multiply(math.sqrt(1-r),gateZ);
return channelNoise(densMatrix, E1, E2);
}
/**
* #ampDampNoise
*
* Applies amplitude damping noise with probability r to density matrix
*
* @param {density matrix}
* @param {r}
* @return {density matrix after ampdamp}
*/
function ampDampNoise(densMatrix, r) {
var a0 = math.add(stateToDens(stateZero),
math.multiply(math.sqrt(r),stateToDens(stateOne)));
var a1 = math.multiply(math.sqrt(1-r),
math.multiply(stateZero,math.transpose(stateOne)));
return channelNoise(densMatrix, a0, a1);;
}
/**
* #isPure
*
* Checks if density matrix is pure
* @param {density matrix}
* @return {Boolean}
*/
function isPure(densMatrix) {
return math.round(trace(math.multiply(densMatrix, math.transpose(densMatrix)))) == 1;
}
/**
* #isValidTrace
*
* Check if density matrix is valid: trace should be 1
*
* @param {density matrix}
* @return {Boolean}
*/
function isValidTrace(densMatrix) {
tr = math.complex(trace(densMatrix));
if (tr.im >= 0.001) {
return false;
}
return (tr.re).toFixed(2) == 1;
}
/**
* #isValidHermitian
*
* Check if density matrix is valid: must be hermitian
*
* @param {density matrix}
* @return {Boolean}
*/
function isValidHermitian(densMatrix) {
return matrixEquals(densMatrix, conjugateTranspose(densMatrix));
}
/**
* #isValidUnitary
*
* Check if unitary is valid
*
* @param {density matrix}
* @return {Boolean}
*/
function isValidUnitary(densMatrix) {
return matrixEquals(math.multiply(densMatrix, conjugateTranspose(densMatrix)),identity);
}
/**
* #isValidEigenvalues
*
* Check if density matrix is valid: eigenvalues should be 0 < lambda < 1
* @param {density matrix}
* @return {Boolean}
*/
function isValidEigenvalues(densMatrix) {
eigval = getEigenvalues(densMatrix);
if (eigval[0].im >= 0.001 || eigval[1].im >= 0.001) {
return false;
}
return ((eigval[0].re <= 1) && (eigval[0].re >= 0) && (eigval[1].re <= 1) && (eigval[1].re >= 0));
}
/**
* #isValidNoiseMatrices
*
* Check if noise matrices are valid: sum_j(EjEj') = identity
*
* @param {E1}
* @param {E2}
* @return {Boolean}
*/
function isValidNoiseMatrices(E1, E2) {
var mat = math.add(math.multiply(E1,conjugateTranspose(E1)),
math.multiply(E2,conjugateTranspose(E2)));
return matrixEquals(mat, identity);
}
/**
* #isHamiltonianTrace
*
* Check if matrix is hamiltonian: trace == 0
*
* @param {matrix}
* @return {Boolean}
*/
function isHamiltonianTrace(matrix) {
return trace(matrix).toFixed(2) == 0;
}
/**
* #getPadeApproxExp
*
* Computes Pade approximation for the exponent of a matrix
* Returns resulting matrix
*
* @param {matrix}
* @return {result}
*/
function getPadeApproxExp(matrix) {
var approx = 5;
var factors = [1,2,9,72,1008,30240];
var denom = 0;
var num = 0;
for (var i = 0; i <= approx; i++) {
addterm = math.multiply(math.pow(matrix,i), 1/factors[i]);
num = math.add(num, addterm);
if (i % 2 == 0) {
denom = math.add(denom,addterm);
} else {
denom = math.subtract(denom,addterm);
}
}
return math.divide(num,denom);
}
/**
* #getUnitaryAtTime
*
* Computes unitary at given time for given Hamiltonian
*
* @param {hamiltonian}
* @param {time}
* @return {result}
*/
function getUnitaryAtTime(hamiltonian, time) {
var eigval = getEigenvalues(hamiltonian);
var diagMat = math.chain(eigval)
.multiply(math.complex("-i"))
.multiply(time)
.exp()
.diag()
.done();
var eigVecMat = getEigenVectors(hamiltonian);
var eigVecInv = math.inv(eigVecMat);
return math.chain(eigVecMat).multiply(diagMat).multiply(eigVecInv).done();
}
/**
* #makeMixedState
*
* Computes mixed state from four states with probabilities
*
* @param {densMat1}
* @param {prob1}
* @param {densMat2}
* @param {prob2}
* @param {densMat3}
* @param {prob3}
* @param {densMat4}
* @param {prob4}
* @return {mixed state}
*/
function makeMixedState(densMat1, prob1, densMat2, prob2, densMat3, prob3, densMat4, prob4) {
var state1 = math.multiply(prob1, densMat1);
var state2 = math.multiply(prob2, densMat2);
var state3 = math.multiply(prob3, densMat3);
var state4 = math.multiply(prob4, densMat4);
var matrix = math.add(state1, state2);
matrix = math.add(matrix, state3);
matrix = math.add(matrix, state4);
return matrix;
}
/**
* #matrixEquals
*
* Returns matrix1 == matrix2
*
* @param {mat1}
* @param {mat2}
* @return {Boolean}
*/
function matrixEquals(mat1, mat2) {
mat1 = math.round(math.complex(mat1),1);
mat2 = math.round(math.complex(mat2),1);
return ((mat1[0][0].im == mat2[0][0].im) &&
(mat1[1][0].im == mat2[1][0].im) &&
(mat1[0][1].im == mat2[0][1].im) &&
(mat1[1][1].im == mat2[1][1].im) &&
(mat1[0][0].re == mat2[0][0].re) &&
(mat1[1][0].re == mat2[1][0].re) &&
(mat1[0][1].re == mat2[0][1].re) &&
(mat1[1][1].re == mat2[1][1].re));
}
/**
* #makePhaseGate
*
* Returns phaseGate, with phase phi
*
* @param {angle}
* @return {matrix}
*/
function makePhaseGate(phi) {
return [[1,0],[0, math.exp(math.multiply(complexi, phi))]];
} |
import React from 'react';
import { Row, Col,Card, Button, Icon, Divider, message, Table, Message, Modal} from 'antd';
import {fetch} from '../../api/tools'
import { receiveData, fetchData } from '@/action';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
class News extends React.Component {
state={
newsInfo: [],
modalContent: {}
}
componentDidMount(){
this.fetchNews(1)
}
fetchNews=(current)=>{
fetch('get',`/usercenter/messages/list?current=${current}&size=10`).then(res=>{
if(res.code == 0){
let newsInfo = res.data.records
// newsInfo = this.state.newsInfo.concat(newsInfo);
newsInfo.forEach((item,index)=>{
item.number = (current-1)*10+index+1;
item.type = 0?'后台消息':'系统消息'
})
this.setState({newsInfo: newsInfo, total: res.data.total, current: current})
}else{
Message.destroy()
Message.error(res.msg)
}
})
}
fetchMore = (page,pageSize) =>{
this.fetchNews(page.current)
}
showModal = (item) => {
this.setState({
visible: true,
modalContent: item
});
let params = {
id: item.id,
status: 1,
}
// fetch('put','/usercenter/messages/update',params).then(res=>{
// if(res.code == 0){
// this.fetchNews(this.state.current)
// this.props.fetchData({funcName:'unreadNews',stateName: 'unreadNewsNum'})
// }else{
// Message.destroy()
// Message.error(res.msg)
// }
// })
};
handleCancel = (e) => {
this.setState({
visible: false,
});
};
render() {
let { newsInfo, total, modalContent, current} = this.state
return (
<div className="gutter-example">
<Card>
<Table
columns={columns}
dataSource={newsInfo}
pagination={{total: total, current: current}}
onChange={(page,pageSize)=>{this.fetchMore(page,pageSize)}}
onRow={(record) => {
return {
onClick: () => {this.showModal(record)}, // 点击行
};
}}
/>
</Card>
<Modal title="消息详情"
visible={this.state.visible}
onCancel={this.handleCancel}
footer={false}
>
<p style={{fontSize: '13px',marginLeft:'-5'}}>{`【${modalContent.type}】`} {modalContent.createTime}</p>
<p style={{color: '#ababab'}}>{modalContent.content}</p>
<div className="modal-footer-btn">
<Button type='primary' onClick={this.handleCancel}>我知道了</Button>
</div>
</Modal>
</div>
);
}
}
const columns= [
{ title: '序号',
// dataIndex: 'number',
key: 'number' ,
render: (record) =>
<span>{record.number}</span>
},
{ title: '时间 ',
// dataIndex: 'createTime',
key: 'createTime',
render: (record) =>
<span>{record.createTime}</span>
},
{ title: '消息类型',
// dataIndex: 'type',
key: '1',
render: (record) =>
<span>{record.type}</span>
},
{ title: '内容',
// dataIndex: 'content',
key: '2' ,
width: '60%',
render: (record) =>
<span className={record.status == 0? 'c-blue col-content':'col-content'}>{record.content}</span>,
},
];
const mapStateToProps = state => {
const { responsive = {data: {}} } = state.httpData;
return {responsive};
};
const mapDispatchToProps = dispatch => ({
fetchData: bindActionCreators(fetchData, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(News)
|
// @flow
export const navigate = (location:string) => ({type: 'NAVIGATE', payload: location})
export const selectVisitor = (visitor: ?string) => ({ type: 'SELECT_VISITOR', payload: visitor })
export const locationChange = (location: Location) => ({ type: 'LOCATION_CHANGE', payload:location })
|
import React from 'react';
let color = {
color: "coral",
letterSpacing: '12px'
};
let time = new Date();
let currentTime = "Morning"
let currentHour = time.getHours();
console.log(currentHour);
let currentColor = {
color: "red"
};
if(currentHour >= 12 && currentHour <= 17 ){
currentTime = "Afternoon";
currentColor.color = "green";
}else if(currentHour >= 18 && currentHour <= 23){
currentTime = "Evening";
currentColor.color = "black"
}
function Heading(){
return <div className="heading">
<h1 style={currentColor}>Good {currentTime}!</h1>
<h1 style={color} >Hello I am Adam</h1>
</div>
}
export default Heading; |
import React from 'react';
import ReactDOM from 'react-dom';
import MovieCard from './components/MovieCard';
const jurassicWorldGenres = ['Action', 'Adventure', 'Science Fiction', 'Thriller'];
ReactDOM.render(
<MovieCard
title="Jurassic World"
genres={jurassicWorldGenres}
/>,
document.getElementById('root')
);
|
/**
* Created by zhangsq on 2017/4/24.
*/
'use strict';
const assert = require('assert');
let version = +process.versions.node.match(/^\w+?/)[0];
const GeneralHistory = version > 5 ? require('../../src/general-history') : require('../../lib/general-history');
describe('GeneralHistory', () => {
let history;
it('Should be able to create instance', () => {
history = new GeneralHistory({stackLimit: 10});
[
'push',
'back',
'forward',
'locate',
'list',
'clear',
'count',
'canBack',
'canForward',
'current',
'currentIndex'
]
.forEach(propertyName => assert.ok(propertyName in history));
});
describe('#push()', () => {
it('Should be have instance method push()', () => {
assert.ok(typeof history.push === 'function');
});
it('Should be able to push data', () => {
assert.ok(history.push('hello') === history);
assert.ok(history.push('world') === history);
[1, 2, 3, 4, 5].forEach(num => assert.ok(history.push(num) === history));
});
});
describe('#back()', () => {
it('Should be have instance method back()', () => {
assert.ok(typeof history.back === 'function');
});
it('Should be able to back history', () => {
assert.ok(history.back() === 4);
assert.ok(history.canBack);
assert.ok(history.current === 4);
assert.ok(history.currentIndex === 5);
});
it('Should be able to back by step', () => {
assert.ok(history.back(5) === 'hello');
});
it('Should be return null if can\'t back', () => {
assert.ok(history.back() === null);
assert.ok(history.back(2) === null);
});
it('#canBack', () => {
assert.ok(!history.canBack);
});
});
describe('#forward()', () => {
it('Should be have instance method forward()', () => {
assert.ok(typeof history.forward === 'function');
});
it('Should be able to forward history', () => {
assert.ok(history.forward() === 'world');
assert.ok(history.canForward);
});
it('Should be able to forward by step', () => {
assert.ok(history.forward(5) === 5);
});
it('Should be return null if can\'t forward', () => {
assert.ok(history.forward() === null);
assert.ok(history.forward(2) === null);
});
it('#canForward', () => {
assert.ok(!history.canForward);
});
});
describe('#locate()', () => {
it('Should be have instance method locate()', () => {
assert.ok(typeof history.locate === 'function');
});
it('Should be able to locate history', () => {
assert.ok(history.locate(0) === 'hello');
assert.ok(history.locate(2) === 1);
assert.ok(history.locate(6) === 5);
});
it('Should be return null if locate a history of not exists', () => {
assert.ok(history.locate(-1) === null);
assert.ok(history.locate(10) === null);
});
});
describe('#list()', () => {
it('Should be have method of instance named list()', () => {
assert.ok(typeof history.list === 'function');
});
it('Should be able to get history list', () => {
assert.deepEqual(history.list(), ['hello', 'world', 1, 2, 3, 4, 5]);
});
it('Should be able custom preprocessor of #list()', () => {
assert.deepEqual(history.list(item => typeof item === 'string' ? item.toUpperCase() : item + 1), ['HELLO', 'WORLD', 2, 3, 4, 5, 6]);
});
});
describe('#count', () => {
it('Should be able to get history count', () => {
assert.ok(history.count === 7);
})
});
describe('#clear()', () => {
it('Should be have method of instance named clear()', () => {
assert.ok(typeof history.clear === 'function');
});
it('Should be able to clear history', () => {
assert.ok(history.clear() === history);
assert.ok(history.count === 0);
});
});
describe('Composite test', () => {
before(() => {
for (let i = 0; i < 5; i++) {
history.push(i + 10);
}
});
it('Should be able push if backed', () => {
assert.ok(history.back(2) === 12);
assert.ok(history.push(15) === history);
assert.ok(history.count === 4);
assert.ok(!history.canForward);
assert.deepEqual(history.list(), [10, 11, 12, 15]);
});
it('Should be able shrink history stack by limit', () => {
for (let i = 0; i < 20; i++) {
assert.ok(history.push(i + 10));
}
assert.ok(history.count === 10);
});
});
}); |
import React from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { useHistory } from "react-router-dom";
import MovieTitle from "./MovieTitle";
import MoviePoster from "./MoviePoster";
export const MovieTableRow = ({
dispatch,
movie,
rank,
}) => {
const { overview, id, poster_path } = movie;
const truncatedOverview = overview.substring(0, 150) + "…";
const history = useHistory();
const handleClick = () => {
history.push(`/movie/${id}`);
};
return (<div className="MovieTableRow" id={`Movie-${id}`} style={{
padding: 20,
cursor: "pointer",
}} onClick={handleClick}>
<div style={{ display: "flex" }}>
<MoviePoster path={poster_path} style={{ height: 70 }} />
<div style={{ marginLeft: 20 }}>
<MovieTitle movie={movie} />
<div>{truncatedOverview} <span className="blue">read more</span></div>
</div>
</div>
</div>);
};
MovieTableRow.propTypes = {
dispatch: PropTypes.func.isRequired,
rank: PropTypes.number,
};
MovieTableRow.defaultProps = {
rank: 0,
};
export default connect((state) => ({
/* Map state to props object:
/* foo: state.foo */
}))(MovieTableRow);
|
var tipsTpl = '<div style="position: absolute; z-index: 999; padding: 0 !important; background-color: #007d60;" class="modal-dialog-buttons">'+
'</div>';
var body = $(document.body);
var tips = $(tipsTpl).hide().appendTo(body);
var tipsHideTimer = null;
(function() {
var userLink = '.aw-user-name';
$(document).on('mouseover', userLink, function(e) {
var link= $(this);
var offset = link.offset();
var data_id = undefined;
// 在大部分页面
if ( link.attr('data-id') != undefined ) {
data_id = link.attr('data-id');
}
// 在 https://www.lundao.com/people/ 页面
else if ( link.parent().parent().children(".operate").children(".follow").length != 0 ) {
var follow_link = link.parent().parent().children(".operate").children(".follow");
var onclick_attr = follow_link.attr('onclick');
// AWS.User.follow($(this), 'user', 372);
var regExp = /, ([0-9]+)\);$/;
var matches = regExp.exec(onclick_attr);
data_id = matches[1];
}
else {
return ;
}
if ( data_id != undefined ) {
tips.html('<span style="padding:0 10px; color: #fff;">论道第'+data_id+'个注册的用户</span>');
}
tips.show().offset({
left: offset.left + link.width() + 5,
top: offset.top
});
data_id = undefined;
});
$(document).on('mouseout', userLink, function(e) {
tips.hide();
data_id = 0;
});
// https://www.lundao.com/people/xxx 页面
if ( $('.aw-user-detail-box').length != 0 ) {
var data_id;
// 其它人的页面
if ( $('.aw-user-detail-box a.follow').length != 0 ) {
follow_link = $('.aw-user-detail-box .follow');
onclick_attr = follow_link.attr('onclick');
// AWS.User.follow($(this), 'user', 372);
var regExp = /, ([0-9]+)\);$/;
var matches = regExp.exec(onclick_attr);
if ( matches ) {
data_id = matches[1];
}
}
// 自己的页面
else {
var script_html = $("script").html();
// var G_USER_ID = "2500";
var regExp = /.*G_USER_ID.*\"([0-9]+)\";/;
var matches = regExp.exec(script_html);
if ( matches ) {
data_id = matches[1];
}
}
var constantTips = $(tipsTpl).hide().appendTo(body);
if ( data_id != undefined ) {
constantTips.html('<span style="padding:0 10px; color: #fff;">论道第'+data_id+'个注册的用户</span>');
}
var item = $('.aw-user-detail-box img');
var offset = item.offset();
constantTips.show().offset({
top: offset.top + item.height() + 10,
left: offset.left
});
}
})();
|
import React from 'react'
import Title from '../components/Title/Title'
import Navbar from '../components/Navbar'
import AnimatedBg from '../components/AnimatedBg'
export default function Template({
data, // this prop will be injected by the GraphQL query below.
}) {
const {markdownRemark} = data // data.markdownRemark holds our post data
const {frontmatter, html} = markdownRemark
return (
<div
className={frontmatter.theme
? `has-background-${frontmatter.theme}`
: 'has-background-dark'}>
<section
className={frontmatter.theme
? `hero is-large animated-bg-parent is-${frontmatter.theme}`
: 'hero is-large animated-bg-parent is-dark'}>
<AnimatedBg bg={frontmatter.bg}/>
<Navbar/>
<div className="hero-body">
<div className="container has-text-centered">
<div className="section">
<div className="columns is-mobile is-centered">
<div className="column is-two-thirds-tablet is-half-desktop">
<p className="title">
{frontmatter.title}
</p>
<p
className="subtitle"
dangerouslySetInnerHTML={{
__html: frontmatter.subtitle
}}/>
</div>
</div>
</div>
</div>
</div>
</section>
<div className="container">
<div className="section">
<div
className="content"
dangerouslySetInnerHTML={{
__html: html
}}/>
</div>
</div>
</div>
)
}
export const pageQuery = graphql `
query BlogPostByPath($path: String!) {
markdownRemark(frontmatter: { path: { eq: $path } }) {
html
frontmatter {
date(formatString: "MMMM DD, YYYY")
path
title
subtitle
bg
theme
}
}
}
` |
export default from './OrderText';
|
import React from 'react'
import gperson from '../img/icons/gradient-person.png';
import lmore from '../img/icons/load-more.png';
import sfocus from '../img/icons/service-focus.png';
import smethod from '../img/icons/service-method.png';
import sknowledge from '../img/icons/service-knowledge.png';
import {Button} from 'react-bootstrap'
const Main = () => {
return (
<div className="container">
<main className="main">
<div className="slider-facebook container">
<div className="row">
<div className="slider-bootstrap carousel slide col-12 col-xl-9" data-right="carousel" id="slides">
<ul className="carousel-indicators slider-bootstrap__indicators">
<li className="active" data-target="#slides" data-slide-to="0"></li>
<li data-target="#slides" data-slide-to="1"></li>
<li data-target="#slides" data-slide-to="2"></li>
<li data-target="#slides" data-slide-to="3"></li>
<li data-target="#slides" data-slide-to="4"></li>
</ul>
<div className="carousel-inner">
<div className="carousel-item slider-bootstrap__item slider-bootstrap__item_one active">
<p className="slider-bootstrap__heading">Control and manage any</p>
<p className="slider-bootstrap__heading slider-bootstrap__heading_last-child">device with cloud
solutions</p>
<p className="slider-bootstrap__subtitle">Improve business performance and the user experience
</p>
<p className="slider-bootstrap__subtitle slider-bootstrap__subtitle_last-child">with the right
mix of IoT technology
and processes
</p>
<a className="slider-bootstrap__link" href="pages/category.html">View more</a>
</div>
<div className="carousel-item slider-bootstrap__item slider-bootstrap__item_two">
<p className="slider-bootstrap__heading">Control and manage any</p>
<p className="slider-bootstrap__heading slider-bootstrap__heading_last-child">device with cloud
solutions</p>
<p className="slider-bootstrap__subtitle">Improve business performance and the user experience
</p>
<p className="slider-bootstrap__subtitle slider-bootstrap__subtitle_last-child">with the right
mix of IoT technology
and processes
</p>
<a className="slider-bootstrap__link" href="pages/category.html">View more</a>
</div>
<div className="carousel-item slider-bootstrap__item slider-bootstrap__item_three">
<p className="slider-bootstrap__heading">Control and manage any</p>
<p className="slider-bootstrap__heading slider-bootstrap__heading_last-child">device with cloud
solutions</p>
<p className="slider-bootstrap__subtitle">Improve business performance and the
user experience</p>
<p className="slider-bootstrap__subtitle slider-bootstrap__subtitle_last-child">with the right
mix of IoT technology
and processes
</p>
<a className="slider-bootstrap__link" href="pages/category.html">View more</a>
</div>
<div className="carousel-item slider-bootstrap__item slider-bootstrap__item_four">
<p className="slider-bootstrap__heading">Control and manage any</p>
<p className="slider-bootstrap__heading slider-bootstrap__heading_last-child">device with cloud
solutions</p>
<p className="slider-bootstrap__subtitle">Improve business performance and the user experience
</p>
<p className="slider-bootstrap__subtitle slider-bootstrap__subtitle_last-child">with the right
mix of IoT technology
and processes
</p>
<a className="slider-bootstrap__link" href="pages/category.html">View more</a>
</div>
<div className="carousel-item slider-bootstrap__item slider-bootstrap__item_five">
<p className="slider-bootstrap__heading">Control and manage any</p>
<p className="slider-bootstrap__heading slider-bootstrap__heading_last-child">device with cloud
solutions</p>
<p className="slider-bootstrap__subtitle">Improve business performance and the user experience
</p>
<p className="slider-bootstrap__subtitle slider-bootstrap__subtitle_last-child">with the right
mix of IoT technology
and processes
</p>
<a className="slider-bootstrap__link" href="pages/category.html">View more</a>
</div>
</div>
</div>
<aside className="facebook-follow d-xl-flex col-xl-3">
<div className="facebook-follow__window">
<p className="facebook-follow__sale">55%</p>
<p className="facebook-follow__description">Summer sales</p>
</div>
<p className="facebook-follow__heading">Follow us on Facebook</p>
<p className="facebook-follow__subtitle">Sed ut perspiciatis unde omnis iste natus error sit</p>
<a className="facebook-follow__link" target="_blank" href="https://www.facebook.com/OSFDigital/"><i
className="fa fa-facebook facebook-follow__icon" aria-hidden="true"></i>Follow</a>
</aside>
</div>
</div>
<div className="products">
<div className="container">
<div className="products__head-whrapper">
<div className="products__line"></div>
<h2 className="products__heading">Popular Items</h2>
<div className="products__line"></div>
</div>
<div className="row products__row">
<div className="col-12 col-md-6 col-xl-3 products__item">
<div className="products__photo products__photo_one">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">Kristina Dam Oak Table With <br/>
White Marble Top</div>
<div className="products__price">$ 799.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item">
<a className="products__photo products__photo_two d-block" href="pages/product.html">
</a>
<div className="products__description">
<a className="products__name products__name_link" href="pages/product.html">Hay - About A Lounge
<br/>
Chair AAL 93</a>
<div className="products__buy-now">
<a className="products__buy-now_price" href="pages/product.html">$659.55</a>
<Button className="products__buy-now_button products__button_buy">Buy now</Button>
</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item">
<div className="products__photo products__photo_three">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">Activate Facial Mask and <br/>
Charcoal Soap</div>
<div className="products__price">$ 129.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item">
<div className="products__photo products__photo_four">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">Cocktail Table Walnut <br/>
| YES</div>
<div className="products__price">$ 299.99</div>
</div>
</div>
</div>
<div className="row products__row">
<div className="col-12 col-md-6 col-xl-3 products__item">
<div className="products__photo products__photo_five">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">Hay - About A Lounge <br/>
Chair AAL 93</div>
<div className="products__price">$ 659.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item">
<div className="products__photo products__photo_six">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">TORY DESK CALENDAR</div>
<div className="products__price">$ 410.99</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item">
<div className="products__photo products__photo_seven">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">CH445 Wing Chair on <br/>
SUITE NY</div>
<div className="products__price">$ 330.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item">
<div className="products__gradient">
<div className="products__gradient_text">My dragons are misbehaving again. Unbelieveable!</div>
<img className="products__gradient_image" src={gperson} alt="person"/>
<div className="products__gradient_counter">5h ago</div>
</div>
<div className="products__photo products__photo_full products__photo_eight">
</div>
</div>
</div>
<div className="row products__row products__slider">
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
<div className="products__photo products__photo_one">
</div>
<div className="products__description">
<div className="products__name">Kristina Dam Oak Table With <br/>
White Marble Top</div>
<div className="products__price">$ 799.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<a className="products__photo products__photo_two d-block" href="pages/product.html">
</a>
<div className="products__description">
<a className="products__name products__name_link" href="pages/product.html">Hay - About A Lounge
<br/>
Chair AAL 93</a>
<div className="products__buy-now">
<a className="products__buy-now_price" href="pages/product.html">$659.55</a>
<Button className="products__buy-now_button products__button_buy">Buy now</Button>
</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__photo products__photo_three">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">Activate Facial Mask and <br/>
Charcoal Soap</div>
<div className="products__price">$ 129.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__photo products__photo_four">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">Cocktail Table Walnut <br/>
| YES</div>
<div className="products__price">$ 299.99</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__photo products__photo_five">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">Hay - About A Lounge <br/>
Chair AAL 93</div>
<div className="products__price">$ 659.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__photo products__photo_six">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">TORY DESK CALENDAR</div>
<div className="products__price">$ 410.99</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__photo products__photo_seven">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">CH445 Wing Chair on <br/>
SUITE NY</div>
<div className="products__price">$ 330.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__gradient">
<div className="products__gradient_text">My dragons are misbehaving again. Unbelieveable!
</div>
<img className="products__gradient_image" src={gperson} alt="person"/>
<div className="products__gradient_counter">5h ago</div>
</div>
<div className="products__photo products__photo_full products__photo_eight"></div>
</div>
</div>
<div className="row products__row" id="loaded-products">
</div>
<Button className="products__load-more" id="btn-main">Load more <img className="products__load-more_image"
src={lmore} alt="load-more"/></Button>
</div>
</div>
<div className="osf-banner">
<h3 className="osf-banner__heading">Banner OSF Theme</h3>
<p className="osf-banner__subtitle">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
</p>
</div>
<div className="products slider-slick">
<div className="container">
<div className="slider-slick__head-whrapper">
<h2 className="slider-slick__heading">Featured Products</h2>
<p className="slider-slick__subtitle">Unde omnis iste natus error sit voluptatem</p>
<div className="slider-slick__arrows">
<div className="slider-slick__lines"></div>
</div>
</div>
<div className="row products__row slider-slick__slider">
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__photo products__photo_one">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">Kristina Dam Oak Table With <br/>
White Marble Top</div>
<div className="products__price">$ 799.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<a className="products__photo products__photo_two d-block" href="product.html">
</a>
<div className="products__description">
<a className="products__name products__name_link" href="product.html">Hay - About A Lounge
<br/>
Chair AAL 93</a>
<div className="products__buy-now">
<a className="products__buy-now_price" href="product.html">$659.55</a>
<Button className="products__buy-now_button products__button_buy">Buy now</Button>
</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__photo products__photo_three">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">Activate Facial Mask and <br/>
Charcoal Soap</div>
<div className="products__price">$ 129.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__photo products__photo_four">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">Cocktail Table Walnut <br/>
| YES</div>
<div className="products__price">$ 299.99</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__photo products__photo_five">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">Hay - About A Lounge <br/>
Chair AAL 93</div>
<div className="products__price">$ 659.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__photo products__photo_six">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">TORY DESK CALENDAR</div>
<div className="products__price">$ 410.99</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__photo products__photo_seven">
<div className="products__hover">
<Button className="products__button products__button_buy"><i className="fa fa-plus"
aria-hidden="true"></i></Button>
<Button className="products__button products__button_like"><i className="fa fa-heart"
aria-hidden="true"></i></Button>
</div>
</div>
<div className="products__description">
<div className="products__name">CH445 Wing Chair on <b/>
SUITE NY</div>
<div className="products__price">$ 330.55</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-3 products__item slider-slick__item">
<div className="products__gradient">
<div className="products__gradient_text">My dragons are misbehaving again. Unbelieveable!
</div>
<img className="products__gradient_image" src={gperson} alt="person"/>
<div className="products__gradient_counter">5h ago</div>
</div>
<div className="products__photo products__photo_full products__photo_eight"></div>
</div>
</div>
</div>
</div>
<div className="sevices-static">
<div className="container">
<div className="row sevices-static__whrapper">
<div className="col-md-4 sevices-static__facility">
<img className="sevices-static__image" src={sfocus} alt="facility"/>
<div className="sevices-static__description">
<p className="sevices-static__title">Focus</p>
<p className="sevices-static__subtitle">Our unwavering focus on superior service delivery and
building
next
generation competencies</p>
</div>
</div>
<div className="col-md-4 sevices-static__facility">
<img className="sevices-static__image" src={smethod} alt="facility"/>
<div className="sevices-static__description">
<p className="sevices-static__title">Method</p>
<p className="sevices-static__subtitle">A standardized methodology designed to deliver
measurable
business
results
and predictable costs</p>
</div>
</div>
<div className="col-md-4 sevices-static__facility">
<img className="sevices-static__image" src={sknowledge} alt="facility"/>
<div className="sevices-static__description">
<p className="sevices-static__title">Knowledge</p>
<p className="sevices-static__subtitle">A highly skilled, proactive workforce that reliably
improves
each
client’s
ROI while mitigating their business risk</p>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
)
}
export default Main;
|
const puppeteer = require('puppeteer');
const hackerearth =require('./hackerearth');
const codeforces =require('./codeforces');
const codechef =require('./codechef');
const hackerrank =require('./hackerrank');
const interviewbit =require('./interviewbit');
(async () => {
await hackerearth.initialize();
await hackerearth.fun();
await codeforces.initialize();
await codeforces.fun();
await codechef.initialize();
await codechef.fun();
await hackerrank.initialize();
await hackerrank.fun();
await interviewbit.initialize();
await interviewbit.fun();
})();
|
"use strict"
let students = [];
let list = "";
let inputs = document.getElementsByClassName("student-input");
function Student(name, surname, email, phone, age) {
this.name = name,
this.surname = surname,
this.email = email,
this.phone = phone,
this.age = age
this.info = function(){
return `<tr><th>${index + 1}</th><td>${this.name}</td><td>${this.surname}</td><td>${this.email}</td><td>${this.phone}</td><td>${this.age}</td></tr>`
}
}
function generateLiItems(value, index) {
list += `<tr><th>${index + 1}</th><td>${value.name}</td><td>${value.surname}</td><td>${value.email}</td><td>${value.phone}</td><td>${value.age}</td></tr>`;
}
function reset() {
list = "";
inputs[0].value = "";
inputs[1].value = "";
inputs[2].value = "";
inputs[3].value = "";
inputs[4].value = "";
document.getElementById("alert").style.display = "none";
document.getElementById("alert-number").style.display = "none";
}
function getInputValues() {
let student = new Student(inputs[0].value.toUpperCase(), inputs[1].value.toUpperCase(), inputs[2].value.toUpperCase(), inputs[3].value, inputs[4].value);
if (inputs[0].value && inputs[1].value && inputs[2].value && inputs[3].value && inputs[4].value) {
if(inputs[4].value > 0){
students.push(student);
getWriteList();
document.getElementById("alert").style.display = "none";
return document.getElementById("alert-number").style.display = "none";
}else{
document.getElementById("alert").style.display = "none";
return document.getElementById("alert-number").style.display = "block"
}
}else {
document.getElementById("alert-number").style.display = "none";
return document.getElementById("alert").style.display = "block";
}
}
function getWriteList() {
students.forEach(generateLiItems);
document.getElementsByClassName("student-list")[0].innerHTML = list;
reset();
}
// When Onclick Sorted
function sortedMetod(value) {
return function (a, b) {
if (a[value] < b[value]) { return -1; } else if (a[value] > b[value]) { return 1 } else { return 0; }
}
}
function sortedList(value) {
students.sort(sortedMetod(value));
getWriteList();
}
// Random Sorted
function randomSort(){
students.sort(myFunct());
getWriteList();
}
function myFunct(){
let random = Math.random() - 0.5;
return function () {
return random;
}
}
|
import contract from 'truffle-contract';
import PersonContract from '@contracts/Person.json';
const Person = {
contract: null,
instance: null,
init: () => {
let self = this;
new Promise((resolve, reject) => {
self.contract = contract(PersonContract);
self.contract.setProvider(window.web3.currentProvider);
self.instance = self.contract.deployed().then(instance => {
return instance;
}).catch(error => {
reject(error);
});
});
},
setName: (name) => {
let self = this;
return new Promise((resolve, reject) => {
self.instance.setName(name, {from: window.web3.eth.accounts[0]})
.then(response => {resolve(response)})
.catch(error => {reject(error)});
});
},
getName: () => {
let self = this;
return new Promise((resolve, reject) => {
self.instance
.then(Person => {
return Person.name();
})
.then(name => {
console.log(name);
resolve(name);
})
.catch(error => {
console.error(error);
});
});
}
};
export default Person;
|
const tl = gsap.timeline({ default: { ease: "power1.out" } })
tl.to("#intro .txt", { y: "0%", opacity: 1, duration: 1, stagger: .25 })
tl.to('#slider', { y: "-100%", opacity: 1, duration: 1, delay: 0.5 })
tl.to('#intro', { y: "-100%", duration: 1 }, "-=1")
let nav = document.querySelector('.main-nav')
window.addEventListener('scroll', console.log('hi'))
// menu
let menuBtn = document.querySelector('.menu-btn')
let subMenu = document.querySelector('.sub-menu')
menuBtn.addEventListener('click', toggleMenu)
function toggleMenu() {
menuBtn.classList.toggle('active')
subMenu.classList.toggle('active')
}
// banner-out
tl.to('.banner .bg', { x: "100%", duration: 1, delay: 0.5 })
tl.from('.banner h2', { y: "50px", opacity: 0, duration: 1, stagger: .25 }) |
import { Spinner, Alert } from "react-bootstrap";
const LoadingOverlay = (props) => {
return (
<Alert variant="success">
<div >
<div className="d-flex justify-content-center">
<Alert.Heading>{props.title || "We are loading data"}</Alert.Heading>
</div>
<div className="d-flex justify-content-center">
<p>Please wait!</p>
</div>
<div className="d-flex justify-content-center">
<Spinner animation="border" variant="success" />
</div>
</div>
</Alert>
);
};
export default LoadingOverlay;
|
function pow(x, n) {
var result = x;
for (var i = 1; i < n; i++) {
result = result * x;
}
return result;
}
var x = prompt('Введите основание', '');
var n = prompt ('Введите степень', '');
if ( n <= 0 ) {
alert('Эта степень ' + n + ' не поддерживается, введите число большее, чем 1');
} else {
console.log(pow(x, n));
}
//
//
//var userArray = [];
//
//function getUser() {
// for (var i =0; i < 3; i++) {
// userArray[i] = prompt('Введите пользователя №'+(i+1), '');
// }
//console.log(userArray);
//}
//
//getUser();
//
//function checkUser () {
// var newUser=prompt('Введите имя пользователя', '');
//
// if ( newUser.length < 1) {
// alert('Achtung partisanen!!!');
// return;
// }
// for ( i = 0; i < userArray.length; ++i) {
// if ( userArray[i] != newUser ) {
// alert(newUser+ 'Нет такого имени пользователя!');
// break;
// } else if(userArray[i] === newUser) {
// alert(newUser+ ', Вы удачно вошли');
// break;
// }
// }
//}
//checkUser();
//var names = [];
//
// for(var i = 0; i < 5; i++){
// names.push( prompt("Введите имя", '') );
// }
//
// console.log('Массив имен = ', names);
//
////Сравнение имени пользователя с именами в массиве
//
// var userName = prompt('Введите имя пользователя', '');
//
// if ( names.indexOf(userName) >= 0) {
// console.log(userName + ', вы успешно вошли');
// } else {
// console.log('Неверное имя пользователя');
// alert('Неверное имя пользователя');
// }
//
//var userArray = [];
//
//function getUser() {
// for (var i =0; i < 3; i++) {
// userArray[i] = prompt('Введите пользователя №'+(i+1), '');
// }
//console.log(userArray);
//}
//
//getUser();
//
//function checkUser () {
// var newUser=prompt('Введите имя пользователя', '');
//
// if ( newUser.length < 1) {
// alert('Achtung partisanen!!!');
// return;
// }
// for ( i = 0; i < userArray.length; ++i) {
// if ( userArray[i] != newUser ) {
// alert(newUser+ 'Нет такого имени пользователя!');
//// break;
// } else if(userArray[i] === newUser) {
// alert(newUser+ ', Вы удачно вошли');
// break;
// }
// }
//}
//checkUser();
var userArray = [];
function getUser() {
for (var i =0; i < 5; i++) {
userArray[i] = prompt('Введите пользователя №'+(i+1), '');
}
console.log(userArray);
}
function checkUser () {
var newUser=prompt('Введите имя пользователя', '');
if ( newUser.length < 1) {
return 'Achtung partisanen!!!';
}
for ( i = 0; i < userArray.length; ++i) {
if(userArray[i] === newUser) {
return newUser+ ', Вы удачно вошли';
}
}
return newUser+ ', Нет такого имени пользователя!';
}
getUser();
var message = checkUser();
alert(message);
|
import axios from 'axios'
import React, { useState } from 'react'
import '../index.css'
import '../App.css';
import CTX from '../util/store'
const NewCard = (props) => {
const [cardData, updateCard] = useState(CTX)
const [ newCard, updateNewCard ] = useState({success: ''})
//set the base url for the database API calls
axios.defaults.baseURL = 'https://europe-west1-boomerang-test-c69c0.cloudfunctions.net/api'
//executes on form submission
const submitBtn = (e) => {
e.preventDefault()
//regex checker for any special characters in the url name
var format = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
//get current details from within the form
let currentState = {
name: document.getElementById('name').value,
imageURL: false,
jobtitle: document.getElementById('jobtitle').value,
phonenumber: document.getElementById('phonenumber').value,
site: document.getElementById('site').value,
businessname: document.getElementById('businessname').value,
email: document.getElementById('email').value,
urlname: document.getElementById('urlname').value,
backgroundCol: '#121212'
}
//this is for validating that the form is complete
let errorArr = []
//complete a for loop making sure that everything that needs to be completed, is completed
for(var key in currentState) {
if(currentState[key] === "") {
errorArr.push(key)
}
}
//if the error array has anything in it then then highlight the relevant form fields and display the error text
if (errorArr.length > 0) {
for (let i = 0; i < errorArr.length; i++) {
document.getElementById(errorArr[i]).style.borderColor = 'red'
document.getElementById(errorArr[i]).style.boxShadow = 'red 1px 1px 10px'
}
document.getElementById('error').innerHTML = 'Please complete all fields'
}
//check to see if there are any special characters in the URlname
else if (format.test(currentState.urlname)){
//display an error message if there is any
document.getElementById('urlname').style.borderColor = 'red'
document.getElementById('urlname').style.boxShadow = 'red 1px 1px 10px'
document.getElementById('error').innerHTML = 'Do not use any special characters in the url name'
}
//if there isn't any error messages then post and create the account
else{
axios.post('/card', currentState)
.then((res) =>{
//check to see if the response states there is a duplicate
if (res.data.duplicate) {
//update the state copy variable to show there is an error
currentState.error = 'A card with that URL already exists, please choose a different URL'
//if there is a success field in the state then delete it
if (currentState.success) {
delete currentState.success
updateCard(currentState)
}
else {
//update the state to show there is an error and then display the duplicate error message
updateCard(currentState)
document.getElementById('error').innerHTML = 'A card with that URL already exists, please choose a different URL'
}
}
else {
//if everything goes correctly then update the state and then move the the admin page of that card
currentState.success = 'Card Created Successfully'
updateCard(currentState)
props.history.push(`/${currentState.urlname}/admin`)
}
})
//catch the errors and update the state to show there is an error, console.log it too
.catch((err) => {
currentState.error = err
console.log(err)
updateCard(currentState)
})
}
}
//updates the state everytime that there is a text change
const handleChange = (e) => {
//creates a variable to check all the fields
const formData = {
name: document.getElementById('name').value,
imageURL: '',
jobtitle: document.getElementById('jobtitle').value,
phonenumber: document.getElementById('phonenumber').value,
site: document.getElementById('site').value,
businessname: document.getElementById('businessname').value,
email: document.getElementById('email').value,
urlname: document.getElementById('urlname').value,
imageURL: false,
backgroundColour: '#121212'
}
//update the state with the variable
updateNewCard(formData)
}
return (
<div className="container">
<div className="row mb-5">
<span>Create your <strong>business card</strong></span>
</div>
<form className="">
<div className="row mb-4">
<div className="col">
<label for="name">Name</label>
<input className="form-control" type="text" name="" id="name" placeholder="Type your name here" onChange={handleChange}/>
</div>
<div className="col">
<label for="jobtitle">Job Title</label>
<input className="form-control" type="text" name="" id="jobtitle" placeholder="Type your job title here" onChange={handleChange}/>
</div>
</div>
<div className="row mb-4">
<div className="col">
<label htmlFor="businessname">Business Name</label>
<input className="form-control" type="text" name="" id="businessname" placeholder="Type your business name here" onChange={handleChange}/>
</div>
</div>
<div className="row mb-4">
<div className="col">
<label htmlFor="phonenumber">Phone Number</label>
<input className="form-control" type="text" name="" id="phonenumber" placeholder="Type your phone number here" onChange={handleChange}/>
</div>
<div className="col">
<label htmlFor="email">Email Address</label>
<input className="form-control" type="text" name="" id="email" placeholder="Type your email address here" onChange={handleChange}/>
</div>
</div>
<div className="row mb-4">
<div className="col">
<label htmlFor="site">Your Website</label>
<input className="form-control" type="text" name="" id="site" placeholder="type your webside address here" onChange={handleChange}/>
</div>
</div>
<div className="row mb-4">
<div className="col">
<label htmlFor="urlname">Business Card Name</label>
<input className="form-control" type="text" name="" id="urlname" aria-describedby="urlhelp" placeholder="Give your business card a unique URL handle here" onChange={handleChange}/>
<small id="urlhelp" className="form-text text-muted">e.g. www.thisWebsite.com/<strong>thisName</strong></small>
</div>
</div>
<div className="success" id="success">
</div>
<div className="error" id="error">
</div>
<div className="row">
<div className="cent">
<button className="btn btn-secondary btn-lg pl-5 pr-5 pt-3 pb-3 " onClick={submitBtn}>CREATE BUSINESS CARD</button>
</div>
</div>
</form>
</div>
)
}
export default NewCard |
import React from "react"
import Translate from "../../components/Translate/Index"
import ShortNumber from "short-number"
const Index = (props) => {
let member = props.member
let state = props.state
return (
<ul className={`nav nav-tabs${props.newDesign ? " sidebar-scroll-new" : ""}`} id="myTab" role="tablist">
{
state.showHomeButtom == 1 ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "home" ? " active" : ""}`} onClick={
() => props.pushTab("home")
} data-bs-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">{Translate(props, "All Posts")}</a>
</li>
:
null
}
{
state.planCreate ?
<React.Fragment>
<li className="nav-item">
<a className={`nav-link${state.tabType == "plans" ? " active" : ""}`} onClick={
() => props.pushTab("plans")
} data-bs-toggle="tab" href="#planCreate" role="tab" aria-controls="planCreate" aria-selected="true">{Translate(props, "Plans")}</a>
</li>
{
member.subscribers ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "subscribers" ? " active" : ""}`} onClick={
() => props.pushTab("subscribers")
} data-bs-toggle="tab" href="#subscribers" role="tab" aria-controls="subscribers" aria-selected="true">{Translate(props, "Subscribers")}</a>
</li>
: null
}
</React.Fragment>
: null
}
{
state.liveVideos && state.liveVideos.results && state.liveVideos.results.length > 0 ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "live" ? " active" : ""}`} onClick={
() => props.pushTab("live")
} data-bs-toggle="tab" href="#live" role="tab" aria-controls="discription" aria-selected="false">{Translate(props, "Live")}</a>
</li>
: null
}
{
props.pageInfoData.videos ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "videos" ? " active" : ""}`} onClick={
() => props.pushTab("videos")
} data-bs-toggle="tab" href="#videos" role="tab" aria-controls="discription" aria-selected="false">{Translate(props, "Videos")}</a>
</li>
: null
}
{
state.movies ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "movies" ? " active" : ""}`} onClick={
() => props.pushTab("movies")
} data-bs-toggle="tab" href="#movies" role="tab" aria-controls="movies" aria-selected="true">{Translate(props, "Movies")}</a>
</li>
: null
}
{
state.series ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "series" ? " active" : ""}`} onClick={
() => props.pushTab("series")
} data-bs-toggle="tab" href="#series" role="tab" aria-controls="series" aria-selected="true">{Translate(props, "Series")}</a>
</li>
: null
}
{
state.channels ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "channels" ? " active" : ""}`} onClick={
() => props.pushTab("channels")
} data-bs-toggle="tab" href="#channels" role="tab" aria-controls="channels" aria-selected="true">{Translate(props, "Channels")}</a>
</li>
: null
}
{
state.audios ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "audio" ? " active" : ""}`} onClick={
() => props.pushTab("audio")
} data-bs-toggle="tab" href="#audios" role="tab" aria-controls="audios" aria-selected="true">{Translate(props, "Audio")}</a>
</li>
: null
}
{
state.blogs ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "blogs" ? " active" : ""}`} onClick={
() => props.pushTab("blogs")
} data-bs-toggle="tab" href="#blogs" role="tab" aria-controls="blogs" aria-selected="true">{Translate(props, "Blogs")}</a>
</li>
: null
}
{
state.paidVideos && state.paidVideos.results && state.paidVideos.results.length > 0 ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "paid" ? " active" : ""}`} onClick={
() => props.pushTab("paid")
} data-bs-toggle="tab" href="#paid" role="tab" aria-controls="discription" aria-selected="false">{Translate(props, "Paid Videos")}</a>
</li>
: null
}
{
state.playlists ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "playlists" ? " active" : ""}`} onClick={
() => props.pushTab("playlists")
} data-bs-toggle="tab" href="#playlists" role="tab" aria-controls="playlists" aria-selected="true">{Translate(props, "Playlists")}</a>
</li>
: null
}
{
props.pageInfoData.appSettings[`${"member_comment"}`] == 1 ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "comments" ? " active" : ""}`} onClick={
() => props.pushTab("comments")
} data-bs-toggle="tab" href="#comments" role="tab" aria-controls="comments" aria-selected="true">{`${Translate(props,"Comments")}`}</a>
</li>
: null
}
{
state.showHomeButtom != 1 ?
<li className="nav-item">
<a className={`nav-link${state.tabType == "about" ? " active" : ""}`} onClick={
() => props.pushTab("about")
} data-bs-toggle="tab" href="#about" role="tab" aria-controls="about" aria-selected="true">{Translate(props, "About")}</a>
</li>
: null
}
</ul>
)
}
export default Index; |
import React from 'react';
import { withStyles } from '@material-ui/styles';
import MaterialTable from 'material-table';
import BackendService from '../services/backendServices';
class Prices extends React.Component {
constructor(props) {
super(props);
this.state = {
columns: [
{ title: 'Service', field: 'service' },
{ title: 'Price(£)', field: 'price' },
],
data: [],
}
this.populate = this.populate.bind(this);
this.addPrice = this.addPrice.bind(this);
this.updatePrice = this.updatePrice.bind(this);
this.deletePrice = this.deletePrice.bind(this);
}
populate = async () => {
try {
const practiceId = localStorage.getItem('userId');
if (practiceId) {
let response = await BackendService.getPrices(practiceId);
this.setState({ data: response.data.data })
} else {
window.location.pathname = '/signin';
}
} catch (error) {
alert('Something went wrong');
}
}
componentWillMount() {
this.populate();
}
addPrice = async (newData) => {
try {
const practiceId = localStorage.getItem('userId');
let response = await BackendService.registerPrice({
practiceId,
service: newData.service,
price: newData.price
});
if (response.data.status) {
this.populate();
this.setState(prevState => {
const data = [...prevState.data];
data.push(newData);
return { ...prevState, data };
});
} else {
alert("Something went wrong");
}
} catch (error) {
alert("Something went wrong");
}
}
updatePrice = async(newData, oldData) => {
try {
if (oldData) {
const practiceId = localStorage.getItem('userId');
let response = await BackendService.updatePrice({
practiceId,
priceId: newData.priceId,
service: newData.service,
price: newData.price
});
if (response.data.status) {
this.setState(prevState => {
const data = [...prevState.data];
data[data.indexOf(oldData)] = newData;
return { ...prevState, data };
});
} else {
alert("Something went wrong");
}
}
} catch (error) {
console.log("Error", error);
alert("Something went wrong");
}
}
deletePrice = async(oldData) => {
try {
if (oldData) {
const practiceId = localStorage.getItem('userId');
let response = await BackendService.deletePrice({
practiceId,
priceId: oldData.priceId
});
if (response.data.status) {
this.setState(prevState => {
const data = [...prevState.data];
data.splice(data.indexOf(oldData), 1);
return { ...prevState, data };
});
} else {
alert("Something went wrong");
}
}
} catch (error) {
console.log("Error", error);
alert("Something went wrong");
}
}
render() {
return (
<MaterialTable
title="Price List"
options={{ pageSize: 7 }}
columns={this.state.columns}
data={this.state.data}
editable={{
onRowAdd: newData => this.addPrice(newData),
onRowUpdate: (newData, oldData) => this.updatePrice(newData, oldData),
onRowDelete: oldData => this.deletePrice(oldData),
}}
/>
);
}
}
export default withStyles({}, { withTheme: true })(Prices) |
'use strict';
const express = require('express');
const app=express();
const PORT = process.env.PORT||3000;
app.use(express.static('./starter-code'));
app.get('/home',function(req,res){
res.sendFile(`${__dirname}/starter-code/index.html`);
});
app.listen(PORT,function(){
console.log('listening on port', PORT);
}); |
const fs = require('fs');
const _ = require('lodash');
const jwt = require('jsonwebtoken');
const config = require('../config');
const errors = require('../common/errors');
const publicKey = fs.readFileSync(config.jwt.publicKey, 'utf8');
const authenticateBearerToken = (req, res, next) => {
let token = req.get('authorization');
if (token && token.startsWith('Bearer ')) {
const jwtVerifyOptions = {
issuer: config.jwt.issuer,
algorithm: [config.jwt.algorithm],
};
token = token.slice(7, token.length);
jwt.verify(token, publicKey, jwtVerifyOptions, (error, decoded) => {
if (error) {
if (error.name === 'TokenExpiredError') {
next(errors.ER_AUTHENTICATION_TOKEN_EXPIRED);
} else if (error.name === 'JsonWebTokenError') {
next(errors.ER_AUTHENTICATION_TOKEN_INVALID);
} else {
next(error);
}
} else {
const authentication = {
bearer: {
token,
expiresAt: new Date(decoded.exp * 1000),
},
user: {
id: decoded.sub,
},
};
_.assignIn(req, { authentication });
next();
}
});
} else {
next(errors.ER_AUTHENTICATION_TOKEN_NOT_FOUND);
}
};
module.exports = {
authenticateBearerToken,
};
|
const gutil = require('gulp-util');
const _injectFakeBuffer = (plugin, input) => {
const fakeBuffer = new Buffer(input.contents);
const fakeFile = new gutil.File(Object.assign({}, input, {
contents: fakeBuffer
}));
plugin.write(fakeFile);
plugin.end();
}
const testBufferOutputMatches = (plugin, input, output, done) => {
plugin.on('data', function(newFile) {
if(output && typeof output.contents === 'string') {
expect(newFile.contents.toString('utf-8').trim()).toEqual(output.contents.trim());
}
if(output && typeof output.path === 'string') {
expect(newFile.path).toEqual(output.path);
}
});
plugin.on('end', function() {
done();
});
_injectFakeBuffer(plugin, input);
}
const testBufferModeThrowsError = (plugin, input, expectedError, done) => {
const timeout = 4;
const timeoutId = setTimeout(() => {
fail(`Expected an error matching \n ${expectedError}\n but none was emitted within ${timeout} seconds`);
done();
}, timeout * 1000);
plugin.on('error', function(error) {
if(typeof expectedError === 'string') {
expect(error.message).toEqual(expectedError)
} else {
expect(error.message).toMatch(expectedError)
}
clearTimeout(timeoutId);
done();
});
_injectFakeBuffer(plugin, input);
}
const testBufferModeIgnoresNullFiles = plugin => {
pending('not yet supported in test-your-gulp-plugin');
}
module.exports = {
testBufferModeThrowsError,
testBufferOutputMatches,
testBufferModeIgnoresNullFiles
}
|
const dummyData = require('./dummy-data')
const express = require('express')
const app = express()
const sqlite3 = require('sqlite3')
const multer = require('multer')
const cookieParser = require('cookie-parser')
const expressSession = require('express-session')
const expressHandlebars = require('express-handlebars')
var path = require('path');
const bodyParser = require('body-parser')
const SQLiteStore = require("connect-sqlite3")(expressSession);
const db = require('./db')
const blogRouter = require('./routers/blogpost-router')
const guestbookRouter = require('./routers/blogpost-router')
const projectRouter = require('./routers/blogpost-router')
const MIN_TITLE_LENGTH = 1
const MIN_CONTENT_LENGTH = 2
const MIN_DESCRIPTION_LENGTH = 1
const MIN_NAME_LENGTH = 1
app.use('/guestbook', guestbookRouter)
app.use('/blogpost', blogRouter)
app.use('/project', projectRouter)
app.use(bodyParser.urlencoded({
extended: false
}))
app.listen(8080, function () {
console.log("Server started on port 8080...");
});
app.use(expressSession({
secret: "dffdfdfgrtggvcdfd",
saveUninitialized: false,
resave: false,
store: new SQLiteStore()
}))
app.engine('hbs', expressHandlebars({
defaultLayout: 'main.hbs',
}))
const adminUsername = "annie"
const adminPassword = "00aa11"
app.get('/', function (request, response) {
const isLoggedIn = request.session.isLoggedIn
const model = {
title: "Home page",
isLoggedIn
}
response.render("home.hbs", model)
})
app.get('/home', function (request, response) {
const isLoggedIn = request.session.isLoggedIn
db.getAllBlogposts(function (error, blogposts) {
if (error) {
console.log(error)
response.render("errorMessage.hbs", {errorMessage: "Could not select data from database, Try again later"})
} else {
const model = {
blogposts,
isLoggedIn,
title: "Home page"
}
response.render("home.hbs", model)
}
})
})
app.post('/home', function (request, response) {
const isLoggedIn = request.session.isLoggedIn
const model = {
isLoggedIn,
blogposts: blogposts,
title: "Home page"
}
response.render("home.hbs", model)
})
app.get('/about', function (request, response) {
const isLoggedIn = request.session.isLoggedIn
const model = {
title: "About page",
isLoggedIn
}
response.render('about.hbs', model)
})
app.get('/contact', function (request, response) {
const isLoggedIn = request.session.isLoggedIn
const model = {
title: "Contact page",
isLoggedIn
}
response.render('contact.hbs', model)
})
app.get('/guestbook', function (request, response) {
const isLoggedIn = request.session.isLoggedIn
db.getAllGuestbookPosts(function (error, gbookposts) {
if (error) {
response.render("errorMessage.hbs", {errorMessage: "Could not select data from database, Try again later"})
console.log(error)
} else {
const model = {
gbookposts,
isLoggedIn,
title: "Guestbook page"
}
response.render("guestbook.hbs", model)
}
})
})
app.post('/guestbook', function (request, response) {
const isLoggedIn = request.session.isLoggedIn
const title = request.body.title
const content = request.body.content
const errors = getValidationErrorsForPost(title, content);
if (errors.length == 0) {
db.createGuestbookPost(title, content, function(error){
if (error) {
response.render("errorMessage.hbs", {errorMessage: "Could not insert data into database, Try again later"})
console.log(error)
} else {
response.redirect('/guestbook')
}
})
} else {
db.getAllGuestbookPosts(function (error, gbookposts) {
if (error) {
response.render("errorMessage.hbs", {errorMessage: "Could not select data from database, Try again later"})
console.log(error)
} else {
const model = {
errors,
gbookposts,
isLoggedIn,
title: "Guestbook page"
}
response.render("guestbook.hbs", model)
}
})
}
})
app.get('/guestbookpost/:id', function (request, response) {
const id = request.params.id
const isLoggedIn = request.session.isLoggedIn
db.getGuestbookPostById(id, function (error, gbookpost) {
if (error) {
response.render("errorMessage.hbs", {errorMessage: "Could not select data from database, Try again later"})
console.log(error)
} else {
const model = {
gbookpost,
title: "Details guestbook page",
isLoggedIn,
}
response.render('guestbookpost.hbs', model)
}
})
})
app.get('/blogpost/:id', function (request, response) {
const id = request.params.id
const isLoggedIn = request.session.isLoggedIn
db.getAllBlogpostById(id, function(error, blogpost){
if (error) {
response.render("errorMessage.hbs", {errorMessage: "Could not select data from database, Try again later"})
console.log(error)
} else {
const model = {
blogpost,
title: "Details page",
isLoggedIn,
}
response.render('blogpost.hbs', model)
}
})
})
app.use(function (request, response, next) {
const isLoggedIn = request.session.isLoggedIn
response.locals.isLoggedIn = isLoggedIn
next()
})
app.get('/error', function(request, response){
request.session.isLoggedIn = true
response.render('errorMessage.hbs')
})
app.get('/login', function (request, response) {
const model = {
layout: false
}
response.render('login.hbs', model)
})
app.post("/login", function (request, response) {
const enteredUsername = request.body.username
const enteredPassword = request.body.password
request.session.isLoggedIn = true
const errors = getValidationErrorsForLogin(enteredPassword, enteredUsername)
if (errors.length == 0) {
response.redirect("/home")
} else {
const model = {
errors,
layout: false
}
response.render('login.hbs', model)
}
})
app.get('/admin', function (request, response) {
if(request.session.isLoggedIn){
const model = {
validationError: [],
title: "Admin page",
}
response.render('admin.hbs', model)
}else{
response.redirect("/login")
}
})
function getValidationErrorsForPost(title, content) {
const validationError = []
if (title.length <= MIN_TITLE_LENGTH) {
validationError.push("Title should contain at least " + MIN_TITLE_LENGTH + " character")
}
if (content.length <= MIN_CONTENT_LENGTH) {
validationError.push("Content should contain at least " + MIN_CONTENT_LENGTH + " characters")
}
return validationError
}
function getValidationErrorsForProject(name, description) {
const validationError = []
if (name.length <= MIN_NAME_LENGTH) {
validationError.push("Name should contain at least " + MIN_NAME_LENGTH + " character")
}
if (description.length <= MIN_DESCRIPTION_LENGTH) {
validationError.push("Description should contain at least " + MIN_DESCRIPTION_LENGTH + " characters")
}
return validationError
}
function getValidationErrorsForLogin(enteredPassword, enteredUsername){
const errors = []
if(enteredUsername != adminUsername) {
console.log("Wrong username");
errors.push("Wrong username")
}
if(enteredPassword != adminPassword){
console.log("Wrong password");
errors.push("Wrong password")
}
return errors
}
app.post('/admin', function (request, response) {
const title = request.body.title
const content = request.body.content
const errors = getValidationErrorsForPost(title, content)
if (!request.session.isLoggedIn) {
errors.push("You have to login to make a blogpost.")
}
if (errors.length == 0) {
db.createBlogPost(title, content, function (error) {
if (error) {
console.log(error)
response.render('errorMessage.hbs', {errorMessage: "Could not insert data into database, try again later"})
} else {
response.redirect('/home')
}
})
} else {
const model = {
errors,
title: "Admin page"
}
response.render('admin.hbs', model)
}
})
app.get('/update-posts/:id', function (request, response) {
/*if(request.session.isLoggedIn){
const model = {
validationError: [],
title: "Update blogpost page",
}
response.render('update-posts.hbs', model)
}else{
response.redirect("/login")
}*/
const id = request.params.id
const isLoggedIn = request.session.isLoggedIn
db.getAllBlogpostById(id, function(error, blogpost){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not select from database, try again later"})
console.log(error)
} else {
const model = {
blogpost,
title: "Update page",
isLoggedIn,
}
response.render('update-posts.hbs', model)
}
})
})
app.post('/update-posts/:id', function (request, response) {
const id = request.params.id
const newTitle = request.body.title
const newContent = request.body.content
const validationError = getValidationErrorsForPost(newTitle, newContent)
if (!request.session.isLoggedIn) {
validationError.push("You have to login to update a blogpost.")
}
if(validationError.length == 0){
db.updateBlogpost(newTitle, newContent, id, function(error){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not update data into database, try again later"})
console.log(error)
} else {
response.redirect("/home")
}
})
}else{
const model = {
blogpost: {
id,
title: newTitle,
content: newContent
},
validationError,
error
}
response.render('update-posts.hbs', model)
}
})
app.get('/update-gpost/:id', function (request, response) {
/*if(request.session.isLoggedIn){
const model = {
validationError: [],
title: "Update guestbook page",
}
response.render('update-gpost.hbs', model)
}else{
response.redirect("/login")
}
*/
const id = request.params.id
const isLoggedIn = request.session.isLoggedIn
db.getGuestbookPostById(id, function (error, gbookpost) {
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not select data from database, try again later"})
console.log(error)
} else {
const model = {
gbookpost,
title: "Update page",
isLoggedIn,
}
response.render('update-gpost.hbs', model)
}
})
})
app.post('/update-gpost/:id', function (request, response) {
const id = request.params.id
const newTitle = request.body.title
const newContent = request.body.content
const validationError = getValidationErrorsForPost(newTitle, newContent)
if (!request.session.isLoggedIn) {
validationError.push("You have to login to update a gueestbook post.")
}
if(validationError.length == 0){
db.updateGuestbookPosts(newTitle, newContent, id, function(error){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not update data into database, try again later"})
console.log(error)
} else {
response.redirect("/guestbook")
}
})
}else{
const model = {
gbookpost: {
id,
title: newTitle,
content: newContent
},
validationError,
title: "Update guestbook post"
}
response.render('update-gpost.hbs', model)
}
})
app.post('/delete-posts/:id', function (request, response) {
const id = request.params.id
db.deleteBlogPostById(id, function(error){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not delete data from database, try again later"})
console.log(error)
} else {
response.redirect('/home')
}
})
})
app.post('/delete-gpost/:id', function (request, response) {
const id = request.params.id
db.deleteGuestbookPostsById(id, function(error){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not delete data from database, try again later"})
console.log(error)
} else {
response.redirect('/guestbook')
}
})
})
app.post('/delete-project/:id', function (request, response) {
const id = request.params.id
db.deleteProjectsById(id, function(error){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not delete data from database, try again later"})
console.log(error)
} else {
response.redirect('/portfolio')
}
})
})
app.get('/portfolio', function (request, response) {
const isLoggedIn = request.session.isLoggedIn
db.getAllProjects(function (error, projects){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not select data from database, try again later"})
console.log(error)
} else {
const model = {
projects,
isLoggedIn,
title: "Portfolio page"
}
response.render("portfolio.hbs", model)
}
})
})
app.post('/portfolio', function (request, response) {
const isLoggedIn = request.session.isLoggedIn
const name = request.body.name
const description = request.body.description
const validationError = getValidationErrorsForProject(name, description);
if(validationError.length == 0){
db.createProject(name, description, function(error){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not insert data into database, try again later"})
console.log(error)
} else {
response.redirect('/portfolio')
}
})
}else{
db.getAllProjects(function(error, projects){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not select data from database, try again later"})
console.log(error)
} else {
const model = {
validationError,
projects,
isLoggedIn,
title: "Portfolio page"
}
response.render("portfolio.hbs", model)
}
})
}
})
app.get('/update-project/:id', function (request, response) {
/*if(request.session.isLoggedIn){
const model = {
validationError: [],
title: "Update guestbook page",
}
response.render('update-gpost.hbs', model)
}else{
response.redirect("/login")
}
*/
const id = request.params.id
const isLoggedIn = request.session.isLoggedIn
db.getProjectById(id, function(error, project){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not select data from database, try again later"})
console.log(error)
} else {
const model = {
project,
title: "Update project page",
isLoggedIn,
}
response.render('update-project.hbs', model)
}
})
})
app.post('/update-project/:id', function (request, response) {
const id = request.params.id
const newName = request.body.name
const newDescription = request.body.description
/*const validationError = getValidationErrorsForPost(newTitle, newContent)
if (!request.session.isLoggedIn) {
validationError.push("You have to login to update a project.")
}*/
const validationError = getValidationErrorsForProject(newName, newDescription)
if (!request.session.isLoggedIn) {
validationError.push("You have to login to update a project post.")
}
if(validationError.length == 0){
db.updateProjects(newName, newDescription, id, function(error){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not update data into database, try again later"})
console.log(error)
} else {
response.redirect("/portfolio")
}
})
}else{
const model = {
project: {
id,
name: newName,
description: newDescription
},
validationError,
title: "Update portfolio post"
}
response.render('update-gpost.hbs', model)
}
})
app.get('/project/:id', function (request, response) {
const id = request.params.id
const isLoggedIn = request.session.isLoggedIn
db.getProjectById(id, function(error, project){
if (error) {
response.render('errorMessage.hbs', {errorMessage: "Could not select data from database, try again later"})
console.log(error)
} else {
const model = {
project,
title: "Details page",
isLoggedIn,
}
response.render('project.hbs', model)
}
})
})
app.post("/logout", function (request, response) {
request.session.isLoggedIn = false
response.redirect("/home")
})
app.use('/dist', express.static(path.join(__dirname, 'dist')))
app.use('/img', express.static(path.join(__dirname, 'img')))
app.use('/views', express.static(path.join(__dirname, 'views')))
|
class Rendererer {
render(Playerheight) {
document.getElementById("Player").style.Bottom = Playerheight + "px";
}
}
class Game {
constructor() {
this.Player = new Box();
this.renderer = new Rendererer();
this.Gameloop();
}
update() {
this.Player.tick();
this.renderer.render(this.Player.height);
}
start() {
document.body.onkeyup = (e) => {
if(e.keyCode == 32){
this.Player.jump();
}
}
}
Gameloop() {
this.start();
setInterval(() => {
this.update();
}, 10);
}
}
class Box {
constructor() {
this.height = 0;
this.speed = 0;
}
tick() {
this.speed += .05;
this.height -= this.speed;
}
jump() {
this.speed += 3;
}
}
let lol = new Game(); |
import React, {useState} from 'react';
import { AsyncStorage, Button, StyleSheet, Text, TextInput, View } from 'react-native';
const SampleAsyncStorage = (props) =>{
const [state, setState] = useState({
name: '',
hobby: '',
textName: '',
textHobby: ''
})
AsyncStorage.getItem('name', (error, result) => {
if (result) {
let resultParsed = JSON.parse(result)
setState({name: resultParsed.name, hobby:resultParsed.hobby})
}
})
AsyncStorage.getItem('hobby', (error, result) => {
if (result) {
setState({hobby: result})
}
})
const onChange = (e) => {
setState({...state, [e.target.name] : e.target.value})
}
const saveData = (e) => {
let name = state.textName;
let hobby = state.textHobby;
let data = {name, hobby}
AsyncStorage.setItem('user', JSON.stringify(data));
alert('Data tersimpan');
}
const showData = (e) => {
alert('Data ditampilkan');
AsyncStorage.getItem('user', (error, result) => {
if (result) {
let resultParsed = JSON.parse(result)
console.log(resultParsed,'hh')
}
})
}
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Anyeong Haseyo!
</Text>
<Text style={styles.instructions}>
Nama: {state.name}{'\n'}
Hobi: {state.hobby}
</Text>
<TextInput style={styles.textInput}
name ="textName"
value = {state.textName}
onChangeText={(textName) => setState({...state, textName})}
placeholder='Nama'
/>
<TextInput style={styles.textInput}
onChangeText={(textHobby) => setState({...state, textHobby})}
placeholder='Hobi'
/>
<Button
title='Simpan'
onPress={(e) => {saveData(e)}}
/>
<Button
title='Masuk autorisasi'
onPress={() => props.navigation.navigate("Auth")}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
backgroundColor: '#F5FCFF',
padding: 16,
paddingTop: 32
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
textInput: {
height: 35,
backgroundColor: 'white',
marginTop: 8,
marginBottom: 8,
borderWidth: 1,
borderColor: 'grey',
padding: 8
}
});
export default SampleAsyncStorage;
|
var express = require('express');
var router = express.Router();
var {
find
} = require('../libs/db')
// 导出token的方法
const {formatData,token} = require('../utils')
router.get('/login', async function (req, res, next){
// 判断用户账户用户密码存在不存在
let {phoneNum,password} = req.query;
// console.log(req.query)
let result = await find('users', {
phoneNum,password
}
)
// console.log(result)
if(result.length>0){
let Athorization = token.create(phoneNum);
res.send(formatData({data:Athorization}))
}else{
res.send(formatData({code:250}))
}
// 判断手机号存在不存在
});
module.exports=router |
import { APIError } from '../errors';
describe('APIError', () => {
it('creates APIError with default properties', () => {
const error = new APIError(404, {});
assert.isUndefined(error.details);
assert.isNull(error.errorCode);
assert.isNull(error.errorMessage);
assert.equal(error.message, 'API call failed');
assert.equal(error.status, 404);
});
it('creates `APIError` with optional properties', () => {
const details = { myDetails: 'p' };
const error = new APIError(404, {
message: 'message',
error_code: '4xx',
details,
ignored: 'dummy',
});
assert.equal(error.details, details);
assert.equal(error.errorCode, '4xx');
assert.equal(error.errorMessage, 'message');
assert.equal(error.message, 'message');
assert.equal(error.status, 404);
});
});
|
/*
* @Description:
* @Author: yamanashi12
* @Date: 2019-05-10 10:18:19
* @LastEditTime: 2020-10-26 17:54:13
* @LastEditors: Please set LastEditors
*/
export default {
schema: {
type: { // 组件类型
type: 'string',
default: 'Img'
},
bgColor: { // 背景色
type: 'string',
default: 'rgba(0, 0, 0, 0)'
},
marginTop: { // 上外边距
type: 'number',
default: 10
},
marginBottom: { // 下外边距
type: 'number',
default: 10
},
paddingTop: { // 上内边距
type: 'number',
default: 0
},
paddingBottom: { // 下内边距
type: 'number',
default: 0
},
value: 'array',
align: { // 布局
type: 'string',
default: 'left'
},
width: { // 图片宽度
type: 'string',
default: 'auto'
},
height: { // 图片高度
type: 'string',
default: 'auto'
}
},
rules: {
value: [{
type: 'array', required: true, message: '请选择一张图片', trigger: 'blur'
}]
}
}
|
$(document).ready(function() {
$.ajax({
method:"post",
url:"php/ordenesSaberOrden.php",
data: {'algo':'algo'},
success: function(resp){
$("#Eventos").html(resp);
establecerBotonesDevolver();
establecerBotonesCancelar();
establecerBotonesConfirmar();
},
error: function(err,or){
$.confirm({
title: 'Error!',
content: 'Lo sentimos, lo trataremos de arreglar lo mas pronto posible',
type: 'red',
closeIcon: true,
columnClass: 'medium',
typeAnimated: true,
buttons:{
Nice:{
text: 'Ok!',
btnClass: 'btn-black',
action: function(){
}
}}
});
}
});
function cancelar()
{
var evento = $(this).attr("data-cancelar");
$.ajax({
method:"post",
url:"php/ordenesEliminarAktuar.php",
data: {'obra':evento},
success: function(resp){
//alert(resp);
parametros = {'operaciones': JSON.parse(resp)}
$.ajax({
method:"post",
url:"php/ordenesEliminarQuetzal.php",
data: parametros,
success: function(resp2){
$.confirm({
title: 'Orden cancelada!',
content: 'La orden ha sido cancelada con éxito!',
type: 'dark',
closeIcon: true,
columnClass: 'medium',
typeAnimated: true,
buttons:{
Nice:{
text: 'Ok!',
btnClass: 'btn-white',
action: function(){
}
}}
});
},
error: function(err,or){
$.confirm({
title: 'Error!',
content: 'Lo sentimos, lo trataremos de arreglar lo mas pronto posible',
type: 'red',
closeIcon: true,
columnClass: 'medium',
typeAnimated: true,
buttons:{
Nice:{
text: 'Ok!',
btnClass: 'btn-black',
action: function(){
}
}}
});
}
});
},
error: function(err,or){
$.confirm({
title: 'Error!',
content: 'Lo sentimos, lo trataremos de arreglar lo mas pronto posible',
type: 'red',
closeIcon: true,
columnClass: 'medium',
typeAnimated: true,
buttons:{
Nice:{
text: 'Ok!',
btnClass: 'btn-black',
action: function(){
}
}}
});
}
});
location.href="ordenesDt.php"
}
function devolver()
{
var evento = $(this).attr("data-devolver");
$.ajax({
method:"post",
url:"php/ordenesDevolverSaberOperaciones.php",
data: {'obra':evento},
success: function(operaciones){
//alert(operaciones);
$.ajax({
method:"post",
url:"php/ordenesDevolverQuetzal.php",
data: {'operaciones':JSON.parse(operaciones)},
success: function(resp1){
//alert(resp1);
$.ajax({
method:"post",
url:"php/ordenesDevolverAktuar.php",
data: {'operacionesN':JSON.parse(resp1),'operacionesA':JSON.parse(operaciones)},
success: function(resp2){
$.confirm({
title: 'Listo!',
content: 'La devolución de los muebles se ha iniciado',
type: 'blue',
closeIcon: true,
columnClass: 'medium',
typeAnimated: true,
buttons:{
Nice:{
text: 'Ok!',
btnClass: 'btn-green',
action: function(){
}
}}
});
},
error: function(err,or){
$.confirm({
title: 'Error!',
content: 'Lo sentimos, lo trataremos de arreglar lo mas pronto posible',
type: 'red',
closeIcon: true,
columnClass: 'medium',
typeAnimated: true,
buttons:{
Nice:{
text: 'Ok!',
btnClass: 'btn-black',
action: function(){
}
}}
});
}
});
},
error: function(err,or){
$.confirm({
title: 'Error!',
content: 'Lo sentimos, lo trataremos de arreglar lo mas pronto posible',
type: 'red',
closeIcon: true,
columnClass: 'medium',
typeAnimated: true,
buttons:{
Nice:{
text: 'Ok!',
btnClass: 'btn-black',
action: function(){
}
}}
});
}
});
},
error: function(err,or){
$.confirm({
title: 'Error!',
content: 'Lo sentimos, lo trataremos de arreglar lo mas pronto posible',
type: 'red',
closeIcon: true,
columnClass: 'medium',
typeAnimated: true,
buttons:{
Nice:{
text: 'Ok!',
btnClass: 'btn-black',
action: function(){
}
}}
});
}
});
}
function confirmar()
{
var evento = $(this).attr("data-confirmar");
$.ajax({
method:"post",
url:"php/ordenesConfirmarLlegada.php",
data: {'obra':evento},
success: function(resp){
$.confirm({
title: 'Listo!',
content: 'Se ha confirmado la obtención del pedido',
type: 'green',
closeIcon: true,
columnClass: 'medium',
typeAnimated: true,
buttons:{
Nice:{
text: 'Ok!',
btnClass: 'btn-blue',
action: function(){
}
}}
});
},
error: function(err,or){
$.confirm({
title: 'Error!',
content: 'Lo sentimos, lo trataremos de arreglar lo mas pronto posible',
type: 'red',
closeIcon: true,
columnClass: 'medium',
typeAnimated: true,
buttons:{
Nice:{
text: 'Ok!',
btnClass: 'btn-black',
action: function(){
}
}}
});
}
});
}
function establecerBotonesDevolver()
{
botones = getAllElementsWithAttribute("data-devolver");
for(var i=0; i<botones.length;i++)
{
botones[i].addEventListener("click", devolver);
}
}
function establecerBotonesCancelar()
{
botones = getAllElementsWithAttribute("data-cancelar");
for(var i=0; i<botones.length;i++)
{
botones[i].addEventListener("click", cancelar);
}
}
function establecerBotonesConfirmar()
{
botones = getAllElementsWithAttribute("data-confirmar");
for(var i=0; i<botones.length;i++)
{
botones[i].addEventListener("click", confirmar);
}
}
function getAllElementsWithAttribute(attribute)
{
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++)
{
if (allElements[i].getAttribute(attribute) !== null)
{
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
});
|
import React, { Component } from 'react';
import Person from './Person/Person'
import PropTypes from 'prop-types';
import Header from '../Header/Header'
class TitleCe extends Component{
static contextTypes = {
themeColor : PropTypes.string
}
render(){
const Lang = window.Intl;
return (
<h1>{Lang.get("lala")}</h1>
)
}
}
class Main extends Component{
constructor(props){
super(props)
}
render(){
return (
<div>
{/* <Header lang = {this.props.lang} onclick={this.props.click} pageNum={this.props.pageNum}/> */}
<TitleCe />
</div>
)
}
}
//有状态组件
class Persons extends Component{
// constructor(props){
// super(props)
// }
//更新组件声明周期钩子函数
componentWillReceiveProps(nextProps){
console.log(nextProps)
}
render(){
return this.props.persons.map((person , index) => {
return <Person
myclick={() => this.props.clicked(index)}
name = {person.name}
count = {person.count}
key = {person.id}
changed = {(event) => this.props.changed(event , person.id)}
/>
})
}
}
//export default Persons;
export default Main;
|
import React, { Component } from "react";
import { connect } from "react-redux";
import { addRecipe } from "../actions";
import RecipeForm from "./RecipeForm";
class RecipeAdd extends Component {
onSubmit = formValues => {
const {recipes} = this.props
const recipe = Object.values(recipes)[Object.keys(recipes).length-1]
let id = !!recipe ? recipe.id + 1 : 0
this.props.addRecipe({id:id,...formValues});
};
render() {
return (
<div>
<h3>Add a Recipe</h3>
<RecipeForm onSubmit={this.onSubmit} />
</div>
);
}
}
const mapStateToProps = state => {
return { recipes: state.recipes }
}
export default connect(
mapStateToProps,
{ addRecipe }
)(RecipeAdd);
|
// let x = 1;
// x = -x;
// alert( x ); // -1, unary negation was applied
// let x = 1, y = 3;
// alert( y - x ); // 2, binary minus subtracts values
// alert( 5 % 2 ); // 1, a remainder of 5 divided by 2
// alert( 8 % 3 ); // 2, a remainder of 8 divided by 3
// alert( 2 ** 2 ); // 4 (2 multiplied by itself 2 times)
// alert( 2 ** 3 ); // 8 (2 * 2 * 2, 3 times)
// alert( 2 ** 4 ); // 16 (2 * 2 * 2 * 2, 4 times)
// alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root)
// alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
// alert( '1' + 2 ); // "12"
// alert( 2 + '1' ); // "21"
// alert(2 + 2 + '1' ); // "41" and not "221"
// /* Numeric conversion, unary +
// The plus + exists in two forms: the binary form that we used above and the unary form.
// The unary plus or, in other words, the plus operator + applied to a single value, doesn’t do anything to numbers. But if the operand is not a number, the unary plus converts it into a number. */
// // No effect on numbers
// let x = 1;
// alert( +x ); // 1
// let y = -2;
// alert( +y ); // -2
// // Converts non-numbers
// alert( +true ); // 1
// alert( +"" ); // 0
// let counter = 2;
// counter++; // works the same as counter = counter + 1, but is shorter
// alert( counter ); // 3
// let counter = 2;
// counter--; // works the same as counter = counter - 1, but is shorter
// alert( counter ); // 1
// let counter = 1;
// let a = counter++; // (*) changed ++counter to counter++
// alert(a); // 1
// let counter = 0;
// counter++;
// ++counter;
// alert( counter ); // 2, the lines above did the same
// let counter = 1;
// alert( 2 * ++counter ); // 4
// let counter = 1;
// alert( 2 * counter++ ); // 2, because counter++ returns the "old" value
// let counter = 1;
// alert( 2 * counter );
// counter++;
let a = 1 , b = 1;
let c = ++a;
alert(c);
let d = b++;
alert(d);
let a = 2;
alert(a);
let x = 1 +(a *= 2);
alert(x);
/* "" + 1 + 0
"" - 1 + 0
true + false
6 / "3"
"2" * "3"
4 + 5 + "px"
"$" + 4 + 5
"4" - 2
"4px" - 2
7 / 0
" -9 " + 5
" -9 " - 5
null + 1
undefined + 1
" \t \n" - 2 */
let a = prompt("First number?");
let b = prompt("Second number?");
alert(a + b); |
// @flow strict
import * as React from 'react';
import { View } from 'react-native';
import { StyleSheet, NetworkImage } from '@kiwicom/mobile-shared';
import { graphql, createFragmentContainer } from '@kiwicom/mobile-relay';
import { defaultTokens } from '@kiwicom/mobile-orbit';
import type { DestinationImage as DestinationImageType } from './__generated__/DestinationImage.graphql';
type Props = {|
+data: DestinationImageType,
|};
const DestinationImage = (props: Props) => (
<View style={styles.container}>
<NetworkImage
source={{
uri: props.data.destinationImageUrl,
}}
style={styles.image}
resizeMode="cover"
/>
</View>
);
export default createFragmentContainer(
DestinationImage,
graphql`
fragment DestinationImage on BookingInterface {
destinationImageUrl(dimensions: _375x165)
}
`,
);
const styles = StyleSheet.create({
image: StyleSheet.absoluteFillObject,
container: {
backgroundColor: defaultTokens.paletteProductLight,
height: 150,
width: '100%',
overflow: 'hidden',
},
});
|
const http = require('http');
const url = require('url');
const fs = require('fs');
const recipes = require('./loadRecipes');
const func = require('./func');
const port = process.env.PORT|| 5000;
const mainFile = "api/about.html";
const spritesFile = "sprite.png";
function recipesGet(what,name,res){
if(recipes[what][name])
func.endJSON(recipes[what][name],res);
else
func.endNotFound(res);
}
function getItemProp(name,prop,res){
if(!recipes.items[name]){
func.endNotFound(res);
return;
}
let item = recipes.items[name];
if(item[prop]) func.endJSON(item[prop],res);
else func.endNotFound(res);
}
function getImg(name,res){
name = name.endsWith('.png')? name: name+'.png';
if(func.images.includes(name))
func.pipeImg('./img/'+name,res);
else func.endNotFound(res);
}
function getList(name,res){
switch (name){
case 'item':
case 'resource':
func.endJSON(recipes[name+'list'],res);
break;
case 'image':
func.endJSON(func.images,res);
break;
default:
func.endNotFound(res);
break;
}
}
const server = http.createServer(function(req,res){
let urlObj = url.parse(req.url,true),
pathname = urlObj.pathname,
path = func.arrayPath(pathname);
console.log(pathname);
switch (path[0]){
// IMAGE
case "image":
if(path[1] && path[1]!="") {
getImg(path[1],res);
break;
}
else func.pipeImg(spritesFile,res);
break;
case "image.png":
if(path[1] && path[1]!="") func.endNotFound(res);
else func.pipeImg(spritesFile,res);
break;
// ITEM
case "item":
if(path[1] && path[1]!=""){
if(path[2] && path[2]!="") getItemProp(path[1],path[2],res);
else recipesGet('items',path[1],res);
}
else func.endJSON(recipes.items,res);
break;
// RESOURCE
case "resource":
if(path[1] && path[1]!="") recipesGet('resources',path[1],res);
else func.endJSON(recipes.resources,res);
break;
// LIST
case "list":
getList(path[1],res);
break;
// ABOUT
case "":
func.pipeHTML(mainFile,res);
break;
case "assets":
if(path[1] && path[1]!="" && path[2] && path[2]!=""){
res.writeHeader(200);
func.pipeFile(`api/assets/${path[1]}/${path[2]}`,res);
}
else func.endNotFound(res);
break;
// ERROR 404 - Not Found
default:
func.endNotFound(res);
}
});
server.listen(port);
|
var express = require('express');
var mongo_client = require('mongodb').MongoClient;
var _ = require('underscore');
var db;
var url = require('url');
var config = require('./models/db_configuration');
function get_cities_db(which_callback, res) {
connecting_string = 'mongodb://' + config.host +':'+ config.port +'/'+ config.db_name;
mongo_client.connect( connecting_string, function(err, db) {
if(!err) {
db.collection( 'cities', function( err, collection ) {
collection.find().toArray( function( err, items ) {
// which_callback( items );
res.jsonp( items );
});
});
}
});
}
function get_home() {
return {};
}
function get_cities(res) {
var output_hash = {};
var can_return = false;
function cities_callback(items) {
_.each( items, function( item ) {
console.log( item.name );
output_hash += item;
});
output_hash = items;
can_return = true;
}
get_cities_db( cities_callback, res );
}
//
// server loop stuff
// this is like, router.
//
var server = express();
server.enable("jsonp callback");
server.get("/", function(req, res) {
res.setHeader('Content-Type', 'application/json');
res.jsonp(get_home());
});
server.get("/cities", function(req, res) {
res.setHeader('Content-Type', 'application/json');
// res.jsonp(get_cities());
get_cities( res );
});
server.get("/cities.json", function(req, res) {
res.setHeader('Content-Type', 'application/json');
// res.jsonp(get_cities());
get_cities( res );
});
server.get("/cities/travel-to/:cityname.json", function(req, res) {
// cityname = req.query.cityname;
cityname = request.params.cityname;
res.setHeader('Content-Type', 'application/json');
// get_cities( res );
res.jsonp( { 'cityname': cityname } );
});
server.listen(3000);
console.log( '^+^ ^+^ Listening on port 3000' );
|
module.exports = {
devServer: {
proxy: {
'/xativa/*': {
target: 'http://172.16.0.157:3000/mock/30'
}
}
}
}
|
import axios from 'axios'
import apiUrl from '../modules/api-url'
import { store } from '../store'
class PairService {
async getCSSPair(seq) {
return await axios(apiUrl.csspair.get, {
params: {
css_file_seq: seq
}
})
}
async getJSPair(seq) {
return await axios(apiUrl.jspair.get, {
params: {
js_file_seq: seq
}
})
}
async createCSSPair(pair) {
return await axios.post(apiUrl.csspair.create, {
html_css_pairs: pair
})
}
}
export default new PairService()
|
// we need this to easily check the current route from every component
riot.routeState = {
view: ''
};
class Router {
constructor() {
this._currentView = null;
this._views = [
'yhteenveto',
'salkkun',
'kansiot',
'kiinteistot',
'tilat',
'kanava',
'haku',
'ilmoitukset',
'profiili'
];
this._defaultView = 'yhteenveto';
riot.route.base('#');
riot.route(this._handleRoute.bind(this));
riot.route.exec(this._handleRoute.bind(this));
}
_handleRoute(view) {
// load default view, if view is not in views list
if (this._views.indexOf(view) === -1) {
return riot.route(this._defaultView);
}
this._loadView(view);
}
_loadView(view) {
if (this._currentView) {
this._currentView.unmount(true);
}
riot.routeState.view = view;
this._currentView = riot.mount('#page-app', 'page-' + view)[0];
}
}
export default new Router() |
/**
* Custom agent prototype
* @param {String} id
* @constructor
* @extend eve.Agent
*/
function ChatAgent(id, app) {
// execute super constructor
eve.Agent.call(this, id);
this.app = app;
// connect to all transports configured by the system
this.connect(eve.system.transports.getAll());
}
// extend the eve.Agent prototype
ChatAgent.prototype = Object.create(eve.Agent.prototype);
ChatAgent.prototype.constructor = ChatAgent;
/**
* Send a greeting to an agent
* @param {String} to
*/
ChatAgent.prototype.sayHello = function(to) {
this.send(to, 'Hello ' + to + '!');
};
/**
* Handle incoming greetings. This overloads the default receive,
* so we can't use ChatAgent.on(pattern, listener) anymore
* @param {String} from Id of the sender
* @param {*} message Received message, a JSON object (often a string)
*/
ChatAgent.prototype.receive = function(from, message) {
console.log(from + ' said: ' + JSON.stringify(message) );
this.app.prop1 = message;
if (typeof message == String && message.indexOf('Hello') === 0) {
this.send(from, 'Hi ' + from + ', nice to meet you!');
this.app.prop1 = message;
}
switch(message.type){
case 'updaterooms':
this.app.room = message.current_room;
/*this.app.$.chat.push('messages',{
author: 'Spoggy',
text: "CONNEXION A "+message.current_room,
created: Date.now()
});*/
break;
case 'changePseudo':
// console.log('pseudo : '+message.pseudo);
this.app.pseudo = message.pseudo;
break;
case 'updateChat':
console.log(message)
this.app.$.chat.messages = this.app.messages;
this.room = message.room;
this.app.author = message.username == this.app.pseudo ? 'me' : 'you'; // For demo
if (this.app.author != 'me'){
message.data = message.username+": "+message.data;
if(!this.app.visible){
this.app.nonlu++;
if(this.app.nonlu > 100){
this.app.nonlu = "++"
}
this.app.icon = "";
}
}
this.app.$.chat.push('messages',{
author: this.app.author,
text: message.data,
created: Date.now()
});
break;
default:
console.log(message);
}
};
|
// vue.config.js
const path = require("path");
module.exports = {
// 选项...
devServer: {
hot: true,
port: '8088',
open: true,
noInfo: false,
overlay: {
warnings: true,
errors: true,
},
proxy: {
'/jasproxy': {
// target: 'http://192.168.50.138:8080/',
// target: 'http://1.119.155.134:10300/',
// target: 'http://nmweb.zyax.cn/',
target: 'http://192.168.100.36:8081/',
changeOrigin: true,
ws: true,
pathRewrite: {
'^/jasproxy': '/pipeline-supervise-platform/',
}
},
'/foo': {
target: '<other_url>'
}
}
},
configureWebpack(config) {
config.resolve.alias['@'] = path.resolve(__dirname, 'src');
},
css: {
loaderOptions: {
// sass: {
// prependData: `@import "./src/assets/scss/style.scss";`
// // sass 版本 9 中使用 additionalData 版本 8 中使用 prependData
// }
}
}
} |
import React from 'react';
class Top extends React.Component {
constructor(props, context) {
super(props, context);
}
render() {
const {background, handleClick} = this.props;
return (<div className="top" style={{background:background}} onClick={handleClick}>
top
</div>);
}
}
Top.displayName = 'Top';
Top.propTypes = {
background: React.PropTypes.string.isRequired,
handleClick: React.PropTypes.func.isRequired,
};
export default Top;
|
var express = require('express');
var router = express.Router();
// /* GET users listing. */
// router.get('/', function(req, res) {
// res.send('respond with a resource');
// });
/* POST to Add User Service */
router.post('/', function(req, res) {
console.log(JSON.stringify(req.body));
//res.send(JSON.stringify(req.body));
var products = req.body;
// Set our internal DB variable
var db = req.db;
// Set our collection
var collection = db.get('usercollection');
var error = false;
var nModified = 0;
for (var i=0; i<products.length; i++) {
var prod = products[i];
// Submit to the DB
collection.update({title:prod.title}, prod, {upsert:true, multi:false},
function(err, data){
if (err) console.log(err);
else console.log("update ok");
});
}
res.send("ok "+nModified);
});
/* POST to delete User Service */
router.delete('/', function(req, res) {
console.log(JSON.stringify(req.body));
//res.send(JSON.stringify(req.body));
// Set our internal DB variable
var db = req.db;
// Set our collection
var collection = db.get('usercollection');
collection.remove(req.body,
function(err, removed) {
if (err) console.log(err);
else console.log("update ok");
});
res.send("ok");
});
module.exports = router;
|
describe('sum', function () {
it('should return sum of arguments', function () {
let pk = Perkeep({
host: 'http://perkeep.test',
user: 'user',
pass: 'pass'
});
pk._discoveryConfig = {
foo: 'bar'
};
chai.expect(pk.discoveryConfig).to.equal('test');
});
}); |
var Cat = function (mediator, name) {
this.mediator = mediator;
this.name = name;
this.text = 'say Meow';
};
Cat.prototype.say = function () {
console.log(this.name + ' ' + this.text);
this.mediator.sayText(this);
};
var Ghost = function (mediator, name) {
this.mediator = mediator;
this.name = name;
this.text = 'say Buuuu!!!';
};
Ghost.prototype.say = function (){
console.log(this.name + ' ' + this.text);
this.mediator.sayText(this);
};
var Human = function (mediator, name) {
this.mediator = mediator;
this.name = name;
this.text = 'say Hello';
};
Human.prototype.say = function () {
console.log(this.name + ' ' + this.text);
this.mediator.sayText(this);
};
var Mediator = {
guys: [],
addGuys: function (guy) {
this.guys.push(guy);
},
sayText: function (guy) {
for (var i = 0; i < this.guys.length; i++) {
if (this.guys[i] !== guy) {
console.log(this.guys[i].name + ' ' + this.guys[i].text);
}
}
}
};
|
X.define("model.dataCleaningModel",function () {
//临时测试数据
var query = "js/data/mockData/purchasers.json";
var dataCleaningModel = X.model.create("model.dataCleaningModel",{service:{ query:query}});
//获取产品图片列表
dataCleaningModel.getProducImgList = function(indexBegin,indexEnd,totalValue,callback){
var option = {url:X.config.dataCleaning.api.listByPage+"indexBegin/indexEnd/?indexBegin="+indexBegin+"&indexEnd="+indexEnd+"",
type:"GET",callback:function(result){
callback&&callback(result);
}};
X.loadData(option);
};
//清除产品水印
dataCleaningModel.clearWatermark =function(objectId,indexOfImage,callback){
var option = {url:X.config.dataCleaning.api.clearWatermark+"objectId/indexOfImage/?objectId="+objectId+"&indexOfImage="+indexOfImage+"",
type:"GET",callback:function(result){
callback&&callback(result);
}};
X.loadData(option);
};
//标记为已读
dataCleaningModel.markImageRead =function(data,callback){
var option = {url:X.config.dataCleaning.api.markImageRead,data:data,
type:"POST",callback:function(result){
callback&&callback(result);
}};
X.loadData(option);
};
//恢复产品图片
dataCleaningModel.cancelDelete =function(objectId,indexOfImage,callback){
var option = {url:X.config.dataCleaning.api.cancelDelete+"objectId/indexOfImage/?objectId="+objectId+"&indexOfImage="+indexOfImage+"",
type:"GET",callback:function(result){
callback&&callback(result);
}};
X.loadData(option);
};
dataCleaningModel.statusconst = {
pagingRange: [
{key: 0, value: "1-100"},
{key: 1, value: "101-200"},
{key: 2, value: "201-300"},
{key: 3, value: "301-400"},
{key: 4, value: "401-500"},
{key: 5, value: "501-600"}
]
};
return dataCleaningModel;
});
|
// # # # # # # # IMPORTS AND DEFINITIONS # # # # # # #
// Imports
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const formidable = require("express-formidable");
const mailgun = require("mailgun-js");
// Server app declaration
const app = express();
app.use(formidable());
app.use(cors());
// # # # # # # # MONGOOSE CONNECTION AND MODELS # # # # # # #
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const Devis = mongoose.model("Devis", {
email: String,
type: String,
etat: String,
usage: String,
situation: String,
montant: String,
zip: String
});
// # # # # # # # MAILGUN SETTINGS # # # # # # #
const API_KEY = process.env.GUNKEY;
const DOMAIN = process.env.GUNDOMAIN;
const mg = mailgun({ apiKey: API_KEY, domain: DOMAIN });
// # # # # # # # ROUTES # # # # # # # # # # # # # #
// - - - - - - - - - - HELLO WORLD - - - - - - - - - - - - - - - - - - - - -
app.get("/", async (req, res) => {
res.status(200).json({ message: "Meilleur Taux Back te passe le bonjour" });
});
// - - - - - - - - - - PING - - - - - - - - - - - - - - - - - - - - - - - -
app.get("/ping", async (req, res) => {
try {
res.status(200).json({ message: "pong" });
} catch (e) {
console.log(e.message);
res.status(400).json({ message: e.message });
}
});
// - - - - - - - - - - AUTHENTIFICATION - - - - - - - - - - - - - - - - - - - - -
app.post("/authent", async (req, res) => {
console.log("authent demandee");
try {
if (req.fields.password === process.env.PASSWORD) {
console.log("authent ok");
res.status(200).json({ token: process.env.TOKEN });
} else {
console.log("authent nope");
res.status(200).json({ message: "authent fail" });
}
} catch (e) {
res.status(400).json({ message: e.message });
}
});
// - - - - - - - - - - DEVIS CREATION - - - - - - - - - - - - - - - - - - -
app.post("/deviscreation", async (req, res) => {
try {
// Create new Entry
console.log("devis creation asked", req.fields.email);
const devis = new Devis(req.fields);
await devis.save();
// Send an Email
console.log("creation OK, sending email");
const data = {
from: "Mailgun Sandbox <postmaster@" + DOMAIN + ">",
to: req.fields.email,
subject: "Meilleur Taux Pierre, Dossier " + devis._id,
text:
"Voici ton récapitulatif Meilleur Taux en JSON" + JSON.stringify(devis)
};
mg.messages().send(data, function(error, body) {
console.log(body);
});
// Send Back Res Status OK
console.log("email done, answering client with id", devis._id);
res.status(200).json({ message: "Created", id: devis._id });
} catch (e) {
console.log(e.message);
res.status(400).json({ message: e.message });
}
});
// - - - - - - - - - - GET ALL DEVIS - - - - - - - - - - - - - - - - - - -
app.get("/getdevis", async (req, res) => {
try {
console.log("get all required");
const alldevis = await Devis.find();
res.status(200).json({ alldevis: alldevis });
} catch (e) {
res.status(400).json({ message: e.message });
}
});
// - - - - - - - - - - DELETE ONE DEVIS - - - - - - - - - - - - - - - - - - -
app.post("/deletedevis", async (req, res) => {
try {
console.log("delete ", req.fields.id);
const alldevis = await Devis.findOneAndDelete(req.fields.id);
res.status(200).json({ message: "deleted" });
} catch (e) {
res.status(400).json({ message: e.message });
}
});
// # # # # # # # STARTER # # # # # # # # # # # # # #
app.listen(process.env.PORT, () => {
console.log("server started on", process.env.PORT);
});
|
// -- Model
function Session () {
this.inProgress = false;
this.report = null;
this.start = function (gps) {
if (this.inProgress) { throw new Error('already started'); }
this.inProgress = true;
};
this.sample = function (bouy, wind) {
if (!this.inProgress) { throw new Error('not started'); }
var w = wind.sample(),
b = bouy.sample();
return {"windSpeedMetersPerSec": w.speed_ms,
"windDirectionDeg": w.direction_deg,
"swellDirectionDeg": b.swell_direction_deg,
"swellPeriodSec": b.swell_period_s,
"swellMeters": b.swell_m};
};
this.setDetails(report) {
this.report = report;
}
this.end = function () {
if (!this.inProgress) { throw new Error('not started'); }
this.inProgress = false;
};
}
Session.all = function () {
return [];
};
// --
function Bouy (gps) {
this.gps = gps;
this.sample = function () {
return {"swell_direction_deg": 0.0, "swell_period_s": 5, "swell_m": 1};
};
}
Bouy.at = function (gps) {
return new Bouy(gps);
}
Bouy.all = function () {
return [];
}
// --
function WindDirection (gps) {
this.gps = gps;
this.sample = function () {
return {"direction_deg": 0.0,
"speed_ms": 0.0};
}
}
WindDirection.at = function (gps) {
return new WindDirection(gps);
}
|
window.onresize=function(){
resize();
}
window.onload = function(){
resize();
}
function resize(){
document.getElementsByTagName("html")[0].style.fontSize =
document.body.clientWidth/7.2+"px";
};
|
import { Router} from 'express';
const ridesRoute = Router();
ridesRoute.get('/', (req, res) => {
// Controller to fetch all the ride offers
res.status(200).json({
message: 'Controller to fetch all ride offers'
});
});
ridesRoute.get('/:rideId', (req, res) => {
// Controller to fetch all single ride id
res.status(200).json({
message: 'Controller to fetch all single ride id'
});
});
ridesRoute.post('/', (req, res) => {
// Controller to create a new ride
res.status(201).json({
message: 'Controller to create a new ride'
});
});
ridesRoute.post('/:rideId/request', (req, res) => {
// Controller to make a request to join a ride
res.status(201).json({
message: 'Controller to make a request to join a ride',
});
});
export default ridesRoute; |
import {Meteor} from 'meteor/meteor';
import {ValidatedMethod} from 'meteor/mdg:validated-method';
import {CallPromiseMixin} from 'meteor/didericis:callpromise-mixin';
import {SimpleSchema} from 'meteor/aldeed:simple-schema';
// Collection
import {Repayment} from '../../imports/api/collections/repayment.js';
export const getLastRepaymentByLoanAccId = new ValidatedMethod({
name: 'microfis.getLastRepaymentByLoanAccId',
mixins: [CallPromiseMixin],
validate: new SimpleSchema({
loanAccId: {type: String}
}).validator(),
run({loanAccId}) {
if (!this.isSimulation) {
let data = Repayment.findOne(
{loanAccId: loanAccId},
{$sort: {_id: -1}}
);
return data;
}
}
}); |
import styled from "styled-components";
import { Menu } from "@material-ui/core";
import { PersonOutline } from "@material-ui/icons";
export const MenuMUI = styled(Menu)`
.MuiMenu-paper {
border: 1px solid #d3d4d5;
}
`;
export const PersonOutlineIcon = styled(PersonOutline)`
font-size: 30px !important;
border-radius: 50%;
color: rgb(0 0 0 / 30%);
background: linear-gradient(to right, #00c9ff, #92fe9d);
`;
|
const Airdrop = artifacts.require("Airdrop");
const MKtoken = artifacts.require("MKtoken");
module.exports = async (_deployer) => {
// Use deployer to state migration tasks.
const token = await MKtoken.deployed();
await _deployer.deploy(Airdrop, token.address);
const airdrop = await Airdrop.deployed();
const amount = web3.utils.toWei("10000", "ether");
await token.transfer(airdrop.address, amount);
};
|
import { StyleSheet } from 'react-native';
import {width, scale, statusBarHeight} from '@/utils/device'
export default StyleSheet.create({
container: {
flex: 1,
},
}) |
module.exports = function (p) {
'use strict';
var pipeMiddle = require('middleware-pipe')
, dwarf = require('../gulp-plugin/dwarf');
return pipeMiddle(p, /\.js$/)
.pipe(function (req) {
return dwarf();
});
};
|
import VectorMap from './vector_map/vector_map';
export default VectorMap;
/**
* @name VectorMapLegendItem
* @inherits BaseLegendItem
* @type object
*/ |
import PermainanResult from './PermainanResult.vue';
export default { title: 'Permainan Result' };
export const standar = () => ({
components: {
PermainanResult
},
data() {
return {
results: {
benar: 20,
salah: 20,
takDiJawab: 20
}
};
},
template: '<permainan-result :results="results"></permainan-result>'
});
|
import isEqual from "lodash.isequal";
import { setBoardColors } from "./setBoardColors";
export const UP = "up";
export const DOWN = "down";
export const RIGHT = "right";
export const LEFT = "left";
function notCombined(tile) {
return !tile.alreadyCombined;
}
export function moveTiles(board, direction, score) {
let newBoard = JSON.parse(JSON.stringify(board));
let newScore = score;
function moveHorizontal() {
newBoard.forEach((tile, idx) => {
if (idx % 4 !== 0 && idx !== 0 && tile.value !== null) {
if (newBoard[idx - 1].value === null) {
newBoard[idx - 1].value = tile.value;
newBoard[idx].value = null;
}
if (
notCombined(newBoard[idx - 1]) &&
notCombined(tile) &&
newBoard[idx - 1].value === tile.value
) {
const newValue = newBoard[idx - 1].value + tile.value;
newScore += newValue;
newBoard[idx - 1].value = newValue;
newBoard[idx - 1].alreadyCombined = true;
newBoard[idx].value = null;
newBoard[idx].alreadyCombined = false;
}
}
});
}
function moveVertical() {
newBoard.forEach((tile, idx) => {
if (idx > 3 && tile.value !== null) {
if (newBoard[idx - 4].value === null) {
newBoard[idx - 4].value = tile.value;
newBoard[idx].value = null;
}
if (
notCombined(newBoard[idx - 4]) &&
notCombined(tile) &&
newBoard[idx - 4].value === tile.value
) {
const newValue = newBoard[idx - 4].value + tile.value;
newScore += newValue;
newBoard[idx - 4].value = newValue;
newBoard[idx - 4].alreadyCombined = true;
newBoard[idx].value = null;
newBoard[idx].alreadyCombined = false;
}
}
});
}
if (direction === UP) moveVertical();
if (direction === DOWN) {
newBoard = newBoard.reverse();
moveVertical();
newBoard = newBoard.reverse();
}
if (direction === RIGHT) {
newBoard = newBoard.reverse();
moveHorizontal();
newBoard = newBoard.reverse();
}
if (direction === LEFT) moveHorizontal();
if (isEqual(board, newBoard)) {
return {
board: setBoardColors(newBoard),
score: newScore
};
}
return moveTiles(newBoard, direction, newScore);
}
|
/**
* Returns the invoices associated with a users account.
* @param {Object} options
* @throws {Error}
* @return {Promise}
*/
module.exports = (options) => {
return new Promise((resolve, reject) => {
resolve({ text: 'ok!' })
})
}
|
import firebase from 'firebase/app';
import 'firebase/firestore'
import 'firebase/auth'
const config = {
apiKey: "AIzaSyBycpiOndPtJ1Spc-QIewhIwgxitHUjVGM",
authDomain: "natural-e-commerce.firebaseapp.com",
databaseURL: "https://natural-e-commerce.firebaseio.com",
projectId: "natural-e-commerce",
storageBucket: "",
messagingSenderId: "259490356151",
appId: "1:259490356151:web:022783e9b70bcd24"
};
firebase.initializeApp(config);
export const auth = firebase.auth();
export const firestore = firebase.firestore();
const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });
export const signInWithGoogle = () => auth.signInWithPopup(provider);
export default firebase; |
/***
* Project: MDL
* Author: Thilina Herath
* Modified by: Akarshani Amarasinghe
* Module: login services
*/
'use strict';
var serviceName = 'mdl.mobileweb.service.dashboard'
angular.module('newApp').service(serviceName,['$http','$cookieStore','$location','settings','mdl.mobileweb.service.login','cacheService',
function ($http, $cookieStore, $location, settings, loginService, cacheService) {
var vm = this;
vm.webApiBaseUrl = settings.webApiBaseUrl;
vm.jaxrsApiBaseUrl = settings.mdljaxrsApiBaseUrl;
vm.getPreActivities = function (stationid, callback) {
var token = loginService.getAccessToken();
var body ={"getprepollactivities":{
"token":token,
"electionid":1,
"pollingstationid" : stationid }};
var authEndpoint = vm.webApiBaseUrl+'services/getprepollactivities';
// return (vm.preactresponse); //To Remove
$http.post(authEndpoint, body, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.success(function (response) {
// success
//console.log(response);
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
callback(errResponse);
});
}
vm.getElectionStatus = function (electionid,stationid,callback) {
var token = loginService.getAccessToken();
var body ={"getelectionstatus":{
"token":token,
"stationid":stationid,
"electionid":electionid
}};
var authEndpoint = vm.webApiBaseUrl+'services/getelectionstatus/getelectionstatus';
$http.post(authEndpoint,body,{headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.success(function (response) {
//console.log(response.result.entry.response);
callback(response);
})
.error(function (errResponse) {
// console.log(" Error returning from " + authEndpoint);
callback(errResponse);
});
}
vm.updatePreActivity = function(actid, status, stationid){
var token = loginService.getAccessToken();
var body ={"updateprepollingactivity":{
"token":token,
"electionid":1,
"pollingstationid" : stationid,
"activityid":actid,
"status" : status
}};
var authEndpoint = vm.webApiBaseUrl+'services/updateprepollingactivity';
$http.post(authEndpoint,body,{headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.success(function (response) {
//console.log(response.result.entry.response);
return(response.result.entry.response);
})
.error(function (errResponse) {
// console.log(" Error returning from " + authEndpoint);
return(errResponse);
});
}
vm.openCurrentStation = function(stationid,callback){
var token = loginService.getAccessToken();
var body ={"openstation":{
"token":token,
"pollingstation_id" : stationid
}};
//console.log(body);
var authEndpoint = vm.webApiBaseUrl+'services/openstation/openstation';
$http.post(authEndpoint,body,{headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.success(function (response) {
//console.log(response.result.entry.response);
callback(response.result.entry.response);
})
.error(function (errResponse) {
// console.log(" Error returning from " + authEndpoint);
callback(errResponse);
});
}
vm.closeCurrentStation = function(stationid,callback){
var token = loginService.getAccessToken();
var body ={"closepollingstation":{
"token":token,
"pollingstationid" : stationid
}};
var authEndpoint = vm.webApiBaseUrl+'services/closepollingstation/closepollingstation';
$http.post(authEndpoint,body,{headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.success(function (response) {
//console.log(response.result.entry.response);
callback(response.result.entry.response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
callback(errResponse);
});
}
vm.updateCloseStats = function(statoinid,closestation,eid,callback){
var token = loginService.getAccessToken();
var body ={"updateclosestats":{
"token":token,
"electionid":eid,
"pollingstationid":statoinid,
"tot_ballots":closestation.tot_ballots,
"tot_spoiled_replaced":closestation.tot_spoiled_replaced,
"tot_unused":closestation.tot_unused,
"tot_tend_ballots":closestation.tot_tend_ballots,
"tot_tend_spoiled":closestation.tot_tend_spoiled,
"tot_tend_unused":closestation.tot_tend_unused
}};
var authEndpoint = vm.webApiBaseUrl+'services/updateclosestats/updateclosestats';
$http.post(authEndpoint,body,{headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.success(function (response) {
//console.log(response.result.entry.response);
callback(response.result.entry.response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
callback(errResponse);
});
}
vm.getPollingStations = function (callback) {
var offline = {};
offline.allowOffline = true;
offline.setCache = function (data) { cacheService.put('pollingStations', data); }
offline.getCache = function () { return cacheService.get('pollingStations'); }
var token = loginService.getAccessToken();
var body ={"getpollingstations":{
"token":token
}};
var authEndpoint = vm.webApiBaseUrl+'services/getpollingstations/getpollingstations';
$http.post(authEndpoint, body, {
offline:offline,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.success(function (response) {
// success
//console.log(response);
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
callback(errResponse);
});
}
vm.getEllectionList = function (stationid, callback) {
var offline = {};
offline.allowOffline = true;
offline.setCache = function (data) { cacheService.put('electionList', data); }
offline.getCache = function () { return cacheService.get('electionList'); }
var token = loginService.getAccessToken();
var body ={"getelectionsbystationid":{
"token":token,
"stationid":stationid
}};
var authEndpoint = vm.webApiBaseUrl+'services/getelectionsbystationid/getelectionsbystationid';
$http.post(authEndpoint, body, {
offline:offline,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.success(function (response) {
// success
//console.log(response);
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
callback(errResponse);
});
}
vm.getOpenStationButtonStatus = function(stationid,callback){
var token = loginService.getAccessToken();
var body ={"getpollingstationstatus":{
"token":token,
"stationid" : stationid }};
var authEndpoint = vm.webApiBaseUrl+'services/getpollingstationstatus';
// return (vm.preactresponse); //To Remove
$http.post(authEndpoint,body,{headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.success(function (response) {
// success
//console.log(response);
callback(response);
})
.error(function (errResponse) {
//console.log(" error Returning from " + authEndpoint);
callback(errResponse);
});
}
vm.getCloseStationButtonStatus = function(stationid,callback){
var token = loginService.getAccessToken();
var body ={"getelectionsbystationid":{
"token":token,
"stationid" : stationid }};
var authEndpoint = vm.webApiBaseUrl+'services/getelectionsbystationid/getelectionsbystationid';
// return (vm.preactresponse); //To Remove
$http.post(authEndpoint,body,{headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.success(function (response) {
// success
//console.log(response);
callback(response);
})
.error(function (errResponse) {
// console.log(" error Returning from " + authEndpoint);
callback(errResponse);
});
}
vm.getPrePollActivities = function (polling_station_id, callback) {
var offline = {};
offline.allowOffline = true;
offline.setCache = function (data) { cacheService.put('prePollActivities', data); }
offline.getCache = function () { return cacheService.get('prePollActivities'); }
var token = loginService.getAccessToken();
var body ={
"getprepollactivities_v2":{
"token":token,
"polling_station_id":polling_station_id,
}
};
var authEndpoint = vm.webApiBaseUrl+'services/getprepollactivities_v2/getprepollactivities_v2';
$http.post(authEndpoint, body, {
offline:offline,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.success(function (response) {
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
});
}
vm.getElectionStats = function(electionId, callback) {
var token = loginService.getAccessToken();
var body ={
"token":token,
"electionId":electionId
};
var authEndpoint = vm.jaxrsApiBaseUrl+'psmdashboard/getstats';
$http.post(authEndpoint,body,{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.success(function (response) {
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
});
}
vm.getAllElections = function(callback){
var token = loginService.getAccessToken();
var body ={
"token":token
};
var authEndpoint = vm.jaxrsApiBaseUrl+'psmdashboard/getelectionsbyuser';
$http.post(authEndpoint,body,{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.success(function (response) {
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
});
};
vm.getpollingstationclosedstatus = function (stationid, callback) {
var token = loginService.getAccessToken();
var body = {
"getpollingstationclosedstatus":{
"token":token,
"stationid":stationid
}
};
var authEndpoint = vm.webApiBaseUrl+'services/getpollingstationclosedstatus/getpollingstationclosedstatus';
$http.post(authEndpoint, body, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.success(function (response) {
console.log(response);
callback(response);
})
.error(function (errResponse) {
console.log(" Error returning from " + authEndpoint);
callback(errResponse);
});
}
vm.getPostPollActivities = function(polling_station_id,election_id,callback){
var token = loginService.getAccessToken();
var body ={
"getpostpollactivities":{
"token":token,
"polling_station_id":polling_station_id,
"electionid":election_id
}
};
var authEndpoint = vm.webApiBaseUrl+'services/getpostpollactivities/getpostpollactivities';
$http.post(authEndpoint,body,{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.success(function (response) {
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
});
}
vm.generateBPA = function(stationid,electionid,callback){
var token = loginService.getAccessToken();
var body ={
"getpostpollactivities":{
"token":token,
"stationid":stationid,
"electionid":electionid
}
};
var authEndpoint = vm.webApiBaseUrl+'services/generatebpa/generatebpa';
$http.post(authEndpoint,body,{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.success(function (response) {
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
});
}
vm.check_allelectionclosed = function(stationid,callback){
var token = loginService.getAccessToken();
var body ={
"getbpastatusbystation":{
"token":token,
"stationid":stationid
}
};
var authEndpoint = vm.webApiBaseUrl+'services/getbpastatusbystation/getbpastatusbystation';
$http.post(authEndpoint,body,{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.success(function (response) {
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
});
}
vm.getBPGeneratedStaus = function(stationid,electionid,callback){
var token = loginService.getAccessToken();
var body ={
"getbpastatus":{
"token":token,
"stationid":stationid,
"electionid": electionid
}
};
var authEndpoint = vm.webApiBaseUrl+'services/getbpastatus/getbpastatus';
$http.post(authEndpoint,body,{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.success(function (response) {
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
});
}
vm.updateprepollactivities_v2 = function(body,callback){
var authEndpoint = vm.jaxrsApiBaseUrl+'psmdashboard/updateprepollingactivity';
$http.post(authEndpoint,body,{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.success(function (response) {
callback(response);
console.log(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
});
};
vm.getBPNames = function(electionid,callback){
var token = loginService.getAccessToken();
var body ={
"getballotpapernames":{
"token":token,
"electionid": electionid
}
};
var authEndpoint = vm.webApiBaseUrl+'services/getballotpapernames/getballotpapernames';
$http.post(authEndpoint,body,{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.success(function (response) {
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
});
}
vm.getBallotType = function(electionid,callback){
var token = loginService.getAccessToken();
var body ={
"getballottypecount":{
"token":token,
"electionid": electionid
}
};
var authEndpoint = vm.webApiBaseUrl+'services/getballottypecount/getballottypecount';
$http.post(authEndpoint,body,{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.success(function (response) {
callback(response);
})
.error(function (errResponse) {
//console.log(" Error returning from " + authEndpoint);
});
}
} ]); |
// pages/device/device.js
var util = require('../../utils/util.js')
Page({
/**
* 页面的初始数据
*/
data: {
list: []
},
/**
* 点击设备即连接该设备,之后跳转到状态界面
*/
connect: function(event) {
var deviceid = event.currentTarget.dataset.item.deviceId;
wx.createBLEConnection({
deviceId: deviceid,
success(res) {
wx.navigateTo({
url: '/pages/status/status?deviceid=' + deviceid,
})
}
})
},
/**
* 生命周期函数--监听页面加载
*页面一加载即执行蓝牙扫描动作
*/
onLoad: function(options) {
var _this = this;
wx.openBluetoothAdapter({
success: function(res) {
console.log("-----openBluetoothAdapter sucess------");
wx.startBluetoothDevicesDiscovery({
success: function(res) {
console.log("------startBluetoothDevicesDiscovery---sucess----");
console.log("getBluetoothDevices:");
wx.getBluetoothDevices({
success: function(res) {
console.log(res.devices);
const devices = res.devices.filter(item => item.name == "GL-S10")
_this.setData({
list: devices
})
},
})
},
})
},
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
}
}) |
import getConfig from '../../utils/config';
const config = getConfig();
const symbolToName = config.get('symbol.symbolToName');
// eslint-disable-next-line import/prefer-default-export
export function covertSymbolToName(syl) {
const s = symbolToName[syl];
if (s) return s;
return '';
}
export function floor(number, after = 1) {
// eslint-disable-next-line no-restricted-properties
const p = Math.pow(10, after);
return Math.floor(number * p) / p;
}
export const Loops = (() => {
/**
* Define class
*
* @author Steve Hoang <particles4dev>
* @version
* @since 0.1
*
* @param d delay time
* @param t a function to execute
*
* */
// eslint-disable-next-line func-names
const f = function(d, t) {
/**
* Private property
* */
const self = this;
let delay = d === null ? 1000 : d;
let todo = t;
let start = 0;
let end = 2 * delay;
let run = true;
/**
* Public property
* */
this.timeoutID = null;
/**
* Get current time
*
* @return Number
* @see void
* */
const getTime = () => new Date().getTime();
/**
* Set a timer to delay
*
* @param value
* @return void
* @see void
* */
this.setDelay = value => {
delay = value;
start = 0;
end = 2 * delay;
};
/**
* Specify a function to execute when the delay time is done
*
* @param func
* @return void
* @see void
* */
this.setTodo = func => {
todo = func;
};
/**
*
*
* @param f
* @param args
* @return void
* @see void
* */
const remind = async (func, args) => {
if (run === true) {
start = getTime();
await func.apply(func, args);
const callback = args[args.length - 1];
if (typeof callback === 'function') callback();
end = getTime();
self.setup(...args);
}
};
/**
*
*
* @param callback
* @return void
* @see void
* */
// eslint-disable-next-line func-names
this.setup = function(...args) {
if (run === true) {
const mt = delay - (end - start);
if (mt > 0) {
this.timeoutID = window.setTimeout(remind, mt, todo, args);
} else {
remind(todo, args);
}
}
};
/**
* exits the loop
*
* @return void
* @see void
* */
// eslint-disable-next-line func-names
this.cancel = function() {
if (typeof this.timeoutID === 'number') {
window.clearTimeout(this.timeoutID);
delete this.timeoutID;
}
run = false;
console.log('stop loop');
return this;
};
/**
* Get current state
*
* @return void
* @see void
* */
this.getState = () => {
console.log(`Run is ${run}`);
return run;
};
};
return f;
})();
|
var XBN = require("../common/xbn.js");
console.log("xbn");
var express = require('express');
var expInstance = express();
function App(vhost){
this.exp = expInstance;
init.call(this,vhost);
}
function init(vhost){
var config = require("../common/config.js");
var _vhost = config.getInstance().getConfig()[vhost];
var rootPath = _vhost.location;
console.log("rootPath:" + rootPath);
this.xbn = new XBN(_vhost);
}
module.exports = App; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.