text
stringlengths
7
3.69M
//07.Write a function that returns the index of the first element in array that is larger than its neighbours or -1, if there’s no such element. //Use the function from the previous exercise. 'use strict'; var numbers = [1, 2, 3, 4, 6, 5, 7, 8, 9]; console.log(firstLargerThanNeighbours(numbers)); function firstLargerThanNeighbours(numbers) { var i, len; for (i = 0, len = numbers.length; i < len; i += 1) { if (largerThanNeighbours(numbers, i)) { return i; } } return -1; } function largerThanNeighbours(numbers, index){ if (index < 1 || index >= numbers.length - 1) { return false; } return numbers[index] > numbers[index + 1] && numbers[index] > numbers[index - 1]; }
import React, { useContext } from "react"; import NavBar from "../navigation/NavBar"; import GifSearchResultList from "../components/GifSearchResultList/GifSearchResultList"; import AppContext from "../context/context"; const GifSearch = () => { const context = useContext(AppContext); const { gifSearchFunction, gifInput, gifs } = context; return ( <> <NavBar /> <h1>Gif Searcher</h1> <form onSubmit={gifSearchFunction}> <input type="text" name="gifInput" id="gifInput" placeholder="e.g cat" value="cat" /> <button type="submit">Search</button> </form> {/* <GifSearchResultList gifInput={gifInput} /> */} <img src={`${gifs}`} alt="" /> </> ); }; export default GifSearch;
define(['knockout', 'jquery'], function(ko, $) { 'use strict'; //TODO nisabhar shouldn't this code be under tasksearch ? /** * KO Binding for Auto suggest. * @type {{init: ko.bindingHandlers.suggestItems.init}} */ ko.bindingHandlers.suggestItems = { init: function(element, valueAccessor, allBindingAccessor, viewModel) { var autoSuggestions = valueAccessor() || []; var itemSize = autoSuggestions.length; var selIndex = 0; var $s1 = $(element); //wrap the input text with a div and then append a div with ul for the menu autoSuggestions $(element).parent() .append('<div id=\'srchmenuroot\' class=\'pcs-ts-autosuggestion-menu-root\'><ul class=\'pcs-ts-autosuggestion-menu-ul\'></ul></div>'); //for each item passed, append a new li to the ul $(element).siblings().css({ top: 26 }); //function to register mouse hover events on all list autoSuggestions function registerEventsOnListItems(lis, items) { lis.hover(function() { lis.removeClass('pcs-ts-autosuggestion-menuitem-selected'); $(this).addClass('pcs-ts-autosuggestion-menuitem-selected'); selIndex = lis.index(this) + 1; }).mousedown(function() { //calling the function passed to the items array as callback items[selIndex - 1].action({ element: $(element), selectedAutoSuggestion: items[selIndex - 1] }); }); } function initItems(itemArr) { var lis = ''; if (itemArr) { itemArr.forEach(function(item) { var label = item.label; var styleClass = item.styleClass; lis += '<li class=\'pcs-ts-autosuggestion-menu-items\'><span class=\'' + styleClass + '\'></span>' + '<span class=\'pcs-ts-autosuggestion-menu-item\'>' + label + '</span></li>'; }); var ul = $(element).parent().find('ul'); $(ul).empty().append(lis); } var $lis = $(element).parent().find('li'); registerEventsOnListItems($lis, itemArr); } //attach event handlers //attach focus and blur handler for input text $(element).focus(function() { $(this).siblings().width($(this).width() + 5); $('#srchmenuroot').show(); }).blur(function() { $(this).siblings().hide(); }); //attach key handlers $s1.keyup(function(event) { var $lis = $s1.parent().find('li'); var code = event.keyCode || event.which; switch (code) { case 13: //enter key if ($(element).siblings().css('display') !== 'none') { var result = {}; var selectedItemIndex = selIndex; $('li:nth-child(' + selIndex + ')', $(element).parent()).removeClass('pcs-ts-autosuggestion-menuitem-selected'); selIndex = 0; $(element).siblings().hide(); result.element = $(element); if (selectedItemIndex === 0) { result.selectedAutoSuggestion = autoSuggestions[selectedItemIndex]; autoSuggestions[selectedItemIndex].action(result); } else { result.selectedAutoSuggestion = autoSuggestions[selectedItemIndex - 1]; autoSuggestions[selectedItemIndex - 1].action(result); } } break; case 27: //escape key $('li:nth-child(' + selIndex + ')', $(element).parent()).removeClass('pcs-ts-autosuggestion-menuitem-selected'); selIndex = 0; $(element).siblings().hide(); break; case 38: //up if ($(element).siblings().css('display') !== 'none') { selIndex = (selIndex > 1) ? selIndex - 1 : itemSize; $lis.removeClass('pcs-ts-autosuggestion-menuitem-selected'); $('li:nth-child(' + selIndex + ')', $(element).parent()).addClass('pcs-ts-autosuggestion-menuitem-selected'); } break; case 40: //down if ($(element).siblings().css('display') !== 'none') { selIndex = (selIndex < itemSize) ? selIndex + 1 : 1; $lis.removeClass('pcs-ts-autosuggestion-menuitem-selected'); $('li:nth-child(' + selIndex + ')', $(element).parent()).addClass('pcs-ts-autosuggestion-menuitem-selected'); } break; default: var isCallBackFunctionRefreshAutoSuggestionDefined = typeof viewModel.refreshAutoSuggestions === 'function'; if (isCallBackFunctionRefreshAutoSuggestionDefined) { var refreshedAutoSuggestions = viewModel.refreshAutoSuggestions(event.currentTarget.value); autoSuggestions = refreshedAutoSuggestions || {}; selIndex = 0; itemSize = autoSuggestions.length; } initItems(autoSuggestions); break; } }); } }; });
'use strict'; define(['jquery'], function ($) { return { init: function () { var inIframe = window != window.top; // I dont know why platform sends me those strange json incompatible value and pretends it is json... // so now I need to do some dirty work here -- clean the dnnVariable and make it json compatible var v = inIframe ? window.parent.document.getElementById('__dnnVariable').value : ''; // remove the first ` v = v.replace('`', ''); // change the rest of ` to " var m = new RegExp('`', 'g'); v = v.replace(m, '"'); // finish clean dnnVariable var dnnVariable = v ? $.parseJSON(v) : null; var tabId = dnnVariable ? dnnVariable['sf_tabId'] : ''; var siteRoot = dnnVariable ? dnnVariable['sf_siteRoot'] : ''; var antiForgeryToken = inIframe ? window.parent.document.getElementsByName('__RequestVerificationToken')[0].value : ''; var currentUserId = inIframe ? window.parent.document.getElementsByName('__personaBarUserId')[0].value : ''; var currentCulture = inIframe ? window.parent.document.getElementsByName('__personaBarCulture')[0].value : 'en-us'; var resxTimeStamp = inIframe ? window.parent.document.getElementsByName('__personaBarResourceFileModifiedTime')[0].value : ''; var avatarUrl = currentUserId ? siteRoot + 'profilepic.ashx?userId=' + currentUserId + '&h=64&w=64' : ''; var logOff = inIframe ? window.parent.document.getElementsByName('__personaBarLogOff')[0].value : ''; var socialModule = inIframe ? window.parent.document.getElementsByName('__personaBarMainSocialModuleOnPage')[0].value : ''; var userSettings = inIframe ? window.parent['__personaBarUserSettings'] : null; var hasValidLicenseOrTrial = inIframe ? window.parent.document.getElementsByName('__personaBarHasValidLicenseOrTrial')[0].value == 'True' : true; var javascriptMainModuleNames = inIframe ? window.parent.document.getElementsByName('__javascriptMainModuleNames')[0].value : ''; var userMode = inIframe ? window.parent.document.getElementsByName('__userMode')[0].value : 'View'; var debugMode = window.top['dnn'] && (window.top['dnn'].getVar('pb_debugMode') == "true"); var rootFolderId = inIframe ? window.parent.document.getElementsByName('__rootFolderId')[0].value : ''; var defaultFolderMappingId = inIframe ? window.parent.document.getElementsByName('__defaultFolderMappingId')[0].value : ''; var fileUploadClientId = inIframe ? window.parent.document.getElementsByName('__fileUploadClientId')[0].value : ''; var sku = inIframe ? window.parent.document.getElementsByName('__sku')[0].value : ''; var isCommunityManager = inIframe ? window.parent.document.getElementsByName('__isCommunityManager')[0].value == 'true' : false; return { tabId: tabId, siteRoot: siteRoot, antiForgeryToken: antiForgeryToken, culture: currentCulture, resxTimeStamp: resxTimeStamp, avatarUrl: avatarUrl, logOff: logOff, socialModule: socialModule, userSettings: userSettings, hasValidLicenseOrTrial: hasValidLicenseOrTrial, javascriptMainModuleNames: javascriptMainModuleNames, userMode: userMode, debugMode: debugMode, rootFolderId: rootFolderId, defaultFolderMappingId: defaultFolderMappingId, fileUploadClientId: fileUploadClientId, sku: sku, isCommunityManager: isCommunityManager }; } }; });
({ choseVolunteer : function(cmp, event) { let volunteers = cmp.get('v.volunteers'); let idx = event.getSource().get('v.value'); let chosenVolunteer = volunteers[idx]; cmp.set('v.chosenVolunteer', chosenVolunteer); this.resetVolunteerSearch(cmp); let eventParams = { 'selectedObject' : chosenVolunteer.id, 'action' : 'SELECTION' }; this.fireEvent(cmp, eventParams); }, clearNameInput : function(cmp) { cmp.set('v.userNameInput', ''); }, displayNoVolunteerResults : function(cmp) { cmp.set('v.volunteers', ''); cmp.set('v.showVolunteersPicklist', false); cmp.set('v.showNoVolunteers', true); }, doNameSearch : function(cmp) { let action = cmp.get('c.searchVolunteers'); let nameInput = cmp.get('v.userNameInput'); nameInput = nameInput ? nameInput.trim() : ''; if (!nameInput.length) { cmp.set('v.volunteers', []); return; } if (nameInput.length < 3) { return; } action.setParams({ 'nameInput' : nameInput }); action.setCallback(this, function(response) { let state = response.getState(); if ('SUCCESS' === state) { cmp.set('v.volunteers', response.getReturnValue()); this.handleVolunteerResultsChange(cmp); } else if ('ERROR' === state) { cmp.set('v.volunteers', []); console.error('error searching volunteers', response.getError()); } }); $A.enqueueAction(action); }, fireEvent : function(cmp, params) { var typeAheadEvent = cmp.getEvent('typeAheadEvent'); typeAheadEvent.setParams(params); typeAheadEvent.fire(); }, handleNameSearchChange : function(cmp) { var delay = 400; var timer = cmp.get('v.timer'); var that = this; clearTimeout(timer); timer = window.setTimeout( $A.getCallback(function(){ that.doNameSearch(cmp); }), delay ); cmp.set('v.timer', timer); }, handleVolunteerResultsChange : function(cmp) { let volunteers = cmp.get('v.volunteers'); let hasVolunteers = (volunteers && volunteers.length); if (!hasVolunteers) { this.resetChosenVolunteer(cmp); cmp.set('v.showVolunteersPicklist', false); } cmp.set('v.showVolunteersPicklist', hasVolunteers); cmp.set('v.showNoVolunteers', !hasVolunteers); }, resetChosenVolunteer : function(cmp) { cmp.set('v.chosenVolunteer', ''); var eventParams = { 'selectedObject' : null, 'action' : 'SELECTION' }; this.fireEvent(cmp, eventParams); }, resetVolunteerSearch : function(cmp) { cmp.set('v.showVolunteersPicklist', false); cmp.set('v.showNoVolunteers', false); }, });
const express = require("express"); const router = express.Router(); const User = require("../models/user"); router.post("/",async(req,res)=> { // creaet user and let userToBeCreated = new User ({ username: req.body.username, emial: req.body.emial, password:req.body.password }); await userToBeCreated.save(); return res.send({ username:userToBeCreated.username, emial:userToBeCreated.emial }); }) module.exports = router;
const dataService = require('../data.service')(); module.exports = (server) => { server.route({ method: 'GET', path:'/api/tasks', handler: (request, reply) => { dataService.getAllTasks() .then(data => reply({data})) .catch(error => reply({error})); } }); server.route({ method: 'GET', path:'/api/tasks/{taskId}', handler: (request, reply) => { const { taskId } = request.params; dataService.getTaskById(taskId) .then(data => reply({data})) .catch(error => reply({error})); } }); server.route({ method: 'POST', path:'/api/tasks', handler: (request, reply) => { const { payload } = request; dataService.addNewTask(payload) .then(data => reply({status: 201, data})) .catch(error => reply({error})); } }); server.route({ method: 'DELETE', path:'/api/tasks/{taskId}', handler: (request, reply) => { const { taskId } = request.params; dataService .removeTask(taskId) .then(data => reply({status: 200, data})) .catch(error => reply({error})); } }); server.route({ method: 'PUT', path:'/api/tasks/{taskId}', handler: (request, reply) => { const { taskId } = request.params; const { payload } = request; dataService .updateTask(taskId, payload) .then(updated => reply({status: 200, updated: payload})) .catch(error => reply({error})); } }); };
function AddItem(itemId) { var addUrl = 'addItem.php?v=2&itemId=' + itemId; $('.addButton').prop('disabled', true); $.getJSON(addUrl).done(function (data) { try { if (data == -3) { if (confirm("This item has already been added to your cart. Would you like an additional one?")) { $.getJSON(addUrl + '&confirm=yes').done(function (data) { if (data < 0) { alert("An unknown error has occurred. Please try your request later."); } else { UpdateCartSize(data); } }).fail(function() { alert("An unknown error has occurred. Please try your request later."); }).always(function() { $('.addButton').prop('disabled', false); }); } } else if (data < 0) { alert("An unknown error has occurred. Please try your request later."); } else { UpdateCartSize(data); } } finally { if (data != -3) $('.addButton').prop('disabled', false); } }).fail(function() { $('.addButton').prop('disabled', false); alert("An unknown error has occurred. Please try your request later."); }); } function UpdateCartSize(newCartSize) { $("#cartSize").html("" + newCartSize); $("#cartItemWord").html(newCartSize == 1 ? "item" : "items"); }
import { StyleSheet, Dimensions } from "react-native"; const getWidth = Dimensions.get("screen").width; export default StyleSheet.create({ body: { flex: 1, flexDirection: "column", paddingTop: 30, paddingBottom: 20, backgroundColor: "#fff", }, mh15: { marginHorizontal: 15, }, headerSectionWrap: { display: "flex", justifyContent: "space-between", flexDirection: "row", alignItems: "center", }, headerSectionLeft: { display: "flex", flexDirection: "row", alignItems: "center", }, imgAvatr: { width: 50, height: 50, resizeMode: "cover", }, white: { color: "#fff", }, smTextWrap: { display: "flex", flexDirection: "column", marginLeft: 10, }, smallTxt: { fontSize: 14, }, split: { display: "flex", flexDirection: "row", justifyContent: "space-between", alignItems: "center", }, mediumTxt: { fontSize: 18, }, largeTxt: { fontSize: 22, }, notifWrap: { width: 50, height: 50, display: "flex", justifyContent: "center", alignItems: "center", borderRadius: 10, }, herobanner: { height: 150, display: "flex", justifyContent: "center", paddingHorizontal: 30, paddingVertical: 20, borderRadius: 20, backgroundColor: "#2a4043", }, heroimg: { position: "absolute", right: 5, bottom: 15, width: 200, height: 250, }, mainText: { fontSize: 18, }, favoriteWrap: { display: "flex", justifyContent: "center", alignItems: "center", width: 35, height: 35, backgroundColor: "pink", borderRadius: 10, marginBottom: 12, }, scrollCards: { flex: 1, justifyContent: "center", width: getWidth / 1.5, height: 200, borderRadius: 10, paddingHorizontal: 15, backgroundColor: "rgba(204, 204, 204, 0.3)", margin: 10, }, });
const db = require('../db/dreckl') const abwesenheitDB = db.abwesenheit const getAbwesenheit = (req, res) => { abwesenheitDB.read((abwesenheit) => { res.json(abwesenheit) }) } module.exports = getAbwesenheit
const axios = require('axios'); const Response = require('../response/response'); const RESPONSE_CODE = require('../response/responseCode'); const extractor = require('../utils/extractor'); class APIcontroller { getPrices (req, res, next) { return new Promise((resolve, reject) => { axios.all([ axios.get('https://crix-api-endpoint.upbit.com/v1/crix/candles/days/?code=CRIX.UPBIT.KRW-BTC'), axios.get('https://crix-api-endpoint.upbit.com/v1/crix/candles/days/?code=CRIX.UPBIT.KRW-ETH'), axios.get('https://crix-api-endpoint.upbit.com/v1/crix/candles/days/?code=CRIX.UPBIT.KRW-XRP'), axios.get('https://crix-api-endpoint.upbit.com/v1/crix/candles/days/?code=CRIX.UPBIT.KRW-EOS') ]).then((result) => { resolve(result); }).catch((err) => { reject(err); }) }).then((result) => { let allData = extractor.extraction(result); res.status(200).json((new Response(RESPONSE_CODE.SUCCESS, 'Request success', allData).value())); return allData }).catch((err) => { err.status = 500; next(err); console.log(err); // res.status(500).json((new Response(RESPONSE_CODE.FAIL, 'Request failed', err).value())); }); }; }; module.exports = new APIcontroller();
const should = require('should'); const supertest = require('supertest'); const _ = require('lodash'); const testUtils = require('../../utils'); const config = require('../../../core/shared/config'); const localUtils = require('./utils'); const ghost = testUtils.startGhost; describe('Admin API key authentication', function () { let request; before(function () { return ghost() .then(function () { request = supertest.agent(config.get('url')); }) .then(function () { return testUtils.initFixtures('api_keys'); }); }); it('Can not access endpoint without a token header', function () { return request.get(localUtils.API.getApiQuery('posts/')) .set('Authorization', `Ghost`) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(401); }); it('Can not access endpoint with a wrong endpoint token', function () { return request.get(localUtils.API.getApiQuery('posts/')) .set('Authorization', `Ghost ${localUtils.getValidAdminToken('https://wrong.com')}`) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(401); }); it('Can access browse endpoint with correct token', function () { return request.get(localUtils.API.getApiQuery('posts/')) .set('Authorization', `Ghost ${localUtils.getValidAdminToken('/canary/admin/')}`) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200); }); it('Can create post', function () { const post = { title: 'Post created with api_key' }; return request .post(localUtils.API.getApiQuery('posts/?include=authors')) .set('Origin', config.get('url')) .set('Authorization', `Ghost ${localUtils.getValidAdminToken('/canary/admin/')}`) .send({ posts: [post] }) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(201) .then((res) => { // falls back to owner user res.body.posts[0].authors.length.should.eql(1); }); }); it('Can read users', function () { return request .get(localUtils.API.getApiQuery('users/')) .set('Origin', config.get('url')) .set('Authorization', `Ghost ${localUtils.getValidAdminToken('/canary/admin/')}`) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .then((res) => { localUtils.API.checkResponse(res.body.users[0], 'user'); }); }); });
Template.MyPolls.onCreated(function() { var self = this; self.autorun(function() { self.subscribe('polls'); }); }); Template.MyPolls.helpers({ polls: function() { return Polls.find({author: Meteor.userId()}); } })
var operator=null var inputValueMemo= 0// para guardar el resultado del calculo function getContentClick(event) { const value = event.target.outerText//puede se innerHTML filterAction(value) } const filterAction = value => { value === "0" ? addNumberInput(0) : null value === "1" ? addNumberInput(1) : null value === "2" ? addNumberInput(2) : null value === "3" ? addNumberInput(3) : null value === "4" ? addNumberInput(4) : null value === "5" ? addNumberInput(5) : null value === "6" ? addNumberInput(6) : null value === "7" ? addNumberInput(7) : null value === "8" ? addNumberInput(8) : null value === "9" ? addNumberInput(9) : null value === "," ? addNumberInput(",") : null value === "+" ? setOperation("+") : null value === "-" ? setOperation("-") : null value === "X" ? setOperation("*") : null value === "/" ? setOperation("/") : null value === "%" ? setOperation("%") : null value === "+/-"?setOperation("+/-") : null value=== "="?calculation():null value=== "AC"?resetCalculator():null } function addNumberInput(value) { const inputScreen = document.getElementsByClassName("calculator__screen")[0] const inputValue = inputScreen.value if (inputValue === "0" && inputValue.length === 1 && value !== ",") inputScreen.value = value else if (inputScreen.value === "" && value===","){ inputScreen.value = 0 + value } else{ inputScreen.value = inputValue + value } } function setOperation(operator){ const inputScreenValue = document.getElementsByClassName("calculator__screen")[0] this.operator=operator if (inputScreenValue !=0){ calculation() } } function calculation(){ const inputScreen = document.getElementsByClassName("calculator__screen")[0] let valueOne= transformCommaToPoint (this.inputValueMemo) let valueTwo= transformCommaToPoint (inputScreen.value) let total=0 //operaciones if (this.operator==="+" && inputScreen.value!==""){ total=valueOne+valueTwo } if (this.operator==="-" && inputScreen.value!==""){ if (valueOne !== 0){ total=valueOne-valueTwo }else{ total=valueTwo } } if (this.operator==="*" && inputScreen.value!==""){ if (valueOne !== 0){ total=valueOne * valueTwo }else{ total=valueTwo } } if (this.operator==="/" && inputScreen.value!==""){ if (valueOne !== 0){ total=valueOne/valueTwo }else{ total=valueTwo } } if (this.operator==="%" && inputScreen.value!==""){ total=valueTwo/100 } if (this.operator==="+/-" && inputScreen.value!==""){ if(valueTwo>0){ total=-valueTwo } } total=transformPointToComma(total) this.inputValueMemo=total inputScreen.value="" inputScreen.placeholder=total } const resetCalculator=()=>{ const inputScreen = document.getElementsByClassName("calculator__screen")[0] inputScreen.value=0 this.inputValueMemo=0 this.operator=null console.log(inputScreen) } function transformCommaToPoint(value){ if(typeof value !=="number"){ let resultTransform=value.replace(',','.') return parseFloat(resultTransform) } return value } function transformPointToComma(value){ let resultTransform=value.toString() resultTransform=resultTransform.replace('.',',') return resultTransform }
import React from 'react'; import { NavLink } from 'react-router-dom' class Sidebar extends React.Component { render() { return ( <ul className="sidebar--nav"> <NavLink to="/timeline" activeClassName="active"> <li className="sidebar--nav--thumb"><i className="sidebar--nav-thumb-icon fa fa-calendar" aria-hidden="true"></i></li> </NavLink> <NavLink to="/cash" activeClassName="active"> <li className="sidebar--nav--thumb"><i className="sidebar--nav-thumb-icon fa fa-credit-card" aria-hidden="true"></i></li> </NavLink> </ul> ); } } export default Sidebar;
import React from "react"; import BoardItem from "./BarodItem"; import "./Board.css"; import more from "../images/more.png"; import { Link } from "react-router-dom"; // import { Image, Item } from "semantic-ui-react"; function Board({ name, data, cat }) { return ( <div className="board"> <div className="board_header"> <Link to={"/" + cat} className="board__title"> {name} </Link> <Link to={"/" + cat} className="board__more"> <img src={more} alt="more" /> </Link> </div> <div className="board_list"> <ul> {data .slice(0) .reverse() .map(item => { return <BoardItem key={item.number} item={item} cat={cat} />; })} {/* <Item.Group> {data .slice(0) .reverse() .map(item => { return ( <Item> <Item.Image size="tiny" src="https://www.economicdevelopmentwinnipeg.com/uploads/blog_post/blog_post_image_835.t1552920467.jpg" /> <Item.Content> <Item.Header as="a">Hello</Item.Header> <Item.Meta>Description</Item.Meta> <Item.Description> {item.body.substring(0, 100)} </Item.Description> <Item.Extra>Additional Details</Item.Extra> </Item.Content> </Item> ); })} </Item.Group> */} </ul> </div> </div> ); } export default Board;
/** * 화면 초기화 - 화면 로드시 자동 호출 됨 */ function _Initialize() { // 단위화면에서 사용될 일반 전역 변수 정의 // $NC.setGlobalVar({ }); var ua = navigator.userAgent; if (ua.indexOf('Trident') != -1) { $('.print').css('position', 'static'); } } /** * 화면 리사이즈 Offset 세팅 */ function _SetResizeOffset() { } /** * Window Resize Event - Window Size 조정시 호출 됨 */ function _OnResize(parent) { var clientWidth = parent.width(); var clientHeight = parent.height(); $("#divProgressBar").css({ "top": Math.ceil((clientHeight - 8) / 2), "left": Math.ceil((clientWidth - 378) / 2), }).progressbar({ value: false }).children().css("background-color", "#e6e6e6"); $("#divProgress").css({ "top": Math.ceil((clientHeight - 30) / 2), "left": Math.ceil((clientWidth - 400) / 2) }); } /** * Load Complete Event */ function _OnPopupOpen() { var params = { P_REPORT_FILE: $NC.G_VAR.userData.reportDoc, P_QUERY_ID: $NC.G_VAR.userData.queryId, P_QUERY_PARAMS: "", P_CHECKED_VALUE: "", P_PRINTER_NM: "", P_SILENT_PRINTER_NM: "", P_INTERNAL_QUERY_YN: "N", P_PRINT_COPY: 1, P_CHECKED_VALUE: "", P_OTHER_TEMPO: "", P_SILENT_PRINT_YN: "N", PRINT_DIV: $NC.G_VAR.userData.PRINT_DIV }; if (!$NC.isNull($NC.G_VAR.userData.checkedValue)) { params.P_CHECKED_VALUE = $NC.G_VAR.userData.checkedValue; } if (!$NC.isNull($NC.G_VAR.userData.otherTempo)) { params.P_OTHER_TEMPO = $NC.G_VAR.userData.otherTempo; } if (!$NC.isNull($NC.G_VAR.userData.printerName)) { params.P_PRINTER_NM = $NC.G_VAR.userData.printerName; } if (!$NC.isNull($NC.G_VAR.userData.silentPrinterName)) { params.P_SILENT_PRINTER_NM = $NC.G_VAR.userData.silentPrinterName; } if (!$NC.isNull($NC.G_VAR.userData.queryParams)) { params.P_QUERY_PARAMS = $NC.getParams($NC.G_VAR.userData.queryParams); } if (!$NC.isNull($NC.G_VAR.userData.internalQueryYn)) { params.P_INTERNAL_QUERY_YN = $NC.G_VAR.userData.internalQueryYn; } if (!$NC.isNull($NC.G_VAR.userData.printCopy)) { params.P_PRINT_COPY = $NC.G_VAR.userData.printCopy; } params.P_USER_ID = $NC.G_USERINFO.USER_ID; params.P_USER_NM = $NC.G_USERINFO.USER_NM; params.P_PRINT_LI_BILL = $NC.G_USERINFO.PRINT_LI_BILL; params.P_PRINT_LO_BILL = $NC.G_USERINFO.PRINT_LO_BILL; params.P_PRINT_RI_BILL = $NC.G_USERINFO.PRINT_RI_BILL; params.P_PRINT_RO_BILL = $NC.G_USERINFO.PRINT_RO_BILL; params.P_PRINT_LO_BOX = $NC.G_USERINFO.PRINT_LO_BOX; params.P_PRINT_WB_NO = $NC.G_USERINFO.PRINT_WB_NO; params.P_PRINT_CARD = $NC.G_USERINFO.PRINT_CARD; params.P_PRINT_SHIP_ID = $NC.G_USERINFO.PRINT_SHIP_ID; params.P_PRINT_LOCATION_ID = $NC.G_USERINFO.PRINT_LOCATION_ID; params.P_PRINT_INBOUND_SEQ = $NC.G_USERINFO.PRINT_INBOUND_SEQ; params = $NC.getParams(params, false); // IE 문제로 body 크기지정 $("body").css({ width: $NC.G_JWINDOW.get("width"), height: $NC.G_JWINDOW.get("height") }); reportPopupName = "reportPreviewIFrame"; var reportForm = $("#reportForm"); reportForm.empty().attr({ method: "post", action: "/report.do", target: reportPopupName }); for ( var paramName in params) { var paramValue = params[paramName]; $("<input/>", { id: paramName, type: "hidden", name: paramName, value: paramValue }).appendTo(reportForm); } reportForm.submit(); if ($.browser.msie && $.browser.versionNumber < 11) { $("#reportPreviewIFrame")[0].onreadystatechange = function() { var localIFrame = $("#reportPreviewIFrame"); var readyState = localIFrame[0].readyState; if (readyState != "loading" && readyState != "uninitialized") { localIFrame[0].onreadystatechange = null; $("#divProgressBar").progressbar("destroy").remove(); $("#divProgress").remove(); var ajaxData = null; try { $(localIFrame[0].contentDocument.body).css("color", "gray").text(); } catch (e) { } if (!$NC.isNull(ajaxData)) { $NC.onError(ajaxData); setTimeout(function() { onCancel(); }, 500); } } }; } else { $("#reportPreviewIFrame").bind( "load", function() { $("#divProgressBar").progressbar("destroy").remove(); $("#divProgress").remove(); var ajaxData = null; try { ajaxData = $($("#reportPreviewIFrame")[0].contentDocument.body).css("color", "gray").text(); } catch (e) { } if (!$NC.isNull(ajaxData)) { $NC.onError(ajaxData); setTimeout(function() { onCancel(); }, 500); } $NC.resizeContainer("#reportPreviewIFrame", $("#ifraCommonPopupPrintPreview").width(), $( "#ifraCommonPopupPrintPreview").height()); }); } // 라벨출력시 출력버튼 표시 if ($NC.G_VAR.userData.print_div == '2') { $('#btnPrint').parent().show().on('click', function(){ $NC.G_VAR.userData.printFn(); }) } } /** * 닫기,취소버튼 클릭 이벤트 */ function onCancel() { $NC.setPopupCloseAction("CANCEL"); $NC.onPopupClose(); } /** * 저장,확인버튼 클릭 이벤트 */ function onClose() { $NC.setPopupCloseAction("OK"); $NC.onPopupClose(); }
/** * Created by hui.sun on 15/12/10. */ /** * 4pl Grid thead配置 * check:true //使用checkbox 注(选中后对象中增加pl4GridCheckbox.checked:true) * checkAll:true //使用全选功能 * field:’id’ //字段名(用于绑定) * name:’序号’ //表头标题名 * link:{ * url:’/aaa/{id}’ //a标签跳转 {id}为参数 (与click只存在一个) * click:’test’ //点击事件方法 参数test(index(当前索引),item(当前对象)) * } * input:true //使用input 注(不设置默认普通文本) * type:text //与input一起使用 注(type:operate为操作项将不绑定field,与按钮配合使用) * buttons:[{ * text:’收货’, //显示文本 * call:’tackGoods’, //点击事件 参数tackGoods(index(当前索引),item(当前对象)) * type:’link button’ //类型 link:a标签 button:按钮 * state:'checkstorage', //跳转路由 注(只有当后台传回按钮数据op.butType=link 才会跳转) * style:’’ //设置样式 * }] //启用按钮 与type:operate配合使用 可多个按钮 * style:’width:10px’ //设置样式 * */ 'use strict'; define(['../../../app'], function(app) { app.factory('inventoryQuery', ['$http', '$q', '$filter', 'HOST', function($http, $q, $filter, HOST) { return { getThead: function() { return [{ field: 'pl4GridCount', name: '序号', type: 'pl4GridCount' }, { field: 'ckName', name: '仓库' },{ field: 'updateTime', name: '库存更新日期' },{ field: 'supliers', name: '供应商' },{ field: 'customer', name: '客户' }, { field: 'sku', name: '商品编码' }, { field: 'goodsType', name: '品类' }, { field: 'brand', name: '商品品牌' }, { field: 'goodsName', name: '商品名称' }, { field: 'model', name: '型号' }, { field: 'meaUnit', name: '计量单位' }, { field: 'factoryCode', name: '出厂编码' }, /*{ field: 'lowStock', name: '安全库存' }, { field: 'highStock', name: '库存上限' },*/ { field: 'factStock', name: '实际库存' },{ field: 'kyStock', name: '可用库存' }, { field: 'damageStock', name: '残损品库存' }, // { // field: 'ckId', // name: '隐藏列' //}, //{ // field: 'state', // name: '库存状态' // }, { field: 'sentCounts', name: '在途数量' }, { field: 'djStock', name: '冻结数量' }, { field: 'cost', name: '库存成本' } , { field: 'name11', name: '操作', type: 'operate',style:'width:50px;', buttons: [{ text: '日志', call: 'logModalCall', btnType: 'button', style: 'font-size:10px;' }] }] }, getLogThead: function(){ return [{ field: 'pl4GridCount', name: '序号', type: 'pl4GridCount' },{ field: 'changeType', name: '操作描述' }, { field: 'opUser', name: '操作人' }, { field: 'taskType', name: '变更原因' },{ field: 'taskId', name: '关联业务单号' }, { field: 'beforeStock', name: '变更前库存数量' }, { field: 'changeCount', name: '变更数量' }, { field: 'afterStock', name: '变更后库存数量' }, { field: 'opTime', name: '操作时间' }] }, getSearch: function() { var deferred = $q.defer(); $http.post(HOST + '/inventoryMonitor/getDicLists',{}) .success(function(data) { deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; }, getDataTable: function(url, data) { //将param转换成json字符串 data.param = $filter('json')(data.param); var deferred = $q.defer(); $http.post(HOST + url, data) .success(function(data) { // console.log(data) deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; } } }]); });
const logic = require('../../../logic') const { expect } = require('chai') const { database, models } = require('wannadog-data') const { User, Dog } = models describe('logic - retrieve favorites', () => { before(() => database.connect('mongodb://172.17.0.2/wannadog-test')) let name, name2, breed, breed2, gender, gender2, size, size2, years, months, notes, notes2, neutered, neutered2, withDogs, withDogs2, withCats, withCats2, withChildren, withChildren2, chip, chip2, longitude, longitude2, latitude, latitude2 let userId, userName, surname, email, password, userLongitude, userLatitude, dogIdOne, dogIdTwo beforeEach(() => { const breedArray = ['Sussex Spaniel', 'Swedish Vallhund', 'Tibetan Mastiff'] const sizeArray = ['small', 'medium', 'large', 'xl'] name = `dogname-${Math.random()}` breed = `${breedArray[Math.floor(Math.random() * breedArray.length)]}` gender = Boolean(Math.round(Math.random())) size = `${sizeArray[Math.floor(Math.random() * sizeArray.length)]}` years = Math.round(Math.random() * 20) months = Math.round(Math.random() * 12) notes = `notes-${Math.random()}` neutered = Boolean(Math.round(Math.random())) withDogs = Boolean(Math.round(Math.random())) withCats = Boolean(Math.round(Math.random())) withChildren = Boolean(Math.round(Math.random())) chip = `chip - ${Math.random()}` longitude = Number((Math.random() * (-180, 180)).toFixed(3) * 1) latitude = Number((Math.random() * (-90, 90)).toFixed(3) * 1) name2 = `dogname-${Math.random()}` breed2 = `${breedArray[Math.floor(Math.random() * breedArray.length)]}` gender2 = Boolean(Math.round(Math.random())) size2 = `${sizeArray[Math.floor(Math.random() * sizeArray.length)]}` years = Math.round(Math.random() * 20) months = Math.round(Math.random() * 12) notes2 = `notes - ${Math.random()}` neutered2 = Boolean(Math.round(Math.random())) withDogs2 = Boolean(Math.round(Math.random())) withCats2 = Boolean(Math.round(Math.random())) withChildren2 = Boolean(Math.round(Math.random())) chip2 = `chip-${Math.random()}` longitude2 = Number((Math.random() * (-180, 180)).toFixed(3) * 1) latitude2 = Number((Math.random() * (-90, 90)).toFixed(3) * 1) userName = `name-${Math.random()}` surname = `surname-${Math.random()}` email = `email-${Math.random()}@mail.com` password = `password-${Math.random()} ` userLongitude = Number((Math.random() * (-180, 180)).toFixed(3) * 1) userLatitude = Number((Math.random() * (-90, 90)).toFixed(3) * 1) return (async () => { await User.deleteMany() await Dog.deleteMany() const dogOne = await Dog.create({ name, breed, gender, size, age: { years, months }, notes, neutered, withDogs, withCats, withChildren, chip, location: { coordinates: [longitude, latitude] } }) const dogTwo = await Dog.create({ name: name2, breed: breed2, gender: gender2, size: size2, age: { years, months }, notes: notes2, neutered: neutered2, withDogs: withDogs2, withCats: withCats2, withChildren: withChildren2, chip: chip2, location: { coordinates: [longitude2, latitude2] } }) dogIdOne = dogOne.id dogIdTwo = dogTwo.id const user = await User.create({ name: userName, surname, email, password, location: { coordinates: [userLongitude, userLatitude] } }) userId = user.id user.favorites.push(dogIdOne, dogIdTwo) await user.save() })() }) it('should retrieve a users favorite dogs', async () => { const result = await logic.retrieveFavorites(userId, email, password) expect(result).to.exist expect(result[0].id).to.equal(dogIdOne.toString()) expect(result[1].id).to.equal(dogIdTwo.toString()) }) after(() => database.disconnect()) })
import Boom from 'boom'; function findOneModel(request, reply) { let settings = request.route.settings.plugins.crudtacular; let model = new settings.model({ id : request.params[settings.idParam], }); let promise = model.fetch({ require : true, withRelated : settings.withRelated, }) .then(() => model.toJSON({ omitPivot : true })) .catch(settings.model.NotFoundError, () => { throw Boom.notFound(); }); reply(promise); } function findOneChild(request, reply) { let settings = request.route.settings.plugins.crudtacular; let model = new settings.model({ id : request.params[settings.idParam], }); let promise = model.fetch({ require : true, }) .then(() => { let child = model.related(settings.relationName); child.query((qb) => { qb.where({ id : request.params[settings.relationIdParam], }); }); return child .fetchOne({ require : true, withRelated : settings.withRelated, }) .catch(child.model.NotFoundError, () => { throw Boom.notFound(); }); }) .then((child) => child.toJSON({ omitPivot : true })) .catch(settings.model.NotFoundError, () => { throw Boom.notFound(); }); reply(promise); } export default function(request, reply) { let settings = request.route.settings.plugins.crudtacular; if (settings.type === 'model') { findOneModel(request, reply); } else { findOneChild(request, reply); } }
var person = { name: 'suho', age:'33', phone: '010-2222-2222', eat : function(food){ console.log(this.name +' 가 '+food+' 먹는다') } }; //person.eat('사과'); //함수가 호출 되는 방법에 따라 this는 달라진다. function a() { console.log(this); } //a(); var p = { run : function () { console.log(this); } }; //p.run(); //3.생성자 호출 function Abc() { console.log(this) } new Abc();
var express = require("express"), router = express.Router(), Appdata = require("../models/appdata"); var perPage = 8; //Sort by Publisher Route router.get("/sortbypublisher", function(req, res){ var pageQuerySort = parseInt(req.query.page); var pageNumberSort = pageQuerySort ? pageQuerySort : 1; Appdata.find({}).sort({publisher: 1}).skip((perPage * pageNumberSort) - perPage).limit(perPage).exec(function (err, allAppdata) { if(err){ console.log(err); } else{ Appdata.countDocuments().exec(function (err, count) { if (err) { console.log(err); } else { res.render("sortbypublisher", { newsdata: allAppdata, current: pageNumberSort, pages: Math.ceil(count / perPage) }); } }); } }); }); //Sort by Title router.get("/sortbytitle", function(req, res){ var pageQuerySort = parseInt(req.query.page); var pageNumberSort = pageQuerySort ? pageQuerySort : 1; Appdata.find({}).sort({articleTitle: 1}).skip((perPage * pageNumberSort) - perPage).limit(perPage).exec(function (err, allAppdata) { if(err){ console.log(err); } else{ Appdata.countDocuments().exec(function (err, count) { if (err) { console.log(err); } else { res.render("sortbytitle", { newsdata: allAppdata, current: pageNumberSort, pages: Math.ceil(count / perPage) }); } }); } }); }) module.exports = router;
var fs = require('fs'); var http = require('http'); http.createServer(function(req,res){ var nF = fs.createWriteStream("temp.txt"); var fileBytes = req.headers['content-length']; var uploadedBytes=0; req.pipe(nF); req.on('data',function(chunk){ uploadedBytes+=chunk.length; var progress = (uploadedBytes/fileBytes)*100; res.write("Progress: "+ parseInt(progress,10) + "%\n"); }); req.on('end',function(){ res.end('File uploaded'); }); }).listen(8080);
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery2 //= require jquery_ujs //= require turbolinks //= require_tree . function update_timestamps(){ $("TIME").timeago(); } $(document).on('ready page:load', function(){ //Keep track of the current page number current_page = $("MAIN").data('current-page'); console.log("Current page is: ", current_page) //Update the timestamps with the timeago plugin update_timestamps(); //Keep track of if we're loading a page loading = false //Loads the next page when called function load_next_page(){ if(loading) return; loading = true; //Increment the page number to be requested current_page++ console.log("Requesting page: ", current_page) //Put the UI into the loading state $("#more-button").hide() $("#loading-text").removeClass("hidden") //Ajax request to the same page, but updating the page number $.ajax("", { data: { //Anything in data ends up in the URL for GET requests page: current_page }, success: function(response){ //Display the new stories $(".stories").append(response); //Update timestamps update_timestamps(); //Remove the loading state from the UI $("#more-button").show() $("#loading-text").addClass("hidden") loading = false; } }) //Prevent the default action return false; } //Bind it to the button $("#more-button").click(load_next_page) //Perform autopaging on scroll $(window).scroll(function(){ var window_top = $(window).scrollTop(); var window_height = $(window).height(); var document_height = $(document).height(); //console.log(window_top, window_height, document_height) // Load a new page at 400% of window height var load_at = window_height * 4.00 if(document_height - window_height - window_top < load_at){ load_next_page() } }) })
export { default } from './BtnBox4.js'
var GooglePlaces = require('node-googleplaces'); var request = require('request'); var gpKey = 'AIzaSyAC12HMebBTpRFxesa8X0CVEtq6VwE8Qjk'; const places = new GooglePlaces(gpKey); const params = { location: '41.1833, -8.6', radius: 100 }; let type = 'restaurant'; /* // Callback places.nearbySearch(query, (err, res) => { console.log(res.body); }); // Promise places.nearbySearch(query).then((res) => { console.log(res.body); }); */ function setLocation(loc) { params.location = loc; } function gpNearbyRequest(cb) { var query = 'https://maps.googleapis.com\\/maps/api/place/nearbysearch/json?key=' + gpKey + '&location=' + params.location + '&radius=' + params.radius + '&type=' + type; request(query, function(error, response, body) { console.log('error:', error); // Print the error if one occurred console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received console.log('body:', body); // Print the HTML for the Google homepage. if (typeof cb === 'function') { cb(body); } }); } module.exports.setLocation = setLocation; module.exports.gpNearbyRequest = gpNearbyRequest;
/** * Primitivos (imutáveis) => string, number, boolean, undefined, null, bigint, symbol - valores são copiados * Referência (mutável) => array, object, function - valores apontam pra um local na memória * */
import React from "react" const Filters = () => { return ( <div className="filters"> <h3>Category</h3> <div className="underline"></div> <form> <div className="check"> <label for="recreation"> <input className="option-recreation" value="recreation" type="checkbox" id="recreation" name="Recreation" /> Recreation </label> </div> <div className="check"> <label for="trail"> <input type="checkbox" id="trail" name="trail" /> Trail </label> </div> <div className="check"> <label for="xc"> <input type="checkbox" id="xc" name="cross country" /> XC </label> </div> </form> <h3>Frame Material</h3> <div className="underline"></div> <form action=""> <div className="check"> <label for="composite"> <input type="checkbox" id="composite" name="composite" /> Composite/Carbon </label> </div> <div className="check"> <label for="aluminium"> <input type="checkbox" id="aluminium" name="aluminium" /> Aluminium </label> </div> </form> <h3>Wheel Size</h3> <div className="underline"></div> <form action=""> <div className="check"> <label for="large"> <input type="checkbox" id="large" name="large" /> 29" </label> </div> <div className="check"> <label for="medium"> <input type="checkbox" id="medium" name="medium" /> 27.5" </label> </div> <div className="check"> <label for="small"> <input type="checkbox" id="small" name="small" /> 26" </label> </div> </form> <h3>Collection</h3> <div className="underline"></div> <form action=""> <div className="check"> <label for="twenty"> <input type="checkbox" id="twenty" name="" /> 2020 </label> </div> <div className="check"> <label for="ninetheen"> <input type="checkbox" id="ninetheen" name="" /> 2019 </label> </div> </form> <h3>Sale</h3> <div className="underline"></div> <form action=""> <div className="check"> <label for="sale"> <input type="checkbox" id="sale" name="sale" /> On Sale </label> </div> </form> </div> ) } export default Filters
import Img1 from '../img/grocery.jpg'; import Img2 from '../img/fruits_and_vegs.jpg'; import Img3 from '../img/furniture.jpg'; import Img4 from '../img/electronics.jpg'; const Sdata = [ { id:"gp", imgsrc:Img1, title:"Grocery products", text:"We provide grocery products that are fresh and availabler at the lowest price in the market", btnColor:"btn btn-primary" }, { id:"fv", imgsrc:Img2, title:"Fruits and Vegetables", text:"Our fruits and vegetables are directly came from the local farmers of your locationa and are fresh", btnColor:"btn btn-danger" }, { id:"f", imgsrc:Img3, title:"Furniture", text:"We Provide best in class furniture for your home and it is built in local shops and stores", btnColor:"btn btn-success" }, { id:"e", imgsrc:Img4, title:"Electronics", text:"We provide best electonics Items in a very affordable cost which is minimum 5% less than market", btnColor:"btn btn-warning" } ] export default Sdata;
var Profile = require('./profile'); var renderer = require('./renderer'); var querystring = require('querystring'); var commonHeaders = { 'Content-Type': 'text/html'} function home(request, response) { if (request.url === '/') { if (request.method.toLowerCase() === 'get') { response.writeHead(200, commonHeaders); renderer.showPage('header', {}, response); renderer.showPage('search', {}, response); renderer.showPage('footer', {}, response); response.end(); } else { request.on('data', function(postBody) { var query = querystring.parse(postBody.toString()); response.writeHead(303, { 'location': '/' + query.username}); response.end(); }); } } } function profile(request, response) { var username = request.url.replace('/', ''); if (username.length > 0) { response.writeHead(200, commonHeaders); var userData = new Profile(username); userData.on('end', function(data) { var values = { avatarUrl: data.gravatar_url, username: data.profile_name, badges: data.badges.length, javascriptPoints: data.points.JavaScript } renderer.showPage('header', {}, response); renderer.showPage('profile', values, response); renderer.showPage('footer', {}, response); response.end(); }); userData.on('error', function(error) { renderer.showPage('header', {}, response); renderer.showPage('error', {errorMessage: error.message}, response); renderer.showPage('search', {}, response); renderer.showPage('footer', {}, response); response.end(); }); } } function static(request, response) { if (request.url.search('.css') !== -1) { response.writeHead(200, { 'Content-Type': 'text/css' }) renderer.serveFile(request.url, response); } } module.exports.home = home; module.exports.profile = profile; module.exports.static = static;
import {pageSize, pageSizeType, paginationConfig, searchConfig} from '../../globalConfig'; const filters = [ {key: 'orderNumber', title: '运单号', type: 'text'}, {key: 'customerDelegateCode', title: '委托号', type: 'text'}, {key: 'customerId', title: '客户', type: 'search', searchType: 'customer_all'}, {key: 'supplierId', title: '供应商', type: 'search', searchType: 'supplier_all'}, {key: 'carInfoId', title: '车牌号码', type: 'search', searchType:'car_all'}, {key: 'driverId', title: '司机', type: 'search', searchType:'driver_all'}, {key: 'businessType', title: '运输类型', type: 'select', dictionary: 'business_type'}, {key: 'customerServiceId', title: '客服人员', type: 'search', searchType: 'user'}, {key: 'transportType', title: '运输方式', type: 'select', dictionary: 'transport_type'}, {key: 'departure', title: '始发地', type: 'search', searchType:'charge_place'}, {key: 'destination', title: '目的地', type: 'search', searchType:'charge_place'}, {key: 'planPickupTimeFrom', title: '要求装货时间开始', type: 'date', props: {showTime: true}}, {key: 'planPickupTimeTo', title: '要求装货时间至', type: 'date', props: {showTime: true}}, {key: 'insertTimeFrom', title: '创建时间开始', type: 'date', props: {showTime: true}}, {key: 'insertTimeTo', title: '创建时间至', type: 'date', props: {showTime: true}} ]; const tableCols = [ {key: 'orderNumber', title: '运单号', link: true}, {key: 'orderType', title: '任务状态', dictionary: 'order_type'}, {key: 'statusType', title: '运单状态', dictionary: 'transport_order'}, {key: 'taskTypeName', title: '文件任务'}, {key: 'fileList', title: '附件', link: 'list'}, {key: 'uploadType', title: '上传方式'}, {key: 'remark', title: '修改原因'}, {key: 'customerId', title: '客户'}, {key: 'customerDelegateCode', title: '委托号'}, {key: 'customerDelegateTime', title: '委托日期'}, {key: 'businessType', title: '运输类型', dictionary: 'business_type'}, {key: 'transportType', title: '运输方式', dictionary: 'transport_type'}, {key: 'carModeId', title: '车型'}, {key: 'supplierId', title: '供应商/车主'}, {key: 'carNumber', title: '车牌号'}, {key: 'driverName', title: '司机名称'}, {key: 'driverMobilePhone', title: '司机号码'}, {key: 'departure', title: '始发地'}, {key: 'destination', title: '目的地'}, {key: 'planPickupTime', title: '要求装货时间'}, {key: 'planDeliveryTime', title: '要求卸货时间'}, {key: 'insertUser', title: '创建人员'}, {key: 'insertTime', title: '创建时间'}, {key: 'updateUser', title: '更新人员'}, {key: 'updateTime', title: '更新时间'}, ]; const menu = [ {key:'webExport',title:'页面导出'}, {key:'allExport',title:'查询导出'}, {key:'templateManager', title:'模板管理'} ]; const commonButtons = [{key: 'export', title: '导出', menu}]; const config = { tabs: [{key: 'index', title: '文件管理', close: false}], subTabs: [ {key: 'uploading', title:'待上传', status: '0'}, {key: 'checking', title:'待审核', status: '1'}, {key: 'checked', title:'已审核', status: '2'}, ], filters, tableCols, initPageSize: pageSize, pageSizeType, paginationConfig, searchConfig, activeKey: 'index', subActiveKey: 'uploading', urlExport: '/tms-service/file_task/list/search', //后端查询导出api配置 isTotal: true, //页签是否需要统计符合条件的记录数 searchData: {},//默认搜索条件值-若有需同步配置searchDataBak searchDataBak: {},//初始搜索条件值-若有则与searchData相同 fixedFilters: {//各tab页签列表搜索时的固定搜索条件 uploading: {fileStatus: 0}, checking: {fileStatus: 1}, checked: {fileStatus: 2}, }, buttons: { //各tab页签操作按钮 uploading:[ {key: 'upload', title: '上传', bsStyle: 'primary'}, {key: 'check', title: '审核通过', confirm: '是否所有勾选记录审核通过?'}, ].concat(commonButtons), checking:[ {key: 'edit', title: '编辑', bsStyle: 'primary'}, {key: 'check1', title: '审核通过', confirm: '是否所有勾选记录审核通过?'}, ].concat(commonButtons), checked: [ {key: 'modify', title: '修改文件', bsStyle: 'primary'} ].concat(commonButtons), } }; export default config;
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const buyerSchema = new Schema({ firstName: String, lastName: String, email: String, phoneNumber: String, password: String, googleID: String, facebookID: String, preferences: Schema.Types.ObjectId, matches: [ Schema.Types.ObjectId ], favoriteMatches: [ Schema.Types.ObjectId ], demographics: Schema.Types.ObjectId }); module.exports = mongoose.model('Buyer', buyerSchema);
// given an unsorted array of integers from 1 to N, // find the missing integer function findMissingConsecutive(nums) { var maxNum = Number.NEGATIVE_INFINITY; var size = nums.length; var sum = 0; for (var i = 0; i < size; i++) { var num = nums[i]; sum += num; if (maxNum < num) { maxNum = num; } } // sum of 1 to N is (N*(N+1))/2 return (maxNum * (maxNum + 1)) / 2 - sum; } module.exports.findMissingConsecutive = findMissingConsecutive;
/** * Created by iyobo on 2016-04-24. */ /* Heap's algorithm generates all possible permutations of N objects */ function swap(array,i1, i2){ if(!Array.isArray(array)) { console.error("Not an array"+ array) return; } // console.log("swapping from "+array) var buffer = array[i1] array[i1] = array[i2] array[i2] = buffer // console.log("to "+array) } function generateAllCombinations(n,a){ if (n===1) console.log(a) else{ for (var i=0; i<n-1; i++){ generateAllCombinations(n-1,a) if(n%2==0){ swap(a,1,n-1) } else { swap(a,0,n-1) } } generateAllCombinations(n-1,a) } } var A = ["red","yellow","green","meat"] var N = A.length generateAllCombinations(N,A) module.exports = generateAllCombinations() // function fibonacci(n){ // var cur= []; // for(var i=0; i<n; i++){ // // var sum=0; // if(i==1) // sum = 1; // // if(cur.length>1){ // var first = cur.length -1; // var second = 0; // // if(cur.length >= 2) // second = cur.length-2; // // sum += cur[first]+cur[second]; // } // cur.push(sum); // } // // console.log(cur); // }
var gulp = require('gulp'), del = require('del'), gp_concat = require('gulp-concat'), gp_minify = require('gulp-minifier'), gp_cssmin = require('gulp-cssmin'); var libs = [ 'bower_components/gl-matrix/dist/gl-matrix-min.js', 'bower_components/mousetrap/mousetrap.min.js' ]; var views = [ 'public/index.html' ]; var application = [ 'bower_components/gl-matrix/dist/gl-matrix-min.js', 'bower_components/mousetrap/mousetrap.min.js', 'public/scripts/application/application.js', 'public/scripts/application/audio.js', 'public/scripts/application/renderer.js', 'public/scripts/application/camera.js', 'public/scripts/application/utilities.js', 'public/scripts/shaders/full_screen_quad.js', 'public/scripts/shaders/particles_init.js', 'public/scripts/shaders/particles_move.js', 'public/scripts/shaders/particles_draw.js', 'public/scripts/index.js' ]; var styles = [ 'public/styles/layout.css' ]; gulp.task('cleanup-pre', function(){ return del('public/libs/*'); }); gulp.task('libs', function(){ return gulp.src(libs).pipe(gulp.dest('public/libs')); }); // Default task gulp.task('default', ['cleanup-pre', 'libs']); // Build task gulp.task('cleanup-pre', function(){ return del('public/dist/*'); }); gulp.task('views', ['cleanup-pre'], function(){ return gulp.src(views) .pipe(gulp.dest('public/dist')); }); gulp.task('application', ['cleanup-pre'], function(){ return gulp.src(application) .pipe(gp_concat('scripts.min.js')) //.pipe(gp_minify({minify: true, minifyJS: true})) .pipe(gulp.dest('public/dist')); }); gulp.task('styles', ['cleanup-pre'], function(){ return gulp.src(styles) .pipe(gp_concat('stylesheets.min.css')) .pipe(gp_cssmin()) .pipe(gulp.dest('public/dist')); }); gulp.task('build', ['cleanup-pre', 'views', 'application', 'styles']);
var app = angular.module('movieSearch', []); var initInjector = angular.injector(['ng']); var $http = initInjector.get('$http'); //TODO: FINISH FUNCTION TO PARSE TITLE QUERIES titleParse = function(title) { var titleArr = title.split(''); for (var i = 0; i < titleArr.length; i++) { if (titleArr[i] == ' ') { titleArr[i] = '+'; } } var newTitle = titleArr.join(''); }
import React from 'react'; import { RecipeFlexCont, InnerPadding, ContainerMin } from './styles'; import { Heading, Paragraph } from '../../../Styling'; import Content from '../Content'; const TypeContent = props => ( <> <RecipeFlexCont> <InnerPadding> <ContainerMin> <Heading>Brewing with {props.type}</Heading> <Paragraph>{props.paragraph}</Paragraph> <Paragraph style={{ color: 'black' }}> Flavor types: <span>{props.flavor1}</span> <span>{props.flavor2}</span> </Paragraph> </ContainerMin> <Content steps={props.steps} ingredients={props.ingredients} /> </InnerPadding> </RecipeFlexCont> </> ); export default TypeContent;
import './ToDoTasks.css'; const ToDoTasks = (props) => { const showToDoTasks = props.values.map((prop) => { return <li key={prop.id}>{prop.task}</li>; }); return ( <div className='todo-list__container'> <div className='todo-list__controls'> <div className='todo-list__control'> <label>Task</label> <ul>{showToDoTasks}</ul> </div> </div> </div> ); }; export default ToDoTasks;
import React from 'react' import PropTypes from 'prop-types' import { Modal, Form, Input, message, Col, Tag } from 'antd' import Upload from '../upload' const config = require('../../../utils/config') const { activeUrl } = config const urlObj = { upload: `${activeUrl}/api/actModel/import`, add: `${activeUrl}/api/actModel/newModel`, } const FormItem = Form.Item const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 6 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 14 }, }, } class actModelModal extends React.Component { state = { maskClosable: false, visible: true, confirmLoading: false, file: {}, } onCancel = () => { let { handleModal, form } = this.props form.resetFields() handleModal('hide') } onUpload = () => { let { file } = this.state let { handleModal } = this.props if (typeof(file) !== 'object') { message.warning('请选择文件') return false } this.setState({ confirmLoading: true, }) let formDate = new FormData() formDate.append('file', file) formDate.append('fileName', file.name) // let xhr = new XMLHttpRequest() // xhr.open('POST', uploadUrl, true) // xhr.setRequestHeader('Content-Type', file.type) // xhr.send(formDate) fetch(urlObj.upload, { method: 'post', body: formDate, }).then((response) => { return response.json() }).then((data) => { setTimeout(() => { if (data.code === 200 || '200') { message.success(data.msg) this.setState({ confirmLoading: false, file: {}, }) handleModal('hide') handleModal('refilter') } else { message.error(data.msg) this.setState({ confirmLoading: false, }) } }, 1000) }) return true } onAdd = () => { let { handleModal, form } = this.props form.validateFields((errors) => { if (errors) { return } }) let addData = { ...form.getFieldsValue(), } this.setState({ confirmLoading: true, }) fetch(urlObj.add, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(addData), }).then((response) => { return response.json() }).then((data) => { setTimeout(() => { if (Number(data.code) === 200) { handleModal('refilter') form.resetFields() message.success(data.msg) let modelId = data.data.id window.open(`/modeler.html?modelId=${modelId}`) } else { message.error(data.msg) } this.setState({ confirmLoading: false, }) }, 1000) }) } getFileObj = (fileObj) => { this.setState({ file: fileObj }) } render () { const { visible, modalType, form: { getFieldDecorator } } = this.props let ModalContent = '' let modalProps = { title: '创建模型', maskClosable: false, onOk: this.onAdd, onCancel: this.onCancel, okText: '提交', cancelText: '取消', confirmLoading: this.state.confirmLoading, } let uploadProps = {} switch (modalType) { case 'import': uploadProps = { text: '添加/修改流程文件', name: 'file', getFile: (fileObj) => { this.getFileObj(fileObj) }, } modalProps.title = '导入XML文件' modalProps.onOk = this.onUpload ModalContent = (<Col offset="6"> <FormItem hasFeedback {...formItemLayout}> <Upload {...uploadProps} /> <Col span="24" >支持文件格式: xml </Col> {this.state.file && this.state.file.name ? <Tag>{this.state.file.name}</Tag> : ''} </FormItem> </Col>) break default : modalProps.title = '创建模型' ModalContent = (<div> <FormItem label="模型名称" hasFeedback {...formItemLayout}> {getFieldDecorator('name', { rules: [{ required: true, message: '请输入模型名称' }], initialValue: '' })(<Input />)} </FormItem> <FormItem label="模型描述" hasFeedback {...formItemLayout}> {getFieldDecorator('description', { initialValue: '' })(<Input />)} </FormItem> </div>) } return ( <div> <Modal {...modalProps} visible={visible} > <Form layout="horizontal"> {ModalContent} </Form> </Modal> </div> ) } } const ModalForm = Form.create()(actModelModal) actModelModal.propTypes = { visible: PropTypes.bool, confirmLoading: PropTypes.bool, form: PropTypes.object, modalType: PropTypes.string, handleModal: PropTypes.func, } export default ModalForm
module.exports = { root: true, extends: [ '@react-native-community', 'prettier', // 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/eslint-recommended' ], rules: { 'react/no-did-mount-set-state': 0, camelcase: 0, '@typescript-eslint/camelcase': 0, '@typescript-eslint/no-inferrable-types': 0, '@typescript-eslint/ban-ts-ignore': 0, '@typescript-eslint/interface-name-prefix': 0, '@typescript-eslint/no-use-before-define': 0, '@typescript-eslint/explicit-function-return-type': 0, 'no-shadow': 0, // 'no-case-declarations': 0, // 'no-prototype-builtins': 0 }, parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint', 'prettier'], };
var delta = 0 var cubeLanes = 5 var cubeAmount = 20 var cubeSpacing = 5 var cubeGrid = { width: cubeLanes * cubeSpacing, height: cubeAmount * cubeSpacing } var cubeSpeed = 0.01 var cubeProbability = 0.2 var score = 0 // var scoreElement = document.getElementById('score') var generatingNotes = false var generatedNotes = [] var patternBacklog = [] var skippedNotes = 0 var tones = ["D2", "E2", "F#2", "A2", "B2"] var synth = new Tone.MembraneSynth({ pitchDecay: 0.05, octaves: 10, oscillator: { type: "sine" }, envelope: { attack: 0.001, decay: 0.4, sustain: 0.01, release: 1.4, attackCurve: "exponential" } }).toMaster(); // var synth = new Tone.PolySynth(6, Tone.Synth).toMaster() // synth.set("detune", -1200); var backgroundSynth = new Tone.MetalSynth({ noise: { type: "white" }, envelope: { attack: .005, decay: .05, sustain: .1, release: .4 } }).toMaster() //Helpers var mouse = {}
import React, {useEffect} from 'react' // Import Page styles import "../styles/Resource.css" // Importing Images import codecademy from "../../images/codecademy.png" import freecodecamp from "../../images/freecodecamp.png" import udemy from "../../images/udemy.jpg" import edx from "../../images/edx.jpg" import coursera from "../../images/coursera.png" import w3schools from "../../images/w3schools.png" import code from "../../images/code.jpg" import sololearn from "../../images/sololearn.png" import bitdegree from "../../images/bitdegree.jpg" // Resources function START function Resources() { // Change Browser Title. useEffect(() =>{ document.title="Resources - spatepate" }, []) return ( <div> {/* Page Header, with title and caption */} <header className="jumbotron jumbotron-fluid bg-dark"> <div className="container-fluid text-center"> <h1 className="display-3">Resources </h1> <p className="lead pb-4"> We will redirect you to some of the best website that provide the best help! </p> </div> </header> {/* Resources section START */} <section className="resources-section"> <div className="container"> <br/> {/* BOOTSTRAP CARDS */} {/* BitDegree */} <div className="row no-gutters bg-light position-relative"> {/* img */} <div className="col-md-6 mb-md-0 p-md-4"> <img src={bitdegree} className="w-100" alt="codecademy online"/> </div> {/* Title, Caption, Link */} <div className="col-md-6 position-static p-4 pl-md-0"> <h5 className="mt-0">BitDegree</h5> <p>Looking for the best online courses? Click here and gain or improve digital skills on our eLearning platform. Enroll in the best online courses today!</p> <a href="https://www.bitdegree.org/learn/" target="_blank" rel="noopener noreferrer" className="stretched-link">Visit BitDegree</a> </div> </div> {/* CODECADEMY */} <div className="row no-gutters bg-light position-relative"> {/* img */} <div className="col-md-6 mb-md-0 p-md-4"> <img src={codecademy} className="w-100" alt="codecademy online"/> </div> {/* Title, Caption, Link */} <div className="col-md-6 position-static p-4 pl-md-0"> <h5 className="mt-0">Codecademy</h5> <p>Codecademy is an American online interactive platform that offers free coding classes in 12 different programming languages including Python, Java, Go, JavaScript, Ruby, SQL, C++, C#, Swift, and Sass, as well as markup languages HTML and CSS.</p> <a href="https://www.codecademy.com/learn" target="_blank" rel="noopener noreferrer" className="stretched-link">Visit Codecademy</a> </div> </div> {/* FREECODECAMP */} <div className="row no-gutters bg-light position-relative"> {/* img */} <div className="col-md-6 mb-md-0 p-md-4"> <img src={freecodecamp} className="w-100" alt="freeCodeCamp, online courses."/> </div> {/* Title, Caption, Link */} <div className="col-md-6 position-static p-4 pl-md-0"> <h5 className="mt-0">freeCodeCamp</h5> <p>freeCodeCamp is a non-profit organization that consists of an interactive learning web platform, an online community forum, chat rooms, online publications and local organizations that intend to make learning web development accessible to anyone.</p> <a href="https://www.freecodecamp.org/" target="_blank" rel="noopener noreferrer" className="stretched-link">Visit freeCodeCamp</a> </div> </div> {/* UDEMY */} <div className="row no-gutters bg-light position-relative"> {/* img */} <div className="col-md-6 mb-md-0 p-md-4"> <img src={udemy} className="w-100" alt="Udemy -Programming"/> </div> {/* Title, Caption, Link */} <div className="col-md-6 position-static p-4 pl-md-0"> <h5 className="mt-0">Udemy</h5> <p>Udemy has lots of programming courses, there are some which are free and some which are paid courses. Udemy provides not only programming courses but many more, in different categories. </p> <a href="https://www.udemy.com/courses/development/programming-languages/" target="_blank" rel="noopener noreferrer" className="stretched-link">Visit Udemy -Programming</a> </div> </div> {/* sololearn */} <div className="row no-gutters bg-light position-relative"> {/* img */} <div className="col-md-6 mb-md-0 p-md-4"> <img src={sololearn} className="w-100" alt="edX"/> </div> {/* Title, Caption, Link */} <div className="col-md-6 position-static p-4 pl-md-0"> <h5 className="mt-0">SoloLearn</h5> <p>SoloLearn is a series of free apps that allows users to learn a variety of programming languages and concepts through short lessons, code challenges, and quizzes. Lessons are written with the beginner in mind, so anyone can learn to read and write their own code.</p> <a href="https://www.sololearn.com/Courses/" target="_blank" rel="noopener noreferrer" className="stretched-link">Visit SoloLearn</a> </div> </div> {/* EDX */} <div className="row no-gutters bg-light position-relative"> {/* img */} <div className="col-md-6 mb-md-0 p-md-4"> <img src={edx} className="w-100" alt="edX"/> </div> {/* Title, Caption, Link */} <div className="col-md-6 position-static p-4 pl-md-0"> <h5 className="mt-0">edX</h5> <p>edX is an American massive open online course provider created by Harvard and MIT. It hosts online university-level courses in a wide range of disciplines to a worldwide student body, including some courses at no charge. It also conducts research into learning based on how people use its platform. </p> <a href="https://www.edx.org/" target="_blank" rel="noopener noreferrer" className="stretched-link">Visit edX</a> </div> </div> {/* coursera */} <div className="row no-gutters bg-light position-relative"> {/* img */} <div className="col-md-6 mb-md-0 p-md-4"> <img src={coursera} className="w-100" alt="edX"/> </div> {/* Title, Caption, Link */} <div className="col-md-6 position-static p-4 pl-md-0"> <h5 className="mt-0">Coursera</h5> <p>Join Coursera for free and learn online. Build skills with courses from top universities like Yale, Michigan, Stanford, and leading companies like Google and IBM.</p> <a href="https://www.coursera.org/courses?query=coding" target="_blank" rel="noopener noreferrer" className="stretched-link">Visit Coursera</a> </div> </div> {/* w3schools */} <div className="row no-gutters bg-light position-relative"> {/* img */} <div className="col-md-6 mb-md-0 p-md-4"> <img src={w3schools} className="w-100" alt="edX"/> </div> {/* Title, Caption, Link */} <div className="col-md-6 position-static p-4 pl-md-0"> <h5 className="mt-0">w3schools</h5> <p>W3Schools is an educational website for learning web technologies online. Content includes tutorials and references relating to HTML, CSS, JavaScript, JSON, PHP, Python, AngularJS, React.js, SQL, Bootstrap, Sass, Node.js, jQuery, XQuery, AJAX, XML, Raspberry Pi, C++, C# and Java.</p> <a href="https://www.w3schools.com/" target="_blank" rel="noopener noreferrer" className="stretched-link">Visit w3schools</a> </div> </div> {/* codeconquest */} <div className="row no-gutters bg-light position-relative"> {/* img */} <div className="col-md-6 mb-md-0 p-md-4"> <img src={code} className="w-100" alt="edX"/> </div> {/* Title, Caption, Link */} <div className="col-md-6 position-static p-4 pl-md-0"> <h5 className="mt-0">codeconquest</h5> <p>Welcome to Code Conquest – a free online guide to coding for beginners. If you’re someone who wants to learn about coding, but you haven’t got a clue where to start, you’ve come to the right place. This site has all the step-by-step information you need to get started.</p> <a href="https://www.codeconquest.com/tutorials/" target="_blank" rel="noopener noreferrer" className="stretched-link">Visit codeconquest</a> </div> </div> </div> </section> {/* Resources section END */} {/* MORE RESOURCES TO FIND AND ADD. */} <p className="text-center p-3 bg-danger" style={{color: "white"}}>more sites to be added!</p> </div> ) } export default Resources
import React from 'react'; import { createStore, applyMiddleware, combineReducers } from 'redux'; import thunkMiddleware from 'redux-thunk' import { createLogger } from 'redux-logger' import { Provider } from 'react-redux'; import { Navigation } from 'react-native-navigation'; // reducers import api from 'oc/js/reducers/api-reducer'; import app from 'oc/js/reducers/app-reducer'; // others import registry from './registry' import * as screenNames from 'oc/js/constants/screen-names' const loggerMiddleware = createLogger() const reducers = combineReducers({api, app}); const store = createStore( reducers, applyMiddleware( thunkMiddleware, loggerMiddleware ) ); registry(store, Provider) Navigation.startSingleScreenApp({ screen: { screen: screenNames.HOME, title: 'Welcome to OC', }, appStyle: { navBarBackgroundColor: '#00adf5', navBarTextColor: 'white', navBarButtonColor: '#ffffff', statusBarTextColorScheme: 'light' } });
import React from 'react'; import CheckBox from './CheckBox' import '../styles/App.css'; const ToggleIngredient = ({addToCart, ingredient}) => { const quantity = ingredient.quantity > 0 ? (ingredient.quantity + ' ' + ingredient.unit) : ''; return ( <div className="row" style={{marginBottom: "15px"}}> <CheckBox ingredient={ingredient.name} value={{quantity: ingredient.quantity, unit: ingredient.unit}} toggle={(ingredient) => addToCart(ingredient)} isActivated={ingredient.inCart}/> <label className="col-sm-10 col-xs-9" style={{marginTop: "7px"}}> {ingredient.name + ' ' + quantity} </label> </div> ); } export default ToggleIngredient;
import React from 'react'; import {Container} from "@material-ui/core"; import {useStyles} from "./styled"; import AuthForm from "../containers/AuthForm/AuthForm"; const AuthPage = () => { const classes = useStyles(); return ( <Container className={classes.root}> <AuthForm/> </Container> ); }; export default AuthPage;
import styled from 'styled-components'; export const List = styled.div ` height:3rem; margin-bottom:0.157rem; display:flex; text-decoration:row; box-sizing:border-box; padding:0.35rem; background:white; .ListItem-img{ flex:1; border-radius:1px; .ListItem-content__img{ /* margin: 0 auto; */ width:47%; height:100%; border-radius:9px; overflow:hidden; &>img{ width:100%; } } } `; export const TextContent = styled.div ` position:relative; height:100%; .ListItem-title{ padding-right:0.3rem; box-sizing:border-box; width:6rem; font-size:0.38rem; font-family: PingFangSC-medium; font-weight:700; color:black; } .ListItem-label{ position:absolute; bottom:0.1rem; color:#9a9a9a; } `
import React from 'react' import { shallow } from 'enzyme' import Comment from '../../../../app/components/Comment' describe('components', () => { describe('Comment', () => { const wrapper = shallow(<Comment author={'foo'}>{'bar'}</Comment>) it('should return author and comment', () => { expect(wrapper.find('.commentAuthor').text()).toBe('foo') expect(wrapper.find('span').render().find('p').text()).toBe('bar') }) }) })
import './App.css'; import {BrowserRouter, Switch, Route} from 'react-router-dom'; import SearchForm from './components/SearchForm'; import DisplayPage from './components/DisplayPage'; function App() { return ( <div className="App"> <BrowserRouter> <h1>Welcome to Luke APIwalker</h1> <br /> <SearchForm></SearchForm> <br /> <br /> <Switch> <Route exact path = "/:category/:id"> <DisplayPage></DisplayPage> </Route> </Switch> </BrowserRouter> </div> ); } export default App;
import { Editor, Mark, Raw } from '../..' import Frame from 'react-frame-component' import React from 'react' import ReactDOM from 'react-dom' import initialState from './state.json' /** * Injector to make `onSelect` work in iframes in React. */ import injector from 'react-frame-aware-selection-plugin' injector() /** * Define the default node type. */ const DEFAULT_NODE = 'paragraph' /** * Define a set of node renderers. * * @type {Object} */ const NODES = { 'block-code': props => <pre><code {...props.attributes}>{props.children}</code></pre>, 'block-quote': props => <blockquote {...props.attributes}>{props.children}</blockquote>, 'heading-two': props => <h2 {...props.attributes}>{props.children}</h2>, 'paragraph': props => <p {...props.attributes}>{props.children}</p> } /** * Define a set of mark renderers. * * @type {Object} */ const MARKS = { bold: props => <strong>{props.children}</strong>, highlight: props => <mark>{props.children}</mark>, italic: props => <em>{props.children}</em>, } /** * The iframes example. * * @type {Component} */ class Iframes extends React.Component { /** * Deserialize the initial editor state. * * @type {Object} */ state = { state: Raw.deserialize(initialState, { terse: true }) }; /** * Check if the current selection has a mark with `type` in it. * * @param {String} type * @return {Boolean} */ hasMark = (type) => { const { state } = this.state return state.marks.some(mark => mark.type == type) } /** * Check if the any of the currently selected blocks are of `type`. * * @param {String} type * @return {Boolean} */ hasBlock = (type) => { const { state } = this.state return state.blocks.some(node => node.type == type) } /** * On change, save the new state. * * @param {State} state */ onChange = (state) => { this.setState({ state }) } /** * On key down, if it's a formatting command toggle a mark. * * @param {Event} e * @param {Object} data * @param {State} state * @return {State} */ onKeyDown = (e, data, state) => { if (!data.isMod) return let mark switch (data.key) { case 'b': mark = 'bold' break case 'i': mark = 'italic' break default: return } state = state .transform() .toggleMark(mark) .apply() e.preventDefault() return state } /** * When a mark button is clicked, toggle the current mark. * * @param {Event} e * @param {String} type */ onClickMark = (e, type) => { e.preventDefault() let { state } = this.state state = state .transform() .toggleMark(type) .apply() this.setState({ state }) } /** * When a block button is clicked, toggle the block type. * * @param {Event} e * @param {String} type */ onClickBlock = (e, type) => { e.preventDefault() let { state } = this.state const isActive = this.hasBlock(type) state = state .transform() .setBlock(isActive ? DEFAULT_NODE : type) .apply() this.setState({ state }) } /** * Render. * * @return {Element} */ render = () => { const bootstrap = ( <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossOrigin="anonymous" ></link> ) const style = { width: '100%', height: '500px' } return ( <div> <p style={{ marginBottom: '10px' }}>This editor is rendered inside of an <code>iframe</code> element, and everything works as usual! This is helpful for scenarios where you need the content to be rendered in an isolated, for example to create a "live example" with a specific set of stylesheets applied.</p> <p style={{ marginBottom: '10px' }}>In this example's case, we've added Bootstrap's CSS to the <code>iframe</code> for default styles:</p> <Frame head={bootstrap} style={style}> <div style={{ padding: '20px' }}> {this.renderToolbar()} {this.renderEditor()} </div> </Frame> </div> ) } /** * Render the toolbar. * * @return {Element} */ renderToolbar = () => { return ( <div className="btn-group" style={{ marginBottom: '20px' }}> {this.renderMarkButton('bold', 'bold')} {this.renderMarkButton('italic', 'italic')} {this.renderMarkButton('highlight', 'pencil')} {this.renderBlockButton('heading-two', 'header')} {this.renderBlockButton('block-code', 'console')} {this.renderBlockButton('block-quote', 'comment')} </div> ) } /** * Render a mark-toggling toolbar button. * * @param {String} type * @param {String} icon * @return {Element} */ renderMarkButton = (type, icon) => { const isActive = this.hasMark(type) const onMouseDown = e => this.onClickMark(e, type) let className = 'btn btn-primary' if (isActive) className += ' active' return ( <button className={className} onMouseDown={onMouseDown}> <span className={`glyphicon glyphicon-${icon}`}></span> </button> ) } /** * Render a block-toggling toolbar button. * * @param {String} type * @param {String} icon * @return {Element} */ renderBlockButton = (type, icon) => { const isActive = this.hasBlock(type) const onMouseDown = e => this.onClickBlock(e, type) let className = 'btn btn-primary' if (isActive) className += ' active' return ( <button className={className} onMouseDown={onMouseDown}> <span className={`glyphicon glyphicon-${icon}`}></span> </button> ) } /** * Render the Slate editor. * * @return {Element} */ renderEditor = () => { return ( <Editor placeholder={'Enter some rich text...'} state={this.state.state} renderNode={this.renderNode} renderMark={this.renderMark} onChange={this.onChange} onKeyDown={this.onKeyDown} /> ) } /** * Return a node renderer for a Slate `node`. * * @param {Node} node * @return {Component or Void} */ renderNode = (node) => { return NODES[node.type] } /** * Return a mark renderer for a Slate `mark`. * * @param {Mark} mark * @return {Object or Void} */ renderMark = (mark) => { return MARKS[mark.type] } } export default Iframes
const DeGiro = require('..'); const degiro = DeGiro.create({ username: 'croa98', password: 'Queteden123', }); degiro.login().then(degiro.getCashFunds) .then(console.log) .catch(console.error);
//view contains a single map var app = app || {}; app.MapView = Backbone.View.extend({ self: this, tagName: 'div', initialize: function() { this.listenTo(this.collection, 'change:displayed', this.updateLayerDisplay); }, render: function() { var self = this; //create a leaflet map this.map = L.map(this.el,{ dragging:true, doubleClickZoom:true, minZoom:5, maxZoom:10 }); //set new view this.map.setView([-4,23], 5); //set zoom listeners (zoomend) => bind with apply to ensure right scope for this this.map.on('zoomend', function () {self.updateLayerDisplay.apply(self)}) //add all layers in the collection this.collection && this.addAllLayers(); //check layer display this.updateLayerDisplay(); //return element return this.el; }, addOneLayer: function(layerGroup) { if (layerGroup.attributes.displayed === true) { this.map.addLayer(layerGroup.attributes.layers); } }, removeOneLayer: function(layerGroup) { this.map.removeLayer(layerGroup.attributes.layers); }, addAllLayers: function() { this.collection.each(this.addOneLayer, this); }, updateLayerDisplay: function () { this.collection.each(this.checkLayerDisplay, this); }, checkLayerDisplay: function (layerGroup) { var zoomLevel = this.map.getZoom(); if (layerGroup.attributes.toggleApproach === 'zoom' && layerGroup.attributes.minZoom && layerGroup.attributes.maxZoom) { if (zoomLevel >= layerGroup.attributes.minZoom && zoomLevel <= layerGroup.attributes.maxZoom) { layerGroup.set('displayed', true); } else { layerGroup.set('displayed', false); } } if ( layerGroup.attributes.displayed === true && this.map.hasLayer(layerGroup.attributes.layers) === false) { this.addOneLayer(layerGroup); } else if (layerGroup.attributes.displayed === false && this.map.hasLayer(layerGroup.attributes.layers) === true) { this.removeOneLayer(layerGroup); } } });
const { prefix } = require("../config.json"); module.exports = { name: "say", description: "The bot will parrot whatever you say in a channel :)", args: true, // Include if command requires args usage: `<channel-id> <message> ex: ${prefix}say 742243914164994089 Amen!`, // Include if args is true guildOnly: true, // Include if exclusive to server admin_permissions: true, // Include if admin permissions required cooldown: 3, execute(message, args) { if (args.length < 2) { return message.reply( `Error: Please consult the usage by typing\n \`${prefix}help ${this.name}\` to get more info` ); } // Find if channel id is valid let guildChannels = message.guild.channels.cache; let channel = guildChannels.get(args[0]); if (!channel) { return message.reply(`Error: Please provide the a valid channel id`); } // Combine args into one string let personalMessage = args.slice(args.indexOf(args[1])).join(" "); console.log(personalMessage); // Send message to that channel channel.send(personalMessage); }, };
import { EXAMPLE_ENDPOINT } from '_Banking/api/example.endpoint' import { mockExampleEndpoint } from '_Banking/standalone/example.fixture' const { EXAMPLE } = EXAMPLE_ENDPOINT(1234) const matchExampleTable = { [EXAMPLE]: mockExampleEndpoint } export default matchExampleTable
import React from 'react' import PropTypes from 'prop-types' import { Flexbox } from '../../Layout' import { Link } from 'react-router-dom' import { Typography, Icon, Button, Divider } from '@material-ui/core' import DownloadIcon from '@material-ui/icons/CloudDownload' import YoutubeEmbed from './VideoEmbed' const getStyle = () => { return { background: 'white', position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)', flex: 1, height: '90%', width: '90%', margin: '0 auto', padding: '3em', overflowY: 'scroll' } } const Guide = ({ guides }) => { return ( <Flexbox style={getStyle()}> <Flexbox flexDirection="column" flex="1"> <Flexbox justifyContent="space-between"> <Typography variant='h5'> {guides.get('title')} </Typography> <Link to={{ pathname: guides.get('download_link')}} target="_blank" download> <Button variant="contained" size="small" style={{ margin: 8 }}> <DownloadIcon style={{ marginRight: 8, fontSize: 20 }} /> Download Repository </Button> </Link> </Flexbox> <YoutubeEmbed embedId={guides.get('embedId')} /> <Divider style={{ marginTop: 10, marginBottom: 10 }} /> <Typography variant='h6'> Getting Started </Typography> <Divider style={{ marginTop: 10, marginBottom: 10 }} /> <Typography variant='p' style={{ paddingTop: 10, paddingBottom: 10 }}> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </Typography> <Divider style={{ marginTop: 10, marginBottom: 10 }} /> <Typography variant='h6'> Understanding the build </Typography> <Divider style={{ marginTop: 10, marginBottom: 10 }} /> <Typography variant='p' style={{ paddingTop: 10, paddingBottom: 10 }}> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </Typography> <Divider style={{ marginTop: 10, marginBottom: 10 }} /> <Typography variant='h6'> The code </Typography> <Divider style={{ marginTop: 10, marginBottom: 10 }} /> <Typography variant='p' style={{ paddingTop: 10, paddingBottom: 12 }}> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </Typography> <pre style={{ background: 'lightgray', fontFamily: 'sans-serif', fontSize: 12, color: 'gray' }}> {` const tile = { type: "tile", attributes: { title: "Video Chat", subtitle: "https://vid.podium.co", icon: "https://assets.podium.com/icons/video-w-gray-bg.png" }, dynamicSend: { url: "http://localhost:9002/dynamicSend", data: JSON.stringify({ some: "special", stuff: "cool" }), keys: [ { name: "some", required: true, scrub: false }, { name: "stuff", required: false } ] } }; const theBody = { type: "body", attributes: { text: "Hey Susan I hope you had an awesome day!! Was just wondering if you got that email from Greg??", isEditable: true }, dynamicSend: { url: "http://localhost:9002/body" } }; `} </pre> <Divider style={{ marginTop: 10, marginBottom: 10 }} /> <Typography variant='h6'> Bringing it all together </Typography> <Divider style={{ marginTop: 10, marginBottom: 10 }} /> <Typography variant='p' style={{ paddingTop: 10, paddingBottom: 10 }}> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </Typography> <Divider style={{ marginTop: 10, marginBottom: 10 }} /> </Flexbox> </Flexbox> ) } Guide.propTypes = { guides: PropTypes.object.isRequired, style: PropTypes.object, } export default Guide
/** * This module contains various operations that will be * used in construction of the model Graph. */ /** * creates eskinOperations Object * @constructor * @param {String} rootElem fully qualified div selector * @param {Object} config a config object * @returns {Object} eskinOperations return eskinOperationsObject */ var eskinOperations = function(rootElem,config){ //rootElem is compulsory parameter //if not passed will result in error var keyStore = new eSkinkeyStore(); var model = null; var view = null; var geneExpressionOverlay = null; var construction = null; var factory = SBMLFactory(); var undoManager = new d3scomos.undoManager(); var contextHandler = null; //---- add geo code --- //TODO: this is supposed to be removed once done with drag and drop var geoAdd ; //----------- if(!rootElem){ d3scomos.Logger.error("eskin model operations rootElem not passed"); return null; } //var thisSVG; /** return this object **/ var operations = { undoManager : undoManager, initCanvas : function(){ view.initCanvas(); }, /** * initializes the modelData object * @param {Object} data object with init params * @throws {ValidationError} if non optional params are missing **/ initModel : function(data){ //clear keyStore keyStore.clear(); keyStore.addKey(data.sId);// //initModel data will loose any previous data model = factory.getSBMLModel(data); construction = new modelConstructor(rootElem,keyStore,model,this); contextHandler = {cut:this.cut,copy:this.copy,paste:this.paste,delete:this.deleteSelected}; view = eskinView(rootElem,config,model,undoManager,construction,contextHandler); }, /** * accepts molecule(species) data and adds it to model after validation * @param {Object} species data * @throws {ValidationError} if non optional params are missing **/ addSpecies : function addSpecies (species){ if(!species || species === {}) throw new TypeError("Empty or no species data passed"); //validate the data try{ undoableOperations.constructSpecies(species,keyStore,model,view); undoManager.add({ undo:function(){ undoableOperations.destructSpecies(species.sId,keyStore,model,view); }, redo : function(){ undoableOperations.constructSpecies(species,keyStore,model,view); } }) //console.warn(undoManager); //dispatch event informing undoManager is changed eskinDispatch.undoManagerEvent(undoManager); } catch(err){ if(err instanceof customErrors.ValidationError){ __logger.error("add species: validation failed "+err.message); } throw err; } }, /** * deltes the current scomosSelections * TODO: for now only one species will be deleted i.e. does not support multi select delete * ALso does not support complex delete * @return {Boolean} deletion status */ deleteSelected:function(){ //deletethe selected species if any var currSelection = d3.selectAll('.selected'); if(currSelection[0].length == 0) return; var confirmDelete = confirm("Please note that selected entity and all its children will be deleted. Do you wish to proceed with this action?"); if(!confirmDelete) { __logger.info('Deletion aborted by user.') return; } try{ var currSelection = view.getSelection().getDestructableSelection(); undoableOperations.destructSelection(currSelection,model,view,keyStore); view.refresh(); undoManager.add({ undo:function(){ undoableOperations.constructSelection(currSelection,model,view,keyStore); }, redo : function(){ undoableOperations.destructSelection(currSelection,model,view,keyStore); } }); //console.warn(undoManager); //dispatch event informing undoManager is changed eskinDispatch.undoManagerEvent(undoManager); view.getSelection().clear(); eskinDispatch.nodeDeleted(); } catch(err){ if(err instanceof customErrors.ValidationError){ __logger.error("add species: validation failed "+err.message); } throw err; } }, /** * adds species as part of GEO drag drop functionality * TODO: remove this method once drag drop is figured out * @param {Object} species Species object to be added. Position values passed in will be ignored. */ addSpeciesGEO : function addSpeciesGEO (species){ species.sId = keyStore.getNextSpecies(); this.addSpecies(species); geneExpressionOverlay = null; //so that new data is loaded }, /** * accepts compartment data and adds it to model after validation * @param {Object} compartment data * @throws {ValidationError} if non optional params are missing **/ addCompartment : function addCompartment (compartment){ if(!compartment || compartment === {}) throw new TypeError("Empty or no Compartment data passed"); try{ undoableOperations.constructCompartment(compartment,keyStore,model,view); undoManager.add({ undo:function(){ undoableOperations.destructCompartment(compartment.sId,keyStore,model,view); }, redo : function(){ undoableOperations.constructCompartment(compartment,keyStore,model,view); } }) //console.warn(undoManager); //dispatch event informing undoManager is changed eskinDispatch.undoManagerEvent(undoManager); } catch(err){ if(err instanceof customErrors.ValidationError){ __logger.error("add Compartment: validation failed "+err.message); } throw err; } }, /** * accepts reaction data and adds it to model after validation * @param {Object} compartment * @throws {ValidationError} if non optional params are missing **/ addReaction : function addReaction (reaction){ if(!reaction || reaction === {}) throw new TypeError("Empty or no species data passed"); //reactions received from the eskin server lacks the iHeight and iWidth //add them reaction.iHeight = reaction.iHeight || 20; reaction.iWidth = reaction.iWidth || 20; try{ undoableOperations.constructReaction(reaction,keyStore,model,view); undoManager.add({ undo:function(){ undoableOperations.destructReaction(reaction.sId,keyStore,model,view); }, redo : function(){ undoableOperations.constructReaction(reaction,keyStore,model,view); } }) //console.warn(undoManager); //dispatch event informing undoManager is changed eskinDispatch.undoManagerEvent(undoManager); } catch(err){ if(err instanceof customErrors.ValidationError){ __logger.error("add Reaction: validation failed "+err.message); } throw err; } }, /** * adds covalent modifier to species species * @param {String} sId [description] * @param {String} modifierType modifier string. Must be valid string. Valid string list is available in construnctionConstants. * @return {String} sModification returns updated sModification string. * @throws customErrors.ValidationError if invalid sId is passed */ addCovalantModification:function(sId,modifierType){ try{ return undoableOperations.addCovalantModification(sId,modifierType,model,view) } catch(err){ if(err instanceof customErrors.ValidationError){ __logger.error("add covalentModification: Operation failed for sId"+sId+'.Reason ;'+err.message); } throw err; } }, /** * adds the newModifier to the reaction. * @param {String} reactionSId source reaction. * @param {{sID:String,bConstant:boolean ... etc}} prouctOptions product build options. * @return {} adds the new product if valid, also puts the operation on undoManager. */ addProduct : function(reactionSId,prouctOptions){ try{ undoableOperations.addProduct(reactionSId,prouctOptions,model,view); undoManager.add({ undo : function(){ undoableOperations.removeProduct(reactionSId,prouctOptions.sId,model,view); }, redo : function(){ undoableOperations.addProduct(reactionSId,prouctOptions,model,view); } }) eskinDispatch.undoManagerEvent(undoManager); }catch(err){ __logger.error('Add product Failed. Reason : ' + err.message); throw err; } }, addReactant : function(reactionSId,reactantOptions){ try{ undoableOperations.addReactant(reactionSId,reactantOptions,model,view); undoManager.add({ undo : function(){ undoableOperations.removeReactant(reactionSId,reactantOptions.sId,model,view); }, redo : function(){ undoableOperations.addReactant(reactionSId,reactantOptions,model,view); } }) eskinDispatch.undoManagerEvent(undoManager); }catch(err){ __logger.error('Add Reactant Failed. Reason : ' + err.message); throw err; } }, addModifier : function(reactionSId,modifierOptions){ try{ undoableOperations.addModifier(reactionSId,modifierOptions,model,view); undoManager.add({ undo : function(){ undoableOperations.removeModifier(reactionSId,modifierOptions.sId,model,view); }, redo : function(){ undoableOperations.addModifier(reactionSId,modifierOptions,model,view); } }) eskinDispatch.undoManagerEvent(undoManager); }catch(err){ __logger.error('Add Modifier Failed. Reason : ' + err.message); throw err; } }, /** * provides node key value update hook for property explorer, so that undo redo will be supported. * @param {string} sId sId of the node to be updated. * @param {string} sKey key in this node that is to be updated. * @param {String|Object} newVal newValue to be updated on this object. Mostly is string could be the Object somethimes. * @return {instanceof Base} returns updated object. */ setNodeValueByKey:function(sId,sKey,newVal){ //check if key exists. try{ var thisNode = model.getNodeObjectBySId(sId); var oldVal = thisNode[sKey]; model.setNodeValueByKey(sId,sKey,newVal); view.refresh(); resizer.updateResizer(); undoManager.add({ undo:function(){ model.setNodeValueByKey(sId,sKey,oldVal); view.refresh(); resizer.updateResizer(); }, redo:function(){ model.setNodeValueByKey(sId,sKey,newVal); view.refresh(); resizer.updateResizer(); } }); eskinDispatch.undoManagerEvent(undoManager); } catch(error){ __logger.error('setNodeValueByKey Falied : ' + error.message); throw error; } }, getNodeNameBySId : function(sId){ return model.getNodeObjectBySId(sId).sName; }, /** * fits this view to the screen * @return {[type]} [description] */ fitToScreen:function(){ view.fitToScreen(); }, resetZoom : function(){ view.resetZoom(); }, zoomIn : function(){ return view.zoomIn(); }, zoomOut : function(){ return view.zoomOut(); }, setViewMode:function(__mode){ __mode = __mode.toUpperCase(); var __panMode; switch (__mode) { case "PAN": __panMode = __mode; break; case "SELECT": __panMode = __mode; break; default: console.log("Invalid pan mode " + __mode + " defaulting mode PAN") __panMode = "PAN"; break; } view.setPanMode(__panMode); }, /** * provides direct access to underlying model object * avoid using this added to enable better testing **/ getModel : function(){ return model; }, /** * loads the pre created SBML model instead of creating new one. * @param {SBMLModel} _model Precreated SBML model. * @return {} loads this model as the model. */ loadSBMLModel : function(_model){ }, refreshView:function(){ view.refresh(); //if(geneExpressionOverlay) geneExpressionOverlay.refresh(); }, /** * initializes SBMLModel with this data and activates GEO functionalities for this Model * @param {{fileHeaderMap:[String], * geneData:{'geneName':{ * 'inPathwayMap':"String", * expressionValues:[number] * visualData:{ * overlayStateList:[overlaystate shortcode:String] * colorList:[String] * } * } * } * }} GEOData overlay data produced by the eskin geneOverlay API] * @return {[type]} [description] * @throws {customErrors.ValidationError} */ loadGEOData:function(GEOData,GEOConfig){ //model.setGEOData(GEOData); //if(!geneExpressionOverlay) geneExpressionOverlay = new GEOverlay(GEOData,GEOConfig); view.enableOverlayMode(); //else //geneExpressionOverlay.updateGEOData(GEOData,GEOConfig); //var GeoConfig = {'currentExperiment':'expressionValue1'}; //geneExpressionOverlay = new GEOverlay(model,{'fileHeaderMap':fHeader,'geneData':mTestData},GeoConfig); }, changeRootElem : function(newRootElem){ rootElem = newRootElem; view.changeGraphRoot(rootElem); construction.updateRootElem(rootElem); }, cut : function(){ //copy content to the clip board clipboard.copy(view.getSelection().getCopiableSelection()); _ops.deleteSelected(); view.refresh(); // trigger destructSelection }, copy : function(){ // copy contents to clipboard. clipboard.copy(view.getSelection().getCopiableSelection()); }, paste : function(){ try{ //means was triggered by contexMenu if(d3.event){ var pasteAt = modelHelper.getTransformedCordinates(rootElem,event); } var pastableSelection = modelHelper.getPastableSelection(clipboard.paste(),keyStore,pasteAt); model.updateModelBoundaries(); console.warn(pastableSelection); undoableOperations.constructSelection(pastableSelection,model,view,keyStore,{markSelected:true}); undoManager.add({ undo : function(){ undoableOperations.destructSelection(pastableSelection,model,view,keyStore); }, redo : function(){ undoableOperations.constructSelection(pastableSelection,model,view,keyStore); } }); eskinDispatch.undoManagerEvent(undoManager); } catch(err){ __logger.error('Paste failed : '+err.message) } }, checkClipboard : function(){ clipboard.triggerClipboardEvent(); }, /** * selectes node based on the provied type. * @param {String} nodeSId node index to be selected. * @param {String} nodeType node type seelcted. * @return {clickevent dispatch} dispatches appropriate click event. */ selectNode : function(nodeSId,nodeType,ctrlKey){ //find the node and select. if(!ctrlKey) ctrlKey = false; else ctrlKey = true; var eventOptions = {ctrlPressed:ctrlKey}; switch (nodeType) { case "Species": var speciesNode = d3.selectAll(".species-node").filter(function(d){return d.sId === nodeSId}); modelHelper.handleExternalNodeSelection(speciesNode,view.getSelection(),ctrlKey); eskinDispatch.speciesClick(speciesNode.datum(),speciesNode.node(),eventOptions); break; case "Reaction": var reactionNode = d3.selectAll(".reaction-node").filter(function(d){return d.sId === nodeSId}); modelHelper.handleExternalNodeSelection(reactionNode,view.getSelection(),ctrlKey); eskinDispatch.reactionClick(reactionNode.datum(),reactionNode.node(),eventOptions); break; case "Compartment": var compartmentNode = d3.selectAll(".compartment").filter(function(d){return d.sId=== nodeSId}); modelHelper.handleExternalNodeSelection(compartmentNode,view.getSelection(),ctrlKey); eskinDispatch.compartmentClick(compartmentNode.datum(),compartmentNode.node(),eventOptions); break; default: } }, /** * Wrapper for all construnction methods * @type {Object} */ construction : { /** * sets the construction mode on/off. * @param {Boolean} isEnabled enable or disable the construction mode * @return {} [description] */ enableConstruction:function(isEnabled){ if(!construction) throw new Error('Operation failed: Enable Construnction mode.') if(isEnabled == true) construction.enable(); else construction.disable(); }, /** * returns all the construcion tools supported by the library * @return {[String]} Array of Tools names without categories */ getAllTools:function(){ return d3.values(d3.values(constructionConstants.tools)[0]); }, /** * set the active tool * @param {string} toolName active tool * @return {string} current active tool * @throws {Error} throws error if invaid toolName specified */ setActiveTool:function(toolName){ construction.setActiveTool(toolName) }, setConstrunctionMode : function(mode){ return construction.setConstrunctionMode(mode); }, } }; var _ops = operations;//store refrence to self. return operations; }
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsWysiwyg = { name: 'wysiwyg', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 3H5a2 2 0 00-2 2v14a2 2 0 002 2h14c1.1 0 2-.9 2-2V5a2 2 0 00-2-2zm0 16H5V7h14v12zm-2-7H7v-2h10v2zm-4 4H7v-2h6v2z"/></svg>` };
define(function(require) { var Backbone = require('Backbone'); //Links are models meant to contain data for html links //{ // link: 'url/goes/here' // name: 'link-replacement //} var Link = Backbone.Model.extend({ defaults: { link: '', name: '' } }); return { linkModel: Link }; });
// TODO COMMENT // INITIAL STATE const initialState = { todos: [ { todo: "Make your first todo", checked: false }, ], }; if(localStorage.getItem('toedoe2')) { const persisted = JSON.parse(localStorage.getItem('toedoe2')); initialState.todos = [...persisted.state]; } // TYPES const ADD_TODO = "ADD_TODO"; const DELETE_TODO = "DELETE_TODO"; const CHECK_TODO = "CHECK_TODO"; //ACTION CREATORS export const addToDo = (str) => ({ type: ADD_TODO, payload: str, }); export const deleteToDo = (index) => ({ type: DELETE_TODO, payload: index, }); export const checkToDo = (index) => ({ type: CHECK_TODO, payload: index, }); //REDUCER const todoListReducer = (state = initialState, { type, payload }) => { switch (type) { case ADD_TODO: return { ...state, todos: [...state.todos, { todo: payload, checked: false }], }; case DELETE_TODO: const copyForDelete = [...state.todos]; copyForDelete.splice(payload, 1); return { ...state, todos: [...copyForDelete] }; case CHECK_TODO: const copyForCheck = [...state.todos]; copyForCheck[payload].checked = !copyForCheck[payload].checked; return { ...state, todos: [...copyForCheck] }; default: return { ...state }; } }; export default todoListReducer;
import Vue from 'vue' import toggleHeader from '../../../src/components/shared/layout/ToggleHeader' const Constructor = Vue.extend(toggleHeader) const vm = new Constructor({ propsData: { title: 'Test Header', collapsed: true, }, }).$mount() describe('toggle-header', () => { it('should match the snapshot', () => { expect(vm.$el).toMatchSnapshot() }) it('should show the collapse button', () => { expect(vm.$el.querySelectorAll('.chevron.right.icon').length).toBe(1) }) }) describe('collapsed is false', () => { beforeEach(() => { vm.collapsed = false }) it('should match the snapshot', () => { expect(vm.$el).toMatchSnapshot() }) it('should show the expand button', () => { expect(vm.$el.querySelectorAll('.chevron.down.icon').length).toBe(1) }) })
var tabDict = { 0: "Home", 1: "Interests", 2: "Skills", 3: "Experience" 4: "Projects" 5: "Contact and Other" }; var numVisibleTabs = 5; class TabView extends React.Component { renderTabTopicSelector () { } renderTabContent () { } render(){ } } class TabSelector extends React.Component { render(){ } } //TODO class TabTopicSelector extends React.Component { render () { } } //Array(9).fill(null) class HUD extends React.Component { constructor(props) { super(props); this.state = { activeTab: null, }; } renderTabSelector() { } renderTabView() { } render() { } }
const TwingNodeExpressionConstant = require('../../../../../../lib/twing/node/expression/constant').TwingNodeExpressionConstant; const TwingTestMockCompiler = require('../../../../../mock/compiler'); const TwingNodeExpressionName = require('../../../../../../lib/twing/node/expression/name').TwingNodeExpressionName; const TwingNodeExpressionNullCoalesce = require('../../../../../../lib/twing/node/expression/null-coalesce').TwingNodeExpressionNullCoalesce; const TwingNodeType = require('../../../../../../lib/twing/node').TwingNodeType; const tap = require('tap'); tap.test('node/expression/null-coalesce', function (test) { test.test('compile', function (test) { let compiler = new TwingTestMockCompiler(); let left = new TwingNodeExpressionName('foo', 1); let right = new TwingNodeExpressionConstant(2, 1); let node = new TwingNodeExpressionNullCoalesce(left, right, 1); test.same(compiler.compile(node).getSource(), `((!!(// line 1 (context.has("foo")) && !(context.get("foo") === null))) ? (context.get("foo")) : (2))`); test.same(node.getType(), TwingNodeType.EXPRESSION_NULL_COALESCE); test.end(); }); test.end(); });
import React from "react"; import Blogs from "../Blogs/Blogs"; import ContactUs from "../ContactUs/ContactUs"; import Doctors from "../Doctors/Doctors"; import Exceptional from "../Exceptional/Exceptional"; import Footer from "../../Shared/Footer/Footer"; import Header from "../Header/Header"; import Services from "../Services/Services"; import Testimonials from "../Testimonials/Testimonials"; import MakeAppoinment from "../MakeAppointment/MakeAppointment"; const Home = () => { return ( <div> <Header /> <Services /> <Exceptional /> <MakeAppoinment /> <Testimonials /> <Blogs /> <Doctors /> <ContactUs /> <Footer /> </div> ); }; export default Home;
(function (cjs, an) { var p; // shortcut to reference prototypes var lib={};var ss={};var img={}; lib.ssMetadata = []; // symbols: // helper functions: function mc_symbol_clone() { var clone = this._cloneProps(new this.constructor(this.mode, this.startPosition, this.loop)); clone.gotoAndStop(this.currentFrame); clone.paused = this.paused; clone.framerate = this.framerate; return clone; } function getMCSymbolPrototype(symbol, nominalBounds, frameBounds) { var prototype = cjs.extend(symbol, cjs.MovieClip); prototype.clone = mc_symbol_clone; prototype.nominalBounds = nominalBounds; prototype.frameBounds = frameBounds; return prototype; } (lib.sputnik = function(mode,startPosition,loop) { this.initialize(mode,startPosition,loop,{}); // Слой 1 this.shape = new cjs.Shape(); this.shape.graphics.f("#66FFFF").s().p("AHQGlQgVgngRgqItTAAQgRAqgVAnQhgCviIAAQiIAAhgivQgWgngQgqQg6iUAAjAQAAjkBTinIANgZQBgivCIAAQCIAABgCvIANAZIOFAAIANgZQBgivCIAAQCIAABgCvQBgCuAAD2QAAD3hgCuQhgCviIAAQiIAAhgivg"); this.timeline.addTween(cjs.Tween.get(this.shape).wait(1)); }).prototype = getMCSymbolPrototype(lib.sputnik, new cjs.Rectangle(-102.4,-59.6,204.8,119.2), null); // stage content: (lib.sputnik_Canvas = function(mode,startPosition,loop) { this.initialize(mode,startPosition,loop,{}); // timeline functions: this.frame_0 = function() { this.addEventListener("tick",f1.bind(this)); var t = 0; function f1(args){ this.sputnik.x = 700/2+200* Math.cos(t); this.sputnik.y = 500/2+100* Math.sin(t); t+= 0.02; } } // actions tween: this.timeline.addTween(cjs.Tween.get(this).call(this.frame_0).wait(1)); // Слой 1 this.sputnik = new lib.sputnik(); this.sputnik.parent = this; this.sputnik.setTransform(176,128.4); this.timeline.addTween(cjs.Tween.get(this.sputnik).wait(1)); }).prototype = p = new cjs.MovieClip(); p.nominalBounds = new cjs.Rectangle(348.6,268.8,204.8,119.2); // library properties: lib.properties = { id: '8B20EF78F9C13D4BA747C5B4CF89B7A3', width: 550, height: 400, fps: 24, color: "#FFFFFF", opacity: 1.00, manifest: [], preloads: [] }; // bootstrap callback support: (lib.Stage = function(canvas) { createjs.Stage.call(this, canvas); }).prototype = p = new createjs.Stage(); p.setAutoPlay = function(autoPlay) { this.tickEnabled = autoPlay; } p.play = function() { this.tickEnabled = true; this.getChildAt(0).gotoAndPlay(this.getTimelinePosition()) } p.stop = function(ms) { if(ms) this.seek(ms); this.tickEnabled = false; } p.seek = function(ms) { this.tickEnabled = true; this.getChildAt(0).gotoAndStop(lib.properties.fps * ms / 1000); } p.getDuration = function() { return this.getChildAt(0).totalFrames / lib.properties.fps * 1000; } p.getTimelinePosition = function() { return this.getChildAt(0).currentFrame / lib.properties.fps * 1000; } an.bootcompsLoaded = an.bootcompsLoaded || []; if(!an.bootstrapListeners) { an.bootstrapListeners=[]; } an.bootstrapCallback=function(fnCallback) { an.bootstrapListeners.push(fnCallback); if(an.bootcompsLoaded.length > 0) { for(var i=0; i<an.bootcompsLoaded.length; ++i) { fnCallback(an.bootcompsLoaded[i]); } } }; an.compositions = an.compositions || {}; an.compositions['8B20EF78F9C13D4BA747C5B4CF89B7A3'] = { getStage: function() { return exportRoot.getStage(); }, getLibrary: function() { return lib; }, getSpriteSheet: function() { return ss; }, getImages: function() { return img; } }; an.compositionLoaded = function(id) { an.bootcompsLoaded.push(id); for(var j=0; j<an.bootstrapListeners.length; j++) { an.bootstrapListeners[j](id); } } an.getComposition = function(id) { return an.compositions[id]; } })(createjs = createjs||{}, AdobeAn = AdobeAn||{}); var createjs, AdobeAn;
import createNode from "./createNode"; /** * @function modal * @param {HTMLElement} content */ const makeModal = (content) => { const modalNode = createNode("div", { class: "o-modal" }); modalNode.addEventListener("click", (e) => { if (e.target === modalNode) { modalNode.remove(); } }); modalNode.append(content); return modalNode; }; export default makeModal;
import React from 'react' import '../Styles/Menu.css' import { withRouter, Redirect } from 'react-router-dom' import {connect} from "react-redux"; import PropTypes from 'prop-types' import {logout} from "../actions/auth" import { useHistory } from 'react-router-dom'; const Menu = ({auth}) => { let history = useHistory(); return ( <div className='menu-main-container'> <div className="menu-logo-user"> <img onClick={() => history.push('/profile')} className="menu-img-logo" src={auth && auth.user ? auth.user.photo : require('../Assets/icon.png')} alt="" /> </div> <div className="menu-main-menu"> {(!auth || auth.loading || !auth.user || !auth.user._id) && <p onClick={() => history.push("/login")}> Inicia sesión </p> } <p onClick={() => history.push('/movies')}> Peliculas </p> <p onClick={() => history.push('/series')}> Series </p> <p onClick={() => history.push('/books')}> Libros </p> <p onClick={() => history.push('/workout')}> Ejercicio </p> <p onClick={() => history.push('/forum')}> Foro </p> {auth && !auth.loading && auth.user && auth.user._id && <p onClick={logout}> Cerrar Sesión </p> } </div> </div> ) }; Menu.propTypes = { auth: PropTypes.object.isRequired } const mapStateToProps = state => ({ auth: state.auth }) export default withRouter(connect(mapStateToProps, null)(Menu))
import React from "react"; import useNavigation from "../navigation/useData.hook"; import SelectingCharacterByPlayerOne from "./left/selectingCharacterByPlayerOne.presenter"; import SelectingCharacterStyleByPlayerOne from "./left/selectingCharacterStyleByPlayerOne.presenter"; import SelectingCharacterColorByPlayerOne from "./left/selectingCharacterColorByPlayerOne.presenter"; import SelectedCharacterCancellableByPlayerOne from "./left/selectedCharacterCancellableByPlayerOne.presenter"; import SelectedCharacter from "./left/selectedCharacter.view"; import TRAINING_SELECTING_CHARACTER_TWO from "../navigation/state/trainingSelectingCharacterTwo.state"; import TRAINING_SELECTING_STAGE from "../navigation/state/trainingSelectingStage.state"; import VERSUS_SELECTING_CHARACTERS from "../navigation/state/versusSelectingCharacters.state"; import VERSUS_SELECTING_STAGE from "../navigation/state/versusSelectingStage.state"; import SELECTING_CHARACTER from "../navigation/sideState/selectingCharacter.state"; import SELECTING_STYLE from "../navigation/sideState/selectingStyle.state"; import SELECTING_COLOR from "../navigation/sideState/selectingColor.state"; import SELECTED from "../navigation/sideState/selected.state"; export default function LeftSide() { const { state, leftSideState, characterOne } = useNavigation(); if (leftSideState === SELECTING_CHARACTER) { return <SelectingCharacterByPlayerOne />; } if (leftSideState === SELECTING_STYLE) { return <SelectingCharacterStyleByPlayerOne character={characterOne} />; } if (leftSideState === SELECTING_COLOR) { return <SelectingCharacterColorByPlayerOne character={characterOne} />; } if (leftSideState === SELECTED && state === TRAINING_SELECTING_CHARACTER_TWO) { return <SelectedCharacterCancellableByPlayerOne character={characterOne} />; } if (leftSideState === SELECTED && state === VERSUS_SELECTING_CHARACTERS) { return <SelectedCharacterCancellableByPlayerOne character={characterOne} />; } if (state === VERSUS_SELECTING_STAGE) { return <SelectedCharacterCancellableByPlayerOne character={characterOne} />; } if (state === TRAINING_SELECTING_STAGE) { return <SelectedCharacter character={characterOne} />; } return null; }
import React, { Component } from "react"; import Board from "./Board"; import "./index.css"; const tail = arr => arr[arr.length - 1]; const calculateWinner = squares => { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return { winner: squares[a], winnerCoords: lines[i] }; } } return { winner: null, winnerCoords: null }; }; class Game extends Component { constructor(props) { super(props); this.state = { // hist contains an array of objects, each with its own board at a specific time history: [{ squares: Array(9).fill(null), coordLocation: "" }], reversed: false, stepNumber: 0, xIsNext: true }; } clickCoordinates = loc => { // need to add 1 b/c Math.ceil(0/3) === 0 loc += 1; const col = loc % 3; return `Location - (Column: ${col ? col : 3} , Row: ${Math.ceil(loc / 3)})`; }; handleClick = i => { console.log(this.clickCoordinates(i)); // i === the location on the board clicked // we take all the past move (history), create a new array of up to and including the current step. // arr.slice([begin[, end]]); end: Zero-based index before which to end extraction. slice extracts up to but not including end. const history = this.state.history.slice(0, this.state.stepNumber + 1); // take the last index value of the array, ie. current version from our history const current = tail(history); // deep copy of the array const squares = [...current.squares]; // did you win or already click that square if (calculateWinner(squares)["winner"] || squares[i]) { return; } squares[i] = this.upNext(); this.setState({ history: history.concat([ { squares: squares, coordLocation: this.clickCoordinates(i) } ]), // by calling history prior to the concat, we do not get the full length of what will be set so we effectively get our new history.length - 1 stepNumber: history.length, xIsNext: !this.state.xIsNext }); }; jumpTo = step => { this.setState({ stepNumber: step, xIsNext: step % 2 === 0 }); }; upNext = () => (this.state.xIsNext ? "X" : "O"); render() { const history = this.state.history; const current = history[this.state.stepNumber]; const { winner, winnerCoords } = calculateWinner(current.squares); // console.log({ winner }); const moves = history.map((step, move) => { // if idx ie. move is is not 0 then give the number const desc = move ? `Go to move #${move}. ${step.coordLocation}` : `Go to game start`; return ( <li key={move}> <button style={{ fontWeight: move === this.state.stepNumber ? "bold" : "normal" }} onClick={() => this.jumpTo(move)} > {desc} </button> </li> ); }); let status; if (winner) { status = `Winner ${winner}`; // was there no winner and the match board does not contain any blanks, then draw } else if (!current.squares.includes(null)) { status = `The match resulted in a draw`; } else { status = `Next Player: ${this.upNext()}`; } return ( <div className="game"> <div className="game-board"> <Board squares={current.squares} onClick={ i => this.handleClick(i) // need to pass i, i will be defined in the Board } upNext={this.upNext} winningCoordinates={winnerCoords} /> </div> <div className="game-info"> <div>{status}</div> <button onClick={() => { this.setState({ reversed: !this.state.reversed }); }} > Reverse Order </button> <ol>{this.state.reversed ? moves.reverse() : moves}</ol> </div> </div> ); } } export default Game;
import * as path from "path"; import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import rollupReplace from "@rollup/plugin-replace"; export default defineConfig({ server: { port: 3000, }, plugins: [ rollupReplace({ preventAssignment: true, values: { __DEV__: JSON.stringify(true), "process.env.NODE_ENV": JSON.stringify("development"), }, }), react(), ], build: { rollupOptions: { // Build two separate bundles, one for each app. input: { main: path.resolve(__dirname, "index.html"), inbox: path.resolve(__dirname, "inbox/index.html"), }, }, }, resolve: process.env.USE_SOURCE ? { alias: { "@remix-run/router": path.resolve( __dirname, "../../packages/router/index.ts" ), "react-router": path.resolve( __dirname, "../../packages/react-router/index.ts" ), "react-router-dom": path.resolve( __dirname, "../../packages/react-router-dom/index.tsx" ), }, } : {}, });
/* eslint-env jest */ import React from 'react'; import { shallow } from 'enzyme'; import { Bio } from '../Bio'; it('renders Profile component without crashing', () => { shallow( <Bio profile={[]} avatar followers following />, ); });
import React from 'react' import { configure, shallow } from 'enzyme' import Counter from '../src/Counter' import Adapter from 'enzyme-adapter-react-16' import _ from 'lodash' configure({ adapter: new Adapter() }) test('Counter accepts initial value', () => { const wrapper = shallow(<Counter initial={123} />) expect(wrapper.find('span').text()).toBe('123') const wrapper2 = shallow(<Counter initial={345} />) expect(wrapper2.find('span').text()).toBe('345') }) test('Counter increments and decrements by buttons', () => { const wrapper = shallow(<Counter initial={123} />) expect(wrapper.find('span').text()).toBe('123') const incButton = wrapper.findWhere((e) => e.type() === 'button' && e.text() === 'Increment') const decButton = wrapper.findWhere((e) => e.type() === 'button' && e.text() === 'Decrement') incButton.simulate('click') expect(wrapper.find('span').text()).toBe('124') decButton.simulate('click') expect(wrapper.find('span').text()).toBe('123') decButton.simulate('click') expect(wrapper.find('span').text()).toBe('122') incButton.simulate('click') expect(wrapper.find('span').text()).toBe('123') }) test('Counter randomize functionality', () => { const wrapper = shallow(<Counter initial={543} />) const PROBES = 10 expect(wrapper.find('span').text()).toBe('543') const randButton = wrapper.findWhere((e) => e.type() === 'button' && e.text() === 'Randomize') const values = _.times(PROBES, () => { randButton.simulate('click') return parseInt(wrapper.find('span').text()) }) expect(_.uniq(values).length).toBeGreaterThan(PROBES - 2) expect(values).not.toEqual(_.sortBy(values)) expect(values).not.toEqual(_.reverse(_.sortBy(values))) })
module.exports = { database: "mongodb://localhost/party", secret: "Endless Sunshine in Darkness" };
// ref (nav bar idea taking from ):https://startbootstrap.com/theme/creative var navbarCollapse = function () { if ($("#mainNav").offset().top > 100) { $("#mainNav").addClass("navbar-scrolled"); } else { $("#mainNav").removeClass("navbar-scrolled"); } }; navbarCollapse(); $(window).scroll(navbarCollapse);
import React, {Component} from 'react'; import { Text, StyleSheet, View, SafeAreaView, TextInput, TouchableOpacity, } from 'react-native'; import {Formik} from 'formik'; import * as Yup from 'yup'; const loginSchema = Yup.object().shape({ email: Yup.string() .email('Email Khong Hop le') .required('Email Khong dc bo trong'), password: Yup.string().required('Password Khong dc bo trong'), }); export default class ValidationFormik extends Component { handleSubmitFormil = value => { console.log(value); }; render() { return ( <SafeAreaView style={styles.container}> <View style={styles.loginForm}> <Text> Login Form</Text> <Formik initialValues={{email: '', password: ''}} onSubmit={this.handleSubmitFormil} validationSchema={loginSchema}> {({values, handleSubmit, handleChange, errors}) => ( <> <View style={styles.inputContainer}> <Text>Email</Text> <TextInput style={[ styles.inputField, errors.email && styles.inputError, ]} value={values.email} placeholder="example@gmail.com" onChangeText={handleChange('email')} /> {errors.email && ( <Text style={styles.errText}>{errors.email}</Text> )} </View> <View style={styles.inputContainer}> <Text>Password</Text> <TextInput style={[ styles.inputField, errors.password && styles.inputError, ]} value={values.password} placeholder="*****" secureTextEntry={true} //=> danh cho Password onChangeText={handleChange('password')} /> {errors.password && ( <Text style={styles.errText}>{errors.password}</Text> )} </View> <TouchableOpacity style={styles.signInBtn} onPress={handleSubmit}> <Text>Sign in</Text> </TouchableOpacity> </> )} </Formik> </View> </SafeAreaView> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, loginForm: { flex: 1, justifyContent: 'center', paddingHorizontal: 20, }, inputField: { borderWidth: 1, padding: 8, }, inputContainer: { padding: 8, }, signInBtn: { backgroundColor: '#bffefe', padding: 8, width: '30%', alignItems: 'center', marginTop: 8, borderRadius: 8, }, inputError: { borderColor: 'red', }, errText: { color: 'red', }, });
module.exports = ["index.md","test.md"]
$(function(){ $("#searchword").focus(function(){ $("#searchword").css("width","340px"); //$("#searchword").animate("width","340px"); }); $("#searchword").blur(function(){ $("#searchword").css("width","200px"); //$("#searchword").animate("width","200px"); }); $(".left-ul-li").click(function(){ $(".left-ul-li").css("border","0px"); $(".left-ul-li").css("background-color","white"); $(this).css("background-color","#EAF4FE"); $(this).css("border-left","solid 2px #328FFA") console.log($("#input-joinfile")); }); //console.log($("#input-joinfile")); $("#input-joinfile").change(function(){ $("#uploadform").submit(); }); });
"use strict"; const dotenv = require("dotenv"); dotenv.config(); const log4js = require("log4js"); const logger = log4js.getLogger("APP.JS"); const express = require("express"); const fileupload = require("express-fileupload"); const session = require("express-session"); const http = require("http"); const path = require("path"); const cors = require("cors"); const morgan = require("morgan")("dev"); const bodyParser = require("body-parser"); const expressJWT = require("express-jwt"); const jwt = require("jsonwebtoken"); const bearerToken = require("express-bearer-token"); const constants = require("./config/constans.json"); // Set host/port const host = process.env.HOST || constants.host; const port = process.env.PORT || constants.port; // Set up ACAO const app = express(); app.use(fileupload({ useTempFiles: true })); app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.setHeader( "Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE" ); res.header( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization" ); next(); }); app.options("*", cors()); app.use(cors()); app.use(morgan); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(express.static(path.join(__dirname, "public"))); // app.use( // session({ // secret: "LuanVan", // cookie: { maxAge: 60000 }, // saveUninitialized: false, // }) // ); app.set("secret", "mysecret"); app.use( expressJWT({ secret: "mysecret", algorithms: ["HS256"], }).unless({ path: ["/api/auth", "/api/auth/register", "/api/auth/getkey"], }) ); app.use(bearerToken()); logger.level = "debug"; // --> Add routes app.use("/public", express.static("public")); app.use("/api/auth", require("./routes/auth.route")); app.use((req, res, next) => { const err = new Error("Not Found"); err.status = 404; next(err); }); const server = http.createServer(app).listen(port, () => { console.log("SERVER STARTED ON LOCALHOST:9999"); }); logger.info("********** SERVER START **************************"); logger.info("********** http://%s:%s *****************", host, port);
const validator = require('validator'); const bcrypt = require('bcrypt-nodejs'); var models = require('../models'); var Users = models.users; module.exports = { getUser: function (req, res, next) { var id = req.params.id; var user = req.user; if (!id) { return res.status(400).json({ success: false, message: "Parameter is missing" }).end(); } Users.findOne({ where: { id : id } }) .then((user) => { if(user === null) { return res.status(400).json({ success: false, message: "No User Found" }).end(); } return res.status(200).json({ success: true, user }).end(); }) .catch(function(err) { console.log(err); return res.status(500).json({ success: false, message: "Internal Server Error" }).end(); }) }, // end of getUser getAllUser: function (req, res, next) { Users.findAll({}) .then((users) => { if(users === null) { return res.status(200).json({ success: false, message: "No Users Exist" }).end(); } return res.status(200).json({ success: true, users }).end(); }) }, updateUserInfo: function (req, res, next) { const validateResult = validateUpdateUserInfoFormBody(req.body) if (!validateResult.success) { return res.status(400).json({ success: false, message: validateResult.message, errors: validateResult.errors }).end(); } let user = req.body; let id = req.params.id; Users.update(user, { where: { id: id } }) .then((data) => { return Users.findOne({ where: { id : id } }); }) .then((data) => { return res.status(200).json({ success: true, message: 'Succesfully updated account', user: data }).end(); }) .catch((error) => { console.log(err); return res.status(500).json({ success: false, message: "Internal Server Error" }).end(); }) }, updateUserPassword: function (req, res, next) { const validateResult = validateUpdateUserPasswordFormBody(req.body) if (!validateResult.success) { return res.status(400).json({ success: false, message: validateResult.message, errors: validateResult.errors }).end(); } let id = req.params.id; let password = req.body; let errors = {}; if (password.newPassword !== password.newPasswordRepeat) { errors.newPasswordRepeat = 'Does not match new password field'; return res.status(400).json({ success: false, message: 'Check Form For Errors', errors: errors }).end(); } let newPassword = bcrypt.hashSync(password.newPassword); Users.findOne({ where: { id: id } }) .then(function(user) { if (!user) { errors.user = 'User Does Not Exist'; return res.status(400).json({ success: false, message: 'Check Form For Errors', errors: errors }).end(); } else { if (!bcrypt.compareSync(password.password, user.hashed_password)) { errors.password = 'You provided a wrong password'; return res.status(400).json({ success: false, message: 'Check Form For Errors', errors: errors }).end(); } else { return Users.update({ hashed_password: newPassword }, { where: { id: id } }); } } }) .then((data) => { return Users.findOne({ where: { id : id } }); }) .then((data) => { return res.status(200).json({ success: true, message: 'Succesfully updated password', user: data }).end(); }) .catch((error) => { // console.log(err); return res.status(500).json({ success: false, message: "Internal Server Error" }).end(); }); }, statusUpdate: function (req, res, next) { let id = req.params.id || 0; // let status = req.body.status; Users.findOne({ where: { id : id } }) .then((user) => { if (!user) { return res.status(200).json({ success: false, message: 'No Such User Exists' }).end(); } return user; }) .then((user) => { let status = user.status; return Users.update({ status: !status }, { where: { id : id } }); }) .then((data) => { return Users.findOne({ where: { id : id } }); }) .then((data) => { return res.status(200).json({ success: true, message: 'Succesfully Changed User Status', user: data }).end(); }) .catch(function(error) { console.log(error); return res.status(500).json({ success: false, message: "Internal Server Error" }).end(); }) }, } function validateUpdateUserInfoFormBody(payload) { const errors = {}; let isFormValid = true; let message = ''; if (!payload || typeof payload.username !== 'string' || payload.username.trim().length === 0) { isFormValid = false; errors.username = 'Please provide your Username'; } if (!payload || typeof payload.first_name !== 'string' || payload.first_name.trim().length === 0) { isFormValid = false; errors.first_name = 'Please provide your First Name'; } if (!payload || typeof payload.last_name !== 'string' || payload.last_name.trim().length === 0) { isFormValid = false; errors.last_name = 'Please provide your Last Name'; } if (!payload || typeof payload.email !== 'string' || !validator.isEmail(payload.email) ) { isFormValid = false; errors.email = 'Please provide your Email'; } if (!isFormValid) { message = 'Check the form for errors'; } return { success: isFormValid, message, errors } } function validateUpdateUserPasswordFormBody(payload) { const errors = {}; let isFormValid = true; let message = ''; if (!payload || typeof payload.password !== 'string' || payload.password.trim().length === 0) { isFormValid = false; errors.password = 'Please provide your current password'; } if (!payload || typeof payload.newPassword !== 'string' || payload.newPassword.trim().length === 0 || payload.newPassword.trim().length < 6) { isFormValid = false; errors.newPassword = 'Please provide your new password'; if (payload.newPassword.trim().length < 6) { errors.newPassword = 'Must be atleast 6 characters.'; } } if (!payload || typeof payload.newPasswordRepeat !== 'string' || payload.newPasswordRepeat.trim().length === 0 || payload.newPasswordRepeat.trim().length < 6) { isFormValid = false; errors.newPasswordRepeat = 'Please provide your new password again.'; let len = payload.newPasswordRepeat.trim().length; if (len < 6) { errors.newPasswordRepeat = 'Must be atleast 6 characters.'; } } if (!isFormValid) { message = 'Check the form for errors'; } return { success: isFormValid, message, errors } }
Ext.Loader.setConfig({ enabled: true }); Ext.Loader.setPath('Ext.ux', '/Scripts/Ext4.0/ux'); Ext.require([ 'Ext.form.Panel', 'Ext.ux.form.MultiSelect', 'Ext.ux.form.ItemSelector' ]); var pageSize = 25; //聲明grid Ext.define('GIGADE.OrderBrandProduces', { extend: 'Ext.data.Model', fields: [ //定單信息 { name: "Order_Id", type: "int" }, //付款單號 { name: "Order_Name", type: "string" }, //訂購人名稱 { name: "Delivery_Name", type: "string" }, //收貨人 { name: "Order_Amount", type: "int" }, //訂單應收金額 { name: "Order_Payment", type: "string" }, //付款方式 { name: "Order_Status", type: "string" }, //訂單狀態 { name: "ordercreatedate", type: "string" }, //建立日期 { name: "Note_Admin", type: "string" }, //管理員備註 { name: "redirect_name", type: "string" }, //來源ID { name: "redirect_url", type: "string" }, //來源ID連接 { name: "order_pay_message", type: "string" },//點數使用明細 //定購人信息 { name: "user_id", type: "int" }, //用戶編號 下面的這些是編輯用戶表時要用到的。 { name: "user_email", type: "string" }, //用戶郵箱 { name: "user_name", type: "string" }, //用戶名 { name: "user_password", type: "string" }, //密碼 { name: "user_gender", type: "string" }, //性別 { name: "user_birthday_year", type: "string" }, //年 { name: "user_birthday_month", type: "string" }, //月 { name: "user_birthday_day", type: "string" }, //日 { name: "user_zip", type: "string" }, //用戶地址 { name: "user_address", type: "string" }, //用戶地址 { name: "birthday", type: "string" }, //生日 { name: "user_mobile", type: "string" }, { name: "user_phone", type: "string" }, //聯絡電話 { name: "suser_reg_date", type: "string" }, //註冊日期 { name: "mytype", type: "string" }, { name: "send_sms_ad", type: "string" }, //是否接收簡訊廣告 { name: "adm_note", type: "string" } //管理員備註 ] }); //獲取grid中的數據 var OrderBrandProducesListStore = Ext.create('Ext.data.Store', { pageSize: pageSize, model: 'GIGADE.OrderBrandProduces', proxy: { type: 'ajax', url: '/OrderManage/GetOrderList', actionMethods: 'post', reader: { type: 'json', totalProperty: 'totalCount', root: 'data' } } }); //運送方式Model Ext.define("gigade.typeModel", { extend: 'Ext.data.Model', fields: [ { name: "type_id", type: "string" }, { name: "type_name", type: "string" } ] }); var sm = Ext.create('Ext.selection.CheckboxModel', { listeners: { selectionchange: function (sm, selections) { Ext.getCmp("OrderBrandProducesListGrid").down('#Remove').setDisabled(selections.length == 0); Ext.getCmp("OrderBrandProducesListtGrid").down('#Edit').setDisabled(selections.length == 0) } } }); var searchStatusrStore = Ext.create('Ext.data.Store', { fields: ['txt', 'value'], data: [ { "txt": "所有訂單資料", "value": "0" }, { "txt": "訂單編號", "value": "1" }, { "txt": "訂購人姓名", "value": "2" }, { "txt": "訂購人信箱", "value": "3" }, { "txt": "收貨人姓名", "value": "4" }, { "txt": "來源ID", "value": "5" } ] }); var dateoneStore = Ext.create('Ext.data.Store', { fields: ['txt', 'value'], data: [ { "txt": "所有日期", "value": "0" }, { "txt": "訂單日期", "value": "1" } ] }); //付款方式 var PayTypeStore = Ext.create('Ext.data.Store', { fields: ['txt', 'value'], data: [ { "txt": "所有方式", "value": "0" }, { "txt": "聯合信用卡", "value": "1" }, { "txt": "永豐ATM", "value": "2" }, { "txt": "藍新信用卡", "value": "3" }, { "txt": "支付寶", "value": "4" }, { "txt": "銀聯", "value": "5" }, { "txt": "傳真刷卡", "value": "6" }, { "txt": "延遲付款", "value": "7" }, { "txt": "黑貓貨到付款", "value": "8" }, { "txt": "現金", "value": "9" }, { "txt": "中國信託信用卡", "value": "10" }, { "txt": "中國信託信用卡紅利折抵", "value": "11" }, { "txt": "中國信託信用卡紅利折抵(10%)", "value": "12" }, { "txt": "網際威信 HiTRUST 信用卡", "value": "13" }, { "txt": "中國信託信用卡紅利折抵(20%)", "value": "14" }, { "txt": "7-11貨到付款", "value": "15" } ] }); OrderBrandProducesListStore.on('beforeload', function () { Ext.apply(OrderBrandProducesListStore.proxy.extraParams, { selecttype: Ext.getCmp('select_type').getValue(), //選擇查詢種類,訂單編號,訂購姓名 searchcon: Ext.getCmp('search_con').getValue(), //查詢的內容 timeone: Ext.getCmp('timeone').getValue(), dateOne: Ext.getCmp('dateOne').getValue(), dateTwo: Ext.getCmp('dateTwo').getValue(), //slave_status: Ext.htmlEncode(Ext.getCmp("slave_status").getValue().Slave_Status), //付款單狀態,付款失敗,已發貨 order_payment: Ext.getCmp("order_payment").getValue(), //付款方式,AT order_pay: Ext.htmlEncode(Ext.getCmp("order_pay").getValue().Order_Pay) //付款狀態 }) }); Ext.onReady(function () { var frm = Ext.create('Ext.form.Panel', { id: 'frm', layout: 'anchor', height: 180, border: 0, width: document.documentElement.clientWidth, items: [ { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', margin: '5 0 0 5', fieldLabel: "查詢條件", items: [ { xtype: 'combobox', allowBlank: true, editable: false, hidden: false, id: 'select_type', name: 'select_type', store: searchStatusrStore, displayField: 'txt', valueField: 'value', typeAhead: true, forceSelection: false, margin: '0 10 0 5', emptyText: '所有訂單資料' }, { xtype: 'textfield', fieldLabel: "查詢內容", width: 200, labelWidth: 60, margin: '0 10 0 0', id: 'search_con', name: 'search_con' } ] }, { xtype: 'fieldcontainer', combineErrors: true, margin: '5 0 0 5', fieldLabel: '日期條件', layout: 'hbox', items: [ { xtype: 'combobox', id: 'timeone', name: 'timeone', fieldLabel: "", margin: '0 10 0 5', store: dateoneStore, displayField: 'txt', valueField: 'value', labelWidth: 80, value: 0 }, { xtype: "datetimefield", labelWidth: 60, margin: '0 0 0 0', id: 'dateOne', name: 'dateOne', format: 'Y-m-d', allowBlank: false, submitValue: true, value: '2010-01-01' }, { xtype: 'displayfield', margin: '0 0 0 0', value: "~" }, { xtype: "datetimefield", format: 'Y-m-d', id: 'dateTwo', name: 'dateTwo', margin: '0 0 0 0', allowBlank: false, submitValue: true, value: Tomorrow() } ] }, { xtype: 'fieldcontainer', combineErrors: true, fieldLabel: '付款單狀態', margin: '5 0 0 5', layout: 'hbox', items: [ { xtype: 'combobox', id: 'a', name: 'a', store: paymentType, fieldLabel: "", width: 200, labelWidth: 80, margin: '0 10 0 5', displayField: 'remark', valueField: 'ParameterCode', emptyText: '付款單狀態' } ] }, { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', margin: '5 0 0 5', fieldLabel: "付款方式", items: [ { xtype: 'combobox', allowBlank: true, hidden: false, id: 'order_payment', name: 'order_payment', store: PayTypeStore, queryMode: 'local', width: 200, labelWidth: 80, margin: '0 10 0 5', displayField: 'txt', valueField: 'value', typeAhead: true, forceSelection: false, editable: false, emptyText: '所有方式' } ] }, { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', margin: '5 0 0 5', fieldLabel: "付款狀態", items: [ { xtype: 'fieldcontainer', combineErrors: true, margin: '0 0 0 5', fieldLabel: '', width: 350, layout: 'hbox', items: [ { xtype: 'radiogroup', id: 'order_pay', name: 'order_pay', colName: 'order_pay', width: 320, defaults: { name: 'Order_Pay' }, columns: 4, items: [ { id: 'OP1', boxLabel: "所有狀態", inputValue: '-1', checked: true, width: 80 }, { id: 'OP2', boxLabel: "已付款", inputValue: '1', width: 80 }, { id: 'OP3', boxLabel: "未付款", inputValue: '2', width: 80 } ] } ] } ] }, { xtype: 'fieldcontainer', combineErrors: true, fieldLabel: '', layout: 'hbox', items: [ { xtype: 'button', text: '送出', iconCls: 'icon-search', margin: '5 0 0 5', id: 'btnQuery', handler: Query } ] } ] }); //頁面加載時創建grid var OrderBrandProducesListGrid = Ext.create('Ext.grid.Panel', { id: 'OrderBrandProducesListGrid', store: OrderBrandProducesListStore, height: 600, columnLines: true, frame: true, columns: [ { header: "付款單號", dataIndex: 'Order_Id', width: 120, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (value != null) { return Ext.String.format("<a id='fkdh" + record.data.Order_Id + "' href='{0}' target='_blank' style='text-decoration:none'>{1}</a>", 'order_show.php?oid='+record.data.Order_Id, record.data.Order_Id); } } }, { header: "訂購人", dataIndex: 'Order_Name', width: 110, align: 'center', renderer: function (value,cellmeta,record,rowIndex,columnIndex,store) { return "<a href='javascript:void(0);' onclick='UpdateUser()'>" + value + "</a>"; } }, { header: "收貨人", dataIndex: 'Delivery_Name', width: 110, align: 'center' }, { header: "訂單應收金額", dataIndex: 'Order_Amount', width: 90, align: 'center' }, { header: "付款方式", dataIndex: 'Order_Payment', width: 205, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { switch (value) { case "1": return ' 聯合信用卡 '; break; case "2": return ' 永豐ATM '; break; case "3": return ' 藍新信用卡 '; break; case "4": return ' 支付寶 '; break; case "5": return ' 銀聯 '; break; case "6": return ' 傳真刷卡 '; break; case "7": return ' 延遲付款'; break; case "8": return ' 黑貓貨到付款 '; break; case "9": return ' 現金 '; break; case "10": return ' 中國信託信用卡 '; break; case "11": return ' 中國信託信用卡紅利折抵 '; break; case "12": return '中國信託信用卡紅利折抵(10%) '; break; case "13": return ' 網際威信 HiTRUST 信用卡 '; break; case "14": return ' 中國信託信用卡紅利折抵(20%) '; break; case "15": return ' 7-11貨到付款 '; break; default: return "數據異常"; break; } } }, { header: "訂單狀態", dataIndex: 'Order_Status', width: 120, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { switch (value) { case "0": return ' 等待付款 '; break; case "1": return '付款失敗 '; break; case "2": return '<font color="green"> 待出貨 </font>'; break; case "3": return ' 出貨中 '; break; case "4": return ' 已出貨 '; break; case "5": return ' 處理中 '; break; case "6": return ' 進倉中 '; break; case "7": return ' 已進倉 '; break; case "8": return ' 已分配 '; break; case "10": return ' 等待取消 '; break; case "20": return ' 訂單異常 '; break; case "89": return ' 單一商品取消 '; break; case "90": return ' 訂單取消 '; break; case "91": return ' 訂單退貨 '; break; case "92": return ' 訂單換貨 '; break; case "99": return ' 訂單歸檔 '; break; default: return "數據異常"; break; } } }, { header: "訂單日期", dataIndex: 'ordercreatedate', width: 150, align: 'center' }, { header: "管理員備註", dataIndex: 'Note_Admin', width: 260, align: 'center' }, { header: "來源ID", dataIndex: 'redirect_name', width: 280, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (record.data.redirect_name != "") { return Ext.String.format('<a href="{0}" target="_blank">{1}</a>', record.data.redirect_url, record.data.redirect_name); } } } ], tbar: [ { xtype: 'button', id: 'Add', text: ADD, iconCls: 'icon-add', hidden: true, handler: onAddClick }, { xtype: 'button', id: 'Edit', text: EDIT, iconCls: 'icon-edit', hidden: true, disabled: true, handler: onEditClick }, { xtype: 'button', id: 'Remove', text: REMOVE, iconCls: 'icon-remove', hidden: true, disabled: true, handler: onRemoveClick } ], listeners: { scrollershow: function (scroller) { if (scroller && scroller.scrollEl) { scroller.clearManagedListeners(); scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller); } } }, bbar: Ext.create('Ext.PagingToolbar', { store: OrderBrandProducesListStore, pageSize: pageSize, displayInfo: true, displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}', emptyMsg: NOTHING_DISPLAY }) }); Ext.create('Ext.Viewport', { layout: 'anchor', items: [frm, OrderBrandProducesListGrid], renderTo: Ext.getBody(), autoScroll: true, listeners: { resize: function () { OrderBrandProducesListGrid.width = document.documentElement.clientWidth; this.doLayout(); } } }); ToolAuthority(); OrderBrandProducesListStore.load({ params: { start: 0, limit: 25 } }); }) function UpdateUser() { var row = Ext.getCmp("OrderBrandProducesListGrid").getSelectionModel().getSelection(); if (row.length == 0) { Ext.Msg.alert(INFORMATION, NO_SELECTION); } else if (row.length > 1) { Ext.Msg.alert(INFORMATION, ONE_SELECTION); } else if (row.length == 1) { editFunction(row[0], OrderBrandProducesListStore); } } onAddClick = function () { editFunction(null, OrderBrandProducesListStore); } onEditClick = function () { var row = Ext.getCmp("OrderBrandProducesListGrid").getSelectionModel().getSelection(); if (row.length == 0) { Ext.Msg.alert(INFORMATION, NO_SELECTION); } else if (row.length > 1) { Ext.Msg.alert(INFORMATION, ONE_SELECTION); } else if (row.length == 1) { editFunction(row[0], OrderBrandProducesListStore); } } onRemoveClick = function () { var row = Ext.getCmp("OrderBrandProducesListGrid").getSelectionModel().getSelection(); if (row.length < 0) { Ext.Msg.alert(INFORMATION, NO_SELECTION); } else { Ext.Msg.confirm(CONFIRM, Ext.String.format(DELETE_INFO, row.length), function (btn) { if (btn == 'yes') { var rowIDs = ''; for (var i = 0; i < row.length; i++) { rowIDs += row[i].data.id + '|'; } Ext.Ajax.request({ url: '/Promotions/DeletePromotionsAmountGift', method: 'post', params: { rowID: rowIDs }, success: function (form, action) { var result = Ext.decode(form.responseText); Ext.Msg.alert(INFORMATION, SUCCESS); if (result.success) { SinopacedtailListStore.load(1); } }, failure: function () { Ext.Msg.alert(INFORMATION, FAILURE); } }); } }); } } /************匯入到Excel**ATM************/ function Export() { Ext.Ajax.request({ url: "/SinopacList/Export", success: function (response) { if (response.responseText == "true") { window.location = '../../ImportUserIOExcel/sinpac_list.csv'; } } }); } //查询 Query = function () { OrderBrandProducesListStore.removeAll(); Ext.getCmp("OrderBrandProducesListGrid").store.loadPage(1, { params: { selecttype: Ext.getCmp('select_type').getValue(), //選擇查詢種類,訂單編號,訂購姓名 searchcon: Ext.getCmp('search_con').getValue(), //查詢的內容 timeone: Ext.getCmp('timeone').getValue(), dateOne: Ext.getCmp('dateOne').getValue(), dateTwo: Ext.getCmp('dateTwo').getValue(), slave_status: Ext.htmlEncode(Ext.getCmp("slave_status").getValue().Slave_Status), //付款單狀態,付款失敗,已發貨 order_payment: Ext.htmlEncode(Ext.getCmp("order_payment").getValue().Order_Payment), //付款方式,AT order_pay: Ext.htmlEncode(Ext.getCmp("order_pay").getValue().Order_Pay) //付款狀態 } }); }
(function(){ 'use strict'; angular.module('app.sedes', [ 'app.sedes.controller', 'app.sedes.services', 'app.sedes.router', 'app.sedes.directivas' ]); })();
const supertest = require('supertest'); const should = require('should'); const server = supertest.agent('http://localhost:8080'); const credentials = {username: 'supermocha', password: 'superpassword'}; const mockPost = {title: 'should', body:'supertest', author:'supermocha'}; describe('Index Route', function () { it('should return home page', function (done) { // calling fastboot middleware server.get('/').expect('Content-type', /text\/html/).expect(200).end((err, res) => { res.status.should.equal(200); res.error.should.equal(false); done(); }); }); }); describe('Users api', function () { describe('POST, /login', function () { it('should login user and return token', function (done) { server.post('/auth/login').send(credentials).expect('Content-type', /json/).expect(200).end(function (err, res) { res.status.should.equal(200); res.body.should.have.property('token').which.is.a.String(); done(); }); }); }); describe('POST, /delete', function () { it('should delete user', function () { return server.post('/auth/login').send(credentials).expect('Content-type', /json/).expect(200).then(function (res) { res.body.should.have.property('token').which.is.a.String(); var result = JSON.parse(res.text); return result.token; }).then(function (token) { server.post('/auth/delete').set('Authorization', 'Bearer ' + token).send({}).expect(200).end(function (err, res) { res.status.should.equal(200); }); }); }); }); describe('POST, /register', function () { it('should register new user', function (done) { server.post('/auth/register').send(credentials).expect('Content-type', /json/).expect(200).end(function (err, res) { res.status.should.equal(200); res.body.should.have.property('token').which.is.a.String(); done(); }); }); }); }); describe('Posts api', function () { var token = ''; describe('POST, /posts', function () { before(function (done) { server.post('/auth/login').send(credentials).expect('Content-type', /json/).expect(200).end(function (err, res) { res.body.should.have.property('token').which.is.a.String(); var result = JSON.parse(res.text); token = result.token; done() }) }) it('should create new post', function (done) { server.post('/api/posts').set('Authorization', 'Bearer ' + token).send(mockPost).expect(200).end(function (err, res) { res.status.should.equal(200); done(); }) }); }); describe('GET, /posts', function () { it('should get all posts', function (done) { server.get('/api/posts').expect('Content-type', /json/).expect(200).end(function (err, res) { res.status.should.equal(200); res.body.should.be.instanceof(Array).and.with.property('length').which.is.above(0); done(); }) }); it('should get posts where author=supermocha', function (done) { server.get('/api/posts').query({ where: { author: 'supermocha' } }).expect('Content-type', /json/).expect(200).end(function (err, res) { res.status.should.equal(200); res.body.should.be.instanceof(Array).and.with.property('length').which.is.above(0); done(); }) }); }); })
import fb from 'firebase/app' class Service { constructor (title, description, imgSrc = '', promo = false, advantages, gallery, id = null) { this.title = title this.description = description this.imgSrc = imgSrc this.promo = promo this.advantages = advantages this.gallery = gallery this.id = id } } export default { state: { podCategories: [ // { // id: 1, // title: 'Окна', // description: '1.Идейные соображения высшего порядка, а также начало повседневной соображения высшего порядка', // imgSrc: '/static/img/main_slider1.d7da8ad.png', // promo: true, // advantages: [ // {title: 'Лучшая звукоизоляция'}, // {title: 'Лучшая шумоизоляция'}, // {title: 'Лучшая Noизоляция'}, // {title: 'Лучшая пукоизоляция'}, // {title: 'Лучшая рукоизоляция'}, // {title: 'Лучшая рукоизоляция'} // ], // gallery: [ // {img: '/static/img/main_slider1.d7da8ad.png'}, // {img: '/static/img/about.df072d6.png'}, // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/about.df072d6.png'}, // {img: '/static/img/main_slider1.d7da8ad.png'} // ] // }, // { // id: 2, // title: 'Двери', // description: '2.Идейные соображения высшего порядка, а также начало повседневной соображения высшего порядка', // imgSrc: '/static/img/about.df072d6.png', // promo: false, // advantages: [ // {title: 'Лучшая звукоизоляция'}, // {title: 'Лучшая шумоизоляция'}, // {title: 'Лучшая пукоизоляция'}, // {title: 'Лучшая рукоизоляция'}, // {title: 'Лучшая Noизоляция'}, // {title: 'Лучшая Noизоляция'} // ], // gallery: [ // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/main_slider1.d7da8ad.png'}, // {img: '/static/img/about.df072d6.png'}, // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/about.df072d6.png'} // ] // }, // { // id: 3, // title: 'Окна 2', // description: '3.Идейные соображения высшего порядка, а также начало повседневной соображения высшего порядка', // imgSrc: '/static/img/main_slider1.d7da8ad.png', // promo: true, // advantages: [ // {title: 'Лучшая пукоизоляция'}, // {title: 'Лучшая рукоизоляция'}, // {title: 'Лучшая звукоизоляция'}, // {title: 'Лучшая шумоизоляция'}, // {title: 'Лучшая Noизоляция'}, // {title: 'Лучшая Noизоляция'} // ], // gallery: [ // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/about.df072d6.png'}, // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/about.df072d6.png'}, // {img: '/static/img/main_slider1.d7da8ad.png'} // ] // }, // { // id: 4, // title: 'Двери 2', // description: '4.Идейные соображения высшего порядка, а также начало повседневной соображения высшего порядка', // imgSrc: '/static/img/about.df072d6.png', // promo: false, // advantages: [ // {title: 'Лучшая рукоизоляция'}, // {title: 'Лучшая Noизоляция'}, // {title: 'Лучшая звукоизоляция'}, // {title: 'Лучшая шумоизоляция'}, // {title: 'Лучшая пукоизоляция'}, // {title: 'Лучшая пукоизоляция'} // ], // gallery: [ // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/about.df072d6.png'}, // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/main_slider1.d7da8ad.png'} // ] // }, // { // id: 5, // title: 'Окна 3', // description: '5.Идейные соображения высшего порядка, а также начало повседневной соображения высшего порядка', // imgSrc: '/static/img/main_slider1.d7da8ad.png', // promo: false, // advantages: [ // {title: 'Лучшая звукоизоляция'}, // {title: 'Лучшая рукоизоляция'}, // {title: 'Лучшая шумоизоляция'}, // {title: 'Лучшая пукоизоляция'}, // {title: 'Лучшая Noизоляция'}, // {title: 'Лучшая Noизоляция'} // ], // gallery: [ // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/about.df072d6.png'}, // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/about.df072d6.png'} // ] // }, // { // id: 6, // title: 'Двери 3', // description: '6.Идейные соображения высшего порядка, а также начало повседневной соображения высшего порядка', // imgSrc: '/static/img/about.df072d6.png', // promo: true, // advantages: [ // {title: 'Преимущество нет :('} // ], // gallery: [ // {img: '/static/img/main_slider1.d7da8ad.png'}, // {img: '/static/img/podservices.c6790b6.png'}, // {img: '/static/img/main_slider1.d7da8ad.png'}, // {img: '/static/img/about.df072d6.png'}, // {img: '/static/img/main_slider1.d7da8ad.png'} // ] // } ] }, mutations: { createService (state, payload) { // console.log(payload) state.podCategories.push(payload) }, loadProducts (state, payload) { state.podCategories = payload }, updateService (state, payload) { const service = state.podCategories.find(a => { return a.id === payload.id }) service.title = payload.title service.description = payload.description service.promo = payload.promo service.advantages = payload.advantages if (payload.imgSrc) { // console.log(payload.imgSrc) service.imgSrc = payload.imgSrc } if (payload.gallery) { service.gallery = payload.gallery } } // updateService (state, {title, description, promo, advantages, imgSrc, gallery, id}) { // const service = state.podCategories.find(a => { // return a.id === id // }) // service.title = title // service.description = description // service.promo = promo // service.advantages = advantages // service.imgSrc = imgSrc // service.gallery = gallery // } }, actions: { async fetchProducts ({commit}) { const resultProducts = [] try { const serviceVal = await fb.database().ref('services').once('value') // console.log(serviceVal.val()) const services = serviceVal.val() Object.keys(services).forEach(key => { const service = services[key] resultProducts.push( new Service( service.title, service.description, service.imgSrc, service.promo, service.advantages, service.gallery, key ) ) commit('loadProducts', resultProducts) }) } catch (error) { // alert(error.message) throw error } }, async createService ({commit, getters}, payload) { const image = payload.image const gallerySrc = payload.gallery const Promises = [] function setImageStorage (array, service) { array.forEach(async (el, i) => { Promises.push(new Promise(async (resolve, reject) => { const imageExt = el.name.slice(el.name.lastIndexOf('.')) const fileData = await fb.storage().ref(`services/${service.key}/image${i}${imageExt}`).put(el) const img = await fb.storage().ref().child(fileData.ref.fullPath).getDownloadURL() resolve({ img: img }) })) }) } try { const newService = new Service( payload.title, payload.description, '', payload.promo, payload.advantages, [{ img: '1234' }] ) if (image === null) { throw new Error('Main image is required') } else { const service = await fb.database().ref('services').push(newService) await setImageStorage(gallerySrc, service) const gallery = await Promise.all(Promises) await fb.database().ref('services').child(service.key).update({ gallery }) const imageExt = image.name.slice(image.name.lastIndexOf('.')) const fileData = await fb.storage().ref(`services/${service.key}/main${imageExt}`).put(image) const imgSrc = await fb.storage().ref().child(fileData.ref.fullPath).getDownloadURL() await fb.database().ref('services').child(service.key).update({imgSrc}) commit('createService', { ...newService, id: service.key, imgSrc, gallery }) } } catch (error) { alert(error.message) // throw error } }, async updateService ({commit}, {title, description, promo, advantages, imgSrc, gallery, id}) { // console.log(imgSrc) const image = imgSrc const gallerySrc = gallery const Promises = [] // console.log(image) NULL // console.log(gallerySrc) ARRAY(0) function setImageStorage (array, service) { array.forEach(async (el, i) => { // console.log(array) Promises.push(new Promise(async (resolve, reject) => { const imageExt = el.name.slice(el.name.lastIndexOf('.')) const fileData = await fb.storage().ref(`services/${service}/image${i}${imageExt}`).put(el) const img = await fb.storage().ref().child(fileData.ref.fullPath).getDownloadURL() resolve({ img: img }) })) }) } try { let updateObject = { title: title, description: description, promo: promo, advantages: advantages } if (image === null && gallerySrc.length === 0) { // console.log('Not image and not gallery') await fb.database().ref('services').child(id).update(updateObject) commit('updateService', { ...updateObject, id }) } else if (image !== null && gallerySrc.length === 0) { // console.log('True image and not gallery') const imageExt = image.name.slice(image.name.lastIndexOf('.')) const fileData = await fb.storage().ref(`services/${id}/main${imageExt}`).put(image) const imgSrc = await fb.storage().ref().child(fileData.ref.fullPath).getDownloadURL() // console.log(imgSrc) await fb.database().ref('services').child(id).update({ ...updateObject, imgSrc }) commit('updateService', { ...updateObject, imgSrc, id }) } else if (image == null && gallerySrc.length !== 0) { // console.log('Not image and true gallery') await setImageStorage(gallerySrc, id) const gallery = await Promise.all(Promises) await fb.database().ref('services').child(id).update({ ...updateObject, gallery }) commit('updateService', { ...updateObject, gallery, id }) } else { // console.log('All is true') const imageExt = image.name.slice(image.name.lastIndexOf('.')) const fileData = await fb.storage().ref(`services/${id}/main${imageExt}`).put(image) const imgSrc = await fb.storage().ref().child(fileData.ref.fullPath).getDownloadURL() await setImageStorage(gallerySrc, id) const gallery = await Promise.all(Promises) await fb.database().ref('services').child(id).update({ ...updateObject, imgSrc, gallery }) commit('updateService', { ...updateObject, imgSrc, gallery, id }) } } catch (error) { alert(error.message) throw error } }, async removeService ({commit, getters}, id) { // console.log(id) try { await fb.database().ref('services').child(id).remove() await fb.storage().ref('services').child(id).remove() } catch (error) { alert(error.message) throw error } } }, getters: { podCategories (state) { return state.podCategories.map((category) => { return ({ ...category, backgroundStyle: `background:url('${category.imgSrc}') center/cover no-repeat` }) }) }, // services (state) { // return state.podCategories // }, servicePromo (state) { return state.podCategories.filter(service => { return service.promo }) }, serviceById (state) { return serviceId => { return state.podCategories.find(service => { return service.id === serviceId }) } } } }
import { connect } from 'react-redux'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import PlayerList from './PlayerList'; import { requestPlayerReadyState } from './../../../shared/actions'; import styles from './lobby.less'; class Lobby extends Component { constructor(props) { super(props); this.state = { ready: false } } render() { const readyText = `${this.props.ready ? '✔' : ' '} Ready`; return <div className={styles['lobby']}> <PlayerList { ... this.props }/> <button onClick= { this.handleReadyClick.bind(this) } > { readyText } </button> </div> } handleReadyClick() { const action = requestPlayerReadyState(this.props.currentPlayer, !this.state.ready, true); this.props.dispatch(action); if(typeof this.props.playerReady === 'function') { this.props.playerReady(); } } } const mapStateToProps = (state, ownProps) => { const player = state.players.find(p => p.id === ownProps.currentPlayer); return { players: state.players, ready: player && player.ready } } Lobby.propTypes = { currentPlayer: PropTypes.string, playerReady: PropTypes.func }; export default connect( mapStateToProps )(Lobby);
function Kirba(game, x, y){ //constructor for main character Phaser.Sprite.call(this, game, x, y, 'kirba'); this.anchor.set(0.5, 0.5); } Kirba.prototype = Object.create(Phaser.Sprite.prototype); Kirba.prototype.constructor = Kirba; //move method Kirba.prototype.move = function (direction) { //-1 will be left, +1 is right this.x += direction * 3; // move 3 pixels each frame }; Kirba.prototype.jump = function (time) { this.y -= 6; this.game.timeCheck = time + 100; }; Kirba.prototype.floor_him = function (position) { this.y = position; this.game.timeCheck = -1; }; Kirba.prototype.getY = function () { return this.y; }; // Play state State = {}; State.preload = function(){ //background image this.game.load.image('background', 'images/background.png'); //sprites this.game.load.image('ground', 'images/ground.png'); this.game.load.image('grass:8x1', 'images/grass_8x1.png'); this.game.load.image('grass:6x1', 'images/grass_6x1.png'); this.game.load.image('grass:4x1', 'images/grass_4x1.png'); this.game.load.image('grass:2x1', 'images/grass_2x1.png'); this.game.load.image('grass:1x1', 'images/grass_1x1.png'); this.game.load.image('kirba', 'images/kirba_init.png'); //level this.game.load.json('level:1', 'data/level1.json'); } State._loadLevel = function (data){ data.platforms.forEach(this._spawnPlatform, this); this._spawnCharacters({kirba: data.kirba}); } State._spawnPlatform = function(platform){ this.game.add.sprite(platform.x, platform.y, platform.image); } State._spawnCharacters = function (data){ //spawn kirba this.kirba = new Kirba(this.game, data.kirba.x, data.kirba.y); this.game.add.existing(this.kirba); } State.update = function () { this._handleInput(); if((this.game.time.now - this.game.timeCheck) > 100 && this.game.timeCheck!=-1){ this.kirba.floor_him(525); } }; State._handleInput = function () { if (this.keys.left.isDown) { // move kirba left this.kirba.move(-1); } else if (this.keys.right.isDown) { // move kirba right this.kirba.move(1); } else if(this.keys.up.isDown){ this.kirba.jump(this.game.time.now); } }; State.create = function(){ this.keys = this.game.input.keyboard.addKeys({ left: Phaser.KeyCode.LEFT, right: Phaser.KeyCode.RIGHT, up: Phaser.KeyCode.UP }); this.game.add.image(0,0, 'background'); this._loadLevel(this.game.cache.getJSON('level:1')); } window.onload = function () { let game = new Phaser.Game(960, 600, Phaser.AUTO, 'game'); game.state.add('play', State); game.state.start('play'); game.global = { timeCheck: 0, currentY : 0 } }
const express = require('express'); const Router = express.Router(); const { getAllProducts, getProduct, postProduct, putProduct, deleteProduct } = require('../controller/products'); const { uploadFile } = require('../middleware/files'); Router .get('/', getAllProducts) .get('/:id', getProduct) .post('/', uploadFile('image'), postProduct) .put('/:id', uploadFile('image'), putProduct) .delete('/:id', deleteProduct); module.exports = Router;
window.onload = function () { // window.location.assign("https://www.w3schools.com") clicked() // if(Qno > 1){ // location.replace("https://www.w3schools.com") // } }; function start(){ clicked() alert("Start") } var QScreen = document.getElementById("Question-screen"); var question = document.getElementById("question"); var list = document.getElementById("ul"); var score = 0; var Questions = [ { id: 1, question: " 2 + 2 = ?", answer: 4, option: ["2", "6", "9", "4"], }, { id: 2, question: "2 + 7 = ?", answer: 9, option: ["9", "4", "6", "2"], }, { id: 3, question: " 4 + 2 = ? ", answer: 6, option: ["6", "9", "4", "2"], }, { id: 4, question: " 3 + 2 = ? ", answer: 5, option: ["3", "4", "5", "0"], }, ]; var Qno = -1; function clicked() { Qno++; question.innerHTML = Questions[Qno].question; ans1.innerHTML = Questions[Qno].option[0]; ans2.innerHTML = Questions[Qno].option[1]; ans3.innerHTML = Questions[Qno].option[2]; ans4.innerHTML = Questions[Qno].option[3]; ans1.setAttribute("Value",Questions[Qno].option[0]) ans2.setAttribute("Value",Questions[Qno].option[1]) ans3.setAttribute("Value",Questions[Qno].option[2]) ans4.setAttribute("Value",Questions[Qno].option[3]) var Qinfo = document.getElementById("Qno") Qinfo.innerHTML = "Question Number : " + (Qno+1) + "/" + Questions.length; } var ans1 = document.createElement("li"); var ans2 = document.createElement("li"); var ans3 = document.createElement("li"); var ans4 = document.createElement("li"); list.appendChild(ans1); list.appendChild(ans2); list.appendChild(ans3); list.appendChild(ans4); ans1.setAttribute("onCLick","ook(this)") ans2.setAttribute("onCLick","ook(this)") ans3.setAttribute("onCLick","ook(this)") ans4.setAttribute("onCLick","ook(this)") function ook(e){ var resultScreen = document.createElement("div"); var tquest = document.createTextNode("Total Questions : " + Questions.length) var tdiv = document.createElement("p"); var tdivt = document.createTextNode( "Score : " + ((Questions.length*10) + "%" ) + " out of " + (score*10) + "%"); var tques = document.createElement("p") var canst = document.createTextNode("Right Answers : " + score) var cans = document.createElement("p") var wans = document.createElement("p") var wanst = document.createTextNode("Wrong Attempts : " + ( Questions.length - score)) var tryAgain = document.createElement("a") var tryAgaint = document.createTextNode("Try Again") console.log( "Question.length : " + Questions.length) tryAgain.appendChild(tryAgaint) tques.appendChild(tquest) wans.appendChild(wanst) tdiv.appendChild(tdivt); resultScreen.appendChild(tques); resultScreen.appendChild(wans); resultScreen.appendChild(tdiv); cans.appendChild(canst) resultScreen.appendChild(cans); console.log( "score : " + (score*10) + "%") resultScreen.appendChild(tryAgain) tryAgain.setAttribute("href","index.html") var b = e.getAttribute("value") if(b == Questions[Qno].answer){ // changes required when you add question ------------------------------------------ if (Qno < 3) { clicked() // changes required when you add question ------------------------------------------ }else if (Qno >= 3) { QScreen.innerHTML = ""; QScreen.appendChild(resultScreen) } ++score }else{ // changes required when you add question ------------------------------------------ if (Qno < 3) { clicked() // changes required when you add question ------------------------------------------ }else if (Qno >= 3) { QScreen.innerHTML = ""; QScreen.appendChild(resultScreen) } } }
function (x, global) { // pseudo imports (avoids having to use fully qualified names) var vtkImageData = vtk.Common.DataModel.vtkImageData; var vtkActor = vtk.Rendering.Core.vtkActor; var vtkImageMarchingCubes = vtk.Filters.General.vtkImageMarchingCubes; var vtkMapper = vtk.Rendering.Core.vtkMapper; var el = global.el var width = global.width var height = global.height const renderWindow = global.windowRenderer.getRenderWindow(); const renderer = global.windowRenderer.getRenderer(); if( !global.initialized ){ global.actor = vtkActor.newInstance(); renderer.addActor(global.actor); var props = global.actor.getProperty(); props.setAmbient(0.1); props.setDiffuse(0.8); props.setSpecular(0); props.setSpecularPower(0); props.setOpacity(0.15); props.setLighting(true); props.setBackfaceCulling(true); props.setFrontfaceCulling(false); global.mapper = vtkMapper.newInstance(); global.marchingCube = vtkImageMarchingCubes.newInstance({ contourValue: 0.0, computeNormals: true, mergePoints: true, }); global.mapper.setInputConnection(global.marchingCube.getOutputPort()); global.actor.setMapper(global.mapper); } const imageData = global.toVtkImageData(x.data.image); global.marchingCube.setInputData(imageData); global.marchingCube.setContourValue(x.data.isovalue); if( !global.initialized ){ global.initialized = true; renderer.resetCamera(); renderer.getActiveCamera().elevation(-70); renderer.updateLightsGeometryToFollowCamera(); renderer.setUseDepthPeeling(false); renderer.setMaximumNumberOfPeels(10); renderer.setOcclusionRatio(0.1); } renderWindow.render(); }
var searchData= [ ['plansza',['Plansza',['../classokienka_1_1_plansza.html',1,'okienka']]] ];
/* global describe, beforeEach, it, browser, expect */ 'use strict'; var GalleryPagePo = require('./gallery.po'); describe('Gallery page', function () { var galleryPage; beforeEach(function () { galleryPage = new GalleryPagePo(); browser.get('/#/gallery'); }); it('should say GalleryCtrl', function () { expect(galleryPage.heading.getText()).toEqual('gallery'); expect(galleryPage.text.getText()).toEqual('GalleryCtrl'); }); });
import React from 'react'; import ReactDOM from 'react-dom' import { BrowserRouter as Router, Route, Link } from 'react-router-dom' ///HEADER import Header from './components/Header/Header' import HeaderMenuTimeline from "./components/HeaderMenu/HeaderMenuTimeline"; import HeaderMenuCash from "./components/HeaderMenu/HeaderMenuCash"; import HeaderMenuHome from "./components/HeaderMenu/HeaderMenuHome"; //SIDEBAR import Sidebar from './components/Sidebar/Sidebar' import SidebarMenu from './components/SidebarMenu/SidebarMenu' //MAIN WRAPPER import MainWrapper from "./components/MainWrapper/MainWrapper"; class Application extends React.Component { render() { return ( <div className="application"> {this.props.children} </div> ) } } ReactDOM.render(( <Router> <Application path="/"> <Header> <Route exact path="/" component={HeaderMenuHome} /> <Route path="/timeline" component={HeaderMenuTimeline} /> <Route path="/cash" component={HeaderMenuCash} /> </Header> <Sidebar> <Sidebar> <Route component={SidebarMenu}/> </Sidebar> </Sidebar> <MainWrapper> </MainWrapper> </Application> </Router> ), document.getElementById('root'));
import React from 'react' import ReactDOM from 'react-dom' window.React = React window.ReactDOM = ReactDOM // アプリケーション共通の名前空間を用意する window.ReactRailsSample = {} ReactRailsSample.Components = require('./components');
/** * Created by Danylo Tiahun on 25.03.2015. */ $(document).ready(function () { function verifyLogin() { if(logins.indexOf($('#users').val()) < 0 && !$('#allUsers').is(':checked')) { $('#noLoginLabel').prop('hidden', false); return false; } return true; } $("#users").autocomplete({ source : logins, minLength: 0 }).focus(function () { $(this).autocomplete("search"); }); $('#allUsers').change(function () { $('#users').val(""); $('#users').prop('disabled', this.checked); if(this.checked) { $('#noLoginLabel').prop('hidden', true); } }); $('#allTypes').change(function () { $('[name="types"]').prop("checked", this.checked); $('#subBtn').prop('disabled', !$('#allTypes').is(':checked')); }); $('.checkType').change(function () { if($('#allTypes').is(':checked')) { this.checked = !this.checked; } var checkedAtLeastOne = false; $('.checkType').each(function() { if ($(this).is(":checked")) { checkedAtLeastOne = true; } $('#subBtn').prop('disabled', !checkedAtLeastOne); }); }); $('#subBtn').click(function () { return verifyLogin(); }); $('#users').change(function () { $('#noLoginLabel').prop('hidden', verifyLogin()); }); })
window.bg_towards = 0; window.bg_last = 0; (() => { let lastTime = 0 const second = 1000 const frames = 60 const jumps = 20 let f = (t) => { if(window.stop_loop === true) return if((t - lastTime) >= second/frames) { let x = window.bg_last let change = (x-window.bg_towards)/jumps if(change >= .02 || change <= -.02) { x -= change window.bg_last = x document.documentElement.style.setProperty('--bg-offset', `${x}%`) } lastTime = t } requestAnimationFrame(f) } f() })() window.onmousemove = (e) => { const speed = 10 let x = e.clientX / speed window.bg_towards = x } //-- async function graphql(body) { return await fetch('/api', { method: 'POST', body }).then(async r => await r.json()) } const force_auth = false const dummy = { username: "Sweetheart", discriminator: "1857", picture: "/images/sweetheart.png", profile: { about: "I'm absolutely amazing!", description: "Hi, i'm **Sweetheart**!\nAnd i'm absolutely amazing *obviously*!", favorite_color: 0xffffff, socials: [ { name: 'Discord', handle: 'Sweetheart#1857' }, { name: 'Website', handle: 'https://sweetheart.flamingo.dev/' } ], timezone: new Date().toTimeString().substring(0, 5), country: "Netherlands", gender: "???", pronouns: "???/???/???", sexuality: "???" } } const dummy_countries = [ { name: "Netherlands", flag: "🇳🇱" }, { name: "Germany", flag: "🇩🇪" }, { name: "China", flag: "🇨🇳" } ] let user = {} let countries = [] let picker = null window.onload = () => { document.getElementById("main").setAttribute('style', 'background-image: url(/images/Space_parallax.png)') const query = `{settings{oauth invite}}` graphql(query).then(r => { document.getElementById('login').setAttribute('href', r.data.settings.oauth) document.getElementById('invite').setAttribute('href', r.data.settings.invite) }) picker = Pickr.create({ el: '#preview-color', theme: 'nano', default: '#fff', components: { preview: true, hue: true, interaction: { hex: true, input: true, save: true, } } }) picker.on('save', (color, instance) => { user.profile.favorite_color = parseInt(color.toHEXA().join(""), 16) updatePreview() }) if(force_auth) { console.log('authenticated') user = dummy countries = dummy_countries authenticated() return } if(localStorage.discord_session) { console.log('authenticated') graphql(`{identity(session: "${localStorage.discord_session}") { username discriminator picture profile{ about description favorite_color socials { name handle } timezone country gender pronouns sexuality } } countries { name flag }}`).then(r => { user = r.data.identity countries = r.data.countries authenticated() }) }else{ const urlParams = new URLSearchParams(window.location.search); const discordCode = urlParams.get('code'); if(discordCode) { const code_query = `{auth(code: "${discordCode}")}` graphql(code_query).then(r => { localStorage.discord_session = r.data.auth window.location.href = "/" }) } } } function authenticated() { document.getElementById('no-preview').style.display = 'none' document.getElementById('embed').style.display = 'grid' document.getElementById('login').style.display = 'none' document.getElementById('inputs').style.display = 'grid' picker.setColor(`#${user.profile.favorite_color.toString(16)}`) countries.sort((a, b) => a.name.localeCompare(b.name)) let celem = document.getElementById('preview-country') for(let i = 0; i < countries.length; i++) { let c = document.createElement("option") c.innerText = `${countries[i].name} ${countries[i].flag}` c.value = countries[i].name celem.appendChild(c) } celem.value = user.profile.country updatePreview() } /* "__NAME:__ HANDLE" <li> <div> {MD} </div> <button onclick="removeSocial({INDEX})"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20"> <line x1="3" x2="17" y1="10" y2="10" stroke="rgb(220, 221, 222)" stroke-width="2" stroke-linecap="round"></line> </svg> </button> </li> */ function updatePreview() { user.profile.timezone = new Date().toTimeString().substring(0, 5) const elems = document.getElementsByClassName("preview") for(let i = 0; i < elems.length; i++) { let elem = elems[i] if(!elem) continue if(elem.getAttribute('preview-attr')) { let val = getDetail(elem.getAttribute("preview")) val = typeof val == "number" ? `#${val.toString(16)}` : val elem.style[elem.getAttribute('preview-attr')] = val }else{ if(elem.tagName.toLowerCase() === "img") { elem.src = getDetail(elem.getAttribute("preview")) continue } let prv = getDetail(elem.getAttribute("preview")) if(elem.getAttribute('preview-tmpl')) { prv = elem.getAttribute('preview-tmpl').replace('%v', prv) } if(elem.getAttribute('raw') === 'true') { elem.innerHTML = prv elem.value = prv continue } if(elem.tagName.toLocaleLowerCase() === "input") { elem.value = prv continue } elem.innerHTML = discordMarkdown.toHTML(prv) } } const elem = document.getElementById("preview-socials") const socPrev = document.getElementById("socials-preview") socPrev.innerHTML = '' let social = '' if(!user.profile.socials) return if(user.profile.socials.length == 0) { elem.innerHTML = 'no socials.' return } for(let i = 0; i < user.profile.socials.length; i++) { let s = user.profile.socials[i] social += `> __${s.name}:__ ${s.handle}\n` let li = document.createElement("li") let button = document.createElement("button") let div = document.createElement("div") div.innerHTML = discordMarkdown.toHTML(`__${s.name}:__ ${s.handle}`) button.innerHTML = `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20"><line x1="3" x2="17" y1="10" y2="10" stroke="rgb(220, 221, 222)" stroke-width="2" stroke-linecap="round"></line></svg>` button.setAttribute('onclick', `deleteSocial(${i})`) li.appendChild(div) li.appendChild(button) socPrev.appendChild(li) } elem.innerHTML = discordMarkdown.toHTML(social) } function getDetail(path) { let dir = path.split(".") let root = user for(let i = 0; i < dir.length; i++) { let v = root[dir[i]] if(v != undefined && v != null) { root = root[dir[i]] }else{ break } } if(path.endsWith("country")) { root += ` ${countries.find((e) => e.name === root).flag}` } return root } function reset() { graphql(`{identity(session: "${localStorage.discord_session}") { username discriminator picture profile{ about description favorite_color socials { name handle } timezone country gender pronouns sexuality } } }`).then(r => { user = r.data.identity authenticated() }) } function updateValue(el, path) { let up = {} up[path] = el.value ? el.value : '' user.profile = Object.assign(user.profile, up) updatePreview() } function save() { graphql(JSON.stringify({ query: `mutation($about: String! $description: String! $favorite_color: Int! $socials: [Social!]! $timezone: Int! $gender: String! $pronouns: String! $sexuality: String! $country: String!) { profile(session: "${localStorage.discord_session}" about: $about description: $description favorite_color: $favorite_color socials: $socials timezone: $timezone gender: $gender pronouns: $pronouns sexuality: $sexuality country: $country ) }`, variables: Object.assign(user.profile, { timezone: new Date().getTimezoneOffset() }) })).then(r => { if(r.data.profile) { notify("Saved profile!") }else{ notify("Failed to save profile! A warning has been sent to the developer about the issue!") } }) } let notif = null function notify(message) { document.getElementById("notification").innerHTML = message document.getElementById("notification").style.opacity = 1 if(notif) clearTimeout(notif) notif = setTimeout(() => { document.getElementById("notification").style.opacity = 0 }, 5000) } function addSocial() { let name = document.getElementById("preview-social-name") let handle = document.getElementById("preview-social-handle") if(!(name.value.length > 0 && handle.value.length > 0)) return user.profile.socials.push({ name: name.value.trim(), handle: handle.value.trim() }) name.value = "" handle.value = "" updatePreview() } function deleteSocial(index) { delete user.profile.socials[index] let n = [] for(let i = 0; i < user.profile.socials.length; i++) { if(user.profile.socials[i]) n.push(user.profile.socials[i]) } user.profile.socials = n updatePreview() }
var hooksObject = { onSubmit: function(insertDoc, updateDoc, currentDoc) { var that = this var shopper = { email: insertDoc.email, password: insertDoc.password, roles: [Mart.ROLES.GLOBAL.SHOPPER], profile: { firstName: insertDoc.firstName, lastName: insertDoc.lastName } } if($.find('#loginModal').length > 0) { $('#loginModal').on('hidden.bs.modal', function (e) { Mart.Accounts.createUser(shopper, function(error) { if(error) { Meteor.setTimeout(function () { $("#loginModal").modal('show') throwError(error.reason) }, 2 * 1000); } else { sAlert.success("Account created.") } that.done() }) }) $("#loginModal").modal('hide') } else { Mart.Accounts.createUser(shopper, function(error) { if(error) { that.done(error) } else { sAlert.success("Account created.") that.done() } }) } return false; }, onError: function(operation, error) { if(error && error.reason) { // a special Meteor.error sAlert.error(error.reason) } } }; AutoForm.addHooks(['shopper-sign-up-homepage'], hooksObject);
export default class CrossFire { constructor(container, config) { this.container = container || document.body; this.canvas = this.createCanvas('experiment'); this.active = false; this.ctx = this.canvas.getContext('2d'); this.cfg = this.setConfigSettings(config); this.gap = {}; this.objects = []; this.objSize = {}; this.mouse = {}; this.currentX = 0; this.currentY = 0; this.devicePixelRatio = window.devicePixelRatio; } setConfigSettings(config) { const cfg = {}; cfg.colors = {}; cfg.parent = config.parent || document.body; cfg.grid = config.grid || { rows: 8, columns: 8 }; cfg.size = config.size || { width: cfg.parent.offsetWidth * this.devicePixelRatio, height: cfg.parent.offsetHeight * this.devicePixelRatio } cfg.colors.primary = config.colors ? config.colors.primary || '#fff' : '#fff'; cfg.colors.secondary = config.colors ? config.colors.secondary || '#000' : '#000'; return cfg; } init() { this.onResize(); this.setupDom(); this.calcObjects(); this.onResize(); this._resetMousePos(); this.update(); this.addEventListeners(); } calcObjects() { this.objects = []; let width = this.gap.x / 2; let height = this.gap.y / 4; for (let i = this.cfg.grid.rows - 1; i > 0; i--) { for (let j = this.cfg.grid.columns - 1; j > 0; j--) { let obj = { x: Math.round((this.gap.x * i) - (width / 2)), y: Math.round((this.gap.y * j) - (height / 2)), w: width, //h: height, h: 1 * this.devicePixelRatio }; this.objects.push(obj); } } } createCanvas(classname) { let canvas = document.createElement('canvas'); canvas.className = classname; return canvas; } setupDom() { this.cfg.parent.appendChild(this.canvas); } addEventListeners() { this._onResize = this.onResize.bind(this); window.addEventListener('resize', this._onResize); this._onPointerMove = this.onPointerMove.bind(this); this.canvas.addEventListener('mousemove', this._onPointerMove); this.canvas.addEventListener('touchmove', this._onPointerMove, { passive: true }); this._onScroll = this.onScroll.bind(this); window.addEventListener('scroll', this._onScroll); } removeEventListeners() { window.removeEventListener('resize', this._onResize); this.canvas.removeEventListener('mousemove', this._onPointerMove); this.canvas.removeEventListener('touchmove', this._onPointerMove); } onResize() { this.canvas.width = this.cfg.parent.offsetWidth * this.devicePixelRatio; this.canvas.height = this.cfg.parent.offsetHeight * this.devicePixelRatio; this.canvas.style.width = `${this.cfg.parent.offsetWidth}px`; this.canvas.style.height = `${this.cfg.parent.offsetHeight}px`; this.gap.x = this.canvas.width / this.cfg.grid.rows; this.gap.y = this.canvas.height / this.cfg.grid.columns; this.onScroll(); this.calcObjects(); } onScroll() { // TODO: use IntersectionObserver to check if we need scrollEvents or not. let bcr = this.canvas.getBoundingClientRect(); this.elementTop = bcr.top; this.elementLeft = bcr.left; } onPointerMove(event) { event.preventDefault(); this.pointerActive = true; if (event.clientX || event.clientX === 0) { this.mouse.x = event.clientX * this.devicePixelRatio; this.mouse.y = event.clientY * this.devicePixelRatio; } else { this.mouse.x = event.touches[0].clientX * this.devicePixelRatio; this.mouse.y = event.touches[0].clientY * this.devicePixelRatio; } this.mouse.x -= Math.floor(this.elementLeft * this.devicePixelRatio); this.mouse.y -= Math.floor(this.elementTop * this.devicePixelRatio); if (!this.active) { this.active = true; this.update(); } requestAnimationFrame(() => { this.pointerActive = false; }); } _resetMousePos() { this.mouse = { x: this.canvas.width / 2, left: 0, y: this.canvas.height / 2, top: 0 }; } lerp(a, b, time) { return a + time * (b - a); } setToActive() { this.active = true; this.render(); } update() { requestAnimationFrame(this.update.bind(this)); this.render(); } render() { if (Math.round(this.currentX) === this.mouse.x && Math.floor(this.currentY) === Math.floor(this.mouse.y)) return; this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); let x; let y; if (this.pointerActive) { x = this.mouse.x; y = this.mouse.y; } else { x = this.lerp(this.mouse.x, this.currentX, 0.96); y = this.lerp(this.mouse.y, this.currentY, 0.96); } for (var i = 0; i < this.objects.length; i++) { let obj = this.objects[i]; let radians = Math.atan2(y - (obj.y + (obj.h / 2)), x - (obj.x + (obj.w / 2))); let translateX = obj.x + (obj.w / 2); let translateY = obj.y + (obj.h / 2); this.ctx.save(); this.ctx.translate(translateX, translateY); this.ctx.rotate(radians); this.ctx.fillStyle = this.cfg.colors.primary; if (this.mouse.x <= translateX + 50 && this.mouse.y >= translateY - 50 && this.mouse.x >= translateX - 50 && this.mouse.y <= translateY + 50) { this.ctx.fillStyle = 'rgba(255, 255, 255, 0.6)'; } this.ctx.fillRect(-obj.w / 2, -obj.h / 2, obj.w, obj.h); this.ctx.fillRect(-obj.h / 2, -obj.w / 2, obj.h, obj.w); this.ctx.restore(); } this.currentX = x; this.currentY = y; } }
import React, { useState, useContext } from "react"; import { Link } from "react-router-dom"; import empty from "../assets/empty.svg"; import all from "../assets/all.png"; import alldark from "../assets/alldark.png"; import exit from "../assets/exit.png"; import roles from "../assets/roles.png"; import branches from "../assets/branches.png"; import brancheswhite from "../assets/brancheswhite.png"; import roleswhite from "../assets/roleswhite.png"; import kadarko from "../assets/Kadarko.svg"; const CreatebranchScreen = () => { // const { state, signup, clearErrorMessage } = useContext(authContext); // const [email, setEmail] = useState(""); // const [password, setPassword] = useState(""); return ( <div class="container-fluid"> <div class="row"> <div class="col col-12 d-flex justify-content-between align-items-center" style={{ background: "#151423", width: "100vw", height: "9vh" }} > <p style={{ color: "white", fontSize: "1rem", marginTop: "1rem", marginLeft: "2rem", }} > <b>Overview</b> <sup>TM</sup> </p> <div class="input-group input-group-sm " style={{ width: "11rem", marginRight: "11rem", position: "relative", }} > <i class="fa fa-search" style={{ position: "absolute", zIndex: "1000", right: "6%", top: "20%", width: "1rem", color: "#C5D6EA", }} ></i> <input type="text" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" placeholder="Search Inventory" style={{ fontSize: "0.7rem", paddingTop: "0.6rem", paddingBottom: "0.6rem", backgroundColor: "#44434F", border: "none", }} ></input> </div> </div> </div> <div class="row"> <div class="col col-md-1 slider" style={{ height: "80vh", marginTop: "40px", borderTopRightRadius: "20px", borderBottomRightRadius: "20px", position: "fixed", }} > {/* inside box */} <div class="row" style={{ height: "100%", width: "100%", }} > <div class="col col-md-10 text-center" style={{ background: "#151423", height: "100%", borderTopRightRadius: "20px", borderBottomRightRadius: "20px", fontSize: "0.6rem", color: "white", // border: "1px solid blue", paddingRight: "15px", }} > {/* first icons */} <div class="text-center d-flex align-content-between flex-column" style={{ // border: "1px solid red", height: "15rem", marginTop: "1rem", }} > <Link to="overview" className="linkTag"> <div className="mt-2 text-center"> <img src={all} alt="all" class="image" style={{ width: "1.5rem" }} /> <p class="">All Inventory</p> </div> </Link> <Link to="assignroles" className="linkTag"> <div className="mt-4"> <img src={roleswhite} alt="roleswhite" class="image" style={{ width: "1.5rem" }} /> <p>Assign Roles</p> </div> </Link> <Link to="createbranch" className="linkTag"> <div className="mt-4" style={{ borderLeft: "2px solid #006CF1", marginLeft: "-0.9rem", paddingLeft: "0.6rem", }} > <img src={brancheswhite} alt="branches" class="image" style={{ width: "1.5rem" }} /> <p style={{ textAlign: "center" }}>Create Branches</p> </div> </Link> </div> {/* second set */} <div style={{ marginTop: "8rem" }}> <Link to="/Signin" className="linkTag"> {" "} <div> <img src={exit} alt="exit" class="image" style={{ width: "1.5rem" }} /> <p>Log Out</p> </div> </Link> </div> </div> </div> </div> <div class="col col-md-11" style={{ marginLeft: "5rem" }}> <div className="row"> <div className="col col-9 mr-auto ml-auto" style={{ marginTop: "2%", textAlign: "center", color: "#707070" }} > <p> <b>Create a new Branch</b> </p> </div> <div className="col col-6 mr-auto ml-auto d-flex justify-content-between" style={{ marginTop: "2%", textAlign: "center" }} > <input type="text" placeholder="Company Name" style={{ border: "1px solid #E0E0E0", fontSize: "0.7rem", width: "13rem", paddingLeft: "0.5rem", }} ></input> <input type="text" placeholder="Address" style={{ border: "1px solid #E0E0E0", fontSize: "0.7rem", width: "13rem", paddingLeft: "0.5rem", }} ></input> <button className="btn btn-sm" style={{ backgroundColor: "#D94F00", color: "white", fontSize: "0.7rem", borderRadius: "3px", }} > Create Branch </button> </div> <div className="col col-9 mr-auto ml-auto" style={{ marginTop: "4%", // border: "1px solid red", }} > <div className="col col-12 table-responsive" style={{ height: "60vh", overflow: "scroll" }} > <table class="table table-hover table-striped table-bordered text-center" style={{ fontSize: "0.8rem" }} > <thead> <tr> <th scope="col">S/N</th> <th scope="col">Name</th> <th scope="col">Address</th> <th scope="col">Add</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Hubmart</td> <td>Lekki</td> <td> {" "} <button className="btn btn-sm" style={{ backgroundColor: "#D94F00", color: "white", fontSize: "0.7rem", borderRadius: "3px", }} > Add Inventory </button> </td> </tr> <tr> <td>2</td> <td>Hubmart</td> <td>Mary Land</td> <td> {" "} <button className="btn btn-sm" style={{ backgroundColor: "#D94F00", color: "white", fontSize: "0.7rem", borderRadius: "3px", }} > Add Inventory </button> </td> </tr> <tr> <td>3</td> <td>Hubmart</td> <td>Yaba</td> <td> {" "} <button className="btn btn-sm" style={{ backgroundColor: "#D94F00", color: "white", fontSize: "0.7rem", borderRadius: "3px", }} > Add Inventory </button> </td> </tr> <tr> <td>4</td> <td>Hubmart</td> <td>Adeola Odeku</td> <td> {" "} <button className="btn btn-sm" style={{ backgroundColor: "#D94F00", color: "white", fontSize: "0.7rem", borderRadius: "3px", }} > Add Inventory </button> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> ); }; export default CreatebranchScreen;
import React, {Component} from 'react'; import {Redirect} from 'react-router-dom'; import Form from 'react-bootstrap/Form'; import Button from 'react-bootstrap/Button'; import {UserConsumer} from '../components/context/user'; import CategoriesService from '../services/categories-service'; import toastr from 'toastr'; class CreateCategory extends Component { constructor(props){ super(props); this.state = { name:'', imageUrl:'' } } static service = new CategoriesService(); handleChange = ({target}) => { this.setState({ [target.id] : target.value }) } handleSubmit = async (event) => { const {name, imageUrl} = this.state; event.preventDefault(); const data = { name, imageUrl } const result = await CreateCategory.service.createCategory(data); if(!result.success) { toastr.error(Object.values(result.errors).join("\r\n"),'Problems with creating category') return } toastr.success(`Successfully created category ${name}`); this.props.history.push('/'); } render() { const {isLoggedIn, isAdmin} = this.props; const {name, imageUrl} = this.state; if(!isLoggedIn || !isAdmin) { toastr.error('You cannot access this page'); return <Redirect to="/"/> } return ( <Form className="col-md-6 centered" onSubmit={this.handleSubmit}> <Form.Group controlId="name"> <Form.Label>Name</Form.Label> <Form.Control type="text" onChange={this.handleChange} value={name} placeholder="Enter name of category" /> </Form.Group> <Form.Group controlId="imageUrl"> <Form.Label>Category Image</Form.Label> <Form.Control type="text" onChange={this.handleChange} value={imageUrl} placeholder="Enter an image url that will appear on all posts with the given category" /> </Form.Group> <Button variant="primary" type="submit"> Submit </Button> </Form> ); } } const CreateCategoryWithContext = (props) => { return ( <UserConsumer> { ({isLoggedIn, isAdmin})=>( <CreateCategory {...props} isLoggedIn={isLoggedIn} isAdmin = {isAdmin} /> ) } </UserConsumer> ); } export default CreateCategoryWithContext
class Sun { constructor() { const geom = new THREE.SphereGeometry(50, 40, 40); const mat = new THREE.MeshPhongMaterial({ map: new THREE.TextureLoader().load("./assets/img/sun.jpg") }); this.mesh = new THREE.Mesh(geom, mat); this.mesh.castShadows = false; this.mesh.receiveShadows = false; } animate() { this.mesh.rotation.y += 0.004; } } export default Sun;
function DlgSelectDataset(mapContainer,obj,options) { options=options||{}; options.rtl=(app.layout=='rtl'); options.showOKButton=false; options.cancelButtonTitle='Close'; DlgTaskBase.call(this, 'DlgSelectDataset' ,(options.title || 'Select Document') , mapContainer,obj,options); var settings= this.obj ||{}; this.url= settings.url || "/datasets?format=json"; this.onAdd= settings.onAdd || function(){}; } DlgSelectDataset.prototype = Object.create(DlgTaskBase.prototype); DlgSelectDataset.prototype.createUI=function(){ var self=this; if(self.activeTemplate){ thumbnail=self.activeTemplate.thumbnail; thumbnail_alt=self.activeTemplate.name; resolution= self.activeTemplate.resolution; } var htm='<div class="scrollable-content" ><form id="'+self.id+'_form" class="modal-body form-horizontal">'; htm+=' <div class="form-group">'; htm+=' <label><p style="padding-left:1em;">Find layer</p></label>'; htm+=' </div>'; htm+=' <div class="form-group">'; htm+=' <div class="input-group">'; htm+=' <input id="autoSearchDatasets" class="mySearch-searchinput form-control background-position-right" placeholder="Search..." type="search" />'; htm+=' <span class="input-group-addon"><i id="autoSearchItems_clear" title="Clear" style=" cursor: pointer;" class="glyphicon glyphicon-remove"></i></span>'; htm+=' </div>'; htm+=' </div>'; htm+=' <div class="form-group">'; htm+=' <div id="autoSearchDatasets_results" class="autocomplete-custom-results"></div>'; htm+=' </div>'; if(app.identity.isAdministrator || app.identity.isPowerUser || app.identity.isDataManager || app.identity.isDataAnalyst){ htm+=' <button id="cmdAddGeoJSON" title="Add GeoJSON layer" class="btn-primary form-control ">Add GeoJSON </button>'; } htm+=' <button id="cmdAddNewWMS" title="Add new WMS layer" class="btn-primary form-control ">Add WMS layer</button>'; htm+=' <button id="cmdAddNewWFS" title="Add new WFS layer" class="btn-primary form-control ">Add WFS layer</button>'; htm+=' <button id="cmdAddNewGroupLayer" title="Add new group layer" class="btn-primary form-control "><span class="glyphicon glyphicon-folder-open"></span> Add new group layer</button>'; //htm+=' <button id="cmdAddNewOSMXML" title="Add new OSM Vector layer" class="btn-primary form-control ">افزودن لایه برداری OSM</button>'; htm += '</form>'; htm+=' </div>'; var content=$(htm).appendTo( this.mainPanel); content.find('#file').change(function(){ }); content.find('#autoSearchItems_clear').click(function(){ var autoSearchEl=content.find('#autoSearchDatasets') ; var autoSearchResultsEl=content.find('#autoSearchDatasets_results') ; $(autoSearchResultsEl).html(''); $(autoSearchResultsEl).val(''); $(autoSearchEl).val(''); }); content.find('#cmdAddNewGroupLayer').click(function(){ app.mapContainer.addNewGroupLayer(); }); content.find('#cmdAddNewWMS').click(function(){ app.mapContainer.addNewWMS(); }); content.find('#cmdAddNewWFS').click(function(){ app.mapContainer.addNewWFS(); }); content.find('#cmdAddNewOSMXML').click(function(){ app.mapContainer.addNewOSMXML(); }); content.find('#cmdAddGeoJSON').click(function(){ app.mapContainer.addGeoJSON(); }); content.find('#cmdWCS').click(function(){ app.mapContainer.downloadDataFromWCS(); }); var autoSearchEl=content.find('#autoSearchDatasets') ; var autoSearchResultsEl=content.find('#autoSearchDatasets_results') ; var $form = $(content.find('#'+self.id +'_form')); $form.on('submit', function(event){ // prevents refreshing page while pressing enter key in input box event.preventDefault(); }); this.beforeApplyHandlers.push(function(evt){ var origIgone= $.validator.defaults.ignore; $.validator.setDefaults({ ignore:'' }); $.validator.unobtrusive.parse($form); $.validator.setDefaults({ ignore:origIgone }); $form.validate(); if(! $form.valid()){ evt.cancel= true; var errElm=$form.find('.input-validation-error').first(); if(errElm){ var offset=errElm.offset().top; //var tabOffset= tabHeader.offset().top; var tabOffset=0; //tabOffset=self.mainPanel.offset().top; tabOffset=$form.offset().top; self.mainPanel.find('.scrollable-content').animate({ scrollTop: offset - tabOffset //-60//-160 }, 1000); } } }); this.applyHandlers.push(function(evt){ }); this.changesApplied=false; var _autoSearchUrl = this.url; var _lastSelectedItem; var cache =undefined;// {}; $(autoSearchEl).autocomplete({ appendTo:content, minLength: 0, source: function (request, response) { var term = request.term; var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" ); var text = $( this ).text(); //if (term in cache) { if (cache && self.downloding) { //var data = cache[term]; var data = cache; var mappedData=$.map(data, function (item) { var description=''; if(item.description){ description= item.description; } if ( item.name && ( !request.term || matcher.test(item.name) || matcher.test(item.id+'') || (description && matcher.test(description)) || (item.keywords && matcher.test(item.keywords)) || (item.author && matcher.test(item.author)) ) ){ return { label: item.name, value: item.name, data:item }; } }) response(mappedData); return; } if(!self.downloding){ self.downloding=true; $.getJSON(_autoSearchUrl, request, function (dataObj, status, xhr) { // cache[term] = data; var data=[]; if(dataObj && dataObj.items){ data= dataObj.items; } cache = data.sort(function(a,b){ if(a.OwnerUser.userName==b.OwnerUser.userName){ return a.updatedAt > b.updatedAt; }else if(a.OwnerUser.userName==app.identity.name){ return -1; }else if(b.OwnerUser.userName==app.identity.name){ return 1; }else { return (a.updatedAt + '-'+a.OwnerUser.userName) > (b.updatedAt + '-'+b.OwnerUser.userName); } }); // var mappedData=$.map(data, function (item) { // return { // label: item.name, // value: item.name, // data:item // }; // }) var mappedData=$.map(data, function (item) { var description=''; if(item.description){ description= item.description; } var projMatch=true; if( self.mapContainer.mapSettings && self.mapContainer.mapSettings.projectId ){ if(item.projectId){ if((item.projectId+'')==(self.mapContainer.mapSettings.projectId+'')){ projMatch=true }else{ projMatch=false; } } } if (projMatch && item.name && ( !request.term || matcher.test(item.name) || matcher.test(item.id+'') || matcher.test(description) || (item.keywords && matcher.test(item.keywords)) || (item.author && matcher.test(item.author)) ) ){ return { label: item.name, value: item.name, data:item }; } }); response(mappedData); self.downloding=false; $(autoSearchEl).removeClass('ui-autocomplete-loading'); }). fail(function( jqXHR, textStatus, errorThrown) { console.log( "error" ); $.notify({ message: "Failed to retrieve item list" },{ type:'danger', delay:2000, animate: { enter: 'animated fadeInDown', exit: 'animated fadeOutUp' } }); self.downloding=false; $(autoSearchEl).removeClass('ui-autocomplete-loading'); }); } }, select: function (event, ui) { _lastSelectedItem = ui.item; $(this).val(ui.item.label); showResults(ui.item); return false; }, focus: function (event, ui) { // $(this).val(ui.item.label); return false; }, open: function() { $("ul.ui-menu").width($(this).innerWidth()); } }) .focus(function (event, ui) { //$(this).trigger('keydown.autocomplete'); $(this).autocomplete("search"); // showResults(ui.item); }) .data("ui-autocomplete")._renderItem = function (ul, item) { if (item.data &&item.data.updatedAt && !item.data.updatedAt_obj) { try { item.data.updatedAt_obj = new Date(item.data.updatedAt); } catch (ex) { } } var label = item.label; var description = item.data.description || ''; description = description.replace(/(?:\r\n|\r|\n)/g, '<br />'); var keywords = item.data.keywords || ''; var term = this.term; if (term) { label = String(label).replace( new RegExp(term, "gi"), "<strong class='ui-state-highlight'>$&</strong>"); description = String(description).replace( new RegExp(term, "gi"), "<strong class='ui-state-highlight'>$&</strong>"); keywords = String(keywords).replace( new RegExp(term, "gi"), "<strong class='ui-state-highlight'>$&</strong>"); } var class_ ='autocomplete-custom-item'+ (item.data.dataType ? ' icon-' + item.data.dataType : ''); var htm = ''; htm += '<div class="' + class_ + '" >'; if (item.data.thumbnail) { htm += '<img class="avatar48" src="/dataset/' + item.data.id + '/thumbnail" />'; } else if (item.data.icon) { // htm += '<i class="avatar48 fa fa-map"> </i>'; // htm+=' <i style="float:left; font-size: 3em;" class=" fa fa-file-o fa-file-'+item.data.icon+'-o" > </i>' } if(item.data.subType=='MultiPolygon'){ htm+=' <span class="layerSubtype">▭ </span>'; } if(item.data.subType=='MultiLineString'){ htm+=' <span class="layerSubtype">▬ </span>'; } if(item.data.subType=='Point'){ htm+=' <span class="layerSubtype">◈ </span>'; } if(item.data.dataType=='raster'){ htm+=' <span class="layerSubtype">▦ </span>'; } if(item.data.dataType=='table'){ htm+=' <span class="layerSubtype">▥ </span>'; } htm += '<strong>'+label+'</strong>' ; //htm += (item.data.description ? '<pre class="nostyle" style="display:inline;"><br/><small style="white-space: pre;">' + description + '</small></pre>' : ''); htm +='<pre class="nostyle" style="display:inline;"><br/><small style="white-space: pre;">' + description + '</small></pre>'; if(keywords){ htm +='<pre class="nostyle" style="display:inline;"><br/><small style="white-space:">' + keywords + '</small></pre>'; } return $("<li></li>").append(htm).appendTo(ul); }; function showResults(item){ if(!item){ $(autoSearchResultsEl).html(''); return; } var label = item.label; var description = item.data.description || ''; description = description.replace(/(?:\r\n|\r|\n)/g, '<br />'); var keywords = item.data.keywords || ''; var class_ ='autocomplete-custom-item '+ (item.data.dataType ? 'icon-' + item.data.dataType : ''); var htm = ''; htm += '<div class="' + class_ + '" >'; if (item.data.thumbnail) { htm += '<img class="avatar48" src="/dataset/' + item.data.id + '/thumbnail" />'; } else { // htm += '<i class="avatar48 fa fa-map"> </i>'; } if(item.data.subType=='MultiPolygon'){ htm+=' <span class="layerSubtype">▭ </span>'; } if(item.data.subType=='MultiLineString'){ htm+=' <span class="layerSubtype">▬ </span>'; } if(item.data.subType=='Point'){ htm+=' <span class="layerSubtype">◈ </span>'; } if(item.data.dataType=='raster'){ htm+=' <span class="layerSubtype">▦ </span>'; } if(item.data.dataType=='table'){ htm+=' <span class="layerSubtype">▥ </span>'; } htm += '<a target="_blank" href="/dataset/' + item.data.id +'">'+ label +'</a>'+ (item.data.description ? '<br/><small style="white-space: pre;">' + description + '</small>' : ''); htm+= (item.data.keywords ? '<br/><small style="white-space: pre;">' + keywords + '</small>' : ''); htm += '<div class="list-inline">'; if (item.data.OwnerUser.userName !== app.identity.name) { htm += ' <li><i class="fa fa-user"></i> <span>' + item.data.OwnerUser.userName + '</span></li>'; } //htm += '<li><i class="fa fa-calendar"></i><span>' + item.data.updatedAt.toUTCString() + '</span></li>'; // htm += '<li><i class="fa fa-calendar"></i><span title="Last modified at">' + item.data.updatedAt.toString() + '</span></li>'; htm +=' <li style="float: right;"><button id="cmdAddDataset" title="Add this layer to map" class="btn-primary "><span class="glyphicon glyphicon-plus"></span>Add</button></lin>'; htm += ' </div>'; htm += '</div>'; $(autoSearchResultsEl).html(htm); $(autoSearchResultsEl).find("#cmdAddDataset").click(function(){ self.onAdd(self,item.data); $(autoSearchResultsEl).html(''); $(autoSearchResultsEl).val(''); }); } }
import React from 'react'; import {ViewTodo} from './viewTodo'; import {EditTodo} from './editTodo'; export class ToDo extends React.Component { constructor(props){ super(props); const todo = this.props.todo; this.state = { id : todo.id, title : todo.title, edit: todo.edit, newTitle : todo.title, isDone : todo.isDone } this.changeMode = this.changeMode.bind(this); this.changeValue = this.changeValue.bind(this); this.saveTodo = this.saveTodo.bind(this); this.cancelEdit = this.cancelEdit.bind(this); this.changeStatus = this.changeStatus.bind(this); } changeMode() { this.setState({ edit: !this.state.edit }); } cancelEdit(){ this.setState({ edit: false, newTitle: this.state.title }); } changeValue(event){ this.setState({newTitle : event.target.value}) } saveTodo(){ this.props.saveTodo(this.state.id,this.state.newTitle); } changeStatus(event){ const checked = event.target.checked; this.props.changeStatus(this.state.id,checked); this.setState({ isDone : checked }) } render() { const todo = this.props.todo; const removeTodo = () => { this.props.removeTodo(todo.id); } const renderTodo = () => { if(this.state.edit){ return ( <EditTodo todo={this.state} changeValue={this.changeValue} changeMode={this.changeMode} saveTodo={this.saveTodo} cancelEdit={this.cancelEdit} /> ) }else{ return ( <ViewTodo changeStatus={this.changeStatus} todo={this.state} removeTodo={removeTodo} onCheck={this.onCheck} changeMode={this.changeMode} /> ) } } return ( <div className="input-group mb-3"> {renderTodo()} </div> ) } }
(function(){ //老的写法,用加号连接,换行是不允许的 /*var roadPoem = 'Then took the other, as just as fair,nt' + 'And having perhaps the better claimnt' + 'Because it was grassy and wanted wear,nt' + 'Though as for that the passing therent' + 'Had worn them really about the same,nt' var fourAgreements = 'You have the right to be you.n You can only be you when you do your best.' */ var roadPoem = `Then took the other, as just as fair, And having perhaps the better claim Because it was grassy and wanted wear, Though as for that the passing there Had worn them really about the same,` var fourAgreements = `You have the right to be you. You can only be you when you do your best.` console.log(roadPoem); console.log(fourAgreements); }())