text
stringlengths
2
6.14k
import freeze from 'deep-freeze' import {ensure} from '#/main/core/tests' import {TYPE_QUIZ, TYPE_STEP} from './../enums' import select from './selectors' import {tex, t} from '#/main/core/translation' describe('Thumbnails selector', () => { it('returns the quiz and step thumbs with active and errors set', () => { ensure.equal(select.thumbnails(fixtureState1()), [ { id: '1', title: t('parameters'), type: TYPE_QUIZ, active: false, hasErrors: false }, { id: 'a', title: `${tex('step')} 1`, type: TYPE_STEP, active: false, hasErrors: true }, { id: 'b', title: `${tex('step')} 2`, type: TYPE_STEP, active: true, hasErrors: false } ]) }) }) describe('Current object deep selector', () => { it('returns quiz properties if quiz is selected', () => { ensure.equal(select.currentObjectDeep(fixtureState2()), { type: TYPE_QUIZ, id: '1' }) }) it('returns step details if step is selected', () => { ensure.equal(select.currentObjectDeep(fixtureState3()), { type: TYPE_STEP, id: 'b', title: 'B', description: 'B desc', parameters: { maxAttempts: 5 }, items: [ { id: 'x', type: 'text/html' } ] }) }) }) describe('Step open panel selector', () => { it('returns false if no step is selected', () => { ensure.equal(select.stepOpenPanel(fixtureState4()), false) }) it('returns open panel key of current step', () => { ensure.equal(select.stepOpenPanel(fixtureState5()), 'bar') }) }) describe('Next object selector', () => { it('returns the quiz if quiz is already current', () => { ensure.equal(select.nextObject(fixtureState2()), { id: '1', type: TYPE_QUIZ }) }) it('returns the quiz if there is only one the step', () => { ensure.equal(select.nextObject(fixtureState6()), { id: '1', type: TYPE_QUIZ }) }) it('returns the next step if there is one', () => { ensure.equal(select.nextObject(fixtureState7()), { id: 'b', type: TYPE_STEP }) }) it('returns the previous step if current is the second and last step', () => { ensure.equal(select.nextObject(fixtureState8()), { id: 'a', type: TYPE_STEP }) }) }) describe('Valid selector', () => { it('returns false in case of item errors', () => { ensure.equal(select.valid(fixtureState1()), false) }) it('returns false in case of quiz errors', () => { ensure.equal(select.valid(fixtureState2()), false) }) it('returns true if no errors', () => { ensure.equal(select.valid(fixtureState3()), true) }) }) function fixtureState1() { return freeze({ quiz: { id: '1', steps: ['a', 'b'] }, steps: { 'a': { id: 'a', items: ['x'] }, 'b': { id: 'b', items: [] } }, items: { x: { _errors: {foo: 'bar'} } }, editor: { currentObject: { id: 'b', type: TYPE_STEP } } }) } function fixtureState2() { return freeze({ quiz: { id: '1', steps: ['a', 'b'], _errors: {bar: 'baz'} }, steps: { 'a': { id: 'a', items: [] }, 'b': { id: 'b', items: [] } }, items: {}, editor: { currentObject: { id: '1', type: TYPE_QUIZ } } }) } function fixtureState3() { return freeze({ quiz: { id: '1', steps: ['a', 'b'] }, steps: { 'a': { id: 'a', items: [] }, 'b': { id: 'b', title: 'B', description: 'B desc', parameters: {maxAttempts: 5}, items: ['x'] } }, items: { 'x': { id: 'x', type: 'text/html' } }, editor: { currentObject: { id: 'b', type: TYPE_STEP } } }) } function fixtureState4() { return freeze({ editor: { currentObject: { id: 'a', type: TYPE_QUIZ }, openPanels: { [TYPE_QUIZ]: 'foo', [TYPE_STEP]: {} } } }) } function fixtureState5() { return freeze({ editor: { currentObject: { id: 'b', type: TYPE_STEP }, openPanels: { [TYPE_QUIZ]: false, [TYPE_STEP]: { 'a': 'foo', 'b': 'bar' } } } }) } function fixtureState6() { return freeze({ quiz: { id: '1', steps: ['a'] }, steps: { 'a': { id: 'a', items: [] } }, editor: { currentObject: { id: 'a', type: TYPE_STEP } } }) } function fixtureState7() { return freeze({ quiz: { id: '1', steps: ['a', 'b'] }, steps: { 'a': { id: 'a', items: [] }, 'b': { id: 'b', items: [] } }, items: {}, editor: { currentObject: { id: 'a', type: TYPE_STEP } } }) } function fixtureState8() { return freeze({ quiz: { id: '1', steps: ['a', 'b'] }, steps: { 'a': { id: 'a', items: [] }, 'b': { id: 'b', items: [] } }, items: {}, editor: { currentObject: { id: 'b', type: TYPE_STEP } } }) }
import React from 'react' import PropTypes from 'prop-types' import Link from '@material-ui/core/Link' import Dialog from '@material-ui/core/Dialog' import IconButton from '@material-ui/core/IconButton' import TableContainer from '@material-ui/core/TableContainer' import Table from '@material-ui/core/Table' import TableBody from '@material-ui/core/TableBody' import TableRow from '@material-ui/core/TableRow' import TableCell from '@material-ui/core/TableCell' import Paper from '@material-ui/core/Paper' import FavoriteBorderIcon from '@material-ui/icons/FavoriteBorder' import inflection from 'inflection' import { useTranslate } from 'react-admin' import config from '../config' import { DialogTitle } from './DialogTitle' import { DialogContent } from './DialogContent' const links = { homepage: 'navidrome.org', reddit: 'reddit.com/r/Navidrome', twitter: 'twitter.com/navidrome', discord: 'discord.gg/xh7j7yF', source: 'github.com/navidrome/navidrome', featureRequests: 'github.com/navidrome/navidrome/issues', } const AboutDialog = ({ open, onClose }) => { const translate = useTranslate() return ( <Dialog onClose={onClose} onBackdropClick={onClose} aria-labelledby="about-dialog-title" open={open} > <DialogTitle id="about-dialog-title" onClose={onClose}> Navidrome Music Server </DialogTitle> <DialogContent dividers> <TableContainer component={Paper}> <Table aria-label={translate('menu.about')} size="small"> <TableBody> <TableRow> <TableCell align="right" component="th" scope="row"> {translate('menu.version')}: </TableCell> {config.version === 'dev' ? ( <TableCell align="left"> {config.version} </TableCell> ) : ( <TableCell align="left"> <Link href={`https://github.com/navidrome/navidrome/releases/tag/v${ config.version.split(' ')[0] }`} target="_blank" rel="noopener noreferrer" > {config.version.split(' ')[0]} </Link> {' ' + config.version.split(' ')[1]} </TableCell> )} </TableRow> {Object.keys(links).map((key) => { return ( <TableRow key={key}> <TableCell align="right" component="th" scope="row"> {translate(`about.links.${key}`, { _: inflection.humanize(inflection.underscore(key)), })} : </TableCell> <TableCell align="left"> <Link href={`https://${links[key]}`} target="_blank" rel="noopener noreferrer" > {links[key]} </Link> </TableCell> </TableRow> ) })} <TableRow> <TableCell align="right" component="th" scope="row"> <Link href={'https://github.com/sponsors/deluan'} target="_blank" rel="noopener noreferrer" > <IconButton size={'small'}> <FavoriteBorderIcon fontSize={'small'} /> </IconButton> </Link> </TableCell> <TableCell align="left"> <Link href={'https://ko-fi.com/deluan'} target="_blank" rel="noopener noreferrer" > ko-fi.com/deluan </Link> </TableCell> </TableRow> </TableBody> </Table> </TableContainer> </DialogContent> </Dialog> ) } AboutDialog.propTypes = { open: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, } export { AboutDialog }
tinymce.PluginManager.add('tabpanel', function(editor, url) { var walker = tinymce.dom.TreeWalker; editor.ui.registry.addNestedMenuItem('tabpanel', { //icon: 'tabpanel', text: "Tabs", tooltip: "Tabs", getSubmenuItems: function () { return [ { type: 'menuitem', //icon: 'tab', text: "New panel", tooltip: "New panel", onAction: function () { let el = editor.selection.getNode(); let parent = el.parentNode; let tabpanels = editor.dom.getParents(el,'.tabpanels')[0]; if(tabpanels !== undefined && tabpanels !== null) { let tabs = editor.dom.select('.nav-tabs',tabpanels)[0], panels = editor.dom.select('.tab-content',tabpanels)[0], nb = tabs.children.length; nb++; editor.dom.add(tabs,'li',false,'<a role="tab" href="#tab'+nb+'" aria-controls="tab'+nb+'" data-toggle="tab"><img class="img-responsive" src="#" alt="color'+nb+'" width="250" height="250" /><span>Color'+nb+'</span></a>'); editor.dom.add(panels,'section',{id:'tab'+nb,class:'tab-pane',role:'tabpanel'},'<p>color'+nb+'</p>'); } } }, { type: 'menuitem', //icon: 'tab', text: "Remove panel", tooltip: "Remove panel", onAction: function () { let el = editor.selection.getNode(); let parent = el.parentNode; let tabpanels = editor.dom.getParents(el,'.tabpanels')[0]; if(tabpanels !== undefined && tabpanels !== null) { let tabs = editor.dom.select('.nav-tabs',tabpanels)[0], panels = editor.dom.select('.tab-content',tabpanels)[0]; tinymce.activeEditor.dom.remove(tinymce.activeEditor.dom.select('li:last-child',tabs)); tinymce.activeEditor.dom.remove(tinymce.activeEditor.dom.select('section:last-child',panels)); } } } ]; } }); }); // Load the required translation files tinymce.PluginManager.requireLangPack('tabpanel', 'en_EN,fr_FR');
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 __()); }; })(); import { Animation } from '../../animations/animation'; import { Transition } from '../../transitions/transition'; var ActionSheetSlideIn = (function (_super) { __extends(ActionSheetSlideIn, _super); function ActionSheetSlideIn() { return _super !== null && _super.apply(this, arguments) || this; } ActionSheetSlideIn.prototype.init = function () { var ele = this.enteringView.pageRef().nativeElement; var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop')); var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper')); backdrop.fromTo('opacity', 0.01, 0.4); wrapper.fromTo('translateY', '100%', '0%'); this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(backdrop).add(wrapper); }; return ActionSheetSlideIn; }(Transition)); export { ActionSheetSlideIn }; var ActionSheetSlideOut = (function (_super) { __extends(ActionSheetSlideOut, _super); function ActionSheetSlideOut() { return _super !== null && _super.apply(this, arguments) || this; } ActionSheetSlideOut.prototype.init = function () { var ele = this.leavingView.pageRef().nativeElement; var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop')); var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper')); backdrop.fromTo('opacity', 0.4, 0); wrapper.fromTo('translateY', '0%', '100%'); this.easing('cubic-bezier(.36,.66,.04,1)').duration(300).add(backdrop).add(wrapper); }; return ActionSheetSlideOut; }(Transition)); export { ActionSheetSlideOut }; var ActionSheetMdSlideIn = (function (_super) { __extends(ActionSheetMdSlideIn, _super); function ActionSheetMdSlideIn() { return _super !== null && _super.apply(this, arguments) || this; } ActionSheetMdSlideIn.prototype.init = function () { var ele = this.enteringView.pageRef().nativeElement; var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop')); var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper')); backdrop.fromTo('opacity', 0.01, 0.26); wrapper.fromTo('translateY', '100%', '0%'); this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(backdrop).add(wrapper); }; return ActionSheetMdSlideIn; }(Transition)); export { ActionSheetMdSlideIn }; var ActionSheetMdSlideOut = (function (_super) { __extends(ActionSheetMdSlideOut, _super); function ActionSheetMdSlideOut() { return _super !== null && _super.apply(this, arguments) || this; } ActionSheetMdSlideOut.prototype.init = function () { var ele = this.leavingView.pageRef().nativeElement; var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop')); var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper')); backdrop.fromTo('opacity', 0.26, 0); wrapper.fromTo('translateY', '0%', '100%'); this.easing('cubic-bezier(.36,.66,.04,1)').duration(450).add(backdrop).add(wrapper); }; return ActionSheetMdSlideOut; }(Transition)); export { ActionSheetMdSlideOut }; var ActionSheetWpSlideIn = (function (_super) { __extends(ActionSheetWpSlideIn, _super); function ActionSheetWpSlideIn() { return _super !== null && _super.apply(this, arguments) || this; } ActionSheetWpSlideIn.prototype.init = function () { var ele = this.enteringView.pageRef().nativeElement; var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop')); var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper')); backdrop.fromTo('opacity', 0.01, 0.16); wrapper.fromTo('translateY', '100%', '0%'); this.easing('cubic-bezier(.36,.66,.04,1)').duration(400).add(backdrop).add(wrapper); }; return ActionSheetWpSlideIn; }(Transition)); export { ActionSheetWpSlideIn }; var ActionSheetWpSlideOut = (function (_super) { __extends(ActionSheetWpSlideOut, _super); function ActionSheetWpSlideOut() { return _super !== null && _super.apply(this, arguments) || this; } ActionSheetWpSlideOut.prototype.init = function () { var ele = this.leavingView.pageRef().nativeElement; var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop')); var wrapper = new Animation(this.plt, ele.querySelector('.action-sheet-wrapper')); backdrop.fromTo('opacity', 0.1, 0); wrapper.fromTo('translateY', '0%', '100%'); this.easing('cubic-bezier(.36,.66,.04,1)').duration(450).add(backdrop).add(wrapper); }; return ActionSheetWpSlideOut; }(Transition)); export { ActionSheetWpSlideOut }; //# sourceMappingURL=action-sheet-transitions.js.map
/* * uSelect iDownload * * Copyright © 2011-2013 Alessandro Guido * Copyright © 2011-2013 Marco Palumbo * * This file is part of uSelect iDownload. * * uSelect iDownload is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * uSelect iDownload is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with uSelect iDownload. If not, see <http://www.gnu.org/licenses/>. */ function req_action_handler(request, sender, sendResponse) { var urls = request['urls']; var action = request['action']; var tabId = request['tabId']; if (action == 'window') { /* * TODO: * - incognito window * - selected */ chrome.windows.create({'url': urls}); } else { switch (action) { case 'download': urls.forEach(function (url) { console.log(url); chrome.downloads.download({ 'url': url, }); }); chrome.tabs.create({ 'url': 'chrome://downloads', 'selected': true, 'openerTabId': sender.tab.id, }); break; case 'tabs': urls.forEach(function (url) { chrome.tabs.create({ 'url': url, 'selected': false, 'openerTabId': sender.tab.id, }); }); break; } } // The chrome.extension.onMessage listener must return true if you want to send a response after the listener returns return true; } function req_inject_handler(request, sender, sendResponse) { chrome.tabs.executeScript(sender.tab.id, {file: 'js/statemachine.js'}, function () { chrome.tabs.executeScript(sender.tab.id, {file: 'js/overlay.js'}, function () { if (sendResponse != null) sendResponse(); }); }); // The chrome.extension.onMessage listener must return true if you want to send a response after the listener returns return true; } /** * Demultiplex requests using the '__req__' property of the request object */ chrome.extension.onMessage.addListener(function (request, sender, sendResponse) { switch (request['__req__']) { case 'inject': return req_inject_handler(request, sender, sendResponse); case 'action': return req_action_handler(request, sender, sendResponse); default: console.log('Unknown message'); } }); chrome.browserAction.onClicked.addListener(function (tab) { chrome.tabs.sendMessage(tab.id, 'toggle'); });
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-19924913-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
'use strict'; angular.module('app').controller('FundraiserNavTabsController', function ($scope, $location) { $scope.active_tab = function(name) { if (name === 'overview' && (/^\/fundraisers\/[a-z-_0-9]+$/i).test($location.path())) { return "active"; } if (name === 'updates' && (/^\/fundraisers\/[a-z-_0-9]+\/updates$/i).test($location.path())) { return "active"; } if (name === 'pledges' && (/^\/fundraisers\/[a-z-_0-9]+\/pledges$/i).test($location.path())) { return "active"; } if (name === 'rewards' && (/^\/fundraisers\/[a-z-_0-9]+\/rewards$/i).test($location.path())) { return "active"; } if (name === 'pledge_now' && (/^\/fundraisers\/[a-z-_0-9]+\/pledge$/i).test($location.path())) { return "active"; } }; });
'use strict' /* globals describe it spyOn expect fail */ const pupilDataService = require('../../../services/data-access/pupil.data.service') const pupilMock = require('../mocks/pupil') const pupilAttendanceDataService = require('../../../services/data-access/pupil-attendance.data.service') const redisCacheService = require('../../../services/data-access/redis-cache.service') const service = require('../../../services/attendance.service') describe('attendanceService', () => { describe('#updatePupilAttendanceBySlug', () => { it('just calls the data service', async () => { spyOn(redisCacheService, 'drop') const slugs = ['slug1', 'slug2', 'slug3'] const code = 'ABSNT' const userId = 1 const schoolId = 7 spyOn(pupilAttendanceDataService, 'markAsNotAttending') await service.updatePupilAttendanceBySlug(slugs, code, userId, schoolId) expect(pupilAttendanceDataService.markAsNotAttending).toHaveBeenCalled() }) }) describe('#unsetAttendanceCode', () => { const pupilSlug = 'slug1' const dfeNumber = 9991999 it('makes a call to get the pupil', async () => { spyOn(pupilDataService, 'sqlFindOneBySlugAndSchool').and.returnValue({}) spyOn(pupilAttendanceDataService, 'sqlDeleteOneByPupilId').and.returnValue(Promise.resolve()) spyOn(redisCacheService, 'drop') try { await service.unsetAttendanceCode(pupilSlug, dfeNumber) expect(pupilDataService.sqlFindOneBySlugAndSchool).toHaveBeenCalled() } catch (error) { fail(error.message) } }) it('throws if the pupil is not found', async () => { spyOn(pupilDataService, 'sqlFindOneBySlugAndSchool') spyOn(redisCacheService, 'drop') try { await service.unsetAttendanceCode(pupilSlug, dfeNumber) fail('expected to throw') } catch (error) { expect(error.message).toBe(`Pupil with id ${pupilSlug} and school ${dfeNumber} not found`) } }) it('makes a call to delete the pupilAttendance record if the pupil is found', async () => { spyOn(pupilDataService, 'sqlFindOneBySlugAndSchool').and.returnValue(Promise.resolve(pupilMock)) spyOn(pupilAttendanceDataService, 'sqlDeleteOneByPupilId').and.returnValue() spyOn(redisCacheService, 'drop') await service.unsetAttendanceCode(pupilSlug, dfeNumber) expect(pupilAttendanceDataService.sqlDeleteOneByPupilId).toHaveBeenCalledWith(pupilMock.id) }) }) describe('#hasAttendance', () => { describe('for live env', () => { it('returns valid if pupil has any attendance', async () => { spyOn(pupilAttendanceDataService, 'findOneByPupilId').and.returnValue({ id: 'id', code: 'A' }) const result = await service.hasAttendance('id', 'live') expect(result).toBe(true) }) it('returns invalid if there is no attendance', async () => { spyOn(pupilAttendanceDataService, 'findOneByPupilId').and.returnValue(undefined) const result = await service.hasAttendance('id', 'live') expect(result).toBe(false) }) }) describe('for familiarisation env', () => { it('returns valid if pupil has left school attendance', async () => { spyOn(pupilAttendanceDataService, 'findOneByPupilId').and.returnValue({ id: 'id', code: 'LEFTT' }) const result = await service.hasAttendance('id', 'familiarisation') expect(result).toBe(true) }) it('returns invalid if pupil has other attendance than left school', async () => { spyOn(pupilAttendanceDataService, 'findOneByPupilId').and.returnValue({ id: 'id', code: 'A' }) const result = await service.hasAttendance('id', 'familiarisation') expect(result).toBe(false) }) it('returns invalid if there is no attendance', async () => { spyOn(pupilAttendanceDataService, 'findOneByPupilId').and.returnValue(undefined) const result = await service.hasAttendance('id', 'familiarisation') expect(result).toBe(false) }) }) }) })
"use strict"; const dbHelper = require('../utils/dbhelper.js'); const Stacks = function () { }; /** * Get all the stack * @param done function to call with the results */ Stacks.getAll = function( done ) { dbHelper.getAllFromTable("STACKS" , done ); }; /** * Add a new stack * @param name Name of the stack to add * @param description * @param done Function to call when we have a result * @done function to call with the result */ Stacks.add = function ( name, description, done) { const sql = "INSERT INTO stacks ( name, description ) values ( $1 , $2 ) returning id"; const params = [ name, description ]; dbHelper.insert( sql, params , function( result ) { done( result.rows[0].id ); }, function(error) { console.log(error); done(null , error ); } ); }; /** * Delete a set of stacks using their ID numbers * @param ids * @param done */ Stacks.delete = function (ids, done) { dbHelper.deleteByIds( "STACKS" , ids , done ); }; module.exports = Stacks;
window.addEvent('domready', function() { // Add effect on all the menu boxes, and the ajax request $('test-button').addEvents( { 'click': function(event) { //prevent the page from changing (i.e. following the link) event.stop(); $('test').set('send', {onSuccess: function(responseText, responseXML) {$('result').set('text', responseText);},}); $('test').send(); } }); $('release-button').addEvents( { 'click': function(event) { //prevent the page from changing (i.e. following the link) event.stop(); $('release').set('send', {onSuccess: function(responseText, responseXML) {$('result').set('text', responseText);},}); $('release').send(); } }); });
angular.module('MODULE.SUBMODULE').factory( 'FACTORY_SERVICE', function FACTORY_SERVICEProvider( $log, otherService ) { 'use strict'; var constructor; constructor = function constructor (spec) { var initialize, instanceVar1, instanceVar2, private1, private2, public1, public2; // ----- // PRIVATE // ---------- initialize = function initialize(spec) { // Constructor-like function. instanceVar1 = 42; instanceVar2 = 'foo'; }; private1 = function private1(spec) { // body... }; private2 = function private2(spec) { // body... }; // ----- // PUBLIC // ---------- public1 = function public1(spec) { // body... }; public2 = function public2(spec) { // body... }; destroy = function destroy () { // body... } // ----- // EXECUTE // ---------- initialize(spec); return { public1: public1, public2: public2, destroy: destroy }; } return constructor } ); // Usage angular.module('MODULE.SUBMODULE').contoller( 'CONTROLLER', function SERVICEProvider( FACTORY_SERVICE ) { if (currentObject) { currentObject.destroy(); currentObject = undefined; } currentObject = FACTORY_SERVICE(spec); } );
Joomla 1.5.23 = 9828ab260a60ea25a88b7657c937f666
#!/usr/bin/env node // // Written by Maarten Thibaut. // Released under the GPL. // var argv = require('optimist') .usage('Usage: $0 -f file [-v var]') .demand(['f']) .argv, fs = require('fs'); function parseCsvFile(fileName, callback_data, callback_close){ var stream = fs.createReadStream(fileName) var iteration = 0, header = [], buffer = "" // You may need to change the pattern to suit your needs //var pattern = /(?:^|;)("(?:[^"]+)*"|[^;]*)/g var pattern = /;/g; stream.addListener('close', callback_close); stream.addListener('data', function(data){ //console.log(data.toString()); // Ensure we can handle \r\n as well as \n returns in files buffer+=data.toString().replace('\r\n','\n'); var parts = buffer.split('\n') //console.log("parts: " + parts); parts.forEach(function(d, i){ // Skip empty lines if(d.length) { //console.log("part nr " + i + ": " + d); if(iteration++ == 0 && i == 0){ header = d.split(pattern) }else{ callback_data(buildRecord(d)) } } }) buffer = parts[parts.length-1] }) function buildRecord(str){ //console.log(str); var record = {}; str.split(pattern).forEach(function(value, index){ if(header[index] != '') record[header[index].toLowerCase()] = value.replace(/"/g, '') }) return record } } // Main program, implemented asynchronously var line = 0; var records = []; parseCsvFile(argv.f, function(data) { // called when there is a row of data records[line++] = data; }, function() { // called on close var varname = "", semicolon = ""; if(argv.v) { varname = argv.v + " = "; semicolon = ";"; } console.log(varname + JSON.stringify(records, null, 4) + semicolon); } );
var xhr, xmlDocumentConstructor; module("responding", { setup: function(){ xhr = new FakeXMLHttpRequest(); xmlDocumentConstructor = makeXMLDocument().constructor; }, teardown: function(){ xhr = undefined; xmlDocumentConstructor = undefined; } }); // Different browsers report different constructors for XML Documents. // Chrome 45.0.2454 and Firefox 40.0.0 report `XMLDocument`, // PhantomJS 1.9.8 reports `Document`. // Make a dummy xml document to determine what constructor to // compare against in the tests below. // This function is taken from `parseXML` in the src/ function makeXMLDocument() { var xmlDoc, text = "<some>xml</some>"; if (typeof DOMParser != "undefined") { var parser = new DOMParser(); xmlDoc = parser.parseFromString(text, "text/xml"); } else { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(text); } return xmlDoc; } test("defaults responseHeaders to {} if not passed", function(){ xhr.respond(200); deepEqual(xhr.responseHeaders, {}); }); test("sets responseHeaders", function(){ xhr.respond(200, {"Content-Type":"application/json"}); deepEqual(xhr.responseHeaders, {"Content-Type":"application/json"}); }); test("sets body", function(){ xhr.respond(200, {"Content-Type":"application/json"}, JSON.stringify({a: 'key'})); equal(xhr.responseText, '{"a":"key"}'); }); test("parses the body if it's XML and no content-type is set", function(){ xhr.respond(200, {}, "<key>value</key>"); equal(xhr.responseXML.constructor, xmlDocumentConstructor); }); test("parses the body if it's XML and xml content type is set", function(){ xhr.respond(200, {'Content-Type':'application/xml'}, "<key>value</key>"); equal(xhr.responseXML.constructor, xmlDocumentConstructor); }); test("does not parse the body if it's XML and another content type is set", function(){ xhr.respond(200, {'Content-Type':'application/json'}, "<key>value</key>"); equal(xhr.responseXML, undefined); }); test("calls the onload callback once", function(){ var wasCalled = 0; xhr.onload = function(ev){ wasCalled += 1; }; xhr.respond(200, {}, ""); strictEqual(wasCalled, 1); }); test("calls onreadystatechange for each state change", function() { var states = []; xhr.onreadystatechange = function() { states.push(this.readyState); }; xhr.open('get', '/some/url'); xhr.respond(200, {}, ""); var expectedStates = [ FakeXMLHttpRequest.OPENED, FakeXMLHttpRequest.HEADERS_RECEIVED, FakeXMLHttpRequest.LOADING, FakeXMLHttpRequest.DONE ]; deepEqual(states, expectedStates); }); test("passes event to onreadystatechange", function() { var event = null; xhr.onreadystatechange = function(e) { event = e; }; xhr.open('get', '/some/url'); xhr.respond(200, {}, ""); ok(event && event.type === 'readystatechange', 'passes event with type "readystatechange"'); }); test("overrideMimeType overrides content-type responseHeader", function(){ xhr.overrideMimeType('text/plain'); xhr.respond(200, {"Content-Type":"application/json"}); deepEqual(xhr.responseHeaders, {"Content-Type":"text/plain"}); }); test("parses the body if it's XML and overrideMimeType is set to xml", function(){ xhr.overrideMimeType('application/xml'); xhr.respond(200, {'Content-Type':'text/plain'}, "<key>value</key>"); equal(xhr.responseXML.constructor, xmlDocumentConstructor); }); test("does not parse the body if it's XML and overrideMimeType is set to another content type", function(){ xhr.overrideMimeType('text/plain'); xhr.respond(200, {'Content-Type':'application/xml'}, "<key>value</key>"); equal(xhr.responseXML, undefined); });
/** * $Id: editor_plugin_src.js,v 1.1 2012/04/05 12:12:25 simoneAdm Exp $ * * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. */ (function() { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, explode = tinymce.explode; tinymce.create('tinymce.plugins.TabFocusPlugin', { init : function(ed, url) { function tabCancel(ed, e) { if (e.keyCode === 9) return Event.cancel(e); }; function tabHandler(ed, e) { var x, i, f, el, v; function find(d) { f = DOM.getParent(ed.id, 'form'); el = f.elements; if (f) { each(el, function(e, i) { if (e.id == ed.id) { x = i; return false; } }); if (d > 0) { for (i = x + 1; i < el.length; i++) { if (el[i].type != 'hidden') return el[i]; } } else { for (i = x - 1; i >= 0; i--) { if (el[i].type != 'hidden') return el[i]; } } } return null; }; if (e.keyCode === 9) { v = explode(ed.getParam('tab_focus', ed.getParam('tabfocus_elements', ':prev,:next'))); if (v.length == 1) { v[1] = v[0]; v[0] = ':prev'; } // Find element to focus if (e.shiftKey) { if (v[0] == ':prev') el = find(-1); else el = DOM.get(v[0]); } else { if (v[1] == ':next') el = find(1); else el = DOM.get(v[1]); } if (el) { if (ed = tinymce.EditorManager.get(el.id || el.name)) ed.focus(); else window.setTimeout(function() {window.focus();el.focus();}, 10); return Event.cancel(e); } } }; ed.onKeyUp.add(tabCancel); if (tinymce.isGecko) { ed.onKeyPress.add(tabHandler); ed.onKeyDown.add(tabCancel); } else ed.onKeyDown.add(tabHandler); ed.onInit.add(function() { each(DOM.select('a:first,a:last', ed.getContainer()), function(n) { Event.add(n, 'focus', function() {ed.focus();}); }); }); }, getInfo : function() { return { longname : 'Tabfocus', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/tabfocus', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('tabfocus', tinymce.plugins.TabFocusPlugin); })();
const StitchMongoFixture = require('../fixtures/stitch_mongo_fixture'); import {getAuthenticatedClient} from '../testutil'; describe('Values V2', ()=>{ let test = new StitchMongoFixture(); let apps; let app; beforeAll(() => test.setup({createApp: false})); afterAll(() => test.teardown()); beforeEach(async () =>{ let adminClient = await getAuthenticatedClient(test.userData.apiKey.key); test.groupId = test.userData.group.groupId; apps = await adminClient.v2().apps(test.groupId); app = await apps.create({name: 'testname'}); appValues = adminClient.v2().apps(test.groupId).app(app._id).values(); }); afterEach(async () => { await apps.app(app._id).remove(); }); let appValues; const testValueName = 'testvaluename'; it('listing values should return empty list', async () => { let values = await appValues.list(); expect(values).toEqual([]); }); it('creating value should make it appear in list', async () => { let value = await appValues.create({name: testValueName}); expect(value.name).toEqual(testValueName); let values = await appValues.list(); expect(values).toHaveLength(1); expect(values[0]).toEqual(value); }); it('fetching a value returns deep value data', async () => { let value = await appValues.create({name: testValueName, value: 'foo'}); const deepValue = await appValues.value(value._id).get(); expect(deepValue.value).toEqual('foo'); delete deepValue.value; expect(value).toEqual(deepValue); }); it('can update a value', async () => { let value = await appValues.create({name: testValueName, value: 'foo'}); value.value = '"abcdefgh"'; await appValues.value(value._id).update(value); const deepValue = await appValues.value(value._id).get(); expect(deepValue.value).toEqual('"abcdefgh"'); }); it('can delete a value', async () => { let value = await appValues.create({name: testValueName}); expect(value.name).toEqual(testValueName); let values = await appValues.list(); expect(values).toHaveLength(1); await appValues.value(value._id).remove(); values = await appValues.list(); expect(values).toHaveLength(0); }); });
var __v=[ { "Id": 2478, "Panel": 1245, "Name": "number", "Sort": 0, "Str": "" } ]
/* global salesReporterFactory, dataLoaderFactory, dataSourceAccessFactory, pointOfSaleDataUtilsFactoryBuilder, reportDataBuilderFactory */ // eslint-disable-next-line function getSalesReporter() { const dataSourceAccess = dataSourceAccessFactory(); const dataLoader = dataLoaderFactory(dataSourceAccess); const pointOfSaleDataUtilsFactory = pointOfSaleDataUtilsFactoryBuilder(); const reportDataBuilder = reportDataBuilderFactory(); return salesReporterFactory( dataLoader, pointOfSaleDataUtilsFactory, reportDataBuilder ); }
import transitionable from 'consul-ui/utils/routing/transitionable'; import { module, test } from 'qunit'; const makeRoute = function(name, params = {}, parent) { return { name: name, paramNames: Object.keys(params), params: params, parent: parent, }; }; module('Unit | Utility | routing/transitionable', function() { test('it walks up the route tree to resolve all the required parameters', function(assert) { const expected = ['dc.service.instance', 'dc-1', 'service-0', 'node-0', 'service-instance-0']; const dc = makeRoute('dc', { dc: 'dc-1' }); const service = makeRoute('dc.service', { service: 'service-0' }, dc); const instance = makeRoute( 'dc.service.instance', { node: 'node-0', id: 'service-instance-0' }, service ); const actual = transitionable(instance, {}); assert.deepEqual(actual, expected); }); test('it walks up the route tree to resolve all the required parameters whilst replacing specified params', function(assert) { const expected = [ 'dc.service.instance', 'dc-1', 'service-0', 'different-node', 'service-instance-0', ]; const dc = makeRoute('dc', { dc: 'dc-1' }); const service = makeRoute('dc.service', { service: 'service-0' }, dc); const instance = makeRoute( 'dc.service.instance', { node: 'node-0', id: 'service-instance-0' }, service ); const actual = transitionable(instance, { node: 'different-node' }); assert.deepEqual(actual, expected); }); });
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ (function() { 'use strict'; var client = Mozilla.Client; var form = new Mozilla.SendYourself('download-firefox-rocket'); form.init(); function checkUpToDate() { // bug 1419573 - only show "Your Firefox is up to date" if it's the latest version. if (client.isFirefoxDesktop) { client.getFirefoxDetails(function(data) { if (data.isUpToDate) { document.querySelector('.c-page-header').classList.add('show-up-to-date-message'); } }); } } Mozilla.UITour.ping(function() { checkUpToDate(); }); })();
// META: script=/resources/testdriver.js // META: script=/resources/testdriver-vendor.js // META: script=/bluetooth/resources/bluetooth-helpers.js 'use strict'; const test_desc = 'multiple calls to getDevices() resolves with the same' + 'BluetoothDevice objects for each granted Bluetooth device.'; bluetooth_test(async () => { await getConnectedHealthThermometerDevice(); let firstDevices = await navigator.bluetooth.getDevices(); assert_equals( firstDevices.length, 1, 'getDevices() should return the granted device.'); let secondDevices = await navigator.bluetooth.getDevices(); assert_equals( secondDevices.length, 1, 'getDevices() should return the granted device.'); assert_equals( firstDevices[0], secondDevices[0], 'getDevices() should produce the same BluetoothDevice objects for a ' + 'given Bluetooth device.'); }, test_desc);
importScript([ '../modevlib/main.js', '../modevlib/Dimension-Bugzilla.js', "../modevlib/Dimension-Tracked.js", "../js/grid.js", "../modevlib/gui/accordion.js", "../modevlib/gui/dynamic.js", "../modevlib/gui/aColor.js", "blockerCharts.js", "nominationCharts.js", "regressionCharts.js", "blockers.css" ]);
const Cu = Components.utils; const {devtools} = Cu.import("resource://gre/modules/devtools/Loader.jsm", {}); const {require} = devtools; const {installHosted, installPackaged} = require("devtools/app-actor-front"); Cu.import("resource://gre/modules/devtools/dbg-server.jsm"); Cu.import("resource://gre/modules/devtools/dbg-client.jsm"); let gClient, gActor; let gAppId = "actor-test"; let onDone = function () { installPackaged(gClient, gActor, "/data/local/app.zip", gAppId) .then(function ({ appId }) { gClient.close(); marionetteScriptFinished("finished"); }, function (e) { gClient.close(); marionetteScriptFinished("Failed install uploaded packaged app: " + e.error + ": " + e.message); }); }; let connect = function(onDone) { // Initialize a loopback remote protocol connection if (!DebuggerServer.initialized) { DebuggerServer.init(function () { return true; }); // We need to register browser actors to have `listTabs` working // and also have a root actor DebuggerServer.addBrowserActors(); } // Setup the debugger client gClient = new DebuggerClient(DebuggerServer.connectPipe()); gClient.connect(function onConnect() { gClient.listTabs(function onListTabs(aResponse) { gActor = aResponse.webappsActor; onDone(); }); }); }; connect(onDone);
function (user, context, callback) { // /!\ DO NOT EDIT THIS FILE /!\ // Please use http://github.com/mozilla-iam/auth0-rules instead var WHITELIST = [ 'moc-sso-monitoring@mozilla.com', // MOC see https://bugzilla.mozilla.org/show_bug.cgi?id=1423903 'moc+servicenow@mozilla.com' // MOC see https://bugzilla.mozilla.org/show_bug.cgi?id=1423903 ]; if (!user.email_verified) { console.log('duosecurity: user primary email NOT verified, refusing login for '+user.email); return callback(null, user, global.postError('notingroup', context)); } if (WHITELIST.indexOf(user.email) >= 0) { console.log('duosecurity: whitelisted account '+user.email+', no 2FA check performed'); // Fake 2FA context.multifactor = true; return callback(null, user, context); } // Any user logging in with LDAP (ad) requires MFA authentication. if (context.connectionStrategy === 'ad') { context.multifactor = { provider: 'duo', ikey: configuration.duo_ikey_mozilla, skey: configuration.duo_skey_mozilla, host: configuration.duo_apihost_mozilla, // optional: // Force DuoSecurity everytime this rule runs. Defaults to false. // If accepted by users the cookie lasts for 30 days - i.e. 30 days MFA session (this cannot be changed) ignoreCookie: false, username: user.email, }; } callback(null, user, context); }
/* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ /* * The list of phases mapped to their corresponding profiles. The object * here must be in strict JSON format, as it will get parsed by the Python * testrunner (no single quotes, extra comma's, etc). */ EnableEngines(["history"]); var phases = { "phase1": "profile1", "phase2": "profile2" }; /* * History asset lists: these define history entries that are used during * the test */ // the initial list of history items to add to the browser var history1 = [ { uri: "http://www.google.com/", title: "Google", visits: [ { type: 1, date: 0 }, { type: 2, date: -1 } ] }, { uri: "http://www.cnn.com/", title: "CNN", visits: [ { type: 1, date: -1 }, { type: 2, date: -36 } ] }, { uri: "http://www.google.com/language_tools?hl=en", title: "Language Tools", visits: [ { type: 1, date: 0 }, { type: 2, date: -40 } ] }, { uri: "http://www.mozilla.com/", title: "Mozilla", visits: [ { type: 1, date: 0 }, { type: 1, date: -1 }, { type: 1, date: -20 }, { type: 2, date: -36 } ] } ]; // a list of items to delete from the history var history_to_delete = [ { uri: "http://www.cnn.com/" }, { begin: -24, end: -1 }, { host: "www.google.com" } ]; // a list which reflects items that should be in the history after // the above items are deleted var history2 = [ { uri: "http://www.mozilla.com/", title: "Mozilla", visits: [ { type: 1, date: 0 }, { type: 2, date: -36 } ] } ]; // a list which includes history entries that should not be present // after deletion of the history_to_delete entries var history_not = [ { uri: "http://www.google.com/", title: "Google", visits: [ { type: 1, date: 0 }, { type: 2, date: -1 } ] }, { uri: "http://www.cnn.com/", title: "CNN", visits: [ { type: 1, date: -1 }, { type: 2, date: -36 } ] }, { uri: "http://www.google.com/language_tools?hl=en", title: "Language Tools", visits: [ { type: 1, date: 0 }, { type: 2, date: -40 } ] }, { uri: "http://www.mozilla.com/", title: "Mozilla", visits: [ { type: 1, date: -1 }, { type: 1, date: -20 } ] } ]; /* * Test phases * Note: there is no test phase in which deleted history entries are * synced to other clients. This functionality is not supported by * Sync, see bug 446517. */ Phase("phase1", [ [History.add, history1], [Sync], ]); Phase("phase2", [ [Sync], [History.verify, history1], [History.delete, history_to_delete], [History.verify, history2], [History.verifyNot, history_not], [Sync] ]);
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * * Date: 03 June 2002 * SUMMARY: Function param or local var with same name as a function property * * See http://bugzilla.mozilla.org/show_bug.cgi?id=137000 * See http://bugzilla.mozilla.org/show_bug.cgi?id=138708 * See http://bugzilla.mozilla.org/show_bug.cgi?id=150032 * See http://bugzilla.mozilla.org/show_bug.cgi?id=150859 * */ //----------------------------------------------------------------------------- var gTestfile = 'regress-137000.js'; var UBound = 0; var BUGNUMBER = 137000; var summary = 'Function param or local var with same name as a function prop'; var status = ''; var statusitems = []; var actual = ''; var actualvalues = []; var expect= ''; var expectedvalues = []; /* * Note use of 'x' both for the parameter to f, * and as a property name for |f| as an object */ function f(x) { } status = inSection(1); f.x = 12; actual = f.x; expect = 12; addThis(); /* * A more elaborate example, using the call() method * to chain constructors from child to parent. * * The key point is the use of the same name 'p' for both * the parameter to the constructor, and as a property name */ function parentObject(p) { this.p = 1; } function childObject() { parentObject.call(this); } childObject.prototype = parentObject; status = inSection(2); var objParent = new parentObject(); actual = objParent.p; expect = 1; addThis(); status = inSection(3); var objChild = new childObject(); actual = objChild.p; expect = 1; addThis(); /* * A similar set-up. Here the same name is being used for * the parameter to both the Base and Child constructors, */ function Base(id) { } function Child(id) { this.prop = id; } Child.prototype=Base; status = inSection(4); var c1 = new Child('child1'); actual = c1.prop; expect = 'child1'; addThis(); /* * Use same identifier as a property name, too - */ function BaseX(id) { } function ChildX(id) { this.id = id; } ChildX.prototype=BaseX; status = inSection(5); c1 = new ChildX('child1'); actual = c1.id; expect = 'child1'; addThis(); /* * From http://bugzilla.mozilla.org/show_bug.cgi?id=150032 * * Here the same name is being used both for a local variable * declared in g(), and as a property name for |g| as an object */ function g() { var propA = g.propA; var propB = g.propC; this.getVarA = function() {return propA;} this.getVarB = function() {return propB;} } g.propA = 'A'; g.propB = 'B'; g.propC = 'C'; var obj = new g(); status = inSection(6); actual = obj.getVarA(); // this one was returning 'undefined' expect = 'A'; addThis(); status = inSection(7); actual = obj.getVarB(); // this one is easy; it never failed expect = 'C'; addThis(); /* * By martin.honnen@gmx.de * From http://bugzilla.mozilla.org/show_bug.cgi?id=150859 * * Here the same name is being used for a local var in F * and as a property name for |F| as an object * * Twist: the property is added via another function. */ function setFProperty(val) { F.propA = val; } function F() { var propA = 'Local variable in F'; } status = inSection(8); setFProperty('Hello'); actual = F.propA; // this was returning 'undefined' expect = 'Hello'; addThis(); //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function addThis() { statusitems[UBound] = status; actualvalues[UBound] = actual; expectedvalues[UBound] = expect; UBound++; } function test() { enterFunc('test'); printBugNumber(BUGNUMBER); printStatus(summary); for (var i=0; i<UBound; i++) { reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]); } exitFunc ('test'); }
importScripts('sw-helpers.js'); async function getFetchResult(record) { response = await record.responseReady; if (!response) return Promise.resolve(null); return { url: response.url, status: response.status, text: await response.text(), }; } self.addEventListener('backgroundfetchsuccess', event => { event.waitUntil( event.registration.matchAll() .then(records => Promise.all(records.map(record => getFetchResult(record)))) .then(results => { const registrationCopy = cloneRegistration(event.registration); sendMessageToDocument({ type: event.type, eventRegistration: registrationCopy, results }) })); });
const getEngineName = (engine) => { switch (engine) { case 'electron': { return 'Electron'; } case 'firefox': { return 'Mozilla Firefox'; } case 'chromium': { return 'Chromium'; } case 'chrome': { return 'Google Chrome'; } case 'brave': { return 'Brave'; } case 'vivaldi': { return 'Vivaldi'; } case 'edge': { return 'Microsoft Edge'; } default: { throw new Error('Engine is not supported'); } } }; export default getEngineName;
linguas.directive('bunchRow', ['$window', 'TranslationService', function ($window, TranslationService) { return { restrict: 'AE', replace: true, scope: { bunch: '=bunch' }, templateUrl: 'app/features/translation-bunch/bunch-row/bunch-row.html', controller: function ($scope) { } }; }]);
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Snackbar from 'material-ui/Snackbar'; import { Route } from 'react-router'; import { store } from '..'; import { isConfigLoaded, getConfig } from '../modules/config'; import AppBar from './AppBar'; import Dashboard from './Dashboard'; import Drawer from './Drawer'; import FailureDialog from './FailureDialog'; import ItemEditor from './ItemEditor'; import Loans from './Loans'; import MainView from './MainView'; import Places from './Places'; import Settings from './Settings'; import SpeedDial from './SpeedDial'; import StuffList from './StuffList'; import Team from './Team'; import timings from '../styles/timings'; import User from './User'; class App extends React.Component { static propTypes = { failed: PropTypes.bool, snackbarMessage: PropTypes.string, getConfig: PropTypes.func.isRequired, } static defaultProps = { failed: false, snackbarMessage: '', } componentDidMount = () => { if (!isConfigLoaded(store.getState())) { this.props.getConfig(); } } render() { const { failed, snackbarMessage } = this.props; if (failed) { return <FailureDialog />; } else { return ( <div> <AppBar /> <Drawer /> <MainView> <Route path="/" component={Dashboard} /> <Route path="/stuff" component={StuffList} /> <Route path="/stuff/:itemSlug" component={ItemEditor} /> <Route path="/places" component={Places} /> <Route path="/loans" component={Loans} /> <Route path="/settings" component={Settings} /> <Route path="/user" component={User} /> <Route path="/team" component={Team} /> </MainView> <SpeedDial /> {snackbarMessage ? ( <Snackbar open message={snackbarMessage} autoHideDuration={timings.snackbarCloseTimeout} /> ) : null} </div> ); } } } export default connect( state => ({ failed: state.tallessa.getIn(['config', 'failed']), snackbarMessage: state.tallessa.getIn(['ui', 'snackbar']), }), { getConfig, }, )(App);
var clover = new Object(); // JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]} clover.pageData = {"classes":[{"el":54,"id":84685,"methods":[{"el":40,"sc":2,"sl":38},{"el":45,"sc":2,"sl":42},{"el":52,"sc":2,"sl":47}],"name":"EscapeHTML","sl":33}]} // JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...}; clover.testTargets = {} // JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]}; clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
/** * app.js * * Use `app.js` to run your app without `sails lift`. * To start the server, run: `node app.js`. * * This is handy in situations where the sails CLI is not relevant or useful. * * For example: * => `node app.js` * => `forever start app.js` * => `node debug app.js` * => `modulus deploy` * => `heroku scale` * * * The same command-line arguments are supported, e.g.: * `node app.js --silent --port=80 --prod` */ // Ensure we're in the project directory, so relative paths work as expected // no matter where we actually lift from. process.chdir(__dirname); // Ensure a "sails" can be located: (function() { var sails; try { sails = require('sails'); } catch (e) { console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.'); console.error('To do that, run `npm install sails`'); console.error(''); console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.'); console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,'); console.error('but if it doesn\'t, the app will run with the global sails instead!'); return; } // Try to get `rc` dependency var rc; try { rc = require('rc'); } catch (e0) { try { rc = require('sails/node_modules/rc'); } catch (e1) { console.error('Could not find dependency: `rc`.'); console.error('Your `.sailsrc` file(s) will be ignored.'); console.error('To resolve this, run:'); console.error('npm install rc --save'); rc = function () { return {}; }; } } // Start server sails.lift(rc('sails')); })();
export const divides = (y) => (x) => y % x === 0; export const divisible = (y) => (x) => x % y === 0;
'use strict'; var REGEXP = /^(.+)\s+(.+)$/ function parser(str) { var deps = str.replace(/(\#(.*))/g, '').split("\n").reduce( (accum, line) => { var match = line.match(REGEXP); if (!match) return accum; let name = match[1].trim(), version = match[2].trim() accum.push({ name: name, version: version || '*', type: 'runtime' }); return accum; }, []); return deps; } module.exports = parser;
import validatePostData from './validatePostData' describe('validatePostData', () => { var user, inGroup, notInGroup before(function () { inGroup = new Group({slug: 'foo', name: 'Foo', group_data_type: 1 }) notInGroup = new Group({slug: 'bar', name: 'Bar', group_data_type: 1 }) user = new User({name: 'Cat', email: 'a@b.c'}) return Promise.join( inGroup.save(), notInGroup.save(), user.save() ).then(function () { return user.joinGroup(inGroup) }) }) it('fails if no name is provided', () => { const fn = () => validatePostData(null, {}) expect(fn).to.throw(/title can't be blank/) }) it('fails if an invalid type is provided', () => { const fn = () => validatePostData(null, {name: 't', type: 'thread'}) expect(fn).to.throw(/not a valid type/) }) it('fails if no group_ids are provided', () => { const fn = () => validatePostData(null, {name: 't'}) expect(fn).to.throw(/no communities specified/) }) it('fails if there is a group_id for a group user is not a member of', () => { const data = {name: 't', group_ids: [inGroup.id, notInGroup.id]} return validatePostData(user.id, data) .catch(function (e) { expect(e.message).to.match(/unable to post to all those communities/) }) }) it('fails if a blank name is provided', () => { const fn = () => validatePostData(null, {name: ' ', group_ids: [inGroup.id]}) expect(fn).to.throw(/title can't be blank/) }) it('fails if there are more than 3 topicNames', () => { const fn = () => validatePostData(null, { name: 't', group_ids: [inGroup.id], topicNames: ['la', 'ra', 'bar', 'far']}) expect(fn).to.throw(/too many topics in post, maximum 3/) }) it('continues the promise chain if name is provided and user is member of communities', () => { const data = {name: 't', group_ids: [inGroup.id]} return validatePostData(user.id, data) .catch(() => expect.fail('should resolve')) }) it('continues the promise chain if valid type is provided', () => { const data = {name: 't', type: Post.Type.PROJECT, group_ids: [inGroup.id]} return validatePostData(user.id, data) .catch(() => expect.fail('should resolve')) }) })
/** * This file is part of Superdesk. * * Copyright 2015 Sourcefabric z.u. and contributors. * * For the full copyright and license information, please see the * AUTHORS and LICENSE files distributed with this source code, or * at https://www.sourcefabric.org/superdesk/license */ (function() { 'use strict'; WorkqueueService.$inject = ['session', 'api']; function WorkqueueService(session, api) { this.items = []; /** * Get all items locked by current user */ this.fetch = function() { return session.getIdentity() .then(angular.bind(this, function(identity) { return api.query('archive', {source: {filter: {term: {lock_user: identity._id}}}}) .then(angular.bind(this, function(res) { this.items = null; this.items = res._items || []; return this.items; })); })); }; /** * Update given item */ this.updateItem = function(itemId) { var old = _.find(this.items, {_id: itemId}); if (old) { return api.find('archive', itemId).then(function(item) { return angular.extend(old, item); }); } }; } WorkqueueCtrl.$inject = ['$scope', '$route', 'workqueue', 'authoringWorkspace', 'multiEdit', 'superdesk', 'lock', '$location']; function WorkqueueCtrl($scope, $route, workqueue, authoringWorkspace, multiEdit, superdesk, lock, $location) { $scope.active = null; $scope.workqueue = workqueue; $scope.multiEdit = multiEdit; $scope.$on('item:lock', updateWorkqueue); $scope.$on('item:unlock', updateWorkqueue); $scope.$on('media_archive', function(e, data) { workqueue.updateItem(data.item); }); updateWorkqueue(); /** * Update list of opened items and set one active if its id is in current route path. */ function updateWorkqueue() { workqueue.fetch().then(function() { var route = $route.current || {_id: null, params: {}}; $scope.isMultiedit = route._id === 'multiedit'; $scope.active = null; if (route.params.item) { $scope.active = _.find(workqueue.items, {_id: route.params.item}); } }); } $scope.openDashboard = function() { superdesk.intent('author', 'dashboard'); }; /** * Closes item. If item is opened, close authoring workspace. * Updates multiedit items, if item is part of multiedit. * When closing last item that was in multiedit(no more items in multiedit), redirects to monitoring. */ $scope.closeItem = function(item) { lock.unlock(item); if (authoringWorkspace.item && item._id === authoringWorkspace.item._id){ authoringWorkspace.close(); } multiEdit.items = _.without(multiEdit.items, _.find(multiEdit.items, {article: item._id})); if (multiEdit.items.length === 0){ $scope.redirectOnCloseMulti(); } }; $scope.openMulti = function() { $scope.isMultiedit = true; multiEdit.open(); }; /** * Close multiedit and all items that were in multiedit. */ $scope.closeMulti = function() { multiEdit.exit(); _.forEach(multiEdit.items, function(item) { lock.unlock(_.find(workqueue.items, {_id: item.article})); }); $scope.redirectOnCloseMulti(); }; /** * If multi edit screen is opened, redirect to monitoring. */ $scope.redirectOnCloseMulti = function() { if (this.isMultiedit){ this.isMultiedit = false; $location.url('/workspace/monitoring'); } }; } WorkqueueListDirective.$inject = ['$rootScope', 'authoringWorkspace', '$location']; function WorkqueueListDirective($rootScope, authoringWorkspace, $location) { return { templateUrl: 'scripts/superdesk-authoring/views/opened-articles.html', controller: 'Workqueue', scope: {}, link: function(scope) { scope.edit = function(item, event) { if (!event.ctrlKey) { scope.active = item; authoringWorkspace.edit(item); scope.redirectOnCloseMulti(); event.preventDefault(); } }; scope.link = function(item) { if (item) { return $rootScope.link('authoring', item); } }; } }; } function ArticleDashboardDirective() { return { templateUrl: 'scripts/superdesk-authoring/views/dashboard-articles.html', controller: 'Workqueue' }; } angular.module('superdesk.authoring.workqueue', [ 'superdesk.activity', 'superdesk.notification', 'superdesk.authoring.multiedit' ]) .service('workqueue', WorkqueueService) .controller('Workqueue', WorkqueueCtrl) .directive('sdWorkqueue', WorkqueueListDirective) .directive('sdDashboardArticles', ArticleDashboardDirective); })();
/* Unused, experimental code for adding project locations via * clickable google map_ */ var markers_position = []; var map; var geocoder = new google.maps.Geocoder(); var first = true; $(document).ready( function() { //change geolocate input value $('div.outer_map form input[type="text"]').focusin(function(ev){ if ($(this).attr('value')=="Location, latitude or longitude") { $(this).attr('value',''); } }); $('div.outer_map form input[type="text"]').focusout(function(ev){ if ($(this).attr('value')=="") { $(this).attr('value','Location, latitude or longitude'); } }); $('a#add_location_map').click(function(ev){ ev.preventDefault(); ev.stopPropagation(); markers_position = []; var position = $(this).offset(); $('div.map_window').css('top',position.top-310+'px'); $('div.map_window').css('left',position.left-140+'px'); $('div.map_window').fadeIn(function(){ var myOptions = { zoom: 1, center: new google.maps.LatLng(30, 0), disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map"),myOptions); var image = new google.maps.MarkerImage('/images/backoffice/projects/project_marker.png',new google.maps.Size(34, 42),new google.maps.Point(0,0), new google.maps.Point(17, 42)); google.maps.event.addListener(map,"click",function(event){ var marker = new google.maps.Marker({position: event.latLng, map:map, icon:image}); markers_position.push(event.latLng); }); $('#project_coordinates li input').each(function(){ var point = $(this).attr('value').replace(/\(/,'').replace(/\)/,'').split(', '); var position = new google.maps.LatLng(point[0],point[1]); var marker = new google.maps.Marker({position: position, map:map, icon:image}); markers_position.push(position); }); }); $(window).resize(function() { var position = $('a#add_location_map').position(); $('div.map_window').css('top',position.top+'px'); $('div.map_window').css('left',position.left+'px'); }); }); $('a.close').live('click', function(){ var li = $(this).closest('li') var point = li.children('input').attr('value'); li.remove(); for(var i=0;i<markers_position.length;i++){ if (point == markers_position[i]) { markers_position.splice(i); } } $(window).unbind('resize'); $('div.map_window').fadeOut(); return false; }); $('a.save').click(function(e){ $('#project_coordinates li').each(function(){ $(this).remove(); }); for(var i=0;i<markers_position.length;i++){ $('#project_coordinates').append('<li><p>'+markers_position[i]+'</p><input type="hidden" name="project[points][]" value="'+markers_position[i]+'" /><a href="javascript:void(null)" class="close"></a></li>'); } $(window).unbind('resize'); $('div.map_window').fadeOut(); }); }); function searchPlace() { var address = $('div.outer_map form input[type="text"]').attr('value'); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.fitBounds(results[0].geometry.bounds); } }); }
import _ from 'lodash' import Joi from 'joi' import { findOrCreateUserByProfile } from '../user-service' import request from 'request-promise' const schema = Joi.object({ clientId: Joi.string().required(), clientSecret: Joi.string().required(), }).required() exports.register = function (server, options, next) { Joi.assert(options, schema) const cookieConfig = _.get(server, 'connections[0].states.settings') server.auth.strategy('facebook', 'bell', { provider: 'facebook', clientId: options.clientId, clientSecret: options.clientSecret, location: server.info.uri, isSecure: cookieConfig.isSecure, password: cookieConfig.password, ttl: cookieConfig.ttl, }) server.route({ method: 'GET', path: '/auth/facebook', config: { auth: 'facebook', handler: authFacebook, }, }) next() } exports.register.attributes = { name: 'facebook', } function authFacebook(req, reply) { const creds = req.auth.credentials.profile const options = { uri: `https://graph.facebook.com/${creds.id}/picture?width=250&height=250`, resolveWithFullResponse: true, } request.get(options) .then((response) => { const profile = { name: creds.displayName, email: creds.email, avatarUrl: response.request.uri.href, oAuthId: creds.id, oAuthProvider: 'facebook', } return findOrCreateUserByProfile(profile) }) .then((token) => { reply() .state('token', token, { path: '/' }) .redirect('/') }) .catch(reply) }
//var socket = io.connect('http://localhost:8081'); //////////////////////////////////////////////////////////////Player design////////////////////////////////////////////////////////////// //$("#player_detect").css({ 'position': 'absolute','z-index': '10', 'background-color': 'green','height': '1.5%', 'width': '1%','left': '10','top':'10' }); //$("#player_div").css({ 'position': 'absolute','z-index': '0','overflow': 'hidden','opacity': '0.3', 'background-color': '','height': CviewY, 'width': CviewX }); //$(".detect").css({ 'position': 'absolute','opacity': '0.3', 'height': '25%', 'width': '25%' }); ///////////////////////////////////////////////////////////////////////Debug///////////////////////////////////////////////////////////////////// var interval = setInterval(function() { updateMovement(); var socket = io.connect('http://localhost:8081'); $("#container").css({ 'position': 'absolute','z-index':'-10', 'background-color': '','height': gameBGResCX, 'width': gameBGResCY,'left': '0%','top':'0%' }); $("#cenario").css({ 'opacity':'0.3','z-index':'3','position': 'absolute','background-image': 'url("'+floorbackimg+'")','background-size': '100% 100%','height': gameBGResCX, 'width': gameBGResCY,'box-sizing': 'border-box','border:': '2px solid red' }); ////////////////////////////////////////////////////////////////Minimap/////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var player = $('#player_detect'); var camera = $('#player_div'); newPos = new Object(); newPos.left = -camera.offset().left; newPos.top = -camera.offset().top; newPos.left = -camera.offset().left; newPos.top = -camera.offset().top; $("#container").offset(newPos); function terminal() { // var socket = io.connect('http://localhost:8081'); var cene = $('#cene'); var playerdiv = $('#player_detect'); // var camera = $('#player_div'); var cene = $('#cene'); var x = cene.offset().left; var y = cene.offset().top; ///////////////////////position feedback///////////////////// //var cord = {x, y}; //socket.emit('CORD', cord, function (data) {}); // both X and X feedback //socket.emit('X', x, function (data) {}); // X feedback //socket.emit('Y', y, function (data) {}); // Y feedback }; terminal(); }, refreshScreen); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var l_cache = SR.State.get('cache'); // language setting var l_lang = require('./language')('english'); SR.Callback.onStart(function () { }); var l_form = SR.State.get('FlexFormMap'); var l_accounts; SR.Callback.onStart(function () { l_form = SR.State.get('FlexFormMap'); l_accounts = SR.State.get('_accountMap'); // check if our form exists or create one if not LOG.warn('l_form size: ' + Object.keys(l_form).length); }); // get session value based on request object's cookie // TODO: make this SR function? var l_getSession = function (req) { var cookie = SR.REST.getCookie(req.headers.cookie); var session = SR.EventManager.getSession(cookie); return session; }; // pass in request object, returns session data if logined, otherwise returns null var l_checkLogin = function (req) { var session = l_getSession(req); if (session.hasOwnProperty('_user')) { var login = session._user; login.admin = (session._user.account === 'admin'); return login; } LOG.warn('user not yet logined...'); return {control: {groups: [], permissions: []}}; }; module.exports = function (app) { // CORS header app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); app.get('/api/menu', (req, res) => { const menu = [ { "path": "/", "redirect": "/dashboard", "name": "Home", "hidden": true, "children": [ { "path": "dashboard" } ] }, { "path": "/device", "redirect": "/device", "name": "Device Manege", "meta": { "title": "device", "icon": "device" }, "children": [ { "path": "create", "name": "create device", "type": "create", "meta": { "title": "create device", "icon": "device" } }, { "path": "list", "name": "list device", "type": "list", "meta": { "title": "list", "icon": "edit" } } ] }, { "path": "external-link", "children": [ { "path": "https://www.google.com/", "meta": { "title": "External Link", "icon": "link" } } ] } ]; res.send(menu); }); };
// rhino.js // 2009-09-11 /* Copyright (c) 2002 Douglas Crockford (www.JSLint.com) Rhino Edition */ // This is the Rhino companion to fulljslint.js. /*global JSLINT */ /*jslint rhino: true, strict: false */ (function (a) { var e, i, input; if (!a[0]) { print("Usage: jslint.js file.js"); quit(1); } input = readFile(a[0]); if (!input) { print("jslint: Couldn't open file '" + a[0] + "'."); quit(1); } if (!JSLINT(input, {bitwise: true, eqeqeq: true, immed: true, newcap: true, nomen: true, onevar: false, plusplus: false, regexp: true, rhino: true, undef: false, white: false, 'continue': true})) { for (i = 0; i < JSLINT.errors.length; i += 1) { e = JSLINT.errors[i]; if (e) { print('Lint at line ' + e.line + ' character ' + e.character + ': ' + e.reason); print((e.evidence || ''). replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1")); print(''); } } quit(2); } else { print("jslint: No problems found in " + a[0]); quit(); } }(arguments));
jQuery(document).ready(function() { jQuery('ul:checkboxList("reservation, reservation_has_user_list")').addFilter(); jQuery.fn.inval = function(options) { var defaults = { attribute: 'id', expr: '' }; var opts = jQuery.extend(defaults, options); var result = $(this).attr(opts.attribute); result = result.replace(opts.expr, '$1'); return parseInt(result); } jQuery.fn.selectionTable = function(options) { var defaults = { itemClass: 'tselectable', selectionClass: 'tselection', selectedClass: 'tselected', dayExpr: /book-(.*)-.*/, indexExpr: /book-.*-(.*)/ }; var opts = jQuery.extend(defaults, options); jQuery(this).each(function () { var table = jQuery(this); var items = table.find('td.' + opts.itemClass); var startItem = null; var downItem = null; var downDay = null; var downIndex = null; var duration = 0; var selectIndexItems = function(min, max, day) { items.each(function() { var item = jQuery(this); var itemDay = item.inval({ expr: opts.dayExpr }); var ok = false; if (itemDay == day) { var itemIndex = item.inval({ expr: opts.indexExpr }); if ((itemIndex >= min) && (itemIndex <= max)) { ok = true; } } if (ok) { item.addClass(opts.selectionClass); } else { item.removeClass(opts.selectionClass); } }); duration = (max - min + 1); }; var mouseDownHandler = function (e) { var buttonLeft = 0; if (jQuery.browser.msie) { buttonLeft = 1; } if (e.button == buttonLeft) { downItem = jQuery(this); startItem = downItem; downItem.addClass(opts.selectionClass); startItem.addClass(opts.selectedClass); downDay = downItem.inval({ expr: opts.dayExpr }); downIndex = downItem.inval({ expr: opts.indexExpr }); duration = 1; jQuery(document).mouseup(mouseUpHandler); jQuery(document).keypress(keyPressHandler); e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } return false; } }; var keyPressHandler = function(e) { if (e.keyCode = 27) { jQuery(document).unbind('mouseup', mouseUpHandler); jQuery(document).unbind('keypress', keyPressHandler); items.removeClass(opts.selectionClass); items.removeClass(opts.selectedClass); downItem = null; downDay = null; downIndex = null; duration = 0; } } var mouseEnterHandler = function (e) { if (downItem) { var target = jQuery(this); var targetIndex = target.inval({ expr: opts.indexExpr }); startItem.removeClass(opts.selectedClass); if (targetIndex < downIndex) { startItem = target; selectIndexItems(targetIndex, downIndex, downDay); } else { startItem = downItem; selectIndexItems(downIndex, targetIndex, downDay); } startItem.addClass(opts.selectedClass); } }; var mouseUpHandler = function () { jQuery(document).unbind('mouseup', mouseUpHandler); jQuery(document).unbind('keypress', keyPressHandler); items.removeClass(opts.selectionClass); downItem.removeClass(opts.selectedClass); if (duration < 1) { duration = 1; } window.location = startItem.find('a').attr('href') + '/duration/' + Math.floor(duration * 30); downItem = null; downDay = null; downIndex = null; duration = 0; return false; }; items.each(function () { // Hides the links inside jQuery(this).find('a').hide(); jQuery(this).append('<span class="autohide">' + jQuery(this).find('a').text() + '</span>'); if ('undefined' !== typeof this.onselectstart) { this.onselectstart = function() { return false; }; } jQuery(this).mousedown(mouseDownHandler); jQuery(this).mouseenter(mouseEnterHandler); jQuery(this).css('cursor', 'pointer'); }); }); }; jQuery('table.planning').selectionTable(); });
if (typeof Mapmaker === 'undefined') Mapmaker = {}; Mapmaker.TopicMappingView = (function($, famous) { var Engine = famous.core.Engine; var Surface = famous.core.Surface; var ImageSurface = famous.surfaces.ImageSurface; var Modifier = famous.core.Modifier; var StateModifier = famous.modifiers.StateModifier; var Transform = famous.core.Transform; var Particle = famous.physics.bodies.Particle; var Repulsion = famous.physics.forces.Repulsion; var Handlers = { mousedown: function(event) { this.mouseIsDown = true; this.hasMoved = false; this.topicParticle.sleep(); $(document).trigger(Mapmaker.TopicMappingView.events.mousedown); }, mouseup: function(event) { this.topicParticle.wake(); Private.cancelClick.call(this); $(document).trigger(Mapmaker.TopicMappingView.events.mouseup, [this]); var storedTime = this.lastClick; var now = Date.now(); this.lastClick = now; if (now - storedTime < this.view.config.DOUBLE_CLICK_TOLERANCE) { $(document).trigger(Mapmaker.TopicMappingView.events.doubleClick, [this]); } }, mousemove: function(event) { var m = this.mapping; var newX, newY; if (this.mouseIsDown) { if (!this.hasMoved) this.hasMoved = true; newX = this.topicParticle.getTransform()[12] + event.movementX; newY = this.topicParticle.getTransform()[13] + event.movementY; // modify the mapping, the saved state m.set("xloc", newX); m.set("yloc", newY); //this.anchorParticle.setPosition([newX, newY, 0]); this.topicParticle.setPosition([newX, newY, 0]); //this.anchorParticle.setVelocity([0, 0, 0]); this.topicParticle.setVelocity([0, 0, 0]); // when changing this topics location, trigger event with location data // so that mapView can move synapses attached to it } } }; var Private = { cancelClick: function() { this.mouseIsDown = false; if (this.hasMoved) { // save the mapping } $(document).trigger(Mapmaker.TopicMappingView.events.dragEnd); }, createImageSurface: function() { var self = this; var topic = this.mapping.getTopic(); var updateMetacodeImage = function() { var metacode = self.view.metacodes.get(topic.get("metacode_id")); var metacodeUrl = metacode.get("icon"); self.imageSurface.setContent(metacodeUrl); }; // add listener topic.on("change:metacode_id", updateMetacodeImage); this.imageSurface = new ImageSurface({ classes: ["noselect"], size: [50, 50] }); updateMetacodeImage(); this.modNode.add(this.imageSurface); // attach events var mousedownHandler = function(event) { event.preventDefault(); Handlers.mousedown.call(self, event); }; this.imageSurface.on("mousedown", mousedownHandler); var mouseupHandler = function(event) { Handlers.mouseup.call(self, event); }; this.imageSurface.on("mouseup", mouseupHandler); var mousemoveHandler = function(event) { Handlers.mousemove.call(self, event); }; //this.imageSurface.on("mousemove", mousemoveHandler); }, createNameSurface: function() { var self = this; var topic = this.mapping.getTopic(); var updateName = function() { self.nameSurface.setContent(topic.get("name")); }; // add listener topic.on("change:name", updateName); this.nameSurface = new Surface({ content: topic.get("name"), classes: ["noselect"], size: [true, true], properties: { marginTop: "35px", borderRadius: "5px", backgroundColor: "#FFF" } }); this.modNode.add(this.nameSurface); // attach events var mousedownHandler = function(event) { Handlers.mousedown.call(self, event); }; this.nameSurface.on("mousedown", mousedownHandler); var mouseupHandler = function(event) { Handlers.mouseup.call(self, event); }; this.nameSurface.on("mouseup", mouseupHandler); var mousemoveHandler = function(event) { Handlers.mousemove.call(self, event); }; //this.nameSurface.on("mousemove", mousemoveHandler); }, attachPhysics: function () { var self = this; var m = this.mapping; var pos = [m.get("xloc"), m.get("yloc"), 0]; // this one is going to stay rooted at the mapping this.anchorParticle = new Particle({ position: pos }); this.view.pe.addBody(this.anchorParticle); // this one is going to dance and move around this.topicParticle = new Particle({ position: pos }); this.view.pe.addBody(this.topicParticle); //var gravity = new Repulsion({ // strength: -3 //}); //this.view.pe.attach(gravity, this.topicParticle, this.anchorParticle); // create a new force and add it to the physics engine //var repel = new Repulsion({ strength: 0.5, radii: {max: 1, min: 0}}); // for 'attach' variables to pass are (Force, Targets, Source) //this.view.pe.attach(repel, undefined, this.topicParticle); this.mod = new Modifier({ transform: function () { return self.topicParticle.getTransform(); } }); this.modNode = this.view.originModNode.add(this.mod); } }; var topicView = function(view, mapping) { var self = this; Mapmaker.MappingView.call(this, view, mapping); this.topic = mapping.getTopic(); Private.attachPhysics.call(this); Private.createImageSurface.call(this); Private.createNameSurface.call(this); var cancelHandler = function(event) { Private.cancelClick.call(self, event); }; Engine.on("mouseup", cancelHandler); var mousemoveHandler = function(event) { Handlers.mousemove.call(self, event); }; Engine.on("mousemove", mousemoveHandler); this.mouseIsDown = false; this.lastClick = null; this.hasMoved = false; }; topicView.prototype = new Mapmaker.MappingView(); topicView.prototype.constructor = topicView; return topicView; }(jQuery, famous)); /** * @class * @static */ Mapmaker.TopicMappingView.events = { mousedown: "Mapmaker:TopicMappingView:mousedown", mouseup: "Mapmaker:TopicMappingView:mouseup", doubleClick: "Mapmaker:TopicMappingView:doubleClick", dragEnd: "Mapmaker:TopicMappingView:dragEnd", };
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'clipboard', 'ug', { copy: 'كۆچۈر', copyError: 'تور كۆرگۈڭىزنىڭ بىخەتەرلىك تەڭشىكى تەھرىرلىگۈچنىڭ كۆچۈر مەشغۇلاتىنى ئۆزلۈكىدىن ئىجرا قىلىشىغا يول قويمايدۇ، ھەرپتاختا تېز كۇنۇپكا (Ctrl/Cmd+C) ئارقىلىق تاماملاڭ', cut: 'كەس', cutError: 'تور كۆرگۈڭىزنىڭ بىخەتەرلىك تەڭشىكى تەھرىرلىگۈچنىڭ كەس مەشغۇلاتىنى ئۆزلۈكىدىن ئىجرا قىلىشىغا يول قويمايدۇ، ھەرپتاختا تېز كۇنۇپكا (Ctrl/Cmd+X) ئارقىلىق تاماملاڭ', paste: 'چاپلا', pasteArea: 'چاپلاش دائىرىسى', pasteMsg: 'ھەرپتاختا تېز كۇنۇپكا (<STRONG>Ctrl/Cmd+V</STRONG>) نى ئىشلىتىپ مەزمۇننى تۆۋەندىكى رامكىغا كۆچۈرۈڭ، ئاندىن <STRONG>جەزملە</STRONG>نى بېسىڭ', securityMsg: 'توركۆرگۈڭىزنىڭ بىخەتەرلىك تەڭشىكى سەۋەبىدىن بۇ تەھرىرلىگۈچ چاپلاش تاختىسىدىكى مەزمۇننى بىۋاستە زىيارەت قىلالمايدۇ، بۇ كۆزنەكتە قايتا بىر قېتىم چاپلىشىڭىز كېرەك.', title: 'چاپلا' } );
define(['handlebars', 'marked'], function(Handlebars, marked) { return function(value) { return new Handlebars.SafeString(marked(value)); }; });
/* Code for Life Copyright (C) 2016, Ocado Innovation Limited This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ADDITIONAL TERMS – Section 7 GNU General Public Licence This licence does not grant any right, title or interest in any “Ocado” logos, trade names or the trademark “Ocado” or any other trademarks or domain names owned by Ocado Innovation Limited or the Ocado group of companies or any other distinctive brand features of “Ocado” as may be secured from time to time. You must not distribute any modification of this program using the trademark “Ocado” or claim any affiliation or association with Ocado or its employees. You are not authorised to use the name Ocado (or any of its trade names) or the names of any author or contributor in advertising or for publicity purposes pertaining to the distribution of this program, without the prior written authorisation of Ocado. Any propagation, distribution or conveyance of this program must include this copyright notice and these terms. You must not misrepresent the origins of this program; modified versions of the program must be marked as such and not identified as the original program. */ var ocargo = ocargo || {}; // Object containing helper js objects (buttons etc). ocargo.jsElements = { image: function(url, class_) { return "<img src='" + url + "'class='" + class_ + "'>"; } }; //FIXME: actually use Django's internationalisation framework. ocargo.messages = { tooManyBlocks: "Whoops. You used too many blocks.", terminated: "Program terminated.", crashed: "Your program crashed.", stoppingTitle: "Stopping...", // Level editor. trafficLightsWarning: "You need to complete level 44 before using a traffic light. ", shareSuccessful: "Your level has been successfully shared! " };
import { Box } from './Box'; export const ColorBox = props => { const { color, ...rest } = props; return ( <Box inline width={2} height={2} lineHeight={2} color={color} backgroundColor={color} content="." {...rest} /> ); };
/* * log.js * * Copyright (C) 2009-13 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ var log4js = require('log4js'); global.logger = log4js.getLogger('shiny-server'); global.logger.setLevel(process.env.SHINY_LOG_LEVEL || 'TRACE');
/* Copyright 2016 icasdri This file is part of PostMaker. PostMaker is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PostMaker is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with PostMaker. If not, see <http://www.gnu.org/licenses/>. */ Workers.gmail = { /* * This function needs to store title and p (the content, whether blurb or full text), * and anything from conf that might be needed (e.g. website url, CC field) * somewhere of its choosing in dat that'll be used by the go() function. * This allows the function to process the contet as it sees fit. * The primaryUrl token %%% will already have been replaced. */ prep: function(primaryUrl, conf, dat, title, contentP) { console.log("Got to Workers.gmail.prep()"); dat.jsoConfig = { providerID: "google", client_id: "853943586263-f2ondnhfv7nbnk6m0ia64qr807of7i0k.apps.googleusercontent.com", redirect_uri: "https://postmaker.surge.sh", authorization: "https://accounts.google.com/o/oauth2/auth", scopes: { request: ["https://www.googleapis.com/auth/gmail.send"] } } dat.content = contentP; dat.subject = title; dat.to = conf.toField.trim(); dat.cc= conf.ccField.trim(); dat.bcc= conf.bccField.trim(); }, go: function(primaryUrl, dat, jso, progress) { if (typeof(primaryUrl) == "function") { // We are primary console.warn("[Workers.gmail] We will be unable to provide a primaryUrl even though we are primary!!!"); } else { // We are secondary } console.log("Got to Workers.gmail.go()"); console.log(jso); console.log(jso.ajax); progress(0); progress("Constructing message..."); message = "To: " + dat.to + "\n"; if (dat.cc) { message += "Cc: " + dat.cc + "\n"; } if (dat.bcc) { message += "Bcc: " + dat.bcc + "\n"; } if (dat.subject) { message += "Subject: " + dat.subject + "\n"; } message += "\n" + dat.content; progress(12); progress("Encoding message..."); var encoded = btoa(message); progress(24); progress("Sending message..."); var scopes = [ "https://mail.google.com/", "https://www.googleapis.com/auth/gmail.compose", "https://www.googleapis.com/auth/gmail.send" ]; jso.ajax({ url: "https://www.googleapis.com/gmail/v1/users/me/messages/send", oauth: { scopes: { request: scopes, require: scopes } }, type: "POST", data: JSON.stringify({ raw: encoded }), contentType: "application/json", dataType: "json", success: function() { progress(100); progress("Sent!"); progress({ color: App.COLORS.SUCCESS }); }, error: function(x) { progress(100); progress("Sending failed."); progress({ color: App.COLORS.ERROR }); console.error("[Workers.gmail] Gmail responded with error: " + x); } }); } };
/** * Created by JetBrains PhpStorm. * User: JK * Date: 1/12/12 * Time: 10:04 AM */ (function () { tinymce.create("tinymce.plugins.fixed", { init:function (editor, url) { var color, classes; //get color color = editor.getParam("fixed_content_color", "yellow"); //get classes classes = editor.getParam("noneditable_noneditable_class", "jkNonEditAble"); editor.formatter.register("fixed", {inline:"span", classes:"%classes", styles:{background:"%color"}}) editor.addCommand("mceFixed", function () { editor.formatter.apply("fixed", {color:color, classes:classes}); }); editor.addButton("fixed", { title:"Fixed", image:"modules/images/fixed.png", cmd:"mceFixed" }); }, getInfo:function () { return { longname:'Fixed Content', author:'JK', authorurl:'http://jkaveri.com', infourl:'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/noneditable', version:tinymce.majorVersion + "." + tinymce.minorVersion }; } }); tinymce.PluginManager.add("fixed_content", tinymce.plugins.fixed); })();
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Alert } from 'react-bootstrap'; import { scanFile } from '../actions/fileActions'; import * as types from '../actions/ActionTypes'; class Notification extends React.Component { constructor(props) { super(props); this.state = { show: !(props.notification.trim() === '') }; this.handleDismiss = this.handleDismiss.bind(this); } UNSAFE_componentWillReceiveProps(newProps) { this.setState({ show: !(newProps.notification.trim() === '') }); } handleDismiss() { this.setState({ show: false }); } render() { const { notification } = this.props; const { show } = this.state; if (!show) return <span />; return ( <Alert bsStyle="danger" className="chemscanner-alert-notification" onDismiss={this.handleDismiss} > {notification} </Alert> ); } } Notification.propTypes = { notification: PropTypes.string }; Notification.defaultProps = { notification: '' }; const NotificationContainer = props => <Notification {...props} />; const mapStateToProps = state => ({ notification: state.get('ui').get('notification'), }); const mapDispatchToProps = dispatch => ({ scanFile: (files, getMol) => { dispatch({ type: types.SET_LOADING }); dispatch(scanFile(files, getMol)).then(() => dispatch({ type: types.UNSET_LOADING })); }, }); export default connect( mapStateToProps, mapDispatchToProps )(NotificationContainer);
/** * Created by mark.feder on 10/13/2015. */ (function (mw, $) { "use strict"; mw.KIVQApi = function (embedPlayer) { return this.init(embedPlayer); }; if (!(mw.KIVQApi.prototype = { bindPostfix: '.KIVQApi', init: function (embedPlayer) { var _this = this; this.destroy(); this.embedPlayer = embedPlayer; this.getUserEntryIdAndQuizParams = function(callback){ var getQuizuserEntryIdAndQuizParams = [{ 'service': 'userEntry', 'action': 'list', 'filter:objectType': 'KalturaQuizUserEntryFilter', 'filter:entryIdEqual': _this.embedPlayer.kentryid, 'filter:userIdEqualCurrent':'1', 'filter:orderBy': '-createdAt' }, { 'service': 'quiz_quiz', 'action': 'get', 'entryId': _this.embedPlayer.kentryid }]; _this.getKClient().doRequest(getQuizuserEntryIdAndQuizParams, function (data) { callback(data); }); }; this.getQuestionAnswerCuepoint = function(kQuizUserEntryId,callback){ var getCp = [{ 'service': 'cuepoint_cuepoint', 'action': 'list', 'filter:entryIdEqual': _this.embedPlayer.kentryid, 'filter:objectType': 'KalturaCuePointFilter', 'filter:cuePointTypeEqual': 'quiz.QUIZ_QUESTION', 'filter:orderBy': '+startTime' },{ 'service': 'cuepoint_cuepoint', 'action': 'list', 'filter:objectType': 'KalturaAnswerCuePointFilter', 'filter:entryIdEqual':_this.embedPlayer.kentryid, 'filter:quizUserEntryIdEqual':kQuizUserEntryId, 'filter:cuePointTypeEqual': 'quiz.QUIZ_ANSWER' }]; _this.getKClient().doRequest(getCp, function (data) { callback(data); }); }; this.createQuizUserEntryId = function(callback){ var createQuizuserEntryId = { 'service': 'userEntry', 'action': 'add', 'userEntry:objectType': 'KalturaQuizUserEntry', 'userEntry:entryId': _this.embedPlayer.kentryid }; _this.getKClient().doRequest(createQuizuserEntryId, function (data) { callback(data); }); }; this.addAnswer = function(isAnswered,selectedAnswer,kQuizUserEntryId,questionNr,callback){ var _this = this,answerParams = {}; var quizSetAnswer = { 'service': 'cuepoint_cuepoint', 'cuePoint:objectType': "KalturaAnswerCuePoint", 'cuePoint:answerKey': selectedAnswer, 'cuePoint:quizUserEntryId': kQuizUserEntryId }; if (isAnswered) { answerParams = { 'action': 'update', 'id': $.cpObject.cpArray[questionNr].answerCpId, 'cuePoint:entryId': _this.embedPlayer.kentryid } } else { answerParams = { 'action': 'add', 'cuePoint:entryId': $.cpObject.cpArray[questionNr].cpEntryId, 'cuePoint:parentId': $.cpObject.cpArray[questionNr].cpId, 'cuePoint:startTime': '0' }; } $.extend(quizSetAnswer, answerParams); _this.getKClient().doRequest(quizSetAnswer, function (data) { callback(data); }); }; this.submitQuiz = function (kQuizUserEntryId,callback) { var submitQuizParams = { 'service': 'userEntry', 'action': 'submitQuiz', 'id': kQuizUserEntryId }; _this.getKClient().doRequest(submitQuizParams, function (data) { callback(data); }); }; this.downloadIvqPDF = function (EntryId,callback) { var downloadPdf = { 'service': 'quiz_quiz', 'action': 'getUrl', 'quizOutputType':1, 'entryId': EntryId }; _this.getKClient().doRequest(downloadPdf, function (data) { callback(data); }); }; }, destroy: function () { }, getKClient: function () { var _this = this; if (!this.kClient) { this.kClient = mw.kApiGetPartnerClient(_this.embedPlayer.kwidgetid); } return this.kClient; } })) { } })(window.mw, window.jQuery );
/** * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'language', 'pt-br', { button: 'Configure o Idioma', remove: 'Remover Idioma' } );
Backbone.SIXHIARA = Backbone.SIXHIARA || {}; Backbone.SIXHIARA.ButtonSaveView = Backbone.View.extend({ events: { "click": "save" }, initialize: function() { this.$el.prop('disabled', true); this.listenTo(this.model, 'aChangeHappens', function(){ this.$el.prop('disabled', false) }, this); }, save: function(){ if(this.model.isValid()){ this.model.save(null, { wait: true, success: function(model, resp, options) { window.location = model.urlShow(); }, error: function(xhr, textStatus, errorThrown) { if (textStatus && textStatus.responseJSON && textStatus.responseJSON.error) { if(Array.isArray(textStatus.responseJSON.error)) { bootbox.alert(textStatus.responseJSON.error.join('\n')); } else{ bootbox.alert(textStatus.responseJSON.error); } } else { bootbox.alert(textStatus.statusText); } } }); } else { bootbox.alert(this.model.validationError.join('\n')); } } });
MWF.xApplication.service = MWF.xApplication.service || {}; MWF.xApplication.service.ServiceManager = MWF.xApplication.service.ServiceManager || {}; MWF.xApplication.service.ServiceManager.options = { "multitask": false, "executable": true };
/** * Node JS intro * * This step covers: * - bootstrap CSS * - rendering a form */ var express = require('express'); // create server var server = express(); server.get('/', function(req, res) { res.render(__dirname + '/views/form.jade'); }); // start server.listen(3000);
class TreeView { constructor($dom, store, adapter) { this.store = store; this.adapter = adapter; this.$view = $dom.find('.octotree_treeview'); this.$tree = this.$view .find('.octotree_view_body') .on('click.jstree', '.jstree-open>a', ({target}) => { setTimeout(() => { this.$jstree.close_node(target) }, 0); }) .on('click.jstree', '.jstree-closed>a', ({target}) => { setTimeout(() => { this.$jstree.open_node(target) }, 0); }) .on('click', this._onItemClick.bind(this)) .jstree({ core: {multiple: false, worker: false, themes: {responsive: false}}, plugins: ['wholerow'] }); } get $jstree() { return this.$tree.jstree(true); } show(repo, token) { const $jstree = this.$jstree; $jstree.settings.core.data = (node, cb) => { const prMode = this.store.get(STORE.PR) && repo.pullNumber; const loadAll = this.adapter.canLoadEntireTree(repo) && (prMode || this.store.get(STORE.LOADALL)); node = !loadAll && (node.id === '#' ? {path: ''} : node.original); this.adapter.loadCodeTree({repo, token, node}, (err, treeData) => { if (err) { if (err.status === 206 && loadAll) { // The repo is too big to load all, need to retry $jstree.refresh(true); } else { $(this).trigger(EVENT.FETCH_ERROR, [err]); } } else { treeData = this._sort(treeData); if (loadAll) { treeData = this._collapse(treeData); } cb(treeData); } }); }; this.$tree.one('refresh.jstree', () => { this.syncSelection(repo); $(this).trigger(EVENT.VIEW_READY); }); this._showHeader(repo); $jstree.refresh(true); } _showHeader(repo) { const adapter = this.adapter; this.$view .find('.octotree_view_header') .html( `<div class="octotree_header_repo"> <a href="/${repo.username}">${repo.username}</a> / <a data-pjax href="/${repo.username}/${repo.reponame}">${repo.reponame}</a> </div> <div class="octotree_header_branch"> ${this._deXss(repo.branch.toString())} </div>` ) .on('click', 'a[data-pjax]', function(event) { event.preventDefault(); // A.href always return absolute URL, don't want that const href = $(this).attr('href'); const newTab = event.shiftKey || event.ctrlKey || event.metaKey; newTab ? adapter.openInNewTab(href) : adapter.selectFile(href); }); } _deXss(str) { return str && str.replace(/[<>'"&]/g, '-'); } _sort(folder) { folder.sort((a, b) => { if (a.type === b.type) return a.text === b.text ? 0 : a.text < b.text ? -1 : 1; return a.type === 'blob' ? 1 : -1; }); folder.forEach((item) => { if (item.type === 'tree' && item.children !== true && item.children.length > 0) { this._sort(item.children); } }); return folder; } _collapse(folder) { return folder.map((item) => { if (item.type === 'tree') { item.children = this._collapse(item.children); if (item.children.length === 1 && item.children[0].type === 'tree') { const onlyChild = item.children[0]; onlyChild.text = item.text + '/' + onlyChild.text; return onlyChild; } } return item; }); } _onItemClick(event) { let $target = $(event.target); let download = false; // Handle middle click if (event.which === 2) return; // Handle icon click, fix #122 if ($target.is('i.jstree-icon')) { $target = $target.parent(); download = true; } if (!$target.is('a.jstree-anchor')) return; // Refocus after complete so that keyboard navigation works, fix #158 const refocusAfterCompletion = () => { $(document).one('pjax:success page:load', () => { this.$jstree.get_container().focus(); }); }; const adapter = this.adapter; const newTab = event.shiftKey || event.ctrlKey || event.metaKey; const href = $target.attr('href'); // The 2nd path is for submodule child links const $icon = $target.children().length ? $target.children(':first') : $target.siblings(':first'); if ($icon.hasClass('commit')) { refocusAfterCompletion(); newTab ? adapter.openInNewTab(href) : adapter.selectSubmodule(href); } else if ($icon.hasClass('blob')) { if (download) { const downloadUrl = $target.attr('data-download-url'); const downloadFileName = $target.attr('data-download-filename'); adapter.downloadFile(downloadUrl, downloadFileName); } else { refocusAfterCompletion(); newTab ? adapter.openInNewTab(href) : adapter.selectFile(href); } } } syncSelection(repo) { const $jstree = this.$jstree; if (!$jstree) return; // Convert /username/reponame/object_type/branch/path to path const path = decodeURIComponent(location.pathname); const match = path.match(/(?:[^\/]+\/){4}(.*)/); if (!match) return; const currentPath = match[1]; const loadAll = this.adapter.canLoadEntireTree(repo) && this.store.get(STORE.LOADALL); selectPath(loadAll ? [currentPath] : breakPath(currentPath)); // Convert ['a/b'] to ['a', 'a/b'] function breakPath(fullPath) { return fullPath.split('/').reduce((res, path, idx) => { res.push(idx === 0 ? path : `${res[idx - 1]}/${path}`); return res; }, []); } function selectPath(paths, index = 0) { const nodeId = NODE_PREFIX + paths[index]; if ($jstree.get_node(nodeId)) { $jstree.deselect_all(); $jstree.select_node(nodeId); $jstree.open_node(nodeId, () => { if (++index < paths.length) { selectPath(paths, index); } }); } } } }
// Tradity.de Server // Copyright (C) 2016 Tradity.de Tech Team <tech@tradity.de> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. "use strict"; /** * Provides the {@link module:access~Access} object. * * @public * @module access */ /** * Represents the access levels in which server code gets executed. * * Access levels are identified by simple strings, but #242 is * basically about throwing them all out and introducing new ones. * After that, there should be a list of the new levels with * associated documentation. * * @public * @constructor module:access~Access */ class Access { constructor() { this.areas = []; this.hasAnyAccess = false; // above code is equiv to this.dropAll(); } /** * Returns a copy of this access object. * * @return {module:access~Access} An access object with identical access levels. * * @function module:access~Access#clone */ clone() { const a = new Access(); a.areas = this.areas.slice(); a.hasAnyAccess = this.hasAnyAccess; return a; } toString() { return this.toJSON(); } /** * Serializes the access levels associated with this access object * into a JSON string that can be passed to {@link module:access~Access.fromJSON}. * * @return {string} A short machine-readable description of the access * levels associated with this access object. * * @function module:access~Access#toJSON */ toJSON() { if (this.hasAnyAccess) { return '["*"]'; } return JSON.stringify(this.areas); } /** * Serializes the access levels associated with this access object * into an array of access levels. * * @return {string[]} A list of the access levels associated with * this access object, possibly including <code>"*"</code>. * * @function module:access~Access#toJSON */ toArray() { if (this.hasAnyAccess) { return ['*']; } return this.areas; } /** * Checks for privileges to a certain access level. * * @param {string} area The access level identifier. * * @return {boolean} Indicates whether access is present. * * @function module:access~Access#has */ has(area) { return this.hasAnyAccess || (this.areas.indexOf(area) !== -1); } /** * Grants all access levels held by another access object. * * @param {module:access~Access} otherAccess Another access object. * * @function module:access~Access#update */ update(otherAccess) { if (otherAccess.hasAnyAccess) { this.grant('*'); } for (let i = 0; i < otherAccess.areas.length; ++i) { this.grant(otherAccess.areas[i]); } } /** * Grants access to a specified access level. * * @param {string} area The access level to grant access to, or * <code>"*"</code> to indicate full access. * * @function module:access~Access#grant */ grant(area) { area = area.trim(); if (!area) { return; } if (area === '*') { return this.grantAny(); } if (this.areas.indexOf(area) === -1) { this.areas.push(area); } } /** * Grants full access to all access levels. * * @function module:access~Access#grantAny */ grantAny() { this.hasAnyAccess = true; } /** * Removes access to a specified access level. * * @param {string} area The access level to remove access from, or * <code>"*"</code> to indicate removing full access. * * @function module:access~Access#drop */ drop(area) { area = area.trim(); if (!area) { return; } if (area === '*') { return this.dropAny(); } let index; while ((index = this.areas.indexOf(area)) !== -1) { this.areas.splice(index, 1); } } /** * Drop full access, if previously held. * Access levels that have been granted explicitly * are not affected. * * @function module:access~Access#dropAny */ dropAny() { this.hasAnyAccess = false; } /** * Drop all access levels held by this objects, * possibly including full access. * * @function module:access~Access#dropAall */ dropAll() { this.dropAny(); this.areas = []; } } /** * Creates a new access object from a JSON specification. * See also {@link module:access~Access#toJSON}. * * @param {string} j A string describing the access levels. * * @return {module:access~Access} An access object with the access levels * speicified in <code>j</code>. * * @function module:access~Access.fromJSON */ Access.fromJSON = function(j) { const a = new Access(); if (!j) { return a; } if (j.trim() === '*') { a.grant('*'); } else { const p = JSON.parse(j); // note that this can handle both an array and the "*" string! for (let i = 0; i < p.length; ++i) { a.grant(p[i]); } } return a; }; exports.Access = Access;
/** * Module dependencies. */ const mongoose = require('mongoose'); const Schema = mongoose.Schema; /** * Support request Schema * * This collection serves as a backup for sent support requests */ const SupportRequestSchema = new Schema({ user: { type: Schema.ObjectId, ref: 'User', }, sent: { type: Date, default: Date.now, }, email: { type: String, trim: true, lowercase: true, }, username: { type: String, }, message: { type: String, required: true, }, userAgent: { type: String, }, reportMember: { type: String, }, }); mongoose.model('SupportRequest', SupportRequestSchema);
//Selectively disables the "Submit" button for student logged assignments, if the //assignment has outcome levels and no outcome level is selected. var SelfGradeOutcomesSelect = document.querySelector("#grade_raw_points"); if(!SelfGradeOutcomesSelect) SelfGradeOutcomesSelect = document.querySelector("#grade_pass_fail_status"); var SelfGradeOutcomesButton = document.querySelector(".self_grade_outcomes_button"); if(SelfGradeOutcomesSelect && SelfGradeOutcomesButton){ SelfGradeOutcomesSelect.addEventListener("change", function(){ if(SelfGradeOutcomesSelect.selectedIndex == 0) SelfGradeOutcomesButton.disabled = true; else SelfGradeOutcomesButton.disabled = false; }); }
define(function(require) { 'use strict'; var _ = require('underscore'); var Backbone = require('backbone'); var PrismBreakSimulation = require('models/simulation/prism-break'); var BendingLightSimView = require('views/sim'); var MediumControlsView = require('views/medium-controls'); var PrismBreakSceneView = require('views/scene/prism-break'); var PrismsPanelView = require('views/prisms-panel'); var PrismBreakControlsView = require('views/prism-break-controls'); var simHtml = require('text!templates/sim/prism-break.html'); /** * */ var PrismBreakSimView = BendingLightSimView.extend({ template: _.template(simHtml), events: _.extend(BendingLightSimView.prototype.events, { }), initialize: function(options) { options = _.extend({ title: 'Prism Break', name: 'prism-break' }, options); BendingLightSimView.prototype.initialize.apply(this, [ options ]); this.initEnvironmentMediumControls(); }, /** * Initializes the Simulation. */ initSimulation: function() { this.simulation = new PrismBreakSimulation(); }, /** * Initializes the SceneView. */ initSceneView: function() { this.sceneView = new PrismBreakSceneView({ simulation: this.simulation }); }, initEnvironmentMediumControls: function() { this.environmentMediumControlsView = new MediumControlsView({ model: this.simulation.environment, simulation: this.simulation, name: 'environment', label: 'Environment' }); }, initPrismsPanel: function() { this.prismsPanelView = new PrismsPanelView({ simulation: this.simulation, prismImages: this.sceneView.getPrismIcons() }); }, initPrismBreakControls: function() { this.prismBreakControlsView = new PrismBreakControlsView({ simulation: this.simulation, sceneView: this.sceneView }); }, /** * Resets the sim and options */ reset: function() { BendingLightSimView.prototype.reset.apply(this); this.prismBreakControlsView.reset(); }, render: function() { BendingLightSimView.prototype.render.apply(this); this.initPrismsPanel(); this.initPrismBreakControls(); this.prismsPanelView.render(); this.prismBreakControlsView.render(); this.environmentMediumControlsView.render(); this.$el.append(this.prismsPanelView.el); this.$el.append(this.prismBreakControlsView.el); this.$el.append(this.environmentMediumControlsView.el); return this; }, postRender: function() { BendingLightSimView.prototype.postRender.apply(this); this.prismBreakControlsView.postRender(); } }); return PrismBreakSimView; });
/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details. * * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/ */ function DonorListController($scope, sharedSpace, $location, navigateBackService, Donors) { Donors.get(function (data) { $scope.donors = data.donors; }); $scope.editDonor = function (id, donationCount) { var data = {query: $scope.query}; navigateBackService.setData(data); sharedSpace.setCountOfDonations(donationCount); $location.path('edit/' + id); }; }
Ext.define('MyDesktop.modules.pages.view.Pages', { extend: 'Ext.window.Window', requires: [ 'Ext.data.ArrayStore', 'Ext.util.Format', 'Ext.grid.Panel', 'Ext.grid.RowNumberer' ], width:900, height:480, animCollapse:false, constrainHeader:true, layout: 'border', initComponent: function() { this.items = [ Ext.create('MyDesktop.modules.pages.view.PagesTree', { title: D.t('Pages tree'), region: 'center' //width: 400, }), this.buildForm() ] this.callParent(); } ,buildForm: function() { var me = this; return { border: false, title: D.t('Page editor'), xtype: 'panel', region: 'east', width:400, split: true, collapsible: true, layout: 'border', items: [ Ext.create('MyDesktop.modules.pages.view.PageEditForm', { region: 'center' }), Ext.create('MyDesktop.modules.pages.view.PageEditBlocks', { region: 'south', collapsible: true, height: 200, split: true }) ] } } })
// function fn_moveElement(elementID,finalX,finalY,interval){ // if (!document.getElementById && !document.getElementById("elementID")) { // return false; // } // var elem=document.getElementById(elementID); // var xPos=parseInt(elem.style.left); // var yPos=parseInt(elem.style.top); // if (xPos===finalX&&yPos===finalY) { // return true; // } // if (xPos<finalX) { // xPos++; // } // if (xPos>finalX) { // xPos--; // } // if (yPos<finalY) { // yPos++; // } // if (yPos>finalY) { // yPos--; // } // elem.style.left=xPos+"px"; // elem.style.top=yPos+"px"; // var repeat="moveElement('"+elementID+"',"+finalX+","+finalY+","+interval+")"; // movement=setTimeout(repeat,interval); // } // function fn_positionMessage() { // body... if (!document.getElementById && !document.getElementById("message")) { return false; } var elem=document.getElementById("message"); elem.style.position="absolute"; elem.style.left="50px"; elem.style.top="100px"; moveElement("message",125,25,10); } fn_addLoadEvent(fn_positionMessage); function moveElement(elementID,finalX,finalY,interval){ if (!document.getElementById && !document.getElementById("elementID")) { return false; } var elem=document.getElementById(elementID); var xPos=parseInt(elem.style.left); var yPos=parseInt(elem.style.top); if (xPos===finalX&&yPos===finalY) { return true; } if (xPos<finalX) { xPos++; } if (xPos>finalX) { xPos--; } if (yPos<finalY) { yPos++; } if (yPos>finalY) { yPos--; } elem.style.left=xPos+"px"; elem.style.top=yPos+"px"; var repeat="moveElement('"+elementID+"',"+finalX+","+finalY+","+interval+")"; movement=setTimeout(repeat,interval); }
import React from 'react' import styles from './styles.scss' class FigureAnimate extends React.PureComponent { constructor (props) { super() this.state = { imgTransform: null } this.time = null } componentDidMount () { this.time = setTimeout(() => { this.setState({ imgTransform: { transform: 'scale(1, 1)' } }) }, 1000) } componentWillUnmount () { clearTimeout(this.time) } render () { const { cls } = this.props return ( <figure className={styles[cls]}> <img src='http://7xpwuf.com1.z0.glb.clouddn.com/WechatIMG13.jpeg' height='300' width='685' className={styles.KenBurns} style={this.state.imgTransform} /> <figcaption> <h2>图片标题</h2> <p>图片注解</p> <p>大图片注解</p> <p>图片注解</p> <div /> </figcaption> </figure> ) } } export default FigureAnimate
(function($) { var cultures = $.global.cultures, en = cultures.en, standard = en.calendars.standard, culture = cultures["mt-MT"] = $.extend(true, {}, en, { name: "mt-MT", englishName: "Maltese (Malta)", nativeName: "Malti (Malta)", language: "mt", numberFormat: { percent: { pattern: ["-%n","%n"] }, currency: { pattern: ["-$n","$n"], symbol: "€" } }, calendars: { standard: $.extend(true, {}, standard, { firstDay: 1, days: { names: ["Il-Ħadd","It-Tnejn","It-Tlieta","L-Erbgħa","Il-Ħamis","Il-Ġimgħa","Is-Sibt"], namesAbbr: ["Ħad","Tne","Tli","Erb","Ħam","Ġim","Sib"], namesShort: ["I","I","I","L","I","I","I"] }, months: { names: ["Jannar","Frar","Marzu","April","Mejju","Ġunju","Lulju","Awissu","Settembru","Ottubru","Novembru","Diċembru",""], namesAbbr: ["Jan","Fra","Mar","Apr","Mej","Ġun","Lul","Awi","Set","Ott","Nov","Diċ",""] }, patterns: { d: "dd/MM/yyyy", D: "dddd, d' ta\\' 'MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd, d' ta\\' 'MMMM yyyy HH:mm", F: "dddd, d' ta\\' 'MMMM yyyy HH:mm:ss", M: "d' ta\\' 'MMMM", Y: "MMMM yyyy" } }) } }, cultures["mt-MT"]); culture.calendar = culture.calendars.standard; })(jQuery);
var searchData= [ ['part_2ec',['part.c',['../part_8c.html',1,'']]], ['part_2eh',['part.h',['../part_8h.html',1,'']]], ['potential_2ec',['potential.c',['../potential_8c.html',1,'']]], ['potential_2eh',['potential.h',['../potential_8h.html',1,'']]], ['potential_5feval_2eh',['potential_eval.h',['../potential__eval_8h.html',1,'']]] ];
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ //#ifdef __PARSER_XHTML apf.XhtmlBodyElement = function(struct, tagName){ this.$init(tagName || "body", apf.NODE_VISIBLE, struct); }; (function(){ this.addEventListener("DOMNodeInsertedIntoDocument", function(e){ if (!this.ownerDocument.body) this.ownerDocument.body = this; this.$ext = this.$int = document.body; }, true); }).call(apf.XhtmlBodyElement.prototype = new apf.AmlElement()); apf.xhtml.setElement("body", apf.XhtmlBodyElement); //#endif
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Mustafa Sak (msak) ************************************************************************ */ /** * @ignore(ColorSwitch) */ qx.Class.define("demobrowser.demo.ui.CommandGroupManager", { extend : qx.application.Standalone, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { main : function() { this.base(arguments); this._manager = new qx.ui.command.GroupManager(); this._createWidgets(); }, _createWidgets : function() { var tabview = new qx.ui.tabview.TabView(); var page1 = new qx.ui.tabview.Page("Page1 - press 5 to change color"); page1.setLayout(new qx.ui.layout.Canvas()); var page2 = new qx.ui.tabview.Page("Page2 - press 5 to change color"); page2.setLayout(new qx.ui.layout.Canvas()); var page3 = new qx.ui.tabview.Page("Page3 - press 5 to change color"); page3.setLayout(new qx.ui.layout.Canvas()); page1.add(new ColorSwitch(this), {edge:0}); page2.add(new ColorSwitch(this), {edge:0}); page3.add(new ColorSwitch(this), {edge:0}); tabview.add(page1); tabview.add(page2); tabview.add(page3); this.getRoot().add(tabview, {edge: 10}); }, getGroupManager : function() { return this._manager; } } }); /** * View */ qx.Class.define("ColorSwitch", { extend : qx.ui.container.Composite, construct : function(controller) { this.base(arguments); this.setLayout(new qx.ui.layout.VBox(15)); this.setPadding(25); this._controller = controller; // create command var cmd = new qx.ui.command.Command("5"); cmd.addListener("execute", this.toggleColor, this); // create command group var group = new qx.ui.command.Group(); this._group = group; // add command into group group.add("toggleColor", cmd); // Register command group at command group manager controller.getGroupManager().add(group); this.addListener("appear", this._onAppear, this); this._createWidgets(); }, members : { _group : null, _createWidgets : function() { var btn = new qx.ui.form.TextField(); btn.setPlaceholder("If focused here, all commands will be disabled! Please press key \"5\"!"); btn.addListener("focusin", this._blockCommands, this); btn.addListener("focusout", this._unblockCommands, this); this.add(btn); var label = new qx.ui.basic.Label("All tabview pages are holding a view class with same command shortcut! Press key \"5\" on any page to change the color of the view. You will see that only the appeared page will change his color."); label.set({ rich : true, wrap : true }); this.add(label); }, toggleColor : function(target, command) { this.setBackgroundColor(this.getBackgroundColor() == "#ABEFEF" ? "#ABEFAB" : "#ABEFEF"); }, _onAppear : function(e) { this._controller.getGroupManager().setActive(this._group); }, _blockCommands : function(e) { this._controller.getGroupManager().block(); }, _unblockCommands : function(e) { this._controller.getGroupManager().unblock(); } } });
'use strict'; var gulp = require('gulp'), sass = require('gulp-sass'), concatCss = require('gulp-concat-css'), csso = require('gulp-csso'), concat = require('gulp-concat'), minifyjs = require('gulp-minify'), processhtml = require('gulp-processhtml'); gulp.task('sass', function () { return gulp.src('./sass/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./css')); }); gulp.task('css_min_concat', function () { return gulp.src([ './css/**/*.css' ]) .pipe(csso()) .pipe(concatCss('style.css')) .pipe(gulp.dest('../public/css')); }); gulp.task('js_min_concat', function () { return gulp.src([ './js/**/*.js' ]) .pipe(minifyjs({ ext:{min: '.min.js'}, noSource: true })) .pipe(concat('script.js')) .pipe(gulp.dest('../public/js')); }); gulp.task('posthtml', function () { return gulp.src('./*.html') .pipe(processhtml()) .pipe(gulp.dest('../views')); }); gulp.task('prod', ['sass', 'css_min_concat', 'js_min_concat', 'posthtml'], function() {});
var printCatalog = function() { print(catalog.crawlHeaderInfo); var schemas = catalog.schemas.toArray(); for ( var i = 0; i < schemas.length; i++) { print(schemas[i].fullName); var tables = catalog.getTables(schemas[i]).toArray(); for ( var j = 0; j < tables.length; j++) { print("o--> " + tables[j].name); var columns = tables[j].columns.toArray(); for ( var k = 0; k < columns.length; k++) { print(" o--> " + columns[k].name); } } } }; printCatalog();
var express = require('express'); module.exports = function(){ var menu = global.beans.menu; var obj = {}; obj.router = express.Router(); obj.router.get('/index', function (req, res) { menu.find().toArray(function(err,doc){ if(err){ throw err; } res.json(doc); }); }); return obj; };
var dir_1dfe7b4d98f7fbcbf3888d2e6eb0ed23 = [ [ "eventBus.hpp", "event_bus_8hpp_source.html", null ], [ "eventHandler.hpp", "event_handler_8hpp_source.html", null ], [ "observable.hpp", "observable_8hpp_source.html", null ], [ "observer.hpp", "observer_8hpp_source.html", null ] ];
import {Component, View, Inject} from 'app/app'; import 'components/contextselector/context-selector'; import {SELECTION_MODE_BOTH, SELECTION_MODE_IN_CONTEXT, SELECTION_MODE_WITHOUT_CONTEXT} from 'components/contextselector/context-selector'; import contextSelectorStubTemplate from 'context-selector.stub.html!text'; @Component({ selector: 'seip-context-selector-stub' }) @View({ template: contextSelectorStubTemplate }) @Inject() export class ContextSelectorStub { constructor() { this.config = { parentId: 'test_id' }; this.config.both = { parentId: 'test_id', contextSelectorSelectionMode: SELECTION_MODE_BOTH }; this.config.selectionModeInContext = { parentId: 'test_id', contextSelectorSelectionMode: SELECTION_MODE_IN_CONTEXT }; this.config.selectionModeWithoutContext = { parentId: 'test_id', contextSelectorSelectionMode: SELECTION_MODE_WITHOUT_CONTEXT }; } }
var searchData= [ ['generic_5ftype',['generic_type',['../structshyft_1_1time__axis_1_1generic__dt.html#a3251a243c6e09621bc1fd0102cd2ec0e',1,'shyft::time_axis::generic_dt']]] ];
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import Marionette from 'backbone.marionette'; import CreateView from './create-view'; import Template from './templates/custom-measures-header.hbs'; export default Marionette.ItemView.extend({ template: Template, events: { 'click #custom-measures-create': 'onCreateClick' }, onCreateClick (e) { e.preventDefault(); this.createCustomMeasure(); }, createCustomMeasure () { new CreateView({ collection: this.collection, projectId: this.options.projectId }).render(); } });
/** * Copyright (c) 2009 - 2010 Chris Leonello * jqPlot is currently available for use in all personal or commercial projects * under both the MIT and GPL version 2.0 licenses. This means that you can * choose the license that best suits your project and use it accordingly. * * The author would appreciate an email letting him know of any substantial * use of jqPlot. You can reach the author at: chris at jqplot dot com * or see http://www.jqplot.com/info.php . This is, of course, * not required. * * If you are feeling kind and generous, consider supporting the project by * making a donation at: http://www.jqplot.com/donate.php . * * Thanks for using jqPlot! * */ (function($) { /** * Class: $.jqplot.ciParser * Data Renderer function which converts a custom JSON data object into jqPlot data format. * Set this as a callable on the jqplot dataRenderer plot option: * * > plot = $.jqplot('mychart', [data], { dataRenderer: $.jqplot.ciParser, ... }); * * Where data is an object in JSON format or a JSON encoded string conforming to the * City Index API spec. * * Note that calling the renderer function is handled internally by jqPlot. The * user does not have to call the function. The parameters described below will * automatically be passed to the ciParser function. * * Parameters: * data - JSON encoded string or object. * plot - reference to jqPlot Plot object. * * Returns: * data array in jqPlot format. * */ $.jqplot.ciParser = function (data, plot) { var ret = [], line, i, j, k, kk; if (typeof(data) == "string") { data = $.jqplot.JSON.parse(data, handleStrings); } else if (typeof(data) == "object") { for (k in data) { for (i=0; i<data[k].length; i++) { for (kk in data[k][i]) { data[k][i][kk] = handleStrings(kk, data[k][i][kk]); } } } } else return null; // function handleStrings // Checks any JSON encoded strings to see if they are // encoded dates. If so, pull out the timestamp. // Expects dates to be represented by js timestamps. function handleStrings(key, value) { var a; if (value != null) { if (value.toString().indexOf('Date') >= 0) { //here we will try to extract the ticks from the Date string in the "value" fields of JSON returned data a = /^\/Date\((-?[0-9]+)\)\/$/.exec(value); if (a) { return parseInt(a[1], 10); } } return value; } } for (var prop in data) { line = []; temp = data[prop]; switch (prop) { case "PriceTicks": for (i=0; i<temp.length; i++) { line.push([temp[i]['TickDate'], temp[i]['Price']]); } break; case "PriceBars": for (i=0; i<temp.length; i++) { line.push([temp[i]['BarDate'], temp[i]['Open'], temp[i]['High'], temp[i]['Low'], temp[i]['Close']]); } break; } ret.push(line); } return ret; }; })(jQuery);
var Db = require('../lib/mongodb').Db, Connection = require('../lib/mongodb').Connection, Server = require('../lib/mongodb').Server; var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; console.log("Connecting to " + host + ":" + port); var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); db.open(function(err, db) { db.dropDatabase(function() { // Fetch the collection test db.collection('test', function(err, collection) { // Remove all records in collection if any collection.remove(function(err, result) { // Insert three records collection.insert([{'a':1}, {'a':2}, {'b':3}], function(docs) { // Count the number of records collection.count(function(err, count) { console.log("There are " + count + " records."); }); // Find all records. find() returns a cursor collection.find(function(err, cursor) { // Print each row, each document has an _id field added on insert // to override the basic behaviour implement a primary key factory // that provides a 12 byte value console.log("Printing docs from Cursor Each") cursor.each(function(err, doc) { if(doc != null) console.log("Doc from Each "); console.dir(doc); }) }); // Cursor has an to array method that reads in all the records to memory collection.find(function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Printing docs from Array") docs.forEach(function(doc) { console.log("Doc from Array "); console.dir(doc); }); }); }); // Different methods to access records (no printing of the results) // Locate specific document by key collection.find({'a':1}, function(err, cursor) { cursor.nextObject(function(err, doc) { console.log("Returned #1 documents"); }); }); // Find records sort by 'a', skip 1, limit 2 records // Sort can be a single name, array, associate array or ordered hash collection.find({}, {'skip':1, 'limit':1, 'sort':'a'}, function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Returned #" + docs.length + " documents"); }) }); // Find all records with 'a' > 1, you can also use $lt, $gte or $lte collection.find({'a':{'$gt':1}}, function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Returned #" + docs.length + " documents"); }); }); collection.find({'a':{'$gt':1, '$lte':3}}, function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Returned #" + docs.length + " documents"); }); }); // Find all records with 'a' in a set of values collection.find({'a':{'$in':[1,2]}}, function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Returned #" + docs.length + " documents"); }); }); // Find by regexp collection.find({'a':/[1|2]/}, function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Returned #" + docs.length + " documents"); }); }); // Print Query explanation collection.find({'a':/[1|2]/}, function(err, cursor) { cursor.explain(function(err, doc) { console.log("-------------------------- Explanation"); console.dir(doc); }) }); // Use a hint with a query, hint's can also be store in the collection // and will be applied to each query done through the collection. // Hint's can also be specified by query which will override the // hint's associated with the collection collection.createIndex('a', function(err, indexName) { collection.hint = 'a'; // You will see a different explanation now that the hint was set collection.find({'a':/[1|2]/}, function(err, cursor) { cursor.explain(function(err, doc) { console.log("-------------------------- Explanation"); console.dir(doc); }) }); collection.find({'a':/[1|2]/}, {'hint':'a'}, function(err, cursor) { cursor.explain(function(err, doc) { console.log("-------------------------- Explanation"); console.dir(doc); db.close(); }) }); }); }); }); }); }); });
'use strict'; var module = angular.module('librarium'); module.controller('GamesList', function ($scope, $resource, GamesRESTService) { $scope.breadcrumb = [ { url: 'games', name: 'Games' } ]; $scope.myData = GamesRESTService.getAllGames().query(); $scope.gridOptions = { data: 'myData' }; });
"use strict"; const angular = require("angular"); require("angular-sanitize"); const app = require("angular").module("app", ["ngSanitize"]); require("./factories"); require("./controllers"); require("./services");
function printError(error) { console.error(`Error: ${error.message}`); } function printMessage(username, badgeCount, points) { const message = `${username} has ${badgeCount} total badge(s) and ${points} points in JavaScript`; console.log(message); } module.exports.printError = printError; module.exports.printMessage = printMessage;
import template from './error.html'; import controller from './error.controller'; import './error.scss'; let ErrorComponent = function () { return { restrict: 'E', scope: {}, template, controller, controllerAs: 'vm', bindToController: true, params:{errors:{value:''}} }; }; export default ErrorComponent;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var index_1 = require("./index"); var express = require("express"); var jwt = require("jsonwebtoken"); var cors = require("cors"); var app = express(); app.use(cors()); var mountpoint = '/'; var prefix = ''; var options = {}; if (!process.env.VIDEOFOLDER) { throw Error('no videofolder provided (by process env)'); } var videofolder = process.env.VIDEOFOLDER; if (process.env.PREFIX) prefix = process.env.PREFIX; if (!process.env.SERVERURI) { throw Error('no SERVERURI provided (by process env)'); } if (!process.env.PORT) { process.env.PORT = 3000; } process.env.PORT = parseInt(process.env.PORT); if (process.env.CONVERSIONDEST) { options.conversion = { dest: process.env.CONVERSIONDEST }; } if (process.env.MODE === 'user' && process.env.SECRET) { options.mode = { type: 'users', secret: process.env.SECRET, ignoreExpiration: true }; } options.serverUri = { path: videofolder, uri: process.env.SERVERURI + mountpoint + 'videolibrary/' }; if (!process.env.MODE) { console.log(videofolder); } else if (process.env.MODE === 'user') { if (!process.env.SECRET) { throw Error('no secret provided (by process env)'); } console.log(jwt.sign({ prefix: '' }, process.env.SECRET)); } app.use(mountpoint, index_1.default(videofolder, options)); app.listen(process.env.PORT);
var data_cost = []; //Kosten function createHistoryCostChart(){ var margin = {top: 60, right: 20, bottom: 120, left: 200}, width = 1160 - margin.right, height = 500 - margin.top - margin.bottom; var x,y,z,xAxis,yAxis,area_pos,area_neg,chart; // chart Kosten x = d3.scaleTime().range([0, width]); y = d3.scaleLinear().range([height, 0]); z = d3.scaleOrdinal(d3.schemeCategory10); area_pos = d3.area() .x(function(d) { return x(d.x); }) .y0(y(0)) .y1(function(d) { return y(d.y); }); area_neg = d3.area() .x(function(d) { return x(d.x); }) .y1(y(0)) .y0(function(d) { return y(d.y); }); chart = d3.select("#cost").append("p").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); xAxis = chart.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(x.axis = d3.axisBottom(x).tickFormat(multiFormat)); yAxis = chart.append("g") .attr("class", "y axis") .call(y.axis = d3.axisLeft(y)); var svg = chart.select(function() { return this.parentNode; }); svg.append("text") .attr("transform", "rotate(-90)") .attr("y", 150) .attr("x",-210) .style("text-anchor", "middle") .text("ct"); if(building_id&&start_date&&end_date) requestCostData(building_id,start_date,end_date,x,y,z,xAxis,yAxis,area_pos,area_neg,chart); } function sortByDateAscending(a, b) { return a.x - b.x; } function requestCostData(building, start_time, end_time, x, y, z, xAxis, yAxis, area_pos, area_neg, chart) { $.getJSON(rest_url+"/rest/getdata/"+building+"/"+start_time+"/"+end_time, function(result) { data_cost = []; for (var i = 0; i < result.length; i++) { var dataJSON = JSON.parse(result[i]); var currentTime = new Date(dataJSON.currentTime.date.year, dataJSON.currentTime.date.month - 1, dataJSON.currentTime.date.day, dataJSON.currentTime.time.hour, dataJSON.currentTime.time.minute, dataJSON.currentTime.time.second, 0); var cost = 0; var production_el = 0; // producers for (var p1 in dataJSON.producers) { if (!dataJSON.producers.hasOwnProperty(p1)) continue; var obj_p = dataJSON.producers[p1]; production_el += obj_p.power_el; cost += obj_p.cost; } for (var s in dataJSON.storages) { if (!dataJSON.storages.hasOwnProperty(s)) continue; var obj_s = dataJSON.storages[s]; if (obj_s.name === "Batterie") { production_el += obj_s.p_out; } } // Strom aus dem Netz / in das Netz cost += 30*(1/(60*60))*(dataJSON.consumption.electrical - production_el); data_cost.push({x: currentTime, y: cost*(-1)}); } data_cost = data_cost.sort(sortByDateAscending); var data_pos = []; var data_neg = []; // copy array for (var j = 0; j < data_cost.length ; j++) { data_pos[j] = {}; data_neg[j] = {}; for (var prop in data_cost[j]) { if (!data_cost[j].hasOwnProperty(prop)) continue; data_pos[j][prop] = data_cost[j][prop]; data_neg[j][prop] = data_cost[j][prop]; } } data_pos.forEach(function(currentValue, index) { if (currentValue.y < 0) { data_pos[index].y = 0; } }); data_neg.forEach(function(currentValue, index) { if (currentValue.y > 0) { data_neg[index].y = 0; } }); var min_y = d3.min(data_cost, function(d) { return d.y })*1.3 > 0 ? 0 : d3.min(data_cost, function(d) { return d.y })*1.3; var max_y = d3.max(data_cost, function(d) { return d.y })*1.3 < 0 ? 0 : d3.max(data_cost, function(d) { return d.y })*1.3; y.domain([min_y, max_y]); x.domain(d3.extent(data_cost, function(d) { return d.x; })); chart.append("path") .datum(data_pos) .attr("class", "area") .attr("opacity", 1) .style("fill", 'green') .style("stroke", 'green') .attr("d", area_pos.y0(y(0))); chart.append("path") .datum(data_neg) .attr("class", "area") .attr("opacity", 1) .style("fill", 'red') .style("stroke", 'red') .attr("d", area_neg.y1(y(0))); xAxis.call(x.axis); yAxis.call(y.axis); var svg = chart.select(function() { return this.parentNode; }); var mean = svg.append('g') .attr('class', 'mean') .attr('transform', 'translate(' + (1160/2 + 150) + ',450)'); var mean_cost = d3.format(".2f")(d3.sum(data_cost, function (d) { return d.y; })/100); var text_color = mean_cost >= 0 ? 'green' : 'red'; mean.append('text') .style("text-anchor", "middle") .text("Gesamtkosten:"); mean.append('text') .attr('y', 30) .style("text-anchor", "middle") .style("stroke", text_color) .style("fill", text_color) .text(mean_cost + "€"); }); }
var User = require('./User') class Parent extends User { constructor( id, first_name, last_name, phone, active, ak_access_token, ak_user_id, ak_token_refresh_interval_sec, ak_token_last_renewed_timestamp, last_login_timestamp, created_on_timestamp, member_since_timestamp, profilePhotoUrl, neighborhood, otherNeighborhood, kids ) { super( id, first_name, last_name, phone, "Parent", active, ak_access_token, ak_user_id, ak_token_refresh_interval_sec, ak_token_last_renewed_timestamp, last_login_timestamp, created_on_timestamp, member_since_timestamp, profilePhotoUrl ) this.neighborhood = neighborhood; this.otherNeighborhood = otherNeighborhood; this.kids = kids; } toString() { return ` Parent\n ${super.toString()} neighborhood\t${this.neighborhood}\n otherNeighborhood\t${this.otherNeighborhood}\n kids\t${this.kids}\n ` } } module.exports = Parent
var User = require('../source/models/User').model; var mongoose = require('../lib/mongoose'); var logger = require('../lib/logging').logger; var list = require('./mocks/users'); exports.testAddUser = function(test){ var length = list.length; for(var i=0; i<length; i++){ var item = list[i]; logger.info( 'User-index ' + i + ' : ' +JSON.stringify(item) ); var user = new User(item); user.save(function(err){ if(err){ logger.error('Fail to save user: '+err); } else{ logger.info('succeed to save user ' + user.username); } }); } test.done(); }; exports.testLoadUser = function(test){ User.find({'_id': 0}, function(err, docs){ if(err){ logger.error('Fail to find: '+err); return; } test.equals(docs.length, 0); test.equals(docs[0].username, 'henryleu'); }); test.done(); };
// @flow /** * Selector to return lobby enable state. * * @param {any} state - State object. * @returns {boolean} */ export function getLobbyEnabled(state: any) { return state['features/lobby'].lobbyEnabled; } /** * Selector to return a list of knocking participants. * * @param {any} state - State object. * @returns {Array<Object>} */ export function getKnockingParticipants(state: any) { return state['features/lobby'].knockingParticipants; } /** * Selector to return lobby visibility. * * @param {any} state - State object. * @returns {any} */ export function getIsLobbyVisible(state: any) { return state['features/lobby'].lobbyVisible; } /** * Selector to return array with knocking participant ids. * * @param {any} state - State object. * @returns {Array} */ export function getKnockingParticipantsById(state: any) { return getKnockingParticipants(state).map(participant => participant.id); }
/* define(['angular','angularMocks', 'app/app'], function (angular, mocks) { describe('MainCtrl', function () { var $scope, ctrl; beforeEach(module('myApp')) beforeEach(inject(function ($controller, $rootScope) { $scope = $rootScope.$new(); ctrl = $controller('MainCtrl', { '$scope': $scope }); })) it('should set message', function () { expect($scope.message).toBeDefined(); }) }) }) */
/** * Copyright 2011 Microsoft Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var assert = require('assert'); var sinon = require('sinon'); // Test includes var testutil = require('../util/util'); // Lib includes var NamedPipeInputChannel = testutil.libRequire('serviceruntime/namedpipeinputchannel'); var RuntimeVersionProtocolClient = testutil.libRequire('serviceruntime/runtimeversionprotocolclient'); var RuntimeVersionManager = testutil.libRequire('serviceruntime/runtimeversionmanager'); suite('runtimeversionmanager-tests', function () { test('getRuntimeClient', function (done) { var versionsEndpointPath = 'versionsEndpointPath'; var inputChannel = new NamedPipeInputChannel(); var stub = sinon.stub(inputChannel, '_readData'); stub.withArgs(versionsEndpointPath).callsArgWith(1, undefined, "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<RuntimeServerDiscovery xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" + "<RuntimeServerEndpoints>" + "<RuntimeServerEndpoint version=\"2011-03-08\" path=\"SomePath.GoalState\" />" + "</RuntimeServerEndpoints>" + "</RuntimeServerDiscovery>" ); var runtimeVersionProtocolClient = new RuntimeVersionProtocolClient(inputChannel); var runtimeKernel = { getGoalStateClient: function () { return {}; }, getCurrentStateClient: function () { return {}; } }; var runtimeVersionManager = new RuntimeVersionManager(runtimeVersionProtocolClient, runtimeKernel); runtimeVersionManager.getRuntimeClient(versionsEndpointPath, function (error, runtimeClient) { assert.equal(error, undefined); assert.notEqual(runtimeClient, null); done(); }); }); });
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var pow = require( '@stdlib/math/base/special/pow' ); var randi = require( '@stdlib/random/base/randi' ); var isInt16Array = require( '@stdlib/assert/is-int16array' ); var pkg = require( './../package.json' ).name; var Int16Array = require( './../lib' ); // FUNCTIONS // /** * Creates a benchmark function. * * @private * @param {PositiveInteger} len - array length * @returns {Function} benchmark function */ function createBenchmark( len ) { var data; var arr; var i; data = []; for ( i = 0; i < len; i++ ) { data.push( randi() ); } arr = new Int16Array( data ); return benchmark; /** * Benchmark function. * * @private * @param {Benchmark} b - benchmark instance */ function benchmark( b ) { var out; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { arr[ i%len ] = randi(); out = arr.sort(); if ( typeof out !== 'object' ) { b.fail( 'should return an object' ); } } b.toc(); if ( !isInt16Array( out ) ) { b.fail( 'should return an Int16Array' ); } b.pass( 'benchmark finished' ); b.end(); } } // MAIN // /** * Main execution sequence. * * @private */ function main() { var len; var min; var max; var f; var i; min = 1; // 10^min max = 5; // 10^max for ( i = min; i <= max; i++ ) { len = pow( 10, i ); f = createBenchmark( len ); bench( pkg+':sort:len='+len, f ); } } main();
const { dest, series, src, symlink } = require('gulp'); const del = require('del'); const inject = require('gulp-inject'); const map = require('map-stream') const path = require('path'); const rename = require('gulp-rename'); const sort = require('gulp-sort'); function deleteSymlinks() { return del(['components/modules/ROOT/pages/*', '!components/modules/ROOT/pages/index.adoc']); } function createSymlinks() { return src('../components/*/src/main/docs/*.adoc') .pipe(map((file, done) => { // this flattens the output to just .../pages/....adoc // instead of .../pages/camel-.../src/main/docs/....adoc file.base = path.dirname(file.path); done(null, file); })) // Antora disabled symlinks, there is an issue open // https://gitlab.com/antora/antora/issues/188 // to reinstate symlink support, until that's resolved // we'll simply copy over instead of creating symlinks // .pipe(symlink('components/modules/ROOT/pages/', { // relativeSymlinks: true // })); // uncomment above .pipe() and remove the .pipe() below // when antora#188 is resolved .pipe(dest('components/modules/ROOT/pages/')); } function nav() { return src('nav.adoc.template') .pipe(inject(src('../components/*/src/main/docs/*.adoc').pipe(sort()), { removeTags: true, transform: (filename, file) => { const filepath = path.basename(filename); const maybeName = /(?:==|##) (.*)/.exec(file.contents.toString()) if (maybeName == null) { throw new Error(`${file.path} doesn't contain Asciidoc heading ('== <Title>') or ('## <Title')`); } return `* xref:${filepath}[${maybeName[1]}]`; } })) .pipe(rename('nav.adoc')) .pipe(dest('components/modules/ROOT/')) } const symlinks = series(deleteSymlinks, createSymlinks); exports.symlinks = symlinks; exports.nav = nav; exports.default = series(symlinks, nav);
import React from "react" import List from "@material-ui/core/List" import ListItem from "@material-ui/core/ListItem" import { Article, Header } from "muy" import Typography from "@material-ui/core/Typography" import { ListItemText } from "@material-ui/core" import Link from "@material-ui/core/Link" export default () => ( <Article> <Header> <Typography component={"h1"} variant={"h1"}> Uhu! Agora é só esperar! </Typography> <Typography component={"p"} variant={"h2"}> Daqui a pouco a gente vai fazer contato com você. </Typography> </Header> <Typography paragraph={true}> Enquanto isso, olha só esses <em lang="en">links</em> interessantes pra você aprender mais sobre programação: </Typography> <List> <ListItem> <ListItemText> <Link href="https://educodar.herokuapp.com/" rel={"noopener noreferrer"} target={"_blank"} tabIndex={0} > Jogo do Aviãozinho </Link> <br /> Passeie pelas nuvens em busca de balões. </ListItemText> </ListItem> </List> </Article> )
"use strict"; var chai = require('chai'); var expect = chai.expect; describe('templates with boolean, 0, or "" default values', function () { var bbj2j = require('../index'); var j2j = bbj2j.instance(); it('default: false', function () { var template = { content: { id: { dataKey: 'id', default: 'unknown' }, boolVal: { dataKey: 'boolVal', default: false } } }; var r = j2j.run(template, { id: 'test' }); expect(r).to.deep.equal({ id: 'test', boolVal: false }); }); it('default: true', function () { var template = { content: { id: { dataKey: 'id', default: 'unknown' }, boolVal: { dataKey: 'boolVal', default: true } } }; var r = j2j.run(template, { id: 'test' }); expect(r).to.deep.equal({ id: 'test', boolVal: true }); }); it('default: 0', function () { var template = { content: { id: { dataKey: 'id', default: 'unknown' }, boolVal: { dataKey: 'boolVal', default: 0 } } }; var r = j2j.run(template, { id: 'test' }); expect(r).to.deep.equal({ id: 'test', boolVal: 0 }); }); it('default: ""', function () { var template = { content: { id: { dataKey: 'id', default: 'unknown' }, boolVal: { dataKey: 'boolVal', default: "" } } }; var r = j2j.run(template, { id: 'test' }); expect(r).to.deep.equal({ id: 'test', boolVal: "" }); }); });
/** * This file is part of the Nodium core package * * (c) Niko van Meurs & Sid Mijnders * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * @author Niko van Meurs <nikovanmeurs@gmail.com> */ (function (context, undefined) { /** * Returns an object based on a fully qualified classname * @param string fullyQualifiedClassName * @return mixed */ context.use = function (fullyQualifiedClassName) { var components = fullyQualifiedClassName.split('.'), parent = context, child; while (child = components.shift()) { parent = parent[child] || {}; } return parent; }; }(this));
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This option controls spacing before a inline comment. * @author Joe Schafer */ goog.module('eslintClosure.rules.inlineCommentSpacing'); const utils = goog.require('eslintClosure.utils'); /** @const {number} */ const DEFAULT_PRECEDING_SPACES = 1; /** @const {!ESLint.RuleDefinition} */ const INLINE_COMMENT_SPACING_RULE = { meta: { docs: { description: 'enforce consistent spacing before the `//` at line end', category: 'Stylistic Issues', recommended: false, }, fixable: 'whitespace', schema: [ { type: 'integer', minimum: 0, maximum: 5, }, ], }, /** * @param {!ESLint.RuleContext} context * @return {!ESLint.VisitorMapping} */ create(context) { // Check for null explicitily because 0 is a falsey value. /** @const {number} */ const minPrecedingSpaces = context.options[0] == null ? DEFAULT_PRECEDING_SPACES : /** @type {number} */ (context.options[0]); /** * Reports a given comment if it's invalid.. * @param {!AST.LineComment} commentNode A comment node to check. * @return {undefined} */ function checkLineCommentForPrecedingSpace(commentNode) { const sourceCode = context.getSourceCode(); // Need to call getComments to attach comments to the AST. sourceCode.getComments(commentNode); // TODO: I'm not sure why I can't just call getTokenBefore. The tests // fail if either of the two calls is missing. const previousToken = sourceCode.getTokenBefore(commentNode, 1) || sourceCode.getTokenOrCommentBefore(commentNode); // Return early if there's no tokens before commentNode or there's only // whitespace. if (previousToken == null || !utils.nodesShareOneLine(commentNode, previousToken)) { return; } const whiteSpaceGap = commentNode.start - previousToken.end; if (whiteSpaceGap < minPrecedingSpaces) { const spacesNoun = minPrecedingSpaces === 1 ? 'space' : 'spaces'; context.report({ node: commentNode, message: `Expected at least ${minPrecedingSpaces} ${spacesNoun} ` + `before inline comment.`, /** * @param {!ESLint.Fixer} fixer * @return {!ESLint.FixCommand} */ fix(fixer) { const numNeededSpaces = minPrecedingSpaces - whiteSpaceGap; const spaces = new Array(numNeededSpaces + 1).join(' '); return fixer.insertTextBefore(commentNode, spaces); }, }); } } return { LineComment: checkLineCommentForPrecedingSpace, }; }, }; exports = INLINE_COMMENT_SPACING_RULE;
/** * This script is a demonstration of how you can use a basic spritesheet. This covers loading of spritesheets and changing the cell gameobjects will use. **/ var Spritesheets = new Kiwi.State('Spritesheets'); Spritesheets.preload = function () { //Just making the stage smaller this.game.stage.resize(800, 250); // Load our spritesheet we want to use. /** * When loading spritesheets you have to pass slightly more information. * - Parameter One - Name of the spritesheet for your reference. * - Parameter Two - The URL to the spritesheet. * - Parameter Three - The width of each cell * - Parameter Four - The height of each cell **/ this.addSpriteSheet('characters', 'assets/spritesheets/characters.png', 150, 117); } Spritesheets.create = function () { /** * To change which cell the sprite is using we can change the CELL INDEX which is on both the sprite and static image objects. **/ this.skele = new Kiwi.GameObjects.Sprite(this, this.textures.characters, 10, 30); this.skele.cellIndex = 2; this.robot = new Kiwi.GameObjects.Sprite(this, this.textures.characters, 210, 30); this.robot.cellIndex = 8; this.spartan = new Kiwi.GameObjects.Sprite(this, this.textures.characters, 410, 30); this.spartan.cellIndex = 5; //add them all to the stage this.addChild(this.skele); this.addChild(this.robot); this.addChild(this.spartan); } //Create's a new Kiwi.Game. /* * Param One - DOMID - String - ID of a DOMElement that the game will reside in. * Param Two - GameName - String - Name that the game will be given. * Param Three - State - Object - The state that is to be loaded by default. * Param Four - Options - Object - Optional options that the game will use whilst playing. Currently this is used to to choose the renderer/debugmode/device to target */ if(typeof gameOptions == "undefined") gameOptions = {}; var game = new Kiwi.Game('game', 'KiwiExample', Spritesheets, gameOptions);
import React from 'react'; import { Box, Button, CheckBox, FileInput, Form, FormField, Grommet, RadioButtonGroup, RangeInput, Select, TextArea, } from 'grommet'; import { grommet } from 'grommet/themes'; export const FieldWithComponentProp = () => ( <Grommet full theme={grommet}> <Box fill overflow="auto" align="center" justify="center" pad="large"> <Box flex={false} width="medium"> <Form onReset={event => console.log(event)} onSubmit={({ value, touched }) => console.log('Submit', value, touched) } > <FormField label="Name" name="name" required validate={[ { regexp: /^[a-z]/i }, name => { if (name && name.length === 1) return 'must be >1 character'; return undefined; }, name => { if (name && name.length <= 2) return { message: "that's short", status: 'info' }; return undefined; }, ]} /> <FormField label="Email" name="email" type="email" required /> <FormField label="Employee ID" name="employeeId" required validate={{ regexp: /^[0-9]{4,6}$/, message: '4-6 digits' }} /> <FormField name="subscribe" component={CheckBox} label="Subscribe?" /> <FormField name="ampm" component={RadioButtonGroup} options={['morning', 'evening']} /> <FormField label="Size" name="size" component={Select} onChange={event => console.log(event)} options={['small', 'medium', 'large', 'xlarge']} /> <FormField label="Comments" name="comments" component={TextArea} /> <FormField label="Age" name="age" component={RangeInput} pad min={15} max={75} /> <FormField label="File" name="file" component={FileInput} /> <FormField label="Custom" name="custom" component={props => <input {...props} />} /> <Box direction="row" justify="between" margin={{ top: 'medium' }}> <Button label="Cancel" /> <Button type="reset" label="Reset" /> <Button type="submit" label="Update" primary /> </Box> </Form> </Box> </Box> </Grommet> ); FieldWithComponentProp.storyName = 'Field with component prop'; export default { title: 'Input/Form/Field with component prop', };
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import firebase from 'firebase'; import ReduxThunk from 'redux-thunk'; import reducers from './src/reducers'; // import LoginForm from './src/components/LoginForm'; import Router from './src/Router'; class App extends Component { componentWillMount() { // Initialize Firebase const config = { apiKey: 'AIzaSyBlE5TJxuDiBiGmhGH1eLymxCmAer7d5Rg', authDomain: 'manager-bab0a.firebaseapp.com', databaseURL: 'https://manager-bab0a.firebaseio.com', projectId: 'manager-bab0a', storageBucket: 'manager-bab0a.appspot.com', messagingSenderId: '607355351109' }; firebase.initializeApp(config); } render() { const store = createStore(reducers, {}, applyMiddleware(ReduxThunk)); return ( <Provider store={store}> <Router /> </Provider> ); } } export default App;
$(function() { var currentPhone = null; $("#input_submit").click(function() { var phone = $("#input_phone").val(); currentPhone = phone; load(phone); loadUserLocation(phone); $("#imageDiv1 div").empty().append("<img src='api/graphic/orignaggregation/" + phone + "' width='1200' height='600'>"); $("#imageDiv2 div").empty().append("<img src='api/graphic/aggregation/" + phone + "' width='1200' height='600'>"); }); $("#userDiv a").click(function() { if (currentPhone == null) { return; } var userLocation = ajax.GET("/location/mining/" + currentPhone, null); updateUserLocation(userLocation); }); function load(phone) { var $tbody = $("#resultDiv tbody"); $tbody.empty(); var locations = ajax.GET("/location/" + phone, null); for ( var i = 0; i < locations.length; i++) { var location = locations[i]; var $tr = $("<tr></tr>"); $tr.append($("<td></td>").text(i + 1)); var loginDate = new Date(location.loginTime); var logoutDate = new Date(location.logoutTime); $tr.append($("<td></td>").text(loginDate.format("yyyy-MM-dd hh:mm:ss") + " - " + logoutDate.format("yyyy-MM-dd hh:mm:ss"))); $tr.append($("<td></td>").text(location.lac)); $tr.append($("<td></td>").text(location.ci)); var state = location.state; var tdClass = ""; if (state == -1) { tdClass = "unknown"; } else if (state == 0) { tdClass = "normal"; } else if (state == 1) { tdClass = "abnormal"; } else if (state == 2) { tdClass = "guess"; } if (location.state == -1) { // 无法定位坐标 $tr.append($("<td class='" + tdClass + "'></td>").text("UnKnown")); } else { // 可以定位坐标 var station = location.station; $tr.append($("<td class='" + tdClass + "'></td>").text("(" + station.lng + "," + station.lat + ")")); } $tbody.append($tr); } } function loadUserLocation(phone) { var userLocation = ajax.GET("/userlocation/" + phone, null); updateUserLocation(userLocation); } function updateUserLocation(userLocation) { var $tbody = $("#userDiv tbody"); $tbody.empty(); $("#userDiv .li_number span").text(""); $("#userDiv .li_accuracy span").text(""); $("#userDiv .li_noise span").text(""); $("#userDiv .li_station span").text(""); if (userLocation == null) { return; } $("#userDiv .li_number span").text(userLocation.number); $("#userDiv .li_accuracy span").text(formatNumber(userLocation.accuracy, "#,##0.00")); $("#userDiv .li_noise span").text(formatNumber(userLocation.noise, "#,##0.00")); $("#userDiv .li_station span").text(formatNumber(userLocation.station, "#,##0.00")); if (userLocation.number > 0) { var pArray = userLocation.locations; var tArray = userLocation.timeSegments; var eArray = userLocation.degrees; for ( var i = 0; i < userLocation.number; i++) { var $tr = $("<tr></tr>"); $tr.append($("<td></td>").text(i + 1)); $tr.append($("<td></td>").text(pArray[i])); $tr.append($("<td></td>").text(tArray[i])); $tr.append($("<td></td>").text(formatNumber(eArray[i], "#,##0.00"))); $tbody.append($tr); } } } });
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // test basic coffeescript functionality couchTests.coffee = function(debug) { var db_name = get_random_db_name(); var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"}); db.createDb(); if (debug) debugger; var ddoc = { _id: "_design/coffee", language: "coffeescript", views: { myview: { map: '(doc) -> if doc.foo\n emit(doc.foo, 1)', reduce: '(keys, values, rereduce) ->\n sum = 0\n for x in values\n sum = sum + x\n sum' } }, shows: { myshow: '(doc) ->\n "Foo #{doc.foo}"' }, lists: { mylist: '(head, req) ->\n while row = getRow()\n send("Foo #{row.value}")\n return "Foo"' }, filters: { filter: "(doc) ->\n doc.foo" } }; db.save(ddoc); var docs = [ {_id:"a", foo: 100}, {foo:1}, {foo:1}, {foo:2}, {foo:2}, {bar:1}, {bar:1}, {bar:2}, {bar:2} ]; db.bulkSave(docs); var res = db.view("coffee/myview"); TEquals(5, res.rows[0].value, "should sum up values"); var res = CouchDB.request("GET", "/" + db.name + "/_design/coffee/_show/myshow/a"); TEquals("Foo 100", res.responseText, "should show 100"); var res = CouchDB.request("GET", "/" + db.name + "/_design/coffee/_list/mylist/myview"); TEquals("Foo 5Foo", res.responseText, "should list"); var changes = db.changes({filter: "coffee/filter"}); TEquals(5, changes.results.length, "should have changes"); // cleanup db.deleteDb(); };