text
stringlengths
7
3.69M
$(function() { console.log("jQuery onReady..."); $('#insertGitHubIssue').click(function(e){ if ($('#insertGitHubIssue').hasClass('disabled')) { return; } // end if $('#insertGitHubIssue').addClass('disabled'); var imageUrl = $('#logo').attr('src'); var serverRoot = gadgets.config.get()['jive-opensocial-ext-v1']['jiveUrl']; imageUrl = imageUrl.replace('//' + serverRoot.split('//')[1], serverRoot); osapi.jive.core.container.closeApp({ data:{ display: { type:"text", icon: imageUrl, label: $('#gitHubIssueURI').val() }, target: { type: "embed", view: "github4jive-issue-view", context: { uri: $('#gitHubIssueURI').val() } } } }); }); }); gadgets.util.registerOnLoadHandler(function() { console.log("gadgets onLoad..."); gadgets.window.adjustHeight(); gadgets.window.adjustWidth(); });
import React from 'react' import { shallow, mount } from 'enzyme' import NavbarDesktop from './NavbarDesktop' import { testAvatarWithUsernameRender } from '../generic/AvatarWithUsername.test' const props = { user: { id: 3114942045618176, first_name: 'Lou', last_name: 'Manetti', avatar: 'https://picsum.photos/g/200', role: 'Software Developer', city: 'Sibiu', books_number: 4, return_date: '2019-03-25T18:54:21.939Z' }, logout: () => {}, goToProfile: () => {} } describe('NavbarDesktop component tests', () => { it('renders without crashing', () => { const wrapper = shallow(<NavbarDesktop {...props} />) expect(wrapper.find('Dropdown').length).toBe(1) }) it('shallow renders without crashing', () => { const wrapper = shallow(<NavbarDesktop {...props} />) expect(wrapper.find('Dropdown').length).toBe(1) }) it('mount renders without crashing', () => { const wrapper = mount(<NavbarDesktop {...props} />) testAvatarWithUsernameRender(wrapper) }) })
import App from './app/app'; import ConfigCenter from './config-center/config-center'; import lib from './util/lib'; import event from './util/event'; import Uploader from './component/uploader'; import Outlet from './component/outlet'; import ImportExcel from './page/import-excel'; export {App, ConfigCenter, Uploader, Outlet, ImportExcel ,lib, event};
URL = "http://10.10.10.134:9988" monitorSearchResults = "" environment = "test" userID = "" version = ""//desktopWidget code = "" loading = '<div style="margin: 50px 0px 0px 110px; font-size: 20px"><img src="./img/Loading.gif" alt="" />&nbsp;&nbsp;Loading...</div>' processing = '<div style="margin: 50px 0px 0px 90px; font-size: 18px">Processing Your Content...</div>' currentPage = "" isMenuOpen = false isCurrentItemChanged = false currentItem = ""
module.exports = function($, _){ return (function(){ var self = this; var storage = {}; this.setPassword = function(name, value, life){ storage[name] = { value: value, visit: new Date().getTime(), life: life * 1000, }; }; this.getPassword = function(name){ if(undefined != storage[name]){ storage[name].visit = new Date().getTime(); return storage[name].value; } else return false; }; this.deletePassword = function(name){ String("The stored password [" + name + "] is now deleted.") .NOTICE(); if(undefined != storage[name]) delete storage[name]; }; this.deleteAllPassword = function(){ String("All passwords stored in memory now deleted.").NOTICE(); storage = {}; }; function refreshStatus(){ var delList = [], now = new Date().getTime(); for(var i in storage){ if(storage[i].visit + storage[i].life < now) delList.push(i); }; for(var i in delList) self.deletePassword(delList[i]); setTimeout(refreshStatus, 300); }; refreshStatus(); return this; })(); };
const TestArticle = () => ( <div className="article"> <div className="imageDiv" style={{ backgroundImage: "url('https://static01.nyt.com/images/2021/02/16/nyregion/16nymayor-johnson/16nymayor-johnson-facebookJumbo.jpg')", backgroundSize: 'cover', }} ></div> <span className="title"> Corey Johnson Exited the N.Y.C. Mayor’s Race. Will He Run for Comptroller? </span> <span className="content"> Mr. Johnson said he would make a final decision on the comptrollers race in the next two weeks, before petitioning is set to start. If he joins the race, he will be able to use the money he raised i… [+1257 chars] </span> <p className="author">Jeffery C. Mays and Emma G. Fitzsimmons</p> <a href="https://www.nytimes.com/2021/02/16/nyregion/corey-johnson-nyc-comptroller.html"> <span className="link">New York Times</span> </a> </div> );
'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _utilsDomUtils = require('../../utils/dom-utils'); var _utilsKey = require('../../utils/key'); var _utilsAssert = require('../../utils/assert'); var _modelsMarker = require('../../models/marker'); function findParentSectionFromNode(renderTree, node) { var renderNode = renderTree.findRenderNodeFromElement(node, function (renderNode) { return renderNode.postNode.isSection; }); return renderNode && renderNode.postNode; } function findOffsetInMarkerable(markerable, node, offset) { var offsetInSection = 0; var marker = markerable.markers.head; while (marker) { var markerNode = marker.renderNode.element; if (markerNode === node) { return offsetInSection + offset; } else if (marker.isAtom) { if (marker.renderNode.headTextNode === node) { return offsetInSection; } else if (marker.renderNode.tailTextNode === node) { return offsetInSection + 1; } } offsetInSection += marker.length; marker = marker.next; } return offsetInSection; } function findOffsetInSection(section, node, offset) { if (section.isMarkerable) { return findOffsetInMarkerable(section, node, offset); } else { (0, _utilsAssert['default'])('findOffsetInSection must be called with markerable or card section', section.isCardSection); var wrapperNode = section.renderNode.element; var endTextNode = wrapperNode.lastChild; if (node === endTextNode) { return 1; } return 0; } } var Position = (function () { function Position(section) { var offset = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; _classCallCheck(this, Position); (0, _utilsAssert['default'])('Position must have a section that is addressable by the cursor', section && section.isLeafSection); (0, _utilsAssert['default'])('Position must have numeric offset', offset !== null && offset !== undefined); this.section = section; this.offset = offset; this.isBlank = false; } _createClass(Position, [{ key: 'clone', value: function clone() { return new Position(this.section, this.offset); } }, { key: 'isEqual', value: function isEqual(position) { return this.section === position.section && this.offset === position.offset; } }, { key: 'isHead', value: function isHead() { return this.isEqual(this.section.headPosition()); } }, { key: 'isTail', value: function isTail() { return this.isEqual(this.section.tailPosition()); } /** * This method returns a new Position instance, it does not modify * this instance. * * @param {Direction} direction to move * @return {Position|null} Return the position one unit in the given * direction, or null if it is not possible to move that direction */ }, { key: 'move', value: function move(direction) { switch (direction) { case _utilsKey.DIRECTION.BACKWARD: return this.moveLeft(); case _utilsKey.DIRECTION.FORWARD: return this.moveRight(); default: (0, _utilsAssert['default'])('Must pass a valid direction to Position.move', false); } } /** * @return {Position|null} */ }, { key: 'moveLeft', value: function moveLeft() { if (this.isHead()) { var prev = this.section.previousLeafSection(); return prev && prev.tailPosition(); } else { var offset = this.offset - 1; if (this.isMarkerable && this.marker) { var code = this.marker.value.charCodeAt(offset); if (code >= _modelsMarker.LOW_SURROGATE_RANGE[0] && code <= _modelsMarker.LOW_SURROGATE_RANGE[1]) { offset = offset - 1; } } return new Position(this.section, offset); } } /** * @return {Position|null} */ }, { key: 'moveRight', value: function moveRight() { if (this.isTail()) { var next = this.section.nextLeafSection(); return next && next.headPosition(); } else { var offset = this.offset + 1; if (this.isMarkerable && this.marker) { var code = this.marker.value.charCodeAt(offset - 1); if (code >= _modelsMarker.HIGH_SURROGATE_RANGE[0] && code <= _modelsMarker.HIGH_SURROGATE_RANGE[1]) { offset = offset + 1; } } return new Position(this.section, offset); } } }, { key: 'leafSectionIndex', get: function get() { var _this = this; var post = this.section.post; var leafSectionIndex = undefined; post.walkAllLeafSections(function (section, index) { if (section === _this.section) { leafSectionIndex = index; } }); return leafSectionIndex; } }, { key: 'isMarkerable', get: function get() { return this.section && this.section.isMarkerable; } }, { key: 'marker', get: function get() { return this.isMarkerable && this.markerPosition.marker; } }, { key: 'offsetInMarker', get: function get() { return this.markerPosition.offset; } }, { key: 'markerPosition', /** * @private */ get: function get() { (0, _utilsAssert['default'])('Cannot get markerPosition without a section', !!this.section); (0, _utilsAssert['default'])('cannot get markerPosition of a non-markerable', !!this.section.isMarkerable); return this.section.markerPositionAtOffset(this.offset); } }], [{ key: 'blankPosition', value: function blankPosition() { return { section: null, offset: 0, marker: null, offsetInTextNode: 0, isBlank: true, isEqual: function isEqual(other) { return other.isBlank; }, markerPosition: {} }; } }, { key: 'fromNode', value: function fromNode(renderTree, node, offset) { if ((0, _utilsDomUtils.isTextNode)(node)) { return Position.fromTextNode(renderTree, node, offset); } else { return Position.fromElementNode(renderTree, node, offset); } } }, { key: 'fromTextNode', value: function fromTextNode(renderTree, textNode, offsetInNode) { var renderNode = renderTree.getElementRenderNode(textNode); var section = undefined, offsetInSection = undefined; if (renderNode) { var marker = renderNode.postNode; section = marker.section; (0, _utilsAssert['default'])('Could not find parent section for mapped text node "' + textNode.textContent + '"', !!section); offsetInSection = section.offsetOfMarker(marker, offsetInNode); } else { // all text nodes should be rendered by markers except: // * text nodes inside cards // * text nodes created by the browser during text input // both of these should have rendered parent sections, though section = findParentSectionFromNode(renderTree, textNode); (0, _utilsAssert['default'])('Could not find parent section for un-mapped text node "' + textNode.textContent + '"', !!section); offsetInSection = findOffsetInSection(section, textNode, offsetInNode); } return new Position(section, offsetInSection); } }, { key: 'fromElementNode', value: function fromElementNode(renderTree, elementNode, offset) { var position = undefined; // The browser may change the reported selection to equal the editor's root // element if the user clicks an element that is immediately removed, // which can happen when clicking to remove a card. if (elementNode === renderTree.rootElement) { var post = renderTree.rootNode.postNode; position = offset === 0 ? post.headPosition() : post.tailPosition(); } else { var section = findParentSectionFromNode(renderTree, elementNode); (0, _utilsAssert['default'])('Could not find parent section from element node', !!section); if (section.isCardSection) { // Selections in cards are usually made on a text node // containing a &zwnj; on one side or the other of the card but // some scenarios (Firefox) will result in selecting the // card's wrapper div. If the offset is 2 we've selected // the final zwnj and should consider the cursor at the // end of the card (offset 1). Otherwise, the cursor is at // the start of the card position = offset < 2 ? section.headPosition() : section.tailPosition(); } else { // In Firefox it is possible for the cursor to be on an atom's wrapper // element. (In Chrome/Safari, the browser corrects this to be on // one of the text nodes surrounding the wrapper). // This code corrects for when the browser reports the cursor position // to be on the wrapper element itself var renderNode = renderTree.getElementRenderNode(elementNode); var postNode = renderNode && renderNode.postNode; if (postNode && postNode.isAtom) { var sectionOffset = section.offsetOfMarker(postNode); if (offset > 1) { // we are on the tail side of the atom sectionOffset += postNode.length; } position = new Position(section, sectionOffset); } else { // The offset is 0 if the cursor is on a non-atom-wrapper element node // (e.g., a <br> tag in a blank markup section) position = section.headPosition(); } } } return position; } }]); return Position; })(); exports['default'] = Position;
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); console.log(web3.currentProvider); //var profesorContract = web3.eth.contract([{"constant":false,"inputs":[],"name":"Professor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_fname","type":"string"},{"name":"_lname","type":"string"},{"name":"_id","type":"uint256"}],"name":"setProfessor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"firstname","type":"string"},{"indexed":false,"name":"lastname","type":"string"},{"indexed":false,"name":"collegeid","type":"uint256"}],"name":"ProfessorEv","type":"event"}]); abi = JSON.parse('[{"constant":false,"inputs":[],"name":"Professor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_fname","type":"string"},{"name":"_lname","type":"string"},{"name":"_id","type":"uint256"}],"name":"setProfessor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"firstname","type":"string"},{"indexed":false,"name":"lastname","type":"string"},{"indexed":false,"name":"collegeid","type":"uint256"}],"name":"ProfessorEv","type":"event"}]'); var ProfContract = web3.eth.contract(abi); contractInstance = ProfContract.at('0x51b666962135943266757af912c05e3f161c9d9d'); $(document).ready(function() { contractInstance.ProfessorEv().watch(function(error, result){ if (!error){ console.log(result.args.firstname); console.log(result.args.lastname); console.log(result.args.collegeid); } else { console.log(error); } }); window.addEventListener('load', function () { if (typeof web3 !== 'undefined') { console.log('Web3 Detected! ' + web3.currentProvider.constructor.name) window.web3 = new Web3(web3.currentProvider); } else { console.log('No Web3 Detected... using HTTP Provider') window.web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/<APIKEY>")); } }) $("#button").click(function() { contractInstance.setProfessor('Billy','Luy',1234, {from: web3.eth.accounts[0]}, function() { }); }); });
import moment from 'moment' // ------------------------------------------------------- // タイムスタンプの取得 // ------------------------------------------------------- export function getTimeStampCreated (userId) { const timestamp = moment().format() const uid = userId return { _created_at: timestamp, _created_by: uid, _updated_at: timestamp, _updated_by: uid } } export function getTimeStampUpdated (userId) { const timestamp = moment().format() const uid = userId return { _updated_at: timestamp, _updated_by: uid } }
export { Model } from './model' export { Store } from './store'
function mostrar() { var edad; var estadoCivilPersona; edad = txtIdEdad.value; estadoCivilPersona = estadoCivil.value; if (edad <18 && estadoCivilPersona != "Soltero") { alert ("es muy joven para no ser soltero"); } }
import commonHandler from './commonHandler.js' import createModul from '../Moduls/createModul.js' import notifyHandler from './notifyHandler.js' import redirectionHandler from './redirectionHandler.js' export default async function createTrek() { this.username = localStorage.getItem('username') this.token = localStorage.getItem('token') await commonHandler.call(this, 'Views/Movies/add.hbs') let form = document.getElementsByTagName('form')[0] form.addEventListener('submit', (e) => { e.preventDefault() notifyHandler(null, 'loadingBox') createModul.call(this, form, this.username, this.token) .then((response) => { notifyHandler('Created successfully!', 'successBox') redirectionHandler.call(this, '#/') }).catch((error) => { if (error.message) { notifyHandler(error.message, 'errorBox') } else { notifyHandler(error, 'errorBox') } }) }) }
var express = require('express'); var bodyParser = require('body-parser'); var morgan = require('morgan'); var config = require("./config"); var mongoose = require('mongoose'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var db = mongoose.connection; mongoose.connect('mongodb://localhost/teamapp',function (err) { if(err){ console.log("Database connect error "+ err); } }); app.use(bodyParser.urlencoded({ extended: true})); app.use(bodyParser.json()); //app.use(morgan('dev')); //to log all the request to the console // All the static html, css, js file needs to be rendered and thus we put those into public directory // The below statment should come before any routing happens app.use(express.static(__dirname + '/public')); var api = require('./app/routes/api')(app,express,io); app.use('/api',api); app.get('*',function (req, res) { res.sendFile(__dirname + '/public/app/views/index.html'); }); http.listen(config.port,function(err){ if(err){ console.log("Error occured " + err); }else { console.log("listening on port 3000"); } });
var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Utils; (function (Utils) { ; var HashSet = /** @class */ (function () { function HashSet() { this.items = {}; } HashSet.prototype.set = function (key, value) { this.items[key] = value; }; HashSet.prototype["delete"] = function (key) { return delete this.items[key]; }; HashSet.prototype.has = function (key) { return key in this.items; }; HashSet.prototype.get = function (key) { return this.items[key]; }; HashSet.prototype.len = function () { return Object.keys(this.items).length; }; HashSet.prototype.forEach = function (f) { for (var k in this.items) { f(k, this.items[k]); } }; return HashSet; }()); Utils.HashSet = HashSet; })(Utils || (Utils = {})); /* ========================================================================= * * Component.ts * Each entity can obtain many components * * ========================================================================= */ /// <reference path="./HashSet.ts" /> var ECS; (function (ECS) { var Component = /** @class */ (function () { function Component(name) { this.name = name; } return Component; }()); ECS.Component = Component; })(ECS || (ECS = {})); /* ========================================================================= * * Utils.ts * Tools * * ========================================================================= */ var Utils; (function (Utils) { var DeviceDetect = /** @class */ (function () { function DeviceDetect() { this.arora = false; this.chrome = false; this.epiphany = false; this.firefox = false; this.mobileSafari = false; this.ie = false; this.ieVersion = 0; this.midori = false; this.opera = false; this.safari = false; this.webApp = false; this.cocoonJS = false; this.android = false; this.chromeOS = false; this.iOS = false; this.linux = false; this.macOS = false; this.windows = false; this.desktop = false; this.pixelRatio = 0; this.iPhone = false; this.iPhone4 = false; this.iPad = false; this.blob = false; this.canvas = false; this.localStorage = false; this.file = false; this.fileSystem = false; this.webGL = false; this.worker = false; this.audioData = false; this.webAudio = false; this.ogg = false; this.opus = false; this.mp3 = false; this.wav = false; this.m4a = false; this.webm = false; this.touch = false; var ua = navigator.userAgent; this.CheckBrowser(ua); this.CheckOS(ua); this.CheckDevice(); this.CheckAudio(); this.CheckFeatures(); } DeviceDetect.prototype.CheckBrowser = function (ua) { if (/Arora/.test(ua)) { this.arora = true; } else if (/Chrome/.test(ua)) { this.chrome = true; } else if (/Epiphany/.test(ua)) { this.epiphany = true; } else if (/Firefox/.test(ua)) { this.firefox = true; } else if (/Mobile Safari/.test(ua)) { this.mobileSafari = true; } else if (/MSIE (\d+\.\d+);/.test(ua)) { this.ie = true; this.ieVersion = parseInt(RegExp.$1, 10); } else if (/Midori/.test(ua)) { this.midori = true; } else if (/Opera/.test(ua)) { this.opera = true; } else if (/Safari/.test(ua)) { this.safari = true; } // Native Application if (navigator['standalone']) { this.webApp = true; } // CocoonJS Application if (navigator['isCocoonJS']) { this.cocoonJS = true; } }; DeviceDetect.prototype.CheckOS = function (ua) { if (/Android/.test(ua)) { this.android = true; } else if (/CrOS/.test(ua)) { this.chromeOS = true; } else if (/iP[ao]d|iPhone/i.test(ua)) { this.iOS = true; } else if (/Linux/.test(ua)) { this.linux = true; } else if (/Mac OS/.test(ua)) { this.macOS = true; } else if (/Windows/.test(ua)) { this.windows = true; } if (this.windows || this.macOS || this.linux) { this.desktop = true; } }; DeviceDetect.prototype.CheckDevice = function () { this.pixelRatio = window['devicePixelRatio'] || 1; this.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1; this.iPhone4 = (this.pixelRatio === 2 && this.iPhone); this.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') !== -1; }; DeviceDetect.prototype.CheckFeatures = function () { if (typeof window['Blob'] !== 'undefined') this.blob = true; this.canvas = !!window['CanvasRenderingContext2D']; try { this.localStorage = !!localStorage.getItem; } catch (error) { this.localStorage = false; } this.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; this.fileSystem = !!window['requestFileSystem']; this.webGL = !!window['WebGLRenderingContext']; this.worker = !!window['Worker']; if ('ontouchstart' in document.documentElement || window.navigator.msPointerEnabled) { this.touch = true; } }; DeviceDetect.prototype.CheckAudio = function () { this.audioData = !!(window['Audio']); this.webAudio = !!(window['webkitAudioContext'] || window['AudioContext']); var audioElement = document.createElement('audio'); var result = false; try { if (result = !!audioElement.canPlayType) { if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) { this.ogg = true; } if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) { this.mp3 = true; } // Mimetypes accepted: // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements // bit.ly/iphoneoscodecs if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) { this.wav = true; } if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) { this.m4a = true; } } } catch (e) { } }; DeviceDetect.prototype.PrintInfo = function () { var output = "DEVICE OUTPUT\n\n"; output += "---\n"; output += "Browser Info :: \n"; output += "Arora : " + this.arora + "\n"; output += "Chrome : " + this.chrome + "\n"; output += "Epiphany : " + this.epiphany + "\n"; output += "Firefox : " + this.firefox + "\n"; output += "Mobile Safari : " + this.mobileSafari + "\n"; output += "IE : " + this.ie; if (this.ie) { output += " (Version " + this.ieVersion + ")\n"; } else { output += "\n"; } output += "Midori : " + this.midori + "\n"; output += "Opera : " + this.opera + "\n"; output += "Safari : " + this.safari + "\n"; output += "Web App : " + this.webApp + "\n"; output += "CocoonJS : " + this.cocoonJS + "\n"; output += "Android : " + this.android + "\n"; output += "---\n"; output += "Operating System :: \n"; output += "Chrome OS : " + this.chromeOS + "\n"; output += "iOS : " + this.iOS + "\n"; output += "Linux : " + this.linux + "\n"; output += "Mac OS : " + this.macOS + "\n"; output += "Windows : " + this.windows + "\n"; output += "Desktop : " + this.desktop + "\n"; output += "---\n"; output += "Device Type : \n"; output += "Pixel Ratio : " + this.pixelRatio + "\n"; output += "iPhone : " + this.iPhone + "\n"; output += "iPhone 4 : " + this.iPhone4 + "\n"; output += "iPad : " + this.iPad + "\n"; output += "---\n"; output += "Features :: \n"; output += "Blob : " + this.blob + "\n"; output += "Canvas : " + this.canvas + "\n"; output += "LocalStorage : " + this.localStorage + "\n"; output += "File : " + this.file + "\n"; output += "File System : " + this.fileSystem + "\n"; output += "WebGL : " + this.webGL + "\n"; output += "Workers : " + this.worker + "\n"; output += "---\n"; output += "Audio :: \n"; output += "AudioData : " + this.audioData + "\n"; output += "WebAudio : " + this.webAudio + "\n"; output += "Supports .ogg : " + this.ogg + "\n"; output += "Supports Opus : " + this.opus + "\n"; output += "Supports .mp3 : " + this.mp3 + "\n"; output += "Supports .wav : " + this.wav + "\n"; output += "Supports .m4a : " + this.m4a + "\n"; output += "Supports .webm : " + this.webm; return output; }; return DeviceDetect; }()); Utils.DeviceDetect = DeviceDetect; })(Utils || (Utils = {})); /* ========================================================================= * * GameLocalData.ts * local storage for game * * ========================================================================= */ var ECS; (function (ECS) { var GameLocalData = /** @class */ (function () { function GameLocalData(id) { this.id = id; } GameLocalData.prototype.store = function (key, value) { localStorage.setItem(this.id + '.' + key, value); }; GameLocalData.prototype.get = function (key) { return localStorage.getItem(this.id + '.' + key) || 0; }; GameLocalData.prototype.remove = function (key) { localStorage.removeItem(this.id + '.' + key); }; GameLocalData.prototype.reset = function () { for (var i in localStorage) { if (i.indexOf(this.id + '.') !== -1) localStorage.removeItem(i); } }; return GameLocalData; }()); ECS.GameLocalData = GameLocalData; })(ECS || (ECS = {})); /* ========================================================================= * * GameAudio.ts * music for game(using cocoonjs and howl) * * ========================================================================= */ /// <reference path="./GameLocalData.ts" /> /// <reference path="./GameConfig.ts" /> /// <reference path="./Utils.ts" /> var ECS; (function (ECS) { var GameAudio = /** @class */ (function () { function GameAudio() { this.soundPool = {}; this.device = new Utils.DeviceDetect(); this.localData = new ECS.GameLocalData(ECS.GameConfig.localID); this.soundList = [ { src: './audio/startScreen', volume: 0.6, maxVolume: 0.6, loop: true, autoPlay: false, type: 'music', name: 'StartMusic' }, { src: './audio/gameScreen', volume: 0.6, maxVolume: 0.6, loop: true, autoPlay: false, type: 'music', name: 'GameMusic' }, { src: './audio/jump01', volume: 0.6, maxVolume: 0.6, loop: false, autoPlay: false, type: 'music', name: 'jump' }, { src: './audio/indoNTiger', volume: 0.6, maxVolume: 0.6, loop: false, autoPlay: false, type: 'music', name: 'indoMode' }, { src: './audio/ninjiaStart', volume: 0.6, maxVolume: 0.6, loop: false, autoPlay: false, type: 'music', name: 'ninjiaMode' }, { src: './audio/ninjiaAttack', volume: 0.6, maxVolume: 0.6, loop: false, autoPlay: false, type: 'music', name: 'ninjiaModeAttack' }, { src: './audio/superMario', volume: 0.6, maxVolume: 0.6, loop: true, autoPlay: false, type: 'music', name: 'superMarioMode' }, { src: './audio/catCome', volume: 0.6, maxVolume: 0.6, loop: false, autoPlay: false, type: 'music', name: 'catCome' }, { src: './audio/catDead', volume: 0.6, maxVolume: 0.6, loop: false, autoPlay: false, type: 'music', name: 'catDead' }, { src: './audio/pickUpFood', volume: 0.6, maxVolume: 0.6, loop: false, autoPlay: false, type: 'music', name: 'pickUpFood' }, { src: './audio/playerDead', volume: 0.6, maxVolume: 0.6, loop: false, autoPlay: false, type: 'music', name: 'playerDead' } ]; this.init(); } GameAudio.prototype.init = function () { for (var i = 0; i < this.soundList.length; i++) { var cSound = this.soundList[i]; cSound.audio = new Howl({ src: [cSound.src + ".mp3"], html5: true, loop: cSound.loop, onload: function () { }, onloaderror: function () { alert("load sound error!"); } }); this.soundPool[cSound.name] = cSound; } }; GameAudio.prototype.play = function (id) { if (this.soundPool.hasOwnProperty(id)) { this.soundPool[id].audio.play(); } else { console.log("WARNING :: Couldn't find sound '" + id + "'."); } }; GameAudio.prototype.soundExists = function (id) { return this.soundPool.hasOwnProperty(id); }; GameAudio.prototype.setVolume = function (id, volume) { if (!this.soundExists(id)) return; Howler.volume(volume); }; GameAudio.prototype.stop = function (id) { this.soundPool[id].audio.stop(); }; return GameAudio; }()); ECS.GameAudio = GameAudio; })(ECS || (ECS = {})); /* ========================================================================= * * GameConfig.ts * config file * * ========================================================================= */ /// <reference path="./HashSet.ts" /> /// <reference path="./GameAudio.ts" /> var ECS; (function (ECS) { var GameRunTime = /** @class */ (function () { function GameRunTime() { this.DELTA_TIME = 1; this.lastTime = Date.now(); this.speed = 1; } GameRunTime.prototype.update = function () { var time = Date.now(); var currentTime = time; this.currentTime = currentTime; //console.log("current time:"+currentTime); var passedTime = currentTime - this.lastTime; this.DELTA_TIME = ((passedTime) * 0.06); this.DELTA_TIME *= this.speed; if (this.DELTA_TIME > 2.3) this.DELTA_TIME = 2.3; this.lastTime = currentTime; }; return GameRunTime; }()); ECS.GameRunTime = GameRunTime; var FOODMODE; (function (FOODMODE) { FOODMODE[FOODMODE["JAPAN"] = 0] = "JAPAN"; FOODMODE[FOODMODE["INDON"] = 1] = "INDON"; })(FOODMODE = ECS.FOODMODE || (ECS.FOODMODE = {})); var SPECIALMODE; (function (SPECIALMODE) { SPECIALMODE[SPECIALMODE["NONE"] = 0] = "NONE"; SPECIALMODE[SPECIALMODE["JAPANMODE"] = 1] = "JAPANMODE"; SPECIALMODE[SPECIALMODE["INDONMODE"] = 2] = "INDONMODE"; SPECIALMODE[SPECIALMODE["NINJAMODE"] = 3] = "NINJAMODE"; })(SPECIALMODE = ECS.SPECIALMODE || (ECS.SPECIALMODE = {})); var GAMEMODE; (function (GAMEMODE) { GAMEMODE[GAMEMODE["TITLE"] = 0] = "TITLE"; GAMEMODE[GAMEMODE["COUNT_DOWN"] = 1] = "COUNT_DOWN"; GAMEMODE[GAMEMODE["PLAYING"] = 2] = "PLAYING"; GAMEMODE[GAMEMODE["GAME_OVER"] = 3] = "GAME_OVER"; GAMEMODE[GAMEMODE["INTRO"] = 4] = "INTRO"; GAMEMODE[GAMEMODE["PAUSED"] = 5] = "PAUSED"; })(GAMEMODE = ECS.GAMEMODE || (ECS.GAMEMODE = {})); var PLAYMODE; (function (PLAYMODE) { PLAYMODE[PLAYMODE["RUNNING"] = 0] = "RUNNING"; PLAYMODE[PLAYMODE["JUMPING1"] = 1] = "JUMPING1"; PLAYMODE[PLAYMODE["JUMPING2"] = 2] = "JUMPING2"; PLAYMODE[PLAYMODE["FALL"] = 3] = "FALL"; PLAYMODE[PLAYMODE["SLIDE"] = 4] = "SLIDE"; })(PLAYMODE = ECS.PLAYMODE || (ECS.PLAYMODE = {})); var GameConfig = /** @class */ (function () { function GameConfig() { } GameConfig.timeClock = function () { return this.tmpTimeClockEnd - this.tmpTimeClockStart; }; GameConfig.timeClock1 = function () { return this.tmpTimeClockEnd1 - this.tmpTimeClockStart1; }; GameConfig.width = 800; GameConfig.height = 600; GameConfig.fixedHeight = 600; GameConfig.xOffset = 0; GameConfig.high_mode = true; GameConfig.camera = new PIXI.Point(); GameConfig.localID = "rw.raymond.wang"; GameConfig.newHighScore = false; GameConfig.time = new GameRunTime(); GameConfig.interactive = true; GameConfig.specialMode = SPECIALMODE.NONE; GameConfig.isOnPlat = false; return GameConfig; }()); ECS.GameConfig = GameConfig; })(ECS || (ECS = {})); /* ========================================================================= * * System.ts * system using for controlling the game * * ========================================================================= */ /// <reference path="./HashSet.ts" /> /// <reference path="./Utils.ts" /> /// <reference path="./GameConfig.ts" /> var ECS; (function (ECS) { var System = /** @class */ (function () { function System(name) { this.name = name; } System.prototype.Init = function () { console.log("[" + this.name + "]System initialization!"); }; System.prototype.Execute = function () { console.log("[" + this.name + "]System Execute!"); }; return System; }()); ECS.System = System; })(ECS || (ECS = {})); /* ========================================================================= * * Entity.js * Each entity has an unique ID * * ========================================================================= */ /// <reference path="./Component.ts" /> /// <reference path="./HashSet.ts" /> var ECS; (function (ECS) { var Entity = /** @class */ (function () { function Entity(name) { this.name = name; this.id = (+new Date()).toString(16) + (Math.random() * 100000000 | 0).toString(16) + this.count; this.count++; this.components = new Utils.HashSet(); } Entity.prototype.addComponent = function (component) { this.components.set(component.name, component); //console.log("add ["+component.name+"] component"); }; Entity.prototype.removeComponent = function (component) { var name = component.name; var deletOrNot = this.components["delete"](name); if (deletOrNot) { console.log("delete [" + name + "] success!"); } else { console.log("delete [" + name + "] fail! not exist!"); } }; return Entity; }()); ECS.Entity = Entity; })(ECS || (ECS = {})); /* ========================================================================= * * GameBackGround.ts * game view scene - background * * ========================================================================= */ /// <reference path="./System.ts" /> var ECS; (function (ECS) { var BackGroundElement = /** @class */ (function () { function BackGroundElement(texture) { this.sprites = []; this.spriteWidth = texture.width - 5; this.spriteHeight = ECS.GameConfig.height * 4 / 5; var amount = 3; for (var i = 0; i < amount; i++) { var sprite = new PIXI.Sprite(texture); sprite.height = ECS.GameConfig.height * 4 / 5; sprite.position.y = 0; this.sprites.push(sprite); } ; this.speed = 1; } BackGroundElement.prototype.setPosition = function (position) { var h = this.spriteWidth; for (var i = 0; i < this.sprites.length; i++) { var pos = -position * this.speed; pos += i * h; pos %= h * this.sprites.length; pos += h / 2; if (!ECS.GameConfig.device.desktop) pos += h / 2; this.sprites[i].position.x = pos; } ; }; return BackGroundElement; }()); ECS.BackGroundElement = BackGroundElement; var GameBackGroundSystem = /** @class */ (function (_super) { __extends(GameBackGroundSystem, _super); function GameBackGroundSystem() { var _this = _super.call(this, "view-background") || this; _this.BackGroundContainer = new PIXI.Container(); _this.width = ECS.GameConfig.width; _this.scrollPosition = ECS.GameConfig.camera.x; var bgTex = PIXI.loader.resources["img/bg_up.png"].texture; if (!ECS.GameConfig.device.desktop) bgTex = PIXI.loader.resources["img/bg_up_ios.png"].texture; _this.bgTex = new BackGroundElement(bgTex); for (var i = 0; i < _this.bgTex.sprites.length; i++) { _this.BackGroundContainer.addChild(_this.bgTex.sprites[i]); } _this.groundAssetList = [ "obstacle-11.png", "tree1.png", "obstacle-13.png", "tree2.png" ]; _this.groundSpriteList = []; for (var i = 0; i < _this.groundAssetList.length; i++) { var gSprite = PIXI.Sprite.fromFrame(_this.groundAssetList[i]); gSprite.anchor.x = 0.5; gSprite.anchor.y = 0.5; gSprite.width = 140 * ECS.GameConfig.height / ECS.GameConfig.fixedHeight; gSprite.height = 240 * ECS.GameConfig.height / ECS.GameConfig.fixedHeight; gSprite.position.y = _this.bgTex.spriteHeight - gSprite.height / 2; _this.BackGroundContainer.addChild(gSprite); _this.groundSpriteList.push(gSprite); } _this.cloud1 = PIXI.Sprite.fromFrame("cloud1.png"); _this.cloud1.position.y = ECS.GameConfig.height / 5; _this.BackGroundContainer.addChild(_this.cloud1); _this.cloud2 = PIXI.Sprite.fromFrame("cloud2.png"); _this.cloud2.position.y = ECS.GameConfig.height / 8; _this.BackGroundContainer.addChild(_this.cloud2); ; _this.bgTex.speed = 1 / 2; ECS.GameConfig.app.ticker.add(function (delta) { // console.log("background run!"); _this.scrollPosition = ECS.GameConfig.camera.x; var intervalDistance = _this.bgTex.sprites[0].width / 4; var cloud1Pos = -_this.scrollPosition * 1.5 / 2; cloud1Pos %= _this.width + intervalDistance; cloud1Pos += _this.width + intervalDistance; cloud1Pos -= _this.cloud1.width / 2; _this.cloud1.position.x = cloud1Pos - ECS.GameConfig.xOffset; var cloud2Pos = -(_this.scrollPosition + _this.width / 2) * 1.5 / 2; cloud2Pos %= _this.width + intervalDistance; cloud2Pos += _this.width + intervalDistance; cloud2Pos -= _this.cloud2.width / 2; _this.cloud2.position.x = cloud2Pos - ECS.GameConfig.xOffset; // for (var i = 0; i < _this.groundAssetList.length; i++) { var gSpritePos = -(_this.scrollPosition + _this.width * (i + 1)) * 3 / 4; gSpritePos %= _this.width + intervalDistance; gSpritePos += _this.width + intervalDistance; gSpritePos -= _this.groundSpriteList[i].width / 2; _this.groundSpriteList[i].position.x = gSpritePos - ECS.GameConfig.xOffset; } _this.bgTex.setPosition(_this.scrollPosition); }); return _this; } return GameBackGroundSystem; }(ECS.System)); ECS.GameBackGroundSystem = GameBackGroundSystem; })(ECS || (ECS = {})); /* ========================================================================= * * GameUI.ts * game ui panel * * ========================================================================= */ /// <reference path="./GameConfig.ts" /> var ECS; (function (ECS) { function formatScore(n) { var nArray = n.toString().split(""); var text = ""; var total = nArray.length; var offset = (total % 3) - 1; for (var i = 0; i < total; i++) { text += nArray[i]; } return text; } var GameUIPanelControl = /** @class */ (function () { function GameUIPanelControl() { this.uiContainer = new PIXI.Container(); this.uiBtnAtk = new PIXI.Sprite(PIXI.loader.resources["img/PlayPanel/btn_atk.png"].texture); this.uiBtnJump = new PIXI.Sprite(PIXI.loader.resources["img/PlayPanel/btn_jump.png"].texture); this.uiBtnSlide = new PIXI.Sprite(PIXI.loader.resources["img/PlayPanel/btn_slide.png"].texture); this.uiBtnAtk.anchor.set(0.5); this.uiBtnJump.anchor.set(0.5); this.uiBtnSlide.anchor.set(0.5); this.uiBtnAtk.scale.set(0.4); this.uiBtnJump.scale.set(0.5); this.uiBtnSlide.scale.set(0.5); this.uiBtnSlide.position.y = ECS.GameConfig.height * 4 / 5 - this.uiBtnSlide.height / 2; this.uiBtnSlide.position.x = 10 + this.uiBtnSlide.width / 2; this.uiBtnJump.position.y = ECS.GameConfig.height * 4 / 5 - this.uiBtnSlide.height / 2 - this.uiBtnJump.height / 2 - 40; this.uiBtnJump.position.x = 10 + this.uiBtnJump.width / 2; this.uiBtnAtk.position.y = ECS.GameConfig.height * 4 / 5 - this.uiBtnAtk.height / 2 - 10; this.uiBtnAtk.position.x = ECS.GameConfig.width - this.uiBtnAtk.width / 2 - 10; this.uiBtnAtk.interactive = true; this.uiBtnJump.interactive = true; this.uiBtnSlide.interactive = true; //button event listener this.uiBtnAtk.on('touchstart', function () { //console.log('atk'); if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.specialMode == ECS.SPECIALMODE.JAPANMODE) { ECS.GameConfig.audio.play("ninjiaModeAttack"); ECS.GameConfig.game.player.view.textures = ECS.GameConfig.game.player.dashFrames; ECS.GameConfig.game.player.view.play(); ECS.GameConfig.game.player.ninjiaOperate(); } else if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.specialMode == ECS.SPECIALMODE.INDONMODE) { ECS.GameConfig.audio.play("indoMode"); ECS.GameConfig.game.player.view.textures = ECS.GameConfig.game.player.runningFrames; ECS.GameConfig.game.player.view.play(); ECS.GameConfig.game.player.indoOperate(); } }); this.uiBtnJump.on('touchstart', function () { if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.playerMode == ECS.PLAYMODE.RUNNING && !ECS.GameConfig.game.player.isPlayingNinjiaEffect) { ECS.GameConfig.game.player.jump(); ECS.GameConfig.audio.play("jump"); } else if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.playerMode == ECS.PLAYMODE.FALL && ECS.GameConfig.game.player.startJump == true && !ECS.GameConfig.game.player.isPlayingNinjiaEffect) { ECS.GameConfig.game.player.jumpTwo(); ECS.GameConfig.audio.play("jump"); } }); this.uiBtnSlide.on('touchstart', function () { //console.log('slide'); if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.playerMode == ECS.PLAYMODE.RUNNING && ECS.GameConfig.game.player.onGround) { ECS.GameConfig.game.player.slide(true); } }); this.uiBtnSlide.on('touchend', function () { //console.log('slide'); if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.game.player.isSlide) { ECS.GameConfig.game.player.slide(false); } }); this.uiContainer.addChild(this.uiBtnJump); this.uiContainer.addChild(this.uiBtnSlide); this.uiContainer.addChild(this.uiBtnAtk); } return GameUIPanelControl; }()); ECS.GameUIPanelControl = GameUIPanelControl; //UIPanel var GameUIPanelUpRight = /** @class */ (function () { function GameUIPanelUpRight() { this.ratio = 0.6; this.uiContainer = new PIXI.Container(); this.uiList = ["Score.png", "Best Score.png", "Distance.png", "Pause.png"]; this.startXList = new Array(); this.startYList = new Array(); var allSpritesLength = 0; this.uiSprites = []; for (var i = 0; i < this.uiList.length; i++) { this.uiList[i] = PIXI.Texture.fromFrame(this.uiList[i]); this.uiSprites[i] = new PIXI.Sprite(this.uiList[i]); this.uiSprites[i].scale.x = this.ratio; this.uiSprites[i].scale.y = this.ratio; allSpritesLength += this.uiSprites[i].width; } this.startX = ECS.GameConfig.width - allSpritesLength; for (var i = 0; i < this.uiList.length; i++) { this.startXList.push(this.startX); this.startYList.push(this.uiSprites[i].height); this.uiContainer.addChild(this.uiSprites[i]); this.uiSprites[i].position.x = this.startX; this.startX += this.uiSprites[i].width; } } return GameUIPanelUpRight; }()); ECS.GameUIPanelUpRight = GameUIPanelUpRight; var NumberUI = /** @class */ (function () { function NumberUI(startXList, startYList) { this.currentScore = 0; this.ratio = 1; this.xOffset = 15; this.yOffset = 15; this.ratio = 0.3; this.startX = startXList[1]; this.startY = startYList[0]; this.container = new PIXI.Container(); this.tmpList = []; this.numberList = { 0: "Number-0.png", 1: "Number-1.png", 2: "Number-2.png", 3: "Number-3.png", 4: "Number-4.png", 5: "Number-5.png", 6: "Number-6.png", 7: "Number-7.png", 8: "Number-8.png", 9: "Number-9.png" }; for (var s in this.numberList) this.numberList[s] = PIXI.Texture.fromFrame(this.numberList[s]); this.numberSprite = []; for (var i = 0; i < 10; i++) { this.numberSprite[i] = new PIXI.Sprite(this.numberList[i]); this.numberSprite[i].scale.x = this.ratio; this.numberSprite[i].scale.y = this.ratio; } this.setScore(0); } NumberUI.prototype.resetScore = function () { for (var i = 0; i < this.tmpList.length; i++) { this.container.removeChild(this.tmpList[i]); } }; NumberUI.prototype.setScore = function (score) { this.currentScore = score; this.resetScore(); var split = formatScore(score).split(""); var position = this.startX - this.xOffset; var allLength = 0; //count all number length for (var i = 0; i < split.length; i++) { var l = this.numberList[split[i]].width * this.ratio; allLength += l; } position -= allLength; for (var i = 0; i < split.length; i++) { var ns = this.numberSprite[i]; ns.visible = true; ns.setTexture(this.numberList[split[i]]); ns.position.x = position; ns.position.y = this.startY / 2 - this.yOffset; position += ns.width; this.tmpList.push(ns); this.container.addChild(ns); } }; return NumberUI; }()); ECS.NumberUI = NumberUI; var Score = /** @class */ (function (_super) { __extends(Score, _super); function Score(startXList, startYList) { return _super.call(this, startXList, startYList) || this; } return Score; }(NumberUI)); ECS.Score = Score; var BestScore = /** @class */ (function (_super) { __extends(BestScore, _super); function BestScore(startXList, startYList) { var _this = _super.call(this, startXList, startYList) || this; _this.startX = startXList[2]; _this.LocalData = new ECS.GameLocalData(ECS.GameConfig.localID); _this.hightScore = _this.LocalData.get('highscore') || 0; _this.update(); return _this; } BestScore.prototype.update = function () { this.setScore(this.LocalData.get('highscore') || 0); }; return BestScore; }(NumberUI)); ECS.BestScore = BestScore; var DistanceScore = /** @class */ (function (_super) { __extends(DistanceScore, _super); function DistanceScore(startXList, startYList) { var _this = _super.call(this, startXList, startYList) || this; _this.startX = startXList[3]; _this.setScore(0); return _this; } return DistanceScore; }(NumberUI)); ECS.DistanceScore = DistanceScore; var SpecialfoodUI = /** @class */ (function () { function SpecialfoodUI() { this.uiContainer = new PIXI.Container(); this.foods = ["Food Grey.png", "Food Grey.png", "Food Grey.png", "Food Grey.png"]; this.activeFoods = ["Food.png", "Food.png", "Food.png", "Food.png"]; for (var i = 0; i < 4; i++) { this.foods[i] = PIXI.Texture.fromFrame(this.foods[i]); this.activeFoods[i] = PIXI.Texture.fromFrame(this.activeFoods[i]); } this.startX = 10; this.digits = []; for (var i = 0; i < 4; i++) { this.digits[i] = new PIXI.Sprite(this.foods[i]); this.digits[i].scale.x = 0.6; this.digits[i].scale.y = 0.6; this.uiContainer.addChild(this.digits[i]); this.setFoodPic(this.digits[i], i * this.digits[i].width); } } SpecialfoodUI.prototype.setFoodPic = function (ui, posx) { ui.position.x = this.startX + posx; }; return SpecialfoodUI; }()); ECS.SpecialfoodUI = SpecialfoodUI; })(ECS || (ECS = {})); /* ========================================================================= * * GameItems.ts * item * * ========================================================================= */ /// <reference path="./GameConfig.ts" /> var ECS; (function (ECS) { var PickUp = /** @class */ (function () { function PickUp() { this.japanFoodTextures = ["RAMEN.png", "OKONOMIYAKI.png", "DANGO.png", "TEPURA.png"]; this.indoFoodTextures = ["BATAGOR.png", "CIRENG.png", "SEBLAK.png", "HAMBURG.png"]; this.position = new PIXI.Point(); var chooseFoodSeed = Math.random() * 10; if (chooseFoodSeed > 5) { this.clip = new PIXI.Sprite(PIXI.Texture.fromFrame(this.japanFoodTextures[Math.floor(Math.random() * this.japanFoodTextures.length)])); this.shine = new PIXI.Sprite(PIXI.Texture.fromImage("img/light2.png")); this.foodType = ECS.FOODMODE.JAPAN; this.shine.scale.y *= 0.5; } else { this.clip = new PIXI.Sprite(PIXI.Texture.fromFrame(this.indoFoodTextures[Math.floor(Math.random() * this.indoFoodTextures.length)])); this.shine = PIXI.Sprite.fromFrame("pickupShine.png"); this.foodType = ECS.FOODMODE.INDON; } this.view = new PIXI.Container(); this.clip.anchor.x = 0.5; this.clip.anchor.y = 0.5; this.shine.anchor.x = this.shine.anchor.y = 0.5; this.shine.scale.x = this.shine.scale.y * ECS.GameConfig.height / ECS.GameConfig.fixedHeight; this.shine.alpha = 0.8; this.view.addChild(this.shine); this.view.addChild(this.clip); this.width = ECS.GameConfig.height * 100 / ECS.GameConfig.fixedHeight; this.height = ECS.GameConfig.height * 100 / ECS.GameConfig.fixedHeight; this.count = Math.random() * 300; } PickUp.prototype.update = function () { if (!this.isPickedUp) { this.count += 0.1 * ECS.GameConfig.time.DELTA_TIME; this.clip.scale.x = ECS.GameConfig.height * 0.4 / ECS.GameConfig.fixedHeight + Math.sin(this.count) * 0.1; this.clip.scale.y = ECS.GameConfig.height * 0.4 / ECS.GameConfig.fixedHeight - Math.cos(this.count) * 0.1; this.clip.rotation = Math.sin(this.count * 1.5) * 0.2; this.shine.rotation = this.count * 0.2; } else { this.view.scale.x = 1 - this.ratio; this.view.scale.y = 1 - this.ratio; this.position.x = this.pickupPosition.x + (this.player.position.x - this.pickupPosition.x) * this.ratio; this.position.y = this.pickupPosition.y + (this.player.position.y - this.pickupPosition.y) * this.ratio; } this.view.position.x = this.position.x - ECS.GameConfig.camera.x; this.view.position.y = this.position.y; }; return PickUp; }()); ECS.PickUp = PickUp; })(ECS || (ECS = {})); /* ========================================================================= * * GameView.ts * game view scene * * ========================================================================= */ /// <reference path="./System.ts" /> /// <reference path="./HashSet.ts" /> /// <reference path="./GameConfig.ts" /> /// <reference path="./GameUI.ts" /> /// <reference path="./GameItems.ts" /> var ECS; (function (ECS) { var GameViewSystem = /** @class */ (function (_super) { __extends(GameViewSystem, _super); function GameViewSystem() { var _this = _super.call(this, "game view") || this; _this.renderer = ECS.GameConfig.app.renderer; _this.GameStage = new PIXI.Container(); _this.GameContainer = new PIXI.Container(); //init scene layer _this.hudContainer = new PIXI.Container(); _this.game = new PIXI.Container(); _this.gameFront = new PIXI.Container(); _this.GameContainer.addChild(_this.game); _this.GameContainer.addChild(_this.gameFront); _this.GameStage.addChild(_this.GameContainer); _this.GameStage.addChild(_this.hudContainer); //background container _this.background = (ECS.GameConfig.allSystem.get("background")).BackGroundContainer; _this.game.addChild(_this.background); _this.count = 0; _this.zoom = 1; ECS.GameConfig.xOffset = _this.GameContainer.position.x; ECS.GameConfig.app.stage.addChild(_this.GameStage); return _this; } GameViewSystem.prototype.showHud = function () { //up left ui panel this.specialFood = new ECS.SpecialfoodUI(); //up right ui panel this.UIPanelUpRight = new ECS.GameUIPanelUpRight(); this.scoreUI = new ECS.Score(this.UIPanelUpRight.startXList, this.UIPanelUpRight.startYList); this.bestScoreUI = new ECS.BestScore(this.UIPanelUpRight.startXList, this.UIPanelUpRight.startYList); this.distanceScoreUI = new ECS.DistanceScore(this.UIPanelUpRight.startXList, this.UIPanelUpRight.startYList); if (!ECS.GameConfig.device.desktop) { this.userControlUI = new ECS.GameUIPanelControl(); this.hudContainer.addChild(this.userControlUI.uiContainer); } this.hudContainer.addChild(this.UIPanelUpRight.uiContainer); this.hudContainer.addChild(this.scoreUI.container); this.hudContainer.addChild(this.bestScoreUI.container); this.hudContainer.addChild(this.distanceScoreUI.container); this.hudContainer.addChild(this.specialFood.uiContainer); }; GameViewSystem.prototype.update = function () { var kernel = ECS.GameConfig.game; this.count += 0.01; var ratio = (this.zoom - 1); var position = -ECS.GameConfig.width / 2; var position2 = -kernel.player.view.position.x; var inter = position + (position2 - position) * ratio; this.GameContainer.position.x = inter * this.zoom; this.GameContainer.position.y = -kernel.player.view.position.y * this.zoom; this.GameContainer.position.x += ECS.GameConfig.width / 2; this.GameContainer.position.y += ECS.GameConfig.height / 2; ECS.GameConfig.xOffset = this.GameContainer.position.x; if (this.GameContainer.position.y > 0) this.GameContainer.position.y = 0; var yMax = -ECS.GameConfig.height * this.zoom; yMax += ECS.GameConfig.height; if (this.GameContainer.position.y < yMax) this.GameContainer.position.y = yMax; this.GameContainer.scale.x = this.zoom; this.GameContainer.scale.y = this.zoom; // this.trail.target = kernel.player; // this.trail2.target = kernel.player; // this.trail.update(); // this.trail2.update(); //this.dust.update(); //this.lava.setPosition(GameConfig.camera.x + 4000); //this.bestScore.update(); //update score ui panel if (this.scoreUI.currentScore != kernel.score) this.scoreUI.setScore(kernel.score); if (this.distanceScoreUI.currentScore != kernel.distanceScore) this.distanceScoreUI.setScore(kernel.distanceScore); var hightScore = this.bestScoreUI.LocalData.get('highscore') || 0; if (this.bestScoreUI.highScore != hightScore) this.bestScoreUI.update(); this.renderer.render(ECS.GameConfig.app.stage); }; // doSplash() { // this.splash.splash(this.kernel.player.position); // } GameViewSystem.prototype.normalMode = function () { this.game.removeChild(this.background); this.game.addChildAt(this.background, 0); //this.stage.addChild(this.white) this.white.alpha = 1; TweenLite.to(this.white, 0.5, { alpha: 0, ease: Sine.easeOut }); }; return GameViewSystem; }(ECS.System)); ECS.GameViewSystem = GameViewSystem; })(ECS || (ECS = {})); /* ========================================================================= * * GameCharacter.ts * character controller * * ========================================================================= */ /// <reference path="./GameConfig.ts" /> /// <reference path="./GameBackGround.ts" /> /// <reference path="./GameManager.ts" /> var ECS; (function (ECS) { var GameCharacter = /** @class */ (function () { function GameCharacter() { this.isSlide = false; this.ninjiaEffectNumber = 0; this.isPlayingNinjiaEffect = false; this.isPlayingInoEffect = false; //console.log("init character!"); this.position = new PIXI.Point(); this.speedUpList = []; this.runningFrames = [ PIXI.Texture.fromFrame("CHARACTER/RUN/Character-01.png"), PIXI.Texture.fromFrame("CHARACTER/RUN/Character-02.png"), PIXI.Texture.fromFrame("CHARACTER/RUN/Character-03.png"), PIXI.Texture.fromFrame("CHARACTER/RUN/Character-04.png"), PIXI.Texture.fromFrame("CHARACTER/RUN/Character-05.png"), PIXI.Texture.fromFrame("CHARACTER/RUN/Character-06.png"), ]; this.indoTightFrame = [ PIXI.Texture.fromFrame("CHARACTER/POWER EFFECTS/INDONTIGHT/boom0001.png"), PIXI.Texture.fromFrame("CHARACTER/POWER EFFECTS/INDONTIGHT/boom0002.png"), PIXI.Texture.fromFrame("CHARACTER/POWER EFFECTS/INDONTIGHT/boom0003.png"), PIXI.Texture.fromFrame("CHARACTER/POWER EFFECTS/INDONTIGHT/boom0004.png") ]; this.jumpFrames = [ PIXI.Texture.fromFrame("CHARACTER/JUMP/Jump.png"), ]; this.slideFrame = [ PIXI.Texture.fromFrame("CHARACTER/SLIDE/Slide.png"), ]; this.dashFrames = [ PIXI.Texture.fromFrame("CHARACTER/POWER/DASH/dash0002.png") ]; this.shootFrame = [ PIXI.Texture.fromFrame("CHARACTER/POWER/SHOOT/shoot0001.png"), PIXI.Texture.fromFrame("CHARACTER/POWER/SHOOT/shoot0002.png") ]; this.view = new PIXI.extras.AnimatedSprite(this.runningFrames); this.view.animationSpeed = 0.23; this.view.anchor.x = 0.5; this.view.anchor.y = 0.5; this.view.height = 115 * ECS.GameConfig.height / ECS.GameConfig.fixedHeight; this.view.width = 65 * ECS.GameConfig.height / ECS.GameConfig.fixedHeight; this.position.x = (ECS.GameConfig.allSystem.get("background")).bgTex.spriteWidth + 100; if (!ECS.GameConfig.device.desktop) this.position.x = 2 * (ECS.GameConfig.allSystem.get("background")).bgTex.spriteWidth + 100; this.floorSpriteHeight = (ECS.GameConfig.allSystem.get("background")).bgTex.spriteHeight; //refresh floor position this.refreshFloorHeight(); this.gravity = 9.8; this.baseSpeed = 12; this.speed = new PIXI.Point(this.baseSpeed, 0); this.activeCount = 0; this.isJumped = false; this.accel = 0; this.width = 26; this.height = 37; this.onGround = true; this.rotationSpeed = 0; this.joyRiding = false; this.level = 1; this.realAnimationSpeed = 0.23; this.volume = 0.3; //start speed this.vStart = 35; this.mass = 65; this.angle = Math.PI * 45 / 360; this.startJump = false; this.b_jumpTwo = false; this.smooth = 0.05; this.cnt = 0; this.shinobiEffect1 = new PIXI.Sprite(PIXI.Texture.fromImage("img/dash_stock.png")); this.shinobiEffect1.anchor.x = -1.5; this.shinobiEffect1.anchor.y = 5.5; this.shinobiEffect1.scale.x = 0.2; this.shinobiEffect1.scale.y = 0.2; this.shinobiEffect2 = new PIXI.Sprite(PIXI.Texture.fromImage("img/dash_stock.png")); this.shinobiEffect2.anchor.x = 0; this.shinobiEffect2.anchor.y = 5.5; this.shinobiEffect2.scale.x = 0.2; this.shinobiEffect2.scale.y = 0.2; this.shinobiEffect3 = new PIXI.Sprite(PIXI.Texture.fromImage("img/dash_stock.png")); this.shinobiEffect3.anchor.x = 1.5; this.shinobiEffect3.anchor.y = 5.5; this.shinobiEffect3.scale.x = 0.2; this.shinobiEffect3.scale.y = 0.2; this.backEffect = new PIXI.Sprite(PIXI.Texture.fromImage("img/blade.png")); this.backEffect.anchor.x = 0.8; this.backEffect.anchor.y = 0.5; this.backEffect.scale.x = 1; this.backEffect.scale.y = 1; this.specialEffectView = new PIXI.Sprite(PIXI.Texture.fromFrame("CHARACTER/POWER EFFECTS/DASH/dash-shinobi-new.png")); this.specialEffectView.anchor.x = 0.2; this.specialEffectView.anchor.y = 0.5; this.specialEffectView.scale.x = 2; this.specialEffectView.scale.y = 2; this.indoEffect = new PIXI.Sprite(PIXI.Texture.fromFrame("CHARACTER/POWER EFFECTS/SHOOT/maung shoot-new.png")); this.indoEffect.anchor.x = 0.2; this.indoEffect.anchor.y = 0.6; this.indoEffect.scale.x = 2; this.indoEffect.scale.y = 2; this.marioEffect = new PIXI.Sprite(PIXI.Texture.fromFrame("CHARACTER/POWER EFFECTS/MARIO/maung ninja.png")); this.marioEffect.anchor.x = 0.1; this.marioEffect.anchor.y = 0.52; this.marioEffect.scale.x = 2; this.marioEffect.scale.y = 2; this.indonTight = new PIXI.extras.AnimatedSprite(this.indoTightFrame); this.indonTight.animationSpeed = 0.1; this.indonTight.anchor.x = 0.5; this.indonTight.anchor.y = 0.5; this.indonTight.height = ECS.GameConfig.height / 2; this.indonTight.width = ECS.GameConfig.width / 2; this.view.play(); //GameConfig.app.start(); } GameCharacter.prototype.update = function () { if (this.isDead) { this.updateDieing(); } else { this.updateRunning(); } }; GameCharacter.prototype.normalMode = function () { this.joyRiding = false; TweenLite.to(this.speed, 0.6, { x: this.baseSpeed, ease: Cubic.easeOut }); this.realAnimationSpeed = 0.23; }; GameCharacter.prototype.chkOnGround = function () { if (this.onGround) { return true; } return false; }; GameCharacter.prototype.resetSpecialFoods = function () { for (var i = 0; i < 4; i++) { ECS.GameConfig.game.view.specialFood.digits[i].texture = ECS.GameConfig.game.view.specialFood.foods[i]; } }; GameCharacter.prototype.ninjiaOperate = function () { if (this.ninjiaEffectNumber < 3 && !this.isPlayingNinjiaEffect) { //console.log("dash"); this.isPlayingNinjiaEffect = true; ECS.GameConfig.tmpTimeClockStart = ECS.GameConfig.time.currentTime; this.view.addChild(this.specialEffectView); switch (this.ninjiaEffectNumber) { case 0: this.view.removeChild(this.shinobiEffect1); break; case 1: this.view.removeChild(this.shinobiEffect2); break; case 2: this.view.removeChild(this.shinobiEffect3); break; } this.speed.x *= 10; this.ninjiaEffectNumber++; } }; GameCharacter.prototype.indoOperate = function () { if (!this.isPlayingInoEffect) { //chara animation this.view.textures = this.shootFrame; this.view.play(); ECS.GameConfig.tmpTimeClockStart = ECS.GameConfig.time.currentTime; this.view.addChild(this.indoEffect); //effect play (ECS.GameConfig.allSystem.get("view")).game.addChild(this.indonTight); this.indonTight.textures = this.indoTightFrame; this.indonTight.play(); this.isPlayingInoEffect = true; } }; GameCharacter.prototype.ninjaMode = function () { if (this.isPlayingNinjiaEffect) { ECS.GameConfig.tmpTimeClockEnd = ECS.GameConfig.time.currentTime; var DuringTime = ECS.GameConfig.timeClock(); //console.log(DuringTime); if (DuringTime > 200) { this.view.textures = this.runningFrames; this.view.play(); this.speed.x /= 10; this.view.removeChild(this.specialEffectView); this.isPlayingNinjiaEffect = false; if (this.ninjiaEffectNumber == 3) { this.ninjiaEffectNumber = 0; ECS.GameConfig.specialMode = ECS.SPECIALMODE.NONE; ECS.GameConfig.game.pickupManager.pickedUpPool = []; ECS.GameConfig.game.pickupManager.canPickOrNot = true; this.resetSpecialFoods(); this.view.removeChild(this.backEffect); //console.log("ninja finished!"); } } } }; GameCharacter.prototype.marioMode = function () { ECS.GameConfig.tmpTimeClockEnd = ECS.GameConfig.time.currentTime; var DuringTime = ECS.GameConfig.timeClock(); //console.log(DuringTime); if (DuringTime > 10000) { //console.log("mario finished!"); ECS.GameConfig.specialMode = ECS.SPECIALMODE.NONE; ECS.GameConfig.game.pickupManager.pickedUpPool = []; ECS.GameConfig.game.pickupManager.canPickOrNot = true; this.speed.x /= 2; this.view.removeChild(this.marioEffect); this.resetSpecialFoods(); ECS.GameConfig.audio.stop("superMarioMode"); ECS.GameConfig.audio.play("GameMusic"); } }; GameCharacter.prototype.indoMode = function () { if (this.isPlayingInoEffect) { this.indonTight.position.x = this.position.x - ECS.GameConfig.camera.x; this.indonTight.position.y = this.position.y - ECS.GameConfig.camera.y; ECS.GameConfig.tmpTimeClockEnd = ECS.GameConfig.time.currentTime; var DuringTime = ECS.GameConfig.timeClock(); if (DuringTime > 1000) { //console.log("indo finished!"); this.isPlayingInoEffect = false; ECS.GameConfig.specialMode = ECS.SPECIALMODE.NONE; ECS.GameConfig.game.pickupManager.pickedUpPool = []; ECS.GameConfig.game.pickupManager.canPickOrNot = true; (ECS.GameConfig.allSystem.get("view")).game.removeChild(this.indonTight); this.view.removeChild(this.indoEffect); this.resetSpecialFoods(); } } }; GameCharacter.prototype.refreshFloorHeight = function () { this.floorHeight = this.floorSpriteHeight - this.view.height * 0.5; this.view.position.y = this.floorHeight; this.position.y = this.floorHeight; this.ground = this.floorHeight; }; GameCharacter.prototype.updateRunning = function () { this.view.animationSpeed = this.realAnimationSpeed * ECS.GameConfig.time.DELTA_TIME * this.level; this.indonTight.animationSpeed = this.realAnimationSpeed * ECS.GameConfig.time.DELTA_TIME * this.level; //speed up when user reach some points var judgeImPoints = Math.floor(ECS.GameConfig.game.distanceScore / 2); if (judgeImPoints != 0 && !this.speedUpList.includes(judgeImPoints) && ECS.GameConfig.game.distanceScore < 20) { //console.log("speed up!"); this.speedUpList.push(judgeImPoints); this.speed.x *= 1.1; } switch (ECS.GameConfig.playerMode) { case ECS.PLAYMODE.JUMPING1: this.speed.y = -this.vStart * Math.sin(this.angle); break; case ECS.PLAYMODE.JUMPING2: this.speed.y = -this.vStart * Math.sin(this.angle); break; case ECS.PLAYMODE.FALL: //should have gravity this.speed.y += this.gravity * ECS.GameConfig.time.DELTA_TIME * this.smooth; break; case ECS.PLAYMODE.RUNNING: this.speed.y = 0; break; case ECS.PLAYMODE.SLIDE: this.speed.y = 0; break; } if (!this.chkOnGround() && (ECS.GameConfig.playerMode == ECS.PLAYMODE.JUMPING1 || ECS.GameConfig.playerMode == ECS.PLAYMODE.JUMPING2)) ECS.GameConfig.playerMode = ECS.PLAYMODE.FALL; else if (ECS.GameConfig.playerMode == ECS.PLAYMODE.FALL && this.chkOnGround()) ECS.GameConfig.playerMode = ECS.PLAYMODE.RUNNING; this.position.x += this.speed.x * ECS.GameConfig.time.DELTA_TIME * this.level; this.position.y += this.speed.y * ECS.GameConfig.time.DELTA_TIME; if (this.onGround && ECS.GameConfig.playerMode == ECS.PLAYMODE.RUNNING && this.view.textures != this.runningFrames && !this.isPlayingInoEffect) { this.view.anchor.y = 0.5; this.view.textures = this.runningFrames; this.view.play(); } else if (ECS.GameConfig.playerMode == ECS.PLAYMODE.SLIDE && this.view.textures != this.slideFrame) { this.view.anchor.y = 0.1; this.view.textures = this.slideFrame; this.view.play(); } else if ((ECS.GameConfig.playerMode == ECS.PLAYMODE.JUMPING1 || ECS.GameConfig.playerMode == ECS.PLAYMODE.JUMPING2) && this.view.textures != this.jumpFrames) { this.view.textures = this.jumpFrames; this.view.play(); } switch (ECS.GameConfig.specialMode) { case ECS.SPECIALMODE.NONE: break; case ECS.SPECIALMODE.NINJAMODE: this.marioMode(); break; case ECS.SPECIALMODE.JAPANMODE: if (this.ninjiaEffectNumber <= 3) { this.ninjaMode(); } break; case ECS.SPECIALMODE.INDONMODE: this.indoMode(); break; } ECS.GameConfig.camera.x = this.position.x - 100; ECS.GameConfig.game.distanceScore = Math.floor(this.position.x / 10000); this.view.position.x = this.position.x - ECS.GameConfig.camera.x; this.view.position.y = this.position.y - ECS.GameConfig.camera.y; this.view.rotation += (this.speed.y * 0.05 - this.view.rotation) * 0.1; }; GameCharacter.prototype.updateDieing = function () { this.speed.x *= 0.999; if (this.onGround) this.speed.y *= 0.99; this.speed.y += 0.1; this.accel += (0 - this.accel) * 0.1 * ECS.GameConfig.time.DELTA_TIME; this.speed.y += this.gravity * ECS.GameConfig.time.DELTA_TIME; ; this.position.x += this.speed.x * ECS.GameConfig.time.DELTA_TIME; ; this.position.y += this.speed.y * ECS.GameConfig.time.DELTA_TIME; ; ECS.GameConfig.camera.x = this.position.x - 100; this.view.position.x = this.position.x - ECS.GameConfig.camera.x; this.view.position.y = this.position.y - ECS.GameConfig.camera.y; if (this.speed.x < 5) { this.view.rotation += this.rotationSpeed * (this.speed.x / 5) * ECS.GameConfig.time.DELTA_TIME; } else { this.view.rotation += this.rotationSpeed * ECS.GameConfig.time.DELTA_TIME; } }; GameCharacter.prototype.jump = function () { if (this.isDead) { if (this.speed.x < 5) { this.isDead = false; this.speed.x = 10; } } this.startJump = true; ECS.GameConfig.playerMode = ECS.PLAYMODE.JUMPING1; }; GameCharacter.prototype.jumpTwo = function () { if (this.isDead) { if (this.speed.x < 5) { this.isDead = false; this.speed.x = 10; } } this.startJump = false; ECS.GameConfig.playerMode = ECS.PLAYMODE.JUMPING2; }; GameCharacter.prototype.slide = function (isSlide) { if (this.isDead) { if (this.speed.x < 5) { this.isDead = false; this.speed.x = 10; } } // console.log(isSlide); if (ECS.GameConfig.playerMode != ECS.PLAYMODE.SLIDE && this.position.y == this.ground) { this.isSlide = isSlide; if (isSlide) ECS.GameConfig.playerMode = ECS.PLAYMODE.SLIDE; } else if (!isSlide) { //console.log("slide finish"); this.onGround = true; this.position.y = this.ground; this.isSlide = isSlide; ECS.GameConfig.playerMode = ECS.PLAYMODE.RUNNING; } }; GameCharacter.prototype.die = function () { if (this.isDead) return; ECS.GameConfig.audio.play("playerDead"); TweenLite.to(ECS.GameConfig.time, 0.5, { speed: 0.1, ease: Cubic.easeOut, onComplete: function () { TweenLite.to(ECS.GameConfig.time, 2, { speed: 1, delay: 1 }); } }); this.isDead = true; this.bounce = 0; this.speed.x = 15; this.speed.y = -15; this.rotationSpeed = 0.3; this.view.stop(); }; GameCharacter.prototype.boil = function () { if (this.isDead) return; this.isDead = true; }; GameCharacter.prototype.fall = function () { this.startJump = false; //this.b_jumpTwo = false; this.isJumped = true; }; GameCharacter.prototype.isAirbourne = function () { }; GameCharacter.prototype.stop = function () { this.view.stop(); }; GameCharacter.prototype.resume = function () { this.view.play(); }; return GameCharacter; }()); ECS.GameCharacter = GameCharacter; var GameEnemy = /** @class */ (function () { function GameEnemy() { this.isEatNow = false; this.isExploded = false; this.position = new PIXI.Point(); this.isHit = false; this.width = 150; this.height = 150; this.speed = -10 + Math.random() * 20; ; this.moveingFrames = [ PIXI.Texture.fromFrame("CHARACTER/NEKO/WALK/neko0001.png"), PIXI.Texture.fromFrame("CHARACTER/NEKO/WALK/neko0002.png"), PIXI.Texture.fromFrame("CHARACTER/NEKO/WALK/neko0003.png"), PIXI.Texture.fromFrame("CHARACTER/NEKO/WALK/neko0004.png"), ]; this.stealFrames = [ PIXI.Texture.fromFrame("CHARACTER/NEKO/STEAL/steal0001.png"), PIXI.Texture.fromFrame("CHARACTER/NEKO/STEAL/steal0002.png"), PIXI.Texture.fromFrame("CHARACTER/NEKO/STEAL/steal0003.png"), PIXI.Texture.fromFrame("CHARACTER/NEKO/STEAL/steal0004.png") ]; this.view = new PIXI.extras.AnimatedSprite(this.moveingFrames); this.view.animationSpeed = 0.23; this.view.anchor.x = 0.5; this.view.anchor.y = 0.5; this.view.height = ECS.GameConfig.height * 130 / ECS.GameConfig.fixedHeight; this.view.width = ECS.GameConfig.height * 130 / ECS.GameConfig.fixedHeight; this.view.play(); } GameEnemy.prototype.reset = function () { this.isHit = false; }; GameEnemy.prototype.hit = function () { if (this.isHit) return; this.isHit = true; ECS.GameConfig.audio.play("catDead"); this.view.setTexture(PIXI.Texture.fromImage("img/empty.png")); }; GameEnemy.prototype.update = function () { this.view.animationSpeed = 0.23 * ECS.GameConfig.time.DELTA_TIME; this.view.position.x = this.position.x - ECS.GameConfig.camera.x; if (!this.isEatNow) { this.position.x += this.speed * Math.sin(ECS.GameConfig.time.DELTA_TIME); ECS.GameConfig.tmpTimeClockStart1 = ECS.GameConfig.time.currentTime; } else { ECS.GameConfig.tmpTimeClockEnd1 = ECS.GameConfig.time.currentTime; if (ECS.GameConfig.timeClock1() > 2000) { this.isEatNow = false; this.view.textures = this.moveingFrames; this.view.play(); ECS.GameConfig.audio.play("catCome"); } } this.view.position.y = this.position.y; }; return GameEnemy; }()); ECS.GameEnemy = GameEnemy; })(ECS || (ECS = {})); /* ========================================================================= * * GameManager.ts * ..... * * ========================================================================= */ /// <reference path="./GameItems.ts" /> /// <reference path="./GameCharacter.ts" /> /// <reference path="./GameBackGround.ts" /> var ECS; (function (ECS) { var GameObjectPool = /** @class */ (function () { function GameObjectPool(classType) { this.classType = classType; this.pool = []; } GameObjectPool.prototype.getObject = function () { var object = this.pool.pop(); if (!object) { object = new this.classType(); } return object; }; return GameObjectPool; }()); ECS.GameObjectPool = GameObjectPool; var SegmentManager = /** @class */ (function () { function SegmentManager(engine) { //console.log("init segmeng manager!"); this.engine = engine; this.sections = data; this.count = 0; this.currentSegment = data[0]; //console.log(this.currentSegment); this.startSegment = { length: 1135 * 2, floor: [0, 1135], blocks: [], coins: [], platform: [] }, this.chillMode = true; this.last = 0; this.position = 0; } SegmentManager.prototype.reset = function (dontReset) { if (dontReset) this.count = 0; this.currentSegment = this.startSegment; this.currentSegment.start = -200; for (var i = 0; i < this.currentSegment.floor.length; i++) { this.engine.floorManager.addFloor(this.currentSegment.start + this.currentSegment.floor[i]); } }; SegmentManager.prototype.update = function () { this.position = ECS.GameConfig.camera.x + ECS.GameConfig.width * 2; var relativePosition = this.position - this.currentSegment.start; if (relativePosition > this.currentSegment.length) { //var nextSegment = this.startSegment;//this.sections[this.count % this.sections.length]; var nextSegment = this.sections[this.count % this.sections.length]; // section finished! nextSegment.start = this.currentSegment.start + this.currentSegment.length; this.currentSegment = nextSegment; // add the elements! //console.log(this.currentSegment.floor.length); var floors = this.currentSegment.floor; var length = floors.length / 1.0; for (var i = 0; i < length; i++) { //console.log(this.currentSegment.start + this.currentSegment.floor[i]); this.engine.floorManager.addFloor(this.currentSegment.start + this.currentSegment.floor[i]); } //add items(temp calcluate for all device) var blocks = this.currentSegment.blocks; var length = blocks.length / 2; for (var i = 0; i < length; i++) { var enemyY = blocks[(i * 2) + 1]; var realEnemyY = ECS.GameConfig.height * enemyY / ECS.GameConfig.fixedHeight; this.engine.enemyManager.addEnemy((ECS.GameConfig.allSystem.get("background")).bgTex.spriteWidth + 100 + this.currentSegment.start + blocks[i * 2], realEnemyY); } var pickups = this.currentSegment.coins; var length = pickups.length / 2; for (var i = 0; i < length; i++) { var XFloat = Math.floor(Math.random() * 50 + 400); var foodY = pickups[(i * 2) + 1]; var realfoodY = ECS.GameConfig.height * foodY / ECS.GameConfig.fixedHeight; this.engine.pickupManager.addPickup((ECS.GameConfig.allSystem.get("background")).bgTex.spriteWidth + 100 + this.currentSegment.start + pickups[i * 2] + XFloat, realfoodY); } var platforms = this.currentSegment.platform; var length = platforms.length / 2; for (var i = 0; i < length; i++) { var platY = platforms[(i * 2) + 1]; var realPlatY = ECS.GameConfig.height * platY / ECS.GameConfig.fixedHeight; this.engine.platManager.addPlatform(this.currentSegment.start + platforms[i * 2], realPlatY); } this.count++; } }; return SegmentManager; }()); ECS.SegmentManager = SegmentManager; var Platform = /** @class */ (function () { function Platform() { this.position = new PIXI.Point(); var platFixedHeight = 50; var newPlatHeight = ECS.GameConfig.height * platFixedHeight / ECS.GameConfig.fixedHeight; var ratio = newPlatHeight / platFixedHeight; this.platBlockHeight = newPlatHeight; this.platBlockWidth = ratio * 50; this.numberOfBlock = -3 + Math.random() * (8 - 5) + 5; this.views = []; for (var i = 0; i < this.numberOfBlock * 2; i++) { var view = new PIXI.Sprite(PIXI.Texture.fromFrame("img/floatingGround.png")); view.anchor.x = 0.5; view.anchor.y = 0.5; view.width = this.platBlockWidth; view.height = this.platBlockHeight; this.views.push(view); } //calculate all platform info this.width = this.platBlockWidth * this.numberOfBlock * 2; this.height = this.platBlockHeight; } Platform.prototype.update = function () { for (var i = -this.numberOfBlock; i < this.numberOfBlock; i++) { this.views[i + this.numberOfBlock].position.x = this.position.x + this.platBlockWidth * i - ECS.GameConfig.camera.x; ; this.views[i + this.numberOfBlock].position.y = this.position.y; } }; return Platform; }()); ECS.Platform = Platform; var PlatformManager = /** @class */ (function () { function PlatformManager(engine) { //console.log("init platform manager!"); this.engine = engine; this.platforms = []; this.platformPool = new GameObjectPool(Platform); } PlatformManager.prototype.update = function () { for (var i = 0; i < this.platforms.length; i++) { var platform = this.platforms[i]; platform.update(); // this.platforms.splice(i, 1); // for(var i=0;i<platform.numberOfBlock;i++){ // if(platform.views[i].position.x < -500 -GameConfig.xOffset && !this.engine.player.isDead) // { // this.engine.view.gameFront.removeChild(platform.views[i]); // } // } // i--; } }; PlatformManager.prototype.destroyAll = function () { for (var i = 0; i < this.platforms.length; i++) { var platform = this.platforms[i]; this.platforms.splice(i, 1); // for(var i=0;i<platform.numberOfBlock;i++){ // if(platform.views[i].position.x < -500 -GameConfig.xOffset && !this.engine.player.isDead) // { // this.engine.view.gameFront.removeChild(platform.views[i]); // } // } i--; } this.platforms = []; }; PlatformManager.prototype.addPlatform = function (x, y) { var platform = this.platformPool.getObject(); platform.position.x = x; platform.position.y = y; for (var i = -platform.numberOfBlock; i < platform.numberOfBlock; i++) { platform.views[i + platform.numberOfBlock].position.x = platform.position.x + 50 * i - ECS.GameConfig.camera.x; ; platform.views[i + platform.numberOfBlock].position.y = platform.position.y; this.platforms.push(platform); this.engine.view.gameFront.addChild(platform.views[i + platform.numberOfBlock]); } }; return PlatformManager; }()); ECS.PlatformManager = PlatformManager; var EnemyManager = /** @class */ (function () { function EnemyManager(engine) { //console.log("init enemy manager!"); this.engine = engine; this.enemies = []; this.enemyPool = new GameObjectPool(ECS.GameEnemy); this.spawnCount = 0; } EnemyManager.prototype.update = function () { for (var i = 0; i < this.enemies.length; i++) { var enemy = this.enemies[i]; enemy.update(); if (enemy.view.position.x < -100 - ECS.GameConfig.xOffset && !this.engine.player.isDead) { ////this.enemyPool.returnObject(enemy); this.enemies.splice(i, 1); this.engine.view.gameFront.removeChild(enemy.view); i--; } else if (enemy.isHit) { this.enemies.splice(i, 1); this.engine.view.gameFront.removeChild(enemy.view); i--; } } }; EnemyManager.prototype.addEnemy = function (x, y) { var enemy = this.enemyPool.getObject(); enemy.position.x = x; enemy.position.y = y; enemy.view.textures = enemy.moveingFrames; enemy.view.play(); this.enemies.push(enemy); this.engine.view.gameFront.addChild(enemy.view); }; EnemyManager.prototype.destroyAll = function () { for (var i = 0; i < this.enemies.length; i++) { var enemy = this.enemies[i]; enemy.reset(); //this.enemyPool.returnObject(enemy); this.engine.view.gameFront.removeChild(enemy.view); } this.enemies = []; }; EnemyManager.prototype.destroyAllOffScreen = function () { for (var i = 0; i < this.enemies.length; i++) { var enemy = this.enemies[i]; if (enemy.x > ECS.GameConfig.camera.x + ECS.GameConfig.width) { this.engine.view.game.removeChild(enemy.view); this.enemies.splice(i, 1); i--; } } }; return EnemyManager; }()); ECS.EnemyManager = EnemyManager; var PickupManager = /** @class */ (function () { function PickupManager(engine) { this.canPickOrNot = true; this.MAX_PICKUP_NUM = 4; //console.log("init pick up manager!"); this.engine = engine; this.pickups = []; this.pickupPool = new GameObjectPool(ECS.PickUp); this.spawnCount = 0; this.pos = 0; this.pickedUpPool = []; } PickupManager.prototype.update = function () { for (var i = 0; i < this.pickups.length; i++) { var pickup = this.pickups[i]; pickup.update(); if (pickup.isPickedUp) { pickup.ratio += (1 - pickup.ratio) * 0.3 * ECS.GameConfig.time.DELTA_TIME; if (pickup.ratio > 0.99) { //this.pickupPool.returnObject(pickup); this.pickups.splice(i, 1); this.engine.view.game.removeChild(pickup.view); i--; } } else { if (pickup.view.position.x < -100 - ECS.GameConfig.xOffset) { // remove! this.engine.view.game.removeChild(pickup.view); this.pickups.splice(i, 1); i--; } } } }; PickupManager.prototype.addPickup = function (x, y) { var pickup = this.pickupPool.getObject(); pickup.position.x = x; pickup.position.y = y; this.pickups.push(pickup); this.engine.view.game.addChild(pickup.view); }; PickupManager.prototype.removePickup = function (index, isPlayer, enemyEntity) { if (isPlayer === void 0) { isPlayer = true; } if (enemyEntity === void 0) { enemyEntity = undefined; } //collect food var pickup = this.pickups[index]; pickup.isPickedUp = true; if (isPlayer) { pickup.player = this.engine.player; pickup.pickupPosition = { x: pickup.position.x, y: pickup.position.y }; pickup.ratio = 0; ECS.GameConfig.audio.play("pickUpFood"); //judge food pool, 0 jap 1 indo if (this.pickedUpPool.length < this.MAX_PICKUP_NUM - 1 && this.canPickOrNot) { this.pickedUpPool.push(pickup.foodType); this.engine.view.specialFood.digits[this.pickedUpPool.length - 1].texture = this.engine.view.specialFood.activeFoods[this.pickedUpPool.length - 1]; } else if (this.pickedUpPool.length == this.MAX_PICKUP_NUM - 1 && this.canPickOrNot) { this.pickedUpPool.push(pickup.foodType); this.engine.view.specialFood.digits[this.pickedUpPool.length - 1].texture = this.engine.view.specialFood.activeFoods[this.pickedUpPool.length - 1]; //count for jan food var cnt = 0; for (var i = 0; i < this.pickedUpPool.length; i++) { if (this.pickedUpPool[i] == 0) { cnt++; } } var specialMode = ECS.SPECIALMODE.NINJAMODE; if (cnt > 2) { specialMode = ECS.SPECIALMODE.JAPANMODE; ECS.GameConfig.game.player.view.addChild(ECS.GameConfig.game.player.shinobiEffect1); ECS.GameConfig.game.player.view.addChild(ECS.GameConfig.game.player.shinobiEffect2); ECS.GameConfig.game.player.view.addChild(ECS.GameConfig.game.player.shinobiEffect3); ECS.GameConfig.game.player.view.addChild(ECS.GameConfig.game.player.backEffect); ECS.GameConfig.audio.play("ninjiaMode"); //console.log("change special mode:japan"); } else if (cnt < 2) { specialMode = ECS.SPECIALMODE.INDONMODE; ECS.GameConfig.tmpTimeClockStart = ECS.GameConfig.time.currentTime; ECS.GameConfig.game.player.view.addChild(ECS.GameConfig.game.player.indoEffect); ECS.GameConfig.audio.play("indoMode"); //console.log("change special mode:indo"); } else if (cnt == 2) { specialMode = ECS.SPECIALMODE.NINJAMODE; ECS.GameConfig.tmpTimeClockStart = ECS.GameConfig.time.currentTime; ECS.GameConfig.game.player.view.addChild(ECS.GameConfig.game.player.marioEffect); ECS.GameConfig.game.player.speed.x *= 2; //console.log("change special mode:ninja"); ECS.GameConfig.audio.stop("GameMusic"); ECS.GameConfig.audio.play("superMarioMode"); } ECS.GameConfig.specialMode = specialMode; this.canPickOrNot = false; } } else { //eat by cat pickup.player = enemyEntity; pickup.pickupPosition = { x: pickup.position.x, y: pickup.position.y }; //.clone(); pickup.ratio = 0; } }; PickupManager.prototype.destroyAll = function () { for (var i = 0; i < this.pickups.length; i++) { var pickup = this.pickups[i]; // remove! //this.pickupPool.returnObject(pickup); this.engine.view.game.removeChild(pickup.view); } this.pickups = []; }; PickupManager.prototype.destroyAllOffScreen = function () { for (var i = 0; i < this.pickups.length; i++) { var pickup = this.pickups[i]; if (pickup.x > ECS.GameConfig.camera.x + ECS.GameConfig.width) { //this.pickupPool.returnObject(pickup); this.engine.view.game.removeChild(pickup.view); this.pickups.splice(i, 1); i--; } } }; return PickupManager; }()); ECS.PickupManager = PickupManager; var Floor = /** @class */ (function () { function Floor() { this.position = new PIXI.Point(); var view = new PIXI.Sprite(PIXI.Texture.fromFrame("img/bg_down.png")); this.view = view; } return Floor; }()); ECS.Floor = Floor; var FloorManager = /** @class */ (function () { function FloorManager(engine) { //console.log("init floor manager!"); this.engine = engine; this.count = 0; this.floors = []; this.floorPool = new GameObjectPool(Floor); } FloorManager.prototype.update = function () { for (var i = 0; i < this.floors.length; i++) { var floor = this.floors[i]; floor.view.position.x = floor.position.x - ECS.GameConfig.camera.x - 16; if (floor.position.x < -1135 - ECS.GameConfig.xOffset - 16) { this.floors.splice(i, 1); i--; this.engine.view.gameFront.removeChild(floor); } } }; FloorManager.prototype.addFloor = function (floorData) { var floor = this.floorPool.getObject(); floor.position.x = floorData; floor.position.y = (ECS.GameConfig.allSystem.get("background")).bgTex.spriteHeight - 1; floor.view.height = ECS.GameConfig.height - floor.position.y + 1; floor.view.position.y = floor.position.y; this.engine.view.gameFront.addChild(floor.view); this.floors.push(floor); }; FloorManager.prototype.destroyAll = function () { for (var i = 0; i < this.floors.length; i++) { var floor = this.floors[i]; this.engine.view.gameFront.removeChild(floor); } this.floors = []; }; return FloorManager; }()); ECS.FloorManager = FloorManager; var CollisionManager = /** @class */ (function () { function CollisionManager(engine) { this.isOnPlat = false; //console.log("init collision manager!"); this.engine = engine; } CollisionManager.prototype.update = function () { this.playerVsBlock(); this.playerVsPickup(); this.playerVsFloor(); this.playerVsPlat(); this.catVsPickup(); }; CollisionManager.prototype.playerVsBlock = function () { var enemies = this.engine.enemyManager.enemies; var player = this.engine.player; var floatRange = 0; for (var i = 0; i < enemies.length; i++) { var enemy = enemies[i]; if (player.isSlide) { floatRange = 10; } else if (ECS.GameConfig.specialMode == ECS.SPECIALMODE.INDONMODE && ECS.GameConfig.game.player.isPlayingInoEffect) { floatRange = -2000; } else { floatRange = 0; } var xdist = enemy.position.x - player.position.x; var ydist = enemy.position.y - player.position.y; //detect japan mode and ninjia mode if (xdist > -enemy.width / 2 + floatRange && xdist < enemy.width / 2 - floatRange) { var ydist = enemy.position.y - player.position.y; if (ydist > -enemy.height / 2 - 20 + floatRange && ydist < enemy.height / 2 - floatRange) { //attack cat and get point ECS.GameConfig.game.score += 10; switch (ECS.GameConfig.specialMode) { case ECS.SPECIALMODE.NONE: player.die(); this.engine.gameover(); enemy.hit(); break; case ECS.SPECIALMODE.INDONMODE: if (floatRange == -2000) { enemy.hit(); } else { player.die(); this.engine.gameover(); enemy.hit(); } break; case ECS.SPECIALMODE.JAPANMODE: if (ECS.GameConfig.game.player.isPlayingNinjiaEffect) { enemy.hit(); } else { player.die(); this.engine.gameover(); enemy.hit(); } break; case ECS.SPECIALMODE.NINJAMODE: enemy.hit(); break; } } } } }; CollisionManager.prototype.catVsPickup = function () { var pickups = this.engine.pickupManager.pickups; var enemies = this.engine.enemyManager.enemies; for (var i = 0; i < enemies.length; i++) { var enemy = enemies[i]; if (enemy.isHit) continue; //console.log("cat eat!"); for (var j = 0; j < pickups.length; j++) { var pickup = pickups[j]; if (pickup.isPickedUp) continue; //console.log("chk cat eat!"); var xdist = pickup.position.x - enemy.position.x; if (xdist > -pickup.width / 2 && xdist < pickup.width / 2) { var ydist = pickup.position.y - enemy.position.y; //console.log("cat eat food1!"); if (ydist > -pickup.height / 2 - 20 && ydist < pickup.height / 2) { //console.log("cat eat food!"); enemy.view.textures = enemy.stealFrames; ECS.GameConfig.audio.play("catCome"); enemy.view.play(); enemy.isEatNow = true; this.engine.pickupManager.removePickup(j, false, enemy); //this.engine.pickup(i); } } } } }; CollisionManager.prototype.playerVsPickup = function () { var pickups = this.engine.pickupManager.pickups; var player = this.engine.player; for (var i = 0; i < pickups.length; i++) { var pickup = pickups[i]; if (pickup.isPickedUp) continue; var xdist = pickup.position.x - player.position.x; if (xdist > -pickup.width / 2 && xdist < pickup.width / 2) { var ydist = pickup.position.y - player.position.y; if (ydist > -pickup.height / 2 - 20 && ydist < pickup.height / 2) { this.engine.pickupManager.removePickup(i); this.engine.pickup(i); } } } }; CollisionManager.prototype.playerVsPlat = function () { var player = this.engine.player; var platforms = this.engine.platManager.platforms; for (var i = 0; i < platforms.length; i++) { var plat = platforms[i]; var xdist = plat.position.x - player.position.x; //check jump to the plat or not if (xdist > -plat.width / 2 && xdist < plat.width / 2) { var ydist = plat.position.y - player.position.y; if (ydist > -plat.height / 2 - 20 && ydist < plat.height / 2) { if (player.position.y < plat.position.y - 20) { //player jump to the plat player.position.y = plat.position.y - plat.height - player.height - 20; player.ground = player.position.y; ECS.GameConfig.isOnPlat = true; player.onGround = true; } } } } //check leave the plat if (ECS.GameConfig.isOnPlat) { var flag = true; for (var i = 0; i < platforms.length; i++) { var plat = platforms[i]; var xdist = plat.position.x - player.position.x; if (xdist > -plat.width / 2 && xdist < plat.width / 2) { var ydist = plat.position.y - plat.height - player.height - player.position.y - 20; if (ydist <= 0) { //console.log("noy"); flag = false; } } } if (flag) { ECS.GameConfig.isOnPlat = false; ; player.ground = this.engine.player.floorHeight; ECS.GameConfig.playerMode = ECS.PLAYMODE.FALL; player.onGround = false; //console.log("leave plat"); } } }; CollisionManager.prototype.playerVsFloor = function () { var floors = this.engine.floorManager.floors; var player = this.engine.player; var max = floors.length; player.onGround = false; if (player.position.y > ECS.GameConfig.height) { if (this.engine.isPlaying) { player.boil(); //this.engine.view.doSplash(); this.engine.gameover(); } else { player.speed.x *= 0.95; if (!ECS.GameConfig.interactive) { //game end //showGameover(); ECS.GameConfig.interactive = true; } if (player.bounce === 0) { player.bounce++; player.boil(); //this.engine.view.doSplash(); } return; } } for (var i = 0; i < max; i++) { var floor = floors[i]; var xdist = floor.position.x - player.position.x + 1135; //console.log(player.position.y + "/" + this.engine.player.floorHeight); if (player.position.y >= this.engine.player.floorHeight) { if (xdist > 0 && xdist < 1135) { if (player.isDead) { player.bounce++; if (player.bounce > 2) { return; } player.speed.y *= -0.7; player.speed.x *= 0.8; if (player.rotationSpeed > 0) { player.rotationSpeed = Math.random() * -0.3; } else if (player.rotationSpeed === 0) { player.rotationSpeed = Math.random() * 0.3; } else { player.rotationSpeed = 0; } } else { player.speed.y = -0.3; } if (!player.isFlying) { player.position.y = this.engine.player.floorHeight; player.onGround = true; } } } } }; return CollisionManager; }()); ECS.CollisionManager = CollisionManager; })(ECS || (ECS = {})); /* ========================================================================= * * GameKernel.ts * game execute logical * * ========================================================================= */ /// <reference path="./System.ts" /> /// <reference path="./GameConfig.ts" /> /// <reference path="./GameLocalData.ts" /> /// <reference path="./GameBackGround.ts" /> /// <reference path="./GameView.ts" /> /// <reference path="./GameManager.ts" /> /// <reference path="./GameCharacter.ts" /> var ECS; (function (ECS) { var GameKernelSystem = /** @class */ (function (_super) { __extends(GameKernelSystem, _super); function GameKernelSystem() { var _this = _super.call(this, "game kernel") || this; _this.view = (ECS.GameConfig.allSystem.get("view")); _this.player = new ECS.GameCharacter(); _this.segmentManager = new ECS.SegmentManager(_this); _this.enemyManager = new ECS.EnemyManager(_this); _this.platManager = new ECS.PlatformManager(_this); _this.pickupManager = new ECS.PickupManager(_this); _this.floorManager = new ECS.FloorManager(_this); _this.collisionManager = new ECS.CollisionManager(_this); _this.LocalData = new ECS.GameLocalData(ECS.GameConfig.localID); _this.player.view.visible = false; _this.bulletMult = 1; _this.pickupCount = 0; _this.score = 0; _this.distanceScore = 0; _this.isPlaying = false; _this.levelCount = 0; _this.gameReallyOver = false; _this.isDying = false; _this.view.game.addChild(_this.player.view); return _this; } GameKernelSystem.prototype.start = function () { this.segmentManager.reset(); this.enemyManager.destroyAll(); this.pickupManager.destroyAll(); this.platManager.destroyAll(); this.isPlaying = true; this.gameReallyOver = false; this.player.level = 1; this.player.speed.y = 0; this.player.speed.x = this.player.baseSpeed; this.player.view.rotation = 0; this.player.isFlying = false; this.player.isDead = false; this.player.view.play(); this.player.view.visible = true; this.segmentManager.chillMode = false; this.bulletMult = 1; ECS.GameConfig.audio.stop("StartMusic"); ECS.GameConfig.audio.setVolume('GameMusic', 0.5); ECS.GameConfig.audio.play("GameMusic"); }; GameKernelSystem.prototype.update = function () { //console.log("game update!!"); ECS.GameConfig.time.update(); var targetCamY = 0; if (targetCamY > 0) targetCamY = 0; if (targetCamY < -70) targetCamY = -70; ECS.GameConfig.camera.y = targetCamY; if (ECS.GameConfig.gameMode !== ECS.GAMEMODE.PAUSED) { this.player.update(); this.collisionManager.update(); this.platManager.update(); this.segmentManager.update(); this.floorManager.update(); this.enemyManager.update(); this.pickupManager.update(); this.levelCount += ECS.GameConfig.time.DELTA_TIME; if (this.levelCount > (60 * 60)) { this.levelCount = 0; this.player.level += 0.05; ECS.GameConfig.time.speed += 0.05; } } this.view.update(); }; GameKernelSystem.prototype.gameover = function () { this.isPlaying = false; this.isDying = true; this.segmentManager.chillMode = true; var nHighscore = this.LocalData.get('highscore'); if (!nHighscore || this.score > nHighscore) { this.LocalData.store('highscore', this.score); ECS.GameConfig.newHighscore = true; } //this.onGameover(); this.view.game.addChild(this.player.view); TweenLite.to(this.view, 0.5, { zoom: 2, ease: Cubic.easeOut }); }; GameKernelSystem.prototype.pickup = function (idx) { if (this.player.isDead) return; this.pickupCount++; }; return GameKernelSystem; }(ECS.System)); ECS.GameKernelSystem = GameKernelSystem; })(ECS || (ECS = {})); /* ========================================================================= * * GameLoad.ts * system using for load the game resources * * ========================================================================= */ /// <reference path="./System.ts" /> /// <reference path="./GameAudio.ts" /> /// <reference path="./GameKernel.ts" /> /// <reference path="./GameView.ts" /> /// <reference path="./GameBackGround.ts" /> var ECS; (function (ECS) { function update() { ECS.GameConfig.game.update(); requestAnimationFrame(update); } ECS.update = update; var MainSystem = /** @class */ (function (_super) { __extends(MainSystem, _super); function MainSystem(othSystems) { var _this = _super.call(this, "main") || this; _this.OtherSystems = othSystems; return _this; } MainSystem.prototype.Execute = function () { _super.prototype.Execute.call(this); this.OtherSystems.forEach(function (key, val) { val.Execute(); }); }; return MainSystem; }(ECS.System)); ECS.MainSystem = MainSystem; var LoadingSystem = /** @class */ (function (_super) { __extends(LoadingSystem, _super); function LoadingSystem() { var _this = _super.call(this, "loading") || this; //device info detect _this.device = new Utils.DeviceDetect(); //console.log(this.device.PrintInfo()); ECS.GameConfig.audio = new ECS.GameAudio(); Howler.mobileAutoEnable = true; //game resources list _this.resourceList = [ "img/light1.png", "img/light2.png", "img/doroCat.png", "img/dash_stock.png", "img/blade.png", "img/bg_up.png", "img/bg_up_ios.png", "img/bg_down.png", "img/PlayPanel/btn_jump.png", "img/PlayPanel/btn_slide.png", "img/PlayPanel/btn_atk.png", "img/floatingGround.png", "assets/background/BackgroundAssets.json", "assets/food/food.json", "assets/obstacle/obstacle.json", "assets/playUI/playPanel.json", "assets/playUI/number.json", "assets/character/chara1.json", "assets/specialEffect/WorldAssets-hd.json" ]; return _this; } LoadingSystem.prototype.playStartScreenMusic = function () { ECS.GameConfig.audio.setVolume('StartMusic', 0.5); ECS.GameConfig.audio.play("StartMusic"); }; LoadingSystem.prototype.loadingAnime = function () { var loadingTextures = []; for (var i = 0; i < 3; i++) { var texture = PIXI.loader.resources['img/Loading' + (i + 1) + '.png'].texture; loadingTextures.push(texture); } var loading = new PIXI.extras.AnimatedSprite(loadingTextures); loading.x = this.width * 0.5; loading.y = this.height * 0.7; loading.anchor.set(0.5); loading.animationSpeed = 0.1; loading.play(); this.loadingStage.addChild(loading); }; LoadingSystem.prototype.Init = function () { var _this = this; _super.prototype.Init.call(this); this.width = window.innerWidth; this.height = window.innerHeight; //init app for game(add some fundmental options) this.app = new PIXI.Application({ width: this.width, height: this.height, antialias: true, transparent: false, resolution: 1 // default: 1 }); //setting renderer this.app.renderer.backgroundColor = 0x061639; this.app.renderer.view.style.position = "absolute"; this.app.renderer.view.style.display = "block"; this.app.renderer.autoResize = true; this.app.renderer.resize(this.width, this.height); document.body.appendChild(this.app.view); this.loadingFrames = [ "img/Loading1.png", "img/Loading2.png", "img/Loading3.png" ]; this.bgImage = "img/bg.png"; this.logoImage = "img/logo.png"; //loading panel PIXI.loader .add(this.loadingFrames) .add(this.bgImage) .add(this.logoImage) .load(function () { //console.log("show loading panel!"); //show bg image _this.loadingStage = new PIXI.Container(); var load_bg = new PIXI.Sprite(PIXI.loader.resources[_this.bgImage].texture); load_bg.anchor.x = 0; load_bg.anchor.y = 0; load_bg.height = _this.height; load_bg.width = _this.width; _this.loadingStage.addChild(load_bg); //show logo var logo = new PIXI.Sprite(PIXI.loader.resources[_this.logoImage].texture); logo.anchor.set(0.5); logo.position.x = _this.width * 0.5; logo.position.y = _this.height * 0.4; var logoRatio = logo.width / logo.height; logo.height = _this.height / 2; logo.width = logo.height * logoRatio; _this.loadingStage.addChild(logo); _this.loadingAnime(); //TODO! progress bar animation _this.app.stage.addChild(_this.loadingStage); //read game resources _this.LoadGameResources(); }); }; LoadingSystem.prototype.LoadGameResources = function () { var _this = this; PIXI.loader .add(this.resourceList) .load(function () { //console.log("data assets loaded!"); //remove loading panel _this.app.stage.removeChild(_this.loadingStage); //setup game main system ECS.GameConfig.app = _this.app; ECS.GameConfig.width = _this.width; ECS.GameConfig.height = _this.height; ECS.GameConfig.device = _this.device; ECS.GameConfig.allSystem = new Utils.HashSet(); var allSystem = ECS.GameConfig.allSystem; allSystem.set("background", new ECS.GameBackGroundSystem()); allSystem.set("view", new ECS.GameViewSystem()); allSystem.set("kernel", new ECS.GameKernelSystem()); var mainSystem = new MainSystem(allSystem); //game start ECS.GameConfig.game = allSystem.get("kernel"); //bind event var evtSys = new EventListenerSystem(); evtSys.bindEvent(); var game = ECS.GameConfig.game; //show hud game.view.showHud(); update(); game.start(); ECS.GameConfig.gameMode = ECS.GAMEMODE.PLAYING; ECS.GameConfig.playerMode = ECS.PLAYMODE.RUNNING; }); }; LoadingSystem.prototype.Execute = function () { _super.prototype.Execute.call(this); }; return LoadingSystem; }(ECS.System)); ECS.LoadingSystem = LoadingSystem; var EventListenerSystem = /** @class */ (function (_super) { __extends(EventListenerSystem, _super); function EventListenerSystem() { return _super.call(this, "eventlistener") || this; } EventListenerSystem.prototype.bindEvent = function () { //for pc version window.addEventListener("keydown", this.onKeyDown, true); window.addEventListener("keyup", this.onKeyUp, true); //window.addEventListener("touchstart", this.onTouchStart, true); }; EventListenerSystem.prototype.onKeyDown = function (event) { if (event.keyCode == 32 || event.keyCode == 38) { if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.playerMode == ECS.PLAYMODE.RUNNING && !ECS.GameConfig.game.player.isPlayingNinjiaEffect) { ECS.GameConfig.game.player.jump(); ECS.GameConfig.audio.play("jump"); } else if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.playerMode == ECS.PLAYMODE.FALL && ECS.GameConfig.game.player.startJump == true && !ECS.GameConfig.game.player.isPlayingNinjiaEffect) { ECS.GameConfig.game.player.jumpTwo(); ECS.GameConfig.audio.play("jump"); } } else if (event.keyCode == 40) { //console.log(GameConfig.game.player.onGround); if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.playerMode == ECS.PLAYMODE.RUNNING && ECS.GameConfig.game.player.onGround) { ECS.GameConfig.game.player.slide(true); } } else if (event.keyCode == 39) { if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.specialMode == ECS.SPECIALMODE.JAPANMODE) { ECS.GameConfig.audio.play("ninjiaModeAttack"); ECS.GameConfig.game.player.view.textures = ECS.GameConfig.game.player.dashFrames; ECS.GameConfig.game.player.view.play(); ECS.GameConfig.game.player.ninjiaOperate(); } else if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.specialMode == ECS.SPECIALMODE.INDONMODE) { ECS.GameConfig.audio.play("indoMode"); ECS.GameConfig.game.player.view.textures = ECS.GameConfig.game.player.runningFrames; ECS.GameConfig.game.player.view.play(); ECS.GameConfig.game.player.indoOperate(); } } }; EventListenerSystem.prototype.onKeyUp = function (event) { if (event.keyCode == 40) { if (ECS.GameConfig.game.isPlaying && ECS.GameConfig.game.player.isSlide) { ECS.GameConfig.game.player.slide(false); } } }; return EventListenerSystem; }(ECS.System)); ECS.EventListenerSystem = EventListenerSystem; })(ECS || (ECS = {})); /// <reference path="./core/Component.ts" /> /// <reference path="./core/System.ts" /> /// <reference path="./core/Entity.ts" /> /// <reference path="./core/HashSet.ts" /> /// <reference path="./core/GameLoad.ts" /> var load_system = new ECS.LoadingSystem(); if (load_system.device.desktop) { $('#modal_movie').modal('show'); load_system.playStartScreenMusic(); } else { $('#modal_setting').modal('show'); } var startGame = function () { load_system.Init(); }; document.getElementById("btn_play").onclick = function () { document.getElementById("global").style.display = "none"; startGame(); }; document.getElementById("openMusic").onclick = function () { load_system.playStartScreenMusic(); $('#modal_setting').modal('hide'); $('#modal_movie').modal('show'); }; document.getElementById("btn_close").onclick = function () { $('#modal_movie').modal('show'); }; /* ========================================================================= * * GamePartical.ts * partical effect * * ========================================================================= */ var ECS; (function (ECS) { var ExplosionPartical = /** @class */ (function () { function ExplosionPartical(id) { PIXI.Sprite.call(this, PIXI.Texture.fromFrame(id)); this.anchor.x = 0.5; this.anchor.y = 0.5; this.speed = new PIXI.Point(); } return ExplosionPartical; }()); ECS.ExplosionPartical = ExplosionPartical; ExplosionPartical.prototype = Object.create(PIXI.Sprite.prototype); var Explosion = /** @class */ (function () { function Explosion() { PIXI.DisplayObjectContainer.call(this); this.particals = []; this.top = new ExplosionPartical("asplodeInner02.png"); this.bottom = new ExplosionPartical("asplodeInner01.png"); this.top.position.y = -20; this.bottom.position.y = 20; this.top.position.x = 20; this.bottom.position.x = 20; this.anchor = new PIXI.Point(); this.addChild(this.top); this.addChild(this.bottom); this.particals = [this.top, this.bottom]; for (var i = 0; i < 5; i++) { this.particals.push(new ExplosionPartical("asplodeSpike_01.png")); this.particals.push(new ExplosionPartical("asplodeSpike_02.png")); } this.clouds = []; for (var i = 0; i < 5; i++) { var cloud = new PIXI.Sprite.fromFrame("dustSwirl.png"); this.clouds.push(cloud); this.addChild(cloud); } this.reset(); } return Explosion; }()); ECS.Explosion = Explosion; Explosion.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); Explosion.prototype.explode = function () { this.exploding = true; }; Explosion.prototype.reset = function () { for (var i = 0; i < 5; i++) { var cloud = this.clouds[i]; cloud.anchor.x = 0.5; cloud.anchor.y = 0.5; cloud.scaleTarget = 2 + Math.random() * 2; cloud.scale.x = cloud.scale.x = 0.5; cloud.alpha = 0.75; cloud.position.x = (Math.random() - 0.5) * 150; cloud.position.y = (Math.random() - 0.5) * 150; cloud.speed = new PIXI.Point(Math.random() * 20 - 10, Math.random() * 20 - 10); cloud.state = 0; cloud.rotSpeed = Math.random() * 0.05; } for (var i = 0; i < this.particals.length; i++) { var partical = this.particals[i]; this.addChild(partical); var angle = (i / this.particals.length) * Math.PI * 2; var speed = 7 + Math.random(); partical.directionX = Math.cos(angle) * speed; partical.directionY = Math.sin(angle) * speed; partical.rotation = -angle; partical.rotationSpeed = Math.random() * 0.02; } }; Explosion.prototype.updateTransform = function () { if (this.exploding) { for (var i = 0; i < this.clouds.length; i++) { var cloud = this.clouds[i]; cloud.rotation += cloud.rotSpeed; if (cloud.state === 0) { cloud.scale.x += (cloud.scaleTarget - cloud.scale.x) * 5; cloud.scale.y = cloud.scale.x; if (cloud.scale.x > cloud.scaleTarget - 0.1) cloud.state = 1; } else { cloud.position.x += cloud.speed.x * 0.05; cloud.position.y += cloud.speed.y * 0.05; } } for (var i = 0; i < this.particals.length; i++) { var partical = this.particals[i]; partical.directionY += 0.1; partical.directionX *= 0.99; partical.position.x += partical.directionX; partical.position.y += partical.directionY; partical.rotation += partical.rotationSpeed; } } PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); }; })(ECS || (ECS = {}));
function AddSubscription() { var email = document.getElementById("email").value; if (email == "") return; Post("/rest/website_news_sub/", { email }, function (msg) { document.getElementById("email").value = ""; viewmodel.FetchAllWebsiteNewsSubscription(); }); } function DeleteAllSubscription() { $.ajax({ url: location.origin + "/rest/website_news_sub/", type: "DELETE", success: function (msg) { viewmodel.FetchAllWebsiteNewsSubscription(); } }); } var WebsiteNewsSubscription = function (data) { var self = this; this.id = ko.observable(data.id); this.email = ko.observable(data.email); this.type = ko.observable(data.type); this.ip = ko.observable(data.ip); this.create_at = ko.observable(data.create_at); this.formated = function () { return `${self.id()}<br>${self.email()}<br>${self.type()}<br>${self.ip()}<br>${self.create_at()}`; } } function AppViewModel() { var self = this; this.subscriptions = ko.observableArray([]); this.visibleSubscriptions = ko.computed(function () { return self.subscriptions().filter(function (location) { return location; }); }, this); this.FetchAllWebsiteNewsSubscription = function () { $.ajax({ url: location.origin + "/rest/website_news_sub/", success: function (msg) { self.subscriptions.removeAll(); for (row of msg.data) { self.subscriptions.push(new WebsiteNewsSubscription(row)); } } }); } } var viewmodel; function main() { viewmodel = new AppViewModel(); ko.applyBindings(viewmodel); viewmodel.FetchAllWebsiteNewsSubscription(); } if (window.BASIC_JS_LOADED) main(); else document.addEventListener("basic_js_loaded", main);
const Dotenv = require('dotenv-webpack') class Env { constructor () { this.options = [] } /** * Register the component. * * Ex: env(path, options) {} * Ex: mix.env('.env.production', { systemvars: true }); * * @param {string} [path] * @param {Object} [options] */ register (path = '.env', options = {}) { this.options.push({ ...options, path }) } /** * Override the generated webpack configuration. * * @param {Object} config */ webpackConfig (config) { this.options.forEach((options) => { config.plugins.push(new Dotenv(options)) }) } } module.exports = new Env()
import React from 'react'; import MenuIcon from '@material-ui/icons/Menu'; import {Drawer, IconButton} from '@material-ui/core/'; // Side List for Menu import SideList from './SideList'; class LeftMenu extends React.Component { state = { left: false, open: false }; handleClick = () => { this.setState(state => ({ open: !state.open })); }; toggleDrawer = (side, open) => () => { this.setState({ [side]: open, }); }; handleContactClick = () => { console.log("blicked") } render() { return ( <div> <IconButton style={{color:"black"}} aria-label="Open Menu" onClick={this.toggleDrawer('left', true)} > <MenuIcon /> </IconButton> <Drawer open={this.state.left} onClose={this.toggleDrawer('left', false)}> <div tabIndex={0} role="button" > <SideList/> </div> </Drawer> </div> ); } } export default LeftMenu;
import AbstractView from "./AbstractView.js"; export default class extends AbstractView { constructor() { super(); this.setTitle("Stars") } // Grab server-side data async getHtml() { return ` <div class="contentWrapper" > <h1>Our currently logged stars</h1> <table> <thead> <tr> <th>ID<th> <th>Name<th> <th>Color<th> </tr> </thead> <tbody id="starTable"> </tbody> </table> </div> `; } }
import React from 'react' import './AddDetails.css' import AddDetails from './AddDetail' import ShowDetails from './ShowDetails' class Details extends React.Component{ render(){ return( <div className="full-form"><br></br> {/* <h3 style = {{color : "grey",textAlign : "left",fontWeight : "bold"}}>My Wallet</h3> */} <div> <ShowDetails></ShowDetails> </div> <div> <AddDetails></AddDetails> </div> </div> ) } } export default Details;
function Card(dir, mag){//should be flyweight this.direction = dir this.magnitude = mag this.display = function(ctx,x,y,width,height, player){ ctx.beginPath() ctx.fillStyle = player.color //ctx.strokeStyle = player.color2 ctx.strokeStyle = 'rgb(200,200,200)' ctx.rect(x,y,width,height) ctx.fill() //ctx.stroke() ctx.beginPath() ctx.strokeStyle = player.color2 var pi = Math.PI //var rot = {"N":0,"NO":pi/4,"O":pi/4*2,"SO":pi/4*3,"S":pi/4*4,"SW":pi/4*5,"W":pi/4*6,"NW":pi/4*7} var R = 1.95**0.5/2 var N = 1 var rot = {"N":[-N,0],"NO":[-R,R],"O":[0,N],"SO":[R,R],"S":[N,0],"SW":[R,-R],"W":[0,-N],"NW":[-R,-R]} ctx.translate(x+width*0.5,y+height*0.5)//translate origin to center of cards //ctx.rotate(rot[this.direction])//rotate the pointer (sounds like some weird bitshift hack) //ctx.scale(1,height/width) ctx.lineWidth=window.LINEWIDTH*3 ctx.moveTo(0,0) //ctx.lineTo(0,-width*0.16666*this.magnitude) //alternatively use a for loop and move up to three times in the by rot defined direction. ctx.lineTo((rot[this.direction][1]*height*this.magnitude)/(6*(height)/width), (rot[this.direction][0]*width*this.magnitude)/(6*width/height)) ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.stroke() ctx.beginPath() ctx.fillStyle = player.color2 ctx.arc(x+width*0.5,y+height*0.5,height/20,0,2*Math.PI) ctx.fill() ctx.lineWidth = window.LINEWIDTH*2 ctx.strokeStyle = player.color for(var i = 1; i <= 3; i++){ ctx.beginPath() ctx.ellipse(x+width*0.5,y+height*0.5,(width-ctx.lineWidth)/6*i, (height-ctx.lineWidth)/6*i,0,2*Math.PI, false) ctx.stroke() } } this.copy = function(){ var cardCopy = new Card() cardCopy.extend(JSON.stringify(this)) return cardCopy } this.extend = function (jsonString){ var obj = JSON.parse(jsonString) for (var key in obj) { this[key] = obj[key] } } }
var dir_80f0f503abfb39369235c25d2f6a7bf4 = [ [ "dominio", "dir_c7a77c7d494d9ad1c1415f56a0ebc61f.html", "dir_c7a77c7d494d9ad1c1415f56a0ebc61f" ] ];
function say(message) { setTimeout(() => { console.log(message) }, 2000) } export default { say }
import * as _ from "lodash"; export const objectEmpty = (data) => ( Object.keys(data).length === 0 ); export const not = (a, b, key = '_id') => { //Compare mongo _id or other key of objects b = _.map(b, key); return a.filter(value => b.indexOf(value[key]) === -1); }; export const intersection = (a, b, key = '_id') => { //Compare mongo _id or other key of objects b = _.map(b, key); return a.filter(value => b.indexOf(value[key]) !== -1); };
import React from 'react' import { View, Text, TouchableOpacity, BackHandler } from 'react-native' import styles from '../style' import Timer from '../../components/Timer/Timer' import ProgressBar from '../../components/ProgressBar/ProgressBar' import Title from '../../components/Title/Title' import Icon from 'react-native-vector-icons/FontAwesome' import BackgroundProgress from '../../components/BackgroundProgress/BackgroundProgress' import Sound from 'react-native-sound' import SoundAlert from '../../../assets/alert.wav' import Square from 'react-native-vector-icons/FontAwesome' import IconAntDesign from 'react-native-vector-icons/AntDesign' import IconFontAwesome from 'react-native-vector-icons/FontAwesome' import KeepAwake from 'react-native-keep-awake'; export default class AmrapRunning extends React.Component { state = { countDownTime: null, time: 15 * 60, countDown: 0, counterTimer: 0, timeCountDown: null, timer: null, fullTime: null, counterSeconds: 0, alertChoose: 'Desligado', pause: false, count: 0 } componentDidMount() { Sound.setCategory('Playback', true) this.alert = new Sound(SoundAlert) const time = this.props.params.time * 60 this.setState({...this.props.params, time, fullTime: time}, () => { this.initialize() }) BackHandler.addEventListener('hardwareBackPress', this.goBack) } initialize = () => { if(this.props.params.countDown) { this.alert.play() timeCountDown = setInterval(() => { if (!this.state.pause) { this.setState({countDownTime: this.state.countDownTime - 1}) this.alert.play() if (this.state.countDownTime === 0) { clearInterval(timeCountDown) this.setState({countDownTime: null}) this.startTimer() } } }, this.props.params.test ? 100 : 1000) this.setState({timeCountDown}) } else { this.startTimer() } } componentWillUnmount() { clearInterval(this.state.timeCountDown) clearInterval(this.state.timer) BackHandler.removeEventListener('hardwareBackPress', this.goBack) } goBack = () => { if (this.state.pause) { this.props.goBack() } return true } stop = () => this.props.stop() pause = () => { this.setState({pause: !this.state.pause}) } refresh = () => { if(this.state.pause) { const time = this.props.params.time * 60 if (this.state.counterTimer === this.state.fullTime) { this.setState({...this.props.params, counterSeconds: 0, time, fullTime: time, count: 0}, () => this.initialize()) } else { this.setState({...this.props.params, counterSeconds: 0, time, fullTime: time, count: 0}, () => { if(this.props.params.countDown) { clearInterval(this.state.timer) clearInterval(this.state.timeCountDown) this.initialize() } }) } } } startTimer = () => { const timer = setInterval(() => { if(!this.state.pause) { this.setState({counterTimer: this.state.counterTimer + 1, time: this.state.time - 1, counterSeconds: this.state.counterSeconds + 1}) if (this.state.counterSeconds === 60) { this.setState({counterSeconds: 0}) } if (this.state.counterTimer === this.state.fullTime) { this.setState({pause: true}) clearInterval(timer) } if(this.state.alertChoose !== 'Desligado' && this.state.counterTimer % parseInt(this.state.alertChoose.replace('s', '')) === 0) { this.alert.play() } } }, this.props.params.test ? 100 : 1000); this.setState({timer}) } render() { const fullTime = this.state.fullTime const counterTime = this.state.counterTimer const opacity = this.state.pause ? 1 : 0.5 const media = this.state.count > 0 ? counterTime / this.state.count : 0 const estimated = media > 0 ? Math.floor(this.state.fullTime / media) : 0 return( <BackgroundProgress value={this.state.counterSeconds / 60 * 100} test={this.props.params.test}> <KeepAwake /> <View style={styles.containerEmonRunning}> <View style={{position:'absolute', top: 20}}> <Title styleContent={styles.styleContent} style={styles.title} stylesTitle={styles.title} stylesSubTitle={styles.subTitle} title='Amrap' /> <Icon style={styles.iconGear} name="gear" color="#FFF" size={70} /> </View> <View style={{flexDirection: 'row', marginBottom: 10}}> <View style={{flex: 1, alignItems: 'center'}}> <Timer styleText={styles.textTimeRemmaing} time={media} /> <Text style={styles.textTimeRemmaing}>Por repetição</Text> </View> <View style={{flex: 1, alignItems: 'center'}}> <Text style={styles.textTimeRemmaing}>{estimated}</Text> <Text style={styles.textTimeRemmaing}>repetições</Text> </View> </View> <Timer styleText={styles.textTimer} time={this.state.counterTimer}/> <ProgressBar value={counterTime / fullTime * 100} test={this.props.params.test} /> <Timer styleText={styles.textTimeRemmaing} time={this.state.time} appendText=' restantes'/> <View style={styles.timerCountDown}> {this.renderCountDown()} <View style={styles.buttonsBottomBackReset}> <TouchableOpacity onPress={this.goBack} activeOpacity={0.7}> <IconAntDesign style={{opacity}} name="arrowleft" color="#FFF" size={30} /> </TouchableOpacity> <TouchableOpacity onPress={this.pause} activeOpacity={0.7} style={styles.buttonPlay}> { this.state.pause ? <IconAntDesign name="caretright" color="#FFF" size={30} /> : <Square name="square" color="#FFF" size={30} /> } </TouchableOpacity> <TouchableOpacity onPress={this.refresh} activeOpacity={0.7}> <IconFontAwesome style={{opacity}} name="refresh" color="#FFF" size={30} /> </TouchableOpacity> </View> </View> </View> </BackgroundProgress> ) } renderCountDown = () => { if (this.state.countDownTime != null) { return <Text style={styles.textTimerCountDown}>{this.state.countDownTime }</Text> } else { return ( <View style={styles.buttonsAmrap}> <TouchableOpacity onPress={() => this.setState({count: this.state.count - 1 > 0 ? this.state.count - 1 : 0})}> <IconAntDesign color="#FFF" size={80} name="minus" /> </TouchableOpacity> <Text style={styles.textTimer}>{this.state.count}</Text> <TouchableOpacity onPress={() => this.setState({count: this.state.count + 1})}> <IconAntDesign color="#FFF" size={80} name="plus" /> </TouchableOpacity> </View> ) } } }
import React,{useContext, useState} from 'react' import ContactContext from '../context/contact/contactcontext' const Filter = () => { const contactContext=useContext(ContactContext) const {filterContact,clearFilter}=contactContext const [value, setvalue] = useState(null) const getValue=(e)=>{ if(e.target.value !==null){ setvalue(e.target.value) filterContact(value)} else { clearFilter() } } return ( <div> <input type="text" className="form-control" placeholder='filter contacts' value={value} onChange={getValue}/> </div> ) } export default Filter
import React from 'react' import '../css/newcollections.css' function NewCollections() { return ( <div className='newCollection'> <div className='newCollection__img' > <img src="http://file.hstatic.net/1000341789/collection/crop.artboard-1-copy-2_00fc97d67e1a462c812832092ca2aa15_grande.png" alt="" /> </div> <div className="newCollection__img"> <img src="http://file.hstatic.net/1000341789/collection/kv---1080x1080-copy_b15fe59b49774b31991b7b598f0da5be_grande.png" alt="" /> </div> <div className='newCollection__img'> <img src="http://file.hstatic.net/1000341789/collection/nat---social1200x1200-copy_429795d1e72c4c0e92c08a39be27e2fd_grande.png" alt="" /> </div> </div> ) } export default NewCollections
const mongoose = require('mongoose') const Club = require('../../server/models/Club') const Team = require('../../server/models/Team') describe('Associations', () => { let bvb, team beforeEach(done => { bvb = new Club({ name: 'BVB' }) team = new Team({ teamName: 'BVB1' }) bvb.teams.push(team) Promise.all([bvb.save(), team.save()]).then(() => done()) }) it.only('saves a relation between a club and a team', done => { Club.findOne({ name: 'BVB' }) .populate('teams') .then(club => { console.log(club) done() }) }) })
$(document).ready(function(){ document.getElementsByClassName('adminnav')[3].style.backgroundColor="#e8e8e8"; var calday = null; $('#calendar').fullCalendar({ editable:true, navLinks:true, enetLimit:true, //이벤트 제한 locale:'ko', //한글버전 events:{ //하나하나의 일정을 select해서 가져와야함 //컨트롤러에 아마도 arrayList로해야하나...?json형태로출력... url:'/asdf', //컨트롤러명하고 일치 error:function(){ console.log("select가 안됨 에러"); } }, //drop이벤트 (날짜수정가능) eventDrop:function(event, delta, revertFunc){ var calendar_title =$('#calendar_title').val(); var calendar_start_date=$('#calendar_start_date').val(); var calendar_end_date=$('#calendar_end_date').val(); $.ajax({ /*type:'POST',*/ url:'/calmodify', data:{calno:calno, calendar_start_date:event.start.format(), calendar_end_date:event.end.format()}, //event_id ->고유키 update 테이블 set start=?, end=? where calId=? cache:false, async:false, success:function(data){ if(result=='OK'){ $('#calendar').fullCalendar('refetchEvents'); } } }) }, //일정 삭제 eventClick: function(calEvent, jsEvent, view){ if(confirm("정비 예약 "+calEvent.title+"을 삭제하시겠습니까?")){ // return false; //취소를 눌렀을때 실행 중단 $.ajax({ /*type:'POST',*/ url:'/caldelete', data:{calno:calEvent.calno}, //calEvent.id => primarykey...고유값만 가져와서 delete하면됨 cache:false, async:false, success:function(data){ console.log("여기"); // if(data =="OK"){ alert("정비 예약이 삭제 되었습니다."); $('#calendar').fullCalendar('refetchEvents'); // } } }) } } //일정삭제 end }); //날짜이전버튼 클릭시 $("button.fc-prev-button").click(function() { var date = $("#calendar").fullCalendar("getDate"); console.log("이전버튼") }); $('.fc-day').click(function(){ var moment = $('.callender_area').fullCalendar('getDate'); // var yy=moment.format("YYYY"); // var mm=moment.format("MM"); // var dd=moment.format("DD"); // var ss=moment.format("dd"); console.log(moment); }); rereplybtn(); }); /* 스케줄 등록 */ function addSchedule(){ var addpop =""; addpop+="<div class='addpop_box'><div class='addpop_tit_box'>스케줄 명</div><div class='addpop_input_box'><input type='text' id='calendar_title' class='calendar_input' value=''></div></div>"; addpop+="<div class='addpop_box'><div class='addpop_tit_box'>시작 날짜</div><div class='addpop_input_box'><input type='date' id='calendar_start_date' value='' class='addpop_input calendar_input'></div></div>"; addpop+="<div class='addpop_box'><div class='addpop_tit_box'>마침 날짜</div><div class='addpop_input_box'><input type='date' id='calendar_end_date' value='' class='addpop_input calendar_input'></div></div>"; addpop+="<div class='addpop_btn'><button onclick='javascript:saveSchedule();' class='admin_btn subminbtn'>저장</button></div>"; openPopup('정비 스케줄 등록', addpop, 400); } function openPopup(subject,contents, widths){ $('#alert_subject').html(subject); $('#alert_contents').html(contents); openMessage('winAlert', widths); //일정값이 담겨있다 } //스케줄저장시 function saveSchedule(){ var calendar_title =$('#calendar_title').val(); var calendar_start_date=$('#calendar_start_date').val(); var calendar_end_date=$('#calendar_end_date').val(); if(!calendar_title){ alert('스케줄 명을 입력해 주세요'); return false; } if(!calendar_start_date){ alert('시작 날짜를 입력해 주세요'); return false; } if(!calendar_end_date){ alert('마침 날짜를 입력해 주세요'); return false; } $.ajax({ /*type:'POST',*/ url:'/calinsert', data:{title:calendar_title, start:calendar_start_date, end:calendar_end_date}, cache:false, async:false, success:function(data){ closeMessage('winAlert'); alert('스케줄이 저장되었습니다.'); $('#calendar').fullCalendar('refetchEvents');//새로고침 되면서 리프레시 } }) } //관리자 답변box function adminreply(obj){ $(obj).parent().parent().next().fadeToggle(); } //예약 저장 버튼 클릭시 function reservsend(reservorder){ var userid=document.getElementById('userid').value; console.log('id' + userid); var textbox = document.getElementById('reservationText'+reservorder); console.log(reservorder); var txt = document.getElementById('reservationText'+reservorder).value; console.log("caldate"+caldate); var reservedata = {"userid":userid,"reservtxt":txt,"reservorder":reservorder}; $.ajax({ url:'/reservationinsert' , data : reservedata , dataType : 'json' , contentType: "application/json;charset=utf-8" , success : function(data) { let result =''; $.each(data,function(index,item){ if(item.reservlevel==0) { console.log("relevel--0일때"); result +='<div class="repair_inquirylist">'; result +='<div class="repair_inquirylist_txt">'; result +='<p class="repair_inquiry_user">'+item.username+'</p>'; result +='<p class="repair_inquiry_date">작성일 :'+item.reservwritedate+'</p>'; result +='<p class="repair_inquiry_txt"><span class="repair_inquiry_cal">예약일자 '+item.caldate+'</span> | '+item.reservtxt+'</p>'; result +='</div>'; result +='<div class="repair_inquirylist_btn" data-temp="ppsc1" style="display:block;">'; result +='<input type="button" value="답변" class="admin_btn" onclick="adminreply(this)">'; result +='</div>'; result +='</div>'; result +='<form style="display:none; height: 70px; margin-left: 24px;">'; result +='<ul>'; result +='<li class="repair_li">'; result +='<label for="reservationText" class="reservation_label">정비 문의</label>'; result +='<input type="hidden" name="userid" value="'+userid+'">'; result +='<textarea rows="3" cols="117" name="reservtxt" id="reservationText'+item.reservorder+'" class="repair_text reservationText" placeholder="문의한 글의 답변 내용을 작성해주시기 바랍니다."></textarea>'; result +='</li>'; result +='<li class="repair_li">'; result +='<input type="hidden" name="caldate" id="caldate">'; result +='<input type="button" value="저장" class="admin_btn subminbtn" onclick="reservsend('+item.reservorder+')">'; result +='</li>'; result +='</ul>'; result +='</form>'; }else if(item.reservlevel==1) { result +='<div class="reply_box">'; result +='<div class="reply">'; result +='<p class="rereply_admin">관리자 답변 | <span class="rereply_admintxt"> '+item.reservtxt+'</span></p>'; result +='</div>'; result +='</div>'; } }); $('#reply_container').html(result); //$('#reservationText').text(''); textbox.value = ''; textbox.parentNode.parentNode.parentNode.remove(); alert("답변이 저장 되었습니다."); amdinrereplybtn(); } , error : function(data){ console.log("저장버튼 클릭시 error"); } }); } function rereplybtn() { var rereplyarr = document.getElementsByClassName('rereply_admin'); for(var i=0; i< rereplyarr.length; i++) { console.log("여기"); rereplyarr[i].parentNode.parentNode.previousSibling.previousSibling.previousSibling.previousSibling.children[1].remove(); } } function amdinrereplybtn() { var rereplyarr = document.getElementsByClassName('rereply_admin'); for(var i=0; i< rereplyarr.length; i++) { console.log("여기"); rereplyarr[i].parentNode.parentNode.previousSibling.previousSibling.children[1].remove(); } } //팝업창 function openMessage(IDS, widths){ $('#'+IDS).css('width', widths+'px'); //특정아디값을 지정하면 $('#'+IDS).bPopup(); //팝업뜨게하는것 } function closeMessage(IDS){ $('#'+IDS).bPopup().close(); }
import { Recipes } from '/imports/api/recipes/recipes.js'; import { Meteor } from 'meteor/meteor'; import './recipe_search_list.html'; import { deleteRecipe } from '/imports/api/recipes/methods.js'; import { ReactiveDict } from 'meteor/reactive-dict' import { FlowRouter } from 'meteor/kadira:flow-router'; Template.recipe_search_list.onCreated(function () { this.state = new ReactiveDict(); this.state.set('searchTerm',''); this.autorun(() => { this.subscribe('recipeSearchResults', this.state.get('searchTerm')) }); }); Template.recipe_search_list.helpers({ recipes() { const template = Template.instance(); if (template.state.get('searchTerm') == '' | template.state.get('searchTerm') == null) { console.log('empty search') return Recipes.find({}); } else { console.log('Not empty search') return Recipes.find({}, { sort: [["score", "desc"]] }) } } }); Template.recipe_search_list.events({ 'keyup #recipe-search': function(event) { console.log('click') const template = Template.instance(); template.state.set('searchTerm', event.target.value) }, 'click .deleteRecipe': function remove(event) { var recipeId = event.currentTarget.id; deleteRecipe.call(recipeId) if (FlowRouter.getParam('_id') == recipeId) { FlowRouter.go('/recipes') } }, 'click .recipe-list': function (event) { const recipeId = event.currentTarget.id; const path = '/recipes/' + recipeId FlowRouter.go(path) } });
import styles from "../styles/UserChatInformation.module.scss" export default function UserChatInformation () { return ( <div className={styles.userChatInfo} > <div className={styles.userNamePhoto} > <div className={styles.userPhoto}> <img src="https://iupac.org/wp-content/uploads/2018/05/default-avatar.png" alt="user" /> </div> <h4>Nicholas Ceneviva</h4> <h6>Philadelphia, PA</h6> </div> <div className={styles.contactInfo}> <hr/> <p>Role:<span>Customer Success Engineer</span></p> <hr/> <p>Company:<span>Databricks</span></p> <hr/> <p>School:<span>Penn State</span></p> <hr/> <p>Pronouns:<span>He/Him</span></p> <hr/> <p>Language:<span>English</span></p> </div> </div> ) }
const { PRIVATE } = require('./constants.js') function middleware (req, res, next) { req[PRIVATE] = {} req[PRIVATE].functionName = req.params["lambdaName"] if(req.body["Role"] !== undefined) { req[PRIVATE].role = req.body["Role"] } if(req.body["Handler"] !== undefined) { req[PRIVATE].handler = req.body["Handler"] } if(req.body["Timeout"] !== undefined) { req[PRIVATE].timeout = req.body["Timeout"] } if(req.body["MemorySize"] !== undefined) { req[PRIVATE].memorySize = req.body["MemorySize"] } if(req.body["Environment"] !== undefined) { req[PRIVATE].environment = req.body["Environment"] } if(req.body["Runtime"] !== undefined) { req[PRIVATE].runtime = req.body["Runtime"] } next() } async function handler (req, res) { console.log(JSON.stringify(req[PRIVATE], null, 2)) const lambda = this.state.lambdas.find( lambda => lambda.functionName === req[PRIVATE].functionName ); if(lambda !== undefined){ lambda.role = req[PRIVATE].role lambda.handler = req[PRIVATE].handler lambda.timeout = req[PRIVATE].timeout lambda.memorySize = req[PRIVATE].memorySize lambda.environment = req[PRIVATE].environment lambda.runtime = req[PRIVATE].runtime } res.end('') } module.exports = { middleware, handler }
const users = require('../user').users; const login = (req,res,next) => { let userFind = users.filter(user => user.name === req.body.name)[0]; if(userFind && req.body.password == userFind.password){ req.session.currentUser = userFind; res.send({userFound: true}) } else{ res.send({ userFound: false }) } } module.exports = { login }
import notificationPage from '../pages/NotificationPage' const notificationRoutes = [ { name: "notifications", path: '/notifications', component: notificationPage, meta: { requiresAuth: true, permission: "CUSTOMFIELDS_SHOW" } } ] export default notificationRoutes
import RoleMixin from "./RoleMixin"; export {RoleMixin} export default RoleMixin
import { SET_DEPOSIT_INFO } from '../actions/deposit'; const initialState = { currency : '', amount : 0, neededTrade : false, confirmations : 0, tx : null }; export default function (state = initialState, action) { switch (action.type) { case SET_DEPOSIT_INFO :{ if((action.action.key == 'isConfirmed') && (action.action.value == true)){ return {...initialState}; } return {...state, [action.action.key] : action.action.value} } default: return state; } }
import styled from 'styled-components'; const CenterContent = styled.div` display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0 auto; max-width: 960px; text-align: center; width: 100%; `; const Container = styled.div` max-width: 1024px; margin: 0 auto; padding: 0 40px; width: 100%; `; export { CenterContent, Container };
angular.module('meanDemoApp') .directive('questionForm', function() { return { restrict: "EA", scope: {}, controller: 'QuestionformCtrl', templateUrl: '/views/question-form.tpl.html' }; });
import { h, Component } from 'preact'; export default class WordMore extends Component { render() { return ( <div className="word-input"> <input className="word-input-btn" name="word-more" type="button" value={this.props.text} onClick={this.props.handleMore} /> </div> ); } }
$(document).ready(function() { // prep for api post/put $.ajaxSetup({ headers: { "X-CSRFToken": window.spacescout_admin.csrf_token } }); var startAddEditor = function (data) { var editor = $('.space-add-section > div'), fields = window.spacescout_admin.fields, i; window.spacescout_admin.spot_schema = data; for (i = 0; i < fields.length; i += 1) { if (typeof fields[i].value === 'object') { if ($.isArray(fields[i].value)) { window.spacescout_admin.appendFieldList(fields[i], getFieldValue, editor); } else { window.spacescout_admin.appendFieldValue(fields[i], getFieldValue, editor); } } } validate(); $('input, textarea, select').change(validate); $('input[class*="required-limit-"]').click(limitChoiceCount); $('input').keydown(validateInput); $('a.btn').click(createSpace); }; var limitChoiceCount = function (e) { var m = $(e.target).prop('class').match(/required-limit-(\d+)/); if (m && $('input[name="' + $(e.target).prop('name') + '"]:checked').length > m[1] && $(e.target).is(':checked')) { e.preventDefault(); } }; var createSpace = function (event) { $.ajax({ url: window.spacescout_admin.app_url_root + 'api/v1/space/', dataType: 'json', contentType: "application/json", data: JSON.stringify(window.spacescout_admin.collectInput()), type: "POST", success: function (json) { window.location.href = window.spacescout_admin.app_url_root + 'space/' + json.id; }, error: XHRError }); }; var validateInput = function (event) { window.spacescout_admin.validateInput(event); setInterval(validate, 200); }; var validate = function () { window.spacescout_admin.validateFields(); if ($('.required-field-icon:visible').length == 0) { $('a.btn').removeAttr('disabled'); } else { $('a.btn').attr('disabled', 'disabled'); } }; var XHRError = function (xhr) { var json; try { json = $.parseJSON(xhr.responseText); console.log('space query service error:' + json.error); } catch (e) { console.log('Unknown space service error: ' + xhr.responseText); } }; var getFieldValue = function (v) { var m; if (v.hasOwnProperty('edit') && v.edit.hasOwnProperty('default')) { m = v.edit.default.match(/{{\s*([\S]+)\s*}}/); if (m && window.spacescout_admin.hasOwnProperty('vars') && window.spacescout_admin.vars.hasOwnProperty(m[1])) { return window.spacescout_admin.vars[m[1]]; } return v.edit.default; } return ''; }; // fetch spot data $.ajax({ url: window.spacescout_admin.app_url_root + 'api/v1/schema', dataType: 'json', success: startAddEditor, error: XHRError }); });
import React from 'react'; import { inject, observer } from 'mobx-react'; @inject('store') @observer class RangeForm extends React.Component { state = { text: '', type: 'range', from: '1', to: '5', }; store = this.props.store.survey; componentDidMount() { const question = this.store.questions.find( question => question.id === this.props.id, ); for (let prop in this.state) { if (!question[prop]) { question[prop] = this.state[prop]; } } } handleInputChange = (e, stateProp) => { this.props.touch() const question = this.store.questions.find( question => question.id === this.props.id, ); if (stateProp === 'from' || stateProp === 'to') { question[stateProp] = Number(e.target.value); } else { question[stateProp] = e.target.value; } }; render() { return ( <div className="range-form"> <div className="form-group"> <input required="required" onChange={e => this.handleInputChange(e, 'text')} type="text" value={this.props.text || this.state.text} /> <label htmlFor="input" className="control-label">Question</label><i className="bar"></i> </div> <input className="select-question select-range" onChange={e => this.handleInputChange(e, 'from')} type="number" placeholder="0" value={this.props.from || this.state.from} /> <span className="range-to">to</span> <input className="select-question select-range" onChange={e => this.handleInputChange(e, 'to')} type="number" placeholder="0" value={this.props.to || this.state.to} /> </div> ); } } export default RangeForm;
module.exports = function experienceCtrl (experienceFactory) { var vm = this; experienceFactory .getWork() .then(function() { vm.work = experienceFactory.work; }); };
const utilities = require('utilities'); const bcrypt = require('bcryptjs'); const services = require('../../services'); exports.token = async (req, res) => { if (utilities.hasEmptyValueInArray(Object.values(req.body))) { return res.status(400).json({ error: 'invalid_request', error_description: 'Required parameters are missing in the request.' }); } try { // eslint-disable-next-line camelcase const { client_id, client_secret, username, password } = req.body; const client = await services.client.findByClientId(client_id); if (!client) { return res.status(401).json({ error: 'access_denied' }); } const validClientPass = await bcrypt.compare( client_secret, client.clientSecret ); if (!validClientPass) { return res.status(401).json({ error: 'access_denied' }); } const user = await services.user.findByUsername(username); if (!user) { return res.status(400).json({ message: 'username or password is wrong' }); } const validUserPass = await bcrypt.compare(password, user.password); if (!validUserPass) { return res.status(401).json({ error: 'username or password is wrong' }); } const token = utilities.generateAccessToken(); return res.json({ token }); } catch (error) { return res.sendStatus(500); } };
const redisConstants = require('../constants/redis'); const redis = require('../shared/redis'); const find = async (id) => { const value = await redis.get(`${redisConstants.usernamePrefix}:${id}`); return value ? value : null; }; const save = async (id, username) => { redis.set(`${redisConstants.usernamePrefix}:${id}`, username); return username; } module.exports = { find, save, };
/** * @file: homeListProducts.js * * @description: Displays the products related to selection Items of the subheader. */ import React from 'react'; import {View, StyleSheet, FlatList} from 'react-native'; //PARTS import HomeListProductsItem from './homeListProductsItem/homeListProductsItem'; const HomeListProducts = ({products, theme}) => { const renderProducts = ({item, index}) => { return <HomeListProductsItem item={item} theme={theme} />; }; return ( <View style={styles.container}> <FlatList data={products} renderItem={renderProducts} showsHorizontalScrollIndicator={false} horizontal={true} keyExtractor={(item, index) => item.key} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 0.7, }, }); export default HomeListProducts;
const FROZEN_EVENT = 'frozen'; //stream frozen on same frame const CRASH_EVENT = 'crash'; //ffmpeg crashed const FRAME_EVENT = 'frame'; //frame matched const UP_EVENT = 'up'; const defaultOptions = { fuzz: 10, delay: 1, freezeTimeLimit: 30, checkFrames: null, checkFrameOptions: {}, screenshotsPath: '/tmp/', actualScreenshotsPath: null, actualScreenshotName: null, limiter: null, differentPixelsLimit: 1000, useMean: false, silenceVolumeLevel: -91.0, crashCountForEmit: 3 }; const EventEmitter = require('events'); const { fileExists, copyFile, moveFile, removeFile, makeScreenshot, imagesEqual, now } = require('./helpers'); class VideoStreamMonitor extends EventEmitter { constructor(streamUrl, filename, options) { super(); this.init(streamUrl, filename, options, true); } init(streamUrl, filename, options, fromConstructor = false) { if (fromConstructor) { this.lastSeenMotion = now(); this.timeoutHandle = null; this.isPreviousExists = false; this.isRunning = false; this.crashCount = 0; } this.url = streamUrl; this.filename = filename; this.options = Object.assign({}, defaultOptions, options); this.currentScreenshotPath = this.options.screenshotsPath + this.filename + '.png'; this.previousScreenshotPath = this.options.screenshotsPath + this.filename + '.old.png'; this._makeScreenshot = (this.options.limiter === null) ? makeScreenshot : this.options.limiter.wrap(makeScreenshot); this.checkFrames = (this.options.checkFrames === null) ? null : this.options.checkFrames; this.checkFrameOptions = this.options.checkFrameOptions; if (this.options.actualScreenshotsPath !== null) this.actualScreenshotPath = `${this.options.actualScreenshotsPath}${this.options.actualScreenshotName}.png`; } _getFrameOption(type, name) { return (this.checkFrameOptions[ type ] && this.checkFrameOptions[ type ][ name ]) ? this.checkFrameOptions[ type ][ name ] : this.options[ name ]; } _currentScreenshotEqual(path, fuzz, differentPixelsLimit) { return imagesEqual(this.currentScreenshotPath, path, fuzz, differentPixelsLimit); } async _cleanup() { try { if (this.isPreviousExists) await removeFile(this.previousScreenshotPath); } catch (e) {} this._scheduleNextCheck(); } _emitter(event, payload) { this.emit(event, payload); return this._cleanup(); } async _screenshotMakingError(silent = false) { try { if (this.isPreviousExists) await moveFile(this.previousScreenshotPath, this.currentScreenshotPath); } catch (e) {} this.isPreviousExists = false; if (!silent) if (this.crashCount >= this.options.crashCountForEmit) return this._emitter(CRASH_EVENT); else return this._cleanup(); } async _check() { if (!this.isRunning) return; try { this.isPreviousExists = await fileExists(this.currentScreenshotPath); if (this.isPreviousExists) await moveFile(this.currentScreenshotPath, this.previousScreenshotPath); } catch (e) { this.isPreviousExists = false; } let volumeLevel; try { volumeLevel = await this._makeScreenshot(this.url, this.currentScreenshotPath, this.options.useMean); } catch (e) { this.crashCount++; return this._screenshotMakingError(!this.isRunning); } this.crashCount = 0; try { if (this.actualScreenshotPath) await copyFile(this.currentScreenshotPath, this.actualScreenshotPath); } catch (e) {} if (this.checkFrames) for (let type in this.checkFrames) if (this.checkFrames.hasOwnProperty(type)) { const fuzz = this._getFrameOption(type, 'fuzz'); const differentPixelsLimit = this._getFrameOption(type, 'differentPixelsLimit'); for (let errorFramePath of this.checkFrames[ type ]) if (await this._currentScreenshotEqual(errorFramePath, fuzz, differentPixelsLimit)) return this._emitter(FRAME_EVENT, type); } const { fuzz, differentPixelsLimit } = this.options; if (this.isPreviousExists && await this._currentScreenshotEqual(this.previousScreenshotPath, fuzz, differentPixelsLimit)) { if (((this.lastSeenMotion + this.options.freezeTimeLimit) < now()) && (volumeLevel <= this.options.silenceVolumeLevel)) return this._emitter(FROZEN_EVENT); } else { this.lastSeenMotion = now(); } return this._emitter(UP_EVENT, volumeLevel); } _scheduleNextCheck() { if (this.isRunning) this.timeoutHandle = setTimeout(this._check.bind(this), this.options.delay * 1000); } start() { this.isRunning = true; this.crashCount = 0; this._scheduleNextCheck(); } //do not forget to manually stop limiter stop() { clearTimeout(this.timeoutHandle); this.isRunning = false; } } module.exports = VideoStreamMonitor;
export default { shaped: ``, transcript: ` 45. toutes les idées, toute la DATA tout ça disponible pour tous sur le HOL-ONG 46. d'ou bout à l'autre de l'arborescence, les VAULTS sont connectées et forment des constellations 47. les premiers SVAGRS ont imaginés des lieus de chill dans lesquels imaginer encore mieux 48. globalement, tout suit le processus d'amélioration continue 49. c'est selon le mécanisme qu'est atteinte l'exponentialié 50. et par l'exponentialité, les ZUMS (et la HOL-LIGHF à travers eux), leur permettra d'atteindre ensuite l'objectif ultime 51. à cette époque déjà on trouve des ABS-VAULTS 52. dans ces lieux semi-virtuels, empreints de très haute sainteté, on réfléchit à ces problématiques de la fin de l'univers ` }
import { CHANGE_SEARCHFIELD, REQUEST_ROBOTS_PENDING, REQUEST_ROBOTS_SUCCESS, REQUEST_ROBOTS_FAILED } from './constants.js'; import * as reducers from './reducers'; describe('testing SearchRobots reducer', () => { it('spits out initial state correctly', () => { expect(reducers.searchRobots(undefined, {})).toEqual({searchfield:''}); }) it('handles CHANGE_SEARCHFIELD well', () => { expect(reducers.searchRobots('', { type: CHANGE_SEARCHFIELD, payload: 'abc' }) ).toEqual({searchfield:'abc'}); }) }) describe('testing RequestRobots reducer', () => { const initialStateRobots = { isPending: '', robots: [], error: '' } it('spits out initial state correctly', () => { expect(reducers.requetRobots(undefined, {})).toEqual(initialStateRobots); }) it('handles REQUEST_ROBOTS_PENDING well', () => { expect(reducers.requetRobots('', { type: REQUEST_ROBOTS_PENDING, }) ).toEqual({ isPending:true, }) }) it('handles REQUEST_ROBOTS_SUCCESS well', () => { expect(reducers.requetRobots('', { type: REQUEST_ROBOTS_SUCCESS, payload: [{ id:101, name: 'Johnny BG', email:'test@caramail.com'}] }) ).toEqual({ isPending:false, robots:[{ id:101, name: 'Johnny BG', email:'test@caramail.com'}], }) }) it('handles REQUEST_ROBOTS_FAILED well', () => { expect(reducers.requetRobots('', { type: REQUEST_ROBOTS_FAILED, payload: 'Dang!' }) ).toEqual({ error:'Dang!', isPending: false }) }) })
var assert = require("assert"); var system = require("system"); var {DelayQueue} = require("../lib/delayqueue"); exports.setUp = function() { }; exports.tearDown = function() { }; exports.testAddAndSize = function() { var dq = new DelayQueue(); assert.strictEqual(dq.size(), 0); dq.add("whatever", 10); assert.strictEqual(dq.size(), 1); dq.add("whatever", 10); assert.strictEqual(dq.size(), 2); }; exports.testPoll = function() { var dq = new DelayQueue(); var val = "whatever"; dq.add(val, 1); assert.strictEqual(dq.poll(), null); try { java.lang.Thread.sleep(500); } catch(e) {} assert.strictEqual(dq.poll(), null); try { java.lang.Thread.sleep(501); } catch(e) {} assert.strictEqual(dq.poll(), val); }; exports.testTimeToNextReady = function() { var dq = new DelayQueue(); assert.isTrue(dq.timeToNextReady() === undefined); dq.add("whatever", 20); assert.isTrue(dq.timeToNextReady() > 19900); dq.add("whatever", 10); assert.isTrue(dq.timeToNextReady() > 9900); };
const Option = require('../models/option'); var cron=require('node-cron'); //var em= require('../controllers/email'); module.exports = { new: newOption, create, index, show, edit, getChoices, deleteOption, showEditPage, updateOption, showChart }; function newOption(req, res) { res.render('options/new'); } function create(req, res) { const option = new Option(req.body); //option.user = req.user._id; option.save(function(err) { if (err) return res.render('options/new'); res.redirect('/options'); }); } function index(req, res) { // Option.find({user: req.user._id}, function(err, options) { // res.render('options/index', {options}); // }); Option.find({}, function(err, options) { // em.sendEmail(options,'vijaybabu.srireddy@gmail.com'); res.render('options/index', {options}); }); } // function show(req, res) { // res.render('options/show'); // } function show(req, res) { // Option.find({user: req.user._id}, function(err, options) { // res.render('options/show', {options}); // }); Option.find({}, function(err, options) { res.render('options/show', {options}); }); } // function addOption(req, res,) { // Option.find({user: req.user._id}, function(err, options) { // res.render('options/show', {options}); // }); // } // function addChoice(req, res) { // Option.find({isChoice: true}, function(err, options) { // res.render('options/show', {options}); // }); // } // function makeChoice(req, res) { // const option = new Option(req.body); // // option.user = req.user._id; // option.isChoice = true; // option.save(function(err) { // if (err) return res.render('options/'); // res.render('options/show'); // }); // // } // function edit(req, res) { // Option.findById(req.params.id, function(err, option) { // // Verify book is "owned" by logged in user // option.isChoice = true; // option.save(function(err) { // console.log('error while saving'); // }); // res.render('options/show', {option}); // }); // } function edit(req, res) { Option.findById(req.params.id, function (err, option) { // Verify book is "owned" by logged in user option.isChoice = true; // var date=new Date(option.date); // var datestr=''+date.getMinutes()+' '+date.getHours()+' '+date.getDate()+' '+(Number(date.getMonth())+1).toString()+' '+option.weekday; // console.log(datestr); // var task=cron.schedule(datestr,function () { // console.log('job scheduled now'); // }); // task.start(); option.save(function (err) { console.log('error while saving'); }); }); Option.find({isChoice:true}, function(err, options) { // Verify book is "owned" by logged in user res.redirect('/options/show'); }); } function showEditPage(req,res) { Option.findById(req.params.id, function (err, option) { res.render('options/edit',{option}); }); } function updateOption(req,res) { Option.findByIdAndUpdate(req.params.id, req.body,function (err, option) { console.log('error while saving'); res.redirect('/options'); }); } function deleteOption(req, res) { Option.findByIdAndDelete(req.params.id, req.body,function (err, option) { console.log('error while deleting'); res.redirect('/options'); }); // Option.deleteOne({_id:req.params.id}, function (err, option) { // console.log('deleted'); // }); // Option.find({}, function(err, options) { // res.redirect('/options'); // }); // Option.deleteOne(req.params.id, function(err, option) { // // Verify book is "owned" by logged in user // console.log('error while deleting'); // res.render('options/show', {option}); // }); } function getChoices(req, res) { Option.find({isChoice:true}, function(err, options) { // Verify book is "owned" by logged in user res.render('options/show', {options}); }); } function showChart(req, res) { Option.find({}, function(err, options) { // Verify book is "owned" by logged in user res.render('options/chart', {options}); }); } // function createChoice(req, res,) { // // Option.deleteOne({user: req.user._id}); // // res.render('/options'); // const option = Option(req.body); // option.user = req.user._id; // option.save(function(err) { // if (err) return res.redirect('/options/show'); // res.render('/options'); // }) // }
// @flow import nock from 'nock'; import * as utils from './http_client'; describe('webinar-registration-service/utils', () => { describe('apiBase', () => { it('is set to GoToWebinar base API URL', () => { expect(utils.apiBase).toEqual('https://api.getgo.com'); }); }); describe('fetchWithBody', () => { it('fetches headers and body', () => { nock('https://example.com') .post('/users', { username: 'pgte', email: 'pedro.teixeira@gmail.com', }) .reply(201, { uid: 123, }); const request = utils.fetchWithBody('https://example.com/users', { method: 'POST', body: JSON.stringify({ username: 'pgte', email: 'pedro.teixeira@gmail.com', }), }); expect.assertions(1); return request.then(data => expect(data.response.status).toEqual(201)); }); }); });
const express = require('express') const evenement = require('../models/evenement') const evenementController = require('../controller/evenementController') const router = express.Router() //var MongoObjectID = require("mongodb").ObjectID; // Necessaire pour gérer les ID mongoDB //Juste pour tester que les évenements se crée dans le base de donnée quand je get localhost:5000/evenement/ -> résultat ok router.get('/', async (req, res) => { res.send('Events') const evenementtest = new evenement({ nomEvenement : 'TestNom', dateDebut : new Date, duree: 7, dateLimiteMax : new Date, dureeCreneau : 60, nombreMembreJury : 3, anneePromo : 3 }) console.log(evenementtest) try{ // cette fonction appelé sur mon instance du model evenement sauvegarde mon instance dans la base de donnée await evenementtest.save() } catch(e) { console.log(e) } }) //----------------------------admin_all_events--------------------------------- router.route('/admin_all_events') .get(evenementController.allEvents) //----------------------------admin_view_event--------------------------------- router.route('/admin_view_event/:_id') .get(function(req,res){ let event = evenementController.eventById(req.params._id) //suppose que id=53dfe7bbfd06f94c156ee96e dans HTML res.render('admin_view_event')//{var1:event.id....} }) //------------------------------student_event-------------------------------- router.route('/student_event') .get(function(req,res){ let event = evenementController.eventById(req.query.id) //suppose que id=53dfe7bbfd06f94c156ee96e dans HTML res.render('student_event')//{var1:event.id....} }) //-----------------------------etu_creat_reservation------------------------ router.route('/etu_creat_reservation') module.exports = router
const { router } = require('../../../config/expressconfig') const Faq = require('../../models/faq') let addQuestion = router.post('/add-new-question',(req,res)=>{ let { id, postedUserId, question, answer } = req.body; let obj = { postedUserId, question, answer } Faq.create(obj).then(result=>{ console.log(result) }).catch(error=>{ console.log(error) }) return res.status(200).json({ msg:"New Question added successfully" }) }) module.exports = { addQuestion }
const express = require("express"); const router = express.Router(); router.post("/add", async (req, res, next) => { let name = req.body.name; let type = req.body.type; let quantity = req.body.quantity; let price = req.body.price; const query = `insert into mandi(name,type,quantity,price) values("${name}", "${type}","${quantity}","${price}");`; db.query(query, (err, result) => { if (err) throw err; }); res.render("index.ejs"); }); router.get("/add", async (req, res, next) => { res.render("seller.ejs", { title: "Welcome to Online Mandi" }); }); router.get("/", async (req, res, next) => { let query = "SELECT * FROM mandi ORDER BY id ASC"; db.query(query, (err, result) => { if (err) res.redirect("/"); res.render("index.ejs", { title: "Home Page", veges: result }); }); }); router.post("/cart", async (req, res, next) => { var take = req.body; console.log(take); var arr = []; for (var i in take) { arr.push(take[i]); } console.log(arr); var j = 0; for (var myKey in take) { let query = `SELECT * from mandi where name='${myKey}';`; db.query(query, (err, result) => { if (err) throw err; else { //console.log(take[myKey]); console.log(arr[j]); let q = `insert into info (name, quantity, price, quantity_b) values('${result[0].name}',${result[0].quantity},${result[0].price}, ${arr[j]});`; console.log(q); j++; db.query(q, (err, result) => { if (err) throw err; }); //} } }); } // for (let i = 0; i < take.length; i++) { // let query = `select * from mandi where name='${take[i]}'`; // db.query(query, (err, result) => { // if (err) throw err; // else { // console.log(result); // //let query2 = `insert into cart values ()` // } // }); // } }); router.get("/cart", async (req, res, next) => { var predict = 10; let query = `SELECT * from info ORDER BY id ASC;`; db.query(query, (err, result) => { if (err) throw err; else { res.render("cart.ejs", { title: "Mandi Cart", cart: result, predict: predict }); } }); }); module.exports = router;
const Header= ({appName}) => ( <nav className="navbar navbar-dark bg-dark navbar-expan-sm"> <a href="#" className="navbar-brand">{appName}</a> </nav> ); export default Header;
import styled from "styled-components"; import {FaGithub as Github, FaLinkedinIn as Linked, FaTwitter as Twitter, FaFacebookF as Facebook, FaHtml5 as FaHtml, FaCss3 as FaCss, FaCheck as FCheck, FaTrophy as FTrophy, FaBootstrap as Bootstrap} from 'react-icons/fa' import {SiJavascript, SiReact, SiNpm} from 'react-icons/si' export const SocialIcon = styled.div` display: inline-flex; align-items: center; justify-content: center; height: 3.5rem; width: 3.5rem; background-color: #495057; color: #fff; border-radius: 100%; font-size: 1.5rem; margin-right: 1.5rem; cursor: pointer; &:hover{ background-color: #bd5d38; } `; export const FaGithub = styled(Github)` width: 50%; height: 50%; `; export const FaLinkedIn = styled(Linked)` width: 50%; height: 50%; `; export const FaTwitter = styled(Twitter)` width: 50%; height: 50%; `; export const FaFacebook = styled(Facebook)` width: 50%; height: 50%; `; export const FaHtml5 = styled(FaHtml)` color: gray; width: 70px; height: 70px; margin-right: 15px; `; export const FaCss3 = styled(FaCss)` color: gray; width: 70px; height: 70px; margin-right: 15px; `; export const FaJavascript = styled(SiJavascript)` color: gray; width: 70px; height: 70px; margin-right: 15px; `; export const FaReact = styled(SiReact)` color: gray; width: 70px; height: 70px; margin-right: 15px; `; export const FaNpm = styled(SiNpm)` color: gray; width: 70px; height: 70px; margin-right: 15px; `; export const FaCheck = styled(FCheck)` width: 20px; height: 20px; margin-right: 15px; display: flex; align-items: center; justify-content: center; color: gray; margin-top: 9px; `; export const FaTrophy = styled(FTrophy)` width: 20px; height: 20px; margin-right: 15px; display: flex; align-items: center; justify-content: center; color: #f5d41b; margin-top: 9px; `; export const FaBootstrap = styled(Bootstrap)` color: gray; width: 70px; height: 70px; margin-right: 15px; `;
import React from "react"; import { Container, Image, Menu } from "semantic-ui-react"; import { NavLink } from "react-router-dom"; const HeaderSection = () => ( <div className="header"> <Menu> <Container> <Menu.Item as="a" header> <Image size="small" src="https://www.robinwieruch.de/img/page/logo.svg" /> </Menu.Item> <Menu.Menu position="right"> <Menu.Item as="a" name="login"> <NavLink to="/login-page" variant="h6" color="white"> Login </NavLink> </Menu.Item> <Menu.Item as="a" name="register"> <NavLink to="/signup-page" variant="h6" color="white"> Register </NavLink> </Menu.Item> </Menu.Menu> </Container> </Menu> </div> ); export default HeaderSection;
import React from 'react'; import Distance from './Distance'; import * as plugData from "./plug-location.json"; import ReactMapGL, { Marker, Popup } from 'react-map-gl'; class Map extends React.Component { state = { selectedPlug: null, viewport: { latitude: 60.198912, longitude: 24.942182, width: '100vw', height: '100vh', zoom: 10, } } setUserLocation = () => { navigator.geolocation.getCurrentPosition(position => { let setUserLocation = { lat: position.coords.latitude, long: position.coords.longitude }; this.setState({ setUserLocation: setUserLocation }); }); }; render() { return ( <div className="map"> <main> <ReactMapGL {...this.state.viewport} mapboxApiAccessToken={process.env.REACT_APP_MAPBOX_TOKEN} mapStyle="mapbox://styles/akeundo/ck0vicxkj0pd41clpjk9abqki" onViewportChange={viewport => { this.setState({ viewport }); }} > {plugData.features.map(plug => ( <Marker key={plug.ID} latitude={plug.AddressInfo.Latitude} longitude={plug.AddressInfo.Longitude} > <button class="marker" onClick={e => { e.preventDefault(); this.setState({ selectedPlug: plug }); }} > <img src="./electric-car.png" alt="plug" /> </button> </Marker> ))} {this.state.selectedPlug ? ( <Popup latitude={this.state.selectedPlug.AddressInfo.Latitude} longitude={this.state.selectedPlug.AddressInfo.Longitude} onClose={() => { this.setState({ selectedPlug: null }); }} > <div> <h2>{this.state.selectedPlug.AddressInfo.Title}</h2> <h2>{this.state.selectedPlug.AddressInfo.AddressLine1}</h2> <h2>{this.state.selectedPlug.AddressInfo.AddressLine2}</h2> <h2>{this.state.selectedPlug.AddressInfo.Postcode}</h2> <h2>{this.state.selectedPlug.AddressInfo.Town}</h2> </div> </Popup> ) : null} </ReactMapGL> <Distance/> </main> </div> ); } } export default Map;
import OtherCard from './OtherCard'; import styled from 'styled-components'; function DetailOtherRoom({ data }) { return ( <OtherRoom> <OtherRoomTitle>이 중개사무소의 다른 방</OtherRoomTitle> <OtherRoomCard> {data.map(other => { return <OtherCard key={other.home_id} other={other} />; })} </OtherRoomCard> </OtherRoom> ); } export default DetailOtherRoom; const OtherRoom = styled.div` width: 1180px; height: 630px; padding: 120px 0px 120px 0px; `; const OtherRoomTitle = styled.h1` font-size: 28px; font-weight: 400; text-align: center; margin-bottom: 30px; `; const OtherRoomCard = styled.div` display: flex; justify-content: flex-start; align-items: center; `;
const expect = require('chai').expect const analisador = require('../dist/index') describe('Analisador Léxico e Sintático', () => { describe('Smoke Testes', () => { it('Retorno deve possuir propriedade "msg"'), () => { const sentenca = "x" const result = analisador.verificaSentenca(sentenca) expect(result.msg).to.be.not(undefined); } it('Retorno deve possuir propriedade "status"'), () => { const sentenca = "x" const result = analisador.verificaSentenca(sentenca) expect(result.status).to.be.not(undefined); } }); it('Deve retornar sucesso quando sentença = "( x )"', () => { const sentenca = "( x )" const result = analisador.verificaSentenca(sentenca) expect(result.status).to.equal("ok"); }); it('Deve retornar erro quando sentença = "( x "', () => { const sentenca = "( x " const result = analisador.verificaSentenca(sentenca) expect(result.status).to.equal("erro"); }); it('Deve retornar erro quando sentença = "x1 "', () => { const sentenca = "x1 " const result = analisador.verificaSentenca(sentenca) expect(result.status).to.equal("erro"); }); it('Deve retornar erro quando sentença = ""', () => { const sentenca = "" const result = analisador.verificaSentenca(sentenca) expect(result.status).to.equal("erro"); }); it('Deve retornar erro quando sentença = "(x)"', () => { const sentenca = "(x)" const result = analisador.verificaSentenca(sentenca) expect(result.status).to.equal("erro"); }); it('Deve retornar erro quando sentença = "x + ( y - x - y )"', () => { const sentenca = "x + ( y - x - y )" const result = analisador.verificaSentenca(sentenca) expect(result.status).to.equal("erro"); }); it('Deve retornar sucesso quando sentença = "x + ( y - x - y )"', () => { const sentenca = "x + ( y - x - y )" const result = analisador.verificaSentenca(sentenca) expect(result.status).to.equal("ok"); }); it('Deve retornar sucesso quando sentença = " ( y - x - y ) + ( 2 - y ) "', () => { const sentenca = " ( y - x - y ) + ( 2 - y ) " const result = analisador.verificaSentenca(sentenca) expect(result.status).to.equal("ok"); }); it('Deve retornar sucesso quando sentença = "( y - x - y ) + x"', () => { const sentenca = "( y - x - y ) + x" const result = analisador.verificaSentenca(sentenca) expect(result.status).to.equal("ok"); }); it('Deve retornar sucesso quando sentença = "( y + ( 2 ) ) - ( 2 - 1 )"', () => { const sentenca = "( y + ( 2 ) ) - ( 2 - 1 )" const result = analisador.verificaSentenca(sentenca) expect(result.status).to.equal("ok"); }); it('Deve retornar sucesso quando sentença = "0"', () => { const sentenca = "0" const result = analisador.verificaSentenca(sentenca) expect(result.status).to.be.equal("ok"); }); }); describe('JSON Tree', () => { it('Deve retornar array quando chamar funcao getChildrenAsJSON(x)', () => { const sentenca = "x" const result = analisador.getChildrenAsJSON(sentenca) // expect(result).to.be.an('array') }); it('Deve retornar array preenchido corretamente quando chamar funcao getChildrenAsJSON("x")', () => { const sentenca = "x" const result = analisador.getChildrenAsJSON(sentenca) expect(result).to.be.have.deep.property('text') console.log(result); }); it('Deve retornar array preenchido corretamente quando chamar funcao getChildrenAsJSON("( x )")', () => { const sentenca = "x + 1" const result = analisador.getChildrenAsJSON(sentenca) expect(result.children.length).to.be.deep.equal(3) console.log(result); }); });
module.exports = { root: true, env: { browser: true, es2021: true, }, plugins: ["solid"], extends: ["eslint:recommended", "plugin:solid/recommended"], overrides: [], parserOptions: { ecmaVersion: "latest", sourceType: "module", }, rules: {}, globals: { suite: true, test: true, describe: true, it: true, expect: true, assert: true, vitest: true, vi: true, beforeAll: true, afterAll: true, beforeEach: true, afterEach: true, }, };
module.exports = (sequelize, DataTypes) => { const Newchapter = sequelize.define('Newchapter', { position: DataTypes.INTEGER, dropboxId: DataTypes.STRING, enTitle: DataTypes.STRING, frTitle: DataTypes.STRING, imgLink: DataTypes.STRING, enText: DataTypes.TEXT, frText: DataTypes.TEXT, }) return Newchapter }
// White a function called search that accepts a value and returns // the index where the calue passed to the function is located. // If the value is not found, return -1 function search(arr, num) { } console.log(search([1,2,3,4,5,6], 4))
import superagent from 'superagent'; const API_ROOT = 'https://api.github.com'; const responseBody = res => res.body; const requests = { get: (url, body) => superagent.get(`${API_ROOT}${url}`).query(body).then(responseBody) }; export const ApiCalls = { getRepos: (username, queryOpt) => requests.get(`/users/${username}/repos`, queryOpt), getOrgs: (username, queryOpt) => requests.get(`/users/${username}/orgs`, queryOpt) };
//опции игры canvasWidth = 980;//высота канваса canvasHeight = 630;//ширина канваса gameSpeed = 16;//общая скорость игры //кратинки для интерфейса imageHole = new Image(); imageHole.src = 'img/holes-sprite-82x82.png'; imageSnake = new Image(); imageSnake.src = 'img/snake-sprite-animation.png'; imageSnowball = new Image(); imageSnowball.src = 'img/snow-ball-sprite-192x204.png'; imageBonus = new Image(); imageBonus.src = 'img/bonus-animation-sprite-129x32.png'; imageLifeTime = new Image(); imageLifeTime.src = 'img/hud-sprite-39x39.png'; //опции уровня drawLevelSpeed = 20;//время шага уровня drawLevelFontSize = 24;//размер шрифта текста // поддерживаются ли трогательные события var isTouch = ('ontouchstart' in window), actionEvent = isTouch ? "touchstart" : "mousedown"; $(document).ready(function(){ drawCanvas = document.getElementById('drawCanvas'); drawCanvas.width = canvasWidth; drawCanvas.height = canvasHeight; if(drawCanvas && drawCanvas.getContext) { ctx = drawCanvas.getContext('2d'); } if (isTouch) { var canvasOffsetX, canvasOffsetY; function findPos (obj) { canvasOffsetX = canvasOffsetY = 0; if (obj.offsetParent) { do { canvasOffsetX += obj.offsetLeft; canvasOffsetY += obj.offsetTop; } while (obj = obj.offsetParent); } }; findPos(drawCanvas); $(window).resize(function () { findPos(drawCanvas); }); }; cGame = new coreGame({ speedDraw: gameSpeed, speedShow: gameSpeed }); cGame.start(); clearCanvas(); game = new drawGame(); document.body.ontouchmove = function(e) { if (e && e.preventDefault) { e.preventDefault(); } if (e && e.stopPropagation) { e.stopPropagation(); } return false; } drawCanvas.addEventListener(actionEvent, function (e) { var isMouse = e.type == "mousedown", X = (isMouse) ? (e.offsetX == undefined ? e.layerX : e.offsetX) : e.touches[0].clientX - canvasOffsetX, Y = (isMouse) ? (e.offsetY == undefined ? e.layerY : e.offsetY) : e.touches[0].clientY - canvasOffsetY; game.mouseClick(X, Y); }); });
import React, { useState, useEffect } from 'react' import InfiniteScroll from 'react-infinite-scroll-component'; import { useAppContext } from "../libs/contextLib"; import { getTokens } from "../functions/UIStateFunctions.js"; import CardGrid from "../components/CardGrid"; import Loader from "../components/Loader"; export default ({ data }) => { const [hasMore, setHasMore] = useState(true); const [start, setStart] = useState(51); const [end, setEnd] = useState(60); const [cardData, setCardData] = useState(null); const { globalState, setGlobalState } = useAppContext(); useEffect(() => { (async () => { const data = await getTokens(1, 50); setCardData(data); })(); }, []); const fetchData = async () => { const newData = await getTokens(start, end); if (!newData[newData.length-1] || newData[newData.length-1].minter.address === "0x0000000000000000000000000000000000000000") { setHasMore(false); return; } setCardData(cardData.concat(newData)); setStart(start+20); setEnd(end+20); } return ( <div className="container"> { cardData ? <InfiniteScroll dataLength={cardData.length} //This is important field to render the next data next={fetchData} hasMore={hasMore} loader={<p className="containerText">Loading...</p>} endMessage={ <p className="containerText"> You have seen it all! </p> } > <CardGrid data={cardData} cardSize="small" globalState={globalState} /> </InfiniteScroll> : <Loader loading={true} /> } </div> ) }
// menu active const menuNodeLink = document.querySelectorAll(".header__nav-menu-link"); for (let index = 0; index < menuNodeLink.length; index++) { menuNodeLink[index].addEventListener("click", function (e) { menuNodeLink.forEach((element) => { element.classList.remove("active"); }); this.classList.add("active"); }); } // active cart block const cart = document.querySelector(".header__nav-left--cart"); const cartBlock = document.querySelector(".cart__block"); cart.addEventListener("click", function () { cartBlock.classList.toggle("active"); }); // slide const productSlideList = document.querySelectorAll( ".product__main-left--slider-slide" ); // thumbnails const thumbnailsNodeImg = document.querySelectorAll( ".product__main-left-thumbnails--img" ); for (let index = 0; index < thumbnailsNodeImg.length; index++) { thumbnailsNodeImg[index].addEventListener("click", function (e) { e.preventDefault(); thumbnailsNodeImg.forEach((item) => item.classList.remove("active")); thumbnailsNodeImg[index].classList.add("active"); productSlideList.forEach((element) => element.classList.remove("active")); productSlideList[index].classList.add("active"); }); } // cart function const btnIncrease = document.querySelector(".btn-increase"); const btnDecrease = document.querySelector(".btn-decrease"); const quantityVal = document.querySelector(".quantity-val"); const cartMenu = document.querySelector(".cart__menu"); const cartIndicator = document.querySelector("#cart-indicator"); const cartEmpty = document.querySelector(".empty-cart"); const cartFooter = document.querySelector(".cart__block-footer"); const btnAddCart = document.querySelector("#add-cart"); const itemCount = document.querySelector("#item-count"); const itemPrice = document.querySelector("#item-price"); const total = document.querySelector("#total"); const btnDelete = document.querySelector("#btn-delete"); const btnCheckOut = document.querySelector("#btn-checkout"); var valOfQuantity = 0; // set quantity of product btnIncrease.addEventListener("click", function () { valOfQuantity += 1; quantityVal.value = valOfQuantity; }); btnDecrease.addEventListener("click", function () { if (valOfQuantity == 0) { valOfQuantity = 0; } else { valOfQuantity -= 1; quantityVal.value = valOfQuantity; } }); // check status cart function checkCart() { if (cartIndicator.innerHTML == 0) { cartEmpty.style.display = "block"; cartMenu.style.display = "none"; cartFooter.style.display = "none"; } else { cartEmpty.style.display = "none"; cartMenu.style.display = "block"; cartFooter.style.display = "block"; } } checkCart(); // get info product to cart let currentTotal = parseInt(cartIndicator.innerHTML); btnAddCart.addEventListener("click", function () { if (quantityVal.value == 0) { alert("Please set your quantity product"); } else { currentTotal += parseInt(quantityVal.value); itemCount.innerHTML = `x ${currentTotal}`; total.innerHTML = `$ ${( currentTotal * parseInt(itemPrice.innerHTML) ).toFixed(2)}`; cartIndicator.innerHTML = currentTotal; checkCart(); } }); // delete product btnDelete.addEventListener("click", function (e) { cartIndicator.innerHTML = 0; currentTotal = 0; checkCart(); }); // check out function btnCheckOut.addEventListener("click", function () { alert( (total.innerHTML = `Total: $ ${( currentTotal * parseInt(itemPrice.innerHTML) ).toFixed(2)}`) ); }); // btn-close menu mobile const btnCloseMobile = document.querySelector("#btn-close-mobile"); const menuMobile = document.querySelector(".mobile-menu"); const openMenu = document.querySelector("#open-menu"); console.log(openMenu); console.log(menuMobile); console.log(btnCloseMobile); openMenu.addEventListener("click", (e) => { menuMobile.classList.toggle("active"); }); btnCloseMobile.addEventListener("click", (e) => { menuMobile.classList.remove("active"); }); // When the user clicks anywhere outside of the modal, close it window.onclick = function (event) { if (event.target == menuMobile) { menuMobile.classList.remove("active"); } };
module.exports = { root: true, env: { "es6": true, "node": true, "browser": true }, plugins: [ 'vue' ], extends: [ "plugin:vue/essential", "eslint:recommended" ], rules: { "no-unused-vars": [0], "no-console": [1], "no-underscore-dangle": [0], "no-param-reassign": [0], "camelcase": [1], "radix": [0], "linebreak-style": [0, "error", "windows"], "max-len": [0], "import/no-unresolved": [0], "import/extensions": [0], "import/no-cycle":[0], }, parserOptions: { "parser": 'babel-eslint', "sourceType": "module" }, };
var scoreSection = document.getElementById("score"); var scoreCiviliansSection = document.getElementById("scoreCivilians"); var gameBoard = document.getElementById("game"); var score = 0; var arrayWithSlots = []; var positionPerson; var personWidth; var civilianProbability = 0.4; var gameInterval; var civiliansKilled = 0; var dif_level = 0; // 0 - novice, 1 - brutal var ammoHTML = document.getElementsByClassName("ammo"); var ammo = Array.prototype.slice.call(ammoHTML); var ammunition = 5; var lifeHTML = document.getElementsByClassName("heart"); var life = Array.prototype.slice.call(lifeHTML); var lifeLeft = 5; var mainNormalInterval = 3000; var mainHardInterval = 1500; var mainChosenInterval; var gunshot = document.getElementById('gunshot'); var noAmmo = document.getElementById('noAmmo'); var scream = document.getElementById('scream'); var screamCyvilian = document.getElementById('screamCyvilian'); var shotKiller = document.getElementById('shotKiller'); var reloadSound = document.getElementById('reload'); var youWereKilled = ''; var classes = ["gangster1", "gangster2", "gangster3", "gangster4"]; var mediaQuery = window.matchMedia("(max-width: 609px)"); if (mediaQuery.matches) { personWidth = 40; } else { personWidth = 80; } //Creating array of available pixel slots. The function accepts person's width as an argument. var boardGameWidth = gameBoard.offsetWidth; function playAudio (sound) { sound.currentTime = 0; sound.play(); } function reload() { ammunition = 5; ammo.forEach(function (bullet) { if (bullet.classList.contains("transparent")) { bullet.classList.remove("transparent"); bullet.classList.add("opaque") } }) } function removeBullet() { ammo[ammunition - 1].classList.remove("opaque"); ammo[ammunition - 1].classList.add("transparent"); if (ammunition > 0) { ammunition = ammunition - 1; } } window.addEventListener('keydown', function (event) { if (event.code === 'KeyR') { playAudio(reloadSound); reload(); } }); ammo.forEach(function (singleAmmo) { singleAmmo.addEventListener('click', function (event) { playAudio(reloadSound); reload(); }); }); function findSlots(personWidth) { return boardGameWidth / personWidth; } function recreateArrayWithSlots(personWidth) { arrayWithSlots = Array.from({length: findSlots(personWidth)}, function (element, index) { return index * personWidth }); } function generatePerson(personClass) { if (arrayWithSlots.length === 0) { return; } var personNode = document.createElement("div"); personNode.classList.add("person"); personNode.classList.add(personClass); positionPerson = arrayWithSlots[Math.floor(Math.random() * arrayWithSlots.length)]; personNode.style.left = positionPerson + "px"; gameBoard.appendChild(personNode); arrayWithSlots.splice(arrayWithSlots.indexOf(positionPerson), 1); } function killerGangsters() { var gangstersHTML = document.getElementsByClassName('person'); var gangsters = Array.prototype.slice.call(gangstersHTML); gangsters.forEach(function(gangster){ if (lifeLeft > 0){ if ((gangster.classList.contains('gangster3')) && (!gangster.classList.contains('dead'))) { life[lifeLeft - 1].classList.remove("opaque"); life[lifeLeft - 1].classList.add("transparent"); lifeLeft = lifeLeft - 1; } } }); } function animateKillers(){ var gangstersHTML = document.getElementsByClassName('person'); var gangsters = Array.prototype.slice.call(gangstersHTML); gangsters.forEach(function(gangster) { if (gangster.classList.contains('gangster3')) { var killerIterator = 1; if (!gangster.classList.contains('dead')){ playAudio(shotKiller); } var killerAnimator = setInterval(function () { gangster.style.backgroundImage = 'url("./game_images/cut3/GunThree' + (killerIterator++) + '.png")'; if (killerIterator === 5) { killerIterator = 1; clearInterval(killerAnimator); } },100) } }) } function shoot(event) { var clickedElement = event.target; if (ammunition < 1) { playAudio(noAmmo); return } removeBullet(); playAudio(gunshot); if (clickedElement.classList.contains('dead')) { return; } if (clickedElement.classList.contains("person")) { clickedElement.classList.add('dead'); if (clickedElement.classList.contains("civilian")) { playAudio(screamCyvilian); } else { playAudio(scream); } if (classes.some(function (className) { return clickedElement.classList.contains(className) })) { score += 1; } else if (clickedElement.classList.contains("civilian")) { civiliansKilled += 1; scoreCiviliansSection.innerText = "Civilians killed: " + civiliansKilled; if (civiliansKilled === 3) { youWereKilled = "Shame on you. You killed too many civilians."; finishGame(); return; } } var animateIterator = 1; var animInterval = setInterval(function () { if (clickedElement.classList.contains("gangster1")) { clickedElement.style.backgroundImage = 'url("./game_images/cut1/GunOne' + (animateIterator++) + '.png")'; } if (clickedElement.classList.contains("gangster2")) { clickedElement.style.backgroundImage = 'url("./game_images/cut2/GunTwo' + (animateIterator++) + '.png")'; } if (clickedElement.classList.contains("gangster3")) { clickedElement.style.backgroundImage = 'url("./game_images/cut3/GunThree' + (animateIterator++) + '.png")'; } if (clickedElement.classList.contains("gangster4")) { clickedElement.style.backgroundImage = 'url("./game_images/cut4/GunFour' + (animateIterator++) + '.png")'; } else if (clickedElement.classList.contains("civilian")) { clickedElement.style.backgroundImage = 'url("./game_images/civ/cyvil-' + (animateIterator++) + '.png")'; } if (animateIterator === 10) { animateIterator = 1; clearInterval(animInterval); if (gameBoard.contains(clickedElement)) { gameBoard.removeChild(clickedElement); } arrayWithSlots.push(parseInt(clickedElement.style.left)); } }, 100); } scoreSection.innerText = "Score: " + score; scoreCiviliansSection.innerText = "Civilians killed: " + civiliansKilled; } function clearBoard() { while (gameBoard.firstChild) { gameBoard.removeChild(gameBoard.firstChild); } } function createRandomPerson() { if (Math.random() > civilianProbability) { generatePerson(classes[Math.floor((Math.random() * 4))]); } else { generatePerson('civilian') } } function update() { killerGangsters(); if (lifeLeft === 0){ youWereKilled = "Too bad. You got yourself killed."; finishGame(); return; } clearBoard(); recreateArrayWithSlots(personWidth); for (var i = 0; i < 7; i++) { createRandomPerson(); } setTimeout(animateKillers, mainChosenInterval-700); } function welcomeScreen() { gameBoard.innerHTML = '' + '<div>' + '<h2>Try the GangBook game</h2>' + '<p>Kill as many gangsters as possible. Shoot men in black before they shoot you.<br/>Spare the civilians! Don\'t kill more than two.</p>' + '<section>' + '<label class="container">Novice <input type="radio" name="dif-level" value="0" checked /><span class="checkmark"></span></label>' + '<label class="container">Brutal <input type="radio" name="dif-level" value="1" /><span class="checkmark"></span></label>' + '</section>' + '<button class="button-game" onclick="runGame()">START</button>' + '<p>To reload, press \'R\' or click a bullet.</p>' + '<p class="welcomeScreenPar">This guy is a civilian<img class="welcomeScreenImg" src="./game_images/civ/cyvil-1.png"/></p>' + '</div>'; } function gameOverScreen() { gameBoard.innerHTML = '' + '<div>' + '<h2>GAME OVER</h2>' + '<p> ' + youWereKilled + ' </p>' + // '<p>Gangsters killed: ' + score + '.</p>' + // '<p>Civilians killed: ' + civiliansKilled + '.</p>' + '<section>' + '<label class="container">Novice <input type="radio" name="dif-level" value="0" checked /><span class="checkmark"></label>' + '<label class="container">Brutal <input type="radio" name="dif-level" value="1" /><span class="checkmark"></label>' + '</section>' + '<button class="button-game" onclick="runGame()">RESTART GAME</button>' + '</div>'; } function runGame() { lifeLeft = 5; dif_level = document.querySelector('[name="dif-level"]:checked').value; mainChosenInterval = dif_level === '1' ? mainHardInterval : mainNormalInterval; gameBoard.addEventListener("mousedown", shoot); resetScores(); update(); reload(); life.forEach(function(element) { element.classList.remove("transparent"); element.classList.add("opaque"); }); gameInterval = setInterval(update, mainChosenInterval); } function finishGame() { gameBoard.removeEventListener("mousedown", shoot); life.forEach(function(element) { element.classList.remove("opaque"); element.classList.add("transparent"); }); ammo.forEach(function (bullet) { bullet.classList.remove("opaque"); bullet.classList.add("transparent") }); clearBoard(); window.clearInterval(gameInterval); gameOverScreen(); } function resetScores() { score = 0; civiliansKilled = 0; } welcomeScreen();
// {/*Setting up Main Component to render React Routes for every Page/Link*/} import React, { Component } from 'react'; import { Switch, Route } from 'react-router-dom'; import Home from '../../Pages/Home/Home'; import QuizList from '../../Pages/QuizList/QuizList'; import StudyCards from '../StudyCards/StudyCards.js'; //importing quiz components import QuizOne from '../QuizTabs/quizOne'; import QuizTwo from '../QuizTabs/quizTwo'; import QuizThree from '../QuizTabs/quizThree'; import QuizFour from '../QuizTabs/quizFour'; import QuizFive from '../QuizTabs/quizFive'; import QuizSix from '../QuizTabs/quizSix'; import QuizSeven from '../QuizTabs/quizSeven'; import QuizEight from '../QuizTabs/quizEight'; import QuizNine from '../QuizTabs/quizNine'; import QuizTen from '../QuizTabs/quizTen'; import QuizEleven from '../QuizTabs/quizEleven'; import QuizTwelve from '../QuizTabs/quizTwelve'; import QuizThirteen from '../QuizTabs/quizThirteen'; import QuizFourteen from '../QuizTabs/quizFourteen'; import QuizFifteen from '../QuizTabs/quizFifteen'; import QuizSixteen from '../QuizTabs/quizSixteen'; import QuizSeventeen from '../QuizTabs/quizSeventeen'; import QuizEighteen from '../QuizTabs/quizEighteen'; import QuizNineteen from '../QuizTabs/quizNineteen'; import QuizTwenty from '../QuizTabs/quizTwenty'; import QuizTwentyOne from '../QuizTabs/quizTwentyOne'; import QuizTwentyTwo from '../QuizTabs/quizTwentyTwo'; import QuizTwentyThree from '../QuizTabs/quizTwentyThree'; import QuizTwentyFour from '../QuizTabs/quizTwentyFour'; import QuizTwentyFive from '../QuizTabs/quizTwentyFive'; import QuizTwentySix from '../QuizTabs/quizTwentySix'; import QuizTwentySeven from '../QuizTabs/quizTwentySeven'; import QuizTwentyEight from '../QuizTabs/quizTwentyEight'; import QuizTwentyNine from '../QuizTabs/quizTwentyNine'; import QuizThirty from '../QuizTabs/quizThirty'; import QuizThirtyOne from '../QuizTabs/quizThirtyOne'; import QuizThirtyTwo from '../QuizTabs/quizThirtyTwo'; import QuizThirtyThree from '../QuizTabs/quizThirtyThree'; import QuizThirtyFour from '../QuizTabs/quizThirtyFour'; import QuizThirtyFive from '../QuizTabs/quizThirtyFive'; import QuizThirtySix from '../QuizTabs/quizThirtySix'; import QuizThirtySeven from '../QuizTabs/quizThirtySeven'; import QuizThirtyEight from '../QuizTabs/quizThirtyEight'; import QuizThirtyNine from '../QuizTabs/quizThirtyNine'; import QuizForty from '../QuizTabs/quizForty'; import QuizFortyOne from '../QuizTabs/quizFortyOne'; import QuizFortyTwo from '../QuizTabs/quizFortyTwo'; import QuizFortyThree from '../QuizTabs/quizFortyThree'; import QuizFortyFour from '../QuizTabs/quizFortyFour'; import QuizFortyFive from '../QuizTabs/quizFortyFive'; import QuizFortySix from '../QuizTabs/quizFortySix'; import QuizFortySeven from '../QuizTabs/quizFortySeven'; import QuizFortyEight from '../QuizTabs/quizFortyEight'; import QuizFortyNine from '../QuizTabs/quizFortyNine'; import QuizFifty from '../QuizTabs/quizFifty'; import QuizFiftyOne from '../QuizTabs/quizFiftyOne'; import QuizFiftyTwo from '../QuizTabs/quizFiftyTwo'; //importing section components import Section1 from '../SectionCards/Section1' export default class Main extends Component { render() { return ( <Switch> <Route exact path='/' component={Home}></Route> <Route exact path='/quiz-list' component={QuizList}></Route> <Route exact path='/sections-list' component={StudyCards}></Route> {/* Quiz List Components */} <Route exact path='/quiz-1' component={QuizOne}></Route> <Route exact path='/quiz-2' component={QuizTwo}></Route> <Route exact path='/quiz-3' component={QuizThree}></Route> <Route exact path='/quiz-4' component={QuizFour}></Route> <Route exact path='/quiz-5' component={QuizFive}></Route> <Route exact path='/quiz-6' component={QuizSix}></Route> <Route exact path='/quiz-7' component={QuizSeven}></Route> <Route exact path='/quiz-8' component={QuizEight}></Route> <Route exact path='/quiz-9' component={QuizNine}></Route> <Route exact path='/quiz-10' component={QuizTen}></Route> <Route exact path='/quiz-11' component={QuizEleven}></Route> <Route exact path='/quiz-12' component={QuizTwelve}></Route> <Route exact path='/quiz-13' component={QuizThirteen}></Route> <Route exact path='/quiz-14' component={QuizFourteen}></Route> <Route exact path='/quiz-15' component={QuizFifteen}></Route> <Route exact path='/quiz-16' component={QuizSixteen}></Route> <Route exact path='/quiz-17' component={QuizSeventeen}></Route> <Route exact path='/quiz-18' component={QuizEighteen}></Route> <Route exact path='/quiz-19' component={QuizNineteen}></Route> <Route exact path='/quiz-20' component={QuizTwenty}></Route> <Route exact path='/quiz-21' component={QuizTwentyOne}></Route> <Route exact path='/quiz-22' component={QuizTwentyTwo}></Route> <Route exact path='/quiz-23' component={QuizTwentyThree}></Route> <Route exact path='/quiz-24' component={QuizTwentyFour}></Route> <Route exact path='/quiz-25' component={QuizTwentyFive}></Route> <Route exact path='/quiz-26' component={QuizTwentySix}></Route> <Route exact path='/quiz-27' component={QuizTwentySeven}></Route> <Route exact path='/quiz-28' component={QuizTwentyEight}></Route> <Route exact path='/quiz-29' component={QuizTwentyNine}></Route> <Route exact path='/quiz-30' component={QuizThirty}></Route> <Route exact path='/quiz-31' component={QuizThirtyOne}></Route> <Route exact path='/quiz-32' component={QuizThirtyTwo}></Route> <Route exact path='/quiz-33' component={QuizThirtyThree}></Route> <Route exact path='/quiz-34' component={QuizThirtyFour}></Route> <Route exact path='/quiz-35' component={QuizThirtyFive}></Route> <Route exact path='/quiz-36' component={QuizThirtySix}></Route> <Route exact path='/quiz-37' component={QuizThirtySeven}></Route> <Route exact path='/quiz-38' component={QuizThirtyEight}></Route> <Route exact path='/quiz-39' component={QuizThirtyNine}></Route> <Route exact path='/quiz-40' component={QuizForty}></Route> <Route exact path='/quiz-41' component={QuizFortyOne}></Route> <Route exact path='/quiz-42' component={QuizFortyTwo}></Route> <Route exact path='/quiz-43' component={QuizFortyThree}></Route> <Route exact path='/quiz-44' component={QuizFortyFour}></Route> <Route exact path='/quiz-45' component={QuizFortyFive}></Route> <Route exact path='/quiz-46' component={QuizFortySix}></Route> <Route exact path='/quiz-47' component={QuizFortySeven}></Route> <Route exact path='/quiz-48' component={QuizFortyEight}></Route> <Route exact path='/quiz-49' component={QuizFortyNine}></Route> <Route exact path='/quiz-50' component={QuizFifty}></Route> <Route exact path='/quiz-51' component={QuizFiftyOne}></Route> <Route exact path='/quiz-52' component={QuizFiftyTwo}></Route> {/* Section Components */} <Route exact path='/section-1' component={Section1}></Route> </Switch> ) } }
const Command = require('../../structures/Command'); const GenericPrompt = require('../../structures/GenericPrompt'); const SubMenu = require('../../structures/SubMenu'); const Util = require('../../util'); module.exports = class EditBoard extends Command { get name() { return 'editboard'; } get _options() { return { aliases: ['eboard', 'eb'], cooldown: 10, permissions: ['auth', 'selectedBoard'] }; } async exec(message, { args, _, trello, userData }) { const handle = await trello.handleResponse({ response: await trello.getBoard(userData.currentBoard), client: this.client, message, _ }); if (handle.stop) return; if (await Util.Trello.ensureBoard(handle, message, _)) return; const json = handle.body; const membership = json.memberships.find(ms => ms.idMember === userData.trelloID); const menu = new SubMenu(this.client, message, { header: `**${_('words.board.one')}:** ${ Util.cutoffText(Util.Escape.markdown(json.name), 50)} (\`${json.shortLink}\`)\n` + `**${_('words.member_type.one')}:** ${_(`trello.member_type.${membership.memberType}`)}\n\n` + _('boards.wywtd'), itemTitle: 'words.subcmd.many', _ }); const menuOpts = [ { // Description names: ['desc', 'description'], title: _('boards.menu.desc'), async exec(client) { const input = args[1] || await client.messageAwaiter.getInput(message, _, { header: _('boards.input_desc') }); if (!input) return; if ((await trello.handleResponse({ response: await trello.updateBoard(json.id, { desc: input }), client, message, _ })).stop) return; return message.channel.createMessage(_('boards.set_desc', { name: Util.cutoffText(Util.Escape.markdown(json.name), 50) })); } } ]; const _this = this; if (json.desc) menuOpts.push({ // Remove Description names: ['removedesc', 'removedescription', 'rdesc'], title: _('boards.menu.remove_desc'), async exec(client) { if ((await trello.handleResponse({ response: await trello.updateBoard(json.id, { desc: '' }), client, message, _ })).stop) return; return message.channel.createMessage(_('boards.removed_desc', { name: Util.cutoffText(Util.Escape.markdown(json.name), 50) })); } }); if (membership.memberType === 'admin') { menuOpts.unshift({ // Archive/Unarchive names: ['archive', 'unarchive', 'open', 'close'], title: _(json.closed ? 'boards.menu.archive_off' : 'boards.menu.archive_on'), async exec(client) { const handle = await trello.handleResponse({ response: await trello.updateBoard(json.id, { closed: !json.closed }), client, message, _ }); if (handle.body === 'unauthorized permission requested') return message.channel.createMessage(_('boards.need_admin')); return message.channel.createMessage( _(json.closed ? 'boards.unarchived' : 'boards.archived', { name: Util.cutoffText(Util.Escape.markdown(json.name), 50) })); } }); menuOpts.unshift({ // Name names: ['name', 'rename'], title: _('boards.menu.name'), async exec(client) { const input = args[1] || await client.messageAwaiter.getInput(message, _, { header: _('boards.input_name') }); if (!input) return; const handle = await trello.handleResponse({ response: await trello.updateBoard(json.id, { name: input }), client, message, _ }); if (handle.body === 'unauthorized permission requested') return message.channel.createMessage(_('boards.need_admin')); return message.channel.createMessage(_('boards.set_name', { old: Util.cutoffText(Util.Escape.markdown(json.name), 50), new: Util.cutoffText(Util.Escape.markdown(input), 50) })); } }); menuOpts.push({ // Comment Perms names: ['comment', 'commentperms', 'com', 'comperms'], title: _('boards.menu.comment', { value: _(`trello.comment_perms.${json.prefs.comments}`) }), exec() { return _this.changePerms('comment_perms', { args, _, trello, client: _this.client, message, board: json }); } }); menuOpts.push({ // Vote Perms names: ['vote', 'voteperms'], title: _('boards.menu.vote', { value: _(`trello.vote_perms.${json.prefs.voting}`) }), exec() { return _this.changePerms('vote_perms', { args, _, trello, client: _this.client, message, board: json }); } }); menuOpts.push({ // Invite Perms names: ['inviteperms'], title: _('boards.menu.invite', { value: _(`trello.invite_perms.${json.prefs.invitations}`) }), exec() { return _this.changePerms('invite_perms', { args, _, trello, client: _this.client, message, board: json }); } }); } return menu.start(message.channel.id, message.author.id, args[0], menuOpts); } async changePerms(type, { args, _, trello, message, client, board }) { const permOpts = { comment_perms: [ 'disabled', 'members', (board.organization ? 'org' : null), 'public' ].filter(v => !!v), vote_perms: [ 'members', (board.organization ? 'org' : null), 'public' ].filter(v => !!v), invite_perms: [ 'admins', 'members' ] }; const fields = { comment_perms: 'prefs/comments', vote_perms: 'prefs/voting', invite_perms: 'prefs/invitations' }; let result = args[1]; if (!permOpts[type].includes(result)) { const prompter = new GenericPrompt(client, message, { items: permOpts[type], itemTitle: 'words.opt.many', display: perm => _(`trello.${type}.${perm}`), _ }); result = await prompter.search(args[1], { channelID: message.channel.id, userID: message.author.id }); if (!result) return; } const handle = await trello.handleResponse({ response: await trello.updateBoard(board.id, { [fields[type]]: result }), client, message, _ }); if (handle.body === 'unauthorized permission requested') return message.channel.createMessage(_('boards.need_admin')); return message.channel.createMessage(_(`boards.set_${type}`, { value: _(`trello.${type}.${result}`) })); } get metadata() { return { category: 'categories.edit', }; } };
import React, { useState } from 'react'; import PropTypes from 'prop-types'; TodoForm.propTypes = { onSubmit: PropTypes.func, onCloseForm: PropTypes.func, }; TodoForm.defaultProps = { onSubmit: null, onCloseForm: null, } function TodoForm(props) { const {onSubmit, onCloseForm} = props; const [input, setInput] = useState({title: '', done: false}); function handleValueChange(e){ const value = e.target.value const name = e.target.name setInput({...input, [name]: value}) } function handleSubmit(e){ e.preventDefault(); if(!onSubmit) return; const formValues = { title: input.title, done: input.done, } console.log(formValues) onSubmit(formValues) setInput({title: '', done: false}) } function handleCloseForm(){ onCloseForm() } return ( <div className="col-xs-4 col-sm-4 col-md-4 col-lg-4"> <div className="card"> <div className="card-header bg-warning"> <div className="row"> <div className="col-10"> <h3 className="panel-title text-white text-left"> Thêm Công Việc </h3> </div> <div className="col-2"> <h3><span className="far fa-times-circle text-white" onClick={handleCloseForm}></span></h3> </div> </div> </div> <div className="card-body"> <form onSubmit={handleSubmit}> <div className="form-group"> <label>Tên :</label> <input type="text" className="form-control" value={input.title} onChange={handleValueChange} name="title"/> <label>Trạng Thái :</label> <select className="form-control" required="required" onChange={handleValueChange} name="done"> <option value="0">Ẩn</option> <option value="1">Kích Hoạt</option> </select> </div> <div className="text-center"> <button type="submit" className="btn btn-warning">Thêm</button>&nbsp; </div> </form> </div> </div> </div> ); } export default TodoForm;
/** * KEditor Line Component * @copyright: Kademi (http://kademi.co) * @author: Kademi (http://kademi.co) * @version: @{version} * @dependencies: $, $.fn.draggable, $.fn.droppable, $.fn.sortable, Bootstrap, FontAwesome (optional) */ (function ($) { var KEditor = $.keditor; var flog = KEditor.log; KEditor.components['line'] = { settingEnabled: true, settingTitle: 'Line Settings', initSettingForm: function (form, keditor) { flog('initSettingForm "line" component'); form.append( '<form class="form-horizontal">' + ' <div class="form-group">' + ' <div class="col-md-12">' + ' <label>Color</label>' + ' <div class="input-group line-color-picker">' + ' <span class="input-group-addon"><i></i></span>' + ' <input type="text" value="" id="line-color" class="form-control" />' + ' </div>' + ' </div>' + ' </div>' + ' <div class="form-group">' + ' <label for="line-height" class="col-sm-12">Height</label>' + ' <div class="col-sm-12">' + ' <input type="number" id="line-height" class="form-control" />' + ' </div>' + ' </div>' + '</form>' ); var lineHeight = form.find('#line-height'); lineHeight.on('change', function () { setStyle(keditor.getSettingComponent().find('.wrapper div'), 'height', this.value); }); form = form.find('form'); KEditor.initPaddingControls(keditor, form, 'prepend'); KEditor.initBgColorControl(keditor, form, 'prepend'); var lineColorPicker = form.find('.line-color-picker'); initColorPicker(lineColorPicker, function (color) { var wrapper = keditor.getSettingComponent().find('.wrapper'); var div = wrapper.children('div'); if (color && color !== 'transparent') { setStyle(div, 'background-color', color); } else { setStyle(div, 'background-color', ''); form.find('#line-color').val(''); } }); }, showSettingForm: function (form, component, keditor) { flog('showSettingForm "line" component', component); var lineHeight = form.find('#line-height'); var height = component.find('.wrapper > div').css('height'); lineHeight.val(height ? height.replace('px', '') : '0'); KEditor.showBgColorControl(keditor, form, component); KEditor.showPaddingControls(keditor, form, component); var wrapper = component.find('.wrapper'); var div = wrapper.children('div'); var lineColorPicker = form.find('.line-color-picker'); flog(div.css('background-color')); lineColorPicker.colorpicker('setValue', div.css('background-color') || ''); } }; })(jQuery);
/** * Created by R9K0H46 on 2015/10/9. */ /** * * */ var appModule=angular.module('app',['ui.router']); appModule.config(function($stateProvider,$urlRouterProvider){ $urlRouterProvider.when("","PageTab"); $stateProvider.state('PageTabe',{ url:'/PageTab', templateUrl:'PageTab.html' }).state('PageTabe.Page1',{ url:'/Page1', templateUrl:'Page1.html' }).state('PageTabe.Page2',{ url:'/Page2', templateUrl:'Page2.html' }).state('PageTabe.Page3',{ url:'/Page3', templateUrl:'Page3.html' }); });
import React from 'react'; import FirstDropdown from '../Dropdown'; import SecondDropdown from '../Dropdown'; import { useStateValue } from '../../StateContextProvider'; import '../../Styles/Header.css'; const Header = () => { const [{ cryptoList, firstSelected, secondSelected }, dispatch] = useStateValue(); const setFirstSelected = (val) => { dispatch({ type: 'updateFirstCryptoSelected', payload: { firstSelected: val } }); } const setSecondSelected = (val) => { dispatch({ type: 'updateSecondCryptoSelected', payload: { secondSelected: val } }); } return ( <div className="card header-container"> <div className="card-body"> <h1 className="header-title">Crypto Exchange</h1> <FirstDropdown selected={firstSelected} options={cryptoList} setSelected={setFirstSelected}/> <SecondDropdown selected={secondSelected} options={cryptoList} setSelected={setSecondSelected}/> </div> </div> ) } export default Header;
var Accommodation = function(name, pricePerPerson, rooms, stars, latlng, address) { this.name = name; this.pricePerPerson = pricePerPerson; this.rooms = rooms; this.stars = stars; this.latlng = latlng; this.address = address; this.rendered = false; // this.bookings = []; } Accommodation.prototype = { bookRoom: function(rooms) { if(rooms <= this.rooms) { this.rooms -= rooms } else(console.log("Not enough rooms")) }, isAvailable: function(desiredRooms) { if (desiredRooms > this.rooms) { return(false); }else{ return(true); } } } module.exports = Accommodation;
const eqArrays = function(arrayOne, arrayTwo) { let result = false; if (arrayOne.length === arrayTwo.length) { for (let i = 0; i < arrayOne.length; i++) { if (arrayOne[i] === arrayTwo[i]) { result = true; } if (arrayOne[i] !== arrayTwo[i]) { result = false; } } } else { result = false; } return result; }; const assertArraysEqual = function(oneArray, twoArray) { if (eqArrays(oneArray, twoArray) === true) { console.log('✅✅✅ Assertion Passed'); } else { console.log('❌❌❌ Assertion Failed'); } }; assertArraysEqual([1, 2, 3], [1, 2, 3]); const letterPositions = function(sentence) { const results = { }; // logic to update results here for (let i = 0; i < sentence.length; i++){ const letter = sentence[i]; //console.log(letter); if(sentence[i] === ' '){ } else if(results[letter]){ results[letter].push(i); } else{ results[letter] = [i]; } //if (results.sentence[i]) { //results.sentence[i].push(i); //} else { // results[sentence[i]] = sentence[i]; // results[sentence[i]].push(i); //} } console.log(results); return results; }; letterPositions("lighthouse in the house");
// Tablacus Explorer Resize = async function () { ResetScroll(); let o = document.getElementById("toolbar"); const offsetTop = o ? o.offsetHeight : 0; let h = 0; o = document.getElementById("bottombar"); const offsetBottom = o.offsetHeight; o = document.getElementById("client"); const ode = document.documentElement || document.body; if (o) { h = Math.max(ode.offsetHeight - offsetBottom - offsetTop, 0); o.style.height = h + "px"; } await Promise.all([ResizeSideBar("Left", h), ResizeSideBar("Right", h)]); o = document.getElementById("Background"); pt = GetPos(o); te.offsetLeft = pt.x; te.offsetRight = ode.offsetWidth - o.offsetWidth - pt.x; te.offsetTop = pt.y; pt = GetPos(document.getElementById("bottombar")); te.offsetBottom = ode.offsetHeight - pt.y; await RunEventUI1("Resize"); api.PostMessage(ui_.hwnd, WM_SIZE, 0, 0); } ResizeSideBar = async function (z, h) { let o = g_.Locations; const r = await Promise.all([te.Data["Conf_" + z + "BarWidth"], o[z + "Bar1"], o[z + "Bar2"], o[z + "Bar3"]]); const w = (r[1] || r[2] || r[3]) ? r[0] : 0; o = document.getElementById(z.toLowerCase() + "bar"); if (w > 0) { o.style.display = ""; if (w != o.offsetWidth) { o.style.width = w + "px"; for (let i = 1; i <= 3; ++i) { document.getElementById(z + "Bar" + i).style.width = w + "px"; } document.getElementById(z.toLowerCase() + "barT").style.width = w + "px"; } } else { o.style.display = "none"; } document.getElementById(z.toLowerCase() + "splitter").style.display = w ? "" : "none"; o = document.getElementById(z.toLowerCase() + "barT"); const th = Math.round(Math.max(h, 0)); o.style.height = th + "px"; const h2 = Math.max(o.clientHeight - document.getElementById(z + "Bar1").offsetHeight - document.getElementById(z + "Bar3").offsetHeight, 0); document.getElementById(z + "Bar2").style.height = h2 + "px"; } ResetScroll = function () { if (document.documentElement && document.documentElement.scrollLeft) { document.documentElement.scrollLeft = 0; } } PanelCreated = async function (Ctrl, Id) { await RunEventUI1("PanelCreated", Ctrl, Id); await Resize(); setTimeout(async function () { ChangeView(await Ctrl.Selected); }, 99); } Activate = async function (o, id) { const TC = await te.Ctrl(CTRL_TC); if (TC && await TC.Id != id) { const FV = await GetInnerFV(id); if (FV) { FV.Focus(); setTimeout(function () { o.focus(); }, 99); } } } GetAddonLocation = async function (strName) { const items = await te.Data.Addons.getElementsByTagName(strName); return await GetLength(items) && await items[0].getAttribute("Location"); } SetAddon = async function (strName, Location, Tag, strVAlign) { if (strName) { const s = await GetAddonLocation(strName); if (s) { Location = s; } } if (Tag) { if (Tag.join) { Tag = Tag.join(""); } const re = /(<[^<>]*placeholder=")([^"<>]+)/; const res = re.exec(Tag); if (res) { Tag = Tag.replace(re, res[1] + await GetTextR(res[2])); } const o = document.getElementById(Location); if (o) { if ("string" === typeof Tag) { o.insertAdjacentHTML("beforeend", Tag); } else { o.appendChild(Tag); } o.style.display = (ui_.IEVer >= 8 && SameText(o.tagName, "td")) ? "table-cell" : "block"; if (strVAlign && !o.style.verticalAlign) { o.style.verticalAlign = strVAlign; } const res = /^(LeftBar|RightBar)/.exec(Location); if (res) { const s = "Conf_" + res[1] + "Width"; if (!await te.Data[s]) { te.Data[s] = 178; } } } else if (Location == "Inner") { AddEventUI("PanelCreated", function (Ctrl, Id) { return SetAddon(null, "Inner1Left_" + Id, Tag.replace(/\$/g, Id)); }); } if (strName) { if (!await g_.Locations[Location]) { g_.Locations[Location] = await api.CreateObject("Array"); } const res = /<img.*?src=["'](.*?)["']/i.exec(String(Tag)); if (res) { strName += "\t" + res[1]; } await g_.Locations[Location].push(strName); } } return Location; } RunSplitter = async function (ev, n) { if ((ev.buttons != null ? ev.buttons : ev.button) == 1) { api.ObjPutI(await g_.mouse, "Capture", n); api.SetCapture(ui_.hwnd); } } DisableImage = function (img, bDisable) { if (img) { if (window.chrome) { img.style.filter = bDisable ? "grayscale(1) opacity(.5)" : ""; } else if (ui_.IEVer >= 10) { let s = decodeURIComponent(img.src); const res = /^data:image\/svg.*?href="([^"]*)/i.exec(s); if (bDisable) { if (!res && /^IMG$/i.test(img.tagName)) { if (/^file:/i.test(s)) { let image; if (image = api.CreateObject("WICBitmap").FromFile(api.PathCreateFromUrl(s))) { s = image.DataURI("image/png"); } } img.src = "data:image/svg+xml," + encodeURIComponent(['<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 ', img.offsetWidth, ' ', img.offsetHeight, '"><filter id="G"><feColorMatrix type="saturate" values="0.1" /></filter><image width="', img.width, '" height="', img.height, '" xlink:href="', s, '" filter="url(#G)"></image></svg>'].join("")); } img.style.opacity = .5; } else { if (res) { img.src = res[1]; } img.style.opacity = 1; } } else { img.style.filter = bDisable ? "gray(), alpha(style=0,opacity=50);" : ""; } } } StartGestureTimer = async function () { const i = await te.Data.Conf_GestureTimeout; if (i) { clearTimeout(await g_.mouse.tidGesture); api.ObjPutI(await g_.mouse, "tidGesture", setTimeout(function () { g_.mouse.EndGesture(true); }, i)); } } FocusFV = function () { setTimeout(async function () { let el; if (document.activeElement) { const rc = document.activeElement.getBoundingClientRect(); el = document.elementFromPoint(rc.left + 2, rc.top + 2); } if (!el || !/input|textarea/i.test(el.tagName)) { const hFocus = await api.GetFocus(); if (hFocus == ui_.hwnd || await api.IsChild(ui_.hwnd, hFocus)) { const FV = await GetFolderView(); if (FV) { if (!await api.PathMatchSpec(await api.GetClassName(hFocus), WC_EDIT + ";" + WC_TREEVIEW)) { FV.Focus(); } } } } }, ui_.DoubleClickTime); } ExitFullscreen = function () { if (document.msExitFullscreen) { document.msExitFullscreen(); } else if (document.exitFullscreen) { document.exitFullscreen(); } } MoveSplitter = async function (x, n) { const w = document.documentElement.offsetWidth || document.body.offsetWidth; if (x >= w) { x = w - 1; } if (n == 1) { te.Data["Conf_LeftBarWidth"] = x; } else if (n == 2) { te.Data["Conf_RightBarWidth"] = w - x; } Resize(); } ShowStatusTextEx = async function (Ctrl, Text, iPart, tm) { if (ui_.Status && ui_.Status[5]) { clearTimeout(ui_.Status[5]); delete ui_.Status; } ui_.Status = [Ctrl, Text, iPart, tm, new Date().getTime(), setTimeout(function () { if (ui_.Status) { if (new Date().getTime() - ui_.Status[4] > ui_.Status[3] / 2) { ShowStatusText(ui_.Status[0], ui_.Status[1], ui_.Status[2]); delete ui_.Status; } } }, tm)]; } importJScript = $.importScript; OnArrange = async function (Ctrl, rc) { const Type = await Ctrl.Type; if (Type == CTRL_TE) { ui_.TCPos = {}; } await RunEventUI1("Arrange", Ctrl, rc); if (Type == CTRL_TC) { const Id = await Ctrl.Id; const p = [rc.left, rc.top, rc.right, rc.bottom, Ctrl.Visible, Ctrl.Left, Ctrl.Top, Ctrl.Width, Ctrl.Height]; if (!document.getElementById("Panel_" + Id)) { const s = ['<table id="Panel_', Id, '" class="layout" style="position: absolute; z-index: 1; color: inherit; visibility: hidden">']; s.push('<tr><td id="InnerLeft_', Id, '" class="sidebar" style="width: 0; display: none; overflow: auto"></td><td style="width: 100%"><div id="InnerTop_', Id, '" style="display: none"></div>'); s.push('<table id="InnerTop2_', Id, '" class="layout">'); s.push('<tr><td id="Inner1Left_', Id, '" class="toolbar1"></td><td id="Inner1Center_', Id, '" class="toolbar2" style="white-space: nowrap"></td><td id="Inner1Right_', Id, '" class="toolbar3"></td></tr></table>'); s.push('<table id="InnerView_', Id, '" class="layout" style="width: 100%"><tr><td id="Inner2Left_', Id, '" style="width: 0"></td><td id="Inner2Center_', Id, '" style="width: 100%"></td><td id="Inner2Right_', Id, '" style="width: 0; overflow: auto"></td></tr></table>'); s.push('<div id="InnerBottom_', Id, '"></div></td><td id="InnerRight_', Id, '" class="sidebar" style="width: 0; display: none"></td></tr></table>'); document.getElementById("Panel").insertAdjacentHTML("beforeend", s.join("")); p.push(PanelCreated(Ctrl, Id)); } Promise.all(p).then(function (r) { const o = document.getElementById("Panel_" + Id); o.style.left = r[0] + "px"; o.style.top = r[1] + "px"; if (r[4]) { const s = r.slice(5, 8).join(","); if (ui_.TCPos[s] && ui_.TCPos[s] != Id) { Ctrl.Close(); return; } ui_.TCPos[s] = Id; o.style.display = ""; } else { o.style.display = "none"; return; } o.style.width = Math.max(r[2] - r[0], 0) + "px"; o.style.height = Math.max(r[3] - r[1], 0) + "px"; let el = document.getElementById("InnerLeft_" + Id); if (!/none/i.test(el.style.display)) { r[0] += el.offsetWidth; } el = document.getElementById("Inner2Left_" + Id); if (!/none/i.test(el.style.display)) { r[0] += el.offsetWidth; } r[1] += document.getElementById("InnerTop_" + Id).offsetHeight + document.getElementById("InnerTop2_" + Id).offsetHeight; el = document.getElementById("InnerRight_" + Id); if (!/none/i.test(el.style.display)) { r[2] -= el.offsetWidth; } el = document.getElementById("Inner2Right_" + Id); if (!/none/i.test(el.style.display)) { r[2] -= el.offsetWidth; } r[3] -= document.getElementById("InnerBottom_" + Id).offsetHeight; api.SetRect(rc, r[0], r[1], r[2], r[3]); document.getElementById("Inner2Center_" + Id).style.height = Math.max(r[3] - r[1], 0) + "px"; Promise.all([te.ArrangeCB(Ctrl, rc)]).then(function () { o.style.visibility = "visible"; if (ui_.Show) { delete ui_.Show; SetWindowAlpha(ui_.hwnd, 255); RunEvent1("VisibleChanged", te, true); } }); }); } } ArrangeAddons = async function () { const r = await Promise.all([api.CreateObject("Object"), te.Data.Conf_IconSize, OpenXml("addons.xml", false, true), api.GetKeyState(VK_SHIFT), api.GetKeyState(VK_CONTROL), api.CreateObject("Array"), GetLangId()]); g_.Locations = r[0]; $.IconSize = IconSize = r[1] || screen.deviceYDPI / 4; const xml = r[2]; te.Data.Addons = xml; if (r[3] < 0 && r[4] < 0) { IsSavePath = function (path) { return false; } return; } const AddonId = {}; const root = await xml.documentElement; if (root) { const items = await root.childNodes; if (items) { let arError = r[5]; const LangId = r[6]; const nLen = await GetLength(items); document.F.style.visibility = "hidden"; for (let i = 0; i < nLen; ++i) { const item = items[i]; const r = await Promise.all([item.nodeName, item.getAttribute("Enabled"), item.getAttribute("Level")]); const Id = r[0]; g_.Error_source = Id; if (!AddonId[Id]) { const Enabled = GetNum(r[1]); if (Enabled) { if (Enabled & 6) { LoadLang2(BuildPath(ui_.Installed, "addons", Id, "lang", LangId + ".xml")); } if (Enabled & 8) { await LoadAddon("vbs", Id, arError, null, window.chrome && GetNum(r[2]) < 2); } if (Enabled & 1) { await LoadAddon("js", Id, arError, null, window.chrome && GetNum(r[2]) < 2); } } AddonId[Id] = true; } g_.Error_source = ""; } if (window.chrome) { arError = await api.CreateObject("SafeArray", arError); } if (arError.length) { setTimeout(async function (arError) { if (await MessageBox(arError.join("\n\n"), TITLE, MB_OKCANCEL) != IDCANCEL) { te.Data.bErrorAddons = true; ShowOptions("Tab=Add-ons"); } }, 500, arError); } } } } GetMiscIcon = async function (n) { const s = BuildPath(ui_.DataFolder, "icons\\misc\\" + n + ".png"); return await fso.FileExists(s) ? s : ""; } // Events AddEvent("VisibleChanged", async function (Ctrl) { if (await Ctrl.Type == CTRL_TC) { const o = document.getElementById("Panel_" + await Ctrl.Id); if (o) { if (await Ctrl.Visible) { o.style.display = ""; ChangeView(await Ctrl.Selected); } else { o.style.display = "none"; } } } }); AddEvent("SystemMessage", async function (Ctrl, hwnd, msg, wParam, lParam) { if (await Ctrl.Type == CTRL_WB) { if (msg == WM_KILLFOCUS) { const o = document.activeElement; if (o) { const s = o.style.visibility; o.style.visibility = "hidden"; o.style.visibility = s; FireEvent(o, "blur"); } } } }); // Browser Events window.addEventListener("load", async function () { if (await api.GetKeyState(VK_SHIFT) < 0 && await api.GetKeyState(VK_CONTROL) < 0) { ShowOptions("Tab=Add-ons"); } }); window.addEventListener("resize", Resize); window.addEventListener("unload", FinalizeUI); window.addEventListener("blur", ResetScroll); window.addEventListener("mouseup", FocusFV); if (window.chrome) { window.addEventListener("mousedown", function (ev) { g_.mouse.ptDown.x = ev.screenX * ui_.Zoom; g_.mouse.ptDown.y = ev.screenY * ui_.Zoom; }); } document.addEventListener("MSFullscreenChange", function () { FullscreenChanged(document.msFullscreenElement != null); }); document.addEventListener("FullscreenChange", function () { FullscreenChanged(document.fullscreenElement != null); }); Init = async function () { te.Data.MainWindow = $; te.Data.NoCssFont = ui_.NoCssFont; await InitCode(); const r = await Promise.all([te.Data.DataFolder, $.DefaultFont, $.HOME_PATH, $.OpenMode, $.DefaultFont.lfFaceName, $.DefaultFont.lfHeight, $.DefaultFont.lfWeight, InitMenus(), LoadLang()]); ui_.DataFolder = r[0]; DefaultFont = r[1]; HOME_PATH = r[2]; OpenMode = r[3]; document.body.style.fontFamily = r[4]; document.body.style.fontSize = Math.abs(r[5]) + "px"; document.body.style.fontWeight = r[6]; await ArrangeAddons(); RunEventUI("BrowserCreatedEx"); await RunEventUI1("Layout"); document.F.style.visibility = ""; te.OnArrange = OnArrange; await InitBG(await GetWinColor(window.getComputedStyle ? getComputedStyle(document.body).getPropertyValue('background-color') : document.body.currentStyle.backgroundColor)); await InitWindow(); await RunEventUI1("Load"); ui_.Show = true; Resize(); AddEvent("BrowserCreatedEx", "setTimeout(async function () { SetWindowAlpha(await GetTopWindow(), 255); }, 99);"); ClearEvent("Layout"); ClearEvent("Load"); }
$(document).ready(function(){ $('#apps').click(function(){ $(".drop-menu").toggle(); }); });
import React from "react" import Typist from "react-typist" const styles = { maxWidth: "50rem", fontSize: "1.4rem", margin: "6rem auto 2rem", padding: "2rem", minHeight: "350px", } const Intro = () => { return ( <div style={styles}> <Typist avgTypingDelay={50} cursor={{ hideWhenDone: true }}> <Typist.Delay ms={1000} /> {"Hi, I'm Michael. "} <Typist.Delay ms={1000} /> {" I just want to build cool things with people I respect and admire."} <br /> <br /> <Typist.Delay ms={500} /> {"I also take a lot of notes."} <Typist.Delay ms={500} />{" "} {"Anytime I hear or read something smart, I try to write it down."} </Typist>{" "} </div> ) } export default Intro
import { playMode } from '../utils/config' const state = { playing: false, // 播放中 fullScreen: true, // 全屏播放器 playList: [], // 播放列表 sequenceList: [], // 顺序列表 playMode: playMode.sequence, // 播放模式 currentIndex: 0 // 当前歌曲下标 } export default state
function ClozeCard (text, cloze) { this.text = text; this.cloze = cloze; } ClozeCard.prototype.showQuestion = function() { var partial = this.text.replace(this.cloze, "..."); console.log("Front: " + partial); } ClozeCard.prototype.showAnswer = function() { console.log("Back: " + this.cloze); } ClozeCard.prototype.showFullText = function() { console.log(this.text); } ClozeCard.prototype.printCard = function() { this.showQuestion(); this.showAnswer(); } var card1 = new ClozeCard("80s popstars Duran Duran was made up of five members, three of whom shared the last name 'Taylor', although none were related.", "Duran Duran"); //card1.createPartial(); module.exports = ClozeCard;
module.exports = { util: function () { var util = require('./../../toolbox/Util'); return new util(); }, homePage: function(){ var homePage = require('./../../modules/home/HomePage'); return new homePage(); }, blogStep: function(){ var blogStep = require('./../../modules/blog/BlogStep'); return new blogStep(); }, blogPage: function(){ var blogPage = require('./../../modules/blog/BlogPage'); return new blogPage(); } };
import React,{ Component } from 'react'; import TodoItems from './component/todoitem/TodoItems'; import AddItem from './component/additem/AddItem'; class App extends Component { state ={ items:[ {id:1,name:'wajeeh',age:21}, {id:2,name:'ayube',age:33} ], } deleteItem=(id)=>{ /* طريقة الاولي let items=this.state.items; let i=items.findIndex(item=>item.id===id); items.splice(i,1); this.setState({items:items}); */ let items=this.state.items.filter(item=>{ return item.id !==id }) this.setState({items:items}) } addItem = (item)=>{ item.id=Math.random(); let items=this.state.items; items.push(item); this.setState({items:items}); } render(){ return ( <div className="App container"> <h1 className="text-center"> قائمة المهام</h1> <TodoItems items={this.state.items} deleteItem={this.deleteItem}/> <AddItem addItem={this.addItem}/> </div> ); }} export default App;
/** * Created by suzanne on 5/4/18. */ import React from 'react' import PropTypes from 'prop-types' import './FlexBox.css' //stateless Component const Box = (props) => { let style = {} if (props.showing!==0) { style.backgroundColor = props.backgroundColor } return ( <div onClick = {props.onClick} className = 'card-container' style={style}> </div> ) } Box.propTypes = { showing: PropTypes.number.isRequired, backgroundColor: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired } export default Box
/* TITLE IMAGE ANIMATION */ $('#hero img').on('mouseover', function() { $(this).velocity({ translateY: -50, scale: 1.25 }, { easing: "easeOutBack", }, 800); }); $('#hero img').on('mouseout', function() { $(this).velocity({ translateY: 0, scale: 1 }, { easing: "spring" }, 250); }); /* SUB-TITLE TYPING ANIMATION */ $(function() { $('.typed-js').typed({ strings: ["need a break", "want to kill time", "love a challenge", "like to have fun"], typeSpeed: 0, backDelay: 1500, loop: true }); }); /* PERFORMANCE STATS */ $(function() { $('#first-byte-time').html(window.performance.timing.responseStart - window.performance.timing.navigationStart); $('#front-end-load').html(window.performance.timing.domComplete - window.performance.timing.domLoading); var resources = window.performance.getEntriesByType('resource'); var entry = "<ul class=\"hidden\">"; $.each(resources, function(i,v){ entry += "<li class=\"resource\"><p>" + v.name + "</p>"; entry += "<p>" + v.initiatorType + "</p>"; entry += "<p>" + (v.responseEnd - v.requestStart) + "ms</p></li>"; }); entry += "</ul>"; $('#performance').append(entry); $('#toggle-resources').click(function() { $('#performance ul').toggleClass('hidden'); }); });
// TODO: include https://siddii.github.io/angular-timer/ for countdown (function() { 'use strict'; angular.module('app') .controller('ChallengeCtrl', ChallengeCtrl); function ChallengeCtrl($state, $ionicHistory, $stateParams, Challenge, $scope, ChallengesService) { var eventId = $stateParams.id; $scope.challenge = ChallengesService.getChallenge(challengeId); // $scope.event = Event; // console.log(Event); $scope.refresh = function() { $scope.event = ChallengesService.getChallenge(challengeId); console.log($scope.challenge); //Stop the ion-refresher from spinning $scope.$broadcast('scroll.refreshComplete'); }; } })();
$(function() { var ticketurl= '/getticket'; $.ajax({ url: ticketurl }) .then( function ( ticket ) { //visOSMKort(ticket); visKort(ticket); map.fitBounds([ [57.751949, 15.193240], [54.559132, 8.074720] ]); L.control.search().addTo(map); }) .fail(function( jqXHR, textStatus, errorThrown ) { alert('Ingen ticket: ' + jqXHR.statusCode() + ", " + textStatus + ", " + jqXHR.responseText); }); if ('serviceWorker' in navigator) { navigator.serviceWorker .register('./service-worker.js') .then(function() { console.log('Service Worker Registered'); }); } });
OC.L10N.register( "files_versions", { "Versions" : "إصدارات", "Failed to revert {file} to revision {timestamp}." : "فشلت استعادة {file} لمراجعة {timestamp}.", "_%n byte_::_%n bytes_" : ["%n بايت","%n بايت","%n بايت","%n بايت","%n بايت","%n بايت"], "Restore" : "استعادة", "No other versions available" : "لا تتوفر إصدارات أخرى" }, "nplurals=6; plural=n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5;");
const express = require('express'); const router = express.Router(); const multer = require("multer") const controller = require("../../controllers/admin/mailTemplates") const is_admin = require("../../middleware/admin/is-admin") router.get('/mail/templates/:language?/:template_id?',multer().none(), is_admin, controller.index) router.post('/mail/templates/:language?/:template_id?',multer().none(), is_admin, controller.index) module.exports = router;
/** * Created by dell-pc on 2017/9/27. */ //function unique(arr){ // return Array.from(new Set(arr)); //} //function unique(arr){ // var data = []; // for(var i=0;i<arr.length;i++){ // if(data.indexOf(arr[i])==-1){ // data.push(arr[i]); // } // } // return data; //} function unique(arr){ var table = {}; var data = []; for(var i=0;i<arr.length;i++){ if(!table[arr[i]]){ table[arr[i]]=true; data.push(arr[i]); } } console.log(table) return data; } var arr = [1,2,3,9,3,4,4,4,4,9,4]; console.log(unique(arr));
const mongoose = require('mongoose'); const uniqueValidator = require('mongoose-unique-validator'); const materialSchema = mongoose.Schema({ nom : {type:String, required:[true,"Le nom du materiel est obligatoire!"]}, date_ajout:{type:Date, default:Date.now}, user: { type: mongoose.Schema.Types.ObjectId, ref: "User" , required: true} }) materialSchema.plugin(uniqueValidator); module.exports = mongoose.model("Material", materialSchema);
const mongoose = require("mongoose"); let personModel = require("./models/person.js"); let person = new personModel({ name: "wafi", age: 29, favoriteFoods: ["pizza", "humburger"] }); mongoose .connect("mongodb+srv://wafi:54900777@cluster0.qxhos.mongodb.net/test", { useNewUrlParser: true, }) .then(() => { console.log("connected"); }) .catch((error) => { console.log("not connected"); }); person.save(function (error, data) { if (error) { console.log(error); } console.log(data); }); let arrayOfPeaple = [ { name: "John", age: 28, favoriteFoods: ["tacos"] }, { name: "Amin", age: 20, favoriteFoods: ["burger", "sandwish"] }, { name: "Asma", age: 32, favoriteFoods: ["panini", "nuggets"] } ]; personModel .create(arrayOfPeaple) .then(() => { console.log("instance of objectes done and saved on the database"); }) .catch((error) => { console.log(error); }); personModel .find({}) .then((data) => { if(data){ console.log(data); } console.log('no data waiting') }) .catch((error) => { console.log(error); }); personModel .findOne({ favoriteFoods: "panini" }) .then((data) => { if (data){ console.log(data); } else { console.log('no one love this food') } }) .catch((error) => { console.log(error); }); personModel .findById("6124519c14411d235c62389d") .then((data) => { if(data){ console.log(data); } else{ console.log('there is no person that have this favourites food') } }) .catch((error) => { console.log(error); }); personModel.findById("6124519c14411d235c62389d").then((data) => { if(data){ data.favoriteFoods.push("humbrger"); data.save().then(()=>{ console.log('stored on the database ') }).catch((error)=>{ console.log(error) }); } else { console.log('no person exist with this id') } }); personModel .findOneAndUpdate( { name: "wafi" }, { age: 20 }, { new: true, upsert: true, } ) .then((data) => { console.log(data); }) .catch((error) => { console.log(error); }); personModel.findByIdAndRemove({ _id:'6124519c14411d235c62389d' }); personModel .remove({ name: "Mary" }) .then((data) => { if(data){ console.log('done') } console.log("no data with this name"); }) .catch((error) => { console.log(error); }); personModel.find({favoriteFoods : "burritos" }) .select({age:0}) .limit(2) .sort({name: 1}) // .sort({name: 'asc'}) .exec((err,person)=>{ console.log("chain search query..") if(err){ console.log(err) } else { console.log(person) }; })
require('dotenv').config(); const PORT = process.env.PORT || 3000; const config = { development: { config_id: 'development', node_port: PORT, db_url: process.env.MongoURL }, release: { config_id: 'release', node_port: PORT, db_url: process.env.MongoURL }, production: { config_id: 'production', node_port: PORT, db_url: process.env.MongoURL } };
exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('users').del() .then(function () { // Inserts seed entries return knex('users').insert([ {full_name: 'Hayden Turek', username: 'guy49', img_url: 'http://bit.ly/2nAudW8'}, {full_name: 'Avery McGinty', username: 'girl88', img_url: 'http://bit.ly/2nTz9Y7'}, {full_name: 'Zubair Desai', username: 'legend00', img_url: 'http://bit.ly/2nFRBCA'} ]); }); };
var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io').listen(server); var users = []; var connections = []; server.listen(3000); app.use('/public', express.static(__dirname + '/public')); app.get('/', function(req, res) { res.sendFile(__dirname + '/index.html'); }); console.log('Server is running'); io.sockets.on('connection', function(socket) { connections.push(socket); console.log('User connected, %s sockets connected.', connections.length); socket.on('disconnect', function(data) { connections.splice(connections.indexOf(socket), 1); console.log('User disconnected, %s sockets connected.', connections.length); }); });
import React, { Component } from 'react'; import Keypad from './Keypad'; import Output from './Output'; import { } from "./style/Calculator.css"; export default class Calculator extends Component { constructor(props) { super(props); this.state = { result: '', }; } buttonPressed = (buttonName) => { if (buttonName === "=") { this.calculate(); } else if (buttonName === "C") { this.reset(); } else if (buttonName === "CE") { this.backspace(); } else { this.setState({ result: this.state.result + buttonName }); } }; calculate = () => { var checkResult = ''; checkResult = this.state.result.includes('--') ? this.state.result.replace('--', '+') : this.state.result; try { this.setState({ // eslint-disable-next-line result: (eval(checkResult) || "") + "" }); } catch (e) { this.setState({ result: "error" }); } }; reset = () => this.setState({ result: "" }); backspace = () => this.setState({ result: this.state.result.slice(0, -1) }); render() { return ( <React.Fragment> <Output result={this.state.result} /> <Keypad buttonPressed={this.buttonPressed} /> </React.Fragment> ); } }
export const ON_LOGIN_START = 'ON_LOGIN_START' export const ON_LOGIN_SUCCESS = 'ON_LOGIN_SUCCESS' export const ON_LOGIN_ERROR = 'ON_LOGIN_ERROR' export const ON_LOGIN_CLEAR = 'ON_LOGIN_CLEAR'
var mutt__history_8c = [ [ "mutt_hist_complete", "mutt__history_8c.html#a9115fdadb99ef83565f9e4d5e436d3be", null ], [ "mutt_hist_observer", "mutt__history_8c.html#a48141d10454e61aa47334280ad18ace4", null ] ];
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Icons from '../../../icons'; import Icon from '../../icon/Icon'; import IconsStore from '../../icon/IconsStore'; import { COLORS } from '../../base/Colors'; import withDisplayName from '../../WithDisplayName'; import './PhotoInput.scss'; class PhotoInput extends Component { constructor(props) { super(props); this.iconsStore = new IconsStore(Icons); } /** * Returns the photo object */ getInputValue() { return this.img.src; } /** * Opens file dialog */ openFileDialog = () => { this.input.click(); }; /** * Loads the image from local device and load a preview */ loadPreview = () => { const { loadPreview, photoPreview, isPhoto } = this.props; loadPreview(this.input, photo => { const reader = new FileReader(); reader.readAsDataURL(photo); reader.onloadend = () => { this.props.updatePhoto({ preview: photoPreview, crop: reader.result, isPhoto, showCropper: true, }); this.input.value = null; }; }); }; /** * Check if open file dialog or image cropper tool */ uploadPhoto = () => { const { updatePhoto, photoPreview, photoCrop, isPhoto } = this.props; if (isPhoto) { updatePhoto({ preview: photoPreview, crop: photoCrop, isPhoto, showCropper: true, }); } else { this.input.click(); } }; render() { const { isPhoto, photoPreview, disabled } = this.props; let icon; if (isPhoto) { icon = ''; } else { icon = ( <Icon icon={this.iconsStore.getIcon('camera')} width={30} color={disabled ? COLORS.DISABLED : COLORS.PRIMARY_BLUE} /> ); } return ( <div className="upload-photo-container"> <div className="upload-photo" onClick={this.uploadPhoto} onKeyDown={() => {}}> <img src={photoPreview} ref={img => { this.img = img; }} alt="doctor" onError={this.onError} /> {icon} <input autoComplete="off" className="hide" type="file" ref={input => { this.input = input; }} accept=".png, .jpg, .jpeg" onChange={this.loadPreview} /> </div> </div> ); } } PhotoInput.propTypes = { photoPreview: PropTypes.string.isRequired, photoCrop: PropTypes.string.isRequired, isPhoto: PropTypes.bool.isRequired, updatePhoto: PropTypes.func.isRequired, loadPreview: PropTypes.func.isRequired, disabled: PropTypes.bool, }; PhotoInput.defaultProps = { disabled: false, }; export default withDisplayName(PhotoInput, 'PhotoInput');
import React, { useEffect, useState } from "react"; import { View, Text, TouchableOpacity, Image, FlatList, ScrollView, } from "react-native"; function GroupCartScreen(props) { const item = props.route.params.item; const [t1, sett1] = useState(true); const [t2, sett2] = useState(false); return ( <View style={{ flex: 1, backgroundColor: "white" }}> <View style={{ marginTop: 20, flexDirection: "row" }}> <TouchableOpacity style={{ padding: 15, borderWidth: 1, borderColor: "#D9D9D9", width: "50%", justifyContent: "center", alignItems: "center", }} onPress={() => { sett1(true); sett2(false); }} > <Text style={{ fontSize: 16, fontWeight: "600" }}>My Bag</Text> </TouchableOpacity> <TouchableOpacity style={{ padding: 15, borderWidth: 1, borderColor: "#D9D9D9", borderLeftWidth: 0, width: "50%", justifyContent: "center", alignItems: "center", }} onPress={() => { sett2(true); sett1(false); }} > <Text style={{ fontSize: 16, fontWeight: "600" }}>Friend's Bag</Text> </TouchableOpacity> </View> {t1 ? ( <ScrollView> <FlatList data={item.mybagitems} renderItem={({ item }) => { return ( <View style={{ margin: 10, flexDirection: "row", padding: 10, borderWidth: 1, borderColor: "#D9D9D9", }} > <Image source={{ uri: item.itemImage }} style={{ width: 150, height: 150 }} /> <View style={{ padding: 10 }}> <Text>{item.itemTitle}</Text> <Text>{item.itemBrand}</Text> <Text style={{ marginTop: 10, color: "red", fontSize: 15 }}> Group Price </Text> </View> </View> ); }} keyExtractor={(item) => item.itemId} /> </ScrollView> ) : null} {t2 ? ( <ScrollView> <View style={{ justifyContent: "center", alignItems: "center", paddingVertical: 100, }} > <Text style={{ fontSize: 14, fontWeight: "bold" }}> Click on the Explore button and Join among </Text> <Text style={{ fontSize: 14, fontWeight: "bold" }}> existing teams to save extra </Text> <TouchableOpacity style={{ backgroundColor: "#FDA5A5", padding: 10, margin: 10, borderRadius: 10, }} onPress={() => props.navigation.navigate("Home")} > <Text style={{ fontSize: 16, fontWeight: "bold" }}>Explore</Text> </TouchableOpacity> </View> <FlatList data={item.mybagitems} renderItem={({ item }) => { return ( <View style={{ margin: 10, flexDirection: "row", padding: 10, borderWidth: 1, borderColor: "#D9D9D9", }} > <Image source={{ uri: item.itemImage }} style={{ width: 150, height: 150 }} /> <View style={{ padding: 10 }}> <Text>{item.itemTitle}</Text> <Text>{item.itemBrand}</Text> <Text style={{ marginTop: 10, color: "red", fontSize: 15 }}> Group Price </Text> </View> </View> ); }} keyExtractor={(item) => item.itemId} /> </ScrollView> ) : null} </View> ); } export default GroupCartScreen;