code
stringlengths
2
1.05M
import { emit } from "../../api"; import { setActiveRoom } from "../room/roomSlice.js"; export function presentChanged(present) { return { type: "localUser/present", present }; } export const ping = () => () => emit("/user/current/ping"); export const changeActiveRoom = roomId => dispatch => { dispatch(setActiveRoom(roomId)); return emit("/user/current/activity", { room: roomId }); }; export function changePresent(present) { return dispatch => { return emit("/user/current/present", { present }).then(() => dispatch(presentChanged(present))); }; }
(function(b,g,j,e,q,o){var i,d,c,f,h,l=function(){i=JSON.parse(e.getItem(b))||{};i=q?q({},i):i},k=function(m,a,n){m.addEventListener('click',function(){l();i[n]=a.value;e.setItem(b,JSON.stringify(i))})};l();o.querySelectorAll('.js-stream-item').forEach(function(a){if(!a.getAttribute(g)){d=a.getAttribute(j);c=a.querySelector('.ProfileCard-bio').parentNode;c.appendChild(f=o.createElement('textarea'),f.style.width='100%',f.style.height='150px',f.setAttribute('placeholder','メモ'),f.textContent=i[d]||'',f);c.appendChild(h=o.createElement('button'),h.className='btn',h.textContent='このアカウントのメモを保存',k(h,f,d),h);a.setAttribute(g,1)}})})('followmemo','data-applied','data-item-id',localStorage,Object.assign,document);
/* * Returns Messages * * This contains all the text for the Returns component. */ import { defineMessages } from 'react-intl'; export default defineMessages({ header: { id: 'app.components.Returns.header', defaultMessage: 'returns', }, returnPolicy: { id: 'app.components.Returns.returnPolicy', defaultMessage: 'Return Policy', }, message: { id: 'app.components.Returns.message', defaultMessage: 'This item must be returned within 30 days of the ship date. See {policyLink} for details. Prices, promotions, styles and availability may vary by store and online.', }, });
import React from 'react' import '../../styles/gkm-item.scss'; import ProductItem from './ProductItem' import Input from '../Common/Input' import SearchBar from '../SearchBar'; import _ from 'lodash' class EtsyProduct extends React.Component { constructor(props, context) { super(props, context); this.editables = { name: { max: 20, display: 'Name' }, shortDescription: { max: 100, display: 'Short Description' }, twitterTitle: { max: 100, display: 'Twitter Text' } }; } onUpdateField(update) { console.log(update) let product = this.props.product _.each(update, (v, k) => { product[k] = v; }) this.props.updateItem(product); } getListingById(id) { return _.find(this.props.listings, (l) => l.id === id) } editableFieldsHtml() { const { product } = this.props return ( <div> {_.map(this.editables, (v, fld) => ( <Input title={v.display} fld={fld} value={product[fld]} id={product.id} onUpdate={ (i, update) => this.onUpdateField(update) } />)) } </div> ) } onAddtoCategory(category) { const { product } = this.props; addItemtoCategory(product, category) } render() { const { product, listings, addListingToProduct } = this.props; const loader = (<div>loading...</div >) const productItems = product.populatedListings.map((listing) => (listing ? < ProductItem key={listing.id} product={listing} inProduct={true} /> : loader)) return ( <div className='gkm-etsy-product' id={product.id}> <h5>Etsy Product</h5> <div> Product Name: {product.name} <div>Categories:</div> {_.map(product.hashtags.all(), (hashtag) => (<div>{hashtag}</div>))} <Input title="add category" fld='category' resetOnClick={true} button={{ text: 'ADD!', action: this.onAddtoCategory }} /> {this.editableFieldsHtml()} </div> {productItems} <div> Add another listing: </div> <SearchBar products={listings} onSelect={ (listingId) => { addListingToProduct(product, this.getListingById(listingId)) } } /> </div> ) } } /* Item.propTypes = { }; */ export default EtsyProduct
/** * Main JS file for Jasper behaviours */ if (typeof jQuery == 'undefined') { document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></' + 'script>'); } (function ($) { "use strict"; // Header Parallax and Fade $(window).on('scroll', function() { var scroll_top = $(this).scrollTop(); var top_offset = 600; $('#site-head-content').css({ 'opacity' : (1-scroll_top/top_offset), 'top' : (scroll_top*-.2) }); /* // Background Image Parallax $('#site-head').css({ 'background-position' : 'center ' + (scroll_top*-.07) + 'px' }); */ }); // Shameless self-promotion console.log("Yo, fellow dev. Check out our homepage, and find out about our other goodies: http://www.farmsoftstudios.com") }(jQuery));
describe('dev-radiolist', function() { beforeEach(function() { browser().navigateTo(mainUrl); }); it('should show radio options and submit new value', function() { var s = '[ng-controller="DevRadiolistCtrl"] '; expect(element(s+'a.normal ').text()).toMatch('status1'); element(s+'a.normal ').click(); expect(element(s+'a.normal ').css('display')).toBe('none'); expect(element(s+'form[editable-form="$form"]').count()).toBe(1); expect(element(s+'form input[type="radio"]:visible:enabled').count()).toBe(2); expect(using(s+'label:eq(0)').input('$parent.$parent.$data').val()).toBe('true'); expect(using(s+'label:eq(1)').input('$parent.$parent.$data').val()).toBe('false'); // select status2 using(s+'label:eq(1)').input('$parent.$parent.$data').select('false'); element(s+'form button[type="submit"]').click(); expect(element(s+'a.normal ').css('display')).not().toBe('none'); expect(element(s+'a.normal ').text()).toMatch('status2'); expect(element(s+'form').count()).toBe(0); }); it('should show radio options and call on-change event', function() { var s = '[ng-controller="DevRadiolistCtrl"] '; expect(element(s+'a.nobuttons ').text()).toMatch('status1'); element(s+'a.nobuttons ').click(); expect(element(s+'a.nobuttons ').css('display')).toBe('none'); expect(element(s+'form[editable-form="$form"]').count()).toBe(1); expect(element(s+'form input[type="radio"]:visible:enabled').count()).toBe(2); expect(element(s+'form input[type="radio"]').attr('ng-change')).toBeDefined(); expect(using(s+'label:eq(0)').input('$parent.$parent.$data').val()).toBe('true'); expect(using(s+'label:eq(1)').input('$parent.$parent.$data').val()).toBe('false'); // select status2 using(s+'label:eq(1)').input('$parent.$parent.$data').select('false'); element(s).click(); expect(element(s+'a.nobuttons ').css('display')).not().toBe('none'); expect(element(s+'a.nobuttons ').text()).toMatch('status1'); expect(element(s+'form').count()).toBe(0); }); });
import React from 'react'; import styles from './App.less'; import withContext from '../../decorators/withContext'; import withStyles from '../../decorators/withStyles'; import Rankinglist from '../Rankinglist/Rankinglist'; @withContext @withStyles(styles) class App { render() { return ( <div id="app"> <div className="panel panel-primary"> <div className="panel-heading"> <h3 className="panel-title">Norges Tour</h3> </div> <div id="main-wrapper"> <nav className="sidebar-left" id="left-menu"> <ul className="nav nav-pills nav-stacked"> <li role="presentation" className="active"><a href="#"> <span className="glyphicon glyphicon-stats" aria-hidden="true"></span> Rankinglister</a> </li> <li role="presentation" className="disabled"><a href="#"> <span className="glyphicon glyphicon-bullhorn" aria-hidden="true"></span> Resultater</a> </li> <li role="presentation" className="disabled"><a href="#"> <span className="glyphicon glyphicon-align-justify" aria-hidden="true"></span> Turneringer</a> </li> </ul> </nav> <main> <Rankinglist /> </main> </div> </div> </div> ); } } export default App;
/** * tiny-di * @module binding/lazy * @copyright Dennis Saenger <tiny-di-15@mail.ds82.de> */ 'use strict'; import { AbstractBinding } from './abstract'; export class LazyBinding extends AbstractBinding { constructor(injector, key, path, opts) { super(injector, key); this.path = path; this.opts = opts; } load() { return this.injector.load(this.key, this.path, this.opts); } $get() { return this.load(); } }
const mtype = require('@lib/mediatype'); const model = require('@lib/model'); const fs = require('fs'); const mcdir = require('@lib/mcdir'); module.exports = function(r) { const db = require('../db')(r); async function addFileToDirectoryInProject(fileToUpload, directoryId, projectId, userId) { let fileEntry = { // Create the id for the file being uploaded as this will determine // the location of the uploaded file in our object store. id: await r.uuid(), name: fileToUpload.name, checksum: fileToUpload.hash, mediatype: mtype.mediaTypeDescriptionsFromMime(fileToUpload.type), size: fileToUpload.size, path: fileToUpload.path, owner: userId, parentId: '', }; let file = await getFileByNameInDirectory(fileToUpload.name, directoryId); if (!file) { // There is no existing file with this name in the directory. fileEntry.usesid = await findMatchingFileIdByChecksum(fileEntry.checksum); return await loadNewFileIntoDirectory(fileEntry, directoryId, projectId); } else if (file.checksum !== fileEntry.checksum) { // There is an existing file in the directory but it has a different // checksum, so we have to do a little book keeping to make this file // the current file, set its parent entry back to the existing, as well // as do the usual steps for uploading a file into the object store. fileEntry.usesid = await findMatchingFileIdByChecksum(fileEntry.checksum); return await loadExistingFileIntoDirectory(file, fileEntry, directoryId, projectId); } else { // If we are here then there is a file with the same name in the directory // and it has the same checksum. In that case there is nothing to load // into the database as the user is attempting to upload an existing // file (name and checksum match the existing file). removeFile(fileEntry.path); return file; } } // getFileByNameInDirectory will return the current file in the directory // that matches the filename. This is used to construct multiple versions // of a file, with only one version being the current one. async function getFileByNameInDirectory(fileName, directoryId) { let file = await r.table('datadir2datafile').getAll(directoryId, {index: 'datadir_id'}) .eqJoin('datafile_id', r.table('datafiles')).zip() .filter({name: fileName, current: true}); if (file) { return file[0]; // query returns an array of 1 entry. } return null; } async function loadNewFileIntoDirectory(fileEntry, directoryId, projectId) { await addToObjectStore(fileEntry); return await createFile(fileEntry, directoryId, projectId); } async function loadExistingFileIntoDirectory(parent, fileEntry, directoryId, projectId) { await addToObjectStore(fileEntry); fileEntry.parentId = parent.id; let created = await createFile(fileEntry, directoryId, projectId); // Parent is no longer the current file await r.table('datafiles').get(parent.id).update({current: false}); return created; } async function addToObjectStore(fileEntry) { if (fileEntry.usesid === '') { // This is a brand new file so move into the object store. await mcdir.moveIntoStore(fileEntry.path, fileEntry.id); } else { // There is already a file in the store with the same checksum // so delete uploaded file. removeFile(fileEntry.path); } } // findMatchingFileIdByChecksum will return the id of the file that // was uploaded with the name checksum or "" if there is no match. async function findMatchingFileIdByChecksum(checksum) { let matching = await r.table('datafiles').getAll(checksum, {index: 'checksum'}); if (matching.length) { // Multiple entries have been found that have the same checksum. In the database // a file has a usesid which points to the original entry that was first uploaded // with the matching checksum. So, we take the first entry in the list, it is // either this original upload, or a file with a usesid that points to the original // upload. We can determine this by checking if usesid === "". If it is return the // id, otherwise return the usesid. return matching[0].usesid === '' ? matching[0].id : matching[0].usesid; } // If we are here then there was no match found, so just return "" to signify no match. return ''; } function removeFile(path) { try { fs.unlinkSync(path); } catch (e) { return false; } } async function createFile(fileEntry, directoryId, projectId) { let file = new model.DataFile(fileEntry.name, fileEntry.owner); file.mediatype = fileEntry.mediatype; file.size = fileEntry.size; file.uploaded = file.size; file.checksum = fileEntry.checksum; file.usesid = fileEntry.usesid; file.id = fileEntry.id; file.parent = fileEntry.parentId ? fileEntry.parentId : ''; let created = await db.insert('datafiles', file); await addFileToDirectory(created.id, directoryId); await addFileToProject(created.id, projectId); return created; } async function addFileToDirectory(fileId, directoryId) { const dd2df = new model.DataDir2DataFile(directoryId, fileId); await r.table('datadir2datafile').insert(dd2df); } async function addFileToProject(fileId, projectId) { let p2df = new model.Project2DataFile(projectId, fileId); await r.table('project2datafile').insert(p2df); } return { addFileToDirectoryInProject, createFile, }; };
'use strict'; import ResponseHandler from './response-handler'; import retrieve from './retrieve'; class ResultList { constructor(search, options, onSuccess, onFailure) { this._search = search; this._options = options; this._onSuccess = onSuccess; this._onFailure = onFailure; this._requestPromises = []; // first call of next will increment to desired page this._options.page -= 1; } next() { const nextPage = this._options.page += 1; if (this._requestPromises[nextPage]) { return this._requestPromises[nextPage]; } return this._get(); } previous() { if (this._options.page <= 1) { throw new Error('There is no previous page'); } const previousPage = this._options.page -= 1; if (this._requestPromises[previousPage]) { return this._requestPromises[previousPage]; } return this._get(); } _get() { const page = this._options.page; const perPage = this._options.per_page; const promise = retrieve(this._search, this._options) .then(this._success(page, perPage)) .catch(this._failure(page, perPage)); this._requestPromises[page] = promise; return promise; } _success(page, perPage) { return res => { const resHndlr = new ResponseHandler(res, page, perPage, this._onSuccess); return resHndlr.success(); }; } _failure(page, perPage) { return res => { const resHndlr = new ResponseHandler(res, page, perPage, this._onFailure); return resHndlr.failure(); }; } } export default ResultList;
// ==UserScript== // @name GitHub Label Manager // @namespace http://github.com/senritsu // @version 0.1 // @description Enables importing/exporting of repository labels // @author senritsu // @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js // @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser.min.js // @match http*://github.com/*/*/labels* // ==/UserScript== /* jshint ignore:start */ var inline_src = (<><![CDATA[ /* jshint ignore:end */ /* jshint esnext: true */ /* jshint asi:true */ const find = (selector, context) => (context || document).querySelector(selector) const findAll = (selector, context) => (context || document).querySelectorAll(selector) const newLabelButton = find('.labels-list .subnav button.js-details-target') const importButton = document.createElement('button') importButton.id = 'import-labels' importButton.classList.add('btn', 'btn-default', 'right', 'select-menu-button') importButton.textContent = 'Import ' const exportButton = document.createElement('button') importButton.id = 'export-labels' exportButton.classList.add('btn', 'btn-default', 'right') exportButton.textContent = 'Export' const author = find('span.author a').textContent const repository = find('.repohead-details-container strong[itemprop=name] a').textContent const exportLink = document.createElement('a') exportLink.style.display = 'none' exportLink.download = `${author}-${repository}-labels.json` exportButton.appendChild(exportLink) const newLabelForm = find('form.new-label') const importForm = document.createElement('form') importForm.id = 'label-import-toolbar' importForm.classList.add('form') importForm.style.padding = '10px' importForm.style.marginBottom = '15px' importForm.style.backgroundColor = '#fafafa' importForm.style.border = '1px solid #e5e5e5' importForm.style.display = 'none' const importInput = document.createElement('input') importInput.id = 'label-import-file' importInput.classList.add('form-control', 'right') importInput.type = 'file' importForm.appendChild(importInput) const clearAllDiv = document.createElement('div') clearAllDiv.classList.add('checkbox', 'right') clearAllDiv.style.marginTop = '9px' clearAllDiv.style.marginRight = '15px' importForm.appendChild(clearAllDiv) const clearAllLabel = document.createElement('label') clearAllDiv.appendChild(clearAllLabel) const clearAllCheckbox = document.createElement('input') clearAllCheckbox.id = 'clear-labels-before-import' clearAllCheckbox.type = 'checkbox' clearAllLabel.appendChild(clearAllCheckbox) clearAllLabel.appendChild(document.createTextNode(' Clear all existing labels first')) const clearfix = document.createElement('div') clearfix.classList.add('clearfix') importForm.appendChild(clearfix) console.log($) if(newLabelButton) { setup() } function setup() { const parent = newLabelButton.parentNode parent.insertBefore(importButton, newLabelButton) parent.insertBefore(exportButton, newLabelButton) newLabelForm.parentNode.insertBefore(importForm, newLabelForm) let open = false importButton.addEventListener('click', (event) => { open = !open importForm.style.display = open ? 'block' : 'none' }) importInput.addEventListener('change', (event) => { const reader = new FileReader() reader.onload = (event) => { const labels = JSON.parse(reader.result) if(clearAllCheckbox.checked) { deleteAllLabels() } for(const label of labels) { addLabel(label) } } reader.readAsText(importInput.files[0]) }) exportButton.addEventListener('click', exportLabels) } function rgb2hex(rgb) { const [_, r, g, b] = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/) const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2) return "#" + hex(r) + hex(g) + hex(b) } function exportLabels() { const labels = Array.from(findAll('.labels-list-item .label-link')) .map((label) => ({ name: find('.label-name', label).textContent, color: rgb2hex(label.style.backgroundColor) })) const data = 'data:text/json;charset=utf8,' + encodeURIComponent(JSON.stringify(labels, null, 2)); exportLink.href = data exportLink.click() } function findLabel(label) { return Array.from(findAll('.labels-list-item')) .filter((x) => find('.label-name', x).textContent === label.name)[0] } function updateLabel(label, element) { find('.js-edit-label', element).click() find('.label-edit-name', element).value = label.name find('.color-editor-input', element).value = label.color find('.new-label-actions .btn-primary', element).click() } function addLabel(label) { find('input.label-edit-name', newLabelForm).value = label.name find('input#edit-label-color-new', newLabelForm).value = label.color find('button[type=submit]', newLabelForm).click() } function deleteLabel(element) { find('.labels-list-actions button.js-details-target', element).click() find('.label-delete button[type=submit]', element).click() } function deleteAllLabels() { const labels = Array.from(findAll('.labels-list-item')) for(const label of labels) { deleteLabel(label) } } /* jshint ignore:start */ ]]></>).toString(); var c = babel.transform(inline_src); eval(c.code); /* jshint ignore:end */
// moment.js locale configuration // locale : german (de) // author : lluchs : https://github.com/lluchs // author: Menelion Elensúle: https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } return moment.defineLocale('de', { months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), monthsShort : 'Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), longDateFormat : { LT: 'HH:mm [Uhr]', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY LT', LLLL : 'dddd, D. MMMM YYYY LT' }, calendar : { sameDay: '[Heute um] LT', sameElse: 'L', nextDay: '[Morgen um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gestern um] LT', lastWeek: '[letzten] dddd [um] LT' }, relativeTime : { future : 'in %s', past : 'vor %s', s : 'ein paar Sekunden', m : processRelativeTime, mm : '%d Minuten', h : processRelativeTime, hh : '%d Stunden', d : processRelativeTime, dd : processRelativeTime, M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); }));
//!Defines two helper functions. /* * c * https://github.com/rumpl/c * * Copyright (c) 2012 Djordje Lukic * Licensed under the MIT license. */ "use strict"; const helpers = module.exports; const colors = require("colors/safe"); //Despite looking unused, is not unused. const fs = require("fs"); const SPACING = 1; //Change this value if you want more or less space between file names and comments. const PADDING = " "; //Change this value for what character should present your padding. /**Prints a coloured node name, padding, and it's assigned comment. * @param {string} nodeName The name of the node. * @param {string} nodeComment The comment for the node. * @param {number} maxLine The length of the longest node name in the specified directory. * @param {string} dir the relative filepath to a directory, the contents of which will be listed. */ function print(nodeName, nodeComment, maxLine, dir) { nodeComment = nodeComment || ""; nodeComment = nodeComment.replace(/(\r\n|\n|\r)/gm, " "); //Removes any new lines with blank spaces. let pad; //The amount of spacing & the colouring changes depending on whether 'file' is a file or a directory. if (fs.statSync(dir + "/" + nodeName).isFile()) { pad = PADDING.repeat(maxLine - nodeName.length + 1 + SPACING); console.log( // @ts-ignore - TS compiler throws an unnecessary error. colors.brightGreen(nodeName) + pad + colors.yellow(nodeComment) ); } else { pad = PADDING.repeat(maxLine - nodeName.length + SPACING); console.log( // @ts-ignore - TS compiler throws an unnecessary error. colors.brightCyan(nodeName + "/") + pad + colors.yellow(nodeComment) ); } } //TODO: refactor printFileComments & printOnlyComments into one function - they're almost identical for the most part /**Prints all of the files and sub-directories of a specified directory, as well as their assigned comments. * @param {Array<string>} files An array of all of the file names in the specified directory. * @param {Array<string>} comments An array of all of the comments in the specified directory. * @param {string} dir the relative filepath to a directory, the content of which will be listed. */ helpers.printFileComments = function (files, comments, dir) { //Gets the length of the longest filename in the array - iterators through files. const maxLine = maxLength(files); //Prints the current file and it's comment print(".", comments["."], maxLine, dir); print("..", comments[".."], maxLine, dir); //For each file run the print function. files.forEach(function (file) { print(file, comments[file], maxLine, dir); }); }; /**Prints only the files and sub-directories of a specified directory which have comments, as well as their assigned comments. * @param {Array<string>} filesNames An array of all of the file names in the specified directory. * @param {Array<string>} comments An array of all of the comments in the specified directory. * @param {string} relativePathToTarget the relative filepath to a directory, the content of which will be listed. */ helpers.printOnlyComments = function ( filesNames, comments, relativePathToTarget ) { //Gets the length of the longest filename in the array - iterators through files. const maxLine = maxLength(filesNames); //Prints the current file and it's comment if (comments["."]) print(".", comments["."], maxLine, relativePathToTarget); if (comments[".."]) print("..", comments[".."], maxLine, relativePathToTarget); //For each file with a comment, run the print function. filesNames.forEach(function (file) { if (comments[file]) print(file, comments[file], maxLine, relativePathToTarget); }); }; /**Calculates the longest file name from all the returned files. * @param {Array<string>} files an array of all the file names in the specified directory. * @returns {number} Returns the length of the longest name in the array. */ function maxLength(files) { return files.reduce((a, b) => { return b.length > a ? b.length : a; }, 0); }
/** * shuji (周氏) * https://github.com/paazmaya/shuji * * Reverse engineering JavaScript and CSS sources from sourcemaps * * Copyright (c) Juga Paazmaya <paazmaya@yahoo.com> (https://paazmaya.fi) * Licensed under the MIT license */ const fs = require('fs'), path = require('path'); const MATCH_MAP = /\.map$/iu; const MATCH_CODE = /\.(js|css)$/iu; const FIND_SOURCE_FILE = /\/\/#\s*sourceMappingURL=([.\w]+map)/iu; const FIND_SOURCE_BASE64 = /\/\*?\/?#\s*sourceMappingURL=([.\w\-/=;:]*)base64,([\w]+=)/iu; const FIND_SOURCE_UENC = /\/\*?\/?#\s*sourceMappingURL=([.\w\-/=;:]+),([;:,.\-\w%]+)/iu; /** * Find the sourceMap and return its contents. * In case the given filepath is already the sourceMap file, not much is done. * In case the given filepath is a JavaScript file, then the matching sourceMap * is being search for. * * @param {string} filepath * @param {object} options Options object. If not defined, verbose=false * @param {boolean} options.verbose Shall there be more output * * @returns {string|boolean} soureMap contents or false when not found */ const findMap = (filepath, options) => { options = options || { verbose: false }; const input = fs.readFileSync(filepath, 'utf8'); if (filepath.match(MATCH_MAP)) { return input; } else if (filepath.match(MATCH_CODE)) { if (input.match(FIND_SOURCE_BASE64)) { const sourceMappingMatch = FIND_SOURCE_BASE64.exec(input); if (sourceMappingMatch && sourceMappingMatch.length > 2) { if (options.verbose) { console.log(`Input file "${filepath}" contains Base64 of ${sourceMappingMatch[2].length} length`); } const buf = Buffer.from(sourceMappingMatch[2], 'base64'); return buf.toString('utf8'); } } else if (input.match(FIND_SOURCE_UENC)) { const sourceMappingMatch = FIND_SOURCE_UENC.exec(input); if (sourceMappingMatch && sourceMappingMatch.length > 2) { if (options.verbose) { console.log(`Input file "${filepath}" contains URL encoded of ${sourceMappingMatch[2].length} length`); } const buf = Buffer.from(sourceMappingMatch[2], 'ascii'); return buf.toString('utf8'); } } else if (input.match(FIND_SOURCE_FILE)) { const sourceMappingMatch = FIND_SOURCE_FILE.exec(input); if (sourceMappingMatch && sourceMappingMatch.length > 1) { if (options.verbose) { console.log(`Input file "${filepath}" points to "${sourceMappingMatch[1]}"`); } } // Since the sourceMappingURL is relative, try to find it from the same folder const mapFile = path.join(path.dirname(filepath), sourceMappingMatch[1]); try { fs.accessSync(mapFile); } catch (error) { console.error(`Could not access "${mapFile}"`); console.error(error.message); return false; } return fs.readFileSync(mapFile, 'utf8'); } } else if (options.verbose) { console.error(`Input file "${filepath}" was not a map nor a code file`); } return false; }; module.exports = findMap;
var Vue = require('vue') function fixFilters() { // 动态 filter Vue.filter('apply', function(value, name) { var filter = this.$options.filters[name] || Vue.options.filters[name] var args = [value].concat( [].slice.call(arguments, 2) ) if (filter) return filter.apply(this, args) return value }) } module.exports = fixFilters
/******************************* Release Config *******************************/ var requireDotFile = require('require-dot-file'), config, npmPackage, version ; /******************************* Derived Values *******************************/ try { config = requireDotFile('pegaMultiselect.json'); } catch(error) {} try { npmPackage = require('../../../package.json'); } catch(error) { // generate fake package npmPackage = { name: 'Unknown', version: 'x.x' }; } // looks for version in config or package.json (whichever is available) version = (npmPackage && npmPackage.version !== undefined && npmPackage.name == 'Multiselect-Pega') ? npmPackage.version : config.version ; /******************************* Export *******************************/ module.exports = { title : 'pegaMultiselect UI', repository : 'https://github.com/ghoshArnab/multiselect', url : 'https://github.com/ghoshArnab/multiselect', banner: '' + ' /*' + '\n' + ' * # <%= title %> - <%= version %>' + '\n' + ' * <%= repository %>' + '\n' + ' * <%= url %>' + '\n' + ' *' + '\n' + ' * Copyright 2014 Contributors' + '\n' + ' * Released under the MIT license' + '\n' + ' * http://opensource.org/licenses/MIT' + '\n' + ' *' + '\n' + ' */' + '\n', version : version };
/** * Placeholder test - checks that an attribute or the content of an * element itself is not a placeholder (i.e. 'click here' for links). */ 'use strict'; quail.components.placeholder = function (quail, test, Case, options) { var resolve = function resolve(element, resolution) { test.add(Case({ element: element, status: resolution })); }; test.get('$scope').find(options.selector).each(function () { var text = ''; if ($(this).css('display') === 'none' && !$(this).is('title')) { resolve(this, 'inapplicable'); return; } if (typeof options.attribute !== 'undefined') { if ((typeof $(this).attr(options.attribute) === 'undefined' || options.attribute === 'tabindex' && $(this).attr(options.attribute) <= 0) && !options.content) { resolve(this, 'failed'); return; } else { if ($(this).attr(options.attribute) && $(this).attr(options.attribute) !== 'undefined') { text += $(this).attr(options.attribute); } } } if (typeof options.attribute === 'undefined' || !options.attribute || options.content) { text += $(this).text(); $(this).find('img[alt]').each(function () { text += $(this).attr('alt'); }); } if (typeof text === 'string' && text.length > 0) { text = quail.cleanString(text); var regex = /^([0-9]*)(k|kb|mb|k bytes|k byte)$/g; var regexResults = regex.exec(text.toLowerCase()); if (regexResults && regexResults[0].length) { resolve(this, 'failed'); } else if (options.empty && quail.isUnreadable(text)) { resolve(this, 'failed'); } else if (quail.strings.placeholders.indexOf(text) > -1) { resolve(this, 'failed'); } // It passes. else { resolve(this, 'passed'); } } else { if (options.empty && typeof text !== 'number') { resolve(this, 'failed'); } } }); };
Parse.initialize("AQxY526I5fcCPVkniY6ONnaBqU5qh1qDMqcOCORz", "y0cZ5QAGDU1SN1o1DtsQA8mHAKL3TKetrRvGwv3Y"); calculateSteps(); function calculateSteps(){ var count = 0; var Trips = Parse.Object.extend("Trip"); var query = new Parse.Query(Trips); query.greaterThan("StepsCompleted", 0); query.find({ success: function(results) { for (var i = 0; i < results.length; i++) { var object = results[i]; var stepsTaken = object.get("StepsCompleted"); count += stepsTaken; document.getElementById('stepsContainer').innerHTML = count.toLocaleString(); var dollarsSaved = (count / 2000) * 2.5; document.getElementById('moneyContainer').innerHTML = dollarsSaved.toFixed(2); var co2Emissions = count * 0.0128; document.getElementById('co2EmissionsContainer').innerHTML = co2Emissions.toFixed(2); } }, error: function(error) { console.log("Error: " + error.code + " " + error.message); } }); //var timer = setInterval(refresh, 3000); } var myVar = setInterval(function(){ refresh() }, 1000); function refresh(){ calculateSteps(); }
'use strict' // Module dependencies. var request = require('request') var querystring = require('querystring') var userAgent = require('random-useragent') // Root for all endpoints. var _baseUrl = 'http://data.europa.eu/euodp/data/api/action' // Infrastructure prevents requests from original user agent of requestee. var headers = { 'User-Agent': userAgent.getRandom(), 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } /** * Calls the service and return the data in a promise, but with POST. * @function * @private * @name _sendRequest * @param {object} options - The request set of options. * @param {string} options.endpoint - Resource endpoint, without any slashes. * @param {object} options.query - The query parameters for the request. * @param {object} options.body - The body if POST, PUT * @param {string} options.method - The method to be used. * @returns {Promise} The response in a promise. */ function _sendRequest (options) { return new Promise((resolve, reject) => { var query = querystring.stringify(options.query) var bodyData = JSON.stringify(options.body) request({ url: _baseUrl + `/${options.endpoint}?${query}`, headers: headers, method: options.method, body: bodyData }, (error, response, body) => { if (error) { reject(error) } resolve(body) }) }) } /** * Get a list of the datasets in JSON. * @param {object} options - The request set of options. * @param {number} options.query.limit - Limit the number of items returned. * @param {number} options.query.offset - Acts like pagination when limited results. */ module.exports.getDatasets = (options) => { return _sendRequest({ method: 'GET', endpoint: 'package_list', query: (options !== undefined ? options.query : '') }) } /** * Return a list of the site's tags. * @param {object} options - The request set of options. * @param {object} options.query - The query parameters. * @param {string} options.query.vocabulary_id - The id or name of a vocabulary. * If given only tags that belong to this vocabulary will be returned. * @param {boolean} options.query.all_fields - Whether to include all fields. */ module.exports.getTags = (options) => { return _sendRequest({ method: 'GET', endpoint: 'tag_list', query: (options !== undefined ? options.query : '') }) } /** * Return a list of the site's tags. * @param {object} options - The request set of options. * @param {object} options.query - The query parameters. * @param {string} options.body.id - The id of the data set. * For example: {"id": "dgt-translation-memory"} */ module.exports.getDataset = (options) => { return _sendRequest({ method: 'POST', endpoint: 'package_show', query: (options !== undefined ? options.query : ''), body: (options !== undefined ? options.body : {}) }) } /** * Searches for packages satisfying a given search criteria. * This action accepts solr search query parameters. * @see http://wiki.apache.org/solr/CommonQueryParameters * @param {object} options - The request set of options. * @param {object} options.query - The query parameters. * @param {object} options.body - The body parameter. * This accepts the solr tags to filter results. */ module.exports.datasetSearch = (options) => { return _sendRequest({ method: 'POST', endpoint: 'package_search', query: (options !== undefined ? options.query : ''), body: (options !== undefined ? options.body : {}) }) }
import logger from "./logger"; const middlewares = { logger, }; export default middlewares;
import React, {PropTypes} from 'react'; import Anchor from './Anchor'; import getIdFromTitle from '../util/getIdFromTitle'; const Title = ({children}) => ( <h3> <Anchor id={getIdFromTitle(children)}> {children} </Anchor> </h3> ); Title.propTypes = { children: PropTypes.string.isRequired, }; export default Title;
import Component from '@ember/component'; export default Component.extend({ domains: null });
import React from 'react'; import { Wrapper } from '../components'; const Container = () => <Wrapper>Journal Container</Wrapper>; export default Container;
/** * * Secure Hash Algorithm (SHA1) * http://www.webtoolkit.info/ * **/ export function SHA1(msg) { function rotate_left(n, s) { var t4 = (n << s) | (n >>> (32 - s)); return t4; }; function lsb_hex(val) { var str = ""; var i; var vh; var vl; for (i = 0; i <= 6; i += 2) { vh = (val >>> (i * 4 + 4)) & 0x0f; vl = (val >>> (i * 4)) & 0x0f; str += vh.toString(16) + vl.toString(16); } return str; }; function cvt_hex(val) { var str = ""; var i; var v; for (i = 7; i >= 0; i--) { v = (val >>> (i * 4)) & 0x0f; str += v.toString(16); } return str; }; function Utf8Encode(string) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }; var blockstart; var i, j; var W = new Array(80); var H0 = 0x67452301; var H1 = 0xEFCDAB89; var H2 = 0x98BADCFE; var H3 = 0x10325476; var H4 = 0xC3D2E1F0; var A, B, C, D, E; var temp; msg = Utf8Encode(msg); var msg_len = msg.length; var word_array = new Array(); for (i = 0; i < msg_len - 3; i += 4) { j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 | msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3); word_array.push(j); } switch (msg_len % 4) { case 0: i = 0x080000000; break; case 1: i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000; break; case 2: i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000; break; case 3: i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80; break; } word_array.push(i); while ((word_array.length % 16) != 14) word_array.push(0); word_array.push(msg_len >>> 29); word_array.push((msg_len << 3) & 0x0ffffffff); for (blockstart = 0; blockstart < word_array.length; blockstart += 16) { for (i = 0; i < 16; i++) W[i] = word_array[blockstart + i]; for (i = 16; i <= 79; i++) W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); A = H0; B = H1; C = H2; D = H3; E = H4; for (i = 0; i <= 19; i++) { temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); B = A; A = temp; } for (i = 20; i <= 39; i++) { temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); B = A; A = temp; } for (i = 40; i <= 59; i++) { temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); B = A; A = temp; } for (i = 60; i <= 79; i++) { temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); B = A; A = temp; } H0 = (H0 + A) & 0x0ffffffff; H1 = (H1 + B) & 0x0ffffffff; H2 = (H2 + C) & 0x0ffffffff; H3 = (H3 + D) & 0x0ffffffff; H4 = (H4 + E) & 0x0ffffffff; } var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4); return temp.toLowerCase(); };
/*global NULL*/ 'use strict'; var sha1 = require('sha1'); module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.bulkInsert('Mentors', [{ nameFirst: 'Betty', nameLast: 'Coder', email: 'betty@coderevolution.com', password: sha1('password'), githubLink: 'http://github.com/bettyc', skillSet1:'mean', skillLevel1: 2, skillSet2:'mern', skillLevel2: 1, bio:'Hi, I\'m Betty and I\'ve been coding since I was three.', userWebLink:'http://mybettyweb.com', mentorRating:3, photoLink: 'public/images/fakefemale1.png' }, { nameFirst: 'Archi', nameLast: 'Thompson', email: 'archi@coderevolution.com', password: sha1('password'), githubLink: 'http://github.com/archi', skillSet1: 'mern', skillLevel1: 3, skillSet2:'mean', skillLevel2: 2, bio:'I love helping new coders discover web development. Let me teach you the MERN stack.', userWebLink:'http://comecodewithme.code', mentorRating:3, photoLink: 'public/images/archithompson.png' }, { nameFirst: 'Cecile', nameLast: 'Diakonova', email: 'cjd@coderevolution.com', password: sha1('password'), githubLink: 'http://github.com/diakonova', skillSet1: 'mern', skillLevel1: 3, bio:'Fully versed in both LAMP and MERN stacks.', userWebLink:'http://comecodewithme.code', mentorRating:3, photoLink: 'public/images/fakefemale2.png' }, { nameFirst: 'Taylor', nameLast: 'Jackson', email: 'taylor@coderevolution.com', password: sha1('password'), githubLink: 'http://github.com/djackson', skillSet1: 'mean', skillLevel1: 3, bio:'I have been a developer for ten years. I am passionate about learning new technologies.', userWebLink:'http://comecodewithme.code', mentorRating:3, photoLink: 'public/images/taylor.jpeg' } ], {}) }, down: function (queryInterface, Sequelize) { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('Person', null, {}); */ return queryInterface.bulkDelete('Mentors', null, {}); } };
'use strict' const getNamespace = require('continuation-local-storage').getNamespace const Promise = require('bluebird') const WorkerStopError = require('error-cat/errors/worker-stop-error') const Ponos = require('../') /** * A simple worker that will publish a message to a queue. * @param {object} job Object describing the job. * @param {string} job.queue Queue on which the message will be published. * @returns {promise} Resolved when the message is put on the queue. */ function basicWorker (job) { return Promise.try(() => { const tid = getNamespace('ponos').get('tid') if (!job.message) { throw new WorkerStopError('message is required', { tid: tid }) } console.log(`hello world: ${job.message}. tid: ${tid}`) }) } const server = new Ponos.Server({ tasks: { 'basic-queue-worker': basicWorker }, events: { 'basic-event-worker': basicWorker } }) server.start() .then(() => { console.log('server started') }) .catch((err) => { console.error('server error:', err.stack || err.message || err) }) process.on('SIGINT', () => { server.stop() .then(() => { console.log('server stopped') }) .catch((err) => { console.error('server error:', err.stack || err.message || err) }) })
import { baseUniDriverFactory } from '../../test/utils/unidriver'; export const boxDriverFactory = base => { return { ...baseUniDriverFactory(base), }; };
export default class MethodMissingClass { constructor() { const handler = { get: this._handleMethodMissing }; return new Proxy(this, handler); } _handleMethodMissing(target, name, receiver) { const origMethod = target[name]; // If it exist, return original member or function. if (Reflect.has(target, name) || name === "methodMissing") { return Reflect.get(target, name, receiver); } // If the method doesn't exist, call methodMissing. return function(...args) { return Reflect.get(target, "methodMissing").call(receiver, name, ...args); }; } methodMissing(name, ...args) { console.log( `Method "${name}" does not exist. Please override methodMissing method to add functionality.` ); } }
var dns = require('native-dns'), util = require('util'); var question = dns.Question({ name: 'www.google.com', type: 'A', // could also be the numerical representation }); var start = new Date().getTime(); var req = dns.Request({ question: question, server: '8.8.8.8', /* // Optionally you can define an object with these properties, // only address is required server: { address: '8.8.8.8', port: 53, type: 'udp' }, */ timeout: 1000, /* Optional -- default 4000 (4 seconds) */ }); req.on('timeout', function () { console.log('Timeout in making request'); }); req.on('message', function (err, res) { if(err) console.error(err, res); else console.log(res); /* answer, authority, additional are all arrays with ResourceRecords */ res.answer.forEach(function (a) { /* promote goes from a generic ResourceRecord to A, AAAA, CNAME etc */ console.log(a.address); }); }); req.on('end', function () { /* Always fired at the end */ var delta = (new Date().getTime()) - start; console.log('Finished processing request: ' + delta.toString() + 'ms'); }); req.send();
Meteor.startup(() => { AutoForm.setDefaultTemplate('ionic'); });
var Client = require('node-rest-client').Client; //REST server properties var host_url = "http://sapient5-evaluation-dw.demandware.net"; var api_path = "/s/SiteGenesis/dw/shop/v17_2/"; var server_url = host_url+api_path; var client_id = "5a40714c-52c3-44df-a00d-9d3bb2dc8ea8"; var max_suggestion = 2; var getURL = function(method){ return server_url+method; }; var client = new Client(); client.registerMethod("products",getURL('products')+"/${id}?all_images=true&expand=images,prices&client_id="+client_id, "GET"); client.registerMethod("productimage",getURL('products')+"/${id}/images?all_images=true&client_id="+client_id, "GET"); client.registerMethod("searchsuggestion",getURL('search_suggestion')+"?q=${arg1}&count=${arg2}&client_id="+client_id, "GET"); client.registerMethod("getCategories",getURL('categories')+"/${id}?level=${2}&client_id="+client_id, "GET"); client.registerMethod("searchproducts",getURL('product_search')+"?q=${arg1}&refine1=cgid=${arg2}&count=100&expand=images,prices&client_id="+client_id, "GET"); module.exports = { getProduct : function(product_id, callbackmethod) { var args = { path: { "id": product_id } // path substitution var }; client.methods.products(args,callbackmethod); }, getSuggestion : function(query,callbackmethod) { var args = { path: { "arg1" : query, "arg2" : max_suggestion } }; client.methods.searchsuggestion(args, callbackmethod); //http://hostname:port/dw/shop/v17_2/search_suggestion?q={String}&count={Integer}&currency={String}&locale={String} }, getProductImages : function(product_id,callbackmethod) { var args = { path: { "id": product_id } // path substitution var }; client.methods.productimage(args,callbackmethod); //http://hostname:port/dw/shop/v17_2/search_suggestion?q={String}&count={Integer}&currency={String}&locale={String} }, searchProducts : function(callbackmethod,query,refine) { var args = { path: { "arg1" : query, "arg2" : ((refine) ? refine : 'root')} }; console.log(JSON.stringify(args)); client.methods.searchproducts(args, callbackmethod); }, getCategories : function(callbackmethod,cgid) { var args = { path: { "id" : ((cgid) ? cgid : 'root'), "arg1" : 1} }; client.methods.getCategories(args, callbackmethod); } //http://sapient3-evaluation-dw.demandware.net/s/SiteGenesis/dw/shop/v17_2/product_search?q=shirt&client_id=5a40714c-52c3-44df-a00d-9d3bb2dc8ea8&expand=images,prices&refine_1=cgid=mens}, };
(function() { 'use strict'; angular .module('app') .constant('FIREBASE_BASE_URL', 'https://word-game-d1e51.firebaseio.com'); })();
module.exports = function (grunt) { var idVideo = 0; var examples = require('./node_modules/grunt-json-mapreduce/examples'); var _ = require('underscore'); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), cfg: { paths: { build: 'dist', bower: 'bower_components', npm: 'node_modules' }, files: { js: { vendor: [ '<%= cfg.paths.npm %>/underscore/underscore.js', '<%= cfg.paths.bower %>/angular/angular.js', '<%= cfg.paths.bower %>/angular-mocks/angular-mocks.js', '<%= cfg.paths.bower %>/angular-route/angular-route.js', '<%= cfg.paths.bower %>/angular-slugify/angular-slugify.js', '<%= cfg.paths.bower %>/angular-youtube-mb/src/angular-youtube-embed.js', // '<%= cfg.paths.bower %>/angular-youtube-embed/dist/angular-youtube-embed.js', // '<%= cfg.paths.bower %>/angular-youtube/angular-youtube-player-api.js', '<%= cfg.paths.bower %>/jquery/dist/jquery.js', '<%= cfg.paths.bower %>/bootstrap/dist/js/bootstrap.js' ], mixins: [ 'app/js/mixins/**/*.js' ], app: [ 'app/js/app.js', 'app/js/**/*.js', '!app/js/mock/*' ] }, css: { vendor: [ '<%= cfg.paths.bower %>/bootstrap/dist/css/bootstrap.css', '<%= cfg.paths.bower %>/bootstrap/dist/css/bootstrap-theme.css' ], app: [ 'app/assets/css/**/*.css' ] } } }, bump: { options: { files: ['package.json', 'bower.json'], pushTo: 'origin', commitFiles: ['-a'] } }, clean: { build: ['<%= cfg.paths.build %>'] }, copy: { static: { files: [{ '<%= cfg.paths.build %>/index.html': 'app/index.html', '<%= cfg.paths.build %>/favicon.png': 'app/assets/favicon.png' }, { expand: true, cwd: 'app/templates/', src: ["*.*", "**/*.*"], dest: '<%= cfg.paths.build %>/templates' }, { expand: true, cwd: 'app/assets/font/', src: ["*.*", "**/*.*"], dest: '<%= cfg.paths.build %>/font' } ] } }, cssmin: { vendor: { files: { '<%= cfg.paths.build %>/css/vendor.css': '<%= cfg.files.css.vendor %>' } }, app: { files: { '<%= cfg.paths.build %>/css/app.css': '<%= cfg.files.css.app %>' } } }, uglify: { options: { mangle: false }, vendor: { files: { '<%= cfg.paths.build %>/js/vendor.js': '<%= cfg.files.js.vendor %>' } }, mixins: { files: { '<%= cfg.paths.build %>/js/mixins.js': '<%= cfg.files.js.mixins %>' } }, app: { files: { '<%= cfg.paths.build %>/js/app.js': '<%= cfg.files.js.app %>' } } }, json_mapreduce: { events: { src: ['data/events/**/*.json'], dest: '<%= cfg.paths.build %>/data/events.json', options: { map: examples.map.pass, reduce: examples.reduce.concat } }, videos: { src: ['data/videos/**/*.json'], dest: '<%= cfg.paths.build %>/data/videos.json', options: { map: function (currentValue, index, array) { return currentValue.map(function (element) { element.id = ++idVideo; return element; }); }, reduce: examples.reduce.concat } }, speakers: { src: ['data/speakers/**/*.json'], dest: '<%= cfg.paths.build %>/data/speakers.json', options: { map: examples.map.pass, reduce: examples.reduce.concat } }, tags: { src: ['data/videos/**/*.json'], dest: '<%= cfg.paths.build %>/data/tags.json', options: { map: function (currentValue, index, array) { var tagLists = currentValue.map(function (element) { return element.tags; }); return _.union.apply(this, tagLists); }, reduce: function(previousValue, currentValue, index, array) { if (typeof previousValue === "undefined") { return currentValue; } else { return _.union(previousValue, currentValue); } } } } }, browserify: { app: { src: ['./app/js/mock/index.js'], dest: '<%= cfg.paths.build %>/js/mock.js' } }, 'http-server': { dist: { root: 'dist', host: '0.0.0.0', port: '9000' } }, jsonlint: { data: { src: ['data/**/*.json'] } }, jshint: { options: { jshintrc: true }, app: { src: ['app/js/**/*.js'] } } }); require('load-grunt-tasks')(grunt); grunt.registerTask('test', [ 'jshint', 'jsonlint' ]); grunt.registerTask('build', [ 'clean', 'copy', 'cssmin', 'uglify' ]); grunt.registerTask('mock', [ 'json_mapreduce', 'browserify' ]); grunt.registerTask('run', [ 'http-server' ]); grunt.registerTask('default', [ 'test', 'build', 'mock', ]); };
/** * Import Request event * @module tracker/events/import-request */ const NError = require('nerror'); const Base = require('./base'); /** * Import Request event class */ class ImportRequest extends Base { /** * Create service * @param {App} app The application * @param {object} config Configuration * @param {Logger} logger Logger service * @param {Registry} registry Registry service * @param {UserRepository} userRepo User repository * @param {DaemonRepository} daemonRepo Daemon repository * @param {PathRepository} pathRepo Path repository * @param {ConnectionRepository} connectionRepo Connection repository */ constructor(app, config, logger, registry, userRepo, daemonRepo, pathRepo, connectionRepo) { super(app); this._config = config; this._logger = logger; this._registry = registry; this._userRepo = userRepo; this._daemonRepo = daemonRepo; this._pathRepo = pathRepo; this._connectionRepo = connectionRepo; } /** * Service name is 'tracker.events.importRequest' * @type {string} */ static get provides() { return 'tracker.events.importRequest'; } /** * Dependencies as constructor arguments * @type {string[]} */ static get requires() { return [ 'app', 'config', 'logger', 'registry', 'repositories.user', 'repositories.daemon', 'repositories.path', 'repositories.connection' ]; } /** * Event name * @type {string} */ get name() { return 'import_request'; } /** * Event handler * @param {string} id ID of the client * @param {object} message The message */ async handle(id, message) { let client = this._registry.clients.get(id); if (!client) return; this._logger.debug('import-request', `Got IMPORT REQUEST from ${id}`); try { let daemons = []; if (client.daemonId) daemons = await this._daemonRepo.find(client.daemonId); let daemon = daemons.length && daemons[0]; if (!daemon) { let response = this.tracker.ImportResponse.create({ response: this.tracker.ImportResponse.Result.REJECTED, }); let reply = this.tracker.ServerMessage.create({ type: this.tracker.ServerMessage.Type.IMPORT_RESPONSE, messageId: message.messageId, importResponse: response, }); let data = this.tracker.ServerMessage.encode(reply).finish(); this._logger.debug('import-request', `Sending REJECTED IMPORT RESPONSE to ${id}`); return this.tracker.send(id, data); } let [paths, connections] = await Promise.all([ this._pathRepo.findByToken(message.importRequest.token), this._connectionRepo.findByToken(message.importRequest.token) ]); let path = paths.length && paths[0]; let connection = connections.length && connections[0]; let userId, actingAs; if (path) { actingAs = 'client'; userId = path.userId; } else if (connection) { actingAs = 'server'; userId = connection.userId; } else { let response = this.tracker.ImportResponse.create({ response: this.tracker.ImportResponse.Result.REJECTED, }); let reply = this.tracker.ServerMessage.create({ type: this.tracker.ServerMessage.Type.IMPORT_RESPONSE, messageId: message.messageId, importResponse: response, }); let data = this.tracker.ServerMessage.encode(reply).finish(); this._logger.debug('import-request', `Sending REJECTED IMPORT RESPONSE to ${id}`); return this.tracker.send(id, data); } let loadConnections = async path => { let result = []; let connections = await this._connectionRepo.findByPath(path); let connection = connections.length && connections[0]; if (connection) result.push(connection); let paths = await this._pathRepo.findByParent(path); let promises = []; for (let subPath of paths) promises.push(loadConnections(subPath)); let loaded = await Promise.all(promises); for (let subConnections of loaded) result = result.concat(subConnections); return result; }; if (actingAs === 'server') connections = [connection]; else connections = await loadConnections(path); let serverConnections = []; let clientConnections = []; let value; let users = await this._userRepo.find(userId); let user = users.length && users[0]; if (!user) { value = this.tracker.ImportResponse.Result.REJECTED; } else { value = this.tracker.ImportResponse.Result.ACCEPTED; if (actingAs === 'server') { let connection = connections.length && connections[0]; if (connection) { let paths = await this._pathRepo.find(connection.pathId); let path = paths.length && paths[0]; if (path) { let clients = []; for (let clientDaemon of await this._daemonRepo.findByConnection(connection)) { if (clientDaemon.actingAs !== 'client') continue; let clientUsers = await this._userRepo.find(clientDaemon.userId); let clientUser = clientUsers.length && clientUsers[0]; if (clientUser) clients.push(clientUser.email + '?' + clientDaemon.name); } let {address, port} = this._registry.addressOverride( connection.connectAddress, connection.connectPort, connection.addressOverride, connection.portOverride ); serverConnections.push(this.tracker.ServerConnection.create({ name: user.email + path.path, connectAddress: address, connectPort: port, encrypted: connection.encrypted, fixed: connection.fixed, clients: clients, })); } } } else { for (let connection of connections) { let paths = await this._pathRepo.find(connection.pathId); let path = paths.length && paths[0]; if (path) { let serverDaemons = await this._daemonRepo.findServerByConnection(connection); let serverDaemon = serverDaemons.length && serverDaemons[0]; let serverUsers = []; if (serverDaemon) serverUsers = await this._userRepo.find(serverDaemon.userId); let serverUser = serverUsers.length && serverUsers[0]; let {address, port} = this._registry.addressOverride( connection.listenAddress, connection.listenPort, connection.addressOverride, connection.portOverride ); clientConnections.push(this.tracker.ClientConnection.create({ name: user.email + path.path, listenAddress: address, listenPort: port, encrypted: connection.encrypted, fixed: connection.fixed, server: (serverDaemon && serverUser) ? serverUser.email + '?' + serverDaemon.name : '', })); } } } } let list = this.tracker.ConnectionsList.create({ serverConnections: serverConnections, clientConnections: clientConnections, }); let response = this.tracker.ImportResponse.create({ response: value, updates: list, }); let reply = this.tracker.ServerMessage.create({ type: this.tracker.ServerMessage.Type.IMPORT_RESPONSE, messageId: message.messageId, importResponse: response, }); let data = this.tracker.ServerMessage.encode(reply).finish(); this._logger.debug('import-request', `Sending RESULTING IMPORT RESPONSE to ${id}`); this.tracker.send(id, data); } catch (error) { this._logger.error(new NError(error, 'ImportRequest.handle()')); } } } module.exports = ImportRequest;
/* SPDX-License-Identifier: MIT */ /** * Handles interaction with a GHData server. * @constructor */ function GHDataAPIClient (apiUrl, owner, repo, apiVersion) { this.owner = owner || ''; this.repo = repo || ''; this.url = apiUrl; this.apiversion = apiVersion || 'unstable'; } /* Request Handling * Create a friendly wrapper around XMLHttpRequest --------------------------------------------------------------*/ /** * Wraps XMLHttpRequest with many goodies. Credit to SomeKittens on StackOverflow. * @param {Object} opts - Stores the url (opts.url), method (opts.method), headers (opts.headers) and query parameters (opt.params). All optional. * @returns {Promise} Resolves with XMLHttpResponse.response */ GHDataAPIClient.prototype.request = function (opts) { // Use GHData by default opts.endpoint = opts.endpoint || ''; opts.url = opts.url || (this.url + this.apiversion + '/' + this.owner + '/' + this.repo + '/' + opts.endpoint); opts.method = opts.method || 'GET'; return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open(opts.method, opts.url); xhr.onload = function () { if (this.status >= 200 && this.status < 300) { resolve(xhr.response); } else { reject({ status: this.status, statusText: xhr.statusText }); } }; xhr.onerror = function () { reject({ status: this.status, statusText: xhr.statusText }); }; if (opts.headers) { Object.keys(opts.headers).forEach(function (key) { xhr.setRequestHeader(key, opts.headers[key]); }); } var params = opts.params; // We'll need to stringify if we've been given an object // If we have a string, this is skipped. if (params && typeof params === 'object') { params = Object.keys(params).map(function (key) { return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); }).join('&'); } xhr.send(params); }); }; /** * Wraps the GET requests with the correct options for most GHData calls * @param {String} endpoint - Endpoint to send the request to * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with Object created from the JSON returned by GHData */ GHDataAPIClient.prototype.get = function (endpoint, params) { var self = this; return new Promise(function (resolve, request) { self.request({ method: 'GET', endpoint: endpoint, params: params }).then(function (response) { // Lets make this thing JSON var result = JSON.parse(response); resolve(result); }); }); }; /* Endpoints * Wrap all the API endpoints to make it as simple as possible --------------------------------------------------------------*/ /** * Commits timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.commitsByWeek = function (params) { return this.get('timeseries/commits', params); }; /** * Forks timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with forks timeeseries object */ GHDataAPIClient.prototype.forksByWeek = function (params) { return this.get('timeseries/forks', params); }; /** * Stargazers timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.stargazersByWeek = function (params) { return this.get('timeseries/stargazers', params); }; /** * Issues timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.issuesByWeek = function (params) { return this.get('timeseries/issues', params); }; /** * Pull Requests timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.pullRequestsByWeek = function (params) { return this.get('timeseries/pulls', params); }; /** * Pull Requests timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.contributionsByWeek = function (params) { return this.get('timeseries/contributions', params); }; /** * How quickly after issues are made they are commented on * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.issuesResponseTime = function (params) { return this.get('timeseries/issues/response_time', params); }; /** * Contributions timeseries * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.contributors = function (params) { return this.get('timeseries/contributors', params); }; /** * Locations of the committers * @param {Object} params - Query string params to pass to the API * @returns {Promise} Resolves with commits timeseries object */ GHDataAPIClient.prototype.committerLocations = function (params) { return this.get('commits/locations', params); };
// LICENSE : MIT "use strict"; import React from "react" global.React = require('react'); var md2react = require("md2react"); var todoRegexp = /^-\s*\[[x ]\]\s*/; function isTODO(line) { return todoRegexp.test(line); } function flatten([first, ...rest]) { if (first === undefined) { return []; } else if (!Array.isArray(first)) { return [first, ...flatten(rest)]; } else { return [...flatten(first), ...flatten(rest)]; } } export default class RepositoryIssueList extends React.Component { static get propTypes() { return { issues: React.PropTypes.array } } //componentDidUpdate() { // this.markdownContainer = React.findDOMNode(this.refs.markdown); // if(!this.markdownContainer) { // return; // } // var list = this.markdownContainer.querySelectorAll("li.checked, li.unchecked"); // console.log(list); //} render() { if (this.props.issue == null) { return <div className="RepositoryIssueList"> <div className="markdown" ref="markdown"> </div> </div>; } var ownerSubTasks = this.props.issue.body.split("\n").filter(isTODO); var commentSubTasks = this.props.comments.map(function (comment) { return comment.body.split("\n").filter(isTODO); }); var subTasks = ownerSubTasks.concat(...commentSubTasks); var subTasksList = subTasks.join("\n"); return <div className="RepositoryIssueList"> <div className="markdown" ref="markdown"> {md2react(subTasksList, { tasklist: true })} </div> </div> } }
var path = require('path'); module.exports = { // entry: ['babel-polyfill', './src/main.js'], entry: './src/main.js', target: 'node', output: { filename: 'main.js', path: path.resolve(__dirname, 'build') }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: [ ['env', { targets: { node: '6.6.0' } }] ] } } } ] }, externals: { 'lodash' : 'commonjs lodash' } };
/* * oskari-compile */ module.exports = function(grunt) { grunt.registerMultiTask('compile', 'Compile appsetup js', function() { var starttime = (new Date()).getTime(); var options = this.data.options; // Run some sync stuff. grunt.log.writeln('Compiling...'); // Catch if required fields are not provided. if ( !options.appSetupFile ) { grunt.fail.warn('No path provided for Compile to scan.'); } if ( !options.dest ) { grunt.fail.warn('No destination path provided for Compile to use.'); } var fs = require('fs'), UglifyJS = require('uglify-js'), parser = require('../parser.js'), processedAppSetup = parser.getComponents(options.appSetupFile); grunt.log.writeln('Parsed appSetup:' + options.appSetupFile); // internal minify i18n files function this.minifyLocalization = function(langfiles, path) { for (var id in langfiles) { //console.log('Minifying loc:' + id + '/' + langfiles[id]); this.minifyJS(langfiles[id], path + 'oskari_lang_' + id + '.js', options.concat); } } // internal minify JS function this.minifyJS = function(files, outputFile, concat) { var okFiles = [], fileMap = {}, result = null; for (var i = 0; i < files.length; ++i) { if (!fs.existsSync(files[i])) { var msg = 'Couldnt locate ' + files[i]; throw msg; } // do not put duplicates on compiled code if(!fileMap[files[i]]) { fileMap[files[i]] = true; okFiles.push(files[i]); } else { grunt.log.writeln('File already added:' + files[i]); } } // minify or concatenate the files if (!concat) { result = UglifyJS.minify(okFiles, { //outSourceMap : "out.js.map", warnings : true, compress : true }); } else { // emulate the result uglify creates, but only concatenating result = {"code" : ""}; for (var j = 0, jlen = okFiles.length; j < jlen; j +=1) { result.code += fs.readFileSync(okFiles[j], 'utf8'); } } // write result to disk fs.writeFileSync(outputFile, result.code, 'utf8'); } // validate parsed appsetup var compiledDir = options.dest; if (!fs.existsSync(compiledDir)) { fs.mkdirSync(compiledDir); } var files = []; for (var j = 0; j < processedAppSetup.length; ++j) { var array = parser.getFilesForComponent(processedAppSetup[j], 'javascript'); files = files.concat(array); } this.minifyJS(files, compiledDir + 'oskari.min.js', options.concat); var langfiles = {}; for (var j = 0; j < processedAppSetup.length; ++j) { var deps = processedAppSetup[j].dependencies; for (var i = 0; i < deps.length; ++i) { for (var lang in deps[i].locales) { if (!langfiles[lang]) { langfiles[lang] = []; } langfiles[lang] = langfiles[lang].concat(deps[i].locales[lang]); } } } this.minifyLocalization(langfiles, compiledDir); var unknownfiles = []; for(var j = 0; j < processedAppSetup.length; ++j) { unknownfiles = unknownfiles.concat(parser.getFilesForComponent(processedAppSetup[j], 'unknown')); } if(unknownfiles.length != 0) { console.log('Appsetup referenced types of files that couldn\'t be handled: ' + unknownfiles); } var endtime = (new Date()).getTime(); grunt.log.writeln('Compile completed in ' + ((endtime - starttime) / 1000) + ' seconds'); }); };
/** * @param {string} s * @param {string} t * @return {boolean} */ var isIsomorphic = function(s, t) { var s = s.split(''); var t = t.split(''); if (new Set(s).size !== new Set(t).size) return false; var zip = new Set(); s.forEach(function (item, i) { zip.add(s[i] + ' ' + t[i]) }); return new Set(zip).size === new Set(s).size; }; var eq = require('assert').equal; eq(isIsomorphic('egg', 'add'), true); eq(isIsomorphic('egg', 'ddd'), false);
'use strict'; angular .module('reflect.calendar') .filter('calendarTruncateEventTitle', function() { return function(string, length, boxHeight) { if (!string) { return ''; } //Only truncate if if actually needs truncating if (string.length >= length && string.length / 20 > boxHeight / 30) { return string.substr(0, length) + '...'; } else { return string; } }; });
'use strict'; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Any commits to this file should be reviewed with security in mind. * * Changes to this file can potentially create security vulnerabilities. * * An approval from 2 Core members with history of modifying * * this file is required. * * * * Does the change somehow allow for arbitrary javascript to be executed? * * Or allows for someone to change the prototype of built-in objects? * * Or gives undesired access to variables likes document or window? * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ var $sanitizeMinErr = angular.$$minErr('$sanitize'); var bind; var extend; var forEach; var isDefined; var lowercase; var noop; var htmlParser; var htmlSanitizeWriter; /** * @ngdoc module * @name ngSanitize * @description * * # ngSanitize * * The `ngSanitize` module provides functionality to sanitize HTML. * * * <div doc-module-components="ngSanitize"></div> * * See {@link ngSanitize.$sanitize `$sanitize`} for usage. */ /** * @ngdoc service * @name $sanitize * @kind function * * @description * Sanitizes an html string by stripping all potentially dangerous tokens. * * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string. * * The whitelist for URL sanitization of attribute values is configured using the functions * `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider * `$compileProvider`}. * * The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}. * * @param {string} html HTML input. * @returns {string} Sanitized HTML. * * @example <example module="sanitizeExample" deps="angular-sanitize.js" name="sanitize-service"> <file name="index.html"> <script> angular.module('sanitizeExample', ['ngSanitize']) .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) { $scope.snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 'snippet</p>'; $scope.deliberatelyTrustDangerousSnippet = function() { return $sce.trustAsHtml($scope.snippet); }; }]); </script> <div ng-controller="ExampleController"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Directive</td> <td>How</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="bind-html-with-sanitize"> <td>ng-bind-html</td> <td>Automatically uses $sanitize</td> <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind-html="snippet"></div></td> </tr> <tr id="bind-html-with-trust"> <td>ng-bind-html</td> <td>Bypass $sanitize by explicitly trusting the dangerous value</td> <td> <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt; &lt;/div&gt;</pre> </td> <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td> </tr> <tr id="bind-default"> <td>ng-bind</td> <td>Automatically escapes</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </div> </file> <file name="protractor.js" type="protractor"> it('should sanitize the html snippet by default', function() { expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should inline raw snippet if bound to a trusted value', function() { expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should escape snippet without any filter', function() { expect(element(by.css('#bind-default div')).getAttribute('innerHTML')). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')). toBe('new <b>text</b>'); expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).toBe( 'new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).toBe( "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;"); }); </file> </example> */ /** * @ngdoc provider * @name $sanitizeProvider * @this * * @description * Creates and configures {@link $sanitize} instance. */ function $SanitizeProvider() { var svgEnabled = false; this.$get = ['$$sanitizeUri', function($$sanitizeUri) { if (svgEnabled) { extend(validElements, svgElements); } return function(html) { var buf = []; htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { return !/^unsafe:/.test($$sanitizeUri(uri, isImage)); })); return buf.join(''); }; }]; /** * @ngdoc method * @name $sanitizeProvider#enableSvg * @kind function * * @description * Enables a subset of svg to be supported by the sanitizer. * * <div class="alert alert-warning"> * <p>By enabling this setting without taking other precautions, you might expose your * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned * outside of the containing element and be rendered over other elements on the page (e.g. a login * link). Such behavior can then result in phishing incidents.</p> * * <p>To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg * tags within the sanitized content:</p> * * <br> * * <pre><code> * .rootOfTheIncludedContent svg { * overflow: hidden !important; * } * </code></pre> * </div> * * @param {boolean=} flag Enable or disable SVG support in the sanitizer. * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called * without an argument or self for chaining otherwise. */ this.enableSvg = function(enableSvg) { if (isDefined(enableSvg)) { svgEnabled = enableSvg; return this; } else { return svgEnabled; } }; ////////////////////////////////////////////////////////////////////////////////////////////////// // Private stuff ////////////////////////////////////////////////////////////////////////////////////////////////// bind = angular.bind; extend = angular.extend; forEach = angular.forEach; isDefined = angular.isDefined; lowercase = angular.lowercase; noop = angular.noop; htmlParser = htmlParserImpl; htmlSanitizeWriter = htmlSanitizeWriterImpl; // Regular Expressions for parsing tags and attributes var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, // Match everything outside of normal chars and " (quote character) NON_ALPHANUMERIC_REGEXP = /([^#-~ |!])/g; // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = toMap('area,br,col,hr,img,wbr'); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'), optionalEndTagInlineElements = toMap('rp,rt'), optionalEndTagElements = extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' + 'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' + 'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul')); // Inline Elements - HTML5 var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' + 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' + 'samp,small,span,strike,strong,sub,sup,time,tt,u,var')); // SVG Elements // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted. // They can potentially allow for arbitrary javascript to be executed. See #11290 var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' + 'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' + 'radialGradient,rect,stop,svg,switch,text,title,tspan'); // Blocked Elements (will be stripped) var blockedElements = toMap('script,style'); var validElements = extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); //Attributes that have href and hence need to be sanitized var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href'); var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' + 'valign,value,vspace,width'); // SVG attributes (without "id" and "name" attributes) // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' + 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' + 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' + 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' + 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' + 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' + 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' + 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' + 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' + 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' + 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' + 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' + 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' + 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true); var validAttrs = extend({}, uriAttrs, svgAttrs, htmlAttrs); function toMap(str, lowercaseKeys) { var obj = {}, items = str.split(','), i; for (i = 0; i < items.length; i++) { obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true; } return obj; } var inertBodyElement; (function(window) { var doc; if (window.document && window.document.implementation) { doc = window.document.implementation.createHTMLDocument('inert'); } else { throw $sanitizeMinErr('noinert', 'Can\'t create an inert html document'); } var docElement = doc.documentElement || doc.getDocumentElement(); var bodyElements = docElement.getElementsByTagName('body'); // usually there should be only one body element in the document, but IE doesn't have any, so we need to create one if (bodyElements.length === 1) { inertBodyElement = bodyElements[0]; } else { var html = doc.createElement('html'); inertBodyElement = doc.createElement('body'); html.appendChild(inertBodyElement); doc.appendChild(html); } })(window); /** * @example * htmlParser(htmlString, { * start: function(tag, attrs) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParserImpl(html, handler) { if (html === null || html === undefined) { html = ''; } else if (typeof html !== 'string') { html = '' + html; } inertBodyElement.innerHTML = html; //mXSS protection var mXSSAttempts = 5; do { if (mXSSAttempts === 0) { throw $sanitizeMinErr('uinput', 'Failed to sanitize html because the input is unstable'); } mXSSAttempts--; // strip custom-namespaced attributes on IE<=11 if (window.document.documentMode) { stripCustomNsAttrs(inertBodyElement); } html = inertBodyElement.innerHTML; //trigger mXSS inertBodyElement.innerHTML = html; } while (html !== inertBodyElement.innerHTML); var node = inertBodyElement.firstChild; while (node) { switch (node.nodeType) { case 1: // ELEMENT_NODE handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes)); break; case 3: // TEXT NODE handler.chars(node.textContent); break; } var nextNode; if (!(nextNode = node.firstChild)) { if (node.nodeType === 1) { handler.end(node.nodeName.toLowerCase()); } nextNode = node.nextSibling; if (!nextNode) { while (nextNode == null) { node = node.parentNode; if (node === inertBodyElement) break; nextNode = node.nextSibling; if (node.nodeType === 1) { handler.end(node.nodeName.toLowerCase()); } } } } node = nextNode; } while ((node = inertBodyElement.firstChild)) { inertBodyElement.removeChild(node); } } function attrToMap(attrs) { var map = {}; for (var i = 0, ii = attrs.length; i < ii; i++) { var attr = attrs[i]; map[attr.name] = attr.value; } return map; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns {string} escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(SURROGATE_PAIR_REGEXP, function(value) { var hi = value.charCodeAt(0); var low = value.charCodeAt(1); return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; }). replace(NON_ALPHANUMERIC_REGEXP, function(value) { return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.join('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriterImpl(buf, uriValidator) { var ignoreCurrentElement = false; var out = bind(buf, buf.push); return { start: function(tag, attrs) { tag = lowercase(tag); if (!ignoreCurrentElement && blockedElements[tag]) { ignoreCurrentElement = tag; } if (!ignoreCurrentElement && validElements[tag] === true) { out('<'); out(tag); forEach(attrs, function(value, key) { var lkey = lowercase(key); var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); if (validAttrs[lkey] === true && (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out('>'); } }, end: function(tag) { tag = lowercase(tag); if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) { out('</'); out(tag); out('>'); } // eslint-disable-next-line eqeqeq if (tag == ignoreCurrentElement) { ignoreCurrentElement = false; } }, chars: function(chars) { if (!ignoreCurrentElement) { out(encodeEntities(chars)); } } }; } /** * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want * to allow any of these custom attributes. This method strips them all. * * @param node Root element to process */ function stripCustomNsAttrs(node) { if (node.nodeType === window.Node.ELEMENT_NODE) { var attrs = node.attributes; for (var i = 0, l = attrs.length; i < l; i++) { var attrNode = attrs[i]; var attrName = attrNode.name.toLowerCase(); if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) { node.removeAttributeNode(attrNode); i--; l--; } } } var nextNode = node.firstChild; if (nextNode) { stripCustomNsAttrs(nextNode); } nextNode = node.nextSibling; if (nextNode) { stripCustomNsAttrs(nextNode); } } } function sanitizeText(chars) { var buf = []; var writer = htmlSanitizeWriter(buf, noop); writer.chars(chars); return buf.join(''); } // define ngSanitize module and register $sanitize service angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); // angular sanitize end angular.module("events", ['ui.router', 'ngSanitize']) .config(function($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise('/'); $stateProvider .state('events', { url : '/', controller: function($state) { $state.go('detail',{domain: "code it", event: 0}, {location: 'replace'}); } }) .state('detail', { url : '/{domain}/{event}', templateUrl : 'partials/event-list.html', controller : function($scope, EventService, $stateParams, params, $sce, $state){ $scope.$sce = $sce; $scope.images = [ "cse", "it", "ece", "eee", "mech", "chem", "bme", "civil", "nontech" ] $scope.domains = {}; EventService.getAllDomains().then(function(domains){ $scope.domains = domains; }) $scope.currDomain = $stateParams.domain; $scope.currEvent = $stateParams.event; // console.log($stateParams.domain) // console.log(params) $scope.hideUntilLoad = true; $scope.domain = []; EventService.getEventList($scope.currDomain).then(function(domain){ if(domain == void(0)) $state.go('detail',{domain: "code it", event: 0}, {location: 'replace'}); var domainInt = parseInt($scope.currEvent); console.log(domainInt) if((domain.length - 1 < domainInt || domainInt < 0) || isNaN(domainInt) ){ // console.log(domain) $state.go('detail',{domain: $scope.currDomain, event: 0}, {location: 'replace'}); } $scope.domain = domain; $scope.hideUntilLoad = false; }) // console.log($scope.domain) }, resolve:{ params: ['$stateParams', function($stateParams){ // console.log([$stateParams.domain, $stateParams.event]) return [$stateParams.domain, $stateParams.event]; }] } }) }) .directive('backImg', function(){ return function(scope, element, attrs){ var url = attrs.backImg; element.css({ 'background-image': 'url(' + url +')', 'background-size' : 'cover' }); }; }) // .controller("DomainController", ['$scope', 'EventService', '$stateParams', function($scope, EventService, $stateParams){ // $scope.domains = {}; // EventService.getAllDomains().then(function(domains){ // $scope.domains = domains; // }) // // console.log($stateParams) // $scope.domain = []; // EventService.getEventList("bme").then(function(domain){ // $scope.domain = domain; // }) // // console.log($scope.domain) // }]) .service('EventService', function($http) { var service = { getAllDomains: function() { return $http.get('data.json', { cache: true }).then(function(resp) { // console.log(resp.data) return resp.data; }); }, getEventList: function(id) { return service.getAllDomains().then(function (domains) { // console.log(domains) // console.log(domains[id]) return domains[id]; }); } } return service; })
ArrangeSwapCommand = new Class({ Implements: ICommand, beginDepths: [], initialize: function(){}, // Move the target to the new depth. execute: function() { this.canvas.swapChildren(this.beginDepths[0], this.beginDepths[1]); }, // Place the target object back in its original depth. revert: function(target) { this.canvas.swapChildren(this.beginDepths[1], this.beginDepths[0]); }, setBeginDepths: function(a) { this.beginDepths = a; }, toString: function() { return '{name: ArrangeSwap, ptA: ' + this.beginDepths[0].toString() + ', ptB: ' + this.beginDepths[1].toString() + '}'; } });
define(['app', 'directives/search/search'], function() { 'use strict'; });
var visualization = function() { var vizData; var vizApp = this; var padding = 40; // padding between groups var max_group_width = 600; // TODO: this assumes fixed note width and height, potentially handle for importance of notes var max_note_width = 240; var max_note_height = 110; var container_width; var max_groups_in_row; var arrayOfNotes = []; var folderNameH6, vizContainer, colorButtons, layoutButtons, saveLayoutButton, notes; var init = function() { folderNameH6 = $('.js-group-name'); vizContainer = $('.js-vizContainer'); colorButtons = $('.coloring li'); layoutButtons = $('.positioning .layout'); saveLayoutButton = $('li[data-action="save_custom"]').hide() } var setData = function(data) { vizData = data; startViz(); } var startViz = function() { console.log(vizData); vizContainer.fadeIn(); container_width = vizContainer.width(); max_groups_in_row = parseInt(container_width / max_group_width) + 1; vizData.folderSpecificAnnotations.map(createNote); setGroupPositions(arrayOfNotes, 'category', true); saveCustomLayout(); notesEls = vizContainer.find('.ui-draggable'); notesEls.hover(function(){ var maxZ = 0; notesEls.each(function() { var index_current = parseInt($(this).css("zIndex"), 10); if(index_current > maxZ) { maxZ = index_current; } }); $(this).css('zIndex', maxZ+1); }) colorButtons.on('click', function() { colorButtons.removeClass('active'); $(this).addClass('active'); var cat = $(this).attr('data-color') console.log(cat); colorNotes(cat); }); layoutButtons.on('click', function() { layoutButtons.removeClass('active'); $(this).addClass('active'); var cat = $(this).attr('data-layout') console.log(cat); rearrangeNotes(cat); }); saveLayoutButton.on('click', saveCustomLayout); } var setGroupPositions = function(notes, type, start) { // create a map representing a group: // category:{'notes': [notes], 'height': height of a group based on num notes in group, 'posy': y position} var groups = {}; var category; notes.map(function(note) { if (type == 'category') { // group by topic category = note.getCategory(); } else { // group by paper category = note.getPaperId(); } if (category in groups) { groups[category]['notes'].push(note); } else { groups[category] = {'notes':[note], 'height': 0, 'posy': 0}; } }); // create grid-positioning for groups // determine the height of each by the number of notes in the group // height will be used to offset groups underneath other groups // width is limited by max_group_width, which currently only fits 2 notes (2 notes in a row within a group) for (var category in groups) { var group_notes = groups[category]['notes']; groups[category]['height'] = Math.ceil(group_notes.length/2) * (max_note_height + padding); } // set height for groups in rows in the viz beyond first row var group_keys = Object.keys(groups); for (var i = max_groups_in_row; i < group_keys.length; i++) { var key = group_keys[i]; // get key of the group directly above this group in the grid var group_above_key = group_keys[i-max_groups_in_row]; groups[key]['posy'] += groups[group_above_key]['height'] + groups[group_above_key]['posy']; } console.log(groups); // set note positions left_order = 0; // order of groups in a row for (var category in groups) { console.log(category); var group_notes = groups[category]['notes']; for (var i = 0; i < group_notes.length; i++) { var note = group_notes[i]; // get left position var left; if (i % 2 == 0) { left = left_order * max_group_width; } else { left = left_order * max_group_width + max_note_width; } // get top position var top; if (i % 2 == 0) { top = groups[category]['posy'] + ((i/2)*max_note_height) } else { top = groups[category]['posy'] + (parseInt(i/2)*max_note_height) } note.position([top,left], start); } left_order++; if (left_order >= max_groups_in_row) { left_order = 0; } } } var createNote = function(noteObj) { var newNote = new Note(noteObj, vizApp, arrayOfNotes.length-1); newNote.setBackground( colorArray[Math.floor(Math.random()*colorArray.length)]); arrayOfNotes.push(newNote); } var rearrangeNotes = function(arrangement) { if(arrangement == "custom") { arrayOfNotes.map(function(note) { var pos = note.customPosition(); note.position(pos); }); saveLayoutButton.fadeOut(); } else { setGroupPositions(arrayOfNotes, arrangement); } } var colorNotes = function(criteria) { if(criteria != "") { var arrayOfCriteria = generateArrayOfAttributes(criteria, arrayOfNotes); arrayOfNotes.map(function(note) { var attr = note.getNoteAttr(criteria); note.setBackground(colorArray[arrayOfCriteria.indexOf(attr)]) }); } else { arrayOfNotes.map(function(note) { note.setBackground('#eee') }); } } var saveCustomLayout = function() { arrayOfNotes.map(function(note) { var pos = note.position(); console.log("custom layout"); console.log(pos); note.customPosition(pos); }); saveLayoutButton.fadeOut(); } this.showSaveLayoutButton = function() { console.log('save button') saveLayoutButton.fadeIn(); } return { setData : setData, init : init } } function generateArrayOfAttributes(criteria, arrayOfNotes) { var rawArray = arrayOfNotes.map(function(note) { return note.getNoteAttr(criteria); }); return rawArray.getUnique(); } //http://stackoverflow.com/questions/1960473/unique-values-in-an-array Array.prototype.getUnique = function(){ var u = {}, a = []; for(var i = 0, l = this.length; i < l; ++i){ if(u.hasOwnProperty(this[i])) { continue; } a.push(this[i]); u[this[i]] = 1; } return a; } var colorArray = [ "#E1BEE7", "#D1C4E9", "#C5CAE9", "#BBDEFB", "#B2EBF2", "#DCEDC8", "#FFECB3", "#D7CCC8", "#CFD8DC", "#FFCDD2", "#F8BBD0" ]
import React from 'react' import ApartmentTable from './ApartmentListContainer' import TextFieldForm from './ApartmentForm' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import {Tabs, Tab} from 'material-ui/Tabs' import Paper from 'material-ui/Paper' import AppBar from 'material-ui/AppBar' import '../../css/apartment.css' const styles = { headline: { fontSize: 24, paddingTop: 16, marginBottom: 12, fontWeight: 400 } } const style = { height: 500, width: 1000, margin: 20, textAlign: 'center', display: 'inline-block' } const Apartment = () => ( <MuiThemeProvider> <div className='apartment'> <Tabs initialSelectedIndex={0} contentContainerClassName='5' > <Tab label='Apartment Form'> <div style={{textAlign: 'center', margin: '25px'}}> <Paper style={style} zDepth={1}> <AppBar title='Apartment Form' showMenuIconButton={false} /> <TextFieldForm /> </Paper> </div> </Tab> <Tab label='Apartment List'> <div style={{textAlign: 'center', margin: '25px'}}> <Paper style={style} zDepth={1}> <AppBar title='Apartment List' showMenuIconButton={false} /> <ApartmentTable /> </Paper> </div> </Tab> </Tabs> </div> </MuiThemeProvider> ) export default Apartment
var gulp = require('gulp'); var browserify = require('gulp-browserify'); var uglify = require('gulp-uglify'); var minify = require('gulp-minify'); var rename = require('gulp-rename'); var concat = require('gulp-concat'); var notify = require("gulp-notify"); gulp.task( 'vendors.css', function() { gulp.src([ 'node_modules/todomvc-common/base.css', 'node_modules/todomvc-app-css/index.css' ]) .pipe(concat('vendors.min.css')) .pipe( minify() ) .pipe(gulp.dest('./public/css')) .pipe(notify("Vendors css bundle has been successfully compiled!")); }); gulp.task( 'vendors.js', function() { gulp.src( [ 'node_modules/vue/dist/vue.js', 'node_modules/vue-resource/dist/vue-resource.js', 'node_modules/todomvc-common/base.js', ]) .pipe(uglify()) .pipe(concat('vendors.min.js')) .pipe(gulp.dest('./public/js')) .pipe(notify("Vendors jaavscript bundle has been successfully compiled!")); }); gulp.task( 'css', function() { gulp.src('./resources/assets/css/style.css') .pipe( minify() ) .pipe(rename('style.bundle.css')) .pipe(gulp.dest('./public/css')) .pipe(notify("Css bundle has been successfully compiled!")); }); gulp.task( 'todos', function() { gulp.src('./src/Todos/js/App.js') .pipe(browserify( { transform: [ 'babelify', 'vueify' ], })) .pipe(uglify()) .pipe(rename('todos.bundle.js')) .pipe(gulp.dest('./public/js/todos')) .pipe(notify("Todos bundle has been successfully compiled!")); }); gulp.task( 'watch-todos', function() { gulp.watch('src/Todos/js/App.js', ['todos']); }); gulp.task( 'vendors', [ 'vendors.css', 'vendors.js' ] ); gulp.task( 'watch', [ 'watch-todos' ] ); gulp.task( 'default', [ 'watch' ] );
// All symbols in the `Zp` category as per Unicode v2.1.9: [ '\u2029' ];
var webpack = require('webpack'); module.exports = { devtool: 'inline-source-map', entry: { 'react-bootstrap-table': './src/index.js' }, output: { path: './dist', filename: '[name].js', library: 'ReactBootstrapTable', libraryTarget: 'umd' }, externals: [ { 'react': { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } }, { 'react-dom': { root: 'ReactDOM', commonjs2: 'react-dom', commonjs: 'react-dom', amd: 'react-dom' } } ], module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loaders: ['babel'] }] } };
export default Ember.Component.extend({ classNames: ['pretty-color'], attributeBindings: ['style'], style: function(){ return 'color: ' + this.get('name') + ';'; }.property('name') });
import request from 'supertest'; import low from 'lowdb'; import apiLoader from '../src/api.js'; import Car from '../../models/Car.js'; const freshDB = () => { const fresh = low(); fresh.defaults({ cars: [] }).write(); return fresh; }; describe('GET /api/cars', () => { let db; let api; beforeEach(() => { db = freshDB(); api = apiLoader(db); }); test('respond with json', () => request(api) .get('/api/cars') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((response) => { expect(response.body.cars).toEqual([]); })); test('respond with cars that match criteria', () => { db.get('cars') .push(new Car('a', 'fox', 20000, 2013, 100000)) .push(new Car('a', 'gol', 20000, 2013, 100000)) .write(); return request(api) .get('/api/cars?query=Fox') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((response) => { expect(response.body.cars.length).toEqual(1); expect(response.body.cars[0].fullName).toEqual('fox'); }); }); test('respond with cars that match criteria with many words', () => { db.get('cars') .push(new Car('a', 'fox', 20000, 2013, 100000)) .push(new Car('a', 'fox outro', 20000, 2013, 100000)) .push(new Car('a', 'gol', 20000, 2013, 100000)) .write(); return request(api) .get('/api/cars?query=Fox outro') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((response) => { expect(response.body.cars.length).toEqual(1); expect(response.body.cars[0].fullName).toEqual('fox outro'); }); }); });
'use strict'; /*! * Snakeskin * https://github.com/SnakeskinTpl/Snakeskin * * Released under the MIT license * https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE */ import Snakeskin from '../core'; import { ws } from '../helpers/string'; import { any } from '../helpers/gcc'; Snakeskin.addDirective( 'return', { block: true, deferInit: true, group: ['return', 'microTemplate'], placement: 'template', trim: true }, function (command) { if (command.slice(-1) === '/') { this.startInlineDir(null, {command: command.slice(0, -1)}); return; } this.startDir(null, {command}); if (!command) { this.wrap(`__RESULT__ = ${this.getResultDecl()};`); } }, function () { const {command} = this.structure.params; const val = command ? this.out(command, {unsafe: true}) : this.getReturnResultDecl(), parent = any(this.hasParentFunction()); if (!parent || parent.block) { this.append(`return ${val};`); return; } const def = ws` __RETURN__ = true; __RETURN_VAL__ = ${val}; `; let str = ''; if (parent.asyncParent) { if (this.getGroup('Async')[parent.asyncParent]) { str += def; if (this.getGroup('waterfall')[parent.asyncParent]) { str += 'return arguments[arguments.length - 1](__RETURN_VAL__);'; } else { str += ws` if (typeof arguments[0] === 'function') { return arguments[0](__RETURN_VAL__); } return false; `; } } else { str += 'return false;'; } } else { if (parent && !this.getGroup('async')[parent.target.name]) { str += def; this.deferReturn = 1; } str += 'return false;'; } this.append(str); } );
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = undefined; var _defineProperty2 = require('babel-runtime/helpers/defineProperty'); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _Checkbox = require('./Checkbox.web'); var _Checkbox2 = _interopRequireDefault(_Checkbox); var _getDataAttr = require('../_util/getDataAttr'); var _getDataAttr2 = _interopRequireDefault(_getDataAttr); var _omit = require('omit.js'); var _omit2 = _interopRequireDefault(_omit); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var __assign = undefined && undefined.__assign || Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } } return t; }; var AgreeItem = function (_React$Component) { (0, _inherits3["default"])(AgreeItem, _React$Component); function AgreeItem() { (0, _classCallCheck3["default"])(this, AgreeItem); return (0, _possibleConstructorReturn3["default"])(this, _React$Component.apply(this, arguments)); } AgreeItem.prototype.render = function render() { var _classNames; var _props = this.props, prefixCls = _props.prefixCls, style = _props.style, className = _props.className; var wrapCls = (0, _classnames2["default"])((_classNames = {}, (0, _defineProperty3["default"])(_classNames, prefixCls + '-agree', true), (0, _defineProperty3["default"])(_classNames, className, className), _classNames)); return _react2["default"].createElement("div", __assign({}, (0, _getDataAttr2["default"])(this.props), { className: wrapCls, style: style }), _react2["default"].createElement(_Checkbox2["default"], __assign({}, (0, _omit2["default"])(this.props, ['style']), { className: prefixCls + '-agree-label' }))); }; return AgreeItem; }(_react2["default"].Component); exports["default"] = AgreeItem; AgreeItem.defaultProps = { prefixCls: 'am-checkbox' }; module.exports = exports['default'];
var request = require('request'); var RestSupport = function() { RestSupport.prototype.get = function(resource, next) { var me = this; request({ url: resource, method: 'GET', headers: { 'content-type': 'application/json' } }, function (err, res, body) { if (err) return next(err); next(err, body, res); }); }; }; module.exports = new RestSupport();
var path = require("path"); var webpack = require("webpack"); module.exports = function(entries, release) { var config = { // entry file to start from entry: entries, output: { // directory to output to path: path.resolve("./lib"), // output file name filename: "[name].js" }, plugins: [ /* * This makes the left side variable available in every module and assigned to the right side module */ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", "window.$": "jquery" }) ] }; if (release) { var uglify = new webpack.optimize.UglifyJsPlugin({ beautify: false, mangle: { screw_ie8: true, keep_fnames: true }, compress: { screw_ie8: true }, comments: false }); config.plugins.push(uglify); }else{ //config.devtool = 'cheap-eval-source-map'; } return config; };
/* @flow */ 'use strict' /* :: import type {CorsConfiguration} from '../../types.js' */ const projectMeta = require('../utils/project-meta.js') const values = require('../values.js') function readCors ( cwd /* : string */ ) /* : Promise<CorsConfiguration | false> */ { return projectMeta.read(cwd) .then((config) => { // Want to support two options here: // 1. Falsey to disable CORS if (!config.server || !config.server.cors) { return false } // 2. Truthy to use default CORS and merge in any custom stuff return Object.assign({ credentials: values.DEFAULT_CORS.CREDENTIALS, exposedHeaders: values.DEFAULT_CORS.EXPOSED_HEADERS, headers: values.DEFAULT_CORS.HEADERS, maxAge: values.DEFAULT_CORS.MAX_AGE, origins: values.DEFAULT_CORS.ORIGINS }, typeof config.server.cors === 'boolean' ? {} : config.server.cors) }) } module.exports = readCors
var mongoose = require('mongoose'), _ = require('underscore'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var Throw = new Schema({ score: { type: Number, required: true, min: 0, max: 25 }, modifier: { type: Number, required: true, min: 1, max: 3 }, }); var DartsPlayer = new Schema({ name: { type: String, required: true }, throws: [Throw], }); DartsPlayer.virtual('score') .get( function() { var game = this.parentArray._parent; if (_.isEmpty(this.throws)) return +game.startingScore; return _.reduce(this.throws, function(memo, t) { var potentialScore = memo - t.score * t.modifier; if (potentialScore < 0 || potentialScore == 0 && game.out == 2 && t.modifier != 2 || potentialScore == 1 && game.out == 2) return memo; else return potentialScore; }, +game.startingScore); }); var DartsGame = new Schema({ startingScore: { type: Number, required: true, min: 301, max: 1001, default: 501 }, out: { type: Number, required: true, min: 1, max: 2, default: 2 }, players: [DartsPlayer], throwNumber: { type: Number, required: true, min: 0, max: 2, default: 0 }, currentPlayer: { type: Number, required: true, default: 0 }, userId: { type: ObjectId, required: true }, }); DartsGame.method('setPlayers', function(players) { for (var i in players) { this.players.push({ id: players[i].id, name: players[i].name, }); } }); DartsGame.method('throw', function(score, modifier) { function validate(score, modifier) { if (score == 25 && (modifier == 1 || modifier == 2)) return; if (score > 20) throw 'Can\'t score higher than 20'; if (score < 0) throw 'Can\'t score lower than 0'; if (modifier > 4) throw 'Modifier bigger than 3 is not allowed'; if (modifier < 0) throw 'Negative modifer is not allowed'; }; function nextThrow(game) { if (game.throwNumber == 2) { game.throwNumber = 0; if (game.currentPlayer == game.players.length - 1) { game.currentPlayer = 0; } else game.currentPlayer++; } else game.throwNumber++; } if (!this.isOver()) { if (modifier == null) modifier = 1; validate(score, modifier); var player = this.players[this.currentPlayer]; player.throws.push({score: score, modifier: modifier}); nextThrow(this); } }); String.prototype.startsWith = function(str) { return (this.indexOf(str) === 0); }; DartsGame.method('parseThrow', function(score) { if (score.startsWith('D')) { this.throw(score.substring(1), 2); } else if (score.startsWith('T')) { this.throw(score.substring(1), 3); } else { if (_.isNumber(+score)) this.throw(+score); else throw 'Not a legal score'; } }); DartsGame.method('isOver', function() { return _.any(this.players, function(player) { return player.score == 0; }); }); DartsGame.method('winner', function() { return _.detect(this.players, function(player) { return player.score == 0; }); }); DartsGame.method('isStarted', function() { return _.any(this.players, function(player) { return !_.isEmpty(player.throws); }); }); DartsGame.method('lastThrower', function() { if (this.throwNumber == 0) { if (this.currentPlayer == 0) { return this.players[this.players.length - 1]; } return this.players[this.currentPlayer - 1]; } else { return this.players[this.currentPlayer]; } }); DartsGame.method('undoThrow', function() { if (this.isStarted()) { if (this.throwNumber == 0) { this.throwNumber = 2; if (this.currentPlayer == 0) { this.currentPlayer = this.players.length - 1; } else { this.currentPlayer--; } } else { this.throwNumber--; } _.last(this.players[this.currentPlayer].throws).remove(); } }); mongoose.model('DartsGame', DartsGame);
{ if (Array.isArray(t) && c(e)) return (t.length = Math.max(t.length, e)), t.splice(e, 1, n), n; if (d(t, e)) return (t[e] = n), n; var r = t.__ob__; return t._isVue || (r && r.vmCount) ? n : r ? (D(r.value, e, n), r.dep.notify(), n) : ((t[e] = n), n); }
(function () { 'use strict'; angular .module('users.admin') .controller('UserController', UserController); UserController.$inject = ['$scope', '$state', '$window', 'Authentication', 'userResolve', '$mdToast']; function UserController($scope, $state, $window, Authentication, user, $mdToast) { var vm = this; vm.authentication = Authentication; vm.user = user; vm.remove = remove; vm.update = update; function remove(user) { if ($window.confirm('Are you sure you want to delete this user?')) { if (user) { user.$remove(); vm.users.splice(vm.users.indexOf(user), 1); } else { vm.user.$remove(function () { $state.go('admin.users'); }); } } } function update(isValid) { if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'vm.userForm'); return false; } var user = vm.user; user.$update(function () { $state.go('admin.user', { userId: user._id }); }, function (errorResponse) { vm.error = errorResponse.data.message; $mdToast.show( $mdToast.simple() .textContent(vm.error) .hideDelay(3000) ); }); } } }());
module.exports = { extends: 'airbnb', parser: 'babel-eslint', plugins: [ 'react', 'jsx-a11y', 'import' ], globals: { OT: true }, env: { browser: true, }, rules: { 'no-confusing-arrow': ['error', { allowParens: true }], 'react/jsx-filename-extension': 'off', 'react/forbid-prop-types': ['error', { forbid: ['any', 'array'] }] } };
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "azure_network_virtualrouter");
export const GET_RESOURCE_TO_VERIFY = 'verificationPortal/GET_RESOURCE_TO_VERIFY' export const FORM_SUCCESSFULLY_SUBMITTED = 'FORM_SUCCESSFULLY_SUBMITTED' export const CLEAR_RESOURCE = 'verificationPortal/CLEAR_RESOURCE'
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { selectUser } from '../../../store/actions' import { PagingState, SortingState, } from '@devexpress/dx-react-grid' import { Grid, TableView, TableHeaderRow, PagingPanel, } from '@devexpress/dx-react-grid-bootstrap3' const URL = 'https://js.devexpress.com/Demos/WidgetsGallery/data/orderItems' class UserList extends React.Component { constructor (props) { super(props) this.state = { columns: [ { name: 'OrderNumber', title: 'Order #', align: 'right' }, { name: 'OrderDate', title: 'Order Date' }, { name: 'StoreCity', title: 'Store City' }, { name: 'StoreState', title: 'Store State' }, { name: 'Employee', title: 'Employee' }, { name: 'SaleAmount', title: 'Sale Amount', align: 'right' }, ], rows: [], sorting: [{ columnName: 'StoreCity', direction: 'asc' }], totalCount: 0, pageSize: 10, allowedPageSizes: [5, 10, 15], currentPage: 0, // loading: true, } this.changeSorting = this.changeSorting.bind(this) this.changeCurrentPage = this.changeCurrentPage.bind(this) this.changePageSize = this.changePageSize.bind(this) } componentDidMount () { this.loadData() } componentDidUpdate () { this.loadData() } changeSorting (sorting) { this.setState({ // loading: true, sorting, }) } changeCurrentPage (currentPage) { this.setState({ // loading: true, currentPage, }) } changePageSize (pageSize) { const totalPages = Math.ceil(this.state.totalCount / pageSize) const currentPage = Math.min(this.state.currentPage, totalPages - 1) this.setState({ // loading: true, pageSize, currentPage, }) } queryString () { const { sorting, pageSize, currentPage } = this.state let queryString = `${URL}?take=${pageSize}&skip=${pageSize * currentPage}` const columnSorting = sorting[0] if (columnSorting) { const sortingDirectionString = columnSorting.direction === 'desc' ? ' desc' : '' queryString = `${queryString}&orderby=${columnSorting.columnName}${sortingDirectionString}` } return queryString } loadData () { const queryString = this.queryString() if (queryString === this.lastQuery) { // this.setState({ loading: false }) return } fetch(queryString) .then(response => response.json()) .then(data => { console.log(data.items.length) this.setState({ rows: data.items, totalCount: data.totalCount, // loading: false, }) }) .catch(() => this.setState({ // loading: false })) this.lastQuery = queryString } createTableItems () { return this.props.users.map((user, i) => { return ( <tr onClick={() => this.props.selectUser(user)} key={i}> <th>{user.id}</th> <th>{user.name}</th> <th>{user.born}</th> <th>{user.description}</th> <th><img src={user.image} alt='' /></th> </tr> ) }) } render () { const { rows, columns, sorting, pageSize, allowedPageSizes, currentPage, totalCount, loading, } = this.state return ( <div style={{ position: 'relative' }}> <Grid rows={rows} columns={columns} > <SortingState sorting={sorting} onSortingChange={this.changeSorting} /> <PagingState currentPage={currentPage} onCurrentPageChange={this.changeCurrentPage} pageSize={pageSize} onPageSizeChange={this.changePageSize} totalCount={totalCount} /> <TableView tableCellTemplate={({ row, column }) => { if (column.name === 'SaleAmount') { return ( <td style={{ textAlign: 'right' }}>${row.SaleAmount}</td> ) } return undefined }} tableNoDataCellTemplate={({ colspan }) => ( <td style={{ textAlign: 'center', padding: '40px 0', }} colSpan={colspan} > <big className='text-muted'>{loading ? '' : 'No data'}</big> </td> )} /> <TableHeaderRow allowSorting /> <PagingPanel allowedPageSizes={allowedPageSizes} /> </Grid> </div> ) } } UserList.propTypes = { users: PropTypes.array, selectUser: PropTypes.func } const mapStateToProps = (state) => ({ users: state.users }) const matchDispatchToProps = (dispatch) => { return bindActionCreators({ selectUser: selectUser }, dispatch) } export default connect(mapStateToProps, matchDispatchToProps)(UserList)
module.exports = { // Load Mock Product Data Into localStorage init: function() { // localStorage.clear(); localStorage.setItem('thing', JSON.stringify([{ _id:'cbus-254-56-61', parent:null, label:'much test' }, { _id:'mesh-099', parent:'voltage', label:'wow' }])); localStorage.setItem('items',JSON.stringify([ { _id:'cbus-254-56-61.level', thing:'cbus-254-56-61', item:'level', label:'much test', value:1, type:'number', icon: 'scotch-beer.png', widget:'Slider' }, { _id:'mesh-099.voltage', thing:'mesh-099', item:'voltage', label:'wow', value:2, type:'number', icon: 'scotch-beer.png', widget:'Slider' } ])); } };
function generateArray(table) { var out = []; var rows = table.querySelectorAll('tr'); var ranges = []; for (var R = 0; R < rows.length; ++R) { var outRow = []; var row = rows[R]; var columns = row.querySelectorAll('td'); for (var C = 0; C < columns.length; ++C) { var cell = columns[C]; var colspan = cell.getAttribute('colspan'); var rowspan = cell.getAttribute('rowspan'); var cellValue = cell.innerText; if(cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue; //Skip ranges ranges.forEach(function(range) { if(R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) { for(var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null); } }); //Handle Row Span if (rowspan || colspan) { rowspan = rowspan || 1; colspan = colspan || 1; ranges.push({s:{r:R, c:outRow.length},e:{r:R+rowspan-1, c:outRow.length+colspan-1}}); }; //Handle Value outRow.push(cellValue !== "" ? cellValue : null); //Handle Colspan if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null); } out.push(outRow); } return [out, ranges]; }; function datenum(v, date1904) { if(date1904) v+=1462; var epoch = Date.parse(v); return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000); } function sheet_from_array_of_arrays(data, opts) { var ws = {}; var range = {s: {c:10000000, r:10000000}, e: {c:0, r:0 }}; for(var R = 0; R != data.length; ++R) { for(var C = 0; C != data[R].length; ++C) { if(range.s.r > R) range.s.r = R; if(range.s.c > C) range.s.c = C; if(range.e.r < R) range.e.r = R; if(range.e.c < C) range.e.c = C; var cell = {v: data[R][C] }; if(cell.v == null) continue; var cell_ref = XLSX.utils.encode_cell({c:C,r:R}); if(typeof cell.v === 'number') cell.t = 'n'; else if(typeof cell.v === 'boolean') cell.t = 'b'; else if(cell.v instanceof Date) { cell.t = 'n'; cell.z = XLSX.SSF._table[14]; cell.v = datenum(cell.v); } else cell.t = 's'; ws[cell_ref] = cell; } } if(range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range); return ws; } function Workbook() { if(!(this instanceof Workbook)) return new Workbook(); this.SheetNames = []; this.Sheets = {}; } function s2ab(s) { var buf = new ArrayBuffer(s.length); var view = new Uint8Array(buf); for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; } function export_table_to_excel(id) { var theTable = document.getElementById(id); var oo = generateArray(theTable); var ranges = oo[1]; /* original data */ var data = oo[0]; var ws_name = "SheetJS"; var wb = new Workbook(), ws = sheet_from_array_of_arrays(data); /* add ranges to worksheet */ ws['!merges'] = ranges; /* add worksheet to workbook */ wb.SheetNames.push(ws_name); wb.Sheets[ws_name] = ws; var wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:false, type: 'binary'}); saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "test.xlsx") }
export default function formatUrl({ baseUrl, size, theme, uri, view }) { let src = `${baseUrl}/?uri=${uri}&size=${size}&theme=${theme}`; if (view) { src += `&view=${view}`; } return src; }
const test = require('tape') const parse = require('../../parse').element('Body') test('b(N+1,N+2)', function (t) { const res = parse('b(N+1,N+2)') t.equal(typeof res, 'object') t.ok(res instanceof Array) t.equal(res.length, 1) t.end() }) test('b(N+1,N+2), c(N-1)', function (t) { const res = parse('b(N+1,N+2), c(N-1)') t.equal(typeof res, 'object') t.ok(res instanceof Array) t.equal(res.length, 2) t.end() })
'use strict'; // Setting up route angular.module('users').config(['$stateProvider', function ($stateProvider) { // Users state routing $stateProvider .state('settings', { abstract: true, url: '/settings', templateUrl: 'modules/users/client/views/settings/settings.client.view.html', data: { // DL - adding supervisor and technician roles roles: ['user', 'admin', 'technician', 'supervisor'] } }) .state('settings.profile', { url: '/profile', templateUrl: 'modules/users/client/views/settings/edit-profile.client.view.html' }) .state('settings.password', { url: '/password', templateUrl: 'modules/users/client/views/settings/change-password.client.view.html' }) .state('settings.accounts', { url: '/accounts', templateUrl: 'modules/users/client/views/settings/manage-social-accounts.client.view.html' }) .state('settings.picture', { url: '/picture', templateUrl: 'modules/users/client/views/settings/change-profile-picture.client.view.html' }) .state('authentication', { abstract: true, url: '/authentication', templateUrl: 'modules/users/client/views/authentication/authentication.client.view.html' }) .state('authentication.signup', { url: '/signup', templateUrl: 'modules/users/client/views/authentication/signup.client.view.html' }) .state('authentication.signin', { url: '/signin?err', templateUrl: 'modules/users/client/views/authentication/signin.client.view.html' }) .state('password', { abstract: true, url: '/password', template: '<ui-view/>' }) .state('password.forgot', { url: '/forgot', templateUrl: 'modules/users/client/views/password/forgot-password.client.view.html' }) .state('password.reset', { abstract: true, url: '/reset', template: '<ui-view/>' }) .state('password.reset.invalid', { url: '/invalid', templateUrl: 'modules/users/client/views/password/reset-password-invalid.client.view.html' }) .state('password.reset.success', { url: '/success', templateUrl: 'modules/users/client/views/password/reset-password-success.client.view.html' }) .state('password.reset.form', { url: '/:token', templateUrl: 'modules/users/client/views/password/reset-password.client.view.html' }); } ]);
var Todo = React.createClass({displayName: "Todo", getInitialState: function() { this.text = ""; return {text: ""}; }, componentWillUnmount: function() { this.ref.off(); }, componentWillMount: function() { this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/" + this.props.todoKey); // Update the todo's text when it changes. this.ref.on("value", function(snap) { if (snap.val() !== null) { this.text = snap.val().text; this.setState({ text: this.text }); } else { this.ref.update({ text: "" }); } }.bind(this)); }, onTextBlur: function(event) { this.ref.update({ text: $(event.target).text() }); }, render: function() { return ( React.createElement("li", {id: this.props.todoKey, className: "list-group-item todo"}, React.createElement("a", {href: "#", className: "pull-left todo-check"}, React.createElement("span", { className: "todo-check-mark glyphicon glyphicon-ok", "aria-hidden": "true"} ) ), React.createElement("span", { onBlur: this.onTextBlur, contentEditable: "true", "data-ph": "Todo", className: "todo-text"}, this.state.text ) ) ); } }); var TodoList = React.createClass({displayName: "TodoList", getInitialState: function() { this.todos = []; return {todos: []}; }, componentWillMount: function() { this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/"); // Add an empty todo if none currently exist. this.ref.on("value", function(snap) { if (snap.val() === null) { this.ref.push({ text: "", checked: false, }); } }.bind(this)); // Add an added child to this.todos. this.ref.on("child_added", function(childSnap) { this.todos.push({ k: childSnap.key(), val: childSnap.val() }); this.setState({ todos: this.todos }); }.bind(this)); this.ref.on("child_removed", function(childSnap) { var key = childSnap.key(); var i; for (i = 0; i < this.todos.length; i++) { if (this.todos[i].k == key) { break; } } this.todos.splice(i, 1); this.setState({ todos: this.todos }); }.bind(this)); }, componentWillUnmount: function() { this.ref.off(); }, render: function() { var todos = this.state.todos.map(function (todo) { return ( React.createElement(Todo, {todoKey: todo.k}) ); }); return ( React.createElement("div", null, React.createElement("h1", {id: "list_title"}, this.props.title), React.createElement("ul", {id: "todo-list", className: "list-group"}, todos ) ) ); } }); var ListPage = React.createClass({displayName: "ListPage", render: function() { return ( React.createElement("div", null, React.createElement("div", {id: "list_page"}, React.createElement("a", { onClick: this.props.app.navOnClick({page: "LISTS"}), href: "/#/lists", id: "lists_link", className: "btn btn-primary"}, "Back to Lists" ) ), React.createElement("div", {className: "page-header"}, this.props.children ) ) ); } }); var Nav = React.createClass({displayName: "Nav", render: function() { return ( React.createElement("nav", {className: "navbar navbar-default navbar-static-top"}, React.createElement("div", {className: "container"}, React.createElement("div", {className: "navbar-header"}, React.createElement("a", {onClick: this.props.app.navOnClick({page: "LISTS"}), className: "navbar-brand", href: "?"}, "Firebase Todo") ), React.createElement("ul", {className: "nav navbar-nav"}, React.createElement("li", null, React.createElement("a", {href: "?"}, "Lists")) ) ) ) ); }, }); var App = React.createClass({displayName: "App", getInitialState: function() { var state = this.getState(); this.setHistory(state, true); return this.getState(); }, setHistory: function(state, replace) { var histFunc = replace ? history.replaceState.bind(history) : history.pushState.bind(history); if (state.page === "LIST") { histFunc(state, "", "#/list/" + state.todoListKey); } else if (state.page === "LISTS") { histFunc(state, "", "#/lists"); } else { console.log("Unknown page: " + state.page); } }, getState: function() { var url = document.location.toString(); if (url.match(/#/)) { var path = url.split("#")[1]; var res = path.match(/\/list\/([^\/]*)$/); if (res) { return { page: "LIST", todoListKey: res[1], }; } res = path.match(/lists$/); if (res) { return { page: "LISTS" } } } return { page: "LISTS" } }, componentWillMount: function() { // Register history listeners. window.onpopstate = function(event) { this.setState(event.state); }; }, navOnClick: function(state) { return function(event) { this.setHistory(state, false); this.setState(state); event.preventDefault(); }.bind(this); }, getPage: function() { if (this.state.page === "LIST") { return ( React.createElement(ListPage, {app: this}, React.createElement(TodoList, {todoListKey: this.state.todoListKey}) ) ); } else if (this.state.page === "LISTS") { return ( React.createElement("a", {onClick: this.navOnClick({page: "LIST", todoListKey: "-JjcFYgp1LyD5oDNNSe2"}), href: "/#/list/-JjcFYgp1LyD5oDNNSe2"}, "hi") ); } else { console.log("Unknown page: " + this.state.page); } }, render: function() { return ( React.createElement("div", null, React.createElement(Nav, {app: this}), React.createElement("div", {className: "container", role: "main"}, this.getPage() ) ) ); } }); React.render( React.createElement(App, null), document.getElementById('content') );
'use strict'; angular.module('myApp').factory('inboundRulesApi', function($resource) { return $resource('/api/scm.config/1.0/inbound_rules', {}, { 'query': { method: 'GET', isArray: true , responseType: 'json', transformResponse: function (data) { var wrapped = angular.fromJson(data); return wrapped.items; } }, 'delete': { method: 'DELETE', url: '/api/scm.config/1.0/inbound_rule/:ruleid', params: { ruleid: '@ruleid' } }, 'update': { method: 'PUT', url: '/api/scm.config/1.0/inbound_rule/:ruleid', params: { ruleid: '@ruleid' } } }); }); angular.module('myApp').service('inboundRulesSelectionSvc', function() { this.inboundRules = { }; this.setinboundRules = function(obj){ this.inboundRules = obj; } this.getinboundRules = function(){ return this.inboundRules; } });
/** * EditableSlot is an abstract class representing Slots that can have a value directly entered into them * in addition to accepting Blocks. * Subclasses must implement createInputSystem() and formatTextSummary() * @param {Block} parent * @param {string} key * @param {number} inputType * @param {number} snapType * @param {number} outputType - [any, num, string, select] The type of data that can be directly entered * @param {Data} data - The initial value of the Slot * @constructor */ function EditableSlot(parent, key, inputType, snapType, outputType, data) { Slot.call(this, parent, key, snapType, outputType); this.inputType = inputType; this.enteredData = data; this.editing = false; //TODO: make the slotShape be an extra argument } EditableSlot.prototype = Object.create(Slot.prototype); EditableSlot.prototype.constructor = EditableSlot; EditableSlot.setConstants = function() { /* The type of Data that can be directly entered into the Slot. */ EditableSlot.inputTypes = {}; EditableSlot.inputTypes.any = 0; EditableSlot.inputTypes.num = 1; EditableSlot.inputTypes.string = 2; EditableSlot.inputTypes.select = 3; }; /** * @param {string} text - The text to set the slotShape to display * @param {boolean} updateDim - Should the Stack be told to update after this? */ EditableSlot.prototype.changeText = function(text, updateDim) { this.slotShape.changeText(text); if (updateDim && this.parent.stack != null) { this.parent.stack.updateDim(); //Update dimensions. } }; /** * Tells the Slot to display an InputSystem so it can be edited. Also sets the slotShape to appear selected */ EditableSlot.prototype.edit = function() { DebugOptions.assert(!this.hasChild); if (!this.editing) { this.editing = true; this.slotShape.select(); const inputSys = this.createInputSystem(); inputSys.show(this.slotShape, this.updateEdit.bind(this), this.finishEdit.bind(this), this.enteredData); } }; /** * @inheritDoc */ EditableSlot.prototype.onTap = function() { this.edit(); }; /** * Generates and displays an interface to modify the Slot's value */ EditableSlot.prototype.createInputSystem = function() { DebugOptions.markAbstract(); }; /** * Called by the InputSystem to change the Slot's data and displayed text * @param {Data} data - The Data the Slot should set its value to * @param {string} [visibleText] - The text the Slot should display as its value. Should correspond to Data. */ EditableSlot.prototype.updateEdit = function(data, visibleText) { DebugOptions.assert(this.editing); if (visibleText == null) { visibleText = this.dataToString(data); } this.enteredData = data; this.changeText(visibleText, true); SaveManager.markEdited(); }; /** * Called when an InputSystem finishes editing the Slot * @param {Data} data - The Data the Slot should be set to */ EditableSlot.prototype.finishEdit = function(data) { DebugOptions.assert(this.editing); if (this.editing) { this.setData(data, true, true); //Sanitize data, updateDims this.slotShape.deselect(); this.editing = false; SaveManager.markEdited(); } }; /** * Returns whether the Slot is being edited * @return {boolean} */ EditableSlot.prototype.isEditing = function() { return this.editing; }; /** * Assigns the Slot's Data and updates its text.w * @param {Data} data - The Data to set to * @param {boolean} sanitize - indicates whether the Data should be run through sanitizeData first * @param {boolean} updateDim - indicates if the Stack should updateDim after this */ EditableSlot.prototype.setData = function(data, sanitize, updateDim) { if (sanitize) { data = this.sanitizeData(data); } if (data == null) return; this.enteredData = data; this.changeText(this.dataToString(this.enteredData), updateDim); }; /** * Converts the Slot's data to a displayable string. Subclasses override this method to apply formatting. * @param {Data} data * @return {string} */ EditableSlot.prototype.dataToString = function(data) { return data.asString().getValue(); }; /** * Validates that the Data is compatible with this Slot. May attempt to fix invalid Data. * By default, this function just converts the data to the correct type. Subclasses override this method. * Makes use of inputType * @param {Data|null} data - The Data to sanitize * @return {Data|null} - The sanitized Data or null if the Data cannot be sanitized */ EditableSlot.prototype.sanitizeData = function(data) { if (data == null) return null; const inputTypes = EditableSlot.inputTypes; // Only valid Data of the correct type is allowed if (this.inputType === inputTypes.string) { data = data.asString(); } else if (this.inputType === inputTypes.num) { data = data.asNum(); } else if (this.inputType === inputTypes.select) { data = data.asSelection(); } if (data.isValid) { return data; } return null; }; /** * @inheritDoc * @return {string} */ EditableSlot.prototype.textSummary = function() { let result = "..."; if (!this.hasChild) { //If it has a child, just use an ellipsis. result = this.dataToString(this.enteredData); } return this.formatTextSummary(result); }; /** * Takes a textSummary and performs string manipulation to format it according to the Slot type * @param {string} textSummary * @return {string} */ EditableSlot.prototype.formatTextSummary = function(textSummary) { DebugOptions.markAbstract(); }; /** * Reads the Data from the Slot, assuming that the Slot has no children. * @return {Data} - The Data stored in the Slot */ EditableSlot.prototype.getDataNotFromChild = function() { return this.enteredData; }; /** * Converts the Slot and its children into XML, storing the value in the enteredData as well * @inheritDoc * @param {Document} xmlDoc * @return {Node} */ EditableSlot.prototype.createXml = function(xmlDoc) { let slot = Slot.prototype.createXml.call(this, xmlDoc); let enteredData = XmlWriter.createElement(xmlDoc, "enteredData"); enteredData.appendChild(this.enteredData.createXml(xmlDoc)); slot.appendChild(enteredData); return slot; }; /** * @inheritDoc * @param {Node} slotNode * @return {EditableSlot} */ EditableSlot.prototype.importXml = function(slotNode) { Slot.prototype.importXml.call(this, slotNode); const enteredDataNode = XmlWriter.findSubElement(slotNode, "enteredData"); const dataNode = XmlWriter.findSubElement(enteredDataNode, "data"); if (dataNode != null) { const data = Data.importXml(dataNode); if (data != null) { this.setData(data, true, false); } } return this; }; /** * @inheritDoc * @param {EditableSlot} slot */ EditableSlot.prototype.copyFrom = function(slot) { Slot.prototype.copyFrom.call(this, slot); this.setData(slot.enteredData, false, false); }; /** * @inheritDoc * @return {boolean} */ EditableSlot.prototype.isEditable = function() { return true; };
'use strict'; describe('Controller: EventCtrl', function () { // load the controller's module beforeEach(module('ngBrxApp')); var EventCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); EventCtrl = $controller('EventCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
import Component from '@glimmer/component'; import VerifiLogoSvg from 'dummy/images/media-registry/verifi-logo.svg'; export default class RegistrationEmbedded extends Component { get registrationEmbedded() { let verifi_id = this.args.model?.verifi_id; if (verifi_id) { return { id: verifi_id, type: 'registration', imgURL: VerifiLogoSvg, title: 'Verifi Registry', description: verifi_id, fields: [ { title: 'asset type', value: this.args.model.asset_type || 'Master Recording', }, { title: 'created', value: this.args.model.verifi_reg_date, type: 'date', }, ], }; } return null; } }
// 3rd const Router = require('koa-router') const compress = require('koa-compress') const nunjucks = require('nunjucks') // 1st const cache = require('../cache') const router = new Router() //////////////////////////////////////////////////////////// router.get('/sitemap.txt', async ctx => { ctx.redirect('/sitemap.xml') }) router.get('/sitemaps/:idx.txt', compress(), async ctx => { const idx = parseInt(ctx.params.idx) || 0 const chunk = cache.get('sitemaps')[idx] ctx.assert(chunk, 404) ctx.type = 'text/plain' ctx.body = chunk.join('\n') }) //////////////////////////////////////////////////////////// // { count: <sitemaps total> } const indexTemplate = nunjucks.compile( ` <?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> {% for i in range(0, count) %} <sitemap> <loc>https://www.roleplayerguild.com/sitemaps/{{ i }}.txt</loc> </sitemap> {% endfor %} </sitemapindex> `.trim() ) router.get('/sitemap.xml', async ctx => { var chunks = cache.get('sitemaps') ctx.type = 'text/xml' ctx.body = indexTemplate.render({ count: chunks.length }) }) //////////////////////////////////////////////////////////// module.exports = router
'use strict'; var SIGNALING_SERVER = 'https://112.108.40.152:443/'; var config = { openSocket: function(config) { console.log('s1'); /* Firebase ver. */ var channel = config.channel || 'screen-capturing-' + location.href.replace( /\/|:|#|%|\.|\[|\]/g , ''); var socket = new Firebase('https://webrtc.firebaseIO.com/' + channel); socket.channel = channel; socket.on("child_added", function(data) { console.log('s2'); config.onmessage && config.onmessage(data.val()); }); socket.send = function(data) { console.log('s3'); this.push(data); }; config.onopen && setTimeout(config.onopen, 1); socket.onDisconnect().remove(); return socket; /* Socket.io ver. (Not yet) */ //var SIGNALING_SERVER = 'https://112.108.40.152:443/'; // //config.channel = config.channel || location.href.replace(/\/|:|#|%|\.|\[|\]/g, ''); //var sender = Math.round(Math.random() * 999999999) + 999999999; // //io.connect(SIGNALING_SERVER).emit('new-channel', { // channel: config.channel, // sender: sender //}); // //var socket = io.connect(SIGNALING_SERVER + config.channel); //socket.channel = config.channel; //socket.on('connect', function () { // if (config.callback) config.callback(socket); //}); // //socket.send = function (message) { // socket.emit('message', { // sender: sender, // data: message // }); //}; // //socket.on('message', config.onmessage); }, onRemoteStream: function(media) { console.log('s4'); var video = media.video; video.setAttribute('controls', true); videosContainer.insertBefore(video, videosContainer.firstChild); video.play(); }, onRoomFound: function(room) { console.log('s5'); dualrtcUI.joinRoom({ roomToken: room.broadcaster, joinUser: room.broadcaster }); }, onNewParticipant: function(numberOfParticipants) { console.log('s7'); //document.title = numberOfParticipants + ' users are viewing your screen!'; }, oniceconnectionstatechange: function(state) { console.log('s8'); if(state == 'failed') { alert('Failed to bypass Firewall rules.'); } if(state == 'connected') { alert('A user successfully received screen.'); } } }; // end of config function captureUserMedia(callback, extensionAvailable) { console.log('s9'); console.log('captureUserMedia chromeMediaSource', DetectRTC.screen.chromeMediaSource); var screen_constraints = { mandatory: { chromeMediaSource: DetectRTC.screen.chromeMediaSource, maxWidth: screen.width > 1920 ? screen.width : 1920, maxHeight: screen.height > 1080 ? screen.height : 1080 // minAspectRatio: 1.77 }, optional: [{ // non-official Google-only optional constraints googTemporalLayeredScreencast: true }, { googLeakyBucket: true }] }; // try to check if extension is installed. if(isChrome && typeof extensionAvailable == 'undefined' && DetectRTC.screen.chromeMediaSource != 'desktop') { DetectRTC.screen.isChromeExtensionAvailable(function(available) { console.log('s10'); captureUserMedia(callback, available); }); return; } if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop' && !DetectRTC.screen.sourceId) { DetectRTC.screen.getSourceId(function(error) { console.log('s11'); if(error && error == 'PermissionDeniedError') { alert('PermissionDeniedError: User denied to share content of his screen.'); } captureUserMedia(callback); }); return; } if(isChrome && !DetectRTC.screen.sourceId) { window.addEventListener('message', function (event) { console.log('s12'); if (event.data && event.data.chromeMediaSourceId) { var sourceId = event.data.chromeMediaSourceId; DetectRTC.screen.sourceId = sourceId; DetectRTC.screen.chromeMediaSource = 'desktop'; if (sourceId == 'PermissionDeniedError') { return alert('User denied to share content of his screen.'); } captureUserMedia(callback, true); } if (event.data && event.data.chromeExtensionStatus) { warn('Screen capturing extension status is:', event.data.chromeExtensionStatus); DetectRTC.screen.chromeMediaSource = 'screen'; captureUserMedia(callback, true); } }); return; } if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop') { screen_constraints.mandatory.chromeMediaSourceId = DetectRTC.screen.sourceId; } var constraints = { audio: false, video: screen_constraints }; if(!!navigator.mozGetUserMedia) { console.warn(Firefox_Screen_Capturing_Warning); constraints.video = { mozMediaSource: 'window', mediaSource: 'window', maxWidth: 1920, maxHeight: 1080, minAspectRatio: 1.77 }; } console.log( JSON.stringify( constraints , null, '\t') ); var video = document.createElement('video'); video.setAttribute('autoplay', true); video.setAttribute('controls', true); videosContainer.insertBefore(video, videosContainer.firstChild); getUserMedia({ video: video, constraints: constraints, onsuccess: function(stream) { console.log('s13'); config.attachStream = stream; callback && callback(); video.setAttribute('muted', true); }, onerror: function() { console.log('s14'); if (isChrome && location.protocol === 'http:') { alert('Please test on HTTPS.'); } else if(isChrome) { alert('Screen capturing is either denied or not supported. Please install chrome extension for screen capturing or run chrome with command-line flag: --enable-usermedia-screen-capturing'); } else if(!!navigator.mozGetUserMedia) { alert(Firefox_Screen_Capturing_Warning); } } }); } // end of captureUserMedia var dualrtcUI = dualrtc(config); var videosContainer = document.getElementById('videos-container'); var secure = (Math.random() * new Date().getTime()).toString(36).toUpperCase().replace( /\./g , '-'); var makeName = $('#makeName'); var joinName = $('#joinName'); var btnMakeRoom = $('#btnMakeRoom'); var btnJoinRoom = $('#btnJoinRoom'); var btnCopy = $('#btnCopy'); var divMake = $('#divMakeRoom'); var divJoin = $('#divJoinRoom'); var divScreen = $('#divScreen'); // about description var divDescript = $('#divDescript'); var divInstallCE01 = $('#divInstallCE01'); var divInstallCE02 = $('#divInstallCE02'); var divWikiWDDM = $('#divWikiWDDM'); btnMakeRoom.click(function () { if (makeName.val()) { makeName.attr('disabled', true); btnJoinRoom.attr('disabled', true); joinName.attr('disabled', true); btnJoinRoom.attr('disabled', true); window.open('about:black').location.href = location.href + makeName.val(); } }); btnJoinRoom.click(function () { if (joinName.val()) { joinName.attr('disabled', true); btnJoinRoom.attr('disabled', true); window.open('about:black').location.href = location.href + joinName.val(); } }); btnCopy.click(function () { makeName.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copy email command was ' + msg); } catch(err) { console.log('Oops, unable to copy'); } }); divInstallCE01.click(function () { window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/desktopcapture/mhpddeoilenchcefgimjlbbccdiepnnk'; }); divInstallCE02.click(function () { window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/dualrtcio/kdgjponegkkhkigjlknapimncipajbpi'; }); divWikiWDDM.click(function () { window.open('about:black').location.href = 'https://dualrtc-io.github.io/'; }); (function() { if (location.hash.length <= 2) { makeName.val(secure); //makeName.attr('placeholder', secure); } else { // 방 들어왔을 때 var roomName = location.hash.substring(2, 21); if (divMake.css('display') == 'block') $('#divMakeRoom').hide(); if (divJoin.css('display') == 'block') $('#divJoinRoom').hide(); if (divScreen.css('display') == 'none') $('#divScreen').show(); if (divDescript.css('display') == 'block') $('#divDescript').hide(); captureUserMedia(function() { dualrtcUI.createRoom({ roomName: (roomName || 'Anonymous') + ' shared his screen with you' }); }); } })(); var Firefox_Screen_Capturing_Warning = 'Make sure that you are using Firefox Nightly and you enabled: media.getusermedia.screensharing.enabled flag from about:config page. You also need to add your domain in "media.getusermedia.screensharing.allowed_domains" flag.';
(function(){ var active = scrolling = false; var MagicScroll = function(selector, options) { if(!(this instanceof MagicScroll)) { return new MagicScroll(selector, options); } if(!selector) { console.log('WTF Bro! Give me selector!'); } else { this.elements = document.querySelectorAll(selector); } return this; }; MagicScroll.prototype.create = function() { for(var i = 0; i < this.elements.length; i++) { var element = this.elements[i]; if(!element.magicScroll) { element.magicScroll = true; element.addEventListener('mousedown', this._start); element.addEventListener('mouseup', this._stop); element.addEventListener('mouseleave', this._stop); element.addEventListener('mousemove', this._move); } } return this; }; MagicScroll.prototype._start = function(e) { active = true; }; MagicScroll.prototype._stop = function(e) { active = false; e.currentTarget.classList.remove('scrolling'); scrolling = false; }; MagicScroll.prototype._move = function(event) { if(active) { event && event.preventDefault(); var $current= event.currentTarget, mY = (event.movementY) ? event.movementY : event.webkitMovementY; if(!scrolling) { $current.classList.add('scrolling'); scrolling = true; } if(mY > 0) { $current.scrollTop -= Math.abs(mY * 2); } else if(mY < 0) { $current.scrollTop += Math.abs(mY * 2); } } }; MagicScroll.prototype.destroy = function() { for(var i = 0; i < this.elements.length; i++) { var element = this.elements[i]; if(element.magicScroll) { element.removeEventListener('mousedown', this._start); element.removeEventListener('mouseup', this._stop); element.removeEventListener('mouseleave', this._stop); element.removeEventListener('mousemove', this._move); delete element.magicScroll; } } }; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = MagicScroll; } exports.MagicScroll = MagicScroll; } else { this.MagicScroll = MagicScroll; } // AMD Registrity if (typeof define === 'function' && define.amd) { define('MagicScroll', [], function() { return MagicScroll; }); } }).call(this);
const curry = require('../../curry'); const compose = require('..'); describe('Compose', () => { test('should compose name', () => { const prefixDr = curry((prefix, name) => `${prefix} ${name}`)('Dr'); const suffixBatchelor = curry((suffix, name) => `${name} ${suffix}`)('BSc'); const suffixMasters = curry((suffix, name) => `${name} ${suffix}`)('MSc'); const suffixDoctor = curry((suffix, name) => `${name} ${suffix}`)('PhD'); const composeName = compose([prefixDr, suffixDoctor, suffixMasters, suffixBatchelor]); expect(composeName('Bob Johnson')).toEqual('Dr Bob Johnson BSc MSc PhD'); }); });
'use strict'; var Bluebird = require('bluebird'); var _ = require('lodash'); var debug = require('debug')('oradbpm:ctrl:get'); var Queue = require('queue-fifo'); var promiseWhile = require('promise-while')(Bluebird); var error = require('./../../common/error.js'); var PackageDependencyTreeModel = require('./../../model/package-dependency-tree-node.model.js'); var PackageVersionDefinition = require('./../../model/package-version-definition.model'); var PackageDependency = require('./../../model/package-dependency.model'); var DeploymentPlan = require('./../../model/deployment-plan.model'); var PackageVersionDeployment = require('./../../model/package-version-deployment.model'); var PackageDependencyTreeRootFactory = require('./../../factory/package-dependency-tree-root.factory'); // TODO: Move to PackageDependencyTreeNode /** * * @param deploymentPlan * @param queue * @param packageRepositoryService * @return Array of {Promise} which resolves with processDependencyTreeNode */ var processDependencyTreeNode = function (deploymentPlan, queue, packageRepositoryService) { // breadth first algorithm var nodeToProcess = queue.dequeue(); // process packageDependencyTreeNode // 1. populate dependencies return Bluebird.all(nodeToProcess.createChildDependencyTreeNodes(packageRepositoryService)) .then(function (dependencyTreeNodes) { // add children to node nodeToProcess.children = dependencyTreeNodes; // 2. TODO: add packageVersionDeploymentProposal to DeploymentPlan.getSchema(packageName) //debug(nodeToProcess.packageVersionDefinition.name, nodeToProcess.packageVersionDefinition.language); //debug(nodeToProcess.packageVersionDefinition); if (nodeToProcess.packageVersionDefinition.language === 'sqlplus') { // do not add to deploymentPlan as it is used only on client side and stored within package, that required it as its dependency //deploymentPlan // .getSchema(nodeToProcess.packageVersionDefinition.name, nodeToProcess.packageVersionDefinition.version) // .addProposal( // new PackageVersionDeployment(nodeToProcess.packageVersionDefinition, nodeToProcess.dependency) // ); } else { var nearestGlobalNode = nodeToProcess.getNearestGlobal(); deploymentPlan // run sql and plsql packages in nearest global package // add deployment to nearest global schema .getSchema(nearestGlobalNode.packageVersionDefinition.name, nearestGlobalNode.packageVersionDefinition.version) .addProposal( new PackageVersionDeployment(nodeToProcess) ); } // breadth first algorithm // 3. enqueue all children _.forEach(nodeToProcess.children, function (childNode) { queue.enqueue(childNode); }); return Bluebird.resolve(); }) .catch(function (err) { return Bluebird.reject(err); }); }; /** * * @param deploymentPlan * @param packageDependencyTreeRoot * @param packageRepositoryService * @return {Promise} */ var populateDependencies = function (deploymentPlan, packageDependencyTreeRoot, packageRepositoryService) { var nodesToProcessQueue = new Queue(); // breadth first resolve dependencies - start with root nodesToProcessQueue.enqueue(packageDependencyTreeRoot); return promiseWhile( function () { return !nodesToProcessQueue.isEmpty(); }, function () { return new Bluebird(function (resolve, reject) { return processDependencyTreeNode(deploymentPlan, nodesToProcessQueue, packageRepositoryService) .then(resolve) .catch(function (err) { return reject(err); }); }); } ) .catch(function (err) { return Bluebird.reject(err); }); }; /** * * @return {DeploymentPlan} */ var createDeploymentPlan = function () { // TODO: populate DeploymentPlan from existing (stored as oradb_modules + oradb_package.json within each package folder) return new DeploymentPlan(); }; /** * @param pkgReferences * @param options * @returns {Promise} */ var get = function (pkgReferences, options) { debug('pkgReferences %s options %s', pkgReferences, JSON.stringify(options, null, 2)); var oraDBPMClient = this; var packageDependencyTreeRootFactory = new PackageDependencyTreeRootFactory(oraDBPMClient.packageFileServiceFactory); // populate stored DeploymentPlan or create new var deploymentPlan = createDeploymentPlan(); var packageDependencyTreeRoot = null; // create PackageReferences array from required pkgReferences var newDependencies = _.reduce(pkgReferences, function (acc, pkgReference) { acc.push(new PackageDependency(pkgReference, options.local)); return acc; }, []); // create PackageDependencyTreeRoot // - read mainPackageVersionDefinitionFile = oradb_package.json // - or create anonymous root return packageDependencyTreeRootFactory.createPackageDependencyTreeRoot(options.packageFilePath) // merge required dependencies (pkgReferences) with dependencies already defined on root (loaded from file) .then(function (treeRoot) { treeRoot.mergeDependencies(newDependencies, {}); packageDependencyTreeRoot = treeRoot; return treeRoot; }) // populate tree of PackageDependencyTreeNodes - start with root .then(function (treeRoot) { return populateDependencies(deploymentPlan, treeRoot, oraDBPMClient.packageRepositoryService); }) .then(function () { //debug(JSON.stringify(packageDependencyTreeRoot.removeCycles())); return deploymentPlan.resolveConflicts(); }) .then(function () { // TODO: download to oradb_modules folder //console.log(JSON.stringify(deploymentPlan.logPlan())); deploymentPlan.logPlan(); return Bluebird.resolve(); }) .then(function () { // TODO: write to file if --save/--save-dev return Bluebird.resolve(); }) .catch(new error.errorHandler(debug)); }; module.exports = get;
version https://git-lfs.github.com/spec/v1 oid sha256:e2a38d0984b9d8a85bbc1b3e0131e2fee2b6a6dc5f31aeb248b213f41f36038d size 575053
'use strict'; const chai = require('chai'), expect = chai.expect, Support = require(__dirname + '/../../support'), DataTypes = require(__dirname + '/../../../../lib/data-types'), dialect = Support.getTestDialect(), _ = require('lodash'), moment = require('moment'), QueryGenerator = require('../../../../lib/dialects/sqlite/query-generator'); if (dialect === 'sqlite') { describe('[SQLITE Specific] QueryGenerator', () => { beforeEach(function() { this.User = this.sequelize.define('User', { username: DataTypes.STRING }); return this.User.sync({ force: true }); }); const suites = { arithmeticQuery: [ { title:'Should use the plus operator', arguments: ['+', 'myTable', { foo: 'bar' }, {}], expectation: 'UPDATE `myTable` SET `foo`=`foo`+ \'bar\' ' }, { title:'Should use the plus operator with where clause', arguments: ['+', 'myTable', { foo: 'bar' }, { bar: 'biz'}], expectation: 'UPDATE `myTable` SET `foo`=`foo`+ \'bar\' WHERE `bar` = \'biz\'' }, { title:'Should use the minus operator', arguments: ['-', 'myTable', { foo: 'bar' }], expectation: 'UPDATE `myTable` SET `foo`=`foo`- \'bar\' ' }, { title:'Should use the minus operator with negative value', arguments: ['-', 'myTable', { foo: -1 }], expectation: 'UPDATE `myTable` SET `foo`=`foo`- -1 ' }, { title:'Should use the minus operator with where clause', arguments: ['-', 'myTable', { foo: 'bar' }, { bar: 'biz'}], expectation: 'UPDATE `myTable` SET `foo`=`foo`- \'bar\' WHERE `bar` = \'biz\'' } ], attributesToSQL: [ { arguments: [{id: 'INTEGER'}], expectation: {id: 'INTEGER'} }, { arguments: [{id: 'INTEGER', foo: 'VARCHAR(255)'}], expectation: {id: 'INTEGER', foo: 'VARCHAR(255)'} }, { arguments: [{id: {type: 'INTEGER'}}], expectation: {id: 'INTEGER'} }, { arguments: [{id: {type: 'INTEGER', allowNull: false}}], expectation: {id: 'INTEGER NOT NULL'} }, { arguments: [{id: {type: 'INTEGER', allowNull: true}}], expectation: {id: 'INTEGER'} }, { arguments: [{id: {type: 'INTEGER', primaryKey: true, autoIncrement: true}}], expectation: {id: 'INTEGER PRIMARY KEY AUTOINCREMENT'} }, { arguments: [{id: {type: 'INTEGER', defaultValue: 0}}], expectation: {id: 'INTEGER DEFAULT 0'} }, { arguments: [{id: {type: 'INTEGER', defaultValue: undefined}}], expectation: {id: 'INTEGER'} }, { arguments: [{id: {type: 'INTEGER', unique: true}}], expectation: {id: 'INTEGER UNIQUE'} }, // New references style { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`id`)'} }, { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar', key: 'pk' }}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`pk`)'} }, { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }, onDelete: 'CASCADE'}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`id`) ON DELETE CASCADE'} }, { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }, onUpdate: 'RESTRICT'}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`id`) ON UPDATE RESTRICT'} }, { arguments: [{id: {type: 'INTEGER', allowNull: false, defaultValue: 1, references: { model: 'Bar' }, onDelete: 'CASCADE', onUpdate: 'RESTRICT'}}], expectation: {id: 'INTEGER NOT NULL DEFAULT 1 REFERENCES `Bar` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT'} } ], createTableQuery: [ { arguments: ['myTable', {data: 'BLOB'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`data` BLOB);' }, { arguments: ['myTable', {data: 'LONGBLOB'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`data` LONGBLOB);' }, { arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255));' }, { arguments: ['myTable', {title: 'VARCHAR BINARY(255)', number: 'INTEGER(5) UNSIGNED PRIMARY KEY '}], // length and unsigned are not allowed on primary key expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR BINARY(255), `number` INTEGER PRIMARY KEY);' }, { arguments: ['myTable', {title: 'ENUM("A", "B", "C")', name: 'VARCHAR(255)'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` ENUM(\"A\", \"B\", \"C\"), `name` VARCHAR(255));' }, { arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)', id: 'INTEGER PRIMARY KEY'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255), `id` INTEGER PRIMARY KEY);' }, { arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)', otherId: 'INTEGER REFERENCES `otherTable` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255), `otherId` INTEGER REFERENCES `otherTable` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION);' }, { arguments: ['myTable', {id: 'INTEGER PRIMARY KEY AUTOINCREMENT', name: 'VARCHAR(255)'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255));' }, { arguments: ['myTable', {id: 'INTEGER PRIMARY KEY AUTOINCREMENT', name: 'VARCHAR(255)', surname: 'VARCHAR(255)'}, {uniqueKeys: {uniqueConstraint: {fields: ['name', 'surname']}}}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `surname` VARCHAR(255), UNIQUE (`name`, `surname`));' } ], selectQuery: [ { arguments: ['myTable'], expectation: 'SELECT * FROM `myTable`;', context: QueryGenerator }, { arguments: ['myTable', {attributes: ['id', 'name']}], expectation: 'SELECT `id`, `name` FROM `myTable`;', context: QueryGenerator }, { arguments: ['myTable', {where: {id: 2}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`id` = 2;', context: QueryGenerator }, { arguments: ['myTable', {where: {name: 'foo'}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`name` = 'foo';", context: QueryGenerator }, { arguments: ['myTable', {where: {name: "foo';DROP TABLE myTable;"}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`name` = 'foo\'\';DROP TABLE myTable;';", context: QueryGenerator }, { arguments: ['myTable', {where: 2}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`id` = 2;', context: QueryGenerator }, { arguments: ['foo', { attributes: [['count(*)', 'count']] }], expectation: 'SELECT count(*) AS `count` FROM `foo`;', context: QueryGenerator }, { arguments: ['myTable', {order: ['id']}], expectation: 'SELECT * FROM `myTable` ORDER BY `id`;', context: QueryGenerator }, { arguments: ['myTable', {order: ['id', 'DESC']}], expectation: 'SELECT * FROM `myTable` ORDER BY `id`, `DESC`;', context: QueryGenerator }, { arguments: ['myTable', {order: ['myTable.id']}], expectation: 'SELECT * FROM `myTable` ORDER BY `myTable`.`id`;', context: QueryGenerator }, { arguments: ['myTable', {order: [['myTable.id', 'DESC']]}], expectation: 'SELECT * FROM `myTable` ORDER BY `myTable`.`id` DESC;', context: QueryGenerator }, { arguments: ['myTable', {order: [['id', 'DESC']]}, function(sequelize) {return sequelize.define('myTable', {});}], expectation: 'SELECT * FROM `myTable` AS `myTable` ORDER BY `myTable`.`id` DESC;', context: QueryGenerator, needsSequelize: true }, { arguments: ['myTable', {order: [['id', 'DESC'], ['name']]}, function(sequelize) {return sequelize.define('myTable', {});}], expectation: 'SELECT * FROM `myTable` AS `myTable` ORDER BY `myTable`.`id` DESC, `myTable`.`name`;', context: QueryGenerator, needsSequelize: true }, { title: 'sequelize.where with .fn as attribute and default comparator', arguments: ['myTable', function(sequelize) { return { where: sequelize.and( sequelize.where(sequelize.fn('LOWER', sequelize.col('user.name')), 'jan'), { type: 1 } ) }; }], expectation: "SELECT * FROM `myTable` WHERE (LOWER(`user`.`name`) = 'jan' AND `myTable`.`type` = 1);", context: QueryGenerator, needsSequelize: true }, { title: 'sequelize.where with .fn as attribute and LIKE comparator', arguments: ['myTable', function(sequelize) { return { where: sequelize.and( sequelize.where(sequelize.fn('LOWER', sequelize.col('user.name')), 'LIKE', '%t%'), { type: 1 } ) }; }], expectation: "SELECT * FROM `myTable` WHERE (LOWER(`user`.`name`) LIKE '%t%' AND `myTable`.`type` = 1);", context: QueryGenerator, needsSequelize: true }, { title: 'functions can take functions as arguments', arguments: ['myTable', function(sequelize) { return { order: [[sequelize.fn('f1', sequelize.fn('f2', sequelize.col('id'))), 'DESC']] }; }], expectation: 'SELECT * FROM `myTable` ORDER BY f1(f2(`id`)) DESC;', context: QueryGenerator, needsSequelize: true }, { title: 'functions can take all types as arguments', arguments: ['myTable', function(sequelize) { return { order: [ [sequelize.fn('f1', sequelize.col('myTable.id')), 'DESC'], [sequelize.fn('f2', 12, 'lalala', new Date(Date.UTC(2011, 2, 27, 10, 1, 55))), 'ASC'] ] }; }], expectation: "SELECT * FROM `myTable` ORDER BY f1(`myTable`.`id`) DESC, f2(12, 'lalala', '2011-03-27 10:01:55.000 +00:00') ASC;", context: QueryGenerator, needsSequelize: true }, { title: 'single string argument is not quoted', arguments: ['myTable', {group: 'name'}], expectation: 'SELECT * FROM `myTable` GROUP BY name;', context: QueryGenerator }, { arguments: ['myTable', {group: ['name']}], expectation: 'SELECT * FROM `myTable` GROUP BY `name`;', context: QueryGenerator }, { title: 'functions work for group by', arguments: ['myTable', function(sequelize) { return { group: [sequelize.fn('YEAR', sequelize.col('createdAt'))] }; }], expectation: 'SELECT * FROM `myTable` GROUP BY YEAR(`createdAt`);', context: QueryGenerator, needsSequelize: true }, { title: 'It is possible to mix sequelize.fn and string arguments to group by', arguments: ['myTable', function(sequelize) { return { group: [sequelize.fn('YEAR', sequelize.col('createdAt')), 'title'] }; }], expectation: 'SELECT * FROM `myTable` GROUP BY YEAR(`createdAt`), `title`;', context: QueryGenerator, needsSequelize: true }, { arguments: ['myTable', {group: ['name', 'title']}], expectation: 'SELECT * FROM `myTable` GROUP BY `name`, `title`;', context: QueryGenerator }, { arguments: ['myTable', {group: 'name', order: [['id', 'DESC']]}], expectation: 'SELECT * FROM `myTable` GROUP BY name ORDER BY `id` DESC;', context: QueryGenerator }, { title: 'HAVING clause works with where-like hash', arguments: ['myTable', function(sequelize) { return { attributes: ['*', [sequelize.fn('YEAR', sequelize.col('createdAt')), 'creationYear']], group: ['creationYear', 'title'], having: { creationYear: { gt: 2002 } } }; }], expectation: 'SELECT *, YEAR(`createdAt`) AS `creationYear` FROM `myTable` GROUP BY `creationYear`, `title` HAVING `creationYear` > 2002;', context: QueryGenerator, needsSequelize: true }, { arguments: ['myTable', {limit: 10}], expectation: 'SELECT * FROM `myTable` LIMIT 10;', context: QueryGenerator }, { arguments: ['myTable', {limit: 10, offset: 2}], expectation: 'SELECT * FROM `myTable` LIMIT 2, 10;', context: QueryGenerator }, { title: 'uses default limit if only offset is specified', arguments: ['myTable', {offset: 2}], expectation: 'SELECT * FROM `myTable` LIMIT 2, 10000000000000;', context: QueryGenerator }, { title: 'multiple where arguments', arguments: ['myTable', {where: {boat: 'canoe', weather: 'cold'}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`boat` = 'canoe' AND `myTable`.`weather` = 'cold';", context: QueryGenerator }, { title: 'no where arguments (object)', arguments: ['myTable', {where: {}}], expectation: 'SELECT * FROM `myTable`;', context: QueryGenerator }, { title: 'no where arguments (string)', arguments: ['myTable', {where: ['']}], expectation: 'SELECT * FROM `myTable` WHERE 1=1;', context: QueryGenerator }, { title: 'no where arguments (null)', arguments: ['myTable', {where: null}], expectation: 'SELECT * FROM `myTable`;', context: QueryGenerator }, { title: 'buffer as where argument', arguments: ['myTable', {where: { field: new Buffer('Sequelize')}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`field` = X'53657175656c697a65';", context: QueryGenerator }, { title: 'use != if ne !== null', arguments: ['myTable', {where: {field: {ne: 0}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` != 0;', context: QueryGenerator }, { title: 'use IS NOT if ne === null', arguments: ['myTable', {where: {field: {ne: null}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` IS NOT NULL;', context: QueryGenerator }, { title: 'use IS NOT if not === BOOLEAN', arguments: ['myTable', {where: {field: {not: true}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` IS NOT 1;', context: QueryGenerator }, { title: 'use != if not !== BOOLEAN', arguments: ['myTable', {where: {field: {not: 3}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` != 3;', context: QueryGenerator } ], insertQuery: [ { arguments: ['myTable', { name: 'foo' }], expectation: "INSERT INTO `myTable` (`name`) VALUES ('foo');" }, { arguments: ['myTable', { name: "'bar'" }], expectation: "INSERT INTO `myTable` (`name`) VALUES ('''bar''');" }, { arguments: ['myTable', {data: new Buffer('Sequelize') }], expectation: "INSERT INTO `myTable` (`data`) VALUES (X'53657175656c697a65');" }, { arguments: ['myTable', { name: 'bar', value: null }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL);" }, { arguments: ['myTable', { name: 'bar', value: undefined }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL);" }, { arguments: ['myTable', {name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}], expectation: "INSERT INTO `myTable` (`name`,`birthday`) VALUES ('foo','2011-03-27 10:01:55.000 +00:00');" }, { arguments: ['myTable', { name: 'foo', value: true }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',1);" }, { arguments: ['myTable', { name: 'foo', value: false }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',0);" }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL);" }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL);", context: {options: {omitNull: false}} }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}], expectation: "INSERT INTO `myTable` (`name`,`foo`) VALUES ('foo',1);", context: {options: {omitNull: true}} }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: undefined}], expectation: "INSERT INTO `myTable` (`name`,`foo`) VALUES ('foo',1);", context: {options: {omitNull: true}} }, { arguments: ['myTable', function(sequelize) { return { foo: sequelize.fn('NOW') }; }], expectation: 'INSERT INTO `myTable` (`foo`) VALUES (NOW());', needsSequelize: true } ], bulkInsertQuery: [ { arguments: ['myTable', [{name: 'foo'}, {name: 'bar'}]], expectation: "INSERT INTO `myTable` (`name`) VALUES ('foo'),('bar');" }, { arguments: ['myTable', [{name: "'bar'"}, {name: 'foo'}]], expectation: "INSERT INTO `myTable` (`name`) VALUES ('''bar'''),('foo');" }, { arguments: ['myTable', [{name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}, {name: 'bar', birthday: moment('2012-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}]], expectation: "INSERT INTO `myTable` (`name`,`birthday`) VALUES ('foo','2011-03-27 10:01:55.000 +00:00'),('bar','2012-03-27 10:01:55.000 +00:00');" }, { arguments: ['myTable', [{name: 'bar', value: null}, {name: 'foo', value: 1}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL),('foo',1);" }, { arguments: ['myTable', [{name: 'bar', value: undefined}, {name: 'bar', value: 2}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL),('bar',2);" }, { arguments: ['myTable', [{name: 'foo', value: true}, {name: 'bar', value: false}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',1),('bar',0);" }, { arguments: ['myTable', [{name: 'foo', value: false}, {name: 'bar', value: false}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',0),('bar',0);" }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);" }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);", context: {options: {omitNull: false}} }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);", context: {options: {omitNull: true}} // Note: We don't honour this because it makes little sense when some rows may have nulls and others not }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);", context: {options: {omitNull: true}} // Note: As above }, { arguments: ['myTable', [{name: 'foo'}, {name: 'bar'}], {ignoreDuplicates: true}], expectation: "INSERT OR IGNORE INTO `myTable` (`name`) VALUES ('foo'),('bar');" } ], updateQuery: [ { arguments: ['myTable', {name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}, {id: 2}], expectation: "UPDATE `myTable` SET `name`='foo',`birthday`='2011-03-27 10:01:55.000 +00:00' WHERE `id` = 2" }, { arguments: ['myTable', {name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}, {id: 2}], expectation: "UPDATE `myTable` SET `name`='foo',`birthday`='2011-03-27 10:01:55.000 +00:00' WHERE `id` = 2" }, { arguments: ['myTable', { name: 'foo' }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='foo' WHERE `id` = 2" }, { arguments: ['myTable', { name: "'bar'" }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='''bar''' WHERE `id` = 2" }, { arguments: ['myTable', { name: 'bar', value: null }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='bar',`value`=NULL WHERE `id` = 2" }, { arguments: ['myTable', { name: 'bar', value: undefined }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='bar',`value`=NULL WHERE `id` = 2" }, { arguments: ['myTable', { flag: true }, { id: 2 }], expectation: 'UPDATE `myTable` SET `flag`=1 WHERE `id` = 2' }, { arguments: ['myTable', { flag: false }, { id: 2 }], expectation: 'UPDATE `myTable` SET `flag`=0 WHERE `id` = 2' }, { arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=2,`nullValue`=NULL WHERE `name` = 'foo'" }, { arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=2,`nullValue`=NULL WHERE `name` = 'foo'", context: {options: {omitNull: false}} }, { arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=2 WHERE `name` = 'foo'", context: {options: {omitNull: true}} }, { arguments: ['myTable', function(sequelize) { return { bar: sequelize.fn('NOW') }; }, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=NOW() WHERE `name` = 'foo'", needsSequelize: true }, { arguments: ['myTable', function(sequelize) { return { bar: sequelize.col('foo') }; }, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=`foo` WHERE `name` = 'foo'", needsSequelize: true } ], renameColumnQuery: [ { title: 'Properly quotes column names', arguments: ['myTable', 'foo', 'commit', {commit: 'VARCHAR(255)', bar: 'VARCHAR(255)'}], expectation: 'CREATE TEMPORARY TABLE IF NOT EXISTS `myTable_backup` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable_backup` SELECT `foo` AS `commit`, `bar` FROM `myTable`;' + 'DROP TABLE `myTable`;' + 'CREATE TABLE IF NOT EXISTS `myTable` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable` SELECT `commit`, `bar` FROM `myTable_backup`;' + 'DROP TABLE `myTable_backup`;' } ], removeColumnQuery: [ { title: 'Properly quotes column names', arguments: ['myTable', {commit: 'VARCHAR(255)', bar: 'VARCHAR(255)'}], expectation: 'CREATE TEMPORARY TABLE IF NOT EXISTS `myTable_backup` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable_backup` SELECT `commit`, `bar` FROM `myTable`;' + 'DROP TABLE `myTable`;' + 'CREATE TABLE IF NOT EXISTS `myTable` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable` SELECT `commit`, `bar` FROM `myTable_backup`;' + 'DROP TABLE `myTable_backup`;' } ] }; _.each(suites, (tests, suiteTitle) => { describe(suiteTitle, () => { tests.forEach(test => { const title = test.title || 'SQLite correctly returns ' + test.expectation + ' for ' + JSON.stringify(test.arguments); it(title, function() { // Options would normally be set by the query interface that instantiates the query-generator, but here we specify it explicitly const context = test.context || {options: {}}; if (test.needsSequelize) { if (_.isFunction(test.arguments[1])) test.arguments[1] = test.arguments[1](this.sequelize); if (_.isFunction(test.arguments[2])) test.arguments[2] = test.arguments[2](this.sequelize); } QueryGenerator.options = _.assign(context.options, { timezone: '+00:00' }); QueryGenerator._dialect = this.sequelize.dialect; QueryGenerator.sequelize = this.sequelize; const conditions = QueryGenerator[suiteTitle].apply(QueryGenerator, test.arguments); expect(conditions).to.deep.equal(test.expectation); }); }); }); }); }); }
Package.describe("Telescope BKX theme"); Package.on_use(function (api) { // api.use(['telescope-lib'], ['client', 'server']); // api.use([ // 'jquery', // 'underscore', // 'templating' // ], 'client'); api.add_files([ 'lib/client/stylesheets/screen.css', ], ['client']); });
/*jshint node:true, indent:2, curly:false, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, regexp:true, undef:true, strict:true, trailing:true, white:true */ /*global X:true, XT:true */ (function () { "use strict"; // All of the "big 4" routes are in here: commit, dispatch, fetch, and retrieve // They all share a lot of similar code so I've broken out the functions createGlobalOptions // and queryInstanceDatabase to reuse code. // All of the functions have "engine" functions that do all the work, and then // "adapter" functions that call the engines and adapt to the express convention. These // adapter functions are also nearly identical so I've reused code there as well. // Sorry for the indirection. /** The options parameter in the XT.dataSource calls to the global database are all the same. Notably, we have to massage the client-expected callback to fit into the backboney callback system of XT.dataSource. */ var createGlobalOptions = function (payload, globalUsername, callback) { var options = JSON.parse(JSON.stringify(payload)); // clone options.username = globalUsername; options.success = function (resp) { callback({data: resp}); }; options.error = function (model, err) { callback({isError: true, message: err}); }; return options; }; /** To query the instance database we pass in a query string to X.database in a way that's very similar for all four operations. We have to massage the client-expected callback to fit with the native callback of X.database. */ var queryInstanceDatabase = function (queryString, functionName, payload, session, callback) { var query, adaptorCallback = function (err, res) { if (err) { callback({isError: true, error: err, message: err.message}); } else if (res && res.rows && res.rows.length > 0) { // the data comes back in an awkward res.rows[0].dispatch form, // and we want to normalize that here so that the data is in response.data callback({data: JSON.parse(res.rows[0][functionName])}); } else { callback({isError: true, message: "No results"}); } }; payload.username = session.passport.user.username; query = queryString.f(JSON.stringify(payload)); X.database.query(session.passport.user.organization, query, adaptorCallback); }; /** Does all the work of commit. Can be called by websockets, or the express route (below), or REST, etc. */ var commitEngine = function (payload, session, callback) { var organization, query, binaryField = payload.binaryField, buffer, binaryData, options; // We need to convert js binary into pg hex (see the file route for // the opposite conversion). See issue #18661 if (binaryField) { binaryData = payload.dataHash[binaryField]; buffer = new Buffer(binaryData, "binary"); // XXX uhoh: binary is deprecated but necessary here binaryData = '\\x' + buffer.toString("hex"); payload.dataHash[binaryField] = binaryData; } if (payload && payload.databaseType === 'global') { // Run this query against the global database. options = createGlobalOptions(payload, session.passport.user.id, callback); if (!payload.dataHash) { callback({message: "Invalid Commit"}); return; } // Passing payload through, but trick dataSource into thinking it's a Model: payload.changeSet = function () { return payload.dataHash; }; options.force = true; XT.dataSource.commitRecord(payload, options); } else { // Run this query against an instance database. queryInstanceDatabase("select xt.commit_record($$%@$$)", "commit_record", payload, session, callback); } }; exports.commitEngine = commitEngine; /** Does all the work of dispatch. Can be called by websockets, or the express route (below), or REST, etc. */ var dispatchEngine = function (payload, session, callback) { var organization, query, options; if (payload && payload.databaseType === 'global') { // Run this query against the global database. options = createGlobalOptions(payload, session.passport.user.id, callback); XT.dataSource.dispatch(payload.className, payload.functionName, payload.parameters, options); } else { // Run this query against an instance database. queryInstanceDatabase("select xt.dispatch('%@')", "dispatch", payload, session, callback); } }; exports.dispatchEngine = dispatchEngine; /** Does all the work of fetch. Can be called by websockets, or the express route (below), or REST, etc. */ var fetchEngine = function (payload, session, callback) { var organization, query, options; if (payload && payload.databaseType === 'global') { // run this query against the global database options = createGlobalOptions(payload, session.passport.user.id, callback); XT.dataSource.fetch(options); } else { // run this query against an instance database queryInstanceDatabase("select xt.fetch('%@')", "fetch", payload, session, callback); } }; exports.fetchEngine = fetchEngine; /** Does all the work of retrieve. Can be called by websockets, or the express route (below), or REST, etc. */ var retrieveEngine = function (payload, session, callback) { var organization, query, options; // TODO: authenticate if (payload && payload.databaseType === 'global') { // run this query against the global database options = createGlobalOptions(payload, session.passport.user.id, callback); XT.dataSource.retrieveRecord(payload.recordType, payload.id, options); } else { // run this query against an instance database queryInstanceDatabase("select xt.retrieve_record('%@')", "retrieve_record", payload, session, callback); } }; exports.retrieveEngine = retrieveEngine; /** The adaptation of express routes to engine functions is the same for all four operations, so we centralize the code here: */ var routeAdapter = function (req, res, engineFunction) { var callback = function (err, resp) { if (err) { res.send(500, {data: err}); } else { res.send({data: resp}); } }; engineFunction(req.query, req.session, callback); }; /** Accesses the commitEngine (above) for a request a la Express */ exports.commit = function (req, res) { routeAdapter(req, res, commitEngine); }; /** Accesses the dispatchEngine (above) for a request a la Express */ exports.dispatch = function (req, res) { routeAdapter(req, res, dispatchEngine); }; /** Accesses the fetchEngine (above) for a request a la Express */ exports.fetch = function (req, res) { routeAdapter(req, res, fetchEngine); }; /** Accesses the retrieveEngine (above) for a request a la Express */ exports.retrieve = function (req, res) { routeAdapter(req, res, retrieveEngine); }; }());
console.log('Hello World!');
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M6 22h12l-6-6-6 6zM23 3H1v16h6v-2H3V5h18v12h-4v2h6V3z" /> , 'AirplaySharp');
function addClass(elem, className) { elem.attr('class', function(index, classNames) { if (typeof classNames == 'undefined') { classNames = ''; } var newcls = classNames + ' ' + className; console.log('ClassNamesA = ' + newcls); return newcls;}); } function removeClass(elem, className) { elem.attr('class', function(index, classNames) { var newcls = classNames.replace(className, ''); console.log('ClassNamesR = ' + newcls); return newcls;}); } function findNode(name) { var node = $("#"+name); console.log('Finding node ' + name); console.log(node); return node } function findEdge(fromName, toName) { console.log('Finding edge ' + fromName + ' to ' + toName); var edge = $("#"+fromName+"_to_"+toName); console.log(edge); return edge; } function enterNode(nodeName) { console.log('entering node ' + nodeName); addClass(findNode(nodeName).find('ellipse'), 'active'); addClass(findNode(nodeName).find('ellipse'), 'current'); }; function exitNode(nodeName) { console.log('exiting node ' + nodeName); removeClass(findNode(nodeName).find('ellipse'), 'current'); removeClass(findNode(nodeName).find('ellipse'), 'active'); }; function callChild(nodeName, childNodeName) { var edge = findEdge(nodeName, childNodeName); addClass(edge.find('path'), 'visited'); var node = findNode(nodeName); removeClass(node.find('ellipse'), 'current'); enterNode(childNodeName); }; function reteAdd(s, p, o, g) { $("#rete-operation-name").html('Add'); $("#rete-operation-graph").html(g); $("#rete-operation-subject").html(s); $("#rete-operation-predicate").html(p); $("#rete-operation-object").html(o); } function reteRemove(s, p, o, g) { $("#rete-operation-name").html('Remove'); $("#rete-operation-graph").html(g); $("#rete-operation-subject").html(s); $("#rete-operation-predicate").html(p); $("#rete-operation-object").html(o); }
// @flow class Context { user: Object; req: express$Request; res: express$Response; depth: number; constructor(req: express$Request, res: express$Response, depth: number = 0) { this.req = req; this.res = res; this.depth = depth; // $FlowIgnore this.user = res.locals.user; } stepInto() { return new Context(this.req, this.res, this.depth + 1); } isInternal() { return this.depth > 0; } } export default Context;
import PerfectNumbers from './perfect-numbers'; describe('Exercise - Perfect Numbers', () => { const perfectNumbers = new PerfectNumbers(); describe('Perfect Numbers', () => { it('Smallest perfect number is classified correctly', () => { expect(perfectNumbers.classify(6)).toEqual('perfect'); }); it('Medium perfect number is classified correctly', () => { expect(perfectNumbers.classify(28)).toEqual('perfect'); }); it('Large perfect number is classified correctly', () => { expect(perfectNumbers.classify(33550336)).toEqual('perfect'); }); }); describe('Abundant Numbers', () => { it('Smallest abundant number is classified correctly', () => { expect(perfectNumbers.classify(12)).toEqual('abundant'); }); it('Medium abundant number is classified correctly', () => { expect(perfectNumbers.classify(30)).toEqual('abundant'); }); it('Large abundant number is classified correctly', () => { expect(perfectNumbers.classify(33550335)).toEqual('abundant'); }); }); describe('Deficient Numbers', () => { it('Smallest prime deficient number is classified correctly', () => { expect(perfectNumbers.classify(2)).toEqual('deficient'); }); it('Smallest non-prime deficient number is classified correctly', () => { expect(perfectNumbers.classify(4)).toEqual('deficient'); }); it('Medium deficient number is classified correctly', () => { expect(perfectNumbers.classify(32)).toEqual('deficient'); }); it('Large deficient number is classified correctly', () => { expect(perfectNumbers.classify(33550337)).toEqual('deficient'); }); it('Edge case (no factors other than itself) is classified correctly', () => { expect(perfectNumbers.classify(1)).toEqual('deficient'); }); }); describe('Invalid Inputs', () => { it('Zero is rejected (not a natural number)', () => { expect(() => perfectNumbers.classify(0)) .toThrow('Classification is only possible for natural numbers.'); }); it('Negative integer is rejected (not a natural number)', () => { expect(() => perfectNumbers.classify(-1)) .toThrow('Classification is only possible for natural numbers.'); }); }); });
'use strict'; module.exports = { plugins: ['jsdoc'], rules: { 'jsdoc/check-access': 'error', 'jsdoc/check-alignment': 'error', 'jsdoc/check-examples': 'error', 'jsdoc/check-indentation': 'error', 'jsdoc/check-param-names': 'error', 'jsdoc/check-property-names': 'error', 'jsdoc/check-syntax': 'error', 'jsdoc/check-tag-names': 'error', 'jsdoc/check-types': 'error', 'jsdoc/check-values': 'error', 'jsdoc/empty-tags': 'error', 'jsdoc/implements-on-classes': 'error', 'jsdoc/match-description': 'error', 'jsdoc/newline-after-description': 'error', 'jsdoc/no-bad-blocks': 'error', 'jsdoc/no-defaults': 'error', 'jsdoc/no-types': 'off', 'jsdoc/no-undefined-types': 'error', 'jsdoc/require-description': 'off', 'jsdoc/require-description-complete-sentence': 'error', 'jsdoc/require-example': 'off', 'jsdoc/require-file-overview': 'off', 'jsdoc/require-hyphen-before-param-description': 'error', 'jsdoc/require-jsdoc': 'off', 'jsdoc/require-param': 'error', 'jsdoc/require-param-description': 'error', 'jsdoc/require-param-name': 'error', 'jsdoc/require-param-type': 'error', 'jsdoc/require-property': 'error', 'jsdoc/require-property-description': 'error', 'jsdoc/require-property-name': 'error', 'jsdoc/require-property-type': 'error', 'jsdoc/require-returns': 'error', 'jsdoc/require-returns-check': 'error', 'jsdoc/require-returns-description': 'error', 'jsdoc/require-returns-type': 'error', 'jsdoc/valid-types': 'error' } };
//Needed components import React from 'react'; import HeaderScrolling from './header-scrolling'; import HeaderTopRow from './header-top-row'; import HeaderContent from './header-content'; import HeaderActions from './header-actions'; /** * Application header */ const AppHeader = () => { return ( <HeaderScrolling> <HeaderTopRow /> <HeaderContent /> <HeaderActions /> </HeaderScrolling> ); } AppHeader.displayName = 'AppHeader'; export default AppHeader;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = undefined; var _style = require('antd/lib/icon/style'); var _icon = require('antd/lib/icon'); var _icon2 = _interopRequireDefault(_icon); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _class, _temp; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _tableRow = require('./tableRow'); var _tableRow2 = _interopRequireDefault(_tableRow); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TBody = (_temp = _class = function (_React$Component) { (0, _inherits3.default)(TBody, _React$Component); function TBody(props) { (0, _classCallCheck3.default)(this, TBody); var _this = (0, _possibleConstructorReturn3.default)(this, (TBody.__proto__ || (0, _getPrototypeOf2.default)(TBody)).call(this, props)); _this.state = {}; return _this; } (0, _createClass3.default)(TBody, [{ key: 'render', value: function render() { var _this2 = this; var _props = this.props; var dataSource = _props.dataSource; var _props$locale = _props.locale; var locale = _props$locale === undefined ? {} : _props$locale; return _react2.default.createElement( 'div', { className: 'nd-body' }, dataSource.length ? _react2.default.createElement( 'div', null, dataSource.map(function (item, dataIndex) { return _react2.default.createElement(_tableRow2.default, (0, _extends3.default)({ key: dataIndex, data: item }, _this2.props)); }) ) : _react2.default.createElement( 'div', null, _react2.default.createElement(_icon2.default, { type: 'frown' }), ' ', locale.no_data || 'No Data' ) ); } }]); return TBody; }(_react2.default.Component), _class.propTypes = { dataSource: _react.PropTypes.array.isRequired, locale: _react.PropTypes.object }, _temp); exports.default = TBody; module.exports = exports['default'];
(function() { var Application, PubSub, Request, Router, Spineless; Application = (function() { function Application() { return { controllers: {}, helpers: { _default: function(locals) { return $.extend(true, {}, locals); } } }; } return Application; })(); Request = (function() { function Request(controller, action, params) { var p; p = params != null ? params : {}; return { controller: $(".controller[data-controller=" + controller + "]"), view: $(".controller[data-controller=" + controller + "] .view[data-action=" + action + "]"), params: $.extend(true, p, { controller: controller, action: action }) }; } return Request; })(); Router = (function() { function Router() { return { parseRoute: function(route) { var hsh, str; str = route + ""; hsh = $.extend(true, {}, { controller: 'application', action: 'index' }); while (str.charAt(0) === '/') { str = str.substr(1); } if (str.length > 0) { $.each(str.split('/'), function(i, e) { if (i === 0) { hsh.controller = e; } if (i === 1) { return hsh.action = e; } }); } return hsh; }, route: function(element) { var route, url; url = element.attr('href') || $(element).attr('data-href'); route = this.parseRoute(url); return this.get(route.controller, route.action, route.params); } }; } return Router; })(); PubSub = (function() { function PubSub() { var o; o = $({}); return { subscribe: function() { return o.on.apply(o, arguments); }, unsubscribe: function() { return o.off.apply(o, arguments); }, publish: function() { return o.trigger.apply(o, arguments); } }; } return PubSub; })(); Spineless = (function() { function Spineless(options) { var controllerActionAvailable, get, init, parseLocals, postRender, prepareRender, render, renderTemplate, root, templates; root = this; templates = function(method, locals) { if (root.app.helpers.hasOwnProperty(method)) { return root.app.helpers[method].apply(root.app, [locals]); } else { return root.app.helpers._default(locals); } }; parseLocals = function(view) { var locals; locals = $(view).attr('data-locals'); if (locals != null) { return $.parseJSON(locals); } else { return {}; } }; prepareRender = function() { if (root.request.controller && root.request.view) { $('.view.active').removeClass('active'); $('.controller.active').removeClass('active'); root.request.view.addClass('active'); root.request.controller.addClass("active"); return root.request.view.find("*[data-template]"); } return []; }; renderTemplate = function(view) { var locals, name, template; name = $(view).attr('data-template'); if (name != null) { locals = parseLocals($(view)); template = $('.templates *[data-template-name=' + name + ']').html(); return view.html($.mustache(template, templates(name, locals))); } }; render = function(elements) { return $.each(elements, function(i, e) { return renderTemplate($(e)); }); }; controllerActionAvailable = function() { return root.app.controllers.hasOwnProperty(root.request.params.controller) && root.app.controllers[root.request.params.controller].hasOwnProperty(root.request.params.action); }; postRender = function() { $('body').attr('data-controller', root.request.params.controller); $('body').attr('data-action', root.request.params.action); $('body').addClass('rendered'); return root.app.publish("afterRender", root.app); }; get = function(controller, action, params) { var itemsToRender; root.request = new Request(controller, action, params); root.app.request = root.request; $('body').removeClass('rendered'); $('html,body').animate({ scrollTop: 0 }, 1); itemsToRender = prepareRender(); if (controllerActionAvailable()) { root.app.controllers[root.request.params.controller][root.request.params.action].apply(root.app, [itemsToRender, root.request]); } else { render(itemsToRender); } return postRender(); }; init = function(options) { $(document).on('click', '.route', function(event) { event.preventDefault(); return root.app.route($(this)); }); return $.extend(true, root.app, options); }; this.app = new Application(); $.extend(true, this.app, new Router()); $.extend(true, this.app, new PubSub()); this.app.get = get; this.app.render = render; init(options); return this.app; } return Spineless; })(); $.spineless = function(options) { return new Spineless(options); }; }).call(this);
Stage.prototype = Object.create(MovieClip.prototype); function Stage(canvas_id, args) { // private vars args = args || {}; args._name = 'stage'; var self = this, _frameRate = args.frameRate || 0, _interval = null, _canvas = document.getElementById(canvas_id), _context = _canvas.getContext('2d'), _displayState = args.displayState || 'dynamic', _lastFrameTime = 0, // private function declarations _updateDisplay, _render, _resize; Object.defineProperty(this, 'frameRate', { get: function() { return _frameRate; }, set: function(fps) { if (fps !== _frameRate) { _frameRate = fps; } } }); Object.defineProperty(this, 'displayState', { get: function() { return _displayState; }, set: function(displayState) { _displayState = displayState; _updateDisplay(); } }); _resize = function() { // updating display _updateDisplay(); self.trigger('onResize'); }; _render = function(time) { if (time-_lastFrameTime >= 1000/_frameRate || _frameRate === 0) { _lastFrameTime = time; // clear canvas _context.clearRect(0, 0, _canvas.width, _canvas.height); // render new graphics self.tickGraphics(_context, Mouse.event); // run logic for tweens and such self.trigger('tickLogic', null, true); // calling on enter frame self.trigger('onEnterFrame'); // clear input context Mouse.clear(); Key.clear(); } _interval = window.requestAnimationFrame(_render); }; //_renderTimer = function _updateDisplay = function() { // code for making sure canvas resolution matches dpi _canvas.width = _canvas.offsetWidth; _canvas.height = _canvas.offsetHeight; // logic for screen if (_displayState == 'original') { self._x = (_canvas.width - self._width)/2; self._y = (_canvas.height - self._height)/2; self._scaleX = 1; self._scaleY = 1; } else if (_displayState == 'stretch') { self._x = 0; self._y = 0; self._scaleX = _canvas.width / self._width; self._scaleY = _canvas.height / self._height; } else if (_displayState == 'fit') { self._x = 0; self._y = 0; self._scaleX = _canvas.width / self._width; self._scaleY = _canvas.height / self._height; if (self._scaleX > self._scaleY) { self._scaleX = self._scaleY; self._x = (_canvas.width - self._width*self._scaleX)/2; } else { self._scaleY = self._scaleX; self._y = (_canvas.height - self._height*self._scaleY)/2; } } else if (_displayState == 'dynamic') { // experimental self._width = _canvas.offsetWidth; self._height = _canvas.offsetHeight; self._x = 0; self._y = 0; self._scaleX = 1; self._scaleY = 1; } }; // public functions this.onResize = null; this.onBlur = null; this.onFocus = null; this.play = function() { if (!self.isPlaying()) { _interval = window.requestAnimationFrame(_render); } }; this.isPlaying = function() { return _interval !== null; }; this.stop = function() { if (self.isPlaying()) { window.cancelAnimationFrame(_interval); //clearInterval(_interval); _interval = null; // render new graphics self.tickGraphics(_context, Mouse.event); } }; // init extended class args._graphic = 'stage'; MovieClip.call(this, args); Mouse.register(_canvas); // setting up handler for resize window.addEventListener('resize', _resize); // setting up handler for blur window.addEventListener('blur', function(e) { // trigger blur events self.trigger('onBlur'); }); // setting up handler for focus window.addEventListener('focus', function(e) { // trigger focus events self.trigger('onFocus'); }); _resize(); }
import { moduleFor, test } from 'ember-qunit'; moduleFor('controller:plants/trees', 'Unit | Controller | plants/trees', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); // Replace this with your real tests. test('it exists', function(assert) { let controller = this.subject(); assert.ok(controller); });
var dojox; //globals var df = dojox.lang.functional; describe("About Applying What We Have Learnt", function() { var operations; beforeEach(function () { operations = [ { direction: "RT", distance: 200}, { direction: "FWD", distance: 50}, { direction: "RT", distance: 100}, { direction: "RT", distance: 20}, { direction: "FWD", distance: 200}, { direction: "RT", distance: 10} ] }); /*********************************************************************************/ it("should find a needle in a haystack (imperative)", function () { var findNeedle = function (ops) { var hasInvalidOperation = false; for (var i = 0; i < ops.length; i+=1) { if (ops[i].direction === "FWD" && ops[i].distance > 100) { hasInvalidOperation = true; break; } } return hasInvalidOperation; }; expect(findNeedle(operations)).toBe(true); }); it("should find needle in a haystack (functional)", function () { expect(df.some(operations, "x.direction === 'FWD' && x.distance > 100")).toBe(true); }); /*********************************************************************************/ it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () { var sum = 0; for(var i=1; i<=1000; i+=1) { if (i % 3 === 0 || i % 5 === 0) { sum += i; } } expect(sum).toBe(234168); }); it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () { var sumIfMultipleOf3Or5 = function (sum, next) { if (next % 3 === 0 || next % 5 === 0) { return sum + next; } return sum; }; var numbers = df.repeat(1000, "+1", 1); expect(df.reduce(numbers, sumIfMultipleOf3Or5, 0)).toBe(234168); }); /*********************************************************************************/ it("should find the sum of all the even valued terms in the fibonacci sequence which do not exceed four million (imperative)", function () { var sum = 0; var fib = [0,1,1]; var i = 3; var currentFib = 0; do { currentFib = fib[i] = fib[i-1] + fib[i-2]; if (currentFib % 2 === 0) { sum += currentFib; } i+=1; } while (currentFib < 4000000); expect(sum).toBe(4613732); }); it("should find the sum of all the even valued terms in the fibonacci sequence which do not exceed four million (functional)", function () { var calcNextFibTuple = function(item, index, array) { return [item[1], item[0]+item[1]]; }; var addEven = function(result, item) { if (item[0] % 2 === 0) { return result + item[0]; } return result; }; var fib = df.until("item[0] > 4000000", calcNextFibTuple, [0,1]); var sum = df.reduce(fib, addEven, 0); expect(sum).toBe(4613732); }); /*********************************************************************************/ /* UNCOMMENT FOR EXTRA CREDIT */ it("should find the largest prime factor of a composite number", function () { }); it("should find the largest palindrome made from the product of two 3 digit numbers", function () { }); it("should what is the smallest number divisible by each of the numbers 1 to 20", function () { }); it("should what is the difference between the sum of the squares and the square of the sums", function () { }); it("should find the 10001st prime", function () { function find_prime_by_index (prime-index) { if :(prime-index > 0) { } i = 1 do { if (i) { } } while (i < prime-index); } expect(find_prime_by_index(10001)).toBe(__); }); });
'use strict'; module.exports = { Model: require('./model') };
// Generated by CoffeeScript 1.12.6 (function() { var Bits, CustomReceiver, DEBUG_INCOMING_PACKET_DATA, DEBUG_INCOMING_PACKET_HASH, DEFAULT_SERVER_NAME, Sequent, StreamServer, aac, avstreams, config, crypto, fs, h264, http, logger, mp4, net, packageJson, ref, rtmp, rtsp, serverName; var uuid = require('node-uuid'); net = require('net'); fs = require('fs'); crypto = require('crypto'); config = require('./config'); rtmp = require('./rtmp'); http = require('./http'); rtsp = require('./rtsp'); h264 = require('./h264'); aac = require('./aac'); mp4 = require('./mp4'); Bits = require('./bits'); avstreams = require('./avstreams'); CustomReceiver = require('./custom_receiver'); logger = require('./logger'); packageJson = require('./package.json'); Sequent = require('sequent'); // var datastore = require('@google-cloud/datastore')({ // projectId: 'hivecast-syndicate', // keyFilename: './hivecast-syndicate.json' // }); DEBUG_INCOMING_PACKET_DATA = false; DEBUG_INCOMING_PACKET_HASH = false; DEFAULT_SERVER_NAME = "node-rtsp-rtmp-server/" + packageJson.version; serverName = (ref = config.serverName) != null ? ref : DEFAULT_SERVER_NAME; StreamServer = (function() { function StreamServer(opts) { var httpHandler, ref1, rtmptCallback; this.serverName = (ref1 = opts != null ? opts.serverName : void 0) != null ? ref1 : serverName; if (config.enableRTMP || config.enableRTMPT) { this.rtmpServer = new rtmp.RTMPServer; this.rtmpServer.on('video_start', (function(_this) { return function(streamId) { var stream; stream = avstreams.getOrCreate(streamId); _this.dumpToFile(streamId); return _this.onReceiveVideoControlBuffer(stream); }; })(this)); this.rtmpServer.on('video_data', (function(_this) { return function(streamId, pts, dts, nalUnits) { var stream; stream = avstreams.get(streamId); if (stream != null) { return _this.onReceiveVideoPacket(stream, nalUnits, pts, dts); } else { return logger.warn("warn: Received invalid streamId from rtmp: " + streamId); } }; })(this)); this.rtmpServer.on('audio_start', (function(_this) { return function(streamId) { var stream; stream = avstreams.getOrCreate(streamId); return _this.onReceiveAudioControlBuffer(stream); }; })(this)); this.rtmpServer.on('audio_data', (function(_this) { return function(streamId, pts, dts, adtsFrame) { var stream; stream = avstreams.get(streamId); if (stream != null) { return _this.onReceiveAudioPacket(stream, adtsFrame, pts, dts); } else { return logger.warn("warn: Received invalid streamId from rtmp: " + streamId); } }; })(this)); } if (config.enableCustomReceiver) { this.customReceiver = new CustomReceiver(config.receiverType, { videoControl: (function(_this) { return function() { return _this.onReceiveVideoControlBuffer.apply(_this, arguments); }; })(this), audioControl: (function(_this) { return function() { return _this.onReceiveAudioControlBuffer.apply(_this, arguments); }; })(this), videoData: (function(_this) { return function() { return _this.onReceiveVideoDataBuffer.apply(_this, arguments); }; })(this), audioData: (function(_this) { return function() { return _this.onReceiveAudioDataBuffer.apply(_this, arguments); }; })(this) }); this.customReceiver.deleteReceiverSocketsSync(); } if (config.enableHTTP) { this.httpHandler = new http.HTTPHandler({ serverName: this.serverName, documentRoot: opts != null ? opts.documentRoot : void 0 }); } if (config.enableRTSP || config.enableHTTP || config.enableRTMPT) { if (config.enableRTMPT) { rtmptCallback = (function(_this) { return function() { var ref2; return (ref2 = _this.rtmpServer).handleRTMPTRequest.apply(ref2, arguments); }; })(this); } else { rtmptCallback = null; } if (config.enableHTTP) { httpHandler = this.httpHandler; } else { httpHandler = null; } this.rtspServer = new rtsp.RTSPServer({ serverName: this.serverName, httpHandler: httpHandler, rtmptCallback: rtmptCallback }); this.rtspServer.on('video_start', (function(_this) { return function(stream) { return _this.onReceiveVideoControlBuffer(stream); }; })(this)); this.rtspServer.on('audio_start', (function(_this) { return function(stream) { return _this.onReceiveAudioControlBuffer(stream); }; })(this)); this.rtspServer.on('video', (function(_this) { return function(stream, nalUnits, pts, dts) { return _this.onReceiveVideoNALUnits(stream, nalUnits, pts, dts); }; })(this)); this.rtspServer.on('audio', (function(_this) { return function(stream, accessUnits, pts, dts) { return _this.onReceiveAudioAccessUnits(stream, accessUnits, pts, dts); }; })(this)); } avstreams.on('new', function(stream) { if (DEBUG_INCOMING_PACKET_HASH) { return stream.lastSentVideoTimestamp = 0; } }); avstreams.on('reset', function(stream) { if (DEBUG_INCOMING_PACKET_HASH) { return stream.lastSentVideoTimestamp = 0; } }); avstreams.on('end', (function(_this) { return function(stream) { if (config.enableRTSP) { _this.rtspServer.sendEOS(stream); } if (config.enableRTMP || config.enableRTMPT) { return _this.rtmpServer.sendEOS(stream); } }; })(this)); avstreams.on('audio_data', (function(_this) { return function(stream, data, pts) { return _this.onReceiveAudioAccessUnits(stream, [data], pts, pts); }; })(this)); avstreams.on('video_data', (function(_this) { return function(stream, nalUnits, pts, dts) { if (dts == null) { dts = pts; } return _this.onReceiveVideoNALUnits(stream, nalUnits, pts, dts); }; })(this)); avstreams.on('audio_start', (function(_this) { return function(stream) { return _this.onReceiveAudioControlBuffer(stream); }; })(this)); avstreams.on('video_start', (function(_this) { return function(stream) { return _this.onReceiveVideoControlBuffer(stream); }; })(this)); } StreamServer.prototype.dumpToFile = function(streamId) { var serverAddr = config.serverAddress; var dumpId = (streamId.split('/'))[1]; var spawn = require('child_process').spawn; var fileName = dumpId + '_' + uuid.v1() + '.flv'; var dumpCmd = 'rtmpdump'; //ffmpeg -re -i input.mp4 -c:v copy -c:a copy -f flv rtmp://localhost/live/STREAM_NAME //rtmpdump -v -r rtmp://localhost/live/STREAM_NAME -o dump.flv var dumpArgs = [ '-v', '-r', `rtmp://${serverAddr}/` + streamId, '-o', `public/file/${fileName}` ]; var dumpProc = spawn(dumpCmd, dumpArgs); //var ds_key = datastore.key(['Stream', ]) dumpProc.stdout.on('data', function(data) { }); dumpProc.stderr.on('data', function(data) { }); dumpProc.on('close', function() { console.log(`Stream dump is finished. File could be found at file/${fileName}`); /*setTimeout(function() { var streamCmd = 'ffmpeg'; var streamArgs = [ '-re', '-i', 'file/' + dumpId + '.flv', '-c', 'copy', '-f', 'flv', `rtmp://${serverAddr}/live/cloned_` + dumpId ]; var streamProc = spawn(streamCmd, streamArgs); streamProc.on('close', function() { console.log(`FLV: file/${dumpId}.flv is streamed successfully.`); }); }, 3000);*/ }); }; StreamServer.prototype.attachRecordedDir = function(dir) { if (config.recordedApplicationName != null) { logger.info("attachRecordedDir: dir=" + dir + " app=" + config.recordedApplicationName); return avstreams.attachRecordedDirToApp(dir, config.recordedApplicationName); } }; StreamServer.prototype.attachMP4 = function(filename, streamName) { var context, generator; logger.info("attachMP4: file=" + filename + " stream=" + streamName); context = this; generator = new avstreams.AVStreamGenerator({ generate: function() { var ascBuf, ascInfo, audioSpecificConfig, bits, err, mp4File, mp4Stream, streamId; try { mp4File = new mp4.MP4File(filename); } catch (error) { err = error; logger.error("error opening MP4 file " + filename + ": " + err); return null; } streamId = avstreams.createNewStreamId(); mp4Stream = new avstreams.MP4Stream(streamId); logger.info("created stream " + streamId + " from " + filename); avstreams.emit('new', mp4Stream); avstreams.add(mp4Stream); mp4Stream.type = avstreams.STREAM_TYPE_RECORDED; audioSpecificConfig = null; mp4File.on('audio_data', function(data, pts) { return context.onReceiveAudioAccessUnits(mp4Stream, [data], pts, pts); }); mp4File.on('video_data', function(nalUnits, pts, dts) { if (dts == null) { dts = pts; } return context.onReceiveVideoNALUnits(mp4Stream, nalUnits, pts, dts); }); mp4File.on('eof', (function(_this) { return function() { return mp4Stream.emit('end'); }; })(this)); mp4File.parse(); mp4Stream.updateSPS(mp4File.getSPS()); mp4Stream.updatePPS(mp4File.getPPS()); ascBuf = mp4File.getAudioSpecificConfig(); bits = new Bits(ascBuf); ascInfo = aac.readAudioSpecificConfig(bits); mp4Stream.updateConfig({ audioSpecificConfig: ascBuf, audioASCInfo: ascInfo, audioSampleRate: ascInfo.samplingFrequency, audioClockRate: 90000, audioChannels: ascInfo.channelConfiguration, audioObjectType: ascInfo.audioObjectType }); mp4Stream.durationSeconds = mp4File.getDurationSeconds(); mp4Stream.lastTagTimestamp = mp4File.getLastTimestamp(); mp4Stream.mp4File = mp4File; mp4File.fillBuffer(function() { context.onReceiveAudioControlBuffer(mp4Stream); return context.onReceiveVideoControlBuffer(mp4Stream); }); return mp4Stream; }, play: function() { return this.mp4File.play(); }, pause: function() { return this.mp4File.pause(); }, resume: function() { return this.mp4File.resume(); }, seek: function(seekSeconds, callback) { var actualStartTime; actualStartTime = this.mp4File.seek(seekSeconds); return callback(null, actualStartTime); }, sendVideoPacketsSinceLastKeyFrame: function(endSeconds, callback) { return this.mp4File.sendVideoPacketsSinceLastKeyFrame(endSeconds, callback); }, teardown: function() { this.mp4File.close(); return this.destroy(); }, getCurrentPlayTime: function() { return this.mp4File.currentPlayTime; }, isPaused: function() { return this.mp4File.isPaused(); } }); return avstreams.addGenerator(streamName, generator); }; StreamServer.prototype.stop = function(callback) { if (config.enableCustomReceiver) { this.customReceiver.deleteReceiverSocketsSync(); } return typeof callback === "function" ? callback() : void 0; }; StreamServer.prototype.start = function(callback) { var seq, waitCount; seq = new Sequent; waitCount = 0; if (config.enableRTMP) { waitCount++; this.rtmpServer.start({ port: config.rtmpServerPort }, function() { return seq.done(); }); } if (config.enableCustomReceiver) { this.customReceiver.start(); } if (config.enableRTSP || config.enableHTTP || config.enableRTMPT) { waitCount++; this.rtspServer.start({ port: config.serverPort }, function() { return seq.done(); }); } return seq.wait(waitCount, function() { return typeof callback === "function" ? callback() : void 0; }); }; StreamServer.prototype.setLivePathConsumer = function(func) { if (config.enableRTSP) { return this.rtspServer.setLivePathConsumer(func); } }; StreamServer.prototype.setAuthenticator = function(func) { if (config.enableRTSP) { return this.rtspServer.setAuthenticator(func); } }; StreamServer.prototype.onReceiveVideoControlBuffer = function(stream, buf) { stream.resetFrameRate(stream); stream.isVideoStarted = true; stream.timeAtVideoStart = Date.now(); return stream.timeAtAudioStart = stream.timeAtVideoStart; }; StreamServer.prototype.onReceiveAudioControlBuffer = function(stream, buf) { stream.isAudioStarted = true; stream.timeAtAudioStart = Date.now(); return stream.timeAtVideoStart = stream.timeAtAudioStart; }; StreamServer.prototype.onReceiveVideoDataBuffer = function(stream, buf) { var dts, nalUnit, pts; pts = buf[1] * 0x010000000000 + buf[2] * 0x0100000000 + buf[3] * 0x01000000 + buf[4] * 0x010000 + buf[5] * 0x0100 + buf[6]; dts = pts; nalUnit = buf.slice(7); return this.onReceiveVideoPacket(stream, nalUnit, pts, dts); }; StreamServer.prototype.onReceiveAudioDataBuffer = function(stream, buf) { var adtsFrame, dts, pts; pts = buf[1] * 0x010000000000 + buf[2] * 0x0100000000 + buf[3] * 0x01000000 + buf[4] * 0x010000 + buf[5] * 0x0100 + buf[6]; dts = pts; adtsFrame = buf.slice(7); return this.onReceiveAudioPacket(stream, adtsFrame, pts, dts); }; StreamServer.prototype.onReceiveVideoNALUnits = function(stream, nalUnits, pts, dts) { var hasVideoFrame, j, len, md5, nalUnit, nalUnitType, tsDiff; if (DEBUG_INCOMING_PACKET_DATA) { logger.info("receive video: num_nal_units=" + nalUnits.length + " pts=" + pts); } if (config.enableRTSP) { this.rtspServer.sendVideoData(stream, nalUnits, pts, dts); } if (config.enableRTMP || config.enableRTMPT) { this.rtmpServer.sendVideoPacket(stream, nalUnits, pts, dts); } hasVideoFrame = false; for (j = 0, len = nalUnits.length; j < len; j++) { nalUnit = nalUnits[j]; nalUnitType = h264.getNALUnitType(nalUnit); if (nalUnitType === h264.NAL_UNIT_TYPE_SPS) { stream.updateSPS(nalUnit); } else if (nalUnitType === h264.NAL_UNIT_TYPE_PPS) { stream.updatePPS(nalUnit); } else if ((nalUnitType === h264.NAL_UNIT_TYPE_IDR_PICTURE) || (nalUnitType === h264.NAL_UNIT_TYPE_NON_IDR_PICTURE)) { hasVideoFrame = true; } if (DEBUG_INCOMING_PACKET_HASH) { md5 = crypto.createHash('md5'); md5.update(nalUnit); tsDiff = pts - stream.lastSentVideoTimestamp; logger.info("video: pts=" + pts + " pts_diff=" + tsDiff + " md5=" + (md5.digest('hex').slice(0, 7)) + " nal_unit_type=" + nalUnitType + " bytes=" + nalUnit.length); stream.lastSentVideoTimestamp = pts; } } if (hasVideoFrame) { stream.calcFrameRate(pts); } }; StreamServer.prototype.onReceiveVideoPacket = function(stream, nalUnitGlob, pts, dts) { var nalUnits; nalUnits = h264.splitIntoNALUnits(nalUnitGlob); if (nalUnits.length === 0) { return; } this.onReceiveVideoNALUnits(stream, nalUnits, pts, dts); }; StreamServer.prototype.onReceiveAudioAccessUnits = function(stream, accessUnits, pts, dts) { var accessUnit, i, j, len, md5, ptsPerFrame; if (config.enableRTSP) { this.rtspServer.sendAudioData(stream, accessUnits, pts, dts); } if (DEBUG_INCOMING_PACKET_DATA) { logger.info("receive audio: num_access_units=" + accessUnits.length + " pts=" + pts); } ptsPerFrame = 90000 / (stream.audioSampleRate / 1024); for (i = j = 0, len = accessUnits.length; j < len; i = ++j) { accessUnit = accessUnits[i]; if (DEBUG_INCOMING_PACKET_HASH) { md5 = crypto.createHash('md5'); md5.update(accessUnit); logger.info("audio: pts=" + pts + " md5=" + (md5.digest('hex').slice(0, 7)) + " bytes=" + accessUnit.length); } if (config.enableRTMP || config.enableRTMPT) { this.rtmpServer.sendAudioPacket(stream, accessUnit, Math.round(pts + ptsPerFrame * i), Math.round(dts + ptsPerFrame * i)); } } }; StreamServer.prototype.onReceiveAudioPacket = function(stream, adtsFrameGlob, pts, dts) { var adtsFrame, adtsFrames, adtsInfo, i, isConfigUpdated, j, len, rawDataBlock, rawDataBlocks, rtpTimePerFrame; adtsFrames = aac.splitIntoADTSFrames(adtsFrameGlob); if (adtsFrames.length === 0) { return; } adtsInfo = aac.parseADTSFrame(adtsFrames[0]); isConfigUpdated = false; stream.updateConfig({ audioSampleRate: adtsInfo.sampleRate, audioClockRate: adtsInfo.sampleRate, audioChannels: adtsInfo.channels, audioObjectType: adtsInfo.audioObjectType }); rtpTimePerFrame = 1024; rawDataBlocks = []; for (i = j = 0, len = adtsFrames.length; j < len; i = ++j) { adtsFrame = adtsFrames[i]; rawDataBlock = adtsFrame.slice(7); rawDataBlocks.push(rawDataBlock); } return this.onReceiveAudioAccessUnits(stream, rawDataBlocks, pts, dts); }; return StreamServer; })(); module.exports = StreamServer; }).call(this);
exports.view = function(req, res){ res.render('settings'); };
var Bookshelf = require('../config/bookshelf'); var Director = Bookshelf.Model.extend({ tableName: 'directors', movies: function() { 'use strict'; return this.hasMany('Movie', 'directorID'); }, virtuals: { fullName: function () { 'use strict'; return this.get('firstName') + ' ' + this.get('lastName'); } } }); module.exports = Bookshelf.model('Director', Director);
import { Meteor } from 'meteor/meteor'; import { $ } from 'meteor/jquery'; import { OHIF } from 'meteor/ohif:core'; import { toolManager } from './toolManager'; import { setActiveViewport } from './setActiveViewport'; import { switchToImageRelative } from './switchToImageRelative'; import { switchToImageByIndex } from './switchToImageByIndex'; import { viewportUtils } from './viewportUtils'; import { panelNavigation } from './panelNavigation'; import { WLPresets } from './WLPresets'; // TODO: add this to namespace definitions Meteor.startup(function() { if (!OHIF.viewer) { OHIF.viewer = {}; } OHIF.viewer.loadIndicatorDelay = 200; OHIF.viewer.defaultTool = 'wwwc'; OHIF.viewer.refLinesEnabled = true; OHIF.viewer.isPlaying = {}; OHIF.viewer.cine = { framesPerSecond: 24, loop: true }; OHIF.viewer.defaultHotkeys = { defaultTool: 'ESC', angle: 'A', stackScroll: 'S', pan: 'P', magnify: 'M', scrollDown: 'DOWN', scrollUp: 'UP', nextDisplaySet: 'PAGEDOWN', previousDisplaySet: 'PAGEUP', nextPanel: 'RIGHT', previousPanel: 'LEFT', invert: 'I', flipV: 'V', flipH: 'H', wwwc: 'W', zoom: 'Z', cinePlay: 'SPACE', rotateR: 'R', rotateL: 'L', toggleOverlayTags: 'SHIFT', WLPresetSoftTissue: ['NUMPAD1', '1'], WLPresetLung: ['NUMPAD2', '2'], WLPresetLiver: ['NUMPAD3', '3'], WLPresetBone: ['NUMPAD4', '4'], WLPresetBrain: ['NUMPAD5', '5'] }; // For now OHIF.viewer.hotkeys = OHIF.viewer.defaultHotkeys; OHIF.viewer.hotkeyFunctions = { wwwc() { toolManager.setActiveTool('wwwc'); }, zoom() { toolManager.setActiveTool('zoom'); }, angle() { toolManager.setActiveTool('angle'); }, dragProbe() { toolManager.setActiveTool('dragProbe'); }, ellipticalRoi() { toolManager.setActiveTool('ellipticalRoi'); }, magnify() { toolManager.setActiveTool('magnify'); }, annotate() { toolManager.setActiveTool('annotate'); }, stackScroll() { toolManager.setActiveTool('stackScroll'); }, pan() { toolManager.setActiveTool('pan'); }, length() { toolManager.setActiveTool('length'); }, spine() { toolManager.setActiveTool('spine'); }, wwwcRegion() { toolManager.setActiveTool('wwwcRegion'); }, zoomIn() { const button = document.getElementById('zoomIn'); flashButton(button); viewportUtils.zoomIn(); }, zoomOut() { const button = document.getElementById('zoomOut'); flashButton(button); viewportUtils.zoomOut(); }, zoomToFit() { const button = document.getElementById('zoomToFit'); flashButton(button); viewportUtils.zoomToFit(); }, scrollDown() { const container = $('.viewportContainer.active'); const button = container.find('#nextImage').get(0); if (!container.find('.imageViewerViewport').hasClass('empty')) { flashButton(button); switchToImageRelative(1); } }, scrollFirstImage() { const container = $('.viewportContainer.active'); if (!container.find('.imageViewerViewport').hasClass('empty')) { switchToImageByIndex(0); } }, scrollLastImage() { const container = $('.viewportContainer.active'); if (!container.find('.imageViewerViewport').hasClass('empty')) { switchToImageByIndex(-1); } }, scrollUp() { const container = $('.viewportContainer.active'); if (!container.find('.imageViewerViewport').hasClass('empty')) { const button = container.find('#prevImage').get(0); flashButton(button); switchToImageRelative(-1); } }, previousDisplaySet() { OHIF.viewerbase.layoutManager.moveDisplaySets(false); }, nextDisplaySet() { OHIF.viewerbase.layoutManager.moveDisplaySets(true); }, nextPanel() { panelNavigation.loadNextActivePanel(); }, previousPanel() { panelNavigation.loadPreviousActivePanel(); }, invert() { const button = document.getElementById('invert'); flashButton(button); viewportUtils.invert(); }, flipV() { const button = document.getElementById('flipV'); flashButton(button); viewportUtils.flipV(); }, flipH() { const button = document.getElementById('flipH'); flashButton(button); viewportUtils.flipH(); }, rotateR() { const button = document.getElementById('rotateR'); flashButton(button); viewportUtils.rotateR(); }, rotateL() { const button = document.getElementById('rotateL'); flashButton(button); viewportUtils.rotateL(); }, cinePlay() { viewportUtils.toggleCinePlay(); }, defaultTool() { const tool = toolManager.getDefaultTool(); toolManager.setActiveTool(tool); }, toggleOverlayTags() { const dicomTags = $('.imageViewerViewportOverlay .dicomTag'); if (dicomTags.eq(0).css('display') === 'none') { dicomTags.show(); } else { dicomTags.hide(); } }, resetStack() { const button = document.getElementById('resetStack'); flashButton(button); resetStack(); }, clearImageAnnotations() { const button = document.getElementById('clearImageAnnotations'); flashButton(button); clearImageAnnotations(); }, cineDialog () { /** * TODO: This won't work in OHIF's, since this element * doesn't exist */ const button = document.getElementById('cine'); flashButton(button); viewportUtils.toggleCineDialog(); button.classList.toggle('active'); } }; OHIF.viewer.loadedSeriesData = {}; }); // Define a jQuery reverse function $.fn.reverse = [].reverse; /** * Overrides OHIF's refLinesEnabled * @param {Boolean} refLinesEnabled True to enable and False to disable */ function setOHIFRefLines(refLinesEnabled) { OHIF.viewer.refLinesEnabled = refLinesEnabled; } /** * Overrides OHIF's hotkeys * @param {Object} hotkeys Object with hotkeys mapping */ function setOHIFHotkeys(hotkeys) { OHIF.viewer.hotkeys = hotkeys; } /** * Global function to merge different hotkeys configurations * but avoiding conflicts between different keys with same action * When this occurs, it will delete the action from OHIF's configuration * So if you want to keep all OHIF's actions, use an unused-ohif-key * Used for compatibility with others systems only * * @param hotkeysActions {object} Object with actions map * @return {object} */ function mergeHotkeys(hotkeysActions) { // Merge hotkeys, overriding OHIF's settings let mergedHotkeys = { ...OHIF.viewer.defaultHotkeys, ...hotkeysActions }; const defaultHotkeys = OHIF.viewer.defaultHotkeys; const hotkeysKeys = Object.keys(hotkeysActions); // Check for conflicts with same keys but different actions Object.keys(defaultHotkeys).forEach(ohifAction => { hotkeysKeys.forEach(definedAction => { // Different action but same key: // Remove action from merge if is not in "hotkeysActions" // If it is, it's already merged so nothing to do if(ohifAction !== definedAction && hotkeysActions[definedAction] === defaultHotkeys[ohifAction] && !hotkeysActions[ohifAction]) { delete mergedHotkeys[ohifAction]; } }); }); return mergedHotkeys; } /** * Add an active class to a button for 100ms only * to give the impressiont the button was pressed. * This is for tools that don't keep the button "pressed" * all the time the tool is active. * * @param button DOM Element for the button to be "flashed" */ function flashButton(button) { if (!button) { return; } button.classList.add('active'); setTimeout(() => { button.classList.remove('active'); }, 100); } /** * Binds a task to a hotkey keydown event * @param {String} hotkey keyboard key * @param {String} task task function name */ function bindHotkey(hotkey, task) { var hotkeyFunctions = OHIF.viewer.hotkeyFunctions; // Only bind defined, non-empty HotKeys if (!hotkey || hotkey === '') { return; } var fn; if (task.indexOf('WLPreset') > -1) { var presetName = task.replace('WLPreset', ''); fn = function() { WLPresets.applyWLPresetToActiveElement(presetName); }; } else { fn = hotkeyFunctions[task]; // If the function doesn't exist in the // hotkey function list, try the viewer-specific function list if (!fn && OHIF.viewer && OHIF.viewer.functionList) { fn = OHIF.viewer.functionList[task]; } } if (!fn) { return; } var hotKeyForBinding = hotkey.toLowerCase(); $(document).bind('keydown', hotKeyForBinding, fn); } /** * Binds all hotkeys keydown events to the tasks defined in * OHIF.viewer.hotkeys or a given param * @param {Object} hotkeys hotkey and task mapping (not required). If not given, uses OHIF.viewer.hotkeys */ function enableHotkeys(hotkeys) { const viewerHotkeys = hotkeys || OHIF.viewer.hotkeys; $(document).unbind('keydown'); Object.keys(viewerHotkeys).forEach(function(task) { const taskHotkeys = viewerHotkeys[task]; if (!taskHotkeys || !taskHotkeys.length) { return; } if (taskHotkeys instanceof Array) { taskHotkeys.forEach(function(hotkey) { bindHotkey(hotkey, task); }); } else { // taskHotkeys represents a single key bindHotkey(taskHotkeys, task); } }); } /** * Export functions inside hotkeyUtils namespace. */ const hotkeyUtils = { setOHIFRefLines, /* @TODO: find a better place for this... */ setOHIFHotkeys, mergeHotkeys, enableHotkeys }; export { hotkeyUtils };
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, IndexRoute, Route, browserHistory } from 'react-router' import App from './components/App'; import Home from './components/Home'; import Page1 from './components/Page1'; import Page2 from './components/Page2'; ReactDOM.render(( <Router history={browserHistory}> <Route component={App}> <Route path="/" component={Home}></Route> <Route path="page1" component={Page1}></Route> <Route path="page2" component={Page2}></Route> </Route> </Router> ), document.getElementById('root'));