text
stringlengths
7
3.69M
const mongoose = require("mongoose"); const { Schema } = mongoose; const userSchema = new Schema({ username: String, usernameKey: String, passwordHash: String, icon: String, points: Number, games: [{ type: mongoose.Schema.Types.ObjectId, ref: "games" }], invites: [{ type: mongoose.Schema.Types.ObjectId, ref: "invites" }], }); userSchema.index({ usernameKey: 1 }, { unique: true }); const User = mongoose.model("users", userSchema); module.exports = User;
/*EXPECTED { value: undefined, done: true } */ class _Main { static function main (args : string[]) : void { var g = (function * () : Generator.<int,string> {})(); log g.next(); } }
/** * kvpListToArray transforms a dictionary style object to an 'array of objects' * @param {object} kvps dictionary style object with key-value-pairs * @param {type} key_label label for the key in each key-value-pair * @param {type} value_label label for the value in each key-value-pair * @return {type} an array of objects */ function kvpListToArray(obj,key_label,value_label) { var array = []; var tempObj = {}; for(var key in obj) { tempObj = {}; tempObj[key_label] = key; tempObj[value_label] = obj[key]; array.push(tempObj); } return array; } var record = { "Data Collector": 70, "Power User": 12, "Designer": 5 }; console.log(kvpListToArray(record,"user_level","quantity"));
function menuHandler() { console.log('--user action: menu--'); console.log('menu: ', typeof menu, '\n', menu); alert(menu); } // function instructionsHandler() { // console.log('-- action: instructions --'); // console.log('instructions:', typeof instructions, '\n', instructions); // alert(instructions); // };
import { useState } from 'react'; import { useDispatch } from 'react-redux'; import { deleteTodo, updateTodo } from '../redux/Store'; export const Todo = (props) => { const { item } = props; const [updateMode, setUpdateMode] = useState(false); const [newTodoValue, setNewTodoValue] = useState(item.todo); const dispatch = useDispatch(); const DeleteTodo = (id) => { dispatch(deleteTodo(id)); }; const UpdateTodo = () => { dispatch(updateTodo(item.id, newTodoValue)); setUpdateMode(false); }; if (updateMode) { return ( <div className='mx-3 my-3 items-center text flex bg-gray-200 justify-center rounded-md'> <input className='pl-5 ' type='text' defaultValue={item.todo} onChange={(e) => setNewTodoValue(e.target.value)} /> <button className='h-10 w-20 bg-gray-400 hover:bg-blue-500 hover:text-white rounded-md' onClick={() => { setNewTodoValue(item.todo); setUpdateMode(false); }} > Cancel </button> <button className='h-10 w-20 bg-gray-400 hover:bg-blue-500 hover:text-white rounded-md' onClick={() => UpdateTodo()} > Done </button> </div> ); } return ( <div className='mx-3 my-3 items-center text flex rounded-md bg-gray-200'> <p className='h-10 w-64 rounded-sm mx-auto truncate ' id={item.id}> {item.todo} </p> <button className='h-10 w-20 bg-gray-400 hover:bg-blue-500 hover:text-white rounded-md' onClick={() => DeleteTodo(item.id)} > Delete </button> <button className='h-10 w-20 bg-gray-400 hover:bg-blue-500 hover:text-white rounded-md' onClick={() => setUpdateMode(true)} > Edit </button> </div> ); };
const express = require("express"); const router = express.Router(); const URLController = require("../controller/URLController"); router.get("/:id_url", URLController.findURL); router.post("/generateShortenedURL", URLController.generateShortenedURL); router.post("/listGeneratedURL/:id", URLController.listGeneratedURL); module.exports = router;
/** * author: huweijian * Date: 2018/11/1 - 10:41 AM * Name: vue.config.js * Desc: */ module.exports = { configureWebpack: { }, productionSourceMap: false, devServer: { port: 9525 } }
'use strict' const Vendedor = use('App/Models/Paquexpress/Vendedore') const Producto = use('App/Models/Paquexpress/Producto'); const Database = use('Database') class VendedoreController { async index ({request,auth, response }) { let vendedores = await Database .table('vendedores') .innerJoin('productos', 'id_Producto','=', 'productos.id') .select('vendedores.id','vendedores.Nombre','vendedores.Direccion', 'vendedores.created_at','vendedores.updated_at','productos.Nombre AS id_Producto') let productos = await Producto.all(); return response.status(200).json({ vendedor: vendedores, producto: productos }); } async Insert ({request,response}) { try { const objeto = request.all(); const vendedores = new Vendedor() vendedores.Nombre = objeto.Nombre vendedores.Direccion = objeto.Direccion vendedores.Correo = objeto.Correo vendedores.id_Producto = objeto.id_Producto await vendedores.save() return response.status(200).json({ message: 'Vendedor creado con exito' }) }catch(error) { return response.status(404).json({ message: 'Ocurrio un error' }) } } async edit({params,response}) { const vendedor = await Vendedor.find(params.id) return response.status(200).json({ Vendedor: vendedor }) } async update({params,request,response}) { const vendedor = await Vendedor.find(params.id) const objeto = request.all(); vendedor.Nombre = objeto.Nombre vendedor.Direccion = objeto.Direccion vendedor.Correo = objeto.Correo vendedor.id_Producto = objeto.id_Producto await vendedor.save() return response.status(200).json({ Vendedor: 'Vendedor actualizado con exito!' }) } async delete({params,request,response}) { const vendedor = await Vendedor.find(params.id) await vendedor.delete(); return response.status(200).json({ Vendedor: 'vendedor borrado con exito!' }) } } module.exports = VendedoreController
const container = document.getElementById("gridContainer"); const newGridButton = document.getElementById("newGridButton"); const autoDrawButton = document.getElementById("autoDrawButton"); const colorInput = document.getElementById("colorPicker"); const borderSelect = document.getElementById('borderSelect'); const gridSlider = document.getElementById('gridSizeSlider'); const autoSpeedSlider = document.getElementById('autoSpeedSlider'); const colorCountSlider = document.getElementById('colorCountSlider'); let gridSize = 16; let totalSize = gridSize * gridSize; let color = "#BB3333"; let colorCounter = 0; let colorCountMax = 10; let mouseDown = false; let drawing = false; let autoDrawInterval; let direction; let squareNum = Math.floor(Math.random() * totalSize) + 1; let currentSquare; document.addEventListener("mousedown", () => (mouseDown = true)); document.addEventListener("mouseup", () => (mouseDown = false)); createGrid(); addHoverListeners(); newGridButton.addEventListener("click", setNewGrid); autoDrawButton.addEventListener("click", autoDraw); colorInput.addEventListener("change", (e) => (color = e.target.value)); gridSizeSlider.addEventListener('change', (e) => { document.getElementById('gridSizeValue').textContent = `${e.target.value} x ${e.target.value}` }) autoSpeedSlider.addEventListener('change', (e) => { document.getElementById('autoSpeedValue').textContent = `${e.target.value}ms/tick` }) colorCountSlider.addEventListener('change', (e) => { document.getElementById('colorCountValue').textContent = `${e.target.value} turns` }) function setNewGrid(e) { e.preventDefault(); gridSize = Number(gridSlider.value); totalSize = gridSize * gridSize; squareNum = Math.floor(Math.random() * totalSize) + 1; removeChildNodes(container); createGrid(); addHoverListeners(); } function createGrid() { for (let i = 1; i <= gridSize * gridSize; i++) { const square = document.createElement("div"); square.classList.add("square"); if (borderSelect.checked) square.classList.add("border") square.setAttribute("id", `square-${i}`); square.style.width = `${(750 - (borderSelect.checked && gridSize * 2)) / gridSize}px`; square.style.height = `${(750 - (borderSelect.checked && gridSize * 2)) / gridSize}px`; container.appendChild(square); } } function removeChildNodes(parentNode) { while (parentNode.firstChild) { parentNode.removeChild(parentNode.firstChild); } } function addHoverListeners() { const squares = document.querySelectorAll(".square"); squares.forEach((square) => { square.addEventListener("mouseover", () => { if (mouseDown) square.style.backgroundColor = color; }); }); } function autoDraw(e) { e.preventDefault(); if (drawing) { clearInterval(autoDrawInterval); autoDrawButton.textContent = "Start Autodraw"; drawing = false; } else { autoDrawButton.textContent = "Stop Autodraw"; autoDrawInterval = setInterval(() => { currentSquare = document.getElementById(`square-${squareNum}`); currentSquare.style.backgroundColor = color; squareNum = pickNewSquare(squareNum); }, autoSpeedSlider.value); drawing = true; } } function pickNewSquare(squareNum) { let newDirection = Math.floor(Math.random() * 4); while (newDirection % 2 === direction % 2 && newDirection !== direction) { console.log(newDirection, direction, newDirection === direction); newDirection = Math.floor(Math.random() * 4); } direction = newDirection; colorCounter++; if (colorCounter > colorCountSlider.value) { colorCounter = 0; color = pickRandomColor(); colorInput.value = color; } if (direction === 0 && squareNum > gridSize) return squareNum - gridSize; else if (direction === 1 && squareNum % gridSize !== 0) return Number(squareNum + 1); else if (direction === 2 && squareNum <= totalSize - gridSize) return Number(squareNum) + gridSize; else if (direction === 3 && squareNum % gridSize !== 1) return squareNum - 1; else return pickNewSquare(squareNum); } function pickRandomColor() { let color = "#"; const hexValues = "0123456789ABCDEF"; for (let i = 0; i < 6; i++) { color += hexValues[Math.floor(Math.random() * 16)]; } return color; }
var userpass = { field: [], msgplace: [], indicator: [], check: function() { var self = this; $.ajax({ url: '/user/password/check-strong', type: 'POST', dataType: 'json', data: 'password=' + self.field.val(), success: function(data, textStatus, jqXHR) { self.msgplace.html(data.msg); self.indicator.attr('class', ''); self.indicator.addClass('strong-' + data.strong); self.msgplace.show(); self.indicator.parent().show(); }, }); }, }; $('#user-newpassword').on('keyup', function() { var thispass = Object.create(userpass); thispass.field = $(this); thispass.msgplace = $('#strongmsg'); thispass.indicator = $('#strongind'); thispass.check(); });
import _ from 'underscore'; import config from 'dev/config'; export default _.extend({ static: 'http://arthurstam.github.io/static' }, config);
export const noop = () => {}; /** * Credit: github.com/paypal/downshift * This is intended to be used to compose event handlers. They are executed in * order until one of them calls `event.preventDefault()`. * * @param {Function} fns the event hanlder functions * @return {Function} the event handler to add to an element */ export function composeEventHandlers(...fns) { return (event, ...args) => fns.some(fn => { fn && fn(event, ...args); return event.defaultPrevented; }); }
import React, { Component } from 'react'; import './App.css'; import Clock from './Clock'; import ButtonLand from './ButtonLand'; import Footer from './Footer'; class App extends Component { constructor(props) { super(props); this.state = { counter: 0, hasClock: false, } } handleClick() { this.setState({ counter: this.state.counter + 1, }); } handleRemoveClock() { this.setState({ hasClock: false, }); } handleReplaceClock() { this.setState({ hasClock: true, }); } render() { return ( <div className="App"> <ButtonLand counter={this.state.counter} onClick={() => this.handleClick()} hasClock={this.state.hasClock} onRemoveClock={() => this.handleRemoveClock()} onReplaceClock={() => this.handleReplaceClock()} /> { this.state.hasClock && <Clock counter={this.state.counter} /> } <Footer> Copyright 2017 Boo Boo </Footer> </div> ); } } export default App;
var message_8c = [ [ "imap_edata_free", "message_8c.html#aca39a57c385f6fdc7aa1297b87c48085", null ], [ "imap_edata_new", "message_8c.html#ae33437ff9ef7407d8c6ac170deeede0f", null ], [ "imap_edata_get", "message_8c.html#a849b9e42b71ec60e252b9fdb9c8edfbc", null ], [ "msg_cache_open", "message_8c.html#a765ce1672ffd93151293512c28bbb1b9", null ], [ "msg_cache_get", "message_8c.html#af8842f3824481fe1303c5928324442ed", null ], [ "msg_cache_put", "message_8c.html#a0257d136f32eed740664990643872650", null ], [ "msg_cache_commit", "message_8c.html#abff6bc396da8f9f4d8eb7f55587bfe7f", null ], [ "msg_cache_clean_cb", "message_8c.html#a2cbef6ffe1a41695a2f341a4678203ba", null ], [ "msg_parse_flags", "message_8c.html#ae2caafd14e477d7a51501898a4e4fdc8", null ], [ "msg_parse_fetch", "message_8c.html#a544caf6f7e206bfbd88069d4693443b3", null ], [ "msg_fetch_header", "message_8c.html#a7ba4c5e23881cd48e34cddd0430d2bce", null ], [ "flush_buffer", "message_8c.html#a6d20c017931a27796e7462278f74defe", null ], [ "query_abort_header_download", "message_8c.html#aa881016bc7aba8e6c29a910459cfa260", null ], [ "imap_alloc_uid_hash", "message_8c.html#af9494c020486cd243659caade6f555d2", null ], [ "imap_fetch_msn_seqset", "message_8c.html#a3c0f36a2c199ad42ce13fe65e014f9a2", null ], [ "set_changed_flag", "message_8c.html#aafd4d11d668ae9ea3af0a3c2b9aaa3a5", null ], [ "read_headers_normal_eval_cache", "message_8c.html#ac859b71390c6ecbcecbe5bf3627db566", null ], [ "read_headers_qresync_eval_cache", "message_8c.html#af545f01449bec3c12f4c2aa74bf22079", null ], [ "read_headers_condstore_qresync_updates", "message_8c.html#a917e82060d06f1a7efc11e13a6033d42", null ], [ "read_headers_fetch_new", "message_8c.html#aba59bdd59b97344cb3827fb02ec616b1", null ], [ "imap_read_headers", "message_8c.html#abe57c68df95e87d0dbe1453903343042", null ], [ "imap_append_message", "message_8c.html#a72d92d03e0cb1862381a7ee22861360d", null ], [ "imap_copy_messages", "message_8c.html#aa9385a09428c5a64e66e588255370360", null ], [ "imap_cache_del", "message_8c.html#aade70cfb183e32e948a40ba633fd711a", null ], [ "imap_cache_clean", "message_8c.html#a12bfed71f3ebb43d6a7dd014d079370f", null ], [ "imap_set_flags", "message_8c.html#a568e8aa0aa74d1941d68b571202aa5af", null ], [ "imap_msg_open", "message_8c.html#a081d91e6a08785cf13de80ccddcc4171", null ], [ "imap_msg_commit", "message_8c.html#a1226858cc62e436a52cf0c64b97f6fdb", null ], [ "imap_msg_close", "message_8c.html#a976a007de492b4814274866632d62708", null ], [ "imap_msg_save_hcache", "message_8c.html#af92aa8eebe364d7a8d1f7e94a1d50d28", null ] ];
// learn push from MDN // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push // Questions to understand: /* 1. What does it do? make sure to explain all the parameters. If it has a function as a parameter, make sure to explain all of the parameters for that function. */ "Adds one (or more) elements to the end of an array. myArray.push(element1, element2, ..., elementN)" myArray = [0, 1, 2, 3, 4, 5]; console.log(myArray); myArray.push(6, 7, 8); console.log(myArray); /* 2. Does it edit the current array? */ "Destructive" /* 3. What does it return? */ "returns the length of the new array" console.log(myArray.push(9, 10, 11)); /* 4. How can I use this? Come up (not one off the internet) with a small real world example and explain it. */ "if I only want specific values from a database I can have a callback function that collects those values into one array without worrying about position. Instead of iterating I can just keep pushing forever." /* 5. Build your real world example. */ var database = [["john", 11, "hello friends"], // ["Name", "Age", "Catchphrase"] ["kerry", 12, "I love books"], ["lemon", 2, "make lemonade"], ["doug", 12, "I have a dog"]]; var ages = []; database.forEach(e => ages.push(e[1])); console.log(ages);
import React, { Component } from "react"; import { Grid, Row, Col, Table } from "react-bootstrap"; import { Card } from "components/Card/Card.jsx"; import translator from "../../middleware/translator"; //Redux import { connect } from 'react-redux'; class PricelistDetails extends Component { render() { const car = this.props.currentCar; return ( <div className="content"> <Grid fluid> <Row> <Col md={10} mdOffset={1}> { car ? ( <Card title={car.CarMake+" "+car.CarModel} category = "car details" content={ <div className="list-group" > <li className="list-group-item" > <b>{translator("make")}: </b>{car.CarMake} </li> <li className="list-group-item" > <b>Model: &nbsp;</b>{car.CarModel} </li> <li className="list-group-item" > <b>Category: &nbsp; </b>{car.CarCategory} </li> <li className="list-group-item" > <b>Car Equipment: &nbsp;</b>{car.CarEquipment ? car.CarEquipment : "N/A"} </li> <li className="list-group-item" > <b>Extra Driver: &nbsp;</b>{car.ExtraDriver ? "Yes" : "No" } </li> <li className="list-group-item" > <b>Driver Equipments: &nbsp;</b>{car.DriverEquipments ? car.DriverEquipments : "N/A"} </li> <li className="list-group-item" > <b>Quantity: &nbsp;</b>{car.Quantity} </li> <h4>Price Without Extras: </h4> { car.PriceWithoutExtras.map( function(price,key){ console.log(price) return ( <div className="list-group" key={key} > { Object.keys(price).map(function(prop,key2){ return ( <li className="list-group-item" key={key2}> <b>{prop}: &nbsp;</b>{price[prop]} </li> ) }) } </div> ) }) } </div> } /> ) : ( <p className="text-center text-success" >Loading...</p> ) } </Col> </Row> </Grid> </div> ); } } const mapStateToProps = state => { // console.log(state.cars.currentPricelist) return { currentCar : state.cars.currentCar } } export default connect(mapStateToProps,null)(PricelistDetails);
import { REGISTER_USER, REQ_FAIL, REQ_LOADING, REQ_SUCCESS } from "../../constants/actionTypes" const auth = (state, { type, payload }) => { switch (type) { case REQ_LOADING: return { ...state, loading: true } case REQ_SUCCESS: return { ...state, loading: false } case REQ_FAIL: return { ...state, loading: false, error: payload } case REGISTER_USER: return { ...state, data: payload } default: return state } } export default auth
import Enemy from './enemy'; class Astro extends Enemy { constructor(level, size, type, posX, posY, speed, angle) { super(level, size, type, posX, posY, speed, angle); this.score = this.size.width === 8 ? 100 : 50; this.img = this.size.width === 8 ? "./imgs/Asteroid3.png" : "./imgs/Asteroid2.png"; } } export default Astro;
var d = document; var b = d.body; var Init = function() { var heading = d.createElement("h1"); var heading_text = d.createTextNode("Hello world"); heading.appendChild(heading_text); b.appendChild(heading); }; window.addEventListener("load", function() { Init(); });
var ObjectID = require('mongodb').ObjectID; function updateOneTask(db,req,res){ var collection = db.collection('tasks'); collection.update( { _id: ObjectID(req) }, { $set : { completed: true, completeTime: new Date() } },function(){ res.end(); }); } module.exports = updateOneTask;
'use strict'; exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('attendees').del() .then(function () { return Promise.all([ // Inserts seed entries knex('attendees').insert({ id: 1, concert_id: 1, name: 'Daniel Bailey', age: 52 }), knex('attendees').insert({ id: 2, concert_id: 1, name: 'Heidi McGuire', age: 30 }), knex('attendees').insert({ id: 3, concert_id: 2, name: 'Corey Reyes', age: 26 }), knex('attendees').insert({ id: 4, concert_id: 2, name: 'Kristi Sheridan', age: 45 }) ]); }); };
const cb = function (el) { console.log(el+1); }; Array.prototype.myEach = function (callback) { // debugger for (var i = 0; i < this.length; i++) { callback(this[i]); } return this; }; Array.prototype.myMap = function (callback) { let arr = []; arr.push(this.myEach(callback)); return arr; }; Array.prototype.myReduce = function (callback, initialValue) { let acc; let i = 0; if (initialValue) { acc = initialValue; } else { acc = this[0]; i++; } while (i < this.length) { acc = callback(acc, this[i]); i++; } return acc; }; const cb2 = function (acc, el) { return acc + el; };
/** *工具service *@author zw */ app.factory("utilService",[function(){ /** // * 从一个对象数组中找到一个指定的的对象 */ var getObjectFromArray = function(key,value,array){ if(key&&value&&array&&array.length>0){ for(var i=0;i<array.length;i++){ if(array[i][key]==value){ return array[i]; } } } return null; } /** * 替换对象数组中某一个值 * @param key 需要匹配的属性 ,例如id * @param value 匹配属性的值 * @param array 对象数组,从该数组中进行寻找 * @param newObj 替代找到的元素 */ var updateObjectFromArray = function(key,value,array,newObj){ if(key&&value&&array&&array.length>0){ for(var i=0;i<array.length;i++){ if(array[i][key]==value){ array[i] = newObj ; } } } } /** * 删除对象数组中的一个值 */ var deleteObjectFromArray = function(key,value,array,newObj){ if(key&&value&&array&&array.length>0){ for(var i=0;i<array.length;i++){ if(array[i][key]==value){ array.splice(i,1); } } } } /** * 将数据普通的数组数据:[{"id":"00000000-0000-0000-0000-000000000000CCE7AED4","pId":null,"name":"深圳总部"},{"id":"9c76d944-22dd-11e5-8e71-00163e00172b","pId":"00000000-0000-0000-0000-000000000000CCE7AED4","name":"深圳分公司"},{"id":"c4cf3050-31de-11e5-ae87-54ee75379faf","pId":"00000000-0000-0000-0000-000000000000CCE7AED4","name":"湖南分公司"}] * 装换成abn-tree需要的格式的数据 */ /** * 元数组格式的对象的形式为:{id:1,pid:222,name=1232} */ function wrapData(sourceData,id,fid,label,fn){ var _rootBranch = [];//等于根 id 为空的集合 for(var i = 0,_length = sourceData.length; i<_length; i++){ if(!getObjectFromArray(id,sourceData[i][fid],sourceData)){ //当父id没有任何对象的id和它对应时,该对象是根节点 var node = setNode(sourceData[i],sourceData,id,fid,label,fn) ; _rootBranch.push(node); } } console.info("包装之后树的数据",_rootBranch); return _rootBranch ; } /** * 设置成指定形式对象的数据 {label:"显示名称"} */ function setNode(obj,sourceArray,id,fid,label,fn){ var node = {}; node["label"] = obj[label] ; node["id"] = obj[id] ; node["fid"] = obj[fid] ; /* * 获取子对象 */ var childs = []; for(var j = 0;j<sourceArray.length;j++){ if(sourceArray[j][fid] == obj[id]){ childs.push(setNode(sourceArray[j],sourceArray,id,fid,label,fn)); } } node["children"] = childs ; /* * 回调函数 */ if(fn){ fn(obj,node) ; } return node ; } return { /** * 从一个对象数组中找到一个指定的的对象,如果有多个重复的对象,那么只返回第一个对象 * @param key 需要匹配的属性 ,例如id * @param value 匹配属性的值 * @param array 对象数组,从该数组中进行寻找 */ getObjectFromArray:getObjectFromArray, updateObjectFromArray:updateObjectFromArray, deleteObjectFromArray:deleteObjectFromArray, /** * 将普通的数据转换成abn—tree 需要形式的数据格式 调用格式:utilService.wrapData(orgData,"id","pId","name") ; * @param sourceData 必须;数据元,必须是数组格式的数据 * @id 必须;对象的id属性名 * @fid 必须;对象的父id属性名 * @label 必须;对象中需要显示的属性名称 * @fn 选择;回调函数,需要显示的对象都会进行该函数的调用;fn(obj,node)、obj,源数据对象,node转化成abn-tree需要的数据格式。其中可以对其进行事件绑定 * 例如:function fn(obj,node){ * //事件处理 * node.onSelect = function(branch){//进行点击事件处理。}; * //个性话属性 * node.hello = ""; * } */ wrapData:wrapData } }]);
const { SortComparers } = require("./Utils/SortComparers"); const { EqualityComparers } = require("./Utils/EqualityComparers"); const { Enumerable } = require("./Sequence/Enumerable"); const { HashSet } = require("./DataStructures/HashSet"); const { Dictionary } = require("./DataStructures/Dictionary"); const { List } = require("./DataStructures/List"); module.exports = { Enumerable, Dictionary, HashSet, EqualityComparers, SortComparers, List, };
export default [ { date: "5th june", day: "friday", session: [ { start_time: "9:00AM", end_time: "10:00AM", event: "Workshop", title: "Marketing Matters! ", image: "/images/speaker1.jpg", tag_name: "@ Melisa Lundryn", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform" }, { start_time: "11:00AM", end_time: "12:00AM", event: "Workshop", title: "Reinventing Experiences ", image: "/images/speaker2.jpg", tag_name: " @ Johnsson Agaton", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform", }, { start_time: "2:00PM", end_time: "3:00PM", event: "Workshop", image: "images/speaker3.jpg", title: "Cultures of Creativity", tag_name: "@ Rebecca Henrikon ", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform", }, { start_time: "3:00PM", end_time: "4:00PM", event: "Workshop", title: "Lunch Break", tag_name: "@ Agaton Johnsson ", class: 'lunch' }, { start_time: "3:00PM", end_time: "4:00PM", event: "Workshop", title: "Human Centered Design ", image: "images/speaker4.jpg", tag_name: " @ Fredric Martinsson", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform", } ] }, { date: "5th june", day: "saturday", session: [ { start_time: "9:00AM", end_time: "10:02AM", event: "Workshop", title: "Marketing Matters! ", image: "/images/speaker1.jpg", tag_name: "@ Melisa Lundryn", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform" }, { start_time: "11:00AM", end_time: "12:00AM", event: "Workshop", title: "Reinventing Experiences ", image: "/images/speaker2.jpg", tag_name: " @ Johnsson Agaton", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform", }, { start_time: "2:00PM", end_time: "3:00PM", event: "Workshop", image: "images/speaker3.jpg", title: "Cultures of Creativity", tag_name: "@ Rebecca Henrikon ", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform", }, { start_time: "3:00PM", end_time: "4:00PM", event: "Workshop", title: "Lunch Break", tag_name: "@ Agaton Johnsson ", class: 'lunch' }, { start_time: "3:00PM", end_time: "4:00PM", event: "Workshop", title: "Human Centered Design ", image: "images/speaker4.jpg", tag_name: " @ Fredric Martinsson", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform", } ] }, { date: "7th june", day: "sunday", session: [ { start_time: "9:00AM", end_time: "10:03AM", event: "Workshop", title: "Marketing Matters! ", image: "/images/speaker1.jpg", tag_name: "@ Melisa Lundryn", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform" }, { start_time: "11:00AM", end_time: "12:00AM", event: "Workshop", title: "Reinventing Experiences ", image: "/images/speaker2.jpg", tag_name: " @ Johnsson Agaton", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform", }, { start_time: "2:00PM", end_time: "3:00PM", event: "Workshop", image: "images/speaker3.jpg", title: "Cultures of Creativity", tag_name: "@ Rebecca Henrikon ", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform", }, { start_time: "3:00PM", end_time: "4:00PM", event: "Workshop", title: "Lunch Break", tag_name: "@ Agaton Johnsson ", class: 'lunch' }, { start_time: "3:00PM", end_time: "4:00PM", event: "Workshop", title: "Human Centered Design ", image: "images/speaker4.jpg", tag_name: " @ Fredric Martinsson", content: "How you transform your business as technology, consumer, habits industry dynamics change? Find out from those leading the charge. How you transform", } ] }, ];
const WarningCircleIcon = ({ fillColor, exclamationColor }) => ( <svg xmlns='http://www.w3.org/2000/svg' fill={fillColor || 'none'} viewBox='0 0 24 24' strokeWidth={1.5} stroke='currentColor' className='w-6 h-6' > <path strokeLinecap='round' strokeLinejoin='round' d='M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z' fill={exclamationColor || 'none'} /> </svg> ); export default WarningCircleIcon;
import * as Actiontypes from './Actiontype' export const Dish=(state={ isloading:true,errmss:null,dishes:[]},action)=>{ switch(action.type){ case Actiontypes.DISH_ADDED: return{...state, isloading:false,errmss:null,dishes:action.payload} case Actiontypes.DISH_LOADING: return{...state, isloading:true,errmss:null,dishes:[]} case Actiontypes.DISH_FAILED: return{...state, isloading:false,errmss:action.payload} default:return state } }
// @flow import './NativeModulesMocks/DeviceInfo'; import './NativeModulesMocks/RNLoggingModule'; import './NativeModulesMocks/RNTranslationManager'; import './NativeModulesMocks/RNCurrencyManager'; import './NativeModulesMocks/RNDeviceInfo'; import './NativeModulesMocks/ReactNativePdf'; import './NativeModulesMocks/RNKiwiGestureController'; import './NativeModulesMocks/RNKiwiBackButton';
// jdyview -form, // Copyright (c)2012 Rainer Schneider, Roggenburg. // Distributed under Apache 2.0 license // http://jdynameta.de /*jslint browser: true, strict: false, plusplus: true */ /*global $, moment */ var JDY = JDY || {}; JDY.view = JDY.view || {}; JDY.view.form = JDY.view.form || {}; JDY.view.openDynamicFormDialog = function (aForm, aFormTitel) { "use strict"; return aForm.getForm().dialog({ autoOpen: false, height: 600, width: 500, modal: true, show: 'clip', title: aFormTitel, buttons: { Save: function () { var bValid = aForm.getForm().valid(); if (bValid) { $(this).dialog("close"); if (aForm.formSaveCallback) { aForm.formSaveCallback(); } } }, Cancel: function () { $(this).dialog("close"); } }, close: function () { } }); }; /** * Create Formular seperated by HTML DIV Elements * for the given ClassInfo object * * @param {JDY.base.ClassInfo} aClassInfo - class info to create panel * @param {type} service to get data */ JDY.view.form.createDivFormForClassInfo = function (aClassInfo, service) { "use strict"; var formElem = $("<form>"), allFieldComps; formElem.validate(); allFieldComps = JDY.view.form.addAttributesToDom(formElem, aClassInfo, null, service); return { getForm: function () { return formElem; }, getFormElem: function () { return formElem[0]; }, setValueObject: function (aValueObj) { var i; for (i = 0; i < allFieldComps.length; i++) { allFieldComps[i].setValInField(aValueObj); } }, writeToValueObject: function (aValueObj) { var i; for (i = 0; i < allFieldComps.length; i++) { allFieldComps[i].getValFromField(aValueObj); } } }; }; JDY.view.form.addAttributesToDom = function (aParentElem, aClassInfo, aParentRef, service) { "use strict"; var allFieldComponents = []; function createAttributeComponent(anAttrInfo, typeHandler) { return { setValInField: function (anObj) { typeHandler.setValue((anObj) ? anObj.val(anAttrInfo) : null); }, getValFromField: function (anObj) { if (anObj) { anObj.setVal(anAttrInfo, typeHandler.getValue()); } } }; } function createLabel(anAttrInfo) { return $("<label>") .addClass("jdyLbl") .attr("for", "name") .attr("width", "250") .text($.t(JDY.i18n.key(aClassInfo,anAttrInfo))); } function addFieldAttributes(anAttrInfo, aField, aParentName) { aField.attr("name", anAttrInfo.getInternalName()); aField.attr("id", aParentName + anAttrInfo.getInternalName()); aField.addClass("jdyField"); if (anAttrInfo.isGenerated) { aField.attr('readonly', true); } } aClassInfo.forEachAttr(function (curAttrInfo) { var rowElem, typeHandler, parentName = "", primitiveTypeVisitor = JDY.view.form.createJqueryInputComponentVisitor(curAttrInfo); rowElem = $("<div>").addClass("jdyDivRow"); rowElem.appendTo(aParentElem); if (curAttrInfo.isPrimitive()) { createLabel(curAttrInfo).appendTo(rowElem); typeHandler = curAttrInfo.getType().handlePrimitiveKey(primitiveTypeVisitor); addFieldAttributes(curAttrInfo, typeHandler.field, parentName); rowElem.append(typeHandler.field); if (typeHandler.initElem) { typeHandler.initElem(); } allFieldComponents.push(createAttributeComponent(curAttrInfo, typeHandler)); } else { allFieldComponents.push(JDY.view.form.addObjectReference(curAttrInfo, rowElem, aParentRef, service)); } }); return allFieldComponents; }; JDY.view.form.createJqueryInputComponentVisitor = function (anAttr) { "use strict"; return { handleBoolean: function (aType) { var fieldElem = $('<input type="checkbox">'); return { field: fieldElem, validation : null, getValue: function () { var result = fieldElem.attr('checked'); result = (result && result.trim().length > 0) ? Boolean(result) : false; return result; }, setValue: function (aValue) { if (aValue) { fieldElem.attr("checked", true); } else { fieldElem.removeAttr("checked"); } } }; }, handleDecimal: function (aType) { var fieldElem = $("<input>"); return { field: fieldElem, getValue: function () { var result = fieldElem.val(); result = (result && result.trim().length > 0) ? Number(result) : null; return result; }, setValue: function (aValue) { fieldElem.val(aValue); }, initElem: function () { fieldElem.rules("add", { min: aType.minValue, max: aType.maxValue, number: true, required: (anAttr.isNotNull ? true : false) }); } }; }, handleTimeStamp: function (aType) { var fieldElem = $("<input>"), result, formatString; if (aType.datePartUsed) { if (aType.datePartUsed && aType.timePartUsed) { formatString = "MM/DD/YYYY HH:mm"; } else { formatString = "MM/DD/YYYY"; } } else { formatString = "HH:mm"; } result = { field: fieldElem, getValue: function () { var result = fieldElem.val(); result = (result && result.trim().length > 0) ? moment(result, formatString) : null; return (result) ? result.toDate() : null; }, setValue: function (aValue) { var dateString = null; if (aValue) { dateString = moment(aValue).format(formatString); } fieldElem.val(dateString); }, initElem: function () { if (aType.datePartUsed && !aType.timePartUsed) { fieldElem.datepicker({ showOn: "button", buttonImage: "js/icons/calendar.gif", buttonImageOnly: true, dateFormat: "mm/dd/yy" }); } if (aType.datePartUsed && !aType.timePartUsed) { fieldElem.rules("add", { date: true, required: (anAttr.isNotNull ? true : false) }); } else { fieldElem.rules("add", { required: (anAttr.isNotNull ? true : false) }); } } }; return result; }, handleFloat: function (aType) { var fieldElem = $("<input>"); return { field: fieldElem, validation : { number: true, required: (anAttr.isNotNull ? true : false) }, getValue: function () { var result = fieldElem.val(); result = (result && result.trim().length > 0) ? Number(result) : null; return result; }, setValue: function (aValue) { fieldElem.val(aValue); }, initElem: function () { fieldElem.rules("add", { number: true, required: (anAttr.isNotNull ? true : false) }); } }; }, handleLong: function (aType) { var fieldElem = $("<input>"), i, isSelect = false; if ( aType.domainValues && aType.domainValues.length > 0){ isSelect = true; fieldElem = $("<select>"); // empty object fieldElem.append(new Option("-", null)); for (i = 0; i < aType.domainValues.length; i++) { fieldElem.append(new Option(aType.domainValues[i].representation, aType.domainValues[i].dbValue)); } } return { field: fieldElem, getValue: function () { var result = fieldElem.val(); if (isSelect) { result = (!result || result === "null") ? null : result; } result = (result && result.trim().length > 0) ? Number(result) : null; return result; }, setValue: function (aValue) { fieldElem.val(aValue); }, initElem: function () { fieldElem.rules("add", { min: aType.minValue, max: aType.maxValue, number: true, required: (anAttr.isNotNull ? true : false) }); } }; }, handleText: function (aType) { var fieldElem = $("<input>"), i, isSelect = false; if ( aType.domainValues && aType.domainValues.length > 0){ isSelect = true; fieldElem = $("<select>"); // empty object fieldElem.append(new Option("-", null)); for (i = 0; i < aType.domainValues.length; i++) { fieldElem.append(new Option(aType.domainValues[i].representation, aType.domainValues[i].dbValue)); } } // $("<select>") // attrSelect.append(new Option(curAttrInfo.getInternalName(), curAttrInfo.getInternalName())); return { field: fieldElem, getValue: function () { var result = fieldElem.val(); if (isSelect) { result = (!result || result === "null") ? null : result; } return result; }, setValue: function (aValue) { fieldElem.val(aValue); }, initElem: function () { fieldElem.rules("add", { minlength: 0, maxlength: aType.length, required: (anAttr.isNotNull ? true : false) }); } }; }, handleVarChar: function (aType) { var fieldElem = $("<textarea>"); return { field: fieldElem, getValue: function () { var result = fieldElem.val(); return result; }, setValue: function (aValue) { fieldElem.val(aValue); }, initElem: function () { fieldElem.rules("add", { minlength: 0, maxlength: aType.length, required: (anAttr.isNotNull ? true : false) }); } }; }, handleBlob: function (aType) { throw new JDY.base.JdyPersistentException("Blob Values not supported"); //return aAttrValue; } }; }; JDY.view.form.addObjectReference = function (aObjReference, aRowElem, aParentRef, service) { "use strict"; function createAttributeObjectComponent(aObjReference, allFieldComps) { return { setValInField: function (anObj) { var refObj = (anObj) ? anObj.val(aObjReference) : null, i; for (i = 0; i < allFieldComps.length; i++) { allFieldComps[i].setValInField(refObj); } }, getValFromField: function (anObj) { var refObj, i; if (anObj) { refObj = anObj.val(aObjReference); for (i = 0; i < allFieldComps.length; i++) { allFieldComps[i].getValFromField(refObj); } } } }; } function createObjectSelect() { var selectSpan = $("<span>"), referenceSelect = $("<input>"), selectBtn = $("<a>"), lazyObjectList, aspectPaths = JDY.view.getDisplayAttributesFor(aObjReference.referencedClass), selectedObject; selectBtn.attr( "tabIndex", -1 ) .attr( "title", "Show All Items" ) .button({ icons: { primary: "ui-icon-triangle-1-s" }, text: false }).addClass( "jdy-select-btn" ); // some asynchronous click handler selectBtn.click( function(e){ var filter = new JDY.base.QueryCreator(aObjReference.referencedClass).query(); function openSelectMenu() { var _offset = selectBtn.offset(), position = { x: _offset.left + 10, y: _offset.top + 10 }; selectBtn.contextMenu(position); } function errorHandler() { window.alert("Error loading options"); } function setOptions(filterdObjects) { lazyObjectList = filterdObjects; openSelectMenu(); } if(lazyObjectList) { openSelectMenu(); } else { service.loadValuesFromDb(filter, setOptions, errorHandler); } }); referenceSelect.attr('readonly', true); selectSpan.addClass("jdyField"); selectSpan.append(referenceSelect); selectSpan.append(selectBtn); // setup context menu selectSpan.contextMenu({ selector: '.jdy-select-btn', trigger: 'none', build: function($trigger, e) { var i, itemsList= {}; for( i= 0; i< lazyObjectList.length; i++) { itemsList[lazyObjectList[i].Name+i] = {name: JDY.view.getTextForAspectPaths(aspectPaths, lazyObjectList[i]), value: lazyObjectList[i]}; } return { callback: function(key, options) { var m = "clicked: " + key, text; selectedObject = itemsList[key].value; text = (selectedObject) ? JDY.view.getTextForAspectPaths(aspectPaths, selectedObject) : ""; referenceSelect.val(text); }, items: itemsList }; } }); return { field: selectSpan, setValInField: function (anObj) { var val = ((anObj) ? anObj.val(aObjReference) : null), text = (val) ? JDY.view.getTextForAspectPaths(aspectPaths, val) : ""; referenceSelect.val(text), selectedObject = val; }, getValFromField: function (anObj) { if (anObj) { anObj.setVal(aObjReference, selectedObject); } } }; } var accordionElem, referenceElem, allFieldComponents, selectElem; // add accordion only at the first level and a depent reference if (!aParentRef && aObjReference.dependent) { accordionElem = $("<div>"); $("<h3>").text(aObjReference.getInternalName()).appendTo(accordionElem); referenceElem = $("<div>"); referenceElem.attr("data-bind", "with: " + aObjReference.getInternalName()); referenceElem.appendTo(accordionElem); aRowElem.append(accordionElem); allFieldComponents = JDY.view.form.addAttributesToDom(referenceElem, aObjReference.referencedClass, aObjReference, service); accordionElem.accordion({ collapsible: true, heightStyle: "content", active: false }); return createAttributeObjectComponent(aObjReference, allFieldComponents); } else { $("<label>") .addClass("jdyLbl") .attr("for", "name") .attr("width", "250") .text(aObjReference.getInternalName()) .appendTo(aRowElem); selectElem = createObjectSelect(); aRowElem.append(selectElem.field); return selectElem; } }; //@Deprected JDY.view.createTableFormForClassInfo = function (tbody, aClassInfo) { "use strict"; tbody.empty(); aClassInfo.forEachAttr(function (curAttrInfo) { var rowElem, colElem, inputElem, accordionElem, accorGroupElem, inputComp; rowElem = $("<tr>"); $("<td>") .addClass("jdyLbl") .text(curAttrInfo.getInternalName()) .data("col", 0) .appendTo(rowElem); if (curAttrInfo.isPrimitive()) { colElem = $("<td>") .addClass("jdyField"); inputComp = curAttrInfo.getType().handlePrimitiveKey(JDY.view.createInputComponentVisitor(curAttrInfo)); inputComp.field.attr("name", curAttrInfo.getInternalName()); inputComp.field.attr("id", curAttrInfo.getInternalName()); //inputComp.databind(inputComp.field, curAttrInfo); colElem.append(inputComp.field); rowElem.append(colElem); } else { colElem = $("<td>") .addClass("jdyObject"); accordionElem = $("<div>"); accorGroupElem = $("<div>").addClass("group"); accorGroupElem.appendTo(accordionElem); $("<h3>").text(curAttrInfo.getInternalName()).appendTo(accorGroupElem); $("<div>").text("value").appendTo(accorGroupElem); accordionElem.accordion({ header: "h3", collapsible: true, heightStyle: "content" }); colElem.append(accordionElem); rowElem.append(colElem); } rowElem.appendTo(tbody); }); };
$(document).ready(function () { $("#alarm").show(function (){ $.ajax({ url: 'http://{{HOST}}:8080/alarm', type: "get", dataType: "json", data: '', success: function(data, textStatus, jqXHR) { // since we are using jQuery, you don't need to parse response for (var i = 0; i < data.length; i++) { var row = $("<tr />"); $("#alarm").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it row.append($("<td>" + data[i].Date + "</td>")); row.append($("<td>" + data[i].Sensor + "</td>")); } } }); }); $("#clearAlarm").click(function () { $.ajax({ async: true, url: 'http://{{HOST}}:8080/alarm', type: 'delete', success: function () { $("#alarm").load(" #alarm") } }); }); });
var inquirer = require("inquirer"); var cowsay = require("cowsay"); const TAs = ["Donny", "Mark", "Clarence", "Lawrence"]; console.log( cowsay.say({ text: "What would you like to do?" }) ); const helpMe = () => { inquirer .prompt({ type: "list", choices: ["Pick a TA", "Exit the app"], name: "selector" }) .then(res => { if (res.selector === "Pick a TA") { var myTA = TAs[Math.floor(Math.random() * TAs.length)]; console.log( cowsay.say({ text: myTA }) ); helpMe(); } else { console.log( cowsay.say({ text: "Bye!" }) ); process.exit(); } }); }; helpMe();
$(document).ready(function(){ // tìm kiếm đơn hàng $('#order_submit').click(function(e) { ajaxSearch(); }); $(document).on("change", "#order_ship_cod, #order_ship_payment", function() { $("#chosen_store").val(''); }); $(document).on("click", "#order_edit_submit", function() { var sub_status = $('#sub_status').val(); if(sub_status == '' || sub_status == 98) { $("#sub_status").focus(); showMsg("Vui lòng chọn trạng thái phụ!"); return false; } }); $(document).on("click", "#order_statistic_excel", function() { var month_filter = $('#month_filter').val(); var year_filter = $('#year_filter').val(); var order_status = $('#order_status').val(); var pay_type = $('#pay_type').val(); var shop_id = $('#shop_id').val(); if(shop_id == '') { $("#shop_id").focus(); showMsg("Vui lòng chọn Shop!"); return false; } location.href = BASE_URL + "excel/order?month_filter="+ month_filter + "&year_filter="+ year_filter + "&shop_id="+ shop_id + "&order_status="+ order_status + "&pay_type="+ pay_type; }); $(document).on("click", "#order_transport_submit", function() { var id = $(this).attr('rel'); var shop_ship_address = $('#shop_ship_address').val(); var ship_partner_id = $('#ship_partner_id').val(); var chosen_store = $('#chosen_store').val(); var order_ship_cod = $('#order_ship_cod').val(); var order_ship_payment = $('#order_ship_payment').val(); var is_ghn = $('#is_ghn').val(); var length = $('#length').val(); var width = $('#width').val(); var height = $('#height').val(); if(chosen_store == '') { $("#chosen_store").focus(); alert("Vui lòng chọn Kho lấy hàng!"); return false; } if (typeof shop_ship_address != 'undefined') { var ship_address = shop_ship_address; }else{ var ship_address = ''; } if(is_ghn == 1){ if(length == ''){ $("#length").focus(); alert("Vui lòng nhập chiều dài của kiện hàng!"); return false; } if(width == ''){ $("#width").focus(); alert("Vui lòng nhập chiều rộng của kiện hàng!"); return false; } if(height == ''){ $("#height").focus(); alert("Vui lòng nhập chiều cao của kiện hàng!"); return false; } } $.ajax({ type: "POST", url: BASE_URL + 'order/order_transport?type=update&id='+ id + '&ship_address=' + ship_address + '&ship_partner_id='+ship_partner_id + '&store_id='+chosen_store + '&order_ship_cod='+order_ship_cod + '&order_ship_payment='+order_ship_payment + '&length=' + length + '&width=' + width + '&height=' + height, data: "ajax", async: true, success: function(response){ if(!response.error){ alert('Tạo vận đơn thành công!'); location.reload(); } else alert(response.msg); return false; } }) }); $(document).on("change", "#ship_partner_id", function() { var partner_id = $(this).val(); if(partner_id == 1){ $("#order_print_ship_transport_submit").show(); } else{ $("#order_print_ship_transport_submit").hide(); } $('#chosen_store').val(''); $('#chosen_store_print').val(''); $('#ship_code_total').val(''); $('#ship_code_display').text(''); $.ajax({ type: "POST", url: BASE_URL + 'order/get_store', data: {partner_id: partner_id}, async: true, success: function(response){ $("#chosen_store").html(response.data_html); $("#chosen_store_print").html(response.data_html); } }); $.ajax({ type: "POST", url: BASE_URL + 'order/stock', data: {id: partner_id}, async: true, success: function(response){ var obj = JSON.parse(response); if(obj.status == 200){ $('.hub_stock').html(obj.html); }else{ $('.hub_stock').html(''); } } }); }); $(document).on("change", "#chosen_store", function() { var chosen_store = $(this).val(); var ship_partner_id = $('#ship_partner_id').val(); var order_ship_cod = $('#order_ship_cod').val(); var order_ship_payment = $('#order_ship_payment').val(); var province_ajax = $('#province_ajax').val(); var district_ajax = $('#district_ajax').val(); $.ajax({ type: "POST", url: BASE_URL + 'order/get_order_store', data: {partner_id: ship_partner_id, store_id: chosen_store}, async: true, success: function(response){ $("#store_name").val(response.name); $("#store_mobile").val(response.mobile); $("#store_full_name").val(response.full_name); $("#store_address").val(response.address); } }); $.ajax({ type: "POST", url: BASE_URL + 'order/order_transport_cal?type=view&id=' + order_id + '&province_ajax=' + province_ajax + '&district_ajax=' + district_ajax + '&ship_partner_id='+ship_partner_id + '&store_id='+chosen_store + '&order_ship_cod='+order_ship_cod + '&order_ship_payment='+order_ship_payment, data: "ajax", async: true, success: function(response){ if(!response.error){ $("#order_ship_transport").text(response.order_ship_transport); $("#order_ship_cod_fee").text(response.order_ship_cod_fee); } else alert(response.msg); } }) }); // chi tiết đơn hàng $(".bootbox-confirm").on(ace.click_event, function() { var id = $(this).attr("rel"); var parent_tr = $(this).parents('tr'); bootbox.confirm("Bạn có chắc chắn xoá sản phẩm khỏi đơn hàng này ?", function(result) { if(result) { $.ajax({ type: "POST", url: BASE_URL + 'order/order_product_delete/?order_id='+order_id+'&product_id='+ id, data: "ajax", async: true, success: function(kq){ parent_tr.slideUp("slow"); location.reload(); } }) }; }); }); $(document).on("click", "#order_transport", function() { var province_ajax = $('#province_ajax').val(); var district_ajax = $('#district_ajax').val(); if(province_ajax == '') { $("#province_ajax").focus(); showMsg("Vui lòng chọn Tỉnh/thành trước khi tạo vận đơn!"); return false; } else{ $("#message_show").html(''); } if(district_ajax == '') { $("#district_ajax").focus(); showMsg("Vui lòng chọn Quận/huyện trước khi tạo vận đơn!"); return false; } else{ $("#message_show").html(''); } $.ajax({ type: "POST", url: BASE_URL + 'order/order_transport?type=view&id=' + order_id + '&province_ajax=' + province_ajax + '&district_ajax=' + district_ajax + '&store_id=1&order_ship_cod=1&order_ship_payment=1', data: "ajax", async: true, success: function(response){ if(!response.error){ $('#myModal').html(response); $('#myModal').modal(); } else alert(response.msg); } }) }); $("#order_transport_cancel").on(ace.click_event, function() { var id = $(this).attr("rel"); var parent_tr = $(this).parents('tr'); bootbox.confirm("Bạn có chắc chắn huỷ vận đơn?", function(result) { if(result) { $.ajax({ type: "POST", url: BASE_URL + 'order/order_transport_cancel', data: {order_id:order_id}, async: true, success: function(kq){ if(kq){ //location.reload(); } else{ alert("Lỗi, vui lòng thử lại!"); return false; } } }) }; }); }); $(document).on("click", ".order_product_add", function() { var product_id = $(this).attr('rel'); $.ajax({ type: "POST", url: BASE_URL + 'order/order_product_ajax', data: {product_id:product_id, order_id:order_id}, async: true, success: function(kq){ if(kq){ alert('Cập nhật thành công!'); location.reload(); }else{ alert('Đã xảy ra lỗi!'); } } }) }); $("#order_retransport").on(ace.click_event, function() { var id = $(this).attr("rel"); var parent_tr = $(this).parents('tr'); bootbox.confirm("Bạn có chắc chắn muốn gửi lại vận chuyển?", function(result) { if(result) { $.ajax({ type: "POST", url: BASE_URL + 'order/order_retransport/?order_id='+order_id, data: "ajax", async: true, success: function(kq){ parent_tr.slideUp("slow"); location.reload(); } }) }; }); }); if($('.edit_text').length >0){ $(window).load(function(){ $.fn.editable.defaults.mode = 'inline'; $('.edit_text').editable({ type: 'text', success: function(k,v){ var field = $(this).attr('rel'); $.ajax({ type: "POST", url: BASE_URL + 'order/order_update', data: {order_id: order_id,field:field,value:v}, async: true, success: function(kq){ if(kq == 1){ location.reload(); } } }) } }); }); } }); function ajaxSearch() { waitingDialog.show('Đang tải dữ liệu.......'); var url_params = ''; var province_id = $('#province_id_ajax').val(); var pay_status = $('#pay_status').val(); var shop_id = $('#shop_id').val(); var sale_id = $('#sale_id').val(); var pay_type = $('#pay_type').val(); var order_status = $('#order_status').val(); var key_search = $('input[name=key_search]').val(); var sub_status = $('#sub_status').val(); var time_filter = $('#reportrange span').text(); var order_shop_id = $('#order_shop_id_ajax').val(); url_params += "time_filter=" + encodeURIComponent(time_filter); if (typeof order_shop_id != 'undefined') { url_params += "&shop_id=" + order_shop_id; } if (province_id !== "" && typeof province_id != 'undefined') { url_params += "&province_id=" + province_id; } if (pay_status !== "" && typeof pay_status != 'undefined') { url_params += "&pay_status=" + pay_status; } if (shop_id !== "" && typeof shop_id != 'undefined') { url_params += "&shop_id=" + shop_id; } if (sale_id !== "" && typeof sale_id != 'undefined') { url_params += "&sale_id=" + sale_id; } if (pay_type !== "" && typeof pay_type != 'undefined') { url_params += "&pay_type=" + pay_type; } if (order_status !== "" && typeof order_status != 'undefined') { url_params += "&order_status=" + order_status; } if (key_search !== "" && typeof key_search != 'undefined') { url_params += "&key_search=" + key_search; } if (sub_status !== "" && typeof sub_status != 'undefined') { url_params += "&sub_status=" + sub_status; } $.ajax({ url: BASE_URL + "order/getOrdersAjax?" + url_params, type: "post", dateType: "text", success: function (result) { if (result) { $('#detail-data').html(result); waitingDialog.hide(); } } }); return false; } $(document).on("click", ".order_product_edit_modal", function() { var product_id = $(this).attr("rel"); $.ajax({ type: "POST", url: BASE_URL + 'order/order_product_modal?type=form&order_id='+order_id+'&product_id=' + product_id, data: "ajax", async: true, success: function(kq){ if(kq){ $('#myModal').html(kq); $('#myModal').modal(); }else{ alert('Đã xảy ra lỗi!'); } } }) }); $(document).on("click", "#order_sale_update", function() { var sale_id = $(this).attr("rel"); $.ajax({ type: "POST", url: BASE_URL + 'order/transfer_sale', data: {order_id:order_id, sale_id:sale_id}, async: true, success: function(kq){ if(kq){ $('#myModal').html(kq); $('#myModal').modal(); }else{ alert('Đã xảy ra lỗi!'); } } }) }); $(document).on("click", "#submit_order_product", function() { var product_id = $(this).attr("rel"); var order_product_quantity = $("#order_product_quantity").val(); var order_product_discount = $("#order_product_discount").val(); if(order_product_quantity <= 0) { $("#order_product_quantity").focus(); $("#popup_msg").text("Số lượng phải lớn hơn 0!"); $("#popup_show_msg").show(); return false; }else{ $("#order_product_quantity").blur(); $("#popup_msg").text(""); $("#popup_show_msg").hide(); } $.ajax({ type: "POST", url: BASE_URL + 'order/order_product_ajax', data: {order_id:order_id, product_id:product_id,quantity:order_product_quantity,discount:order_product_discount}, async: true, success: function(kq){ if(kq){ alert('Cập nhật thành công!'); location.reload(); }else{ alert('Đã xảy ra lỗi!'); } } }) }); $(document).on("click", "#btn_find_ajax", function() { var product_name_search = $("#product_name_search").val(); if(product_name_search == 0) { $("#product_name_search").focus(); $("#popup_msg").text("Vui lòng nhập tên sản phẩm!"); $("#popup_show_msg").show(); return false; } else{ $("#product_name_search").blur(); $("#popup_msg").text(""); $("#popup_show_msg").hide(); } $.ajax({ type: "POST", url: BASE_URL + 'product/product_search_ajax/?shop_id='+ shop_id +'&product_name_search='+ encodeURI(product_name_search), data: "ajax", async: true, success: function(kq){ $("#product_display_ajax").html(kq); } }) }); $(document).on("click", "#order_transport_print", function() { $.ajax({ type: "POST", url: BASE_URL + 'order/ship_tranport_print', data: "ajax", async: true, success: function(kq){ if(kq){ $('#myModal').html(kq); $('#myModal').modal(); }else{ alert('Đã xảy ra lỗi!'); } } }) }); $(document).on("change", "#chosen_store_print", function() { $("#ship_code_total").html(''); $("#ship_code_display").html(''); var ship_partner_id = $('#ship_partner_id').val(); var store_id = $(this).val(); if(ship_partner_id == '') { $("#ship_partner_id").focus(); alert("Vui lòng chọn một đơn vị Ship!"); return false; } $.ajax({ type: "POST", url: BASE_URL + 'order/get_order_ship_transport', data: {store_id: store_id, ship_partner_id:ship_partner_id}, async: true, success: function(response){ $("#ship_code_total").html(response.ship_code_total); $("#ship_code_display").html(response.data_html); $("#ship_code_display_hidden").html(response.data_string); } }); }); $(document).on("change", "#order_status", function() { var status = $(this).val(); $.ajax({ type: "POST", url: BASE_URL + 'order/get_sub_status', data: {status: status}, async: true, success: function(response){ $("#sub_status").html(response.data_html); } }); }); $(document).on("click", "#order_update_ship_transport_submit", function() { var ship_code_display_hidden = $("#ship_code_display_hidden").text(); var store_id = $('#chosen_store_print').val(); if(ship_code_display_hidden == '') { alert("Không tồn tại mã vận đơn, vui lòng thử lại!"); return false; } $.ajax({ type: "POST", url: BASE_URL + 'order/update_ship_transport_print', data: {store_id: store_id, ship_code_list: ship_code_display_hidden}, async: true, success: function(response){ alert('Cập nhật thành công!'); location.reload(); } }); }); $(document).on("click", "#order_print_ship_transport_list_submit", function() { var ship_partner_id = $("#ship_partner_id").val(); var chosen_store_print = $("#chosen_store_print").val(); var ship_code_display_hidden = $("#ship_code_display_hidden").text(); if(ship_partner_id == '') { $("#ship_partner_id").focus(); alert("Vui lòng chọn một đơn vị Ship!"); return false; } if(chosen_store_print == '' || ship_code_display_hidden == '') { $("#chosen_store_print").focus(); alert("Bạn chưa chọn kho, hoặc kho này không tồn tại vận đơn!"); return false; } window.open(BASE_URL + 'order/transport_list?code=' + ship_code_display_hidden); }); $(document).on("click", "#order_print_ship_transport_submit", function() { var store_id = $(this).val(); var ship_code_display_hidden = $("#ship_code_display_hidden").text(); var chosen_store_print = $("#chosen_store_print").val(); if(chosen_store_print == '' || ship_code_display_hidden == '') { $("#chosen_store_print").focus(); alert("Bạn chưa chọn kho hoặc kho này không tồn tại vận đơn!"); return false; } window.open('https://seller.shipchung.vn/#/print_new?code=' + ship_code_display_hidden); }); $(document).on("click", "#order_change_sale_submit", function() { var sale_id = $("#sale_id_select").val(); if(sale_id == '') { $("#sale_id_select").focus(); alert("Vui lòng nhập chọn Sale!"); return false; } if(sale_id >0) { $.ajax({ type: "POST", url: BASE_URL + 'order/change_sale', data: {order_id:order_id, sale_id:sale_id}, async: true, success: function(response){ if(!response.error){ alert(response.msg); location.reload(); } else alert(response.msg); } }) } else{ alert("Không tồn tại Sale muốn chuyển!"); return false; } }); $(document).on("click", "#order_send_sms", function() { var mobile = $(this).attr('rel'); var order_id = $(this).attr('order_id_rel'); var sms_content = $('#sms_content').val(); if(!validatePhone(mobile)) { showMsg("Số điện thoại gửi không đúng!"); return false; } else{ $("#message_show").html(''); } if(sms_content == '') { $("#sms_content").focus(); showMsg("Vui lòng nhập nội dung!"); return false; } else{ $("#message_show").html(''); } $.ajax({ type: "POST", url: BASE_URL + 'globalaction/smsSend', data: {order_id: order_id, mobile: mobile, content: sms_content}, dateType: "text", success: function(response){ if(!response.error){ alert(response.msg); $('#smsModal').modal('hide'); } else alert(response.msg); } }); }); $(document).on("click", "#order_update_discount_button", function() { var discount = $("#order_discount_value").val(); if(discount == '') { $("#order_discount_value").focus(); alert('Vui lòng nhập tiền giảm giá!'); return false; } else{ $("#message_pop_show").html(''); } $.ajax({ url: BASE_URL + 'order/update_discount_ajax', type: "post", data: {order_id: order_id, discount: discount}, dateType: "text", success: function (response) { if(!response.error){ alert(response.msg); location.reload(); } else showMsgPop(response.msg); } }); }); $(document).on("click", "#order_update_ship_button", function() { var ship_fee = $("#order_ship_value").val(); if(ship_fee == '') { $("#order_ship_value").focus(); alert('Vui lòng nhập phí Ship!'); return false; } else{ $("#message_pop_show").html(''); } $.ajax({ url: BASE_URL + 'order/update_ship_ajax', type: "post", data: {order_id: order_id, ship_fee: ship_fee}, dateType: "text", success: function (response) { if(!response.error){ alert(response.msg); location.reload(); } else showMsgPop(response.msg); } }); }); $(document).on("click", "#order_update_pay_button", function() { var pay_fee = $("#order_pay_value").val(); if(pay_fee == '') { $("#order_pay_value").focus(); alert('Vui lòng nhập phí thanh toán!'); return false; } else{ $("#message_pop_show").html(''); } $.ajax({ url: BASE_URL + 'order/update_pay_ajax', type: "post", data: {order_id: order_id, pay_fee: pay_fee}, dateType: "text", success: function (response) { if(!response.error){ alert(response.msg); location.reload(); } else showMsgPop(response.msg); } }); });
//Id apoteke na koju je kliknuto var id //Prikaz info o apoteci $(document).on('click', '.btnPharmacy', function () { var allPharmacies = $(".allPharmacies"); var onePharmacy = $(".onePharmacy"); var card = $(".card") var pharmacists = $(".pharmacists") var dermatologists = $(".dermatologists") var medicine = $(".medicine"); var availableAppointments = $(".availableAppointments"); allPharmacies.hide(); onePharmacy.show(); pharmacists.hide(); card.show(); dermatologists.hide(); medicine.hide(); availableAppointments.hide(); id = this.id; console.log(id); var id1 = JSON.stringify({"id" : id}); $.ajax({ type: "POST", url: "http://localhost:8081/pharmacy", dataType: "json", contentType: "application/json", data: id1, beforeSend: function(xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function (data) { console.log("SUCCESS: ", data); $('#pharmacyName').append(data['name']); $('#address1').append(data['address']); $('#description1').append(data['description']); $('#rating1').append(data['rating']); }, error: function (data) { window.location.href = "error.html" } }); }); //*************************Farmaceuti //Prikaz farmaceuta $(document).on('click', '#patientAllPharmacists', function () { var card = $(".card") var pharmacists = $(".pharmacists") var dermatologists = $(".dermatologists") var medicine = $(".medicine"); var availableAppointments = $(".availableAppointments"); pharmacists.show(); card.hide(); dermatologists.hide(); medicine.hide(); availableAppointments.hide(); var counseling = $(".counseling"); counseling.hide(); var id1 = JSON.stringify({"id" : id}); $.ajax({ type: "POST", url: "http://localhost:8081/pharmacists/allPharmacistsFromPharmacy", dataType: "json", contentType: "application/json", data: id1, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function (data) { console.log("SUCCESS", data); for (i = 0; i < data.length; i++) { var row = "<tr>"; row += "<td>" + data[i]['firstName'] + "</td>"; row += "<td>" + data[i]['lastName'] + "</td>"; row += "<td>" + data[i]['rating'] + "</td>"; row += "<td>" + data[i]['pharmacy']['name'] + "</td>"; var btnMakeAppointment = "<button class='btnMakeAppointment' id = " + data[i]['id'] + "> Zakazi savetovanje </button>"; row += "<td>" + btnMakeAppointment + "</td>"; $('#tablePharmacistsAdminPharmacy').append(row); } }, error: function (jqXHR) { if(jqXHR.status === 403) { window.location.href="error.html"; } if(jqXHR.status === 401) { window.location.href="error.html"; } } }); }); //Zakazivanje var idPh $(document).on('click', '.btnMakeAppointment', function (){ idPh = this.id; console.log("GGG", idPh); var counseling = $(".counseling"); counseling.show(); var pharmacistsShowAdminPharmacy = $(".pharmacistsShowAdminPharmacy"); pharmacistsShowAdminPharmacy.hide() }); $(document).on('click', '#btnCounseling', function () { var beginCounseling = $("#beginCounseling").val(); var myJSON = JSON.stringify({"id" : idPh, "beginofappointment" : beginCounseling}); $.ajax({ type: "POST", url: "http://localhost:8081/counselings/createCounseling", dataType: "json", contentType: "application/json", data: myJSON, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function (data) { alert("Uspesno zakazano savetovanje!"); window.location.href="pharmacies.html"; }, error: function (jqXHR) { if(jqXHR.status === 403) { window.location.href="error.html"; } if(jqXHR.status === 401) { window.location.href="error.html"; } } }); }); //************************Dermatolozi $(document).on('click', '#patientAllDermatologists', function () { var card = $(".card") var pharmacists = $(".pharmacists") var dermatologists = $(".dermatologists") var medicine = $(".medicine"); var availableAppointments = $(".availableAppointments"); pharmacists.hide(); card.hide(); dermatologists.show(); medicine.hide(); availableAppointments.hide(); var id1 = JSON.stringify({"id" : id}); $.ajax({ type: "POST", url: "http://localhost:8081/dermatologists/dermatologistsByPharmacy", dataType: "json", contentType: "application/json", data: id1, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function (data) { console.log("SUCCESS", data); for (i = 0; i < data.length; i++) { var row = "<tr>"; var list = "<ul"; row += "<td>" + data[i]['firstName'] + "</td>"; row += "<td>" + data[i]['lastName'] + "</td>"; row += "<td>" + data[i]['rating'] + "</td>"; for (var j = 0; j < data[i]['pharmacies'].length; j++) { console.log(data[i]['pharmacies'][j]['name']); list += "<li>" + data[i]['pharmacies'][j]['name'] + "</li>"; } row += "<td>" + list+ "</td>"; $('#tableDermatologistsAdminPharmacy').append(row); } }, error: function (jqXHR) { if(jqXHR.status === 403) { window.location.href="error.html"; } if(jqXHR.status === 401) { window.location.href="error.html"; } } }); }); //***********************Lekovi $(document).on('click', '#patientAllMedicine', function () { var card = $(".card") var pharmacists = $(".pharmacists") var dermatologists = $(".dermatologists") var medicine = $(".medicine"); var availableAppointments = $(".availableAppointments"); pharmacists.hide(); card.hide(); dermatologists.hide(); medicine.show(); availableAppointments.hide(); var id1 = JSON.stringify({"id" : id}); $.ajax({ type: "POST", url: "http://localhost:8081/medications/allMedicationsByPharmacy", dataType: "json", contentType: "application/json", data: id1, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function (data) { console.log("SUCCESS", data); for (i = 0; i < data.length; i++) { var row = "<tr>"; row += "<td>" + data[i]['code'] + "</td>"; row += "<td>" + data[i]['name'] + "</td>"; row += "<td>" + data[i]['producer'] + "</td>"; row += "<td>" + data[i]['price'] + "</td>"; var btnReserve = "<button class='btnReserve' id = " + data[i]['name'] + "> Rezervisi lek </button>"; row += "<td>" + btnReserve + "</td>"; $('#tableMedicineAdminPharmacy').append(row); } }, error: function (jqXHR) { if(jqXHR.status === 403) { window.location.href="error.html"; } if(jqXHR.status === 401) { window.location.href="error.html"; } } }); }); //Rezervacija $(document).on('click', '.btnReserve', function () { var nameMed = this.id; $(document).on('click', '#btnMedicineReservation', function () { var dateReservation = $("#dateReservation").val(); var myJSON = JSON.stringify({"id": id, "name":nameMed, "dateofreservation" : dateReservation}); $.ajax({ type: "POST", url: "http://localhost:8081/reservations/createReservation", dataType: "json", contentType: "application/json", data: myJSON, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function (data) { alert("Lek uspesno rezervisan"); window.location.href="pharmacies.html"; }, error: function (jqXHR) { if(jqXHR.status === 403) { window.location.href="error.html"; } if(jqXHR.status === 401) { window.location.href="error.html"; } } }); }); }); //***********************Slobodni termini $(document).on('click', '#patientAllAvailableAppointments', function () { var card = $(".card") var pharmacists = $(".pharmacists") var dermatologists = $(".dermatologists") var medicine = $(".medicine"); var availableAppointments = $(".availableAppointments"); pharmacists.hide(); card.hide(); dermatologists.hide(); medicine.hide(); availableAppointments.show(); var id1 = JSON.stringify({"id" : id}); $.ajax({ type: "POST", url: "http://localhost:8081/appointments/availableAppointmentsByPharmacy", dataType: "json", contentType: "application/json", data: id1, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function (data) { console.log("SUCCESS", data); for (i = 0; i < data.length; i++) { var row = "<tr>"; row += "<td>" + data[i]['dermatologist']['firstName'] + "</td>"; row += "<td>" + data[i]['dermatologist']['lastName'] + "</td>"; row += "<td>" + data[i]['beginofappointment'] + "</td>"; row += "<td>" + data[i]['endofappointment'] + "</td>"; row += "<td>" + data[i]['price'] + "</td>"; var btnMake = "<button class='btnMake' id = " + data[i]['id'] + ">Zakazi</button>"; row += "<td>" + btnMake + "</td>"; $('#tableAppointmentsAdminPharmacy').append(row); } }, error: function (jqXHR) { if(jqXHR.status === 403) { window.location.href="error.html"; } if(jqXHR.status === 401) { window.location.href="error.html"; } } }); }); $(document).on('click', '.btnMake', function (){ var idApp = this.id; var id1 = JSON.stringify({"id":idApp}); $.ajax({ type: "POST", url: "http://localhost:8081/appointments/reserveappointment", dataType: "json", contentType: "application/json", data: id1, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function (data) { console.log("SUCCESS", data); alert("Uspesno zakazan termin!"); window.location.href="pharmacies.html"; }, error: function (jqXHR) { if(jqXHR.status === 403) { window.location.href="error.html"; } if(jqXHR.status === 401) { window.location.href="error.html"; } } }); });
// let portée de bloc /// var portée élargie // ATTENTION évitons de déclarer plusieurs variables dans différents espaces en utilisant un même nom ( cet ex est juste pour la démonstration) // function porteeNew() { let xLet = 1; var yVar = 2; if (true){ let xLet = 500; //let n'aura pas de portée au dela de ce bloc de code var yVar = 100;// var aura une portée au dela de ce bloc de code de ce if document.getElementById('p1').innerHTML = ' La variable let "xLet" dans le if = ' + xLet ; document.getElementById('p2').innerHTML = ' La variable var "yVar" dans le if = ' + yVar ; //console.log(xLet); }// fin du if true document.getElementById('p3').innerHTML = ' La variable let "xLet" dans le if = ' + xLet ; document.getElementById('p4').innerHTML = ' La variable var "yVar" dans le if = ' + yVar ; // yVar affichera la dernière valeur déclarée car var a une portée élargie }// fin function porteeNew();
var shoppingCart = { items : [ 'Apple','Orange','Fineapple'] ,inventory : { Apple: 1, Orange : 0, Fineapple : 0 } ,checkout() { this.items.forEach( item => { if (!this.inventory[item]) { console.log(' Item '+ item + ' has sold out. '); } }) } } shoppingCart.checkout(); const WorkoutPlna = () => {}; // let workout = new WorkoutPlna(); console.log(WorkoutPlna.prototype);
if (g_id != -1) { $("#sc_id").val(sc_id); $("#made_in").val(mi); $.post('ajax_request.php', {newGoods: g_id}, function (data) { var inf = eval('(' + data + ')'); $('#g_name').append('<option value = "' + inf.id + '">' + inf.name + '</option>'); }); getGInf(); } $("#g_name").change(function () { g_id = $("#g_name option:selected").val(); getGInf(); }); $("#sc_id").change(function () { $("#g_name").load("ajax_request.php", { categoryCheck: $("#sc_id option:selected").val(), situation:1 }, $("#g_name").empty()) }); $('#changeSc').change(function(){ $.post('ajax_request.php',{alterCategory: $("#changeSc option:selected").val(),g_id:g_id},function(data){ }); }); $(document).on('change', '.category', function () { $.post('ajax_request.php', {changeCategory: 1, d_id: $(this).attr('id'), value: $(this).val()},function(data){ showToast('修改成功'); }); }) $(document).on('change', '.sale', function () { //alert('change'); $.post('ajax_request.php', {changeSale: 1, d_id: $(this).attr("id"), value: $(this).val()},function(data){ showToast('修改成功'); }); }); $(document).on('change', '.wholesale', function () { $.post('ajax_request.php', {changeWholesale: 1, d_id: $(this).attr("id"), value: $(this).val()},function(data){ showToast('修改成功'); }); }); $(document).on('click', '#add_category', function () { $.post('ajax_request.php', {addNewCategory: 1, g_id: g_id}, function (data) { $('#add-button').before( '<p>规格:<input class="detail-input category" type="text" id="' + data + '"value="规格' +data + '"/>' + '售价:<input class="detail-input" type="text" class="sale" id="' +data + '"value="9999"/>' + '<a class="detail-delete" href="controller.php?del_detail_id=' +data + '&g_id=' + g_id + '">删除此规格</a>' + '</p>'); }); }); $(document).on('click', '.is_cover', function () { $.post('ajax_request.php', {set_cover_id: $(this).val(), g_id: g_id},function(data){ showToast('已设为封面图') }); }); $(document).on('click','.img-upload',function(){ $('#g-img-up').click(); }); $(document).on('change','#g-img-up',function(){ $.ajaxFileUpload({ url:'upload.php?g_id='+g_id, secureuri: false, fileElementId: $(this).attr('id'), //文件上传域的ID dataType: 'json', //返回值类型 一般设置为json success: function (v, status){ if('SUCCESS'== v.state){ var isCheck = (1 == v.cover ? 'checked = true' : ''); var content = '<div class="demo-box"><input type="radio" name="is_cover"class="is_cover"value="' + v.id + '"' + isCheck + '/>作为缩略图' + '<a href="#"class="deleteImg"id="'+v.md5+'"><img class="demo" src= "../' + v.url + '" alt = "error" /></a></div>'; $('.img-upload').before(content); }else{ showToast(v.state); } } //服务器成功响应处理函数 }); }); $(document).on('click','.alt_img',function(){ var id=$(this).attr('id').slice(3) $('#alt_img'+id).click(); }) $(document).on('change','.alt_input',function(){ var id=$(this).attr('id').slice(7); $.ajaxFileUpload({ url:'upload.php?alt_img='+id, secureuri: false, fileElementId: 'alt_img'+id, //文件上传域的ID dataType: 'json', //返回值类型 一般设置为json success: function (v, status){ if('SUCCESS'== v.state){ $('#img'+id).attr('src','../'+ v.url); //var isCheck = (1 == v.cover ? 'checked = true' : ''); //var content = '<div class="demo-box"><input type="radio" name="is_cover"class="is_cover"value="' + v.id + '"' + isCheck + '/>作为缩略图' // + '<a href="#"class="deleteImg"id="'+v.md5+'"><img class="demo" src= "../' + v.url + '" alt = "error" /></a></div>'; // //$('.img-upload').before(content); }else{ showToast(v.state); } } //服务器成功响应处理函数 }); }); $(document).on('click','.deleteImg',function(){ var id=$(this).attr('id'); $.post('ajax_request.php',{del_g_img:1,md5:id,g_id:g_id},function(data){ $('#'+id).parent().remove(); }); }); $(document).on('click','.part_dft',function(){ var id=$(this).attr('id').slice(5); var stu=true==$(this).prop('checked')?1:0; $.post('ajax_request.php',{change_part_stu:1,id:id,value:stu},function(data){ if(data==1){ showToast('已设为默认配件') }else{ showToast('已取消默认配件') } }); }); $(document).on('click','.coop_dft',function(){ var id=$(this).attr('id').slice(4); var stu=true==$(this).prop('checked')?1:0; $.post('ajax_request.php',{change_coop_stu:1,part_id:id,g_id:g_id,value:stu},function(data){ if(data==1){ showToast('已设定') }else{ showToast('已取消') } }); }); /** * 获取货品信息 */ function getGInf() { $('#g_id_img').val(g_id); $('#hidden_g_id').val(g_id); $('#goods_detail').empty(); $('#goods_image').empty(); $('#intro').empty(); $('#changeSituation').empty(); $('.parm-set').empty(); $('#host_set').empty(); $('#coop_set').empty(); $('#changeCategory').css('display','none'); $.post("ajax_request.php", {get_g_inf:1,g_id: g_id}, function (data) { var inf = eval('(' + data + ')'); if(0==inf.goodsInf.situation){ var stub='<a href="controller.php?goodsSituation=1&g_id='+g_id+'">上架</a>' }else{ var stub='<a href="controller.php?goodsSituation=0&g_id='+g_id+'">下架</a>' } $('#intro').append(inf.goodsInf.intro); $('#changeSituation').append(stub); $('#name').val(inf.goodsInf.name); $('#s_name').val(inf.goodsInf.made_in); $('#produce_id').val(inf.goodsInf.produce_id); if(null!=inf.goodsInf.inf) { um.setContent(inf.goodsInf.inf); }else{ um.setContent(''); } if(null!=inf.afterInf) { afterEdit.setContent(inf.afterInf); }else{ afterEdit.setContent(''); } if(null!=inf.detail) { $.each(inf.detail, function (k, v) { var content = '<p>规格:<input class="detail-input category" type="text" id="' + v.id + '"value="' + v.category + '"/>' + '售价:<input class="detail-input sale" type="text" class="sale" id="' + v.id + '"value="' + v.sale + '"/>' + '<a class="detail-delete" href="controller.php?del_detail_id=' + v.id + '&g_id=' + g_id + '">删除此规格</a>' + '</p>'; $('#goods_detail').append(content); }); $('#goods_detail').append('<div class="divButton"id="add-button"><p id="add_category">添加规格</p></div>'); } if (null != inf.img) { $('#goods_image').append('<div class="module-title"><h4>图片展示</h4></div>'); $.each(inf.img, function (k, v) { var isCheck = (1 == v.front_cover ? 'checked = true' : ''); var content = '<div class="demo-box"><input type="radio" name="is_cover"class="is_cover"value="' + v.id + '"' + isCheck + '/>作为缩略图' + '<a class="alt_img"id="alt'+v.id+'"><img class="demo"id="img'+ v.id+'" src= "../' + v.url + '" alt = "error" /></a><input type="file"class="alt_input"id="alt_img'+ v.id+'"name="alt_img'+ v.id+'"style="display: none">' +'<a href="#"class="deleteImg"id="'+v.remark+'">删除</a></div>' $('#goods_image').append(content); }); } $('#goods_image').append('<a class="img-upload"></a><input type="file"id="g-img-up"name="g-img-up"style="display: none">'); var precon='<div class="module-title">'+ '<h4>参数设置</h4>'+ '</div><form id="updateParm"action="controller.php?updateParm=1&g_id='+g_id+'"method="post">'; $.each(inf.parm,function(k,v){ var cateName=k; var con='<table class="parmInput"><tr><td colspan="2">'+cateName+'</td></tr>' $.each(v,function(subk,subv){ var scon='<tr><td>'+subv.name+'</td><td><input type="text" name="'+subv.col+'"value="'+subv.value+'"/></td></tr>' con+=scon; }); con+='</table>' precon+=con }); $('.parm-set').append(precon+'<button>提交参数修改</button></form>'); $('#host_set').append('<div class="module-title"><h4>配件默认状态</h4></div>'); if(null!=inf.parts) { $.each(inf.parts, function (k, v) { //alert('have parts'); var checked = 1 == v.dft_check ? 'checked="checked"' : '' var con = '<div class="option_block"><input type="checkbox"class="part_dft"' + checked + 'id="parts' + v.id + '"/>' + v.part_name + ' ' + v.part_produce_id +'</div>' $('#host_set').append(con); }); } $('#coop_set').append('<div class="module-title"><h4>搭配产品</h4></div>'); if(null!=inf.coop) { $.each(inf.coop, function (k, v) { //alert('have parts'); var checked = 1 == v.checked ? 'checked="checked"' : '' var con = '<div class="option_block"><input type="checkbox"class="coop_dft"' + checked + 'id="coop' + v.id + '"/>' + v.name + ' ' + v.produce_id +'</div>' $('#coop_set').append(con); }); } $('#g_inf').slideDown('fast'); $('#changeCategory').css('display','block'); }); }
'use strict'; const passport = require('passport'); module.exports.info = [ passport.authenticate('bearer', {session: true}), (req, res) => { const {user} = req; res.json({user_id: user.id, name: user.name, scope: req.authInfo.scope}); } ]; module.exports.ping = [ passport.authenticate('bearer', {session: true}), (req, res) => { res.status(200).send('OK'); } ]; module.exports.devices = [ passport.authenticate('bearer', {session: true}), (req, res) => { const reqId = req.get('X-Request-Id'); const r = { request_id: reqId, payload: { user_id: "1", devices: [] } }; for (const d of global.devices) { r.payload.devices.push(d.getInfo()); }; res.status(200).send(r); } ]; module.exports.query = [ passport.authenticate('bearer', {session: true}), (req, res) => { const reqId = req.get('X-Request-Id'); const r = { request_id: reqId, payload: { devices: [] } }; for (const d of req.body.devices) { const ldevice = global.devices.find(device => device.data.id == d.id); r.payload.devices.push(ldevice.getState()); }; res.status(200).send(r); } ]; module.exports.action = [ passport.authenticate('bearer', {session: true}), (req, res) => { const reqId = req.get('X-Request-Id'); const r = { request_id: reqId, payload: { devices: [] } }; for (const payloadDevice of req.body.payload.devices) { const {id} = payloadDevice; const capabilities = []; const ldevice = global.devices.find(device => device.data.id == id); for (const pdc of payloadDevice.capabilities) { capabilities.push(ldevice.setCapabilityState(pdc.state.value , pdc.type, pdc.state.instance)); } r.payload.devices.push({id, capabilities}); }; res.status(200).send(r); } ]; module.exports.unlink = [ passport.authenticate('bearer', {session: true}), (req, res) => { const reqId = req.get('X-Request-Id'); const r = { request_id: reqId, } res.status(200).send(r); } ];
/** * DatosReservaController * * @description :: Server-side logic for managing Datosreservas * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ module.exports = { register: function (req, res) { if (req.method == 'POST') { //console.log(req.param('id_hab')); Habitacion.find({ id: req.param('id_habT') }).exec(function (err, habitaciones) { if (err) { return res.serverError(err); } return res.view('reservation', { pclassR: 'active', pclassD: 'disabled', pclassS: 'disabled', pclassC: 'disabled', tclassR: 'in active', tclassD: ' ', tclassS: ' ', tclassC: ' ', habitacionesF: habitaciones, nombres: req.param('nombres'), apellidos: req.param('apellidos'), cedula: req.param('cedula'), email: req.param('email'), direccion: req.param('direccion'), telefono: req.param('telefono'), fecha_reserva: req.param('fecha_reserva'), dias: req.param('dias'), num_tarjeta: req.param('num_tarjeta'), personas: req.param('personas') }); }); } } };
const commonFunction = require("../functions/commonFunctions") const categoryModel = require("../models/categories") const settingModel = require("../models/settings") const md5 = require("md5") const globalModel = require("../models/globalModel") const privacyLevelModel = require("../models/levelPermissions") const userModel = require("../models/users") const videoModel = require("../models/videos") const moment = require("moment") const privacyModel = require("../models/privacy") exports.create = async (req, res) => { await commonFunction.getGeneralInfo(req, res, "live_streaming_create") let custom_url = req.params.custom_url let video = null if(custom_url){ await videoModel.findByCustomUrl(custom_url,req,res).then(result => { if(result){ if(result.scheduled){ let date = moment(result.scheduled) result.scheduled = date.tz(process.env.TZ).toDate(); } video = result } }) } if(video){ await privacyModel.permission(req, 'video', 'edit', video).then(result => { video.canEdit = result }).catch(err => { }) if(!video.scheduled || !video.canEdit){ if (req.query.data) { res.send({data: req.query,user_login:1}); return } req.app.render(req, res, '/permission-error', req.query); return }else{ req.query.editItem = video } req.query.videoId = custom_url } if(!req.user){ if (req.query.data) { res.send({data: req.query,user_login:1}); return } req.app.render(req, res, '/login', req.query); return } let settings = await settingModel.settingData(req); if(!settings["live_streaming_type"]){ settings["live_streaming_type"] = 1; } if(parseInt(settings["live_stream_start"]) != 1 || ( (parseInt(settings['live_streaming_type']) == 1 && !settings["agora_app_id"]) && (parseInt(settings['live_streaming_type']) == 1 && !settings["antserver_media_url"] ) )){ if (req.query.data) { res.send({ data: req.query, pagenotfound: 1 }); return } req.app.render(req, res, '/page-not-found', req.query); return } //owner plans await privacyLevelModel.findBykey(req,"member",'allow_create_subscriptionplans',req.user.level_id).then(result => { req.query.planCreate = result == 1 ? 1 : 0 }) if(req.query.planCreate == 1){ //get user plans await userModel.getPlans(req, { owner_id: req.user.user_id }).then(result => { if (result) { req.query.plans = result } }) } //tip data if enabled if(parseInt(req.appSettings['video_tip']) == 1 && req.query.editItem){ //get tip data await videoModel.getTips(req,{resource_id:req.query.editItem.video_id,resource_type:"video",view:true}).then(result => { if(result && result.length > 0) req.query.editItem.tips = result }) } //get categories const categories = [] await categoryModel.findAll(req, { type: "video" }).then(result => { result.forEach(function (doc, index) { if (doc.subcategory_id == 0 && doc.subsubcategory_id == 0) { const docObject = doc //2nd level let sub = [] result.forEach(function (subcat, index) { if (subcat.subcategory_id == doc.category_id) { let subsub = [] result.forEach(function (subsubcat, index) { if (subsubcat.subsubcategory_id == subcat.category_id) { subsub.push(subsubcat) } }); if (subsub.length > 0) { subcat["subsubcategories"] = subsub; } sub.push(subcat) } }); if (sub.length > 0) { docObject["subcategories"] = sub; } categories.push(docObject); } }) }) if (categories.length > 0) req.query.videoCategories = categories if(settings['live_streaming_type'] == 1 || !settings['live_streaming_type']){ req.query.agora_app_id = settings["agora_app_id"]; }else{ req.query.media_url = settings["antserver_media_url"]; } if(req.appSettings['livestreamingtype'] && req.appSettings['livestreamingtype'] == 0 && (typeof req.appSettings['antserver_media_token'] == "undefined" || req.appSettings['antserver_media_token'] == 1)){ let maximum = 15000 let minimum = 12987 let date = new Date() let time = date.getTime() let number = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; let streamingId = "" + number + time if(req.appSettings['antserver_media_singlekey'] == 1){ streamingId = md5(""+req.user.user_id+(process.env.SECRETKEY ? process.env.SECRETKEY : "")); } await exports.createKey(req,streamingId).then(response => { req.query.tokenStream = response.token }).catch(err => { console.log(err) }); req.query.streamingId = streamingId }else if(req.appSettings['antserver_media_singlekey'] == 1){ req.query.streamingId = md5(""+req.user.user_id+(process.env.SECRETKEY ? process.env.SECRETKEY : "")); } await globalModel.custom(req,"UPDATE users set streamkey = MD5(CONCAT(user_id,'"+(process.env.SECRETKEY ? process.env.SECRETKEY : '') +"')) WHERE streamkey IS NULL AND user_id = ?",[req.user.user_id]).then(result => {}).catch(err => {}); if (req.query.data) { res.send({ data: req.query }) return } req.app.render(req, res, '/create-livestreaming', req.query); } exports.createKey = (req,streamingId) => { return new Promise(async (resolve,reject) => { const https = require('https'); const agent = new https.Agent({ rejectUnauthorized: false }); let reqData = {listenerHookURL:process.env.PUBLIC_URL+"/api/live-streaming/status","streamId":streamingId,"type": "liveStream","name": req.user.user_id+" - "+req.user.displayname+" live streaming",rtmpURL:"rtmp://"+(req.appSettings['antserver_media_url'].replace("https://","").replace("http://",""))+`/${req.appSettings['antserver_media_app']}`} var config = { method: 'post', url: req.appSettings["antserver_media_url"].replace("https://","http://")+`:5080/${req.appSettings['antserver_media_app']}/rest/v2/broadcasts/create`, headers: { 'Content-Type': 'application/json;charset=utf-8' }, data : JSON.stringify(reqData), //httpsAgent: agent }; axios(config) .then(function (response) { if(response.data.status == "created"){ var myDate = new Date(); myDate.setHours(myDate.getHours()+24); var config = { method: 'get', url: req.appSettings["antserver_media_url"].replace("https://","http://")+`:5080/${req.appSettings['antserver_media_app']}/rest/v2/broadcasts/`+streamingId+"/token?expireDate="+(myDate.getTime() / 1000).toFixed(0)+"&type=publish", headers: { 'Content-Type': 'application/json;charset=utf-8' }, //httpsAgent: agent }; axios(config) .then(function (response) { if(response.data.tokenId){ resolve({ token:response.data.tokenId }); }else{ reject(response.error) } }) }else{ console.log(response.data); reject(false); } }) .catch(function (error) { console.log(error) reject(error); }); }); }
var MongoClient = require('mongodb').MongoClient; var express = require('express'); var http = require('http'); var path = require('path'); var bodyParser = require('body-parser'); var routerTasks = require('./routes/tasks'); var PORT = process.env.PORT || 3000; var app = express(); app.locals.moment = require('moment'); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(bodyParser.urlencoded({extended: true})); app.use( require('less-middleware')(path.join(__dirname, 'public')) ); app.use( express.static(path.join(__dirname, 'public')) ); var url = 'mongodb://localhost:27017/tasks'; MongoClient.connect( url, function(err, db) { app.use ('/', routerTasks(db) ); app.get ('/', function(req, res) { res.redirect('/tasks'); } ); app.all('*', function(req, res){ res.status(404).send(); }) app.listen( PORT, function(){ console.log('Express server listening on port ' + PORT); }); } )
import React, { PureComponent } from 'react'; import PropTypes from "prop-types" import withForm from "../../src/helpers/with-form"; class TestButtonMarkup extends PureComponent { render() { const {value, onClick, name} = this.props; return ( <button type="submit" onClick={onClick} name={name}>{value}</button> ) } } TestButtonMarkup.propTypes = { value: PropTypes.string.isRequired }; export default withForm(TestButtonMarkup)
define(['durandal/app', 'knockout', 'plugins/http', 'plugins/router', 'underscore', 'jqueryui', 'jquerymobile', 'bootstrap'], function (app, ko, http, router, _) { //TODO: move these to a config of sorts var URL_ARTSDATABANKEN = 'https://artsdatabanken.no/'; var URL_API_TAXON = URL_ARTSDATABANKEN + 'Api/Taxon/'; var URL_API_NAME = URL_ARTSDATABANKEN + 'Api/Taxon/ScientificName/'; var URL_MEDIA = URL_ARTSDATABANKEN + 'Media/'; var URL_PAGES = URL_ARTSDATABANKEN + 'Pages/'; var URL_SCRIPTS = URL_ARTSDATABANKEN + 'Scripts'; var URL_TAXON = URL_ARTSDATABANKEN + 'Taxon/'; var URL_WIDGETS = URL_ARTSDATABANKEN + 'Widgets/'; // var URL_API_ARTSKART = 'https://pavlov.itea.ntnu.no/artskart/Api/'; var widgetHtml = function(url){ return '<div class="artsdatabanken-widget"><a href="' + url + '"></a></div><script src="' + URL_SCRIPTS + '/widget.js"></script>' }; var getUrlParameter = function getUrlParameter(sParam) { var sPageURL = decodeURIComponent(window.location.search.substring(1)), sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : sParameterName[1]; } } }; var l = ko.observable(getLanguage(getUrlParameter('lang') || 'no')); var key = { name: ko.observable(), geography: ko.observable(), language: ko.observable(), intro: ko.observable(), description: ko.observable(), taxa: ko.observableArray(), characters: ko.observableArray(), usesSubsets: false, usesMorphs: false, relevantTaxa: ko.pureComputed(function () { return _.filter(key.taxa(), function (taxon) { return taxon.reasonsToDrop === 0; }); }), irrelevantTaxa: ko.pureComputed(function () { return _.uniq(_.filter(key.taxa(), function (taxon) { return taxon.reasonsToDrop !== 0 && !(_.some(key.relevantTaxa(), { 'id': taxon.taxonId, 'subset': taxon.subset })); }), function (taxon) { return taxon.taxonId + taxon.subset + taxon.morph;; }); }), remainingSubsets: ko.pureComputed(function () { if(key.usesSubsets) return _.uniq(key.relevantTaxa(), function(taxon) {return taxon.taxonId + taxon.subset;}).length; else return _.uniq(key.relevantTaxa(), function(taxon) {return taxon.taxonId;}).length; }), remainingMorphs: ko.pureComputed(function () { return key.relevantTaxa().length; }), removed: ko.pureComputed(function () { var uniqueSubsets = _.uniq(_.cloneDeep(removedTaxa()), function (taxon) { return taxon.taxonId + taxon.subset; }); return uniqueSubsets.length; }), commonTaxonomy: ko.observable([]), foundTaxonomy: ko.pureComputed(function () { var array = _.map(_.pluck(key.relevantTaxa(), 'taxonObject.AcceptedName.higherClassification'), function (tax) { return _.slice(tax, key.commonTaxonomy().length); }); return _.filter(_.first(array), function (firstItem) { return _.every(_.rest(array), function (otherArray) { return _.some(otherArray, function (otherItem) { return _.isEqual(firstItem, otherItem); }); }); }); }), lastCommon: function () { if (key.foundTaxonomy().length > 0) return _.last(key.foundTaxonomy()).scientificName; else return false; }, taxaList: ko.pureComputed(function () { var uniqueTaxa = _.uniq(_.cloneDeep(key.relevantTaxa()), function (taxon) { return taxon.taxonId; }); if(key.usesMorphs) { _.forEach(uniqueTaxa, function(t){ if(_.some(key.relevantTaxa(), function(r) {return r.taxonId == t.taxonId && r.morph != t.morph;})) { t.morph = null; } }); } if(!key.usesSubsets) return uniqueTaxa; var uniqueSubsets = _.uniq(_.cloneDeep(key.relevantTaxa()), function (taxon) { return taxon.taxonId + taxon.subset; }); if(key.usesMorphs) { _.forEach(uniqueSubsets, function(t){ if(_.some(key.relevantTaxa(), function(r) {return r.taxonId == t.taxonId && r.morph != t.morph;})) { t.morph = null; } }); } if(uniqueTaxa.length == 1) { return uniqueSubsets; } for (i = 0; i < uniqueTaxa.length; i++) { var taxon = uniqueTaxa[i]; taxon.subset = (_(_.pluck(_.filter(uniqueSubsets, function(t) {return t.taxonId === taxon.taxonId && t.subset;}), 'subset')).toString()).replace(",","/"); } return uniqueTaxa; }), droppedTaxa: ko.pureComputed(function () { var uniqueSubsets = _.uniq(_.cloneDeep(key.irrelevantTaxa()), function (taxon) { return taxon.taxonId + taxon.subset; }); if (uniqueSubsets.length === 1) { return uniqueSubsets; } var uniqueTaxa = _.uniq(_.cloneDeep(uniqueSubsets), function (taxon) { return taxon.taxonId; }); if(key.usesSubsets) { for (i = 0; i < uniqueTaxa.length; i++) { var taxon = uniqueTaxa[i]; taxon.subset = (_(_.pluck(_.filter(uniqueSubsets, function(t) {return t.taxonId === taxon.taxonId && !!t.subset;}), 'subset')).toString()).replace(",","/"); } } return uniqueTaxa; }), listView: ko.observable(false), widgetHtml: ko.observable(false), widgetLink: ko.observable(false), showTaxon: ko.observable(false), //~ the id of the character that received the most recent input (needed for focus) lastAnswered: ko.observable(null), //~ the id of the first unanswered question, unless the lastAnswered is still relevant focus: ko.pureComputed(function () { if(key.lastAnswered() !== null) { var character = _.find(key.characters(), function (char) { return char.id === key.lastAnswered(); }); if(character.relevance() > 0) { return key.lastAnswered(); } } if(key.characters_unanswered().length > 0) { return _.first(key.characters_unanswered()).id; } return -1; }).extend({notify: 'always', rateLimit: 10}), firstCharacter: ko.pureComputed(function () { //~ the id of the first question, regardless of answered or not if(key.characters_answered().length > 0) return _.first(key.characters_answered()).id; if(key.characters_unanswered().length > 0) return _.first(key.characters_unanswered()).id; return -1; }).extend({notify: 'always', rateLimit: 10}), lastCharacter: ko.pureComputed(function () { //~ the id of the last unanswered question if(key.characters_unanswered().length > 0) return _.last(key.characters_unanswered()).id; return -1; }).extend({notify: 'always', rateLimit: 10}), //~ questions that have been fully answered characters_answered: ko.pureComputed(function () { return _.sortBy(_.filter(key.characters(), function (character) { return character.checked() && character.relevance() === 0; }), function(a){return a.timestamp();}); }), //~ questions that are relevant but have not been (fully) answered characters_unanswered: ko.pureComputed(function () { //~ for (i = 0; i < array.length; i++) //~ { //~ array[i].states(_.sortBy(array[i].states(), function(a) { //~ return [-a.status(), a.id]; //~ })); //~ } //~ sortBy won't work with multiple funtions :( return _.sortBy(_.sortBy(_.sortBy(_.filter(key.characters(), function (character) { return character.relevance() !== 0 && character.evaluate(); }), function(c){return c.skewness();}),'sort'), function(c){return c.skipped();}); }) //~ characters_hidden: ko.pureComputed(function () { //~ return _.filter(key.characters(), function (character) { //~ return !character.skipped() && (!character.evaluate() || (character.relevance() > 1)); //~ }); //~ }), //~ characters_all: ko.pureComputed(function () { //~ return _([]).concat(key.characters_checked(), key.characters_unanswered(), key.characters_skipped()).value(); //~ return _.filter(key.characters(), function (character) { //~ return character.evaluate(); //~ }); //~ }).extend({notify: 'always', rateLimit: 10}) }, removedTaxa = ko.observableArray(), parseCSV = function (array) { while(array[0].length > array[array.length-1].length) array.pop(); array = array.map(function(a) {return a.map(function(v) {return (typeof v === 'string' ? v.trim() : v);});}); var self = this, keyFields = ['key name', 'geographic range', 'language', 'key intro', 'key description'], keyName, keyRange, keyLanguage, keyIntro, keyDescription, headerRow = 0, headerColumn = 2; while (!array[headerRow][0] || keyFields.indexOf(array[headerRow][0].toLowerCase()) !== -1) { if (array[headerRow][0]) { if (array[headerRow][0].toLowerCase() === keyFields[0]) keyName = array[headerRow][1]; else if (array[headerRow][0].toLowerCase() === keyFields[1]) keyRange = array[headerRow][1]; else if (array[headerRow][0].toLowerCase() === keyFields[2]) keyLanguage = array[headerRow][1]; else if (array[headerRow][0].toLowerCase() === keyFields[3]) keyIntro = array[headerRow][1]; else if (array[headerRow][0].toLowerCase() === keyFields[4]) keyDescription = array[headerRow][1]; } headerRow++; } while (!array[0][headerColumn]) { headerColumn++; } for (var row = headerRow + 1; row < array.length; row++) { for (var col = headerColumn + 1; col < array[0].length; col++) { array[row][col] = ("" + array[row][col]).replace(",", "."); if (array[row][col] === "" || !(0 <= +array[row][col] && +array[row][col] <= 1)) array[row][col] = null; else array[row][col] = +array[row][col]; } } var taxonHeaders = []; for (var i = 0; i < headerRow; i++) taxonHeaders.push(array[i][headerColumn]); var taxa = [], taxonNameRow = taxonHeaders.indexOf('Name'), taxonSubsetRow = taxonHeaders.indexOf('Subset'), taxonMorphRow = taxonHeaders.indexOf('Morph'), taxonIdRow = taxonHeaders.indexOf('Taxon'), taxonScientificNameIdRow = taxonHeaders.indexOf('ScientificNameID'), taxonMediaRow = taxonHeaders.indexOf('Media'), taxonDescriptionRow = taxonHeaders.indexOf('Description'), taxonSortRow = taxonHeaders.indexOf('Sort'), taxonFollowupRow = taxonHeaders.indexOf('Followup'); for (var i = headerColumn + 1; i < array[0].length; i++) { taxa.push({ taxonId: (taxonIdRow > -1 && array[taxonIdRow][i] && $.isNumeric(array[taxonIdRow][i]) ? array[taxonIdRow][i] : null), scientificNameId: (taxonScientificNameIdRow > -1 && array[taxonScientificNameIdRow][i] && $.isNumeric(array[taxonScientificNameIdRow][i]) ? array[taxonScientificNameIdRow][i] : null), index: i, name: (taxonNameRow > -1 && array[taxonNameRow][i] ? array[taxonNameRow][i] : null), subset: (taxonSubsetRow > -1 && array[taxonSubsetRow][i] ? array[taxonSubsetRow][i] : null), morph: (taxonMorphRow > -1 && array[taxonMorphRow][i] ? array[taxonMorphRow][i] : null), media: (taxonMediaRow > -1 && array[taxonMediaRow][i] ? array[taxonMediaRow][i] : null), sort: (taxonSortRow > -1 && array[taxonSortRow][i] ? Number(array[taxonSortRow][i]) : 0), description: (taxonDescriptionRow > -1 && array[taxonDescriptionRow][i] ? array[taxonDescriptionRow][i] : null), followup: (taxonFollowupRow > -1 && array[taxonFollowupRow][i] ? array[taxonFollowupRow][i] : null), taxonObject: null, stateValues: [] }); if(!key.usesSubsets && taxonSubsetRow > -1 && array[taxonSubsetRow][i]) key.usesSubsets = true; if(!key.usesMorphs && taxonMorphRow > -1 && array[taxonMorphRow][i]) key.usesMorphs = true; } var characterHeaders = []; for (var i = 0; i < headerColumn; i++) characterHeaders.push(array[headerRow][i]); var characters = [], characterNameCol = characterHeaders.indexOf('Character'), stateNameCol = characterHeaders.indexOf('State'), stateRefCol = characterHeaders.indexOf('State id'), characterRuleCol = characterHeaders.indexOf('Character requirement'), stateMediaCol = characterHeaders.indexOf('State media'), characterMultiCol = characterHeaders.indexOf('Multistate character'), characterSort = characterHeaders.indexOf('Sort'), characterDescription = characterHeaders.indexOf('Description'); for (var i = headerRow + 1; i < array.length; i++) { var characterName = (characterNameCol > -1 && array[i][characterNameCol] ? array[i][characterNameCol] : null), stateName = (stateNameCol > -1 && array[i][stateNameCol] ? array[i][stateNameCol] : null), ref = (stateRefCol > -1 && array[i][stateRefCol] ? array[i][stateRefCol] : null), rule = (characterRuleCol > -1 && array[i][characterRuleCol] ? array[i][characterRuleCol] : null), media = (stateMediaCol > -1 && array[i][stateMediaCol] ? array[i][stateMediaCol] : null), sort = (characterSort > -1 && array[i][characterSort] ? Number(array[i][characterSort]) : 0), description = (characterDescription > -1 && array[i][characterDescription] ? array[i][characterDescription] : null), multi = (characterMultiCol > -1 && array[i][characterMultiCol] && array[i][characterMultiCol].toLowerCase() === "true"); if (!stateName) break; var values = array[i].slice(headerColumn + 1); if (characterName) { characters.push({ id: i, string: characterName, sort: sort, description: description, rule: rule, multistate: multi, valuePattern: [], stateOrder: [], twins: [], states: ko.observableArray() }); } characters[characters.length - 1].states.push({ parent: characters[characters.length - 1].id, id: i, string: stateName, ref: ref, media: media }); characters[characters.length - 1].valuePattern.push([characters[characters.length - 1].states().length - 1, values]); for (var j = 0; j < values.length; j++) { if (_.isFinite(values[j])) taxa[j].stateValues.push({state: i, value: values[j], characterString: characters[characters.length - 1].string, stateString: characters[characters.length - 1].states()[characters[characters.length - 1].states().length - 1].string}); } } for (i = 0; i < characters.length; i++) { characters[i].valuePattern = _.sortBy(characters[i].valuePattern, function(a) { return a[1]; }); characters[i].stateOrder = _.map(characters[i].valuePattern, function(x){return x[0];}); characters[i].valuePattern = (_.map(characters[i].valuePattern, function(x){return x[1].toString();})).toString(); } key.name(keyName); key.geography(keyRange); key.language(keyLanguage); l(getLanguage((getUrlParameter('lang')) || keyLanguage || 'no')); key.intro(keyIntro); key.description(keyDescription); fillKey(taxa, characters); }, fillKey = function (taxa, characters) { var gettingAbundances = [], gettingTaxa = [], idCounter = 0, urlTaxa = getUrlParameter('taxa'); if(urlTaxa) urlTaxa = urlTaxa.split(',').map(function(x){return +x;}); else urlTaxa = []; _.forEach(taxa, function (taxon) { taxon.vernacular = taxon.name || 'Loading...'; taxon.scientific = ''; taxon.reasonsToDrop = 0; taxon.removed = false; taxon.imageUrl = function (argString) { if (taxon.media === null) return null; else if (taxon.media.indexOf('/') === -1){ return URL_MEDIA + taxon.media + '?' + argString; } else return taxon.media + '?' + argString; } gettingTaxa.push(function (taxon) { var dfd = $.Deferred(); $.getJSON((taxon.scientificNameId ? URL_API_NAME + taxon.scientificNameId : null), function (data) { taxon.taxonId = data.taxonID; }).always(function () { $.getJSON(URL_API_TAXON + taxon.taxonId, function (data) { taxon.taxonObject = { 'AcceptedName' : { 'scientificName' : data.AcceptedName.scientificName, 'higherClassification' : [] } }; if(data.PreferredVernacularName) { taxon.taxonObject.PreferredVernacularName = {'vernacularName' : data.PreferredVernacularName.vernacularName}; } for (var i = 0; i < data.AcceptedName.higherClassification.length; i++) { var higher = {}; if(data.AcceptedName.higherClassification[i].taxonRank) higher.taxonRank = data.AcceptedName.higherClassification[i].taxonRank; if(data.AcceptedName.higherClassification[i].scientificName) higher.scientificName = data.AcceptedName.higherClassification[i].scientificName; if(data.AcceptedName.higherClassification[i].taxonID) higher.taxonID = data.AcceptedName.higherClassification[i].taxonID; taxon.taxonObject.AcceptedName.higherClassification.push(higher); } if (data.AcceptedName) { taxon.scientific = data.AcceptedName.scientificName; var higher = {}; if(data.AcceptedName.taxonRank) higher.taxonRank = data.AcceptedName.taxonRank; if(data.AcceptedName.scientificName) higher.scientificName = data.AcceptedName.scientificName; higher.taxonID = +taxon.taxonId; taxon.taxonObject.AcceptedName.higherClassification.push(higher); } }).done(function () { if (taxon.taxonObject) { if(urlTaxa.length > 0 && taxon.taxonObject.AcceptedName && _.intersection(_.map(taxon.taxonObject.AcceptedName.higherClassification, 'taxonID'), urlTaxa).length < 1) taxon.remove = true; if (taxon.taxonObject.PreferredVernacularName) taxon.vernacular = _.capitalize(taxon.taxonObject.PreferredVernacularName.vernacularName); else if (taxon.taxonObject.AcceptedName) taxon.vernacular = taxon.scientific; } }).always(function () { dfd.resolve(taxon.taxonObject); }); }); return dfd.promise(); }(taxon)); }); taxa = _.sortBy(taxa, 'sort'); key.taxa(taxa); $.when.apply($, gettingTaxa).then(function () { key.taxa(taxa); taxa = _.filter(taxa, function(t){return t.remove !== true;}); var array = _.pluck(key.taxa(), 'taxonObject.AcceptedName.higherClassification'); key.commonTaxonomy(_.filter(_.first(array), function (firstItem) { return _.every(_.rest(array), function (otherArray) { return _.some(otherArray, function (otherItem) { return _.isEqual(firstItem, otherItem); }); }); })); //~ fetch abundances from the API if there are other taxa with the same sort // _.forEach(_.uniq(taxa, function (taxon) { // return taxon.id; // }), function (taxon) { // if(_.some(taxa, function(t) {return t.id !== taxon.id && t.sort === taxon.sort;})) { // gettingAbundances.push(function (taxon) { // var dfd = $.Deferred(); // $.getJSON(URL_API_ARTSKART + 'Observations/list/?pageSize=0&taxons[]=' + taxon.id, function (data) { // _.forEach(_.filter(taxa, function (t) { // return t.id === taxon.id; // }), function (taxon) { // taxon.abundance = data.TotalCount; // }); // }).done(function () { // dfd.resolve(taxon.abundance); // }); // return dfd.promise(); // }(taxon)); // } // }); // // $.when.apply($, gettingAbundances).then(function () { // //~ lodash 3.10 has no orderBy // key.taxa(_.sortBy(_.sortBy(taxa, function(tt){return -tt.abundance;}),'sort')); // }); }); _.forEach(characters, function (character) { _.forEach(character.states(), function (state) { state.checked = ko.observable(null); state.imageUrl = function (argString) { if (state.media === null) return null; else if (state.media.indexOf("/") === -1) return URL_MEDIA + state.media + "?" + argString; else return state.media + "?" + argString; }; }); character.checked = ko.pureComputed(function () { return _.some(character.states(), function (state) { return state.checked() !== null; }); }); character.showFalse = character.multistate || character.states().length !== 2; character.timestamp = ko.observable(0); character.skipped = ko.observable(false); character.evaluate = ko.pureComputed(function () { if (!character.rule) return true; var string = character.rule; while (~string.indexOf('{')) { var start = string.indexOf('{'); var stop = string.indexOf('}'); string = string.substring(0, start) + evaluateState(string.substring(start + 1, stop)) + string.substring(stop + 1); } return !!eval(string); //~ returns the boolean value of a state with a provided ref. True when either checked manually or 1 for all remaining taxa function evaluateState(ref) { return (_.find(_.find(characters, function (char) { return _.some(char.states(), function (s) { return s.ref === ref; }); }).states(), function (state) { return state.ref === ref; })).status() === 1; } }); _.forEach(character.states(), function (state) { state.zeroes = ko.pureComputed(function () { return _.filter(key.relevantTaxa(), function (taxon) { return _.some(taxon.stateValues, {state: state.id, value: 0}); }).length; }); state.status = ko.pureComputed(function () { if (state.checked() !== null) return state.checked(); if (character.checked() && !character.multistate) { if (_.some(character.states(), function (state) { return state.checked() === 1; })) { return -1; // Was 0 } if (character.states().length === 2) { return 1; } } if (state.zeroes() === key.relevantTaxa().length) return -1; // Was 0 if ((_.filter(key.relevantTaxa(), function (taxon) { return _.some(taxon.stateValues, {state: state.id, value: 1}); })).length === key.relevantTaxa().length) return 1; return null; }); state.relevance = ko.pureComputed(function () { //~ if you know the answer, or it does not matter (like when there's one answer left or it's never false), it's a silly question //~ if the state excludes all or no taxa, it is not relevant, unless it is needed for a later evaluation if (state.status() !== null || key.relevantTaxa().length === 1 || (state.zeroes() === 0 && state.ref == null)) { return 0; } //~ otherwise, as long as it's never totally unknown (even when not distinctive), it's always a valid question var haveValues = _.filter(key.relevantTaxa(), function (taxon) { return _.some(taxon.stateValues, {state: state.id}); }); if (key.relevantTaxa().length === haveValues.length) { return 1; } //~ Otherwise it is always silly return 0; }); }); character.relevance = ko.pureComputed(function () { //~ average of all state relevances if(key.remainingSubsets() < 2) return 0; var stateRelevances = _.filter(_.map(character.states(), function (state) { return state.relevance(); }), function (n) { return n > 0; }); return _.reduce(stateRelevances, function (memo, num) { return memo + num; }, 0) / (stateRelevances.length === 0 ? 1 : stateRelevances.length); }); character.skewness = ko.pureComputed(function () { if (character.relevance === 0) return 1; //~ if there are any conflicting morphs it will be moved to the end of the list by setting a high skewness here if(key.usesMorphs) { for (var i = 0; i < character.states().length; i++) { if(_.some(key.relevantTaxa(), function(t) { return _.some(key.relevantTaxa(), function(r) { return (r.taxonId == t.taxonId && r.subset == t.subset && !_.isEqual(_.find(t.stateValues, {'state': character.states()[i].id}), _.find(r.stateValues, {'state': character.states()[i].id}))); }); })) { return 1; } } } var relevantStates = _.filter(character.states(), function (state) { return state.status() === null; }), perfect = key.relevantTaxa().length * (1 - (1 / relevantStates.length)); return Math.sqrt(_.reduce(relevantStates, function (total, state) { return total + ((state.zeroes() - perfect) * (state.zeroes() - perfect)); }, 0) / relevantStates.length); }); }); for (i = 0; i < characters.length; i++) { for(j = i+1; j < characters.length; j++) { if(characters[i].valuePattern === characters[j].valuePattern) { var reordered = []; for (x = 0; x < characters[i].stateOrder.length; x++) { reordered.push(characters[j].states()[characters[j].stateOrder.indexOf(characters[i].stateOrder[x])]); } characters[j].states(reordered); characters[i].twins.push(characters[j]); characters.splice(j,1); j--; } } } key.characters(characters); }, resetAll = function () { if (dragged_csv != "") { parseCSV(Papa.parse(dragged_csv).data); } _.forEach(key.characters(), function (character) { character.skipped(false); character.timestamp(0); _.forEach(character.states(), function (state) { state.checked(null); }); }); _.forEach(key.taxa(), function (taxon) { taxon.reasonsToDrop = 0; taxon.removed = false; }); key.taxa.valueHasMutated(); }, dropTaxon = function (array, value) { _.forEach(array, function (index) { var taxon = _.find(key.taxa(), _.matchesProperty('index', index)); taxon.reasonsToDrop += value; if (value > 0) taxon.removed = true; else taxon.removed = false; }); key.taxa.valueHasMutated(); }, setState = function (id, parent, value) { var character = _.find(key.characters(), function (char) { return char.id === parent; }), state = _.find(character.states(), function (state) { return state.id === id; }), oldValue = state.checked(); state.checked(value); character.timestamp(Date.now()); _.forEach(key.taxa(), function (taxon) { if (value === 1 && _.find(taxon.stateValues, { 'state': state.id, 'value': 0 })) taxon.reasonsToDrop = taxon.reasonsToDrop + 1; else if (value === -1 && _.find(taxon.stateValues, { 'state': state.id, 'value': 1 })) taxon.reasonsToDrop = taxon.reasonsToDrop + 1; else if (value === null && oldValue === 1 && _.find(taxon.stateValues, { 'state': state.id, 'value': 0 })) taxon.reasonsToDrop = taxon.reasonsToDrop - 1; else if (value === null && oldValue === -1 && _.find(taxon.stateValues, { 'state': state.id, 'value': 1 })) taxon.reasonsToDrop = taxon.reasonsToDrop - 1; //~ when undoing a partial state answer, if all other relevant states are zero for that taxon, decrease reasons to drop else if (value === null && oldValue === -1 && _.find(taxon.stateValues, function(sv){ return sv.state == state.id && sv.value > 0; })) { var restoreIt = true; var si = 0; while (si < character.states().length && restoreIt) { var cs = character.states()[si]; restoreIt = (cs.id === state.id || cs.relevance() !== 1 || !(_.find(taxon.stateValues, function(sv){ return sv.state === cs.id && sv.value > 0; }))); si++; } if(restoreIt) taxon.reasonsToDrop = taxon.reasonsToDrop - 1; } //~ if this excludes the last partial option for a taxon, it also has to be dismissed else if (value === -1 && _.find(taxon.stateValues, function(sv) { return sv.state === state.id && 1 > sv.value && sv.value > 0; })) { //~ for each other relevant state in character, check if it is zero. If all are zero, drop taxon var keepIt = false; var si = 0; while (si < character.states().length && !keepIt) { var cs = character.states()[si]; keepIt = (cs.id != state.id && cs.relevance() === 1 && _.find(taxon.stateValues, function(sv){ return sv.state === cs.id && sv.value > 0; })); si++; } if(!keepIt) taxon.reasonsToDrop = taxon.reasonsToDrop + 1; } }); key.lastAnswered(character.id); key.taxa.valueHasMutated(); }, loadCSVurl = function (url) { http.get(url).then(function (response) { var pp = Papa.parse(response); if(pp.errors.length == 0 && pp.data.length > 2 && pp.data[2].length > 2) parseCSV(pp.data); else alert(l().invalidInput); }); }, loadCSVarray = function (array) { parseCSV(array); }; return { //~ key object serving what the GUI needs key: key, l: l, toggleListView: function () { key.listView(!key.listView()); }, loadCSV_parent: function (array) { loadCSVarray(parent.hotData); }, removeSelected: function (taxon) { //~ if there is one taxon id left, remove all with the current subset if (key.usesSubsets && _.uniq(_.cloneDeep(key.relevantTaxa()), function (t) { return t.taxonId; }).length === 1) { var removing = _.pluck(_.filter(key.taxa(), function (t) { return t.taxonId === taxon.taxonId && t.subset === taxon.subset }), 'index'); } //~ otherwise remove all with that id else { var removing = _.pluck(_.filter(key.taxa(), function (t) { return t.taxonId === taxon.taxonId }), 'index'); } removedTaxa.push(removing); dropTaxon(removing, 1); if (key.remainingSubsets() === 1 || (key.characters_unanswered().length == 0)) { if (key.remainingSubsets() === 1) key.showTaxon(key.taxaList()[0]); $('#taxonModal').modal('show'); } }, undoRemoval: function (taxon) { if (taxon.index) { //~ a particular taxon is provided: find its removal event and unremove all siblings in that array var deletion = _.find(removedTaxa(), function (l) { return _.includes(l, taxon.index); }); _.forEach(deletion, function (i) { dropTaxon([i], -1); }); removedTaxa(_.reject(removedTaxa(), function (t) { return t[0] === taxon.index; })); } else dropTaxon(removedTaxa.pop(), -1); }, closeModal: function (t) { key.widgetHtml("<i class=\"fa fa-spinner fa-pulse fa-5x\"></i>"); key.showTaxon(false); }, enlargeImage: function (t) { var taxon = (_.has(t, 'key') ? key.relevantTaxa()[0] : t); if (taxon.imageUrl === null) return; if ($('#taxonModal').is(':visible')) { $('#taxonModal').modal('hide'); } $('#widgetModal').modal('show'); if (taxon.media.indexOf("/") === -1) { //~ $.get('https://data.artsdatabanken.no/Databank/Content/' + taxon.media + '?Template=Inline', function (data) { $.get(URL_WIDGETS + taxon.media + '?Template=Inline', function (data) { //~ key.widgetHtml("<div class=\"artsdatabanken-widget\"><a href=\"https://data.artsdatabanken.no/Databank/Content/" + taxon.media + "?Template=Inline\"></a></div><script src=\"https://data.artsdatabanken.no/Scripts/widget.js\"></script>"); key.widgetHtml(widgetHtml(URL_WIDGETS + taxon.media)); key.widgetLink(false); }); //~ $.get("https://data.artsdatabanken.no/Widgets/F" + taxon.media, function (data) { //~ key.widgetHtml("<div class=\"artsdatabanken-widget\"><a href=\"https://data.artsdatabanken.no/Widgets/F" + taxon.media + "\"></a></div><script src=\"https://data.artsdatabanken.no/Scripts/widget.js\"></script>"); //~ }); //~ console.log("https://data.artsdatabanken.no/Databank/Content/" + taxon.media + "?Template=Inline"); //~ $.get("https://data.artsdatabanken.no/Databank/Content/F" + taxon.media + "?Template=Inline", function (data) { //~ key.widgetHtml(data); //~ }); } else key.widgetHtml('<img src="' + taxon.media + '"/>'); key.widgetLink(taxon.media); }, showTaxonModal: function (t) { key.widgetHtml('<i class="fa fa-spinner fa-pulse fa-5x"></i>'); key.showTaxon(t); $('#taxonModal').modal('show'); }, showDescription: function (t) { key.widgetHtml('<i class="fa fa-spinner fa-pulse fa-5x"></i>'); if ($('#taxonModal').is(':visible')) { $('#taxonModal').modal('hide'); } $('#widgetModal').modal('show'); var taxon = (_.has(t, 'key') ? key.relevantTaxa()[0] : t); if (!taxon.widgetHtml) { if (taxon.description > 0) { $.get(URL_WIDGETS + taxon.description, function (data) { taxon.widgetHtml = widgetHtml(URL_WIDGETS + taxon.description); //~ key.taxa.valueHasMutated(); key.widgetHtml(taxon.widgetHtml); key.widgetLink(URL_PAGES + taxon.description); }); } } else { key.widgetHtml(taxon.widgetHtml); key.widgetLink(URL_PAGES + taxon.description); } }, showTaxonPage: function (t) { key.widgetHtml('<i class="fa fa-spinner fa-pulse fa-5x"></i>'); if ($('#taxonModal').is(':visible')) { $('#taxonModal').modal('hide'); } $('#widgetModal').modal('show'); var taxon = (_.has(t, 'key') ? key.relevantTaxa()[0] : t); if (taxon.taxonId > 0) { $.get(URL_WIDGETS + '/Taxon/' + taxon.taxonId, function (data) { key.widgetHtml(widgetHtml(URL_WIDGETS+ '/Taxon/' + taxon.taxonId)); key.widgetLink(URL_TAXON + taxon.taxonId); }); } }, showStateHelp: function (s) { key.widgetHtml('<i class="fa fa-spinner fa-pulse fa-5x"></i>'); $('#widgetModal').modal('show'); $.get(URL_WIDGETS + s.description, function (data) { key.widgetHtml(widgetHtml(URL_WIDGETS + s.description)); key.widgetLink(URL_PAGES + s.description); }); }, showAboutWidget: function (s) { var printJSON = function(thing) { var returnValue = ""; if(_.isFunction(thing)) { returnValue += printJSON(thing()); } else if(_.isArray(thing)) { returnValue += "["; for (var i = 0; i < thing.length; i++) { if(i > 0) returnValue += ","; returnValue += printJSON(thing[i]); } returnValue += "]"; } else if(_.isObject(thing)) { returnValue += "{"; for (var item in thing) { var thisValue = printJSON(thing[item]); if(thisValue != "null") { returnValue += "\"" + item + "\" : "; returnValue += thisValue; returnValue += ","; } } if(returnValue.length > 1) returnValue = returnValue.substring(0, returnValue.length-1) + "}"; else returnValue = ""; } else if(_.isString(thing)) { returnValue += "\"" + thing + "\""; } else { returnValue += thing; } return returnValue; }; console.log("{" + "\"name\" : " + printJSON(key.name) + "," + "\"geography\" : " + printJSON(key.geography) + "," + "\"language\": " + printJSON(key.language) + "," + "\"intro\" : " + printJSON(key.intro) + "," + "\"description\" : " + printJSON(key.description) + "," + "\"taxa\" : " + printJSON(key.taxa) + "," + "\"characters\" : " + printJSON(key.characters) + "," + "\"usesSubsets\" : " + printJSON(key.usesSubsets) + "," + "\"usesMorphs\" : " + printJSON(key.usesMorphs) + "}"); key.widgetHtml('<i class="fa fa-spinner fa-pulse fa-5x"></i>'); if ($('#aboutKeyModal').is(':visible')) { $('#aboutKeyModal').modal('hide'); } $('#widgetModal').modal('show'); $.get(URL_WIDGETS + key.description(), function (data) { key.widgetHtml(widgetHtml(URL_WIDGETS + key.description())); key.widgetLink(URL_PAGES + key.description()); }); }, inputTrue: function (state) { //~ set the checked state if it has no status yet if (state.status() === null) { setState(state.id, state.parent, 1); if (key.listView() && $('#focus')[0]) $('#focus')[0].scrollIntoView(true); if (key.remainingSubsets() === 1 || (key.characters_unanswered().length == 0)) { if (key.remainingSubsets() === 1) key.showTaxon(key.taxaList()[0]); $('#taxonModal').modal('show'); } } }, inputFalse: function (state) { //~ set the checked state if it has no status yet if (state.status() === null) { setState(state.id, state.parent, -1); if (key.listView() && $('#focus')[0]) $('#focus')[0].scrollIntoView(true); if (key.remainingSubsets() === 1 || (key.characters_unanswered().length == 0)) { if (key.remainingSubsets() === 1) key.showTaxon(key.taxaList()[0]); $('#taxonModal').modal('show'); } } }, inputReset: function (state) { //~ reset the checked state if it had been checked explicitly if(state.checked() !== null) setState(state.id, state.parent, null); }, skipCharacter: function (character) { _.find(key.characters(), function (char) { return char.id === character.id; }).skipped(true); }, resetAll: function () { if (confirm(l().ConfirmReset)) { removedTaxa([]); key.widgetHtml(false); key.lastAnswered(null); resetAll(); } }, getView: function() { var csvUrl = getUrlParameter('csv'); if (csvUrl) { loadCSVurl(csvUrl); } var fg = getUrlParameter('fg') || 'E86C19'; var bg = getUrlParameter('bg') || 'fff'; var height = getUrlParameter('height') || '100%'; var sheet = document.createElement('style'); sheet.innerHTML = 'html, body {height: ' + height + ';}\ .fg {color: #' + fg + ' !important;}\ .bg {color: #' + bg + ' !important;}\ .ui-state-default {background-color: #' + bg + ' !important;}\ .ui-state-default a {color: #' + fg + ' !important;}\ .ui-tabs-active {background-color: #' + fg + ' !important;}\ .ui-tabs-active a {color: #' + bg + ' !important;}\ .colorize {color: #' + fg + ' !important; background-color: #' + bg + ' !important; text-shadow: unset !important;}'; if(getUrlParameter('minimal')) { sheet.innerHTML += '.colorize_negative {color: #' + fg + ' !important; background-color: #' + bg + ' !important;}'; sheet.innerHTML += '.colorize_negative a {color: #' + fg + ' !important;}'; sheet.innerHTML += '.colorize_neutral {color: #000 !important; background-color: #fff !important;}'; sheet.innerHTML += '.colorize_hide {visibility: hidden !important; width: 0px !important; height: 0px !important; padding: 0px !important;}'; } else { sheet.innerHTML += '.colorize_negative, .colorize_neutral, .colorize_hide {color: #' + bg + ' !important; background-color: #' + fg + ' !important; text-shadow: unset !important;}'; sheet.innerHTML += '.minimal_only {visibility: hidden !important; height: 0px !important; padding: 0px !important;}'; sheet.innerHTML += '.colorize_negative a {color: #' + bg + ' !important;}'; sheet.innerHTML += '.colorize_negative .btn-default {background-color: #' + fg + ' !important; text-shadow: unset !important; box-shadow: none; border: none;}'; } document.body.appendChild(sheet); }, compositionComplete: function(view, parnt) { $('#tabs').tabs(); $('#tabs').tabs('option', 'active', 0); $('#character-carousel').swiperight(function () { $('.carousel').carousel('prev'); }); $('#character-carousel').swipeleft(function () { $('.carousel').carousel('next'); }); parent.postMessage(document.body.scrollHeight, '*'); $('#fileToUpload')[0].addEventListener('change', handleFile, false); } }; });
import Ember from 'ember'; import jQuery from 'jquery'; export default Ember.Component.extend({ actions: { showInfo: function(e) { var $s = this.$('.album-info'); $s.velocity('transition.slideUpBigIn', { duration: 400, drag: true }); }, hideInfo: function(e) { var $s = this.$('.album-info'); $s.velocity('transition.slideDownBigOut', { duration: 400, drag: true }); }, openAlbum: function() { this.get('parentView.controller').send('openAlbum', this.get('album').get('id')); } }, click: function() { this.send('openAlbum'); }, mouseEnter: function() { this.send('showInfo'); }, mouseLeave: function() { this.send('hideInfo'); } });
import React from 'react'; import {render} from 'react-dom'; import {CardComponent} from './CardComponent' export class App extends React.Component { render() { return ( <CardComponent> Hello React! </CardComponent> ) } } render(<App />, document.getElementById('app'));
var $ = require('jquery'); require('bootstrap/dist/css/bootstrap.min.css'); require('@fortawesome/fontawesome-free/css/all.min.css'); require('../css/admin/simple-sidebar.css'); require('../css/admin/login.css'); require('../css/admin/admin.css'); require('../js/bootstrap-select'); //require('jquery-ui'); require('bootstrap'); (function($) { "use strict"; // Start of use strict })(jQuery); // End of use strict $(document).ready(function() { $('[data-toggle="popover"]').popover(); $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); });
/** * LINKURIOUS CONFIDENTIAL * Copyright Linkurious SAS 2012 - 2018 * * - Created on 2016-05-11. */ 'use strict'; // external libs const Promise = require('bluebird'); // services const LKE = require('../../index'); const AlertManager = LKE.getAlert(); const Utils = LKE.getUtils(); const Access = LKE.getAccess(); const Errors = LKE.getErrors(); // locals const api = require('../api'); module.exports = function(app) { app.all('/api/:dataSource/alerts*', api.proxy(req => { if (!LKE.isEnterprise()) { return Errors.business( 'not_implemented', 'Alerts are not available in Linkurious Starter edition.', true ); } return Access.isAuthenticated(req); })); /** * @apiDefine ReturnGetAlertUser * * @apiSuccess (Success 200) {number} id ID of the alert * @apiSuccess (Success 200) {string} title Title of the alert * @apiSuccess (Success 200) {string} sourceKey Key of the data-source * @apiSuccess (Success 200) {object[]} columns Columns among the returned values of the query to save in a match as scalar values * @apiSuccess (Success 200) {string="number","string"} columns.type Type of the column * @apiSuccess (Success 200) {string} columns.columnName Name of the column in the query * @apiSuccess (Success 200) {string} columns.columnTitle Name of the column for the UI * @apiSuccess (Success 200) {string} createdAt Creation date in ISO-8601 format * @apiSuccess (Success 200) {string} updatedAt Last update date in ISO-8601 format * @apiSuccess (Success 200) {string} lastRun Last time the query was executed in ISO-8601 format (`null` it was never executed) * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * "id": 7, * "title": "alert title", * "sourceKey": "584f2569", * "columns": [ * {"type": "number", "columnName": "n1.score", "columnTitle": "Score"} * ], * "createdAt": "2016-05-16T08:23:35.730Z", * "updatedAt": "2016-05-16T08:23:35.730Z", * "lastRun": "2016-05-16T08:23:35.730Z" * } */ /** * @apiDefine ReturnGetAlertsArrayUser * * @apiSuccess (Success 200) {object[]} alerts Alerts * @apiSuccess (Success 200) {number} alerts.id ID of the alert * @apiSuccess (Success 200) {string} alerts.title Title of the alert * @apiSuccess (Success 200) {boolean} alerts.enabled Whether the query will run periodically or not * @apiSuccess (Success 200) {object[]} alerts.columns Columns among the returned values of the query to save in a match as scalar values * @apiSuccess (Success 200) {string="number","string"} alerts.columns.type Type of the column * @apiSuccess (Success 200) {string} alerts.columns.columnName Name of the column in the query * @apiSuccess (Success 200) {string} alerts.columns.columnTitle Name of the column for the UI * @apiSuccess (Success 200) {string} alerts.sourceKey Key of the data-source * @apiSuccess (Success 200) {string} alerts.createdAt Creation date in ISO-8601 format * @apiSuccess (Success 200) {string} alerts.updatedAt Last update date in ISO-8601 format * @apiSuccess (Success 200) {string} alerts.lastRun Last time the query was executed in ISO-8601 format (`null` it was never executed) * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * [ * { * "id": 9, * "title": "alert title 2", * "enabled": true, * "sourceKey": "584f2569", * "columns": [ * {"type": "number", "columnName": "n1.score", "columnTitle": "Score"} * ], * "createdAt": "2016-05-16T08:23:35.730Z", * "updatedAt": "2016-05-16T08:23:35.730Z", * "lastRun": "2016-05-16T08:23:35.730Z" * }, * { * "id": 8, * "title": "alert title 1", * "enabled": true, * "sourceKey": "584f2569", * "columns": [ * {"type": "number", "columnName": "n1.score", "columnTitle": "Score"} * ], * "createdAt": "2016-04-16T08:23:35.730Z", * "updatedAt": "2016-04-16T08:23:35.730Z", * "lastRun": "2016-05-16T08:23:35.730Z" * } * ] */ /** * @apiDefine ReturnGetMatch * * @apiSuccess (Success 200) {number} id ID of the match * @apiSuccess (Success 200) {string} sourceKey Key of the data-source * @apiSuccess (Success 200) {number} alertId ID of the alert * @apiSuccess (Success 200) {string} hash Hash of the match * @apiSuccess (Success 200) {string="unconfirmed","confirmed","dismissed"} status Status of the match * @apiSuccess (Success 200) {object} user Last user that changed the status (`null` if it was never changed) * @apiSuccess (Success 200) {number} user.id ID of the user * @apiSuccess (Success 200) {string} user.username Username of the user * @apiSuccess (Success 200) {string} user.email E-mail of the user * @apiSuccess (Success 200) {object[]} viewers Users that viewed the match (ordered by date in decreasing order) * @apiSuccess (Success 200) {number} viewers.id ID of the user * @apiSuccess (Success 200) {string} viewers.username Username of the user * @apiSuccess (Success 200) {string} viewers.email E-mail of the user * @apiSuccess (Success 200) {string} viewers.date Date of the view in ISO-8601 format * @apiSuccess (Success 200) {type:id[]} nodes IDs of the nodes of the match * @apiSuccess (Success 200) {type:id[]} edges IDs of the edges of the match * @apiSuccess (Success 200) {string} columns Scalar value for a given column by index defined in the alert * @apiSuccess (Success 200) {string} expirationDate Date in ISO-8601 format after which the match is deleted * @apiSuccess (Success 200) {string} createdAt Creation date in ISO-8601 format * @apiSuccess (Success 200) {string} updatedAt Last update date in ISO-8601 format * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * "id": 1, * "sourceKey": "584f2569", * "alertId": 2, * "hash": "897f54ff366922a4077c78955c77bcdd", * "status": "unconfirmed", * "user": null, * "viewers": [], * "nodes": [5971, 5974], * "edges": [523], * "columns": [ * 1999 * ], * "expirationDate": "2016-05-26T08:23:35.730Z", * "createdAt": "2016-05-16T08:23:35.730Z", * "updatedAt": "2016-05-16T08:23:35.730Z" * } */ /** * @apiDefine ReturnGetMatchesArray * * @apiSuccess (Success 200) {object} counts Match counts * @apiSuccess (Success 200) {number} counts.unconfirmed Count of unconfirmed matches * @apiSuccess (Success 200) {number} counts.confirmed Count of confirmed matches * @apiSuccess (Success 200) {number} counts.dismissed Count of dismissed matches * @apiSuccess (Success 200) {object[]} matches Matches * @apiSuccess (Success 200) {number} matches.id ID of the match * @apiSuccess (Success 200) {string} matches.sourceKey Key of the data-source * @apiSuccess (Success 200) {number} matches.alertId ID of the alert * @apiSuccess (Success 200) {string} matches.hash Hash of the match * @apiSuccess (Success 200) {string="unconfirmed","confirmed",dismissed"} matches.status Status of the match * @apiSuccess (Success 200) {object} matches.user Last user that changed the status (`null` if it was never changed) * @apiSuccess (Success 200) {number} matches.user.id ID of the user * @apiSuccess (Success 200) {string} matches.user.username Username of the user * @apiSuccess (Success 200) {string} matches.user.email E-mail of the user * @apiSuccess (Success 200) {object[]} matches.viewers Users that viewed the match (ordered by date in decreasing order) * @apiSuccess (Success 200) {number} matches.viewers.id ID of the user * @apiSuccess (Success 200) {string} matches.viewers.username Username of the user * @apiSuccess (Success 200) {string} matches.viewers.email E-mail of the user * @apiSuccess (Success 200) {string} matches.viewers.date Date of the view in ISO-8601 format * @apiSuccess (Success 200) {type:id[]} matches.nodes IDs of the nodes of the match * @apiSuccess (Success 200) {type:id[]} matches.edges IDs of the edges of the match * @apiSuccess (Success 200) {string} matches.columns Scalar value for a given column by index defined in the alert * @apiSuccess (Success 200) {string} matches.expirationDate Date in ISO-8601 format after which the match is deleted * @apiSuccess (Success 200) {string} matches.createdAt Creation date in ISO-8601 format * @apiSuccess (Success 200) {string} matches.updatedAt Last update date in ISO-8601 format * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * "counts": { * "unconfirmed": 1, * "confirmed": 1, * "dismissed": 0 * }, * "matches": [ * { * "id": 1, * "sourceKey": "584f2569", * "alertId": 2, * "hash": "897f54ff366922a4077c78955c77bcdd", * "status": "confirmed", * "user": { * "id": 1, * "username": "alice", * "email": "alice@example.com" * }, * "viewers": [ * { * "id": 1, * "username": "alice", * "email": "alice@example.com", * "date": "2016-05-16T08:13:35.030Z" * } * ], * "nodes": [5971], * "edges": [], * "columns": [ * 1999 * ], * "expirationDate": "2016-05-26T08:23:35.730Z", * "createdAt": "2016-05-16T08:23:35.730Z", * "updatedAt": "2016-05-16T08:23:35.730Z" * }, * { * "id": 2, * "sourceKey": "584f2569", * "alertId": 2, * "hash": "5f221db1e438f2d9b7cdd284364e379b", * "status": "unconfirmed", * "user": null, * "viewers": [], * "nodes": [5976], * "edges": [], * "columns": [ * 1998 * ], * "expirationDate": "2016-05-26T08:23:35.730Z", * "createdAt": "2016-05-16T08:23:35.730Z", * "updatedAt": "2016-05-16T08:23:35.730Z" * } * ] * } */ /** * @api {get} /api/:dataSource/alerts Get all the alerts (User) * @apiName GetAlertsForUsers * @apiGroup Alerts * @apiVersion 1.0.0 * @apiPermission authenticated * @apiPermission apiright:alert.read * * @apiDescription Get all the alerts of a given data-source ordered by creation date. * The fields are filtered to be viewed by a simple user. * * @apiParam {string} dataSource Key of the data-source * * @apiUse ReturnGetAlertsArrayUser */ app.get('/api/:dataSource/alerts', api.respond(req => { return AlertManager.getAlerts( req.param('dataSource'), false, Access.getUserCheck(req, 'alert.read') ); }, 200)); /** * @api {get} /api/:dataSource/alerts/:alertId Get an alert (User) * @apiName GetAlertForUsers * @apiGroup Alerts * @apiVersion 1.0.0 * @apiPermission authenticated * @apiPermission apiright:alert.read * * @apiDescription Get the alert selected by id. The fields are filtered to be viewed by a simple * user. * * @apiParam {string} dataSource Key of the data-source * @apiParam {number} alertId ID of the alert * * @apiUse ReturnGetAlertUser */ app.get('/api/:dataSource/alerts/:alertId', api.respond(req => { return AlertManager.getAlert( req.param('dataSource'), Utils.tryParsePosInt(req.param('alertId'), 'alertId'), false, Access.getUserCheck(req, 'alert.read') ); }, 200)); /** * @api {get} /api/:dataSource/alerts/:alertId/matches Get all the matches of an alert * @apiName GetMatches * @apiGroup Alerts * @apiVersion 1.0.0 * @apiPermission authenticated * @apiPermission apiright:alert.read * * @apiDescription Get all the matches of an alert. * * @apiParam {string} dataSource Key of the data-source * @apiParam {number} alertId ID the alert * @apiParam {string} [offset=0] Offset from the first result * @apiParam {string} [limit=20] Page size (maximum number of returned matches) * @apiParam {string="asc","desc"} [sort_direction="desc"] Direction used to sort * @apiParam {string="date","0","1","2","3","4"} [sort_by="date"] Sort by date or a given column * @apiParam {string="unconfirmed","confirmed","dismissed"} [status] Filter on match status * * @apiUse ReturnGetMatchesArray */ app.get('/api/:dataSource/alerts/:alertId/matches', api.respond(req => { const alertId = Utils.tryParsePosInt(req.param('alertId'), 'alertId'); const user = Access.getUserCheck(req, 'alert.read'); return Promise.props({ counts: AlertManager.getMatchCount(req.param('dataSource'), alertId, user), matches: AlertManager.getMatches( req.param('dataSource'), alertId, { sortDirection: req.param('sort_direction'), sortBy: req.param('sort_by'), offset: Utils.tryParsePosInt(req.param('offset'), 'offset', true), limit: Utils.tryParsePosInt(req.param('limit'), 'limit', true), status: req.param('status') }, user ) }); }, 200)); /** * @api {get} /api/:dataSource/alerts/:alertId/matches/:matchId Get a match * @apiName GetMatch * @apiGroup Alerts * @apiVersion 1.0.0 * @apiPermission authenticated * @apiPermission apiright:alert.read * * @apiDescription Get the match selected by id. * * @apiParam {string} dataSource Key of the data-source * @apiParam {number} alertId ID of the alert * @apiParam {number} matchId ID of the match * * @apiUse ReturnGetMatch */ app.get('/api/:dataSource/alerts/:alertId/matches/:matchId', api.respond(req => { return AlertManager.getMatch( Utils.tryParsePosInt(req.param('matchId'), 'matchId'), Access.getUserCheck(req, 'alert.read'), req.param('dataSource'), Utils.tryParsePosInt(req.param('alertId'), 'alertId', true) ); }, 200)); /** * @api {post} /api/:dataSource/alerts/:alertId/matches/:matchId/action Do an action on a match * @apiName DoMatchAction * @apiGroup Alerts * @apiVersion 1.0.0 * @apiPermission authenticated * @apiPermission apiright:alert.doAction * * @apiDescription Do an action (open, dismiss, confirm, unconfirm) on a match. * * @apiParam {string} dataSource Key of the data-source * @apiParam {number} alertId ID of the alert * @apiParam {number} matchId ID of the match * @apiParam (body) {string="confirm","dismiss","unconfirm","open"} action The action to perform * * @apiSuccessExample {none} Success-Response: * HTTP/1.1 204 No Content */ app.post('/api/:dataSource/alerts/:alertId/matches/:matchId/action', api.respond(req => { return AlertManager.doMatchAction( req.param('dataSource'), Utils.tryParsePosInt(req.param('alertId'), 'alertId'), Utils.tryParsePosInt(req.param('matchId'), 'matchId'), req.param('action'), Access.getUserCheck(req, 'alert.doAction') ); }, 204)); /** * @api {get} /api/:dataSource/alerts/:alertId/matches/:matchId/actions Get all the actions of a match * * @apiName GetMatchActions * @apiGroup Alerts * @apiVersion 1.0.0 * @apiPermission authenticated * @apiPermission apiright:alert.read * * @apiDescription Get all the actions of a match ordered by creation date. * * @apiParam {string} dataSource Key of the data-source * @apiParam {number} alertId ID of the alert * @apiParam {number} matchId ID of the match * * @apiSuccess (Success 200) {object[]} matchActions Actions * @apiSuccess (Success 200) {number} matchActions.id ID of the action * @apiSuccess (Success 200) {number} matchActions.matchId ID of the match * @apiSuccess (Success 200) {object} matchActions.user User that did the action * @apiSuccess (Success 200) {number} matchActions.user.id ID of the user * @apiSuccess (Success 200) {string} matchActions.user.username Username of the user * @apiSuccess (Success 200) {string} matchActions.user.email E-mail of the user * @apiSuccess (Success 200) {string="open","confirm","dismiss","unconfirm"} matchActions.action The action performed * @apiSuccess (Success 200) {string} matchActions.createdAt Creation date in ISO-8601 format * @apiSuccess (Success 200) {string} matchActions.updatedAt Last update date in ISO-8601 format * * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * [ * { * "id": 9, * "matchId": 3, * "user": { * "id": 1, * "username": "alice", * "email": "alice@example.com" * }, * "action": "dismiss", * "createdAt": "2016-06-16T08:22:35.730Z", * "updatedAt": "2016-06-16T08:22:35.730Z" * }, * { * "id": 8, * "matchId": 4, * "user": { * "id": 2, * "username": "bob", * "email": "bob@example.com" * }, * "action": "open", * "createdAt": "2016-05-16T08:23:35.730Z", * "updatedAt": "2016-05-16T08:23:35.730Z" * } * ] */ app.get('/api/:dataSource/alerts/:alertId/matches/:matchId/actions', api.respond(req => { return AlertManager.getMatchActions( req.param('dataSource'), Utils.tryParsePosInt(req.param('alertId'), 'alertId'), Utils.tryParsePosInt(req.param('matchId'), 'matchId'), { offset: Utils.tryParsePosInt(req.param('offset'), 'offset', true), limit: Utils.tryParsePosInt(req.param('limit'), 'limit', true) }, Access.getUserCheck(req, 'alert.read') ); }, 200)); };
import Ember from 'ember'; export default Ember.Controller.extend({ fonte: null, banca: null, actions: { novaFonte() { let nome = this.get('fonte'); let fonte = this.get('store').createRecord('fonte', { nome }); let banca = this.get('store').createRecord('banca', { nome }); fonte.save() .then(f => { this.set('fonte', f); }); banca.save() .then(f => { this.set('banca', f); }); }, removerEvento(ev) { this.get('store').find('banca', '-KoGACg1R__8dn23jvsU') .then( b => { ev.get('bancas').removeObject(b); return ev.save(); } ) .then(console.log); }, novoEvento() { let store = this.get('store'); let {casa, fora, campeonato, realizacao} = this.getProperties('casa', 'fora', 'campeonato', 'realizacao'); let restricao = this.get('model.restricao'); let banca = this.get('model.banca'); let evento = store.createRecord('evento', { casa, fora, campeonato, inicio: new Date() }); evento.save() .then( ev => { let j = store.createRecord('jogo', { exibir: true }); j.set('evento', ev); j.set('restricao', restricao); banca.get('painel').addObject(j); return banca.save(); }) .catch(console.log) .finally(console.log); } } });
define([ 'stomp/stomp' ], function(stomp) { var module = {}, subs = [], client = null, connected = false, connecting = false, connpending = [], connidentity = 0; function connect(callback, errback) { var client, idx; if( !connected ) { connpending.push({ cb:callback, eb:errback }); if( !connecting ) { connecting = true; client = Stomp.client('ws://'+window.location.host+'/cxm/stomp'); client.connect('test', 'user', function () { connected = true; connecting = false; for(idx=0; idx<connpending.length; idx++) { if( typeof connpending[idx].cb === 'function' ) { connpending[idx].cb(client); } } connpending = []; }, function (error) { connecting = false; for(idx=0; idx<connpending.length; idx++) { if ( typeof connpending[idx].eb === 'function' ) { connpending[idx].eb(error); } } connpending = []; }); } } else { setTimeout(function () { if( typeof callback === 'function' ) { callback(client); } }, 0); } }; function read(uri, callback) { connect( function (client) { var connid = connidentity++; client.subscribe('/user/topic/data/CH'+connid, function (msg) { if( typeof callback === 'function' ) { if( msg.body ) { callback(JSON.parse(msg.body)); } } }); client.send('/app/read/CH'+connid, {}, JSON.stringify({ uri: uri })); }, function (error) { console.debug(error); } ); }; module.read = read; return module; });
$(document).ready(function(){ new WOW().init(); $('#main-nav').onePageNav({ currentClass: 'current', changeHash: true, scrollSpeed: 1200 }); $('#write_us').onePageNav({ currentClass: 'current', changeHash: true, scrollSpeed: 1200 }); $("#testimonial-slider").owlCarousel({ items:1, itemsDesktop:[1000,1], itemsDesktopSmall:[979,1], itemsTablet:[768,1], pagination:true, navigation:false, navigationText:["",""], slideSpeed:1000, singleItem:true, autoPlay:true }); $("#contact_form_submit_button").children('img').hide(); //to hide loding animation //animated header class $(window).scroll(function() { var scroll = $(window).scrollTop(); //console.log(scroll); if (scroll > 200) { //console.log('a'); $(".navigation").addClass("animated"); } else { //console.log('a'); $(".navigation").removeClass("animated"); }}); $("#contact-form").validate({ rules: { name: { required: true, minlength: 2 }, mobile: { required: true, }, message: { required: true, minlength: 2 }, email: { required: true, email: true } }, messages: { name: { required: "Please enter Your Name", minlength: "Your name must consist of at least 2 characters" }, message: { required: "Please Write Something", minlength: "Your message must consist of at least 2 characters" }, email: "Please enter a valid email address" }, submitHandler: function(form) { $("#contact_form_submit_button").children('img').show(); //to show loding animation $("#contact_form_submit_button").children('p').hide(); //to hide send option $("#contact_form_submit_button").prop('disabled', true); //to disable send option $.ajax({ url : "sendmail/", // the endpoint type : "POST", // http method data : { name : $('#name').val(), email: $('#email').val(), mobile:$('#mobile').val(), message: $('#message').val(), }, // data sent with the post request // handle a successful response success : function(json) { $('#name').val(''); // remove the value from the input $('#mobile').val(''); // remove the value from the input $('#email').val(''); // remove the value from the input $('#message').val(''); // remove the value from the input $("#contact_form_submit_button").children('img').hide(); //to hide loding animation $('#result').show().html(json['result']) $("#contact_form_submit_button").prop('disabled', false); //to enable send option $("#contact_form_submit_button").children('p').show(); //to show send option }, // handle a non-successful response error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom } }); } }); $('#result').hide() }); /*for typewriter effect*/ var app = document.getElementById('app'); var typewriter = new Typewriter(app, { loop: true }); typewriter.typeString('We don\'t just build Websites' ) .pauseFor(500) .deleteChars(8) .typeString('Apps ') .pauseFor(500) .deleteChars(5) .typeString('Softwares ') .pauseFor(500) .deleteAll() .typeString('We build your Business !') .pauseFor(2500) .deleteChars(10) .typeString('Dreams !') .pauseFor(2500) .deleteAll() .start(); function alpha(e) { var k; document.all ? k = e.keyCode : k = e.which; return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57)); }
import React from 'react'; import './index.css'; import Dragbox from './dragbox'; import Boundary from '../../../components/boundary'; import { Tooltip, Button, Form, Input, Divider, Typography, Select, Collapse, message, Modal } from 'antd'; import { DeleteOutlined, ArrowUpOutlined, ArrowDownOutlined, ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons'; import Edtbox from './edtbox'; import Showbox from './showbox'; import DebounceSelect from './debounceSelect'; import { BASEWIDTH } from "../../../config"; import base from '../../../http/base'; import api from '../../../http/api'; const { Title } = Typography; const { Option } = Select; const { Panel } = Collapse; const { TextArea } = Input; export default class Newpage extends React.Component { constructor(props){ super(props); this.showArea = React.createRef(); this.resizeFangdou = true; this.savetempinterval = null; this.user = JSON.parse(localStorage.getItem('user')); this.fromRef = React.createRef(); this.isEditTemp = false; this.state = { components: [], component: {}, edtArray:[], data:[], pageConfig:{lookuser: 'all',category:'文章'}, current:0, saveLoading:false, publishLoading:false, rate:null, selectedKey:'scale', urlStatus:'', pageid:null, isEdit:false, //用于标记页面有没有被编辑(修改基本配置,添加、删除组件,修改组件的数据) visible:false, selectedKeys:[], editAreaStyle:{}, deleteGroupSelected:'', serchSelectedValue: [], serchModleVisible:false, newGroupName:'', groupItems:[], groupSelected:'', } }; componentDidMount(){ //获取界面的样式 this.setState({ editAreaStyle:JSON.parse(localStorage.getItem('editAreaStyle')) || {} }); //获取选择的展示样式 this.addResizeEvent(); let selectedKey = localStorage.getItem('selectedKey')||'scale'; if (selectedKey){ this.changeRate(selectedKey); } //获取某个用户需要显示的组件 this.getMicroapp(); //判断页面是否有传id过来,若有传则表示是重新编辑页面,若没有传则表示是新页面 const id = this.props.match.params.id; //获取本地缓存和网络缓存,查看该用户是否有没保存的数据,若有则提示是否恢复 this.haveDontSaveData(()=>{ if (id){ this.getPageDataById(id); } }); //设置一个定时器,每个一段时间检查一下是否有数据没有保存,若有则自动保存到临时表和本地 this.savetempinterval = setInterval(this.saveTemp, 10000); }; componentWillUnmount(){ //该页面卸载的时候,需要去检查是否有数据没有保存,若有则做数据备份(本地和数据库双重备份) this.saveTemp(); clearInterval(this.savetempinterval); }; //获取该用户需要显示到左边的组件 getMicroapp(){ this.user && api.showcomponent({ count: this.user.count }) .then(res=>res.json()) .then(data=>{ if (data.status === 1){ this.setState({ components: data.data }); } }) .catch(error=>{}); } //获取本地缓存和网络缓存,查看该用户是否有没保存的数据,若有则提示是否恢复 haveDontSaveData = (callback)=>{ let dontSaveData = JSON.parse(localStorage.getItem('dontSaveData')) || []; let index = dontSaveData.findIndex(v=>v.usercount===this.user.count); api.queryhavetemp(this.user.count) .then(res=>res.json()) .then(data=>{ if (data.status === 1){ if (!data.data && index === -1){ throw new Error('没有未保存的数据'); } this.setState({ visible:true }); } else { throw new Error('没有未保存的数据'); } }) .catch(error=>{ callback(); }); }; //当页面传入一个id时,去获取该id对应的页面的数据 getPageDataById = (id)=>{ api.querypage(id) .then(res=>res.json()) .then(async data=>{ if (data.status === 1){ data = data.data; let cpdata = []; let edtArray = []; for (let i = 0; i < data.componentData.length; i++){ const value = data.componentData[i]; cpdata.push({cpname:value.cpname, cpdata:JSON.parse(value.cpdata.replace(/\n/g,"\\n").replace(/\r/g,"\\r"))}); let micorRes = await api.showcomponent({micorkey: value.cpname}); micorRes = await micorRes.json(); let key = this.randomKey(); edtArray.push({key, component:micorRes.data[0]}); } this.setState({ data:cpdata, edtArray, current:-1, urlStatus:'success', pageid:id, pageConfig:{url:data.url, lookuser: data.lookuser, category:data.category, title:data.title, discription:data.discription} }); this.fromRef.current.resetFields(); } }) .catch(error=>{}); }; //检查是否有数据没有保存,若有,则做数据备份(本地和数据库双重备份) saveTemp = ()=>{ if (this.state.isEdit && this.isEditTemp){ this.isEditTemp = false; let data = { usercount:this.user.count, componentData:JSON.stringify(this.state.data), pageConfig:this.state.pageConfig, time:(new Date()).format('yyyy-MM-dd hh:mm:ss'), }; if (this.state.pageid){ data.pageConfig.pageid = this.state.pageid; } data.pageConfig = JSON.stringify(data.pageConfig); //将数据做本地存储 let dontSaveData = JSON.parse(localStorage.getItem('dontSaveData')) || []; let index = dontSaveData.findIndex(v=>v.usercount===this.user.count); if (index !== -1){ dontSaveData[index] = data; } else dontSaveData.push(data); localStorage.setItem('dontSaveData', JSON.stringify(dontSaveData)); //将数据提交到数据库中存储,不验证是否提交成功 data.componentData = data.componentData.replace(/\"/g,"\\\"").replace(/'/g,"\\'"); data.pageConfig = data.pageConfig.replace(/\"/g,"\\\"").replace(/'/g,"\\'"); api.savetemp(JSON.stringify(data)); } }; //当手动保存数据,或提交数据之后,将自动清空本地的临时保存的数据和数据库中临时保存的数据 deleteTemp = ()=>{ let dontSaveData = JSON.parse(localStorage.getItem('dontSaveData')) || []; let index = dontSaveData.findIndex(v=>v.usercount===this.user.count); if (index !== -1){ dontSaveData = [...dontSaveData.slice(0,index), ...dontSaveData.slice(index+1)]; localStorage.setItem('dontSaveData', JSON.stringify(dontSaveData)); } api.deletetemp(this.user.count); }; //给展示框添加监听大小改变的时间 addResizeEvent = ()=>{ let showArea = this.showArea.current; let iframe = showArea.parentNode.getElementsByTagName('iframe')[0]; // this.showResize(iframe.offsetWidth); (iframe.contentWindow || iframe).onresize = (e) => { if (this.state.selectedKey==='scale' && this.resizeFangdou){ this.showResize(e.target.innerWidth); this.resizeFangdou = false; setTimeout(()=>{ this.resizeFangdou = true; },50); } } }; //展示框大小改变时 showResize = (width)=>{ let rate = width/BASEWIDTH; rate = Math.floor(rate*100)/100; this.setState({ rate }); }; //改变缩放比例 changeRate = (e)=>{ localStorage.setItem('selectedKey',e); if (e === 'scale') { let showArea = this.showArea.current; let iframe = showArea.parentNode.getElementsByTagName('iframe')[0]; this.showResize(iframe.offsetWidth); this.setState({ selectedKey:e }); return; } let rate = null; if (e === 'seven') rate = 0.75; else if (e === 'five') rate = 0.5; this.setState({ rate, selectedKey:e }); }; drag = (component)=>{ //优化,减少render的调用 if (this.state.component === component){ return; } this.setState({ component }); }; overDrop = (ev) => { ev.preventDefault(); }; //当释放鼠标时执行的函数 drop = (ev) => { ev.preventDefault(); this.isEditTemp = true; //随机生成循环的key,保证不能与其他的key相同 let key = this.randomKey(); //将新节点添加到节点数组中 this.setState({ data:[...this.state.data, {cpname:this.state.component.micorkey}], edtArray:[...this.state.edtArray, {key, component:this.state.component}], current:this.state.data.length, isEdit:true, selectedKeys:[...this.state.selectedKeys, key] }); }; //循环随机生成key randomKey(){ let flag = true; let key; while(flag) { flag = false; key = Math.random(); for (let i = 0; i < this.state.edtArray.length; i++){ if (key === this.state.edtArray[i].key){ flag = true; break; } } } return key; } //用于删除某个组件 deleteClick = (e, index)=>{ e.stopPropagation(); this.isEditTemp = true; this.setState({ data:[...this.state.data.slice(0,index), ...this.state.data.slice(index+1)], edtArray:[...this.state.edtArray.slice(0,index), ...this.state.edtArray.slice(index+1)], current:this.state.current > index ? this.state.current-1 : this.state.current, isEdit:true }); }; //用于上移某个组件 arrowUpClick = (e, index)=>{ e.stopPropagation(); if (index === 0) return; this.isEditTemp = true; this.setState({ data:[...this.state.data.slice(0,index-1),this.state.data[index],this.state.data[index-1], ...this.state.data.slice(index+1)], edtArray:[...this.state.edtArray.slice(0,index-1),this.state.edtArray[index],this.state.edtArray[index-1], ...this.state.edtArray.slice(index+1)], current:index-1, isEdit:true }); }; //用于下移某个组件 arrowDownClick = (e, index)=>{ e.stopPropagation(); if (index === this.state.edtArray.length-1) return; this.isEditTemp = true; this.setState({ data:[...this.state.data.slice(0,index),this.state.data[index+1],this.state.data[index], ...this.state.data.slice(index+2)], edtArray:[...this.state.edtArray.slice(0,index),this.state.edtArray[index+1],this.state.edtArray[index], ...this.state.edtArray.slice(index+2)], current:index+1, isEdit:true }); }; //用于子节点修改对应的data updateData = (index, data)=>{ this.isEditTemp = true; this.setState({ data:[...this.state.data.slice(0,index), data, ...this.state.data.slice(index+1)], isEdit:true }); }; //点击某个折叠板 panelChange = (e)=>{ this.setState({ selectedKeys:e }); }; //选择某个区域 selectAera = (e, index)=>{ e.stopPropagation(); this.setState({ current:index }); }; //用于取消选择某个区域 cancelSelectAera = (e)=>{ e.stopPropagation(); this.setState({ current:-1 }); }; //用于删除样式组 deletegroup = (e, key)=>{ e.stopPropagation(); const selectKeys = ['直接删除', ...this.getOtherGroupName(key)]; this.setState({ deleteGroupSelected: '直接删除' }); Modal.confirm({ title: `确定删除 ${key} 分组`, icon: <ExclamationCircleOutlined />, content: ( <div style={{display:'flex', alignItems:'center'}}> <p style={{margin:0}}>内部组件的变动方式:</p> <Select defaultValue='直接删除' onChange={this.deleteGroupChange} > { selectKeys.map((value, index)=>{ return ( index === 0 ? <Option key={index} value={value}> {value} </Option> : <Option key={index} value={`移动至 ${value}`}> {`移动至 ${value}`} </Option> ) }) } </Select> </div> ), okText:'确定', cancelText:'取消', onOk: () => { const data = { usercount: this.user.count, groupname: key, action: this.state.deleteGroupSelected }; return api.deletemicorgroup(JSON.stringify(data)) .then(res=>res.json()) .then(data=>{ if (data.status === 1){ message.success('操作成功!'); this.getMicroapp(); } else { message.warning('操作失败!'); } }) .catch(error=>{ message.warning('操作失败!'); }); }, }) }; deleteGroupChange = (value)=>{ this.setState({ deleteGroupSelected:value }); }; //用于删除单个样式 editSigleMicor = (component, groupname) => { const selectKeys = ['直接删除', ...this.getOtherGroupName(groupname)]; this.setState({ deleteGroupSelected: '直接删除' }); Modal.confirm({ title: `确定删除 ${component.micorname} 样式`, icon: <ExclamationCircleOutlined />, content: ( <div style={{display:'flex', alignItems:'center'}}> <p style={{margin:0}}>删除方式:</p> <Select defaultValue='直接删除' onChange={this.deleteGroupChange} > { selectKeys.map((value, index)=>{ return ( index === 0 ? <Option key={index} value={value}> {value} </Option> : <Option key={index} value={`移动至 ${value}`}> {`移动至 ${value}`} </Option> ) }) } </Select> </div> ), okText:'确定', cancelText:'取消', onOk: () => { const data = { usercount: this.user.count, groupname: groupname, action: this.state.deleteGroupSelected, micorid: component.id }; return api.deletesiglemicor(JSON.stringify(data)) .then(res=>res.json()) .then(data=>{ if (data.status === 1){ message.success('操作成功!'); this.getMicroapp(); } else { message.warning('操作失败!'); } }) .catch(error=>{ message.warning('操作失败!'); }); }, }) }; //用于搜索样式 serchStyle = (e)=>{ e.stopPropagation(); this.setState({ serchModleVisible:true, groupItems:this.getOtherGroupName('') }); }; fetchUserList = async (serchText) => { if (!serchText) return; return api.serchmicor(serchText, this.user.count) .then(res=>res.json()) .then(data=>{ if (data.status === 1){ //查找已经存在的id(用于过滤) const ids = []; for (let key in this.state.components){ if (key === '基础样式') continue; this.state.components[key].forEach(value=>{ ids.push(value.id) }) } return data.data.map(value=>({ label: value.micorname, value: value.id })).filter(item=>{ return !ids.includes(item.value) }); } else return []; }) .catch(error=>{}) }; onNameChange = event => { this.setState({ newGroupName: event.target.value, }); }; addItem = () => { if (!this.state.newGroupName) return; this.setState({ groupItems: [...this.state.groupItems, this.state.newGroupName], newGroupName: '', }); }; groupSelectChange = (e)=>{ this.setState({ groupSelected:e }); }; serchHandleOk = ()=>{ const data = { usercount:this.user.count, groupname:this.state.groupSelected, micorid:this.state.serchSelectedValue.map(item=>item.value) }; return api.addmicorgroup(JSON.stringify(data)) .then(res=>res.json()) .then(data=>{ if (data.status === 1){ message.success('添加成功!'); this.getMicroapp(); //重新拉取组件数据 this.setState({ serchModleVisible:false, groupSelected:'', serchSelectedValue:[] }) } else { message.warning('添加失败!') } }) .catch(error=>{ message.warning('添加失败!') }); }; serchHandleCancel = ()=>{ this.setState({ serchModleVisible:false }) }; //获取该用户除 指定分组样式和基础样式 外的其他分组名称 getOtherGroupName = (name)=>{ return Object.keys(this.state.components).filter((value)=>{ return value !== '基础样式' && value !== name }) }; //按钮的事件 saveClick = ()=>{ let data = this.saveAndPublish(); if (data === -1) return; api.savepage(JSON.stringify(data)) .then(res=>res.json()) .then(data=>{ if (data.status === 1){ this.setState({ pageid:data.data.id, isEdit:false }); this.deleteTemp(); message.destroy(); message.success('保存成功!'); } else { message.destroy(); message.warning('保存失败!'); } }) .catch(error=>{ message.destroy(); message.warning('保存失败!'); }); }; publishClick = ()=>{ let data = this.saveAndPublish(); if (data === -1) return; api.publish(JSON.stringify(data)) .then(res=>res.json()) .then(data=>{ if (data.status === 1){ this.isEditTemp = false; this.deleteTemp(); this.props.history.push('/mine/publish'); message.destroy(); message.success('发表成功!'); } else { message.destroy(); message.warning('发表失败!'); } }) .catch(error=>{ message.destroy(); message.warning('发表失败!'); }); }; saveAndPublish = ()=>{ if (!this.state.pageConfig.url){ message.destroy(); message.warning('请输入访问地址!'); return -1; } if (this.state.urlStatus !== 'success'){ message.destroy(); message.warning('输入的访问地址不可用!'); return -1; } let componentData = []; let temp = null; this.state.data.forEach(value => { temp = {...value}; temp.cpdata = JSON.stringify(temp.cpdata).replace(/\"/g,"\\\"").replace(/'/g,"\\'"); componentData.push(temp); }); return this.state.pageid===null?{ componentData, usercount:this.user.count, time:(new Date()).format('yyyy-MM-dd hh:mm:ss'), ...this.state.pageConfig } : { componentData, time:(new Date()).format('yyyy-MM-dd hh:mm:ss'), id:this.state.pageid, ...this.state.pageConfig }; }; //头部的事件 pageConfigChange = (value, values)=>{ this.isEditTemp = true; this.setState({ pageConfig:{...values}, isEdit:true }); }; //检查输入的地址是否可以用 availableUrl = (e)=>{ api.availableurl(this.user.count, e.target.value) .then(res=>res.json()) .then(data=>{ if (data.status === 1){ this.setState({ urlStatus:'success' }); } else { message.destroy(); message.warning('该地址不可用!'); this.setState({ urlStatus:'error' }); } }) .catch(error=>{ message.destroy(); message.warning('该地址不可用!'); this.setState({ urlStatus:'error' }); }); }; //界面变化 boundaryChange = (boundaryStyle, childWidth)=>{ let editAreaStyle = {boundaryStyle,childWidth}; localStorage.setItem('editAreaStyle', JSON.stringify(editAreaStyle)); }; //弹出的modle的事件 handleOk = ()=>{ let dontSaveData = JSON.parse(localStorage.getItem('dontSaveData')) || []; let index = dontSaveData.findIndex(v=>v.usercount===this.user.count); api.querytemp(this.user.count) .then(res=>res.json()) .then(async data=>{ if (data.status === 1){ data = data.data;//初始化为服务器的数据 if (data && index !== -1){ //若本地和服务器都有数据,则取时间靠后的为准 if (new Date(dontSaveData[index].time)>new Date(data.time)) data = dontSaveData[index]; } else if (index !== -1){ //若只有本地有数据,则取本地的数据 data = dontSaveData[index]; } //现在计算后的data就是需要恢复的数据 data.componentData = JSON.parse(data.componentData.replace(/\n/g,"\\n").replace(/\r/g,"\\r")); data.pageConfig = JSON.parse(data.pageConfig.replace(/\n/g,"\\n").replace(/\r/g,"\\r")); let cpdata = []; let edtArray = []; for (let i = 0; i < data.componentData.length; i++){ const value = data.componentData[i]; cpdata.push({cpname:value.cpname, cpdata:value.cpdata}); let micorRes = await api.showcomponent({micorkey: value.cpname}); micorRes = await micorRes.json(); let key = this.randomKey(); edtArray.push({key, component:micorRes.data[0]}); } //如果没有id,但是有url则需要去数据库验证该url是否可用 if (!data.pageConfig.pageid && data.pageConfig.url){ this.availableUrl({target:{value:data.pageConfig.url}}); } this.setState({ data:cpdata, edtArray, current:-1, isEdit:true, urlStatus:data.pageConfig.pageid?'success':'', pageid:data.pageConfig.pageid||null, pageConfig:{url:data.pageConfig.url, lookuser: data.pageConfig.lookuser, category:data.pageConfig.category, title:data.pageConfig.title, discription:data.pageConfig.discription} }); this.fromRef.current.resetFields(); } }) .catch(error=>{}); this.setState({ visible:false }); }; handleCancel = ()=>{ const id = this.props.match.params.id; if (id){ this.getPageDataById(id); } this.deleteTemp(); this.setState({ visible:false }); }; render(){ const style = this.state.rate? {width:1/this.state.rate*100+'%', height:'', transform: 'scale('+this.state.rate+')'} : {width:'100%', height:'', transform: 'scale(1)'}; return( <div> <Boundary change={this.boundaryChange} boundaryStyle={this.state.editAreaStyle.boundaryStyle} > <Boundary.Item span={this.state.editAreaStyle.childWidth?this.state.editAreaStyle.childWidth[0]:20}> <div className='dragBox'> <h3 className='tipTitle'>选择样式</h3> <Collapse ghost defaultActiveKey={[0]} > { Object.keys(this.state.components).map((key, idx)=>{ return ( <Panel header={key} key={idx} extra={ key !== '基础样式' && <Tooltip placement="top" title='删除该分组'> <DeleteOutlined className='edt-close' onClick={(e)=>{this.deletegroup(e, key)}}/> </Tooltip>} > { this.state.components[key].map((value, index) => { return ( <Dragbox drag={this.drag} component={value} groupname={key} showEdit={this.editSigleMicor} key={index} > {value.micorname} </Dragbox> ); }) } </Panel> ) }) } </Collapse> <Button type='primary' className='serch-btn' onClick={this.serchStyle} >搜索样式</Button> </div> </Boundary.Item> <Boundary.Item span={this.state.editAreaStyle.childWidth&&this.state.editAreaStyle.childWidth[1]}> <div className='centerBox' onClick={this.cancelSelectAera}> <h3 className='tipTitle'>编辑区域</h3> {/*上方的基本配置*/} <Collapse defaultActiveKey={['1']} ghost style={{borderBottom:'1px solid #ddd'}}> <Panel header="文章的基本配置" key="1"> <Form layout="vertical" initialValues={this.state.pageConfig} onValuesChange={this.pageConfigChange} ref={this.fromRef} > <Form.Item label="访问地址:" name="url" rules={[ { required: true, message: '请输入文章地址!' }, { pattern: /^[a-zA-Z0-9]{4,23}$/, message: '只能输入字母和数字(4~23)位!' } ]} hasFeedback validateStatus={this.state.urlStatus} > <Input addonBefore={base.baseUrl+"/showpage/"+this.user.count+'/'} placeholder='文章地址' onBlur={this.availableUrl} disabled = {this.state.pageid===null?false:true} /> </Form.Item> <Form.Item label="谁可见:" name="lookuser" > <Select> <Option value="all">所有人</Option> <Option value="online">登录可见</Option> <Option value="onlyme">仅自己</Option> </Select> </Form.Item> <Form.Item label="分类:" name="category" > <Select> <Option value="文章">文章</Option> <Option value="计算机">计算机</Option> <Option value="笔记">笔记</Option> <Option value="数学">数学</Option> <Option value="分享">分享</Option> </Select> </Form.Item> <Form.Item label="标题:" name="title" > <Input placeholder='文章标题'/> </Form.Item> <Form.Item label="描述:" name="discription" > <TextArea rows={4} placeholder='文章的描述'/> </Form.Item> </Form> </Panel> </Collapse> {/*中间工作区域*/} <div onDrop={(e)=>{this.drop(e)}} onDragOver={(e)=>{this.overDrop(e)}} className='dropBox' > <Collapse activeKey={this.state.selectedKeys} onChange={(e)=>{this.panelChange(e)}} ghost > { this.state.edtArray.map((value, index)=>{ const component = value.component; return ( <Panel header={component.micorname} key={value.key} extra={<div className='edt-extra'> <Tooltip placement="top" title='上移该部分'> <ArrowUpOutlined className={index===0&&'disabled'} onClick={(e)=>{this.arrowUpClick(e, index)}}/> </Tooltip> <Tooltip placement="top" title='下移该部分'> <ArrowDownOutlined className={index===this.state.edtArray.length-1&&'disabled'} onClick={(e)=>{this.arrowDownClick(e, index)}}/> </Tooltip> <Tooltip placement="top" title='删除该部分'> <DeleteOutlined className='edt-close' onClick={(e)=>{this.deleteClick(e, index)}}/> </Tooltip> </div>} className={this.state.current===index?'active':''} > <Edtbox index={index} data={this.state.data[index]} updateData={this.updateData} micorkey={component.micorkey} /> </Panel> ) }) } </Collapse> </div> {/*下方按钮组*/} <div className='drop-btn-box'> <Button type="primary" loading={this.state.saveLoading} onClick={this.saveClick} style={{marginRight:'10px'}} disabled={!this.state.isEdit} > 存稿 </Button> <Button type="primary" loading={this.state.publishLoading} onClick={this.publishClick} > 发表 </Button> </div> </div> </Boundary.Item> <Boundary.Item span={this.state.editAreaStyle.childWidth&&this.state.editAreaStyle.childWidth[2]}> <div className='showBox' onClick={this.cancelSelectAera}> <iframe></iframe> <div className='tipTitle'> <h3>结果预览</h3> <Select value={this.state.selectedKey} style={{ width: 90, fontSize:10, marginLeft:20 }} onChange={this.changeRate} bordered={false} > { this.state.selectedKey==='scale'? <Option value="scale">{this.state.rate}</Option> : <Option value="scale">比例缩放</Option> } <Option value="five">50%</Option> <Option value="seven">75%</Option> <Option value="noscale">不缩放</Option> </Select> </div> <div className='show-area' ref={this.showArea} style={style} > <Title level={2} className='page-title'> {this.state.pageConfig.title} </Title> { this.state.edtArray.map((value,index)=>{ return ( <div key={value.key} className={this.state.current===index?'show-outer active':'show-outer'} onClick={(e)=>{this.selectAera(e,index)}} > <Showbox data={this.state.data[index]} micorkey={value.component.micorkey} /> </div> ) }) } </div> </div> </Boundary.Item> </Boundary> <Modal title="提示信息" visible={this.state.visible} onOk={this.handleOk} onCancel={this.handleCancel} cancelText='取消' okText='恢复' maskClosable={false} > <p>您有上次离开页面有没保存的数据,是否恢复?</p> </Modal> <Modal title="添加更多样式" visible={this.state.serchModleVisible} onOk={this.serchHandleOk} onCancel={this.serchHandleCancel} cancelText='取消' okText='确定' maskClosable={false} > <div className='serch-more-style'> <span>搜索样式:</span> <DebounceSelect mode="multiple" value={this.state.serchSelectedValue} placeholder="Select users" fetchOptions={this.fetchUserList} onChange={(newValue) => { this.setState({ serchSelectedValue: newValue }) }} > </DebounceSelect> </div> <div className='serch-more-style'> <span>添加至分组:</span> <Select value={this.state.groupSelected} placeholder="将新增样式添加至某个分组" dropdownRender={menu => ( <div> {menu} <Divider style={{ margin: '4px 0' }} /> <div style={{ display: 'flex', flexWrap: 'nowrap', padding: 8 }}> <Input style={{ flex: 'auto' }} value={this.state.newGroupName} onChange={this.onNameChange} /> <a style={{ flex: 'none', padding: '8px', display: 'block', cursor: 'pointer' }} onClick={this.addItem} > <PlusOutlined /> 新分组 </a> </div> </div> )} onChange={this.groupSelectChange} > {this.state.groupItems.map(item => ( <Option key={item}>{item}</Option> ))} </Select> </div> </Modal> </div> ); } }
module.exports = { presets: [ '@vue/cli-plugin-babel/preset' ], plugins: [ ["module-resolver", { "alias": { "@components": "./src/components", "@images": "./src/assets/images" } }] ] }
var mongoose = require('./db.js'), Schema = mongoose.Schema; var DetailSchema = new Schema({ title:String, type:Number, name :String, tip:String, infor:[], other:[], detail:{ thumbnails:[], metas:[{ label:String, content:String }] }, tele:String, createTime:{ type:Date, default:Date.now }, updateTime:{ type:Date, default:Date.now } },{ versionKey:false }); module.exports = mongoose.model('details',DetailSchema);
const meowFunction = function() { let hey = 8; let meow = ["peaas", "cars"]; } console.log("yes"); var someArray = [1, 4, 6, 2, 17]; someArray.forEach(/* pass in function here*/); document.querySelector();
function funcInit() { $('header .function .button').on(EVT_MOUSECLICK, function (e) { var action = $(this).attr('data-action'); switch (action) { case BTN_FUNC_NEW: docNew(); break; case BTN_FUNC_OPEN: docOpen(); break; case BTN_FUNC_SAVE: docSave(); break; case BTN_FUNC_SAVEAS: docSaveAs(); break; case BTN_FUNC_PREVIEW: docPreview(); break; case BTN_FUNC_DELETE: docClose(); break; case BTN_FUNC_PUBLISH: docPublish(); break; default: break; } }); }
exports.increment = (a,b) => { return a + b; } exports.decrement = (a,b) => { return a - b; } exports.multiply = (a,b) =>{ return a * b; } // module.exports = { // increment, // decrement, // multiply // };
let modelElement = document.querySelector('.model'); let registerFormElement = modelElement.querySelector(".auth-form__register"); let loginFormElement = modelElement.querySelector(".auth-form__login"); let navMTicon = document.querySelector('.header__mobile-navbar') let navMT = document.querySelector('.header__mobile-tablet-navbar') let navOverlay = document.querySelector('.header__tablet-navbar-overlay') let closeNav = document.querySelector('.mobile-tablet-navbar__close') function changeForm(showForm, hideForm) { modelElement.style.display = `flex` showForm.style.display = `block` hideForm.style.display = `none` } function clickRegister() { changeForm(registerFormElement, loginFormElement) } function clickLogin() { changeForm(loginFormElement, registerFormElement) } function closeAuthform() { modelElement.style.display = `none` } document.querySelector(".model__overlay").onclick = () => { modelElement.style.display = `none` } function changeNav(showNav, event) { if (event == true) { navOverlay.style.display = `block` showNav.style.display = `block` } else { navOverlay.style.display = `none` showNav.style.display = `none` } } navMTicon.onclick = (e) => { changeNav(navMT, true) } closeNav.onclick = function() { changeNav(navMT, false) } navOverlay.onclick = () => { changeNav(navMT, false) }
const cardImage = { 'Luke Skywalker': require('../Utils/assets/cards/luke-skywalker.jpg'), 'C-3PO': require('../Utils/assets/cards/c-3po.jpg'), 'R2-D2': require('../Utils/assets/cards/r2-d2.jpg'), 'Darth Vader': require('../Utils/assets/cards/darthvader.jpg'), 'Leia Organa': require('../Utils/assets/cards/Leia.jpg'), 'Owen Lars': require('../Utils/assets/cards/uncle.jpg'), 'Beru Whitesun lars': require('../Utils/assets/cards/beru.jpg'), 'R5-D4': require('../Utils/assets/cards/r5-d4.jpg'), 'Biggs Darklighter': require('../Utils/assets/cards/biggs.jpg'), 'Obi-Wan Kenobi': require('../Utils/assets/cards/obi-wan.jpg'), 'Alderaan': require('../Utils/assets/cards/alderaan.jpg'), 'Yavin IV': require('../Utils/assets/cards/yavin.jpg'), 'Hoth': require('../Utils/assets/cards/hoth.jpg'), 'Dagobah': require('../Utils/assets/cards/dagobah.jpg'), 'Bespin': require('../Utils/assets/cards/bespin.jpg'), 'Endor': require('../Utils/assets/cards/endor.jpg'), 'Naboo': require('../Utils/assets/cards/noboo.jpg'), 'Coruscant': require('../Utils/assets/cards/cruscant.jpg'), 'Kamino': require('../Utils/assets/cards/kamino.jpg'), 'Geonosis': require('../Utils/assets/cards/geonosis.jpg'), 'Sand Crawler': require('../Utils/assets/cards/sand.jpg'), 'T-16 skyhopper': require('../Utils/assets/cards/skyhopper.jpg'), 'X-34 landspeeder': require('../Utils/assets/cards/landspeeder.jpg'), 'TIE/LN starfighter': require('../Utils/assets/cards/tie.jpg'), 'Snowspeeder': require('../Utils/assets/cards/snowspeed.jpg'), 'TIE bomber': require('../Utils/assets/cards/bomber.jpg'), 'AT-AT': require('../Utils/assets/cards/at-at.jpg'), 'AT-ST': require('../Utils/assets/cards/at-st.jpg'), 'Storm IV Twin-Pod cloud car': require('../Utils/assets/cards/pod.jpg'), 'Sail barge': require('../Utils/assets/cards/sail.jpg'), true: require('../Utils/assets/cards/star-true.svg'), false: require('../Utils/assets/cards/star-false.svg') } export default cardImage;
import PropTypes from "prop-types"; import React from "react"; import estGestionnaire from "utils/roles"; export default function Histoire(props) { const { DateD, Statut, onOpenModalSupprimerSuivie, SupprimerCondition, IdInfosuivi, roles, } = props; const isGestionnaire = estGestionnaire(roles); const te = { DateD }; const t = new Date(te.DateD); const jour = t.toLocaleDateString(); const heure = t.toLocaleTimeString(); return ( <tr id={IdInfosuivi}> <td>{jour}</td> <td>{heure}</td> <td>{Statut}</td> {isGestionnaire && ( <td> {!({ Statut }.Statut in SupprimerCondition) && ( <button type="button" className="btn btn-secondary btn-sm glyphicon glyphicon-trash center-block" title="Supprimer" onClick={() => onOpenModalSupprimerSuivie({ IdInfosuivi })} /> )} </td> )} </tr> ); } Histoire.propTypes = { DateD: PropTypes.number.isRequired, Statut: PropTypes.string.isRequired, onOpenModalSupprimerSuivie: PropTypes.func.isRequired, SupprimerCondition: PropTypes.func.isRequired, IdInfosuivi: PropTypes.number.isRequired, roles: PropTypes.arrayOf(PropTypes.string).isRequired, };
/* * email:746979855@qq.com * Version:0.1 * auth:Mr.xu * Data:2014年2月29日 10:51:33 */ var mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent); var touchstart = mobile ? "touchstart" : "mousedown"; var touchend = mobile ? "touchend" : "mouseup"; var touchmove = mobile ? "touchmove" : "mousemove"; var Valglobal = { href : '项目图片地址', imgs:['项目图片资源'], random : function (Max,Min){ var Range = Max - Min; var Rand = Math.random(); return(Min + Math.round(Rand * Range)); } } var agents = navigator.userAgent.toLowerCase(); //检测是否是ios var iLastTouch = null; //缓存上一次tap的时间 if(agents.indexOf('iphone') >= 0 || agents.indexOf('ipad') >= 0) { document.body.addEventListener('touchend', function(event) { var iNow = new Date() .getTime(); iLastTouch = iLastTouch || iNow + 1 /** 第一次时将iLastTouch设为当前时间+1 */ ; var delta = iNow - iLastTouch; if(delta < 500 && delta > 0) { event.preventDefault(); return false; } iLastTouch = iNow; }, false); } function loading() { var loctionhref = Valglobal.href; function Load() {} Load.prototype.loadImgs = function(urls, callback) { this.urls = urls; this.imgNumbers = urls.length; this.loadImgNumbers = 0; var that = this; for(var i = 0; i < urls.length; i++) { var obj = new Image(); obj.src = loctionhref+urls[i]; obj.onload = function() { that.loadImgNumbers++; callback(parseInt((that.loadImgNumbers / that.imgNumbers) * 100)); } } }; var loader = new Load(); loader.loadImgs(Valglobal.imgs, function(percent) { // console.log(percent) document.getElementById("percent").innerHTML = percent+'%'; if(percent == 100) { var start = new Date().getTime(); $("img").each(function(){ var _this = $(this); if(_this.attr("data-src")){ _this.attr("src",loctionhref+_this.attr("data-src")+'?t=2'); } }); var end = new Date().getTime(); console.log(end - start+'s'); $(".loading").fadeOut(); } }); } // 执行 loading 方法 loading(); /* 数组去重 */ Array.prototype.only = function() { var res = []; var json = {}; for(var i = 0; i < this.length; i++) { if(!json[this[i]]) { res.push(this[i]); json[this[i]] = 1; } } return res; } $(function() { orientNotice(); var ua = navigator.userAgent.toLowerCase();//获取判断用的对象 if (ua.match(/HUAWEI/i) == "huawei") { /* width:360px height:519px*/ // alert('破~~~~手机改换了。'); } }) var stageWidth,stageHeight; function orientNotice() { if(stageWidth!=document.documentElement.clientWidth||stageHeight!= document.documentElement.clientHeight) { window.viewportW = 640; stageWidth = document.documentElement.clientWidth; stageHeight = document.documentElement.clientHeight; /* 设置新宽高 */ console.log(stageWidth,stageHeight); var phoneWidth = parseInt(window.screen.width); var phoneScale = phoneWidth / window.viewportW; var ua = navigator.userAgent; if(/Android (\d+\.\d+)/.test(ua)) { var version = parseFloat(RegExp.$1); if(version > 2.3) { document.getElementById('viewport').innerHTML = ('<meta class="viewport" name="viewport" content="width=' + window.viewportW + ', minimum-scale = ' + phoneScale + ', maximum-scale = ' + phoneScale + ', target-densitydpi=device-dpi">'); } else { document.getElementById('viewport').innerHTML = ('<meta class="viewport" name="viewport" content="width=' + window.viewportW + ', target-densitydpi=device-dpi">'); } } else { document.getElementById('viewport').innerHTML = ('<meta class="viewport" name="viewport" content="width=' + window.viewportW +', user-scalable=no, target-densitydpi=device-dpi">'); } } }
import notesAdapter from '../adapters/notesAdapter' export function addNote(noteTitle){ const note = notesAdapter.createNote({title: noteTitle, body: ''}) return { type: 'ADD_NOTE', payload: note } } export function fetchNotes(){ const notes = notesAdapter.fetchNotes() return { type: 'FETCH_NOTES', payload: notes } } export function updateCurrentNote(noteId){ return { type: 'UPDATE_CURRENT_NOTE', payload: noteId } } export function updateNote(noteParams){ notesAdapter.updateNote(noteParams) return { type: 'UPDATE_NOTE', payload: { id: noteParams.id, body: noteParams.note.body, title: noteParams.note.title } } } export function loginUser(loginParams){ const user = noteAdapter.loginUser(loginParams) return { payload: user, type: 'LOGIN_USER' } }
import React from "react" import "./header.scss" function Header() { return ( <header className="header"> <nav className="top-bar"> <a className="brand" href="/"> SpaceX Launch Programs </a> </nav> </header> ) } export default Header
var stuffToDo = ["Klipp gräset ", "Betala räkningar", "Köp mjölk", "Spika upp tavlor "]; sessionStorage.setItem("ToDo", stuffToDo); var json_str = JSON.stringify(stuffToDo); sessionStorage.doList = json_str; console.log(stuffToDo) var obj = JSON.parse(json_str); var printList; for (var i = 0; i < obj.length; i++) { printList += "<h1>" + obj[i] + "</h1>"; } // document.getElementById("printlist").innerHTML = obj; var username = "Ali" var password = "Afshar" /** Check if username and password from input fields are the same as the global variables and logging in if matched */ function validateForm() { var usernameInput = document.getElementById("username").value var passwordInput = document.getElementById("password").value if (usernameInput == username && passwordInput == password) { sessionStorage.setItem("username", usernameInput); document.getElementById("printlist").innerHTML = sessionStorage.getItem("username"); } else { document.getElementById("printlist").innerHTML = "Har du glömt ditt lösenord"; } }
export const renderSelectBreeds = (parent, breeds) => { const markup = breeds.map(breed => `<option value="${breed.slug}">${breed.name}</option>`).join(''); parent.insertAdjacentHTML('beforeend', markup); }; export const renderListBreeds = (parent, breeds) => { const markup = breeds.map(breed => `<li>${breed.name}</li>`).join(''); parent.insertAdjacentHTML('beforeend', markup); };
import nanoid from 'nanoid'; import { ITEM_TYPE } from './../constants'; class VideoModel { constructor(entity) { Object.assign( this, { id: nanoid(), type: ITEM_TYPE.VIDEO, url: '', views: 0 }, entity ); } } export default VideoModel;
const array = [ { "name": "sample 1", "age": 25, "id": 123 }, { "name": "sample 2", "age": 26, "id": 124 }, { "name": "sample 3", "age": 27, "id": 125 }, { "name": "sample 4", "age": 28, "id": 126 }, { "name": "sample 4", "age": 29, "id": 127 } ]; console.table(array);
import VueDefaultImage from './components/vue-default-image' const install = (Vue) => { Vue.component(VueDefaultImage.name, VueDefaultImage) } if (typeof window !== 'undefined' && window.Vue) { install(window.Vue); } export default { install, VueDefaultImage, } export { VueDefaultImage }
/** * LINKURIOUS CONFIDENTIAL * Copyright Linkurious SAS 2012 - 2018 * * - Created on 2014-12-05. */ 'use strict'; // external libs const _ = require('lodash'); const Promise = require('bluebird'); // services const LKE = require('../index'); const Db = LKE.getSqlDb(); const Utils = LKE.getUtils(); const Errors = LKE.getErrors(); const Data = LKE.getData(); const AccessRightDAO = LKE.getAccessRightDAO(); // locals const UserCache = require('./UserCache'); const builtinGroups = require('../../../server/services/access/builtinGroups'); class GroupDAO { /** * @type {GroupModel} */ get model() { return Db.models.group; } /** * Given a subset of access rights, the targetType and the node categories or the edge types * in the schema, produce the complete access rights set for the targetType: * - we expand `*` based on the schema information * - we set to `none` everything not in the access rights but in the schema * * @param {string} targetType 'nodeCategory' or 'edgeType' * @param {PublicAccessRight[]} accessRights Explicit access rights of a group * @param {string[]} categoriesOrTypes List of node categories or edge types in the schema * @returns {PublicAccessRight[]} * @private */ _expandAccessRights(targetType, accessRights, categoriesOrTypes) { // first we look for the wildcard access right, if present // 0 or 1 wildcards can be in the list let wildcardValue = Db.models.accessRight.TYPES.NONE; for (let i = 0; i < accessRights.length; ++i) { const currentRight = accessRights[i]; if (currentRight.targetName === '*') { wildcardValue = currentRight.type; accessRights.splice(i, 1); // we remove the wildcard access right break; } } // now we set everything in the schema with the wildcardValue const missingAccessRightsTargetNames = _.difference( categoriesOrTypes, _.map(accessRights, 'targetName') ); [].push.apply(accessRights, missingAccessRightsTargetNames.map(targetName => { return { type: wildcardValue, targetType: targetType, targetName: targetName }; })); return accessRights; } /** * Return the proper access rights for a builtin group based on its name. * * @param {PublicGroup} group * @returns {PublicAccessRight[]} * @private */ _getBuiltinAccessRights(group) { if (group.builtin) { switch (group.name) { case Db.models.group.READ_ONLY_GROUP_NAME: return builtinGroups.READ_ONLY_ACCESS_RIGHTS; case Db.models.group.READ_GROUP_NAME: return builtinGroups.READ_ACCESS_RIGHTS; case Db.models.group.READ_AND_EDIT_GROUP_NAME: return builtinGroups.READ_EDIT_ACCESS_RIGHTS; case Db.models.group.READ_EDIT_AND_DELETE_GROUP_NAME: return builtinGroups.READ_EDIT_DELETE_ACCESS_RIGHTS; case Db.models.group.SOURCE_MANAGER_GROUP_NAME: return builtinGroups.SOURCE_MANAGER_ACCESS_RIGHTS; case Db.models.group.ADMIN_GROUP_NAME: return builtinGroups.ADMIN_ACCESS_RIGHTS; } } } /** * In this function we do the following: * - we turn the groupInstance into group attributes * - we add the user-count to the group * - if `withAccessRights` we add the access rights for the group * - if `expandRights` is true * - we expand `*` based on the schema information * - we set to `none` everything not in the access rights but in the schema * * @param {GroupInstance} groupInstance Group instance * @param {object} [options] * @param {boolean} [options.withAccessRights] Whether to populate the accessRights * @param {boolean} [options.withUserCount] Whether to populate the userCount * @param {boolean} [options.withDates] Whether to populate the creation and update dates * @param {string} [options.sourceKey] Override sourceKey of the groupInstance (used to expand categories on the admin group) * @param {boolean} [options.expandRights=true] Whether to expand the wildcard value on schema access rights * @returns {Bluebird<PublicGroup>} */ formatToPublicGroup(groupInstance, options) { const group = this.model.instanceToPublicAttributes(groupInstance, options.withDates); let publicAccessRights; let sourceKey; const expandRights = options.expandRights !== false; return Promise.resolve().then(() => { if (!options.withUserCount) { return; } return Db.models.user.count({ where: {id: {'$notIn': [Db.models.user.UNIQUE_USER_ID]}}, include: [{ model: Db.models.group, where: {id: groupInstance.id} }] }).then(count => { group.userCount = count; }); }).then(() => { if (!options.withAccessRights) { return group; } // if we format the admin group, the sourceKey is '*' but we want to format it // correctly for a given data-source sourceKey = Utils.hasValue(options.sourceKey) ? options.sourceKey : groupInstance.sourceKey; // order of the statements is important because the admin group could have accessRights // saved in the sql db before the upgrade publicAccessRights = this._getBuiltinAccessRights(group); if (Utils.noValue(publicAccessRights)) { if (Utils.hasValue(groupInstance.accessRights)) { publicAccessRights = groupInstance.accessRights.map(right => { return Db.models.accessRight.instanceToPublicAttributes(right); }); } else { publicAccessRights = []; } } // in LKS we return the access rights for the admin group so the actions of the unique user are populated if (!expandRights || !LKE.isEnterprise()) { group.accessRights = publicAccessRights; return group; } return Promise.all([ Data.getSchemaNodeTypeNames(sourceKey), Data.getSchemaEdgeTypeNames(sourceKey) ]).spread((nodeCategories, edgeTypes) => { // we add to the possible node categories the special category "[no_category]" const dataSource = Data.resolveSource(sourceKey); if (dataSource.features.minNodeCategories === 0) { nodeCategories.push(AccessRightDAO.NO_CATEGORY_TARGET_NAME); } // we partition the access rights in schema related and non const [schemaAccessRights, otherAccessRights] = _.partition(publicAccessRights, right => right.targetType === Db.models.accessRight.TARGET_TYPES.NODE_CATEGORY || right.targetType === Db.models.accessRight.TARGET_TYPES.EDGE_TYPE); group.accessRights = otherAccessRights; // all the schema-related access rights will be expanded to the whole schema // first we expand the wildcard `*`, then we fill the voids for the missing access rights // we partition them again in node category and edge type const [nodeAccessRights, edgeAccessRights] = _.partition(schemaAccessRights, right => right.targetType === Db.models.accessRight.TARGET_TYPES.NODE_CATEGORY); [].push.apply(group.accessRights, this._expandAccessRights( Db.models.accessRight.TARGET_TYPES.NODE_CATEGORY, nodeAccessRights, nodeCategories)); [].push.apply(group.accessRights, this._expandAccessRights( Db.models.accessRight.TARGET_TYPES.EDGE_TYPE, edgeAccessRights, edgeTypes)); return group; }); }); } /** * Get multiple group instances by id. * * @param {number[]} groupIds IDs of the groups * @param {boolean} [withAccessRights] Whether to include the access rights * @returns {Bluebird<GroupInstance[]>} */ getGroupInstances(groupIds, withAccessRights) { Utils.check.intArray('groupIds', groupIds); const query = {where: {id: groupIds}}; if (withAccessRights) { query.include = [Db.models.accessRight]; } return this.model.findAll(query).then(groups => { if (groups.length !== groupIds.length) { const missing = _.difference(groupIds, groups.map(g => g.id)); if (missing.length > 0) { return Errors.business('not_found', `Group #${missing[0]} was not found.`, true); } } return groups; }); } /** * Retrieve a group instance by ID. * Return a rejected promise if the group wasn't found or if the sourceKey don't match. * * @param {number} groupId ID of the group * @param {string} sourceKey Key of the data-source * @returns {Bluebird<GroupInstance>} * @private */ _getGroupInstance(groupId, sourceKey) { Utils.check.posInt('groupId', groupId); // check if the source exists and connected Data.resolveSource(sourceKey); return this.getGroupInstances([groupId], true).then(groupInstances => { // unwrap it from the array const group = groupInstances[0]; if (group.sourceKey !== sourceKey) { return Errors.access( 'forbidden', `Group #${groupId} doesn't belong to data-source "${sourceKey}".`, true ); } return group; }); } /** * Get a group by id. * * @param {number} groupId ID of the group * @param {string} sourceKey Key of the data-source * @returns {Bluebird<PublicGroup>} */ getGroup(groupId, sourceKey) { // it's possible to get also the admin group if (groupId === this.model.ADMIN_GROUP.id) { return this.formatToPublicGroup(this.model.ADMIN_GROUP, { withAccessRights: true, withUserCount: true, withDates: true, sourceKey: sourceKey }); } return this._getGroupInstance(groupId, sourceKey).then(groupInstance => { return this.formatToPublicGroup(groupInstance, { withAccessRights: true, withUserCount: true, withDates: true }); }); } /** * Get all groups within a data-source. * * @param {string} sourceKey Key of the data-source * @param {boolean} [withAccessRights] Whether to include the access rights * * @returns {Bluebird<PublicGroup[]>} */ getGroups(sourceKey, withAccessRights) { Data.resolveSource(sourceKey); const query = {where: {sourceKey: [sourceKey, '*']}}; if (withAccessRights) { query.include = [Db.models.accessRight]; } return this.model.findAll(query).map(groupInstance => { return this.formatToPublicGroup(groupInstance, { withAccessRights: withAccessRights, withUserCount: true, withDates: true, sourceKey: sourceKey }); }); } /** * Create a group. * * @param {string} groupName Name of the group * @param {string} sourceKey Key of the data-source * @returns {Bluebird<PublicGroup>} */ createGroup(groupName, sourceKey) { if (!LKE.isEnterprise()) { return Errors.business('not_implemented', undefined, true); } // check if the group name is legal Utils.check.nonEmpty('groupName', groupName); Data.resolveSource(sourceKey); return this.model.findOrCreate({where: {name: groupName, sourceKey: sourceKey}}) .spread((groupInstance, created) => { if (!created) { return Errors.business('group_exists', 'The group already exists', true); } return this.formatToPublicGroup(groupInstance, { withAccessRights: true, withUserCount: true, withDates: true }); }); } /** * Rename a group. * * @param {number} groupId ID of the group * @param {string} sourceKey Key of the data-source * @param {string} name New name of the group * @returns {Bluebird<PublicGroup>} */ renameGroup(groupId, sourceKey, name) { if (!LKE.isEnterprise()) { return Errors.business('not_implemented', undefined, true); } // check if the group name is legal Utils.check.nonEmpty('name', name); return this._getGroupInstance(groupId, sourceKey).then(groupInstance => { if (groupInstance.builtin) { return Errors.access('forbidden', 'You can\'t rename a builtin group.', true); } groupInstance.name = name; return groupInstance.save().then(() => { UserCache.emptyCache(); return this.formatToPublicGroup(groupInstance, { withAccessRights: true, withUserCount: true, withDates: true }); }); }); } /** * Delete a group and all the rights linked to that group. * * @param {number} groupId ID of the group to delete * @param {string} sourceKey Key of the data-source * @returns {Bluebird<void>} */ deleteGroup(groupId, sourceKey) { if (!LKE.isEnterprise()) { return Errors.business('not_implemented', undefined, true); } return this._getGroupInstance(groupId, sourceKey).then(groupInstance => { if (groupInstance.builtin) { return Errors.access( 'forbidden', 'You can\'t delete a builtin group.', true ); } // we delete the access rights associated to the group return Db.models.accessRight.destroy({where: {groupId: groupId}}).then(() => { UserCache.emptyCache(); return groupInstance.destroy(); }); }); } /** * Set an array of access rights on a group. * * @param {number} groupId ID of the group * @param {string} sourceKey Key of the data-source * @param {AccessRightAttributes[]} rights Access rights to set * @param {boolean} [validateAgainstSchema] Whether the access rights will be checked to be of node categories or edge types in the schema * @returns {Bluebird<void>} */ setRightsOnGroup(groupId, sourceKey, rights, validateAgainstSchema) { if (!LKE.isEnterprise()) { return Errors.business('not_implemented', undefined, true); } rights = rights.map(right => { right.sourceKey = sourceKey; return right; }); Utils.check.array('rights', rights, 1); Data.resolveSource(sourceKey); // check that all the access rights are legit return AccessRightDAO.checkRights(rights, sourceKey, validateAgainstSchema).then(() => { return this._getGroupInstance(groupId, sourceKey); }).then(groupInstance => { if (groupInstance.builtin) { return Errors.access( 'forbidden', 'Cannot set access rights for builtin groups.', true ); } return Promise.map(rights, right => { // we look for an existing access right with the same scope return AccessRightDAO.findMatchingRight(groupInstance.id, right).then(existingRight => { // matching access rights exist if (Utils.hasValue(existingRight)) { // update the existing access right existingRight.type = right.type; return existingRight.save().return(); } // no matching access right found, create a new one return Db.models.accessRight.create(right).then(rightInstance => { return groupInstance.addAccessRight(rightInstance); }).return(); }); }, {concurrency: 1}); }).then(() => { UserCache.emptyCache(); }); } /** * Delete an access right from a group. * * @param {number} groupId ID of the group * @param {string} sourceKey Key of the data-source * @param {string} targetType Type of the target of the access rights to delete * @param {string} targetName Name of the target of the access rights to delete * @returns {Bluebird<void>} */ deleteRightOnGroup(groupId, sourceKey, targetType, targetName) { if (!LKE.isEnterprise()) { return Errors.business('not_implemented', undefined, true); } // we check if the group exists and the sourceKey is valid return this._getGroupInstance(groupId, sourceKey).then(groupInstance => { if (groupInstance.builtin) { return Errors.access( 'forbidden', 'Cannot set access rights for builtin groups.', true ); } const rightAttributes = { targetType, targetName, sourceKey, type: '' // AccessRightDAO::findMatchingRight doesn't care about the type }; return AccessRightDAO.findMatchingRight(groupId, rightAttributes); }).then(rightInstance => { if (Utils.noValue(rightInstance)) { return Errors.business('not_found', 'Access right not found', true); } return rightInstance.destroy(); }).then(() => { UserCache.emptyCache(); }); } } module.exports = new GroupDAO();
(function() { 'use strict'; angular .module('app.invinvtry') .factory('InvinvtryForm', factory); factory.$inject = ['$translate']; /* @ngInject */ function factory($translate) { var getFormFields = function(disabled) { var fields = [ { className: 'row', fieldGroup: [ { className: 'col-xs-6', type: 'select', key: 'ptnrType', templateOptions: { label: $translate.instant('InvInvtry_invInvtryType_description.title'), disabled:disabled, required:true, options: [ ] } }, { className: 'col-xs-6', type: 'input', key: 'ctryOfRsdnc', templateOptions: { label: $translate.instant('InvInvtry_acsngUser_description.title'), //pattern: '\\d{5}', disabled:disabled, required:true } } ] }, { className: 'row', fieldGroup: [ { className: 'col-xs-4', type: 'input', key: 'cpnyName', templateOptions: { label: $translate.instant('InvInvtry_acsngUserFullName_description.title'), disabled:disabled, required:true } }, { className: 'col-xs-4', type: 'input', key: 'gender', templateOptions: { label: $translate.instant('InvInvtry_invtryGroup_description.title'), disabled:disabled } }, { className: 'col-xs-4', type: 'input', key: 'legalForm', templateOptions: { label: $translate.instant('InvInvtry_descptn_description.title'), disabled:disabled } } ] }, { className: 'row', fieldGroup: [ { className: 'col-xs-3', type: 'input', key: 'firstName', templateOptions: { label: $translate.instant('InvInvtryItem_section_description.title'), disabled:disabled, required:true } }, { className: 'col-xs-3', type: 'input', key: 'lastName', templateOptions: { label: $translate.instant('InvInvtryItem_sectionName_description.title'), disabled:disabled } }, { className: 'col-xs-3', type: 'input', key: 'gender', templateOptions: { label: $translate.instant('InvInvtryItem_artNameStart_description.title'), disabled:disabled } }, { className: 'col-xs-3', type: 'input', key: 'brthDt', templateOptions: { label: $translate.instant('InvInvtryItem_artNameEnd_description.title'), disabled:disabled } } ] } ]; return fields; }; var service = { getFormFields: getFormFields }; return service; } })();
if (Meteor.isClient) { Router.configure({autoStart: true}); MyCustomController = RouteController.extend({ template: 'other' }); Router.map(function () { this.route('home', { path: '/', controller: MyCustomController }); }); }
// Imports import React, { useReducer } from 'react'; import { View, StyleSheet, TouchableOpacity } from 'react-native'; import { Feather } from '@expo/vector-icons'; export default function Checkbox(props) { const [checked, toggleChecked] = useReducer(checked => !checked, props.startChecked ? true : false); function handlePress() { if(props.onChange) props.onChange(); toggleChecked(); } return ( <View style={props.style || {}}> <TouchableOpacity style={styles.toggler} onPress={handlePress}> {checked ? props.checked || (<Feather name="check-square" size={24} color="black" />) : props.unchecked || (<Feather name="square" size={24} color="black" />)} </TouchableOpacity> </View> ) } const styles = StyleSheet.create({ toggler: { margin: 2, padding: 3, } });
const util = require('../app util/util'); const code = require('../constants').http_codes; const msg = require('../constants').messages; const bcrypt = require('bcrypt'); const user = require('../schema/user') const crypto = require('crypto'); const env = require('dotenv').config() const userDao = require('../user/userDao'); const fs = require('fs'); function uploadPhoto(req, res) { let token = req.headers['authorization'] let userToken = util.decodeToken(token) req._id = userToken.id req.newFile_name = []; let query = { _id: req._id } userDao.findone(query).then((data) => { if (data.imageUrl != '' && !(!data.imageUrl)) { var imageName = data.imageUrl.split("/")[3]; req.image = imageName fs.unlink('./img/' + imageName, function (err) { if (err) { return res.json({ code: 404, message: 'image not found' }) } }) } else { req.image = '' } util.upload(req, res, async function (err) { if (err) { return res.json({ code: code.badRequest, message: err }) } else { const files = req.files; let index, len; var filepathlist = [] for (index = 0, len = files.length; index < len; ++index) { let filepath = process.env.IMAGEPREFIX + files[index].path.slice(4,); filepathlist.push(filepath) } return res.json({ code: code.created, message: msg.ok, data: filepathlist }) } }); }) } module.exports = { uploadPhoto }
import React from 'react'; import {connect} from 'react-redux'; import './App.css'; import SearchBar from './components/SearchBar/SearchBar'; import Table from './components/Table/Table'; import {filterTable, sortTable, getData} from './redux/table_reducer'; function App(props) { return ( <div className="appWrapper"> <SearchBar filterTable={props.filterTable}/> <Table data={props.data} sortMethod={props.sortMethod} reverseToggler={props.reverseToggler} searchQuery={props.searchQuery} sortTable={props.sortTable} toggleModal={props.toggleModal} getData={props.getData}/> </div> ); } const mapStateToProps = (state) => { return { data: state.table.data, sortMethod: state.table.sortMethod, reverseToggler: state.table.reverseToggler, searchQuery: state.table.searchQuery, } } let AppContainer = connect(mapStateToProps, {filterTable, sortTable, getData})(App); export default AppContainer;
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableOpacity, Image, ScrollView, TextInput, Switch, KeyboardAvoidingView, AlertIOS } from 'react-native'; import {connect} from 'react-redux'; import Swiper from "react-native-deck-swiper"; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import { registor_username, registor_password, createAccount, set_password_danger, set_username_danger, reset_registor, createAccountSuccess, findAccount } from '../states/post-actions.js'; class RegisterScreen extends Component { constructor(props) { super(props); this.state = { }; } componentWillMount() { this.props.dispatch(reset_registor()); } handleUserInputChange(text) { this.props.dispatch(registor_username(text)); if(text){ this.props.dispatch(set_password_danger('')); this.props.dispatch(set_username_danger('')); } } handlePasswordInputChange(text) { this.props.dispatch(registor_password(text)); } handle_registor_click(username, password){ if(!username){ this.props.dispatch(set_username_danger('has-danger')); return; } if(!password){ this.props.dispatch(set_password_danger('has-danger')); return; } this.props.dispatch(createAccount(username, password)); this.props.dispatch(createAccountSuccess(true)); this.props.dispatch(findAccount("", username, password)); setTimeout(() => { this.props.navigation.navigate('Home'); }, 1000) } render() { const {registor_username_value, registor_password_value, password_danger, username_danger} = this.props; return ( <KeyboardAwareScrollView style = {{backgroundColor:'white'}}> <View> <Text style = {styles.title}>Register an account</Text> </View> <View> <View style = {styles.inputView}> <TextInput style = {styles.textInput} placeholder="Username" value={this.props.inputValue} // controlled component onChangeText={text => this.handleUserInputChange(text)} returnKeyType = 'done' /> </View> </View> <View style = {{marginTop:20}}> <View style = {styles.inputView}> <TextInput style = {styles.textInput} placeholder="Password" value={this.props.inputValue} // controlled component onChangeText={text => this.handlePasswordInputChange(text)} returnKeyType = 'done' secureTextEntry = 'true' /> </View> </View> <View style = {styles.doneView}> <TouchableOpacity onPress = {() => this.handle_registor_click(registor_username_value, registor_password_value)} style = {styles.doneRec}> <Text style = {styles.doneText}>Create</Text> </TouchableOpacity> </View> </KeyboardAwareScrollView> ); } } const styles = StyleSheet.create({ title:{ fontSize:20, fontWeight:'300', color:'#244048', alignSelf:'center', marginTop:35, marginBottom:10 }, inputView:{ width:'100%', height:40, marginTop:5, }, textInput:{ height:50, marginTop:15, textAlign:'center', padding:'2%', width:'90%', borderWidth:2, borderRadius:9, alignSelf:'center', borderColor:'#D1D1D1' }, icon:{ width:50, height:50, marginLeft:20, marginTop:20 }, subTitle:{ width:200, marginLeft:80, color:'#777777', fontWeight:'300', fontSize:25, marginTop:-35 }, or:{ alignSelf:'center', fontSize:14, fontWeight:'400', color:'#95989A', marginTop:40 }, location:{ alignSelf:'center', fontSize:17, fontWeight:'400', color:'#95989A', marginTop:10 }, doneRec:{ backgroundColor:'#99DFF4', width:325, height:50, alignSelf:'center', borderColor:'#99DFF4', borderWidth:2, borderRadius:10, justifyContent:'center' }, doneView:{ marginTop:70, marginBottom:100 }, doneText:{ textAlign:'center', fontSize:20, fontWeight:'600', color:'white', } }); export default connect((state) => { return { ...state.Registor, ...state.Main_state }; })(RegisterScreen);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Camera = require("./Camera"); const scene = require("./scene"); SupRuntime.registerPlugin("Camera", Camera); SupRuntime.registerPlugin("scene", scene);
import React from 'react'; import styles from './App.css'; export default class Sidebar extends React.Component { render() { return ( <div> <ul id="slide-out" class="sidenav sidenav-fixed"> <br /> <li><img class="display" src="../img/logo.png"></img></li> <br /> <li><a href="/timeline.html">Timeline</a></li> <li><a href="#!">Charities</a></li> <li><a href="#!">Donation report</a></li> </ul> </div> ); } }
module.exports = function makeExchange(currency) { let summ = currency; if (summ <= 0) return {}; if (summ > 10000) return {error: "You are rich, my friend! We don't have so much coins for exchange"}; let h = 0; let q = 0; let d = 0; let n = 0; let p = 0; let money = {}; function ext(summ) { if (summ >= 50) { h = h + 1; money["H"] = h; return ext(summ - 50); } else { if(summ >= 25) { q = q + 1; money["Q"] = q; return ext(summ - 25); } else { if (summ >= 10) { d = d + 1; money["D"] = d; return ext(summ - 10); } else { if (summ >= 5) { n = n + 1; money["N"] = n; return ext(summ - 5); } else { if (summ != 0) { p = summ; money["P"] = p; } } } } } } ext(summ); return money; }
export const findAll = () => { const maybeIssues = JSON.parse(localStorage.getItem("issues")); return maybeIssues ? maybeIssues : []; }; export const saveAll = (issues) => { localStorage.setItem("issues", JSON.stringify(issues)); }; export const save = (issue) => { const issues = findAll(); issues.push(issue); saveAll(issues); };
import * as actions from '../constants/actionTypes'; const initialState = { fetching: false, loggedIn: false, user: { name: '', photoURL: '', email: '' }, error: '' }; const userReducer = (state = initialState, action) => { switch(action.type) { case actions.LOGIN_SUCCESS: return { ...state, error: '', loggedIn: true, user: {...action.payload} }; case actions.LOGIN_ERROR: return {...state, fetching: false, error: action.error}; case actions.LOGOUT: return { fetching: false, loggedIn: false, user: { name: '', photoURL: '', email: '' }, error: '' }; default: return state; } }; export default userReducer;
import React, { useState, useEffect } from "react"; import firebaseApp from "../credenciales"; import { getAuth, signOut } from "firebase/auth"; import { getFirestore, doc, getDoc, setDoc } from "firebase/firestore"; import { Container, Button } from "react-bootstrap"; import AgregarTarea from "./AgregarTarea"; import ListadoTareas from "./ListadoTareas"; const auth = getAuth(firebaseApp); const firestore = getFirestore(firebaseApp); const Home = ({ correoUsuario }) => { const [arrayTareas, setArrayTareas] = useState(null); const fakeData = [ { id: 1, descripcion: "tarea falsa 1", url: "https://picsum.photos/420" }, { id: 2, descripcion: "tarea falsa 2", url: "https://picsum.photos/420" }, { id: 3, descripcion: "tarea falsa 3", url: "https://picsum.photos/420" }, ]; async function buscarDocumentOrCrearDocumento(idDocumento) { //crear referencia al documento const docuRef = doc(firestore, `usuarios/${idDocumento}`); // buscar documento const consulta = await getDoc(docuRef); // revisar si existe if (consulta.exists()) { // si sí existe const infoDocu = consulta.data(); return infoDocu.tareas; } else { // si no existe await setDoc(docuRef, { tareas: [...fakeData] }); const consulta = await getDoc(docuRef); const infoDocu = consulta.data(); return infoDocu.tareas; } } useEffect(() => { async function fetchTareas() { const tareasFetchadas = await buscarDocumentOrCrearDocumento( correoUsuario ); setArrayTareas(tareasFetchadas); } fetchTareas(); }, []); return ( <Container> <h4>hola, sesión iniciada</h4> <Button onClick={() => signOut(auth)}>Cerrar sesión</Button> <hr /> <AgregarTarea arrayTareas={arrayTareas} setArrayTareas={setArrayTareas} correoUsuario={correoUsuario} /> {arrayTareas ? ( <ListadoTareas arrayTareas={arrayTareas} setArrayTareas={setArrayTareas} correoUsuario={correoUsuario} /> ) : null} </Container> ); }; export default Home;
/** * 2013-2015 BeTechnology Solutions Ltd * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to info@betechnology.es so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author BeTechnology Solutions Ltd <info@betechnology.es> * @copyright 2013-2015 BeTechnology Solutions Ltd * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ $(document).ready( function() { // Change event handler for "Manage Accounts:". $("#tiresiastagging_language").change(function() { var langId = parseInt($(this).val()), $currentLanguage = $('#tiresiastagging_current_language'), $form = $('form.tiresiastagging'); $currentLanguage.val(langId); $form.submit(); }); // Click event handler for the "Account settings". $("#tiresiastagging_account_setup").click(function(event) { event.preventDefault(); var $iframe = $('#tiresiastagging_iframe'), $installedView = $('#tiresiastagging_installed'); $installedView.show(); $iframe.hide(); }); // Click event handler for the "Back" button on the "You have installed Tiresias...." page. $('#tiresiastagging_back_to_iframe').click(function(event) { event.preventDefault(); var $iframe = $('#tiresiastagging_iframe'), $installedView = $('#tiresiastagging_installed'); $iframe.show(); $installedView.hide(); }); // Init the iframe re-sizer. $('#tiresiastagging_iframe').iFrameResize({heightCalculationMethod : 'bodyScroll'}); });
const puppeteer = require("puppeteer"); const fs = require("fs"); function getchordsheets(singername, websitename) { fs.readFile( singername + "/" + websitename + ".txt", "utf8", async function (err, data) { if (err) throw err; console.log("OK: "); const alllinks = data.split("\n"); for (let j = 0; j < alllinks.length; j++) { console.log(alllinks[j]); await getpage(alllinks[j], function (result) { console.log(result); fs.writeFile( "output/" + websitename + "/" + singername + "-" + j + ".txt", result, function (err) { if (err) return console.log(err); console.log("written"); } ); }); } } ); } async function getpage(link, callback) { try { if (link.indexOf("guitarians.com/chord") != -1) { return (async () => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(link, { waitUntil: "load", }); const pageresult = await page.evaluate(() => { return { text: document.getElementsByClassName("section-part")[0] .innerText, }; }); // console.log(pageresult.text); await browser.close(); callback(pageresult.text); } catch { callback("server error"); } })(); } else if (link.indexOf("polygonguitar.blogspot.com") != -1) { return (async () => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(link, { waitUntil: "load", }); const pageresult = await page.evaluate(() => { return { text: document.getElementsByClassName("post-body")[0].innerText, }; }); // console.log(pageresult.text); await browser.close(); callback(pageresult.text); } catch { callback("server error"); } })(); } else if (link.indexOf("daydayguitar.blogspot.com") != -1) { return (async () => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(link, { waitUntil: "load", }); const pageresult = await page.evaluate(() => { return { text: document.getElementsByTagName("article")[0].innerText, }; }); // console.log(pageresult.text); await browser.close(); callback(pageresult.text); } catch { callback("server error"); } })(); } else if (link.indexOf("blog.xuite.net") != -1) { // return callback('not supported'); return (async () => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(link, { waitUntil: "load", }); const pageresult = await page.evaluate(() => { return { text: document .getElementsByClassName("blogbody")[0] .innerText.split("--------------")[0], }; }); // console.log(pageresult.text); await browser.close(); callback(pageresult.text); } catch { callback("server error"); } })(); } else if (link.indexOf("91pu.com") != -1) { return (async () => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(link, { waitUntil: "load", }); const pageresult = await page.evaluate(() => { return { text: document.getElementsByClassName("tone")[0].innerText, }; }); // console.log(pageresult.text); await browser.close(); callback(pageresult.text); } catch { callback("server error"); } })(); } else if (link.indexOf("tabs.ultimate-guitar.com") != -1) { return (async () => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(link, { waitUntil: "load", }); const pageresult = await page.evaluate(() => { return { text: document.getElementsByTagName("code")[0].innerText, }; }); // console.log(pageresult.text); await browser.close(); callback(pageresult.text); } catch { callback("server error"); } })(); } else if (link.indexOf("chord4.com/tabs") != -1) { return (async () => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(link, { waitUntil: "load", }); const pageresult = await page.evaluate(() => { return { text: document.getElementsByTagName("pre")[0].innerText, }; }); // console.log(pageresult.text); await browser.close(); callback(pageresult.text); } catch { callback("server error"); } })(); } else if (link.indexOf("chords-and-tabs.net") != -1) { return (async () => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(link, { waitUntil: "load", }); const pageresult = await page.evaluate(() => { return { text: document.getElementsByClassName("contentdiv")[0].innerText, }; }); // console.log(pageresult.text); await browser.close(); callback(pageresult.text); } catch { callback("server error"); } })(); } else if (link.indexOf("polygon.guitars") != -1) { return (async () => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(link, { waitUntil: "load", }); const pageresult = await page.evaluate(() => { var allline = document .getElementsByClassName("cnl_page")[0] .getElementsByClassName("cnl_line"); var tempresult = ""; for (var j = 0; j < allline.length; j++) { var tempallchord = allline[j].getElementsByClassName("chord"); for (var k = 0; k < tempallchord.length; k++) { tempresult += tempallchord[k].innerText; } tempresult += "\n"; var tempalllyric = allline[j].getElementsByClassName("lyric"); for (var k = 0; k < tempalllyric.length; k++) { tempresult += tempalllyric[k].innerText; } tempresult += "\n"; } console.log(tempresult); return { text: tempresult, }; }); var tempresult = pageresult.text; for (var j = 0; j < tempresult; j++) { if (tempresult[j] == "\n") { tempresult[j] = "\0"; } } // console.log(tempresult); await browser.close(); callback(tempresult); } catch { callback("server error"); } })(); } else { callback("not supported"); } } catch (e) { console.log(e); callback("server error"); } } exports.getchordsheets = getchordsheets;
import React from 'react'; import {TouchableOpacity, Text, View} from 'react-native'; import style from './../style.js'; const Nav = props => ( <View style={{marginTop: 150}}> <TouchableOpacity style={style.navButton} onPress={() => props.handlePages('displayPlaces')} > <Text style={style.navText}>Places</Text> </TouchableOpacity> <TouchableOpacity style={style.navButton} onPress={() => props.handlePages('displayRestaurants')} > <Text style={style.navText}>Restaurants</Text> </TouchableOpacity> <TouchableOpacity style={style.navButton} onPress={() => props.handlePages('logOut')} > <Text style={style.navText}>Log Out</Text> </TouchableOpacity> </View> ); export default Nav;
import React, { Component } from 'react' class Brick extends Component { constructor() { super() this.state = { hiddenArray: [] } } contentColor = () => { const {contents} = this.props switch (contents) { case 1: return 'blue' case 2: return 'green' case 3: return 'red' case 4: return 'navy' case 5: return 'maroon' case 6: return 'teal' case 7: return 'purple' case 8: return 'black' case 'm': return '' default: return 'black' } } render() { let flagInd = '' if (this.props.flags.includes(this.props.index)){ flagInd = 'flag' } if (this.props.hidden === true){ if (!this.props.flags.includes(this.props.index)){ return ( <div onClick={() => this.props.toggleHidden(this.props.contentsArray, this.props.hiddenArray, this.props.index)} className={`boxhidden${flagInd}`}> </div> ) } else { return ( <div onClick={() => this.props.toggleHidden('flag', this.props.hiddenArray, this.props.index)} className={`boxhidden${flagInd}`}> </div> ) } } else { if (this.props.contents ==='m'){ return ( <div className='box'> <div className='mine'></div> </div> ) } else { return ( <div className='box' style={{color: this.contentColor()}}> {this.props.contents} </div> ) } } } } export default Brick
/** * Created by Mibert on 20.07.2017. */ var ORDERED_COLUMN = 'created_at'; var DIRECTION = 'desc'; function seenClick(that) { $(that).hide().parent().append('<i class="fa fa-refresh fa-spin"></i>'); $.ajax({ type: "GET", data: { 'post_id': that.value, 'seen': that.checked }, url: "/adminzone/posts/seentoogle", success: function () { $(that).parents('tr').toggleClass('panel-info') }, error: function () { $(that).prop('checked', $(that).prop('checked') == false) }, complete: function () { $('.fa-spin').remove(); $(that).show(); } }) } function activeClick(checkbox) { $(checkbox).hide().parent().append('<i class="fa fa-refresh fa-spin"></i>'); $.ajax({ type: "GET", data: { 'post_id': checkbox.value, 'active': checkbox.checked }, url: "/adminzone/posts/activetoogle", success: function () { $(checkbox).parents('tr').toggleClass('panel-warning') }, error: function () { $(checkbox).prop('checked', $(checkbox).prop('checked') == false) }, complete: function () { $('.fa-spin').remove(); $(checkbox).show(); } }) } function deleteClick(that) { $.ajax({ type: "POST", dataType: "html", data: { '_token': $('input[name="_token"]').val(), 'post_id': that.value }, url: "/adminzone/posts/delete", success: function (data) { $(that).parents("tr").remove(); var page = ($(".responsive-table .pagination .active span").html()); getData(page); createPopupForAjax(data); } }) } function setEventHandlersForTable() { $('.responsive-table input:checkbox[name="seen"]').on('change' , function () { seenClick(this) }) $('.responsive-table input:checkbox[name="active"]').on('change', function () { activeClick(this) }) $('.responsive-table .icon-delete').on('click', function () { deleteClick(this); }) } function getData(page, url) { $.ajax({ url: url, type: "GET", data: { 'direction': DIRECTION, 'ordered': ORDERED_COLUMN, 'page': page }, success: function (data) { $('.responsive-table').children('tbody').empty().append(data); setEventHandlersForTable(); location.hash = page; } }) } $(window).on('hashchange', function() { if (window.location.hash) { var page = window.location.hash.replace('#', ''); if (page == Number.NaN || page <= 0) { return false; }else{ getData(page); } } }); $(document).ready( function () { setEventHandlersForTable() $(document).on('click', '.pagination a', function(event) { $('li').removeClass('active'); $(this).parent('li').addClass('active'); event.preventDefault(); var myurl = $(this).attr('href'); var page=$(this).attr('href').split('page=')[1]; getData(page, myurl); }) $('.order').on('click', function () { var icon = $(this).children('i'); var icons = $('.order').children('i'); if(icon.hasClass('fa-sort-desc')) { icons.removeClass('fa-sort-desc fa-sort-asc').addClass('fa-sort'); icon.removeClass('fa-sort-desc').addClass('fa-sort-asc'); DIRECTION = 'asc'; } else { icons.removeClass('fa-sort-desc fa-sort-asc').addClass('fa-sort'); icon.removeClass('fa-sort-asc').addClass('fa-sort-desc'); DIRECTION = 'desc'; } ORDERED_COLUMN = $(this).prop('name'); $.ajax({ type: "GET", url: "/adminzone/posts/all", data: { '_token': $('input[name="_token"]').val(), 'direction': DIRECTION, 'ordered': $(this).prop('name') }, success: function (data) { $('.responsive-table').children('tbody').empty().append(data); setEventHandlersForTable(); } }) }) })
var ssi = require('ssi'); var inputDirectory = "ehp-web-hrs-amir-test/"; var outputDirectory = "data_B/web_output/"; var matcher = "/**/*.shtml"; var includes = new ssi(inputDirectory, outputDirectory, matcher, true); includes.compile();
import React from 'react'; import ReactDom from 'react-dom'; import Card from './Card'; import "./index.css"; import Sdata from "./Sdata"; ReactDom.render( <> <h1 className="heading_style"> List Of Top 5 Netflix Series in 2020</h1> <Card sname={Sdata[0].sname} imgscr={Sdata[0].imgscr} title={Sdata[0].title} link={Sdata[0].link} /> <Card sname={Sdata[1].sname} imgscr={Sdata[1].imgscr} title={Sdata[1].title} link={Sdata[1].link} /> <Card sname={Sdata[2].sname} imgscr={Sdata[2].imgscr} title={Sdata[2].title} link={Sdata[2].link} /> <Card sname={Sdata[3].sname} imgscr={Sdata[3].imgscr} title={Sdata[3].title} link={Sdata[3].link} /> <Card sname={Sdata[4].sname} imgscr={Sdata[4].imgscr} title={Sdata[4].title} link={Sdata[4].link} /> </>, document.getElementById('root') );
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux'; import { createStore } from 'redux' import reducers from './reducers' import router from './router'; const store = createStore(reducers) // const appElement = document.getElementById('app') // function render() { // ReactDOM.render( // <Home />, // appElement // ) // } // // render() // store.subscribe(render) ReactDOM.render( <Provider store={store}>{router}</Provider>, document.getElementById('app') );
import React from 'react'; import SpotifyPlayer from 'react-spotify-web-playback'; const Player = ({ token, transferPlayback }) => { return ( <div className="navbar is-fixed-bottom"> <SpotifyPlayer callback={(state) => { console.log(state); }} token={token} autoPlay={true} persistDeviceSelection={true} /> </div> ); } export default Player;
import React, { Component } from 'react'; import Header from '../components/Header' import Footer from '../components/Footer' import Swiper from 'swiper' import 'swiper/dist/css/swiper.css' class Home extends Component { state={ dataList:[], data:[ { id:1, url:'http://pic41.nipic.com/20140508/18609517_112216473140_2.jpg' }, { id:2, url:'http://pic33.nipic.com/20131007/13639685_123501617185_2.jpg' }, { id:3, url:'http://pic.58pic.com/58pic/13/16/45/68p58PICJZr_1024.png' } ], ico:[ { icon:'glyphicon glyphicon-home', tit:'肖战' }, { icon:'glyphicon glyphicon-cloud', tit:'肖战' }, { icon:'glyphicon glyphicon-asterisk', tit:'肖战' }, { icon:'glyphicon glyphicon-heart', tit:'肖战' }, { icon:'glyphicon glyphicon-inbox', tit:'肖战' }, { icon:'glyphicon glyphicon-lock', tit:'肖战' }, { icon:'glyphicon glyphicon-picture', tit:'肖战1' }, { icon:'glyphicon glyphicon-screenshot', tit:'肖战' } ] } componentDidMount(){ new Swiper('.swiper-container',{ autoplay:true, delay:1000 }) } render() { let {data,ico} =this.state return ( <div className="wrap"> <Header></Header> <main className="main"> <div className="banner"> <div className="swiper-container"> <div className="swiper-wrapper"> { data.map((item,ind)=><div key={ind} className="swiper-slide"> <img src={item.url} alt=""/> </div>) } </div> </div> </div> <div className="nav" > { ico.map((item,ind)=><dl key={ind} onClick={()=>this.btn(item.tit)}> <dt><i className= {item.icon}></i></dt> <dd>{item.tit}</dd> </dl>) } </div> </main> <Footer {...this.props}/> </div> ); } btn=(name)=>{ if(name==="肖战1"){ this.props.history.push('/release') } } } export default Home;
/* Web sitesinin rotalarını yönettiğim kısım. Web sayfasını burda ayağa kaldırıyorum. */ //seo içeriklerini çektiğim modul const indexSeo = require('./../views/seo/indexRoutesSeo') //mongoDB bağlantısından önce test veriler için kullandığım veriler // const blogYazilari = require('./../models/blogModel') const express = require('express'), router = express.Router(); router.get('/',(req,res) => { res.status(200).render("user/home",{seo:indexSeo.seo["index"],dbBlogYazilari:{}}); }) router.get('/blog',(req,res)=>{ res.status(200).render('user/blog',{seo:indexSeo.seo["blog"]}) }) router.get('/hakkimizda',(req,res)=>{ res.status(200).render('user/hakkimizda',{seo:indexSeo.seo["hakkimizda"]}) }) router.get('/iletisim',(req,res)=>{ res.status(200).render('user/iletisim',{seo:indexSeo.seo["iletisim"]}) }) module.exports = router
import React from "react"; import {connect} from "react-redux"; import {signIn} from "../actions/authActions"; class SignIn extends React.Component{ state = { email: '', password: '' } handleChange = (e) => { this.setState({ [e.target.id]: e.target.value }) } handleSubmit = (e) => { e.preventDefault(); this.props.signIn(this.state); } render() { const {authError} = this.props; return( <div className="container" style={{width: "30%"}}> <h3 className="text-center">Sign In</h3> <form onSubmit={this.handleSubmit} className="justify-content-center"> <div className="form-group"> <label htmlFor="email">Email address</label> <input type="email" className="form-control" id="email" placeholder="Enter email" onChange={this.handleChange} /> </div> <div className="form-group"> <label htmlFor="password">Password</label> <input type="password" className="form-control" id="password" placeholder="Password" onChange={this.handleChange} /> </div> <button type="submit" className="btn btn-primary">Submit</button> <div className="text-center text-danger"> {authError ? <p>{authError}</p> : null} </div> </form> </div> ) } } const mapStateToProps = (state) => { // console.log(state); return { authError: state.auth.authError } } const mapDispatchToProps = (dispatch) => { return { signIn: (cred) => dispatch(signIn(cred)) } } export default connect(mapStateToProps, mapDispatchToProps)(SignIn);
import React, {Component} from "react" import {DateRangePicker} from "element-react" import "./calendar.scss" export default class Calendar extends Component { constructor(props) { super(props); } render () { return ( <div className={`date-range-picker-container ${this.props.className ? this.props.className : ""}`}> <DateRangePicker placeholder="选择日期范围" isShowTime={true} {...this.props} /> </div> ) } }
import renderMethod from "../../component/Render"; import Css from 'SRC/pages/Css' import React, { Component } from 'react' export const CssData = { title:'Html & Css', id:'css', component:Css, path: '/htmlcss', subtitle: 'html & css 相关问题', default: '/all', navData:[ { name: 'Html', submenus: [ { name: 'html5 新增内容', id: 'html5' }, ] }, { name: 'Css', submenus: [ { name: '杂记', id: 'all' }, { name: 'css3 新属性', id: 'css3' }, { name: 'BFC', id: 'bfc' }, { name: '实现局中', id: 'center' }, { name: '盒模型', id: 'box' }, { name: 'flex', id: 'flex' } ] }, ] } const navData = CssData.navData const menu = {} navData.map(item => { item.submenus.map(it => { menu[it.id] = (props) => { return <div key={it}> { renderMethod( require('./Content/' + it.id).default, props ) } </div> } }) }) export const content = { ...menu }
/* * @Author: zhenglfsir@gmail.com * @Date: 2019-01-03 22:23:37 * @Last Modified by: zhenglfsir@gmail.com * @Last Modified time: 2019-02-28 13:08:21 * redux 中间件 */ import * as Sentry from '@sentry/browser'; export const createPromiseMiddleware = (effects) => { return () => (next) => (action) => { if (Object.keys(effects).indexOf(action.type) > -1) { return new Promise((resolve, reject) => { next({ ...action, _resolve: resolve, _reject: reject, }); }); } return next(action); }; }; export const crashReporterMiddleware = () => { return (store) => (next) => (action) => { try { return next(action); } catch (err) { console.error('crash reporter:', err); Sentry.withScope((scope) => { scope.setExtra('action', action); scope.setExtra('state', store.getState()); }); Sentry.captureException(err); } }; };
import React from "react"; import PropTypes from "prop-types"; const Jumbo = props => { return ( <div className=" d-flex flex-column align-items-center justify-content-center mx-2"> <div className="jumbotron"> <h1 className="display-4"> Welcome to the Simple Landing Page </h1> <p className="lead"> This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information. </p> <hr className="my-4" /> <p> It uses utility classes for typography and spacing to space content out within the larger container. </p> <a className="btn btn-outline-success btn-lg" href="#" role="button"> Call to Action! </a> </div> </div> ); }; Jumbo.propTypes = { name: PropTypes.string }; export default Jumbo;
const initialState = {loading: false, err: null}; export default (state=initialState, action) => { switch (action.type) { case 'REGISTER_USER_REQUEST': return {loading: true, err: state.err}; case 'REGISTER_USER_SUCCESS': return {loading: false, err: null}; case 'REGISTER_USER_ERROR': return {loading: false, err: action.err}; default: return state; } };
import cartIcon from './cart-icon.component.jsx' export default cartIcon;
//todo react year changer import * as React from 'react' import { Range } from 'react-range' import ReactDOM from 'react-dom' import EventEmitter from './eventEmitter.js' //import RangeControl from './rangeControl' class SuperSimple extends React.Component { state = { values: [0, 100] } render() { return ( <div style={{ display: 'flex', justifyContent: 'center', flexWrap: 'wrap', margin: '0 2em', marginRight: '8.5em', }} > <Range values={this.state.values} step={1} min={0} max={100} onChange={(values) => this.setState({ values })} renderTrack={({ props, children }) => ( <div onMouseDown={props.onMouseDown} onTouchStart={props.onTouchStart} style={{ ...props.style, height: '31px', display: 'flex', width: '100%', }} > <div ref={props.ref} style={{ height: '5px', width: '100%', borderRadius: '4px', alignSelf: 'center', }} > {children} </div> </div> )} renderThumb={({ props, isDragged }) => ( <div {...props} style={{ ...props.style, height: '34px', width: '34px', borderRadius: '2px', backgroundColor: 'whitesmoke', display: 'flex', justifyContent: 'center', alignItems: 'center', boxShadow: '0px 2px 6px #AAA', }} > <div style={{ height: '16px', width: '5px', backgroundColor: isDragged ? '#548BF4' : 'rgba(0,162,232,0.7)', }} /> </div> )} /> </div> ) } } export default class YearControl extends EventEmitter { constructor() { super() //first must window.yearControl = this const simple = <SuperSimple /> console.log('before render YearControl') ReactDOM.render(simple, document.getElementById('events-info-container')) } static create() { return new YearControl() } } //https://codesandbox.io/s/rlp1j1183n?file=/src/index.js:240-2385
// create a custom div element class MyDiv extends HTMLDivElement { constructor() { // Always call super first in constructor super(); this.style.backgroundColor = "yellow"; } setValue(htmlCode) { this.innerHTML = htmlCode } } // register custom elements : https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements customElements.define('my-div', MyDiv, { extends: 'div' });
import React from 'react' import {NavLink} from "react-router-dom"; const activeStyle = { fontWeight: '700' } export default class Footer extends React.Component{ render() { return ( <footer className='footer'> <nav> <ul className='footer-list'> <li className='footer-item'> <NavLink exact to='/' activeStyle={activeStyle} onClick={() => window.scrollTo(0, 0)}> <img src={require('../img/home.svg')} width='20' height='20' alt='Перейти на главную'/> <span>Главная</span> </NavLink> </li> <li className='footer-item'> <NavLink to='/form' activeStyle={activeStyle} onClick={() => window.scrollTo(0, 0)}> <img src={require('../img/edit.svg')} width='20' height='20' alt='Перейти на страницу записи'/> <span>Записаться</span> </NavLink> </li> <li className='footer-item'> <NavLink to='/education' activeStyle={activeStyle} onClick={() => window.scrollTo(0, 0)}> <img src={require('../img/mortarboard.svg')} width='20' height='20' alt='Перейти на страницу обучения'/> <span>Обучение</span> </NavLink> </li> <li className='footer-item'> <NavLink to='/galery' activeStyle={activeStyle} onClick={() => window.scrollTo(0, 0)}> <img src={require('../img/gallery.svg')} width='20' height='20' alt='Перейти в галерею'/> <span>Мои работы</span> </NavLink> </li> </ul> </nav> </footer> ) } }