code
stringlengths
2
1.05M
(function() { function AlbumListController($scope){ $scope.adding_album={}; $scope.add_album_error=""; $scope.albumNames=[ {name:'Madrid',title:'Weekend in Madrid',date:'12.03.2014', describtion: 'At Madrid'}, {name:'London',title:'Weekend in London',date:'11.06.2013',describtion: 'At London'}, {name:'Berlin',title:'Weekend in Berlin',date:'23.05.2011',describtion: 'Berlin'}, {name:'Bkk',title:'Weekend in Bkk',date:'21.09.2012',describtion: 'At Bangkok'}, {name:'Paris',title:'Weekend in Paris',date:'16.09.2014',describtion: 'At Paris'} ]; //model $scope.addAlbum= function (new_album){ // form validation if(!new_album.title) $scope.add_album_error="Missing title"; else if (!new_album.date || !is_valid_date(new_album.date)) $scope.add_album_error="Date incorrect"; else if(!new_album.describtion) $scope.add_album_error="Missing description"; else if(!new_album.name) $scope.add_album_error="Missing short name"; else { $scope.albumNames.push(new_album); $scope.adding_album={}; $scope.add_album_error=""; } }; } function Controller404($scope){ } photoApp.controller("AlbumListController", AlbumListController); function is_valid_date(the_date){ if(the_date.match(/[0-9]{2,4}\.[0-9]{1,2}\.[0-9]{1,2}/)){ var d = new Date(the_date); return !isNaN(d.getTime()); } else{ return false; } } })();
import React from 'react'; import ContextMenu from '../../components/ContextMenu'; import AlloyEditorComponent from '../../components/AlloyEditorComponent'; export default class PageHtml extends React.Component { constructor(props) { super(props); } static getInfo() { return { title: '에디터 포틀릿', image: null } } static getDefault() { return { title: '에디터 포틀릿', image: null, options: { padding: 5, w: 4, h: 4, x: 0, y: Infinity, static: false, isDraggable: true, isResizable: true } }; } render() { let padding = this.props.padding; if (padding <= 0) { padding = 5; } return ( <div style={{ width: '100%', height: '100%', padding: padding }}> <ContextMenu idx={this.props.idx} isContextMenuShow={this.props.isContextMenuShow} /> <AlloyEditorComponent container="editable"/> </div> ) } }
'use strict'; function focusOrCreateTab(url) { chrome.windows.getAll({'populate': true}, function (windows) { var existingTab; for (var i in windows) { if (windows.hasOwnProperty(i)) { var tabs = windows[i].tabs; for (var j in tabs) { if (tabs.hasOwnProperty(j)) { var tab = tabs[j]; if (tab.url === url) { existingTab = tab; break; } } } } } if (existingTab) { chrome.tabs.update(existingTab.id, {'selected': true}); } else { chrome.tabs.create({'url': url, 'selected': true}); } }); } chrome.browserAction.onClicked.addListener(function () { var url = chrome.extension.getURL('search.html'); focusOrCreateTab(url); });
// License: (MIT) Copyright (C) 2013 Scott Gay define([ "js/base.js", "js/libraries/jquery.min.js" ], function(Base){ underpin.subpagecontrols.base = function(parameters){ Base.call(this); this.init = function(){ this.parameters = parameters; } this.init(); } underpin.subpagecontrols.base.prototype = Object.create(Base.prototype); underpin.subpagecontrols.base.prototype.getContainer = function(){ // this creates a container for each subpagecontrol this.container = $('<div>').appendTo(this.parameters.container); } underpin.subpagecontrols.base.prototype.destroyControl = function(){ this.container.remove(); } underpin.subpagecontrols.base.prototype.hidePage = function(){ this.container.hide(); } underpin.subpagecontrols.base.prototype.showPage = function(){ this.container.show(); } return underpin.subpagecontrols.base; });
var Application = require("./Application") var express = require("express"); var app = express(); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); Application.run(app); app.listen(3000);
(function() { "use strict"; var parse_line, warnings; module.exports = function(grunt) { grunt.registerMultiTask('sass_linter', 'Advanced style guide fascism for SASS', function() { var error_count, options; options = this.options({ warn: { deep_selectors: true, multi_selectors: true, magic_numbers: true } }); grunt.verbose.writeflags(options, 'sass-lint options'); error_count = 0; this.filesSrc.forEach(function(path) { var doc; grunt.log.writeln(path); doc = { tab_size: 2 }; grunt.file.read(path).split('\n').map(parse_line).forEach(function(p, index) { var errors, key, warn; errors = ((function() { var _results; _results = []; for (key in warnings) { warn = warnings[key]; if (options[key]) { _results.push(warn(p, doc)); } } return _results; })()).filter(function(x) { return x != null; }); error_count += errors.length; if (errors.length) { return grunt.log.errorlns("" + index + ": " + doc.lines[index] + "\n"); } }); if (error_count) { return grunt.log.errorlns("" + error_count + " errors found."); } else { return grunt.log.oklns("No errors found. Hooray!"); } }); return done(); }); }; warnings = { deep_selectors: function(line, doc) { var depth; if (line.kind !== "selector") { return; } depth = line.indent / doc.tab_size + Math.max.apply(null, line.args.map(function(g) { return g.length; })); if (depth > 3) { grunt.log.errorlns("Warning: selector " + depth + " levels deep"); return { deep_selectors: depth }; } }, multi_selectors: function(line, doc) { var selector_count; if (line.kind !== "selector") { return; } selector_count = line.args.length; if (selector_count > 1) { grunt.log.errorlns("Warning: " + selector_count + " selectors on single line"); return { multi_selectors: selector_count }; } }, magic_numbers: function(line, doc) { var blacklist, errors, whitelist; if (line.kind !== "attribute") { return; } if (line.args[0][0] === '$') { return; } blacklist = /(px|%|#|rgb)/; whitelist = /^(1px|100%|50%|25%|20%)/; errors = line.args.map(function(arg) { if (blacklist.test(arg)) { return arg; } }).filter(function(arg) { return (arg != null) && !whitelist.test(arg); }); if (errors.length) { grunt.log.errorlns("Warning: Magic Numbers " + (errors.join(', '))); return { magic_numbers: errors }; } } }; parse_line = function(line) { var kind, trim; if (line == null) { return null; } trim = line.trimLeft(); kind = line.indexOf('@') > 0 ? "mixin" : line.indexOf(': ') > 0 ? "attribute" : "selector"; return { indent: line.length - trim.length, kind: kind, args: (function() { if (kind === "attribute") { return trim.split(/\s|:\s/); } else if (kind === "selector") { return trim.split(/\s*,\s*/).filter(function(group) { return group != null; }).map(function(group) { return group.split(/\s+/); }); } else { return null; } })() }; }; }).call(this);
exports.action = { name: 'printerList', description: 'Returns an array of Printers from an Organization', version: 1, inputs: { required: [ 'organizationId' ], optional: [] }, outputExample: { printers: [ { name: 'My Color Printer', id: '123', location: 'Room 201', manufacturer: 'Ricoh', model: 'ABC123', ipAddress: '192.168.100.20', serial: '12345ABCDE' } ] }, run: function (api, connection, next) { var id = api.mongoose.Types.ObjectId(connection.params.organizationId); api.mongoose.model('Organization') .findOne({ _id: id }) .populate({ path: 'printers', model: 'Printer' }) .exec(function (err, res) { connection.response.printers = []; if (res && res.printers) { res.printers.forEach(function (r) { connection.response.printers.push({ name: r.name, id: r._id, location: r.location, manufacturer: r.manufacturer, model: r.model, ipAddress: r.ipAddress, serial: r.serial, status: r.status }); }); } next(connection, true); } ); } };
// # Ghost Configuration // Setup your Ghost install for various [environments](http://support.ghost.org/config/#about-environments). // Ghost runs in `development` mode by default. Full documentation can be found at http://support.ghost.org/config/ var path = require('path'), config; config = { // ### Production // When running Ghost in the wild, use the production environment. // Configure your URL and mail settings here production: { url: 'http://<URL>', mail: { transport: 'SMTP', options: { service: 'Sendgrid', auth: { user: '<USERNAME>', pass: '<PASSWORD>' } } }, database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost.db') }, debug: false }, server: { host: '<IP>', port: '2368' } }, // ### Development **(default)** development: { // The url to use when providing links to the site, E.g. in RSS and email. // Change this to your Ghost blog's published URL. url: 'http://localhost:2368', // Example mail config // Visit http://support.ghost.org/mail for instructions // ``` // mail: { // transport: 'SMTP', // options: { // service: 'Mailgun', // auth: { // user: '', // mailgun username // pass: '' // mailgun password // } // } // }, // ``` // #### Database // Ghost supports sqlite3 (default), MySQL & PostgreSQL database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-dev.db') }, debug: false }, // #### Server // Can be host & port (default), or socket server: { // Host to be passed to node's `net.Server#listen()` host: '127.0.0.1', // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT` port: '2368' }, // #### Paths // Specify where your content directory lives paths: { contentPath: path.join(__dirname, '/content/') } }, // **Developers only need to edit below here** // ### Testing // Used when developing Ghost to run tests and check the health of Ghost // Uses a different port number testing: { url: 'http://127.0.0.1:2369', database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-test.db') }, pool: { afterCreate: function (conn, done) { conn.run('PRAGMA synchronous=OFF;' + 'PRAGMA journal_mode=MEMORY;' + 'PRAGMA locking_mode=EXCLUSIVE;' + 'BEGIN EXCLUSIVE; COMMIT;', done); } } }, server: { host: '127.0.0.1', port: '2369' }, logging: false }, // ### Testing MySQL // Used by Travis - Automated testing run through GitHub 'testing-mysql': { url: 'http://127.0.0.1:2369', database: { client: 'mysql', connection: { host : '127.0.0.1', user : 'root', password : '', database : 'ghost_testing', charset : 'utf8' } }, server: { host: '127.0.0.1', port: '2369' }, logging: false }, // ### Testing pg // Used by Travis - Automated testing run through GitHub 'testing-pg': { url: 'http://127.0.0.1:2369', database: { client: 'pg', connection: { host : '127.0.0.1', user : 'postgres', password : '', database : 'ghost_testing', charset : 'utf8' } }, server: { host: '127.0.0.1', port: '2369' }, logging: false } }; module.exports = config;
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery-2.1.4.min //= require bootstrap.min //= require privacy-modal-why-show-hide.js //---require_tree .
var should = require("chai").should(); var path = require('path'); var month = require(path.join(process.cwd() + "/lib/month")); //Month test items describe('Month', function() { describe('object', function() { it('should return a month name', function() { var jan = month[1]; var may = month[5]; var oct = month[10]; var dec = month[12]; jan.should.be.an('object'); jan.name.should.equal('January'); may.name.should.equal('May'); oct.name.should.equal('October'); dec.name.should.equal('December'); }) it('should return a month length', function() { var jan = month[1]; var feb = month[2]; var jun = month[6]; var dec = month[12]; jan.should.be.an('object'); jan.days.should.equal('31'); feb.days.should.equal('28'); jun.days.should.equal('30'); dec.days.should.equal('31'); }) }); }); //end of Month test set
import CardSet from "../../artifact/js/CardSet.js"; import CardSubset from "../../artifact/js/CardSubset.js"; import CardType from "../../artifact/js/CardType.js"; import Sphere from "../../artifact/js/Sphere.js"; import EntityFilter from "../../model/js/EntityFilter.js"; import RangeFilter from "../../model/js/RangeFilter.js"; import Button from "../../view/js/Button.js"; import InputPanel from "../../view/js/InputPanel.js"; import Action from "./Action.js"; import DefaultFilters from "./DefaultFilters.js"; class FilterUI extends React.Component { constructor(props) { super(props); this.state = { sphereValues: (this.props.filters.sphereKey ? this.props.filters.sphereKey.values() : []), cardTypeValues: (this.props.filters.cardTypeKey ? this.props.filters.cardTypeKey.values() : []), cardSetValues: (this.props.filters.cardSetKey ? this.props.filters.cardSetKey.values() : []), cardSubsetValues: (this.props.filters.cardSubsetKey ? this.props.filters.cardSubsetKey.values() : []), isImplementedValues: (this.props.filters.isImplemented ? this.props.filters.isImplemented.values() : []), }; } render() { var cells = []; cells.push(ReactDOMFactories.td( { key: cells.length, }, this.createRangeTable())); cells.push(ReactDOMFactories.td( { key: cells.length, className: "f6 v-top", }, this.createEntityTable())); var rows = []; rows.push(ReactDOMFactories.tr( { key: rows.length, }, cells)); rows.push(ReactDOMFactories.tr( { key: rows.length, }, ReactDOMFactories.td( { colSpan: 5, }, this.createButtonTable()))); return ReactDOMFactories.table( { className: "f6 v-top", }, ReactDOMFactories.tbody( {}, rows)); } createButtonTable() { var restoreButton = React.createElement(Button, { name: "Restore Defaults", onClick: this.restoreActionPerformed, }); var unfilterButton = React.createElement(Button, { name: "Remove Filter", onClick: this.unfilterActionPerformed, }); var filterButton = React.createElement(Button, { name: "Apply Filter", onClick: this.filterActionPerformed, }); var cells = []; cells.push(ReactDOMFactories.td( { key: cells.length, }, restoreButton)); cells.push(ReactDOMFactories.td( { key: cells.length, }, unfilterButton)); cells.push(ReactDOMFactories.td( { key: cells.length, }, filterButton)); var row = ReactDOMFactories.tr( {}, cells); return ReactDOMFactories.table( {}, ReactDOMFactories.tbody( {}, row)); } createEntityTable() { var cells = []; DefaultFilters.entityColumns.forEach(function(column) { var values; var labelFunction; var clientProps = {}; switch (column.key) { case "sphereKey": values = Sphere.keys(); labelFunction = function(value) { return Sphere.properties[value].name; }; clientProps["data-entitytype"] = "sphereKey"; break; case "cardTypeKey": values = [CardType.ALLY, CardType.ATTACHMENT, CardType.EVENT, CardType.HERO]; labelFunction = function(value) { return CardType.properties[value].name; }; clientProps["data-entitytype"] = "cardTypeKey"; break; case "cardSetKey": values = CardSet.keys(); labelFunction = function(value) { return CardSet.properties[value].name; }; clientProps["data-entitytype"] = "cardSetKey"; break; case "cardSubsetKey": values = CardSubset.keys(); labelFunction = function(value) { return (CardSubset.properties[value] ? CardSubset.properties[value].name : undefined); }; clientProps["data-entitytype"] = "cardSubsetKey"; break; case "isImplemented": values = [true, false]; labelFunction = function(value) { return (value ? "true" : "false"); }; clientProps["data-entitytype"] = "isImplemented"; break; default: throw "Unknown entity column: " + column.key; } var oldFilter = this.context.store.getState().filters[column.key]; var initialValues = []; if (oldFilter) { initialValues = initialValues.concat(oldFilter.values()); } var label = ReactDOMFactories.span( { className: "b f6", }, column.label); var checkboxPanel = React.createElement(InputPanel, { type: InputPanel.Type.CHECKBOX, values: values, labelFunction: labelFunction, initialValues: initialValues, onChange: this.handleEntityChange, panelClass: "bg-white f7 tl", clientProps: clientProps, }); cells.push(ReactDOMFactories.td( { key: cells.length, className: "pl1 v-top", }, label, ReactDOMFactories.div( { className: "entitiesContainer overflow-y-auto pl1", }, checkboxPanel))); }, this); var row = ReactDOMFactories.tr( {}, cells); return ReactDOMFactories.table( { className: "f6 v-top", }, ReactDOMFactories.tbody( {}, row)); } createRangeTable() { var rows = []; DefaultFilters.rangeColumns.forEach(function(column) { var filter = this.props.filters[column.key]; var cells = []; cells.push(ReactDOMFactories.td( { key: cells.length, }, ReactDOMFactories.input( { id: column.key + "MinChecked", type: "checkbox", defaultChecked: (filter ? filter.isMinEnabled() : false), onChange: this.handleRangeChange, }))); cells.push(ReactDOMFactories.td( { key: cells.length, }, ReactDOMFactories.input( { id: column.key + "Min", type: "number", className: "filterField", defaultValue: (filter ? filter.minValue() : 0), onChange: this.handleRangeChange, }))); cells.push(ReactDOMFactories.td( { key: cells.length, }, "\u2264 " + column.label + " \u2264")); cells.push(ReactDOMFactories.td( { key: cells.length, }, ReactDOMFactories.input( { id: column.key + "MaxChecked", type: "checkbox", defaultChecked: (filter ? filter.isMaxEnabled() : false), onChange: this.handleRangeChange, }))); cells.push(ReactDOMFactories.td( { key: cells.length, }, ReactDOMFactories.input( { id: column.key + "Max", type: "number", className: "filterField", defaultValue: (filter ? filter.maxValue() : 10), onChange: this.handleRangeChange, }))); rows.push(ReactDOMFactories.tr( { key: rows.length, className: "striped--light-gray", }, cells)); }, this); return ReactDOMFactories.table( { className: "bg-white", }, ReactDOMFactories.tbody( {}, rows)); } filterActionPerformed() { LOGGER.trace("FilterUI.filterActionPerformed() start"); var filters = {}; DefaultFilters.entityColumns.forEach(function(column) { var values = []; switch (column.key) { case "sphereKey": values = values.concat(this.state.sphereValues); break; case "cardTypeKey": values = values.concat(this.state.cardTypeValues); break; case "cardSetKey": values = values.concat(this.state.cardSetValues); break; case "cardSubsetKey": values = values.concat(this.state.cardSubsetValues); break; case "isImplemented": values = values.concat(this.state.isImplementedValues); break; default: throw "Unknown entity column: " + column.key; } var filter = new EntityFilter(column.key, values); filters[column.key] = filter; }, this); DefaultFilters.rangeColumns.forEach(function(column) { var isMinEnabled = document.getElementById(column.key + "MinChecked").checked; var minValue = document.getElementById(column.key + "Min").value; var isMaxEnabled = document.getElementById(column.key + "MaxChecked").checked; var maxValue = document.getElementById(column.key + "Max").value; var filter = new RangeFilter(column.key, isMinEnabled, minValue, isMaxEnabled, maxValue); filters[column.key] = filter; }); this.context.store.dispatch(Action.setFilters(filters)); LOGGER.trace("FilterUI.filterActionPerformed() end"); } handleEntityChange(event, selected) { LOGGER.trace("FilterUI.handleEntityChange() start"); var entityType = event.target.dataset.entitytype; LOGGER.debug("entityType = " + entityType); var values = []; values = values.concat(selected); switch (entityType) { case "sphereKey": this.setState( { sphereValues: values, }); break; case "cardTypeKey": this.setState( { cardTypeValues: values, }); break; case "cardSetKey": this.setState( { cardSetValues: values, }); break; case "cardSubsetKey": this.setState( { cardSubsetValues: values, }); break; case "isImplemented": this.setState( { isImplementedValues: values, }); break; default: throw "Unknown entityType: " + entityType; } LOGGER.trace("FilterUI.handleEntityChange() end"); } restoreActionPerformed() { LOGGER.trace("FilterUI.restoreActionPerformed() start"); this.context.store.dispatch(Action.setDefaultFilters()); LOGGER.trace("FilterUI.restoreActionPerformed() end"); } unfilterActionPerformed() { LOGGER.trace("FilterUI.unfilterActionPerformed() start"); this.context.store.dispatch(Action.removeFilters()); LOGGER.trace("FilterUI.unfilterActionPerformed() end"); } } FilterUI.contextTypes = { store: PropTypes.object.isRequired, }; FilterUI.propTypes = { filters: PropTypes.object.isRequired, }; export default FilterUI;
var searchData= [ ['operand',['Operand',['../class_operand.html',1,'']]], ['opexpression',['OPExpression',['../class_o_p_expression.html',1,'']]], ['opimmediate',['OPImmediate',['../class_o_p_immediate.html',1,'']]], ['oplabel',['OPLabel',['../class_o_p_label.html',1,'']]], ['opregister',['OPRegister',['../class_o_p_register.html',1,'']]] ];
function ResetAddForm() { $('#add-user div.modal-body form div div input#input-user-name').val(''); $('#add-user div.modal-body form div div textarea#input-user-description').val(''); $('#add-user div.modal-body form div div input#input-user-deletable').prop('checked', false); } function ResetEditForm() { $('#edit-user div.modal-body form div div input#input-user-id').val(''); $('#edit-user div.modal-body form div div input#input-user-name').val(''); $('#edit-user div.modal-body form div div textarea#input-user-description').val(''); $('#edit-user div.modal-body form div div input#input-user-deletable').prop('checked', false); } function ResetDeleteForm() { $('#del-user div.modal-body form div div input#input-user-id').val(''); $('#del-user div.modal-body form div div input#input-user-name').val(''); $('#del-user div.modal-body form div div textarea#input-user-description').val(''); $('#del-user div.modal-body form div div input#input-user-deletable').prop('checked', false); } function AddUser(parent, name, description, deletable, callback) { AsyncRPC('/admin/users/add', { parent: parent, name: name, description: description, deletable: deletable }, callback); } function EditUser(id, description, callback) { AsyncRPC('/admin/users/edit', { id: id, description: description }, callback); } function DeleteUser(id, callback) { AsyncRPC('/admin/users/delete', { id: id }, callback); } function ProcessUser(userList) { __elsaa_user_userList = userList; $('#userListBody').empty(); $.each(userList, function (index, item) { var deletable = __elsaa_user_perms["Delete User"]; var canModify = __elsaa_user_perms["Modify User"]; var buttonGroup = '<div class="btn-group btn-group-xs"><button class="btn btn-default modify-button" ' + (canModify ? '' : 'disabled') + ' data-user-id="' + item.ID + '" data-toggle="modify" data-target="#edit-user">Modify</button><button class="btn btn-default delete-button" ' + (deletable ? '' : 'disabled') + ' data-user-id="' + item.ID + '" data-toggle="modify" data-target="#del-user">Delete</button></div>'; var tr = $('<tr>').append( '<td><input type="checkbox" data-user-id="' + item.ID + '"></td><td>' + item.USERNAME + '</td><td>' + item.FULLNAME + '</td><td>' + item.EMAIL + '</td><td>' + item.TYPE + '</td><td>' + item.ACTIVE + '</td><td>' + buttonGroup + '</td>' ); tr.appendTo($('#userListBody')); }); BindModifyButtons(true); BindDeleteButtons(true); } $('#add-user div.modal-footer button#add-user-close-btn').click(function (e) { ResetAddForm(); }); $('#add-user div.modal-footer button#add-user-ok-btn').click(function (e) { var parent = $('#add-user div.modal-body form div div select#input-user-parent').select2('val'); var name = $('#add-user div.modal-body form div div input#input-user-name').val(); var description = $('#add-user div.modal-body form div div textarea#input-user-description').val(); var deletable = $('#add-user div.modal-body form div div input#input-user-deletable').is(':checked'); AddUser(parent, name, description, deletable, function (result) { if (result == true) { AsyncRPC('/admin/users/all', {}, function (result) { ProcessUser(result); }); } }); ResetAddForm(); }); $('#edit-user div.modal-footer button#edit-user-close-btn').click(function (e) { ResetEditForm(); }); $('#edit-user div.modal-footer button#edit-user-ok-btn').click(function (e) { var id = $('#edit-user div.modal-body form div div input#input-user-id').val(); var description = $('#edit-user div.modal-body form div div textarea#input-user-description').val(); EditUser(id, description, function (result) { if (result == true) { AsyncRPC('/admin/users/all', {}, function (result) { ProcessUser(result); }); } }); ResetEditForm(); }); $('#del-user div.modal-footer button#del-user-close-btn').click(function (e) { ResetDeleteForm(); }); $('#del-user div.modal-footer button#del-user-ok-btn').click(function (e) { var id = $('#del-user div.modal-body form div div input#input-user-id').val(); DeleteUser(id, function (result) { if (result == true) { AsyncRPC('/admin/users/all', {}, function (result) { ProcessUser(result); }); } }); ResetDeleteForm(); }); function BindModifyButtons(rebind) { $('.modify-button').unbind('click').bind({ 'click': function (e) { var btn = e.currentTarget; if (rebind) { $($(btn).data('target')).modal('show'); } var user = $.grep(__elsaa_user_userList, function (item, index) { return item.ID == $(btn).data('userId'); })[0]; $('#edit-user div.modal-body form div div input#input-user-id').val(user.ID); $('#edit-user div.modal-body form div div input#input-user-name').val(user.NAME); $('#edit-user div.modal-body form div div textarea#input-user-description').val(user.DESCRIPTION); $('#edit-user div.modal-body form div div input#input-user-deletable').prop('checked', user.DELETABLE == 1); } }); } function BindDeleteButtons(rebind) { $('.delete-button').unbind('click').bind({ 'click': function (e) { var btn = e.currentTarget; if (rebind) { $($(btn).data('target')).modal('show'); } var user = $.grep(__elsaa_user_userList, function (item, index) { return item.ID == $(btn).data('userId'); })[0]; $('#del-user div.modal-body form div div input#input-user-id').val(user.ID); $('#del-user div.modal-body form div div input#input-user-name').val(user.NAME); $('#del-user div.modal-body form div div textarea#input-user-description').val(user.DESCRIPTION); $('#del-user div.modal-body form div div input#input-user-deletable').prop('checked', user.DELETABLE == 1); } }); } BindModifyButtons(); BindDeleteButtons(); AsyncRPC('/admin/users/all', {}, function (result) { ProcessUser(result); });
export const compass2 = {"viewBox":"0 0 16 16","children":[{"name":"path","attribs":{"fill":"#000000","d":"M8 0c-4.418 0-8 3.582-8 8s3.582 8 8 8 8-3.582 8-8-3.582-8-8-8zM1.5 8c0-3.59 2.91-6.5 6.5-6.5 1.712 0 3.269 0.662 4.43 1.744l-6.43 2.756-2.756 6.43c-1.082-1.161-1.744-2.718-1.744-4.43zM9.143 9.143l-4.001 1.715 1.715-4.001 2.286 2.286zM8 14.5c-1.712 0-3.269-0.662-4.43-1.744l6.43-2.756 2.756-6.43c1.082 1.161 1.744 2.718 1.744 4.43 0 3.59-2.91 6.5-6.5 6.5z"}}]};
var mongoose = require('mongoose'); module.exports = function() { var schema = mongoose.Schema({ sport: { type: mongoose.Schema.ObjectId, required: true }, name: { type: String, required: true }, description: { type: String, required: true }, date_time: { type: Date, default: Date.now, required: true }, location: { type: String, required: true }, cost: { type: String } }); return mongoose.model('Event', schema); }; /* ------------------------------------------------------- //Exemple: //Collection "events" { sport: ObjectId("555a1a7ad84f00d15557a728"), name: "Pelagin", description: "Desfcription test - blablabla", date_time: "Mon Jan 02 2015 00:00:00 GMT+0100 (CET)", location: "Paula Ramos", cost: "R$10,00" } */
angular.module('jeecommerce') .controller('cuentaController', function($scope, $http){ $scope.modificarPerfil = function(){ var hayErrores = false; if ($scope.frmPerfil.$invalid) { alertify.error("El formulario contiene campos no válidos. Por favor, revise los campos."); hayErrores = true; return; } if (typeof $scope.email != 'undefined' && $scope.email.length < 6) { alertify.error("El campo <email> contiene fallos."); $('#email').addClass('ng-invalid'); hayErrores = true; } if (typeof $scope.contrasenaNueva != 'undefined') { if ($scope.contrasenaNueva.length < 6) { alertify.error('La longitud de su nueva contraseña debe ser mayor de 6'); $('#contrasenaNueva').addClass('ng-invalid'); hayErrores = true; } if (typeof $scope.contrasenaActual === 'undefined') { alertify.error('Debe introducir su contraseña actual para cambiar de contraseña'); $('#contrasenaActual').addClass('ng-invalid'); hayErrores = true; } if (typeof $scope.contrasenaNuevaConfirmar === 'undefined') { alertify.error('Debe confirmar su contraseña para modificar su perfil.'); $('#contrasenaNuevaConfirmar').addClass('ng-invalid') hayErrores = true; } } // Si hay errores, volver. if (hayErrores === true) return; // Si no hay errores modificar el perfil y hacer comprobación por parte del servidor $http({ method: 'POST', url: ABS_PATH + "/usuarios/perfil", data: { tipo: 'modificar', perfil: { correo: $('#email').val(), oldContrasena: $('#contrasenaActual').val(), newContrasena: $('#contrasenaNueva').val(), confirmContrasena: $('#contrasenaNuevaConfirmar').val() } } }).then(function successEditProfileCallback(response){ if (response.data.success) { alertify.success("Su cuenta ha sido modificada con éxito."); if (response.data.activacion) { $scope.cuentaNecesitaVerificacion = true; } } }, function errorEditProfileCallback(response){ alertify.error("Ha sucedido un error durante la modificación de su cuenta. Por favor inténtelo más tarde o contacte con nosotros"); }); }; $scope.modificarDireccion = function(did){ window.location.href = ABS_PATH + '/editar-direccion.html?did=' + did; }; });
import FlexItem from '../flex/FlexItem' export default FlexItem
// import rp from "request-promise"; import xhr from "xhr"; import SchedServerActionCreators from "../actions/schedServerActionCreators.js"; // TODO(pht) find how to clean that up const SCHED_API_URL = "http://localhost:8086/sched/api"; // The 'request promise' module seems to not be compilable anymore with // babel, so I use this small wrapper instead. function rp(options) { return new Promise(function (resolve, reject) { xhr(options, function (err, resp, body) { if (err) { reject(err); } else { if (resp.statusCode !== 200) { reject(resp); } else { resolve(body); } } }); }); } var SchedApi = { fetch(jobId) { return rp({ uri: SCHED_API_URL + "/job?jobId=" + jobId, method: "GET", json: true }).then(function(jobs) { if (jobs && jobs.length > 0) { SchedServerActionCreators.jobReceived(jobs[0]); } }); }, fetchAll() { return rp({ uri: SCHED_API_URL + "/job", method: "GET", json: true }).then(function (jobs) { SchedServerActionCreators.jobsReceived(jobs); }); }, delete(jobId) { return rp({ uri : SCHED_API_URL + "/job-def", method : "DELETE", json : { id : jobId } }).then(function () { SchedServerActionCreators.jobDeleted(jobId); }); }, unlock(jobId) { return rp({ uri : SCHED_API_URL + "/job-action/ack", method : "POST", json : { id : jobId } }).then(function () { // Or should we refetch the job ? // Or should the API return the new version of the job ? SchedServerActionCreators.jobUnlocked(jobId); }); }, trigger(jobId) { return rp({ uri : SCHED_API_URL + "/job-action/trigger", method : "POST", json : { id : jobId } }).then(function () { // Not sure if this one is usefull SchedServerActionCreators.jobTriggered(jobId); // Or should it be the store's job ? SchedApi.fetch(jobId); }); } }; export default SchedApi;
var newPlugin = require('./plugins').newPlugin; // Pixel restoration filters. See definitions.js. newPlugin('Blur(rd:, d:, b:MMX)'); newPlugin('Sharpen(rd:, d:, b:MMX)'); newPlugin('GeneralConvolution(i:bias, q:matrix, d:divisor, b:auto)'); newPlugin('SpatialSoften(ri:, ri:, ri:)'); newPlugin('TemporalSoften(ri:, ri:, ri:, i:scenechange, i:mode)'); newPlugin('FixBrokenChromaUpsampling');
'use strict' require('./check-versions')() process.env.NODE_ENV = 'production' const ora = require('ora') const rm = require('rimraf') const path = require('path') const chalk = require('chalk') const webpack = require('webpack') const config = require('../config') const webpackConfig = require('./webpack.prod.conf') const spinner = ora('building for production...') spinner.start() rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { if (err) throw err webpack(webpackConfig, (err, stats) => { spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n\n') if (stats.hasErrors()) { console.log(chalk.red(' Build failed with errors.\n')) process.exit(1) } console.log(chalk.cyan(' Build complete.\n')) console.log(chalk.yellow( ' Tip: built files are meant to be served over an HTTP server.\n' + ' Opening index.html over file:// won\'t work.\n' )) }) })
"use strict"; let axios = require("axios"); let cheerio = require("cheerio"); let url = require("../config").url; module.exports = { getLastDownloads() { return new Promise((resolve, reject) => { axios.get(url).then(response => { let $ = cheerio.load(response.data); let lastDownloads = $('.miniboxs.miniboxs-ficha li'); let downloads = []; for (let i = 0; i < lastDownloads.length; i++) { let download = {}; let $item = $(lastDownloads[i]); let relativeUrl = $item.find('a')[0].attribs.href; download.name = $item.find('a.nombre').text(); download.url = url + relativeUrl; download.id = relativeUrl.split('/')[2]; download.image = url + '/' + $item.find('img')[0].attribs.src; download.category = $item.find('span.categoria').text(); downloads.push(download); } resolve(downloads); }).catch(err => { reject(err); }); }); }, getTorrent(id) { return new Promise((resolve, reject) => { axios.get(url + '/torrent/' + id + '/').then(response => { let $ = cheerio.load(response.data); let $boxCard = $('#box-ficha'); let torrent = {}; torrent.title = $boxCard.find('h2').text(); torrent.image = url + '/' + $boxCard.find('img.imagen_ficha').attr('src'); torrent.description = $boxCard.find('.descrip').eq(1).text(); torrent.size = $boxCard.find('dt').filter((index, element) => $(element).text() === 'Tamaño').next().text(); torrent.category = $boxCard.find('dt').filter((index, element) => $(element).text() === 'Categoria').next().text(); let torrentUrls = $('a.enlace_torrent'); torrent.url = url + torrentUrls.get(1).attribs.href; torrent.magnet = torrentUrls.get(2).attribs.href; resolve(torrent); }).catch(err => { reject(err); }); }); }, search(query, page) { return new Promise((resolve, reject) => { let queryUrl = url + '/resultados/' + query; if (page) { queryUrl += '/pag:' + page; } axios.get(queryUrl).then(response => { let $ = cheerio.load(response.data); let searchResults = $('.miniboxs.miniboxs-ficha li'); let totalAux = $('.box-seccion .nav h3').text().split('(total ')[1]; let total = parseInt(totalAux.slice(0, totalAux.length - 1)); let downloads = []; for (let i = 0; i < searchResults.length; i++) { let result = {}; let $item = $(searchResults[i]); let relativeUrl = $item.find('a')[0].attribs.href; result.name = $item.find('a.nombre').text(); result.url = url + relativeUrl; result.id = relativeUrl.split('/')[2]; result.image = url + '/' + $item.find('img')[0].attribs.src; result.category = $item.find('span.categoria').text(); downloads.push(result); } resolve({ torrents: downloads, total: total }); }).catch(err => { reject(err); }); }); } };
import { define, render, WeElement } from '../../src/omi' define('my-component', class extends WeElement { static propTypes = { user: Object } render(props) { return ( <div>name: {props.user.name}, age: {props.user.age}</div> ) } })
var stream = require('stream'); var util = require('util'); var fs = require('fs'); var os = require('os'); var path = require('path'); var CRLF = "\r\n"; var MIMECHUNK = 76; // MIME standard wants 76 char chunks when sending out. var BASE64CHUNK= 24; // BASE64 bits needed before padding is used var MIME64CHUNK= MIMECHUNK * 6; // meets both base64 and mime divisibility var BUFFERSIZE = MIMECHUNK*24*7; // size of the message stream buffer var counter = 0; // support for nodejs without Buffer.concat native function if(!Buffer.concat) { require("bufferjs/concat"); } var generate_boundary = function() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'()+_,-./:=?"; for(var i=0; i < 69; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; }; var Message = function(headers) { this.attachments = []; this.alternative = null; this.header = {"message-id":"<" + (new Date()).getTime() + "." + (counter++) + "." + process.pid + "@" + os.hostname() +">"}; this.content = "text/plain; charset=utf-8"; for(var header in headers) { // allow user to override default content-type to override charset or send a single non-text message if(/^content-type$/i.test(header)) { this.content = headers[header]; } else if(header == 'text') { this.text = headers[header]; } else if(header == "attachment" && typeof (headers[header]) == "object") { if((headers[header]).constructor == Array) { var that = this; headers[header].forEach(function(attachment) { that.attach(attachment); }); } else { this.attach(headers[header]); } } else { // allow any headers the user wants to set?? // if(/cc|bcc|to|from|reply-to|sender|subject|date|message-id/i.test(header)) this.header[header.toLowerCase()] = headers[header]; } } }; Message.prototype = { attach: function(options) { /* legacy support, will remove eventually... arguments -> (path, type, name, headers) */ if (arguments.length > 1) options = {path:options, type:arguments[1], name:arguments[2]}; // sender can specify an attachment as an alternative if(options.alternative) { this.alternative = options; this.alternative.charset = options.charset || "utf-8"; this.alternative.type = options.type || "text/html"; this.alternative.inline = true; } else this.attachments.push(options); return this; }, /* legacy support, will remove eventually... should use Message.attach() instead */ attach_alternative: function(html, charset) { this.alternative = { data: html, charset: charset || "utf-8", type: "text/html", inline: true }; return this; }, valid: function(callback) { var self = this; if(!self.header.from) { callback(false, "message does not have a valid sender"); } if(!self.header.to) { callback(false, "message does not have a valid recipient"); } else if(self.attachments.length === 0) { callback(true); } else { var check = []; var failed = []; self.attachments.forEach(function(attachment, index) { if(attachment.path) { // migrating path->fs for existsSync) if(!(fs.existsSync || path.existsSync)(attachment.path)) failed.push(attachment.path + " does not exist"); } else if(attachment.stream) { if(!attachment.stream.readable) failed.push("attachment stream is not readable"); } else if(!attachment.data) { failed.push("attachment has no data associated with it"); } }); callback(failed.length === 0, failed.join(", ")); } }, stream: function() { return new MessageStream(this); }, read: function(callback) { var buffer = ""; var capture = function(data) { buffer += data; }; var output = function(err) { callback(err, buffer); }; var str = this.stream(); str.on('data', capture); str.on('end', output); str.on('error', output); } }; var MessageStream = function(message) { var self = this; stream.Stream.call(self); self.message = message; self.readable = true; self.paused = false; self.buffer = new Buffer(MIMECHUNK*24*7); self.bufferIndex = 0; var output_process = function(next, args) { if(self.paused) { self.resumed = function() { next.apply(null, args); }; } else { next.apply(null, args); } next.apply(null, args); }; var output_mixed = function() { var boundary = generate_boundary(); var data = ["Content-Type: multipart/mixed; boundary=\"", boundary, "\"", CRLF, CRLF, "--", boundary, CRLF]; output(data.join('')); if(!self.message.alternative) { output_text(self.message); output_message(boundary, self.message.attachments, 0, close); } else { output_alternative(self.message, function() { output_message(boundary, self.message.attachments, 0, close); }); } }; var output_message = function(boundary, list, index, callback) { if(index < list.length) { output(["--", boundary, CRLF].join('')); if(list[index].related) { output_related(list[index], function() { output_message(boundary, list, index + 1, callback); }); } else { output_attachment(list[index], function() { output_message(boundary, list, index + 1, callback); }); } } else { output([CRLF, "--", boundary, "--", CRLF, CRLF].join('')); callback(); } }; var output_attachment_headers = function(attachment) { var data = [], header, headers = { 'content-type': attachment.type + (attachment.charset ? "; charset=" + attachment.charset : ""), 'content-transfer-encoding': 'base64', 'content-disposition': attachment.inline ? 'inline' : 'attachment; filename="' + attachment.name + '"' }; for(header in (attachment.headers || {})) { // allow sender to override default headers headers[header.toLowerCase()] = attachment.headers[header]; } for(header in headers) { data = data.concat([header, ': ', headers[header], CRLF]); } output(data.concat([CRLF]).join('')); }; var output_attachment = function(attachment, callback) { var build = attachment.path ? output_file : attachment.stream ? output_stream : output_data; output_attachment_headers(attachment); build(attachment, callback); }; var output_data = function(attachment, callback) { output_base64(attachment.encoded ? attachment.data : new Buffer(attachment.data).toString("base64"), callback); }; var output_file = function(attachment, next) { var chunk = MIME64CHUNK*16; var buffer = new Buffer(chunk); var closed = function(fd) { fs.close(fd); }; var opened = function(err, fd) { if(!err) { var read = function(err, bytes) { if(!err && self.readable) { // guaranteed to be encoded without padding unless it is our last read output_base64(buffer.toString("base64", 0, bytes), function() { if(bytes == chunk) // we read a full chunk, there might be more { fs.read(fd, buffer, 0, chunk, null, read); } else // that was the last chunk, we are done reading the file { self.removeListener("error", closed); fs.close(fd, next); } }); } else { self.emit('error', err || {message:"message stream was interrupted somehow!"}); } }; fs.read(fd, buffer, 0, chunk, null, read); self.once("error", closed); } else self.emit('error', err); }; fs.open(attachment.path, 'r+', opened); }; var output_stream = function(attachment, callback) { if(attachment.stream.readable) { var previous = null; attachment.stream.resume(); attachment.stream.on('end', function() { output_base64((previous || new Buffer(0)).toString("base64"), callback); self.removeListener('pause', attachment.stream.pause); self.removeListener('resume', attachment.stream.resume); self.removeListener('error', attachment.stream.resume); }); attachment.stream.on('data', function(buffer) { // do we have bytes from a previous stream data event? if(previous) { var buffer2 = Buffer.concat([previous, buffer]); previous = null; // free up the buffer buffer = null; // free up the buffer buffer = buffer2; } var padded = buffer.length % (MIME64CHUNK); // encode as much of the buffer to base64 without empty bytes if(padded) { previous = new Buffer(padded); // copy dangling bytes into previous buffer buffer.copy(previous, 0, buffer.length - padded); } output_base64(buffer.toString("base64", 0, buffer.length - padded)); }); self.on('pause', attachment.stream.pause); self.on('resume', attachment.stream.resume); self.on('error', attachment.stream.resume); } else self.emit('error', {message:"stream not readable"}); }; var output_base64 = function(data, callback) { var loops = Math.floor(data.length / MIMECHUNK); var leftover= Math.abs(data.length - loops*MIMECHUNK); var loop = function(index) { if(index < loops) output(data.substring(MIMECHUNK * index, MIMECHUNK * (index + 1)) + CRLF, loop, [index + 1]); else if(leftover) output(data.substring(index*MIMECHUNK) + CRLF, callback); else if(callback) callback(); }; loop(0); }; var output_text = function(message) { var data = []; data = data.concat(["Content-Type:", message.content, CRLF, "Content-Transfer-Encoding: 7bit", CRLF]); data = data.concat(["Content-Disposition: inline", CRLF, CRLF]); data = data.concat([message.text || "", CRLF, CRLF]); output(data.join('')); }; var output_alternative = function(message, callback) { var data = [], boundary = generate_boundary(); data = data.concat(["Content-Type: multipart/alternative; boundary=\"", boundary, "\"", CRLF, CRLF]); data = data.concat(["--", boundary, CRLF]); output(data.join('')); output_text(message); output(["--", boundary, CRLF].join('')); var finish = function() { output([CRLF, "--", boundary, "--", CRLF, CRLF].join('')); callback(); }; if(message.alternative.related) { output_related(message.alternative, finish); } else { output_attachment(message.alternative, finish); } }; var output_related = function(message, callback) { var data = [], boundary = generate_boundary(); data = data.concat(["Content-Type: multipart/related; boundary=\"", boundary, "\"", CRLF, CRLF]); data = data.concat(["--", boundary, CRLF]); output(data.join('')); output_attachment(message, function() { output_message(boundary, message.related, 0, function() { output([CRLF, "--", boundary, "--", CRLF, CRLF].join('')); callback(); }); }); }; var output_header_data = function() { if(self.message.attachments.length || self.message.alternative) { output("MIME-Version: 1.0" + CRLF); output_mixed(); } else // you only have a text message! { output_text(self.message); close(); } }; var output_header = function() { var data = []; for(var header in self.message.header) { // do not output BCC in the headers... if(!(/bcc/i.test(header))) data = data.concat([header, ": ", self.message.header[header], CRLF]); } output(data.join('')); output_header_data(); }; var output = function(data, callback, args) { var bytes = Buffer.byteLength(data); // can we buffer the data? if(bytes + self.bufferIndex < self.buffer.length) { self.buffer.write(data, self.bufferIndex); self.bufferIndex += bytes; if(callback) callback.apply(null, args); } else if(bytes > self.buffer.length) { close({message:"internal buffer got too large to handle!"}); } else // we need to clean out the buffer, it is getting full { if(!self.paused) { self.emit('data', self.buffer.toString("utf-8", 0, self.bufferIndex)); self.buffer.write(data, 0); self.bufferIndex = bytes; // we could get paused after emitting data... if(self.paused) { self.once("resume", function() { callback.apply(null, args); }); } else if(callback) { callback.apply(null, args); } } else // we can't empty out the buffer, so let's wait till we resume before adding to it { self.once("resume", function() { output(data, callback, args); }); } } }; var close = function(err) { if(err) { self.emit("error", err); } else { self.emit('data', self.buffer.toString("utf-8", 0, self.bufferIndex)); self.emit('end'); } self.buffer = null; self.bufferIndex = 0; self.readable = false; self.removeAllListeners("resume"); self.removeAllListeners("pause"); self.removeAllListeners("error"); self.removeAllListeners("data"); self.removeAllListeners("end"); }; self.once("destroy", close); process.nextTick(output_header); }; util.inherits(MessageStream, stream.Stream); MessageStream.prototype.pause = function() { this.paused = true; this.emit('pause'); }; MessageStream.prototype.resume = function() { this.paused = false; this.emit('resume'); }; MessageStream.prototype.destroy = function() { this.emit("destroy", self.bufferIndex > 0 ? {message:"message stream destroyed"} : null); }; MessageStream.prototype.destroySoon = function() { this.emit("destroy"); }; exports.Message = Message; exports.BUFFERSIZE = BUFFERSIZE; exports.create = function(headers) { return new Message(headers); };
'use strict'; const fs = require('fs'), net = require('net'), filename = process.argv[2], server = net.createServer(function(connection) { // process called when connection is created // reporting console.log('Subscriber connected.'); connection.write(JSON.stringify({ type: 'watching', file: filename }) + '\n'); // watcher setup let watcher = fs.watch(filename, function() { connection.write(JSON.stringify({ type: 'changed', file: filename, timestamp: Date.now() }) + '\n'); }); // cleanup connection.on('close', function() { console.log('Subscriber disconnected.'); watcher.close(); }); }); if (!filename) { throw Error('No target filename was specified.'); } // here is the additional 'secret sauce' to clean up the socket process.on('SIGINT', function() { // event when process receives a signal (SIGINT) console.log('\nClosing socket'); // i.e. ctrl c to cancel the connection server.close(function() { process.exit(1) }); }); server.listen('/tmp/watcher.sock', function() { // unix network socket console.log('Listening for subscribers...'); // nc -U /tmp/watcher.sock in shell to connect });
(function ($) { // register namespace $.extend(true, window, { "Slick": { "CellExternalCopyManager": CellExternalCopyManager } }); function CellExternalCopyManager(options) { /* This manager enables users to copy/paste data from/to an external Spreadsheet application such as MS-Excel® or OpenOffice-Spreadsheet. Since it is not possible to access directly the clipboard in javascript, the plugin uses a trick to do it's job. After detecting the keystroke, we dynamically create a textarea where the browser copies/pastes the serialized data. options: copiedCellStyle : sets the css className used for copied cells. default : "copied" copiedCellStyleLayerKey : sets the layer key for setting css values of copied cells. default : "copy-manager" dataItemColumnValueExtractor : option to specify a custom column value extractor function dataItemColumnValueSetter : option to specify a custom column value setter function clipboardCommandHandler : option to specify a custom handler for paste actions includeHeaderWhenCopying : set to true and the plugin will take the name property from each column (which is usually what appears in your header) and put that as the first row of the text that's copied to the clipboard bodyElement: option to specify a custom DOM element which to will be added the hidden textbox. It's useful if the grid is inside a modal dialog. onCopyInit: optional handler to run when copy action initializes onCopySuccess: optional handler to run when copy action is complete newRowCreator: function to add rows to table if paste overflows bottom of table readOnlyMode: suppresses paste */ var _grid; var _self = this; var _copiedRanges; var _options = options || {}; var _copiedCellStyleLayerKey = _options.copiedCellStyleLayerKey || "copy-manager"; var _copiedCellStyle = _options.copiedCellStyle || "copied"; var _clearCopyTI = 0; var _bodyElement = _options.bodyElement || document.body; var _onCopyInit = _options.onCopyInit || null; var _onCopySuccess = _options.onCopySuccess || null; var keyCodes = { 'C': 67, 'V': 86, 'ESC': 27, 'INSERT': 45 }; function init(grid) { _grid = grid; _grid.onKeyDown.subscribe(handleKeyDown); // we need a cell selection model var cellSelectionModel = grid.getSelectionModel(); if (!cellSelectionModel){ throw new Error("Selection model is mandatory for this plugin. Please set a selection model on the grid before adding this plugin: grid.setSelectionModel(new Slick.CellSelectionModel())"); } // we give focus on the grid when a selection is done on it. // without this, if the user selects a range of cell without giving focus on a particular cell, the grid doesn't get the focus and key stroke handles (ctrl+c) don't work cellSelectionModel.onSelectedRangesChanged.subscribe(function(e, args){ if(!_options.noAutoFocus) { _grid.focus(); } }); } function destroy() { _grid.onKeyDown.unsubscribe(handleKeyDown); } function getDataItemValueForColumn(item, columnDef) { if (_options.dataItemColumnValueExtractor) { var dataItemColumnValueExtractorValue = _options.dataItemColumnValueExtractor(item, columnDef); if (dataItemColumnValueExtractorValue) return dataItemColumnValueExtractorValue; } var retVal = ''; // if a custom getter is not defined, we call serializeValue of the editor to serialize if (columnDef.editor){ var editorArgs = { 'container':$("<p>"), // a dummy container 'column':columnDef, 'position':{'top':0, 'left':0}, // a dummy position required by some editors 'grid':_grid }; var editor = new columnDef.editor(editorArgs); editor.loadValue(item); retVal = editor.serializeValue(); editor.destroy(); } else { retVal = item[columnDef.field]; } return retVal; } function setDataItemValueForColumn(item, columnDef, value) { if (_options.dataItemColumnValueSetter) { return _options.dataItemColumnValueSetter(item, columnDef, value); } // if a custom setter is not defined, we call applyValue of the editor to unserialize if (columnDef.editor){ var editorArgs = { 'container':$("body"), // a dummy container 'column':columnDef, 'position':{'top':0, 'left':0}, // a dummy position required by some editors 'grid':_grid }; var editor = new columnDef.editor(editorArgs); editor.loadValue(item); editor.applyValue(item, value); editor.destroy(); } } function _createTextBox(innerText){ var ta = document.createElement('textarea'); ta.style.position = 'absolute'; ta.style.left = '-1000px'; ta.style.top = document.body.scrollTop + 'px'; ta.value = innerText; _bodyElement.appendChild(ta); ta.select(); return ta; } function _decodeTabularData(_grid, ta){ var columns = _grid.getColumns(); var clipText = ta.value; var clipRows = clipText.split(/[\n\f\r]/); // trim trailing CR if present if (clipRows[clipRows.length - 1]=="") { clipRows.pop(); } var clippedRange = []; var j = 0; _bodyElement.removeChild(ta); for (var i=0; i<clipRows.length; i++) { if (clipRows[i]!="") clippedRange[j++] = clipRows[i].split("\t"); else clippedRange[i] = [""]; } var selectedCell = _grid.getActiveCell(); var ranges = _grid.getSelectionModel().getSelectedRanges(); var selectedRange = ranges && ranges.length ? ranges[0] : null; // pick only one selection var activeRow = null; var activeCell = null; if (selectedRange){ activeRow = selectedRange.fromRow; activeCell = selectedRange.fromCell; } else if (selectedCell){ activeRow = selectedCell.row; activeCell = selectedCell.cell; } else { // we don't know where to paste return; } var oneCellToMultiple = false; var destH = clippedRange.length; var destW = clippedRange.length ? clippedRange[0].length : 0; if (clippedRange.length == 1 && clippedRange[0].length == 1 && selectedRange){ oneCellToMultiple = true; destH = selectedRange.toRow - selectedRange.fromRow +1; destW = selectedRange.toCell - selectedRange.fromCell +1; } // var availableRows = _grid.getData().getLength() - activeRow; var addRows = 0; // if(availableRows < destH) // { // var d = _grid.getData(); // for(addRows = 1; addRows <= destH - availableRows; addRows++) // d.push({}); // _grid.setData(d); // _grid.render(); // } var overflowsBottomOfGrid = activeRow + destH > _grid.getDataLength(); if (_options.newRowCreator && overflowsBottomOfGrid) { var newRowsNeeded = activeRow + destH - _grid.getDataLength(); _options.newRowCreator(newRowsNeeded); } var clipCommand = { isClipboardCommand: true, clippedRange: clippedRange, oldValues: [], cellExternalCopyManager: _self, _options: _options, setDataItemValueForColumn: setDataItemValueForColumn, markCopySelection: markCopySelection, oneCellToMultiple: oneCellToMultiple, activeRow: activeRow, activeCell: activeCell, destH: destH, destW: destW, maxDestY: _grid.getDataLength(), maxDestX: _grid.getColumns().length, h: 0, w: 0, execute: function() { this.h=0; for (var y = 0; y < this.destH; y++){ this.oldValues[y] = []; this.w=0; this.h++; for (var x = 0; x < this.destW; x++){ this.w++; var desty = activeRow + y; var destx = activeCell + x; if (desty < this.maxDestY && destx < this.maxDestX ) { var nd = _grid.getCellNode(desty, destx); var dt = _grid.getDataItem(desty); this.oldValues[y][x] = dt[columns[destx]['field']]; if (oneCellToMultiple) this.setDataItemValueForColumn(dt, columns[destx], clippedRange[0][0]); else this.setDataItemValueForColumn(dt, columns[destx], clippedRange[y] ? clippedRange[y][x] : ''); _grid.updateCell(desty, destx); _grid.onCellChange.notify({ row: desty, cell: destx, item: dt, grid: _grid }); } } } var bRange = { 'fromCell': activeCell, 'fromRow': activeRow, 'toCell': activeCell+this.w-1, 'toRow': activeRow+this.h-1 } this.markCopySelection([bRange]); _grid.getSelectionModel().setSelectedRanges([bRange]); this.cellExternalCopyManager.onPasteCells.notify({ranges: [bRange]}); }, undo: function() { for (var y = 0; y < this.destH; y++){ for (var x = 0; x < this.destW; x++){ var desty = activeRow + y; var destx = activeCell + x; if (desty < this.maxDestY && destx < this.maxDestX ) { var nd = _grid.getCellNode(desty, destx); var dt = _grid.getDataItem(desty); if (oneCellToMultiple) this.setDataItemValueForColumn(dt, columns[destx], this.oldValues[0][0]); else this.setDataItemValueForColumn(dt, columns[destx], this.oldValues[y][x]); _grid.updateCell(desty, destx); _grid.onCellChange.notify({ row: desty, cell: destx, item: dt, grid: _grid }); } } } var bRange = { 'fromCell': activeCell, 'fromRow': activeRow, 'toCell': activeCell+this.w-1, 'toRow': activeRow+this.h-1 } this.markCopySelection([bRange]); _grid.getSelectionModel().setSelectedRanges([bRange]); this.cellExternalCopyManager.onPasteCells.notify({ranges: [bRange]}); if(addRows > 1){ var d = _grid.getData(); for(; addRows > 1; addRows--) d.splice(d.length - 1, 1); _grid.setData(d); _grid.render(); } } }; if(_options.clipboardCommandHandler) { _options.clipboardCommandHandler(clipCommand); } else { clipCommand.execute(); } } function handleKeyDown(e, args) { var ranges; if (!_grid.getEditorLock().isActive() || _grid.getOptions().autoEdit) { if (e.which == keyCodes.ESC) { if (_copiedRanges) { e.preventDefault(); clearCopySelection(); _self.onCopyCancelled.notify({ranges: _copiedRanges}); _copiedRanges = null; } } if ((e.which === keyCodes.C || e.which === keyCodes.INSERT) && (e.ctrlKey || e.metaKey) && !e.shiftKey) { // CTRL+C or CTRL+INS if (_onCopyInit) { _onCopyInit.call(); } ranges = _grid.getSelectionModel().getSelectedRanges(); if (ranges.length != 0) { _copiedRanges = ranges; markCopySelection(ranges); _self.onCopyCells.notify({ranges: ranges}); var columns = _grid.getColumns(); var clipText = ""; for (var rg = 0; rg < ranges.length; rg++){ var range = ranges[rg]; var clipTextRows = []; for (var i=range.fromRow; i< range.toRow+1 ; i++){ var clipTextCells = []; var dt = _grid.getDataItem(i); if (clipTextRows == "" && _options.includeHeaderWhenCopying) { var clipTextHeaders = []; for (var j = range.fromCell; j < range.toCell + 1 ; j++) { if (columns[j].name.length > 0) clipTextHeaders.push(columns[j].name); } clipTextRows.push(clipTextHeaders.join("\t")); } for (var j=range.fromCell; j< range.toCell+1 ; j++){ clipTextCells.push(getDataItemValueForColumn(dt, columns[j])); } clipTextRows.push(clipTextCells.join("\t")); } clipText += clipTextRows.join("\r\n") + "\r\n"; } if(window.clipboardData) { window.clipboardData.setData("Text", clipText); return true; } else { var focusEl = document.activeElement; var ta = _createTextBox(clipText); ta.focus(); setTimeout(function(){ _bodyElement.removeChild(ta); // restore focus if (focusEl) focusEl.focus(); else console.log("Not element to restore focus to after copy?"); }, 100); if (_onCopySuccess) { var rowCount = 0; // If it's cell selection, use the toRow/fromRow fields if (ranges.length === 1) { rowCount = (ranges[0].toRow + 1) - ranges[0].fromRow; } else { rowCount = ranges.length; } _onCopySuccess.call(this, rowCount); } return false; } } } if (!_options.readOnlyMode && ( (e.which === keyCodes.V && (e.ctrlKey || e.metaKey) && !e.shiftKey) || (e.which === keyCodes.INSERT && e.shiftKey && !e.ctrlKey) )) { // CTRL+V or Shift+INS var ta = _createTextBox(''); setTimeout(function(){ _decodeTabularData(_grid, ta); }, 100); return false; } } } function markCopySelection(ranges) { clearCopySelection(); var columns = _grid.getColumns(); var hash = {}; for (var i = 0; i < ranges.length; i++) { for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) { hash[j] = {}; for (var k = ranges[i].fromCell; k <= ranges[i].toCell && k<columns.length; k++) { hash[j][columns[k].id] = _copiedCellStyle; } } } _grid.setCellCssStyles(_copiedCellStyleLayerKey, hash); clearTimeout(_clearCopyTI); _clearCopyTI = setTimeout(function(){ _self.clearCopySelection(); }, 800); } function clearCopySelection() { _grid.removeCellCssStyles(_copiedCellStyleLayerKey); } $.extend(this, { "init": init, "destroy": destroy, "clearCopySelection": clearCopySelection, "handleKeyDown":handleKeyDown, "onCopyCells": new Slick.Event(), "onCopyCancelled": new Slick.Event(), "onPasteCells": new Slick.Event() }); } })(jQuery);
var searchData= [ ['feature',['feature',['../class_cell_geometry_animation.html#ac034a0c3200238ebfb525752fdff4bea',1,'CellGeometryAnimation']]], ['features',['features',['../class_gene.html#a555f8852e1dfda7c5ac9230dcd5a5cc8',1,'Gene::features()'],['../class_genome.html#a18edd762dd69f2f2d994142aa02ee8e3',1,'Genome::features()']]], ['figurehandle',['figureHandle',['../class_state_browser.html#a8c69a8eecc2f6fa4168c8e904ff6d448',1,'StateBrowser']]], ['finaltimeindexs',['finalTimeIndexs',['../class_condition.html#aecf5120c87e8430a84d1edc6efac07a1',1,'Condition']]], ['finaltimes',['finalTimes',['../class_stimuli.html#aeda99e0dc4ccc474735df674dabc8fd0',1,'Stimuli']]], ['fittedconstantnames',['fittedConstantNames',['../class_molecule_count_state.html#adbfbbc167f8464ad46d26ea53b6098aa',1,'MoleculeCountState::fittedConstantNames()'],['../class_process.html#a265625b65a935096ec937fee83591471',1,'Process::fittedConstantNames()']]], ['fittedconstantnames_5f_5f',['fittedConstantNames__',['../class_host_interaction.html#a0efa3df8246850564affdbdc3c1d1156',1,'HostInteraction::fittedConstantNames__()'],['../class_process.html#a43985f0d967338b6105351187510d6ec',1,'Process::fittedConstantNames__()']]], ['fiveprimecoordinate',['fivePrimeCoordinate',['../class_gene.html#a97d597ab9bbee18bd459daa3b3fcbc81',1,'Gene::fivePrimeCoordinate()'],['../class_genome_feature.html#ad888065f8fce97881d5ea3d860533b14',1,'GenomeFeature::fivePrimeCoordinate()']]], ['fixedconstantnames',['fixedConstantNames',['../class_molecule_count_state.html#ad7b9758ab3d39144e017e8b2af4e8050',1,'MoleculeCountState::fixedConstantNames()'],['../class_process.html#a455a0c3d9ea9d6ed8ea4047b3e7a2af8',1,'Process::fixedConstantNames()']]], ['fixedconstantnames_5f_5f',['fixedConstantNames__',['../class_host_interaction.html#aab55572e37cdbaf8fc4c4cf03c6c6494',1,'HostInteraction::fixedConstantNames__()'],['../class_process.html#a305a73769b0a84f30e5bf43cde8b7e3f',1,'Process::fixedConstantNames__()']]], ['fmethionineindexs',['fmethionineIndexs',['../class_knowledge_base.html#af52f780035ee5820408675845e6059e3',1,'KnowledgeBase']]], ['foldedsequence',['foldedSequence',['../class_protein_monomer.html#a93cd19a4c1511dc7bd3ea81f097322cd',1,'ProteinMonomer']]], ['foldedsequencebasecount',['foldedSequenceBaseCount',['../class_protein_monomer.html#a1ecdcc209d185e70e0d66b3aa893ed5c',1,'ProteinMonomer']]], ['foldedsequencedecayreaction',['foldedSequenceDecayReaction',['../class_protein_monomer.html#a1b97e4f4495e881d8b70be0d1c1fbd58',1,'ProteinMonomer']]], ['foldedsequencehalflife',['foldedSequenceHalfLife',['../class_protein_monomer.html#a920c5b709f370596afb0f2e71a2bebb1',1,'ProteinMonomer']]], ['foldedsequencelength',['foldedSequenceLength',['../class_protein_monomer.html#a7047572a7445322a068e7e9767c81f0b',1,'ProteinMonomer']]], ['foldedsequencemolecularweight',['foldedSequenceMolecularWeight',['../class_protein_monomer.html#a178738c9333e91fed77e14eb136be81d',1,'ProteinMonomer']]], ['for',['for',['../class_state_browser.html#a403dbb2003a31fb470b7a5064426e72d',1,'StateBrowser']]], ['framefilepattern',['frameFilePattern',['../class_animation.html#a56222bce86cf62631ebd1d1d56a40dac',1,'Animation::frameFilePattern()'],['../class_cell_geometry_animation.html#a0336d77e0cd80d693a166b3e811aeb0f',1,'CellGeometryAnimation::frameFilePattern()']]], ['frameformat',['frameFormat',['../class_animation.html#a4c705eb345d207fba994c17b4015663f',1,'Animation']]], ['frameformatoptions',['frameFormatOptions',['../class_animation.html#a0d42d0ef743888a1a46f1112fb45efe2',1,'Animation']]], ['framerate',['frameRate',['../class_animation.html#a07a13a691aa95d34d8b5634fdb0e9911',1,'Animation::frameRate()'],['../class_cell_geometry_animation.html#a43c535626730b1a9062b2200069fd25e',1,'CellGeometryAnimation::frameRate()']]], ['framerenderer',['frameRenderer',['../class_animation.html#a291afb97b3bcf5105a27bbf491588586',1,'Animation::frameRenderer()'],['../class_cell_geometry_animation.html#a3e973cd39da463caa06e9d3958815e1b',1,'CellGeometryAnimation::frameRenderer()']]], ['fullprecision',['fullPrecision',['../class_rand_stream.html#a3cc912a1047f6e981535ceaffd4c8870',1,'RandStream']]] ];
/* * This implements link hinting. Typing "F" will enter link-hinting mode, where all clickable items on the * page have a hint marker displayed containing a sequence of letters. Typing those letters will select a link. * * In our 'default' mode, the characters we use to show link hints are a user-configurable option. By default * they're the home row. The CSS which is used on the link hints is also a configurable option. * * In 'filter' mode, our link hints are numbers, and the user can narrow down the range of possibilities by * typing the text of the link itself. */ var linkHints = { hintMarkers: [], hintMarkerContainingDiv: null, // The characters that were typed in while in "link hints" mode. shouldOpenInNewTab: false, shouldOpenWithQueue: false, // flag for copying link instead of opening shouldCopyLinkUrl: false, // Whether link hint's "open in current/new tab" setting is currently toggled openLinkModeToggle: false, // Whether we have added to the page the CSS needed to display link hints. cssAdded: false, // While in delayMode, all keypresses have no effect. delayMode: false, // Handle the link hinting marker generation and matching. Must be initialized after settings have been // loaded, so that we can retrieve the option setting. markerMatcher: undefined, /* * To be called after linkHints has been generated from linkHintsBase. */ init: function() { this.onKeyDownInMode = this.onKeyDownInMode.bind(this); this.onKeyUpInMode = this.onKeyUpInMode.bind(this); this.markerMatcher = settings.get('filterLinkHints') == "true" ? filterHints : alphabetHints; }, /* * Generate an XPath describing what a clickable element is. * The final expression will be something like "//button | //xhtml:button | ..." */ clickableElementsXPath: (function() { var clickableElements = ["a", "area[@href]", "textarea", "button", "select", "input[not(@type='hidden')]", "*[@onclick or @tabindex or @role='link' or @role='button']"]; var xpath = []; for (var i in clickableElements) xpath.push("//" + clickableElements[i], "//xhtml:" + clickableElements[i]); return xpath.join(" | ") })(), // We need this as a top-level function because our command system doesn't yet support arguments. activateModeToOpenInNewTab: function() { this.activateMode(true, false, false); }, activateModeToCopyLinkUrl: function() { this.activateMode(false, false, true); }, activateModeWithQueue: function() { this.activateMode(true, true, false); }, activateMode: function(openInNewTab, withQueue, copyLinkUrl) { if (!this.cssAdded) addCssToPage(linkHintCss); // linkHintCss is declared by vimiumFrontend.js this.linkHintCssAdded = true; this.setOpenLinkMode(openInNewTab, withQueue, copyLinkUrl); this.buildLinkHints(); handlerStack.push({ // modeKeyHandler is declared by vimiumFrontend.js keydown: this.onKeyDownInMode, keyup: this.onKeyUpInMode }); this.openLinkModeToggle = false; }, setOpenLinkMode: function(openInNewTab, withQueue, copyLinkUrl) { this.shouldOpenInNewTab = openInNewTab; this.shouldOpenWithQueue = withQueue; this.shouldCopyLinkUrl = copyLinkUrl; if (this.shouldCopyLinkUrl) { HUD.show("Copy link URL to Clipboard"); } else if (this.shouldOpenWithQueue) { HUD.show("Open multiple links in a new tab"); } else { if (this.shouldOpenInNewTab) HUD.show("Open link in new tab"); else HUD.show("Open link in current tab"); } }, /* * Builds and displays link hints for every visible clickable item on the page. */ buildLinkHints: function() { var visibleElements = this.getVisibleClickableElements(); this.hintMarkers = this.markerMatcher.getHintMarkers(visibleElements); // Note(philc): Append these markers as top level children instead of as child nodes to the link itself, // because some clickable elements cannot contain children, e.g. submit buttons. This has the caveat // that if you scroll the page and the link has position=fixed, the marker will not stay fixed. // Also note that adding these nodes to document.body all at once is significantly faster than one-by-one. this.hintMarkerContainingDiv = document.createElement("div"); this.hintMarkerContainingDiv.className = "internalVimiumHintMarker"; for (var i = 0; i < this.hintMarkers.length; i++) this.hintMarkerContainingDiv.appendChild(this.hintMarkers[i]); // sometimes this is triggered before documentElement is created // TODO(int3): fail more gracefully? if (document.documentElement) document.documentElement.appendChild(this.hintMarkerContainingDiv); else this.deactivateMode(); }, /* * Returns all clickable elements that are not hidden and are in the current viewport. * We prune invisible elements partly for performance reasons, but moreso it's to decrease the number * of digits needed to enumerate all of the links on screen. */ getVisibleClickableElements: function() { var resultSet = document.evaluate(this.clickableElementsXPath, document.body, function(namespace) { return namespace == "xhtml" ? "http://www.w3.org/1999/xhtml" : null; }, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); var visibleElements = []; // Find all visible clickable elements. for (var i = 0, count = resultSet.snapshotLength; i < count; i++) { var element = resultSet.snapshotItem(i); // Note: this call will be expensive if we modify the DOM in between calls. var clientRect = element.getClientRects()[0]; if (this.isVisible(element, clientRect)) visibleElements.push({element: element, rect: clientRect}); // If the link has zero dimensions, it may be wrapping visible // but floated elements. Check for this. if (clientRect && (clientRect.width == 0 || clientRect.height == 0)) { for (var j = 0, childrenCount = element.children.length; j < childrenCount; j++) { var computedStyle = window.getComputedStyle(element.children[j], null); // Ignore child elements which are not floated and not absolutely positioned for parent elements with zero width/height if (computedStyle.getPropertyValue('float') == 'none' && computedStyle.getPropertyValue('position') != 'absolute') continue; var childClientRect = element.children[j].getClientRects()[0]; if (!this.isVisible(element.children[j], childClientRect)) continue; visibleElements.push({element: element.children[j], rect: childClientRect}); break; } } if (element.localName === "area") { var map = element.parentElement; var img = document.querySelector("img[usemap='#" + map.getAttribute("name") + "']"); var clientRect = img.getClientRects()[0]; var c = element.coords.split(/,/); var coords = [parseInt(c[0], 10), parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10)]; var rect = { top: clientRect.top + coords[1], left: clientRect.left + coords[0], right: clientRect.left + coords[2], bottom: clientRect.top + coords[3], width: coords[2] - coords[0], height: coords[3] - coords[1] }; visibleElements.push({element: element, rect: rect}); } } return visibleElements; }, /* * Returns true if element is visible. */ isVisible: function(element, clientRect) { // Exclude links which have just a few pixels on screen, because the link hints won't show for them // anyway. if (!clientRect || clientRect.top < 0 || clientRect.top >= window.innerHeight - 4 || clientRect.left < 0 || clientRect.left >= window.innerWidth - 4) return false; if (clientRect.width < 3 || clientRect.height < 3) return false; // eliminate invisible elements (see test_harnesses/visibility_test.html) var computedStyle = window.getComputedStyle(element, null); if (computedStyle.getPropertyValue('visibility') != 'visible' || computedStyle.getPropertyValue('display') == 'none') return false; return true; }, /* * Handles shift and esc keys. The other keys are passed to markerMatcher.matchHintsByKey. */ onKeyDownInMode: function(event) { if (this.delayMode) return; if (event.keyCode == keyCodes.shiftKey && !this.openLinkModeToggle) { // Toggle whether to open link in a new or current tab. this.setOpenLinkMode(!this.shouldOpenInNewTab, this.shouldOpenWithQueue, false); this.openLinkModeToggle = true; } // TODO(philc): Ignore keys that have modifiers. if (isEscape(event)) { this.deactivateMode(); } else { var keyResult = this.markerMatcher.matchHintsByKey(event, this.hintMarkers); var linksMatched = keyResult.linksMatched; var delay = keyResult.delay !== undefined ? keyResult.delay : 0; if (linksMatched.length == 0) { this.deactivateMode(); } else if (linksMatched.length == 1) { this.activateLink(linksMatched[0].clickableItem, delay); } else { for (var i in this.hintMarkers) this.hideMarker(this.hintMarkers[i]); for (var i in linksMatched) this.showMarker(linksMatched[i], this.markerMatcher.hintKeystrokeQueue.length); } } event.stopPropagation(); event.preventDefault(); }, onKeyUpInMode: function(event) { if (event.keyCode == keyCodes.shiftKey && this.openLinkModeToggle) { // Revert toggle on whether to open link in new or current tab. this.setOpenLinkMode(!this.shouldOpenInNewTab, this.shouldOpenWithQueue, false); this.openLinkModeToggle = false; } event.stopPropagation(); event.preventDefault(); }, /* * When only one link hint remains, this function activates it in the appropriate way. */ activateLink: function(matchedLink, delay) { var that = this; this.delayMode = true; if (this.isSelectable(matchedLink)) { this.simulateSelect(matchedLink); this.deactivateMode(delay, function() { that.delayMode = false; }); } else { if (this.shouldOpenWithQueue) { this.simulateClick(matchedLink); this.deactivateMode(delay, function() { that.delayMode = false; that.activateModeWithQueue(); }); } else if (this.shouldCopyLinkUrl) { this.copyLinkUrl(matchedLink); this.deactivateMode(delay, function() { that.delayMode = false; }); } else if (this.shouldOpenInNewTab) { this.simulateClick(matchedLink); matchedLink.focus(); this.deactivateMode(delay, function() { that.delayMode = false; }); } else { // When we're opening the link in the current tab, don't navigate to the selected link immediately; // we want to give the user some feedback depicting which link they've selected by focusing it. setTimeout(this.simulateClick.bind(this, matchedLink), 400); matchedLink.focus(); this.deactivateMode(delay, function() { that.delayMode = false; }); } } }, /* * Selectable means the element has a text caret; this is not the same as "focusable". */ isSelectable: function(element) { var selectableTypes = ["search", "text", "password"]; return (element.nodeName.toLowerCase() == "input" && selectableTypes.indexOf(element.type) >= 0) || element.nodeName.toLowerCase() == "textarea"; }, copyLinkUrl: function(link) { chrome.extension.sendRequest({handler: 'copyLinkUrl', data: link.href}); }, simulateSelect: function(element) { element.focus(); // When focusing a textbox, put the selection caret at the end of the textbox's contents. element.setSelectionRange(element.value.length, element.value.length); }, /* * Shows the marker, highlighting matchingCharCount characters. */ showMarker: function(linkMarker, matchingCharCount) { linkMarker.style.display = ""; for (var j = 0, count = linkMarker.childNodes.length; j < count; j++) linkMarker.childNodes[j].className = (j >= matchingCharCount) ? "" : "matchingCharacter"; }, hideMarker: function(linkMarker) { linkMarker.style.display = "none"; }, simulateClick: function(link) { var event = document.createEvent("MouseEvents"); // When "clicking" on a link, dispatch the event with the appropriate meta key (CMD on Mac, CTRL on windows) // to open it in a new tab if necessary. var metaKey = (platform == "Mac" && linkHints.shouldOpenInNewTab); var ctrlKey = (platform != "Mac" && linkHints.shouldOpenInNewTab); event.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0, ctrlKey, false, false, metaKey, 0, null); // Debugging note: Firefox will not execute the link's default action if we dispatch this click event, // but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately link.dispatchEvent(event); // TODO(int3): do this for @role='link' and similar elements as well var nodeName = link.nodeName.toLowerCase(); if (nodeName == 'a' || nodeName == 'button') link.blur(); }, /* * If called without arguments, it executes immediately. Othewise, it * executes after 'delay' and invokes 'callback' when it is finished. */ deactivateMode: function(delay, callback) { var that = this; function deactivate() { if (that.markerMatcher.deactivate) that.markerMatcher.deactivate(); if (that.hintMarkerContainingDiv) that.hintMarkerContainingDiv.parentNode.removeChild(that.hintMarkerContainingDiv); that.hintMarkerContainingDiv = null; that.hintMarkers = []; handlerStack.pop(); HUD.hide(); } // we invoke the deactivate() function directly instead of using setTimeout(callback, 0) so that // deactivateMode can be tested synchronously if (!delay) { deactivate(); if (callback) callback(); } else { setTimeout(function() { deactivate(); if (callback) callback(); }, delay); } }, }; var alphabetHints = { hintKeystrokeQueue: [], logXOfBase: function(x, base) { return Math.log(x) / Math.log(base); }, getHintMarkers: function(visibleElements) { //Initialize the number used to generate the character hints to be as many digits as we need to highlight //all the links on the page; we don't want some link hints to have more chars than others. var digitsNeeded = Math.ceil(this.logXOfBase( visibleElements.length, settings.get('linkHintCharacters').length)); var hintMarkers = []; for (var i = 0, count = visibleElements.length; i < count; i++) { var hintString = this.numberToHintString(i, digitsNeeded); var marker = hintUtils.createMarkerFor(visibleElements[i]); marker.innerHTML = hintUtils.spanWrap(hintString); marker.setAttribute("hintString", hintString); hintMarkers.push(marker); } return hintMarkers; }, /* * Converts a number like "8" into a hint string like "JK". This is used to sequentially generate all of * the hint text. The hint string will be "padded with zeroes" to ensure its length is equal to numHintDigits. */ numberToHintString: function(number, numHintDigits) { var base = settings.get('linkHintCharacters').length; var hintString = []; var remainder = 0; do { remainder = number % base; hintString.unshift(settings.get('linkHintCharacters')[remainder]); number -= remainder; number /= Math.floor(base); } while (number > 0); // Pad the hint string we're returning so that it matches numHintDigits. // Note: the loop body changes hintString.length, so the original length must be cached! var hintStringLength = hintString.length; for (var i = 0; i < numHintDigits - hintStringLength; i++) hintString.unshift(settings.get('linkHintCharacters')[0]); // Reversing the hint string has the advantage of making the link hints // appear to spread out after the first key is hit. This is helpful on a // page that has http links that are close to each other where link hints // of 2 characters or more occlude each other. hintString.reverse(); return hintString.join(""); }, matchHintsByKey: function(event, hintMarkers) { var linksMatched = hintMarkers; var keyChar = getKeyChar(event); if (!keyChar) return { 'linksMatched': linksMatched }; if (event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey) { if (this.hintKeystrokeQueue.length == 0) { var linksMatched = []; } else { this.hintKeystrokeQueue.pop(); var matchString = this.hintKeystrokeQueue.join(""); var linksMatched = linksMatched.filter(function(linkMarker) { return linkMarker.getAttribute("hintString").indexOf(matchString) == 0; }); } } else if (settings.get('linkHintCharacters').indexOf(keyChar) >= 0) { this.hintKeystrokeQueue.push(keyChar); var matchString = this.hintKeystrokeQueue.join(""); var linksMatched = linksMatched.filter(function(linkMarker) { return linkMarker.getAttribute("hintString").indexOf(matchString) == 0; }); } return { 'linksMatched': linksMatched }; }, deactivate: function() { this.hintKeystrokeQueue = []; } }; var filterHints = { hintKeystrokeQueue: [], linkTextKeystrokeQueue: [], labelMap: {}, /* * Generate a map of input element => label */ generateLabelMap: function() { var labels = document.querySelectorAll("label"); for (var i = 0, count = labels.length; i < count; i++) { var forElement = labels[i].getAttribute("for"); if (forElement) { var labelText = labels[i].textContent.trim(); // remove trailing : commonly found in labels if (labelText[labelText.length-1] == ":") labelText = labelText.substr(0, labelText.length-1); this.labelMap[forElement] = labelText; } } }, setMarkerAttributes: function(marker, linkHintNumber) { var hintString = (linkHintNumber + 1).toString(); var linkText = ""; var showLinkText = false; var element = marker.clickableItem; // toLowerCase is necessary as html documents return 'IMG' // and xhtml documents return 'img' var nodeName = element.nodeName.toLowerCase(); if (nodeName == "input") { if (this.labelMap[element.id]) { linkText = this.labelMap[element.id]; showLinkText = true; } else if (element.type != "password") { linkText = element.value; } // check if there is an image embedded in the <a> tag } else if (nodeName == "a" && !element.textContent.trim() && element.firstElementChild && element.firstElementChild.nodeName.toLowerCase() == "img") { linkText = element.firstElementChild.alt || element.firstElementChild.title; if (linkText) showLinkText = true; } else { linkText = element.textContent || element.innerHTML; } linkText = linkText.trim().toLowerCase(); marker.setAttribute("hintString", hintString); marker.innerHTML = hintUtils.spanWrap(hintString + (showLinkText ? ": " + linkText : "")); marker.setAttribute("linkText", linkText); }, getHintMarkers: function(visibleElements) { this.generateLabelMap(); var hintMarkers = []; for (var i = 0, count = visibleElements.length; i < count; i++) { var marker = hintUtils.createMarkerFor(visibleElements[i]); this.setMarkerAttributes(marker, i); hintMarkers.push(marker); } return hintMarkers; }, matchHintsByKey: function(event, hintMarkers) { var linksMatched = hintMarkers; var delay = 0; var keyChar = getKeyChar(event); if (event.keyCode == keyCodes.backspace || event.keyCode == keyCodes.deleteKey) { // backspace clears hint key queue first, then acts on link text key queue if (this.hintKeystrokeQueue.pop()) linksMatched = this.filterLinkHints(linksMatched); else if (this.linkTextKeystrokeQueue.pop()) linksMatched = this.filterLinkHints(linksMatched); else // both queues are empty. exit hinting mode linksMatched = []; } else if (event.keyCode == keyCodes.enter) { // activate the lowest-numbered link hint that is visible for (var i = 0, count = linksMatched.length; i < count; i++) if (linksMatched[i].style.display != 'none') { linksMatched = [ linksMatched[i] ]; break; } } else if (keyChar) { var matchString; if (/[0-9]/.test(keyChar)) { this.hintKeystrokeQueue.push(keyChar); matchString = this.hintKeystrokeQueue.join(""); linksMatched = linksMatched.filter(function(linkMarker) { return linkMarker.getAttribute('filtered') != 'true' && linkMarker.getAttribute("hintString").indexOf(matchString) == 0; }); } else { // since we might renumber the hints, the current hintKeyStrokeQueue // should be rendered invalid (i.e. reset). this.hintKeystrokeQueue = []; this.linkTextKeystrokeQueue.push(keyChar); linksMatched = this.filterLinkHints(linksMatched); } if (linksMatched.length == 1 && !/[0-9]/.test(keyChar)) { // In filter mode, people tend to type out words past the point // needed for a unique match. Hence we should avoid passing // control back to command mode immediately after a match is found. var delay = 200; } } return { 'linksMatched': linksMatched, 'delay': delay }; }, /* * Hides the links that do not match the linkText search string and marks them with the 'filtered' DOM * property. Renumbers the remainder. Should only be called when there is a change in * linkTextKeystrokeQueue, to avoid undesired renumbering. */ filterLinkHints: function(hintMarkers) { var linksMatched = []; var linkSearchString = this.linkTextKeystrokeQueue.join(""); for (var i = 0; i < hintMarkers.length; i++) { var linkMarker = hintMarkers[i]; var matchedLink = linkMarker.getAttribute("linkText").toLowerCase() .indexOf(linkSearchString.toLowerCase()) >= 0; if (!matchedLink) { linkMarker.setAttribute("filtered", "true"); } else { this.setMarkerAttributes(linkMarker, linksMatched.length); linkMarker.setAttribute("filtered", "false"); linksMatched.push(linkMarker); } } return linksMatched; }, deactivate: function(delay, callback) { this.hintKeystrokeQueue = []; this.linkTextKeystrokeQueue = []; this.labelMap = {}; } }; var hintUtils = { /* * Make each hint character a span, so that we can highlight the typed characters as you type them. */ spanWrap: function(hintString) { var innerHTML = []; for (var i = 0; i < hintString.length; i++) innerHTML.push("<span>" + hintString[i].toUpperCase() + "</span>"); return innerHTML.join(""); }, /* * Creates a link marker for the given link. */ createMarkerFor: function(link) { var marker = document.createElement("div"); marker.className = "internalVimiumHintMarker vimiumHintMarker"; marker.clickableItem = link.element; var clientRect = link.rect; marker.style.left = clientRect.left + window.scrollX + "px"; marker.style.top = clientRect.top + window.scrollY + "px"; return marker; } };
var gulp = require('gulp'); var rename = require('gulp-rename'); var sourcemaps = require('gulp-sourcemaps'); var uglify = require('gulp-uglify'); gulp.task('minify', function() { gulp.src('./dist/linq.js') .pipe(sourcemaps.init()) .pipe(uglify()) .pipe(rename('linq.min.js')) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist')); });
import $ from 'jquery/dist/jquery'; import {Socket} from './lib/socket'; import components from './components/index'; import api from './api/index'; // Open connection to server var connection = new Socket($('.status')); // Load components & apis components(connection); api(connection); // List active pens connection.connect().then(() => { window.periscope.pen.list(); });
var GlobalOffensive = require('./index.js'); GlobalOffensive.GCConnectionStatus = { HAVE_SESSION: 0, GC_GOING_DOWN: 1, NO_SESSION: 2, NO_SESSION_IN_LOGON_QUEUE: 3, NO_STEAM: 4 }; GlobalOffensive.ItemCustomizationNotification = { NameItem: 1006, UnlockCrate: 1007, XRayItemReveal: 1008, XRayItemClaim: 1009, CasketTooFull: 1011, CasketContents: 1012, CasketAdded: 1013, CasketRemoved: 1014, CasketInvFull: 1015, NameBaseItem: 1019, RemoveItemName: 1030, RemoveSticker: 1053, ApplySticker: 1086, StatTrakSwap: 1088, ActivateFanToken: 9178, ActivateOperationCoin: 9179, GraffitiUnseal: 9185, GenerateSouvenir: 9204 };
/* * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog * * Subdivision Geometry Modifier * using Catmull-Clark Subdivision Surfaces * for creating smooth geometry meshes * * Note: a modifier modifies vertices and faces of geometry, * so use geometry.clone() if original geometry needs to be retained * * Readings: * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/ * http://xrt.wikidot.com/blog:31 * "Subdivision Surfaces in Character Animation" * * (on boundary edges) * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description * * Supports: * Closed and Open geometries. * * TODO: * crease vertex and "semi-sharp" features * selective subdivision */ THREE.SubdivisionModifier = function ( subdivisions ) { this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions; // Settings this.useOldVertexColors = false; this.supportUVs = true; this.debug = false; }; // Applies the "modify" pattern THREE.SubdivisionModifier.prototype.modify = function ( geometry ) { var repeats = this.subdivisions; while ( repeats-- > 0 ) { this.smooth( geometry ); } }; /// REFACTORING THIS OUT THREE.GeometryUtils.orderedKey = function ( a, b ) { return Math.min( a, b ) + "_" + Math.max( a, b ); }; // Returns a hashmap - of { edge_key: face_index } THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) { var i, il, v1, v2, j, k, face, faceIndices, faceIndex, edge, hash, edgeFaceMap = {}; var orderedKey = THREE.GeometryUtils.orderedKey; function mapEdgeHash( hash, i ) { if ( edgeFaceMap[ hash ] === undefined ) { edgeFaceMap[ hash ] = []; } edgeFaceMap[ hash ].push( i ); } // construct vertex -> face map for( i = 0, il = geometry.faces.length; i < il; i ++ ) { face = geometry.faces[ i ]; if ( face instanceof THREE.Face3 ) { hash = orderedKey( face.a, face.b ); mapEdgeHash( hash, i ); hash = orderedKey( face.b, face.c ); mapEdgeHash( hash, i ); hash = orderedKey( face.c, face.a ); mapEdgeHash( hash, i ); } else if ( face instanceof THREE.Face4 ) { hash = orderedKey( face.a, face.b ); mapEdgeHash( hash, i ); hash = orderedKey( face.b, face.c ); mapEdgeHash( hash, i ); hash = orderedKey( face.c, face.d ); mapEdgeHash( hash, i ); hash = orderedKey( face.d, face.a ); mapEdgeHash( hash, i ); } } // extract faces // var edges = []; // // var numOfEdges = 0; // for (i in edgeFaceMap) { // numOfEdges++; // // edge = edgeFaceMap[i]; // edges.push(edge); // // } //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges); return edgeFaceMap; } ///////////////////////////// // Performs an iteration of Catmull-Clark Subdivision THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) { //debug( 'running smooth' ); // New set of vertices, faces and uvs var newVertices = [], newFaces = [], newUVs = []; function v( x, y, z ) { newVertices.push( new THREE.Vector3( x, y, z ) ); } var scope = this; var orderedKey = THREE.GeometryUtils.orderedKey; var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces; function assert() { if (scope.debug && console && console.assert) console.assert.apply(console, arguments); } function debug() { if (scope.debug) console.log.apply(console, arguments); } function warn() { if (console) console.log.apply(console, arguments); } function f4( a, b, c, d, oldFace, orders, facei ) { // TODO move vertex selection over here! var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex ); if (scope.useOldVertexColors) { newFace.vertexColors = []; var color, tmpColor, order; for (var i=0;i<4;i++) { order = orders[i]; color = new THREE.Color(), color.setRGB(0,0,0); for (var j=0, jl=0; j<order.length;j++) { tmpColor = oldFace.vertexColors[order[j]-1]; color.r += tmpColor.r; color.g += tmpColor.g; color.b += tmpColor.b; } color.r /= order.length; color.g /= order.length; color.b /= order.length; newFace.vertexColors[i] = color; } } newFaces.push( newFace ); if (scope.supportUVs) { var aUv = [ getUV(a, ''), getUV(b, facei), getUV(c, facei), getUV(d, facei) ]; if (!aUv[0]) debug('a :( ', a+':'+facei); else if (!aUv[1]) debug('b :( ', b+':'+facei); else if (!aUv[2]) debug('c :( ', c+':'+facei); else if (!aUv[3]) debug('d :( ', d+':'+facei); else newUVs.push( aUv ); } } var originalPoints = oldGeometry.vertices; var originalFaces = oldGeometry.faces; var originalVerticesLength = originalPoints.length; var newPoints = originalPoints.concat(); // New set of vertices to work on var facePoints = [], // these are new points on exisiting faces edgePoints = {}; // these are new points on exisiting edges var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them // TODO: handle this correctly. var uvForVertices = {}; // Stored in {vertex}:{old face} format function debugCoreStuff() { console.log('facePoints', facePoints, 'edgePoints', edgePoints); console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap); } function getUV(vertexNo, oldFaceNo) { var j,jl; var key = vertexNo+':'+oldFaceNo; var theUV = uvForVertices[key]; if (!theUV) { if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) { debug('face pt'); } else { debug('edge pt'); } warn('warning, UV not found for', key); return null; } return theUV; // Original faces -> Vertex Nos. // new Facepoint -> Vertex Nos. // edge Points } function addUV(vertexNo, oldFaceNo, value) { var key = vertexNo+':'+oldFaceNo; if (!(key in uvForVertices)) { uvForVertices[key] = value; } else { warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]); } } // Step 1 // For each face, add a face point // Set each face point to be the centroid of all original points for the respective face. // debug(oldGeometry); var i, il, j, jl, face; // For Uvs var uvs = oldGeometry.faceVertexUvs[0]; var abcd = 'abcd', vertice; debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength); if (scope.supportUVs) for (i=0, il = uvs.length; i<il; i++ ) { for (j=0,jl=uvs[i].length;j<jl;j++) { vertice = originalFaces[i][abcd.charAt(j)]; addUV(vertice, i, uvs[i][j]); } } if (uvs.length == 0) scope.supportUVs = false; // Additional UVs check, if we index original var uvCount = 0; for (var u in uvForVertices) { uvCount++; } if (!uvCount) { scope.supportUVs = false; debug('no uvs'); } var avgUv ; for (i=0, il = originalFaces.length; i<il ;i++) { face = originalFaces[ i ]; facePoints.push( face.centroid ); newPoints.push( face.centroid ); if (!scope.supportUVs) continue; // Prepare subdivided uv avgUv = new THREE.Vector2(); if ( face instanceof THREE.Face3 ) { avgUv.x = getUV( face.a, i ).x + getUV( face.b, i ).x + getUV( face.c, i ).x; avgUv.y = getUV( face.a, i ).y + getUV( face.b, i ).y + getUV( face.c, i ).y; avgUv.x /= 3; avgUv.y /= 3; } else if ( face instanceof THREE.Face4 ) { avgUv.x = getUV( face.a, i ).x + getUV( face.b, i ).x + getUV( face.c, i ).x + getUV( face.d, i ).x; avgUv.y = getUV( face.a, i ).y + getUV( face.b, i ).y + getUV( face.c, i ).y + getUV( face.d, i ).y; avgUv.x /= 4; avgUv.y /= 4; } addUV(originalVerticesLength + i, '', avgUv); } // Step 2 // For each edge, add an edge point. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]} var edge, faceIndexA, faceIndexB, avg; // debug('edgeFaceMap', edgeFaceMap); var edgeCount = 0; var edgeVertex, edgeVertexA, edgeVertexB; //// var vertexEdgeMap = {}; // Gives edges connecting from each vertex var vertexFaceMap = {}; // Gives faces connecting from each vertex function addVertexEdgeMap(vertex, edge) { if (vertexEdgeMap[vertex]===undefined) { vertexEdgeMap[vertex] = []; } vertexEdgeMap[vertex].push(edge); } function addVertexFaceMap(vertex, face, edge) { if (vertexFaceMap[vertex]===undefined) { vertexFaceMap[vertex] = {}; } vertexFaceMap[vertex][face] = edge; // vertexFaceMap[vertex][face] = null; } // Prepares vertexEdgeMap and vertexFaceMap for (i in edgeFaceMap) { // This is for every edge edge = edgeFaceMap[i]; edgeVertex = i.split('_'); edgeVertexA = edgeVertex[0]; edgeVertexB = edgeVertex[1]; // Maps an edgeVertex to connecting edges addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] ); addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] ); for (j=0,jl=edge.length;j<jl;j++) { face = edge[j]; addVertexFaceMap(edgeVertexA, face, i); addVertexFaceMap(edgeVertexB, face, i); } // {edge vertex: { face1: edge_key, face2: edge_key.. } } // this thing is fishy right now. if (edge.length < 2) { // edge is "sharp"; sharpEdges[i] = true; sharpVertices[edgeVertexA] = true; sharpVertices[edgeVertexB] = true; } } for (i in edgeFaceMap) { edge = edgeFaceMap[i]; faceIndexA = edge[0]; // face index a faceIndexB = edge[1]; // face index b edgeVertex = i.split('_'); edgeVertexA = edgeVertex[0]; edgeVertexB = edgeVertex[1]; avg = new THREE.Vector3(); //debug(i, faceIndexB,facePoints[faceIndexB]); assert(edge.length > 0, 'an edge without faces?!'); if (edge.length==1) { avg.add( originalPoints[ edgeVertexA ] ); avg.add( originalPoints[ edgeVertexB ] ); avg.multiplyScalar( 0.5 ); sharpVertices[newPoints.length] = true; } else { avg.add( facePoints[ faceIndexA ] ); avg.add( facePoints[ faceIndexB ] ); avg.add( originalPoints[ edgeVertexA ] ); avg.add( originalPoints[ edgeVertexB ] ); avg.multiplyScalar( 0.25 ); } edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount; newPoints.push( avg ); edgeCount ++; if (!scope.supportUVs) { continue; } // Prepare subdivided uv avgUv = new THREE.Vector2(); avgUv.x = getUV(edgeVertexA, faceIndexA).x + getUV(edgeVertexB, faceIndexA).x; avgUv.y = getUV(edgeVertexA, faceIndexA).y + getUV(edgeVertexB, faceIndexA).y; avgUv.x /= 2; avgUv.y /= 2; addUV(edgePoints[i], faceIndexA, avgUv); if (edge.length>=2) { assert(edge.length == 2, 'did we plan for more than 2 edges?'); avgUv = new THREE.Vector2(); avgUv.x = getUV(edgeVertexA, faceIndexB).x + getUV(edgeVertexB, faceIndexB).x; avgUv.y = getUV(edgeVertexA, faceIndexB).y + getUV(edgeVertexB, faceIndexB).y; avgUv.x /= 2; avgUv.y /= 2; addUV(edgePoints[i], faceIndexB, avgUv); } } debug('-- Step 2 done'); // Step 3 // For each face point, add an edge for every edge of the face, // connecting the face point to each edge point for the face. var facePt, currentVerticeIndex; var hashAB, hashBC, hashCD, hashDA, hashCA; var abc123 = ['123', '12', '2', '23']; var bca123 = ['123', '23', '3', '31']; var cab123 = ['123', '31', '1', '12']; var abc1234 = ['1234', '12', '2', '23']; var bcd1234 = ['1234', '23', '3', '34']; var cda1234 = ['1234', '34', '4', '41']; var dab1234 = ['1234', '41', '1', '12']; for (i=0, il = facePoints.length; i<il ;i++) { // for every face facePt = facePoints[i]; face = originalFaces[i]; currentVerticeIndex = originalVerticesLength+ i; if ( face instanceof THREE.Face3 ) { // create 3 face4s hashAB = orderedKey( face.a, face.b ); hashBC = orderedKey( face.b, face.c ); hashCA = orderedKey( face.c, face.a ); f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i ); f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i ); f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i ); } else if ( face instanceof THREE.Face4 ) { // create 4 face4s hashAB = orderedKey( face.a, face.b ); hashBC = orderedKey( face.b, face.c ); hashCD = orderedKey( face.c, face.d ); hashDA = orderedKey( face.d, face.a ); f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i ); f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i ); f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i ); f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i ); } else { debug('face should be a face!', face); } } newVertices = newPoints; // Step 4 // For each original point P, // take the average F of all n face points for faces touching P, // and take the average R of all n edge midpoints for edges touching P, // where each edge midpoint is the average of its two endpoint vertices. // Move each original point to the point var F = new THREE.Vector3(); var R = new THREE.Vector3(); var n; for (i=0, il = originalPoints.length; i<il; i++) { // (F + 2R + (n-3)P) / n if (vertexEdgeMap[i]===undefined) continue; F.set(0,0,0); R.set(0,0,0); var newPos = new THREE.Vector3(0,0,0); var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?) for (j in vertexFaceMap[i]) { F.add(facePoints[j]); f++; } var sharpEdgeCount = 0; n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges // Are we on the border? var boundary_case = f != n; // if (boundary_case) { // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2); // } for (j=0;j<n;j++) { if ( sharpEdges[ orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1]) ]) { sharpEdgeCount++; } } // if ( sharpEdgeCount==2 ) { // continue; // // Do not move vertex if there's 2 connecting sharp edges. // } /* if (sharpEdgeCount>2) { // TODO } */ F.divideScalar(f); var boundary_edges = 0; if (boundary_case) { var bb_edge; for (j=0; j<n;j++) { edge = vertexEdgeMap[i][j]; bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1 if (bb_edge) { var midPt = originalPoints[edge[0]].clone().add(originalPoints[edge[1]]).divideScalar(2); R.add(midPt); boundary_edges++; } } R.divideScalar(4); // console.log(j + ' --- ' + n + ' --- ' + boundary_edges); assert(boundary_edges == 2, 'should have only 2 boundary edges'); } else { for (j=0; j<n;j++) { edge = vertexEdgeMap[i][j]; var midPt = originalPoints[edge[0]].clone().add(originalPoints[edge[1]]).divideScalar(2); R.add(midPt); } R.divideScalar(n); } // Sum the formula newPos.add(originalPoints[i]); if (boundary_case) { newPos.divideScalar(2); newPos.add(R); } else { newPos.multiplyScalar(n - 3); newPos.add(F); newPos.add(R.multiplyScalar(2)); newPos.divideScalar(n); } newVertices[i] = newPos; } var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P newGeometry.vertices = newVertices; newGeometry.faces = newFaces; newGeometry.faceVertexUvs[ 0 ] = newUVs; delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P newGeometry.computeCentroids(); newGeometry.computeFaceNormals(); newGeometry.computeVertexNormals(); };
var React = require("react"), App = React.createFactory(require("../../components/app")); if (typeof window !== "undefined") { window.onload = function() { React.render(App(), document.getElementById("content")); }; }
export class FloatValueConverter { fromView(value) { const result = parseFloat(value) if (isNaN(result)) { return 0 } return result } }
import {observable} from 'mobservable' const counter = observable({ value: 0 }) export default counter
export { default as LoadingScreen } from './loading'
// Allows to use the standard jQuery API for cross-domain requests on IE8 define(['jquery'], function($) { if ( window.XDomainRequest ) { $.ajaxTransport(function( s ) { if ( s.crossDomain && s.async ) { if ( s.timeout ) { s.xdrTimeout = s.timeout; delete s.timeout; } var xdr; return { send: function( _, complete ) { function callback( status, statusText, responses, responseHeaders ) { xdr.onload = xdr.onerror = xdr.ontimeout = null; xdr = undefined; complete( status, statusText, responses, responseHeaders ); } xdr = new XDomainRequest(); xdr.contentType = "text/plain"; xdr.onload = function() { callback( 200, "OK", { text: xdr.responseText }, "Content-Type: " + xdr.contentType ); }; xdr.onerror = function() { callback( 404, "Not Found", { text: xdr.responseText } ); }; xdr.onprogress = function() {}; xdr.ontimeout = function() { callback( 0, "timeout" ); }; xdr.timeout = s.xdrTimeout || Number.MAX_VALUE; xdr.open( s.type, s.url ); xdr.send( ( s.hasContent && s.data ) || null ); } }; } }); } });
class dximagetransform_microsoft_crinset_1 { constructor() { // int Capabilities () {get} this.Capabilities = undefined; // float Duration () {get} {set} this.Duration = undefined; // float Progress () {get} {set} this.Progress = undefined; // float StepResolution () {get} this.StepResolution = undefined; } } module.exports = dximagetransform_microsoft_crinset_1;
(function() { var clone = fabric.util.object.clone; /** * IText class (introduced in <b>v1.4</b>) * @class fabric.IText * @extends fabric.Text * @mixes fabric.Observable * * @fires changed ("text:changed" when observing canvas) * @fires editing:entered ("text:editing:entered" when observing canvas) * @fires editing:exited ("text:editing:exited" when observing canvas) * * @return {fabric.IText} thisArg * @see {@link fabric.IText#initialize} for constructor definition * * <p>Supported key combinations:</p> * <pre> * Move cursor: left, right, up, down * Select character: shift + left, shift + right * Select text vertically: shift + up, shift + down * Move cursor by word: alt + left, alt + right * Select words: shift + alt + left, shift + alt + right * Move cursor to line start/end: cmd + left, cmd + right * Select till start/end of line: cmd + shift + left, cmd + shift + right * Jump to start/end of text: cmd + up, cmd + down * Select till start/end of text: cmd + shift + up, cmd + shift + down * Delete character: backspace * Delete word: alt + backspace * Delete line: cmd + backspace * Forward delete: delete * Copy text: ctrl/cmd + c * Paste text: ctrl/cmd + v * Cut text: ctrl/cmd + x * Select entire text: ctrl/cmd + a * </pre> * * <p>Supported mouse/touch combination</p> * <pre> * Position cursor: click/touch * Create selection: click/touch & drag * Create selection: click & shift + click * Select word: double click * Select line: triple click * </pre> */ fabric.IText = fabric.util.createClass(fabric.Text, fabric.Observable, /** @lends fabric.IText.prototype */ { /** * Type of an object * @type String * @default */ type: 'i-text', /** * Index where text selection starts (or where cursor is when there is no selection) * @type Nubmer * @default */ selectionStart: 0, /** * Index where text selection ends * @type Nubmer * @default */ selectionEnd: 0, /** * Color of text selection * @type String * @default */ selectionColor: 'rgba(17,119,255,0.3)', /** * Indicates whether text is in editing mode * @type Boolean * @default */ isEditing: false, /** * Indicates whether a text can be edited * @type Boolean * @default */ editable: true, /** * Border color of text object while it's in editing mode * @type String * @default */ editingBorderColor: 'rgba(102,153,255,0.25)', /** * Width of cursor (in px) * @type Number * @default */ cursorWidth: 2, /** * Color of default cursor (when not overwritten by character style) * @type String * @default */ cursorColor: '#333', /** * Delay between cursor blink (in ms) * @type Number * @default */ cursorDelay: 1000, /** * Duration of cursor fadein (in ms) * @type Number * @default */ cursorDuration: 600, /** * Object containing character styles * (where top-level properties corresponds to line number and 2nd-level properties -- to char number in a line) * @type Object * @default */ styles: null, /** * Indicates whether internal text char widths can be cached * @type Boolean * @default */ caching: true, /** * @private * @type Boolean * @default */ _skipFillStrokeCheck: true, /** * @private */ _reSpace: /\s|\n/, /** * @private */ _fontSizeFraction: 4, /** * @private */ _currentCursorOpacity: 0, /** * @private */ _selectionDirection: null, /** * @private */ _abortCursorAnimation: false, /** * @private */ _charWidthsCache: { }, /** * Constructor * @param {String} text Text string * @param {Object} [options] Options object * @return {fabric.IText} thisArg */ initialize: function(text, options) { this.styles = options ? (options.styles || { }) : { }; this.callSuper('initialize', text, options); this.initBehavior(); fabric.IText.instances.push(this); // caching this.__lineWidths = { }; this.__lineHeights = { }; this.__lineOffsets = { }; }, /** * Returns true if object has no styling */ isEmptyStyles: function() { if (!this.styles) return true; var obj = this.styles; for (var p1 in obj) { for (var p2 in obj[p1]) { /*jshint unused:false */ for (var p3 in obj[p1][p2]) { return false; } } } return true; }, /** * Sets selection start (left boundary of a selection) * @param {Number} index Index to set selection start to */ setSelectionStart: function(index) { this.selectionStart = index; this.hiddenTextarea && (this.hiddenTextarea.selectionStart = index); }, /** * Sets selection end (right boundary of a selection) * @param {Number} index Index to set selection end to */ setSelectionEnd: function(index) { this.selectionEnd = index; this.hiddenTextarea && (this.hiddenTextarea.selectionEnd = index); }, /** * Gets style of a current selection/cursor (at the start position) * @param {Number} [startIndex] Start index to get styles at * @param {Number} [endIndex] End index to get styles at * @return {Object} styles Style object at a specified (or current) index */ getSelectionStyles: function(startIndex, endIndex) { if (arguments.length === 2) { var styles = [ ]; for (var i = startIndex; i < endIndex; i++) { styles.push(this.getSelectionStyles(i)); } return styles; } var loc = this.get2DCursorLocation(startIndex); if (this.styles[loc.lineIndex]) { return this.styles[loc.lineIndex][loc.charIndex] || { }; } return { }; }, /** * Sets style of a current selection * @param {Object} [styles] Styles object * @return {fabric.IText} thisArg * @chainable */ setSelectionStyles: function(styles) { if (this.selectionStart === this.selectionEnd) { this._extendStyles(this.selectionStart, styles); } else { for (var i = this.selectionStart; i < this.selectionEnd; i++) { this._extendStyles(i, styles); } } return this; }, /** * @private */ _extendStyles: function(index, styles) { var loc = this.get2DCursorLocation(index); if (!this.styles[loc.lineIndex]) { this.styles[loc.lineIndex] = { }; } if (!this.styles[loc.lineIndex][loc.charIndex]) { this.styles[loc.lineIndex][loc.charIndex] = { }; } fabric.util.object.extend(this.styles[loc.lineIndex][loc.charIndex], styles); }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _render: function(ctx) { this.callSuper('_render', ctx); this.ctx = ctx; this.isEditing && this.renderCursorOrSelection(); }, /** * Renders cursor or selection (depending on what exists) */ renderCursorOrSelection: function() { if (!this.active) return; var chars = this.text.split(''), boundaries; if (this.selectionStart === this.selectionEnd) { boundaries = this._getCursorBoundaries(chars, 'cursor'); this.renderCursor(boundaries); } else { boundaries = this._getCursorBoundaries(chars, 'selection'); this.renderSelection(chars, boundaries); } }, /** * Returns 2d representation (lineIndex and charIndex) of cursor (or selection start) * @param {Number} [selectionStart] Optional index. When not given, current selectionStart is used. */ get2DCursorLocation: function(selectionStart) { if (typeof selectionStart === 'undefined') { selectionStart = this.selectionStart; } var textBeforeCursor = this.text.slice(0, selectionStart); var linesBeforeCursor = textBeforeCursor.split(this._reNewline); return { lineIndex: linesBeforeCursor.length - 1, charIndex: linesBeforeCursor[linesBeforeCursor.length - 1].length }; }, /** * Returns fontSize of char at the current cursor * @param {Number} lineIndex Line index * @param {Number} charIndex Char index * @return {Number} Character font size */ getCurrentCharFontSize: function(lineIndex, charIndex) { return ( this.styles[lineIndex] && this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)] && this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)].fontSize) || this.fontSize; }, /** * Returns color (fill) of char at the current cursor * @param {Number} lineIndex Line index * @param {Number} charIndex Char index * @return {String} Character color (fill) */ getCurrentCharColor: function(lineIndex, charIndex) { return ( this.styles[lineIndex] && this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)] && this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)].fill) || this.cursorColor; }, /** * Returns cursor boundaries (left, top, leftOffset, topOffset) * @private * @param {Array} chars Array of characters * @param {String} typeOfBoundaries */ _getCursorBoundaries: function(chars, typeOfBoundaries) { var cursorLocation = this.get2DCursorLocation(), textLines = this.text.split(this._reNewline), // left/top are left/top of entire text box // leftOffset/topOffset are offset from that left/top point of a text box left = Math.round(this._getLeftOffset()), top = -this.height / 2, offsets = this._getCursorBoundariesOffsets( chars, typeOfBoundaries, cursorLocation, textLines); return { left: left, top: top, leftOffset: offsets.left + offsets.lineLeft, topOffset: offsets.top }; }, /** * @private */ _getCursorBoundariesOffsets: function(chars, typeOfBoundaries, cursorLocation, textLines) { var lineLeftOffset = 0, lineIndex = 0, charIndex = 0, leftOffset = 0, topOffset = typeOfBoundaries === 'cursor' // selection starts at the very top of the line, // whereas cursor starts at the padding created by line height ? (this._getHeightOfLine(this.ctx, 0) - this.getCurrentCharFontSize(cursorLocation.lineIndex, cursorLocation.charIndex)) : 0; for (var i = 0; i < this.selectionStart; i++) { if (chars[i] === '\n') { leftOffset = 0; var index = lineIndex + (typeOfBoundaries === 'cursor' ? 1 : 0); topOffset += this._getCachedLineHeight(index); lineIndex++; charIndex = 0; } else { leftOffset += this._getWidthOfChar(this.ctx, chars[i], lineIndex, charIndex); charIndex++; } lineLeftOffset = this._getCachedLineOffset(lineIndex, textLines); } this._clearCache(); return { top: topOffset, left: leftOffset, lineLeft: lineLeftOffset }; }, /** * @private */ _clearCache: function() { this.__lineWidths = { }; this.__lineHeights = { }; this.__lineOffsets = { }; }, /** * @private */ _getCachedLineHeight: function(index) { return this.__lineHeights[index] || (this.__lineHeights[index] = this._getHeightOfLine(this.ctx, index)); }, /** * @private */ _getCachedLineWidth: function(lineIndex, textLines) { return this.__lineWidths[lineIndex] || (this.__lineWidths[lineIndex] = this._getWidthOfLine(this.ctx, lineIndex, textLines)); }, /** * @private */ _getCachedLineOffset: function(lineIndex, textLines) { var widthOfLine = this._getCachedLineWidth(lineIndex, textLines); return this.__lineOffsets[lineIndex] || (this.__lineOffsets[lineIndex] = this._getLineLeftOffset(widthOfLine)); }, /** * Renders cursor * @param {Object} boundaries */ renderCursor: function(boundaries) { var ctx = this.ctx; ctx.save(); var cursorLocation = this.get2DCursorLocation(), lineIndex = cursorLocation.lineIndex, charIndex = cursorLocation.charIndex, charHeight = this.getCurrentCharFontSize(lineIndex, charIndex); ctx.fillStyle = this.getCurrentCharColor(lineIndex, charIndex); ctx.globalAlpha = this._currentCursorOpacity; ctx.fillRect( boundaries.left + boundaries.leftOffset, boundaries.top + boundaries.topOffset, this.cursorWidth / this.scaleX, charHeight); ctx.restore(); }, /** * Renders text selection * @param {Array} chars Array of characters * @param {Object} boundaries Object with left/top/leftOffset/topOffset */ renderSelection: function(chars, boundaries) { var ctx = this.ctx; ctx.save(); ctx.fillStyle = this.selectionColor; var cursorLocation = this.get2DCursorLocation(), lineIndex = cursorLocation.lineIndex, charIndex = cursorLocation.charIndex, textLines = this.text.split(this._reNewline), origLineIndex = lineIndex; for (var i = this.selectionStart; i < this.selectionEnd; i++) { if (chars[i] === '\n') { boundaries.leftOffset = 0; boundaries.topOffset += this._getHeightOfLine(ctx, lineIndex); lineIndex++; charIndex = 0; } else if (i !== this.text.length) { var charWidth = this._getWidthOfChar(ctx, chars[i], lineIndex, charIndex), lineOffset = this._getLineLeftOffset(this._getWidthOfLine(ctx, lineIndex, textLines)) || 0; if (lineIndex === origLineIndex) { // only offset the line if we're rendering selection of 2nd, 3rd, etc. line lineOffset = 0; } ctx.fillRect( boundaries.left + boundaries.leftOffset + lineOffset, boundaries.top + boundaries.topOffset, charWidth, this._getHeightOfLine(ctx, lineIndex)); boundaries.leftOffset += charWidth; charIndex++; } } ctx.restore(); }, /** * @private * @param {String} method * @param {CanvasRenderingContext2D} ctx Context to render on */ _renderChars: function(method, ctx, line, left, top, lineIndex) { if (this.isEmptyStyles()) { return this._renderCharsFast(method, ctx, line, left, top); } this.skipTextAlign = true; // set proper box offset left -= this.textAlign === 'center' ? (this.width / 2) : (this.textAlign === 'right') ? this.width : 0; // set proper line offset var textLines = this.text.split(this._reNewline), lineWidth = this._getWidthOfLine(ctx, lineIndex, textLines), lineHeight = this._getHeightOfLine(ctx, lineIndex, textLines), lineLeftOffset = this._getLineLeftOffset(lineWidth), chars = line.split(''); left += lineLeftOffset || 0; ctx.save(); for (var i = 0, len = chars.length; i < len; i++) { this._renderChar(method, ctx, lineIndex, i, chars[i], left, top, lineHeight); } ctx.restore(); }, /** * @private * @param {String} method * @param {CanvasRenderingContext2D} ctx Context to render on * @param {String} line */ _renderCharsFast: function(method, ctx, line, left, top) { this.skipTextAlign = false; if (method === 'fillText' && this.fill) { this.callSuper('_renderChars', method, ctx, line, left, top); } if (method === 'strokeText' && this.stroke) { this.callSuper('_renderChars', method, ctx, line, left, top); } }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _renderChar: function(method, ctx, lineIndex, i, _char, left, top, lineHeight) { var decl, charWidth, charHeight; if (this.styles && this.styles[lineIndex] && (decl = this.styles[lineIndex][i])) { var shouldStroke = decl.stroke || this.stroke, shouldFill = decl.fill || this.fill; ctx.save(); charWidth = this._applyCharStylesGetWidth(ctx, _char, lineIndex, i, decl); charHeight = this._getHeightOfChar(ctx, _char, lineIndex, i); if (shouldFill) { ctx.fillText(_char, left, top); } if (shouldStroke) { ctx.strokeText(_char, left, top); } this._renderCharDecoration(ctx, decl, left, top, charWidth, lineHeight, charHeight); ctx.restore(); ctx.translate(charWidth, 0); } else { if (method === 'strokeText' && this.stroke) { ctx[method](_char, left, top); } if (method === 'fillText' && this.fill) { ctx[method](_char, left, top); } charWidth = this._applyCharStylesGetWidth(ctx, _char, lineIndex, i); this._renderCharDecoration(ctx, null, left, top, charWidth, lineHeight); ctx.translate(ctx.measureText(_char).width, 0); } }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _renderCharDecoration: function(ctx, styleDeclaration, left, top, charWidth, lineHeight, charHeight) { var textDecoration = styleDeclaration ? (styleDeclaration.textDecoration || this.textDecoration) : this.textDecoration; var fontSize = (styleDeclaration ? styleDeclaration.fontSize : null) || this.fontSize; if (!textDecoration) return; if (textDecoration.indexOf('underline') > -1) { this._renderCharDecorationAtOffset( ctx, left, top + (this.fontSize / this._fontSizeFraction), charWidth, 0, this.fontSize / 20 ); } if (textDecoration.indexOf('line-through') > -1) { this._renderCharDecorationAtOffset( ctx, left, top + (this.fontSize / this._fontSizeFraction), charWidth, charHeight / 2, fontSize / 20 ); } if (textDecoration.indexOf('overline') > -1) { this._renderCharDecorationAtOffset( ctx, left, top, charWidth, lineHeight - (this.fontSize / this._fontSizeFraction), this.fontSize / 20 ); } }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _renderCharDecorationAtOffset: function(ctx, left, top, charWidth, offset, thickness) { ctx.fillRect(left, top - offset, charWidth, thickness); }, /** * @private * @param {String} method * @param {CanvasRenderingContext2D} ctx Context to render on * @param {String} line */ _renderTextLine: function(method, ctx, line, left, top, lineIndex) { // to "cancel" this.fontSize subtraction in fabric.Text#_renderTextLine top += this.fontSize / 4; this.callSuper('_renderTextLine', method, ctx, line, left, top, lineIndex); }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on * @param {Array} textLines */ _renderTextDecoration: function(ctx, textLines) { if (this.isEmptyStyles()) { return this.callSuper('_renderTextDecoration', ctx, textLines); } }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on * @param {Array} textLines Array of all text lines */ _renderTextLinesBackground: function(ctx, textLines) { if (!this.textBackgroundColor && !this.styles) return; ctx.save(); if (this.textBackgroundColor) { ctx.fillStyle = this.textBackgroundColor; } var lineHeights = 0, fractionOfFontSize = this.fontSize / this._fontSizeFraction; for (var i = 0, len = textLines.length; i < len; i++) { var heightOfLine = this._getHeightOfLine(ctx, i, textLines); if (textLines[i] === '') { lineHeights += heightOfLine; continue; } var lineWidth = this._getWidthOfLine(ctx, i, textLines), lineLeftOffset = this._getLineLeftOffset(lineWidth); if (this.textBackgroundColor) { ctx.fillStyle = this.textBackgroundColor; ctx.fillRect( this._getLeftOffset() + lineLeftOffset, this._getTopOffset() + lineHeights + fractionOfFontSize, lineWidth, heightOfLine ); } if (this.styles[i]) { for (var j = 0, jlen = textLines[i].length; j < jlen; j++) { if (this.styles[i] && this.styles[i][j] && this.styles[i][j].textBackgroundColor) { var _char = textLines[i][j]; ctx.fillStyle = this.styles[i][j].textBackgroundColor; ctx.fillRect( this._getLeftOffset() + lineLeftOffset + this._getWidthOfCharsAt(ctx, i, j, textLines), this._getTopOffset() + lineHeights + fractionOfFontSize, this._getWidthOfChar(ctx, _char, i, j, textLines) + 1, heightOfLine ); } } } lineHeights += heightOfLine; } ctx.restore(); }, /** * @private */ _getCacheProp: function(_char, styleDeclaration) { return _char + styleDeclaration.fontFamily + styleDeclaration.fontSize + styleDeclaration.fontWeight + styleDeclaration.fontStyle + styleDeclaration.shadow; }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on * @param {String} _char * @param {Number} lineIndex * @param {Number} charIndex * @param {Object} [decl] */ _applyCharStylesGetWidth: function(ctx, _char, lineIndex, charIndex, decl) { var styleDeclaration = decl || (this.styles[lineIndex] && this.styles[lineIndex][charIndex]); if (styleDeclaration) { // cloning so that original style object is not polluted with following font declarations styleDeclaration = clone(styleDeclaration); } else { styleDeclaration = { }; } this._applyFontStyles(styleDeclaration); var cacheProp = this._getCacheProp(_char, styleDeclaration); // short-circuit if no styles if (this.isEmptyStyles() && this._charWidthsCache[cacheProp] && this.caching) { return this._charWidthsCache[cacheProp]; } if (typeof styleDeclaration.shadow === 'string') { styleDeclaration.shadow = new fabric.Shadow(styleDeclaration.shadow); } var fill = styleDeclaration.fill || this.fill; ctx.fillStyle = fill.toLive ? fill.toLive(ctx) : fill; if (styleDeclaration.stroke) { ctx.strokeStyle = (styleDeclaration.stroke && styleDeclaration.stroke.toLive) ? styleDeclaration.stroke.toLive(ctx) : styleDeclaration.stroke; } ctx.lineWidth = styleDeclaration.strokeWidth || this.strokeWidth; ctx.font = this._getFontDeclaration.call(styleDeclaration); this._setShadow.call(styleDeclaration, ctx); if (!this.caching) { return ctx.measureText(_char).width; } if (!this._charWidthsCache[cacheProp]) { this._charWidthsCache[cacheProp] = ctx.measureText(_char).width; } return this._charWidthsCache[cacheProp]; }, /** * @private * @param {Object} styleDeclaration */ _applyFontStyles: function(styleDeclaration) { if (!styleDeclaration.fontFamily) { styleDeclaration.fontFamily = this.fontFamily; } if (!styleDeclaration.fontSize) { styleDeclaration.fontSize = this.fontSize; } if (!styleDeclaration.fontWeight) { styleDeclaration.fontWeight = this.fontWeight; } if (!styleDeclaration.fontStyle) { styleDeclaration.fontStyle = this.fontStyle; } }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _getWidthOfChar: function(ctx, _char, lineIndex, charIndex) { ctx.save(); var width = this._applyCharStylesGetWidth(ctx, _char, lineIndex, charIndex); ctx.restore(); return width; }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _getHeightOfChar: function(ctx, _char, lineIndex, charIndex) { if (this.styles[lineIndex] && this.styles[lineIndex][charIndex]) { return this.styles[lineIndex][charIndex].fontSize || this.fontSize; } return this.fontSize; }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _getWidthOfCharAt: function(ctx, lineIndex, charIndex, lines) { lines = lines || this.text.split(this._reNewline); var _char = lines[lineIndex].split('')[charIndex]; return this._getWidthOfChar(ctx, _char, lineIndex, charIndex); }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _getHeightOfCharAt: function(ctx, lineIndex, charIndex, lines) { lines = lines || this.text.split(this._reNewline); var _char = lines[lineIndex].split('')[charIndex]; return this._getHeightOfChar(ctx, _char, lineIndex, charIndex); }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _getWidthOfCharsAt: function(ctx, lineIndex, charIndex, lines) { var width = 0; for (var i = 0; i < charIndex; i++) { width += this._getWidthOfCharAt(ctx, lineIndex, i, lines); } return width; }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _getWidthOfLine: function(ctx, lineIndex, textLines) { // if (!this.styles[lineIndex]) { // return this.callSuper('_getLineWidth', ctx, textLines[lineIndex]); // } return this._getWidthOfCharsAt(ctx, lineIndex, textLines[lineIndex].length, textLines); }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _getTextWidth: function(ctx, textLines) { if (this.isEmptyStyles()) { return this.callSuper('_getTextWidth', ctx, textLines); } var maxWidth = this._getWidthOfLine(ctx, 0, textLines); for (var i = 1, len = textLines.length; i < len; i++) { var currentLineWidth = this._getWidthOfLine(ctx, i, textLines); if (currentLineWidth > maxWidth) { maxWidth = currentLineWidth; } } return maxWidth; }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _getHeightOfLine: function(ctx, lineIndex, textLines) { textLines = textLines || this.text.split(this._reNewline); var maxHeight = this._getHeightOfChar(ctx, textLines[lineIndex][0], lineIndex, 0), line = textLines[lineIndex], chars = line.split(''); for (var i = 1, len = chars.length; i < len; i++) { var currentCharHeight = this._getHeightOfChar(ctx, chars[i], lineIndex, i); if (currentCharHeight > maxHeight) { maxHeight = currentCharHeight; } } return maxHeight * this.lineHeight; }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _getTextHeight: function(ctx, textLines) { var height = 0; for (var i = 0, len = textLines.length; i < len; i++) { height += this._getHeightOfLine(ctx, i, textLines); } return height; }, /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on */ _getTopOffset: function() { var topOffset = fabric.Text.prototype._getTopOffset.call(this); return topOffset - (this.fontSize / this._fontSizeFraction); }, /** * @private * This method is overwritten to account for different top offset */ _renderTextBoxBackground: function(ctx) { if (!this.backgroundColor) return; ctx.save(); ctx.fillStyle = this.backgroundColor; ctx.fillRect( this._getLeftOffset(), this._getTopOffset() + (this.fontSize / this._fontSizeFraction), this.width, this.height ); ctx.restore(); }, /** * Returns object representation of an instance * @methd toObject * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output * @return {Object} object representation of an instance */ toObject: function(propertiesToInclude) { return fabric.util.object.extend(this.callSuper('toObject', propertiesToInclude), { styles: clone(this.styles) }); } }); /** * Returns fabric.IText instance from an object representation * @static * @memberOf fabric.IText * @param {Object} object Object to create an instance from * @return {fabric.IText} instance of fabric.IText */ fabric.IText.fromObject = function(object) { return new fabric.IText(object.text, clone(object)); }; /** * Contains all fabric.IText objects that have been created * @static * @memberof fabric.IText * @type Array */ fabric.IText.instances = [ ]; })();
/** * Copyright (c) 2015-present, Alejandro Mantilla <@AlejoJamC>. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree or translated in the assets folder. */ var express = require('express'); var serviceRoutes = express.Router(); var request = require('request'); /* GET home page. */ serviceRoutes.get('/servicios', function (req, res) { res.render('services', { title : 'Servicios | Avaritia', level : '', processMessage: '', error: '', module: 'Servicios', moduleURL:'servicios', moduleDescription:'Lista de servicios', services : '' }); }); module.exports = serviceRoutes;
define(function () { function guid() { return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); }; return { guid: guid } });
export const download = {"viewBox":"0 0 20 20","children":[{"name":"path","attribs":{"d":"M15,7h-3V1H8v6H5l5,5L15,7z M19.338,13.532c-0.21-0.224-1.611-1.723-2.011-2.114C17.062,11.159,16.683,11,16.285,11h-1.757\r\n\tl3.064,2.994h-3.544c-0.102,0-0.194,0.052-0.24,0.133L12.992,16H7.008l-0.816-1.873c-0.046-0.081-0.139-0.133-0.24-0.133H2.408\r\n\tL5.471,11H3.715c-0.397,0-0.776,0.159-1.042,0.418c-0.4,0.392-1.801,1.891-2.011,2.114c-0.489,0.521-0.758,0.936-0.63,1.449\r\n\tl0.561,3.074c0.128,0.514,0.691,0.936,1.252,0.936h16.312c0.561,0,1.124-0.422,1.252-0.936l0.561-3.074\r\n\tC20.096,14.468,19.828,14.053,19.338,13.532z"}}]};
/** * Created by dust2 on 15-1-11. */ $(document).ready(function(){ //站点脚注时间 $('#currYear').empty().append(new Date().getFullYear()) //异步发送post请求,发送需截词文本 $("#seg-form").submit(function(event) { event.preventDefault(); var $form = $( this ); var term = $form.find( 'textarea' ).val(); var url = $form.attr( 'action' ); $.post( url, { 'text' : term}, function( data ) { $('#cut-text').empty().append(data); } ); }); //追加截词后文本在表单域中 $("#speech-form").submit(function(event) { var $form = $( this ); $(document).find('#selected-cut-speech').empty().append($(document).find('#cut-text').text()); //alert($(document).find('#selected-cut-speech').val()); }); $('#about').click(function(){ $('#info').remove(); $("<div class='row info' id='info'> <div class='col-md-8 col-md-offset-2'> <div class='alert alert-info row' role='alert'> <button class='close' type='button' data-dismiss='alert'></button>Text To Speech </div> </div> </div>") .insertAfter($('#title')); setTimeout("$('#info').slideUp('slow')", 5000); }); });
var gulp = require('gulp'); var elixir = require('laravel-elixir'); var svgmin = require('gulp-svgmin'); var svgstore = require('gulp-svgstore'); // var path = require('path'); var jade = require('gulp-jade'); elixir.config.assetsPath = 'src/assets'; elixir.config.publicPath = 'dist/assets'; elixir.config.production = false; elixir.config.sourcemaps = true; var paths = { jade: { src: 'src/jade/*.jade', dest: 'dist', }, stylesheets: { src: [ 'app.scss', ], dest: 'dist/assets/css', }, scripts: { src: [ 'app.js', ], dest: 'dist/assets/js', }, }; gulp.task('jade', function() { 'use strict'; return gulp .src(paths.jade.src) .pipe(jade({ pretty: true })) .pipe(gulp.dest(paths.jade.dest)); }); gulp.task('svg', function() { 'use strict'; return gulp .src('src/assets/imgs/svg/noteicon/*.svg') .pipe(svgmin({ plugins: [ { sortAttrs: true }, { transformsWithOnePath: true }, { collapseGroups: true }, { convertShapeToPath: true }, { mergePaths: true }, ], js2svg: { pretty: true }, })) .pipe(svgstore()) .pipe(gulp.dest('src/assets/imgs/svg')); }); elixir(function(mix) { 'use strict'; mix .sass(paths.stylesheets.src) .browserify(paths.scripts.src) .task('jade', paths.jade.src) .task('svg', 'src/assets/imgs/svg/*/*.svg'); });
-My build DIGITAL Command Language: -Muhammad Adi Nugroho,S.Adm.Neg.: -Via My Notepad (HTML Editor): -HAR: { "log": { "version": "1.2", "creator": { "name": "WebInspector", "version": "537.36" }, "pages": [], "entries": [ { "startedDateTime": "2016-04-17T17:17:54.623Z", "time": 294.2449999995915, "request": { "method": "GET", "url": "http://edge.quantserve.com/quant.js", "httpVersion": "unknown", "headers": [ { "name": "Accept", "value": "*/*" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36" } ], "queryString": [], "cookies": [], "headersSize": -1, "bodySize": 0 }, "response": { "status": 200, "statusText": "OK", "httpVersion": "unknown", "headers": [ { "name": "Date", "value": "Sat, 16 Apr 2016 17:44:28 GMT" }, { "name": "Cache-Control", "value": "private, max-age=86400" }, { "name": "Last-Modified", "value": "Fri, 26 Apr 2013 00:53:20 GMT" }, { "name": "Server", "value": "Apache" }, { "name": "Content-Type", "value": "application/x-javascript" }, { "name": "Content-Length", "value": "7874" }, { "name": "Expires", "value": "Sun, 17 Apr 2016 17:44:28 GMT" } ], "cookies": [], "content": { "size": 7874, "mimeType": "application/x-javascript" }, "redirectURL": "", "headersSize": -1, "bodySize": 0, "_transferSize": 0 }, "cache": {}, "timings": { "blocked": 120.640999999978, "dns": -1, "connect": -1, "send": 0, "wait": 144.365999999991, "receive": 29.237999999622502, "ssl": -1 } } ] } } -To be evaluated in console: var _qevents = _qevents || []; (function() { var elem = document.createElement('script'); elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") + ".quantserve.com/quant.js"; elem.async = true; elem.type = "text/javascript"; var scpt = document.getElementsByTagName('script')[0]; scpt.parentNode.insertBefore(elem, scpt); })(); _qevents.push({qacct:"p-areXX4VycFJp8"}); 2016-04-18 00:17:54.974 quant.js:3 Uncaught SecurityError: Failed to read the 'cookie' property from 'Document': Access is denied for this document.__qc.qcgc @ quant.js:3__qc.qcsc @ quant.js:6__qc.qcenqp @ quant.js:40__qc.quantserve @ quant.js:43quantserve @ quant.js:45(anonymous function) @ quant.js:46 2016-04-18 00:17:55.037 Error saving setting with name: consoleHistory, value length: 5235876. Error: Failed to set the 'consoleHistory' property on 'Storage': Setting the value of 'consoleHistory' exceeded the quota. 2016-04-18 00:17:55.053 Ten largest settings: 2016-04-18 00:17:55.229 Setting: 'consoleHistory', size: 5235397 2016-04-18 00:17:55.229 Setting: 'savedURLs', size: 3698 2016-04-18 00:17:55.229 Setting: 'previouslyViewedFiles', size: 3041 2016-04-18 00:17:55.229 Setting: 'breakpoints', size: 227 2016-04-18 00:17:55.230 Setting: 'eventListenerBreakpoints', size: 220 2016-04-18 00:17:55.231 Setting: 'watchExpressions', size: 45 2016-04-18 00:17:55.231 Setting: 'lastSelectedSourcesSidebarPaneTab', size: 7 2016-04-18 00:17:55.231 Setting: 'experiments', size: 2 2016-04-18 00:17:55.231 Setting: 'domBreakpoints', size: 2 2016-04-18 00:17:55.231 Setting: 'workspaceExcludedFolders', size: 2 1
import React from 'react' import { Button, Title, Paragraph, Modal, Marger } from 'kitten' import { DocsPage } from 'storybook/docs-page' const paragraphContainer = ` Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? ` const StoryContent = ({ content }) => ( <Marger top="8" bottom="8"> <Marger bottom="2"> <Title modifier="tertiary" noMargin tag="p"> Lorem ipsum dolor sit consectetuer </Title> </Marger> <Marger top="2" bottom="4"> <Paragraph modifier="secondary" noMargin tag="p"> {content} </Paragraph> </Marger> <Marger top="4" bottom="10"> <Button modifier="helium" size="big"> Action 1 Button </Button> </Marger> </Marger> ) const StoryButton = ({ children }) => ( <Button modifier="helium">{children}</Button> ) export default { title: 'Layer/Modal', component: Modal, parameters: { docs: { page: () => <DocsPage filepath={__filename} importString="Modal" />, }, }, decorators: [ story => <div className="story-Container story-Grid">{story()}</div>, ], } export const OldModal = () => ( <> <p className="k-u-weight-light"> This Modal will be deprecated in the future. </p> <Modal closeButtonLabel="Fermer" trigger={<StoryButton children="Open" />} content={<StoryContent content={paragraphContainer} />} disableOutsideScroll /> </> )
function decodeUTF16(buff) { var dist = []; for (var cx = 0, dx = buff; cx < dx; cx += 2) { var m = (buff[cx] << 8) + buff[cx + 1]; var t; if (m > 0b1101111111111111 || m < 0b1101100000000000) { t = m; } else { var n = (buff[cx + 2] << 8) + buff[cx + 3]; if (n < 0b1101100000000000 || n > 0b1101111111111111) { continue; } cx += 2; if (m < n) { t = 10000 + ((m & 0b1111111111) << 10) + (n & 0b1111111111) } else { t = 10000 + ((n & 0b1111111111) << 10) + (m & 0b1111111111) } } dist.push(String.fromCodePoint(t)); } return dist.join(''); } module.exports = decodeUTF16;
import React from 'react'; import { shallow } from 'enzyme'; describe('(Component) Host', function() { it('should exist', function() { }); });
const postcss = require('postcss'); module.exports = postcss.plugin('postcss-precision', options => { options = options || {} options.units = options.units || '%|em|px|rem' options.precision = options.precision || 3 const isFloat = new RegExp(`([-+]?\\d*\\.\\d{${options.precision},})`, 'gi') const precision = Math.pow(10, options.precision) return function (css) { css.walkRules(function (rule) { rule.walkDecls(function (decl, i) { if (decl.value) { let value = decl.value let matches while ((matches = isFloat.exec(decl.value)) !== null) { const rounded = Math.round(parseFloat(matches[1]) * precision) / precision value = value.replace(matches[1], rounded.toString()) } decl.value = value } }) }) } })
var Tccc; (function (Tccc) { var AdminSchedulesController = /** @class */ (function () { function AdminSchedulesController(scheduleApi, talkApi, $routeParams) { this.scheduleApi = scheduleApi; this.talkApi = talkApi; this.$routeParams = $routeParams; this.hasLoadedSchedule = false; this.talks = []; var eventNumber = $routeParams["eventNumber"]; this.eventId = "events/" + eventNumber; } Object.defineProperty(AdminSchedulesController.prototype, "canAddSchedule", { get: function () { return this.hasLoadedSchedule && !this.schedule; }, enumerable: true, configurable: true }); AdminSchedulesController.prototype.$onInit = function () { var _this = this; this.loadTalksForEvent(); this.scheduleApi.getScheduleForEvent(this.eventId) .then(function (result) { _this.hasLoadedSchedule = true; _this.schedule = result; }); }; AdminSchedulesController.prototype.addSchedule = function () { if (this.hasLoadedSchedule && !this.schedule) { var newSched = Tccc.Schedule.empty(); newSched.eventId = this.eventId; this.schedule = newSched; this.loadTalksForEvent(); } }; AdminSchedulesController.prototype.loadTalksForEvent = function () { var _this = this; this.talkApi.getTalks(this.eventId) .then(function (results) { return _this.talks = results.sort(function (a, b) { return a.title.localeCompare(b.title); }); }); }; AdminSchedulesController.prototype.addTimeslot = function () { if (this.schedule) { this.schedule.timeslots.push(new Tccc.ScheduleTimeslot({ start: 0, duration: 0, items: [] })); } }; AdminSchedulesController.prototype.removeTimeslot = function (timeslot) { if (this.schedule) { _.pull(this.schedule.timeslots, timeslot); } }; AdminSchedulesController.prototype.addTimeslotItem = function (timeslot) { timeslot.items.push(new Tccc.ScheduleItem({ author: "", room: "", talkId: "", title: "" })); }; AdminSchedulesController.prototype.removeTimeslotItem = function (item, timeslot) { _.pull(timeslot.items, item); }; AdminSchedulesController.prototype.saveSchedule = function () { var _this = this; if (this.schedule && !this.schedule.isSaving) { this.schedule.isSaving = true; this.scheduleApi.save(this.schedule) .then(function (result) { return angular.merge(_this.schedule, result); }) .finally(function () { return _this.schedule.isSaving = false; }); } }; AdminSchedulesController.prototype.talkSetForTimeslotItem = function (item) { if (item.talkId) { var talk = this.talks.find(function (t) { return t.id === item.talkId; }); if (talk) { item.title = talk.title; item.author = talk.author; } } }; AdminSchedulesController.$inject = [ "scheduleApi", "talkApi", "$routeParams" ]; return AdminSchedulesController; }()); Tccc.AdminSchedulesController = AdminSchedulesController; Tccc.App.controller("AdminSchedulesController", AdminSchedulesController); })(Tccc || (Tccc = {})); //# sourceMappingURL=AdminSchedulesController.js.map
function test() { var val1 = 'test'; var val2 = '["Headline 1","Headline 2","Headline 3"]'; var val3 = 'Headline 1'; var val4 = 'Headline 2'; var val5 = '{"nested":"object"}'; }
/* global describe, expect, it, jasmine */ var RecordHandler = require( '../../src/record/record-handler' ), msg = require( '../test-helper/test-helper' ).msg, StorageMock = require( '../mocks/storage-mock' ), SocketMock = require( '../mocks/socket-mock' ), SocketWrapper = require( '../../src/message/socket-wrapper' ), LoggerMock = require( '../mocks/logger-mock' ), noopMessageConnector = require( '../../src/default-plugins/noop-message-connector' ); describe( 'record handler handles messages', function(){ var recordHandler, subscribingClient = new SocketWrapper( new SocketMock(), {} ), listeningClient = new SocketWrapper( new SocketMock(), {} ), options = { cache: new StorageMock(), storage: new StorageMock(), logger: new LoggerMock(), messageConnector: noopMessageConnector }; it( 'creates the record handler', function(){ recordHandler = new RecordHandler( options ); expect( recordHandler.handle ).toBeDefined(); }); it( 'subscribes to record a and b', function() { recordHandler.handle( subscribingClient, { topic: 'R', action: 'CR', data: [ 'user/A' ] }); expect( subscribingClient.socket.lastSendMessage ).toBe( msg( 'R|R|user/A|0|{}+' ) ); recordHandler.handle( subscribingClient, { topic: 'R', action: 'CR', data: [ 'user/B' ] }); expect( subscribingClient.socket.lastSendMessage ).toBe( msg( 'R|R|user/B|0|{}+' ) ); }); it( 'registers a listener', function() { recordHandler.handle( listeningClient, { topic: 'R', action: 'L', data: [ 'user\/.*' ] }); expect( listeningClient.socket.getMsg( 2 ) ).toBe( msg( 'R|A|L|user\/.*+' ) ); expect( listeningClient.socket.getMsg( 1 ) ).toBe( msg( 'R|SP|user\/.*|user/A+' ) ); expect( listeningClient.socket.getMsg( 0 ) ).toBe( msg( 'R|SP|user\/.*|user/B+' ) ); }); it( 'makes a new subscription', function() { recordHandler.handle( subscribingClient, { topic: 'R', action: 'CR', data: [ 'user/C' ] }); expect( subscribingClient.socket.lastSendMessage ).toBe( msg( 'R|R|user/C|0|{}+' ) ); expect( listeningClient.socket.lastSendMessage ).toBe( msg( 'R|SP|user\/.*|user/C+' ) ); }); it( 'doesn\'t send messages for subsequent subscriptions', function(){ expect( listeningClient.socket.sendMessages.length ).toBe( 4 ); recordHandler.handle( subscribingClient, { topic: 'R', action: 'CR', data: [ 'user/C' ] }); expect( listeningClient.socket.sendMessages.length ).toBe( 4 ); }); it( 'removes listeners', function() { recordHandler.handle( listeningClient, { topic: 'R', action: 'UL', data: [ 'user\/.*' ] }); expect( listeningClient.socket.lastSendMessage ).toBe( msg( 'R|A|UL|user\/.*+' ) ); expect( listeningClient.socket.sendMessages.length ).toBe( 5 ); recordHandler.handle( subscribingClient, { topic: 'R', action: 'CR', data: [ 'user/D' ] }); expect( listeningClient.socket.sendMessages.length ).toBe( 5 ); }); });
//here we export the main object from the npm library //where we will convert it to an es module //below it is "chart.js" export {default} from "chart.js";
import ArticleMoveDialog from './article-move-dialog' export default ArticleMoveDialog
// Copyright 2016 David Lavieri. All rights reserved. // Use of this source code is governed by a MIT License // License that can be found in the LICENSE file. import * as types from './../constants/system_message'; const initialState = []; export {initialState}; export default (state = initialState, action) => { switch(action.type) { case types.ADD: { let match = false; const newState = state.map(message => { if(message.code === action.payload.code) { match = true; return { ...action.payload, count: message.count ? message.count + 1 : 1 } } return message; }); if(match) { return newState; } return [{ ...action.payload, count: 1 }, ...newState ]; } case types.DELETE: return state.filter(message => message.code !== action.payload); default: return state; } }
var mongoose = require('mongoose'), Schema = mongoose.Schema; var publicacionDisLikeSchema = new Schema({ id_publicacion: { type: String, required: true }, id_usuario: { type: String, required: true }, fechaCreacion: { type: Date, default: Date.now } }); module.exports = mongoose.model('publicacionDisLike', publicacionDisLikeSchema); var mongoose = require('mongoose');
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.7-5-b-28 description: > Object.defineProperties - 'descObj' is an Error object which implements its own [[Get]] method to get 'enumerable' property (8.10.5 step 3.a) includes: [runTestCase.js] ---*/ function testcase() { var obj = {}; var descObj = new Error(); var accessed = false; descObj.enumerable = true; Object.defineProperties(obj, { prop: descObj }); for (var property in obj) { if (property === "prop") { accessed = true; } } return accessed; } runTestCase(testcase);
'use strict'; // setup ======================== var express = require('express'); var app = express.createServer(); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); //SET USER AND PASSWORD! var user = ""; var pass = ""; // configuration ================== app.use(express.static('./app')); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); mongoose.connect('mongodb://' + user + ':' + pass + '@ds054128.mongolab.com:54128/main_data'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log('Succesfully connected to mongolab'); }); // Schema settings ================================ var Apartments = mongoose.model('Apartment', { "address": { "description": String, "street": String, //"buildingnum": Number, "city": String }, "floornum": Number, "roomsNum": Number, "size": Number, "renov": String, "renovYear": Number, "other": String, 'doc_updated': Date, 'doc_created': { type: Date, default: Date.now } }); // writing to mongo example ================================ app.post('/api/newapt', function(req, res) { var item = new Apartments({ 'address': { 'description': req.body.address['description'], 'street': req.body.address['terms'][0].value, 'city': req.body.address['terms'][1].value }, "floornum": req.body.floornum, "roomsNum": req.body.roomsNum, "size": req.body.size, "renov": req.body.renov, "renovYear": req.body.renovYear, "other": req.body.other }); item.save(function(err) { if (err) { res.status(500).json({ error: "save failed", err: err }); return; } else { res.status(201).json(item); }; }) }); // run server ================================ var server = app.listen(5000, function() { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); });
/** * Cowboy is a powerful extension to Mootools Framework * @namespace cowboy namespace */ var cowboy = {}; /** * Extension to the Mootools Options * @class cowboy.Options * @implements {Options} */ cowboy.Options = new Class({ Implements: Options, /** * Extension to setOptions to get parameters from the element * @method setElementOptions * @param {Object} options Options of the class * @param {Element} element Element used by the class */ setElementOptions: function(options, element) { Object.keys(Object.clone(options)).each(function(property) { if(element.getProperty('data-' + property)) { options[property] = element.getProperty('data-' + property); } }); this.setOptions(options); } }); /** * Extension to Mootools Request to handle file upload * @class cowboy.Request * @extends {Request} * @link By mloberg : https://gist.github.com/mloberg/1342473 */ cowboy.Request = new Class({ Extends: Request, options: { emulation: false, urlEncoded: false }, /** * Constructor * @constructor * @param {Object} options Options for the request */ initialize: function(options) { this.xhr = new Browser.Request(); this.xhr.addEventListener("loadstart", options.onLoadStart, false); this.xhr.addEventListener("progress", options.onProgress, false); this.formData = new FormData(); this.setOptions(options); this.headers = this.options.headers; }, /** * Append data to the request * @method append * @param {String} key Key * @param {Mixed} value Value associated to the key * @return {cowboy.Request} Itself */ append: function(key, value) { this.formData.append(key, value); return this.formData; }, /** * Reset the form * @method reset * @return {[type]} [description] */ reset: function() { this.formData = new FormData(); }, /** * Send the request * @method send * @param {Object} options Options for the request * @return {cowboy.Request} Itself */ send: function(options) { var url = options.url || this.options.url; this.options.isSuccess = this.options.isSuccess || this.isSuccess; this.running = true; var xhr = this.xhr; xhr.open('POST', url, true); xhr.onreadystatechange = this.onStateChange.bind(this); Object.each(this.headers, function(value, key){ try { xhr.setRequestHeader(key, value); } catch(e) { this.fireEvent('exception', [key, value]); } }, this); this.fireEvent('request'); xhr.send(this.formData); if(!this.options.async) this.onStateChange(); if(this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this); return this; } });
(function ($) { "use strict"; $("#contact").validate(); /* CONTACT FORM */ $("#contact").submit(function (e) { e.preventDefault(); var name = $("#form-name").val(); var email = $("#form-email").val(); var subject = $("#form-subject").val(); var message = $("#form-message").val(); var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message; function validEmail(emailAddress) { var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i); return pattern.test(emailAddress); }; if (validEmail(email) && (message.length > 1) && (name.length > 1)) { $.ajax({ type: "POST", url: "send-mail.php", data: dataString, success: function () { $('.successContent').fadeIn(1000); $('.errorContent').fadeOut(500); } }); } else { $('.errorContent').fadeIn(1000); $('.successContent').fadeOut(500); } return false; }); })(jQuery);
var webpack = require('webpack'); var config = require('./webpack.config'); delete config.devtool; config.entry.demo = [config.entry.demo[0]]; config.plugins = [config.plugins[0], new webpack.optimize.UglifyJsPlugin({ sourceMap: false, output: { ascii_only: true } })]; config.module.loaders.forEach(function(loader) { if (loader.loader === 'babel') { // remove preset hmre loader.query.presets = loader.query.presets.slice(0, 3); } return loader; }); module.exports = config;
var deasync = require('deasync'); var cheerio = require("cheerio"); var ACCEPTED_GENDER_VALUES = ['male','female','random']; var DEFAULT_GENDER_VALUE = 'random'; var ACCEPTED_COUNTRY_VALUES = ["au", "as", "bg", "br", "ca", "cyen", "cygk", "cz", "dk", "ee", "fi", "fr", "gr", "gl", "hu", "is", "it", "nl", "nz", "no", "pl", "pt", "sl", "za", "sp", "sw", "sz", "tn", "uk", "us", "uy"]; var DEFAULT_COUNTRY_VALUE = 'us'; var ACCEPTED_NAMESET_VALUES = ["us", "ar", "au", "br", "celat", "ch", "zhtw", "hr", "cs", "dk", "nl", "en", "er", "fi", "fr", "gr", "gl", "sp", "hobbit", "hu", "is", "ig", "it", "jpja", "jp", "tlh", "ninja", "no", "fa", "pl", "ru", "rucyr", "gd", "sl", "sw", "th", "vn"]; var DEFAULT_NAMESET_VALUE = 'us'; var validateParams = function(param, paramList, defaultvalue){ param=param.toLowerCase(); if(paramList.indexOf(param)!=-1){ return param; } else{ console.error('Param '+param+' is not a valid value, using default'); return defaultvalue; } } var getHtml = function(options){ var options = options || {}; var gender = options.gender ? validateParams(options.gender, ACCEPTED_GENDER_VALUES, DEFAULT_GENDER_VALUE) : DEFAULT_GENDER_VALUE; var country = options.country ? validateParams(options.country, ACCEPTED_COUNTRY_VALUES, DEFAULT_COUNTRY_VALUE) : DEFAULT_COUNTRY_VALUE; var nameset = options.nameset ? validateParams(options.nameset, ACCEPTED_NAMESET_VALUES, DEFAULT_NAMESET_VALUE) : DEFAULT_NAMESET_VALUE; var html; var http = require('http'); var options = { host: 'www.fakenamegenerator.com', path: '/gen-'+gender+'-'+nameset+'-'+country+'.php' }; callback = function(response) { var str = ''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { html = str; }); } http.request(options, callback).end(); while(html==undefined){ deasync.runLoopOnce(); }; return html; } var getRandomData = function(options){ var randomData = { }; var html = getHtml(options); var $ = cheerio.load(html); var addressData = $('#details > div.content > div.info > div > div.address > div').html(); var addresses = addressData.replace(/\n/g,"").trimLeft().split('<br>'); var addressLine = addresses[0].trim(); var cityStateSplit = addresses[1].split(','); var city = cityStateSplit[0]; var stateZipSplit = cityStateSplit[1].split(' '); var state = stateZipSplit[1]; var zipCode = stateZipSplit[2]; randomData.name = $('#details > div.content > div.info > div > div.address > h3').text(); randomData.addressLine = addressLine; randomData.city = city; randomData.state = state; randomData.zipCode = zipCode; randomData.mothersMaidenName = $('#details > div.content > div.info > div > div.extra > dl:nth-child(1) > dd').text(); randomData.ssn = $('#details > div.content > div.info > div > div.extra > dl:nth-child(2) > dd').html().split('<div')[0].trim(); randomData.geoCoordinates = $('#geo').text(); randomData.phone = $('#details > div.content > div.info > div > div.extra > dl:nth-child(5) > dd').text(); randomData.DOB = $('#details > div.content > div.info > div > div.extra > dl:nth-child(8) > dd').text(); randomData.age = $('#details > div.content > div.info > div > div.extra > dl:nth-child(9) > dd').text(); randomData.zodiac = $('#details > div.content > div.info > div > div.extra > dl:nth-child(10) > dd').text(); randomData.emailAddress = $('#details > div.content > div.info > div > div.extra > dl:nth-child(12) > dd').html().split('<div')[0].trim(); randomData.userName = $('#details > div.content > div.info > div > div.extra > dl:nth-child(13) > dd').text() randomData.passWord = $('#details > div.content > div.info > div > div.extra > dl:nth-child(14) > dd').text(); randomData.website = $('#details > div.content > div.info > div > div.extra > dl:nth-child(15) > dd').text(); randomData.cardNumber = $('#details > div.content > div.info > div > div.extra > dl:nth-child(18) > dd').text(); randomData.expires = $('#details > div.content > div.info > div > div.extra > dl:nth-child(19) > dd').text(); randomData.cvv2 = $('#details > div.content > div.info > div > div.extra > dl:nth-child(20) > dd').text(); randomData.company = $('#details > div.content > div.info > div > div.extra > dl:nth-child(22) > dd').text(); randomData.occupation = $('#details > div.content > div.info > div > div.extra > dl:nth-child(23) > dd').text(); randomData.height = $('#details > div.content > div.info > div > div.extra > dl:nth-child(25) > dd').text(); randomData.weight = $('#details > div.content > div.info > div > div.extra > dl:nth-child(26) > dd').text(); randomData.bloodType = $('#details > div.content > div.info > div > div.extra > dl:nth-child(27) > dd').text(); randomData.upsTrackingNumber = $('#details > div.content > div.info > div > div.extra > dl:nth-child(29) > dd').text(); randomData.westernUnion = $('#details > div.content > div.info > div > div.extra > dl:nth-child(30) > dd').text(); randomData.moneyGram = $('#details > div.content > div.info > div > div.extra > dl:nth-child(31) > dd').text(); randomData.favoriteColor = $('#details > div.content > div.info > div > div.extra > dl:nth-child(33) > dd').text(); randomData.vehicle = $('#details > div.content > div.info > div > div.extra > dl:nth-child(34) > dd').text(); randomData.guid = $('#details > div.content > div.info > div > div.extra > dl:nth-child(35) > dd').text(); return randomData; } module.exports = { getRandomData : getRandomData } //getRandomData();
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21.87 17c-.47 0-.85.34-.98.8-.35 1.27-1.51 2.2-2.89 2.2h-2v-2h1c1.1 0 2-.9 2-2v-.88c0-2.1-1.55-3.53-3.03-3.88l-2.7-.67c-.87-.22-1.57-.81-1.95-1.57H8.5c-.28 0-.5-.22-.5-.5s.22-.5.5-.5h2.52L11 7H8.5c-.28 0-.5-.22-.5-.5s.22-.5.5-.5H11V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2h1v2H3c-.55 0-1 .45-1 1s.45 1 1 1h15c2.33 0 4.29-1.6 4.84-3.75.17-.63-.32-1.25-.97-1.25zM14 20H8v-2h6v2z" /> , 'IceSkatingRounded');
/* * grunt-card * https://github.com/sdicgdev/grunt-card * * Copyright (c) 2014 Evan Short * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'] }, // Configuration to be run (and then tested). card: { options: { bump: ['package.json'], } }, // Unit tests. nodeunit: { tests: ['test/*_test.js'] } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'card', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
import React from 'react' import PropTypes from 'prop-types' export default function wrapPage (app, Component) { return class extends React.Component { static displayName = `Page(${Component.displayName || Component.name})` static async getInitialProps (ctx) { const { query } = ctx const { action, ...params } = query const route = app.route(action) if (!route || !route.handler) { throw 'Page did not match route' } const props = await route.handler(params, { ...ctx, route }) if (props) { return { action, params, ...props } } else { return { action, params } } } static childContextTypes = { app: PropTypes.object } getChildContext () { return { app } } render () { const actions = app.routeHandlersByModuleAndName() const route = app.route(this.props.action) const localActions = actions[route.module] return <Component actions={actions} {...localActions} {...this.props} /> } } }
requirejs.config({ baseUrl: 'scripts', paths: { backbone: '../bower_components/backbone/backbone', jquery: '../../bower_components/jquery/dist/jquery', jQuery: '../../bower_components/jquery/dist/jquery', underscore: '../bower_components/underscore/underscore', bootstrap: '../bower_components/bootstrap/js', 'class': '../bower_components/backbone.class/backbone.class', 'es6-promise' : '../bower_components/es6-promise/promise', hbs: '../bower_components/require-handlebars-plugin/hbs' }, shim:{ 'backbone': { deps: ['underscore', 'jquery'], exports: 'Backbone' }, 'underscore': { exports: '_' }, 'class' : { deps: ['backbone'], exports: 'Backbone.Class' } } });
import { combineReducers } from 'redux' import ideas from './ideas' const rootReducer = combineReducers({ ideas }) export default rootReducer
'use strict'; // Declare app level module which depends on views, and components angular.module('baikalApp', [ 'ngRoute', 'ngTouch', 'baikalApp.home', 'baikalApp.photo', 'baikalApp.media', 'baikalApp.version', 'baikalApp.services', 'baikalApp.controllers', 'baikalApp.filters', 'baikalApp.routes', 'pascalprecht.translate', 'ngCookies', ]). config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({redirectTo: '/home'}); }]) .config( [ '$compileProvider', function( $compileProvider ) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|skype|tel):/); } ]) .config(function ($translateProvider) { $translateProvider.translations('ru', { TITLE: 'Лига Байкальских Ледовых Капитанов', COPYRIGHT_TEXT: 'Все права защищены', COPYRIGHT_AUTHOR: 'Александр Бурмейстер', MAIN_PAGE: 'Главная', PHOTO: 'Фото', SPRING: 'Весна', SUMMER: 'Лето', AUTUMN: 'Осень', WINTER: 'Зима', SPRING_SUBTITLE: 'с 20 апреля по 15 июня', SUMMER_SUBTITLE: 'с 15 июня по 10 августа', AUTUMN_SUBTITLE: 'с 10 августа по 25 октября', WINTER_SUBTITLE: 'с 1 января по 15 апреля', ABOUT_US: 'О нас', ABOUT_LEAGUE: 'О лиге', ABOUT_BAIKAL: 'О Байкале', FAMILY: 'Семья', NEWS: 'Новости', MEDIA: 'СМИ', EXPEDITIONS: 'Экспедиции', WINTER_BAIKAL: 'Зимний Байкал', BAIKAL_ICE_CODE: 'Правила Ледового Движения', RECORDS: 'Рекорды', VOLUNTEERS: 'Волонтёры', CREATIVE: 'Творчество', YOGA: 'Йога', YOGA_TEXT: 'Раздел заполняется', SKYPE_LESSONS: 'Skype уроки', SKYPE_LESSONS_TEXT: 'Кейси училась и жила в Америке, Франции, Испании и Китае, побывала более чем в 10 странах мира, и работает преподавателем английского языка уже 6 лет. Сейчас она продолжает путешествовать и изучать эту планету, и если тебе бы хотелось научиться говорить и думать по-английски, возможно, skype-уроки из разных уголков планеты, это то, что тебе нужно.', OUR_GUESTS: 'Наши гости', JOURNEY: 'Путешествия', CONTACTS: 'Контакты', FILMS: 'Фильмы', BAIKAL_SPRING: 'Байкал весной', BAIKAL_SUMMER: 'Байкал летом', AUTUMN_BAIKAL: 'Осенний байкал', BAIKAL_WINTER: 'Байкал зимой', WRITE_TO_YOU_FROM_BAIKAL: 'Пишу тебе с Байкала', SACRED_PLACES_OF_LAKE_BAIKAL: 'Сакральные места Байкала', BAIKAL_JOURNEY_TITLE: 'ЛИГА БАЙКАЛЬСКИХ ЛЕДОВЫХ КАПИТАНОВ им. А. Ю. БУРМЕЙСТЕРА', BAIKAL_JOURNEY_DESCRIPTION: 'У нас, в Сибири, говорят: «Тот, кто испил воды из священного озера Байкал, тот будет жить долго и счастливо». Здесь, на Байкале, существует и по сегодняшний день древнейшая культура общения Человека и Природы. Байкал завораживает, дает мудрость, истинное понимание красоты и раскрывает внутренние способности. Посвященным Байкал дает возможность пережить разные стихии: ураганный ветер, жесткие шторма, зеркальный штиль и чистейший лед! Байкал формирует духовную культуру и истинные отношения между людьми. Дни, проведенные на Байкале, Господь не засчитывает в счет прожитых лет.', BAIKAL_JOURNEY_AUTHOR: 'Александр Бурмейстер', BAIKAL_JOURNEY_BUTTON: 'Отправиться в путешествие »', OUR_CONTACTS: 'Наши контакты', ADDRESS: 'Адрес', PHONE: 'Телефон', PHONE_TEXT: '+7 (902) 511-45-67', SKYPE:'Skype' , SKYPE_TEXT: 'baikalicekapitan', E_MAIL: 'e-mail', E_MAIL_TEXT: 'aburmeister@mail.ru', MUSIC_PLAY: 'Музыка', MUSIC: 'Песни Ксюши Бурмейстер', NEWS_MEDIA: 'Новости: СМИ', EXPEDITIONS_SUBTITLE: 'Круглый год м можем предложить вам потрясающие экспедиции.' }); $translateProvider.translations('en', { TITLE: 'Baikal Ice Captain League', COPYRIGHT_TEXT: 'All rights reserved', COPYRIGHT_AUTHOR: 'Alexander Burmeister', MAIN_PAGE: 'Home', PHOTO: 'Photo', SPRING: 'Spring', SUMMER: 'Summer', AUTUMN: 'Autumn', WINTER: 'Winter', SPRING_SUBTITLE: 'from 20th of april to 15th of june', SUMMER_SUBTITLE: 'from 15th of june to 10th of august', AUTUMN_SUBTITLE: 'from 10th of august to 25th of october', WINTER_SUBTITLE: 'from 1st of january to 15th of aprile', ABOUT_US: 'About us', ABOUT_LEAGUE: 'About League', ABOUT_BAIKAL: 'About Baikal', FAMILY: 'Family', NEWS: 'News', MEDIA: 'Media', EXPEDITIONS: 'Expeditions', WINTER_BAIKAL: 'Winter Baikal', BAIKAL_ICE_CODE: 'Ice Driving Code', RECORDS: 'Records', VOLUNTEERS: 'Volunteers', CREATIVE: 'Creative', YOGA: 'Yoga', YOGA_TEXT: 'It empty for a while', SKYPE_LESSONS: 'Skype lessons', SKYPE_LESSONS_TEXT: 'KC has studied and lived in the USA, France, Spain and China. She has been to more than 10 different countries, and has been teaching English for 6 years. KC is fluent in English fluently and continues to travel and explorу the world. If you are looking to learn Russian and have an online pen-pal, KC offers Skype lessons from every corner of Earth.', OUR_GUESTS: 'Our guests', JOURNEY: 'Journey', CONTACTS: 'Contacts', FILMS: 'Films', BAIKAL_SPRING: 'Spring Baikal', BAIKAL_SUMMER: 'Summer Baikal', AUTUMN_BAIKAL: 'Autumn Baikal', BAIKAL_WINTER: 'Winter Baikal', WRITE_TO_YOU_FROM_BAIKAL: 'Write to you from Baikal', SACRED_PLACES_OF_LAKE_BAIKAL: 'Sacred places of Lake Baikal', BAIKAL_JOURNEY_TITLE: 'BAIKAL LEAGUE of ICE CAPTAINS named after A.BURMEISTER', BAIKAL_JOURNEY_DESCRIPTION: '"One that has tried water from the sacred lake Baikal will live a long and happy life". There is still an ancient culture of communication here between man and nature. Baikal charms: it provides wisdom, affords an understanding of beauty, and reveals inner powers. Baikal gives the initiate an opportunity to experience many different elements: fierce storms, savage gales, peaceful calms, and of course its famous crystal-clear ice. Baikal fosters a spiritual culture and genuine relationships between people. "Days spent on the Lake Baikal, the Lord doesn\'t count against past years."', BAIKAL_JOURNEY_AUTHOR: 'Aleksander Burmeister', BAIKAL_JOURNEY_BUTTON: 'Make a step to my adventure »', OUR_CONTACTS: 'Our contacts', PHONE: 'Tel.', PHONE_TEXT: '+7 (902) 511-45-67', SKYPE:'Skype' , SKYPE_TEXT: 'baikalicekapitan', E_MAIL: 'e-mail', E_MAIL_TEXT: 'aburmeister@mail.ru', MUSIC_PLAY: 'Music', MUSIC: 'Kseniya Burmeister Songs', NEWS_MEDIA: 'Media news', EXPEDITIONS_SUBTITLE: 'English expeditions subtitle.' }); $translateProvider.preferredLanguage('ru'); $translateProvider.useLocalStorage(); });
var ProviderClient = require('./ProviderClient'); module.exports = ReadOnlyProviderClient; function ReadOnlyProviderClient(provider) { ProviderClient.call(this, provider); } ReadOnlyProviderClient.prototype = Object.create(ProviderClient.prototype); ReadOnlyProviderClient.prototype.patch = function() { // Read-only }; ReadOnlyProviderClient.prototype.set = function() { // Read-only };
exports.config = { seleniumAddress: 'http://localhost:4444/wd/hub', specs: ['e2e/spec.js'] }
(function() { 'use strict'; /* Services */ angular.module('myApp.services', []) // put your services here! // .service('serviceName', ['dependency', function(dependency) {}]); .factory('messageList', ['fbutil', function(fbutil) { return fbutil.syncArray('messages', {limit: 10, endAt: null}); }]) .factory('flowList', ['fbutil', function(fbutil) { return fbutil.syncArray('flows', {limit: 10}); }]) .factory('flow', ['fbutil', '$routeParams', function(fbutil, $routeParams) { return fbutil.syncObject('flows/' + $routeParams.flowId); }]) .factory('mandrill', function() { return { initMandrill: function() { return new mandrill.Mandrill('MhYflar4NJx7K24Bpri_3A', true); } }; }); })();
'use strict' import smileyDead from './assets/smiley-dead.png' import smileySmile from './assets/smiley-smile.png' const sprites = document.getElementById('sprites') const canvas = document.getElementById('canvas') const width = canvas.width = 26 const height = canvas.height = 26 const ctx = canvas.getContext('2d') const draw = isAlive => { const sprite = isAlive ? smileySmile : smileyDead ctx.clearRect(0, 0, width, height) ctx.drawImage(sprites, sprite.x, sprite.y, sprite.width, sprite.height, 0, 0, width, height) return !isAlive } let isAlive = draw(true) canvas.addEventListener('click', () => isAlive = draw(isAlive))
'use strict'; angular.module('app', [ //modules 'app.templates', //pages 'app.pages.catalog', 'app.pages.book', //factories 'app.api.factory', 'ngMaterial', 'ngResource', 'ui.router' ]) .config(function($mdThemingProvider) { $mdThemingProvider.theme('default') .primaryPalette('cyan') .accentPalette('blue-grey'); }) .config(function($stateProvider, $urlRouterProvider, $locationProvider) { $locationProvider.html5Mode(true); $stateProvider .state('404', { templateUrl: '404/404.html' }); $urlRouterProvider.otherwise(function($injector, $location){ var state = $injector.get('$state'); state.go('404'); return $location.path(); }); }) .run();
var express = require('express'); var multiparty = require('multiparty'); var format = require('util').format; var app = module.exports = express(); app.get('/', function(req, res){ res.send('<form method="post" enctype="multipart/form-data">' + '<p>Title: <input type="text" name="title" /></p>' + '<p>Image: <input type="file" name="image" /></p>' + '<p><input type="submit" value="Upload" /></p>' + '</form>'); }); app.post('/', function(req, res, next){ // create a form to begin parsing var form = new multiparty.Form(); var image; var title; form.on('error', next); form.on('close', function(){ res.send(format('\nuploaded %s (%d Kb) as %s' , image.filename , image.size / 1024 | 0 , title)); }); // listen on field event for title form.on('field', function(name, val){ if (name !== 'title') return; title = val; }); // listen on part event for image file form.on('part', function(part){ if (!part.filename) return; if (part.name !== 'image') return part.resume(); image = {}; image.filename = part.filename; image.size = 0; part.on('data', function(buf){ image.size += buf.length; }); }); // parse the form form.parse(req); }); /* istanbul ignore next */ if (!module.parent) { app.listen(4000); console.log('Express started on port 4000'); }
/** * Created by Ed on 7/29/2015. * * jslint browser: true, tolerate: messy white space, maxerr: 50, * indent: 4 * globals: TEXTAPP document */ var TEXTAPP = {}; (function (textApp) { 'use strict'; textApp.newInventory = function () { var that = {}, inventory = []; that.find = function (name) { var result = null; inventory.forEach(function (item) { if (name === item.name) { result = item; } }); return result; }; that.look = function () { var result = ''; inventory.forEach(function (item) { result += '<span class="inventoryNames">' + item.name + '</span><br>'; }); return result; }; that.doActions = function () { var results = ''; inventory.forEach(function (item) { if (item.action) { results += ' ' + item.action(); } }); return results; }; that.add = function (obj) { inventory.push(obj); }; that.remove = function (obj) { inventory.forEach(function (item, index) { if (obj.name === item.name) { inventory.splice(index, 1); } }); }; return that; }; textApp.newGameObject = function (spec) { var that = {}, name = (spec && spec.name) || textApp.adjectives.random(), description = (spec && spec.description) || '', inventory = TEXTAPP.newInventory(), location = (spec && spec.location) || null; that.superior = function (funcName) { var super_that = this, method = super_that[funcName]; return function () { return method.apply(super_that, arguments); }; }; if (spec && spec.inventory) { spec.inventory.forEach(function (item) { inventory.add(item); }); } that.use = function (itemName) { var result = '', obj = inventory.find(itemName); if (obj) { result = obj.use(); } else { result = 'can not find ' + itemName; } return result; }; that.action = function () { var result = ''; return result; }; that.doActions = function () { return inventory.doActions(); }; that.look = function (target) { if (target) { var obj = inventory.find(target); if (obj) { return obj.look(); } else { return 'can not see ' + target; } } else { var result = inventory.look(); if (result) { return description + '<br> has: <br> ' + result; } else { return description + '<br> has: nothing'; } } }; that.take = function (target) { var item = inventory.find(target); if (item) { inventory.remove(item); } return item; }; that.drop = function (obj) { inventory.add(obj); }; that.location = location; that.name = name; return that; }; }(TEXTAPP));
import React from 'react'; class NotFound extends React.Component { render() { return ( <div> <h1>404 Opps</h1> </div> ); } } export default NotFound;
const chai = require("chai"); const chaiAsPromised = require("chai-as-promised"); const nock = require("nock"); chai.use(chaiAsPromised); chai.should(); const pnut = require("../lib/pnut"); before(function() { let base = "https://api.pnut.io/v0"; nock(base) .get("/posts/1") .reply(200, {}); nock(base) .get("/posts?ids=4,12,1000") .reply(200, {}); nock(base) .get("/posts/1/revisions") .reply(200, {}); nock(base) .get("/posts/tag/pnut-butter") .reply(200, {}); nock(base) .get("/posts/1/thread") .reply(200, {}); nock(base) .get("/posts/1/actions") .reply(200, {}); nock(base) .get("/users/me/actions") .reply(200, {}); nock(base) .post("/posts", { text: "An awesome post" }) .reply(200, {}); nock(base) .post("/posts", { text: "An awesome post", is_nsfw: 1 }) .reply(200, {}); nock(base) .post("/posts", { text: "An awesome post", is_nsfw: 1, reply_to: 1234, entities: { parse_links: 0, parse_markdown_links: 0 } }) .reply(200, {}); nock(base) .post("/posts", { text: "A post with raw data", raw: { type: "io.pnut.core.language", value: { language: "en" } } }) .reply(200, {}); nock(base) .put("/posts/1000", { text: "A revised, but still awesome post" }) .reply(200, {}); nock(base) .delete("/posts/1000") .reply(200, {}); nock(base) .put("/posts/1000/repost") .reply(200, {}); nock(base) .delete("/posts/1000/repost") .reply(200, {}); nock(base) .get("/users/1/bookmarks") .reply(200, {}); nock(base) .put("/posts/1000/bookmark") .reply(200, {}); nock(base) .delete("/posts/1000/bookmark") .reply(200, {}); nock(base) .get("/posts/streams/global") .reply(200, { data: [{ id: 2000 }, { id: 2001 }] }); nock(base) .get("/posts/streams/global?before_id=2000") .reply(200, { data: [{ id: 1998 }, { id: 1999 }] }); nock(base) .get("/posts/streams/me") .reply(200, {}); nock(base) .get("/posts/streams/unified") .reply(200, {}); nock(base) .get("/posts/search?tags=mndp,MondayNightDanceParty") .reply(200, {}); }); after(function() { nock.cleanAll(); }); describe("Posts", () => { it("should be able to fetch the the global timeline", () => { return pnut.global().should.become({ data: [{ id: 2000 }, { id: 2001 }] }); }); it("should be able to fetch the global timeline with additional parameters", () => { return pnut.global({ beforeId: 2000 }).should.become({ data: [{ id: 1998 }, { id: 1999 }] }); }); it("should be able to fetch the personal stream", () => { return pnut.personal().should.become({}); }); it("should be able to fetch a unified streams", () => { return pnut.unified().should.become({}); }); it("should be able to fetch a post by id", () => { return pnut.post(1).should.become({}); }); it("should be able to fetch an array of posts by their ids", () => { return pnut.posts(4, 12, 1000).should.become({}); }); it("should be able to fetch revisions of posts", () => { return pnut.revisions(1).should.become({}); }); it("should be able to fetch mentions for a specific user", () => { return pnut.mentions(1).should.become({}); }); it("should be able to fetch posts of a specific user", () => { return pnut.postsFrom(1).should.become({}); }); it("should be able to fetch posts by tags", () => { return pnut.postsTaggedWith("pnut-butter").should.become({}); }); it("should be able to fetch posts within a thread", () => { return pnut.thread("1").should.become({}); }); it("should be able to fetch actions executed against a post", () => { return pnut.actions("1").should.become({}); }); it("should be able to fetch actions for the posts of the authenticated user", () => { return pnut.usersActions().should.become({}); }); it("should be able to create a new post", () => { return pnut.createPost("An awesome post").should.become({}); }); it("should be able to create a new post with a single additional option", () => { return pnut.createPost("An awesome post", { nsfw: true }); }); it("should be able to create a new post with additional options", () => { return pnut .createPost("An awesome post", { nsfw: true, replyTo: 1234, parseLinks: false, parseMarkdownLinks: false }) .should.become({}); }); it("should be able to create a new post with raw parameters ", () => { return pnut.createPost("A post with raw data", { raw: { type: "io.pnut.core.language", value: { language: "en" } } }); }); it("should be able to edit a post", () => { return pnut .updatePost(1000, "A revised, but still awesome post") .should.become({}); }); it("should be able to delete a post", () => { return pnut.deletePost(1000).should.become({}); }); it("should be able to repost something", () => { return pnut.repost(1000).should.become({}); }); it("should be able to delete a repost", () => { return pnut.deleteRepost(1000).should.become({}); }); it("should be able to fetch a list of posts bookmarked by a user", () => { return pnut.bookmarks(1).should.become({}); }); it("should be able to bookmark a post", () => { return pnut.bookmark(1000).should.become({}); }); it("should be able to delete a bookmark", () => { return pnut.deleteBookmark(1000).should.become({}); }); it("should be possbible to search for posts", () => { return pnut .searchPosts({ tags: ["mndp", "MondayNightDanceParty"] }) .should.become({}); }); });
var namespaceapp = [ [ "actions", null, [ [ "models", "namespaceapp_1_1actions_1_1models.html", "namespaceapp_1_1actions_1_1models" ] ] ], [ "charges", null, [ [ "models", "namespaceapp_1_1charges_1_1models.html", "namespaceapp_1_1charges_1_1models" ] ] ], [ "committees", null, [ [ "models", "namespaceapp_1_1committees_1_1models.html", "namespaceapp_1_1committees_1_1models" ] ] ], [ "invitations", null, [ [ "models", "namespaceapp_1_1invitations_1_1models.html", "namespaceapp_1_1invitations_1_1models" ] ] ], [ "members", null, null ], [ "notes", null, [ [ "models", "namespaceapp_1_1notes_1_1models.html", "namespaceapp_1_1notes_1_1models" ] ] ], [ "users", null, [ [ "models", "namespaceapp_1_1users_1_1models.html", "namespaceapp_1_1users_1_1models" ], [ "permissions", "namespaceapp_1_1users_1_1permissions.html", "namespaceapp_1_1users_1_1permissions" ] ] ] ];
class dximagetransform_microsoft_wipe_1 { constructor() { // int Capabilities () {get} this.Capabilities = undefined; // float Duration () {get} {set} this.Duration = undefined; // float GradientSize () {get} {set} this.GradientSize = undefined; // string Motion () {get} {set} this.Motion = undefined; // float Progress () {get} {set} this.Progress = undefined; // float StepResolution () {get} this.StepResolution = undefined; // DXWIPEDIRECTION WipeStyle () {get} {set} this.WipeStyle = undefined; } } module.exports = dximagetransform_microsoft_wipe_1;
setTimeout(function () { process.stdout.write('second stdout'); }, 300); setTimeout(function () { process.stdout.write('third stdout'); }, 1400); setTimeout(function () { process.exit(); }, 1600); process.stdout.write('first stdout');
/* eslint no-process-env: 0 */ // Generate random bucket name so to ensure tests preparation // are not restricted by an existing bucket. const bucket = 'wrhs-test'; const acl = 'public-read'; const s3endpoint = 'http://localhost:4572'; const pkgcloud = { accessKeyId: 'fakeId', secretAccessKey: 'fakeKey', provider: 'amazon', endpoint: s3endpoint, forcePathBucket: true }; module.exports = { prefix: bucket, dynamodb: { endpoint: 'http://localhost:4569', region: 'us-east-1' }, s3: { endpoint: s3endpoint }, cdn: { test: { check: `${ s3endpoint }/${ bucket }/`, url: s3endpoint, pkgcloud, acl }, dev: { check: `${ s3endpoint }/${ bucket }/`, url: s3endpoint, pkgcloud, acl } } };
/* eslint-disable no-undef */ import React from 'react'; import { mount, render } from 'enzyme'; import DropdownMenu from '../src/DropdownMenu'; import { Item as MenuItem, ItemGroup as MenuItemGroup } from 'rc-menu'; describe('DropdownMenu', () => { it('renders correctly', () => { const menuItems = [ <MenuItemGroup key="group1"> <MenuItem key="1">1</MenuItem> </MenuItemGroup>, <MenuItemGroup key="group2"> <MenuItem key="2">2</MenuItem> </MenuItemGroup>, ]; const wrapper = render( <DropdownMenu menuItems={menuItems} value={[{ key: '1' }]} /> ); expect(wrapper).toMatchSnapshot(); }); it('save first active item', () => { const menuItems = [ <MenuItem key="1">1</MenuItem>, <MenuItem key="2">2</MenuItem>, ]; const wrapper = mount( <DropdownMenu menuItems={menuItems} value={[{ key: '1' }]} /> ); expect(wrapper.instance().firstActiveItem.props.children).toBe('1'); }); it('set active key to menu', () => { const menuItems = [ <MenuItem key="1">1</MenuItem>, <MenuItem key="2">2</MenuItem>, ]; const wrapper = mount( <DropdownMenu menuItems={menuItems} value={[{ key: '1' }]} /> ); wrapper.setProps({ visible: true }); expect(wrapper.find('Menu').props().activeKey).toBe('1'); wrapper.setProps({ inputValue: 'foo' }); expect(wrapper.find('Menu').props().activeKey).toBe(''); }); it('save firstActiveValue', () => { const menuItems = [ <MenuItem key="1">1</MenuItem>, <MenuItem key="2">2</MenuItem>, ]; const wrapper = mount( <DropdownMenu menuItems={menuItems} firstActiveValue={'2'} /> ); expect(wrapper.instance().firstActiveItem.props.children).toBe('2'); }); it('set firstActiveValue key to menu', () => { const menuItems = [ <MenuItem key="1">1</MenuItem>, <MenuItem key="2">2</MenuItem>, ]; const wrapper = mount( <DropdownMenu menuItems={menuItems} firstActiveValue={'2'} /> ); wrapper.setProps({ visible: true }); expect(wrapper.find('Menu').props().activeKey).toBe('2'); wrapper.setProps({ inputValue: 'foo' }); expect(wrapper.find('Menu').props().activeKey).toBe(''); }); it('save value not firstActiveValue', () => { const menuItems = [ <MenuItem key="1">1</MenuItem>, <MenuItem key="2">2</MenuItem>, ]; const wrapper = mount( <DropdownMenu value={[{ key: '1' }]} menuItems={menuItems} firstActiveValue={'2'} /> ); expect(wrapper.instance().firstActiveItem.props.children).toBe('1'); }); it('save visible and inputValue when update', () => { const wrapper = mount( <DropdownMenu /> ); wrapper.setProps({ visible: true, inputValue: 'foo' }); expect(wrapper.instance().lastVisible).toBe(true); expect(wrapper.instance().lastInputValue).toBe('foo'); }); it('not update when next visible is false', () => { const wrapper = mount( <DropdownMenu /> ); expect(wrapper.instance().shouldComponentUpdate({ visible: true })).toBe(true); expect(wrapper.instance().shouldComponentUpdate({ visible: false })).toBe(false); }); });
module.exports = { name: 'crawler-admin', db: { mongo: { host: 'localhost', port: 27017, name: 'crawler' }, redis: { host: 'localhost', port: 6379, index: 7, ttl: 3600 * 24 * 365, secret: '1' } }, cookie: { secret: '1', name: '', }, mail: { smtp: { host: '', port: 0, user: '', pass: '' }, send: { from: '' } }, oauth: { host: '', consumer_key: 'BAlBL5mxnhnfSNxNvFmSCLq6O8tfUAO0j0g7atER7XDpiDHHiH', consumer_secret: 'QkNGjINpgrlV2qeTpDe1nYX85IsEQHZDlmBtL8rCuLgNjzu5Zw', token: 'owBb8s1p9gM6sP287yZCfp8J80f2ioH83hof0f4fDBlinMYco1', token_secret: '0Yoo20IubdR762TzOBeKHtQLyBoNe2mdCeaKCX5sOlg8CSnpgl' }, host: 'localhost', port: 3000 };
import styled, { keyframes } from 'styled-components'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import ModalComponent from 'common/Modal'; import ButtonComponent from 'components/Button'; const spin = keyframes` from { transform:rotate(0deg); } to { transform:rotate(360deg); } `; export const TableRow = styled.tr` &:nth-child(2n) { background-color: #dbdbdb; } `; export const TableCell = styled.td` text-align: ${({ centered }) => (centered ? 'center' : 'left')}; padding: 0 10px; `; export const Icon = styled(FontAwesomeIcon)` margin: 0 10px; `; export const IconAnimated = styled(FontAwesomeIcon)` margin: 0 10px; animation-name: ${spin}; animation-duration: 2000ms; animation-iteration-count: infinite; animation-timing-function: linear; `; export const IconClickable = styled(FontAwesomeIcon)` margin: 0 10px; cursor: pointer; `; export const Year = styled.input``; export const Semester = styled.select``; export const Option = styled.option``; export const Until = styled.p` color: ${({ active }) => (active ? 'green' : 'red')}; `; export const Buttons = styled.div` display: flex; width: 100%; `; export const ModalText = styled.h2``; export const Modal = styled(ModalComponent)` display: flex; align-items: center; `; export const Button = styled(ButtonComponent)` margin: 10px; flex-basis: 200px; flex-grow: 1; `;
'use strict'; const { resolvePluginConfig, extendDefaultPlugins, } = require('../../lib/svgo/config.js'); describe('config', function () { describe('extend config with object', function () { var plugins = [ { name: 'removeDoctype', active: false }, { name: 'convertColors', params: { shorthex: false } }, { name: 'removeRasterImages', params: { param: true } }, ].map((plugin) => resolvePluginConfig(plugin)); const removeDoctype = getPlugin('removeDoctype', plugins); const convertColors = getPlugin('convertColors', plugins); const removeRasterImages = getPlugin('removeRasterImages', plugins); it('removeDoctype plugin should be disabled', function () { expect(removeDoctype.active).toEqual(false); }); describe('enable plugin with params object', function () { it('removeRasterImages plugin should be enabled', function () { expect(removeRasterImages.active).toEqual(true); }); it('removeRasterImages plugin should have property "params"', function () { expect(removeRasterImages).toHaveProperty('params'); }); it('"params" should be an instance of Object', function () { expect(removeRasterImages.params).toBeInstanceOf(Object); }); it('"params" should have property "param" with value of true', function () { expect(removeRasterImages.params).toHaveProperty('param', true); }); }); describe('extend plugin params with object', function () { it('convertColors plugin should have property "params"', function () { expect(convertColors).toHaveProperty('params'); }); it('"params" should be an instance of Object', function () { expect(convertColors.params).toBeInstanceOf(Object); }); it('"params" should have property "shorthex" with value of false', function () { expect(convertColors.params).toHaveProperty('shorthex', false); }); }); }); describe('replace default config with custom', function () { const config = { multipass: true, plugins: [ 'convertPathData', { name: 'cleanupNumericValues' }, { name: 'customPlugin', fn: () => {} }, ], }; const plugins = config.plugins.map((plugin) => resolvePluginConfig(plugin)); const cleanupNumericValues = getPlugin('cleanupNumericValues', plugins); const convertPathData = getPlugin('convertPathData', plugins); it('should have "multipass"', function () { expect(config.multipass).toEqual(true); }); it('config.plugins should have length 3', function () { expect(plugins).toHaveLength(3); }); it('specified plugins should be enabled', function () { expect(cleanupNumericValues.active).toEqual(true); expect(convertPathData.active).toEqual(true); }); }); describe('custom plugins', function () { describe('extend config with custom plugin', function () { const plugins = [ { name: 'aCustomPlugin', type: 'perItem', fn: function () {}, }, ].map((plugin) => resolvePluginConfig(plugin)); const customPlugin = getPlugin('aCustomPlugin', plugins); it('custom plugin should be enabled', function () { expect(customPlugin.active).toEqual(true); }); it('custom plugin should have been given a name', function () { expect(customPlugin.name).toEqual('aCustomPlugin'); }); }); describe('replace default config with custom plugin', function () { const plugins = [ { name: 'aCustomPlugin', type: 'perItem', fn: function () {}, }, ].map((plugin) => resolvePluginConfig(plugin)); const customPlugin = getPlugin('aCustomPlugin', plugins); it('config.plugins should have length 1', function () { expect(plugins).toHaveLength(1); }); it('custom plugin should be enabled', function () { expect(customPlugin.active).toEqual(true); }); it('custom plugin should have been given a name', function () { expect(customPlugin.name).toEqual('aCustomPlugin'); }); }); }); describe('allows to extend default plugins list', () => { const extendedPlugins = extendDefaultPlugins([ { name: 'customPlugin', fn: () => {}, }, { name: 'removeAttrs', params: { atts: ['aria-label'] }, }, { name: 'cleanupIDs', params: { remove: false }, }, ]); const removeAttrsIndex = extendedPlugins.findIndex( (item) => item.name === 'removeAttrs' ); const cleanupIDsIndex = extendedPlugins.findIndex( (item) => item.name === 'cleanupIDs' ); it('should preserve internal plugins order', () => { expect(removeAttrsIndex).toEqual(41); expect(cleanupIDsIndex).toEqual(11); }); it('should activate inactive by default plugins', () => { const removeAttrsPlugin = resolvePluginConfig( extendedPlugins[removeAttrsIndex] ); const cleanupIDsPlugin = resolvePluginConfig( extendedPlugins[cleanupIDsIndex] ); expect(removeAttrsPlugin.active).toEqual(true); expect(cleanupIDsPlugin.active).toEqual(true); }); it('should leave not extended inactive plugins to be inactive', () => { const inactivePlugin = resolvePluginConfig( extendedPlugins.find((item) => item.name === 'addClassesToSVGElement') ); expect(inactivePlugin.active).toEqual(false); }); it('should put custom plugins in the end', () => { expect(extendedPlugins[extendedPlugins.length - 1].name).toEqual( 'customPlugin' ); }); }); }); function getPlugin(name, plugins) { return plugins.find((plugin) => plugin.name === name); }
var botContext = require('bot/bot-context'); exports.postHook = function postHook(req, res) { try { require(req.params.skill); } catch (ex) { return res.status(400).send("The '" + req.params.skill + "' skill is not installed."); } try { var targetHooksFunction = require(req.params.skill + '/hooks'); } catch (ex) { return res.status(400).send("The '" + req.params.skill + "' skill does not support hooks handling."); } try { targetHooksFunction(req.body, botContext.controller, botContext.bot, function(message) { return res.status(200).send(message || 'OK'); }); } catch (ex) { return res.status(400).send("An exception occurred during hook handling: '" + ex.message + "'"); } };
/** * Created by MuyBien on 1/31/16. */ $(document).ready(function() { initializePage(); }) function initializePage() { console.log("initializing pages..."); //$('.AddTestJournal').click(function(e) { // e.preventDefault(); // console.log("add new test journal button clicked!"); // // $.post('/journal/new_test_journal', "", function() { // console.log("try to refresh the page!"); // window.location.href = '/myjournal'; // reload the page // }); //}); $('.datepicker').datepicker({ format: "dd/mm/yyyy" }); }
var PeerConnection = require('rtcpeerconnection'); var WildEmitter = require('wildemitter'); function Peer(options) { var self = this; this.id = options.id; this.parent = options.parent; this.oneway = options.oneway || false; this.browserPrefix = options.prefix; this.stream = options.stream; this.channels = {}; // Create an RTCPeerConnection via the polyfill this.pc = new PeerConnection(this.parent.config.peerConnectionConfig, this.parent.config.peerConnectionContraints); this.pc.on('ice', this.onIceCandidate.bind(this)); this.pc.on('addChannel', this.handleDataChannelAdded.bind(this)); // Just fire negotiation needed events for now // When browser re-negotiation handling seems to work // we can use this as the trigger for starting the offer/answer process // automatically. We'll just leave it be for now while this stabalizes. this.pc.on('negotiationNeeded', this.emit.bind(this, 'negotiationNeeded')); this.logger = this.parent.logger; if (webrtc.dataChannel) { // we may not have reliable channels try { this.reliableChannel = this.getDataChannel('reliable', {reliable: true}); if (!this.reliableChannel.reliable) throw Error('Failed to make reliable channel'); } catch (e) { this.logger.warn('Failed to create reliable data channel.'); this.reliableChannel = false; delete this.channels.reliable; } // in FF I can't seem to create unreliable channels now try { this.unreliableChannel = this.getDataChannel('unreliable', {reliable: false, preset: true}); if (this.unreliableChannel.unreliable !== false) throw Error('Failed to make unreliable channel'); } catch (e) { this.logger.warn('Failed to create unreliable data channel.'); this.unreliableChannel = false; delete this.channels.unreliableChannel; } } // call emitter constructor WildEmitter.call(this); // proxy events to parent this.on('*', function () { self.parent.emit.apply(self.parent, arguments); }); } Peer.prototype = Object.create(WildEmitter.prototype, { constructor: { value: Peer } }); Peer.prototype.handleMessage = function (message) { var self = this; this.logger.log('getting', message.type, message); if (message.prefix) this.browserPrefix = message.prefix; if (message.type === 'offer') { this.pc.answer(message.payload, function (err, sessionDesc) { self.send('answer', sessionDesc); }); } else if (message.type === 'answer') { this.pc.handleAnswer(message.payload); } else if (message.type === 'candidate') { this.pc.processIce(message.payload); } else if (message.type === 'data') { this.parent.emit('data', message); } }; Peer.prototype.send = function (messageType, payload) { var message = { to: this.id, roomType: this.type, type: messageType, payload: payload, prefix: webrtc.prefix }; this.logger.log('sending', messageType, message); this.parent.emit('message', message); }; // Internal method registering handlers for a data channel and emitting events on the peer Peer.prototype._observeDataChannel = function (channel) { var self = this; channel.onclose = this.emit.bind(this, 'channelClose', channel); channel.onerror = this.emit.bind(this, 'channelError', channel); channel.onmessage = function (event) { self.emit('message', channel.label, event.data, channel, event); }; channel.onopen = this.emit.bind(this, 'channelOpen', channel); }; // Fetch or create a data channel by the given name Peer.prototype.getDataChannel = function (name, opts) { if (!webrtc.dataChannel) return this.emit('error', new Error('createDataChannel not supported')); var channel = this.channels[name]; opts || (opts = {}); if (channel) return channel; // if we don't have one by this label, create it channel = this.channels[name] = this.pc.createDataChannel(name, opts); this._observeDataChannel(channel); return channel; }; Peer.prototype.onIceCandidate = function (candidate) { if (this.closed) return; if (candidate) { this.send('candidate', candidate); } else { this.logger.log("End of candidates."); } }; Peer.prototype.start = function () { var self = this; this.pc.offer(function (err, sessionDescription) { self.send('offer', sessionDescription); }); }; Peer.prototype.end = function () { this.pc.close(); }; Peer.prototype.handleDataChannelAdded = function (channel) { this.channels[channel.name] = channel; }; module.exports = Peer;
var packager = require('electron-packager'); var config = require('./package.json'); packager({ dir: './', out: './dist', name: config.name, platform: 'win32,darwin', arch: 'x64', version: '0.30.0', icon: './app.icns', 'app-bundle-id': 'jp.co.liginc.demoapp.electron', 'app-version': config.version, 'helper-bundle-id': 'jp.co.liginc.demoapp.electron', overwrite: true, asar: true, prune: true, ignore: "node_modules/(electron-packager|electron-prebuilt|\.bin)|release\.js|dist", 'version-string': { CompanyName: 'LIG inc', FileDescription: 'LIG Blog用デモアプリケーション', OriginalFilename: config.name, FileVersion: config.version, ProductVersion: config.version, ProductName: config.name, InternalName: config.name } }, function done (err, appPath) { if(err) { throw new Error(err); } console.log('Done!!'); });
/** * main.js * * @version 1.0 * * DESCRIPTION: * Core module for the CLIENT-side application of RugbyTrack. * * uses backbone.js MVC framework, which depends on the underscore.js utility library. * The main concept I follow when using Backbone.js is to make Views listen for * changes in the Model and react accordingly. * Models are the heart of any JavaScript application, containing the interactive * data as well as a large part of the logic surrounding it: conversions, validations, * computed properties, and access control.A Model in Backbone.js can represent any entity. * chair = Backbone.model.extend( {object definition}); * * We can easily create Models but without * any structure they are fairly useless because we can’t iterate through * them unless they are grouped together. So Backbone.js implements the Collection * class which allows us to order our models. * chairs = Backbone.collections.extend( {initialize: function(models, options ) {}); * * Then you can bind listeners/events * to Models and Collections. So whenever there are changes to the data we can * call events to react accordingly. * AppView = Backbone.View.extend({}); * * @throws none * @see * * @author Bob Drummond * (C) 2012 PINK PELICAN NZ LTD */ // ================ // GLOBAL VARIABLES // ================ var DEBUG = true; // ================ // globals stored in the window object requirejs.config({ shim: { 'underscore': { exports: '_' }, 'backbone': { deps: ['underscore', 'jquery'], exports: 'Backbone' }, 'bootstrap': { deps: ['jquery'], exports: 'bootstrap' } }, /** * HACK: * Modified Underscore and Backbone to be AMD compatible (define themselves) * since it didn't work properly with the RequireJS shim when optimizing */ paths: { 'text' : 'lib/text', 'jquery' : 'lib/jquery', 'underscore' : 'lib/underscore-amd', 'backbone' : 'lib/backbone-amd', 'bootstrap' : 'lib/bootstrap', 'moment' : 'lib/moment', 'Mediator' : 'lib/mediator', 'myassert' : 'lib/myassert', 'logToServer' : 'lib/logtoserver', 'App' : 'app', 'Router' : 'router', // <TODO - add other collections ,views, models 'HomeView' : 'views/home', 'HeaderView' : 'views/header', 'AboutView' : 'views/about', 'SigninView' : 'views/signin', 'ContactView' : 'views/contact', 'FieldView' : 'views/field', 'UserModel' : 'models/user', 'UserCollection' : 'collections/users', 'UserListView' : 'views/users/index', 'UserEditView' : 'views/users/edit', 'UserView' : 'views/users/show', 'TeamModel' : 'models/team', 'TeamCollection' : 'collections/teams', 'TeamListView' : 'views/teams/index', 'TeamEditView' : 'views/teams/edit', 'TeamView' : 'views/teams/show', 'GameModel' : 'models/game', 'GameCollection' : 'collections/games', 'GameListView' : 'views/games/index', 'GameEditView' : 'views/games/edit', 'GameView' : 'views/games/show', 'EventModel' : 'models/event', 'EventCollection' : 'collections/events', 'EventListView' : 'views/events/index', 'EventEditView' : 'views/events/edit', 'EventView' : 'views/events/show', 'SessionModel' : 'models/session', 'SessionListView' : 'views/sessions/index', 'SessionCollection': 'collections/sessions' } }); require(['App','myassert','logToServer','SessionModel','UserModel'], function(App, User, Team, Game, Event, Session) { // <TODO plus other collections App.initialize(); // Initialize Globals at startup window.appDomain = document.domain; window.appPort = document.location.port; window.appAPI = '/api/v1'; if (DEBUG) console.log('main.js: using API url root '+'http://'+window.appDomain+':'+window.appPort+window.appAPI); if(DEBUG){ myassert.setDisplayInWindow(true); // log assertion failures and passes in the window footer myassert.setDisplayInConsole(true); // log to browser debug console on assertion failed myassert.setDisplayInAlert(true); // popup on assert failed // as a test of displayInWindow only var randomtestresult = 24; myassert.ok( randomtestresult > 23, 'Checking the assert function - this should show as true'); } // log client-side window DOM or jQuery errors to the server for stats window.onerror = function(message, file, line) { logToServer(file + ':' + line + ' #error #window_error ' + message); }; // log client-side ajax errors to the server for stats $(document).ajaxError(function(e, xhr, settings) { logToServer(settings.url + ':' + xhr.status + ' #error #ajax_error ' + xhr.responseText); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:c280ca7aca0f5ce13201691215499fb8b241dee846a545113ba31263e44b6518 size 34281
/*jslint browser: true*/ /*global console, Framework7, MyApp, $document*/ MyApp.angular.factory('DataService', ['$document', function ($document) { 'use strict'; }]);
'use strict'; jest.dontMock('../lib/util-guid'); var guid = require('../lib/util-guid'); describe('guid', () => { it('#guid(16) should return a string whose length is 16', () => { expect(guid(16).length).toBe(16); }); it('#guid(32) should return a string whose length is 32', () => { expect(guid(32).length).toBe(32); }); it('#guid() should return a default string whose length is 32', () => { expect(guid().length).toBe(32); }); it('Every time invoke guid() should return a different value', () => { expect(guid(16)).not.toEqual(guid(16)); expect(guid(32)).not.toEqual(guid(32)); expect(guid()).not.toEqual(guid()); }); });
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */ /*global define, $, brackets, PathUtils, window, Mustache */ /** * Utilities functions for displaying update notifications * */ define(function (require, exports, module) { "use strict"; var Dialogs = require("widgets/Dialogs"), NativeApp = require("utils/NativeApp"), PreferencesManager = require("preferences/PreferencesManager"), Strings = require("strings"), StringUtils = require("utils/StringUtils"), Global = require("utils/Global"), UpdateDialogTemplate = require("text!htmlContent/update-dialog.html"), UpdateListTemplate = require("text!htmlContent/update-list.html"); var defaultPrefs = {lastNotifiedBuildNumber: 0}; // Extract current build number from package.json version field 0.0.0-0 var _buildNumber = Number(/-([0-9]+)/.exec(brackets.metadata.version)[1]); // PreferenceStorage //var _prefs = PreferencesManager.getPreferenceStorage(module, defaultPrefs); var _prefs = { getValue: function() { return '' }}; //TODO: Remove preferences migration code PreferencesManager.handleClientIdChange(_prefs, module.id); // This is the last version we notified the user about. If checkForUpdate() // is called with "false", only show the update notification dialog if there // is an update newer than this one. This value is saved in preferences. var _lastNotifiedBuildNumber = _prefs.getValue("lastNotifiedBuildNumber"); // Last time the versionInfoURL was fetched var _lastInfoURLFetchTime = _prefs.getValue("lastInfoURLFetchTime"); // URL to load version info from. By default this is loaded no more than once a day. If // you force an update check it is always loaded. // URL to fetch the version information. var _versionInfoURL; // Information on all posted builds of Brackets. This is an Array, where each element is // an Object with the following fields: // // {Number} buildNumber Number of the build // {String} versionString String representation of the build number (ie "Sprint 14") // {String} dateString Date of the build // {String} releaseNotesURL URL of the release notes for this build // {String} downloadURL URL to download this build // {Array} newFeatures Array of new features in this build. Each entry has two fields: // {String} name Name of the feature // {String} description Description of the feature // // This array must be reverse sorted by buildNumber (newest build info first) /** * @private * Flag that indicates if we've added a click handler to the update notification icon. */ var _addedClickHandler = false; /** * Get a data structure that has information for all builds of Brackets. * * If force is true, the information is always fetched from _versionInfoURL. * If force is false, we try to use cached information. If more than * 24 hours have passed since the last fetch, or if cached data can't be found, * the data is fetched again. * * If new data is fetched and dontCache is false, the data is saved in preferences * for quick fetching later. */ function _getUpdateInformation(force, dontCache) { var result = new $.Deferred(); var fetchData = false; var data; // If force is true, always fetch if (force) { fetchData = true; } // If we don't have data saved in prefs, fetch data = _prefs.getValue("updateInfo"); if (!data) { fetchData = true; } // If more than 24 hours have passed since our last fetch, fetch again if ((new Date()).getTime() > _lastInfoURLFetchTime + (1000 * 60 * 60 * 24)) { fetchData = true; } // Never fetch from inside the browser if (brackets.inBrowser) { fetchData = false; } if (fetchData) { $.ajax(_versionInfoURL, { dataType: "text", cache: false, complete: function (jqXHR, status) { if (status === "success") { try { data = JSON.parse(jqXHR.responseText); if (!dontCache) { _lastInfoURLFetchTime = (new Date()).getTime(); _prefs.setValue("lastInfoURLFetchTime", _lastInfoURLFetchTime); _prefs.setValue("updateInfo", data); } result.resolve(data); } catch (e) { console.log("Error parsing version information"); console.log(e); result.reject(); } } }, error: function (jqXHR, status, error) { // When loading data for unit tests, the error handler is // called but the responseText is valid. Try to use it here, // but *don't* save the results in prefs. if (!jqXHR.responseText) { // Text is NULL or empty string, reject(). result.reject(); return; } try { data = JSON.parse(jqXHR.responseText); result.resolve(data); } catch (e) { result.reject(); } } }); } else { result.resolve(data); } return result.promise(); } /** * Return a new array of version information that is newer than "buildNumber". * Returns null if there is no new version information. */ function _stripOldVersionInfo(versionInfo, buildNumber) { // Do a simple linear search. Since we are going in reverse-chronological order, we // should get through the search quickly. var lastIndex = 0; var len = versionInfo.length; while (lastIndex < len) { if (versionInfo[lastIndex].buildNumber <= buildNumber) { break; } lastIndex++; } if (lastIndex > 0) { return versionInfo.slice(0, lastIndex); } // No new version info return null; } /** * Show a dialog that shows the update */ function _showUpdateNotificationDialog(updates) { Dialogs.showModalDialogUsingTemplate(Mustache.render(UpdateDialogTemplate, Strings)) .done(function (id) { if (id === Dialogs.DIALOG_BTN_DOWNLOAD) { // The first entry in the updates array has the latest download link NativeApp.openURLInDefaultBrowser(updates[0].downloadURL); } }); // Populate the update data var $dlg = $(".update-dialog.instance"); var $updateList = $dlg.find(".update-info"); var templateVars = $.extend(updates, Strings); $updateList.html(Mustache.render(UpdateListTemplate, templateVars)); $dlg.on("click", "a", function (e) { var url = $(e.currentTarget).attr("data-url"); if (url) { // Make sure the URL has a domain that we know about if (/(brackets\.io|github\.com|adobe\.com)$/i.test(PathUtils.parseUrl(url).hostname)) { NativeApp.openURLInDefaultBrowser(url); } } }); } /** * Check for updates. If "force" is true, update notification dialogs are always displayed * (if an update is available). If "force" is false, the update notification is only * displayed for newly available updates. * * If an update is available, show the "update available" notification icon in the title bar. * * @param {boolean} force If true, always show the notification dialog. * @param {Object} _testValues This should only be used for testing purposes. See comments for details. * @return {$.Promise} jQuery Promise object that is resolved or rejected after the update check is complete. */ function checkForUpdate(force, _testValues) { // The second param, if non-null, is an Object containing value overrides. Values // in the object temporarily override the local values. This should *only* be used for testing. // If any overrides are set, permanent changes are not made (including showing // the update notification icon and saving prefs). var oldValues; var usingOverrides = false; // true if any of the values are overridden. var result = new $.Deferred(); if (_testValues) { oldValues = {}; if (_testValues.hasOwnProperty("_buildNumber")) { oldValues._buildNumber = _buildNumber; _buildNumber = _testValues._buildNumber; usingOverrides = true; } if (_testValues.hasOwnProperty("_lastNotifiedBuildNumber")) { oldValues._lastNotifiedBuildNumber = _lastNotifiedBuildNumber; _lastNotifiedBuildNumber = _testValues._lastNotifiedBuildNumber; usingOverrides = true; } if (_testValues.hasOwnProperty("_versionInfoURL")) { oldValues._versionInfoURL = _versionInfoURL; _versionInfoURL = _testValues._versionInfoURL; usingOverrides = true; } } _getUpdateInformation(force || usingOverrides, usingOverrides) .done(function (versionInfo) { if (!versionInfo) { return; } // Get all available updates var allUpdates = _stripOldVersionInfo(versionInfo, _buildNumber); // When running directly from GitHub source (as opposed to // an installed build), _buildNumber is 0. In this case, if the // test is not forced, don't show the update notification icon or // dialog. if (_buildNumber === 0 && !force) { result.resolve(); return; } if (allUpdates) { // Always show the "update available" icon if any updates are available var $updateNotification = $("#update-notification"); $updateNotification.css("display", "inline-block"); if (!_addedClickHandler) { _addedClickHandler = true; $updateNotification.on("click", function () { checkForUpdate(true); }); } // Only show the update dialog if force = true, or if the user hasn't been // alerted of this update if (force || allUpdates[0].buildNumber > _lastNotifiedBuildNumber) { _showUpdateNotificationDialog(allUpdates); // Update prefs with the last notified build number _lastNotifiedBuildNumber = allUpdates[0].buildNumber; // Don't save prefs is we have overridden values if (!usingOverrides) { _prefs.setValue("lastNotifiedBuildNumber", _lastNotifiedBuildNumber); } } } else if (force) { // No updates are available. If force == true, let the user know. Dialogs.showModalDialog( Dialogs.DIALOG_ID_ERROR, Strings.NO_UPDATE_TITLE, Strings.NO_UPDATE_MESSAGE ); } if (oldValues) { if (oldValues.hasOwnProperty("_buildNumber")) { _buildNumber = oldValues._buildNumber; } if (oldValues.hasOwnProperty("_lastNotifiedBuildNumber")) { _lastNotifiedBuildNumber = oldValues._lastNotifiedBuildNumber; } if (oldValues.hasOwnProperty("_versionInfoURL")) { _versionInfoURL = oldValues._versionInfoURL; } } result.resolve(); }) .fail(function () { // Error fetching the update data. If this is a forced check, alert the user if (force) { Dialogs.showModalDialog( Dialogs.DIALOG_ID_ERROR, Strings.ERROR_FETCHING_UPDATE_INFO_TITLE, Strings.ERROR_FETCHING_UPDATE_INFO_MSG ); } result.reject(); }); return result.promise(); } // Append locale to version info URL _versionInfoURL = brackets.config.update_info_url + brackets.getLocale() + ".json"; // Define public API exports.checkForUpdate = checkForUpdate; });
/* Static dependencies */ import '../index.html'; // import '../stylesheets/style'; /* JS dependencies */ import React from 'react'; import { Router, Route, IndexRoute, Link } from 'react-router'; import { createHistory, useBasename } from 'history'; /** Components **/ import ConcentrationGameApp from './components/ConcentrationGameApp'; import SetupLevel from './components/SetupLevel'; import Play from './components/Play'; import Results from './components/Results'; import NoMatch from './components/NoMatch'; // Use history object in <Router history={ history }> to use clean URLs // const history = useBasename(createHistory)({ // basename: '' // }) React.render( <Router> <Route path='/' component={ ConcentrationGameApp }> <IndexRoute component={ SetupLevel } /> <Route path='setup' component={ SetupLevel }/> <Route path='play' component={ Play }/> <Route path='play/:pairsNum' component={ Play }/> <Route path='results' component={ Results }/> <Route path='*' component={ NoMatch }/> </Route> </Router> , document.getElementById('main'));
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by CodeZu. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ var constants = require('../../constants'); module.exports = function(Client){ return Client.sub({ getEvents :Client.method({ method: constants.verbs.GET, url: '{+homePod}api/event/pull/?startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&filter={filter}&responseFields={responseFields}' }), getEvent :Client.method({ method: constants.verbs.GET, url: '{+homePod}api/event/pull/{eventId}?responseFields={responseFields}' }) }); };
var should = require('should')() var assert = require("assert") var osmdown = require('../lib') describe('Parser', function() { it('Should run the parse function', function(done) { osmdown.parse() done() }) })
/* * Copyright (c) 2015 by Greg Reimer <gregreimer@gmail.com> * MIT License. See mit-license.txt for more info. */ import $ref from './ref'; /* * Recursively iterate through every node in a JSON object tree. */ export default function* walkObj(value, parents, path, parent, key) { parents = parents || []; path = path || []; let isLeaf = isLeafNode(value); yield { parents, path, value, isLeaf }; // in case there was a mutation over the yield value = parent !== undefined ? parent[key] : value; isLeaf = isLeafNode(value); if (!isLeaf) { parents.push(value); for (const { key, child } of iterate(value)) { path.push(key); const isLeaf = isLeafNode(child); yield* walkObj(value[key], parents, path, value, key); path.pop(); } parents.pop(); } } export const isLeafNode = (() => { const $jsongLeafTypes = new Set([ 'ref', 'atom', 'error' ]); const $branchTypes = new Set([ 'object' ]); return function(thing) { const isLeaf = !thing || !$branchTypes.has(typeof thing); const isJsongLeaf = !!thing && $jsongLeafTypes.has(thing.$type); return isLeaf || isJsongLeaf; }; })(); // just for testing export function* expensiveWalkObject(...args) { for (const thing of walkObj(...args)) { thing.parents = thing.parents.slice(); thing.path = thing.path.slice(); yield thing; } } // object/array agnostic iterator function* iterate(thing) { if (Array.isArray(thing)) { for (let key=0; key<thing.length; key++) { const child = thing[key]; yield { key, child }; } } else { for (const key in thing) { if (!thing.hasOwnProperty(key)) { continue; } const child = thing[key]; yield { key, child }; } } }
import React from "react"; import ReactDOM from "react-dom"; import Home from "./home.js"; import Archive from "./archive.js"; import Resume from "./resume.js";
/** * A binder that toggles an attribute on or off if the expression is truthy or falsey. Use for attributes without * values such as `selected`, `disabled`, or `readonly`. */ module.exports = function(specificAttrName) { return function(value) { var attrName = specificAttrName || this.match; if (!value) { this.element.removeAttribute(attrName); } else { this.element.setAttribute(attrName, ''); } }; };
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.8/esri/copyright.txt for details. //>>built define("require exports dojo/_base/lang ../../core/Warning ./PointCloudBitfieldFilter ./PointCloudReturnFilter ./PointCloudValueFilter".split(" "),function(n,b,g,h,k,l,m){Object.defineProperty(b,"__esModule",{value:!0});var e={pointCloudValueFilter:m,pointCloudBitfieldFilter:k,pointCloudReturnFilter:l};b.read=function(a,f,c){if(a&&Array.isArray(a))return a.map(function(a){var d=a?e[a.type]||null:null;if(d)return d=new d,d.read(a,c),d;c&&c.messages&&a&&c.messages.push(new h("point-cloud-filter:unsupported", "Point cloud filters of type '"+(a.type||"unknown")+"' are not supported",{definition:a,context:c}))})};b.write=function(a,f,c,b){a=a.map(function(a){return a.write({},b)});g.setObject(c,a,f)};b.fromJSON=function(a){var b=a?e[a.type]||null:null;return b?b.fromJSON(a):null}});