text
stringlengths
7
3.69M
export function greet(){ return "Hello"; } export function greetUser(username="somebody"){ //return "Hello " + username; return `Hello ${username}`; //template literal } export function greetUserAsPerTime(username="nobody"){ let greet = ""; let today = new Date(); let h = today.getHours(); if(h>=3 && h<=11){ greet = "Good Morning "; }else if(h>=12 && h<=16){ greet = "Good Noon"; }else { greet="Good Evening" } return `${greet} ${username}`; //template literal } export const greetAll = function(userNames){ /* for(let i=0;i<userNames.length;i++){ console.log(greetUser(userNames[i])); }*/ let str = `${userNames}`; console.log(greetUser(str)); }
const withCSS = require('@zeit/next-css') const withTypescript = require('@zeit/next-typescript') const Dotenv = require('dotenv-webpack') const fs = require('fs') const path = require('path') function listPages(parentDir, parentPath = '') { const pages = [] fs.readdirSync(parentDir).forEach(childName => { if (['__tests__', 'components', 'containers'].includes(childName)) { return } if (childName.startsWith('_app.') || childName.startsWith('_document.')) { return } const childPath = path.resolve(parentDir, childName) if (fs.lstatSync(childPath).isDirectory()) { pages.push(...listPages(childPath, parentPath + '/' + childName)) } const childNameOnly = path.parse(childName).name if (childNameOnly === 'index') { pages.push(parentPath === '' ? '/' : parentPath) } else { pages.push(parentPath + '/' + childNameOnly) } }) return pages } let config = { exportPathMap: async function(defaultPathMap) { const pathsDir = path.resolve(__dirname, 'pages') const pages = listPages(pathsDir) const pathMap = {} for (var i = 0; i < pages.length; i++) { const page = pages[i] pathMap[page] = { page } } return pathMap }, pageExtensions: ['js', 'jsx', 'ts', 'tsx'], webpack: (config, options) => { config.node = config.node || {} config.node = { ...config.node, fs: 'empty' } config.plugins = config.plugins || [] config.plugins = [ ...config.plugins, new Dotenv({ path: path.join(__dirname, '.env'), systemvars: true, defaults: path.join(__dirname, '.env.defaults') }) ] if (!options.dev) { // 개발 과정에서 IE11 사용 금지 // https://github.com/zeit/next.js/tree/canary/examples/with-polyfills const originalEntry = config.entry config.entry = async () => { const entries = await originalEntry() if ( entries['main.js'] && !entries['main.js'].includes('./polyfills.js') ) { entries['main.js'].unshift('./polyfills.js') } return entries } } return config } } config = withCSS(config) config = withTypescript(config) module.exports = config
import React, { Component } from 'react' import Display from './Display' import Controls from './Controls' const initialState = { inputValue: '0', savedValue: '', operator: null, isFinished: false, memory: '' } const Operations = { '+': (prev, next) => prev + next, '−': (prev, next) => prev - next, '×': (prev, next) => prev * next, '÷': (prev, next) => prev / next } const operatorAtTheEnd = str => Object.keys(Operations).includes(str[str.length - 2]) const answer = (s, i, o) => Math.round(Operations[o](parseFloat(s), parseFloat(i)) * 100) / 100 class App extends Component { state = initialState handleValue = v => { const { inputValue, savedValue, isFinished, memory } = this.state if ( v == '.' && /\.\d*$/.test(inputValue) && !operatorAtTheEnd(memory) ) return false if (!isFinished) { this.setState({ inputValue: (inputValue == '0' || operatorAtTheEnd(memory)) ? v : inputValue + v, memory: memory + v }) } else { this.setState({ inputValue: v, isFinished: false, memory: v }) } if (!savedValue && memory.slice(1, 2) == '-') { this.setState({ inputValue: '-' + v }) } } handleOperator = nextOperator => { const { inputValue, savedValue, operator, isFinished, memory } = this.state if (!inputValue && nextOperator !== '-') return false if (!operatorAtTheEnd(memory)) { this.setState({ operator: nextOperator, isFinished: false, memory: isFinished ? `${inputValue} ${nextOperator} ` : `${memory} ${nextOperator} ` }) !savedValue ? this.setState({ inputValue: inputValue, savedValue: inputValue, }) : this.setState({ inputValue: answer(savedValue, inputValue, operator), savedValue: answer(savedValue, inputValue, operator), }) } else { this.setState({ operator: nextOperator, memory: memory.replace(/..$/, `${nextOperator} `) }) } if (operator && isNaN(answer(savedValue, inputValue, operator))) { this.setState({ inputValue: 'Error', savedValue: '', operator: null, isFinished: true, memory: '' }) } if (inputValue == 'Error') { this.setState({ inputValue: '0', savedValue: '0', operator: nextOperator, isFinished: false, memory: '0 ' + `${nextOperator} ` }) } } handleEquals = () => { const { inputValue, savedValue, operator, isFinished, memory } = this.state const a = answer(savedValue, inputValue, operator) if (operatorAtTheEnd(memory)) return false this.setState({ inputValue: String(a), savedValue: '', operator: null, isFinished: true, memory: '' }) if (isNaN(a)) { this.setState({ inputValue: 'Error', savedValue: '', operator: null, isFinished: true, memory: '' }) } } handleAC = () => { this.setState(initialState) } handleCE = () => { const { inputValue, isFinished, memory } = this.state this.setState({ inputValue: inputValue.slice(0, -1) || '0', memory: memory.slice(0, -1) }) } handleKeyDown = event => { let { key } = event let pairs = { '+': '+', '-': '−', '*': '×', '/': '÷' } if (/^\d/.test(key)) this.handleValue(key) if (key in pairs) this.handleOperator(pairs[key]) if (key === 'Enter') this.handleEquals() if (key === 'Backspace') this.handleCE() if (key === 'Clear') this.handleAC() } componentDidMount() { document.addEventListener('keydown', this.handleKeyDown) } componentWillUnmount() { document.removeEventListener('keydown', this.handleKeyDown) } render() { const { inputValue, isFinished, memory } = this.state return ( <div id="calculator"> <Display inputValue={inputValue} isFinished={isFinished} memory={memory} onCE={this.handleCE} onAC={this.handleAC} /> <Controls onValue={this.handleValue} onOperator={this.handleOperator} onEquals={this.handleEquals} /> </div> ) } } export default App
import React from 'react' export const NotFound = () => { return ( <div className='app-container'> <div style={{textAlign: 'center', margin: '5rem 0'}} className='register-form-container-100'> <h1 style={{margin: '1rem 0 0 0', padding: 0, fontWeight: 'bold', fontSize: '3rem'}}>¡Lo sentimos!</h1> <h2 style={{margin: '0', padding: 0, fontWeight: 200, fontSize: '3rem'}}>No encontramos la página que buscas</h2> </div> </div> ) }
import React from 'react'; const Steps = () => { return ( <div> <h4>Notes.</h4> <p>The main difference of this approach is that we use an action creator to load the questions array and a reducer to deliver this data to the view.</p> </div> ); }; export default Steps;
var gridManager;//表格对象 // 初始化加载用户列表数据 $(function() { var roleId = $("#roleId").val(); var url = "../sysRole/findUserList.shtml?roleId="+roleId ; findUserList(url); gridManager = $("#maingrid").ligerGetGridManager(); }); //加载用户列表 function findUserList(url) { window['g'] = $("#maingrid").ligerGrid( { height : '89%', width : '99.7%', headerRowHeight : 28, rowHeight : 26, checkbox : true, columns : [ {display : '用户标识',name : 'userId',width : '15%'}, {display : '用户名称',name : 'userName', width : '15%'}, {display : '用户真实姓名',name : 'userRealName',width : '16%'}, {display : '用户状态',name : 'curStatusCode',width : '12%',type : 'int',align : 'center', render : function(row) { if (row.curStatusCode == "01") { return "正常"; } else if (row.curStatusCode == "02") { return "<font color='red'>注销</font>"; } }}, {display : '性别',name : 'gender',width : '12%',type : 'int',align : 'center',render : function(row) { if (row.gender == "01") { return "男"; } else if (row.gender == "02") { return "女"; } }}, {display : '职务',name : 'position',width : '12%'} ], url : url, pageSize : 10, rownumbers : true, pageParmName : "curNo", pagesizeParmName : "curSize" }); $("#pageloading").hide(); } // 根据用户名称或者真实姓名模糊查询用户信息 function doSearch() { var roleId = $("#roleId").val(); var userName = $("#userName").val(); var realName = $("#realName").val(); var url = "../sysRole/findUserList.shtml?roleId="+roleId+"&userName=" + userName + "&realName="+ realName; findUserList(url); } //保存添加的用户信息 function forSaveUserToRole() { var rowsdata = gridManager.getCheckedRows(); if (rowsdata.length != 0) { var str = ""; $(rowsdata).each(function() { str += this.userId + ","; }); $.ajax( { url : "../sysRole/addUserToRole.shtml?userIds=" + str + "&roleId=" + $("#roleId").val(), type : "POST", async : false, dataType : "json", success : function(result) { var falg = result.msg; if (falg == 'success') { $.ligerDialog.success("操作成功!"); parent.reload($("#roleId").val()); } else { $.ligerDialog.error("操作失败"); } }, error : function(error) { $.ligerDialog.error("服务器操作异常"); } }); } else { $.ligerDialog.warn("请选择行"); } }
import React from 'react' import {render} from 'react-dom' import {Provider} from 'react-redux' import {Router, browserHistory} from 'react-router' import configureStore from './store' import { syncHistoryWithStore } from 'react-router-redux' import {routes} from './routes' const store = configureStore() const history = syncHistoryWithStore(browserHistory, store) window._reduxStore = store; Meteor.startup(() => { render( <Provider store={store}> <Router history={history}> {routes} </Router> </Provider>, document.getElementById('app') ) })
//import { } from '../api/db_nosql/controllers/.....'; export default { Query: { anyQuery: (_,args) => 'DATO DE RESPUESTA SERVER GRAPHQL http://localhost:3000/graphql', }, Mutation: { anyMutation: (_, { parameter }) => 'result mutation', } };
import React from 'react'; import Jumbotron from 'react-bootstrap/Jumbotron'; import Container from 'react-bootstrap/Container'; import Button from 'react-bootstrap/Button'; import Form from 'react-bootstrap/Form'; import { useState, useEffect } from "react"; import { Alert } from 'react-bootstrap'; import axios from 'axios'; import "./Preferences.css"; function Preferences() { const [budget, setBudget] = useState(""); const [time, setTime] = useState('Morning'); const [length, setLength] = useState(""); const [type, setType] = useState('Hotel'); const [rating, setRating] = useState(0); const [transport, setTransport] = useState('Flight'); const [pref, setPref] = useState({}); const [show, setShow] = useState(false); const handleSubmit = (e) => { e.preventDefault(); let prefData = new Object(); prefData.budget = budget; prefData.time = time; prefData.length = length; prefData.type = type; prefData.rating = rating; prefData.transport = transport; let prefString = JSON.stringify(prefData); axios({ method: "post", url: "http://localhost:4000/api/preferences", data: prefString, headers: {"Content-Type": "application/json", Authorization: `JWT ${localStorage.getItem('JWT')}`} }) .then(function(res){ console.log("data saved!"); }) .catch(function(res) { console.log(res); }); setShow(true); } useEffect(() => { axios({ method: "GET", url: "http://localhost:4000/api/preferences", headers: { "Content-Type": "application/json", Authorization: `JWT ${localStorage.getItem('JWT')}` } }).then(user => { setPref(user.data); }); }, []); let showSaved = null; if (show === true) { showSaved = <Alert variant="success" onClose={() => setShow(false)} dismissible>Preferences submitted.</Alert>; } function showPref(a) { if (a !== null) { return ( <div> <p className="preference">These are your current preferences:</p> <ul className="preference"> <li>Trip Budget: ${a.budget}</li> <li>Departure Time: {a.time}</li> <li>Duration (days): {a.length}</li> <li>Stay Type: {a.type}</li> <li>Stay rating: {a.rating}</li> <li>Transportation: {a.transport}</li> </ul> </div> ) } else { return ( <p className="nopref">You currently did not set up preferences!</p> ); } } return ( // Container with padding <Container> <h3>Trip Preferences</h3> <br /> {showPref(pref)} {showSaved} <Form onSubmit={e => { handleSubmit(e) }}> <Form.Group controlId="TripBudget"> <Form.Label>Trip Budget</Form.Label> <Form.Control size="sm" type="text" placeholder="$" value={budget} onChange={e => { setBudget(e.target.value) }} /> </Form.Group> <Form.Group controlId="DepartureTime"> <Form.Label>Departure Time</Form.Label> <Form.Control size="sm" as="select" value={time} onChange={e => { setTime(e.target.value) }} > <option>Morning</option> <option>Afternoon</option> <option>Evening</option> <option>Night</option> <option>Red-Eye</option> </Form.Control> </Form.Group> <Form.Group controlId="Duration"> <Form.Label>Duration</Form.Label> <Form.Control size="sm" type="text" placeholder="Number of Nights" value={length} onChange={e => { setLength(e.target.value) }} /> </Form.Group> <Form.Group controlId="StayType"> <Form.Label>Stay Type</Form.Label> <Form.Control size="sm" as="select" value={type} onChange={e => { setType(e.target.value) }}> <option>Hotel</option> <option>Apartment</option> <option>Home Stay</option> <option>Hostel</option> </Form.Control> </Form.Group> <Form.Group controlId="Rating"> <Form.Label>Stay Rating</Form.Label> <Form.Control size="sm" as="select" value={rating} onChange={e => { setRating(e.target.value) }}> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </Form.Control> </Form.Group> <Form.Group controlId="Transportation"> <Form.Label>Transportation</Form.Label> <Form.Control size="sm" as="select" value={transport} onChange={e => { setTransport(e.target.value) }}> <option>Flight</option> <option>Train</option> <option>Bus</option> <option>Personal</option> </Form.Control> </Form.Group> <div class="col-sm-12 text-center"> <Button type="submit" className="buttons">Confirm</Button> <Button href='/profile' className="buttons">Back to Profile</Button> </div> </Form > </Container > ); } export default Preferences;
/* * Copyright 2014 Jive Software * * 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. */ /** * This object is a pure service for the StrategySetBuilder. It handles the storage of * GitHubFacade handler tokens. It is a simple and general wrapper on a hash. Thus, it * can be used for other purposes but at time of writing (9/8/2014) it is only used for * the builder. * * Keys can be any string except null empty or contain whitespace. */ function TokenPool(){ this.tokens = {}; } exports.INVALID_KEY = "INVALID_TOKEN_KEY"; exports.INVALID_TOKEN = "INVALID_TOKEN"; exports.DUPLICATE_KEY = "DUPLICATE_TOKEN_KEY"; /** * Add token to pool with unique key. * @param {string} key the unique key to identify the token in this pool. Must not be null, empty or contain whitespace * @param {object} token the thing that the key identifies. Must not be null. Just a string in Set Buolder */ TokenPool.prototype.addToken = function (key, token) { if(!key || key.match(/\s+/) ){ throw Error(this.INVALID_KEY); } if(this.tokens[key]){ throw Error(this.DUPLICATE_KEY); } if(!token){ throw Error(this.INVALID_TOKEN); } this.tokens[key] = token; }; /** * This is pretty self explanatory * @param string key the key that identifies the token * @return object the token object identified by the key. */ TokenPool.prototype.getByKey = function (key) { return this.tokens[key] || false; }; /** * This is pretty self explanatory * @param string key the key that identifies the token * @return boolean true if the key was successfully deleted. Only fails is the delete keyword fails or if the key does not exist */ TokenPool.prototype.removeTokenByKey = function (key) { return (delete this.tokens[key]); }; /** * @return {[string]} Returns an array of all the keys that are currently in the pool. */ TokenPool.prototype.tokenKeys = function () { return Object.keys(this.tokens); }; /** * @return {[object]} Returns all token objects currently in the pool. Does not return key with it. */ TokenPool.prototype.allTokens = function () { var self = this; return this.tokenKeys().map(function (key) { return self.tokens[key]; }); }; module.exports = TokenPool;
var helicopterIMG, helicopterSprite, packageSprite,packageIMG; var packageBody,ground const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; function preload() { helicopterIMG=loadImage("helicopter.png") packageIMG=loadImage("package.png") } function setup() { createCanvas(800, 700); rectMode(CENTER); engine = Engine.create(); world = engine.world; packageSprite=createSprite(width/2, 80, 10,10); packageSprite.addImage(packageIMG) packageSprite.scale=0.2 helicopterSprite=createSprite(width/2, 200, 10,10); helicopterSprite.addImage(helicopterIMG) helicopterSprite.scale=0.6 bottom = createSprite(400, 650, 200, 20); bottom.shapeColor = ("red"); rightWall = createSprite(500, 610, 20, 100); rightWall.shapeColor = ("red"); leftWall = createSprite(300, 610, 20, 100); leftWall.shapeColor = ("red"); groundSprite=createSprite(width/2, height-35, width,10); groundSprite.shapeColor=color(255) packageBody_options = { restitution : 0 } packageBody = Bodies.circle(width/2 , 200 , 5, packageBody_options); World.add(world, packageBody); Matter.Body.setStatic(packageBody,true); bottomBody = Bodies.rectangle(400, 630, 200, 20, {isStatic:true}) World.add(world, bottomBody); leftBody = Bodies.rectangle(320, 610, 20, 100, {isStatic:true}) World.add(world, leftBody); rightBody = Bodies.rectangle(480, 610, 20, 100, {isStatic:true}) World.add(world, rightBody); //Create a Ground ground = Bodies.rectangle(width/2, 650, width, 10 , {isStatic:true}); World.add(world, ground); Engine.run(engine); } function draw() { Engine.update(engine); background(0); rectMode(CENTER); packageSprite.x = packageBody.position.x packageSprite.y = packageBody.position.y //keyPressed(); drawSprites(); } function keyPressed() { if (keyCode === DOWN_ARROW) { Matter.Body.setStatic(packageBody,false); } }
import axios from "axios"; import { FETCH_BANNERS } from "../constants/banners"; export const fetchBanners = () => (dispatch) => { axios .get("http://localhost:4200/banners") .then((res) => dispatch({ type: FETCH_BANNERS, payload: res.data })) .catch((err) => console.error(err)); };
import React from 'react'; import PropTypes from 'prop-types'; import Timestamp from 'react-timestamp'; import styled from 'styled-components'; import { colors } from '../utils'; import { Icon, BigLabel } from '../elements'; const RevisionListItem = ({ title, number, mergeable, createdAt, author }) => ( <QuickRevision> <Icon name="revisions" /> <div> <RevisionTitle>{title}</RevisionTitle> <RevisionDesc> {number} opened <Timestamp time={createdAt} /> by {author.login} </RevisionDesc> </div> <RevisionLabel pass>{mergeable.toLowerCase()}</RevisionLabel> </QuickRevision> ); RevisionListItem.defaultProps = { title: 'revision descriptiom', author: 'author', number: 0, mergeable: 'Mergeable', createdAt: '2018-08-23T09:27:37Z', }; RevisionListItem.propTypes = { title: PropTypes.string, author: PropTypes.object, number: PropTypes.number, mergeable: PropTypes.string, createdAt: PropTypes.string, }; const QuickRevision = styled.div` display: grid; grid-template-columns: 24px auto 148px; grid-gap: 12px; border-bottom: 1px solid ${colors.lightGrey}; padding: 16px; &:last-child { border-bottom: none; } `; const RevisionTitle = styled.h3` font-family: GTAmericaMedium; margin: 4px 0 6px 0; max-width: 300px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; height: 22px; `; const RevisionDesc = styled.p` color: ${colors.grey}; max-width: 300px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; height: 22px; `; const RevisionLabel = styled(BigLabel)` align-self: center; `; export default RevisionListItem;
TRAFFIC.Curve = function (_at_A, _at_B, _at_O, _at_Q) { this.A = _at_A; this.B = _at_B; this.O = _at_O; this.Q = _at_Q; this.AB = new TRAFFIC.Segment(this.A, this.B); this.AO = new TRAFFIC.Segment(this.A, this.O); this.OQ = new TRAFFIC.Segment(this.O, this.Q); this.QB = new TRAFFIC.Segment(this.Q, this.B); this._length = null; Object.defineProperty(this, 'length', { get: function() { var i, point, pointsNumber, prevoiusPoint, _i; if (this._length == null) { pointsNumber = 10; prevoiusPoint = null; this._length = 0; for (i = _i = 0; 0 <= pointsNumber ? _i <= pointsNumber : _i >= pointsNumber; i = 0 <= pointsNumber ? ++_i : --_i) { point = this.getPoint(i / pointsNumber); if (prevoiusPoint) { this._length += point.subtract(prevoiusPoint).length; } prevoiusPoint = point; } } return this._length; } }); } TRAFFIC.Curve.prototype = { constructor: TRAFFIC.Curve, getPoint : function(a) { var p0, p1, p2, r0, r1; p0 = this.AO.getPoint(a); p1 = this.OQ.getPoint(a); p2 = this.QB.getPoint(a); r0 = (new TRAFFIC.Segment(p0, p1)).getPoint(a); r1 = (new TRAFFIC.Segment(p1, p2)).getPoint(a); return (new TRAFFIC.Segment(r0, r1)).getPoint(a); }, getDirection : function(a) { var p0, p1, p2, r0, r1; p0 = this.AO.getPoint(a); p1 = this.OQ.getPoint(a); p2 = this.QB.getPoint(a); r0 = (new TRAFFIC.Segment(p0, p1)).getPoint(a); r1 = (new TRAFFIC.Segment(p1, p2)).getPoint(a); return (new TRAFFIC.Segment(r0, r1)).direction; } }
/*jshint esversion: 6*/ /** * heartData is the real-sample heart data * StepsData is the real-sample steps data */ const heartData = require("../sampleData/allHeartRate.json"); const stepsData = require("../sampleData/allSteps.json"); const serialProcessor = (request,response)=>{ try{ console.time("serial"); const spikeCounter = getSpikes(heartData.value).length; const heartAvg = heartData.value.reduce((acc, value)=>acc+value.heartRate,0); const obj = { spikeCounter :spikeCounter, heartAvg : heartAvg/heartData.value.length }; response.status(200).send(obj); console.timeEnd("serial"); }catch(e){ console.log(e); response.status(500).send(e); } }; //spike(the heartrate wich is very high than the desired one) filtering const getSpikesFilter = (element) => element.heartRate <= 55 || element.heartRate >= 100 ? element : null; //filters only spike values const getSpikes = (heartData) => { return heartData.filter(getSpikesFilter); }; module.exports={ serialProcessor : serialProcessor };
import React from "react"; import ClaimPanel from "../../../UI/ProofWrapper/ClaimPanel/ClaimPanel"; import MN from "../../../UI/MathJaxNode/MathJaxNode"; const headingTitle = "Důkaz 1"; const breadcrumbsCurrent = "Důkazy přímo"; const stepSum = 7; const claimPanel = ( <ClaimPanel> Dokažte přímo:{" "} <cite> <q> {" "} <MN>\forall G=(V,E)</MN>: Nechť <MN>G</MN> je souvislý graf. Jestliže hrana <MN>e</MN> není most v <MN>G</MN>, pak v <MN>G</MN> existuje kružnice obsahující hranu <MN>e</MN>. </q>{" "} </cite> </ClaimPanel> ); const proofStepPanels = [ { name: "proofStepPanel1", activeForSteps: [1], content: ( <p> Pokud <MN>{"e=\\{x,y\\}"}</MN> není most v <MN>G</MN>, poté z definice mostu platí, že graf <MN>G-e</MN> má stejný počet komponent jako{" "} <MN>G</MN>. </p> ) }, { name: "proofStepPanel2", activeForSteps: [2, 3], content: ( <p> Protože uvažujeme souvislý graf <MN>G</MN>, musí mezi libovolně zvolenými vrcholy <MN>u</MN> a <MN>v</MN> existovat cesta. </p> ) }, { name: "proofStepPanel3", activeForSteps: [4], content: ( <p> Když existuje <MN>u</MN>-<MN>v</MN> cesta <MN>{"P_{uv}"}</MN> v{" "} <MN>G</MN>, tak existuje <MN>u</MN>-<MN>v</MN> cesta{" "} <MN>{"P'_{uv}"}</MN> v <MN>G-e</MN>. (Uvažujeme totiž stále hranu{" "} <MN>e</MN>, která není mostem.) <br /> <br /> Poznámka: <MN>{"P'_{uv}"}</MN> se nemusí nutně <MN>{"=P_{uv}"}</MN>. </p> ) }, { name: "proofStepPanel4", activeForSteps: [5], content: ( <p> Z toho vyplývá, že v <MN>G-e</MN> musí v existovat také cesta{" "} <MN>{"P_{xy}"}</MN> mezi vrcholy <MN>x</MN> a <MN>y</MN> z hrany{" "} <MN>e</MN>. </p> ) }, { name: "proofStepPanel5", activeForSteps: [6], content: ( <p> Protože <MN>G</MN> vznikne z <MN>G-e</MN> přidáním hrany <MN>e</MN>, musí se <MN>x</MN>-<MN>y</MN> cesta <MN>{"P_{xy}"}</MN> nacházet také v{" "} <MN>G</MN>. </p> ) }, { name: "proofStepPanel6", activeForSteps: [7], content: ( <div> <p> Pak podle definice kružnice platí, že cesta <MN>{"P_{xy}"}</MN> spolu s hranou <MN>{"e=\\{x,y\\}"}</MN> tvoří v <MN>G</MN> kružnici obsahující hranu <MN>e</MN>. </p> <p className="text-center"> Tím je dokázáno stanovené tvrzení. <MN>\Box</MN> </p> </div> ) } ]; const descriptionPanels = [ { id: 1, showForSteps: [1], content: ( <p> Sestrojení příkladu souvislého grafu <MN>G</MN>, kde existuje hrana{" "} <MN>e</MN>, která není most. </p> ) }, { id: 2, showForSteps: [2], content: ( <p> Zvolení libovolných vrcholů <MN>u</MN> a <MN>v</MN>. </p> ) }, { id: 3, showForSteps: [3], content: ( <p> Příklad sestrojení <MN>u</MN>-<MN>v</MN> cesty <MN>{"P_{uv}"}</MN> v grafu <MN>G</MN>. </p> ) }, { id: 4, showForSteps: [4], content: ( <p> Vlevo předchozí příklad <MN>u</MN>-<MN>v</MN> cesty <MN>{"P_{uv}"}</MN>{" "} v grafu <MN>G</MN>. <br /> Vpravo příklad <MN>u</MN>-<MN>v</MN> cesty <MN>{"P'_{uv}"}</MN> v grafu{" "} <MN>G-e</MN>. </p> ) }, { id: 5, showForSteps: [5], content: ( <p> <MN>x</MN>-<MN>y</MN> cesta <MN>{"P_{xy}"}</MN> v grafu <MN>G-e</MN> </p> ) }, { id: 6, showForSteps: [6], content: ( <p> <MN>x</MN>-<MN>y</MN> cesta <MN>{"P_{xy}"}</MN> v grafu <MN>G</MN> </p> ) }, { id: 7, showForSteps: [7], content: ( <p> Cesta <MN>{"P_{xy}"}</MN> spolu s hranou <MN>{"e=\\{x,y\\}"}</MN> tvoří kružnici v <MN>G</MN> obsahující hranu <MN>e</MN>. </p> ) } ]; const definitionPanels = [ { id: 1, showForSteps: [1], content: ( <div> <p> DEFINICE MOSTU (1.11) <br /> Nechť je dán graf <MN>G=(V,E)</MN>, vrchol <MN>v \in V</MN> a hrana{" "} <MN>e \in E</MN>. </p> <p> Hrana <MN>e</MN> je most grafu <MN>G</MN>, jestliže graf <MN>G-e</MN>{" "} má více komponent než graf <MN>G</MN>. </p> </div> ) }, { id: 2, showForSteps: [2, 3], content: ( <div> <p> DEFINICE SOUVISLÉHO GRAFU (1.9) <br /> Souvislý graf je graf, ve kterém mezi každými jeho dvěma vrcholy existuje cesta. </p> </div> ) }, { id: 3, showForSteps: [7], content: ( <div> <p> KRUŽNICE (Definice 1.8) <br /> Kružnice délky <MN>k, k \geq 3</MN>, v grafu <MN>G</MN> je posloupnost{" "} <MN>{"(v_{0}, e_{1}, v_{1},...,e_{k}, v_{0})"}</MN>, kde{" "} <MN>{"e_{i}=\\{v_{i-1}, v_{i}\\}"}</MN>, <MN>i=1,...,k-1</MN>,{" "} <MN>{"e_{k}=\\{v_{k-1}, v_{0}\\}"}</MN> a pro <MN>i \neq j</MN> platí{" "} <MN>{"v_{i} \\neq v_{j}"}</MN>. </p> </div> ) } ]; const cameraPosition0 = { position: { x: 0, y: -10 }, scale: 1.5, animation: { duration: 1500, easingFunction: "easeInOutQuad" } }; const cameraPosition1 = { position: { x: 170, y: -10 }, scale: 0.82, animation: { duration: 1000, easingFunction: "easeInOutQuad" } }; const cameraPosition2 = { position: { x: 400, y: -10 }, scale: 1.5, animation: { duration: 4000, easingFunction: "easeInOutQuad" } }; export const constants = { headingTitle: headingTitle, breadcrumbsCurrent: breadcrumbsCurrent, stepSum: stepSum, claimPanel: claimPanel, proofStepPanels: proofStepPanels, descriptionPanels: descriptionPanels, definitionPanels: definitionPanels }; export const cameraPositions = [ cameraPosition0, cameraPosition1, cameraPosition2 ];
import React, { useState } from "react"; import styled from "styled-components"; import { search } from "../../store/actions"; import { connect } from "react-redux"; const SearchInput = styled.input` padding: 1em; margin-bottom: 1em; background: #ebebeb; border: none; border-radius: 30px; width: 100%; `; const Search = ({ doSearch }) => { const [searchTerm, setSearchTerm] = useState(""); const buscar = (e) => { e.preventDefault(); doSearch(searchTerm); }; return ( <> <form onSubmit={buscar}> <SearchInput type="text" placeholder="Busque um filme por nome, ano ou gênero" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} /> </form> {/* <button onClick={buscar}>Pesquisar</button> */} </> ); }; const mapDispatchToProps = (dispatch) => ({ doSearch: (searchTerm) => dispatch(search(searchTerm)), }); export default connect(null, mapDispatchToProps)(Search);
import React from 'react' function Allergies(props) { let allergy=props.allergy.map((ele)=>{ return ( <div key={ele.id} className="app-card"> <span> {ele.allergy} </span> <div className="app-card__subtext days-left"> {ele.triggers} </div> </div> ) }) return ( <div> <div className="content-section-title">Common &amp; Medication Allergies</div> <div className="apps-card"> {allergy} </div> </div> ) } export default Allergies
let tours = document.querySelectorAll('.all-inclusive__element-tour'); let hotels = document.querySelectorAll('.all-inclusive__element-hotels'); let store = []; let topText = document.querySelector('.slider__headline-top'); let bottomText = document.querySelector('.slider__headline-bottom'); let sliderTexts = [ { top: 'Відкривай', bottom: 'Україну 365' }, { top: 'Відкривай', bottom: 'Карпати 365' }, { top: 'Відкривай', bottom: 'Черкаси 365' } ]; let valText = 1; let valTextPrev = 2; sliderNext = () => { if (valText === sliderTexts.length) { valText = 0; } topText.innerHTML = sliderTexts[valText].top; bottomText.innerHTML = sliderTexts[valText].bottom; valText++; }; sliderPrev = () => { if (valTextPrev === -1) { valTextPrev = 2; } topText.innerHTML = sliderTexts[valTextPrev].top; bottomText.innerHTML = sliderTexts[valTextPrev].bottom; valTextPrev--; }; next = (elem) => { storeSave(elem); for (let i = elem.length, k = 0, j = 1; i > 0; i--, k++, j++) { if( j === store.length ) { j = 0; } elem[j].innerHTML = store[k] } }; prev = (elem) => { storeSave(elem); for (let i = elem.length, k = 1, j = 0; i > 0; i--, k++, j++) { if( k === store.length ) { k = 0; } elem[j].innerHTML = store[k] } }; storeSave = (st) => { for (let i = st.length, k = 0; i > 0; i--, k++) { store[k] = $(st[k]).html() } };
"use strict"; function ViewModel() { var self, map, geocoder, infoWindow, wikiUrl, infoPane; self = this; map = new google.maps.Map(document.getElementById("map"), { center: {lat: 34.033222, lng: -84.4709025}, zoom: 12 }); self.pins = ko.observableArray([]); geocoder = new google.maps.Geocoder(); infoWindow = new google.maps.InfoWindow(); infoPane = document.getElementById("info-pane"); wikiUrl = "https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&origin=*"; self.query = ko.observable(""); self.infoPaneText = ko.observable(""); // map pins setup - instantiation, event listeners, Wikipedia link for(var marker of markers) { var markerInstance = createMapPin(marker, map); // This needs to be set outside the instantiation // above in order to work properly if(markerInstance) { markerInstance.title = marker.title; } self.pins.push(markerInstance); google.maps.event.addListener(markerInstance, "mouseover", openInfoWindow); google.maps.event.addListener(markerInstance, "mouseout", closeInfoWindow); google.maps.event.addListener(markerInstance, "click", loadAndOpenInfoPane); infoPane.getElementsByClassName("close")[0].addEventListener("click", closeInfoPane); } // Create map pin function createMapPin(pinDataSource, targetMap) { if("coords" in pinDataSource && "gm_accessors_" in map) { return new google.maps.Marker({ map: targetMap, position: {lat: pinDataSource.coords.lat, lng: pinDataSource.coords.lng}, animation: google.maps.Animation.DROP, }); } // Error handling if argument(s) is/are invalid alert("There was a problem loading the map pins.") } // Open Google Maps' infoWindow function openInfoWindow() { infoWindow.setContent(this.title); infoWindow.open(map, this); } // close Google Maps' infoWindow function closeInfoWindow() { infoWindow.close(); } // load and open infoPane function loadAndOpenInfoPane() { var latLng = new google.maps.LatLng(this.position.lat(), this.position.lng()); var closureTitle = this.title; // bounce pin this.setAnimation(google.maps.Animation.BOUNCE); setTimeout((function() { this.setAnimation(null); }).bind(this), 1000); // get address from pin's lat-lng geocoder.geocode({location: latLng}, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { if(results[0]) { // get Wikipedia link fetch(wikiUrl + "&titles=" + closureTitle) .then(function(response) { return response.json(); }) .then(function(data) { // we got a valid Wikipedia ID if(data.query.pages[0].pageid) { self.infoPaneText(` <h3 class="location-name">${closureTitle}</h3> <div class="location-address">${results[0].formatted_address}</div> <div class="wiki-link"><a href="https://en.wikipedia.org/?curid=${data.query.pages[0].pageid}" target="_blank">Wikipedia</a></div> `); } // we didn't get a valid Wikipedia ID else { self.infoPaneText(` <h3 class="location-name">${closureTitle}</h3> <div class="location-address">${results[0].formatted_address}</div> <div class="wiki-link">A Wikipedia link was not found for this location</div> `); } }) .catch(function(error) { // the request itself failed e.g. network error self.infoPaneText(` <h3 class="location-name">${closureTitle}</h3> <div class="location-address">${results[0].formatted_address}</div> <div class="wiki-link">Unable to fetch Wikipedia link</div> `); }); infoPane.classList.add("open"); } } }); } // populate infoPane self.populateInfoPane = ko.computed(function() { return self.infoPaneText(); }); // close infoPane function closeInfoPane() { infoPane.classList.remove("open"); } // trigger pin when matching list item is clicked self.triggerClickOnPin = function(data, event) { var matchingPin = self.pins().filter(function(pin) { return pin.title.toLowerCase() === data.title.toLowerCase(); })[0]; if(matchingPin) { google.maps.event.trigger(matchingPin, "click"); } } // filter pins and locations list self.filteredPins = ko.computed(function() { // filter pins filterPins(); // filter locations list if(!self.query()) { return self.pins(); } return self.pins().filter(function(pin) { return pin.title .toLowerCase() .includes(self.query() .trim() .toLowerCase()); }); }); // filter pins function filterPins() { for(var pin of self.pins()) { if(pin.title.toLowerCase().includes(self.query().trim().toLowerCase())) { pin.setVisible(true); } else { pin.setVisible(false); } } } console.log("🎉 Map initialized. 🎉"); } function mapError() { window.alert("Map could not be initialized."); } function initMap() { ko.applyBindings(new ViewModel()); }
import React from "react"; import { Route, Router } from "react-router-dom"; import history from "../history"; const App = () => { return ( <Router history={history}> <div className="app">App Component</div> </Router> ); }; export default App;
import React from 'react'; import { Alert } from '@material-ui/lab'; const Error = ({ msg }) => { return ( <Alert style={{ margin: "0 10%" }} severity="error">{msg}</Alert> ) } export default Error
import React, {Component} from 'react' import AppHeader from "./app-header"; import PostAddForm from "./post-add-form"; import PostList from "./post-list/post-list"; import SearchPanel from "./search-panel/search-panel"; import './todo-list.css' import PostStatusFilter from "./post-status-filter/post-status-filter"; import {connect} from "react-redux"; import {bindActionCreators} from "redux"; import {filterPost, searchPost} from "../../actions/postActions"; export class TodoList extends Component { render() { console.log(this.props) const {posts, filter, filtered, term, isChanged, searchPost, filterPost, postValue} = this.props; const countLike = posts.filter(item => item.like).length; const countPost = posts.length; const filteredPosts = isChanged ? filtered : posts; return ( <div className="container"> <AppHeader countLike={countLike} countPost={countPost}/> <div className="search-panel d-flex"> <SearchPanel filter={filter} searchValue={term} onUpdateSearch={searchPost}/> <PostStatusFilter filter={filter} data={filteredPosts} onFilterSelect={filterPost}/> </div> <PostList posts={filteredPosts} /> <PostAddForm postValue={postValue} /> </div> ) } // } } const mapStateToProps = (state) => { console.log(state) const {posts, filter, filtered, term, isChanged, postValue} = state.postReducer return { posts, filter, filtered, term, isChanged, postValue } } const mapDispatchToProps = (dispatch) => { console.log(dispatch) return bindActionCreators({ searchPost, filterPost }, dispatch) } export default connect(mapStateToProps, mapDispatchToProps)(TodoList);
const ConnectionInfoController = require("../controleur/connectionInfo"); const MiddlewareId = require("../Middleware/Authorization"); const MiddlewareAuth = require("../Middleware/jwtAuth"); const Router = require("express-promise-router"); const router = new Router; router.get('/getAllPseudos', MiddlewareAuth.identification, MiddlewareId.mustbeAdmin, ConnectionInfoController.getAllPseudo); module.exports = router;
import { createMaterialBottomTabNavigator } from "react-navigation-material-bottom-tabs"; import { createAppContainer } from "react-navigation"; import MainScreen from "../screens/MainScreen"; import AboutScreen from "../screens/AboutScreen"; import FavoritsScreen from "../screens/FavoritsScreen"; import SettingsScreen from "../screens/SettingsScreen"; import ColorDetails from '../screens/ColorDetails'; import React from 'react'; import {Image} from 'react-native'; import { createStackNavigator } from 'react-navigation-stack'; const HomeNavigator = createStackNavigator( { Home: {screen: MainScreen}, Details: {screen: ColorDetails}, }, { initialRouteName: 'Home', defaultNavigationOptions: { headerStyle: { backgroundColor: '#423F3F' }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold' } } }); const TabNavigator = createMaterialBottomTabNavigator({ MainScreen: { screen: HomeNavigator, navigationOptions:{ tabBarLabel: 'Home', tabBarIcon: ({tintColor}) => ( <Image source={require('../assets/home.png')} style={{width:28 , height: 28}} /> //<Icon color={"#FFFFFF"} size={20} name={'image'} /> ), barStyle: { backgroundColor: '#2B2626' } } }, FavoritsScreen: { screen: FavoritsScreen, navigationOptions:{ tabBarLabel: 'Favorits', tabBarIcon: ({tintColor}) => ( //<Icon2 color={"#FFFFFF"} size={20} name={'heart'} /> <Image source={require('../assets/favorits.png')} style={{width:28 , height: 28}} /> ), barStyle: { backgroundColor: '#2B2626' } } }, SettingsScreen: { screen: SettingsScreen, navigationOptions:{ tabBarLabel: 'Settings', tabBarIcon: ({tintColor}) => ( //<Icon3 color={"#FFFFFF"} size={20} name={'pencil'} /> <Image source={require('../assets/edit.png')} style={{width:28 , height: 28}} /> ), barStyle: { backgroundColor: '#2B2626' } } }, AboutScreen: { screen: AboutScreen, navigationOptions:{ tabBarLabel: 'About', tabBarIcon: ({tintColor}) => ( //<Icon4 color={"#FFFFFF"} size={20} name={'info-circle'} /> <Image source={require('../assets/about.png')} style={{width:28 , height: 28}} /> ), barStyle: { backgroundColor: '#2B2626' }, } } }, { initialRouteName: 'MainScreen' } ); export default createAppContainer(TabNavigator);
/**class pessoa { constructor(nome){ this.nome = nome } falar() { console.log(`Meu nome é ${this.nome}`) } } const p1 = new pessoa('Nicolas') p1.falar() */ function pessoa(nome){ this.nome = nome // Pode ser com essa linha comentada, a unica diferença é que, se comentada a linha 23 não vai achar o nome this.Criador = () => console.log(`Meu nome é ${nome}`) } const p1 = new pessoa('Nicolas') p1.Criador() console.log(p1.nome)
const assert = require("assert"); const chai = require("chai"); const chaiHttp = require("chai-http"); const server = require("../server"); const should = chai.should(); chai.use(chaiHttp); describe("Records", function() { this.timeout(10000); describe("Get records", function() { it('should return records with specified date and count range', function(done) { chai.request(server) .post("/getRecords") .send({ "startDate": "2017-01-26", "endDate": "2017-02-02", "minCount": 100, "maxCount": 1000 }) .end((err, res) => { if (err) done(err); res.should.have.status(200); done() }) }) }) });
$(function(){ console.log("Main init called"); init(); }); function InitFilesRankBrd() { // initializing files and rank board... for(var i=0;i<BRD_SQ_NUM;i++){ FilesBrd[i] = SQUARES.OFFBOARD; RanksBrd[i] = SQUARES.OFFBOARD; } for(var rank=RANKS.RANK_1;rank <= RANKS.RANK_8 ; rank++){ for(var file=FILES.FILE_A; file < FILES.FILE_H; file++){ pos = FR2SQ(file, rank); FilesBrd[pos] = file; RanksBrd[pos] = rank; } } } function init(){ console.log("init() Called"); }
const socket = io() let messages = document.getElementById("message_list") let message_box = document.getElementById("message_box") let users_connected = document.getElementById("users_connected") socket.on('message', data => { let li = document.createElement('li') if (data.enableHTML) { li.innerHTML = data.nick + ": " + data.msg } else { li.textContent = data.nick + ": " + data.msg } messages.appendChild(li) }) socket.on('update_users', users => { let str = "Users connected: " for (let element in users) { str += users[element] + ", " } users_connected.textContent = str }) let nick = prompt("Enter your nick:") while (nick == null || nick == undefined || nick == "Server" || !/[a-zA-Z0-9]{3,}/.test(nick)) nick = prompt("Enter your nick: (3 or more alphanumeric characters)") socket.emit('login', { nick: nick }) message_box.focus() function sendMessage() { socket.emit('send_message', message_box.value) message_box.value = "" }
// 招投标 require('./PageTendering.less'); import { Component, LogicRender } from 'refast'; import { Tabs, WhiteSpace , WingBlank, Badge, SearchBar, List } from 'antd-mobile'; import logic from './PageLogic'; import { Link } from 'react-keeper'; // import SearchBarMine from '../../components/searchBar/searchbar'; import mydingready from './../../dings/mydingready'; const { AUTH_URL , IMGCOMMONURI } = require(`config/develop.json`); const TabPane = Tabs.TabPane; const Item = List.Item; class Tendering extends Component { constructor(props) { super(props, logic); mydingready.ddReady({pageTitle: '招投标'}); } componentDidMount () { this.getTenderingList({state: 'CHECKING'}); // this.autoFocusInst.focus(); } /** * 发送自定义事件(设置state) */ dispatchFn = (val) => { this.dispatch('setStateData',val) } /** * 获取招投标列表 */ getTenderingList = ({state ,searchWord }) => { let userId = mydingready.globalData.userId ? mydingready.globalData.userId : localStorage.getItem('userId'); let url = searchWord ? `${AUTH_URL}bidding/gain/type?state=${state}&userId=${userId}&searchWord=${searchWord}&pageNum=1&pageSize=1000` : `${AUTH_URL}bidding/gain/type?state=${state}&userId=${userId}&pageNum=1&pageSize=1000` fetch(url) .then(res => res.json()) .then(data => { if (data.state == 'SUCCESS') { this.dispatchFn({listData: data.values.biddings.list}); this.dispatchFn({ pageInfo: { pageNum: 1, pageSize: 1000, searchWord: '', // CHECKING-待审核;PASS-通过;REBUT-驳回; state: state, userId: null }, }); /* dd.device.notification.toast({ icon: 'success', //icon样式,有success和error,默认为空 text: '数据加载成功', //提示信息 duration: 1, //显示持续时间,单位秒,默认按系统规范[android只有两种(<=2s >2s)] });*/ return } }) } /** * 搜索 */ goSearch = (val) => { console.log('文本框内容',val,this.state.searchVal) let { pageInfo , } = this.state; this.getTenderingList({ state: pageInfo.state, searchWord: val }) } /* * 离焦 */ searchBlur = (e) => { this.dispatch('setSearchVal',''); } /** * 文本输入变化 */ searchChange = (e) => { this.dispatch('setSearchVal',e); } render() { const { tabs, searchVal ,listData} = this.state; const tabNode = tabs.forEach( (v,inx) => { return <span>{v.title}</span> }) let listCom = listData.map(v => { return <Link to={`/detailtendering/${v.biddingId}`} className="listBox"> <div className="list"> <div className="tenderingTitle"> <div>招投标名称</div> <span className="h2">{v.biddingName}</span> </div> <p>{v.content}</p> <div className="line"></div> <div className="tenderingDetail"> <span>审批人</span> <div className="flex"> <div className="blueBox_">{JSON.parse(v.approver)[0] ? JSON.parse(v.approver)[0].name : ''}</div> <img src={`${IMGCOMMONURI}common_level2_icon_bg_color.png`} /> </div> </div> </div> </Link> }) return ( <div className="tendering"> {/* 招投标页面 */} <Tabs tabs={tabs} initialPage={0} onChange={(tab, index) => this.getTenderingList({state: tab.state})} onTabClick={(tab, index) => console.log(tab.state)} > <div className="tabBody"> <SearchBar className="searchBox" placeholder="审批人/投标名称" value={searchVal} onSubmit={this.goSearch} onBlur={this.searchBlur} onChange={this.searchChange} /> {/*<Link to={`/detailtendering/72`} className="listBox"> <div className="list"> <div className="tenderingTitle"> <div>招投标名称</div> <span className="h2">v.biddingName</span> </div> <p>v.content</p> <div className="line"></div> <div className="tenderingDetail"> <span>审批人</span> <div className="flex"> <div className="blueBox_">JSON.parse(v.approver)[0].name</div> <img src={`${IMGCOMMONURI}common_level2_icon_bg_color.png`} /> </div> </div> </div> </Link>*/} {listData.length ? listCom : ''} </div> <div className="tabBody"> <SearchBar className="searchBox" placeholder="审批人/投标名称" value={searchVal} onSubmit={this.goSearch} onBlur={this.searchBlur} onChange={this.searchChange} /> <div> {listData.length ? listCom : ''} </div> </div> <div className="tabBody"> <SearchBar className="searchBox" placeholder="审批人/投标名称" value={searchVal} onSubmit={this.goSearch} onBlur={this.searchBlur} onChange={this.searchChange} /> <div> {listData.length ? listCom : ''} </div> </div> </Tabs> {/* 新增页面按钮 */} <Link type='img' src={`${IMGCOMMONURI}add_big.png`} className='addTenderingBtn' to={ '/addtendering' } /> </div> ); } } export default Tendering ;
import * as React from "react"; import PropTypes from "prop-types"; const HeroList = (props) => { // render() { const { children, items, message, clickExpand, clickCollapse } = props; const listItems = items.map((item, index) => ( <li className="ms-ListItem" key={index}> <i className={`ms-Icon ms-Icon--CollapseMenu`}></i> <span className="ms-font-m ms-fontColor-neutralPrimary">{item.name}</span> <button class="ms-Button ms-Button--hero" onClick={() => clickExpand(item.from, item.to)} > <span class="ms-Button-icon"><i class="ms-Icon ms-Icon--Add"></i></span> {/* <span class="ms-Button-label">Expand</span> */} </button> <button class="ms-Button ms-Button--hero" onClick={() => clickCollapse(item.from, item.to)} > <span class="ms-Button-icon"><i class="ms-Icon ms-Icon--CollapseContentSingle"></i></span> {/* <span class="ms-Button-label">Collapse</span> */} </button> </li> )); return ( <main className="ms-welcome__main"> <h2 className="ms-font-xl ms-fontWeight-semilight ms-fontColor-neutralPrimary ms-u-slideUpIn20">{message}</h2> <ul className="ms-List ms-welcome__features ms-u-slideUpIn10">{listItems}</ul> {children} </main> ); // } } HeroList.propTypes = { children: PropTypes.node, items: PropTypes.array, message: PropTypes.string, }; export default HeroList;
/** * Authors: Diego Ceresuela, Luis Jesús Pellicer, Raúl Piracés. * Date: 16-05-2016 * Name file: cron.js * Description: Start a cron to check the date of pending tweets * (send to Twitter API and refresh statics). */ (function () { var mongoose = require('mongoose'); var CronJob = require('cron').CronJob; var OAuth = require('./OAuth'); function startCron() { // Mongodb models. var Tweet = mongoose.model('tweets'); var TweetCommons = require('./tweets'); // Each minute. new CronJob('00 * * * * *', function () { var date = new Date(); Tweet.find({}, function (err, result) { for (var tweet in result) { var id_str = result[tweet].id_str; var user = {token: result[tweet].token, secret: result[tweet].secret, user: result[tweet].user}; // If date is bigger than tweet's date, post it. if (result[tweet].date <= date) { OAuth.initTwitterOauth(function(oa){ oa.post( "https://api.twitter.com/1.1/statuses/update.json" , result[tweet].token , result[tweet].secret // Tweet content , { "status": result[tweet].status } , function (error, data, response) { if (error) { console.log(error); } else { console.log("Cron sent tweet: " + JSON.stringify(data)); // Update statistics TweetCommons.updateStatistics(user,id_str,1); // Delete tweet from DB Tweet.findOneAndRemove({ _id: result[tweet].id, user: result[tweet].user }, function (err, tweet) { if (err) { console.log("Cannot delete " + "pending tweet"); } else if (tweet == null) { console.log("This pending " + "tweet doesn't exists"); } }); } } ); }); } } }); }, null, true, 'Europe/Madrid'); // timeZone } exports.startCron = startCron; })();
function attachEvents() { let sendButtonElement = document.getElementById('submit'); let refreshButtonElement = document.getElementById('refresh'); sendButtonElement.addEventListener('click', sendMessage); refreshButtonElement.addEventListener('click', getAllMessages); function sendMessage() { let author = document.querySelector('input[name="author"]') .value; let content = document.querySelector('input[name="content"]') .value; document.querySelector('input[name="author"]').value = ''; document.querySelector('input[name="content"]').value = ''; fetch('http://localhost:3030/jsonstore/messenger', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ author, content }) }) .then(res => res.json()) .then(res => console.log(res)) .catch(err => console.log(err)); } async function getAllMessages() { let messagesRequest = await fetch('http://localhost:3030/jsonstore/messenger'); let messagesObject = await messagesRequest.json(); let textBoxElement = document.getElementById('messages'); let allMessages = []; for (const m of Object.values(messagesObject)) { let author = m.author; let content = m.content; allMessages.push(`${author}: ${content}`); } textBoxElement.textContent = allMessages.join('\n'); } } attachEvents();
import React, { useEffect, useRef, useState } from 'react'; // menu icon import MoreHorizIcon from '@/icons/Common/more_horiz.svg'; const Dropdown = ({ onItemClick, menu, length }) => { // creating a ref for the dropdown menu const dropdownRef = useRef(null); // creating a state variable for the dropdown visibility const [isOpen, setIsOpen] = useState(false); const toggleDropdown = () => { setIsOpen(!isOpen); }; const closeDropdown = (event) => { if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { setIsOpen(false); } }; useEffect(() => { document.addEventListener('click', closeDropdown); return () => { document.removeEventListener('click', closeDropdown); }; }, []); return ( <div className='Menu_dropdown' ref={dropdownRef}> {/* this is the button */} <button id='dropdownMenuIconHorizontalButton' onClick={toggleDropdown} className='w-10 h-10 p-2 rounded-lg border border-grey-200 flex justify-center items-center hover:border-grey-300' type='button'> <MoreHorizIcon /> </button> {/* Dropdown menu list */} <div id='dropdownDotsHorizontal' className={`z-10 ${ isOpen ? 'block' : 'hidden' } bg-white divide-y divide-gray-100 rounded-lg shadow w-44 dark:bg-gray-700 dark:divide-gray-600 mt-1`}> <ul className='py-2 text-sm text-gray-700 dark:text-gray-200'> {menu.map((item) => ( <li key={item.id} className='px-2'> <span onClick={() => onItemClick(item.id)} className='flex justify-center px-3 py-2 hover:bg-gray-100 dark:hover:bg-gray-600 cursor-pointer rounded-md'> {item.name} </span> </li> ))} </ul> </div> {/* this is custom css for the dropdown */} <style jsx>{` .Menu_dropdown { position: relative; } .Menu_dropdown #dropdownDotsHorizontal { position: absolute; right: 0; ${length === 'last' ? 'bottom: calc(100% + 0.25rem);' : 'top: 100%;'} } `}</style> </div> ); }; export default Dropdown;
const bodyParser = require('body-parser'); const app = require('express')(); const {auth} = require('./middleware'); const commentPublic = require('./routes/comment'); const postPublic = require('./routes/post'); const userPublic = require('./routes/user'); const commentPrivate = require('./routes/commentPrivate'); const postPrivate = require('./routes/postPrivate'); const userPrivate = require('./routes/userPrivate'); const port = 3000; // Middleware // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); // Pubic Routes app.use('/user', userPublic); app.use('/post', postPublic); app.use('/comment', commentPublic); // Authenticate Middleware app.use(auth); // Private Routes app.use('/user', userPrivate); app.use('/post', postPrivate); app.use('/comment', commentPrivate); app.use((req, res) => { res.json({ message: 'API BASE', }); }); // Listener app.listen(port, _=>{ console.log('Listening on port: ', port); }) ;
// Copyright 2016 Google Inc. // // 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. var cacheName = 'pwapp-reactmemory-v0.1.25'; var filesToCache = [ '/', '/#', '/index.html', '/index.html#', '/scripts/app.js', '/scripts/react.js', '/scripts/react-dom.js', '/scripts/browser.js', '/scripts/jquery.min.js', '/scripts/marked.min.js', '/styles/inline.css', '/images/espaceur.gif', '/images/ic_refresh_white_24px.svg', '/images/img01.jpg', '/images/img02.jpg', '/images/img03.jpg', '/images/img04.jpg', '/images/img05.jpg', '/images/img06.jpg', '/images/img07.jpg', '/images/img08.jpg', '/images/img09.jpg', '/images/img10.jpg', '/images/img11.jpg', '/images/img12.jpg', '/images/img13.jpg', '/images/img14.jpg', '/images/img15.jpg', '/images/img16.jpg', '/images/img17.jpg', '/images/img18.jpg', '/images/img19.jpg', '/images/img20.jpg', '/images/img21.jpg', '/images/img22.jpg', '/images/img23.jpg' ]; // Install event - cache files (...or not) // Be sure to call skipWaiting()! self.addEventListener('install', function (e) { console.log('[ServiceWorker] Install'); e.waitUntil( caches.open(cacheName).then(function (cache) { console.log('[ServiceWorker] Caching app shell'); // Important to `return` the promise here to have `skipWaiting()` // fire after the cache has been updated. return cache.addAll(filesToCache); }).then(function () { // `skipWaiting()` forces the waiting ServiceWorker to become the // active ServiceWorker, triggering the `onactivate` event. // Together with `Clients.claim()` this allows a worker to take effect // immediately in the client(s). return self.skipWaiting(); }) ); }); // Activate event // Be sure to call self.clients.claim() self.addEventListener('activate', function (e) { console.log('[ServiceWorker] Activate'); e.waitUntil( caches.keys().then(function (keyList) { return Promise.all(keyList.map(function (key) { if (key !== cacheName) { console.log('[ServiceWorker] Removing old cache', key); return caches.delete(key); } })); }) ); // `claim()` sets this worker as the active worker for all clients that // match the workers scope and triggers an `oncontrollerchange` event for // the clients. return self.clients.claim(); }); self.addEventListener('fetch', function (e) { console.log('[Service Worker] Fetch', e.request.url); /* * The app is asking for app shell files. In this scenario the app uses the * "Cache, falling back to the network" offline strategy: * https://jakearchibald.com/2014/offline-cookbook/#cache-falling-back-to-network */ e.respondWith( caches.match(e.request).then(function (response) { return response || fetch(e.request); }) ); });
var App = require('app'); /** * Users View View * * @namespace App * @extends {Ember.View} */ App.UsersViewView = Em.View.extend({ templateName: 'users/view' });
//var xmlIdPreguntas = null; function gestionarXml(dadesXml){ var xmlDoc = dadesXml.responseXML; var maxNode = xmlDoc.getElementsByTagName("title").length; var pregunta = null; var tipo = null; var id = null; var html = ""; var opcionesCargadas = null; var opciones = null; for(i=0; i<maxNode;i++) { pregunta = xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue; tipo = xmlDoc.getElementsByTagName("type")[i].childNodes[0].nodeValue; id = xmlDoc.getElementsByTagName("question")[i].getAttribute("id"); //if(xmlIdPreguntas == null){ // xmlIdPreguntas = id+"#"; // }else{ // xmlIdPreguntas += id+"#"; // } html += "<tr>"; html += "<td style=\"width: auto;\">"; if(tipo == "text"){ html += "<label>"+pregunta+"<\/label>"; html += "<br>" html += "<input type=\"text\" value=\"\" name=\""+id+"\"\/>"; } else if (tipo == "checkbox"){ opcionesCargadas = xmlDoc.getElementById(id).getElementsByTagName('option').length; html += "<label>"+pregunta+"<\/label><br>"; for (j = 0; j < opcionesCargadas; j++) { opciones = xmlDoc.getElementById(id).getElementsByTagName('option')[j].childNodes[0].nodeValue; html += "<input type=\"checkbox\" name=\""+id+"\" value=\""+j+"\">"+opciones+"<br>"; } } else if (tipo == "select"){ opcionesCargadas = xmlDoc.getElementById(id).getElementsByTagName('option').length; html += "<label>"+pregunta+"<\/label><br>"; html += "<select name=\""+id+"\">" for (j = 0; j < opcionesCargadas; j++) { opciones = xmlDoc.getElementById(id).getElementsByTagName('option')[j].childNodes[0].nodeValue; html += "<option type=\"select\" name=\"option\" value=\""+j+"\">"+opciones+"<br>"; } html += "</select>" } else if (tipo == "radio"){ opcionesCargadas = xmlDoc.getElementById(id).getElementsByTagName('option').length; html += "<label>"+pregunta+"<\/label><br>"; for (j = 0; j < opcionesCargadas; j++) { opciones = xmlDoc.getElementById(id).getElementsByTagName('option')[j].childNodes[0].nodeValue; html += "<input type=\"radio\" name=\""+id+"\" value=\""+j+"\">"+opciones+"<br>"; } } else if (tipo == "multiple"){ opcionesCargadas = xmlDoc.getElementById(id).getElementsByTagName('option').length; html += "<label>"+pregunta+"<\/label><br>"; html += "<select multiple name=\""+id+"\">" for (j = 0; j < opcionesCargadas; j++) { opciones = xmlDoc.getElementById(id).getElementsByTagName('option')[j].childNodes[0].nodeValue; html += "<option type=\"select\" name=\"option\" value=\""+j+"\">"+opciones+"<br>"; } html += "</select>" } html += "<\/td>"; html += "<\/tr>"; } document.getElementById("preguntas").innerHTML = html; } function contruirXmlRespuestas(){ var arrayId = xmlIdPreguntas.split("#"); var xmlRespuestas = null; var respuesta = null; xmlRespuestas = "<Resultados>"; for (i = 0; i < arrayId.length; i++) { if(document.getElementById(arrayId[i]) != null){ respuesta = document.getElementById(arrayId[i]).value; xmlRespuestas += "<Respuesta id=\""+arrayId[i]+"\">"+respuesta+"<\/Respuesta>"; } } xmlRespuestas += "</Resultados>"; alert(xmlRespuestas); document.getElementById("resultadoxml").value = xmlRespuestas; document.formulariopreguntas.submit(); } window.onload = function(){ var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { gestionarXml(this); } }; xhttp.open("GET", "lectura.xql", true); xhttp.send(); }
function onRequest(request, response, modules) { var subject = JSON.parse(request.body.subject); var userId = request.body.userId; var installationId = request.body.installationId; var db = modules.oData; var push = modules.oPush; var result = { "setSubject": null, "subscribeChannel": null }; subject.user = { "__type": "Pointer", "className": "_User", "objectId": userId }; db.insert({ "table": "Subject", "data": subject }, function (err, data) { result.setSubject = JSON.parse(data); push.update({ "objectId": installationId, "data": { "channels": { "__op": "AddUnique", "objects": [result.setSubject.objectId] } } }, function (err, data) { result.subscribeChannel = JSON.parse(data); response.send(result); }); }); }
var fs = require('fs'); module.exports = function(app){ require('./analysis')(app); require('./auth')(app); require('./corpora')(app); require('./documentation')(app); require('./templates')(app); }
// profile // import profilePage from '../pages/profile/ProfilePage.vue' // import profilePostsPage from '../pages/profile/ProfilePostsPage.vue' // single pages import homePage from '../pages/Home.vue' import newsPage from '../pages/news/NewsPage.vue' import login from '@/components/dung/Login.vue' import Register from '@/components/dung/Register.vue' import notFoundPage from '../pages/NotFound.vue' import UitemDetail from '@/components/item/UitemDetail' import UpdateUser from '@/components/dung/UpdateUser.vue' import CartPage from '../pages/cart' import List from '@/components/cuc/List.vue' import ListItem from '../components/cuc/ListItem.vue' import OrderTracking from '../components/hang/OrderTracking.vue' import { routePropResolver } from './util' import { DOMAIN_TITLE } from '../.env' import Checkout from '../components/ngoc/checkout.vue' export const routes = [ { path: '/', name: 'index', component: homePage, meta: { title: `${DOMAIN_TITLE} | home` } }, { path: '/uitem-detail/:id', props: true, name: 'UitemDetail', component: UitemDetail, meta: { title: `${DOMAIN_TITLE} | UitemDetail` } }, { path: '/news', name: 'news', component: newsPage, meta: { title: `${DOMAIN_TITLE} | news` }, props: routePropResolver }, { path: '/profile', component: UpdateUser, meta: { title: `${DOMAIN_TITLE} | profile` } }, { path: '/login', name: 'login', component: login, meta: { title: `${DOMAIN_TITLE} | login` } }, { path: '/register', name: 'Register', component: Register, meta: { title: `${DOMAIN_TITLE} | register` } }, { path: '*', component: notFoundPage, meta: { title: `${DOMAIN_TITLE} | not found` } }, { path: '/list-item', name: 'list-item', component: ListItem, meta: { title: `${DOMAIN_TITLE} | not found` } }, { component: List, path: '/order-tracking/:id', // eslint-disable-next-line no-dupe-keys component: OrderTracking, meta: { title: `${DOMAIN_TITLE} | not found` } }, { path: '/Checkout', name: 'Checkout', component: Checkout, meta: { title: `${DOMAIN_TITLE} | Checkout` } }, { path: '/cart', name: 'cart', component: CartPage, meta: { title: `${DOMAIN_TITLE} | cart` } }]
import css from 'styled-jsx/css' import font from '../styles/variables/font' import { primary, secondary } from '../styles/variables/colors' export default css` .post-tag { font-family: ${font}; font-size: 12px; font-weight: 200; color: #eee; border: 1px #e9e9e9 solid; margin: 0 5px 5px 0; padding: 3px; } @media (max-width: 780px) { .post-tag { font-weight: 300; } }`
let botonRegistrar = document.querySelector('#btnRegistrarCliente'); botonRegistrar.addEventListener('click', regCliente); function regCliente(){ let nombre = document.querySelector('#txtNombre').value; let apellido1 = document.querySelector('#txtPrimerApellido').value; let apellido2 = document.querySelector('#txtSegundoApellido').value; let cedula = document.querySelector('#txtCedula').value; let telefono = document.querySelector('#txtTelefono').value; let email = document.querySelector('#email').value; let objCliente = new Cliente(nombre, apellido1, apellido2, cedula, telefono, email); registrarCliente(objCliente); }
import React from 'react'; import PropTypes from 'prop-types'; const renderDetail = (aDetail, index) => ( <li key={index}>{aDetail}</li> ); const TechnicalDetails = ({ data }) => ( <ul> {data.map(renderDetail)} </ul> ); TechnicalDetails.propTypes = { data: PropTypes.array.isRequired }; export default TechnicalDetails;
const express = require('express'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser') const hbs = require('hbs'); var jwt = require('jsonwebtoken'); const db = require('./bootstrap/db'); const users = require('./handlers/users'); const auth = require('./handlers/auth'); const dashboard = require('./handlers/dashboard'); const blogposts = require('./handlers/blogposts'); // create this file db.initDB(); let app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(cookieParser()); app.use(express.static('public')); hbs.registerPartials(__dirname + '/views/partials'); app.use((req, res, next) => { let whitelist = [ '/', '/register' ]; if(!whitelist.includes(req.path)){ if(req.cookies.jwt){ jwt.verify(req.cookies.jwt, auth.tokenKey, (err, payload) => { if(err){ return res.status(401).send('Unauthorized'); } return next(); }) } else { return res.status(401).send('Unauthorized'); } } else { return next(); } }); app.set('view engine', 'hbs'); // routes app.get('/', auth.viewLogin); app.post('/', auth.apiLogin); app.get('/register', auth.viewRegister); app.post('/register', auth.apiRegister); app.get('/logout', auth.apiLogout); app.get('/dashboard', dashboard.viewDashboard); // from here to the end // app.get('/users/new', users.viewNewUser) // app.post('/users/new', users.apiNewUser) // app.get('/users/edit/:id', users.viewEditUser) // app.post('/users/edit/:id', users.apiEditUser) // app.get('/users/delete/:id', users.apiDeleteUser) // app.get('/blogposts/new', blogposts.viewNewBlogpost) // app.post('/blogposts/new', blogposts.apiNewBlogpost) // app.get('/blogposts/edit/:id', blogposts.viewEditBlogpost) // app.post('/blogposts/edit/:id', blogposts.apiEditBlogpost) // app.get('/blogposts/delete/:id', blogposts.apiDeleteBlogpost) app.listen(8080, (err) => { if(err){ console.error(err); return; } console.log('Started on port 8080'); });
(function($, App, window) { App.prototype._buildRoutes = Backbone.Router.extend({ routes: { '': 'indexRoute', ':partial': 'partialRoute' } }); App.prototype._initRoutes = function() { var self = this; this.routes = new this._buildRoutes; this.routes.on('route', function(route) { console.log('route:' + route); }, self); // Listen out for changes to the URL. Backbone.history.start({pushState: true}); }; })(jQuery, App, window);
'use strict'; var ngApp = angular.module('app', ['ui.bootstrap', 'ui.tms', 'http.ui.xxt', 'snsshare.ui.xxt', 'directive.enroll']); ngApp.controller('ctrlMain', ['$scope', '$uibModal', 'http2', 'tmsSnsShare', function($scope, $uibModal, http2, tmsSnsShare) { var _oNewInvite, _oMatterList = {}; $scope.newInvite = _oNewInvite = {}; $scope.criteria = { id: '' }; $scope.addInviteCode = function() { $uibModal.open({ templateUrl: 'codeEditor.html', backdrop: 'static', controller: ['$uibModalInstance', '$scope', function($mi, $scope) { $scope.code = {}; $scope.isDate = 'N'; $scope.cancel = function() { $mi.dismiss(); }; $scope.ok = function() { var regx = /^[0-9]\d*$/; if ($scope.code.max_count === '' || (!regx.test($scope.code.max_count))) { alert('请输入正确的使用次数值'); return false; } if ($scope.isDate == 'N') { $scope.code.expire_at = '0'; } $mi.close($scope.code); }; }] }).result.then(function(oNewCode) { http2.post('/rest/site/fe/invite/code/add?invite=' + $scope.invite.id, oNewCode).then(function(rsp) { $scope.inviteCodes.splice(0, 0, rsp.data); }); }); }; $scope.updateInvite = function(prop) { var posted = {}; posted[prop] = _oNewInvite[prop]; http2.post('/rest/site/fe/invite/update?invite=' + $scope.invite.id, posted).then(function(rsp) { $scope.invite[prop] = _oNewInvite[prop]; }); }; $scope.$watch('criteria.id', function(nv) { if (!nv) return; http2.get('/rest/site/fe/invite/create?matter=' + _oMatterList[nv].type + ',' + nv).then(function(rsp) { var oInvite = rsp.data; _oNewInvite.message = oInvite.message; $scope.invite = oInvite; http2.get('/rest/site/fe/user/invite/codeList?invite=' + oInvite.id).then(function(rsp) { var codes = rsp.data; $scope.inviteCodes = codes; }); if (/MicroMessenger/i.test(navigator.userAgent)) { $scope.wxAgent = true; tmsSnsShare.config({ siteId: oInvite.matter_siteid, logger: function(shareto) {}, jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] }); tmsSnsShare.set(oInvite.matter_title, oInvite.entryUrl, oInvite.matter_summary, oInvite.matter_pic); } }); }); http2.get('/rest/site/fe/user/get').then(function(rsp) { $scope.loginUser = rsp.data; if ($scope.loginUser.unionid) { http2.get('/rest/site/fe/invite/listInviteMatter' + location.search).then(function(rsp) { $scope.matterList = rsp.data; if (rsp.data.length === 1) { $scope.criteria.id = rsp.data[0].id; } $scope.matterList.forEach(function(matter) { _oMatterList[matter.id] = matter; }); }); } }); }]);
(function(){ angular .module('everycent.common') .directive('ecMessage', ecMessage); function ecMessage(){ var directive = { restrict:'E', templateUrl: 'app/common/ec-message-directive.html', scope: {}, controller: controller, controllerAs: 'vm', bindToController: true }; return directive; } controller.$inject = ['MessageService']; function controller(MessageService){ var vm = this; vm.ui = MessageService.getMessageData(); vm.remove = MessageService.clearMessage; } })();
var express = require('express'); var path = require('path'); var bodyParser = require('body-parser'); var app = express(); var mysql = require('mysql'); var pool = mysql.createPool({ connectionLimit : 10, host : 'localhost', user : 'root', password : '123456', database : 'moonrise_crystals_database', dateStrings: 'date' }); // configure app app.use(express.static(path.join(__dirname, 'public'))); app.set('view engine', 'jade'); app.set('views', path.join(__dirname, 'views')); // middleware app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); var router = express.Router(); app.use('', router); function allUsers(callback) { pool.query('SELECT * from customers ORDER BY customer_id DESC', function(err, rows) { if (err) throw err; else callback(null, rows) }); } function getUser(customer_id,callback) { pool.query('SELECT * FROM customers WHERE customer_id=' + customer_id, function(err, results) { if (err) throw err; else callback(null, results) }); } function allOrders(callback) { pool.query('select *, (SELECT SUM(order_details.quantity * order_details.price) FROM order_details where order_details.order_id = orders.order_id GROUP BY order_details.order_id) as Total FROM orders INNER JOIN customers on customers.customer_id = orders.customer_id INNER JOIN platforms on orders.platform_id = platforms.platform_id ORDER BY orders.date DESC', function (err, rows) { if (err) throw err; callback(null, rows) }); } function getOrder(order_id, callback) { pool.query('select *, platforms.name as platform_name, orders.notes as order_notes, products.name as product_name FROM order_details INNER JOIN orders on order_details.order_id = orders.order_id INNER JOIN products on order_details.product_id = products.product_id INNER JOIN customers on orders.customer_id = customers.customer_id INNER JOIN platforms on platforms.platform_ID = orders.platform_id where order_details.order_id = ' + order_id, function (err, results) { if (err) throw err; callback(null, results); }); } function listOrders(customer_id, callback) { pool.query('select *, (SELECT SUM(order_details.quantity * order_details.price) FROM order_details where order_details.order_id = orders.order_id GROUP BY order_details.order_id) as Total FROM orders INNER JOIN customers on customers.customer_id = orders.customer_id INNER JOIN platforms on orders.platform_id = platforms.platform_id where customers.customer_id =' + customer_id + " ORDER BY order_id DESC" , function (err, orders) { if (err) throw err; else callback(null, orders) }); } //// Index router.get('/', function (req, res) { res.render('index', { title: 'Dashboard - Moonrise Crystals', }); }); // // // -- CUSTOMERS -- // // router.get('/customers', function (req, res) { allUsers(function (req, allCustomers) { res.render('allCustomers', { title: 'List of Customers', customers: allCustomers }); }); }); router.get('/customers/new',function (req, res) { res.render('addCustomer', { title: 'Add new Customer' }); }); router.get('/customers/:id/', function (req,res) { getUser(req.params.id, function (req1, results) { if (results.length == 0) { res.send('Customer does not exist <br> <a href=/Customers>Go back</a>'); } else{ listOrders(req.params.id, function(req, orders) { res.render('viewCustomer', { title: 'View Customer', customer: results, orders: orders }); }); } }); }); router.get('/Customers/Edit/:id', function (req,res) { getUser(req.params.id, function (req, results) { if (results.length == 0) { res.send('Customer does not exist <br> <a href=/Customers>Go back</a>'); } else { res.render('editCustomer', { title: 'View Customer', customer: results }); } }); }); router.post('/Customers/Edit/:id', function (req, res) { var Customer = req.body; pool.query('UPDATE customers SET first_name = ?, last_name = ?, email = ?, username = ?, phone_number = ?, address = ?, city = ?, state = ?, zip = ?, country = ?, notes = ? WHERE customer_id = ?', [Customer.first_name,Customer.last_name,Customer.email,Customer.username,Customer.phone_number,Customer.address,Customer.city,Customer.state, Customer.zip, Customer.Country,Customer.notes, req.params.id] , function(err) { if (err) console.log(err); res.redirect('/Customers/' + req.params.id); }); }); router.post('/customers/new' , function (req, res) { pool.query('INSERT INTO customers SET ?', req.body, function (err,result) { if (err) console.log(err); res.redirect('/Customers/' + result.insertId); }); }); // // // -- ORDERS -- // // router.get('/Orders/', function (req, res) { allOrders(function (req, allOrders) { res.render('Orders', { title: 'List of Orders', orders: allOrders }); }); }); router.get('/Orders/New/:id', function (req, res) { pool.query('SELECT *, name as label from platforms', function (err, result) { if (err) console.log(err); res.render('addOrder', { title: 'New Order', customerID : req.params.id, platforms: JSON.stringify(result) }); }); }); router.post('/Orders/New', function (req, res) { pool.query('INSERT INTO orders SET ?', req.body, function (err, result) { if (err) console.log(err); pool.query('INSERT INTO order_details SET ?', {order_id: result.insertId, product_id: 1, quantity: 1, price: 0, feedback_message:0}, function (err, results) { if (err) console.log(err); res.redirect('/Orders/Item/' + results.insertId); }); }) }); router.get('/Orders/:id', function (req,res) { getOrder(req.params.id, function (req, results) { res.render('viewOrder', { title: 'View Order', order: results, }); }); }); router.get('/Orders/Edit/:id', function (req, res) { pool.query('SELECT * from orders where order_id =' + req.params.id, function (err, result) { if (err) console.log(err); res.render('editOrder', { title: 'Edit order', order: result }) }); }); router.post('/Orders/Edit', function (req, res) { pool.query('UPDATE orders SET ? where order_id =' + req.body.order_id, req.body, function (err) { res.redirect('/Orders/' + req.body.order_id); }); }); router.post('/Orders/Item/New/:id', function (req, res) { pool.query('INSERT INTO order_details SET ?', {order_id: req.params.id, product_id: 1, quantity: 1, price: 0, feedback_message: 0}, function (err, result2) { if (err) console.log(err); res.redirect('/Orders/Item/' + result2.insertId); }); }); router.get('/Orders/Item/:id', function (req, res) { pool.query('SELECT * FROM order_details INNER JOIN products ON products.product_id = order_details.product_id WHERE order_details_id =' + req.params.id, function (req1, results) { pool.query('SELECT *, products.name as label FROM products', function (err, result) { res.render('editItem', { title:'View Item', data: JSON.stringify(result), item: results }); }); }); }); router.post('/Orders/Item', function (req, res){ pool.query('UPDATE order_details SET order_id = ?, product_id = ?, quantity = ?, price = ?, feedback_message = ? where order_details_id = ?', [req.body.order_id, req.body.product_id, req.body.quantity, req.body.product_price, req.body.feedback_message, req.body.order_details_id], function (err) { if (err) console.log(err); res.redirect('/Orders/' + req.body.order_id); }) }); // // // -- ITEMS -- // // // router.get('/Items', function (req, res) { pool.query('SELECT * from products ORDER BY name', function (err, results){ if (err) console.log(err); res.render('allItems', { title: 'List of all Items', items: results }) }); }); router.get('/Items/Edit/:id', function (req, res) { pool.query('SELECT * FROM products WHERE product_id =' + req.params.id , function (err, results) { if (err) console.log(err); res.render('editProduct', { title: 'Edit item', item: results}); }); }); router.post('/Items/Edit', function (req,res) { pool.query('UPDATE products SET name = ?, status = ?, default_price = ? where product_id =' + req.body.product_id, [req.body.name, req.body.status, req.body.price], function (err) { if (err) console.log(err); res.redirect('/Items'); }) }); // // // -- FEEDBACK -- // // router.get('/Feedbacks', function (req, res) { pool.query('SELECT *, products.name as product_name, platforms.name as platform_name FROM order_details INNER JOIN products on order_details.product_id = products.product_id INNER JOIN orders ON order_details.order_id = orders.order_id INNER JOIN platforms on platforms.platform_id = orders.platform_id INNER JOIN customers on orders.customer_id = customers.customer_id WHERE order_details.feedback_message !=\'0\' AND order_details.feedback_message IS NOT NULL ORDER BY product_name', function (err, results) { if (err) console.log(err); res.render('allFeedbacks', { title: "All Feedbacks", feedbacks: results }); }); }); router.get('/Stats', function (req, res) { res.render('Stats', { title:"Moonrise Crystals Stats home" }); }); router.get('/Stats/DailyIncome/:year/:month', function (req, res) { pool.query('select orders.order_id, platforms.name, orders.date, orders.platform_id, sum((SELECT SUM(order_details.quantity * order_details.price) FROM order_details where order_details.order_id = orders.order_id GROUP BY order_details.order_id)) as DailyTotal FROM orders INNER JOIN platforms on orders.platform_id = platforms.platform_id where year(orders.date)= ' + req.params.year + ' AND month(orders.date) = ' + req.params.month + ' GROUP BY orders.date, orders.platform_id', function (err, results) { if (err) console.log(err); res.render('DailyIncome', { title:'MRC Daily Stats', numbers:results}); }); }); app.listen(1337, function () { console.log('The server is ready and listening on port 1337 at localhost.'); });
const withBundleAnalyzer = require("@next/bundle-analyzer")({ enabled: process.env.ANALYZE === "true", }) process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" const nextConfig = { serverRuntimeConfig: { PROJECT_ROOT: __dirname, }, images: { domains: [""], }, } module.exports = withBundleAnalyzer(nextConfig)
module.exports = function(kafka, Message, Publish, DefaultPartitioner, _) { var Middleware = function(options) { var use_options = options || {}, client = null; if (!use_options.producer) throw new Error('producer options must be set'); if (!use_options.client) { use_options.client = { url: '127.0.0.1:2181', client_id: 'kafka-node-producer' } } if (use_options.client instanceof kafka.Client) { client = use_options.client; } else { if (use_options.verbose) { console.log('> KAFKA MIDDLEWARE - Will connect to ' + use_options.client.url) } client = new kafka.Client(use_options.client.url, use_options.client.client_id, {}); } use_options.messages = _.defaults({verbose: use_options.verbose}, use_options.messages || {}); if (use_options.key && !_.isFunction(use_options.key)) { use_options.key = null; } if (use_options.message && !_.isFunction(use_options.message)) { use_options.message = null; } if (use_options.error && !_.isFunction(use_options.error)) { use_options.error = null; } // settings: https://github.com/SOHU-Co/kafka-node/blob/7101c4e1818987f4b6f8cf52c7fd5565c11768db/lib/highLevelProducer.js#L37-L38 var producer = new kafka.HighLevelProducer(client, use_options.producer.settings || {}), publisher = _.noop; client.on('ready', function () { if (publisher != _.noop) { return; } // needs to forcely request topic metadata in order to get the proper number of partitions client.refreshMetadata([use_options.producer.topic], function() { publisher = Publish.generate(producer, _.defaults({verbose: use_options.verbose, parse_to_json: true, batch: use_options.batch, partitioner: DefaultPartitioner}, use_options.producer), (client.topicPartitions[use_options.producer.topic] || []).length); }); if (use_options.verbose) { console.log('> KAFKA MIDDLEWARE - Client Ready'); producer.on('ready', function () { console.log('> KAFKA MIDDLEWARE - Producer Ready'); }); } }); var middleware = function(req, res, next) { var sent = function(err, message) { if(err) { if (use_options.verbose) { console.log("> KAFKA MIDDLEWARE - Error sending message: " + err); } if (use_options.error) { return use_options.error(err, req, res, next); } else { return next(); } } else { return next(); } } var send = function(err, message) { if (err) { if (use_options.error) { return use_options.error(err, req, res, next); } else { return next(); } } if (use_options.verbose) { console.log("> KAFKA MIDDLEWARE - MESSAGE: " + message); } if (use_options.key) { use_options.key(req, res, function(err, key) { if(err) { if (use_options.verbose) { console.log("> KAFKA MIDDLEWARE - Error Generating Key: " + err); } if (use_options.error) { return use_options.error(err, req, res, next); } else { return next(); } } else { if (use_options.verbose) { console.log("> KAFKA MIDDLEWARE - KEY: " + key); } publisher(message, key, sent); } }); } else { publisher(message, null, sent); } }; if (use_options.message) { return use_options.message(req, res, send); } else { return Message.generate(use_options.messages, req, res, send); } } return middleware; } return Middleware; }
console.log(` Level 18 Debugging JS`); console.log(` =======================`) const array = [ { name: "N. Armstrong", profession: "spacecowboy", age: 89 }, { name: "H. de Haan", profession: "kippen hypnotiseur", age: 59 }, { name: "A. Curry", profession: "kikvorsman", age: 32 }, { name: "F. Vonk", profession: "slangenmelker", age: 36 }, { name: "B. Bunny", profession: "konijnen uitlaatservice", age: 27 }, { name: "Dr.Evil", profession: "digital overlord", age: 56 } ]; console.log(`===== opdracht 1 log al list =====`) for (let person of array) { console.log(person); } console.log(`===== opdracht 2 Log al names =====`) for (let person of array) { console.log(`This is: ${person.name}`); } console.log(`===== opdracht 3 log Day of birth =====`) date = new Date; let YearNow = date.getFullYear(); console.log(`Its now the year: ${YearNow}`); for (let person of array) { console.log(`${person.name} was born in: ${YearNow - person.age}`); } console.log(`===== opdracht 4 log name plus beroep =====`) for (let person of array) { console.log(`${person.name} is a ${person.profession}`); } console.log(`===== opdracht 5 if statement older than 50 =====`) for (let person of array) { if (person.age > 50) { console.log(`${person.name} = ${person.age}`); } }
'use strict'; const fs = require( 'fs' ); const path = require( 'path' ); const objectpath = require( 'object-path' ); const util = require( 'util' ); const p = util.promisify; const deepmerge = require( 'deepmerge' ); module.exports = { array, buildError, capitalize, clone, inArray, getFiles, noop() {return 0}, replaceCharInObjectKeys, isFunction: isFunction, regexEscape, arrayMergePreserveSource, promisify, round, trace, unflatten, weightedAvg }; function array( v ) { return v === undefined ? [] : Array.isArray( v ) ? v : [ v ]; } function buildError( err ) { if ( err instanceof Error ) { return { message: err.message, stack: err.stack.split( '\n' ) }; } if ( typeof err !== 'object' || Array.isArray( err ) ) { var err2 = new Error( err ); var tmp2 = err2.stack.split( '\n' ); tmp2.splice( 1, 1 ); return { message: JSON.stringify( err ), stack: tmp2 }; } if ( err.err ) { var tmp = buildError( err.err ); return deepmerge( err, tmp, { arrayMerge: arrayMergePreserveSource } ); } // If there error has been caught, traced, and returned through another API server elsewhere it won't have a .err or // .stack if ( err.message && !err.stack ) { var tmp = buildError( new Error( err.message ) ); return deepmerge( err, tmp, { arrayMerge: arrayMergePreserveSource } ); } return err; } function capitalize( a ) { return a.charAt( 0 ).toUpperCase() + a.slice( 1 ); } function clone( a ) { return JSON.parse( JSON.stringify( a ) ); } function inArray( v ) { v = array( v ); if ( v ) { return { $in: v }; } } function getFiles( paths, files, ignore_folders, extensions ) { if ( !Array.isArray( paths ) ) { paths = [ paths ]; } extensions = extensions || []; ignore_folders = ignore_folders || []; files = files || []; var folders = []; paths.forEach( function ( p ) { fs.readdirSync( p ).forEach( function ( fn ) { fn = path.resolve( p, fn ); var stat = fs.statSync( fn ); if ( stat.isDirectory() ) { if ( ignore_folders.indexOf( path.basename( fn ) ) === -1 ) { folders.push( fn ); } } else if ( stat.isFile() ) { if ( extensions.indexOf( path.extname( fn ) ) !== -1 ) { files.push( fn ); } } } ); } ); if ( folders.length ) { getFiles( folders, files, ignore_folders, extensions ); } return files; } function replaceCharInObjectKeys( data, a, b ) { // Check if we have keys that could be replaced if ( !data || typeof data !== 'object' || typeof a !== 'string' || typeof b !== 'string' ) { return data; } var _data = {}; // Loop through all the keys Object.keys( data ).forEach( function ( k ) { // Replace 'a' with 'b' var _k = k.replace( new RegExp( regexEscape( a ), 'g' ), b ); // Recurse and associate _data[ _k ] = replaceCharInObjectKeys( data[ k ], a, b ); } ); return _data; } function isFunction( functionToCheck ) { return functionToCheck && {}.toString.call( functionToCheck ) === '[object Function]'; } function regexEscape( str ) { // the two opening square brackets might be redundant, might want to replace second one with \[ return str.replace( /[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&' ); } function arrayMergePreserveSource( dest, source, options ) { return source; } function promisify( fn ) { fn = p( fn ); return async function () { const stack = new Error().stack.split( '\n' ).slice( 2 ).join( '\n' ); try { return await fn( ...arguments ); } catch ( err ) { if ( err.err && err.err instanceof Error ) { err.err.stack = `${err.err.stack}\n${stack}`; } else if ( err instanceof Error ) { err.stack = `${err.stack}\n---\n${stack}`; } throw err; } }; } function round( n, z = 100 ) { if ( typeof n === 'number' ) { return Math.round( n * z ) / z; } if ( Array.isArray( n ) ) { return n.map( n => n !== n ? 0 : round( n, z ) ); } if ( typeof n === 'object' ) { const obj = Object.assign( {}, n ); for ( const [ k, v ] of Object.entries( obj ) ) { obj[ k ] = round( v, z ); } return obj; } return n; } function trace( fn ) { var err = new Error( 'If you are seeing this error message, something is broken!' ); var tmp = []; var filter = err.stack.split( '\n' ).slice( 2 ); return function () { if ( !arguments[ 0 ] ) { return fn.apply( null, arguments ); } filter.forEach( tmp.push.bind( tmp ) ); arguments[ 0 ] = buildError( arguments[ 0 ] ); arguments[ 0 ].stack.reverse().forEach( tmp.unshift.bind( tmp ) ); arguments[ 0 ].stack = tmp; fn.apply( null, arguments ); }; } function unflatten( flat ) { const obj = {}; for ( const [ k, v ] of Object.entries( flat ) ) { objectpath.set( obj, k, v ); } return obj; } function weightedAvg( a ) { const sum = a.reduce( ( [ vs, ws ], [ v, w ] ) => [ vs + v * w, ws + w ], [ 0, 0 ] ); return sum[ 0 ] / sum[ 1 ]; }
import React from 'react'; import New from './../components/New'; import Popular from './../components/Popular'; const getDisplayName = WrappedComponent => { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; }; function withHighlight(WrappedComponent) { function WithHighlight(props) { const { views } = props; const node = <WrappedComponent {...props}/>; if (views < 100) { return ( <New>{node}</New> ); } if (views >= 1000) { return ( <Popular>{node}</Popular> ); } return ( <>{node}</> ); } WithHighlight.displayName = `WithHighlight(${getDisplayName(WrappedComponent)})`; return WithHighlight; } export default withHighlight;
// homebridge-hue/lib/HueSensor.js // Copyright © 2016-2023 Erik Baauw. All rights reserved. // // Homebridge plugin for Philips Hue and/or deCONZ. 'use strict' // Link this module to HuePlatform. module.exports = { setHomebridge, HueSensor } function toInt (value, minValue, maxValue) { const n = parseInt(value) if (isNaN(n) || n < minValue) { return minValue } if (n > maxValue) { return maxValue } return n } function dateToString (date, utc = true) { if (date == null || date === 'none') { return 'n/a' } if (utc && !date.endsWith('Z')) { date += 'Z' } return String(new Date(date)).slice(0, 24) } const daylightEvents = { 100: { name: 'Solar Midnight', period: 'Night' }, 110: { name: 'Astronomical Dawn', period: 'Astronomical Twilight' }, 120: { name: 'Nautical Dawn', period: 'Nautical Twilight' }, 130: { name: 'Dawn', period: 'Twilight' }, 140: { name: 'Sunrise', period: 'Sunrise' }, 150: { name: 'End Sunrise', period: 'Golden Hour' }, 160: { name: 'End Golden Hour', period: 'Day' }, 170: { name: 'Solar Noon', period: 'Day' }, 180: { name: 'Start Golden Hour', period: 'Golden Hour' }, 190: { name: 'Start Sunset', period: 'Sunset' }, 200: { name: 'Sunset', period: 'Twilight' }, 210: { name: 'Dusk', period: 'Nautical Twilight' }, 220: { name: 'Nautical Dusk', period: 'Astronomical Twilight' }, 230: { name: 'Astronomical Dusk', period: 'Night' } } const daylightPeriods = { Night: { lightlevel: 0, daylight: false, dark: true }, 'Astronomical Twilight': { lightlevel: 100, daylight: false, dark: true }, 'Nautical Twilight': { lightlevel: 1000, daylight: false, dark: true }, Twilight: { lightlevel: 10000, daylight: false, dark: false }, Sunrise: { lightlevel: 15000, daylight: true, dark: false }, Sunset: { lightlevel: 20000, daylight: true, dark: false }, 'Golden Hour': { lightlevel: 40000, daylight: true, dark: false }, Day: { lightlevel: 65535, daylight: true, dark: false } } // ===== Homebridge ============================================================ // Link this module to homebridge. let Service let Characteristic let my let eve // let HistoryService let SINGLE let SINGLE_DOUBLE let SINGLE_LONG let SINGLE_DOUBLE_LONG // let DOUBLE // let DOUBLE_LONG let LONG let airQualityValues function setHomebridge (homebridge, _my, _eve) { Service = homebridge.hap.Service Characteristic = homebridge.hap.Characteristic my = _my eve = _eve SINGLE = { minValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, maxValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, validValues: [ Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS ] } SINGLE_DOUBLE = { minValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, maxValue: Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS, validValues: [ Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS ] } SINGLE_LONG = { minValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, maxValue: Characteristic.ProgrammableSwitchEvent.LONG_PRESS, validValues: [ Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, Characteristic.ProgrammableSwitchEvent.LONG_PRESS ] } SINGLE_DOUBLE_LONG = { minValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, maxValue: Characteristic.ProgrammableSwitchEvent.LONG_PRESS, validValues: [ Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS, Characteristic.ProgrammableSwitchEvent.LONG_PRESS ] } // DOUBLE = { // minValue: Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS, // maxValue: Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS, // validValues: [ // Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS // ] // } // DOUBLE_LONG = { // minValue: Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS, // maxValue: Characteristic.ProgrammableSwitchEvent.LONG_PRESS, // validValues: [ // Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS, // Characteristic.ProgrammableSwitchEvent.LONG_PRESS // ] // } LONG = { minValue: Characteristic.ProgrammableSwitchEvent.LONG_PRESS, maxValue: Characteristic.ProgrammableSwitchEvent.LONG_PRESS, validValues: [ Characteristic.ProgrammableSwitchEvent.LONG_PRESS ] } airQualityValues = { excellent: Characteristic.AirQuality.EXCELLENT, good: Characteristic.AirQuality.GOOD, moderate: Characteristic.AirQuality.FAIR, poor: Characteristic.AirQuality.INFERIOR, unhealthy: Characteristic.AirQuality.POOR } } function hkLightLevel (v) { let l = v ? Math.pow(10, (v - 1) / 10000) : 0.0001 l = Math.round(l * 10000) / 10000 return l > 100000 ? 100000 : l < 0.0001 ? 0.0001 : l } const PRESS = 0 const HOLD = 1 const SHORT_RELEASE = 2 const LONG_RELEASE = 3 const DOUBLE_PRESS = 4 const TRIPLE_PRESS = 5 const QUADRUPLE_PRESS = 6 const SHAKE = 7 const DROP = 8 // const TILT = 9 // As homebridge-hue polls the Hue bridge, not all dimmer switch buttonevents // are received reliably. Consequently, we only issue one HomeKit change per // Press/Hold/Release event series. function hkZLLSwitchAction (value, oldValue, repeat = false) { if (value < 1000) { return Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS } const button = Math.floor(value / 1000) const oldButton = Math.floor(oldValue / 1000) const event = value % 1000 const oldEvent = oldValue % 1000 switch (event) { case PRESS: // Wait for Hold or Release after press. return null case SHORT_RELEASE: return Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS case HOLD: case LONG_RELEASE: if (repeat) { return Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS } if (button === oldButton && oldEvent === HOLD) { // Already issued action on previous Hold. return null } // falls through case TRIPLE_PRESS: case QUADRUPLE_PRESS: case SHAKE: return Characteristic.ProgrammableSwitchEvent.LONG_PRESS case DOUBLE_PRESS: case DROP: return Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS default: return null } } // ===== HueSensor ============================================================= function HueSensor (accessory, id, obj) { this.accessory = accessory this.id = id this.obj = obj this.bridge = this.accessory.bridge this.log = this.accessory.log this.serialNumber = this.accessory.serialNumber this.name = this.obj.name this.hk = {} this.resource = '/sensors/' + id this.serviceList = [] if (this.obj.type[0] === 'Z') { // Zigbee sensor. this.manufacturer = this.obj.manufacturername this.model = this.obj.modelid this.endpoint = this.obj.uniqueid.split('-')[1] this.cluster = this.obj.uniqueid.split('-')[2] this.subtype = this.endpoint + '-' + this.cluster this.version = this.obj.swversion } else { // Hue bridge internal sensor. this.manufacturer = this.bridge.manufacturer if (this.accessory.isMulti) { this.model = 'MultiCLIP' this.subtype = this.id } else if ( this.obj.manufacturername === 'homebridge-hue' && this.obj.modelid === this.obj.type && this.obj.uniqueid.split('-')[1] === this.id ) { // Combine multiple CLIP sensors into one accessory. this.model = 'MultiCLIP' this.subtype = this.id } else { this.model = this.obj.type } this.version = this.bridge.version } this.infoService = this.accessory.getInfoService(this) let durationKey = 'duration' let temperatureHistory = 'weather' let heatValue = 'auto' let presenceevent = false switch (this.obj.type) { case 'ZGPSwitch': case 'ZLLSwitch': case 'ZHASwitch': { this.buttonMap = {} let namespace = Characteristic.ServiceLabelNamespace.ARABIC_NUMERALS let homekitValue = (v) => { return Math.floor(v / 1000) } let homekitAction = hkZLLSwitchAction switch (this.obj.manufacturername) { case 'Bitron Home': switch (this.obj.modelid) { case '902010/23': // Bitron remote, see #639. namespace = Characteristic.ServiceLabelNamespace.DOTS this.createButton(1, 'DimUp', SINGLE) this.createButton(2, 'On', SINGLE) this.createButton(3, 'Off', SINGLE) this.createButton(4, 'DimDown', SINGLE) break default: break } break case 'Busch-Jaeger': switch (this.obj.modelid) { case 'RM01': // Busch-Jaeger Light Link control element (mains-powered) case 'RB01': // Busch-Jaeger Light Link wall-mounted transmitter if (this.endpoint === '0a') { this.createButton(1, 'Button 1', SINGLE_LONG) this.createButton(2, 'Button 2', SINGLE_LONG) } else if (this.endpoint === '0b') { this.createButton(3, 'Button 3', SINGLE_LONG) this.createButton(4, 'Button 4', SINGLE_LONG) } else if (this.endpoint === '0c') { this.createButton(5, 'Button 5', SINGLE_LONG) this.createButton(6, 'Button 6', SINGLE_LONG) } else if (this.endpoint === '0d') { this.createButton(7, 'Button 7', SINGLE_LONG) this.createButton(8, 'Button 8', SINGLE_LONG) } break default: break } break case 'Echostar': switch (this.obj.modelid) { case 'Bell': this.createButton(1, 'Front Doorbell', SINGLE) this.createButton(2, 'Rear Doorbell', SINGLE) break default: break } break case 'ELKO': switch (this.obj.modelid) { case 'ElkoDimmerRemoteZHA': // ELKO ESH 316 Endevender RF, see #922. this.createButton(1, 'Press', SINGLE) this.createButton(2, 'Dim Up', SINGLE) this.createButton(3, 'Dim Down', SINGLE) break default: break } break case 'Heiman': switch (this.obj.modelid) { case 'RC-EF-3.0': namespace = Characteristic.ServiceLabelNamespace.DOTS this.createButton(1, 'HomeMode', SINGLE) this.createButton(2, 'Disarm', SINGLE) this.createButton(3, 'SOS', SINGLE) this.createButton(4, 'Arm', SINGLE) break default: break } break case 'IKEA of Sweden': switch (this.obj.modelid) { case 'Remote Control N2': this.createButton(1, 'DimUp', SINGLE_LONG) this.createButton(2, 'DimDown', SINGLE_LONG) this.createButton(3, 'Previous', SINGLE_LONG) this.createButton(4, 'Next', SINGLE_LONG) break case 'SYMFONISK Sound Controller': this.createButton(1, 'Button', SINGLE_DOUBLE_LONG) if (this.obj.mode === 1) { this.createButton(2, 'Turn Right', LONG) this.createButton(3, 'Turn Left', LONG) } else { this.createButton(2, 'Turn Right', SINGLE) this.createButton(3, 'Turn Left', SINGLE) } break case 'TRADFRI SHORTCUT Button': this.createButton(1, 'Button', SINGLE_DOUBLE_LONG) break case 'TRADFRI on/off switch': this.createButton(1, 'On', SINGLE_LONG) this.createButton(2, 'Off', SINGLE_LONG) break case 'TRADFRI open/close remote': this.createButton(1, 'Open', SINGLE_LONG) this.createButton(2, 'Close', SINGLE_LONG) break case 'TRADFRI remote control': this.createButton(1, 'On/Off', SINGLE) this.createButton(2, 'Dim Up', SINGLE_LONG) this.createButton(3, 'Dim Down', SINGLE_LONG) this.createButton(4, 'Previous', SINGLE_LONG) this.createButton(5, 'Next', SINGLE_LONG) break case 'TRADFRI wireless dimmer': if (this.obj.mode === 1) { this.createButton(1, 'Turn Right', SINGLE_LONG) this.createButton(2, 'Turn Left', SINGLE_LONG) } else { this.createButton(1, 'On', SINGLE) this.createButton(2, 'Dim Up', SINGLE) this.createButton(3, 'Dim Down', SINGLE) this.createButton(4, 'Off', SINGLE) } break default: break } break case 'Insta': switch (this.obj.modelid) { case 'HS_4f_GJ_1': // Gira/Jung Light Link hand transmitter case 'WS_3f_G_1': // Gira Light Link wall transmitter case 'WS_4f_J_1': // Jung Light Link wall transmitter this.createButton(1, 'Off', SINGLE_DOUBLE_LONG) this.createButton(2, 'On', SINGLE_DOUBLE_LONG) this.createButton(3, 'Scene 1', SINGLE) this.createButton(4, 'Scene 2', SINGLE) this.createButton(5, 'Scene 3', SINGLE) this.createButton(6, 'Scene 4', SINGLE) if (this.obj.modelid !== 'WS_3f_G_1') { this.createButton(7, 'Scene 5', SINGLE) this.createButton(8, 'Scene 6', SINGLE) } break default: break } break case 'LDS': switch (this.obj.modelid) { case 'ZBT-DIMController-D0800': this.createButton(1, 'On/Off', SINGLE) this.createButton(2, 'DimUp', SINGLE_LONG) this.createButton(3, 'DimDown', SINGLE_LONG) this.createButton(4, 'Scene', SINGLE_LONG) break default: break } break case 'LIDL Livarno Lux': switch (this.obj.modelid) { case 'HG06323': this.createButton(1, 'On', SINGLE_DOUBLE_LONG) this.createButton(2, 'DimUp', SINGLE_LONG) this.createButton(3, 'DimDown', SINGLE_LONG) this.createButton(4, 'Off', SINGLE) break default: break } break case 'LUMI': switch (this.obj.modelid) { case 'lumi.remote.b1acn01': case 'lumi.remote.b186acn01': case 'lumi.remote.b186acn02': this.createButton(1, 'Left', SINGLE_DOUBLE_LONG) break case 'lumi.remote.b28ac1': case 'lumi.remote.b286acn01': case 'lumi.remote.b286acn02': this.createButton(1, 'Left', SINGLE_DOUBLE_LONG) this.createButton(2, 'Right', SINGLE_DOUBLE_LONG) this.createButton(3, 'Both', SINGLE_DOUBLE_LONG) break case 'lumi.remote.b286opcn01': // Xiaomi Aqara Opple, see #637. case 'lumi.remote.b486opcn01': // Xiaomi Aqara Opple, see #637. case 'lumi.remote.b686opcn01': // Xiaomi Aqara Opple, see #637. this.createButton(1, '1', SINGLE_DOUBLE_LONG) this.createButton(2, '2', SINGLE_DOUBLE_LONG) if (this.obj.modelid !== 'lumi.remote.b286opcn01') { this.createButton(3, '3', SINGLE_DOUBLE_LONG) this.createButton(4, '4', SINGLE_DOUBLE_LONG) if (this.obj.modelid === 'lumi.remote.b686opcn01') { this.createButton(5, '5', SINGLE_DOUBLE_LONG) this.createButton(6, '6', SINGLE_DOUBLE_LONG) } } break case 'lumi.ctrl_ln1.aq1': case 'lumi.sensor_86sw1': // Xiaomi wall switch (single button). case 'lumi.switch.l1aeu1': // Xiaomi Aqara H1, see #1149. case 'lumi.switch.n1aeu1': // Xiaomi Aqara H1, see #1149. this.createButton(1, 'Button', SINGLE_DOUBLE) break case 'lumi.ctrl_ln2.aq1': case 'lumi.sensor_86sw2': // Xiaomi wall switch (two buttons). case 'lumi.switch.l2aeu1': // Xiaomi Aqara H2, see #1149. case 'lumi.switch.n2aeu1': // Xiaomi Aqara H2, see #1149. this.createButton(1, 'Left', SINGLE_DOUBLE) this.createButton(2, 'Right', SINGLE_DOUBLE) this.createButton(3, 'Both', SINGLE_DOUBLE) break case 'lumi.sensor_cube': case 'lumi.sensor_cube.aqgl01': if (this.endpoint === '02') { this.createButton(1, 'Side 1', SINGLE_DOUBLE_LONG) this.createButton(2, 'Side 2', SINGLE_DOUBLE_LONG) this.createButton(3, 'Side 3', SINGLE_DOUBLE_LONG) this.createButton(4, 'Side 4', SINGLE_DOUBLE_LONG) this.createButton(5, 'Side 5', SINGLE_DOUBLE_LONG) this.createButton(6, 'Side 6', SINGLE_DOUBLE_LONG) this.createButton(7, 'Cube', SINGLE_DOUBLE_LONG) homekitAction = (v) => { if (v === 7000) { // Wakeup return Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS } else if (v === 7007) { // Shake return Characteristic.ProgrammableSwitchEvent.LONG_PRESS } else if (v === 7008) { // Drop return Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS } else if (v % 1000 === 0) { // Push return Characteristic.ProgrammableSwitchEvent.LONG_PRESS } else if (v % 1000 === Math.floor(v / 1000)) { // Double tap return Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS } else { // Flip return Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS } } } else if (this.endpoint === '03') { this.createButton(8, 'Turn Right', SINGLE_DOUBLE_LONG) this.createButton(9, 'Turn Left', SINGLE_DOUBLE_LONG) homekitValue = (v) => { return v > 0 ? 8 : 9 } homekitAction = (v) => { return Math.abs(v) < 4500 ? Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS : Math.abs(v) < 9000 ? Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS : Characteristic.ProgrammableSwitchEvent.LONG_PRESS } } break case 'lumi.sensor_switch': // Xiaomi Mi wireless switch case 'lumi.sensor_switch.aq2': // Xiaomi Aqara smart wireless switch case 'lumi.sensor_switch.aq3': // Xiaomi Aqara smart wireless switch with gyro this.createButton(1, 'Button', SINGLE_DOUBLE_LONG) break default: break } break case 'Lutron': switch (this.obj.modelid) { case 'LZL4BWHL01 Remote': // Lutron Pico, see 102. this.createButton(1, 'On', SINGLE) this.createButton(2, 'DimUp', LONG) this.createButton(3, 'DimDown', LONG) this.createButton(4, 'Off', SINGLE) break case 'Z3-1BRL': // Lutron Aurora, see #522. if (this.bridge.isHue) { this.createButton(1, 'Button', SINGLE_LONG) } else { this.createButton(1, 'Button', SINGLE) this.createButton(2, 'Turn Right', SINGLE) this.createButton(3, 'Turn Left', SINGLE) } break default: break } break case 'MLI': switch (this.obj.modelid) { case 'ZBT-Remote-ALL-RGBW': // Tint remote control by Müller-Licht see deconz-rest-plugin#1209 this.createButton(1, 'On/Off', SINGLE) this.createButton(2, 'DimUp', SINGLE_LONG) this.createButton(3, 'DimDown', SINGLE_LONG) this.createButton(4, 'Warm', SINGLE) this.createButton(5, 'Cool', SINGLE) this.createButton(6, 'Colour Wheel', SINGLE) this.createButton(7, 'Work Light', SINGLE) this.createButton(8, 'Sunset', SINGLE) this.createButton(9, 'Party', SINGLE) this.createButton(10, 'Night Light', SINGLE) this.createButton(11, 'Campfire', SINGLE) this.createButton(12, 'Romance', SINGLE) break default: break } break case 'OSRAM': switch (this.obj.modelid) { case 'Lightify Switch Mini': this.createButton(1, 'Up', SINGLE_LONG) this.createButton(2, 'Down', SINGLE_LONG) this.createButton(3, 'Middle', SINGLE_LONG) break default: break } break case 'Philips': case 'Signify Netherlands B.V.': { const repeat = this.bridge.platform.config.hueDimmerRepeat const events = repeat ? SINGLE : SINGLE_LONG switch (this.obj.modelid) { case 'RDM001': // Hue wall switch module switch (obj.config.devicemode) { case 'singlerocker': this.createButton(1, 'Rocker 1', SINGLE) break case 'singlepushbutton': this.createButton(1, 'Push Button 1', events) if (repeat) this.repeat = [1] break case 'dualrocker': this.createButton(1, 'Rocker 1', SINGLE) this.createButton(2, 'Rocker 2', SINGLE) break case 'dualpushbutton': this.createButton(1, 'Push Button 1', events) this.createButton(2, 'Push Button 2', events) if (repeat) this.repeat = [1, 2] break default: break } break case 'RDM002': // Hue tap dial switch namespace = Characteristic.ServiceLabelNamespace.DOTS this.createButton(1, '1', events) // On/Off this.createButton(2, '2', events) this.createButton(3, '3', events) this.createButton(4, '4', events) // Hue if (repeat) this.repeat = [1, 2, 3, 4] break case 'ROM001': // Hue smart button this.createButton(1, 'Button', events) if (repeat) this.repeat = [1] break case 'RWL020': case 'RWL021': // Hue dimmer switch this.createButton(1, 'On', SINGLE_LONG) this.createButton(2, 'Dim Up', events) this.createButton(3, 'Dim Down', events) this.createButton(4, 'Off', SINGLE_LONG) if (repeat) this.repeat = [2, 3] break case 'RWL022': // Hue dimmer switch (2021) this.createButton(1, 'On', SINGLE_LONG) // On/Off this.createButton(2, 'Dim Up', events) this.createButton(3, 'Dim Down', events) this.createButton(4, 'Off', SINGLE_LONG) // Hue if (repeat) this.repeat = [2, 3] break case 'ZGPSWITCH': // Hue tap namespace = Characteristic.ServiceLabelNamespace.DOTS this.createButton(1, '1', SINGLE) this.createButton(2, '2', SINGLE) this.createButton(3, '3', SINGLE) this.createButton(4, '4', SINGLE) this.createButton(5, '1 and 2', SINGLE) this.createButton(6, '3 and 4', SINGLE) this.convertButtonEvent = (value) => { return { 34: 1002, // Press 1 1000: 1002, 16: 2002, // Press 2 2000: 2002, 17: 3002, // Press 3 3000: 3002, 18: 4002, // Press 4 4000: 4002, 100: 5000, // Press 1 and 2 101: 5002, // Release 1 and 2 98: 6000, // Press 3 and 4 99: 6002 // Release 3 and 4 }[value] } break default: break } break } case 'PhilipsFoH': switch (this.obj.modelid) { case 'FOHSWITCH': { // Friends-of-Hue switch const events = this.bridge.isDeconz ? SINGLE_LONG : SINGLE this.createButton(1, 'Top Left', events) this.createButton(2, 'Bottom Left', events) this.createButton(3, 'Top Right', events) this.createButton(4, 'Bottom Right', events) this.createButton(5, 'Top Both', events) this.createButton(6, 'Bottom Both', events) this.convertButtonEvent = (value) => { if (value < 1000) { return { 16: 1000, // Press Top Left 20: 1002, // Release Top Left 17: 2000, // Press Bottom Left 21: 2002, // Release Bottom Left 19: 3000, // Press Top Right 23: 3002, // Relesase Top Right 18: 4000, // Press Botton Right 22: 4002, // Release Bottom Right 100: 5000, // Press Top Both 101: 5002, // Release Top Both 98: 6000, // Press Bottom Both 99: 6002 // Release Bottom Both }[value] } return value } break } default: break } break case 'Samjin': switch (this.obj.modelid) { case 'button': this.createButton(1, 'Button', SINGLE_DOUBLE_LONG) break default: break } break case 'Sunricher': switch (this.obj.modelid) { case 'ZG2833K8_EU05': // Sunricher 8-button remote, see #529. if (this.endpoint === '01') { this.createButton(1, 'On 1', SINGLE_LONG) this.createButton(2, 'Off 1', SINGLE_LONG) } else if (this.endpoint === '02') { this.createButton(3, 'On 2', SINGLE_LONG) this.createButton(4, 'Off 2', SINGLE_LONG) } else if (this.endpoint === '03') { this.createButton(5, 'On 3', SINGLE_LONG) this.createButton(6, 'Off 3', SINGLE_LONG) } else if (this.endpoint === '04') { this.createButton(7, 'On 4', SINGLE_LONG) this.createButton(8, 'Off 4', SINGLE_LONG) } break case 'ZG2833PAC': // Sunricher C4 this.createButton(1, 'Rocker 1', SINGLE) this.createButton(2, 'Rocker 2', SINGLE) this.createButton(3, 'Rocker 3', SINGLE) this.createButton(4, 'Rocker 4', SINGLE) break case 'ZGRC-KEY-002': // Sunricher CCT remote, see #529. this.createButton(1, 'On', SINGLE) this.createButton(2, 'Off', SINGLE) this.createButton(3, 'Dim', LONG) this.createButton(4, 'C/W', SINGLE_LONG) break default: break } break case '_TZ3000_arfwfgoa': switch (this.obj.modelid) { case 'TS0042': // Tuys 2-button switch, single endpoint this.createButton(1, 'Left', SINGLE_DOUBLE_LONG) this.createButton(2, 'Right', SINGLE_DOUBLE_LONG) break default: break } break case '_TZ3000_dfgbtub0': case '_TZ3000_i3rjdrwu': switch (this.obj.modelid) { case 'TS0042': // Tuya 2-button switch, see #1060. if (this.endpoint === '01') { this.createButton(1, 'Button 1', SINGLE_DOUBLE_LONG) } else if (this.endpoint === '02') { this.createButton(2, 'Button 2', SINGLE_DOUBLE_LONG) } break default: break } break case '_TZ3000_pzui3skt': switch (this.obj.modelid) { case 'TS0041': // Tuya 1-button switch this.createButton(1, 'Button', SINGLE_DOUBLE_LONG) break default: break } break case '_TZ3000_rrjr1q0u': switch (this.obj.modelid) { case 'TS0043': // Tuya 3-button switch this.createButton(1, 'Left', SINGLE_DOUBLE_LONG) this.createButton(2, 'Middle', SINGLE_DOUBLE_LONG) this.createButton(3, 'Right', SINGLE_DOUBLE_LONG) break default: break } break case '_TZ3000_vp6clf9d': switch (this.obj.modelid) { case 'TS0044': this.createButton(1, 'Bottom Left', SINGLE_DOUBLE_LONG) this.createButton(2, 'Bottom Right', SINGLE_DOUBLE_LONG) this.createButton(3, 'Top Right', SINGLE_DOUBLE_LONG) this.createButton(4, 'Top Left', SINGLE_DOUBLE_LONG) break default: break } break case '_TZ3000_wkai4ga5': switch (this.obj.modelid) { case 'TS0044': namespace = Characteristic.ServiceLabelNamespace.DOTS this.createButton(1, 'Top Left', SINGLE_DOUBLE_LONG) this.createButton(2, 'Top Right', SINGLE_DOUBLE_LONG) this.createButton(3, 'Bottom Left', SINGLE_DOUBLE_LONG) this.createButton(4, 'Bottom Right', SINGLE_DOUBLE_LONG) break default: break } break case '_TZ3000_xabckq1v': switch (this.obj.modelid) { case 'TS004F': // Tuya 4-button switch, single press only this.createButton(1, 'Top Left', SINGLE) this.createButton(2, 'Bottom Left', SINGLE) this.createButton(3, 'Top Right', SINGLE) this.createButton(4, 'Bottom Right', SINGLE) break default: break } break case 'dresden elektronik': switch (this.obj.modelid) { case 'Kobold': this.createButton(1, 'Button', SINGLE_LONG) break case 'Lighting Switch': if (this.endpoint === '01') { if (this.obj.mode !== 2) { this.log.warn( '%s: %s: warning: Lighting Switch mode %d instead of 2', this.bridge.name, this.resource, this.obj.mode ) } this.createButton(1, 'Top Left', SINGLE_LONG) this.createButton(2, 'Bottom Left', SINGLE_LONG) this.createButton(3, 'Top Right', SINGLE_LONG) this.createButton(4, 'Bottom Right', SINGLE_LONG) } break case 'Scene Switch': this.createButton(1, 'On', SINGLE_LONG) this.createButton(2, 'Off', SINGLE_LONG) this.createButton(3, 'Scene 1', SINGLE) this.createButton(4, 'Scene 2', SINGLE) this.createButton(5, 'Scene 3', SINGLE) this.createButton(6, 'Scene 4', SINGLE) break default: break } break case 'eWeLink': switch (this.obj.modelid) { case 'WB01': this.createButton(1, 'Press', SINGLE_DOUBLE_LONG) break default: break } break case 'icasa': switch (this.obj.modelid) { case 'ICZB-KPD12': case 'ICZB-KPD14S': case 'ICZB-KPD18S': this.createButton(1, 'Off', SINGLE_LONG) this.createButton(2, 'On', SINGLE_LONG) if (this.obj.modelid !== 'ICZB-KPD12') { this.createButton(3, 'S1', SINGLE) this.createButton(4, 'S2', SINGLE) if (this.obj.modelid === 'ICZB-KPD18S') { this.createButton(5, 'S3', SINGLE) this.createButton(6, 'S4', SINGLE) this.createButton(7, 'S5', SINGLE) this.createButton(8, 'S6', SINGLE) } } break case 'ICZB-RM11S': this.createButton(1, '1 Off', SINGLE_LONG) this.createButton(2, '1 On', SINGLE_LONG) this.createButton(3, '2 Off', SINGLE_LONG) this.createButton(4, '2 On', SINGLE_LONG) this.createButton(5, '3 Off', SINGLE_LONG) this.createButton(6, '3 On', SINGLE_LONG) this.createButton(7, '4 Off', SINGLE_LONG) this.createButton(8, '4 On', SINGLE_LONG) this.createButton(9, 'S1', SINGLE) this.createButton(10, 'S2', SINGLE) break default: break } break case 'innr': switch (this.obj.modelid) { case 'RC 110': if (this.endpoint === '01') { this.createButton(1, 'On/Off', SINGLE) this.createButton(2, 'Dim Up', SINGLE_LONG) this.createButton(3, 'Dim Down', SINGLE_LONG) this.createButton(4, '1', SINGLE) this.createButton(5, '2', SINGLE) this.createButton(6, '3', SINGLE) this.createButton(7, '4', SINGLE) this.createButton(8, '5', SINGLE) this.createButton(9, '6', SINGLE) for (let i = 1; i <= 6; i++) { const button = 7 + i * 3 this.createButton(button, `On/Off ${i}`, SINGLE) this.createButton(button + 1, `Dim Up ${i}`, SINGLE_LONG) this.createButton(button + 2, `Dim Down ${i}`, SINGLE_LONG) } } break default: break } break case 'lk': switch (this.obj.modelid) { case 'ZBT-DIMSwitch-D0001': // Linkind 1-Key Remote Control, see #949. this.createButton(1, 'Button', SINGLE_LONG) homekitValue = (v) => { return 1 } break default: break } break case 'ubisys': switch (this.obj.modelid) { case 'C4 (5504)': case 'C4-R (5604)': this.createButton(1, '1', SINGLE_LONG) this.createButton(2, '2', SINGLE_LONG) this.createButton(3, '3', SINGLE_LONG) this.createButton(4, '4', SINGLE_LONG) break case 'D1 (5503)': case 'D1-R (5603)': case 'S1-R (5601)': case 'S2 (5502)': case 'S2-R (5602)': this.createButton(1, '1', SINGLE_LONG) this.createButton(2, '2', SINGLE_LONG) break case 'S1 (5501)': this.createButton(1, '1', SINGLE_LONG) break default: break } break default: break } if (Object.keys(this.buttonMap).length > 0) { this.createLabel(namespace) this.type = { key: 'buttonevent', homekitValue, homekitAction } } else { this.log.warn( '%s: %s: warning: ignoring unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } break } case 'ZHARelativeRotary': case 'ZLLRelativeRotary': { this.buttonMap = {} let namespace = Characteristic.ServiceLabelNamespace.ARABIC_NUMERALS let homekitValue if ( this.obj.manufacturername === 'Signify Netherlands B.V.' && this.obj.modelid === 'RDM002' ) { // Hue tap dial switch namespace = Characteristic.ServiceLabelNamespace.DOTS this.createButton(5, 'Turn Right', SINGLE) this.createButton(6, 'Turn Left', SINGLE) homekitValue = (v) => { return v > 0 ? 5 : 6 } } else if ( this.obj.manufacturername === 'Lutron' && this.obj.modelid === 'Z3-1BRL' ) { // Lutron Aurora, see #522. this.createButton(2, 'Turn Right', SINGLE) this.createButton(3, 'Turn Left', SINGLE) homekitValue = (v) => { return v > 0 ? 2 : 3 } } if (Object.keys(this.buttonMap).length > 0) { this.createLabel(namespace) this.type = { key: 'expectedrotation', homekitValue, homekitAction: () => { return Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS } } } else { this.log.warn( '%s: %s: warning: ignoring unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } break } case 'CLIPSwitch': // 2.1 // We'd need a way to specify the number of buttons, cf. max value for // a CLIPGenericStatus sensor. this.log.warn( '%s: %s: warning: ignoring unsupported sensor type %s', this.bridge.name, this.resource, this.obj.type ) break case 'ZLLPresence': // falls through case 'ZHAPresence': if ( ['Philips', 'Signify Netherlands B.V.'].includes(this.obj.manufacturername) && ['SML001', 'SML002', 'SML003', 'SML004'].includes(this.obj.modelid) ) { // 1.3 - Hue motion sensor durationKey = 'delay' } else if ( this.obj.manufacturername === 'IKEA of Sweden' && this.obj.modelid === 'TRADFRI motion sensor' ) { // Ikea Trådfri motion sensor this.obj.state.dark = false } else if ( this.obj.manufacturername === 'LUMI' && ( this.obj.modelid === 'lumi.sensor_motion' || this.obj.modelid === 'lumi.sensor_motion.aq2' ) ) { // Xiaomi motion sensor // Xiaomi Aqara motion sensor } else if ( this.obj.manufacturername === 'aqara' && this.obj.modelid === 'lumi.motion.ac01' ) { // Aqara Presence Detector FP1 presenceevent = true // this.obj.config.sensitivitymax = 2 } else if ( this.obj.manufacturername === 'Heiman' && this.obj.modelid === 'PIR_TPV11' ) { // Heiman motion sensor } else if ( this.obj.manufacturername === 'SmartThings' && this.obj.modelid === 'tagv4' ) { // Samsung SmartThings arrival sensor } else if ( this.obj.manufacturername === 'Konke' && this.obj.modelid === '3AFE28010402000D' ) { // Konke motion sensor } else if ( this.obj.manufacturername === 'SILVERCREST' && this.obj.modelid === 'TY0202' ) { // LIDL motion sensor, see #979. } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPPresence': // 2.3 case 'Geofence': // Undocumented this.service = new eve.Services.MotionSensor(this.name, this.subtype) this.serviceList.push(this.service) this.duration = 0 this.type = { Characteristic: Characteristic.MotionDetected, key: presenceevent ? 'presenceevent' : 'presence', name: 'motion', unit: '', history: 'motion', homekitValue: presenceevent ? (v) => { return v.endsWith('leave') ? 0 : 1 } : (v) => { return v ? 1 : 0 }, durationKey, sensitivitymax: this.obj.config.sensitivitymax } break case 'ZLLTemperature': case 'ZHATemperature': if ( ['Philips', 'Signify Netherlands B.V.'].includes(this.obj.manufacturername) && ['SML001', 'SML002', 'SML003', 'SML004'].includes(this.obj.modelid) ) { // 1.4 - Hue motion sensor } else if ( this.obj.manufacturername === 'LUMI' && ( this.obj.modelid === 'lumi.weather' || this.obj.modelid === 'lumi.sensor_ht' ) ) { // Xiaomi temperature/humidity sensor // Xiaomi Aqara weather sensor } else if ( this.obj.manufacturername === 'Heiman' && (this.obj.modelid === 'TH-H_V15' || this.obj.modelid === 'TH-T_V15') ) { // Heiman temperature/humidity sensor } else if ( this.obj.manufacturername === 'Samjin' && this.obj.modelid === 'button' ) { // Samsung SmartThings Button temperature sensor } else if ( this.obj.manufacturername === 'Samjin' && this.obj.modelid === 'multi' ) { // Samsung SmartThings multipurpose sensor } else if ( this.obj.manufacturername === 'Develco Products AS' && ( this.obj.modelid === 'SMSZB-120' || this.obj.modelid === 'HESZB-120' ) ) { // Develco smoke sensor // Develco heat sensor } else if (this.obj.modelid === 'lumi.airmonitor.acn01') { // Xiaomi Aquara TVOC Sensor temperatureHistory = 'room2' } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPTemperature': // 2.4 this.service = new eve.Services.TemperatureSensor(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.CurrentTemperature, key: 'temperature', name: 'temperature', unit: '°C', history: temperatureHistory, homekitValue: (v) => { return v ? Math.round(v / 10) / 10 : 0 } } break case 'ZHAAirQuality': if ( this.obj.manufacturername === 'LUMI' && this.obj.modelid === 'lumi.airmonitor.acn01' ) { // Xiaomi Aqara airquality sensor } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPAirQuality': this.service = new Service.AirQualitySensor(this.name, this.subtype) this.serviceList.push(this.service) this.service .addOptionalCharacteristic(Characteristic.AirQuality) this.type = { Characteristic: Characteristic.VOCDensity, key: 'airqualityppb', name: 'VOC density', unit: ' µg/m³', props: { minValue: 0, maxValue: 65535, minStep: 1 }, history: 'room2', homekitValue: (v) => { return v ? Math.round(v * 4.57) : 0 } } break case 'ZLLLightLevel': // 2.7 - Hue Motion Sensor case 'ZHALightLevel': if ( ['Philips', 'Signify Netherlands B.V.'].includes(this.obj.manufacturername) && ['SML001', 'SML002', 'SML003', 'SML004'].includes(this.obj.modelid) ) { // 1.4 - Hue motion sensor } else if ( this.obj.manufacturername === 'LUMI' && this.obj.modelid === 'lumi.sensor_motion.aq2' ) { // Xiaomi Aqara motion sensor } else if ( this.obj.manufacturername === 'LUMI' && this.obj.modelid === 'lumi.sen_ill.mgl01' ) { // Xiaomi Mi light intensity sensor } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPLightLevel': // 2.7 this.service = new Service.LightSensor(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.CurrentAmbientLightLevel, key: 'lightlevel', name: 'light level', unit: ' lux', homekitValue: hkLightLevel } break case 'ZHAOpenClose': if ( this.obj.manufacturername === 'LUMI' && ( this.obj.modelid === 'lumi.sensor_magnet.aq2' || this.obj.modelid === 'lumi.sensor_magnet' ) ) { // Xiaomi Aqara door/window sensor // Xiaomi Mi door/window sensor } else if ( this.obj.manufacturername === 'Heiman' && this.obj.modelid === 'DOOR_TPV13' ) { // Heiman smart door sensor } else if ( this.obj.manufacturername === 'Samjin' && this.obj.modelid === 'multi' ) { // Samsung SmartThings multipurpose sensor } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPOpenClose': // 2.2 this.service = new eve.Services.ContactSensor(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.ContactSensorState, key: 'open', name: 'contact', unit: '', history: 'door', homekitValue: (v) => { return v ? 1 : 0 } } break case 'ZHAHumidity': if ( this.obj.manufacturername === 'LUMI' && ( this.obj.modelid === 'lumi.weather' || this.obj.modelid === 'lumi.sensor_ht' ) ) { // Xiaomi Aqara weather sensor // Xiaomi Mi temperature/humidity sensor } else if (this.obj.modelid === 'lumi.airmonitor.acn01') { // Xiaomi Aquara TVOC Sensor temperatureHistory = 'room2' } else if ( this.obj.manufacturername === 'Heiman' && (this.obj.modelid === 'TH-H_V15' || this.obj.modelid === 'TH-T_V15') ) { // Heiman temperature/humidity sensor } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPHumidity': // 2.5 this.service = new Service.HumiditySensor(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.CurrentRelativeHumidity, key: 'humidity', name: 'humidity', unit: '%', history: temperatureHistory, homekitValue: (v) => { return v ? Math.round(v / 100) : 0 } } break case 'ZHAPressure': if ( this.obj.manufacturername === 'LUMI' && this.obj.modelid === 'lumi.weather' ) { // Xiaomi Aqara weather sensor } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPPressure': this.service = new eve.Services.AirPressureSensor(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: eve.Characteristics.AirPressure, key: 'pressure', name: 'pressure', unit: ' hPa', history: 'weather', homekitValue: (v) => { return v ? Math.round(v) : 0 } } this.service.updateCharacteristic(eve.Characteristics.Elevation, 0) break case 'ZHAAlarm': if ( this.obj.manufacturername.toLowerCase() === 'heiman' && this.obj.modelid.startsWith('WarningDevice') ) { // Heiman Siren } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPAlarm': this.service = new my.Services.Resource(this.name, this.subtype) this.service.addOptionalCharacteristic(my.Characteristics.Alarm) this.serviceList.push(this.service) this.type = { Characteristic: my.Characteristics.Alarm, key: 'alarm', name: 'alarm', homekitValue: (v) => { return v ? 1 : 0 } } break case 'ZHACarbonMonoxide': if ( this.obj.manufacturername === 'Heiman' && this.obj.modelid === 'CO_V16' ) { // Heiman CO sensor } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPCarbonMonoxide': this.service = new Service.CarbonMonoxideSensor(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.CarbonMonoxideDetected, key: 'carbonmonoxide', name: 'CO', unit: '', homekitValue: (v) => { return v ? 1 : 0 } } break case 'ZHAFire': if ( this.obj.manufacturername.toLowerCase() === 'heiman' && ( this.obj.modelid === 'SMOK_V16' || this.obj.modelid === 'SMOK_YDLV10' || this.obj.modelid === 'GAS_V15' || this.obj.modelid === 'SmokeSensor-N-3.0' || this.obj.modelid === 'SmokeSensor-EF-3.0' || this.obj.modelid === 'GASSensor-EM' ) ) { // Heiman fire sensor // Heiman gas sensor } else if ( this.obj.manufacturername === 'Develco Products AS' && ( this.obj.modelid === 'SMSZB-120' || this.obj.modelid === 'HESZB-120' ) ) { // Develco smoke sensor // Develco heat sensor } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPFire': this.service = new Service.SmokeSensor(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.SmokeDetected, key: 'fire', name: 'smoke', unit: '', homekitValue: (v) => { return v ? 1 : 0 } } break case 'ZHAVibration': if ( this.obj.manufacturername === 'LUMI' && this.obj.modelid === 'lumi.vibration.aq1' ) { // Xiaomi vibration sensor } else if ( this.obj.manufacturername === 'Samjin' && this.obj.modelid === 'multi' ) { // Samsung SmartThings multipurpose sensor } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPVibration': this.service = new eve.Services.MotionSensor(this.name, this.subtype) this.serviceList.push(this.service) this.duration = 0 this.type = { Characteristic: Characteristic.MotionDetected, key: 'vibration', name: 'motion', unit: '', history: 'motion', durationKey, homekitValue: (v) => { return v ? 1 : 0 }, sensitivitymax: this.obj.config.sensitivitymax } break case 'ZHAWater': if ( ( this.obj.manufacturername === 'LUMI' && this.obj.modelid === 'lumi.sensor_wleak.aq1' ) || ( this.obj.manufacturername === 'Heiman' && this.obj.modelid === 'WATER_TPV11' ) ) { // Xiaomi Aqara flood sensor // Heiman water sensor } else { this.log.warn( '%s: %s: warning: unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } // falls through case 'CLIPWater': this.service = new Service.LeakSensor(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.LeakDetected, key: 'water', name: 'leak', unit: '', homekitValue: (v) => { return v ? 1 : 0 } } break case 'ZHAConsumption': // falls through case 'CLIPConsumption': if (this.accessory.lightService == null) { this.service = new my.Services.Resource(this.name, this.subtype) } else { this.service = this.accessory.lightService // this.noSetNameCallback = true } this.serviceList.push(this.service) this.service .addOptionalCharacteristic(eve.Characteristics.TotalConsumption) this.type = { Characteristic: eve.Characteristics.TotalConsumption, key: 'consumption', name: 'total consumption', unit: ' kWh', history: 'energy', homekitValue: (v) => { return v / 1000.0 } } break case 'ZHAPower': // falls through case 'CLIPPower': if (this.accessory.lightService == null) { this.service = new my.Services.Resource(this.name, this.subtype) } else { this.service = this.accessory.lightService // this.noSetNameCallback = true } this.serviceList.push(this.service) this.service .addOptionalCharacteristic(eve.Characteristics.Consumption) this.type = { Characteristic: eve.Characteristics.Consumption, key: 'power', name: 'current consumption', unit: ' W', history: 'energy', homekitValue: (v) => { return v } } break case 'ZHAThermostat': if ( this.obj.manufacturername === 'ELKO' && this.obj.modelid === 'Super TR' ) { heatValue = 'heat' } // falls through case 'CLIPThermostat': if (this.obj.config.mode == null) { this.log.warn( '%s: %s: warning: incompatible %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } this.service = new Service.Thermostat(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.CurrentTemperature, key: 'temperature', name: 'temperature', unit: '°C', history: 'thermo', heatValue, homekitValue: (v) => { return v ? Math.round(v / 10) / 10 : 0 } } break case 'ZHATime': this.log.warn( '%s: %s: warning: ignoring unsupported sensor type %s', this.bridge.name, this.resource, this.obj.type ) break case 'Daylight': if ( this.obj.manufacturername === this.bridge.philips && this.obj.modelid === 'PHDL00' ) { // 2.6 - Built-in daylight sensor. if (!this.obj.config.configured) { this.log.warn( '%s: %s: warning: %s sensor not configured', this.bridge.name, this.resource, this.obj.type ) } this.manufacturer = this.obj.manufacturername this.model = this.obj.modelid this.service = new Service.LightSensor(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.CurrentAmbientLightLevel, key: 'lightlevel', name: 'light level', unit: ' lux', homekitValue: hkLightLevel } if (obj.state.status == null) { // Hue bridge obj.state.lightlevel = obj.state.daylight ? 65535 : 0 obj.state.dark = !obj.state.daylight } obj.config.reachable = obj.config.configured } else { this.log.warn( '%s: %s: warning: ignoring unknown %s sensor %j', this.bridge.name, this.resource, this.obj.type, this.obj ) } break case 'ZHABattery': case 'CLIPBattery': this.service = this.accessory.getBatteryService( this.obj.state.battery ) // this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.BatteryLevel, key: 'battery', name: 'battery', unit: '%', homekitValue: (v) => { return toInt(v, 0, 100) } } break case 'CLIPGenericFlag': // 2.8 this.service = new Service.Switch(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.On, key: 'flag', name: 'on', unit: '', homekitValue: (v) => { return v }, bridgeValue: (v) => { return v }, setter: true } // Note that Eve handles a read-only switch correctly, but Home doesn't. if ( this.obj.manufacturername === 'homebridge-hue' && this.obj.modelid === 'CLIPGenericFlag' && this.obj.swversion === '0' ) { this.type.props = { perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] } } break case 'CLIPGenericStatus': // 2.9 if ( this.obj.manufacturername === 'Philips' && this.obj.modelid === 'HUELABSVTOGGLE' && this.obj.swversion === '2.0' ) { // Hue labs toggle, see #1028. this.service = new Service.Switch(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: Characteristic.On, key: 'status', name: 'on', unit: '', homekitValue: (v) => { return v !== 0 }, bridgeValue: (v) => { return v ? 1 : 0 }, setter: true } break } this.service = new my.Services.Status(this.name, this.subtype) this.serviceList.push(this.service) this.type = { Characteristic: my.Characteristics.Status, key: 'status', name: 'status', unit: '', homekitValue: (v) => { return v > 127 ? 127 : v < -127 ? -127 : v }, bridgeValue: (v) => { return v }, setter: true } if ( this.obj.manufacturername === 'homebridge-hue' && this.obj.modelid === 'CLIPGenericStatus' ) { const min = parseInt(obj.swversion.split(',')[0]) const max = parseInt(obj.swversion.split(',')[1]) const step = parseInt(obj.swversion.split(',')[2]) // Eve 3.1 displays the following controls, depending on the properties: // 1. {minValue: 0, maxValue: 1, minStep: 1} switch // 2. {minValue: a, maxValue: b, minStep: 1}, 1 < b - a <= 20 down|up // 3. {minValue: a, maxValue: b}, (a, b) != (0, 1) slider // 4. {minValue: a, maxValue: b, minStep: 1}, b - a > 20 slider // Avoid the following bugs: // 5. {minValue: 0, maxValue: 1} nothing // 6. {minValue: a, maxValue: b, minStep: 1}, b - a = 1 switch* // *) switch sends values 0 and 1 instead of a and b; if (min === 0 && max === 0) { this.type.props = { perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] } } else if (min >= -127 && max <= 127 && min < max) { if (min === 0 && max === 1) { // Workaround Eve bug (case 5 above). this.type.props = { minValue: min, maxValue: max, minStep: 1 } } else if (max - min === 1) { // Workaround Eve bug (case 6 above). this.type.props = { minValue: min, maxValue: max } } else if (step !== 1) { // Default to slider for backwards compatibility. this.type.props = { minValue: min, maxValue: max } } else { this.type.props = { minValue: min, maxValue: max, minStep: 1 } } } this.log.debug( '%s: %s: props: %j', this.bridge.name, this.resource, this.type.props ) } break default: this.log.warn( '%s: %s: warning: ignoring unknown sensor type %j', this.bridge.name, this.resource, this.obj ) break } if (this.service) { if (this.type.Characteristic) { const char = this.service.getCharacteristic(this.type.Characteristic) if (this.type.props) { char.setProps(this.type.props) } if (this.type.setter) { char.on('set', this.setValue.bind(this)) } if (this.type.history != null) { this.historyService = this.accessory .getHistoryService(this.type.history, this) this.history = this.accessory.history if (this.type.history !== this.history.type) { // History service already used for other type. this.historyService = null this.history = null this.type.history = null } const now = Math.round(new Date().valueOf() / 1000) const epoch = Math.round( new Date('2001-01-01T00:00:00Z').valueOf() / 1000 ) switch (this.type.history) { case 'door': this.hk.timesOpened = 0 this.historyService .addOptionalCharacteristic(eve.Characteristics.ResetTotal) this.historyService.getCharacteristic(eve.Characteristics.ResetTotal) .setValue(now - epoch) .on('set', (value, callback) => { this.hk.timesOpened = 0 this.service.updateCharacteristic( eve.Characteristics.TimesOpened, this.hk.timesOpened ) callback(null) }) // falls through case 'motion': this.history.entry.status = 0 break case 'energy': this.service .addOptionalCharacteristic(eve.Characteristics.TotalConsumption) this.service .addOptionalCharacteristic(eve.Characteristics.Consumption) if (this.history.resource.type.key === 'power') { this.history.consumption = 0 this.history.totalConsumption = 0 this.historyService .addOptionalCharacteristic(eve.Characteristics.ResetTotal) this.historyService .getCharacteristic(eve.Characteristics.ResetTotal) .setValue(now - epoch) .on('set', (value, callback) => { this.history.totalConsumption = 0 this.service.updateCharacteristic( eve.Characteristics.TotalConsumption, this.history.totalConsumption ) callback(null) }) } this.history.entry.power = 0 break case 'thermo': this.history.entry.currentTemp = 0 this.history.entry.setTemp = 0 this.history.entry.valvePosition = 0 break case 'weather': this.history.entry.temp = 0 this.history.entry.humidity = 0 this.history.entry.pressure = 0 break case 'room2': this.history.entry.temp = 0 this.history.entry.humidity = 0 this.history.entry.voc = 0 break default: break } } this.checkValue(this.obj.state[this.type.key]) } // if (this.obj.lastseen !== undefined) { // this.service.addOptionalCharacteristic(my.Characteristics.LastSeen) // this.checkLastSeen(this.obj.lastseen) // } this.service.addOptionalCharacteristic(my.Characteristics.LastUpdated) this.checkLastupdated(this.obj.state.lastupdated) if (this.obj.state.dark !== undefined) { this.service.addOptionalCharacteristic(my.Characteristics.Dark) this.checkDark(this.obj.state.dark) } if (this.obj.state.daylight !== undefined) { this.service.addOptionalCharacteristic(my.Characteristics.Daylight) this.checkDaylight(this.obj.state.daylight) } if (this.obj.state.sunrise !== undefined) { this.service.addOptionalCharacteristic(my.Characteristics.Sunrise) this.checkSunrise(this.obj.state.sunrise) } if (this.obj.state.sunset !== undefined) { this.service.addOptionalCharacteristic(my.Characteristics.Sunset) this.checkSunset(this.obj.state.sunset) } if (this.obj.state.tampered !== undefined && this.type.history !== 'door') { this.service.addOptionalCharacteristic(Characteristic.StatusTampered) this.checkTampered(this.obj.state.tampered) } if (this.obj.state.current !== undefined) { this.service.addOptionalCharacteristic(eve.Characteristics.ElectricCurrent) this.checkCurrent(this.obj.state.current) } if (this.obj.state.voltage !== undefined) { this.service.addOptionalCharacteristic(eve.Characteristics.Voltage) this.checkVoltage(this.obj.state.voltage) } if (this.obj.state.on !== undefined) { this.checkStateOn(this.obj.state.on) } if (this.obj.state.valve !== undefined) { this.service.addOptionalCharacteristic(eve.Characteristics.ValvePosition) this.checkValve(this.obj.state.valve) } if ( this.obj.state.daylight !== undefined && this.obj.state.status !== undefined ) { this.service.addOptionalCharacteristic(my.Characteristics.Status) this.service.getCharacteristic(my.Characteristics.Status) .setProps({ minValue: 100, maxValue: 230, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }) this.service.addOptionalCharacteristic(my.Characteristics.LastEvent) this.service.addOptionalCharacteristic(my.Characteristics.Period) this.checkStatus(this.obj.state.status) } if (this.obj.config[this.type.durationKey] !== undefined) { this.checkDuration(this.obj.config[this.type.durationKey]) this.service.getCharacteristic(eve.Characteristics.Duration) .on('set', this.setDuration.bind(this)) delete this.duration } else if (this.duration !== undefined) { // Add fake duration for Hue motion sensor connected to the Hue bridge this.hk.duration = 5 this.service.getCharacteristic(eve.Characteristics.Duration) .setValue(this.hk.duration) .on('set', this.setDuration.bind(this)) } if ( this.obj.config.sensitivity !== undefined && this.obj.type !== 'ZHASwitch' ) { this.checkSensitivity(this.obj.config.sensitivity) if (this.type.sensitivitymax != null) { this.service.getCharacteristic(eve.Characteristics.Sensitivity) .on('set', this.setSensitivity.bind(this)) } } if (this.type.key === 'temperature' && this.obj.config.offset !== undefined) { this.service.addOptionalCharacteristic(my.Characteristics.Offset) this.checkOffset(this.obj.config.offset) this.service.getCharacteristic(my.Characteristics.Offset) .on('set', this.setOffset.bind(this)) } if (this.obj.config.heatsetpoint !== undefined) { this.service.getCharacteristic(Characteristic.CurrentHeatingCoolingState) .setProps({ validValues: [ Characteristic.CurrentHeatingCoolingState.OFF, Characteristic.CurrentHeatingCoolingState.HEAT ] }) this.service.getCharacteristic(Characteristic.TargetHeatingCoolingState) .setProps({ validValues: [ Characteristic.TargetHeatingCoolingState.OFF, Characteristic.TargetHeatingCoolingState.HEAT ] }) .on('set', this.setTargetHeatingCoolingState.bind(this)) this.checkMode(this.obj.config.mode) if (this.obj.config.schedule_on !== undefined) { this.checkScheduleOn(this.obj.config.schedule_on) } this.service.getCharacteristic(Characteristic.TargetTemperature) .setProps({ minValue: 5, maxValue: 30, minStep: 0.5 }) .on('set', this.setTargetTemperature.bind(this)) this.checkHeatSetPoint(this.obj.config.heatsetpoint) this.service.addOptionalCharacteristic(eve.Characteristics.ProgramCommand) this.service.getCharacteristic(eve.Characteristics.ProgramCommand) .on('set', this.setProgramCommand.bind(this)) this.service.addOptionalCharacteristic(eve.Characteristics.ProgramData) this.service.getCharacteristic(eve.Characteristics.ProgramData) // .setValue(Buffer.from('ff04f6', 'hex').toString('base64')) .on('get', this.getProgramData.bind(this)) } if (this.obj.config.displayflipped !== undefined) { this.service.addOptionalCharacteristic(Characteristic.ImageMirroring) this.checkDisplayFlipped(this.obj.config.displayflipped) this.service.getCharacteristic(Characteristic.ImageMirroring) .on('set', this.setMirroring.bind(this)) } if (this.obj.config.locked !== undefined) { this.service.addOptionalCharacteristic(Characteristic.LockPhysicalControls) this.checkLocked(this.obj.config.locked) this.service.getCharacteristic(Characteristic.LockPhysicalControls) .on('set', this.setLocked.bind(this)) } this.service.addOptionalCharacteristic(Characteristic.StatusFault) this.checkReachable(this.obj.config.reachable) this.service.addOptionalCharacteristic(Characteristic.StatusActive) this.service.addOptionalCharacteristic(my.Characteristics.Enabled) this.checkOn(this.obj.config.on) this.service.getCharacteristic(my.Characteristics.Enabled) .on('set', this.setEnabled.bind(this)) if ( this.bridge.platform.config.resource && !this.service.testCharacteristic(my.Characteristics.Resource) ) { this.service.addOptionalCharacteristic(my.Characteristics.Resource) this.service.getCharacteristic(my.Characteristics.Resource) .updateValue(this.resource) } if ( this.bridge.platform.config.configuredName && !this.service.testCharacteristic(Characteristic.ConfiguredName) ) { this.service.addCharacteristic(Characteristic.ConfiguredName) // this.service.addOptionalCharacteristic(Characteristic.ConfiguredName) // this.service.getCharacteristic(Characteristic.ConfiguredName) // .on('set', this.setName.bind(this)) } } if (this.obj.config.battery !== undefined) { this.batteryService = this.accessory.getBatteryService( this.obj.config.battery ) } } HueSensor.prototype.createLabel = function (labelNamespace) { if (this.accessory.labelService == null) { this.service = new Service.ServiceLabel(this.name) this.service.getCharacteristic(Characteristic.ServiceLabelNamespace) .updateValue(labelNamespace) this.accessory.labelService = this.service } else { this.service = this.accessory.labelService // this.noSetNameCallback = true } } HueSensor.prototype.createButton = function (buttonIndex, buttonName, props) { // FIXME: subtype should be based on buttonIndex, not on buttonName. const service = new Service.StatelessProgrammableSwitch( this.name + ' ' + buttonName, buttonName ) this.serviceList.push(service) this.buttonMap['' + buttonIndex] = service service.getCharacteristic(Characteristic.ProgrammableSwitchEvent) .setProps(props) service.getCharacteristic(Characteristic.ServiceLabelIndex) .setValue(buttonIndex) } // ===== Bridge Events ========================================================= HueSensor.prototype.heartbeat = function (beat, obj) { // this.checkName(obj.name) if ( obj.state.daylight != null && obj.state.lightlevel == null && obj.state.status == null ) { // Daylight sensor on Hue bridge. obj.state.lightlevel = obj.state.daylight ? 65535 : 0 obj.state.dark = !obj.state.daylight } this.checkState(obj.state, false) if (obj.config.configured != null && obj.config.reachable == null) { obj.config.reachable = obj.config.configured } this.checkConfig(obj.config, false) } HueSensor.prototype.checkAttr = function (attr, event) { for (const key in attr) { switch (key) { case 'lastannounced': break case 'lastseen': // this.checkLastSeen(attr.lastseen) break // case 'name': // this.checkName(attr.name) // break default: break } } } HueSensor.prototype.checkState = function (state, event) { for (const key in state) { switch (key) { case 'airquality': this.checkAirQuality(state.airquality) break case 'angle': break case 'battery': this.accessory.checkBattery(state.battery) break case 'buttonevent': this.checkButtonevent(state.buttonevent, state.lastupdated) break case 'charging': this.checkCharging(state.charging) break case 'current': this.checkCurrent(state.current) break case 'dark': this.checkDark(state.dark) break case 'daylight': this.checkDaylight(state.daylight) break case 'eventduration': case 'expectedeventduration': break case 'expectedrotation': this.checkButtonevent(state.expectedrotation, state.lastupdated) break case 'gesture': break case 'lastupdated': this.checkLastupdated(state.lastupdated) break case 'lowbattery': break case 'lux': break case 'on': this.checkStateOn(state.on) break case 'orientation': break case 'resetpresence': break case 'rotaryevent': break case 'sunrise': this.checkSunrise(state.sunrise) break case 'sunset': this.checkSunset(state.sunset) break case 'tampered': this.checkTampered(state.tampered) break case 'test': if (state.test) { this.checkValue(true) } break case 'tiltangle': break case 'valve': this.checkValve(state.valve) break case 'vibrationstrength': break case 'voltage': this.checkVoltage(state.voltage) break case 'xy': break default: if (key === this.type.key) { this.checkValue(state[this.type.key]) } else if (key === 'presence') { // Aqara FP1 } else if (key === 'status') { this.checkStatus(state.status) } else if (key === 'power') { // this.checkPower(state.power) } else { this.log.debug( '%s: ignore unknown attribute state.%s', this.name, key ) } break } } } HueSensor.prototype.checkValue = function (value) { if (value === undefined) { return } if (this.obj.state[this.type.key] !== value) { this.log.debug( '%s: sensor %s changed from %j to %j', this.name, this.type.key, this.obj.state[this.type.key], value ) this.obj.state[this.type.key] = value } const hkValue = this.type.homekitValue(this.obj.state[this.type.key]) if (this.durationTimer != null) { if (hkValue !== 0) { clearTimeout(this.durationTimer) this.durationTimer = null this.log.debug( '%s: cancel timer to keep homekit %s on %s%s for %ss', this.name, this.type.name, hkValue, this.type.unit, this.hk.duration ) } return } if (this.hk[this.type.key] !== hkValue) { if (this.duration > 0 && hkValue === 0) { this.log.debug( '%s: keep homekit %s on %s%s for %ss', this.name, this.type.name, this.hk[this.type.key], this.type.unit, this.hk.duration ) const saved = { oldValue: this.hk[this.type.key], value: hkValue, duration: this.hk.duration } this.durationTimer = setTimeout(() => { this.log.info( '%s: set homekit %s from %s%s to %s%s, after %ss', this.name, this.type.name, saved.oldValue, this.type.unit, saved.value, this.type.unit, saved.duration ) this.durationTimer = null this.hk[this.type.key] = saved.value this.service .updateCharacteristic(this.type.Characteristic, this.hk[this.type.key]) this.addEntry(true) }, this.duration * 1000) return } if (this.hk[this.type.key] !== undefined) { this.log.info( '%s: set homekit %s from %s%s to %s%s', this.name, this.type.name, this.hk[this.type.key], this.type.unit, hkValue, this.type.unit ) } this.hk[this.type.key] = hkValue this.service .updateCharacteristic(this.type.Characteristic, this.hk[this.type.key]) this.addEntry(true) if ( this.type.key === 'power' && this.accessory.resource.config != null && this.accessory.resource.config.outlet ) { const hkInUse = hkValue > 0 ? 1 : 0 if (this.hk.inUse !== hkInUse) { if (this.hk.inUse !== undefined) { this.log.info( '%s: set homekit outlet in use from %s to %s', this.name, this.hk.inUse, hkInUse ) } this.hk.inUse = hkInUse this.service.getCharacteristic(Characteristic.OutletInUse) .updateValue(this.hk.inUse) } } } } HueSensor.prototype.addEntry = function (changed) { if (this.history == null) { return } const initialising = this.history.entry.time == null const now = Math.round(new Date().valueOf() / 1000) this.history.entry.time = now switch (this.history.type) { case 'door': if (changed) { this.hk.timesOpened += this.hk[this.type.key] this.service.updateCharacteristic( eve.Characteristics.TimesOpened, this.hk.timesOpened ) } // falls through case 'motion': if (changed) { this.hk.lastActivation = now - this.historyService.getInitialTime() this.service.updateCharacteristic( eve.Characteristics.LastActivation, this.hk.lastActivation ) } this.history.entry.status = this.hk[this.type.key] break case 'energy': if (this.history.resource.type.key === 'power') { if (!initialising) { const delta = this.history.power * (now - this.history.time) // Ws this.history.consumption += Math.round(delta / 600.0) // W * 10 min this.history.totalConsumption += Math.round(delta / 3600.0) // Wh } this.history.power = this.hk.power this.history.time = now } if (changed || this.type.key !== this.history.resource.type.key) { return } if (this.history.resource.type.key === 'power') { this.history.entry.power = this.history.consumption this.history.consumption = 0 this.log.info( '%s: set homekit total consumption to %s kWh', this.name, this.history.totalConsumption / 1000 // kWh ) this.service.updateCharacteristic( eve.Characteristics.TotalConsumption, this.history.totalConsumption ) } else { if (this.history.consumption != null) { const delta = this.obj.state.consumption - this.history.consumption // Wh this.history.entry.power = delta * 6 // W * 10 min if (!this.accessory.resources.sensors.Power) { this.log.info( '%s: set homekit current consumption to %s W', this.name, this.hk.current, delta ) this.service.updateCharacteristic( eve.Characteristics.Consumption, this.history.entry.power ) } } this.history.consumption = this.obj.state.consumption } break case 'thermo': this.history.entry.currentTemp = this.hk.temperature this.history.entry.setTemp = this.hk.targetTemperature this.history.entry.valvePosition = this.hk.valvePosition if (changed) { return } break case 'weather': { const key = this.type.key === 'temperature' ? 'temp' : this.type.key this.history.entry[key] = this.hk[this.type.key] if (changed || this.type.key !== this.history.resource.type.key) { return } } break case 'room2': { const key = this.type.key === 'airqualityppb' ? 'voc' : (this.type.key === 'temperature' ? 'temp' : this.type.key) this.history.entry[key] = this.hk[this.type.key] if (changed || this.type.key !== this.history.resource.type.key) { return } } break default: return } if (initialising) { return } setTimeout(() => { // Make sure all weather entry attributes have been updated const entry = Object.assign({}, this.history.entry) this.log.debug('%s: add history entry %j', this.name, entry) this.historyService.addEntry(entry) }, 0) } HueSensor.prototype.checkButtonevent = function (rawEvent, lastupdated) { const event = this.convertButtonEvent?.(rawEvent) ?? rawEvent const previousEvent = this.convertButtonEvent?.(this.obj.state[this.type.key]) ?? this.obj.state[this.type.key] if ( rawEvent !== this.obj.state[this.type.key] || lastupdated > this.obj.state.lastupdated ) { this.log.debug( '%s: sensor %s %j on %s', this.name, this.type.key, rawEvent, lastupdated ) this.obj.state[this.type.key] = rawEvent } if (event !== previousEvent || lastupdated > this.obj.state.lastupdated) { const buttonIndex = this.type.homekitValue(event) const action = this.type.homekitAction( event, previousEvent, this.repeat != null && this.repeat.includes(buttonIndex) ) if (buttonIndex != null && action != null && this.buttonMap[buttonIndex] != null) { const char = this.buttonMap[buttonIndex] .getCharacteristic(Characteristic.ProgrammableSwitchEvent) if (char.props.validValues.includes(action)) { this.log.info( '%s: homekit button %s', this.buttonMap[buttonIndex].displayName, { 0: 'single press', 1: 'double press', 2: 'long press' }[action] ) char.updateValue(action) } } } } HueSensor.prototype.checkCharging = function (charging) { if (this.obj.state.charging !== charging) { this.log.debug( '%s: charging changed from %j to %j', this.name, this.obj.state.charging, charging ) this.obj.state.charging = charging } const hkCharging = this.obj.state.charging ? Characteristic.ChargingState.CHARGING : Characteristic.ChargingState.NOT_CHARGING if (this.hk.charging !== hkCharging) { if (this.hk.charging !== undefined) { this.log.info( '%s: set homekit charging state from %j to %j', this.name, this.hk.charging, hkCharging ) } this.hk.charging = hkCharging this.service.getCharacteristic(Characteristic.ChargingState) .updateValue(this.hk.charging) } } HueSensor.prototype.checkCurrent = function (current) { if (this.obj.state.current !== current) { this.log.debug( '%s: current changed from %s to %s', this.name, this.obj.state.current, current ) this.obj.state.current = current } const hkCurrent = this.obj.state.current / 1000.0 if (this.hk.current !== hkCurrent) { if (this.hk.current !== undefined) { this.log.info( '%s: set homekit electric current from %s A to %s A', this.name, this.hk.current, hkCurrent ) } this.hk.current = hkCurrent this.service.getCharacteristic(eve.Characteristics.ElectricCurrent) .updateValue(this.hk.current) } } HueSensor.prototype.checkDark = function (dark) { if (this.obj.state.dark !== dark) { this.log.debug( '%s: sensor dark changed from %j to %j', this.name, this.obj.state.dark, dark ) this.obj.state.dark = dark } const hkDark = this.obj.state.dark ? 1 : 0 if (this.hk.dark !== hkDark) { if (this.hk.dark !== undefined) { this.log.info( '%s: set homekit dark from %s to %s', this.name, this.hk.dark, hkDark ) } this.hk.dark = hkDark this.service .updateCharacteristic(my.Characteristics.Dark, this.hk.dark) } } HueSensor.prototype.checkDaylight = function (daylight) { if (this.obj.state.daylight !== daylight) { this.log.debug( '%s: sensor daylight changed from %j to %j', this.name, this.obj.state.daylight, daylight ) this.obj.state.daylight = daylight } const hkDaylight = this.obj.state.daylight ? 1 : 0 if (this.hk.daylight !== hkDaylight) { if (this.hk.daylight !== undefined) { this.log.info( '%s: set homekit daylight from %s to %s', this.name, this.hk.daylight, hkDaylight ) } this.hk.daylight = hkDaylight this.service .updateCharacteristic(my.Characteristics.Daylight, this.hk.daylight) } } // HueSensor.prototype.checkLastSeen = function (lastseen) { // if (this.obj.lastseen !== lastseen) { // // this.log.debug( // // '%s: lastseen changed from %s to %s', this.name, // // this.obj.lastseen, lastseen // // ) // this.obj.lastseen = lastseen // } // const hkLastSeen = dateToString(this.obj.lastseen).slice(0, -3) // if (this.hk.lastSeen !== hkLastSeen) { // // if (this.hk.lastSeen !== undefined) { // // this.log.info( // // '%s: set homekit last seen from %s to %s', this.name, // // this.hk.lastSeen, hkLastSeen // // ) // // } // this.hk.lastSeen = hkLastSeen // this.service.getCharacteristic(my.Characteristics.LastSeen) // .updateValue(this.hk.lastSeen) // } // } HueSensor.prototype.checkLastupdated = function (lastupdated) { if (this.obj.state.lastupdated < lastupdated) { this.log.debug( '%s: sensor lastupdated changed from %s to %s', this.name, this.obj.state.lastupdated, lastupdated ) this.obj.state.lastupdated = lastupdated } const hkLastupdated = dateToString(this.obj.state.lastupdated) if (this.hk.lastupdated !== hkLastupdated) { // this.log.info( // '%s: set homekit last updated from %s to %s', this.name, // this.hk.lastupdated, hkLastupdated // ) this.hk.lastupdated = hkLastupdated this.service .updateCharacteristic(my.Characteristics.LastUpdated, this.hk.lastupdated) } } HueSensor.prototype.checkStatus = function (status) { if (this.obj.state.status !== status) { this.log.debug( '%s: sensor status changed from %j to %j', this.name, this.obj.state.status, status ) this.obj.state.status = status } const hkStatus = this.obj.state.status if (this.hk.status !== hkStatus) { if (this.hk.status !== undefined) { this.log.info( '%s: set homekit status from %s to %s', this.name, this.hk.status, hkStatus ) } this.hk.status = hkStatus this.service .updateCharacteristic(my.Characteristics.Status, this.hk.status) } const daylightEvent = daylightEvents[this.obj.state.status] if (daylightEvent == null) { return } const period = daylightPeriods[daylightEvent.period] this.checkValue(period.lightlevel) const hkEvent = daylightEvent.name if (this.hk.event !== hkEvent) { if (this.hk.event !== undefined) { this.log.info( '%s: set homekit last event from %s to %s', this.name, this.hk.event, hkEvent ) } this.hk.event = hkEvent this.service .updateCharacteristic(my.Characteristics.LastEvent, this.hk.event) } const hkPeriod = daylightEvent.period if (this.hk.period !== hkPeriod) { if (this.hk.period !== undefined) { this.log.info( '%s: set homekit period from %s to %s', this.name, this.hk.period, hkPeriod ) } this.hk.period = hkPeriod this.service .updateCharacteristic(my.Characteristics.Period, this.hk.period) } } HueSensor.prototype.checkStateOn = function (on) { if (this.obj.state.on !== on) { this.log.debug( '%s: sensor on changed from %j to %j', this.name, this.obj.state.on, on ) this.obj.state.on = on } const hkCurrentHeatingCoolingState = on ? Characteristic.CurrentHeatingCoolingState.HEAT : Characteristic.CurrentHeatingCoolingState.OFF if (this.hk.currentHeatingCoolingState !== hkCurrentHeatingCoolingState) { if (this.hk.currentHeatingCoolingState !== undefined) { this.log.info( '%s: set homekit current heating cooling state from %s to %s', this.name, this.hk.currentHeatingCoolingState, hkCurrentHeatingCoolingState ) } this.hk.currentHeatingCoolingState = hkCurrentHeatingCoolingState this.service.updateCharacteristic( Characteristic.CurrentHeatingCoolingState, this.hk.currentHeatingCoolingState ) } } HueSensor.prototype.checkSunrise = function (sunrise) { if (this.obj.state.sunrise !== sunrise) { this.log.debug( '%s: sensor sunrise changed from %s to %s', this.name, this.obj.state.sunrise, sunrise ) this.obj.state.sunrise = sunrise } const hkSunrise = dateToString(this.obj.state.sunrise) if (this.hk.sunrise !== hkSunrise) { if (this.hk.sunrise !== undefined) { this.log.info( '%s: set homekit sunrise from %s to %s', this.name, this.hk.sunrise, hkSunrise ) } this.hk.sunrise = hkSunrise this.service .updateCharacteristic(my.Characteristics.Sunrise, this.hk.sunrise) } } HueSensor.prototype.checkSunset = function (sunset) { if (this.obj.state.sunset !== sunset) { this.log.debug( '%s: sensor sunset changed from %s to %s', this.name, this.obj.state.sunset, sunset ) this.obj.state.sunset = sunset } const hkSunset = dateToString(this.obj.state.sunset) if (this.hk.sunset !== hkSunset) { if (this.hk.sunset !== undefined) { this.log.info( '%s: set homekit sunset from %s to %s', this.name, this.hk.sunset, hkSunset ) } this.hk.sunset = hkSunset this.service .updateCharacteristic(my.Characteristics.Sunset, this.hk.sunset) } } HueSensor.prototype.checkTampered = function (tampered) { if (this.type.history === 'door') { return } if (this.obj.state.tampered !== tampered) { this.log.debug( '%s: sensor tampered changed from %j to %j', this.name, this.obj.state.tampered, tampered ) this.obj.state.tampered = tampered } const hkTampered = this.obj.state.tampered ? 1 : 0 if (this.hk.tampered !== hkTampered) { if (this.hk.tampered !== undefined) { this.log.info( '%s: set homekit status tampered from %s to %s', this.name, this.hk.tampered, hkTampered ) } this.hk.tampered = hkTampered this.service .updateCharacteristic(Characteristic.StatusTampered, this.hk.tampered) } } HueSensor.prototype.checkValve = function (valve) { if (this.obj.state.valve !== valve) { this.log.debug( '%s: valve changed from %j to %j', this.name, this.obj.state.valve, valve ) this.obj.state.valve = valve } const hkValve = Math.round(this.obj.state.valve / 2.55) if (this.hk.valvePosition !== hkValve) { if (this.hk.valvePosition !== undefined) { this.log.info( '%s: set homekit valve position from %s% to %s%', this.name, this.hk.valvePosition, hkValve ) } this.hk.valvePosition = hkValve this.service.getCharacteristic(eve.Characteristics.ValvePosition) .updateValue(this.hk.valvePosition) } } HueSensor.prototype.checkVoltage = function (voltage) { if (this.obj.state.voltage !== voltage) { this.log.debug( '%s: voltage changed from %j to %j', this.name, this.obj.state.voltage, voltage ) this.obj.state.voltage = voltage } const hkVoltage = this.obj.state.voltage if (this.hk.voltage !== hkVoltage) { if (this.hk.voltage !== undefined) { this.log.info( '%s: set homekit voltage from %s V to %s V', this.name, this.hk.voltage, hkVoltage ) } this.hk.voltage = hkVoltage this.service.getCharacteristic(eve.Characteristics.Voltage) .updateValue(this.hk.voltage) } } HueSensor.prototype.checkAirQuality = function (airquality) { if (this.obj.state.airquality !== airquality) { this.log.debug( '%s: airquality changed from %j to %j', this.name, this.obj.state.airquality, airquality ) this.obj.state.airquality = airquality } let hkAirQuality = airQualityValues[airquality] if (!hkAirQuality) { hkAirQuality = Characteristic.AirQuality.UNKNOWN } if (this.hk.airquality !== hkAirQuality) { if (this.hk.airquality !== undefined) { this.log.info( '%s: set homekit airquality from %s to %s', this.name, this.hk.airquality, hkAirQuality ) } this.hk.airquality = hkAirQuality this.service.getCharacteristic(Characteristic.AirQuality) .updateValue(this.hk.airquality) } } HueSensor.prototype.checkConfig = function (config) { for (const key in config) { switch (key) { case 'alert': break case 'battery': this.accessory.checkBattery(config.battery) break case 'configured': break case 'delay': if (this.type.durationKey === 'delay') { this.checkDuration(config.delay) } break case 'devicemode': if (config.devicemode !== this.obj.config.devicemode) { this.log.warn( '%s: restart homebridge to handle new devicemode %s', this.name, config.devicemode ) this.obj.config.devicemode = config.devicemode } break case 'devicemodevalues': break case 'displayflipped': this.checkDisplayFlipped(config.displayflipped) break case 'duration': this.checkDuration(config.duration) break case 'enrolled': break case 'group': break case 'heatsetpoint': this.checkHeatSetPoint(config.heatsetpoint) break case 'lastchange': break case 'ledindication': break case 'locked': this.checkLocked(config.locked) break case 'mode': this.checkMode(config.mode) break case 'offset': this.checkOffset(config.offset) break case 'on': this.checkOn(config.on) break case 'pending': break case 'reachable': this.checkReachable(config.reachable) break case 'schedule': case 'scheduler': case 'scheduleron': break case 'schedule_on': this.checkScheduleOn(config.schedule_on) break case 'sensitivity': this.checkSensitivity(config.sensitivity) break case 'sensitivitymax': break case 'sunriseoffset': break case 'sunsetoffset': break case 'temperature': break case 'tholddark': break case 'tholdoffset': break case 'triggerdistance': break case 'usertest': break default: this.log.debug( '%s: ignore unknown attribute config.%s', this.name, key ) break } } } HueSensor.prototype.checkDisplayFlipped = function (displayflipped) { if (this.obj.config.displayflipped !== displayflipped) { this.log.debug( '%s: sensor displayflipped changed from %j to %j', this.name, this.obj.config.displayflipped, displayflipped ) this.obj.config.displayflipped = displayflipped } const hkMirroring = this.obj.config.displayflipped if (this.hk.mirroring !== hkMirroring) { if (this.hk.mirroring !== undefined) { this.log.info( '%s: set homekit mirroring from %s to %s', this.name, this.hk.mirroring, hkMirroring ) } this.hk.mirroring = hkMirroring this.service .updateCharacteristic(Characteristic.ImageMirroring, this.hk.mirroring) } } HueSensor.prototype.checkDuration = function (duration) { if (this.type.name !== 'motion') { // Workaround while IAS Zone sensors are exposed as ZHAPresence return } if (this.obj.config[this.type.durationKey] !== duration) { this.log.debug( '%s: sensor %s changed from %j to %j', this.name, this.type.durationKey, this.obj.config[this.type.durationKey], duration ) this.obj.config[this.type.durationKey] = duration } const char = this.service.getCharacteristic(eve.Characteristics.Duration) let hkDuration for (const value of char.props.validValues) { hkDuration = value if (this.obj.config[this.type.durationKey] <= value) { break } } if (this.hk.duration !== hkDuration) { if (this.hk.duration !== undefined) { this.log.info( '%s: set homekit duration from %ss to %ss', this.name, this.hk.duration, hkDuration ) } this.hk.duration = hkDuration this.service .updateCharacteristic(eve.Characteristics.Duration, this.hk.duration) } } HueSensor.prototype.checkHeatSetPoint = function (heatsetpoint) { if (this.obj.config.heatsetpoint !== heatsetpoint) { this.log.debug( '%s: sensor heatsetpoint changed from %j to %j', this.name, this.obj.config.heatsetpoint, heatsetpoint ) this.obj.config.heatsetpoint = heatsetpoint } const hkTargetTemperature = Math.round(this.obj.config.heatsetpoint / 50) / 2 if (this.hk.targetTemperature !== hkTargetTemperature) { if (this.hk.targetTemperature !== undefined) { this.log.info( '%s: set homekit target temperature from %s°C to %s°C', this.name, this.hk.targetTemperature, hkTargetTemperature ) } this.hk.targetTemperature = hkTargetTemperature this.service.updateCharacteristic( Characteristic.TargetTemperature, this.hk.targetTemperature ) } } HueSensor.prototype.checkLocked = function (locked) { if (this.obj.config.locked !== locked) { this.log.debug( '%s: sensor locked changed from %j to %j', this.name, this.obj.config.locked, locked ) this.obj.config.locked = locked } const hkLocked = this.obj.config.locked ? 1 : 0 if (this.hk.locked !== hkLocked) { if (this.hk.locked !== undefined) { this.log.info( '%s: set homekit locked from %s to %s', this.name, this.hk.locked, hkLocked ) } this.hk.locked = hkLocked this.service .updateCharacteristic(Characteristic.LockPhysicalControls, this.hk.locked) } } HueSensor.prototype.checkMode = function (mode) { if (this.obj.type !== 'ZHAThermostat') { return } if (this.obj.config.mode !== mode) { this.log.debug( '%s: sensor mode changed from %j to %j', this.name, this.obj.config.mode, mode ) this.obj.config.mode = mode } const hkTargetHeatingCoolingState = mode === 'off' ? Characteristic.TargetHeatingCoolingState.OFF : Characteristic.TargetHeatingCoolingState.HEAT if (this.hk.targetHeatingCoolingState !== hkTargetHeatingCoolingState) { if (this.hk.targetHeatingCoolingState !== undefined) { this.log.info( '%s: set homekit target heating cooling state from %s to %s', this.name, this.hk.targetHeatingCoolingState, hkTargetHeatingCoolingState ) } this.hk.targetHeatingCoolingState = hkTargetHeatingCoolingState this.service.getCharacteristic(Characteristic.TargetHeatingCoolingState) .updateValue(this.hk.targetHeatingCoolingState) } } // HueSensor.prototype.checkName = function (name) { // if (this.obj.name !== name) { // this.log.debug( // '%s: name changed from %j to %j', this.name, this.obj.name, name // ) // this.obj.name = name // } // const hkName = this.obj.name // if (this.hk.name !== hkName) { // if (this.hk.name !== undefined) { // this.log.info( // '%s: set homekit name from %j to %j', this.name, this.hk.name, hkName // ) // } // this.hk.name = hkName // this.service.getCharacteristic(Characteristic.ConfiguredName) // .updateValue(hkName) // this.name = this.hk.name // } // } HueSensor.prototype.checkOffset = function (offset) { if (this.type.key !== 'temperature') { return } if (this.obj.config.offset !== offset) { this.log.debug( '%s: sensor offset changed from %j to %j', this.name, this.obj.config.offset, offset ) this.obj.config.offset = offset } let hkOffset = toInt(this.obj.config.offset, -500, 500) hkOffset = Math.round(hkOffset / 10) / 10 if (this.hk.offset !== hkOffset) { if (this.hk.offset !== undefined) { this.log.info( '%s: set homekit offset from %s°C to %s°C', this.name, this.hk.offset, hkOffset ) } this.hk.offset = hkOffset this.service .updateCharacteristic(my.Characteristics.Offset, this.hk.offset) } } HueSensor.prototype.checkOn = function (on) { if (this.obj.config.on !== on) { this.log.debug( '%s: sensor on changed from %j to %j', this.name, this.obj.config.on, on ) this.obj.config.on = on } const hkEnabled = this.obj.config.on if (this.hk.enabled !== hkEnabled) { if (this.hk.enabled !== undefined) { this.log.info( '%s: set homekit enabled from %s to %s', this.name, this.hk.enabled, hkEnabled ) } this.hk.enabled = hkEnabled this.service .updateCharacteristic(Characteristic.StatusActive, this.hk.enabled) .updateCharacteristic(my.Characteristics.Enabled, this.hk.enabled) } } HueSensor.prototype.checkReachable = function (reachable) { if (this.obj.config.reachable !== reachable) { this.log.debug( '%s: sensor reachable changed from %j to %j', this.name, this.obj.config.reachable, reachable ) this.obj.config.reachable = reachable } const hkFault = this.obj.config.reachable === false ? 1 : 0 if (this.hk.fault !== hkFault) { if (this.hk.fault !== undefined) { this.log.info( '%s: set homekit status fault from %s to %s', this.name, this.hk.fault, hkFault ) } this.hk.fault = hkFault this.service.getCharacteristic(Characteristic.StatusFault) .updateValue(this.hk.fault) } } HueSensor.prototype.checkScheduleOn = function (scheduleOn) { if (this.obj.config.schedule_on !== scheduleOn) { this.log.debug( '%s: sensor schedule_on changed from %j to %j', this.name, this.obj.config.scheduleOn, scheduleOn ) this.obj.config.schedule_on = scheduleOn } } HueSensor.prototype.checkSensitivity = function (sensitivity) { if (this.obj.config.sensitivity == null || this.obj.type === 'ZHASwitch') { return } if (this.obj.config.sensitivity !== sensitivity) { this.log.debug( '%s: sensor sensitivity changed from %j to %j', this.name, this.obj.config.sensitivity, sensitivity ) this.obj.config.sensitivity = sensitivity } const hkSensitivity = sensitivity === this.type.sensitivitymax ? 0 : sensitivity === 0 ? 7 : 4 if (this.hk.sensitivity !== hkSensitivity) { if (this.hk.sensitivity !== undefined) { this.log.info( '%s: set homekit sensitivity from %s to %s', this.name, this.hk.sensitivity, hkSensitivity ) } this.hk.sensitivity = hkSensitivity this.service.updateCharacteristic( eve.Characteristics.Sensitivity, this.hk.sensitivity ) } } // ===== Homekit Events ======================================================== HueSensor.prototype.identify = function (callback) { if (this.obj.config.alert === undefined) { return callback() } this.log.info('%s: identify', this.name) this.put('/config', { alert: 'select' }).then((obj) => { return callback() }).catch((error) => { return callback(error) }) } HueSensor.prototype.setValue = function (value, callback) { if (typeof value === 'number') { value = Math.round(value) } if (value === this.hk[this.type.key]) { return callback() } this.log.info( '%s: homekit %s changed from %s%s to %s%s', this.name, this.type.name, this.hk[this.type.key], this.type.unit, value, this.type.unit ) this.hk[this.type.key] = value const newValue = this.type.bridgeValue(value) const body = {} body[this.type.key] = newValue this.put('/state', body).then((obj) => { this.obj.state[this.type.key] = newValue this.value = newValue return callback() }).catch((error) => { return callback(error) }) } HueSensor.prototype.setDuration = function (duration, callback) { if (duration === this.hk.duration) { return callback() } this.log.info( '%s: homekit duration changed from %ss to %ss', this.name, this.hk.duration, duration ) this.hk.duration = duration const hueDuration = duration === 5 ? 0 : duration if (this.duration !== undefined) { this.duration = hueDuration return callback() } const body = {} body[this.type.durationKey] = hueDuration this.put('/config', body).then((obj) => { this.obj.config[this.type.durationKey] = hueDuration return callback() }).catch((error) => { return callback(error) }) } HueSensor.prototype.setEnabled = function (enabled, callback) { if (enabled === this.hk.enabled) { return callback() } this.log.info( '%s: homekit enabled changed from %s to %s', this.name, this.hk.enabled, enabled ) this.hk.enabled = enabled const on = this.hk.enabled this.put('/config', { on }).then((obj) => { this.obj.config.on = on this.service .updateCharacteristic(Characteristic.StatusActive, this.hk.enabled) return callback() }).catch((error) => { return callback(error) }) } HueSensor.prototype.setLocked = function (locked, callback) { if (locked === this.hk.locked) { return callback() } this.log.info( '%s: homekit locked changed from %s to %s', this.name, this.hk.locked, locked ) this.hk.locked = locked const hueLocked = !!this.hk.locked this.put('/config', { locked: hueLocked }).then((obj) => { this.obj.config.locked = hueLocked return callback() }).catch((error) => { return callback(error) }) } HueSensor.prototype.setMirroring = function (mirroring, callback) { if (mirroring === this.hk.mirroring) { return callback() } this.log.info( '%s: homekit mirroring changed from %s to %s', this.name, this.hk.mirroring, mirroring ) this.hk.mirroring = mirroring const displayflipped = this.hk.mirroring this.put('/config', { displayflipped }).then((obj) => { this.obj.config.displayflipped = displayflipped return callback() }).catch((error) => { return callback(error) }) } // HueSensor.prototype.setName = function (name, callback) { // if (this.noSetNameCallback) { // callback = () => {} // } // if (name === this.hk.name) { // return callback() // } // name = name.trim() // .slice(0, 32).trim() // if (name === '') { // return callback(new Error()) // } // this.log.info( // '%s: homekit name changed from %j to %j', this.name, this.hk.name, name // ) // this.put('', { name: name }).then((obj) => { // if (obj.name == null) { // this.obj.name = name // this.hk.name = name // return callback(new Error()) // } // this.obj.name = obj.name // this.name = obj.name // setImmediate(() => { // this.hk.name = name // this.service.getCharacteristic(Characteristic.ConfiguredName) // .updateValue(this.hk.name) // }) // return callback() // }).catch((error) => { // return callback(error) // }) // } HueSensor.prototype.setOffset = function (offset, callback) { offset = Math.round(offset * 10) / 10 if (offset === this.hk.offset) { return callback() } this.log.info( '%s: homekit offset changed from %s to %s', this.name, this.hk.offset, offset ) this.hk.offset = offset const hueOffset = Math.round(offset * 100) this.put('/config', { offset: hueOffset }).then((obj) => { this.obj.config.offset = hueOffset return callback() }).catch((error) => { return callback(error) }) } HueSensor.prototype.setProgramCommand = function (value, callback) { const buffer = Buffer.from(value, 'base64') value = buffer.toString('hex') this.log.debug( '%s: homekit program command changed to %s', this.name, buffer.toString('hex').toUpperCase() ) let offset let scheduleOn for (let i = 0; i < buffer.length; i++) { const opcode = buffer[i] switch (opcode) { case 0x00: // Begin this.log.debug('%s: 00 begin', this.name) break case 0x06: // End this.log.debug('%s: 06 end', this.name) break case 0x12: // Offset offset = buffer.readInt8(++i) / 10 this.log.debug('%s: 12 offset: %s°C', this.name, offset.toFixed(1)) break case 0x13: // Schedule Enable scheduleOn = buffer[++i] === 1 this.log.debug('%s: 13 schudule_on %s', this.name, scheduleOn) break case 0x1A: // Away transitions { let s = '' for (let j = 1; j <= 8; j++) { if (buffer[i + j] !== 0xFF) { const time = buffer[i + j] * 10 const h = ('0' + Math.floor(time / 60)).slice(-2) const m = ('0' + time % 60).slice(-2) s += ' ' + h + ':' + m } } this.log.debug('%s: Free%s', this.name, s) i += 8 } break case 0xF4: // Temperature { const now = (buffer[++i] / 2).toFixed(1) const low = (buffer[++i] / 2).toFixed(1) const high = (buffer[++i] / 2).toFixed(1) this.log.debug('%s: F4 temp: %s°C, %s°C, %s°C', this.name, now, low, high) } break case 0xFC: // Time { const n = ('0' + buffer[++i]).slice(-2) const h = ('0' + buffer[++i]).slice(-2) const d = ('0' + buffer[++i]).slice(-2) const m = ('0' + buffer[++i]).slice(-2) const y = 2000 + buffer[++i] this.log.debug('%s: FC time: %s-%s-%sT%s:%s', this.name, y, m, d, h, n) } break case 0xFA: // Daily transitions for (let d = 0; d <= 6; d++) { let s = '' for (let j = 1; j <= 8; j++) { if (buffer[i + j] !== 0xFF) { const time = buffer[i + j] * 10 const h = ('0' + Math.floor(time / 60)).slice(-2) const m = ('0' + time % 60).slice(-2) s += ' ' + h + ':' + m } } this.log.debug( '%s: %s %s', this.name, ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][d], s ) i += 8 } break case 0xFF: // Reset? i += 2 this.log.debug('%s: FF reset', this.name) break default: // Unknown this.log.debug( '%s: %s', this.name, ('00' + buffer[i].toString(16).toUpperCase()).slice(-2) ) break } } if (scheduleOn != null) { if (this.obj.config.schedule_on !== scheduleOn) { this.put('/config', { schedule_on: scheduleOn }).then((obj) => { this.obj.config.schedule_on = scheduleOn return callback() }) return } } if (offset != null) { offset *= 100 if (this.obj.config.offset !== offset) { this.put('/config', { offset }).then((obj) => { this.obj.config.offset = offset return callback() }) return } } callback() } HueSensor.prototype.getProgramData = function (callback) { let buffer = Buffer.alloc(1024) let offset = 0 // Temperature Offset buffer[offset++] = 0x12 buffer[offset++] = Math.round(this.obj.config.offset / 50) * 5 // Scheduler buffer[offset++] = 0x13 buffer[offset++] = this.obj.config.schedule_on ? 0x01 : 0x00 // Install Status buffer[offset++] = 0x14 buffer[offset++] = 0xC0 // Vacation buffer[offset++] = 0x19 buffer[offset++] = 0x00 buffer[offset++] = 0xFF // Temperature buffer[offset++] = 0xF4 buffer[offset++] = 15 * 2 buffer[offset++] = 15 * 2 buffer[offset++] = 15 * 2 buffer[offset++] = 15 * 2 // Time buffer[offset++] = 0xFC const dt = new Date() buffer[offset++] = dt.getMinutes() buffer[offset++] = dt.getHours() buffer[offset++] = dt.getDate() buffer[offset++] = dt.getMonth() + 1 buffer[offset++] = dt.getFullYear() - 2000 // Open Window buffer[offset++] = 0xF6 buffer[offset++] = 0x00 buffer[offset++] = 0x00 buffer[offset++] = 0x00 // Schedule buffer[offset++] = 0xFA for (let d = 0; d <= 6; d++) { buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF } // Free day buffer[offset++] = 0x1A buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer[offset++] = 0xFF buffer = buffer.slice(0, offset) this.log.debug( '%s: get homekit program data return %s', this.name, buffer.toString('hex') ) return callback(null, buffer.toString('base64')) } HueSensor.prototype.setTargetHeatingCoolingState = function ( targetHeatingCoolingState, callback ) { if (targetHeatingCoolingState === this.hk.targetHeatingCoolingState) { return callback() } this.log.info( '%s: homekit target heating cooling state changed from %s to %s', this.name, this.hk.targetHeatingCoolingState, targetHeatingCoolingState ) this.hk.targetHeatingCoolingState = targetHeatingCoolingState let mode switch (this.hk.targetHeatingCoolingState) { case Characteristic.TargetHeatingCoolingState.OFF: mode = 'off' break case Characteristic.TargetHeatingCoolingState.HEAT: default: mode = this.type.heatValue break } this.put('/config', { mode }).then((obj) => { this.obj.config.mode = mode return callback() }).catch((error) => { return callback(error) }) } HueSensor.prototype.setTargetTemperature = function (targetTemperature, callback) { if (targetTemperature === this.hk.targetTemperature) { return callback() } this.log.info( '%s: homekit target temperature changed from %s°C to %s°C', this.name, this.hk.targetTemperature, targetTemperature ) this.hk.targetTemperature = targetTemperature const hueHeatSetPoint = Math.round(targetTemperature * 100) this.put('/config', { heatsetpoint: hueHeatSetPoint }).then((obj) => { this.obj.config.heatsetpoint = hueHeatSetPoint return callback() }).catch((error) => { return callback(error) }) } HueSensor.prototype.setSensitivity = function (sensitivity, callback) { if (sensitivity === this.hk.sensitivity) { return callback() } this.log.info( '%s: homekit sensitivity changed from %s to %s', this.name, this.hk.sensitivity, sensitivity ) this.hk.sensitivity = sensitivity const hueSensitivity = this.hk.sensitivity === 0 ? this.type.sensitivitymax : this.hk.sensitivity === 7 ? 0 : Math.round(this.type.sensitivitymax / 2) this.put('/config', { sensitivity: hueSensitivity }).then((obj) => { this.obj.config.sensitivity = hueSensitivity return callback() }).catch((error) => { return callback(error) }) } HueSensor.prototype.put = function (resource, body) { return this.bridge.put(this.resource + resource, body) }
const path = require('path') const CleanWebpackPlugin = require('clean-webpack-plugin') const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin module.exports = { entry: ['babel-polyfill', path.resolve('src/front', 'app.js')], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), publicPath: 'dist/', pathinfo: false }, resolve: { modules: [path.join(__dirname, 'src'), 'node_modules'] }, resolveLoader: { moduleExtensions: ['-loader'] }, plugins: [new CleanWebpackPlugin(['dist']), new BundleAnalyzerPlugin()], module: { rules: [ { test: /\.vue$/, loader: 'vue' }, { test: /\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\.html$/, use: [{ loader: 'vue-html' }] }, { test: /\.css/, use: ['style', 'css'] }, { test: /\.scss/, use: ['style', 'css', 'sass'] }, { test: /\.(png|jpg|gif|svg)$/, loader: 'url?limit=100000&name=../img/[name].[ext]' }, { test: /\.(woff(2)?|eot|otf|ttf|svg)(\?[a-z0-9=\.]+)?$/, loader: 'file?name=../fonts/[name].[ext]' } ] } }
import styles from './_NavItem.scss'; import React from 'react'; import classNames from "classnames" let { PropTypes } = React; export default class NavItem extends React.Component { static defaultProps = { }; static propTypes = { page: PropTypes.object, selected: PropTypes.bool, onItemClick: PropTypes.func }; getClassName() { return classNames(styles.navItem, { [styles["navItem--selected"]]: this.props.selected, }, this.props.className) } render() { return ( <li className={this.getClassName()} onClick={!this.props.selected && this.props.onItemClick.bind(this, this.props.page)}> <h2 className={styles.label}>{this.props.page.name}</h2> </li> ); } }
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { genre:"All", tracks: [ { num:0, album:"All", genre:"All", }, { num:1, track:"Great Big White World ", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.20902777777777778 }, { num:2, track:"The Dope Show", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.15694444444444444 }, { num:3, track:"Mechanical Animals", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.18958333333333333 }, { num:4, track:"Rock Is Dead", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.13125 }, { num:"5.", track:"Disassociative", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.2013888888888889 }, { num:"6.", track:"The Speed of Pain", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.22916666666666666 }, { num:7, track:"Posthuman", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.17847222222222223 }, { num:8, track:"I Want to Disappear", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.12222222222222222 }, { num:9, track:"I Don't Like the Drugs (But the Drugs Like Me)", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.21041666666666667 }, { num:10, track:"New Model No. 15", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.1527777777777778 }, { num:11, track:"User Friendly", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.17847222222222223 }, { num:12, track:"Fundamentally Loathsome", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.20069444444444445 }, { num:13, track:"«The Last Day on Earth»", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.20902777777777778 }, { num:14, track:"Coma White", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.23472222222222222 }, { num:15, track:"Без названия (Untitled)", artist:"Marilyn Manson", album:"Mechanical Animals", genre:"Industrial Metal", time:0.05694444444444444 }, { num:1, track:"Bullet Ride", artist:"In Flames", album:"Clayman", genre:"MDM", time:0.19583333333333333 }, { num:2, track:"Pinball Map", artist:"In Flames", album:"Clayman", genre:"MDM", time:0.17222222222222222 }, { num:3, track:"Only for the Weak", artist:"In Flames", album:"Clayman", genre:"MDM", time:0.2048611111111111 }, { num:4, track:"...as the Future Repeats Today", artist:"In Flames", album:"Clayman", genre:"MDM", time:0.14375 }, { num:"5.", track:"Square Nothing", artist:"In Flames", album:"Clayman", genre:"MDM", time:0.16458333333333333 }, { num:"6.", track:"Clay man", artist:"In Flames", album:"Clayman", genre:"MDM", time:0.14444444444444443 }, { num:7, track:"Satellites and Astronauts", artist:"In Flames", album:"Clayman", genre:"MDM", time:0.20833333333333334 }, { num:8, track:"Brush the Dust Away", artist:"In Flames", album:"Clayman", genre:"MDM", time:0.13680555555555557 }, { num:9, track:"Swim", artist:"In Flames", album:"Clayman", genre:"MDM", time:0.13472222222222222 }, { num:10, track:"Suburban Me", artist:"In Flames", album:"Clayman", genre:"MDM", time:0.14930555555555555 }, { num:11, track:"Another Day in Quicksand", artist:"In Flames", album:"Clayman", genre:"MDM", time:0.1638888888888889 }, { num:1, track:"Inertia", artist:"Insomnium", album:"One for Sorrow", genre:"MDM", time:0.15486111111111112 }, { num:2, track:"Through the Shadows", artist:"Insomnium", album:"One for Sorrow", genre:"MDM", time:0.18819444444444444 }, { num:3, track:"Song of the Blackest Bird", artist:"Insomnium", album:"One for Sorrow", genre:"MDM", time:0.31180555555555556 }, { num:4, track:"Only One Who Waits", artist:"Insomnium", album:"One for Sorrow", genre:"MDM", time:0.22013888888888888 }, { num:"5.", track:"Unsung", artist:"Insomnium", album:"One for Sorrow", genre:"MDM", time:0.2111111111111111 }, { num:"6.", track:"Every Hour Wounds", artist:"Insomnium", album:"One for Sorrow", genre:"MDM", time:0.22569444444444445 }, { num:7, track:"Decoherence", artist:"Insomnium", album:"One for Sorrow", genre:"MDM", time:0.1375 }, { num:8, track:"Lay the Ghost to Rest", artist:"Insomnium", album:"One for Sorrow", genre:"MDM", time:0.3236111111111111 }, { num:9, track:"Regain the Fire", artist:"Insomnium", album:"One for Sorrow", genre:"MDM", time:0.18541666666666667 }, { num:10, track:"One for Sorrow", artist:"Insomnium", album:"One for Sorrow", genre:"MDM", time:0.2548611111111111 }, { num:1, track:"Chertograd ", artist:"Deathstars", album:"Night Electric Night", genre:"Industrial Metal", time:0.19791666666666666 }, { num:2, track:"Night Electric Night", artist:"Deathstars", album:"Night Electric Night", genre:"Industrial Metal", time:0.16944444444444445 }, { num:3, track:"Death Dies Hard ", artist:"Deathstars", album:"Night Electric Night", genre:"Industrial Metal", time:0.13958333333333334 }, { num:4, track:"The Mark of the Gun ", artist:"Deathstars", album:"Night Electric Night", genre:"Industrial Metal", time:0.16805555555555557 }, { num:5, track:"Via the End", artist:"Deathstars", album:"Night Electric Night", genre:"Industrial Metal", time:0.17152777777777778 }, { num:6, track:"Blood Stains Blondes ", artist:"Deathstars", album:"Night Electric Night", genre:"Industrial Metal", time:0.13541666666666666 }, { num:7, track:"Babylon ", artist:"Deathstars", album:"Night Electric Night", genre:"Industrial Metal", time:0.17916666666666667 }, { num:8, track:"The Fuel Ignites ", artist:"Deathstars", album:"Night Electric Night", genre:"Industrial Metal", time:0.16666666666666666 }, { num:9, track:"Arclight ", artist:"Deathstars", album:"Night Electric Night", genre:"Industrial Metal", time:0.1909722222222222 }, { num:10, track:"Venus in Arms ", artist:"Deathstars", album:"Night Electric Night", genre:"Industrial Metal", time:0.16805555555555557 }, { num:11, track:"Opium ", artist:"Deathstars", album:"Night Electric Night", genre:"Industrial Metal", time:0.15486111111111112 }, { num:1, track:"Sa Bir", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.08333333333333333 }, { num:2, track:"Vinushka", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.40069444444444446 }, { num:3, track:"Red Soil", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.14166666666666666 }, { num:4, track:"Dōkoku to Sarinu ", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.15833333333333333 }, { num:5, track:"Toguro ", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.16458333333333333 }, { num:6, track:"Glass Skin", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.18541666666666667 }, { num:7, track:"Stuck Man", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.1486111111111111 }, { num:8, track:"Reiketsu Nariseba", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.14791666666666667 }, { num:9, track:"Ware, Yami Tote… ", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.2923611111111111 }, { num:10, track:"Bugaboo", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.19652777777777777 }, { num:11, track:"Gaika, Chinmoku ga Nemuru Koro", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.18194444444444444 }, { num:12, track:"Dozing Green", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.1701388888888889 }, { num:13, track:"Inconvenient Ideal", artist:"DIR EN GREY", album:"UROBOROS", genre:"Avant-garde Metal", time:0.18263888888888888 }, { num:1, track:"Kyōkotsu no Nari ", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.08194444444444444 }, { num:2, track:"The Blossoming Beelzebub", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.3159722222222222 }, { num:3, track:"Different Sense", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.21041666666666667 }, { num:4, track:"Amon", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.16875 }, { num:5, track:"Yokusō ni Dreambox' Aruiwa Seijuku no Rinen to Tsumetai Ame", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.20069444444444445 }, { num:6, track:"Jūyoku", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.14444444444444443 }, { num:7, track:"Shitataru Mōrō ", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.16805555555555557 }, { num:8, track:"Lotus", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.16875 }, { num:9, track:"Diabolos", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.41041666666666665 }, { num:10, track:"Akatsuki", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.14791666666666667 }, { num:11, track:"Decayed Crow", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.15833333333333333 }, { num:12, track:"Hageshisa to, Kono Mune no Naka de Karamitsuita Shakunetsu no Yami", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.16875 }, { num:13, track:"Vanitas ", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.22708333333333333 }, { num:14, track:"Ruten no Tō ", artist:"DIR EN GREY", album:"DUM SPIRO SPERO", genre:"Avant-garde Metal", time:0.18541666666666667 } ] }, actions: { }, mutations: { }, getters: { unique(state) { return state.tracks.reduce((acc, el) => { if (acc.indexOf(el.genre) != -1) { return acc; } return [...acc, el.genre] },[]); }, getAlbums(state) { return state.tracks.reduce((acc, el) => { if (acc.indexOf(el.album) != -1) { return acc; } return [...acc, el.album] },[]); }, } })
/* eslint-disable no-console */ import { mailchimpApi, formatFormInput, formatSignUpResponse } from '../utilities'; export default function signUp(event, _, cb) { const mailingListId = process.env.MAILING_LIST_ID; const body = formatFormInput(event, false, 'pending'); return mailchimpApi( `https://us6.api.mailchimp.com/3.0/lists/${mailingListId}/members/`, 'POST', JSON.stringify(body), ) .then(json => { console.log('signUp request:', JSON.stringify(body, true, '..')); console.log('NEW sign up service post ok:', json); const result = formatSignUpResponse(json, body); cb(null, result); }) .catch(err => { console.error('sign up service error:', err, err.stack); cb(err); }); }
import server from './server'; import {agent} from 'supertest'; let request = agent(server); describe('Testing server error handling routes', function () { it('should receive a 404 for an unknown url', function (done) { const url = '/thisRouteDoesNotExist'; request .get(url) .expect(404) .end(done); }); it('redirect to /search from the route url', function(done){ const url = '/'; request .get(url) .expect('Location', /search/, done); }); });
let mongoose = require('mongoose') let DATABASE_URL = process.env.DATABASE_URL || 'mongodb://localhost/hrd' mongoose.Promise = Promise mongoose.set('debug', true) mongoose.connect(DATABASE_URL) module.exports.User = require('./user') module.exports.Absensi = require('./attendance') module.exports.Fulldata = require('./fulldata') module.exports.KeteranganPayroll = require('./keterangan-payroll.js') module.exports.Configuration = require('./configuration') module.exports.PayrollReport = require('./payroll-report.js')
import React, { useEffect } from 'react'; import { Helmet } from 'react-helmet'; import { connect } from 'react-redux'; import { Button } from 'antd'; import { RocketOutlined } from '@ant-design/icons'; import styles from './Company.module.css'; import * as JobActions from '../../store/actions/jobsActions'; import JobList from '../../components/JobList/JobList'; const Company = (props) => { useEffect(() => { // make API Request props.fetchAllJobs({ company: props.match.params.id }); }, []); return ( <React.Fragment> <Helmet> <meta charSet="utf-8" /> <title> {`${props?.company?.companyName} Careers Page`}</title> </Helmet> <div style={{ backgroundColor: '#F7F8FC' }}> <div className={styles.company_header}> <div className={styles.company_name}> {props?.company?.companyName} </div> <Button className={styles.company_website} icon={<RocketOutlined />} onClick={() => window.open(`${props?.company?.website}`, '_blank')} > Company Website </Button> </div> <section className={styles.image_section}> <div className={styles.image}></div> <div className={styles.opening_btn}> <span className={styles.join_our_team}>Join Our Team</span> <a href="#all-openings"> <button className={styles.btn}>VIEW OPENINGS</button> </a> </div> </section> <section id="all-openings" className={styles.all_openings}> <span className={styles.heading}>All Openings</span> {props.jobFetched && ( <div className={styles.job_lists}> {props.activeJobs && props.activeJobs.map((job, index) => ( <JobList key={index} companyName={props.company.companyName} role={job.role} minExperience={job.minExperience} maxExperience={job.maxExperience} location={job.location} jobId={job.id} /> ))} </div> )} </section> </div> </React.Fragment> ); }; const mapStateToProps = (state) => { return { isLoading: state.Job.isLoading, successMessage: state.Job.successMessage, activeJobs: state.Job.activeJobs, jobFetched: state.Job.jobFetched, company: state.Job.company, }; }; const mapDispatchToProps = { fetchAllJobs: JobActions.fetchedJobRequest, }; export default connect(mapStateToProps, mapDispatchToProps)(Company);
/** * */ $(function (){ alert(1); $("base").attr("href","http://localhost:8080/frames/"); })
import CoreHero from "../../Component/IQCore/CoreHero"; import { CoreData } from "../../Component/IQCore/CoreData"; import { Container, Typography, makeStyles, Box } from "@material-ui/core"; import { NextSeo } from "next-seo"; const styles = makeStyles((theme) => ({ box: { margin: "15px auto", textAlign: "center", }, })); function IqCore() { const classes = styles(); return ( <> <NextSeo title="printIQ Core Modules. Cloud based print MIS with end to end Workflow capabilities" description="The printIQ Core is made up of 8 modules that create a seamless, end‑to‑end estimating, ordering and production workflow encompassing everything needed for your future success in print." openGraph={{ url: "https://www.printiq.com/software/iq-core", title: "printIQ Core Moules. Cloud based print MIS with end to end Workflow capabilities", description: "The printIQ Core is made up of 8 modules that create a seamless, end‑to‑end estimating, ordering and production workflow encompassing everything needed for your future success in print.", images: [ { url: "https://iq-website.vercel.app/images/homepage/printIQ-Universe2020-map.jpg", width: 800, height: 600, alt: "printIQ product Map", }, ], site_name: "https://www.printiq.com/software/iq-core", locale: "en_US", }} twitter={{ handle: "https://printiq.com/software/iq-core", site: "@printIQGlobal", cardType: "summary_large_image", }} /> <CoreHero /> <Container> {CoreData.map((data, index) => ( <Box key={index}> <Typography variant="h5" component="h3" gutterBottom={true}> {data.name} </Typography> <Typography variant="body1" component="p" gutterBottom={true}> {data.paragraph1} </Typography> <Typography variant="body1" component="p" gutterBottom={true}> {data.paragraph2} </Typography> {data.benefits.length > 1 ? ( <Typography> <strong>The Benefits</strong> <ul> {data.benefits.map((moduleBenefits) => ( <li key={moduleBenefits.id}>{moduleBenefits.name}</li> ))} </ul> </Typography> ) : null} {data.video ? ( <Box className={classes.box}> <iframe width="720" height="480" src={data.videoURL} frameBorder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowFullScreen /> </Box> ) : null} </Box> ))} </Container> </> ); } export default IqCore;
const { Console } = require('console') const { readdir, readFile } = require('mz/fs') const shelljs = require('shelljs') const { compressRecordings, deleteRecordings } = require('./utils') const recordSnapshot = grepValue => new Promise((resolve, reject) => { shelljs.exec( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `POLLYJS_MODE=record SOURCEGRAPH_BASE_URL=https://sourcegraph.com pnpm run-integration --grep='${grepValue}'`, (code, stdout, stderr) => { console.log(`stdout: ${stdout}`) console.log(`stderr: ${stderr}`) if (code === 0) { resolve() } const error = new Error() error.code = code reject(error) } ) }) const recordTests = async () => { // 1. Record by --grep args const args = process.argv.slice(2) for (let index = 0; index < args.length; ++index) { if (args[index] === '--grep' && !!args[index + 1]) { await recordSnapshot(args[index + 1]) return } } // 2. Record all tests const fileNames = await readdir('./src/integration') const testFileNames = fileNames.filter(fileName => fileName.endsWith('.test.ts')) const testFiles = await Promise.all( testFileNames.map(testFileName => readFile(`./src/integration/${testFileName}`, 'utf-8')) ) const testNames = testFiles // Ignore template strings for now. If we have lots of tests with parameterized test names, we // can use heuristics to still be able to run them. .flatMap(testFile => testFile.split('\n').map(line => line.match(/\bit\((["'])(.*)\1/))) .filter(Boolean) .map(matchArray => matchArray[2]) for (const testName of testNames) { await recordSnapshot(testName) } } // eslint-disable-next-line no-void void (async () => { try { await recordTests() await compressRecordings() process.exit(0) } catch (error) { await deleteRecordings() process.exit(error.code ?? 1) } })()
// transformation function proBench(){ let suite = new Benchmark.Suite; const optInterval = 500; const optTake = 100; suite.add('project cepjs', function(deferred){ cepjs.interval(optInterval) .pipe(cepjsOp.take(optTake), cepjsOp.project(['payload'], 'project event')) .subscribe({ next: (value) =>{}, error: (error) =>{}, complete: () =>{ deferred.resolve(); } }); }, benchOpts ).add('project cepjs-most', function(deferred){ cepjsMost.interval(optInterval) .pipe(cepjsMostOp.take(optTake), cepjsMostOp.project(['payload'], 'project event')) .subscribe({ next: (value) =>{}, error: (error) =>{}, complete: () =>{ deferred.resolve(); } }); }, benchOpts ).add('project cepjs-mostcore', function(deferred){ cepjsMostCore.interval(optInterval) .pipe(cepjsMostCoreOp.take(optTake), cepjsMostCoreOp.project(['payload'], 'project event')) .subscribe({ next: (value) =>{}, error: (error) =>{}, complete: () =>{ deferred.resolve(); } }); }, benchOpts ).on('cycle', onSuiteCycle) .on('complete', onSuiteComplete) .run({'async': true}); }
// = triggers //-----------------------------------------------------------------------------// $('.main-search').before('<a id="js-search-toggle" class="search-toggle primary-nav-item icon-search col small_2 btn btn--small btn--link"><span class="visuallyhidden">Search</span></a>'); $('#js-nav-toggle').on('click', function() { $('#js-primary-nav').toggleClass('show'); }); $('#js-search-toggle').on('click', function() { $('#js-main-search-wrap').toggleClass('show'); }); jQuery.expr[':'].parents = function(a,i,m){ return jQuery(a).parents(m[3]).length < 1; }; function toggleNavSearch(container, e) { e.preventDefault(); $('header').find('.toggle').filter(':parents(' + container + ')').removeClass('show'); $(container).find('.toggle').toggleClass('show'); $('.wrap-search, .nav-utility').each(function(index, element) { var link = $(element).find('.utility-link, .search-link'); if($(element).find('.toggle').hasClass('show')) { link.addClass('active'); } else { link.removeClass('active'); } }); } function loadAsync(url, loadFn) { loadFn = loadFn || function() {} $(function() { var script = document.createElement('script'); script.src = url; script.async = true; $(script).on('load', loadFn); var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(script, s); }); } $(function () { $('#tabs').children('li').first().children('a').addClass('active') .next().addClass('is-open').show(); $('#tabs').on('click', 'li > a', function() { if (!$(this).hasClass('active')) { $('#tabs .is-open').removeClass('is-open').hide(); $(this).next().toggleClass('is-open').toggle(); $('#tabs').find('.active').removeClass('active'); $(this).addClass('active'); } else { $('#tabs .is-open').removeClass('is-open').hide(); $(this).removeClass('active'); } }); }); $(".js-toggle-content").hide(); $(".js-toggle.js-toggle--open").addClass("js-toggle--active").next().show(); var toggleNavFilter = function (elem) { elem.siblings('div').toggle(); elem.children('i').toggleClass("icon-plus").toggleClass("icon-minus"); elem.toggleClass("js-toggle--active"); }; var toggle = $('.js-toggle'); toggle.on('click', function () { toggleNavFilter($(this)); });
import firebase from 'firebase'; import config from './firebaseConfing'; const fire = firebase.initializeApp(config); const db = fire.firestore(); const settings = { timestampsInSnapshots: true }; db.settings(settings); export default db;
// Tag 5 - 10.01.2020 // MausEvents (In HTML Camelcase, in JavaScript alles klein) onmousemove // Maus bewegen onmousedown // Tastendruck onmouseup // Maustaste loslassen onmousenter // Maus betritt einen Bereich onmouseout // Maus verlässt einen Bereich // Noch mal wiederholung https: //www.mediaevent.de/javascript/canvas.html // https://developer.mozilla.org/de/docs/Web/API/MouseEvent // https://www2.informatik.hu-berlin.de/Themen/www/selfhtml/javascript/sprache/eventhandler.htm // Math pow() // Math.pow() // max() // Math.max() // Maximalwert min() // Math.min() // Minimalwert sin() // Math.sin() // Sinus sqrt() // Math.sqrt() // Quadratwurzel // Dreieck let a = 3; let b = 4; c = Math.sqrt(a * a + b * b) 600 x400x4 = 960.000 // Jedes Pixel besteht aus 4 Bytes (R,G,B,A)
const $toggleFunc = document.getElementsByClassName("toggleFunc"); for (let i = 0; i < $toggleFunc.length; i++) { $toggleFunc[i].addEventListener("click", (e) => { e.preventDefault(); const $container = document.querySelector(".container"); $container.classList.toggle("active"); }); }
import domAdapter from '../dom_adapter'; import injector from './dependency_injector'; import { hasWindow } from './window'; import callOnce from './call_once'; var callbacks = []; var isReady = () => { // NOTE: we can't use document.readyState === "interactive" because of ie9/ie10 support return domAdapter.getReadyState() === 'complete' || domAdapter.getReadyState() !== 'loading' && !domAdapter.getDocumentElement().doScroll; }; var subscribeReady = callOnce(() => { var removeListener = domAdapter.listen(domAdapter.getDocument(), 'DOMContentLoaded', () => { readyCallbacks.fire(); removeListener(); }); }); var readyCallbacks = { add: callback => { var windowExists = hasWindow(); if (windowExists && isReady()) { callback(); } else { callbacks.push(callback); windowExists && subscribeReady(); } }, fire: () => { callbacks.forEach(callback => callback()); callbacks = []; } }; export default injector(readyCallbacks);
(function () { angular .module('ponysticker.utilites') .factory('stickerActionSheet', stickerActionSheet); function stickerActionSheet($rootScope, $ionicActionSheet, $state, $translate, database) { return function showActionSheet(sticker, jump, imgBase64, remote) { $translate([ 'UTILITES_SET_TAGS', 'UTILITES_CANCEL', 'UTILITES_SHARE_STICKER', 'UTILITES_ADD_FAVORITE', 'UTILITES_REMOVE_FAVORITE', 'UTILITES_JUMP_TO_PACKAGE' ]) .then(function(trans) { database .getMeta('sticker', sticker) .success(function(res) { var meta = res; var buttons = []; buttons.push({text: trans.UTILITES_SHARE_STICKER}); if (meta) { if (meta.star) { buttons.push({text: trans.UTILITES_REMOVE_FAVORITE}); } else { buttons.push({text: trans.UTILITES_ADD_FAVORITE}); } buttons.push({text: trans.UTILITES_SET_TAGS}); if (jump) { buttons.push({text: trans.UTILITES_JUMP_TO_PACKAGE}); } } $ionicActionSheet.show({ buttons: buttons, cancelText: trans.UTILITES_CANCEL, buttonClicked: function(index) { switch(index) { case 0: actionSheetShare(meta, imgBase64, remote); break; case 1: actionSheetFavorite(meta); break; case 2: actionSheetSetTags(meta); break; case 3: actionSheetJumpToPackage(meta); } return true; }, }); }) .error(function() { //TODO }); }); }; function actionSheetShare(meta, imgBase64, remote) { if (!remote) { meta.recent = Date.now(); database .updateMeta('sticker', meta); } if ($rootScope.intentType === 'main') { window.PonyPlugin.shareWithBase64(imgBase64); } else if ($rootScope.intentType === 'browser') { window.open('data:image/jpg;base64,'+imgBase64,'_blank'); } else { window.PonyPlugin.setResultWithBase64(imgBase64); } } function actionSheetFavorite(meta) { if (meta.star === 0) { meta.star = 1; } else { meta.star = 0; } database .updateMeta('sticker', meta) .error(function() { //TODO }); } function actionSheetSetTags(meta) { $state.go('tags', { type:'sticker', id: meta.id}); } function actionSheetJumpToPackage(meta) { $state.go('package', { repo: 'local', packageId: meta.packageId }); } } }());
(function (angular) { function JediAddController ($scope, $uibModalInstance, modalParam, jediAddService, jediListService) { var that = this; that.id = modalParam.id; that.typeLoad = modalParam.type; function init(){ jediAddService.load(that.id).then(function(data){ that.jediObj = data; if(that.typeLoad && that.typeLoad == "copia"){ delete that.jediObj.id; } that.jediObj.status = parseInt(that.jediObj.status); }); jediListService.loadStatus().then(function(data){ that.status = data; }); } that.save = function () { jediAddService.save(that.jediObj).then(function(){ $uibModalInstance.dismiss(); }); } that.close = function () { $uibModalInstance.dismiss(); } init(); }; JediAddController.$inject = ['$scope', '$uibModalInstance', 'modalParam', 'jediAddService', 'jediListService']; app.controller('JediAddController', JediAddController); })(angular);
export const human = "X" export const robot = "🤖"
import { Link } from "react-router-dom"; const menus = [ { label: "Login", path: "/login" }, { label: "Register", path: "/register" }, ]; const Navbar = () => { return ( <nav className="navbar navbar-light bg-light px-5 mb-3"> <Link to="/foods" className="navbar-brand"> FOODS </Link> <ul className="nav"> {menus.map(({ label, path }) => ( <li key={path} className="nav-item"> <Link to={path} className="nav-link"> {label} </Link> </li> ))} </ul> </nav> ); }; export default Navbar;
import React, { useEffect, useState } from "react"; import { BirthCertificate } from "./abi/abi"; import Web3 from "web3"; import "./App.css"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import Registration from "./components/Registration"; const web3 = new Web3(Web3.givenProvider); const contractAddress = "0x2E041d3507815dE6a67FAb385E639bF856e5e962"; const storageContract = new web3.eth.Contract( BirthCertificate, contractAddress ); function App() { const [cert, setBirthCert] = useState(""); const [birthCertList, setBirthCertList] = useState([]); async function fetchData() { const certIdCount = await storageContract.methods.certIdCount().call(); setBirthCertList([]); let _lists = []; for (let i = 0; i <= certIdCount; i++) { _lists.push(await storageContract.methods.certificates(i).call()); } setBirthCertList(_lists); } useEffect(() => { fetchData(); }, []); const addBirthCert = async () => { const accounts = await window.ethereum.enable(); const account = accounts[0]; let createCertificate = await storageContract.methods .createCertificate(cert) .send({ from: account, }); setBirthCertList([ ...birthCertList, // createCertificate.events.CertCreated.returnValues, ]); }; const listItems = birthCertList.map((number) => ( <li key={number.id}>{number.chld_firstname}</li> )); // return ( // <div className="App"> // <input onChange={(e) => setBirthCert(e.target.value)} /> // <button onClick={addBirthCert}>Save Task</button> // <ul>{listItems}</ul> // </div> // ); return ( <Router> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/registration">Registration</Link> </li> </ul> </nav> <Switch> <Route path="/registration"> <Registration /> </Route> <Route path="/"> <Home /> </Route> </Switch> </div> </Router> ); } function Home(){ return <div>Home</div>; } export default App;
function updateRole(roleId){ $.get("system/role/getRole", {"roleId": roleId}, function (r) { if (r.code === 200) { var $form = $('#addRoleModal'); $form.modal(); var role = r.msg.role; var permIds = r.msg.permissionIds; $form.find("input[name='name']").val(role.name); $form.find("input[name='oldName']").val(role.name); $form.find("input[name='note']").val(role.note); $form.find("input[name='id']").val(role.id); $rolePermsTree.setSelectedItem(permIds) $("#roleAddBtn").attr("name","update"); } else { $Jtk.n_danger(r.msg); } }); }
$( function() { }); $(document).ready(function() { $('#resultsTable').DataTable({ "order": [ 2, 'desc' ], stateSave: true }); $('#resultsTable_length').addClass("ui input"); $('select[name=resultsTable_length]').addClass("ui input dropdown"); $('#channelsTable').DataTable({ "order": [ 2, 'desc' ], stateSave: true }); $('#channelsTable_length').addClass("ui input"); $('select[name=channelsTable_length]').addClass("ui input dropdown"); } ); $('#refreshApi').on('click', function (event) { console.log("request button triggered"); $("#apiRequestForm").submit(); }); $('#apiRequestForm').on('submit', function (event) { event.preventDefault(); // Stop the form from causing a page refresh. var postURL = "/api/" + channelId; $.ajax({ url: postURL, data: $("#apiRequestForm").serialize(), method: 'POST' }).then(function (response) { console.log("refresh requested"); }); }); $('#resultsTable tbody').on('click', '.clickable-row', function(){ window.location = $(this).data("href"); }); $('#subscribersTable tbody').on('click', '.clickable-row', function(){ window.location = $(this).data("href"); });
export const BOARD_KEYS = [ 'id', 'title', 'width', 'height', 'grid', 'gridSize', ]; export const SHAPE_KEYS = [ 'id', 'shape', 'fill', 'stroke', 'strokeSize', 'fontSize', 'x', 'cx', 'x1', 'x2', 'y', 'cy', 'y1', 'y2', 'width', 'height', 'r', 'rx', 'ry', 'name', 'text', 'points', ];
const mongoose = require('mongoose'), answerSchema = new mongoose.Schema({ content: {type: String, required: true}, voteCount: {type: Number, default: 0}, responder: {type: mongoose.Schema.Types.ObjectId, ref: 'User'} }, {timestamps: true}), questionSchema = new mongoose.Schema({ content: {type: String, required: true}, category: {type: String, default: "Uncategorized"}, questioner: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, answers: [answerSchema] }, {timestamps: true}) module.exports = mongoose.model('Question', questionSchema)
'use strict'; var Error = require('../Error'); var request = require('request'); function WiaResourceCommands(wia) { this.run = function(opt, cb) { if (!opt) return cb(new Error.WiaRequestException("Options cannot be null")); if (wia.stream && wia.stream.connected) { wia.stream.publish('devices/' + opt.id + '/commands/run', opt ? JSON.stringify(opt) : null, cb); } else { setTimeout(function() { if (wia.stream && wia.stream.connected) { wia.stream.publish('devices/' + opt.id + '/commands/run', opt ? JSON.stringify(opt) : null, cb); } else { console.log("Must be connected to the stream to send commands. Try using wia.stream.connect();"); } }, 1250); } } } module.exports = WiaResourceCommands;
import React, { Component } from 'react'; import './css/videopage.css'; export default class Videopage extends Component { constructor(option){ super(option); this.state = { showInput:false, textTop:'1.5rem' } } render() { let style ={ background:'url(./assets/images/bg1.jpg) no-repeat center top', backgroundSize:'cover' }; let style1 ={ background:'url(./assets/images/videobg.png) no-repeat center 59%', backgroundSize:'cover', }; return ( <div className='videopage-C' style={style} onTouchTap={this.beginInput.bind(this)}> <h1></h1> <div className='video-C' style={style1}> <video style={{display:this.state.showInput?'none':'inline-block'}} ref='video' controls src='./assets/video/1.mp4' autoPlay></video> </div> <div className='shi'> <img src='./assets/images/shi.png'/> </div> <div className='wish-C'> <section className='wish-input'> <span>今又重阳,让爱相聚</span> <span className='wish-ico'> <i></i> <i></i> <i></i> </span> </section> </div> {this.state.showInput && <div className='wish-input-C' ref='wish-input-C'> <div> <textarea autoFocus={true} style={{marginTop:this.state.textTop}} className='wish-input' ref='wish-input'></textarea> <span onTouchTap={this.entryShare.bind(this)}>确定</span> <span onTouchTap={this.cancel.bind(this)}>取消</span> </div> </div>} </div> ); } componentDidMount(){ } beginInput(e){ e.preventDefault(); if(e.target.nodeName === 'VIDEO' || e.target.classList.contains('video-C') || e.target.innerHTML === "取消"){ return; } this.setState({ showInput:true },()=>{ var wish = document.querySelector('.wish-input'); wish.click(); wish.focus(); if(this.refs['wish-input'].autofocus){ wish.focus(); wish.click(); } this.t = setInterval(()=>{ this.refs['wish-input'].focus(); },10); setTimeout(()=>{ /*this.setState({ //textTop:0 })*/ clearInterval(this.t); },5000); }); this.refs['video'].pause(); } cancel(){ this.setState({showInput:false},()=>{ this.t && clearInterval(this.t); }); //this.refs['video'].play(); } entryShare(){ let {obserable} = this.props; let value =(this.refs['wish-input'].value); var value1 = encodeURI(value); var data = { value:value1 } let json = encodeURI(JSON.stringify(data)); var href='./share.html?data='+json; window.location.href = href; } }
var bubbleSort = function(array){ var swapped = false; for(var i = 0; i < array.length-1; i++){ swapped = false; for(var j = 0; j < array.length-1-i; j++){ if(array[j+1] < array[j]){ swapped = true array[j] = array[j] ^ array[j+1]; array[j+1] = array[j] ^ array[j+1]; array[j] = array[j] ^ array[j+1]; } } if(!swapped){ break; } } return array; }; console.log(bubbleSort([1,4,3,5,2])); console.log(bubbleSort([-1,2,0,1,-2])); console.log(bubbleSort([2,-1,5,3,0])); console.log(bubbleSort([9,8,7,6,5]));
import { withRouter } from 'rax-use-router'; import { useAppLaunch, useAppError, useAppHide, useAppShare, useAppShow, usePageNotFound } from './app'; import { usePageHide, usePageShow } from './page'; import runApp from './runApp'; import { registerNativeEventListeners, addNativeEventListener, removeNativeEventListener } from './nativeEventListener'; export { runApp, withRouter, useAppLaunch, useAppError, useAppHide, useAppShare, useAppShow, usePageNotFound, usePageHide, usePageShow, registerNativeEventListeners, addNativeEventListener, removeNativeEventListener };
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const UserSchemaII = new Schema({ user_id: {type: String, required: true}, hobbies: {type: String, require: true}, }); module.exports = User = mongoose.model("Userrs", UserSchemaII)
//This section is written by using pure Javascript. //In this project, some pages are written by using pure Javascript and the others pages are written by using Jquery. //I have done that just for practicing both Javascript and Jquery(a very popular library). // Part 1 : Function for Pagination Button document.querySelector('.prev-button').addEventListener('click',prevButton); document.querySelector('.next-button').addEventListener('click',nextButton); let buttonNumber = document.querySelectorAll('.button-number'); for (let i=0; i < buttonNumber.length; i++){ buttonNumber[i].addEventListener('click',numberButton) } function prevButton(){ document.body.scrollTop = 0; document.documentElement.scrollTop = 0; let currentPage = document.querySelector('.active'); currentPage.parentNode.childNodes.forEach(elm => elm.nodeType != 1 && elm.parentNode.removeChild(elm));//remove text node if (currentPage.textContent == 1) return else { currentPage.previousSibling.classList.add('active'); currentPage.classList.remove('active'); } let pageGone = document.querySelectorAll(`.page-${currentPage.textContent}`); for (let i = 0; i < pageGone.length; i++){ pageGone[i].style.display = "none"; } let pageArrived = document.querySelectorAll(`.page-${currentPage.previousSibling.textContent}`); for (let i = 0; i < pageArrived.length; i++){ pageArrived[i].style.display = "block"; } } function nextButton(){ document.body.scrollTop = 0; document.documentElement.scrollTop = 0; let currentPage = document.querySelector('.active'); currentPage.parentNode.childNodes.forEach(elm => elm.nodeType != 1 && elm.parentNode.removeChild(elm)); //remove text node if (currentPage.textContent == 2) return else { currentPage.nextSibling.classList.add('active'); currentPage.classList.remove('active'); } let pageGone = document.querySelectorAll(`.page-${currentPage.textContent}`); for (let i = 0; i < pageGone.length; i++){ pageGone[i].style.display = "none"; } let pageArrived = document.querySelectorAll(`.page-${currentPage.nextSibling.textContent}`); for (let i = 0; i < pageArrived.length; i++){ pageArrived[i].style.display = "block"; } } function numberButton(){ document.body.scrollTop = 0; document.documentElement.scrollTop = 0; let currentPage = document.querySelector('.active'); currentPage.parentNode.childNodes.forEach(elm => elm.nodeType != 1 && elm.parentNode.removeChild(elm)); //remove text node if (currentPage.textContent == this.textContent) return else { this.classList.add('active'); currentPage.classList.remove('active'); } let pageGone = document.querySelectorAll(`.page-${currentPage.textContent}`); for (let i = 0; i < pageGone.length; i++){ pageGone[i].style.display = "none"; } let pageArrived = document.querySelectorAll(`.page-${this.textContent}`); for (let i = 0; i < pageArrived.length; i++){ pageArrived[i].style.display = "block"; } }
/* * Copyright (c) 2018 Thomas Müller <thomas.mueller@tmit.eu> * * This file is licensed under the Affero General Public License version 3 * or later. * * See the COPYING-README file. * */ (function(OCA) { var NS_DAV = OC.Files.Client.NS_DAV; var TEMPLATE_LOCK_STATUS_ACTION = '<a class="action action-lock-status permanent" title="{{message}}" href="#">' + '<span class="icon icon-lock-closed" />' + '</a>'; /** * Parses an XML lock node * * @param {Node} xmlvalue node to parse * @return {Object} parsed values in associative array */ function parseLockNode(xmlvalue) { var lockInfo = { lockscope: getChildNodeLocalName(xmlvalue.getElementsByTagNameNS(NS_DAV, 'lockscope')[0]), locktype: getChildNodeLocalName(xmlvalue.getElementsByTagNameNS(NS_DAV, 'locktype')[0]), lockroot: getHrefNodeContents(xmlvalue.getElementsByTagNameNS(NS_DAV, 'lockroot')[0]), // string, as it can also be "infinite" depth: xmlvalue.getElementsByTagNameNS(NS_DAV, 'depth')[0].textContent, timeout: xmlvalue.getElementsByTagNameNS(NS_DAV, 'timeout')[0].textContent, locktoken: getHrefNodeContents(xmlvalue.getElementsByTagNameNS(NS_DAV, 'locktoken')[0]) }; var owner = null; var ownerEl = xmlvalue.getElementsByTagNameNS(NS_DAV, 'owner'); if (ownerEl && ownerEl.length) { owner = ownerEl[0].textContent; } lockInfo.owner = owner || t('files', 'Unknown user'); return lockInfo; } function getHrefNodeContents(node) { var nodes = node.getElementsByTagNameNS(NS_DAV, 'href'); if (!nodes.length) { return null; } return nodes[0].textContent; } /** * Filter out text nodes from a list of XML nodes * * @param {Array.<Node>} nodes nodes to filter * @return {Array.<Node>} filtered array of nodes */ function getChildNodeLocalName(node) { for (var i = 0; i < node.childNodes.length; i++) { // skip pure text nodes if (node.childNodes[i].nodeType === 1) { return node.childNodes[i].localName; } } return null; } OCA.Files = OCA.Files || {}; /** * @namespace OCA.Files.LockPlugin */ OCA.Files.LockPlugin = { /** * @param fileList */ attach: function(fileList) { this._extendFileActions(fileList); var oldCreateRow = fileList._createRow; fileList._createRow = function(fileData) { var $tr = oldCreateRow.apply(this, arguments); if (fileData.activeLocks) { $tr.attr('data-activelocks', JSON.stringify(fileData.activeLocks)); } return $tr; }; var oldElementToFile = fileList.elementToFile; fileList.elementToFile = function($el) { var fileInfo = oldElementToFile.apply(this, arguments); var activeLocks = $el.attr('data-activelocks'); if (_.isUndefined(activeLocks)) { activeLocks = '[]'; } fileInfo.activeLocks = JSON.parse(activeLocks); return fileInfo; }; var oldGetWebdavProperties = fileList._getWebdavProperties; fileList._getWebdavProperties = function() { var props = oldGetWebdavProperties.apply(this, arguments); props.push('{DAV:}lockdiscovery'); return props; }; var lockTab = new OCA.Files.LockTabView('lockTabView', {order: -20}); fileList.registerTabView(lockTab); fileList.filesClient.addFileInfoParser(function(response) { var data = {}; var props = response.propStat[0].properties; var activeLocks = props['{DAV:}lockdiscovery']; if (!_.isUndefined(activeLocks) && activeLocks !== '') { data.activeLocks = _.chain(activeLocks).filter(function(xmlvalue) { return (xmlvalue.namespaceURI === NS_DAV && xmlvalue.nodeName.split(':')[1] === 'activelock'); }).map(function(xmlvalue) { return parseLockNode(xmlvalue); }).value(); } return data; }); }, /** * @param fileList * @private */ _extendFileActions: function(fileList) { var self = this; fileList.fileActions.registerAction({ name: 'lock-status', displayName: t('files', 'Lock status'), mime: 'all', permissions: OC.PERMISSION_READ, type: OCA.Files.FileActions.TYPE_INLINE, render: function(actionSpec, isDefault, context) { var $file = context.$file; var isLocked = $file.data('activelocks'); if (isLocked && isLocked.length > 0) { var $actionLink = $(self.renderLink()); context.$file.find('a.name>span.fileactions').append($actionLink); return $actionLink; } return ''; }, actionHandler: function(fileName) { fileList.showDetailsView(fileName, 'lockTabView'); } }); if (oc_appconfig.files.enable_lock_file_action) { fileList.fileActions.registerAction({ name: 'lock', mime: 'all', displayName: t('files', 'Lock file'), permissions: OC.PERMISSION_UPDATE, type: OCA.Files.FileActions.TYPE_DROPDOWN, iconClass: 'icon-lock-closed', actionHandler: function (filename, context) { const file = context.fileInfoModel.getFullPath(); context.fileInfoModel._filesClient.lock(file).then(function (result, response) { const xml = response.xhr.responseXML; const activelock = xml.getElementsByTagNameNS('DAV:', 'activelock'); const lock = parseLockNode(activelock[0]); context.fileInfoModel.set('activeLocks', [lock]); }, function (error) { console.log(error) OC.Notification.show(t('files', 'Failed to lock.')); }); } }); fileList.fileActions.addAdvancedFilter(function (actions, context) { var $file = context.$file; if (context.fileInfoModel && context.fileInfoModel.attributes.mimetype === 'httpd/unix-directory') { delete (actions.lock); return actions; } var isLocked = $file.data('activelocks'); if (isLocked && isLocked.length > 0) { delete (actions.lock); } return actions; }); } }, renderLink: function () { if (!this._template) { this._template = Handlebars.compile(TEMPLATE_LOCK_STATUS_ACTION); } return this._template({ message: t('files', 'This resource is locked. Click to see more details.') }); } }; })(OCA); OC.Plugins.register('OCA.Files.FileList', OCA.Files.LockPlugin);
import { ORDER_TRACKING_STATUS_PENDING, ORDER_TYPE_EXPRESS, ORDER_TYPE_DISTRIBUTION, ORDER_TRACKING_STATUS_CLOSE, ORDER_TRACKING_STATUS_ON_TRIP, ORDER_TRACKING_STATUS_PICKUP } from './constants/orders'; export function getOrderTypeText(orderType) { let response; switch (orderType.toLowerCase()) { case ORDER_TYPE_EXPRESS: response = 'Envío rápido'; break; case ORDER_TYPE_DISTRIBUTION: response = 'Reparto'; break; default: break; } return response; } export function getClientTrackingStatusText(status) { let response; switch (status) { case ORDER_TRACKING_STATUS_PENDING: response = 'Pendiente: Tu transportista todavía no inició el viaje'; break; case ORDER_TRACKING_STATUS_PICKUP: response = 'Por cargar: Tu transportista está de camino a buscar tu pedido'; break; case ORDER_TRACKING_STATUS_ON_TRIP: response = 'En viaje: Tu transportista tiene tu pedido'; break; case ORDER_TRACKING_STATUS_CLOSE: response = 'Entregado: Tu pedido fue realizado'; break; default: break; } return response; }
void (function() { 'use strict'; angular.module('films') .controller('FilmsController', FilmsController) FilmsController.$inject = ['$scope', '$stateParams', '$location', 'Authentication', 'Films'] function FilmsController($scope, $stateParams, $location, Authentication, Films) { var self = this $scope.authentication = Authentication self.filmRoll = {} // Create new Film self.create = function() { // Create new Film object var film = new Films ({ camera : self.filmRoll.camera, catalog : self.filmRoll.catalog, film : self.filmRoll.film, type : self.filmRoll.type, iso : self.filmRoll.iso, format : self.filmRoll.format, description : self.filmRoll.description, start : self.filmRoll.start, finish : self.filmRoll.finish, develop : self.filmRoll.develop, scan : self.filmRoll.scan }) // Redirect after save film.$save(function(response) { $location.path('films/' + response._id) // Clear form fields self.filmRoll.camera = '' self.filmRoll.catalog = '' self.filmRoll.film = '' self.filmRoll.type = '' self.filmRoll.iso = '' self.filmRoll.format = '' self.filmRoll.description = '' self.filmRoll.start = '' self.filmRoll.finish = '' self.filmRoll.develop = '' self.filmRoll.scan = '' }, function(errorResponse) { $scope.error = errorResponse.data.message }) } // Remove existing Film self.remove = function(film) { if ( film ) { film.$remove() for (var i in self.films) { if (self.films [i] === film) { self.films.splice(i, 1) } } } else { self.film.$remove(function() { $location.path('films') }) } } // Update existing Film self.update = function() { var film = self.film film.$update(function() { $location.path('films/' + film._id) }, function(errorResponse) { $scope.error = errorResponse.data.message }) } // Find a list of Films self.find = function() { self.films = Films.query() } // Find existing Film self.findOne = function() { self.film = Films.get({ filmId: $stateParams.filmId }) } $scope.FilmsCtrl = self } })()
(function () { 'use strict'; angular.module('dungeonApp', ['ui.router']) .config(config); function config($stateProvider, $urlRouterProvider){ /** * Default state */ $urlRouterProvider.otherwise('/home'); /** * State provider */ // TODO: Use ui-router resolve function to initialize dungeon. Will change states when the user navigates certain areas in the dungeon. // TODO: Make a child state for individual dungeon maps. $stateProvider .state('home',{ url: '/home', templateUrl: 'app/states/home.html', controller: 'homeController', controllerAs: 'homeCtrl' }) .state('login', { url: '/login', templateUrl: 'app/states/login.html', controller: 'loginController', controllerAs: 'loginCtrl' }) .state('signup', { url: '/signup', templateUrl: 'app/states/signup.html', controller: 'loginController', controllerAs: 'loginCtrl' }) .state('map', { url: '/:mapId', templateUrl: 'app/states/map.html', controller: 'mapController', controllerAs: 'mapCtrl' }); } }());
import React from 'react' import {connect} from 'react-redux' import {shopSelectorForObjects} from '../../Redux/store/store.selector' import {createStructuredSelector} from 'reselect' import './shopDisplayOverview.scss' import ShopDisplay from '../Shop Display/shopDisplay' const ShopOverview = ({collections})=> { return( <div> { collections.map(({id, ...otherCollectionProps} )=> ( <ShopDisplay key = {id} {...otherCollectionProps}/> )) } </div> ) } const mapStateToProps = createStructuredSelector({ collections:shopSelectorForObjects }) export default connect(mapStateToProps)(ShopOverview)
import React from "react"; import Link from "gatsby-link"; import Img from "components/Common/Img"; import Helmet from "react-helmet"; import Track from "utils/Track"; import spotifyLogo from "data/successful-resumes/company-logos/2x-spotify-logo.png"; import Subscribe from "components/SuccessfulResumes/Subscribe"; import FamousResumesList from "components/SuccessfulResumes/FamousResumesList"; import ResumeList from "components/SuccessfulResumes/List"; import ResumePreview from "components/SuccessfulResumes/ResumePreview"; import Modal from "components/Modal"; import Meta from "components/Meta"; import DefaultLayout from "layouts/DefaultLayout"; const IMAGE_KEYS = ["subImageOne", "subImageTwo", "subImageThree"]; export default function FeaturedResume({ data }) { const subImageId = Math.floor(Math.random() * 3); const subImage = data[IMAGE_KEYS[subImageId]]; return ( <DefaultLayout className="resumeslist"> <Meta title="Real Resume Examples that Got People Hired | Enhancv" description="Ditch lifeless resume templates and see a collection of real resume examples to show you how to stand out, get inspired, and get the job" metaImage={data.shareImage.publicURL} /> <main className="container"> <section className="page--head"> <h1 className="h1">Resume examples that get people like you hired</h1> <h5 className="h5 text-gray-2 m-xs-top-1 m-md-top-3"> Get inspired and learn from these real life examples </h5> </section> <section className="animate-in resume--highlighted m-sm-top-4 m-md-top-5 m-sm-bottom-4 m-md-bottom-10"> <div className="Grid p-xs-top-4 p-md-top-5"> <div className="resume--highlighted-image Grid-cell--md-5 Grid-cell--sm-10 Grid-cell--xs-12"> <Img className="resume--highlighted-person-image" resolutions={data.mainImage.childImageSharp.resolutions} alt="Sam's photo" /> <span className="resume--highlighted-preview"> <Img resolutions={data.mainResumePreview.childImageSharp.resolutions} alt="Sam's resume preview" /> <Modal trigger={<a className="btn-resume-preview" />}> <ResumePreview resumePageOne={data.mainResumeOne} resumePageTwo={data.mainResumeTwo} altText="Sam's resume" /> </Modal> </span> </div> <div className="resume--highlighted-content Grid Grid--alignCenter Grid-cell--md-7 Grid-cell--xs-12"> <div className="text-center-sm-max full-width"> <h3 className="h3"> From investment banking to Spotify - Sam’s career change </h3> <div className="resume--highlighted-text m-top-4"> <p> It took a lot of planning, hard work, and an amazing resume to get Sam her dream job at Spotify. We break down how she did it step by step. </p> </div> <div className="resume--highlighted-hired m-xs-top-2 m-md-top-4"> <span className="label">Hired at</span> <img style={{ height: 30 }} src={spotifyLogo} alt="Spotify Company logo" /> <span className="line m-left-2 m-right-2" /> <span className="jobtitle m-xs-top-2"> IT, Senior, Operations </span> </div> <Link to="/successful-resumes/sam-young" className="btn btn-big btn-primary m-top-4"> SEE HOW SHE DID IT </Link> </div> </div> </div> </section> <ResumeList data={data.allUserResumesJson.edges} /> <section className="fix-zindex-sr text-center m-sm-bottom-4 m-md-bottom-6"> <h2 className="h2">They changed the world</h2> <h5 className="h5 text-gray-2 m-sm-top-1 m-md-top-2"> Learn from famous resume examples </h5> </section> <section className="fix-zindex-sr resumes--accent accent--reverse Grid full-width noBackground"> <div className="resumes--preview Grid-cell--md-6 Grid-cell--xs-12 m-sm-top-3 m-xs-top-5 m-md-top-6"> <span className="resumes--preview-holder"> <Modal trigger={ <a style={{ cursor: "pointer" }} onClick={() => Track( "Successful Resumes", "Expand Resume", `Featured Casey Neistat` )}> <div className="responsive-gatsby"> <Img resolutions={data.famousResume.childImageSharp.small} alt="Casey's resume preview" imgStyle={{ borderRadius: "5px", boxShadow: "0 2px 2px 0 rgba(223,223,223,0.5)", border: "1px solid rgba(71,72,75,0.04)", }} /> </div> <button className="btn-resume-preview" /> </a> }> <ResumePreview resumePageOne={data.famousResume} altText="Casey's resume" /> </Modal> </span> </div> <div className="resumes--content Grid-cell--md-6 Grid-cell--xs-12"> <div className="text Grid-cell--md-9"> <h3 className="h3 m-xs-top-6"> From dishwasher to iconic Youtube filmmaker </h3> <div className="m-xs-top-1 m-md-top-3"> <p className="p-big"> Every time he tries something new, Casey shows the importance of knowing why you do what you do. He also shows why success can be dangerous. His unique example of a filmmaker resume tells that story. </p> </div> <Link to="/successful-resumes/famous/casey-neistat" className="btn btn-big btn-primary m-xs-top-2 m-md-top-6"> Read Resume </Link> <a href="#explore-more-resumes" className="page--scroll"> Explore more resumes </a> </div> </div> </section> <FamousResumesList data={data.allFamousResumesJson.edges} /> <Subscribe image={subImage} /> </main> </DefaultLayout> ); } export const pageQuery = graphql` query AllResumes { allUserResumesJson(limit: 200) { edges { node { url label name tags title industry resumes { image { childImageSharp { resolutions(width: 240, height: 329) { ...GatsbyImageSharpResolutions } } } } companyLogo { childImageSharp { resolutions(width: 200) { ...GatsbyImageSharpResolutions } } } avatar { childImageSharp { resolutions(width: 126) { ...GatsbyImageSharpResolutions } } } } } } allFamousResumesJson(limit: 200) { edges { node { url name description position avatar { childImageSharp { resolutions(width: 126) { ...GatsbyImageSharpResolutions } } } resumes { image { childImageSharp { resolutions(width: 240, height: 339) { ...GatsbyImageSharpResolutions } } } } } } } mainImage: file(relativePath: { eq: "successful-resumes/Sam_photo@2.png" }) { childImageSharp { resolutions(width: 475, height: 370) { ...GatsbyImageSharpResolutions } } } mainResumePreview: file(relativePath: { eq: "successful-resumes/sam_resume@2.png" }) { childImageSharp { resolutions(width: 214, height: 281) { ...GatsbyImageSharpResolutions } } } mainResumeOne: file(relativePath: { eq: "successful-resumes/sam-young-resume-1.jpg" }) { childImageSharp { large: resolutions(width: 1240) { ...GatsbyImageSharpResolutions } } } mainResumeTwo: file(relativePath: { eq: "successful-resumes/sam-young-resume-2.jpg" }) { childImageSharp { large: resolutions(width: 1240) { ...GatsbyImageSharpResolutions } } } famousResume: file(relativePath: { eq: "famous-resumes/youtuber-casey-neistat.jpg" }) { childImageSharp { small: resolutions(width: 535, height: 741) { ...GatsbyImageSharpResolutions } large: resolutions(width: 1240) { ...GatsbyImageSharpResolutions } } } subImageOne: file(relativePath: { eq: "man_subscribe_illustration@2.png" }) { childImageSharp { resolutions(width: 475, height: 404) { ...GatsbyImageSharpResolutions } } } subImageTwo: file(relativePath: { eq: "mulat_girl_subscribe_illustration.png" }) { childImageSharp { resolutions(width: 475, height: 404) { ...GatsbyImageSharpResolutions } } } subImageThree: file(relativePath: { eq: "white_girl_subscribe_illustration@2.png" }) { childImageSharp { resolutions(width: 475, height: 404) { ...GatsbyImageSharpResolutions } } } shareImage: file(relativePath: { eq: "successful-resumes/sr-share.png" }) { publicURL } } `;
export default function formatTime(seconds) { const date = new Date(seconds * 1000 + 3600 * 5 * 1000); const options = { hour: "numeric", minute: "numeric", second: "numeric", timeZone: "America/New_york" }; let ans = date.toLocaleString("en-US", options); if (ans[1] === ":") { ans = `0${ans}`; } return ans; }
import React, { Component } from "react"; import { connect } from "react-redux"; import _ from "lodash"; import DiamondBox from "../../../../DiamondBox"; import "./index.css"; class SlotsDetails extends Component { constructor(props) { super(props); this.state = { value: 0, result: 0, game: null }; } componentDidMount() { this.projectData(this.props); } componentWillReceiveProps(props) { this.projectData(props); } projectData = async props => { const { bet } = this.props; const result = bet.outcomeResultSpace.index; const game = bet.game; const resultSpace = bet.game.resultSpace; const winAmount = bet.winAmount.toFixed(8); this.setState({ winAmount, resultSpace, result, game }); }; render() { const { game, winAmount, result, resultSpace } = this.state; if (game === null) { return null; } return ( <DiamondBox resultSpace={resultSpace} profitAmount={winAmount} resultBack={result} /> ); } } function mapStateToProps(state) { return { profile: state.profile, ln: state.language }; } export default connect(mapStateToProps)(SlotsDetails);
// $(document).ready(function(){ // just to refresh $('#searchbtn').on('click', function(){ var citySearch = $('#searchVal').val(); $('#searchVal').val(""); $.ajax({ method: "GET", // http://api.openweathermap.org/data/2.5/weather?q={city name},{country code} // &appid=3cd94b4dd9f9500379beff57f6c3b579 // url: "http://api.openweathermap.org/data/2.5/weather?q=telaviv&appid=3cd94b4dd9f9500379beff57f6c3b579", url: "http://api.openweathermap.org/data/2.5/weather?q="+citySearch+"&appid=3cd94b4dd9f9500379beff57f6c3b579", dataType: "json", success: function(data) { console.log(data); displayData(data); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus); } }) }); var displayData = function(data) { var source = $('#weather-template').html(); var template = Handlebars.compile(source); var cityData = { city: data.name, tempK: data.main.temp, tempC: Math.round(data.main.temp - 273.15), tempF: Math.round(data.main.temp * (9/5) - 459.67), requestTime: new Date() }; // console.log(city + " C: " + tempC + " F: " + tempF); // console.log(requestTime); var newHTML = template(cityData); $('.weather-display').append(newHTML); }; $('.weather-display').on('click', '.trashBtn', function(){ $(this).closest('.weatherData').remove(); }); $('.weather-display').on('click', '.commentBtn', function(){ var comment = $(this).closest('.comments-input').find('.commentVal').val(); $(this).closest('.weatherData').find('.comments-section').append('<p>'+comment+'</p>'); $(this).closest('.comments-input').find('.commentVal').val(""); });
/*global $*/ $('.burger, .overlay').click(function () { $('.burger').toggleClass('clicked'); $('.overlay').toggleClass('show'); $('nav').toggleClass('show'); $('body').toggleClass('overflow'); }); $('.faq-list dt').click(function () { var myList = $(this).next('dd'); if (!$(this).hasClass('selected')) { $('.faq-list dt').removeClass('selected'); $(this).addClass('selected'); $('.faq-list dd').hide(); myList.show(); } else { $(this).removeClass('selected'); myList.hide(); } return false; }); $('.slider').each(function () { var $this = $(this); var $group = $this.find('.slide_group'); var $slides = $this.find('.slide'); var bulletArray = []; var currentIndex = 0; var timeout; function move(newIndex) { var animateLeft, slideLeft; advance(); if ($group.is(':animated') || currentIndex === newIndex) { return; } bulletArray[currentIndex].removeClass('active'); bulletArray[newIndex].addClass('active'); if (newIndex > currentIndex) { slideLeft = '100%'; animateLeft = '-100%'; } else { slideLeft = '-100%'; animateLeft = '100%'; } $slides.eq(newIndex).css({ display: 'block', left: slideLeft }); $group.animate({ left: animateLeft }, function () { $slides.eq(currentIndex).css({ display: 'none' }); $slides.eq(newIndex).css({ left: 0 }); $group.css({ left: 0 }); currentIndex = newIndex; }); } function advance() { clearTimeout(timeout); timeout = setTimeout(function () { if (currentIndex < ($slides.length - 1)) { move(currentIndex + 1); } else { move(0); } }, 4000); } $.each($slides, function (index) { var $button = $('<a class="slide_btn">&bull;</a>'); if (index === currentIndex) { $button.addClass('active'); } $button.on('click', function () { move(index); }).appendTo('.slide_buttons'); bulletArray.push($button); }); advance(); }); (function ($) { $.fn.visible = function (partial) { var $t = $(this), $w = $(window), viewTop = $w.scrollTop(), viewBottom = viewTop + $w.height(), _top = $t.offset().top, _bottom = _top + $t.height(), compareTop = partial === true ? _bottom : _top, compareBottom = partial === true ? _top : _bottom; return ((compareBottom <= viewBottom) && (compareTop >= viewTop)); }; })(jQuery); var win = $(window); var allMods = $(".module"); allMods.each(function (i, el) { var el = $(el); if (el.visible(true)) { el.addClass("already-visible"); } }); win.scroll(function (event) { allMods.each(function (i, el) { var el = $(el); if (el.visible(true)) { el.addClass("come-in"); } }); }); $(function () { $('.monster').fadeIn('slow'); }); $(document).ready(function () { $(window).scroll(function () { $('.hideme').each(function (i) { var bottom_of_object = $(this).position().top + $(this).outerHeight(); var bottom_of_window = $(window).scrollTop() + $(window).height(); if (bottom_of_window > bottom_of_object) { $(this).animate({ 'opacity': '1' }, 1500); } }); }); }); jQuery(document).ready(function ($) { setTimeout(function () { $('body').addClass('overflow'); $('.loader').addClass('loaded'); $('#main').addClass('visible'); }, 200); var detalhe = $('.detalhe'); $('.abreDetalhe').click(function (e) { //console.log(e); e.preventDefault(); $(".img-membro").toggleClass("img-membro-transition"); //detalhe.toggleClass('aberto'); }) $('.btnFechar').click(function (e) { //console.log(e); detalhe.toggleClass('aberto'); $(".img-membro").toggleClass("img-membro-transition"); }) }); $(function () { var selectedClass = ""; $(".fil-cat").click(function () { selectedClass = $(this).attr("data-rel"); $("#portfolio").fadeTo(100, 0.1); $("#portfolio div").not("." + selectedClass).fadeOut().removeClass('scale-anm'); setTimeout(function () { $("." + selectedClass).fadeIn().addClass('scale-anm'); $("#portfolio").fadeTo(300, 1); }, 300); }); }); $('.thumbnail').click(function(){ $('.modal-body').empty(); var title = $(this).parent('a').attr("title"); $('.modal-title').html(title); $($(this).parents('div').html()).appendTo('.modal-body'); $('#myModal').modal({show:true}); }); $('a.controls').click(function(){ // Current alert ('control!'); }); // //$('nav li').mouseenter(function () { // //make sure menu does not fly off the right of the screen // if ($(this).children('ul').offset().left + 200 > $(window).width()) { // $(this).children('ul').css('right', 180); // } //});
var mongoose = require('mongoose'); // var OrderSchema = new mongoose.Schema({ // odCode: String, // odUser: {}, // odTotal: Number, // odController: { // odToken: String, // odStatus: String // }, // odShip: { // odShipWayBillBarcode: String, // odShipWayBillDate: String, // odShipOutDate: String, // odTotalWeight: Number, // odCost: Number, // odWeightCode: String, // odZone: String, // odWeightBand: Number // }, // odCart: [], // odCartTotalAmount: Number, // odPayStatus: {}, // odPayObj: { // odDate: String, // odPayMethod: String, // odPayDate: String, // odCardType: String, // odCardNumber: String, // odCVVC: String // } // }); var OrderSchema = new mongoose.Schema({ odCode: String, uuidv1: String, odCreationDate: String, odUser: {}, odTotal: Number, odCart: [], odCartTotalAmount: Number, controlObj: { odToken: String, odStatus: String }, odShip: { odShipWayBillBarcode: String, odShipWayBillDate: String, odShipOutDate: String, odTotalWeight: Number, odCost: Number, odWeightCode: String, odZone: String, odWeightBand: Number }, odPayObj: {} }); // var OrderSchema = new mongoose.Schema({ // odStatus:String, // odWayBill:{odBarcode:String,odWayBillDate:String}, // odUser:{}, // odc:String, // odcc:[], // odccc:Number, // odcccc:{ // odDate: String, // odPayMethod:String, // odPayDate:String, // odCardType:String, // odCardNumber:String, // odCVVC:String // } // }); OrderSchema.methods.toJSON = function() { var order = this.toObject(); return order; }; var OrderCounterSchema = new mongoose.Schema({ incrementId: String, seq: Number }); var Ordercounter = mongoose.model('OrderCounter', OrderCounterSchema); OrderSchema.pre('save', function(next) { var doc= this; Ordercounter.findOneAndUpdate({ 'incrementId': 'order' }, { $inc: { seq: 1 } }, function(err, item) { doc.odCode=item.seq; next(); }) }) module.exports = mongoose.model('Order', OrderSchema);
const servers = require("./server"); const request = require("supertest"); const db = require("./app/models/") // const MalwareURL = db.testDB.malware; // const Op = db.testDB.Sequelize.Op; describe('test that routes for serever', () => { beforeAll(async () => { await db.testDB.sequelize.sync({force: true}); }); test('creates a recored in database', async () => { expect.assertions(1); const malware = await db.testDB.malware.create({ id: 1, address: 'www.example.com' }) expect(malware.id).toEqual(1); }); test("get url ", async () => { expect.assertions(1); const malware = await db.testDB.malware.findOne({ where: { address: 'www.example.com'} }) expect(malware.address).toEqual('www.example.com'); }) it('should give status 200 if route exists for port 100', async () => { const res = await request(servers.app) .get("/urlinfo/1/:hostname/*"); expect(res.statusCode).toEqual(200); }); afterAll(async () => { await db.DevDB.sequelize.close(); }); }); // describe('test routes', () => { // it('should give status 200 if route exists for port 100', async () => { // const res = await request(servers.app) // .get("/urlinfo/1/:hostname/*"); // expect(res.statusCode).toEqual(200); // }); // });
const express = require("express"); const router = express.Router(); const { check } = require("express-validator"); const authenticator = require("../middleware/authenticator"); const { login, register, getUser, resetPassword, forgotPassword, } = require("../controllers/auth"); /* * @desc Gets logged in user * @method GET * @api private */ router.get("/user", authenticator, getUser); /* * @desc Logs in a user * @method POST * @api public */ router.post( "/login", [ check("email", "All fields are required").not().isEmpty(), check("password", "All fields are required").not().isEmpty(), ], login ); /* * @desc Registers a user * @method POST * @api public */ router.post( "/register", [ check("name", "Field shouldn't be empty").not().isEmpty(), check("email", "Please input a valid email address") .isEmail() .normalizeEmail(), check( "username", "Your username must be at least 4 characters long" ).isLength({ min: 4 }), check( "password", "Your password must be at least 8 characters long" ).isLength({ min: 8 }), ], register ); /* * @desc sends token to email if user wants to reset their password * @method POST * @api public */ router.post( "/forgot-password", check("email", "Email field is required").not().isEmpty(), forgotPassword ); /* * @desc Resets password * @method POST * @api public */ router.post( "/reset-password/", [ check( "password", "Your password must be at least 8 characters long" ).isLength({ min: 8 }), check("token", "Token field is required").not().isEmpty(), ], resetPassword ); module.exports = router;
let numbers = []; for (let i = 1; i <=25 ; i+=1) { numbers.push(i) } for(let j = 0; j < numbers.length ; j+=1){ console.log(numbers[j] / 2) }