text
stringlengths
7
3.69M
import { get, post, post_array } from '@/http/axios' export default { namespaced: true, state: { address: [], // 存放所有的地址信息 }, mutations: { // 突变函数,唯一修改state的方法 // 所有突变函数接收的第一个参数都是state // 刷新地址信息 refreshAddress(state, address) { // 需要接收一个参数address,state是系统给的 state.address = address } }, actions: { // 做异步交互 // 根据顾客id查询地址信息 async findCustomerAddressById({commit},id) { // context是系统分发给actions的对象,里面包含的commit可以让action去触发突变,让突变去修改state const response = await get('/address/findByCustomerId',{ id }); // 2.将地址信息设置到state.address中 // 使用commit去触发突变,先指定突变名称,再传递一个参数 commit('refreshAddress', response.data) } } }
// * Global import Vue from "vue"; import Toasted from "vue-toasted"; import vClickOutside from "v-click-outside"; import App from "@project_src/App.vue"; // * Modules import store from "@project_src/store"; // * Assets import "@project_src/assets/styles/theme.scss"; Vue.use(Toasted); Vue.use(vClickOutside); new Vue({ store, render: (h) => h(App), }).$mount("#app");
/** * Copyright 2017 PeopleWare n.v. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Quick hack to test conditions. */ module.exports = { validateConditions: function (conditions, args) { conditions.forEach(condition => { let conditionResult try { conditionResult = condition.apply(undefined, args) } catch (err) { throw new Error('condition ' + condition + ' has an error: ' + err) } if (!conditionResult) { throw new Error('condition violation for: ' + condition + ' (' + JSON.stringify(args) + ')') } }) }, validateInvariants: function (subject) { if (!subject.invariants) { throw new Error('invariants do not hold') } } }
import React from 'react'; import { Link } from 'react-router-dom'; const Nav = () => { return ( <div className="nav"> <div className="nav-left"> <span className="nav-logo"><Link to="/">Lattice Movie Finder</Link></span> <span className="nav-link"><Link to="/">homepage</Link></span> <span className="nav-link"><Link to="/about">about</Link></span> </div> <div className="nav-right"> <span className="nav-item"></span> </div> </div> ) } export default Nav;
// LauncherOSX // // Created by Boris Schneiderman. // Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. define(["../globals", "jquery", "underscore", "eventEmitter", "../models/bookmark_data", "./cfi_navigation_logic", "../models/current_pages_info", "../helpers", "../models/page_open_request", "../models/viewer_settings", "ResizeSensor"], function(Globals, $, _, EventEmitter, BookmarkData, CfiNavigationLogic, CurrentPagesInfo, Helpers, PageOpenRequest, ViewerSettings, ResizeSensor) { /** * Renders reflowable content using CSS columns * @param options * @constructor */ var ReflowableView = function(options, reader){ $.extend(this, new EventEmitter()); var self = this; var _$viewport = $(options.$viewport); var _spine = options.spine; var _userStyles = options.userStyles; var _bookStyles = options.bookStyles; var _iframeLoader = options.iframeLoader; var _currentSpineItem; var _isWaitingFrameRender = false; var _deferredPageRequest; var _fontSize = 100; var _fontSelection = 0; var _$contentFrame; var _navigationLogic; var _$el; var _$iframe; var _$epubHtml; var _lastPageRequest = undefined; var _cfiClassBlacklist = ["cfi-marker", "mo-cfi-highlight", "resize-sensor", "resize-sensor-expand", "resize-sensor-shrink", "resize-sensor-inner", "js-hypothesis-config", "js-hypothesis-embed"]; var _cfiElementBlacklist = ["hypothesis-adder"]; var _cfiIdBlacklist = ["MathJax_Message", "MathJax_SVG_Hidden"]; var _$htmlBody; var _htmlBodyIsVerticalWritingMode; var _htmlBodyIsLTRDirection; var _htmlBodyIsLTRWritingMode; var _currentOpacity = -1; var _lastViewPortSize = { width: undefined, height: undefined }; var _lastBodySize = { width: undefined, height: undefined }; var _paginationInfo = { visibleColumnCount : 2, columnGap : 20, columnMaxWidth: 550, columnMinWidth: 400, spreadCount : 0, currentSpreadIndex : 0, currentPageIndex: 0, columnWidth : undefined, pageOffset : 0, columnCount: 0 }; this.render = function(){ var template = Helpers.loadTemplate("reflowable_book_frame", {}); _$el = $(template); _$viewport.append(_$el); var settings = reader.viewerSettings(); if (!settings || typeof settings.enableGPUHardwareAccelerationCSS3D === "undefined") { //defaults settings = new ViewerSettings({}); } if (settings.enableGPUHardwareAccelerationCSS3D) { // This fixes rendering issues with WebView (native apps), which clips content embedded in iframes unless GPU hardware acceleration is enabled for CSS rendering. _$el.css("transform", "translateZ(0)"); } // See ReaderView.handleViewportResize // var lazyResize = _.debounce(self.onViewportResize, 100); // $(window).on("resize.ReadiumSDK.reflowableView", _.bind(lazyResize, self)); renderIframe(); return self; }; function setFrameSizesToRectangle(rectangle) { _$contentFrame.css("left", rectangle.left + "px"); _$contentFrame.css("top", rectangle.top + "px"); _$contentFrame.css("right", rectangle.right + "px"); _$contentFrame.css("bottom", rectangle.bottom + "px"); } this.remove = function() { //$(window).off("resize.ReadiumSDK.reflowableView"); _$el.remove(); }; this.isReflowable = function() { return true; }; this.onViewportResize = function() { if(updateViewportSize()) { updatePagination(); } }; var _viewSettings = undefined; this.setViewSettings = function(settings, docWillChange) { _viewSettings = settings; _paginationInfo.columnGap = settings.columnGap; _paginationInfo.columnMaxWidth = settings.columnMaxWidth; _paginationInfo.columnMinWidth = settings.columnMinWidth; _fontSize = settings.fontSize; _fontSelection = settings.fontSelection; updateViewportSize(); if (!docWillChange) { updateColumnGap(); updateHtmlFontInfo(); } }; function getFrameDimensions() { return { width: _$iframe[0].clientWidth, height: _$iframe[0].clientHeight }; } function getPageOffset() { if (_paginationInfo.rightToLeft && !_paginationInfo.isVerticalWritingMode) { return -_paginationInfo.pageOffset; } return _paginationInfo.pageOffset; } function getPaginationOffsets() { var offset = getPageOffset(); if (_paginationInfo.isVerticalWritingMode) { return { top: offset, left: 0 }; } return { top: 0, left: offset }; } function renderIframe() { if (_$contentFrame) { //destroy old contentFrame _$contentFrame.remove(); } var template = Helpers.loadTemplate("reflowable_book_page_frame", {}); var $bookFrame = $(template); $bookFrame = _$el.append($bookFrame); _$contentFrame = $("#reflowable-content-frame", $bookFrame); _$iframe = $("#epubContentIframe", $bookFrame); _$iframe.css("left", ""); _$iframe.css("right", ""); _$iframe.css("position", "relative"); //_$iframe.css(_spine.isLeftToRight() ? "left" : "right", "0px"); _$iframe.css("overflow", "hidden"); _navigationLogic = new CfiNavigationLogic({ $iframe: _$iframe, frameDimensionsGetter: getFrameDimensions, paginationInfo: _paginationInfo, paginationOffsetsGetter: getPaginationOffsets, classBlacklist: _cfiClassBlacklist, elementBlacklist: _cfiElementBlacklist, idBlacklist: _cfiIdBlacklist }); } function loadSpineItem(spineItem) { if(_currentSpineItem != spineItem) { //create & append iframe to container frame renderIframe(); if (_currentSpineItem) { Globals.logEvent("CONTENT_DOCUMENT_UNLOADED", "EMIT", "reflowable_view.js [ " + _currentSpineItem.href + " ]"); self.emit(Globals.Events.CONTENT_DOCUMENT_UNLOADED, _$iframe, _currentSpineItem); } self.resetCurrentPosition(); _paginationInfo.pageOffset = 0; _paginationInfo.currentSpreadIndex = 0; _paginationInfo.currentPageIndex = 0; _currentSpineItem = spineItem; // TODO: this is a dirty hack!! _currentSpineItem.paginationInfo = _paginationInfo; _isWaitingFrameRender = true; var src = _spine.package.resolveRelativeUrl(spineItem.href); Globals.logEvent("CONTENT_DOCUMENT_LOAD_START", "EMIT", "reflowable_view.js [ " + spineItem.href + " -- " + src + " ]"); self.emit(Globals.Events.CONTENT_DOCUMENT_LOAD_START, _$iframe, spineItem); _$iframe.css("opacity", "0.01"); _iframeLoader.loadIframe(_$iframe[0], src, onIFrameLoad, self, {spineItem : spineItem}); } } function updateHtmlFontInfo() { if(_$epubHtml) { var i = _fontSelection; var useDefault = !reader.fonts || !reader.fonts.length || i <= 0 || (i-1) >= reader.fonts.length; var font = (useDefault ? {} : reader.fonts[i - 1]); Helpers.UpdateHtmlFontAttributes(_$epubHtml, _fontSize, font, function() {self.applyStyles();}); } } function updateColumnGap() { if(_$epubHtml) { _$epubHtml.css("column-gap", _paginationInfo.columnGap + "px"); } } function onIFrameLoad(success) { _isWaitingFrameRender = false; //while we where loading frame new request came if(_deferredPageRequest && _deferredPageRequest.spineItem != _currentSpineItem) { loadSpineItem(_deferredPageRequest.spineItem); return; } if(!success) { _$iframe.css("opacity", "1"); _deferredPageRequest = undefined; return; } Globals.logEvent("CONTENT_DOCUMENT_LOADED", "EMIT", "reflowable_view.js [ " + _currentSpineItem.href + " ]"); self.emit(Globals.Events.CONTENT_DOCUMENT_LOADED, _$iframe, _currentSpineItem); var epubContentDocument = _$iframe[0].contentDocument; _$epubHtml = $("html", epubContentDocument); _$htmlBody = $("body", _$epubHtml); // TODO: how to address this correctly across all the affected platforms?! // Video surface sometimes (depends on the video codec) disappears from CSS column (i.e. reflow page) during playback // (audio continues to play normally, but video canvas is invisible). // https://github.com/readium/readium-js-viewer/issues/265#issuecomment-73018762 // ...Meanwhile, reverting https://github.com/readium/readium-js-viewer/issues/239 // by commenting the code below (which unfortunately only works with some GPU / codec configurations, // but actually fails on several other machines!!) /* if(window.chrome && window.navigator.vendor === "Google Inc.") // TODO: Opera (WebKit) sometimes suffers from this rendering bug too (depends on the video codec), but unfortunately GPU-accelerated rendering makes the video controls unresponsive!! { $("video", _$htmlBody).css("transform", "translateZ(0)"); } */ _htmlBodyIsVerticalWritingMode = false; _htmlBodyIsLTRDirection = true; _htmlBodyIsLTRWritingMode = undefined; var win = _$iframe[0].contentDocument.defaultView || _$iframe[0].contentWindow; //Helpers.isIframeAlive var htmlBodyComputedStyle = win.getComputedStyle(_$htmlBody[0], null); if (htmlBodyComputedStyle) { _htmlBodyIsLTRDirection = htmlBodyComputedStyle.direction === "ltr"; var writingMode = undefined; if (htmlBodyComputedStyle.getPropertyValue) { writingMode = htmlBodyComputedStyle.getPropertyValue("-webkit-writing-mode") || htmlBodyComputedStyle.getPropertyValue("-moz-writing-mode") || htmlBodyComputedStyle.getPropertyValue("-ms-writing-mode") || htmlBodyComputedStyle.getPropertyValue("-o-writing-mode") || htmlBodyComputedStyle.getPropertyValue("-epub-writing-mode") || htmlBodyComputedStyle.getPropertyValue("writing-mode"); } else { writingMode = htmlBodyComputedStyle.webkitWritingMode || htmlBodyComputedStyle.mozWritingMode || htmlBodyComputedStyle.msWritingMode || htmlBodyComputedStyle.oWritingMode || htmlBodyComputedStyle.epubWritingMode || htmlBodyComputedStyle.writingMode; } if (writingMode) { _htmlBodyIsLTRWritingMode = writingMode.indexOf("-lr") >= 0; // || writingMode.indexOf("horizontal-") >= 0; we need explicit! if (writingMode.indexOf("vertical") >= 0 || writingMode.indexOf("tb-") >= 0 || writingMode.indexOf("bt-") >= 0) { _htmlBodyIsVerticalWritingMode = true; } } } if (_htmlBodyIsLTRDirection) { if (_$htmlBody[0].getAttribute("dir") === "rtl" || _$epubHtml[0].getAttribute("dir") === "rtl") { _htmlBodyIsLTRDirection = false; } } // Some EPUBs may not have explicit RTL content direction (via CSS "direction" property or @dir attribute) despite having a RTL page progression direction. Readium consequently tweaks the HTML in order to restore the correct block flow in the browser renderer, resulting in the appropriate CSS columnisation (which is used to emulate pagination). if (!_spine.isLeftToRight() && _htmlBodyIsLTRDirection && !_htmlBodyIsVerticalWritingMode) { _$htmlBody[0].setAttribute("dir", "rtl"); _htmlBodyIsLTRDirection = false; _htmlBodyIsLTRWritingMode = false; } _paginationInfo.isVerticalWritingMode = _htmlBodyIsVerticalWritingMode; hideBook(); _$iframe.css("opacity", "1"); updateViewportSize(); _$epubHtml.css("height", _lastViewPortSize.height + "px"); _$epubHtml.css("position", "relative"); _$epubHtml.css("margin", "0"); _$epubHtml.css("padding", "0"); _$epubHtml.css("column-axis", (_htmlBodyIsVerticalWritingMode ? "vertical" : "horizontal")); // // ///////// // //Columns Debugging // // _$epubHtml.css("column-rule-color", "red"); // _$epubHtml.css("column-rule-style", "dashed"); // _$epubHtml.css("column-rule-width", "1px"); // _$epubHtml.css("background-color", '#b0c4de'); // // //// self.applyBookStyles(); resizeImages(); updateColumnGap(); updateHtmlFontInfo(); } this.applyStyles = function() { Helpers.setStyles(_userStyles.getStyles(), _$el.parent()); //because left, top, bottom, right setting ignores padding of parent container //we have to take it to account manually var elementMargins = Helpers.Margins.fromElement(_$el); setFrameSizesToRectangle(elementMargins.padding); updateViewportSize(); updatePagination(); }; this.applyBookStyles = function() { if(_$epubHtml) { // implies _$iframe Helpers.setStyles(_bookStyles.getStyles(), _$iframe[0].contentDocument); //_$epubHtml } }; function openDeferredElement() { if(!_deferredPageRequest) { return; } var deferredData = _deferredPageRequest; _deferredPageRequest = undefined; self.openPage(deferredData); } function _openPageInternal(pageRequest) { if(_isWaitingFrameRender) { _deferredPageRequest = pageRequest; return false; } // if no spine item specified we are talking about current spine item if(pageRequest.spineItem && pageRequest.spineItem != _currentSpineItem) { _deferredPageRequest = pageRequest; loadSpineItem(pageRequest.spineItem); return true; } var pageIndex = undefined; if(pageRequest.spineItemPageIndex !== undefined) { pageIndex = pageRequest.spineItemPageIndex; } else if(pageRequest.elementId) { pageIndex = _paginationInfo.currentPageIndex + _navigationLogic.getPageIndexDeltaForElementId(pageRequest.elementId); } else if(pageRequest.firstVisibleCfi && pageRequest.lastVisibleCfi) { var firstPageIndex; var lastPageIndex; try { firstPageIndex = _navigationLogic.getPageIndexDeltaForCfi(pageRequest.firstVisibleCfi, _cfiClassBlacklist, _cfiElementBlacklist, _cfiIdBlacklist); } catch (e) { firstPageIndex = 0; console.error(e); } try { lastPageIndex = _navigationLogic.getPageIndexDeltaForCfi(pageRequest.lastVisibleCfi, _cfiClassBlacklist, _cfiElementBlacklist, _cfiIdBlacklist); } catch (e) { lastPageIndex = 0; console.error(e); } // Go to the page in the middle of the two elements pageIndex = _paginationInfo.currentPageIndex + Math.round((firstPageIndex + lastPageIndex) / 2); } else if(pageRequest.elementCfi) { try { pageIndex = _paginationInfo.currentPageIndex + _navigationLogic.getPageIndexDeltaForCfi(pageRequest.elementCfi, _cfiClassBlacklist, _cfiElementBlacklist, _cfiIdBlacklist); } catch (e) { pageIndex = 0; console.error(e); } } else if(pageRequest.firstPage) { pageIndex = 0; } else if(pageRequest.lastPage) { pageIndex = _paginationInfo.columnCount - 1; } else { console.debug("No criteria in pageRequest"); pageIndex = 0; } if (pageIndex < 0 || pageIndex > _paginationInfo.columnCount) { console.log('Illegal pageIndex value: ', pageIndex, 'column count is ', _paginationInfo.columnCount); pageIndex = pageIndex < 0 ? 0 : _paginationInfo.columnCount; } _paginationInfo.currentPageIndex = pageIndex; _paginationInfo.currentSpreadIndex = Math.floor(pageIndex / _paginationInfo.visibleColumnCount) ; onPaginationChanged(pageRequest.initiator, pageRequest.spineItem, pageRequest.elementId); return true; } this.openPage = function(pageRequest) { // Go to request page, it will save the new position in onPaginationChanged _openPageInternal(pageRequest); // Save it for when pagination is updated _lastPageRequest = pageRequest; }; this.resetCurrentPosition = function() { _lastPageRequest = undefined; }; this.saveCurrentPosition = function() { // If there's a deferred page request, there's no point in saving the current position // as it's going to change soon if (_deferredPageRequest) { return; } var _firstVisibleCfi = self.getFirstVisibleCfi(); var _lastVisibleCfi = self.getLastVisibleCfi(); _lastPageRequest = new PageOpenRequest(_currentSpineItem, self); _lastPageRequest.setFirstAndLastVisibleCfi(_firstVisibleCfi.contentCFI, _lastVisibleCfi.contentCFI); }; this.restoreCurrentPosition = function() { if (_lastPageRequest) { _openPageInternal(_lastPageRequest); } }; function redraw() { var offsetVal = -_paginationInfo.pageOffset + "px"; if (_htmlBodyIsVerticalWritingMode) { _$epubHtml.css("top", offsetVal); } else { var ltr = _htmlBodyIsLTRDirection || _htmlBodyIsLTRWritingMode; _$epubHtml.css("left", ltr ? offsetVal : ""); _$epubHtml.css("right", !ltr ? offsetVal : ""); } showBook(); // as it's no longer hidden by shifting the position } function updateViewportSize() { var newWidth = _$contentFrame.width(); // Ensure that the new viewport width is always even numbered // this is to prevent a rendering inconsistency between browsers when odd-numbered bounds are used for CSS columns // See https://github.com/readium/readium-shared-js/issues/37 newWidth -= newWidth % 2; var newHeight = _$contentFrame.height(); if(_lastViewPortSize.width !== newWidth || _lastViewPortSize.height !== newHeight){ _lastViewPortSize.width = newWidth; _lastViewPortSize.height = newHeight; return true; } return false; } function onPaginationChanged_(initiator, paginationRequest_spineItem, paginationRequest_elementId) { _paginationInfo.currentPageIndex = _paginationInfo.currentSpreadIndex * _paginationInfo.visibleColumnCount; _paginationInfo.pageOffset = (_paginationInfo.columnWidth + _paginationInfo.columnGap) * _paginationInfo.visibleColumnCount * _paginationInfo.currentSpreadIndex; redraw(); _.defer(function () { if (_lastPageRequest == undefined) { self.saveCurrentPosition(); } Globals.logEvent("InternalEvents.CURRENT_VIEW_PAGINATION_CHANGED", "EMIT", "reflowable_view.js"); self.emit(Globals.InternalEvents.CURRENT_VIEW_PAGINATION_CHANGED, { paginationInfo: self.getPaginationInfo(), initiator: initiator, spineItem: paginationRequest_spineItem, elementId: paginationRequest_elementId }); }); } var onPaginationChanged = _.debounce(onPaginationChanged_, 100); this.openPagePrev = function (initiator) { if(!_currentSpineItem) { return; } if(_paginationInfo.currentSpreadIndex > 0) { // Page will change, the current position is not valid any more // Reset it so it's saved next time onPaginationChanged is called this.resetCurrentPosition(); _paginationInfo.currentSpreadIndex--; onPaginationChanged(initiator, _currentSpineItem); } else { var prevSpineItem = _spine.prevItem(_currentSpineItem, true); if(prevSpineItem) { var pageRequest = new PageOpenRequest(prevSpineItem, initiator); pageRequest.setLastPage(); self.openPage(pageRequest); } } }; this.openPageNext = function (initiator) { if(!_currentSpineItem) { return; } if(_paginationInfo.currentSpreadIndex < _paginationInfo.spreadCount - 1) { // Page will change, the current position is not valid any more // Reset it so it's saved next time onPaginationChanged is called this.resetCurrentPosition(); _paginationInfo.currentSpreadIndex++; onPaginationChanged(initiator, _currentSpineItem); } else { var nextSpineItem = _spine.nextItem(_currentSpineItem, true); if(nextSpineItem) { var pageRequest = new PageOpenRequest(nextSpineItem, initiator); pageRequest.setFirstPage(); self.openPage(pageRequest); } } }; function updatePagination_() { // At 100% font-size = 16px (on HTML, not body or descendant markup!) var MAXW = _paginationInfo.columnMaxWidth; var MINW = _paginationInfo.columnMinWidth; var isDoublePageSyntheticSpread = Helpers.deduceSyntheticSpread(_$viewport, _currentSpineItem, _viewSettings); var forced = (isDoublePageSyntheticSpread === false) || (isDoublePageSyntheticSpread === true); // excludes 0 and 1 falsy/truthy values which denote non-forced result // console.debug("isDoublePageSyntheticSpread: " + isDoublePageSyntheticSpread); // console.debug("forced: " + forced); // if (isDoublePageSyntheticSpread === 0) { isDoublePageSyntheticSpread = 1; // try double page, will shrink if doesn't fit // console.debug("TRYING SPREAD INSTEAD OF SINGLE..."); } _paginationInfo.visibleColumnCount = isDoublePageSyntheticSpread ? 2 : 1; if (_htmlBodyIsVerticalWritingMode) { MAXW *= 2; isDoublePageSyntheticSpread = false; forced = true; _paginationInfo.visibleColumnCount = 1; // console.debug("Vertical Writing Mode => single CSS column, but behaves as if two-page spread"); } if(!_$epubHtml) { return; } hideBook(); // shiftBookOfScreen(); // "borderLeft" is the blank vertical strip (e.g. 40px wide) where the left-arrow button resides, i.e. previous page command var borderLeft = parseInt(_$viewport.css("border-left-width")); // The "columnGap" separates two consecutive columns in a 2-page synthetic spread (e.g. 60px wide). // This middle gap (blank vertical strip) actually corresponds to the left page's right-most margin, combined with the right page's left-most margin. // So, "adjustedGapLeft" is half of the center strip... var adjustedGapLeft = _paginationInfo.columnGap/2; // ...but we include the "borderLeft" strip to avoid wasting valuable rendering real-estate: adjustedGapLeft = Math.max(0, adjustedGapLeft-borderLeft); // Typically, "adjustedGapLeft" is zero because the space available for the 'previous page' button is wider than half of the column gap! // "borderRight" is the blank vertical strip (e.g. 40px wide) where the right-arrow button resides, i.e. next page command var borderRight = parseInt(_$viewport.css("border-right-width")); // The "columnGap" separates two consecutive columns in a 2-page synthetic spread (e.g. 60px wide). // This middle gap (blank vertical strip) actually corresponds to the left page's right-most margin, combined with the right page's left-most margin. // So, "adjustedGapRight" is half of the center strip... var adjustedGapRight = _paginationInfo.columnGap/2; // ...but we include the "borderRight" strip to avoid wasting valuable rendering real-estate: adjustedGapRight = Math.max(0, adjustedGapRight-borderRight); // Typically, "adjustedGapRight" is zero because the space available for the 'next page' button is wider than half of the column gap! (in other words, the right-most and left-most page margins are fully included in the strips reserved for the arrow buttons) // Note that "availableWidth" does not contain "borderLeft" and "borderRight" (.width() excludes the padding and border and margin in the CSS box model of div#epub-reader-frame) var availableWidth = _$viewport.width(); // ...So, we substract the page margins and button spacing to obtain the width available for actual text: var textWidth = availableWidth - adjustedGapLeft - adjustedGapRight; // ...and if we have 2 pages / columns, then we split the text width in half: if (isDoublePageSyntheticSpread) { textWidth = (textWidth - _paginationInfo.columnGap) * 0.5; } var filler = 0; // Now, if the resulting width actually available for document content is greater than the maximum allowed value, we create even more left+right blank space to "compress" the horizontal run of text. if (textWidth > MAXW) { var eachPageColumnReduction = textWidth - MAXW; // if we have a 2-page synthetic spread, then we "trim" left and right sides by adding "eachPageColumnReduction" blank space. // if we have a single page / column, then this loss of text real estate is shared between right and left sides filler = Math.floor(eachPageColumnReduction * (isDoublePageSyntheticSpread ? 1 : 0.5)); } // Let's check whether a narrow two-page synthetic spread (impeded reabability) can be reduced down to a single page / column: else if (!forced && textWidth < MINW && isDoublePageSyntheticSpread) { isDoublePageSyntheticSpread = false; _paginationInfo.visibleColumnCount = 1; textWidth = availableWidth - adjustedGapLeft - adjustedGapRight; if (textWidth > MAXW) { filler = Math.floor((textWidth - MAXW) * 0.5); } } _$el.css({"left": (filler+adjustedGapLeft + "px"), "right": (filler+adjustedGapRight + "px")}); updateViewportSize(); //_$contentFrame ==> _lastViewPortSize var resultingColumnWidth = _$el.width(); if (isDoublePageSyntheticSpread) { resultingColumnWidth = (resultingColumnWidth - _paginationInfo.columnGap) / 2; } resultingColumnWidth = Math.floor(resultingColumnWidth); if ((resultingColumnWidth-1) > MAXW) { console.debug("resultingColumnWidth > MAXW ! " + resultingColumnWidth + " > " + MAXW); } _$iframe.css("width", _lastViewPortSize.width + "px"); _$iframe.css("height", _lastViewPortSize.height + "px"); _$epubHtml.css("height", _lastViewPortSize.height + "px"); // below min- max- are required in vertical writing mode (height is not enough, in some cases...weird!) _$epubHtml.css("min-height", _lastViewPortSize.height + "px"); _$epubHtml.css("max-height", _lastViewPortSize.height + "px"); //normalise spacing to avoid interference with column-isation _$epubHtml.css('margin', 0); _$epubHtml.css('padding', 0); _$epubHtml.css('border', 0); // In order for the ResizeSensor to work, the content body needs to be "positioned". // This may be an issue since it changes the assumptions some content authors might make when positioning their content. _$htmlBody.css('position', 'relative'); _$htmlBody.css('margin', 0); _$htmlBody.css('padding', 0); _paginationInfo.rightToLeft = _spine.isRightToLeft(); _paginationInfo.columnWidth = Math.round(((_htmlBodyIsVerticalWritingMode ? _lastViewPortSize.height : _lastViewPortSize.width) - _paginationInfo.columnGap * (_paginationInfo.visibleColumnCount - 1)) / _paginationInfo.visibleColumnCount); var useColumnCountNotWidth = _paginationInfo.visibleColumnCount > 1; // column-count == 1 does not work in Chrome, and is not needed anyway (HTML width is full viewport width, no Firefox video flickering) if (useColumnCountNotWidth) { _$epubHtml.css("width", _lastViewPortSize.width + "px"); _$epubHtml.css("column-width", "auto"); _$epubHtml.css("column-count", _paginationInfo.visibleColumnCount); } else { _$epubHtml.css("width", (_htmlBodyIsVerticalWritingMode ? _lastViewPortSize.width : _paginationInfo.columnWidth) + "px"); _$epubHtml.css("column-count", "auto"); _$epubHtml.css("column-width", _paginationInfo.columnWidth + "px"); } _$epubHtml.css("column-fill", "auto"); _$epubHtml.css({left: "0", right: "0", top: "0"}); Helpers.triggerLayout(_$iframe); var dim = (_htmlBodyIsVerticalWritingMode ? _$epubHtml[0].scrollHeight : _$epubHtml[0].scrollWidth); if (dim == 0) { console.error("Document dimensions zero?!"); } _paginationInfo.columnCount = (dim + _paginationInfo.columnGap) / (_paginationInfo.columnWidth + _paginationInfo.columnGap); _paginationInfo.columnCount = Math.round(_paginationInfo.columnCount); if (_paginationInfo.columnCount == 0) { console.error("Column count zero?!"); } var totalGaps = (_paginationInfo.columnCount-1) * _paginationInfo.columnGap; var colWidthCheck = (dim - totalGaps) / _paginationInfo.columnCount; colWidthCheck = Math.round(colWidthCheck); if (colWidthCheck > _paginationInfo.columnWidth) { console.debug("ADJUST COLUMN"); console.log(_paginationInfo.columnWidth); console.log(colWidthCheck); _paginationInfo.columnWidth = colWidthCheck; } _paginationInfo.spreadCount = Math.ceil(_paginationInfo.columnCount / _paginationInfo.visibleColumnCount); if(_paginationInfo.currentSpreadIndex >= _paginationInfo.spreadCount) { _paginationInfo.currentSpreadIndex = _paginationInfo.spreadCount - 1; } if(_deferredPageRequest) { //if there is a request for specific page we get here openDeferredElement(); } else { // we get here on resizing the viewport if (_lastPageRequest) { // Make sure we stay on the same page after the content or the viewport // has been resized _paginationInfo.currentPageIndex = 0; // current page index is not stable, reset it self.restoreCurrentPosition(); } else { onPaginationChanged(self, _currentSpineItem); // => redraw() => showBook(), so the trick below is not needed } //onPaginationChanged(self, _currentSpineItem); // => redraw() => showBook(), so the trick below is not needed // //We do this to force re-rendering of the document in the iframe. // //There is a bug in WebView control with right to left columns layout - after resizing the window html document // //is shifted in side the containing div. Hiding and showing the html element puts document in place. // _$epubHtml.hide(); // setTimeout(function() { // _$epubHtml.show(); // onPaginationChanged(self, _currentSpineItem); // => redraw() => showBook() // }, 50); } // Only initializes the resize sensor once the content has been paginated once, // to avoid the pagination process to trigger a resize event during its first // execution, provoking a flicker initResizeSensor(); } var updatePagination = _.debounce(updatePagination_, 100); function initResizeSensor() { var bodyElement = _$htmlBody[0]; if (bodyElement.resizeSensor) { return; } // We need to make sure the content has indeed be resized, especially // the first time it is triggered _lastBodySize.width = $(bodyElement).width(); _lastBodySize.height = $(bodyElement).height(); bodyElement.resizeSensor = new ResizeSensor(bodyElement, function() { var newBodySize = { width: $(bodyElement).width(), height: $(bodyElement).height() }; console.debug("ReflowableView content resized ...", newBodySize.width, newBodySize.height, _currentSpineItem.idref); if (newBodySize.width != _lastBodySize.width || newBodySize.height != _lastBodySize.height) { _lastBodySize.width = newBodySize.width; _lastBodySize.height = newBodySize.height; console.debug("... updating pagination."); updatePagination(); } else { console.debug("... ignored (identical dimensions)."); } }); } // function shiftBookOfScreen() { // // if(_spine.isLeftToRight()) { // _$epubHtml.css("left", (_lastViewPortSize.width + 1000) + "px"); // } // else { // _$epubHtml.css("right", (_lastViewPortSize.width + 1000) + "px"); // } // } function hideBook() { if (_currentOpacity != -1) return; // already hidden // css('opacity') produces invalid result in Firefox, when iframes are involved and when is called // directly after set, i.e. after showBook(), see: https://github.com/jquery/jquery/issues/2622 //_currentOpacity = $epubHtml.css('opacity'); _currentOpacity = _$epubHtml[0].style.opacity; _$epubHtml.css('opacity', "0"); } function showBook() { if (_currentOpacity != -1) { _$epubHtml.css('opacity', _currentOpacity); } _currentOpacity = -1; } this.getPaginationInfo = function() { var paginationInfo = new CurrentPagesInfo(_spine, false); if(!_currentSpineItem) { return paginationInfo; } var pageIndexes = getOpenPageIndexes(); for(var i = 0, count = pageIndexes.length; i < count; i++) { paginationInfo.addOpenPage(pageIndexes[i], _paginationInfo.columnCount, _currentSpineItem.idref, _currentSpineItem.index); } return paginationInfo; }; function getOpenPageIndexes() { var indexes = []; var currentPage = _paginationInfo.currentSpreadIndex * _paginationInfo.visibleColumnCount; for(var i = 0; i < _paginationInfo.visibleColumnCount && (currentPage + i) < _paginationInfo.columnCount; i++) { indexes.push(currentPage + i); } return indexes; } //we need this styles for css columnizer not to chop big images function resizeImages() { if(!_$epubHtml) { return; } var $elem; var height; var width; $('img, svg', _$epubHtml).each(function(){ $elem = $(this); // if we set max-width/max-height to 100% columnizing engine chops images embedded in the text // (but not if we set it to 99-98%) go figure. // TODO: CSS min-w/h is content-box, not border-box (does not take into account padding + border)? => images may still overrun? $elem.css('max-width', '98%'); $elem.css('max-height', '98%'); if(!$elem.css('height')) { $elem.css('height', 'auto'); } if(!$elem.css('width')) { $elem.css('width', 'auto'); } }); } this.bookmarkCurrentPage = function() { if(!_currentSpineItem) { return undefined; } return self.getFirstVisibleCfi(); }; this.getLoadedSpineItems = function() { return [_currentSpineItem]; }; this.getElementByCfi = function(spineItemIdref, cfi, classBlacklist, elementBlacklist, idBlacklist) { if(spineItemIdref != _currentSpineItem.idref) { console.warn("spine item is not loaded"); return undefined; } return _navigationLogic.getElementByCfi(cfi, classBlacklist, elementBlacklist, idBlacklist); }; this.getElementById = function(spineItemIdref, id) { if(spineItemIdref != _currentSpineItem.idref) { console.error("spine item is not loaded"); return undefined; } return _navigationLogic.getElementById(id); }; this.getElement = function(spineItemIdref, selector) { if(spineItemIdref != _currentSpineItem.idref) { console.warn("spine item is not loaded"); return undefined; } return _navigationLogic.getElement(selector); }; this.getFirstVisibleMediaOverlayElement = function() { return _navigationLogic.getFirstVisibleMediaOverlayElement(); }; this.insureElementVisibility = function(spineItemId, element, initiator) { var $element = $(element); if(_navigationLogic.isElementVisible($element)) { return; } var elementCfi = _navigationLogic.getCfiForElement(element); if (!elementCfi) { return; } var openPageRequest = new PageOpenRequest(_currentSpineItem, initiator); openPageRequest.setElementCfi(elementCfi); var id = element.id; if (!id) { id = element.getAttribute("id"); } if (id) { openPageRequest.setElementId(id); } self.openPage(openPageRequest); }; this.getVisibleElementsWithFilter = function(filterFunction, includeSpineItem) { var elements = _navigationLogic.getVisibleElementsWithFilter(null, filterFunction); if (includeSpineItem) { return [{elements: elements, spineItem:_currentSpineItem}]; } else { return elements; } }; this.getVisibleElements = function(selector, includeSpineItem) { var elements = _navigationLogic.getAllVisibleElementsWithSelector(selector); if (includeSpineItem) { return [{elements: elements, spineItem:_currentSpineItem}]; } else { return elements; } }; this.isElementVisible = function ($element) { return _navigationLogic.isElementVisible($element); }; this.getElements = function(spineItemIdref, selector) { if(spineItemIdref != _currentSpineItem.idref) { console.warn("spine item is not loaded"); return undefined; } return _navigationLogic.getElements(selector); }; this.isNodeFromRangeCfiVisible = function (spineIdref, partialCfi) { if (_currentSpineItem.idref === spineIdref) { return _navigationLogic.isNodeFromRangeCfiVisible(partialCfi); } return undefined; }; this.isVisibleSpineItemElementCfi = function (spineIdRef, partialCfi) { if (_navigationLogic.isRangeCfi(partialCfi)) { return this.isNodeFromRangeCfiVisible(spineIdRef, partialCfi); } var $elementFromCfi = this.getElementByCfi(spineIdRef, partialCfi); return ($elementFromCfi && this.isElementVisible($elementFromCfi)); }; this.getNodeRangeInfoFromCfi = function (spineIdRef, partialCfi) { if (spineIdRef != _currentSpineItem.idref) { console.warn("spine item is not loaded"); return undefined; } return _navigationLogic.getNodeRangeInfoFromCfi(partialCfi); }; function createBookmarkFromCfi(cfi){ return new BookmarkData(_currentSpineItem.idref, cfi); } this.getFirstVisibleCfi = function () { return createBookmarkFromCfi(_navigationLogic.getFirstVisibleCfi()); }; this.getLastVisibleCfi = function () { return createBookmarkFromCfi(_navigationLogic.getLastVisibleCfi()); }; this.getStartCfi = function () { return createBookmarkFromCfi(_navigationLogic.getStartCfi()); }; this.getEndCfi = function () { return createBookmarkFromCfi(_navigationLogic.getEndCfi()); }; this.getDomRangeFromRangeCfi = function (rangeCfi, rangeCfi2, inclusive) { if (rangeCfi2 && rangeCfi.idref !== rangeCfi2.idref) { console.error("getDomRangeFromRangeCfi: both CFIs must be scoped under the same spineitem idref"); return undefined; } return _navigationLogic.getDomRangeFromRangeCfi(rangeCfi.contentCFI, rangeCfi2? rangeCfi2.contentCFI: null, inclusive); }; this.getRangeCfiFromDomRange = function (domRange) { return createBookmarkFromCfi(_navigationLogic.getRangeCfiFromDomRange(domRange)); }; this.getVisibleCfiFromPoint = function (x, y, precisePoint) { return createBookmarkFromCfi(_navigationLogic.getVisibleCfiFromPoint(x, y, precisePoint)); }; this.getRangeCfiFromPoints = function(startX, startY, endX, endY) { return createBookmarkFromCfi(_navigationLogic.getRangeCfiFromPoints(startX, startY, endX, endY)); }; this.getCfiForElement = function(element) { return createBookmarkFromCfi(_navigationLogic.getCfiForElement(element)); }; this.getElementFromPoint = function(x, y) { return _navigationLogic.getElementFromPoint(x,y); }; this.getNearestCfiFromElement = function(element) { return createBookmarkFromCfi(_navigationLogic.getNearestCfiFromElement(element)); }; }; return ReflowableView; });
#!/usr/bin/env node 'use strict'; // To require local modules from root. global.ROOT = __dirname + '/../dist/'; const colors = require('colors'); const fs = require('fs'); const path = require('path'); const vm = require('vm'); const GRAMMAR_MODE = require(ROOT + 'grammar/grammar-mode').MODES; const Grammar = require(ROOT + 'grammar/grammar').default; const options = require('nomnom') .script('syntax') .options({ mode: { abbr: 'm', help: `Parser mode: ${getModesList()}`, transform: normalizeMode, }, grammar: { abbr: 'g', help: 'File containing LL or LR grammar', metavar: 'FILE' }, lex: { abbr: 'l', help: 'File containing lexical grammar', required: false, metavar: 'FILE' }, table: { abbr: 't', help: 'Generate and output parsing table', flag: true, }, collection: { abbr: 'c', help: 'Generate and output canonical collection of LR items', flag: true, }, sets: { abbr: 's', help: 'Generate and output parsing sets (all/first/follow/predict)', }, parse: { abbr: 'p', help: 'Parse a string and checks for acceptance', type: 'string', }, file: { abbr: 'f', help: 'File to be parsed', type: 'string', metavar: 'FILE' }, output: { abbr: 'o', help: 'Output file for a generated parser module', type: 'string', metavar: 'FILE' }, 'custom-tokenizer': { abbr: 'k', help: 'Path to a file with custom tokenizer class', type: 'string', metavar: 'FILE' }, 'tokenizer-only': { help: 'Whether to generate only standalone tokenizer output file', flag: true, }, 'tokenize': { help: 'Show list of tokens', flag: true, }, 'ignore-whitespaces': { abbr: 'w', help: 'Adds a Lex rule to ignore whitespaces', flag: true, }, 'resolve-conflicts': { abbr: 'r', help: 'Whether to auto-resolve conflicts with default action', flag: true, }, 'generate-inline-parser': { help: 'Whether to generate a parser module for parsing a passed string', flag: true, }, 'loc': { help: 'Capture token locations (offsets, line and column numbers)', flag: true, }, 'case-insensitive': { help: 'Sets case-insensitive mode to lexical grammar', abbr: 'i', flag: true, }, namespace: { help: 'Append a wrapping namespace to generated code', type: 'string', }, }) .parse(); /** * Default generator options. */ const generatorOptions = { customTokenizer: options['custom-tokenizer'], resolveConflicts: options['resolve-conflicts'], namespace: options['namespace'], }; /** * Set of parsers. */ const parsers = { LR0(options) { return this._genericLR(GRAMMAR_MODE.LR0, options); }, SLR1(options) { return this._genericLR(GRAMMAR_MODE.SLR1, options); }, CLR1(options) { return this._genericLR(GRAMMAR_MODE.CLR1, options); }, LALR1(options) { return this._genericLR(GRAMMAR_MODE.LALR1, options); }, _genericLR(mode, options) { const grammar = getGrammar(options.grammar, mode); console.info(`\nParsing mode: ${grammar.getMode()}.`); // Canonical collection or LR items. if (options.collection) { const CanonicalCollection = require(ROOT + 'lr/canonical-collection').default; new CanonicalCollection({grammar}) .print(); } // LR parsing table. if (options.table) { const CanonicalCollection = require(ROOT + 'lr/canonical-collection').default; const LRParsingTable = require(ROOT + 'lr/lr-parsing-table').default; new LRParsingTable({ grammar, canonicalCollection: new CanonicalCollection({grammar}), resolveConflicts: options['resolve-conflicts'], }).print(); } // Parse a string. if (provided('parse')) { parse(options.parse, grammar); } // Parse a file. if (provided('file')) { parse(fs.readFileSync(options.file, 'utf-8'), grammar); } // Output information about tokens. if (options['tokenize']) { tokenizeFromOptions(options, grammar.getLexGrammar()); } // Generate parser module. if (options.output) { const outputFile = options.output; const language = path.extname(outputFile).slice(1); // Generator is language agnostic. const GENERATORS = { // Default. 'js' : require(ROOT + 'lr/lr-parser-generator-default.js').default, // Plugins. 'example' : require(ROOT + 'plugins/example/lr/lr-parser-generator-example.js').default, 'py' : require(ROOT + 'plugins/python/lr/lr-parser-generator-py.js').default, 'php': require(ROOT + 'plugins/php/lr/lr-parser-generator-php.js').default, 'rb' : require(ROOT + 'plugins/ruby/lr/lr-parser-generator-ruby.js').default, 'cs' : require(ROOT + 'plugins/csharp/lr/lr-parser-generator-csharp.js').default, }; const LRParserGenerator = GENERATORS[language] || GENERATORS.js; new LRParserGenerator({ grammar, outputFile, options: generatorOptions, }).generate(); showGeneratedSuccessMessage(options.output); } }, LL1(options) { const grammar = getGrammar(options.grammar, GRAMMAR_MODE.LL1); console.info(`\nParsing mode: ${grammar.getMode()}.`); // LL parsing table. if (options.table) { const LLParsingTable = require(ROOT + 'll/ll-parsing-table').default; new LLParsingTable({ grammar, }).print(); } // Parse a string. if (provided('parse')) { parse(options.parse, grammar); } // Parse a file. if (provided('file')) { parse(fs.readFileSync(options.file, 'utf-8'), grammar); } // Output information about tokens. if (options['tokenize']) { tokenizeFromOptions(options, grammar.getLexGrammar()); } // Generate parser module. if (options.output) { const outputFile = options.output; const language = path.extname(outputFile).slice(1); // Generator is language agnostic. const GENERATORS = { // Default. 'js': require(ROOT + 'll/ll-parser-generator-default.js').default, // Plugins. 'example': require(ROOT + 'plugins/example/ll/ll-parser-generator-example.js').default, 'py': require(ROOT + 'plugins/python/ll/ll-parser-generator-py.js').default, 'php': require(ROOT + 'plugins/php/ll/ll-parser-generator-php.js').default, 'rb' : require(ROOT + 'plugins/ruby/ll/ll-parser-generator-ruby.js').default, }; const LLParserGenerator = GENERATORS[language]; new LLParserGenerator({ grammar, outputFile, options: generatorOptions, }).generate(); showGeneratedSuccessMessage(options.output); } }, }; function showGeneratedSuccessMessage(filePath) { console.info( `${colors.green('\n\u2713 Successfully generated:')}`, filePath, '\n' ); } function parse(string, grammar) { console.info(`\n${colors.bold('Parsing:')}\n\n${string}\n`); try { const parsed = grammar.getMode().isLR() ? lrParse(string, grammar) : llParse(string, grammar); if (parsed.status === 'accept') { console.info(`${colors.green('\u2713 Accepted')}\n`); } if (parsed.hasOwnProperty('value')) { console.info( colors.bold('Parsed value:'), '\n\n' + formatParsedOutput(parsed.value), '\n' ); } } catch (e) { console.info(`${colors.red(e.stack)}\n`); process.exit(1); } } function lrParse(string, grammar) { const LRParser = require(ROOT + 'lr/lr-parser').default; if (options['generate-inline-parser']) { return LRParser.fromParserGenerator({grammar}).parse(string); } return new LRParser({grammar}).parse(string); } function llParse(string, grammar) { const LLParser = require(ROOT + 'll/ll-parser').default; if (options['generate-inline-parser']) { return LLParser.fromParserGenerator({grammar}).parse(string); } return new LLParser({grammar}).parse(string); } function formatParsedOutput(output) { // Object constructor is used from another realm, so no direct // constructor check, neither `instanceof` would work. Check // `name` property. if ( Array.isArray(output) || (output && output.constructor && output.constructor.name === 'Object') ) { return JSON.stringify(output, null, 2); } return output; } function getGrammar(grammarFile, mode) { if (!grammarFile) { return null; } const grammarData = Grammar.dataFromGrammarFile(grammarFile, 'bnf'); // If explicit lexical grammar file was passed, use it. const lexGrammarData = getLexGrammarData(options); if (lexGrammarData) { grammarData.lex = Object.assign( {}, grammarData.lex || {}, lexGrammarData ); } const grammarOptions = { /** * Parsing mode. */ mode, /** * Whether to capture locations. */ captureLocations: options.loc, }; return Grammar.fromData(grammarData, grammarOptions); } function getLexGrammarData(options) { let data = null; // If explicit lexical grammar file was passed, use it. if (options.lex) { data = Grammar.dataFromGrammarFile(options.lex, 'lex'); } if (options['ignore-whitespaces'] && !data) { data = { rules: [ ['\\s+', /* skip whitespace */''], ], }; } if (options['case-insensitive']) { if (!data) { data = {}; } if (!data.options) { data.options = {}; } data.options['case-insensitive'] = true; } return data; } function normalizeMode(mode) { return mode.toUpperCase(); } function getModesList() { return Object.keys(GRAMMAR_MODE).join(', '); } function extractMode(options) { let mode = options.mode; // If no explicit mode is passed, try // infer it from the grammar file extension. if (!mode && options.grammar) { mode = path.extname(options.grammar).slice(1); } if (!mode) { error(`\nError: "mode" option is required for parsing\n`); return null; } mode = normalizeMode(mode); if (!GRAMMAR_MODE.hasOwnProperty(mode)) { error(`\nError: "${mode}" is not a valid parsing mode. ` + `Valid modes are: ${getModesList()}.\n` ); return null; } if (!parsers.hasOwnProperty(mode)) { let availableModes = Object.keys(parsers) .filter(mode => !mode.startsWith('_')) .join(', '); error( `\nError: "${mode}" is not implemented yet. ` + `Available parsers are: ${availableModes}.\n` ); return null; } return (options.mode = mode); } function handleSets() { const SetsGenerator = require(ROOT + 'sets-generator').default; let sets = options.sets; let sg = new SetsGenerator({ grammar: getGrammar(options.grammar, options.mode), }); if (sets.indexOf('first') !== -1 || sets === 'all') { sg.printSet(sg.getFirstSets()); } if (sets.indexOf('follow') !== -1 || sets === 'all') { sg.printSet(sg.getFollowSets()); } if (sets.indexOf('predict') !== -1 || sets === 'all') { sg.printSet(sg.getPredictSets()); } } function error(message) { console.error(colors.red(message)); console.log('Run --help for details.\n'); process.exit(1); } function isTokenizerOnly(options) { return options['tokenizer-only'] || (options.lex && !options.grammar); } function handleStandaloneTokenizer() { const LexGrammar = require(ROOT + 'grammar/lex-grammar').default; let lexGrammarData = getLexGrammarData(options); let lexGrammar; if (lexGrammarData) { lexGrammar = new LexGrammar(lexGrammarData); } else { // Try infer from --grammar. lexGrammar = getGrammar(options.grammar, options.mode).getLexGrammar(); } if (!provided('tokenize') && !provided('output')) { error('\nError: for tokenization pass either --tokenize or --output.\n'); } if (options['tokenize']) { tokenizeFromOptions(options, lexGrammar); } } function provided(option) { return options.hasOwnProperty(option); } function tokenizeFromOptions(options, lexGrammar) { if (!provided('parse') && !provided('file')) { error('\nError: tokenization requires -p or -f parameter\n'); return; } // Tokenize a string. if (provided('parse')) { tokenize(options.parse, lexGrammar); } // Tokinize a file. if (provided('file')) { tokenize(fs.readFileSync(options.file, 'utf-8'), lexGrammar); } } function tokenize(string, lexGrammar) { // Inline tokenization supported only for JS. const Tokenizer = require(ROOT + 'tokenizer').default; const tokens = (new Tokenizer({string, lexGrammar})).getTokens(); // Don't show last EOF token. tokens.pop(); console.info( colors.bold('\nList of tokens:'), '\n\n', formatParsedOutput(tokens), '\n' ); } function main() { if (!options.grammar && !options.lex) { error(`\nError: expected at least --grammar or --lex parameters.\n`); return; } // Generating a standalone tokenizer, either from direct --lex // parameter, or from the `lex` part of the --grammar parameter. if (isTokenizerOnly(options)) { return handleStandaloneTokenizer(); } // Sets. if (options.sets) { handleSets(); } parsers[extractMode(options)](options); } if (require.main === module) { main(); }
var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2" }); var sns = new AWS.SNS(); async function add(req, context) { var body = req['body-json']; var ep = body.email var params = { Protocol: 'email', TopicArn: 'arn:aws:sns:us-west-2:272838180588:aws-iot-button-sns-topic', Endpoint: ep }; console.log(params); var subdata = await sns.subscribe(params).promise() console.log(subdata); var redirectPage = '<html><head><meta http-equiv="refresh" content="5;url=http://mslingsu.com/#/" /></head><body><h1>Redirecting in 5 seconds...</h1></body></html>' return redirectPage } module.exports = { add: add }
import { useRef, useState, useCallback } from "react"; import * as tf from "@tensorflow/tfjs"; import * as posenet from "@tensorflow-models/posenet"; import { clearCanvas, drawEmoticons } from "./utils"; import "./App.css"; import VideoCamera from "./components/VideoCamera/VideoCamera"; // TODOS // - Only show button if there are multiple cameras // - Make emoticon settings adjstable by the user // - Allow multiple input resolutions // App consts const REFRESH_RATE = 100; const INPUT_RESOLUTION = { width: 640, height: 480 }; const SCALE = 1; const EMOTICONS = { nose: "❌", leftEye: "🌀", rightEye: "🌀", leftEar: "⚠️", rightEar: "⚠️", }; function App() { const [facingMode, setFacingMode] = useState("user"); const webcamEl = useRef(null); const canvasEl = useRef(null); const handleCameraClick = useCallback(() => { // Clear emoticons from canvas clearCanvas(canvasEl.current); // Set facing mode to environment or user setFacingMode(facingMode === "environment" ? "user" : "environment"); }, [facingMode]); const detectPose = async (posenet_model) => { if (webcamEl.current !== null && webcamEl.current.readyState === 4) { const camera = webcamEl.current; const videoWidth = webcamEl.current.videoWidth; const videoHeight = webcamEl.current.videoHeight; webcamEl.current.width = videoWidth; webcamEl.current.height = videoHeight; // Get pose and detect body parts using the posenet model const posenet = await posenet_model.estimateSinglePose(camera); drawEmoticons( posenet, camera, videoWidth, videoHeight, canvasEl, EMOTICONS ); } }; const initPoseNet = async () => { const model = await posenet.load({ inputResolution: INPUT_RESOLUTION, scale: SCALE, }); setInterval(() => { detectPose(model); }, REFRESH_RATE); }; initPoseNet(); return ( <div className="App"> <VideoCamera videoRef={webcamEl} constraints={{ video: { facingMode, }, }} /> <canvas ref={canvasEl} /> <button onClick={handleCameraClick}>Flip cameras</button> </div> ); } export default App;
import React from 'react'; import PropTypes from 'prop-types'; import { Modal, Button, } from 'semantic-ui-react'; const CommentDeleteModal = ({ ...props }) => { const { openDelete, closeDeleteModal, handleDelete, size, } = props; return ( <div> <Modal size={size} open={openDelete} onClose={closeDeleteModal}> <Modal.Header>Delete Your Comment</Modal.Header> <Modal.Content> <p>Are you sure you want to delete your comment</p> </Modal.Content> <Modal.Actions> <Button secondary onClick={closeDeleteModal}>No</Button> <Button className="ui medium teal button" icon="checkmark" labelPosition="right" content="Yes" onClick={handleDelete} /> </Modal.Actions> </Modal> </div> ); }; CommentDeleteModal.propTypes = { openDelete: PropTypes.func.isRequired, closeDeleteModal: PropTypes.func.isRequired, handleDelete: PropTypes.func.isRequired, size: PropTypes.string.isRequired, }; export default CommentDeleteModal;
import { combineReducers } from "redux" import transactionReducer from './transactions' export default combineReducers({ transactions:transactionReducer, });
// 这里专门处理http服务 const http = require("http"); const port = 8000; // 引入处理请求的函数 const serverHandle = require("../app"); const server = http.createServer(serverHandle); server.listen(port); console.log("blok1 ok", process.env.NODE_ENV);
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Die Software darf unter den Bedingungen // der APGL ( Affero Gnu Public Licence ) genutzt werden // // weblet: warehouse/productpart/detail // ================================================================================ { var i; var str = ""; var ivalues = { schema : 'mne_warehouse', query : 'productpart', table : 'productpart', okfunction : 'productpart_ok', delfunction : 'productpart_del' }; var svalues = { }; weblet.initDefaults(ivalues, svalues); weblet.loadview(); var attr = { hinput : false, partcostInput : { onblur : function() { this.weblet.showInputDefined(this.weblet.obj.inputs.partcostsum, this.value * this.weblet.obj.inputs.count.value, 'double') }, onreturn : function() { this.onblur(); } }, partcostsumInput : { onblur : function() { if ( Number(this.weblet.obj.inputs.count.value) != 0 ) this.weblet.showInputDefined(this.weblet.obj.inputs.partcost, this.value / this.weblet.obj.inputs.count.value , 'double') }, onreturn : function() { this.onblur(); } }, countInput : { onblur : function() { this.weblet.showInputDefined(this.weblet.obj.inputs.partcostsum, this.value * this.weblet.obj.inputs.partcost.value, 'double') }, onreturn : function() { this.onblur(); } }, productidInput : { notclear : true }, productnameOutput : { notclear : true }, fixturetypeidInput : { inputcheckobject : 'fixturetype' }, partidInput : { inputcheckobject : 'partname' }, okButton : { "style.width" : "10em" } } weblet.findIO(attr); weblet.showLabel(); weblet.showids = new Array("productpartid"); weblet.titleString.add = weblet.txtGetText("#mne_lang#Material hinzufügen"); weblet.titleString.mod = weblet.txtGetText("#mne_lang#Material bearbeiten"); var param = { "schema" : "mne_crm", "query" : "companyown", "cols" : "currencyid,currency", "sqlend" : 1 }; MneAjaxData.prototype.read.call(weblet, "/db/utils/query/data.xml", param) if ( weblet.values.length > 0 ) weblet.defvalues = { partcostsumcurrency : weblet.values[0][1], partcostcurrency : weblet.values[0][1] } else weblet.defvalues = { partcostsumcurrency : '#mne_lang#Währung bitte wählen', partcostcurrency : '#mne_lang#Währung bitte wählen'} weblet.showValue = function(weblet) { if ( weblet == null ) return; if ( typeof weblet.act_values.productpartid == 'undefined' || weblet.act_values.productpartid == '' ) { if ( typeof weblet.act_values.productid == 'undefined' || weblet.act_values.productid == '################' ) { alert("#mne_lang#Kein Produkt ausgewählt"); return false; } this.add(); this.showInput(this.obj.inputs.productid, weblet.act_values.productid); return; } return MneAjaxWeblet.prototype.showValue.call(this,weblet); } weblet.ok = function(setdepend) { var result; var p = { schema : this.initpar.schema, name : this.initpar.okfunction, typ2 : "double", typ5 : "double", sqlend : 1 } p = this.addParam(p, "par0", this.obj.inputs.productpartid); p = this.addParam(p, "par1", this.obj.inputs.productid); p = this.addParam(p, "par2", this.obj.inputs.count); p = this.addParam(p, "par3", this.obj.inputs.partgroup); p = this.addParam(p, "par4", this.obj.inputs.partdescription); p = this.addParam(p, "par5", this.obj.inputs.partcost); p = this.addParam(p, "par6", this.obj.inputs.partid); p = this.addParam(p, "par7", this.obj.inputs.fixturetypeid); p = this.addParam(p, "par8", this.obj.inputs.unit); result = MneAjaxWeblet.prototype.func.call(this, p, "productpartid", setdepend, "ok"); return result; } weblet.del = function(setdepend) { if ( this.confirm(this.txtSprintf(this.titleString.del, this.act_values[this.titleString.delid])) != true ) return false; var result; var p = { schema : this.initpar.schema, name : this.initpar.delfunction, sqlend : 1 } p = this.addParam(p, "par0", this.obj.inputs.productpartid); result = MneAjaxWeblet.prototype.func.call(this, p, null, setdepend, "del"); return result; } weblet.onbtnok = function(button) { var ele; if ( this.inputlist != null ) ele = this.inputlist.element; else ele = null; MneAjaxWeblet.prototype.onbtnok.call(this, button); if ( ele == 'partname' ) { this.showInput('fixturetypeid', ''); this.showOutput('fixturetype', ''); this.showInput('unit', ''); this.obj.inputs.partcost.onblur(); } else if ( ele == 'fixturetype' ) { this.showInput('partid', ''); this.showOutput('partname', ''); this.obj.inputs.partcost.onblur(); } else if ( ele == 'productname') { this.obj.inputs.partcost.onblur(); } } }
const dbDetails = require("./secrete/data") const Pool = require("pg").Pool; const pool = new Pool({ user: dbDetails.database.user, password: dbDetails.database.password, host : dbDetails.database.host, database: dbDetails.database.database }) module.exports = pool;
'use strict'; function UserController() { //returns an object to Handlebars to render pages this.renderParams = (err, user, title, isIndex) => { let admin = false; let index = false; let username; if (user) { username = user.username; admin = user.local.isAdmin; } if (isIndex) { index = true; } return { error: err || "", title: title, loggedin: user, username: username, admin: admin, index: index }; } this.isLoggedIn = (req, res, next) => { if (req.isAuthenticated()) { return next(); } else { console.log('No permission'); res.redirect('/'); } } this.isAdmin = (req, res, next) => { if (req.isAuthenticated()) { if (req.user.local.isAdmin) { return next(); } } res.redirect('/'); } //try replace this with identical api method this.getPost = (id, res) => { const Pk = require('../models/pk'); const ObjectId = require('mongodb').ObjectID; Pk.find(ObjectId(id)) .exec((err, doc) => { if (err) throw err; return res(doc) }) } } module.exports = UserController;
import React from 'react'; import {Link,Route} from 'react-router-dom'; export default class ArticleItem extends React.Component { constructor(props) { super(props); } render() { return ( <div className="articleItem_container"> <div className="articleItem_header">JavaScript正则表达式</div> <div className="articleItem_body">对象属性、字符类、js正则提供预定义类来匹配常见的字符类、js正则提供几个常用的边界匹配字符、量词、贪婪模式、利用()进行分组.....</div> <div className="articleItem_footer"> <div>李桥</div> <div>2018-08-10</div> </div> </div> ); } }
import { loginComponent } from "./pages/login/login.component"; import { tabsComponent } from "./pages/user/tabs/tabs.component"; import { notFoundComponent } from "./common/not-found.component"; import { usersComponent } from "./pages/user/users/users.component"; import { friendComponent } from "./pages/user/friends/friends.component"; export const appRoutes = [ { path: '', component: loginComponent }, { path: 'login', component: loginComponent }, { path: '**', component: notFoundComponent } ];
const router = require('express').Router(); const axios = require('axios'); const pool = require('../modules/pool'); const projectQueries = require('../queries/project.query'); const projectCombiner = require('../modules/utils/project-combiner'); const combineAndSend = async ({ res, projectIds, projectNames }) => { try { const [challengeId] = projectIds; let warnings = []; const projects = await Promise.all(projectIds.map(async (projectId) => { const projectResult = await pool.query(projectQueries.select(projectId)); const { details: projectDetails, challenge_id: botChallengeId } = projectResult && projectResult.rows && projectResult.rows[0]; if (projectDetails) { // match strings and numbers for challenges // eslint-disable-next-line eqeqeq if (challengeId != projectId && challengeId != botChallengeId) { warnings = [...warnings, 'Not all challenge ids match. Bots may be built for different challenges!']; } return projectDetails; } throw new Error(`No project found with id of ${projectId}`); })); if (projects.length > 1) { const [baseChallengeProject, ...competitors] = projects; res.send(projectCombiner({ baseChallengeProject, competitors, projectNames, warnings, })); } else { res.send(projects[0]); } } catch (error) { console.log('Error in combineAndSend while getting project', error); res.status(500).send(error.message); } }; router.get('/challenges', async (req, res) => { try { const { selectAll, selectAllOfficial } = projectQueries; const queryToRun = req.query.showPrivateChallenges === 'true' ? selectAll() : selectAllOfficial(); const { rows } = await pool.query(queryToRun); res.send(rows); } catch (error) { console.log('Error getting all challenges', error); res.sendStatus(500); } }); router.get('/', async (req, res) => { try { console.log('hitting project route with projectId', req.query); let { challenge } = req.query; const { difficulty, player1, player2, fullscreen, botSecretKey, } = req.query; if (!fullscreen) { const playerOneQuery = await pool.query(projectQueries.select(player1)); const botSecretKeyMatches = playerOneQuery.rows && playerOneQuery.rows[0] && playerOneQuery.rows[0].bot_secret_key === botSecretKey; if (!botSecretKeyMatches) { throw new Error('Bot secret key does not match'); } } if (!challenge) { // if no challenge, check if player1 has a challenge id to use const playerOneQuery = await pool.query(projectQueries.select(player1)); challenge = playerOneQuery.rows[0].challenge_id; if (!challenge) throw new Error('No challenge project id'); } // allow players to select a difficulty and play other bots if (difficulty && difficulty === 'hard' && !player2) { // search for corresponding challenge difficulty bot id const challengeQuery = await pool.query(projectQueries.select(challenge)); // set player 2 to the corresponding difficulty level const hardOpponent = challengeQuery.rows[0].hard_opponent; if (hardOpponent) { req.query.player2 = hardOpponent; } } const projectIds = [challenge]; let i = 1; const projectNames = []; while (req.query[`player${i}`]) { projectIds.push(req.query[`player${i}`]); projectNames.push(req.query[`player${i}name`]); i += 1; } await combineAndSend({ res, projectIds, projectNames }); } catch (error) { console.log('Error in base / path while getting project', error); res.status(500).send(error.message); } }); router.post('/add-scratch-project', async (req, res) => { try { const { scratchId, title, difficulty, description, } = req.body; if (!scratchId) throw new Error('No project id'); console.log('Adding a scratch project'); const scratchResponse = await axios.get(`https://projects.scratch.mit.edu/${scratchId}`); const scratchProject = { scratchId, title, difficulty, description, details: scratchResponse.data, isChallenge: true, }; const results = await pool.query(projectQueries.insert(scratchProject)); const savedProject = results.rows[0]; const message = `Added Scratch project ID ${scratchId} as ${savedProject.id}`; res.send({ message, newProjectId: savedProject.id }); } catch (error) { console.log('Error adding project', error); res.sendStatus(500); } }); router.post('/copy-challenge', async (req, res) => { try { const { existingChallengeId, title, difficulty, description, } = req.body; if (!existingChallengeId) throw new Error('No project id'); console.log('Adding a scratch project'); const projectResult = await pool.query(projectQueries.select(existingChallengeId)); const scratchProject = { title, difficulty, description, details: projectResult.rows[0].details, isChallenge: true, }; const results = await pool.query(projectQueries.insert(scratchProject)); const savedProject = results.rows[0]; const message = `Added copy of project ID ${existingChallengeId} as ${savedProject.id}`; res.send({ message, newProjectId: savedProject.id }); } catch (error) { console.log('Error adding project', error); res.sendStatus(500); } }); router.post('/new-player-project', async (req, res) => { try { const { challengeId } = req.body; if (!challengeId) throw new Error('No project id'); console.log('Adding a scratch project'); const projectResult = await pool.query(projectQueries.select(challengeId)); const projectDetails = projectResult && projectResult.rows && projectResult.rows[0] && projectResult.rows[0].details; const newProject = { challengeId, details: projectDetails }; const results = await pool.query(projectQueries.insert(newProject)); const savedProject = results.rows[0]; res.send({ ...savedProject, challengeId }); } catch (error) { console.log('Error adding project', error); res.sendStatus(500); } }); const saveProject = async ({ req, res, projectId, botSecretKey, }) => { if (!projectId) throw new Error('Missing a projectId'); // const baseGame = await pool.query(projectQueries.select(baseGameId)); const details = req.body; // TODO: Protect projects with some type of hash // TODO: Validate projects and return feedback to user const results = await pool.query(projectQueries.update({ details, projectId, botSecretKey })); if (results.rows.length > 0) { res.send({ status: 'ok', 'content-length': 24845, 'content-name': '292793519', 'autosave-internal': '120', 'result-code': 0, }); } else { res.sendStatus(400); } }; router.put('/', async (req, res) => { try { await saveProject({ req, res, projectId: req.query.player1, botSecretKey: req.query.botSecretKey, }); } catch (error) { console.log(error); res.sendStatus(500); } }); router.use('/', (req, res) => { console.log('Unhandled project request'); res.sendStatus(500); }); module.exports = router;
// Written by Liling Yuan, Spring 2019 // B+ Tree implementation $(document).ready(function() { "use strict"; function newTree(jsav, maximum, detail){ return new tree(jsav, maximum, detail); } function tree(jsav, maximum, d){ this.emptyArray = []; for(var i = 0; i < maximum; i++){ this.emptyArray.push(""); } this.detail = d; this.jsav = jsav; this.list = []; //store array with different level inside this.level = 1; this.max = maximum; this.root = BPTreeNode.newNode(this.emptyArray, jsav, maximum, true, this.detail); //root will be stored as a BPTreeNode this.root.center(); this.leafValue = []; //stored BPTreeNode for the leaf Node this.leafValue[0] = this.root; this.list[0] = this.leafValue; this.update = -1; this.updateInfo = ""; this.checkUpdateMergeLeaf = false; this.edge = []; this.canvas = $(this.root.array.element).parent();//get canvas width this.w = $(this.canvas).innerWidth(); this.aw = $(this.root.array.element).outerWidth() / 2; //half of the outerWidth } var BPTreeproto = tree.prototype; //following function is for graphing BPTreeproto.printTree = function(){ this.printNode(); this.printArrow(this.aw, this.ah); } BPTreeproto.hideEdge = function(){ for(var i = this.edge.length - 1; i >= 0; i--){ this.edge[i].hide(); this.edge.pop(); } } BPTreeproto.printNode = function(){ //hide edge and redraw this.hideEdge(); var nvg = 80; //node vertical gap //graph leaf nodes var leafNodeSize = this.leafValue.length; var nhgl = this.w / (leafNodeSize + 1); var trackLeafIndex = 0; while(trackLeafIndex < this.leafValue.length){ var hori = (trackLeafIndex + 1) * nhgl - this.aw; var vert = (this.list.length - 1) * nvg; this.leafValue[trackLeafIndex].move(hori, vert); trackLeafIndex++; } //graph parent nodes var tl = 1; //track list index while(tl < this.list.length){ var tli = 0; //track list info index while(tli < this.list[tl].length){ this.list[tl][tli].array.element.addClass("internal-node"); var cs = this.list[tl][tli].size_child; //size of children //front edge var fe = $(this.list[tl][tli].child[0].array.element).position().left; //back edge var be = $(this.list[tl][tli].child[cs - 1].array.element).position().left; var hori = (fe + be) / 2; var vert = (this.list.length - tl - 1) * nvg; this.list[tl][tli].move(hori, vert); tli++; } tl++; } } //hw is the half of the width that the block has //vw is the height that the block has BPTreeproto.printArrow = function(hw){ var vw = $(this.root.array.element).outerHeight(); //height var oblock = (hw * 2) / this.max; //the width of one block in one node var tli = this.list.length - 1; //list index, starting from the root while(tli > 0){ var tci = 0; //track children's index while(tci < this.list[tli].length){ var x = $(this.list[tli][tci].array.element).position().left; var y = $(this.list[tli][tci].array.element).position().top; for(var i = 0; i < this.list[tli][tci].size_child; i++){ var x2 = $(this.list[tli][tci].child[i].array.element).position().left + hw; var y2 = $(this.list[tli][tci].child[i].array.element).position().top; var x1 = x + i * oblock; var y1 = y + vw; var a = this.jsav.g.line(x1, y1, x2, y2, { "stroke-width": 1.0}); this.edge.push(a); } tci++; } tli--; } } //Following functions are helper functions for add and delete /** * split the current TreeNode Return the new TreeNode * * @param rt the current TreeNode that will be split * @param addInfo the new value that will be added in * @return the new TreeNode that will be created */ BPTreeproto.split = function(rt, addInfo, information){ var leftSize = Math.trunc((this.max + 1) / 2); var addPos = rt.findHelp(addInfo,0, this.max - 1); var next = BPTreeNode.newNode(this.emptyArray, this.jsav, this.max, true, this.detail); if(this.detail){ this.printTree(); //hide all arrow this.hideEdge(); var nvg = 80; //node vertical gap var leafNodeSize = this.leafValue.length; var nhgl = this.w / (leafNodeSize + 2); var trackLeafIndex = 0; var vert = (this.list.length - 1) * nvg; while(trackLeafIndex < this.leafValue.length){ var hori = (trackLeafIndex + 1) * nhgl - this.aw; this.leafValue[trackLeafIndex].move(hori, vert); if(this.leafValue[trackLeafIndex] == rt){ break; } trackLeafIndex++; } trackLeafIndex++; next.move($(rt.array.element).position().left + nhgl, vert); while(trackLeafIndex < this.leafValue.length){ var hori = (trackLeafIndex + 2) * nhgl - this.aw; this.leafValue[trackLeafIndex].move(hori, vert); trackLeafIndex++; } (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + "): " + "Since the leaf node is full, it must be split. Add a new empty node to the right."); (this.jsav).step(); } //add new value to the left TreeNode if(addPos < leftSize){ for(var i = leftSize - 1; i < this.max; i++){ next.insert(rt.getValue()[i], rt.info[i]); } for(var i = this.max - 1; i >= leftSize - 1; i--){ rt.delete(rt.getValue()[i]); } if(this.detail){ next.addInfoGraph(); (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + "): " + "Because the value " + addInfo + " is smaller than " + leftSize + " (which is the min value in this node), move the rest of the key-value pair to the new node to make sure the current node is not overfull after adding key-value pair (" + addInfo + ", " + information + ")."); (this.jsav).step(); } rt.insert(addInfo, information); if(this.detail){ rt.addInfoGraph(); (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + ")."); } } //add new value to the next TreeNode else { for (var i = leftSize; i < this.max; i++) { next.insert(rt.getValue()[i], rt.info[i]); } for(var i = this.max - 1; i >= leftSize; i--){ rt.delete(rt.getValue()[i]); } if(this.detail){ next.addInfoGraph(); (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + "): " + "Because the value " + addInfo + " is greater than or equal to " + leftSize + " (which is the min value in this full node), move the rightmost key-value pair to the new node."); (this.jsav).step(); } next.insert(addInfo, information); } if(this.detail){ next.addInfoGraph(); (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + ")."); (this.jsav).step(); } return next; } /** * add Children to the parent * * @param parent parent TreeNode * @param newChild new Child that will be added in the parent * @param split false when it does not need split, true when it does need * split * @param newParent when split is true, newParent is the TreeNode that created * to hold other part of the value of the parent, when split is * false, newParent is null */ BPTreeproto.addChildren = function(parent, newChild, split, newParent) { var pos = parent.insertChildrenPos(newChild); if (split) { var leftSize = Math.trunc((this.max + 1) / 2); if (pos > leftSize) { var j = 0; for (var i = leftSize + 1; i <= this.max; i++) { newParent.addChildrenInNodeIndex(j, parent.getChildren()[i]); parent.setChildren(i, null); j += 1; } for(var i = 0; i < j; i++){ parent.popChild(); } this.addChildren(newParent, newChild, false, null); } else { var j = 0; for (var i = leftSize; i <= this.max; i++) { newParent.addChildrenInNodeIndex(j, parent.getChildren()[i]); parent.setChildren(i, null); j += 1; } for(var i = 0; i < j; i++){ parent.popChild(); } this.addChildren(parent, newChild, false, null); } } else { for (var i = parent.getChildrenSize(); i > pos; i--) { parent.setChildren(i, parent.getChildren()[i - 1]); } parent.addChildrenInNodeIndex(pos, newChild); } } BPTreeproto.parentSplit = function(rt, lev) { var next = BPTreeNode.newNode(this.emptyArray, this.jsav, this.max, false, this.detail); if(this.detail){ this.printTree(); //hide all arrow this.hideEdge(); var nvg = 80; //node vertical gap var leafNodeSize = this.list[lev - 1].length; var nhgl = this.w / (leafNodeSize + 2); var trackLeafIndex = 0; var vert = $(rt.array.element).position().top; while(trackLeafIndex < leafNodeSize){ var hori = (trackLeafIndex + 1) * nhgl - this.aw; this.list[lev- 1][trackLeafIndex].move(hori, vert); if(this.list[lev - 1][trackLeafIndex] == rt){ break; } trackLeafIndex++; } trackLeafIndex++; next.move($(rt.array.element).position().left + nhgl, vert); while(trackLeafIndex < leafNodeSize){ var hori = (trackLeafIndex + 2) * nhgl - this.aw; this.list[lev - 1][trackLeafIndex].move(hori, vert); trackLeafIndex++; } rt.highlight(false); (this.jsav).umsg("The parent node is full, so it has to be split."); (this.jsav).step(); } var leftSize = Math.trunc((this.max + 1) / 2); var addPos = rt.findHelp(this.update, 0, this.max - 1); // deal with parentNode if (addPos < leftSize) { var updateBackUp = rt.getValue()[leftSize - 1]; var updateBackUpInfo = rt.info[leftSize - 1]; for (var i = leftSize; i < this.max; i++) { next.insert(rt.getValue()[i], rt.info[i]); } for(var i = this.max - 1; i >= leftSize; i--){ rt.delete(rt.getValue()[i]); } for (var i = leftSize - 1; i > addPos; i--) { rt.setValue(i, rt.getValue()[i - 1], rt.info[i - 1]); } rt.setValue(addPos, this.update, this.updateInfo); if(this.detail){ rt.highlight(false); (this.jsav).umsg("Update key-value pair (" + this.update + "," + this.updateInfo + "): " + "Move all key-value pairs after index " + leftSize + " (included) which is the min value in the node to the new parent node and change the newly updated key-value pair to (" + updateBackUp + "," + updateBackUpInfo + ")."); (this.jsav).step(); } this.update = updateBackUp; this.updateInfo = updateBackUpInfo; } else if (addPos > leftSize) { var updateBackUp = rt.getValue()[leftSize]; var updateBackUpInfo = rt.info[leftSize]; for (var i = leftSize + 1; i < this.max; i++) { next.insert(rt.getValue()[i], rt.info[i]); } next.insert(this.update, this.updateInfo); for(var i = this.max - 1; i >= leftSize; i--){ rt.delete(rt.getValue()[i]); } if(this.detail){ (this.jsav).umsg("Update key-value pair (" + this.update + "," + this.updateInfo + "): " + "Move all key-values pair after index " + leftSize + " (but not included), which is the min value in this node, to the new parent node and change the newly updated key-value pair to (" + updateBackUp + "," + updateBackUpInfo + ")."); (this.jsav).step(); } this.update = updateBackUp; this.updateInfo = updateBackUpInfo; } else { for (var i = leftSize; i < this.max; i++) { next.insert(rt.getValue()[i], rt.info[i]); } for(var i = this.max - 1; i >= leftSize; i--){ rt.delete(rt.getValue()[i]); } if(this.detail){ (this.jsav).umsg("Update key-value pair (" + this.update + "," + this.updateInfo + "): " + "Move all key-value pairs after index " + leftSize + " (included), which is the min value in the node, to the new parent node and keep the update key-value pair as (" + this.update + "," + this.updateInfo + ")."); (this.jsav).step(); } } return next; } /** * add TreeNode into the linkedList: outside insert (Leaf) * * @param obj the TreeNode that will be added in the Data Structure */ BPTreeproto.insertTreeNode = function(listt, obj) { var pos = 0; var b = obj.getValue()[obj.size() - 1]; var curr = listt[pos]; while (pos < listt.length - 1) { if (b <= curr.getValue()[0]) { break; } else { pos++; curr = listt[pos]; } } if (b > curr.getValue()[0]) { pos++; } listt.splice(pos, 0, obj); return listt; } /** * delete help method which check if this b plus tree has value of delInfo * * @param rt root * @param delInfo info that we are looking for * @return true if it contains, otherwise, return false */ BPTreeproto.find = function(rt, delInfo) { if (rt.isLeaf()) { for (var i = 0; i < rt.size(); i++) { if (rt.getValue()[i] == delInfo) { return true; } } return false; } else { var pos = rt.findHelp(delInfo, 0, rt.size() - 1); return this.find(rt.getChildren()[pos], delInfo); } } //search will be the datastructure BPTreeproto.getPosInList = function(search, node) { for (var i = 0; i < search.length; i++) { if (search[i] == node) { return i; } } return -1; } //rt will be the treeNode BPTreeproto.mergeLeaf = function(rt) { if (rt.size() < this.max / 2) { // need borrow or merge this.checkUpdateMergeLeaf = true; var index = this.getPosInList(this.leafValue, rt); // Borrow from Left if (index != 0 && (this.leafValue[index - 1].size() - 1) >= this.max / 2) { if(this.detail){ (this.jsav).umsg("The size of the current node is less than the half of the capacity for a node. However, its left sibling has enough records to give one key-value pair to the current node."); (this.jsav).step(); } var biggestPos = this.leafValue[index - 1].size() - 1; var biggest = this.leafValue[index - 1].getValue()[biggestPos]; var biggestInfo = this.leafValue[index - 1].info[biggestPos]; this.leafValue[index - 1].delete(biggest); rt.insert(biggest,biggestInfo); rt.array.value(0, rt.value[0] + "<br><div class='leaf-node-value'>" + rt.info[0] + "</div>"); rt.addInfoGraph(); if(this.detail){ (this.jsav).umsg("Borrow key-value pair (" + biggest + ", " + biggestInfo + ") from the current node's left sibling."); (this.jsav).step(); } } // Borrow from Right else if (index != this.leafValue.length - 1 && (this.leafValue[index + 1].size() - 1) >= (this.max / 2)) { if(this.detail){ (this.jsav).umsg("The current node holds less than half its capacity. However, its right sibling has enough records to give one key-value pair to the current node. (We cannot borrow from the left sibling, because after borrowing, the left sibling would not have enough records.)"); (this.jsav).step(); } var smallest = this.leafValue[index + 1].getValue()[0]; var smallestInfo = this.leafValue[index + 1].info[0]; this.leafValue[index + 1].delete(smallest); this.leafValue[index + 1].addInfoGraph(); rt.insert(smallest, smallestInfo); var len = rt.size_value; rt.array.value(len - 1, rt.value[len - 1] + "<br><div class='leaf-node-value'>" + rt.info[len - 1] + "</div>"); if(this.detail){ (this.jsav).umsg("Borrow key-value pair (" + smallest + ", " + smallestInfo + ") from the right sibling. Move it to the current node."); (this.jsav).step(); } if(this.detail){ rt.highlight(false); } this.leafValue[index + 1].addInfoGraph(); return this.leafValue[index + 1]; } // Merge to the Left - Deal with the Value else if (index != 0) { if(this.detail){ (this.jsav).umsg("The number of records in the current node is less than the half the capcity. However, we cannot borrow a key-value pair from either of the left or right sibling. So we need to merge the current node to the left sibling."); (this.jsav).step(); } var prev = this.leafValue[index - 1]; for (var i = 0; i < rt.size(); i++) { var del = rt.getValue()[i]; prev.insert(del, rt.info[i], false); } rt.clearValue(); prev.addInfoGraph(); if(this.detail){ (this.jsav).umsg("Move key-value pairs to the left sibling."); (this.jsav).step(); } } // Merge to the Right - Deal with the Value else { if(this.detail){ (this.jsav).umsg("The current node now holds less than the half of the node capacity. However, we cannot borrow a key-value pair from either of the left or right sibling nodes. We also cannot merge with the left sibling. So we need to merge with the right sibling."); (this.jsav).step(); } var next = this.leafValue[index + 1]; for (var i = 0; i < rt.size(); i++) { var del = rt.getValue()[i]; next.insert(del, rt.info[i]); } rt.clearValue(); next.addInfoGraph(); if(this.detail){ (this.jsav).umsg("Move key-value pairs to the right sibling."); (this.jsav).step(); } } } if(this.detail){ rt.highlight(false); } return rt; } BPTreeproto.getSmallest = function(rt) { while (rt.size_child > 0) { rt = rt.getChildren()[0]; } return rt.getValue()[0]; } BPTreeproto.getSmallestInfo = function(rt){ while (rt.size_child > 0) { rt = rt.getChildren()[0]; } return rt.info[0]; } BPTreeproto.updateParent = function(rt, info) { if (rt.isLeaf()) { return rt; } else { var pos = rt.findHelp(info, 0, rt.size() - 1); var next = this.updateParent(rt.getChildren()[pos], info); if (next != null && pos == 0) { return rt; } else if (next != null) { rt.setValue(pos - 1, next.getValue()[0], next.info[0]); } return null; } } BPTreeproto.mergeParent = function(rt, lev) { var parentValue = this.list[lev - 1]; //parentValue will be an array var index = this.getPosInList(parentValue, rt); // Borrow from Left if (index != 0 && parentValue[index - 1].size() != 1) { // deal with value var biggestPos = parentValue[index - 1].size() - 1; var biggest = parentValue[index - 1].getValue()[biggestPos]; parentValue[index - 1].delete(biggest); rt.clearValue(); rt.insert(this.getSmallest(rt.getChildren()[0]), this.getSmallestInfo(rt.getChildren()[0]), false); // deal with children var moveChild = parentValue[index - 1].getChildren()[biggestPos + 1]; parentValue[index - 1].popChild(); var lowerBound = rt.getChildrenSize(); for (var j = lowerBound; j > 0; j--) { rt.setChildren(j, rt.getChildren()[j - 1]); } rt.setChildren(0, moveChild); rt.size_child++; var node = moveChild; while (node.size_child > 0) { node = node.getChildren()[0]; } if(this.detail){ this.printTree(); rt.highlight(true); (this.jsav).umsg("After removing the empty node, the current node only has one child. Since the left sibling has more than 2 children, we will borrow one child from left sibling."); (this.jsav).step(); this.checkUpdateMergeLeaf = false; } return node; } // Borrow from Right else if (index != parentValue.length - 1 && parentValue[index + 1].size() != 1) { // deal with value var smallest = parentValue[index + 1].getValue()[0]; parentValue[index + 1].delete(smallest); rt.clearValue(); // deal with children rt.addChildrenInNodeIndex(1, parentValue[index + 1].getChildren()[0]); var upperBound = parentValue[index + 1].getChildrenSize() - 1; for (var j = 0; j < upperBound; j++) { parentValue[index + 1].setChildren(j, parentValue[index + 1].getChildren()[j + 1]); } parentValue[index + 1].popChild(); rt.insert(this.getSmallest(rt.getChildren()[1]), this.getSmallestInfo(rt.getChildren()[1]), false); var node = parentValue[index + 1]; while (node.size_child > 0) { node = node.getChildren()[0]; } this.updateParent(node, node.getValue()[0]); if(this.detail){ this.printTree(); rt.highlight(true); (this.jsav).umsg("After removing the empty node, the current node only has one child. Since the left sibling only has 2 children, and the right sibling has more than 2 children, we will borrow one child from right sibling."); (this.jsav).step(); this.checkUpdateMergeLeaf = false; } return null; } // Merge to the Left - Deal with the Value else if (index != 0) { var prev = parentValue[index - 1]; // deal with value rt.clearValue(); prev.insert(this.getSmallest(rt.getChildren()[0]), this.getSmallestInfo(rt.getChildren()[0]), false); if(this.detail){ this.printTree(); rt.highlight(true); (this.jsav).umsg("After removing the empty node, the current node only has one child. Since both left and right siblings only have 2 children, we will merge the current node with the left sibling."); (this.jsav).step(); this.checkUpdateMergeLeaf = false; } // deal with children prev.addChildrenInNodeIndex(prev.getChildrenSize(), rt.getChildren()[0]); rt.clearChildren(); return rt; } // Merge to the Right - Deal with the Value else { // deal with value rt.clearValue(); var neededInfo = this.getSmallestInfo(parentValue[index + 1].getChildren()[0]); parentValue[index + 1].insert(this.getSmallest(parentValue[index + 1].getChildren()[0]), neededInfo, false); // deal with children if(this.detail){ this.printTree(); rt.highlight(true); (this.jsav).umsg("After removing the empty node, the current node only has one child. Since there is no left sibling, and theright sibling only has 2 children, we will merge the current node with the right sibling."); (this.jsav).step(); this.checkUpdateMergeLeaf = false; } var oriSize = parentValue[index + 1].getChildrenSize(); for (var j = oriSize; j > 0; j--) { parentValue[index + 1].setChildren(j, parentValue[index + 1].getChildren()[j - 1]); } parentValue[index + 1].setChildren(0, rt.getChildren()[0]); parentValue[index + 1].size_child++; rt.clearChildren(); return rt; } } BPTreeproto.remove = function(rt, delInfo, lev) { if (rt.isLeaf()) { // leaf node if(this.detail){ rt.unhighlight(this.list[lev]); rt.highlight(true); (this.jsav).umsg("We have found the correct leaf node. Now delete " + delInfo); (this.jsav).step(); } if(this.level > 1){ rt.delete(delInfo); }else{ rt.delete(delInfo, true); } rt.addInfoGraph(); return this.mergeLeaf(rt); } else { // parent node var pos = rt.findHelp(delInfo, 0, rt.size() - 1); if(this.detail){ if(rt != this.root){ rt.unhighlight(this.list[lev]); if(pos == 0){ (this.jsav).umsg("Delete " + delInfo + ": Because " + delInfo + " is less than " + rt.value[0] + ", follow the leftmost pointer."); }else if(pos == rt.size_value){ (this.jsav).umsg("Delete " + delInfo + ": Because " + delInfo + " is bigger or equal than " + rt.value[rt.size_value - 1] + ", go to the most right child node."); }else{ (this.jsav).umsg("Delete " + delInfo + ": Because " + delInfo + " is greater than or equal to " + rt.value[pos - 1] + " and " + delInfo + " is less than " + rt.value[pos] + ", follow the middle pointer."); } }else { if(pos == 0){ (this.jsav).umsg("Delete " + delInfo + ": First look at the root node. Because " + delInfo + " is less than " + rt.value[0] + ", follow the leftmost pointer."); }else if(pos == rt.size_value){ (this.jsav).umsg("Delete " + delInfo + ": First look at the root node. Because " + delInfo + " is greater than or equal to " + rt.value[rt.size_value - 1] + ", follow the rightmost pointer."); }else{ (this.jsav).umsg("Delete " + delInfo + ": First look at the root node. Because " + delInfo + " is greater than or equal to " + rt.value[pos - 1] + " and " + delInfo + " is less than " + rt.value[pos] + ", go to the child node between " + rt.value[pos - 1] + " and " + rt.value[pos]); } } rt.highlight(true); (this.jsav).step(); } if(lev > 2 && this.detail){ var tempuse = []; for(var k = 0; k < rt.size_value; k++){ tempuse[k] = rt.value[k]; } } var change = this.remove(rt.getChildren()[pos], delInfo, lev - 1); // changed child if(this.detail){ rt.unhighlight(this.list[lev - 2]); } if (change != null) { var mergeNode = change; if (change.size() == 0) { // update parent rt after merging change.hide(); var i = this.getPosInList(this.list[lev - 2], change); if (pos == 0) { mergeNode = this.list[lev - 2][i + 1]; while (mergeNode.size_child > 0) { mergeNode = mergeNode.getChildren()[0]; } } this.list[lev - 2].splice(i, 1); // remove from the list var upperBound = rt.getChildrenSize(); for (var j = pos; j < upperBound - 1; j++) { rt.setChildren(j, rt.getChildren()[j + 1]); } rt.popChild(); rt.clearValue(); for (var j = 1; j < upperBound - 1; j++) { rt.insert(this.getSmallest(rt.getChildren()[j]), this.getSmallestInfo(rt.getChildren()[j]), false); } if(this.detail && lev > 2 && !rt.checkSame(tempuse)){ this.printTree(); rt.highlight(true); (this.jsav).umsg("Update internal node."); (this.jsav).step(); } if(this.detail && this.checkUpdateMergeLeaf && rt.size_child != 1){ this.printTree(); rt.highlight(true); (this.jsav).umsg("Remove the empty node and update the parent node"); (this.jsav).step(); this.checkUpdateMergeLeaf = false; } } else {// borrow from the right if (pos + 1 < rt.getChildrenSize() && rt.getChildren()[pos + 1] == change) { pos++; } if(this.detail && this.checkUpdateMergeLeaf){ this.printTree(); rt.highlight(true); (this.jsav).umsg("Update the parent node."); (this.jsav).step(); this.checkUpdateMergeLeaf = false; } } if (rt == this.root && rt.getChildrenSize() == 1) { rt.hide(); this.root = rt.getChildren()[0]; this.list.pop(); this.level--; if(this.detail){ (this.jsav).umsg("Since the root node is empty and only has one child, remove the root node, and set the only child to be the new root."); } return this.root; } else if (rt.getChildrenSize() == 1) { // need borrow and merge return this.mergeParent(rt, lev); } else if (change.size() == 0) { if (change != mergeNode) { if(this.detail && rt == this.root){ rt.highlight(false); } return mergeNode; } } else if (pos != 0 && !rt.isLeaf() && rt.child[0].isLeaf()) { rt.setValue(pos - 1, rt.child[pos].value[0], rt.child[pos].info[0]); if(pos - 2 >= 0) { rt.setValue(pos - 2, rt.child[pos - 1].value[0], rt.child[pos - 1].info[0]); } }else if(pos != 0){ rt.setValue(pos - 1, change.getValue()[0], change.info[0]); } else { if(this.detail && lev > 2 && !rt.checkSame(tempuse)){ rt.highlight(true); (this.jsav).umsg("Update internal node."); (this.jsav).step(); } if(this.detail && rt == this.root){ rt.highlight(false); } return change; } }else if(rt.size_child > pos + 1){ var small = this.getSmallest(rt.getChildren()[pos + 1]); var smallestInfo = this.getSmallestInfo(rt.getChildren()[pos + 1]); if(this.detail){ var temp = rt.value[pos]; if(temp != small){ rt.highlight(true); (this.jsav).umsg("Update Internal node"); } } rt.setValue(pos, small, smallestInfo); } if(this.detail && lev > 2 && !rt.checkSame(tempuse)){ rt.highlight(true); (this.jsav).umsg("Update internal node."); (this.jsav).step(); } if(this.detail && rt == this.root){ rt.highlight(false); } return null; } } /** * insert into the B+ Tree * * @param rt parent Node * @param addInfo new Info that will be added in * @param detail true which will display the each step in the visualization * @return current TreeNode */ BPTreeproto.insert = function(rt, addInfo, lev, information) { if (rt.isLeaf()) { if(this.level > 1){ rt.unhighlight(this.list[1]); } if(this.detail && this.level != 1){ rt.highlight(true); (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + "): We have found the correct leaf node."); (this.jsav).step(); } var checkAdd = rt.insert(addInfo, information); if (checkAdd) { this.update = -1; this.updateInfo = ""; //add key rt.addInfoGraph(); if(this.detail){ rt.highlight(false); (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + ")"); (this.jsav).step(); } return rt; } else { // split if(this.detail && this.level != 1){ rt.highlight(false); } var next = this.split(rt, addInfo, information); //add key rt.addInfoGraph(); next.addInfoGraph(); this.leafValue = this.insertTreeNode(this.leafValue, next);// add in the single linked list this.update = next.getValue()[0]; this.updateInfo = next.info[0];//information if (rt == this.root) { var parent = BPTreeNode.newNode(this.emptyArray, this.jsav, this.max, false, this.detail); // add new parent node var temp = this.update; var tempInfo = this.updateInfo; parent.insert(this.update, this.updateInfo); parent.addChildrenInNode(rt); parent.addChildrenInNode(next); this.root = parent; this.update = -1; this.updateInfo = ""; this.level++; var newList = []; newList[0] = parent; this.list[this.level - 1] = newList; if(this.detail){ parent.setValue(0, "", ""); this.printNode(); (this.jsav).umsg("A new internal node is created. This is going to become the new root node."); (this.jsav).step(); parent.setValue(0, temp, tempInfo); this.printNode(); this.printArrow(this.aw); (this.jsav).umsg("Set the key of the internal node and links to the leaf node."); (this.jsav).step(); } return parent; } return next; } } //internal node else { if(this.level > lev){ rt.unhighlight(this.list[lev]); } var pos = rt.findHelp(addInfo, 0, rt.size() - 1); if(this.detail){ rt.highlight(true); if(rt == this.root){ if(pos == 0){ (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + "): First look at the root node. Because " + addInfo + " is less than " + rt.value[0] + ", follow the leftmost pointer."); }else if(pos == rt.size_value){ (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + "): First look at the root node. Because " + addInfo + " is greater than or equal to " + rt.value[rt.size_value - 1] + ", follow the rightmost pointer."); }else{ (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + "): First look at the root node. Because " + addInfo + " is greater than or equal to " + rt.value[pos - 1] + " and " + addInfo + " is less than " + rt.value[pos] + ", follow the pointer between " + rt.value[pos - 1] + " and " + rt.value[pos]); } }else{ if(pos == 0){ (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + "): Because " + addInfo + " is less than " + rt.value[0] + ", follow the leftmost pointer."); }else if(pos == rt.size_value){ (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + "): Because " + addInfo + " is greater than or equal to " + rt.value[rt.size_value - 1] + ", follow the rightmost pointer."); }else{ (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + "): Because " + addInfo + " is greater than or equal to" + rt.value[pos - 1] + " and is less than " + rt.value[pos] + ", follow the pointer between " + rt.value[pos - 1] + " and " + rt.value[pos]); } } (this.jsav).step(); } var next = this.insert(rt.getChildren()[pos], addInfo, lev - 1, information); // new child //if create another node if (next != rt.getChildren()[pos]) { if(this.detail){ rt.highlight(true); (this.jsav).umsg("The lowest value in the new node created gets promoted: Update current parent node (insert the updated key-value pair (" + this.update + "," + this.updateInfo + "))"); (this.jsav).step(); } var checkAdd = rt.insert(this.update, this.updateInfo); if (checkAdd) { this.addChildren(rt, next, false, null); this.update = -1; this.updateInfo = ""; if(this.detail){ rt.highlight(false); this.printTree(); (this.jsav).umsg("Link the leaf node being updated"); (this.jsav).step(); } return rt; } else { // split var nextNode = this.parentSplit(rt, lev); // parallel with rt this.list[lev - 1] = this.insertTreeNode(this.list[lev - 1], nextNode); // change children this.addChildren(rt, next, true, nextNode); if (rt == this.root) { var parent = BPTreeNode.newNode(this.emptyArray, this.jsav, this.max, false, this.detail); // add new parent node parent.insert(this.update, this.updateInfo); parent.addChildrenInNode(rt); parent.addChildrenInNodeIndex(1, nextNode); this.root = parent; this.update = -1; this.updateInfo = ""; this.level++; var newList = []; newList[0] = parent; this.list[this.level - 1] = newList; if(this.detail){ this.printNode(); (this.jsav).umsg("A new internal node is created. This is going to become the new root node."); (this.jsav).step(); this.printArrow(this.aw); (this.jsav).umsg("Link all the nodes"); (this.jsav).step(); } return parent; } return nextNode; } } return rt; } } BPTreeproto.addWithoutGraphic = function(addInfo, information) { var node = this.insert(this.root, addInfo, this.level, information); } BPTreeproto.findDetail = function(rt, findInfo, last){ if(rt.isLeaf()){ last.highlight(false); rt.highlight(true); (this.jsav).umsg("We have found the correct leaf node."); (this.jsav).step(); }else{ if(rt == this.root){ rt.unhighlight(this.list[0]); } var pos = rt.findHelp(findInfo, 0, rt.size() - 1); rt.highlight(true); if(pos == 0){ (this.jsav).umsg("Find " + findInfo + ": Because " + findInfo + " is less than " + rt.value[0] + ", follow the leftmost pointer."); }else if(pos == rt.size_value){ (this.jsav).umsg("Find " + findInfo + ": Because " + findInfo + " is greater than or equal to " + rt.value[rt.size_value - 1] + ", follow the rightmost pointer."); }else{ (this.jsav).umsg("Find " + findInfo + ": Because " + findInfo + " is greater than or equal to " + rt.value[pos - 1] + " and is less than " + rt.value[pos] + ", follow the pointer between " + rt.value[pos - 1] + " and " + rt.value[pos]); } (this.jsav).step(); if(rt != this.root){ last.highlight(false); } this.findDetail(rt.getChildren()[pos], findInfo, rt); } } //following two functions are for ADD and DELETE in the B+Tree BPTreeproto.add = function(addInfo, information, detail) { var node = this.insert(this.root, addInfo, this.level, information); if(!this.detail){ this.printTree(); (this.jsav).umsg("Insert key-value pair (" + addInfo + ", " + information + ")."); (this.jsav).step(); } } BPTreeproto.delete = function(delInfo) { if (this.find(this.root, delInfo)) { if (this.leafValue.length > 1) { if(this.detail){ (this.jsav).umsg("Delete " + delInfo + ": First we need to find the leaf node with matching key."); (this.jsav).step(); } this.remove(this.root, delInfo, this.level); this.printTree(); } else { this.root.delete(delInfo, true); } } else { alert ("Element " + delInfo + " is not found!"); } if(!this.detail){ (this.jsav).umsg("Delete " + delInfo + "."); (this.jsav).step(); } } // Publicize the public functions var BPTree = {}; BPTree.newTree = newTree; window.BPTree = BPTree; });
import React from 'react' import { storiesOf } from '@storybook/react' import HeaderParagraph from './HeaderParagraph' storiesOf('Molecules/HeaderParagraph', module) .add('ResetPassword', () => <HeaderParagraph title="Reset Password">To change the caller's password, first confirm their identity by asking the security questions on this page. If they answer correctly, click the "Reset Password" link on this page to send an...</HeaderParagraph>) .add('ForgotPassword', () => <HeaderParagraph title="Forgotten Password">If the caller has forgotten their password, first confirm their identity by asking the security....</HeaderParagraph>)
import React, { useState, useEffect } from 'react'; const ProductDetails = (props) => { const [prodDetails, setProdDetails] = useState([]); useEffect(() => { // Get Product details const getProdDetails = async () => { const response = await fetch(`http://localhost:3000/productDetails/` + props.match.params.prodId); const data = await response.json(); setProdDetails(data); }; getProdDetails(); }, []); const productDetails = () => { return ( <div> <table class="table table-striped"> <tbody> <tr> <td>Product Id : </td> <td>{prodDetails.id}</td> </tr> <tr> <td>Product Name : </td> <td>{prodDetails.name}</td> </tr> <tr> <td>Product Description : </td> <td>{prodDetails.description}</td> </tr> <tr> <td>Product Category Id : </td> <td>{prodDetails.categoryId}</td> </tr> </tbody> </table> </div> ) } return ( <div> {productDetails()} </div> ) } export default ProductDetails;
import React from "react"; const ListItem = props => { return( <li> {props.item} <button className="action" onClick={ () => {props.handleRemove(props.itemIndex)} }> x </button> </li> ); }; export default ListItem;
import React,{Component,Fragment,createRef,createContext} from 'react'; import $ from 'jquery' import './index.css'; const dpContext = createContext(); class RDropdownButton extends Component { constructor(props){ super(props); this.state = {open:this.props.open || false,searchValue:''} this.dom = createRef(); this.touch = 'ontouchstart' in document.documentElement; } toggle(state = !this.state.open,isBackdrop){ clearTimeout(this.timeOut); this.timeOut = setTimeout(()=>{ if(state === this.state.open){return} this.setState({open:state,searchValue:''}); if(state){ $('body').addClass('rdb-open'); } else{ $('body').removeClass('rdb-open'); } var {onBackdropClick,onToggle} = this.props; if(onBackdropClick && isBackdrop){onBackdropClick(this.props)} if(onToggle){onToggle(state)} },100) } getValue(value){return typeof value === 'function' ? value(this.props):value;} click(e){ if($(e.target).parents('.rdb-checkeds').length !== 0){return;} var {items,onClick = ()=>{}} = this.props; if(items){this.toggle(true);} else{onClick(this.props);} } showPopup(){ var {items} = this.props; var {open} = this.state; if(!open){return false;} if(items !== undefined){return true;} return false } getIcon(icon,iconClass,iconStyle){ if(icon){return <div className={'rdb-icon'} style={this.getValue(iconStyle)}>{this.getValue(icon)}</div>} if(iconClass){ return ( <div className={'rdb-icon ' + this.getValue(iconClass)} style={this.getValue(iconStyle)}></div> ) } return null; } getBadge(badge){ if(badge === undefined){return null;} var badge = parseInt(this.getValue(this.props.badge)); if(isNaN(badge)){console.error('RDropdownButton => badge props is not an number'); return null;} if(badge < 1){return null;} if(badge > 99){badge = '+99';} var badgeStyle = this.getValue(this.props.badgeStyle); return <div className='rdb-badge' style={badgeStyle}>{badge}</div> } getText(text,icon){ if(text === undefined || text === ''){return ''} if(icon === null){return text;} var {gap = 6} = this.props; return ( <Fragment> <div className='rdb-gap' style={{width:gap}}></div> {text} </Fragment> ) } getHoverEnabled(){ if(this.touch){return false} return this.getValue(this.props.hover); } itemClick(index,e){ if($(e.target).parents('.rdb-list-item-after').length !== 0){return;} var item = this.items[index]; var {onClick,checkField} = this.props; var disabled = this.getValue(item.disabled); if(disabled){return;} var checked = this.getValue(item[checkField]) if(item.onClick){item.onClick(item,index,this.context);} else if(onClick){onClick(item,index,this.context);} if(item.close !== false && checked === undefined ){this.toggle();} } getCaret(){ var {items,caret} = this.props; if(!items || !caret){return '';} if(caret === true){ return <Fragment><div style={{flex:1}}></div><div className='rdb-caret default'></div></Fragment>; } if(typeof caret === 'string'){return <div className={caret}></div>} return caret; } render(){ var id = this.getValue(this.props.id); var disabled = this.getValue(this.props.disabled); var title = this.getValue(this.props.title); var className = this.getValue(this.props.className); var rtl = this.getValue(this.props.rtl); var style = this.getValue(this.props.style); var icon = this.getValue(this.props.icon); var text = this.getValue(this.props.text); var Icon = this.getIcon(icon,this.props.iconClass,this.props.iconStyle); var Text = this.getText(text,Icon); var hover = this.getHoverEnabled(); var badge = this.getValue(this.props.badge); var after = this.getValue(this.props.after); var After = after?<div className='rdb-after'>{after}</div>:''; var {items,type,onClick=()=>{},checkField,caret} = this.props; var {searchValue} = this.state; var content = typeof items === 'function'?items(this.context):items; var checks = []; var Items; if(!Array.isArray(content)){Items = content;} else{ let filteredItems = content.filter((item)=>{ if(item[checkField]){checks.push(item)} if(!searchValue){return true;} if(item.text === undefined){return true;} return item.text.indexOf(searchValue) !== -1 }); this.items = filteredItems; Items = filteredItems.map((item, i)=>{ if(item.html){ return <Fragment key={i}>{this.getValue(item.html)}</Fragment>; } return <ListItem key={i} item={item} index={i}/> }) } var contextValue = {...this.props,items:Items,getIcon:this.getIcon.bind(this),getText:this.getText.bind(this)}; contextValue.toggle = this.toggle.bind(this); contextValue.SetState = (obj)=>this.setState(obj); contextValue.getValue = this.getValue.bind(this); contextValue.itemClick = this.itemClick.bind(this); contextValue.hover = hover var props = { id, className:`r-dropdown-button ${rtl?'rtl':'ltr'}${className?' ' + className:''}`, style:$.extend({},{direction:rtl?'rtl':'ltr'},this.getValue(style)), disabled,title, ref:this.dom, onClick:this.click.bind(this), onMouseEnter:hover?()=>this.toggle(true):undefined, onMouseLeave:hover?()=>this.toggle(false):undefined, tabIndex:0 } var Caret = this.getCaret(); var Badge = this.getBadge(badge); return ( <dpContext.Provider value={contextValue}> { type === 'multiselect' && <div className='rdb-multiselect' style={{width:props.style.width}}> <button {...props}>{Icon} {Text} {Caret} {after} {Badge}</button> { checks.length !== 0 && <div className={'rdb-checkeds' + (rtl?' rtl':'')}> { checks.map((check)=>{return ( <div className='rdb-checked' onClick={()=>onClick(check)}> <div className='rdb-checked-close'></div> <div className='rdb-checked-text'>{check.text}</div> </div> )})} </div> } </div> } {type !== 'multiselect' && <button {...props}>{Icon} {Text} {Caret} {after}{Badge}</button>} {this.showPopup() && <Popup ref={this.popup}/>} </dpContext.Provider> ); } } RDropdownButton.defaultProps = {checkField:'checked'} class Popup extends Component{ static contextType = dpContext; constructor(props){ super(props); this.dom = createRef(); this.activeIndex = false; } getLimit(dom){ var offset = dom.offset(); var left = offset.left - window.pageXOffset; var top = offset.top - window.pageYOffset; var width = dom.outerWidth(); var height = dom.outerHeight(); var right = left + width; var bottom = top + height; return {left,top,right,bottom,width,height}; } update(){ var {rtl,openRelatedTo,animate,dropdownType,type} = this.context; var popup = $(this.dom.current); var button = type === 'multiselect'?popup.prev().find('.r-dropdown-button'):popup.prev(); var parent = openRelatedTo?popup.parents(openRelatedTo):undefined; parent = Array.isArray(parent) && parent.length === 0?undefined:parent; var bodyWidth = window.innerWidth; var bodyHeight = window.innerHeight; var parentLimit = parent?this.getLimit(parent):{left:0,top:0,right:bodyWidth,bottom:bodyHeight}; if(parentLimit.left < 0){parentLimit.left = 0;} if(parentLimit.right > bodyWidth){parentLimit.right = bodyWidth;} if(parentLimit.top < 0){parentLimit.top = 0;} if(parentLimit.bottom > bodyHeight){parentLimit.bottom = bodyHeight;} var buttonLimit = this.getLimit(button); var popupLimit = this.getLimit(popup); var left,right,top,bottom,style = {}; top = buttonLimit.bottom; bottom = top + popupLimit.height; if(dropdownType === 'fit'){ style.left = buttonLimit.left; style.width = buttonLimit.width; } else if(dropdownType === 'center'){ } else if(rtl){ right = buttonLimit.right; left = right - popupLimit.width; if(left < parentLimit.left){style.left = parentLimit.left;} else{style.left = left;} } else{ left = buttonLimit.left; right = left + popupLimit.width; if(right > parentLimit.right){style.left = parentLimit.right - popupLimit.width;} else{style.left = left} } if(dropdownType === 'center'){ } else if(bottom > parentLimit.bottom){ if(popupLimit.height > buttonLimit.top - parentLimit.top){style.top = parentLimit.bottom - popupLimit.height;} else{style.top = buttonLimit.top - popupLimit.height;} } else{ style.top = buttonLimit.bottom; } if(animate){ popup.css({...style,opacity:0,top:style.top + 60}) popup.animate({top:style.top,opacity:1},{duration:150}) } else{ popup.css(style) } popup.focus(); $('body').addClass('rdb-open'); } componentDidMount(){ this.update(); } getStyle(){ var {rtl,dropdownType} = this.context; let style = { direction:rtl?'rtl':'ltr' } if(dropdownType === 'center'){ style.left = 0; style.top = 0; style.width = '100%'; style.height = '100%'; style.display = 'flex'; style.alignItems = 'center'; style.justifyContent = 'center'; } return style; } getBackDropStyle(){ var {backdropStyle} = this.context; return {height:'100%',width:'100%',right:0,top:0,position:'fixed',background:'rgba(0,0,0,0)',...backdropStyle} } keyDown(e){ console.log(e.keyCode); if(e.keyCode === 40){ e.preventDefault(); var items = $(this.dom.current).find('.rdb-list-item') var active = items.filter('.active'); if(active.length === 0){ this.activeIndex = 0; items.eq(0).addClass('active'); } else{ let index = active.attr('dataindex'); index++; if(index >= items.length){ index = 0; } items.removeClass('active'); this.activeIndex = index; items.eq(index).addClass('active').focus(); } } else if(e.keyCode === 38){ e.preventDefault(); var items = $(this.dom.current).find('.rdb-list-item') var active = items.filter('.active'); if(active.length === 0){ this.activeIndex = items.length - 1; items.eq(items.length - 1).addClass('active'); } else{ let index = active.attr('dataindex'); index--; if(index < 0){ index = items.length - 1; } items.removeClass('active'); this.activeIndex = index; items.eq(index).addClass('active').focus(); } } else if(e.keyCode === 13){ let {itemClick} = this.context; if(this.activeIndex !== false){ itemClick(this.activeIndex); } } else if(e.keyCode === 27){ let {toggle} = this.context; toggle(); } } render(){ var {search,items,toggle,getValue,rtl,hover,popupClassName,searchValue,SetState,placeHolder} = this.context; var popupStyle = getValue(this.context.popupStyle); return( <div className={"rdb-popup-container " + (popupClassName?' ' + popupClassName:'') + (rtl?' rtl':' ltr')} ref={this.dom} style={this.getStyle()} onMouseEnter={()=>{if(hover){toggle(true)}}} onMouseLeave={()=>{if(hover){toggle(false)}}} onKeyDown={this.keyDown.bind(this)} tabIndex={0}> {!hover && <div className='rdb-backdrop' onClick={()=>toggle(false,true)} style={this.getBackDropStyle()}></div>} <div className="rdb-popup" style={popupStyle}> { search && <div className='rdb-search'> <div className={'rdb-search-icon' + (searchValue?' rdb-search-icon-filled':'')} onClick={()=>{this.setState({searchValue:''})}}></div> <input type='text' value={searchValue} placeholder={placeHolder} onChange={(e)=>{ if(typeof search === 'function'){ search(e.target.value); return; } SetState({searchValue:e.target.value}) }} /> </div> } <div className='rdb-items'>{items}</div> </div> </div> ); } } class ListItem extends Component{ static contextType = dpContext; getText(text,icon){ if(text === undefined || text === ''){return ''} if(icon === null){return <div className='rdb-text' title={text}>{text}</div>;} var {gap = 6} = this.props; return ( <Fragment> <div className='rdb-gap' style={{width:gap}}></div> <div className='rdb-text' title={text}>{text}</div> </Fragment> ) } render(){ var {item,index} = this.props; var {getValue,getIcon,itemClick,gap = 8,rtl,checkField} = this.context; var disabled = getValue(item.disabled); var text = getValue(item.text); var checked = getValue(item[checkField]); var after = getValue(item.after); var After = after?<div className='rdb-list-item-after'>{after}</div>:''; this.checked = checked; var Icon = getIcon(item.icon,item.iconClass,item.iconStyle); var Text = this.getText(text,Icon); var CheckIcon = checked !== undefined?( <Fragment> <div className={'rdb-check-icon' + (checked?' checked':'')}></div> <div className='rdb-gap' style={{width:gap}}></div> </Fragment> ):null; var href = getValue(item.href); var className = getValue(item.className); var props = { className:`rdb-list-item${className?' ' + className:''}${disabled?' disabled':''}`, style:getValue(item.style),onClick:(e)=>itemClick(index,e),title:'',dataindex:index,tabIndex:0 } return( <Fragment> {item.splitter &&<div className={'rdb-splitter ' + (rtl?'rtl':'ltr')}>{item.splitter}</div>} {href?<a href={href} {...props}>{Icon}{Text}{After}</a>:<div {...props}>{CheckIcon}{Icon}{Text}{After}</div>} </Fragment> ); } } export default RDropdownButton;
"use strict"; var React = require('react'); var _a = require('react-router'), IndexRoute = _a.IndexRoute, Route = _a.Route; var app_1 = require('../containers/app'); var about_page_1 = require('../containers/about-page'); var counter_page_1 = require('../containers/counter-page'); exports.__esModule = true; exports["default"] = (<Route path="/" component={app_1["default"]}> <IndexRoute component={counter_page_1["default"]}/> <Route path="about" component={about_page_1["default"]}/> </Route>);
function lelang(a){ var harga = 10000 for(var i = 1 ; i<=a; i++){ if(i%4==0){ harga = Math.ceil(harga*1.1) } else{ harga = Math.ceil(harga*1.2) } } if(harga<30000000){ console.log('Menit ke '+ a+ ' ' +harga) } else{ console.log('Menit ke '+ a+' barang sudah terjual') } } console.log(lelang(50))
import { fetchApi } from "../helpers/fetchApi"; export const getUserProfile = (id) => fetchApi(`users/${id}`); export const addUser = (user) => fetchApi("users", { method: "POST", body: JSON.stringify(user), });
export const API_DEFAULT_URL = "https://pokeapi.co/api/v2/"; export function API_POKEMON(nomePokemon) { return { url: API_DEFAULT_URL + `pokemon/${nomePokemon}`, options: { method: "GET", }, }; }
// pages/comment/comment.js const app = getApp() Page({ /** * 页面的初始数据 */ data: { result: [], //选中的评价[{id:'',num:9},{}] namelist: [], //上个页面选中的名字列表 optionsList: [], //备选项列表,四个维度及其下属相应的选项 classId: '', //上个页面传过来的 }, onChange(e) { //将选择的项目的编号记录下来 console.log(e) console.log(this.data.result) let index = e.currentTarget.dataset.index let result = this.data.result result[index].id = e.detail if (result[index].num == 0) { //如果选之前是0,选中之后,数量变为1 let list = this.data.result list[index].num = 1 this.setData({ result: list }) } this.setData({ result: result }); console.log(this.data.result) }, onchangeNum(e) { console.log(e) let index = e.currentTarget.dataset.index let result = this.data.result result[index].num = e.detail this.setData({ result: result }); console.log(this.data.result) }, comfirm() { //提交评价 let classId = this.data.classId; let idlist = wx.getStorageSync('chooseidlist'); //学生id数组 let m = { students: idlist, items: this.data.result } console.log(m); let flag = false; //至少选中一个选项 m.items.forEach((item) => { if (item) { flag = true } }) if (flag) { //封装数据 //将封装table wx.showLoading({ title: '提交中...', mask: true }) wx.request({ url: `${app.globalData.serverPath}/api/archives/addRewardByWx`, method: 'POST', data: { classId: classId, table: JSON.stringify(m) }, header: app.getHeader2(), success(res) { console.log(res.data) wx.hideLoading() if (res.data.errcode === '0') { wx.showToast({ icon: 'none', title: res.data.errmsg }) //提交成功后需要清除id 的 list缓存 wx.removeStorageSync('chooseidlist') wx.removeStorageSync('choosenamelist') setTimeout(function() { wx.switchTab({ url: '/pages/txl/txl', }) }, 2000) } else { wx.showToast({ icon: 'none', title: res.data.errmsg }) } }, fail(res) { wx.hideLoading() wx.showToast({ icon: 'none', title: JSON.stringify(res) }) } }) } else { wx.showToast({ title: '请至少选择一项', icon: 'none', duration: 3000, mask: true }) } }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { if (options.classId) { this.setData({ classId: options.classId }) } this.getData() }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function() { }, /** * 生命周期函数--监听页面显示 */ onShow: function() { let value = wx.getStorageSync('choosenamelist') console.log(value) this.setData({ namelist: value }) }, /** * 生命周期函数--监听页面隐藏 */ onHide: function() { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function() { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function() { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function() { }, /** * 用户点击右上角分享 */ onShareAppMessage: function() { }, getData: function() { let _this = this; wx.showLoading({ title: '加载中...', mask: true }) wx.request({ url: `${app.globalData.serverPath}/api/dimensionality/getDimensionalitys`, method: 'POST', data:{ type:'all' }, header: app.getHeader2(), success(res) { console.log(res.data) wx.hideLoading() if (res.data.errcode === '0') { _this.setData({ optionsList: res.data.data }) let list = [] //根据维度数生成 单选组 绑定数组的长度 _this.data.optionsList.forEach((item) => { list.push({ id: '', num: 0 }) }) _this.setData({ result: list }) } }, fail(res) { wx.hideLoading() wx.showToast({ icon: 'none', title: JSON.stringify(res) }) } }) } })
const str = "Hello World"; const greet = () => str; module.exports = { greet }
var express = require('express'); var app = express() module.exports = function(app){ app.get('/register',function(req,res){ res,render('register'); }) } //引用模块 var bodyParser = require('body-parser'); var multer = require('multer'); var session = require('express-session'); //调用中间件使用 // app.use(bodyParser.json()); // app.use(bodyParser.urlencoded({ extended: true })); // app.use(multer()); app.post('/register',function(req,res){ var User = global.dbHelper.getModel('user'), uname = req.body.uname; User.findOne({name:uname},function(error,doc){ if(doc){ req.session.error = '用户已经存在'; res.send(500) }else{ User.create({ name:uname, password:req.body.upwd },function(error,doc){ if(error){ res.send(500) }else{ req.session.error ='用户名创建成功'; res.send(200); } }) } }) })
const dbUser = "zorkiy"; const dbPassword = "Maks125"; const config = { port: 3113, secret: 'secret-key', dbUser, dbPassword, databaseUrl: `mongodb+srv://${dbUser}:${dbPassword}@cluster0-dldrs.mongodb.net/nodejs-test` }; module.exports = config;
import React from 'react'; import styles from './button.css'; export default ({ tagName = 'button', type = 'default', href, className = '', children }) => { if (href) { return <a href={href} className={`button button--${type} button--link ${className}`}>{children}</a>; } else { const Tag = tagName; return <Tag className={`button button--${type} ${className}`}>{children}</Tag> } };
import * as types from './action-types'; import { getTopBannerData,getHotRecommend,getNewAlbum } from '@services/recommend'; import { HOT_RECOMMEND_LIMIT } from '../../common/constants'; const action = { getTopBannerAction() { return async dispatch => { const { data } = await getTopBannerData(); dispatch(action.changeBannerDataAction(data.banners)) } }, changeBannerDataAction(bannerList) { return { type: types.CHANGE_TOP_BANNER, payload: bannerList } }, getHotRecommendAction() { return async dispatch => { const res = await getHotRecommend(HOT_RECOMMEND_LIMIT); dispatch(action.changeHotRecommendAction(res.data.result)); } }, changeHotRecommendAction(hotRecommendList) { return { type: types.CHANGE_HOT_RECOMMEND, payload: hotRecommendList } }, getAlbumsAction() { return async dispatch => { const { data } = await getNewAlbum(); dispatch(action.chnageTopAlbumsAction(data.albums)); } }, chnageTopAlbumsAction(payload) { return { type: types.CHANGE_TOP_ALBUM, payload } } } export default action;
// pages/today-new-list/today-new-list.js import { me, xmini, xPage, } from '../../config/xmini'; import api from '../../api/index'; import { mapTo, pullList, } from '../../utils/index'; import mixins from '../../utils/mixins'; xPage({ ...mixins, ...pullList, /** * 页面的初始数据 */ data: { isLoading:true, list: [], showFooter: false, listMode: 'card', lowerThreshold: 300, pullLoading: false, }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.onPageInit(options); this.setData({ lowerThreshold: wx.getSystemInfoSync().screenHeight / 2, }); this.refresh(); }, onShow() { this.updatadSpmPage(); // 新增更新spm 三段中的 page }, onUnload() { }, // pull refresh refresh: function () { this.initPullList(); wx.showLoading(); this.pullParams.scope = this; this.pullParams.weights = 1; this.pullModel = api.getNewSkuList; this.setData({ isLoading: true, }) // 主动触发加载事件 this.onScrollToLower(); }, afterPull() { if (this.pullParams.pageNum == 1) { delete this.pullParams.scope; delete this.pullParams.weights; } }, afterPullData(){ this.setData({ isLoading: false, }) }, // dealwith data dealList: function (list = []) { return mapTo(list, (item) => { const isShowLootAll = !item.onLine || !item.inStock; return { id: item.pinActivitiesId, title: item.coupleTitle, image: item.skuPic, priceObj: { rmb: 1, price: item.couplePrice, marketPrice: item.marketPrice, memberPrice: item.member_price, }, isShowLootAll, tags: item.tags.splice(0,2) || [], inStock: item.inStock, onLine: item.onLine, endTime: item.endTime, showCountDownLimit: item.showCountDownLimit, merchantType: item.merchant_type, expired_date_text: item.expired_date_text_two, link: item.link, }; }); }, // click event onTapNext: function (e) { const { id, index, online, instock, url = '', } = e.currentTarget.dataset; xmini.piwikEvent('pinActivitiesId', { 'pinActivitiesId': id, index, }); if (online && instock && url) { this.onUrlPage(e); } }, });
import { createAppContainer } from 'react-navigation'; import { createStackNavigator } from 'react-navigation-stack'; import {createDrawerNavigator} from 'react-navigation-drawer'; import SplashScreen from "../features/SplashScreen"; import SideMenu from './sideMenu'; //@BlueprintImportInsertion import UserProfile94333Navigator from '../features/UserProfile94333/navigator'; import Settings94332Navigator from '../features/Settings94332/navigator'; import Settings94330Navigator from '../features/Settings94330/navigator'; import SignIn294328Navigator from '../features/SignIn294328/navigator'; /** * new navigators can be imported here */ const AppNavigator = { //@BlueprintNavigationInsertion UserProfile94333: { screen: UserProfile94333Navigator }, Settings94332: { screen: Settings94332Navigator }, Settings94330: { screen: Settings94330Navigator }, SignIn294328: { screen: SignIn294328Navigator }, /** new navigators can be added here */ SplashScreen: { screen: SplashScreen } }; const DrawerAppNavigator = createDrawerNavigator( { ...AppNavigator, }, { contentComponent: SideMenu }, ); const AppContainer = createAppContainer(DrawerAppNavigator); export default AppContainer;
/* Equipe: Aline Andressa Carvalho da Silva - Subturma C (Líder) Maria Eduarda Lagos Fernandes - Subturma C Etapas: 9 e 10; */ //player x= 35; y= 365; z=35; w=35; //lixo organico melan movObjeto=3 qtObjetos=3; aIn=[]; bIn=[]; rxo=25; ryo=25; //lixo ornganico banana movBanana=3 qtBanana=10; aBn=[]; bBn=[]; rxoB=25; ryoB=25; //inimigos LIXO TOXICO movToxico=2; qtToxico=5; xT=[]; yT=[]; rxoT=25; ryoT=25; //tiro tiro = false; xd=0; yd=0; //dinamica vidas= 3; score= "0"; level=0; nivel=0; barraScore=10; barralevel=10; barraVida=3; tela=1; plant=false plant2=false plant3=false //plantinha(s) qtPlanta=4; aPl=[]; aPl[0]= 70; bPl1=480 ra1=100; rb1=100 vPlanta=[] contPlant=0; o=0; p=0; j=0; h=0; r=2; let image1; let image5; let image2; function preload(){ pilha=loadImage("Pilhapng.png") fazenda=loadImage("image10.jpg") banana=loadImage("image6.png") pers=loadImage("lixo.png") melan=loadImage("image5.png") planta1=loadImage("image2.png") planta2=loadImage("image3.png") planta3=loadImage("image4.png") fundo=loadImage("image11.jpg") tela3=loadImage("arvore.png") vPlanta [0] = planta1 vPlanta [1] = planta2 vPlanta [2] = planta3 vPlanta [3] = tela3 } function setup() { createCanvas(640, 500); LetrasCor = color(100, 50, 150) for(var i=0;i<qtObjetos;i++) { aIn[i]= +800+(random(200)) bIn[i]= random(30,400) } for(var q=0;q<qtBanana;q++) { aBn[q]= +800+(random(200)) bBn[q]= random(30,400) } for(var e=0;e<qtPlanta;e++) { aPl[e+1]= aPl[e]+160 } for (var t=0;t<qtToxico;t++) { xT[t]=+800+(random(200)) yT[t]= random(30,400) } } function draw () { if(tela==1){ LetrasCor.setGreen(128 + 128 * sin(millis() / 100)); background(1000); fill(LetrasCor) textSize(40); text("Seja um ser humano consciente,", 40, 200) textSize(30) text(" adube as árvores com lixo orgânico.", 50, 250) textSize(30); text("Pressione SHIFT para começar a plantar",30,410) if(keyIsDown(16)){ tela=2; } } if(tela==2) { background(0); fill(0, 102, 153) textSize(25); text('Vida: '+ vidas, 10, 30); text('Tamanho: '+ score, 200, 30); text('Level: '+level, 480, 30); if (keyIsDown(LEFT_ARROW)) x-=12; if (keyIsDown(RIGHT_ARROW)) x+=7; if (keyIsDown(UP_ARROW)) y-=7; if (keyIsDown(40)) y+=7; if( x>605) { x=605 } if( x<35) { x=35 } if(y<70) { y=70 } if(y>435) { y=435 } Player=image(pers, x, y, 2*z, 2*w) //////funções de tiro///// if(keyIsDown(32) && w==60 && tiro== false) { xd=x yd=y tiro = true z=35 w=35 } if (tiro==true){ ellipse(xd+35, yd,10,10) yd+=10 if (yd>500 ){ tiro = false } } //plantinhas draw imageMode(CENTER) for(var e=0;e<qtPlanta;e++) { image(vPlanta[h], aPl[0], bPl1 ,ra1,rb1) if(dist(xd, yd,aPl[0], bPl1)<=50 && tiro==true){ tiro=false h++; if(h>=3){ h=3 } } image(vPlanta[o], aPl[1], bPl1 ,ra1,rb1) if(dist(xd, yd,aPl[1], bPl1)<=50 && tiro==true){ tiro=false o++; if(o>=3){ o=3 } } image(vPlanta[p], aPl[2], bPl1 ,ra1,rb1) if(dist(xd, yd,aPl[2], bPl1)<=50 && tiro==true){ tiro=false p++; if(p>=3){ p=3 } } image(vPlanta[j], aPl[3], bPl1 ,ra1,rb1) if(dist(xd, yd,aPl[3], bPl1)<=50 && tiro==true){ tiro=false j++; if(j>=3){ j=3 } } } level=o+p+h+j imageMode(CORNER) //melan for( i=0;i<qtObjetos;i++) { image(melan, aIn[i], bIn[i], 2*rxo, 2*ryo); aIn[i]=aIn[i]-movObjeto if (aIn[i]<-2*rxo) { aIn[i]=640+rxo; bIn[i]= random(70,400); } ///DINAMICA if(dist(x, y, aIn[i], bIn[i])< z+rxo-3){ aIn[i]=-50 bIn[i]=-50 z++ w++ } } //banana for(q=0;q<qtBanana;q++) { image(banana, aBn[q], bBn[q], 2*rxoB, 2*ryoB); aBn[q]=aBn[q]-movBanana if (aBn[q]<-50) { aBn[q]=640+rxoB; bBn[q]= random(70,400); } ///DINAMICA if(dist(x, y, aBn[q], bBn[q])< z+rxoB-3){ aBn[q]=-50 bBn[q]=-50 z++ w++ } } qtToxico=1 barralevel=1; if(level>barralevel){ barralevel++; qtToxico+=2} for( t=0;t<qtToxico;t++) { image(pilha, xT[t], yT[t], 2*rxoT, 2*ryoT); xT[t]=xT[t]-movToxico if (xT[t]<-rxoT*2) { xT[t]=640; yT[t]= random(70,400); } ///DINAMICA if(dist(x, y, xT[t], yT[t])< z+rxoT-3){ xT[t]=-rxoT*2 z-=5 w-=5 } } //TAMANHO if(z>60){ z=60 w=60 score="Maximo" } if(z<=35) { score="Pequeno" } if(z<25){ z=15 w=15 vidas-- z=35 w=35 x=35 y=365 } if(vidas==0){ tela=3; } if(level==12){ tela=4 } } if(tela==4){ LetrasCor.setGreen(128 + 128 * sin(millis() / 100)); background(1000); fill(LetrasCor) textSize(60); text("YOU WIN", 50, 300) textSize(30); text("Pressione espaço para começar a plantar",30,410) if(keyIsDown(32)){ tela=1; vidas=3; } } if(tela==3){ LetrasCor.setGreen(128 + 128 * sin(millis() / 100)); background(1000) fill(0) textSize(30); text('Poluiu demais,', 40, 150); text('plante mais árvores',20,200) text('novamente!',60,250) fill(LetrasCor) textSize(30) text("Pressione CONTROL para jogar novamente",30,410) text("Ou ESPAÇO para voltar para tela inicial",40,440) frameRate(5) var step = frameCount % 10; translate(300, 50); applyMatrix(1 / step, 0, 0, 1 / step, 0, 0); image(tela3, 0, 0, 300, 300); filter(GRAY) if(keyIsDown(CONTROL)){ vidas=3; tela=2; } if(keyIsDown(32)){ tela=1; vidas=3 } } }
import styled from "styled-components"; export const StyledTitle = styled.h3` font-size: 22px; text-align: center; `;
// ********************* // Modules scripts // ********************* // MINIFIED Vendor file should be copied over via copyScripts.js (it is by default) // IMPORT all modules here. Keep lib and minified files out this file. // Except for the example below //the import statments for CSS and JS can and should be exactly the same. Components that are CSS only should have some example markup in the HTML folder. The JS file is optional. import 'modules/bLazySettings'; import 'modules/backToTop'; import 'modules/flickitySettings'; import '../components/accordion/bf_accordion'; import '../components/back_to_top/bf_back_to_top'; import '../components/carousel/bf_carousel'; import '../components/forms/bf_forms'; import '../components/modal/bf_modal'; import '../components/nav_main/bf_nav_main'; import '../components/search/searchBox/bf_searchBox'; import '../components/search/searchFilters/bf_searchFilters'; import '../components/social/bf_social'; import '../components/tabs/bf_tabs'; import '../components/headers/bf_headers'; // USING production variables is simple with the envVar function // Burn after reading import envVar from 'lib/envVar'; var dev_var = envVar({production:'myProductionURL', development: 'myDevelopmentURL'}); // Test using `$ gulp production` vs `$ gulp` in terminal console.log(dev_var);
module.exports = async (client, guild) => { const guildDB = await client.database.GuildSchema.findOne({ '_id': guild.id}) if (guildDB) { await client.database.GuildSchema.deleteOne({ '_id': guild.id }) } }
function runTest() { FBTest.openNewTab(basePath + "console/api/dirxml.html", function(win) { FBTest.openFirebug(function() { FBTest.enableConsolePanel(function(win) { var config = {tagName: "div", classes: "logRow logRow-dirxml"}; FBTest.waitForDisplayedElement("console", config, function(row) { var xml = /\s*<div\s*id=\"content\"\s*style=\"display:\s*none;\"><span>a<\/span><span><span>b<\/span><\/span><\/div>/; FBTest.compare(xml, row.textContent, "XML must be properly displayed."); FBTest.testDone(); }); // Execute test implemented on the test page. FBTest.click(win.document.getElementById("testButton")); }); }); }); }
import * as R from 'rodin/core'; import {SkySphere} from './SkySphere.js'; export const changeEnv = (evt, i) => { if(evt.globals.env) { evt.globals.env.dispose(); } evt.globals.env = new SkySphere(evt.globals.envTextures[i]); R.Scene.add(evt.globals.env); };
console.log('a'); export default { a: 'rrrrr' }
class Holidays { constructor() { /* src: [20190513 access] https://pl.wikipedia.org/wiki/%C5%9Awi%C4%99ta_pa%C5%84stwowe_w_Polsce https://pl.wikipedia.org/wiki/Dni_wolne_od_pracy_w_Polsce */ this.holidays = [ // [month, day] 1-indexed [1, 1], [1, 6], [3, 1], [5, 1], [5, 3], [8, 15], [11, 1], [11, 11], [12, 25], [12, 26] ]; let date = new Date(); this.year = date.getFullYear(); this.addEaster(this.year); } isHoliday(month, day) { let date = this.getDate(this.year, month, day); let weekend = [6, 0]; // saturday & sunday if (weekend.includes(date.getDay())) { return true; } let checkedDate = [month, day]; // cannot use .includes, 2d array let isHoliday = false; for (let holiday of this.holidays) { isHoliday = isHoliday || ( holiday[0] == checkedDate[0] && holiday[1] == checkedDate[1]); } return isHoliday; } addEaster(year) { this.holidays.push(this.getEasterSunday(year)); this.holidays.push(this.getEasterMonday(year)); this.holidays.push(this.getZieloneSwiatki(year)); this.holidays.push(this.getBozeCialo(year)); } getEasterSunday(year) { // source = https://gist.github.com/johndyer/0dffbdd98c2046f41180c051f378f343 var f = Math.floor, G = year % 19, C = f(year / 100), H = (C - f(C / 4) - f((8 * C + 13)/25) + 19 * G + 15) % 30, I = H - f(H/28) * (1 - f(29/(H + 1)) * f((21-G)/11)), J = (year + f(year / 4) + I + 2 - C + f(C / 4)) % 7, L = I - J, month = 3 + f((L + 40)/44), day = L + 28 - 31 * f(month / 4); return [month,day]; } getEasterMonday(year) { return this.getDateAfterEaster(year, 1); } getZieloneSwiatki(year) { return this.getDateAfterEaster(year, 49); } getBozeCialo(year) { return this.getDateAfterEaster(year, 60); } getDateAfterEaster(year, daysAfter) { let sundayMonth, sundayDay, mondayMonth, mondayDay; [sundayMonth, sundayDay] = this.getEasterSunday(year); let monday = this.getDate(year, sundayMonth, sundayDay+daysAfter); [mondayMonth, mondayDay] = [monday.getMonth()+1, monday.getDate()] return [mondayMonth, mondayDay]; } getDate(year, month, day) { return new Date(year, month-1, day); } } class Calendar { constructor() { this.holidays = new Holidays(); let date = new Date(); this.year = date.getFullYear(); this.month = date.getMonth() + 1; } getMonth() { let daysList = []; let daysAmount = this.daysInMonth(this.year, this.month); for (let day = 1; day <= daysAmount; day++) { let dayObject = { day: day, month: this.month, year: this.year, isHoliday: this.holidays.isHoliday(this.month, day) }; daysList.push(dayObject); } return daysList; } daysInMonth(year, month) { // month is 0-indexed, so it returns 0th day of the next month, // hence last day of specified month alas the amount of them return new Date(year, month, 0).getDate(); } } class MonthTable { constructor() { let calendar = new Calendar(); this.month = calendar.getMonth(); } generate(pageBreak=false) { let tableWidths = ['auto', '*', '*', '*', '*', '*'] let tableHeaders = [ 'Dzień', 'Godzina rozpoczęcia', 'Godzina zakończenia', 'Razem godzin', 'Podpis', 'Uwagi' ]; let tableBody = [tableHeaders]; for (let day of this.month) { let emptyCell = {text: ''}; let dayRow = [ {text: day.day}, emptyCell, emptyCell, emptyCell, emptyCell, emptyCell ]; for (let i in dayRow) { dayRow[i].style = ['tableCell']; if (day.isHoliday) { dayRow[i].style.push('holiday'); } } tableBody.push(dayRow); } let table = { layout: '', table: { headerRows: 1, widths: tableWidths, body: tableBody }, style: 'calendar' }; if (pageBreak) { table.pageBreak = 'after'; } return [table]; } } class Header { constructor(firstName, lastName) { let date = new Date(); let months = [ "Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień" ]; this.firstName = firstName; this.lastName = lastName; this.year = date.getFullYear(); this.yearSuffix = this.year.toString().slice(-2); // 2018 -> 18 this.month = months[date.getMonth()].toLowerCase(); } generate() { let textTop = { text: 'LISTA OBECNOŚCI', style: 'header' }; let information = { columns: [ { width: '*', style: 'nameTemplate', text: [ 'Imię: ', {text: this.firstName, style: 'name'} ] }, { width: '*', style: 'nameTemplate', text: [ 'Nazwisko: ', {text: this.lastName, style: 'name'} ] }, { width: '*', style: 'nameTemplate', text: [ 'Miesiąc: ', {text: `${this.month} ’${this.yearSuffix}`, style: 'name'} ] } ], style: 'information' }; return [textTop, information]; } } class PdfGenerator { constructor() { let PdfPrinter = require('pdfmake'); let fonts = { Roboto: { normal: 'fonts/Roboto-Regular.ttf', bold: 'fonts/Roboto-Medium.ttf', italics: 'fonts/Roboto-Italic.ttf', bolditalics: 'fonts/Roboto-MediumItalic.ttf' } }; this.printer = new PdfPrinter(fonts); this.filename = 'lista-obecnosci.pdf'; this.styles = { holiday: { fillColor: '#A6A6A6' }, header: { fontSize: 24, alignment: 'center', margin: 16 }, name: { bold: true, fontSize: 14 }, nameTemplate: { bold: true, fontSize: 8 }, tableCell: { alignment: 'center' }, information: { margin: [24, 8, 24, 4] }, calendar: { margin: [8, 0, 8, 0] } } this.document = { content: [], styles: this.styles }; } generateEmployees(employees) { let document = []; for (let employeeIndex in employees) { let employee = employees[employeeIndex]; let firstName = employee.firstName; let lastName = employee.lastName; let lastEmployee = employeeIndex == employees.length - 1; let pageBreak = !lastEmployee; let table = new MonthTable().generate(pageBreak); let header = new Header(firstName, lastName).generate(); document.push([header, table]); } this.document.content.push(document); } outputHeaders(response) { let filename = this.filename; response.setHeader('Content-disposition', `inline; filename="${filename}"`); response.setHeader('Content-type', 'application/pdf'); } output(response) { this.outputHeaders(); let pdf = this.printer.createPdfKitDocument(this.document); let chunks = []; let result; pdf.on('data', chunk => { chunks.push(chunk); }); pdf.on('end', () => { result = Buffer.concat(chunks); response.send(result); }); pdf.end(); } outputFile(path, callback=function(){}) { let fs = require('fs'); let pdf = this.printer.createPdfKitDocument(this.document); let stream = fs.createWriteStream(path+'/'+this.filename); pdf.pipe(stream); pdf.end(); stream.on('finish', () => { callback(); }); } } function generatePdf(callback) { let employees = require('./database.json'); let employeesList = employees.employees; let gen = new PdfGenerator(); gen.generateEmployees(employeesList); const nodeMailer = require('nodemailer'); gen.outputFile("cache", callback); } function sendMail(mail, auth, destination) { const nodemailer = require("nodemailer"); let transporter = nodemailer.createTransport({ host: mail.host, port: mail.port, secure: mail.secure, auth: auth }); // send mail with defined transport object transporter.sendMail({ from: `"${auth.name}" <${auth.user}>`, to: destination, subject: "Wygenerowane listy obecności.", text: "W załączniku przesyłam listy obecności na bieżący miesiąc.", html: "W załączniku przesyłam listy obecności na bieżący miesiąc.", attachments: [{ filename: 'lista-obecnosci.pdf', path: 'cache/lista-obecnosci.pdf' }] }); } function run(req, res) { let destination = req.params.destination; if (destination == null || destination == "") { res.send("Podaj email!"); return; } let config = require("./config.json"); let mail = config.mail; let auth = config.auth; mail.secure = mail.port == 465; generatePdf(() => { sendMail(mail, auth, destination); res.send("Rozpoczęto wysyłanie emaila."); console.log("Rozpoczęto wysyłanie emaila -- "+destination); }); } const express = require('express'); const app = express(); const port = 80; app.use(express.static('public')); app.get('/send/:destination', (req, res) => run(req, res)); app.listen(port, () => console.log(`Narzędzie do generowania list obecności chodzi pod portem ${port}.`));
module.exports = { database: 'mongodb://localhost/nodejs-bolg', secret: 'niuyulei' }
import { createSlice, createSelector } from "@reduxjs/toolkit"; const userSlice = createSlice({ name: "userSlice", initialState: { loginUser: null, userLoading: true, }, reducers: { setLoginUser: (state, { payload: loginUser }) => { state.loginUser = loginUser; state.userLoading = false; }, clearLoginUser: (state) => { state.loginUser = null; state.userLoading = false; }, }, }); const selectLoginUserID = createSelector( (state) => state.loginUser && state.loginUser.id, (loginUserID) => loginUserID ); const selectLoginUser = createSelector( (state) => state.loginUser, (loginUser) => loginUser ); const selectUserLoading = createSelector( (state) => state.userLoading, (userLoading) => userLoading ); export const USER = userSlice.name; export const userReducer = userSlice.reducer; export const userActions = userSlice.actions; export const userSelector = { loginUserID: (state) => selectLoginUserID(state[USER]), loginUser: (state) => selectLoginUser(state[USER]), userLoading: (state) => selectUserLoading(state[USER]), };
const colorfulNumbers = number => { const set = new Set(); const nums = [...String(number)]; for (let i = 0; i < nums.length; i++) { let prev = 1; for (let j = i; j < nums.length; j++) { const product = prev * nums[j]; if (set.has(product)) return false; else set.add(product); prev = product; } } return true; }; console.log(colorfulNumbers(3245)) console.log(colorfulNumbers(326))
/** * Component displaying interactions in a circle view * * @class * @extends Biojs * * @author <a href="mailto:rafael@ebi.ac.uk">Rafael C Jimenez</a> * @version 1.0.0 * @category 0 * * @requires <a href='http://d3js.org/'>D3.js v3</a> * @dependency <script language="JavaScript" type="text/javascript" src="../biojs/dependencies/d3/d3.v2.5.js"></script> * * * @requires <a href='http://d3js.org/'>d3.layout</a> * @dependency <script language="JavaScript" type="text/javascript" src="../biojs/dependencies/d3.layout.js"></script> * * * @requires <a href='http://d3js.org/'>packages</a> * @dependency <script language="JavaScript" type="text/javascript" src="../biojs/dependencies/packages.js"></script> * * @requires <a href='../biojs/css/Biojs.InteractionsCircleView.css'>Biojs.InteractionsCircleView.css</a> * @dependency <link href="../biojs/css/Biojs.InteractionsCircleView.css" rel="stylesheet" type="text/css" /> * * @param {Object} options An object with the options to display the component. * * @option {string} target * Identifier of the DIV tag where the component should be displayed. * * @option {Array} inputData * Input data * * */ //todo: bring dependencies to BioJS Biojs.InteractionsCircleView = Biojs.extend ( /** @lends Biojs.InteractionsCircleView# */ { constructor: function (options) { this._startD3(); //this._playground(); }, _playground: function(){ var div = d3.select('#'+this.opt.target).append("div"); var span = d3.select('#'+this.opt.target).insert("span"); var h1 = div.append("h1"); h1.style("top", "60px"); h1.attr("class", "hell") span.style("top", "70px"); div.style("top", "80px"); }, _startD3: function(){ Biojs.console.enable(); var self = this; this._svg; var w = this.opt.width, //OPT width h = this.opt.height, //OPT height rx = w / 2, ry = h / 2, m0, rotate = 0; var splines = []; /* The cluster LAYOUT produces dendrograms */ var cluster = d3.layout.cluster() .size([360, ry - 120]) .sort(function(a, b) { return d3.ascending(a.key, b.key); }); /* LAYOUT implementing Danny Holten's hierarchical edge bundling algorithm */ var bundle = d3.layout.bundle(); /* Constructs a new radial line generator */ var line = d3.svg.line.radial() .interpolate("bundle") .tension(this.opt.tension) .radius(function(d) { return d.y; }) .angle(function(d) { return d.x / 180 * Math.PI; }); /* Create SVG in a new div container */ // Chrome 15 bug: <http://code.google.com/p/chromium/issues/detail?id=98951> var container = d3.select('#'+this.opt.target) .append("div") .attr("class", Biojs.InteractionsCircleView.COMPONENT_PREFIX + "container") .style("width", w + "px") .style("height", h + "px") var div = container.insert("div", "h2") //.style("top", "-80px") //.style("left", "-160px") //.style("left", "-360px") .style("width", w + "px") .style("height", w + "px") .style("position", "absolute") .style("-webkit-backface-visibility", "hidden") .attr("class", Biojs.InteractionsCircleView.COMPONENT_PREFIX + "subcontainer"); this._svg = div.append("svg:svg") .attr("width", w) .attr("height", w) .append("svg:g") .attr("transform", "translate(" + rx + "," + ry + ")"); this._svg.append("svg:path") .attr("class", "arc") .attr("d", d3.svg.arc().outerRadius(ry - 120).innerRadius(0).startAngle(0).endAngle(2 * Math.PI)) .on("mousedown", mousedown); //d3.json("flare-interactions2.json", function(classes) { //OPT json input var classes = this.opt.inputData; /* Apply layouts */ var nodes = cluster.nodes(packages.root(classes)), // Apply cluster layout links = packages.interactions(nodes), splines = bundle(links); // Apply bundle layout /* Create svg panel for edges */ var path = this._svg.selectAll("path.link") .data(links) .enter().append("svg:path") .attr("class", function(d) { return "link source-" + d.source.key + " target-" + d.target.key; }) .attr("d", function(d, i) { return line(splines[i]); }); /* Create svg panel for nodes */ this._svg.selectAll("g.node") .data(nodes.filter(function(n) { return !n.children; })) .enter().append("svg:g") .attr("class", "node") .attr("id", function(d) { return "node-" + d.key; }) .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; }) .append("svg:text") .attr("dx", function(d) { return d.x < 180 ? 8 : -8; }) .attr("dy", ".31em") .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; }) .attr("transform", function(d) { return d.x < 180 ? null : "rotate(180)"; }) .text(function(d) { return d.key; }) .on("mouseover", mouseover) .on("click", mouseclick) .on("mouseout", mouseout); /* Tension listener */ d3.select("input[type=range]").on("change", function() { line.tension(this.value / 100); path.attr("d", function(d, i) { return line(splines[i]); }); }); //}); /* Circle rotation */ d3.select(window) .on("mousemove", mousemove) .on("mouseup", mouseup); function mouse(e) { return [(e.layerX) - rx, e.layerY - ry]; } function mousedown() { m0 = mouse(d3.event); d3.event.preventDefault(); } function mousemove() { if (m0) { var m1 = mouse(d3.event), dm = Math.atan2(cross(m0, m1), dot(m0, m1)) * 180 / Math.PI; div.style("-webkit-transform", "translateY(" + (ry - rx) + "px)rotateZ(" + dm + "deg)translateY(" + (rx - ry) + "px)"); } } function mouseup() { if (m0) { var m1 = mouse(d3.event), dm = Math.atan2(cross(m0, m1), dot(m0, m1)) * 180 / Math.PI; rotate += dm; if (rotate > 360) rotate -= 360; else if (rotate < 0) rotate += 360; m0 = null; div.style("-webkit-transform", null); self._svg.attr("transform", "translate(" + rx + "," + ry + ")rotate(" + rotate + ")") .selectAll("g.node text") .attr("dx", function(d) { return (d.x + rotate) % 360 < 180 ? 8 : -8; }) .attr("text-anchor", function(d) { return (d.x + rotate) % 360 < 180 ? "start" : "end"; }) .attr("transform", function(d) { return (d.x + rotate) % 360 < 180 ? null : "rotate(180)"; }); } } function cross(a, b) { return a[0] * b[1] - a[1] * b[0]; } function dot(a, b) { return a[0] * b[0] + a[1] * b[1]; } /* Node mouseover -> node + edges highlight*/ function mouseclick(d) { self._mouseclick(d); } function mouseover(d) { self._mouseover(d); // Biojs.console.log(d.key); // // self._svg.selectAll("path.link.target-" + d.key) // .classed("target", true) // .each(updateNodes("source", true)); // // self._svg.selectAll("path.link.source-" + d.key) // .classed("source", true) // .each(updateNodes("target", true)); } function mouseout(d) { self._mouseout(d); // self._svg.selectAll("path.link.source-" + d.key) // .classed("source", false) // .each(updateNodes("target", false)); // // self._svg.selectAll("path.link.target-" + d.key) // .classed("target", false) // .each(updateNodes("source", false)); } // function updateNodes(name, value) { // return function(d) { // if (value) this.parentNode.appendChild(this); // self._svg.select("#node-" + d[name].key).classed(name, value); // }; // } }, /* * Function: Biojs.InteractionsCircleView._updateNodes * Purpose: - * Returns: - * Inputs: - */ _updateNodes: function(name, value){ var self = this; return function(d) { if (value) this.parentNode.appendChild(this); self._svg.select("#node-" + d[name].key).classed(name, value); }; }, /* * Function: Biojs.InteractionsCircleView._mouseclick * Purpose: - * Returns: - * Inputs: - */ _mouseclick: function(d){ var highlighted = this.toggleHighlightNode(d.key); this.raiseEvent( "onNodeClick", { "nodeName": d.key, "highlighted": highlighted } ); }, /* * Function: Biojs.InteractionsCircleView._mouseout * Purpose: - * Returns: - * Inputs: - */ _mouseout: function(d){ this._svg.selectAll("path.link.source-" + d.key) .classed("source", false) .each(this._updateNodes("target", false)); this._svg.selectAll("path.link.target-" + d.key) .classed("target", false) .each(this._updateNodes("source", false)); }, /* * Function: Biojs.InteractionsCircleView._mouseover * Purpose: - * Returns: - * Inputs: - */ _mouseover: function(d){ this._svg.selectAll("path.link.target-" + d.key) .classed("target", true) .each(this._updateNodes("source", true)); this._svg.selectAll("path.link.source-" + d.key) .classed("source", true) .each(this._updateNodes("target", true)); }, /** * Select node and highlight (color) interactions. * @param {string} identifier Interactor identifier. * * @example * instance.selectNode("P07200"); * */ toggleHighlightNode: function(id){ var newHighlight = true; if(this._svg.selectAll("g.node#node-" + id).classed("highlighted") == true){ newHighlight = false; } this.unhighlightNodes(); if(newHighlight){ this.highlightNode(id); } else { this.unhighlightNode(id); } return newHighlight; }, highlightNode: function (id) { this._svg.select("g.node#node-" + id).classed("highlighted", true); this._svg.selectAll("path.source-" + id).classed("highlighted", true); this._svg.selectAll('path.link.source-' + id).classed("highlighted", true); this._svg.selectAll('path.link.target-' + id) .each(function (d, i) { if (d.target.interactions != undefined) { d.target.interactions.forEach( function (node, index) { var nodeName = node; if (node.lastIndexOf(".") != -1) { nodeName = node.substring(node.lastIndexOf(".") + 1); } console.log(nodeName); d3.select("g.node#node-" + nodeName).classed("highlighted", true); } ); } }); }, /* old code highlightNode: function(id){ this._svg.selectAll("g.node#node-" + id).classed("highlighted", true); this._svg.selectAll("g.node.source").classed("highlighted", true); this._svg.selectAll("path.source").classed("highlighted", true); },*/ unhighlightNode: function(id){ this._svg.selectAll("g.node#node-" + id).classed("highlighted", false); }, unhighlightNodes: function(){ this._svg.selectAll("g.node.highlighted").classed("highlighted", false); this._svg.selectAll("path.highlighted").classed("highlighted", false); }, /** * Select node and highlight (color) interactions. * @param {string} identifier Interactor identifier. * * @example * instance.selectNode("P07200"); * */ selectNode: function(id){ //console.log("select " + id); //RISE EVENT this._svg.selectAll("path.link.source-" + id) .classed("selected", true); this._svg.selectAll("g.node#node-" + id) .classed("selected", true); //.each(this._updateNodes("target", false)); }, /** * Unselect node and remove highlight (color). * @param {string} identifier Interactor identifier. * * @example * instance.unselectNode("P07200"); * */ unselectNode: function(id){ console.log("UNselect " + id); //RISE EVENT this._svg.selectAll("path.link.source-" + id) .classed("selected", false); this._svg.selectAll("g.node#node-" + id) .classed("selected", false); //.each(this._updateNodes("target", false)); }, /** * Select nodes and highlight (color) interactions. * @param {Array} identifiers List of interactor identifiers. * * @example * instance.selectNodes(["P07200","Q15052"]); * */ selectNodes: function(ids){ for (var i = 0; i < ids.length; i++) { this.selectNode(ids[i]); } }, /** * Unselect nodes and remove highlight (color). * @param {Array} identifiers List of Interactor identifiers. * * @example * instance.unselectNodes(["P07200","Q15052"]); * */ unselectNodes: function(ids){ for (var i = 0; i < ids.length; i++) { this.unselectNode(ids[i]); } }, /** * Unselect all nodes and remove highlight (color). * * @example * instance.unselectAllNodes(); * */ unselectAllNodes: function(){ //RISE EVENT this._svg.selectAll("path.link") .classed("selected", false); this._svg.selectAll("g.node.selected") .classed("selected", false); //.each(this._updateNodes("target", false)); }, getInteractions: function(interactor){ var interactions = new Array(); this.opt.inputData.forEach(function(d,i) { if(d.key == interactor){ d.interactions.forEach(function(s,j){ var dotLoc = s.lastIndexOf("."); if(dotLoc != -1 && dotLoc+1 < s.length){ var acc = s.substring(dotLoc+1, s.length); interactions.push(acc); } }) } }); return interactions; }, displayAlternativeNames: function(){ var self = this; for (var key in this.opt.alternativeNames) { if (this.opt.alternativeNames.hasOwnProperty(key) && self.opt.alternativeNames[key] != "") { d3.select(d3.select("g#node-"+key+" text").node()).text(self.opt.alternativeNames[key]); } } }, displayPrimaryNames: function(){ var self = this; for (var key in this.opt.alternativeNames) { if (this.opt.alternativeNames.hasOwnProperty(key)) { d3.select(d3.select("g#node-"+key+" text").node()).text(key); } } }, /** * Default values for the options * @name Biojs.InteractionsCircleView-opt */ opt: { target: "YourOwnDivId", inputData: [], tension: 0.85, width:1280, height: 800, alternativeNames: {} }, /** * Array containing the supported event names * @name Biojs.InteractionsCircleView-eventTypes */ eventTypes : [ /** * @name Biojs.SelectionList#onNodeClick * @event * @param {function} actionPerformed A function which receives a {@link Biojs.Event} object as argument. * @eventData {string} nodeName Node name. * * @example * instance.onNodeClick( * function( event ) { * alert( event.nodeName ); * } * ); * **/ "onNodeClick" ] },{ // Some static values COMPONENT_PREFIX: "icv_" });
'use-scrict'; /* * FIREBASE INITIALIZE CONFIGS * -------------------------------------------------------- */ var config = { apiKey: "AIzaSyCT1M3Fbz4M3iN3bVoc9jnAh98OGTjQcvQ", authDomain: "teste-lipperhub.firebaseapp.com", databaseURL: "https://teste-lipperhub.firebaseio.com", projectId: "teste-lipperhub", storageBucket: "teste-lipperhub.appspot.com", messagingSenderId: "1067565145692" }; firebase.initializeApp(config); body = document.querySelector('body'); usuario = document.querySelector('#usuario'); login = document.querySelector('#form-login'); register = document.querySelector('#form-register'); //Escutando status do Firebase firebase.auth().onAuthStateChanged(function(user) { if (user) { login.classList.remove('active'); usuario.classList.add('active'); $('#usuario').find('.email').html(user.email); } else { usuario.classList.remove('active'); login.classList.add('active'); } }); /* * LOADER * -------------------------------------------------------- */ window.onload = function() { document.querySelector('#loader').classList.add('hidden'); body.classList.add('loaded'); }; /* * MENU MOBILE * -------------------------------------------------------- */ const btn_mobile = document.querySelector('.btn-mobile'); btn_mobile.addEventListener("click",function(){ this.classList.toggle('active'); document.querySelector('header nav').classList.toggle('active'); }); /* * TABS SERVICE * -------------------------------------------------------- */ const mask = document.querySelector('.mask'); const services = document.querySelector('.services'); const service = document.querySelector('.service'); $('[data-service]').click(function(event) { event.preventDefault(); nav = this.getAttribute('data-service'); services.classList.add('active'); services.querySelector('.service.' + nav).classList.add('active'); services.querySelector('.service:not(.'+ nav +')').classList.remove('active'); mask.classList.add('active'); }); mask.addEventListener("click",function(){ closeNav(); }); function closeNav() { mask.classList.remove('active'); services.classList.remove('active'); services.querySelector('.service01').classList.remove('active'); services.querySelector('.service02').classList.remove('active'); services.querySelector('.service03').classList.remove('active'); } /* * FIXED MENU * -------------------------------------------------------- */ window.addEventListener('scroll', function() { var element = document.querySelector("html"); var scroll = element.scrollTop; var banner = $('#banner').height(); if(scroll > banner) { body.classList.add('fixed-menu'); } else { body.classList.remove('fixed-menu'); } }); /* * ANCHOR MENU * -------------------------------------------------------- */ $('header nav ul li a').click(function(e) { var page = $(this).attr('href').replace('#', '/#/'); if($(window).width() < 768) { $('.btn-mobile').removeClass('active'); $('header nav').slideUp(); } if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top - 50 }, 800); return false; } } }); /* * MODAL * -------------------------------------------------------- */ const modal = document.querySelector('#modal'); document.querySelector('.mask-modal').addEventListener("click",function(){ fecharModal(); }); document.querySelector('.fechar').addEventListener("click",function(){ fecharModal(); }); function openModal() { modal.classList.add('active'); } const msg = document.querySelector('#msg'); function fecharModal() { modal.classList.remove('active'); } /* * FORMS * -------------------------------------------------------- */ $('[data-form]').click(function(event) { event.preventDefault(); form = $(this).attr('data-form'); $('form').removeClass('active'); $('#form-'+form).addClass('active'); }); function msgModal(message) { msg.innerHTML = message; openModal(); } document.querySelector('#exit').addEventListener("click",function(event){ event.preventDefault(); firebase.auth().signOut() .then(function() { msgModal('Logout'); usuario.classList.remove('active'); // login.classList.add('active'); location.reload(); }, function(error) { msgModal(error.message); }); }); $('#form-login').submit(function(event) { event.preventDefault(); email = $(this).find('#lemail').val(); pass = $(this).find('#lpass').val(); firebase.auth().signInWithEmailAndPassword(email, pass) .then(function() { msgModal('Login Done'); $('#form-login')[0].reset(); $('#form-login').hide(); $('#usuario').show(); }).catch(function(error) { msgModal(error.message); }); }); $('#form-register').submit(function(event) { event.preventDefault(); email = $(this).find('#remail').val(); pass = $(this).find('#rpass').val(); firebase.auth().createUserWithEmailAndPassword(email, pass) .then(function(success){ msgModal('User created successfully'); $('#form-register')[0].reset(); $('#form-register').hide(); $('#form-login').show(); }).catch(function(error) { msgModal(error.message); }); });
(() => { const PATTERN = /^[/]wiki[/]([A-Z_0-9]+)[/]([^\\/]+)$/; const showPageView = () => { $(".title-group .icon-button").on("click", () => { const parts = PATTERN.exec(location.pathname); const projectKey = parts[1]; const pageName = decodeURIComponent(parts[2]); if (pageName.indexOf("/") === -1) { return true; } const paths = pageName.split("/"); paths[paths.length - 1] = "New Child Page" const parent = paths.join("/"); location.href = `/wiki/${projectKey}/${encodeURIComponent(parent)}/create`; return false; }); } const main = () => { if (location.pathname.match(PATTERN)) { setTimeout(() => { showPageView(); }, 0); } } PowerUps.isEnabled("child-page", (enabled) => { if (enabled) { main(); } }); })();
//Debemos lograr mostrar un mensaje al presionar el botón 'MOSTRAR'. function Mostrar() { alert("Funciona 6-iteraciones"); var importe; contador=0; while(contador<7) { contador++; importe=prompt("ingrese importe numero "+contador); while(importe<1) { importe=prompt("error, ingrese importe numero "+contador); } if(contador==1) { maximo=importe; } if(importe>maximo) { maximo=importe; } } }
let Pet = require('mongoose').model('Pet'); let errorHandler = require('./helpers/error-handler'); module.exports = { pets(req, res) { Pet.find().sort({ type: 1 }) .then(data => { res.json(data) }) // all responses just spit json .catch(errorHandler.bind(res)); // .bind ensures this will refer to the response object and not the errorHandler function }, show(req, res) { Pet.findById(req.params.id) .then(data => res.json(data)) .catch(errorHandler.bind(res)); }, create(req, res) { Pet.find({ name: req.body.name }) .then(data => { console.log('we have duplicate names', data); if (data.length > 0) { res.json({ err: ['Pet Name must be unique'], errors: true }) } else { console.log('we are making a new pet!') Pet.create(req.body) .then(data => res.json(data)) .catch(errorHandler.bind(res)); } }) .catch(errorHandler.bind(res)); }, update(req, res) { Pet.findOne({ name: req.body.name }) .then(pet => { console.log(pet); console.log(req.body); if (pet === null || pet['name'] === req.body.oldName) { Pet.update({ _id: req.params.id }, req.body, { runValidators: true }) .then(pet => res.json(pet)) .catch(errorHandler.bind(res)); } else { res.json({ err: ['Pet Name must be unique'], errors: true }) } }) .catch(errorHandler.bind(res)); }, // Pet.update({ // _id: req.params.id // }, { // name: req.body.name, // type: req.body.type, // description: req.body.description, // skill1: req.body.skill1, // skill2: req.body.skill2, // skill3: req.body.skill3 // }, { // new: true, // runValidators: true // }) // .then(data => res.json(data)) // .catch(errorHandler.bind(res)); // }, like(req, res) { Pet.findOneAndUpdate({ _id: req.params.id }, { $inc: { likes: 1 } }, { new: true //use new:true to return the document AFTER the update was applied }) .then(data => res.json(data)) .catch(errorHandler.bind(res)); }, destroy(req, res) { Pet.findByIdAndRemove(req.params.id) .then(result => res.json(result)) .catch(errorHandler.bind(res)); }, };
const centerX = 960; const centerY = 540; var config = { type: Phaser.CANVAS, scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, width: 1920, height: 1080, physics: { default: 'arcade', arcade: { gravity: { x: 300 }, debug: false } } }, scene: [SceneInitial, Apresentation, Frame1, Frame2, Frame3, Frame4 ] }; var font_LatoRegular = { fontFamily: "Lato-Regular", boundsAlignH: "center", boundsAlignV: "middle" } var font_LatoBlack = { fontFamily: "Lato-Black", boundsAlignH: "center", boundsAlignV: "middle" } var game = new Phaser.Game(config);
require('dotenv').config(); const express = require('express'); const router = express.Router(); const User = require('../models/User'); const Profile = require('../models/Profile'); const Journal = require('../models/Journal'); const auth = require('../middleware/auth'); //@route get profile/me //@desc get user's profile //@access private router.get('/me', auth, async (req, res) => { try { const profile = await Profile.findOne({ owner: req.user.id, }).populate('owner', ['username', '_id', 'avatar']); if (!profile) { return res.status(400).json({ msg: 'There is no profile for this user' }); } res.json(profile); } catch (err) { if (err.kind === 'ObjectId') { return res.status(404).json({ msg: 'User not found' }); } res.status(500).send('Server error'); } }); //@route GET api/profile/:user_id //@desc Get specific user's profile by user_id //@access Public router.get('/:user_id', async (req, res) => { try { const profile = await Profile.findOne({ owner: req.params.user_id, }).populate('owner', ['username', '_id', 'avatar']); res.json(profile); } catch (err) { if (err.kind == 'ObjectId') { return res .status(400) .json({ msg: 'There is no profile for this user.' }); } else res.status(500).send('server error'); } }); //@route POST api/profile //@desc Create /update user profile //@access Private router.post('/', auth, async (req, res) => { const { bio, allPrivate, status } = req.body; //Build profile object const profileFields = { owner: req.user.id, bio, allPrivate, status, }; try { // Using upsert option (creates new doc if no match is found): let profile = await Profile.findOneAndUpdate( { owner: req.user.id }, { $set: profileFields }, { new: true, upsert: true } ); // one-key to set all journals be private if (profile.allPrivate === 'true') { profile.journals.forEach(async (journal_id) => { const journal = await Journal.findById(journal_id); journal.setPrivate = true; await journal.save(); }); } res.json(profile); } catch (err) { res.status(500).send('Server Error'); } }); //@route DELETE /profile //@desc DELETE user, profile & journals //@access Private router.delete('/', auth, async (req, res) => { try { //remove user's posts await Journal.deleteMany({ author: req.user.id }); //remove profile await Profile.findOneAndRemove({ owner: req.user.id }); await User.findOneAndRemove({ _id: req.user.id }); res.json({ msg: 'User deleted' }); } catch (err) { res.status(500).send('Server Error'); } }); module.exports = router;
import React, {useState} from "react" import SearchIcon from "@material-ui/icons/Search" import {useDispatch} from "react-redux" import {searchProfileByEmail, searchProfileByPhone, searchProfileByUser, searchProfileByCard, searchProfileByMac, searchProfileByUrl, searchProfileByDomain } from "../state/actions" const Search = ({handleStage}) => { const [criteria, setCriteria] = useState("Email") const [value, setValue] = useState("") const dispatch = useDispatch() const onSubmit = (e) => { e.preventDefault() if(value.length === 0){ return; } switch(criteria){ case "Email": dispatch(searchProfileByEmail(value)) handleStage() return case "Phone Number": dispatch(searchProfileByPhone(value)) handleStage() return case "UserName": dispatch(searchProfileByUser(value)) handleStage() return case "Card Number": dispatch(searchProfileByCard(value)) handleStage() return case "Mac Address": dispatch(searchProfileByMac(value)) handleStage() return case "URL": dispatch(searchProfileByUrl(value)) handleStage() return case "Domain Name": dispatch(searchProfileByDomain(value)) handleStage() return default: return } } return( <div className="transactions__header__top__search"> <div className="transactions__header__top__search__input"> <SearchIcon/> <form onSubmit={onSubmit}> <input type="text" value={value} onChange={e => setValue(e.target.value)} placeholder={`Search Customer By ${criteria}`}/> </form> </div> <select onChange={e => setCriteria(e.target.value)}> <option value="Email">By Email</option> <option value="Phone Number">By Phone Number</option> <option value="UserName">By UserName</option> <option value="Card Number">By Card Number</option> <option value="Mac Address">By Mac Address</option> <option value="URL">By URL</option> <option value="Domain Name">By Domain Name</option> </select> </div> ) } export default Search
var React = require('react'); var Signup = React.createClass({ render: function() { return ( <div className="pure-g" id="full"> <div className="pure-u-1-1"> <iframe id="iframe" src="http://mailman.yale.edu/mailman/listinfo/yaleoutdoors" /> </div> </div> ); } }); module.exports = Signup;
var score = 0; // Enemies our player must avoid var Enemy = function(x,y) { // Variables applied to each of our instances go here, // we've provided one for you to get starte this.x = x; this.y = y; this.speed = getRandomInt(50, 300); this.sprite = 'images/enemy-bug.png'; }; function gameOver(){ console.log("collision"); oldScore = score alert("GAMEOVER, your score is "+ oldScore); score = 0; document.getElementById("score").innerHTML = "Score: 0"; player.reset(); } // Update the enemy's position, required method for game // Parameter: dt, a time delta between ticks Enemy.prototype.update = function(dt) { if (this.x < 505) { this.x += (this.speed * dt); } else{ this.x = -50; } //Enemy-player collision GAMEOVER : // In refrence to MDN - Mozilla found on https://developer.mozilla.org/kab/docs/Games/Techniques/2D_collision_detection. allEnemies.forEach(function(enemy){ if (player.x < enemy.x + 50 && player.x + 50 > enemy.x && player.y < enemy.y + 50 && 50 + player.y > enemy.y) { gameOver(); } }); } // Draw the enemy on the screen, required method for game Enemy.prototype.render = function() { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); }; // Now write your own player class // This class requires an update(), render() and // a handleInput() method. var Player = function(x,y){ this.x = x; this.y = y; this.sprite = 'images/char-pink-girl.png'; } Player.prototype.update = function(dt) { if (this.y < -5){ score++; document.getElementById("score").innerHTML = "Score:"+ score; this.reset(); } // to prevent going off the screen: if (this.x > 506){ this.x = 430; } else if (this.x < -15){ this.x = -10; } else if (this.y>606){ this.y = 530; } } Player.prototype.reset = function() { this.x = 200; this.y = 450; } Player.prototype.render = function() { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); } Player.prototype.handleInput = function(key) { switch (key){ case 'right': this.x +=50; break; case 'left': this.x -=50; break; case 'down': this.y +=50; break; case 'up': this.y -=50; break; } } // getRandomInt(min, max) function retrieved from a Stackoverflow question: //From the Mozilla Developer Network documentation: function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // Now instantiate your objects. // Place all enemy objects in an array called allEnemies // Place the player object in a variable called player //var enemy = new Enemy(200,200); allEnemies.push(enemy); var allEnemies = [] for (i=1;i<=5;i++){ var yValue = getRandomInt(50, 140) enemy = new Enemy(-10,yValue); allEnemies.push(enemy); } var player = new Player(200,450); // This listens for key presses and sends the keys to your // Player.handleInput() method. You don't need to modify this. document.addEventListener('keyup', function(e) { var allowedKeys = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; player.handleInput(allowedKeys[e.keyCode]); });
// 配置文件 // 开发环境或者默认配置 let config = { request_url: 'https://car.xyasin.cn/api', // 请求地址公共url reg_open: true, // 是否开启正则验证 request_timeout: 10, // 请求超时时间 单位s skeleton_time: 300, // 骨架屏等待时间 ms 用于mixin 内的全局定时器 // #ifdef H5 appid: 'wx130fb21739fa675d', // 公众号appid // #endif } // 非开发环境下配置 if (process.env.NODE_ENV != 'development') { config.request_url = 'https://car.xyasin.cn/api'; // 请求地址 config.reg_open = true; // 开启正则验证 config.skeleton_time = 300; // 骨架屏等待时间 // #ifdef H5 config.appid = 'wx280025459fa1971f'; // 公众号appid // #endif } export default config
const findBy = (key, value) => (element) => element[key] === value; export default findBy;
const express = require("express"); const router = express.Router(); const passport = require("passport"); // Model const User = require("../models/user"); const Faculty = require("../models/faculty"); const Student = require("../models/student"); // Middleware const checkAuth = require("../middleware/check-auth"); // var middlewareObj = require("../middleware"); // Controllor const studentControllor = require('../controller/student'); const uploadImage = require("../middleware").imgUpload; const uploadFile = require("../middleware").fileUpload; var mongoose = require("mongoose"); var Institution = require("../models/institution"); const GridFsStorage = require('multer-gridfs-storage'); const multer = require('multer'); const crypto = require('crypto'); const path = require('path'); const Grid = require('gridfs-stream'); const Helper = require('../helpers/index'); const addEsIndex = Helper.esSearch; const mongodb = require('mongodb'); // when user login, according to the userid to get the information of this student router.get("/:id", checkAuth, function(req, res, next) { // console.log("backend fatched user: " + req.userData.userId) Student.findOne({"user_id": req.params.id}, function(err, student){ if(err){ res.status(500).json({ message: "Fetching student failed!", student: null }); } else { res.status(200).json({ message: "student fetched successfully", student:student }) } }); }) // get the institution information of this student router.get("/institution/:id", checkAuth, function(req, res, next) { console.log("institution id:" + req.params.id); Institution.findById(req.params.id, function(err, foundInstitution) { res.send(foundInstitution); }) }) // const mongoAdd = 'mongodb+srv://yueningzhu505:volunteer123@cluster0-9ccmb.mongodb.net/curve'; // const connect = mongoose.createConnection(mongoAdd); // let gfs; // connect.once('open',() => { // gfs = Grid(connect.db, mongoose.mongo); // gfs.collection('uploads'); // }) // const storage = new GridFsStorage({ // url: mongoAdd, // file: (req, file) => { // console.log(req.params.id) // user_id = req.params.id // return new Promise((resolve, reject) => { // console.log(file.originalname); // crypto.randomBytes(16, (err, buf) => { // if (err) { // return reject(err); // } // gfs.files.find({"metadata.studentID": user_id}).toArray(function(err, files){ // gfs.files.deleteOne({"metadata.studentID": user_id}); // }); // const filename = buf.toString('hex') + path.extname(file.originalname); // const studentID = user_id // const fileInfo = { // filename: filename, // bucketName: req.params.filename, // metadata: { // studentID: user_id // } // }; // resolve(fileInfo, studentID); // }); // }); // } // }); // const upload = multer({ storage }); // router.post("/edit/resumes/:filename/:id", upload.single('file'),(req,res) => { // //res.json({file: req.file}); // console.log(1111); // res.json({'message':'upload successfully'}); // }); router.get("/transcript/:filename/:id", (req, res) => { gfs = Grid(connect.db, mongoose.mongo); gfs.collection(req.params.filename); //set collection name to lookup into /** First check if file exists */ console.log(req.params.id); gfs.files.find({"metadata.studentID": req.params.id}).toArray(function(err, files){ if(!files || files.length === 0){ return res.status(404).json({ responseCode: 1, responseMessage: "error" }); } // create read stream var readstream = gfs.createReadStream({ filename: files[0].filename, root: req.params.filename }); // set the proper content type res.set('Content-Type', files[0].contentType) //const file = `${__dirname}`; //res.download(file); console.log("display") readstream.pipe(res); //res.attachment('5.pdf'); //readstream1.pipe(res); }); }); router.post("/update", checkAuth, async function(req, res) { try { const updates = { first_name: req.body.first_name, last_name: req.body.last_name, gender: req.body.gender, date_of_birth: req.body.date_of_birth, major: req.body.major, minor: req.body.minor, email: req.body.email, phone: req.body.phone, graduation_class: req.body.class } const student = await Student.findOneAndUpdate({user_id: req.body.user_id}, updates); student.first_name = req.body.first_name; student.last_name = req.body.last_name; student.gender = req.body.gender; student.date_of_birth = req.body.date_of_birth; student.major = req.body.major; student.minor = req.body.minor; student.email = req.body.email; student.phone = req.body.phone; student.graduation_class = req.body.class; res.send(student); } catch(e) { res.status(400).send(e); } }) router.put("/editInterest", checkAuth, async function(req, res) { try { let student = await Student.findOneAndUpdate({user_id: req.body.id}, {interests: req.body.interests}); student.interests = req.body.interests; res.send(student); } catch(e) { console.log(e); res.send(e); } // res.send('OK'); }) // Basic includes search router.get("/search/:query", checkAuth, async function(req, res) { let query = req.params.query.split(' '); Helper.SearchHelper(query, req.params.query) .then((result) => { res.send(result); }) .catch((e) => { res.status(400).send(); }) }); // Uploads a picture to be saved as image field // Uploads to aws s3 // Should take image and id as form-data router.post("/upload/profilePic", checkAuth, uploadImage.single('image'), async function(req, res) { let id = mongoose.Types.ObjectId(req.body.id); try{ let student = await Student.findOneAndUpdate({user_id: id}, {image: req.file.location}); let oldImg = student.image; if(oldImg && oldImg.trim() != ''){ Helper.deleteS3(oldImg); } student.image = req.file.location; res.send(student); } catch(e) { console.log(e); res.send(e); } }) router.post("/upload/file", checkAuth, uploadFile.single('file'), async function(req, res) { let id = mongoose.Types.ObjectId(req.body.id); try { let fileType = req.body.fileType; // Either cv or resume student = {}; if (fileType == 'cv') { student = await Student.findOneAndUpdate({user_id: id}, {cv: req.file.location}); } else if (fileType == 'resume') { student = await Student.findOneAndUpdate({user_id: id}, {resume: req.file.location}); } else { res.status(400).send({message: "Upload only supports cv and resume params"}); } let oldFile = student[fileType]; if(oldFile && oldFile.trim() != ''){ Helper.deleteS3(oldFile); } student[fileType] = req.file.location; res.send(student); } catch(e) { console.log(e); res.status(400).send({errors: e}); } }); // Update a students summary field router.post("/update/summary", checkAuth, async function(req, res) { let id = req.body.user_id let summary = req.body.summary try { let student = await Student.findOneAndUpdate({user_id: id}, {summary: summary}); if(!student) { res.status(404).send({'error': "Could not find student"}); } student.summary = summary; res.status(200).send(student); } catch(e) { res.status(500).send({'error': "Error updating summary"}); } }) // UPDATE DOCUMENTS TO MATCH MODEL router.post("/update/model", checkAuth, async function(req, res) { try { await User.updateMany({}, {$set: {unreadMessages: []}}); res.status(200).send('Updated'); } catch(e) { res.status(400).send(e); } }) router.post("/add/index", checkAuth, async function(req, res) { try { const students = await Student.find({}); console.log(students.length); let promiseArr = []; students.forEach((s) => { promiseArr.push(addEsIndex(s)); }); Promise.all(promiseArr) .then((body) => { res.send('ok'); }) .catch((e) => { console.log(e); res.status(400).send('Error'); }) // res.send('ok'); } catch(e) { res.status(400).send("Error"); } }) // add application to the shopping cart router.post("/addToShoppingCart",checkAuth,studentControllor.addToShoppingCart); // delete item from the cart router.post("/deleteItem",checkAuth,studentControllor.deleteItem); // get shopping cart router.post("/getShoppingCartItemsByIds",checkAuth,studentControllor.getShoppingCartItemsByIds); module.exports = router;
$(document).ready(function () { var swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', spaceBetween: 30, autoplayDisableOnInteraction: false, autoHeight: false }); var apiInfo = [{ name: "guacamole", placement: "#guac-card-holder" }, { name: "margarita", placement: "#margarita-card-holder" }, { name: "mexican rice", placement: "#rice-card-holder" }, { name: "taco filling", placement: "#filling-card-holder" }, { name: "salsa", placement: "#salsa-card-holder" }, ]; var apiCounter = 0; function printCards(searchTerm, destination) { var queryURL = "https://api.edamam.com/search?q=" + searchTerm + "&app_id=37a0ea27&app_key=bc7804ad0a82ffd292c9b2f97619876b&from=0&to=3"; //edamam API call $.ajax({ url: queryURL, method: "GET" }).then(function (response) { console.log(response); for (var i = 0; i < response.hits.length; i++) { // console.log(response.hits[i]) var cardHolder = $(destination) //create a div with a col class var cardCol = $('<div>'); cardCol.addClass("col s4"); //create the card var card = $('<div>'); card.addClass("card blue-grey darken-1"); //create card content var cardContent = $('<div>'); cardContent.addClass('card-content white-text'); var cardTitle = $('<span>'); cardTitle.addClass('card-title'); cardTitle.html(response.hits[i].recipe.label) cardContent.prepend(cardTitle); var recipeSource = $('<p>'); recipeSource.html(response.hits[i].recipe.source); cardContent.append(recipeSource); var recipeLink = $('<div>'); recipeLink.addClass("card-action center-align"); var a = $("<a>"); a.attr("href", response.hits[i].recipe.shareAs); a.attr("target", "_blank"); a.html("Get Recipe"); recipeLink.append(a); cardContent.append(recipeLink); card.append(cardContent); cardCol.append(card); cardHolder.append(cardCol); } apiCounter++; if (apiCounter < apiInfo.length) { printCards(apiInfo[apiCounter].name, apiInfo[apiCounter].placement); } }); } printCards(apiInfo[apiCounter].name, apiInfo[apiCounter].placement); //Pinterest API call var queryURL2 = "https://api.pinterest.com/v1/boards/eventprep/fiesta-themed-event/pins/?access_token=AVLO9DT26n5QIo51b82JWrmEjD1UFR1gVsDvElxEyV7qa4AvwAAAAAA&fields=id%2Clink%2Cnote%2Curl%2Cboard%2Cimage&limit=3"; $.ajax({ url: queryURL2, method: "GET" }).then(function (pinterest) { console.log(pinterest); var results = pinterest.data; for (var i = 0; i < results.length; i++) { var cardHolder = $("#party-ideas") //create a div with a col class var cardCol = $('<div>'); cardCol.addClass("col s4"); //create the card var card = $('<div>'); card.addClass("card blue-grey darken-1"); //create card content var cardContent = $('<div>'); cardContent.addClass('card-content white-text'); var cardTitle = $('<span>'); cardTitle.addClass('card-title'); cardTitle.html(results[i].note) cardTitle.attr("style", "font-size: 16px"); cardContent.prepend(cardTitle); var partyLink = $('<div>'); partyLink.addClass("card-action center-align"); var a = $("<a>"); a.attr("href", results[i].link); a.attr("target", "_blank"); a.html("Get Ideas"); partyLink.append(a); cardContent.append(partyLink); card.append(cardContent); cardCol.append(card); cardHolder.append(cardCol); } }); //firebase var config = { apiKey: "AIzaSyDXjvCeNcd0deU_LCHEnLq80jQsFavW_ng", authDomain: "letstacoboutit01.firebaseapp.com", databaseURL: "https://letstacoboutit01.firebaseio.com", projectId: "letstacoboutit01", storageBucket: "letstacoboutit01.appspot.com", messagingSenderId: "458312732124" }; firebase.initializeApp(config); // Create a variable to reference the database var database = firebase.database(); var name = ""; var email = ""; var comment = ""; $("#submit-form").on("click", function () { event.preventDefault(); // Grabbed values from text boxes name = $("#name-input").find("input").val().trim(); email = $("#email-input").find("input").val().trim(); comment = $("#comment-input").find("textarea").val().trim(); console.log(name, email, comment); //Change what is saved in firebase if (name === '' || email === '' || comment === '') { var verify = $(".verify"); verify.addClass("alert alert-secondary"); verify.attr("role", "alert"); verify.attr("style", "color: red"); verify.html("Missing information"); } else { database.ref().set({ name: name, email: email, comment: comment }); var verify = $(".verify"); verify.addClass("alert alert-secondary"); verify.attr("role", "alert"); verify.attr("style", "color: white"); verify.html("Thank you for your feedback!"); name = $("#name-input").find("input").val(""); email = $("#email-input").find("input").val(""); comment = $("#comment-input").find("textarea").val(""); } }); });
function _Initialize() { grdMasterInitialize(); $NC.setInitDatePicker("#edtQEnd_Date"); $NC.setValue("#edtQBu_Cd", $NC.G_USERINFO.BU_CD); $NC.setValue("#edtQBu_Nm", $NC.G_USERINFO.BU_NM); $("#btnQBu_Cd").click(showUserBuPopup); $("#btnQBrand_Cd").click(showBuBrandPopup); $("#btnClose").click(onBtnCloseClick); $NC.setInitCombo("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CSUSERCENTER", P_QUERY_PARAMS: $NC.getParams({ P_USER_ID: $NC.G_USERINFO.USER_ID, P_CENTER_CD: "%" }) }, { selector: "#cboQCenter_Cd", codeField: "CENTER_CD", nameField: "CENTER_NM", onComplete: function() { $("#cboQCenter_Cd").val($NC.G_USERINFO.CENTER_CD); } }); } function _OnLoaded() { } function _SetResizeOffset() { // 화면 리사이즈 Offset 계산 $NC.G_OFFSET.nonClientHeight = $("#divConditionView").outerHeight() + $NC.G_LAYOUT.nonClientHeight; } function _OnResize(parent) { var clientWidth = parent.width() - $NC.G_LAYOUT.border1; var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight; $NC.resizeContainer("#divMasterView", clientWidth, clientHeight); $NC.resizeGrid("#grdMaster", clientWidth, $("#grdMaster").parent().height() - $NC.G_LAYOUT.header); } function _OnConditionChange(e, view, val) { var id = view.prop("id").substr(4).toUpperCase(); switch (id) { case "CENTER_CD": break; case "BU_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { P_QUERY_PARAMS = { P_USER_ID: $NC.G_USERINFO.USER_ID, P_BU_CD: val }; O_RESULT_DATA = $NP.getUserBuInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onUserBuPopup(O_RESULT_DATA[0]); } else { $NP.showUserBuPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onUserBuPopup, onUserBuPopup); } return; case "BRAND_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { var BU_CD = $NC.getValue("#edtQBu_Cd"); P_QUERY_PARAMS = { P_BU_CD: BU_CD, P_BRAND_CD: val }; O_RESULT_DATA = $NP.getBuBrandInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onBuBrandPopup(O_RESULT_DATA[0]); } else { $NP.showBuBrandPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onBuBrandPopup, onBuBrandPopup); } return; } onChangingCondition(); } function _Inquiry() { var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); if ($NC.isNull(CENTER_CD)) { alert("물류센터를 선택하십시오."); $NC.setFocus("#cboQCenter_Cd"); return; } var BU_CD = $NC.getValue("#edtQBu_Cd"); if ($NC.isNull(BU_CD)) { alert("사업부를 입력하십시오."); $NC.setFocus("#edtQBu_Cd"); return; } var END_DATE = $NC.getValue("#edtQEnd_Date"); if ($NC.isNull(END_DATE)) { alert("마감일자를 입력하십시오."); $NC.setFocus("#edtQEnd_Date"); return; } var BRAND_CD = $NC.getValue("#edtQBrand_Cd", true); var ITEM_CD = $NC.getValue("#edtQItem_Cd"); var ITEM_NM = $NC.getValue("#edtQItem_Nm"); $NC.setInitGridVar(G_GRDMASTER); $NC.setInitGridData(G_GRDMASTER); $NC.setGridDisplayRows("#grdMaster", 0, 0); G_GRDMASTER.queryParams = $NC.getParams({ P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD, P_END_DATE: END_DATE, P_BRAND_CD: BRAND_CD, P_ITEM_CD: ITEM_CD, P_ITEM_NM: ITEM_NM }); $NC.serviceCall("/LF08010Q/getDataSet.do", $NC.getGridParams(G_GRDMASTER), onGetMaster); } function _New() { } function _Save() { } function _Delete() { } function _Cancel() { } function _Print(printIndex, printName) { } function grdMasterOnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "END_DATE", field: "END_DATE", name: "마감일자", minWidth: 90, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "LOCATION_CD", field: "LOCATION_CD", name: "로케이션", minWidth: 140, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "BRAND_CD", field: "BRAND_CD", name: "브랜드코드", minWidth: 90, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "BRAND_NM", field: "BRAND_NM", name: "브랜드명", minWidth: 120 }); $NC.setGridColumn(columns, { id: "ITEM_CD", field: "ITEM_CD", name: "상품코드", minWidth: 90 }); $NC.setGridColumn(columns, { id: "ITEM_NM", field: "ITEM_NM", name: "상품명", minWidth: 180 }); $NC.setGridColumn(columns, { id: "ITEM_SPEC", field: "ITEM_SPEC", name: "규격", minWidth: 90 }); $NC.setGridColumn(columns, { id: "ITEM_STATE", field: "ITEM_STATE", name: "상품상태", minWidth: 60 }); $NC.setGridColumn(columns, { id: "ITEM_LOT", field: "ITEM_LOT", name: "LOT번호", minWidth: 100 }); $NC.setGridColumn(columns, { id: "STOCK_DATE", field: "STOCK_DATE", name: "재고입고일자", minWidth: 100, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "STOCK_QTY", field: "STOCK_QTY", name: "재고수량", minWidth: 100, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "HOLD_YN", field: "HOLD_YN", name: "보류여부", minWidth: 60 }); $NC.setGridColumn(columns, { id: "REMARK1", field: "REMARK1", name: "비고", minWidth: 200 }); return $NC.setGridColumnDefaultFormatter(columns); } function grdMasterInitialize() { var options = { frozenColumn: 4 }; $NC.setInitGridObject("#grdMaster", { columns: grdMasterOnGetColumns(), queryId: "LF08010Q.RS_MASTER", sortCol: "", gridOptions: options }); } function grdMasterOnAfterScroll(e, args) { var row = args.rows[0]; if (G_GRDMASTER.lastRow != null) { if (row == G_GRDMASTER.lastRow) { e.stopImmediatePropagation(); return; } } $NC.setGridDisplayRows("#grdMaster", row + 1); } function onGetMaster(ajaxData) { $NC.setInitGridData(G_GRDMASTER, ajaxData); if (G_GRDMASTER.data.getLength() > 0) { if ($NC.isNull(G_GRDMASTER.lastKeyVal)) { $NC.setGridSelectRow(G_GRDMASTER, 0); } else { $NC.setGridSelectRow(G_GRDMASTER, { selectKey: new Array("ORDER_DATE", "ORDER_NO"), selectVal: G_GRDMASTER.lastKeyVal }); } } else { $NC.setGridDisplayRows("#grdMaster", 0, 0); } $NC.G_VAR.buttons._inquiry = "1"; $NC.G_VAR.buttons._new = "0"; $NC.G_VAR.buttons._save = "0"; $NC.G_VAR.buttons._cancel = "0"; $NC.G_VAR.buttons._delete = "0"; $NC.G_VAR.buttons._print = "0"; $NC.setInitTopButtons($NC.G_VAR.buttons); } function onChangingCondition() { $NC.clearGridData(G_GRDMASTER); $NC.G_VAR.buttons._inquiry = "1"; $NC.G_VAR.buttons._new = "0"; $NC.G_VAR.buttons._save = "0"; $NC.G_VAR.buttons._cancel = "0"; $NC.G_VAR.buttons._delete = "0"; $NC.G_VAR.buttons._print = "0"; $NC.setInitTopButtons($NC.G_VAR.buttons); } function showUserBuPopup() { $NP.showUserBuPopup({ P_USER_ID: $NC.G_USERINFO.USER_ID, P_BU_CD: "%" }, onUserBuPopup, function() { $NC.setFocus("#edtQBu_Cd", true); }); } function showBuBrandPopup() { var BU_CD = $NC.getValue("#edtQBu_Cd"); $NP.showBuBrandPopup({ P_BU_CD: BU_CD, P_BRAND_CD: "%" }, onBuBrandPopup, function() { $NC.setFocus("#edtQBrand_Cd", true); }); } function showVendorPopup() { } function onUserBuPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQBu_Cd", resultInfo.BU_CD); $NC.setValue("#edtQBu_Nm", resultInfo.BU_NM); $NC.setValue("#edtQCust_Cd", resultInfo.CUST_CD); } else { $NC.setValue("#edtQBu_Cd"); $NC.setValue("#edtQBu_Nm"); $NC.setValue("#edtQCust_Cd"); $NC.setFocus("#edtQBu_Cd", true); } onChangingCondition(); } function onBuBrandPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQBrand_Cd", resultInfo.BRAND_CD); $NC.setValue("#edtQBrand_Nm", resultInfo.BRAND_NM); } else { $NC.setValue("#edtQBrand_Cd"); $NC.setValue("#edtQBrand_Nm"); $NC.setFocus("#edtQBrand_Cd", true); } onChangingCondition(); } function onBtnCloseClick() { var result = confirm("일마감처리를 하시겠습니까?"); if (!result) { return; } var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); if ($NC.isNull(CENTER_CD)) { alert("물류센터를 선택하십시오."); $NC.setFocus("#cboQCenter_Cd"); return; } var CLOSE_DATE = $NC.getValue("#edtQEnd_Date"); if ($NC.isNull(CLOSE_DATE)) { alert("마감일자를 입력하십시오."); $NC.setFocus("#edtQEnd_Date"); return; } $NC.serviceCall("/LF08010Q/callSP.do", { P_QUERY_ID: "LS_DAYSTOCK_CREATION", P_QUERY_PARAMS: $NC.getParams({ P_CLOSE_DATE: CLOSE_DATE, P_CENTER_CD: CENTER_CD, P_USER_ID: $NC.G_USERINFO.USER_ID }) }, function() { alert("일마감처리가 완료되었습니다."); _Inquiry(); }); } function setPolicyValInfo() { $NC.G_VAR.policyVal.LI110 = ""; $NC.G_VAR.policyVal.LI420 = ""; var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); var BU_CD = $NC.getValue("#edtQBu_Cd"); for ( var POLICY_CD in $NC.G_VAR.policyVal) { $NC.serviceCall("/LF08010Q/callSP.do", { P_QUERY_ID: "WF.GET_POLICY_VAL", P_QUERY_PARAMS: $NC.getParams({ P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD, P_POLICY_CD: POLICY_CD }) }, onGetPolicyVal); } } function onGetPolicyVal(ajaxData) { var resultData = $NC.toArray(ajaxData); if (!$NC.isNull(resultData)) { if (resultData.O_MSG === "OK") { $NC.G_VAR.policyVal[resultData.P_POLICY_CD] = resultData.O_POLICY_VAL; if (resultData.P_POLICY_CD != "LI420") { return; } var policyVal = resultData.O_POLICY_VAL; G_GRDDETAIL.view.setColumns(grdDetailOnGetColumns(policyVal)); } } } function setProcessStateInfo() { $NC.G_VAR.stateFWBW.CONFIRM = ""; $NC.G_VAR.stateFWBW.CANCEL = ""; var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); var BU_CD = $NC.getValue("#edtQBu_Cd"); $NC.serviceCall("/LF08010Q/callSP.do", { P_QUERY_ID: "WF.GET_PROCESS_STATE_FWBW", P_QUERY_PARAMS: $NC.getParams({ P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD, P_PROCESS_GRP: "LI", P_PROCESS_CD: "A" }) }, onGetProcessState); } function onGetProcessState(ajaxData) { var resultData = $NC.toArray(ajaxData); if (!$NC.isNull(resultData)) { if (resultData.O_MSG === "OK") { $NC.G_VAR.stateFWBW.CONFIRM = $NC.nullToDefault(resultData.O_STATE_CONFIRM, ""); $NC.G_VAR.stateFWBW.CANCEL = $NC.nullToDefault(resultData.O_STATE_CANCEL, ""); } } }
var TableTable_Bang_BOSS = { map: function() { if (!this._map) this._map = pi.JsonLoader.getInstance().load_dict("map/Table_Bang_BOSS_Auto.js") if (!this._map) PILogE("Table_Bang_BOSS: load map fail"); return this._map; }, info: function(id) { var map = this.map(); if (!map) return null; var val = map[id]; if (!val) PILogE("Table_Bang_BOSS: id not found"); return val; }, getZijinLimitTotal: function(id) { var info = this.info(id); return info ? info["zijinLimitTotal"] : null; }, getYinLimitTotal: function(id) { var info = this.info(id); return info ? info["yinLimitTotal"] : null; }, getName: function(id, translate) { var info = this.info(id); if (!info) return; return translate ? _V(info["name"]) : info["name"]; }, getNeedProgress: function(id) { var info = this.info(id); return info ? info["needProgress"] : null; }, getIconId: function(id) { var info = this.info(id); return info ? info["iconId"] : null; }, getCardId: function(id) { var info = this.info(id); return info ? info["cardId"] : null; }, getRewardYin: function(id) { var info = this.info(id); return info ? info["rewardYin"] : null; }, getImageId: function(id) { var info = this.info(id); return info ? info["imageId"] : null; }, getName2: function(id, translate) { var info = this.info(id); if (!info) return; return translate ? _V(info["name2"]) : info["name2"]; }, getBlood: function(id) { var info = this.info(id); return info ? info["blood"] : null; }, getYinLimitOnce: function(id) { var info = this.info(id); return info ? info["yinLimitOnce"] : null; }, getTime: function(id) { var info = this.info(id); return info ? info["time"] : null; }, getMoreZijin: function(id) { var info = this.info(id); return info ? info["moreZijin"] : null; }, getCD: function(id) { var info = this.info(id); return info ? info["CD"] : null; }, getRewardZijin: function(id) { var info = this.info(id); return info ? info["rewardZijin"] : null; }, getNpcHeroRefIdList: function(id) { var info = this.info(id); return info ? info["npcHeroRefIdList"] : null; }, _map : null, _cache_sign : null, _cache_mark : null, _cache_name : null }
import axios from 'axios' const axiosInstance = axios.create({ baseURL: '' }); // attach the API_KEY with every request axiosInstance.interceptors.request.use((config) => { config.params = { ...config.params, } return config }, (error) => { return Promise.reject(error) }) export default axiosInstance
require('dotenv').config(); const fs = require('fs').promises; const path = require('path'); const { Client } = require('pg'); const tableNames = ['users', 'boards', 'lists', 'cards']; module.exports = async function createTables() { const client = new Client({ database: 'reflect' }); client.on('error', console.error); try { await client.connect(); for (const tableName of tableNames) { const sqlPath = path.join(__dirname, 'tables', `${tableName}.sql`); const sql = await fs.readFile(sqlPath, 'utf8'); await client.query(sql); } } catch (e) { console.error(e); } finally { await client.end(); } };
'use strict'; function is_repeat_number(element, index, array){ /* 和其之后的元素进行比较,如果有一样的就直接返回false */ for(var i = index + 1; i < array.length; i++){ if(array[i] == element){ return false; } } return true; } function choose_no_repeat_number(collection) { //在这里写入代码 var result = collection.filter(is_repeat_number); return result; } module.exports = choose_no_repeat_number;
//toEqual const data = { name: 'Orinami', lastname: 'Olatunji' }; test('Object Assignment', () => { expect(data).toEqual({name: 'Orinami', lastname: 'Olatunji'}); }); // For truthiness test('null', () => { const n = null; expect(n).toBeNull(); expect(n).toBeDefined(); expect(n).not.toBeUndefined(); }); test('zero', () => { const zero = 0; expect(zero).not.toBeNull(); expect(zero).toBeDefined(); expect(zero).not.toBeUndefined(); }); // For Numbers const sum = 5 + 6; test('five + six', () => { expect(sum).toBeGreaterThan(10); expect(sum).toBeGreaterThanOrEqual(11); expect(sum).toBeLessThan(12); expect(sum).toBeLessThanOrEqual(11); }); //toContain - For arrays const languages = [ 'JavaScript', 'PHP', 'Ruby', ]; test('languages contains JavaScript', () => { expect(languages).toContain('JavaScript'); }); //toMatch - For strings test('g in programmer', () => { expect('Programmer').toMatch(/g/); });
import React from "react"; import "./FileInput.scss"; import { useState } from "react"; import { useRef } from "react"; function FileInput({ handleUpload, children, preview }) { const [filename, setFilename] = useState(null); const inputRef = useRef(); const handleFileChange = (e) => { if (e.target.files.length) { const file = e.target.files[0]; setFilename(file.name); handleUpload(file); } }; const handleClick = () => { inputRef.current.click(); }; return ( <div className="file-input"> <label onClick={handleClick}>{children}</label> <input type="file" ref={inputRef} onChange={handleFileChange} /> {preview && filename && <div className="preview">{filename}</div>} </div> ); } export default FileInput;
define(function(require, exports, module) { var case_com = require('../../sub/upload/case_com'); var com = require('../../sub/upload/upload_com'); var relatedInput = require('../../lib/plugin/form/relatedInput'); var formcheck = require('../../lib/plugin/form/formCheck'); var request = require('../../lib/http/request'); var temp = '<li class="pic_list" script-role="self_list">'+ '<dl>'+ '<dt>'+ '<img src="" width="97" height="93" / script-role="self_type_image">'+ '</dt>'+ '<dd>'+ '<p class="pt_5 pb_5" script-role="self_type"></p>'+ '<p>'+ '<span script-role="self_detail"></span>'+ '<span script-role="self_square"></span>'+ '</p>'+ '</dd>'+ '</dl>'+ '</li>'; /* 获取装修项目 */ (function(){ var oSelect, target, oCreate; oSelect = $('[script-role = project]'); target = '/index.php/view/project/getlist'; oCreate = $('[script-role = create_inspir]'); com.checkCreate(oSelect, oCreate, 'show'); com.getSelectData(oSelect, target, null, function(data){ com.renderOption(oSelect, data.data, 'project_id', 'project_name', '创建装修项目', 'check'); }, function(name, id ,url){ if(url) { window.location = url; } else { com.checkCreate(oSelect, oCreate, 'show', '创建装修项目'); } }, '创建装修项目'); })(); /* 获取省市 */ (function(){ var oProvince, oCity, sProvinceUrl, sChangeUrl, sStartId; oProvince = $('[script-role = province]'); oCity = $('[script-role = city]'); sProvinceUrl = '/index.php/view/project/getarea'; sChangeUrl = '/index.php/posts/userset/getdistrict'; com.getSelectData(oProvince, sProvinceUrl, null, function(data){ com.renderOption(oProvince, data.data.province, 'district_code', 'district_name'); com.renderOption(oCity, data.data.city, 'district_code', 'district_name'); }, function(name, id){ com.getSelectData(oProvince, sChangeUrl, {district_pcode: id}, function(data){ com.renderOption(oCity, data.data, 'district_code', 'district_name'); }); }); })(); /* 上传 */ (function(){ var oList, oImage, oType, oDetail, oSquare, realData, oRg; com.upload({ sRole: 'upload_btn_area', sId: 'upload_btn_area', temp: temp, width: 164, height: 111, btnClass: 'case2', btnbg: 'url("/static/images/lib/button/button.png") no-repeat -341px -321px', target: '/index.php/upload/apartment', queueId: 'step1_list', addWay : 'prepend', queueSizeLimit : 1, onStart: function() { if(oList)oList.remove(); }, onSelectErr: function() { alert('户型图只限上传一张'); }, onsuc: function(file, data) { oList = $('[script-role = self_list]'); oImage = $('[script-role = self_type_image]'); realData = eval('('+ data +')'); if(!realData.err) { oImage.attr('src', realData.data); } else { oList.remove(); alert(realData.msg); } } }); })(); /* 联想楼盘名称 */ (function(){ var oProvince, oCity, sProvince, sCity, oBuild, oType, sGetUrl, newJson, oUl, oSquare; oType = $('[script-role = house_type]'); oProvince = $('[script-role = province]'); oCity = $('[script-role = city]'); sGetUrl = '/index.php/view/apartment/typelist'; oUl = $('[script-role = list_wrap]'); oSquare = $('[script-role = squre]'); oBuild = $('[script-role = building_name]'); selectList(oUl); oBuild.attr('house_id', ''); var related = new relatedInput({ oWrap: $('[script-role = building_name]'), postName: 'house', url: '/index.php/view/house/getlist', onchange: function(param) { param.house_city = oCity.get(0).options[oCity.get(0).selectedIndex].id; }, getValue: function(oLi,oInput) { //oInput.attr('house_id', oLi.attr('id')); }, fnDo: function(data, oWrap) { var i, num, oLi; num = data.data.length; for(i=0; i<num; i++) { oLi = $('<li id='+ data.data[i].house_id +'><span></span></li>'); oLi.children(0).html(data.data[i].house_name); oWrap.append(oLi); } }, blur: function(sName, aLi, oInput) { var result = false; if(aLi.length) { aLi.each(function(i){ if(aLi.eq(i).text() == sName) { oInput.attr('house_id', aLi.eq(i).attr('id')); result = true; } }); if(!result) { oInput.attr('house_id', ''); if($('[script-role = sys_list]')) $('[script-role = sys_list]').remove(); oType.get(0).selectedIndex = 0; } } } }); /* 选择户型 */ com.getSelectData(oType, sGetUrl, newJson, function(data){ com.renderOption(oType, data.data, 'tag_id', 'tag_name', null, 'check'); },function(name, id){ var newJson = {}; newJson.tag_id = id; newJson.house_id = oBuild.attr('house_id'); makeList(newJson); }); related.addEvent(); function makeList(param) { var i, num, html, tId, oLi, realData; sUrl = '/index.php/view/apartment/getfloorpic'; tId = 'case1_uploadList'; if(!param.house_id)return; request({ url: sUrl, data: param, sucDo: function(data) { if($('[script-role = sys_list]')) $('[script-role = sys_list]').remove(); realData = data.data; num = realData.length; for(i=0; i<num; i++) { oLi = $('<li class="pic_list" script-role="sys_list" apartment_id='+ realData[i].apartment_id +'></li>'); oLi.get(0).innerHTML = '<dl>'+ '<dt>'+ '<img src="' + realData[i].apartment_floor_pic1 + '" width="97" height="93" / script-role="type_image">'+ '</dt>'+ '<dd>'+ '<p class="pt_5 pb_5" script-role="type">' + realData[i].apartment_category + '</p>'+ '<p>'+ '<span script-role="detail">'+ realData[i].apartment_title +'</span>'+ '<span script-role="square">'+ realData[i].apartment_size +'</span>'+ '</p>'+ '</dd>'+ '</dl>'; oUl.prepend(oLi); } } }); } function selectList(oWrap) { var nSquare; oWrap.on('click', '[script-role = sys_list]', function(){ $(this).addClass('actb').siblings().removeClass('actb'); nSquare = parseInt($(this).find('[script-role = square]').text()); oSquare.attr('readonly', 'readonly'); oSquare.val(nSquare); }); oWrap.on('click', '[script-role = self_list]', function(){ $('[script-role = sys_list]').removeClass('actb'); $(this).addClass('actb'); oSquare.val(''); oSquare.removeAttr('readonly'); }); } })(); /* makeName */ (function(){ var oProvince, oCity, oHouse, oType, oSquare, oName, oProjectName, sName, fps; oProvince = $('[script-role = province]'); oCity = $('[script-role = city]'); oHouse = $('[script-role = building_name]'); oType = $('[script-role = house_type]'); oSquare = $('[script-role = squre]'); oName = $('[script-role = namespace]'); oProjectName = $('[script-role = project_name]'); fps = 1000; setInterval(getName,fps); function getName() { sName = oProvince.val() + '+' + oCity.val() + '+' + (oHouse.val() ? oHouse.val() : '楼盘名称') + '+' + (oType.val() ? oType.val() : '户型名称') + '+' + (oSquare.val() ? oSquare.val() : '面积') + '+' + (oName.val() ? oName.val() : '客户称谓'); oProjectName.html(sName); } })(); (function(){ var result = false; var oFormcheck = new formcheck({ subUrl: '/index.php/posts/project/addproject', btnName: 'upload_confirm_btn', boundName: 'step1_check', fnSumbit: function(data) { data.project_status = data.project_status == '1' ? '1' : '2'; data.house_city = $('[script-role = city]').get(0).options[$('[script-role = city]').get(0).selectedIndex].id; data.house_id = $('[script-role = building_name]').attr('house_id') ? $('[script-role = building_name]').attr('house_id') : '0'; data.house_name = $('[script-role = building_name]').attr('house_id') ? '' : $('[script-role = building_name]').val(); data.apartment_category_id = $('[script-role = house_type]').get(0).options[$('[script-role = house_type]').get(0).selectedIndex].id; data.apartment_id = $('[script-role = list_wrap]').find('li.actb').attr('apartment_id') ? $('[script-role = list_wrap]').find('li.actb').attr('apartment_id') : ''; data.apartment_floor_pic = $('[script-role = list_wrap]').find('li.actb').attr('apartment_id') ? '' : $('[script-role = list_wrap]').find('li.actb').find('img').attr('src').replace(/\/uploads\/temp\/apartment\//,''); }, sucDo: function(data) { window.location = data.data.url; }, failDo: function(msg) { alert(msg); var sUrl = window.location; window.location = sUrl; }, otherCheck: { 'tag_namelist' : [ function() { var stepList = $('[script-role = list_wrap]').children(); stepList.each(function(i){ if(stepList.eq(i).hasClass('actb')) { result = true; } }); if(result) { return true; } else { return false; } }, function() { return true; } ] } }); oFormcheck.check(); })(); });
app.listen(3000, ()=>{console.log('server is running...')});
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class card extends Component { constructor(props) { super(); this.preco = parseInt(props.preco); this.nome = props.nome; this.src = props.src || "http://www.crispel.com.br/uProdutos/CdcPZJKTAP/CdcPZJKTAP_800_.jpg"; } formatPrice(valor) { return "R$ " + valor.toFixed(2); } render() { return ( <div className="col-md-3 col-sm-6 p-3"> <div className="card text-center" > <div className="card-block box shadow" > <div className="card-title"> <h4 className="card-title-text">{this.nome}</h4> </div> <img src={this.src} className="img-fluid" width="110px" /> <div className="card-text"> Preço: {this.formatPrice(this.preco)} <br /> <a styles="margin-top: 10px;" href="#" className="btn btn-primary">Ver mais</a> </div> </div> </div> </div> ); } } export default card;
import styled from 'styled-components' import Close from '../svg/cancel.svg' const Alert = ({msg, color}) => { return ( <Wrapper color={color}> <CloseBtn> <Close /> </CloseBtn> {msg} </Wrapper> ) } const Wrapper = styled.div(props => ({ background: props.color, width: "100%", height: "53px", marginBottom: "14px", borderRadius: "4px", boxShadow: "0px 4px 16px rgba(102, 102, 102, 0.15)", display: "flex", justifyContent: "flex-end", alignItems: "center", position: "relative", })) const CloseBtn = styled.div` width: 25px; height: 25px; position: absolute; left: 3%; ` export default Alert
import React from 'react'; import '../../App.scss'; import {Tables} from "../table/tables" import {Button, Card} from 'antd'; const axios = require('axios'); const cardDivStyle = { padding: "30px", } const cardStyle = { width: "100%", border: "2px solid grey", borderRadius: "5px" } const cardContent = { display: "flex", justifyContent: "space-evenly" } export default class Findcontainer extends React.Component{ constructor(props) { super(props); this.state = { result : [], lpnLocation: {}, ilpn: '' }; this.columns = [ { title: 'LPN', dataIndex: 'ilpn', key: 'ilpn', }, { title: 'Submit', dataIndex: 'submit', key: 'submit', render: (text, record) => ( <Button type="primary" onClick={(e) => { this.onFind(record, e)}}> Find </Button> ) } ]; this.onFind = this.onFind.bind(this); } onFind(record,e){ e.preventDefault(); this.setState({ilpn: record.ilpn}, ()=>{ axios.post('/users/findparticularcontainer',{ilpn: this.state.ilpn}) .then(result => { this.setState( {lpnLocation: result.data} ,()=>{console.log(this.state.lpnLocation)}); }) }) } componentDidMount() { // Your axios request here axios.post('/users/findbox') .then(res => { console.log(res.data); let result = res.data; this.setState( {result}); }) } render() { return( <div className="site-layout-content"> Find Container <Tables dataSource = {this.state.result} columns = {this.columns}/> {this.state.ilpn && <div style = {cardDivStyle}> <Card title="Details" bordered={true} style={cardStyle}> <div style={cardContent}> <div> <label style={{marginRight:"1em"}}>LPN:</label> <label style={{marginRight:"10em"}}>{this.state.lpnLocation.ilpn}</label> </div> <div> <label style={{marginRight:"1em"}}>Location:</label> <label style={{marginRight:"10em"}}>{this.state.lpnLocation.Found_location}</label> </div> </div> </Card> </div>} </div> ) } }
// Book Class class Book { constructor(title, author, numOfPages, isRead) { this.title = title; this.author = author; this.numOfPages = numOfPages; this.isRead = isRead; } } class Store { static getBook() { let myLibrary; if(localStorage.getItem('books') === null) { myLibrary = []; } else { myLibrary = JSON.parse(localStorage.getItem('books')); } return myLibrary; } static displayBook() { const books = Store.getBook(); books.forEach(function(book) { // Instantiate UI const ui = new UI(); ui.addBookToList(book); }); } static addBook(book) { const books = Store.getBook(); books.push(book); localStorage.setItem('books', JSON.stringify(books)); } static removeBook(bookInd) { const books = Store.getBook(); bookInd = bookInd -1; books.forEach(function(book, index) { if(books.indexOf(book) == bookInd) { books.splice(index, 1); } }); localStorage.setItem('books', JSON.stringify(books)); } static toggleRead(bookInd) { const books = Store.getBook(); books[bookInd - 1].isRead = !(books[bookInd - 1].isRead); localStorage.setItem('books', JSON.stringify(books)); } } class UI { // Read button static read(isRead) { return isRead ? `<button type="button" class="btn btn-sm btn-light">Read</button>` : `<button type="button" class="btn btn-sm btn-dark">Not Read</button>`; } addBookToList(book) { // Create a book list div bookIndex++; const bookList = document.createElement('div'); bookList.className = 'jumbotron py-3'; bookList.innerHTML = '<a class="float-right"><span class="text-dark">&times;</span></a>'; bookList.innerHTML += `<h4>${book.title}</h4>`; bookList.innerHTML += `<p class="lead">By ${book.author} <span class="text-muted float-right">${book.numOfPages} Pg.</span></p>`; bookList.innerHTML += UI.read(book.isRead); bookList.setAttribute('data-attribute', String(bookIndex)); document.querySelector('.list-group').appendChild(bookList); } clearField() { document.querySelector('#author').value = ''; document.querySelector('#title').value = ''; document.querySelector('#pages').value = ''; } removeBookFromList(target) { if(confirm('Are you sure you want to delete book?')) { target.parentElement.parentElement.remove(); } } toggleReadBtn(target) { if(target.textContent === 'Read') { target.textContent = 'Not Read'; target.classList.remove('btn-light'); target.classList.add('btn-dark'); } else { target.textContent = 'Read'; target.classList.remove('btn-dark'); target.classList.add('btn-light'); } Store.toggleRead(target.parentElement.getAttribute('data-attribute')); } } let bookIndex = 0; // EventListeners // DOM load event document.addEventListener('DOMContentLoaded', Store.displayBook); // Add book event listener document.querySelector('#addBook').addEventListener('click', function() { const author = document.querySelector('#author'), title = document.querySelector('#title'), pages = document.querySelector('#pages'), readOption = document.querySelector('#isRead'); if(title.value !== '' && author.value !== '' && pages.value !== '' && readOption.value !== '') { // Instantiate book const book = new Book(title.value, author.value, pages.value, readOption.value === 'true' ? true : false); // Instantiate UI const ui = new UI(); // Add book to list ui.addBookToList(book); // Add Book to LS Store.addBook(book); // clear input fields ui.clearField(); } else { alert('Please input all fields'); } }); document.querySelector('.list-group').addEventListener('click', function(e) { // Remove book event listener if(e.target.parentElement.classList.contains('float-right')) { // Instantiate UI const ui = new UI(); // Remove book from list ui.removeBookFromList(e.target); // Remove book from LS Store.removeBook(e.target.parentElement.parentElement.getAttribute('data-attribute')); } // Toggle read button if(e.target.classList.contains('btn')) { // Instantiate UI const ui = new UI(); // Toggle button ui.toggleReadBtn(e.target); } });
import React from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import Btn from '../../reuse/Btn'; import * as appActionsTypes from '../../actions/AppActions'; // import trigger_print from '../../helpers/trigger_print'; const Content3 = (props) => { const { estimate, appActions, } = props; const { cancel, } = appActions; return ( <div className='content_3'> <div className='content_3_estimate_title'>Примерное время ожидания составит:</div> <div className='content_3_circle'> <div className='content_3_circle_content'> <div className='content_3_circle_number'>{estimate}</div> <div className='content_3_circle_text'>{estimate > 1 ? 'месяца' : 'месяц'}</div> </div> </div> <div className='content_3_estimate_title'>Рекомендации для уменьшения срока ожидания:</div> <div className='content_3_recomendations'> <div>- Уменьшите сумму и срок займа;</div> <div>- Увеличьте первоначальный и ежемесячный взносы</div> <div>- Учавствуйте в специальных акциях для Пайщиков.</div> </div> <div className='content_3_bnt_block'> <Btn title='перерасчет' type='grey' handleClick={cancel} /> <Btn title='сохранить в pdf' type='crimson' // handleClick={trigger_print} /> </div> </div> ) }; const mapStateToProps = (state) => { const { estimate, } = state.app; return { estimate, } }; const mapDispatchToProps = (dispatch) => { return { appActions: bindActionCreators(appActionsTypes, dispatch), } }; export default connect(mapStateToProps,mapDispatchToProps)(Content3);
const TwingProfilerDumperText = require('../../../../../../lib/twing/profiler/dumper/text').TwingProfilerDumperText; const TwingTestMockBuilderProfile = require('../../../../../mock-builder/profiler/profile'); const tap = require('tap'); tap.test('text profiler dumper', function (test) { test.test('dump', function(test) { let dumper = new TwingProfilerDumperText(); test.matches(dumper.dump(TwingTestMockBuilderProfile.getProfile()), new RegExp(`main (\\d+)\\.(\\d+)ms\\/(\\d+)% └ index\\.twig (\\d+)\\.(\\d+)ms\\/(\\d+)% └ embedded\\.twig::block\\(body\\) └ embedded\\.twig │ └ included\\.twig └ index\\.twig::macro\\(foo\\) └ embedded\\.twig └ included\\.twig`)); test.end(); }); test.end(); });
import * as React from 'react'; import { Feather } from '@expo/vector-icons'; //Styling import colors from '../styles/colors'; export default function BottomTabIcon(props) { return ( <Feather name={props.name} size={30} color={props.focused ? colors.black : colors.grey} /> ); }
'use strict'; (function () { var setup = document.querySelector('.setup'); var form = setup.querySelector('.setup-wizard-form'); var wizards = []; var coatColor; var eyesColor; var getRank = function (wizard) { var rank = 0; if (wizard.colorCoat === coatColor) { rank += 2; } if (wizard.colorEyes === eyesColor) { rank += 1; } return rank; }; // функция для фильтрации данных var updateWizards = function () { window.render(wizards.sort(function (a, b) { if (getRank(b) === getRank(a)) { return b.name - a.name; } else { return getRank(b) - getRank(a); } })); }; window.wizard.onEyesChange = function (color) { eyesColor = color; window.debounce(updateWizards); }; window.wizard.onCoatChange = function (color) { coatColor = color; window.debounce(updateWizards); }; // обработчик успешной загрузки var successHandler = function (data) { wizards = data; updateWizards(); }; // обработчик ошибки var errorHandler = function (errMessage) { var node = document.createElement('div'); node.style = 'position: absolute; z-index: 110; color: white; font-size: 30px; text-align: center;'; node.style.backgroundColor = 'red'; node.style.width = '100%'; node.style.boxShadow = '-1px -1px 14px -3px black'; node.textContent = errMessage; form.insertBefore(node, form.querySelector('.setup-footer')); }; // получение данных с сервера window.backend.load(successHandler, errorHandler); // отправка формы на сервер form.addEventListener('submit', function (evt) { evt.preventDefault(); window.backend.save(new FormData(form), function () { setup.classList.add('hidden'); }, errorHandler); }); })();
const Messages = require("../../../models/Message"); module.exports = async ({ uuid }) => { try { await Messages.deleteOne({ uuid }); return null; } catch (error) { return error.message; } };
import { createApp } from 'vue' import App from './App.vue' import router from './router' import PrimeVue from 'primevue/config' import Button from 'primevue/button' import Dialog from 'primevue/dialog' import Sidebar from 'primevue/sidebar' import Column from 'primevue/column' import DataTable from 'primevue/datatable' import Accordion from 'primevue/accordion' import AccordionTab from 'primevue/accordiontab' import InputText from 'primevue/inputtext' import AutoComplete from 'primevue/autocomplete' import SplitButton from 'primevue/splitbutton' import Calendar from 'primevue/calendar' import FileUpload from 'primevue/fileupload' import Toolbar from 'primevue/toolbar' import Rating from 'primevue/rating' import Textarea from 'primevue/textarea' import Dropdown from 'primevue/dropdown' import RadioButton from 'primevue/radiobutton' import InputNumber from 'primevue/inputnumber' import ConfirmationService from 'primevue/confirmationservice' import ConfirmPopup from 'primevue/confirmpopup' import ToastService from 'primevue/toastservice' import MultiSelect from 'primevue/multiselect' import 'primeflex/primeflex.css' import 'primevue/resources/themes/saga-blue/theme.css' import 'primevue/resources/primevue.min.css' import 'primeicons/primeicons.css' const app = createApp(App) app.use(ConfirmationService) app.use(ToastService) app.use(PrimeVue) app.use(router) app.component('ConfirmPopup', ConfirmPopup) app.component('Dialog', Dialog) app.component('Button', Button) app.component('Column', Column) app.component('Sidebar', Sidebar) app.component('DataTable', DataTable) app.component('Accordion', Accordion) app.component('AccordionTab', AccordionTab) app.component('InputText', InputText) app.component('AutoComplete', AutoComplete) app.component('SplitButton', SplitButton) app.component('Calendar', Calendar) app.component('FileUpload', FileUpload) app.component('Toolbar', Toolbar) app.component('Rating', Rating) app.component('Textarea', Textarea) app.component('Dropdown', Dropdown) app.component('RadioButton', RadioButton) app.component('InputNumber', InputNumber) app.component('MultiSelect', MultiSelect) app.mount('#app')
import d3 from 'd3'; export const FULL_ARC = 2 * Math.PI; export function calculateQuota(fullQuota, usedQuota) { return usedQuota / fullQuota * FULL_ARC; } const focusedOrSelected = node => node.layout.focus || node.layout.selected; export function distributeNodes({master, nodes}, width, height) { const masterWidthFactor = 0.5; const masterHeightFactor = 0.5; const masterFn = d => { return { pid: 'master', x: width * masterWidthFactor, y: height * masterHeightFactor, r: d.r, fixed: d.fixed, master: true, }; }; const anyFocusedOrSelected = nodes.some(focusedOrSelected); const slaveFn = d => { return { pid: d.pid, r: focusedOrSelected(d) ? d.layout.r * 1.25 : d.layout.r, focusedOrSelected: d.layout.focus || d.layout.selected, frameworks: d.frameworks.map(f => ({id: f.name})), anyFocusedOrSelected, master: false, }; }; const masterAndNodes = [master.toJS()].concat(nodes.toJS()); return masterAndNodes.map(s => s.master ? masterFn(s) : slaveFn(s)); } export function saturateColor(color) { return d3.hsl(color).brighter(1.3).toString(); } export function onNodeFocus() { d3.select(this).select('circle').transition() .duration(500) .attr('r', d => d.r); } export function onNodeBlur() { d3.select(this).select('circle').transition() .duration(500) .attr('r', d => d.r); } function validNumbers(node, quadPoint) { return (node.x - quadPoint.x) !== 0 && (node.y - quadPoint.y) !== 0; } export function preventCollision(alpha, nodes) { const padding = 1.5; const maxRadius = 12; const quadtree = d3.geom.quadtree(nodes); return function quadCb(d) { let r = d.r + maxRadius + padding; const nx1 = d.x - r; const nx2 = d.x + r; const ny1 = d.y - r; const ny2 = d.y + r; quadtree.visit(function visitCb(quad, x1, y1, x2, y2) { if (quad.point && (quad.point !== d) && validNumbers(d, quad.point)) { let x = d.x - quad.point.x; let y = d.y - quad.point.y; let l = Math.sqrt(x * x + y * y); r = d.r + quad.point.r + padding; if (l < r) { l = (l - r) / l * alpha; d.x -= x *= l; d.y -= y *= l; quad.point.x += x; quad.point.y += y; } } return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1; }); }; }
var canvas; var allSprite = new Image(); var spriteNumber = 0; var time; var size = 100; function init(){ canvas = document.getElementById('canvas'); ctx = canvas.getContext('2d'); allSprite.src = './images/coin-sprite-animation.png'; time = window.requestAnimationFrame(renderNextSprite); } function renderNextSprite(){ pausecomp(200); spriteNumber +=1; if(spriteNumber > 9){ // 10 different sprites spriteNumber = 0; } console.log(spriteNumber); ctx.clearRect(0,0,size,size); ctx.drawImage(allSprite, spriteNumber*size, 0, size, size,0,0,size, size); window.requestAnimationFrame(renderNextSprite); } function pausecomp(millis){ var date = new Date(); var curDate = null; do{ curDate = new Date(); }while(curDate-date<millis); }
import { comp2 } from './comp2.js'; // $.get('component2-comp.html', function (data) { // //console.log(data); // }); var vm1 = new Vue({ el: '#app1', data: { message: 'welcome to vuejs', show:false }, methods:{ doClick(){ alert('doClick'); } } });
$('.language span').click( function () { $(this).addClass('on').siblings().removeClass('on'); }); $('.btn').click( function () { $('.search').show(); }); $('.en').hide(); $('#en').click(function(){ $('.cn').hide(); $('.en').show(); }); $('#zn').click(function(){ $('.cn').show(); $('.en').hide(); });
const initialCategories = [ { name: "Marvel", description: "Categoría Marvel", }, { name: "DC Comics", description: "Categoría DC Comics", }, { name: "Avengers", description: "Categoría Avengers", }, { name: "X-Men", description: "Categoría X-Men", }, { name: "Fantastic Four", description: "Categoría Fantastic Four", }, { name: "Justice League", description: "Categoría Justice League", }, { name: "Legend", description: "Categoría Legend", }, { name: "Young Titans", description: "Categoría Young Titans", }, ]; const initialProducts = [ { name: "Captain America", description: "Captain America", price: 75, imagen: "https://inst-1.cdn.shockers.de/hs_cdn/out/pictures/master/product/1/avengers-endgame-captain-america-funko-pop-figur-37039.jpg", stock: 0, }, { name: "Captain Marvel", description: "Carol Danvers", price: 60, imagen: "https://s1.thcdn.com/productimg/1600/1600/12219168-2454704917695557.jpg", stock: 10, }, { name: "Iron Man", description: "Iron Man, alias Tony Stark", price: 95, imagen: "https://tienda.stripmarvel.com/wp-content/uploads/2020/02/x_fk47756.jpg", stock: 10, }, { name: "Incredible Hulk", description: "Hulk, alias Bruce Banner", price: 55, imagen: "https://deepsanddeeps.com/media/catalog/product/cache/3/image/750x750/9df78eab33525d08d6e5fb8d27136e95/d/e/deeps-and-deeps-funko-pop-avengers-age-of-ultron-el-increible-hulk--foto-completa-4776.jpg", stock: 10, }, { name: "Wolverine", description: "Wolverine, alias Logan", price: 150, imagen: "https://funkollection.es/wp-content/uploads/2019/10/img_159639_b8aa192ff58a991a1d18178ac1b44081_1.jpg", stock: 4, }, { name: "Mystique", description: "Mystique, alias Raven", price: 99, imagen: "https://d26lpennugtm8s.cloudfront.net/stores/841/670/products/mystique-638-sola1-a41fb9cc88b2a20a3416016884983272-1024-1024.jpg", stock: 10, }, { name: "The Rock", description: "The Rock", price: 120, imagen: "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRAVZrXeMzx71HvELEyL9IyVrt_kLZnZjGLJA&usqp=CAU", stock: 10, }, { name: "Invisible Woman", description: "Invisible Woman", price: 180, imagen: "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQPj9Fovd3ueQ44hVdQ-D8_hglvW11RhoxQqA&usqp=CAU", stock: 10, }, { name: "Superman", description: "Superman", price: 45, imagen: "https://i5.walmartimages.com/asr/57ecbd76-8180-478a-b16e-b4d3c8235c26.9fb16ef98d7033d4c4c51765ebcfc72d.png", stock: 10, }, { name: "Batman Kryptonite Suit", description: "Batman Kryptonite Suit (Batman vs Superman)", price: 70, imagen: "https://i5.walmartimages.com/asr/c736dd92-c8c9-4b6f-9f0e-1963111de155_1.ff6517eacfd8aae94d837d5d0a911d64.jpeg?odnWidth=612&odnHeight=612&odnBg=ffffff", stock: 10, }, { name: "Batman Grim Knight", description: "Batman Grim Knight", price: 89, imagen: "https://http2.mlstatic.com/funko-pop-heroes-batman-arkham-knight-batman-71-D_Q_NP_958692-MLA40973694734_032020-F.webp", stock: 10, }, { name: "Wonder Woman", description: "Wonder Woman", price: 105, imagen: "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTxH10sds60X5PTPIGqJ_Xi2sEnVy9Bdo5MKw&usqp=CAU", stock: 10, }, { name: "White Canary", description: "White Canary alias Sara Lance", price: 400, imagen: "https://hottopic.scene7.com/is/image/HotTopic/10720103_av1?$pdp_hero_large$", stock: 10, }, ]; const categoryProducts = [ { categoryId: 1, productId: 1 }, { categoryId: 1, productId: 2 }, { categoryId: 1, productId: 3 }, { categoryId: 1, productId: 4 }, { categoryId: 1, productId: 5 }, { categoryId: 1, productId: 6 }, { categoryId: 1, productId: 7 }, { categoryId: 1, productId: 8 }, { categoryId: 2, productId: 9 }, { categoryId: 2, productId: 10 }, { categoryId: 2, productId: 11 }, { categoryId: 2, productId: 12 }, { categoryId: 2, productId: 13 }, { categoryId: 3, productId: 1 }, { categoryId: 3, productId: 2 }, { categoryId: 3, productId: 3 }, { categoryId: 3, productId: 4 }, { categoryId: 4, productId: 5 }, { categoryId: 4, productId: 6 }, { categoryId: 5, productId: 7 }, { categoryId: 5, productId: 8 }, { categoryId: 6, productId: 9 }, { categoryId: 6, productId: 10 }, { categoryId: 6, productId: 11 }, { categoryId: 6, productId: 12 }, { categoryId: 7, productId: 13 }, ]; let initialUsers = [ /* { id: -1, username: "Guest", fullname: "Invitado", email: "guest@funkos.com", phone: "123456789", address: "Av siempre viva 123", state: "Argentina", isAdmin: false, password: "password" }, */ { username: "Ele", fullname: "Elena Gonzalez", email: "ele@admin.com", phone: "123456789", address: "Av siempre viva 123", state: "Argentina", isAdmin: true, password: "password" }, { username: "Panchito", fullname: "Francisco Gonzalez", email: "pancho@admin.com", phone: "123456789", address: "Av siempre viva 123", state: "Argentina", isAdmin: false, password: "SoyPancho" }, { username: "Homero", fullname: "Homero Simpson", email: "homero@admin.com", phone: "123456789", address: "Av siempre viva 123", state: "Argentina", isAdmin: false, password: "LisaNecesitaFrenos" } ]; let initialOrders = [ { total: 1000, state: "cart", userId: 1 }, { total: 2000, state: "created", userId: 1 }, { total: 1000, state: "processing", userId: 1 }, { total: 1000, state: "canceled", userId: 1 }, { total: 1000, state: "completed", userId: 1 }, { total: 1000, state: "cart", userId: 2 }, { total: 1000, state: "canceled", userId: 2 }, { total: 1000, state: "cart", userId: 3 }, { total: 1000, state: "canceled", userId: 3 }, { total: 1000, state: "completed", userId: 3 }, ] let initialOrderlines = [ { productId: 3, orderId: 1, quantity: 6, price: 50, subtotal: 300 }, { productId: 2, orderId: 1, quantity: 3, price: 20, subtotal: 60 }, { productId: 5, orderId: 2, quantity: 7, price: 25, subtotal: 175 }, { productId: 7, orderId: 2, quantity: 5, price: 100, subtotal: 500 }, { productId: 12, orderId: 3, quantity: 3, price: 300, subtotal: 900 }, { productId: 11, orderId: 3, quantity: 1, price: 50, subtotal: 50 }, { productId: 2, orderId: 3, quantity: 2, price: 20, subtotal: 40 }, ] let initialRates = [ { id: 1, qualification: 1, // wolverine description: 'un capo el logan se la re banca quien pudiera tener adamantium en el cuerpo', prodId: 5, userId: 1, } ] module.exports = { initialCategories, initialProducts, categoryProducts, initialUsers, initialOrders, initialOrderlines, };
Meteor.methods({ editTeamProfile: function(){ } });
var communityId=window.parent.document.getElementById("community_id_index").value; var mapTryOut={}; var mapTryOut =window.parent.mapTryOut; var clickObj=window.parent.clickObj; function testTop(clickNum,clickObc) { for ( var key in clickObj) { var value = key.replace(/[^0-9]/ig,""); var biao=""; if(value==1){ var obj=clickObj[key]; var obj2=clickObj["this_data1"]; var clickAddNum=(clickNum-obj2.clickNum); var clickAddUser=clickObc.clickUser-obj2.clickUser; var clickAddTest=clickObc.testClick-obj2.testClick; var clickAddUserTest=clickObc.testClickUser-obj2.testClickUser; var clickAdd=clickObc.click-obj2.click; biao=key.replace(/[0-9]/ig,""); if("this_data"==biao||"this_week"==biao||"this_month"==biao||"total_id"==biao){ var usList=new Array(); var usList2=new Array(); usList=obj.clickUserList; usList2=clickObc.clickUserList; usList=usList.concat(usList2); if(usList.length>1){ usList=unique3(usList); } var clickNumTop= parseInt(obj.clickNum)+parseInt(clickAddNum); var clickTop= parseInt(obj.click)+parseInt(clickAdd); var clickBi=0; if(clickNumTop>0){ clickBi=(clickTop/clickNumTop)*100; } document.getElementById(biao).innerHTML= parseInt(obj.click)+parseInt(clickAdd); document.getElementById(biao+"_user").innerHTML=parseInt(obj.clickUser)+parseInt(clickAddUser); document.getElementById(biao+"_test").innerHTML="("+(parseInt(obj.testClick)+ parseInt(clickAddTest))+")"; document.getElementById(biao+"_user_test").innerHTML="("+ (parseInt(obj.testClickUser)+ parseInt(clickAddUserTest))+")"; }else{ biao=key.replace(/[0-9]/ig,""); if(obj.click==0){ document.getElementById(biao).innerHTML="(无明细["+obj.total+"])"; }else{ document.getElementById(biao).innerHTML=obj.click; } document.getElementById(biao+"_user").innerHTML=obj.clickUser; document.getElementById(biao+"_test").innerHTML="("+obj.testClick+")"; document.getElementById(biao+"_user_test").innerHTML="("+obj.testClickUser+")"; } } } onSchedule(); } function thisClickNum() { var myDate=new Date(); var month=myDate.getMonth()+1; var da = myDate.getDate() + 1; var startTime = myDate.getFullYear() + "-" + month + "-" +myDate.getDate() + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00"; var start = stringToTime(startTime) / 1000; var end = stringToTime(endTime) / 1000; var path = "/api/v1/communities/" + communityId + "/users/1/orderHistories/getClickAmount?url=http://115.28.73.37:9090/api/V1/communities/" + communityId + "/modules/statistics/"+start+"/" + (end-1); $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var info; var click = 0; var clickNum = 0; var clickTime=0; for ( var i = 0; i < data.length; i++) { info = data[i].info; for ( var j = 0; j < info.length; j++) { var clickList=info[j].userClick; if(info[j].serviceId=="0"){ if(info[j].serviceName!="通知公告"){ continue; } } if(info[j].serviceId=="17"){ continue; } for ( var k = 0; k < clickList.length; k++) { if(mapTryOut[clickList[k].emobId] == "1"){ }else if(clickList[k].emobId!=undefined&&clickList[k].emobId!=""){ clickTime+= clickList[k].click; clickNum += clickList[k].click; } } } } thisClick(clickNum); }, error : function(er) { } }); } function thisClick(clickNum) { var myDate = new Date(); var month = myDate.getMonth() + 1; var da = myDate.getDate() + 1; var startTime = myDate.getFullYear() + "-" + month + "-" + myDate.getDate() + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" +da + " 00:00:00"; var start = stringToTime(startTime) / 1000; var end = stringToTime(endTime) / 1000; var time = 0; var path = "/api/v1/communities/" + communityId + "/users/1/orderHistories/getClickAmount?url=http://115.28.73.37:9090/api/V1/communities/" + communityId + "/events_details_daily/statistics/1/" + start + "/" + (end - 1); //alert(path); $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var info; var click = 0; var testClick = 0; var clickUser = 0; var clickUserList = new Array(); var testClickUser = 0; var testClickUserList = new Array(); var total=0; // info = data.userClick; for ( var i = 0; i < data.length; i++) { var clickList = data[i].userClick; total+=data[i].total; for ( var j = 0; j < clickList.length; j++) { if (mapTryOut[clickList[j].emobId] == "1") { testClickUserList[testClickUser++] = clickList[j].emobId; testClick += clickList[j].click; // alert(clickList[j].emobId); } else { if(clickList[j].emobId!=undefined&&clickList[j].emobId!=""){ clickUserList[clickUser++] =clickList[j].emobId ; click += clickList[j].click; } } } } // alert(testClickUserList.unique2().length); if(testClickUserList.length>1){ testClickUserList=testClickUserList.unique2(); } if(clickUserList.length>1){ clickUserList=clickUserList.unique2(); } //var clickNum=clickNumMap[biao]; var clickBi=0; if(clickNum>0){ clickBi=(click/clickNum)*100; } var clickUser=clickUserList.length; if(clickUser==0){ //total="["+total+"]"; click=0; clickUser=0; } var clickObc={ "total":total, "click":click, "clickUser":clickUser, "testClick":testClick, "clickUserList":clickUserList, "testClickUser":testClickUserList.length }; testTop(clickNum,clickObc); }, error : function(er) { onSchedule(); } }); } function getTryOut() { if(window.parent.isClick==63){ // testTop(); getTop(); thisClickNum(); quickShopData(); }else{ schedule(); setTimeout("getTryOut()", 2000); //setInterval("alert(100)",5000); } } function newActivities() { var myDate = new Date(); var month = myDate.getMonth() + 1; var da = myDate.getDate(); var startTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" +(da+1) + " 00:00:00"; var path="/api/v1/communities/"+communityId+"/activities/webIm/getAddActivity?startTime="+startTime+"&endTime="+endTime; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; document.getElementById("new_activities").innerHTML = data.acitvityNum; }, error : function(er) { } }); } function tryOut(emobGroupId) { var path = "/api/v1/communities/"+communityId+"/userStatistics/getUserList"; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var tryOut=data.listTryOut; var listUsers=data.listUsers; for ( var i = 0; i < tryOut.length; i++) { mapTryOut[tryOut[i].usersId]="1"; } newActivitiesListDetail(emobGroupId); }, error : function(er) { top.location='/'; } }); } function newActivitiesListDetail(emobGroupId) { var myDate = new Date(); var month = myDate.getMonth() + 1; var da = myDate.getDate(); var startTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" +(da+1) + " 00:00:00"; var path="/api/v1/communities/"+communityId+"/activities/webIm/newActivitiesListDetail?emobGroupId="+emobGroupId+"&startTime="+startTime+"&endTime="+endTime; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var repair_overman = $("#statistics_list_id"); repair_overman.empty(); repair_overman .append("<tr ><th>用户昵称</th><th> 用户号码</th> <th>加群时间</th><th></th></tr>"); for ( var i = 0; i < data.length; i++) { var liList = ""; if (i % 2 == 0) { liList += "<tr class=\"even\">"; } else { liList += "<tr class=\"odd\">"; } if(mapTryOut[data[i].userId]=="1"){ liList += "<td><b class=\"greenword\">" + data[i].nickname + "</b></td><td ><b class=\"greenword\">" + data[i].username+ "</b></td>"; liList += "<td><b class=\"greenword\">"+ toStringTime(data[i].createTime * 1000) + "</b></td>"; }else{ liList += "<td>" + data[i].nickname + "</td><td >" + data[i].username+ "</td>"; liList += "<td>"+ toStringTime(data[i].createTime * 1000) + "</td>"; } /*+ "<td></td>"*/ liList += "</tr>"; repair_overman.append(liList); } }, error : function(er) { } }); } function newActivitiesList(pageNum) { var myDate = new Date(); var month = myDate.getMonth() + 1; var da = myDate.getDate(); var startTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" +(+da+1) + " 00:00:00"; var path = "/api/v1/communities/"+communityId+"/activities/webIm/newActivitiesList?startTime=" + startTime + "&endTime=" + endTime; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var repair_overman = $("#statistics_list_id"); repair_overman.empty(); repair_overman .append("<tr ><th>活动名称</th><th> 群组人数</th> <th>详情</th><th></th></tr>"); for ( var i = 0; i < data.length; i++) { var liList = ""; if (i % 2 == 0) { liList += "<tr class=\"even\">"; } else { liList += "<tr class=\"odd\">"; } liList += "<td>" + data[i].activityTitle + "</td><td >" + data[i].addActivity+ "</td>"; liList += "<td>"+ "<a onclick=\"tryOut('"+data[i].emobGroupId+"');\">详情</a>" + "</td>"; /*+ "<td></td>"*/ liList += "</tr>"; repair_overman.append(liList); } document.getElementById("is_list_detail").value="detail"; }, error : function(er) { } }); } function getClickAmountTop( startTime, endTime,type) { var start = stringToTime(startTime) / 1000; var end = stringToTime(endTime) / 1000; var time = 0; var path = "/api/v1/communities/" + communityId + "/users/1/orderHistories/getClickAmount?url=http://115.28.73.37:9090/api/V1/communities/" + communityId + "/modules/statistics/" + start+ "/" + (end-1); //alert(path); $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var info; var click = 0; var clickNum = 0; for ( var i = 0; i < data.length; i++) { info = data[i].info; for ( var j = 0; j < info.length; j++) { var clickList=info[j].userClick; if(info[j].serviceId=="0"){ if(info[j].serviceName!="通知公告"){ continue; } } if(info[j].serviceId=="17"){ continue; } for ( var k = 0; k < clickList.length; k++) { if(mapTryOut[clickList[k].emobId] == "1"){ }else if(clickList[k].emobId!=undefined&&clickList[k].emobId!=""){ clickNum += clickList[k].click; } } //alert(info[j].serviceName+"---"+i); } } // getQuickShopTop( startTime, endTime, type,click,clickNum); getClick( startTime, endTime, type, clickNum); }, error : function(er) { // alert("网络连接失败..."); } }); } function getClick( startTime, endTime, type, clickNum) { var start = stringToTime(startTime) / 1000; var end = stringToTime(endTime) / 1000; var time = 0; var path = "/api/v1/communities/" + communityId + "/users/1/orderHistories/getClickAmount?url=http://115.28.73.37:9090/api/V1/communities/" + communityId + "/events_details_daily/statistics/1/" + start + "/" + (end - 1); //alert(path); $ .ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var info; var click = 0; var testClick = 0; var clickUser = 0; var clickUserList = new Array(); var testClickUser = 0; var testClickUserList = new Array(); var total=0; // info = data.userClick; for ( var i = 0; i < data.length; i++) { var clickList = data[i].userClick; total+=data[i].total; for ( var j = 0; j < clickList.length; j++) { if (mapTryOut[clickList[j].emobId] == "1") { testClickUserList[testClickUser++] = clickList[j].emobId; testClick += clickList[j].click; // alert(clickList[j].emobId); } else { if(clickList[j].emobId!=undefined&&clickList[j].emobId!=""){ clickUserList[clickUser++] =clickList[j].emobId ; click += clickList[j].click; } } } } // alert(testClickUserList.unique2().length); if(testClickUserList.length>1){ testClickUserList=testClickUserList.unique2(); } if(clickUserList.length>1){ clickUserList=clickUserList.unique2(); } // alert(i); getQuickShopTop( startTime, endTime, type, clickNum,click,testClick,clickUserList.length,testClickUserList.length,total); }, error : function(er) { onSchedule(); } }); } function getQuickShopTop(biao,startTime, endTime) { var path = "/api/v1/communities/"+communityId+"/activities/webIm/getActivitiesTop?startTime=" + startTime + "&endTime=" + endTime; var myDate = new Date(stringToTime(startTime)); var myDate2 = new Date(stringToTime(endTime)); var dates = Math.abs((myDate2 - myDate)) / (1000 * 60 * 60 * 24); var startTimeFilter = myDate.getMonth() + 1 + "月" + myDate.getDate() + "日"; var endTimeFilter = myDate2.getMonth() + 1 + "月" + myDate2.getDate() + "日"; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var ord = data.activitesNum / dates; document.getElementById(biao+"_add_user").innerHTML = data.addActivity; document.getElementById(biao+"_add_user_test").innerHTML ="("+ data.addTestActivity+")"; document.getElementById(biao+"_add_activities").innerHTML = data.activityNum; document.getElementById("statistics_date_1").innerHTML = startTimeFilter; document.getElementById("statistics_date_2").innerHTML = endTimeFilter; document.getElementById("avg_day_order").innerHTML = ord.toFixed(0); }, error : function(er) { } }); } function getQuickShopList(pageNum, startTime, endTime,map) { var path = "/api/v1/communities/"+communityId+"/activities/webIm/getActivitiesDateList?pageSize=50&pageNum=" + pageNum + "&startTime=" + startTime + "&endTime=" + endTime; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; $("#master_repair_datai_PageNum_get").val(data.num); $("#master_repair_datai_PageSize_get").val(data.pageCount); $("#master_repair_datai_PageNum").html(data.num); $("#master_repair_datai_PageSize").html(data.pageCount); $("#master_repair_datai_sum").html(data.rowCount); data = data.pageData; var repair_overman = $("#statistics_list_id"); repair_overman.empty(); repair_overman .append("<tr ><th>活动名称</th><th> 群组人数</th><th>增加人数 </th><th></th></tr>"); for ( var i = 0; i < data.length; i++) { var liList = ""; if (i % 2 == 0) { liList += "<tr class=\"even\">"; } else { liList += "<tr class=\"odd\">"; } liList += "<td>" + data[i].activityTitle + "</td><td >" + data[i].addActivity+ "</td>"; liList += "<td>" + data[i].activitesNum + "</td>"; /*+ "<td><a onclick=\"getShopsOrderDetailList('1','" + data[i].activitiesId + "');\">详情</a></td>"*/ liList += "</tr>"; repair_overman.append(liList); } document.getElementById("is_list_detail").value="detail"; }, error : function(er) { } }); } function thisUserData(){ var myDate = new Date(); var month = myDate.getMonth() + 1; var da = myDate.getDate() -1; var startTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" +myDate.getDate() + " 00:00:00"; getQuickShopTop('to_day',startTime,endTime); } function toDayUserData(){ var myDate = new Date(); var month = myDate.getMonth() + 1; var da = myDate.getDate() + 1; var startTime = myDate.getFullYear() + "-" + month + "-" + myDate.getDate() + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" +da + " 00:00:00"; getQuickShopTop('this_data',startTime,endTime); } function thisMonthUser() { var myDate = new Date(); var month = myDate.getMonth()+1; var month2 = myDate.getMonth()+2; var startTime = myDate.getFullYear() + "-" + month + "-" + 1 + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month2 + "-1" + " 00:00:00"; getQuickShopTop('this_month',startTime,endTime); } function monthUser() { var myDate = new Date(); var month = myDate.getMonth(); var month2 = myDate.getMonth()+1; var startTime = myDate.getFullYear() + "-" + month + "-" + 1 + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month2 + "-1" + " 00:00:00"; getQuickShopTop('last_month',startTime,endTime); } function weekUser() { var d = getPreviousWeekStartEnd(); var startTime = d.start; var endTime = d.end; getQuickShopTop('last_week',startTime,endTime); } function thisWeekUser() { var d = getWeekBenUp(); var startTime = d.start; var endTime = d.end; getQuickShopTop('this_week',startTime,endTime); } function totalUser() { var myDate = new Date(); var month = myDate.getMonth()+1; var da=myDate.getDate()+1; var startTime="2015-06-01 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-"+ da + " 00:00:00"; getQuickShopTop("total_id",startTime, endTime); } function getTop() { toDayUserData(); thisUserData(); thisWeekUser(); thisMonthUser(); //getUserTop(); // quickUserData(); weekUser() ; monthUser(); totalUser(); } function quickShopData() { schedule(); var myDate = new Date(); var month = myDate.getMonth() + 1; var da = myDate.getDate(); var startTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" +(da+1) + " 00:00:00"; // newActivities(); getClickAmountList(1, startTime, endTime, '日'); //getClickAmountTop(startTime, endTime); onSchedule(); } function maintainMonth() { var myDate = new Date(); var month = myDate.getMonth(); var month2 = myDate.getMonth()+1; var startTime = myDate.getFullYear() + "-" + month + "-" + 1 + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month2 + "-" + 1 + " 00:00:00"; // getQuickShopList(1, startTime, endTime); getClickAmountList(1, startTime, endTime, '月'); //getClickAmountTop(startTime, endTime); } function alterMonth(num) { var startTime = document.getElementById("master_repir_startTime").value; var type = document.getElementById("date_type_get").value; var d = alterDate(num, type, startTime); var startTime = d.start; var endTime = d.end; getClickAmountList(1, startTime, endTime, type); //getClickAmountTop(startTime, endTime); } function weekMonth() { var d = getPreviousWeekStartEnd(); var startTime = d.start; var endTime = d.end; getClickAmountList(1, startTime, endTime, '周'); //getClickAmountTop(startTime, endTime); } function turnover() { document.getElementById("statistics_id").style.display = "none"; document.getElementById("turnover_id").style.display = ""; } function statistics() { document.getElementById("statistics_id").style.display = ""; document.getElementById("turnover_id").style.display = "none"; } function selectStatistics() { var startTime = document.getElementById("txtBeginDate").value + " 00:00:00"; var endTime = document.getElementById("txtEndDate").value + " 00:00:00"; getClickAmountList(1, startTime, endTime); // getClickAmountTop(startTime, endTime); } function turnoverTurnover() { var startTime = document.getElementById("turnoverBeginDate").value + " 00:00:00"; var endTime = document.getElementById("turnoverEndDate").value + " 00:00:00"; getQuickShopList(1, startTime, endTime); getClickAmountTop(startTime, endTime); } function getMasterRepairDetailPage(num) { var page_num = 1; var repairRecordPageNum = document .getElementById("master_repair_datai_PageNum_get").value; var repairRecordPageSize = document .getElementById("master_repair_datai_PageSize_get").value; var startTime = document.getElementById("master_repir_startTime").value; var endTime = document.getElementById("master_repir_endTime").value; var is_list_detail = document.getElementById("is_list_detail").value; var shopId = document.getElementById("shop_id_detail").value; if (num == -1) { // 上一页 if (repairRecordPageNum != 1) { page_num = repairRecordPageNum - 1; } else { alert("已经是第一页了"); return; } } else if (num == -2) { // 下一页 if (parseInt(repairRecordPageNum) < parseInt(repairRecordPageSize)) { page_num = parseInt(repairRecordPageNum) + parseInt(1); } else { alert("已经是最后一页了"); return; } } else if (num == -3) { // 首页 if (repairRecordPageNum != 1) { page_num = 1; } else { alert("已经是首页了"); return; } } else if (num == -4) { // 尾页 if (parseInt(repairRecordPageNum) < parseInt(repairRecordPageSize)) { page_num = repairRecordPageSize; } else { alert("已经是尾页了"); return; } } if (page_num != 0) { if (is_list_detail == "detail") { var tim= document.getElementById("time_day").value; var da = tim * 1000; var myDate = new Date(da); var month = myDate.getMonth() + 1; var da = myDate.getDate() + 1; var startTime = myDate.getFullYear() + "-" + month + "-" + myDate.getDate() + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00"; getQuickShopList(page_num, startTime, endTime); } else { getClickAmountList(page_num, startTime, endTime); } getClickAmountTop(startTime, endTime); } } function getShopsOrderDetailList(pageNum, activityId) { document.getElementById("shop_id_detail").value = activityId; document.getElementById("is_list_detail").value = "detail"; var startTime = document.getElementById("master_repir_startTime").value; var endTime = document.getElementById("master_repir_endTime").value; var path = "/api/v1/communities/"+communityId+"/activities/webIm/getActivitiesDetailList?pageSize=50" + "&pageNum=" + pageNum + "&activitiesId=" + activityId + "&startTime=" + startTime + "&endTime=" + endTime; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; $("#master_repair_datai_PageNum_get").val(data.num); $("#master_repair_datai_PageSize_get").val(data.pageCount); $("#master_repair_datai_PageNum").html(data.num); $("#master_repair_datai_PageSize").html(data.pageCount); $("#master_repair_datai_sum").html(data.rowCount); data = data.pageData; var repair_overman = $("#statistics_list_id"); repair_overman.empty(); // var liList=''; repair_overman .append("<tr class=\"odd\"><td>统计时间</td><td>活动人数</td><td>增加人数</td> </tr>"); var myDate = new Date(); var month = myDate.getMonth() + 1; var da = myDate.getDate() - 1; var da2 = myDate.getDate() - 2; var startTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" + myDate.getDate() + " 00:00:00"; var startTime2 = myDate.getFullYear() + "-" + month + "-" + da2 + " 00:00:00"; var startTime_day_long = stringToTime(startTime) / 1000; var endTime_day_long = stringToTime(endTime) / 1000; var startTime2_day_long = stringToTime(startTime2) / 1000; for ( var i = 0; i < data.length; i++) { var liList = ""; if (i % 2 == 0) { liList += "<tr class=\"even\">"; } else { liList += "<tr class=\"odd\">"; } // liList += "<tr class=\"odd\">"; liList += "<td>"; if (data[i].activityTime > startTime_day_long && data[i].activityTime < endTime_day_long) { liList += "昨天"; } else if (data[i].activityTime > startTime2_day_long && data[i].activityTime < startTime_day_long) { liList += "前天"; } else { var myDate = new Date(data[i].activityTime * 1000); var startTimeFilter = myDate.getMonth() + 1 + "月" + myDate.getDate() + "日"; liList += startTimeFilter; } liList += "</td><td >" + data[i].addActivity + "</td>"; liList += "<td>" + data[i].activitesNum + "</td></tr>"; repair_overman.append(liList); } }, error : function(er) { } }); } function timeClick(clickId) { if (clickId == "data_clik") { document.getElementById("data_clik").className = "select"; quickShopData(); } else { document.getElementById("data_clik").className = ""; } if (clickId == "week_clik") { document.getElementById("week_clik").className = "select"; weekMonth(); } else { document.getElementById("week_clik").className = ""; } if (clickId == "month_clik") { document.getElementById("month_clik").className = "select"; maintainMonth(); } else { document.getElementById("month_clik").className = ""; } } function getClickAmountList( pageNum, startTime, endTime,type) { var path = "/api/v1/communities/"+communityId+"/activities/webIm/getActivitiesTop?startTime=" + startTime + "&endTime=" + endTime; var myDate = new Date(stringToTime(startTime)); var myDate2 = new Date(stringToTime(endTime)); var dates = Math.abs((myDate2 - myDate)) / (1000 * 60 * 60 * 24); var startTimeFilter = myDate.getMonth() + 1 + "月" + myDate.getDate() + "日"; var endTimeFilter = myDate2.getMonth() + 1 + "月" + myDate2.getDate() + "日"; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; getClickAmountList2( pageNum, startTime, endTime,type,data.addActivity,data.addTestActivity,data.activityNum); }, error : function(er) { } }); } function getClickAmountList2( pageNum, startTime, endTime,type,addActivityAge,addTestActivityAge,activityNumAge) { document.getElementById("is_list_detail").value=""; var start = stringToTime(startTime) / 1000; var end = stringToTime(endTime) / 1000; var time = 0; var path = "/api/v1/communities/" + communityId + "/users/1/orderHistories/getClickAmount?url=http://115.28.73.37:9090/api/V1/communities/" + communityId + "/events_details_daily/statistics/1/" + start + "/" +(end-1); $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var clickUserListNum = new Array(); var testClickUserListNum = new Array(); var clickUserNum=0; var testClickUserNum=0; var clickSumNum=0; var testClickSumNum=0; for ( var i = 0; i < data.length; i++) { var clickList = data[i].userClick; for ( var j = 0; j < clickList.length; j++) { if (mapTryOut[clickList[j].emobId] == "1") { testClickUserListNum[testClickUserNum++] = clickList[j].emobId; testClickSumNum += clickList[j].click; // alert(clickList[j].emobId); } else { if(clickList[j].emobId!=undefined&&clickList[j].emobId!=""){ clickUserListNum[clickUserNum++] =clickList[j].emobId ; clickSumNum += clickList[j].click; } } } } // alert(testClickUserList.unique2().length); if(testClickUserListNum.length>1){ testClickUserListNum=testClickUserListNum.unique2(); } if(clickUserListNum.length>1){ clickUserListNum=clickUserListNum.unique2(); } var map = {}; var click = 0; var testClick = 0; var clickUser = 0; var testClickUser = 0; var time; var total=0; for ( var i = 0; i < data.length; i++) { var clickUserList = new Array(); var testClickUserList = new Array(); var clickList = data[i].userClick; time = getStringTime(data[i]._id.time * 24 * 60 * 60 * 1000); total+=data[i].total; for ( var j = 0; j < clickList.length; j++) { if (mapTryOut[clickList[j].emobId] == "1") { testClickUserList[testClickUser++] = clickList[j].emobId; testClick += clickList[j].click; // alert(clickList[j].emobId); } else { if(clickList[j].emobId!=undefined&&clickList[j].emobId!=""){ clickUserList[clickUser++] = clickList[j].emobId; click += clickList[j].click; }else{ } } } if(testClickUserList.length>1){ testClickUserList=testClickUserList.unique2(); } if(clickUserList.length>1){ clickUserList=clickUserList.unique2(); } var clickDetl={ "click" : click, "testClick" : testClick, "clickUser" : clickUserList.length, "testClickUser" : testClickUserList.length, "total" : total }; map[time] = clickDetl; click = 0; testClickUser = 0; testClick=0; clickUser = 0; total = 0; } timeQuantum(startTime, endTime); timeDisplay(type); getUseAmountList( pageNum, startTime, endTime,map,clickUserListNum.length,testClickUserListNum.length,addActivityAge,addTestActivityAge,activityNumAge); }, error : function(er) { } }); } function getUseAmountList(pageNum, startTime, endTime,map,clickUserListNum,testClickUserListNum,addActivityAge,addTestActivityAge,activityNumAge) { // document.getElementById("shop_sort_id").value; var d=show(getStringTime(stringToTime(startTime)),getStringTime(stringToTime(endTime))); var en=""; for ( var i = 0; i < d.length-1; i++) { en+="&sqlTime="+d[i]+" 00:00:00"; } var path = "/api/v1/communities/"+communityId+"/activities/webIm/getActivitiesList?startTime=" + startTime + "&endTime=" + endTime+en; $.ajax({ url : path, type : "GET", dataType : 'json', success : function(data) { data = data.info; var map2={}; var repair_overman = $("#statistics_list_id"); repair_overman.empty(); // var liList=''; //repair_overman.append("<tr class=\"odd\"><td>统计时间</td><td> 活动人数</td><td>点击量</td><td>增加人数</td> <td>详情 </td></tr>"); repair_overman.append("<tr class=\"odd\"><td>统计时间</td><td>发言条数</td><td>发言人数</td><td>群活跃度</td><td>参与群活动人数</td> </tr>"); var myDate = new Date(); var month = myDate.getMonth() + 1; var da = myDate.getDate() - 1; var da2 = myDate.getDate() - 2; var startTime1 = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00"; var endTime1 = myDate.getFullYear() + "-" + month + "-" + myDate.getDate() + " 00:00:00"; var startTime2 = myDate.getFullYear() + "-" + month + "-" + da2 + " 00:00:00"; var startTime_day_long = stringToTime(startTime1) / 1000; var endTime_day_long = stringToTime(endTime1) / 1000; var startTime2_day_long = stringToTime(startTime2) / 1000; for( var i = 0; i < data.length; i++){ map2[getStringTime(data[i].createTime*1000)]=data[i]; } var data2; var shi=show(getStringTime(stringToTime(startTime)),getStringTime(stringToTime(endTime))); var activitesNumTotal=0; var addActivityTotal=0; var addTestActivityTotal=0; var clickTotal=0; var testClickTotal=0; var liList = ""; for ( var i = shi.length-2; i >=0 ; i--) { data2=map2[shi[i]]; if(data2==undefined){ var data2={ "activityTime":stringToTime(shi[i]+" 00:00:00")/1000, "activitesNum":0, "addActivity":0, "addTestActivity":0 }; } var time=getStringTime(data2.activityTime*1000); var bi = 0; var time = shi[i]; var c = map[time]; var click=0; var testClick=0; var testClickUser=0; var clickUser=0; var total=0; if (c != undefined ) { click = c.click; testClick = c.testClick; testClickUser = c.testClickUser; clickUser = c.clickUser; total = c.total; } if(click!=0){ bi = ((data2.orderQuantity / click) * 100); } if(clickUser==0){ clickUser="无明细["+total+"]"; } if (i % 2 == 0) { liList += "<tr class=\"even\">"; } else { liList += "<tr class=\"odd\">"; } // liList += "<tr class=\"odd\">"; liList += "<td>"; var myDate = new Date(data2.createTime * 1000); var startTimeFilter = myDate.getMonth() + 1 + "月" + myDate.getDate() + "日"; liList += startTimeFilter; // liList += "</td><td >" +data2.addActivity ; liList += "</td>" ; liList += "<td>" + click + "<b class=\"greenword\">("+testClick+")</b></td>" ; liList += "<td>" + clickUser + "<b class=\"greenword\">("+testClickUser+")</b></td>" ; liList+= "<td >"+data2.addActivity +"<b class=\"greenword\">("+data2.addTestActivity+")</b></td>"; liList+="<td>"+data2.activityNum + "</td></tr>"; activitesNumTotal+=data2.activityNum; addActivityTotal+=data2.addActivity; addTestActivityTotal+=data2.addTestActivity; clickTotal+=click; testClickTotal+=testClick; } var liTop=""; liTop+="<tr class=\"even\"><td>合计</td>"; liTop+="<td>"+clickTotal+ "<b class=\"greenword\">("+testClickTotal + ")</b></td>"; liTop+="<td>"+clickUserListNum+ "<b class=\"greenword\">("+ testClickUserListNum + ")</b></td>"; liTop+="<td>"+addActivityAge+"<b class=\"greenword\">(" + addTestActivityAge + ")</b></td>"; liTop+="<td>" + activityNumAge + "</td>"; liTop+="</tr>"; repair_overman.append(liTop); repair_overman.append(liList); document.getElementById("master_repir_startTime").value = startTime; document.getElementById("master_repir_endTime").value = endTime; document.getElementById("is_list_detail").value=""; // document.getElementById("shop_sort_id").value=sort; }, error : function(er) { } }); } function selectData(tim) { document.getElementById("is_list_detail").value="detail"; document.getElementById("time_day").value=tim; var da = tim * 1000; var myDate = new Date(da); var month = myDate.getMonth() + 1; var da = myDate.getDate() + 1; var startTime = myDate.getFullYear() + "-" + month + "-" + myDate.getDate() + " 00:00:00"; var endTime = myDate.getFullYear() + "-" + month + "-" + da + " 00:00:00"; // alert(startTime+"=="+endTime); getQuickShopList(1, startTime, endTime); }
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import {BrowserRouter} from "react-router-dom"; import {ThemeProvider} from "@material-ui/styles"; import {createTheme, Slide} from "@material-ui/core"; import {Provider} from "react-redux"; import store from "./redux/store"; import {SnackbarProvider} from "notistack"; const theme = createTheme({ typography: { fontFamily: 'Raleway, IBM Plex Mono, sans-serif;' }, palette: { primary: { main: '#374151', light: '#6B7280', dark: '#1F2937' }, secondary: { main: '#DC2626' }, text: { primary: '#E5E7EB', secondary: '#374151', disabled: '#9CA3AF' }, action: { active: '#E5E7EB' }, background: { default: '#111827', paper: '#1F2937' }, type: 'dark' }, shape: { borderRadius: 32 } }); ReactDOM.render( <React.StrictMode> <Provider store={store}> <BrowserRouter> <ThemeProvider theme={theme}> <SnackbarProvider TransitionComponent={Slide} anchorOrigin={{vertical: 'top', horizontal: 'right'}}> <App/> </SnackbarProvider> </ThemeProvider> </BrowserRouter> </Provider> </React.StrictMode>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
import { SET_POSTS, SET_DEFAULT_POSTS_SORT, SORT_POSTS, VOTE_POST, NEW_POST, SET_POST_TO_EDIT, CLEAR_POST_TO_EDIT, UPDATE_POST, REMOVE_POST } from '../actions' export default function posts (state = {}, action) { switch (action.type) { case SET_POSTS: const { posts } = action return { ...state, posts: posts.filter(p => !p.deleted) } case SET_DEFAULT_POSTS_SORT: return { ...state, defaultSort: 'voteScore' } case SORT_POSTS: return { ...state, defaultSort: action.option } case VOTE_POST: const { vId, vOption } = action return { ...state, posts: [ ...state.posts ].map(p => { if (p.id === vId) { if (vOption === 'upVote') { return { ...p, voteScore: p.voteScore + 1} } else if (vOption === 'downVote') { return { ...p, voteScore: p.voteScore - 1} } } return p }) } case NEW_POST: const { post } = action return { ...state, posts: [ ...state.posts ].concat([ post ]) } case SET_POST_TO_EDIT: const postToEdit = action.post return { ...state, postToEdit } case CLEAR_POST_TO_EDIT: return { ...state, postToEdit: null } case UPDATE_POST: const { uPost } = action return { ...state, posts: [ ...state.posts ].map(p => p.id === uPost.id ? uPost : p ) } case REMOVE_POST: const { rPostId } = action return { ...state, posts: [ ...state.posts ].filter(p => p.id !== rPostId) } default: return state } }
const arr = ['🍎', '🍐', '🍊', '🍌'] // a função includes irá retornar um valor booleano // de acordo com a sentença que declararmos. // se o array incluir o elemento incluido na sentença, será retornado true, // caso contrário, será retornado false: const arrayContemLaranja = arr.includes('🍊') console.log(arrayContemLaranja) // true const arrayContemUva = arr.includes('🍇') console.log(arrayContemUva) // false
/****************************************************************************** * Compilation: node BubbleSort.js * * Purpose: Program to sort a given array using Bubble Sort Algorithm. * * @author Nishant Kumar * @version 1.0 * @since 16-10-2018 * ******************************************************************************/ // Array which will be sorted. var arr = ["nishant", "akshansh", "chiraag", "sarthak", "deepankan"]; /** * Function to sort a given array using Bubble Sort Algorithm. * * @param a It is the array to be sorted. */ function sort(a) { var len = a.length, temp; // Outer loop will run from 0 till len-1. for (var i = 0; i < len - 1; i++) { // Inner loop will run from 0 till len-i-1. for (var j = 0; j < len - i - 1; j++) { /* If the element present at j is greater than the element present at it's * right index, they will be swapped. */ if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } } // Calling 'sort()' method to start sorting the elements. sort(arr); // Printing the array after sorting. console.log(arr);
//webpackの設定ファイル const path = require('path'); // less32 const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // less33 const HtmlWebpackPlugin = require('html-webpack-plugin'); // less35 const { CleanWebpackPlugin } = require('clean-webpack-plugin');// {}で複数あるclean...plugin機能の特定のやつだけ使う const loader = require('sass-loader'); module.exports = { mode: 'development', devtool: 'source-map',//less62 jsコードを人間が読みやすいようにする。 entry: './src/javascripts/main.js', output: {//出力先 path: path.resolve(__dirname, './dist'),//path.resolveで絶対パスを取得(webpack絶対パスじゃないとエラー)引数1=現在のフォルダのある階層。 filename: 'javascripts/main.js',//出力されるファイル名を変更 }, module: { rules: [//配列 { test: /\.(ts|tsx)/, exclude: /node_modules/, use: [ { loader: 'ts-loader', }, ], }, {// JS系 test: /\.js/, exclude: /node_modules/,//node_moduleはトランスパイルしない use: [ { loader: "babel-loader", options: { presets: [ ['@babel/preset-env', { 'targets': '> 0.25%, not dead'}], '@babel/preset-react', ],//babelプラグインをまとめてインストール。{}内は、0.25%以上のシェアを持っているブラウザで且つ公式のサポートが終了していないブラウザを対象にトランスパイル } } ] }, {//CSS系 test: /\.(css|sass|scss)/, use: [ { loader: MiniCssExtractPlugin.loader,//読みこんだcssを処理 },//loaderは必ず "下から上に" 適用されていく。→ .cssあったら、まず、css-loader読み込まれ、次にstyle-loader { loader: 'css-loader',//.cssのファイルを読み込み options: { sourceMap: true, }, }, { loader: 'sass-loader', }, ], }, {//less40 画像系 test: /\.(png|jpg|jpeg)/,//.png, .jpgのファイル読み込み use: [ { loader: 'file-loader', options: { esModule: false, name: 'images/[name].[ext]',//extは拡張子 }, }, {// less66 loader: 'image-webpack-loader', options: { mozjpeg: { progressive: true, quality: 65,//圧縮率 }, }, }, ], }, {// PUG・HTML系 test: /\.pug/, use: [ { loader: 'html-loader', }, { loader: 'pug-html-loader', options: { pretty: true,//出力されるhtmlコードを1行にまとめない }, }, ], }, ], }, plugins: [ new MiniCssExtractPlugin({ filename: './stylesheets/main.css', }), new HtmlWebpackPlugin({ template: './src/templates/index.pug', filename: 'index.html' }), new HtmlWebpackPlugin({ template: './src/templates/access.pug', filename: 'access.html' }), new HtmlWebpackPlugin({ template: './src/templates/members/taro.pug', filename: 'members/taro.html' }), new CleanWebpackPlugin(), ] } /* rulesは張烈 中に、testとuse \.cssは正規表現。スラッシュのなかで . を使うために、バックスラッシュを前に書く(.cssを検知できる) つまり、.cssというファイルを見つけたら、use(ルール)を適用しろという意味。 */
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var async = require('async'); var tableSchema = new Schema({ name:{ type: String, required: true }, table:{ type: Schema.Types.ObjectId, ref: "Table", required: true }, start_time:{ type: Date, required: true, }, end_time:{ type: Date, required: true, } }); tableSchema.statics.QueryData = function(query,where, sort, cb){ var qry = this.find(where); if(where){ console.log(where); if(sort){ qry.sort(sort); } // qry = qry.find(where); // console.log("qry", qry); } qry.exec(cb || console.log) } module.exports = DB_CONNECTION.model("Booking", tableSchema);
import React, { Component } from "react"; class BodyItemClass extends Component { constructor(props) { super(props); this.state = { count: 0, }; } render() { return <div> {/* <p>State Test with React Class</p> <p> Click {this.state.count} time</p> <button onClick={() => this.setState({count: this.state.count + 1})}> Click Me! </button> */} </div>; } } export default BodyItemClass;
$(function() { $("#userList").click(function() { fetchList("user"); }); $("#moneyList").click(function() { fetchList("money"); }); $("#sourcesList").click(function() { fetchList("money/inoutSources"); }); $("#uploadExcelFile").submit(function(e) { e.preventDefault(); var formData = new FormData(this); $.ajax({ type:"POST", url:"/moneymonster/money/readExcel/"+$("#modelFor").val(), data:formData, cache:false, contentType:false, processData:false, success:function(data) { $("#uploaded-data").html(data); } }); }); }); var pageConstant = "?page=1"; function addForm(type) { modifyData(type+"/form"); } function editForm(type, id) { $("#myModal").modal('hide'); modifyData(type+"/edit/"+id); } function fetchList(type) { modifyData(type+"/list"+pageConstant); } function refresh(type) { modifyData(type+"/refresh"+pageConstant); } function list(type, page) { modifyData(type+"/list?page="+page); } function modifyData(suffix) { $.ajax({ type : "GET", url : "/moneymonster/"+suffix, success : function(data) { $(".inner-jsp").html(data); } }); } function deleteData(type, id) { toastr.warning("<div>Are you sure you want to delete this?</div>" + "<div class='btn-group pull-right'>" + "<button type='button' id='confirmationYes' class='btn btn-xs btn-default'><i class='glyphicon glyphicon-ok'></i> Yes</button>" + "<button type='button' class='btn btn-xs btn-default clear'><i class='glyphicon glyphicon-remove'></i> No</button>" + "</div>", "Delete Confirmation", { allowHtml:true, closeButton:true, onShown: function() { $("#confirmationYes").click(function() { $.ajax({ type : "GET", url : "/moneymonster/"+type+"/delete/"+id, success : function(data) { fetchList(type); toastr.success(data.message, "Delete Confirmation", { closeButton:true }); } }); }); } }); } function fetchSources() { var type = $("#type").val(); if(type != "") { $.ajax({ type : "GET", url : "/moneymonster/money/fetch/"+type, success : function(data) { $("#sourceDivId").html(data); } }); } } function yearlyEarningDestribution(year) { $.ajax({ type : "GET", url : "/moneymonster/money/yearlyEarning/"+year, success : function(data) { $("#sourceModalData").html(data); $("#sourceModal").modal('show'); $(".model-label").text(year); } }); } function distributionBySource(id, name, page) { $.ajax({ type : "GET", url : "/moneymonster/money/distributionBySource/"+id+"?page="+page, success : function(data) { $("#sourceModalData").html(data); $("#sourceModal").modal('show'); $(".model-label").text(name); } }); } function uploadModal(modalFor) { $.ajax({ type : "GET", url : "/moneymonster/money/uploadModal/"+modalFor, success : function(data) { $("#modal-data").html(data); $("#uploadModal").modal('show'); $(".model-label").text(modalFor); $(".modal-body").css("height", "65px"); } }); }
/** * Class for finding Tangent between circles * * Implementation from * https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Tangents_between_two_circles */ class CircleTangents { constructor(x1, y1, r1, x2, y2, r2) { /** @private */ this._x1 = x1; /** @private */ this._y1 = y1; /** @private */ this._r1 = r1; /** @private */ this._x2 = x2; /** @private */ this._y2 = y2; /** @private */ this._r2 = r2; /** @private */ this._tangents = this._getTangents(); } get tangents() { return this._tangents; } _getTangents() { const x1 = this._x1; const y1 = this._y1; const r1 = this._r1; const x2 = this._x2; const y2 = this._y2; const r2 = this._r2; const sqd = ((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)); if (sqd <= (r1 - r2) * (r1 - r2)) { return [...Array(4)].map(() => []); } const dist = Math.sqrt(sqd); const vx = (x2 - x1) / dist; const vy = (y2 - y1) / dist; const res = [...Array(4)].map(() => []); let i = 0; for (let sign1 = +1; sign1 >= -1; sign1 -= 2) { const c = (r1 - (sign1 * r2)) / dist; if (c * c > 1.0) { continue; } const h = Math.sqrt(Math.max(0.0, 1.0 - (c * c))); for (let sign2 = +1; sign2 >= -1; sign2 -= 2) { const nx = (vx * c) - (sign2 * h * vy); const ny = (vy * c) + (sign2 * h * vx); res[i].push(x1 + (r1 * nx)); res[i].push(y1 + (r1 * ny)); res[i].push(x2 + (sign1 * r2 * nx)); res[i].push(y2 + (sign1 * r2 * ny)); i += 1; } } return res; } } module.exports = CircleTangents;
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export const store = new Vuex.Store({ state : { queryUrl : 'localhost' , queryPort : 5353 , queryPath : '/getrs' , excelPath : '/getexcel' , currentQuery: { serial: 1 , header: "" , query: "" } , querySerial: 1 , resultSets: [] } , mutations : { updateQuery (state, query) { state.currentQuery.serial = state.querySerial++ state.currentQuery.header = query.header state.currentQuery.query = query.query } , addResultSet(state, queryResult) { state.resultSets.push({header: queryResult.header, rs: queryResult.rs}) } , incQuerySerial (state) { state.querySerial++ } , decQuerySerial (state) { state.querySerial-- } } , getters : { currentQuery: state => state.currentQuery , resultSets: state => state.resultSets , queryUrl: state => state.queryUrl , queryPort: state => state.queryPort , queryPath: state => state.queryPath , excelPath: state => state.excelPath , nextQuerySerial: state => state.querySerial } })
import React, { Component } from 'react' class Footer extends Component { render() { return ( <React.Fragment> <link rel="manifest" href="%PUBLIC_URL%/manifest.json"/> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossOrigin="anonymous"/> <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossOrigin="anonymous"/> <link href="https://fonts.googleapis.com/css?family=Anton|Montserrat:700|Roboto+Condensed" rel="stylesheet"/> <link href="https://fonts.googleapis.com/css?family=Montserrat|Roboto" rel="stylesheet"/> <script defer src="https://use.fontawesome.com/releases/v5.0.9/js/all.js" integrity="sha384-8iPTk2s/jMVj81dnzb/iFR2sdA7u06vHJyyLlAd4snFpCl/SnyUjRrbdJsw1pGIl" crossOrigin="anonymous"/> </React.Fragment> ) } } export default Footer
var Foam = require('foam-gl'), Program = Foam.Program; Foam.App.newOnLoadWithResource({ path : PATH_TO_SHADER },{ setup: function(resource){ this.setWindowSize(800,600); this.setFPS(60); this._program = new Program(resource); this._program.bind(); var windowWidth = this.getWindowWidth(), windowHeight = this.getWindowHeight(); this._gl.viewport(0,0,windowWidth,windowHeight); this._glTrans.setWindowMatrices(windowWidth,windowHeight,true); }, update : function(){ var gl = this._gl, glTrans = this._glTrans, glDraw = this._glDraw; gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.clearColor(0.25,0.25,0.25,1.0); glTrans.pushMatrix(); glTrans.translate3f(this.getWindowWidth() * 0.5 - 50, this.getWindowHeight() * 0.5 - 50,0); glTrans.scale3f(100,100,0); glDraw.drawRect(); glTrans.popMatrix(); } });
/*global JSAV, document */ // Written by Brannon Angers $(document).ready(function() { "use strict"; var av = new JSAV("AutomataCON", {animationMode: "none"}); var left = 200; var ytop = 20; var elements = ["a", "a", "b", "b", "a", "b", "", "", "", ""]; var tape = av.ds.tape(elements, left + 30, ytop, "right"); tape.arr.highlight(2); //Control unit av.g.rect(left + 50, ytop + 105, 148, 152, {"stroke-width": 1}); av.g.circle(left + 124, ytop + 194, 48, {"stroke-width": 1}); // Arrow in circle of control unit av.g.line(left + 124, ytop + 194, left + 134, ytop + 184, {"stroke-width": 1}); av.g.polyline([[left + 129, ytop + 186], [left + 134, ytop + 184], [left + 132, ytop + 188]], {"stroke-width": 1}); //Arrow from control unit to input tape av.g.line(left + 107, ytop + 38, left + 107, ytop + 105, {"stroke-width": 1}); av.g.polyline([[left + 104, ytop + 44], [left + 107, ytop + 38], [left + 110, ytop + 44]], {"stroke-width": 1}); //Arrow from control unit to storage av.g.line(left + 198, ytop + 204, left + 245, ytop + 204, {"stroke-width": 1}); av.g.polyline([[left + 239, ytop + 201], [left + 245, ytop + 204], [left + 239, ytop + 207]], {"stroke-width": 1}); // Right edge of storage av.g.line(left + 248, ytop + 194, left + 248, ytop + 300, {"stroke-width": 1}); // Left edge of storage av.g.line(left + 278, ytop + 194, left + 278, ytop + 300, {"stroke-width": 1}); // Inner lines of storage from top to bottom av.g.line(left + 248, ytop + 204, left + 278, ytop + 204, {"stroke-width": 1}); av.g.line(left + 248, ytop + 229, left + 278, ytop + 229, {"stroke-width": 1}); av.g.line(left + 248, ytop + 254, left + 278, ytop + 254, {"stroke-width": 1}); av.g.line(left + 248, ytop + 278, left + 278, ytop + 278, {"stroke-width": 1}); av.label("input tape", {left: left + 90, top: ytop - 35}); // Inner text of input tape av.label("tape head", {left: left + 126, top: ytop + 25}); av.label("control unit", {left: left + 85, top: ytop + 100}); av.label("0", {left: left + 105, top: ytop + 145}); av.label("1", {left: left + 140, top: ytop + 145}); av.label("storage", {left: left + 290, top: ytop + 170}); av.label("(optional)", {left: left + 290, top: ytop + 190}); av.displayInit(); av.recorded(); });
import ingredientsReducer from '../ingredientsReducer'; import * as types from '../../actions/ingredientsActions'; import { ingredientsMock } from './mock'; const initialState = { inProgress: false, ingredients: [], ingredientsError: '', ingredientInfo: {}, }; describe('INGREDIENTS REDUCER', () => { it('should return the initial state', () => { expect(ingredientsReducer(undefined, {})).toEqual(initialState); }); it('should handle INGREDIENTS_REQUEST', () => { expect(ingredientsReducer(initialState, { type: types.INGREDIENTS_REQUEST, })).toEqual({ ...initialState, inProgress: true, }); }); it('should handle INGREDIENTS_REQUEST_SUCCESS', () => { expect(ingredientsReducer({ ...initialState, inProgress: true, }, { type: types.INGREDIENTS_REQUEST_SUCCESS, payload: ingredientsMock, })).toEqual({ ...initialState, inProgress: false, ingredients: ingredientsMock, }); }); it('should handle INGREDIENTS_REQUSET_FAILED', () => { expect(ingredientsReducer({ ...initialState, inProgress: true, }, { type: types.INGREDIENTS_REQUSET_FAILED, payload: 'Ошибка получения данных...', })).toEqual({ ...initialState, inProgress: false, ingredientsError: 'Ошибка получения данных...', }); }); it('should handle SHOW_INGREDIENT_INFO', () => { expect(ingredientsReducer(initialState, { type: types.SHOW_INGREDIENT_INFO, payload: ingredientsMock[0], })).toEqual({ ...initialState, ingredientInfo: ingredientsMock[0], }); }); it('should handle CLEAR_INGREDIENT_INFO', () => { expect(ingredientsReducer({ ...initialState, ingredientInfo: ingredientsMock[0], }, { type: types.CLEAR_INGREDIENT_INFO, })).toEqual(initialState); }); });
function Amazon(jsdom, jquery) { /* * Returns the first page of search results from Amazon's mobile search */ this.search = function(keywords, callback) { searchURL = "http://www.amazon.com/gp/aw/s/ref=is_box_?k="+keywords; jsdom.env(searchURL, [jquery], function (errors, window) { if (errors) callback(errors); else { var results = []; var prices = window.$('font:contains(Price) font b'); window.$('form[method=post] > a').each(function(i, e) { results.push({ name: e.textContent, price: (prices[i] ? prices[i].textContent : "N/A"), url: e.href }); }); callback(null, results); } }) } /* * Uses the search method to retrieve search results based on the * keyword, accesses the given product URL and retrieves the customer * rating. The rating is also provided as a percent for convenience. */ this.rating = function(keywords, callback) { this.search(keywords, function(err, results) { if (results.length > 0) { var result = results[0]; jsdom.env(result.url, [jquery], function (errors, window) { if (errors) callback(errors); else { var html = window.$('body').html(), ratingData = html.match(/\:&nbsp;(\d+\.?\d+)&nbsp;\/&nbsp;(\d+\.?\d+)/); if (ratingData) { result.rating = parseFloat(ratingData[1]); result.ratingPercent = (result.rating[0] / 5.0) * 100; } else { result.rating = "N/A"; result.ratingPercent = "N/A"; } callback(null, result); } }) } else callback(null, {}); }); }.bind(this); }; module.exports = Amazon;