diff --git a/pool/shard000/JavaScript/0001378_gulpfile.js b/pool/shard000/JavaScript/0001378_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..0af8b537083e321e7b11db7bb9fae309eb761515 --- /dev/null +++ b/pool/shard000/JavaScript/0001378_gulpfile.js @@ -0,0 +1,43 @@ +var gulp = require('gulp'), + tap = require('gulp-tap'), + rename = require('gulp-rename'), + browserify = require('browserify'); + +var bundler = function (file) { + var opts = { + entries: [file.path], + paths: ['./node_modules', './src'], + debug: true + } + + file.contents = browserify(opts) + .transform("babelify", {presets: ["es2015"], plugins: ["syntax-jsx", "transform-h-jsx"]}) + .bundle(); +} + +gulp.task('example:router', function () { + return gulp.src('examples/router/app.js', {read: false}) + .pipe(tap(bundler)) + .pipe(rename('app.bundle.js')) + .pipe(gulp.dest('examples/router')); +}); + +gulp.task('example:rest', function () { + return gulp.src('examples/rest/app.js', {read: false}) + .pipe(tap(bundler)) + .pipe(rename('app.bundle.js')) + .pipe(gulp.dest('examples/rest')); +}); + +gulp.task('example:todomvc', function () { + return gulp.src('examples/todomvc/src/app.js', {read: false}) + .pipe(tap(bundler)) + .pipe(rename('app.bundle.js')) + .pipe(gulp.dest('examples/todomvc')); +}); + +gulp.task('default', [ + 'example:router', + 'example:rest', + 'example:todomvc' +]); diff --git a/pool/shard000/JavaScript/0001379_urlBarSuggestionsReducerTest.js b/pool/shard000/JavaScript/0001379_urlBarSuggestionsReducerTest.js new file mode 100644 index 0000000000000000000000000000000000000000..b3cec29ea847ec67a299d53ed3185115efe06852 --- /dev/null +++ b/pool/shard000/JavaScript/0001379_urlBarSuggestionsReducerTest.js @@ -0,0 +1,94 @@ +/* global describe, it, before, after, afterEach */ +const mockery = require('mockery') +const sinon = require('sinon') +const Immutable = require('immutable') +const assert = require('assert') + +const appConstants = require('../../../../../js/constants/appConstants') +require('../../../braveUnit') + +describe('urlBarSuggestionsReducer', function () { + let urlBarSuggestionsReducer + before(function () { + mockery.enable({ + warnOnReplace: false, + warnOnUnregistered: false, + useCleanCache: true + }) + + this.siteSuggestionsStub = { + init: sinon.stub(), + add: sinon.stub() + } + mockery.registerMock('../../common/lib/siteSuggestions', this.siteSuggestionsStub) + + this.suggestionStub = { + generateNewSuggestionsList: sinon.stub(), + generateNewSearchXHRResults: sinon.stub() + } + mockery.registerMock('../../common/lib/suggestion', this.suggestionStub) + + urlBarSuggestionsReducer = require('../../../../../app/browser/reducers/urlBarSuggestionsReducer') + }) + + after(function () { + mockery.disable() + }) + + afterEach(function () { + this.siteSuggestionsStub.init.reset() + this.siteSuggestionsStub.add.reset() + this.suggestionStub.generateNewSuggestionsList.reset() + this.suggestionStub.generateNewSearchXHRResults.reset() + }) + + const site1 = { + location: 'https://brave.com' + } + + const initState = Immutable.fromJS({ + sites: { + 'key': site1 + } + }) + + describe('APP_SET_STATE', function () { + it('inits the suggestions lib with sites', function () { + urlBarSuggestionsReducer(Immutable.Map(), {actionType: appConstants.APP_SET_STATE, appState: initState}) + const callCount = this.siteSuggestionsStub.init.calledOnce + assert.equal(callCount, 1) + assert.deepEqual(this.siteSuggestionsStub.init.args[0][0], [site1]) + }) + }) + describe('APP_ADD_SITE', function () { + it('adds a site in the suggestions lib', function () { + const newState = urlBarSuggestionsReducer(initState, {actionType: appConstants.APP_ADD_SITE, siteDetail: site1}) + const callCount = this.siteSuggestionsStub.add.calledOnce + assert.equal(callCount, 1) + assert.deepEqual(this.siteSuggestionsStub.add.args[0][0], site1) + assert.deepEqual(newState, initState) + }) + }) + describe('APP_URL_BAR_TEXT_CHANGED', function () { + it('regenerates suggestions', function () { + const windowId = 1 + const tabId = 42 + const input = 'hello world' + const newState = urlBarSuggestionsReducer(initState, {actionType: appConstants.APP_URL_BAR_TEXT_CHANGED, tabId, windowId, input}) + const callCount = this.suggestionStub.generateNewSuggestionsList.calledOnce + assert.equal(callCount, 1) + assert.deepEqual(this.suggestionStub.generateNewSuggestionsList.args[0][0], initState) + assert.deepEqual(this.suggestionStub.generateNewSuggestionsList.args[0][1], windowId) + assert.deepEqual(this.suggestionStub.generateNewSuggestionsList.args[0][2], tabId) + assert.deepEqual(this.suggestionStub.generateNewSuggestionsList.args[0][3], input) + assert.deepEqual(newState, initState) + + const xhrCallCount = this.suggestionStub.generateNewSearchXHRResults.calledOnce + assert.equal(xhrCallCount, 1) + assert.deepEqual(this.suggestionStub.generateNewSearchXHRResults.args[0][0], initState) + assert.deepEqual(this.suggestionStub.generateNewSearchXHRResults.args[0][1], windowId) + assert.deepEqual(this.suggestionStub.generateNewSearchXHRResults.args[0][2], tabId) + assert.deepEqual(this.suggestionStub.generateNewSearchXHRResults.args[0][3], input) + }) + }) +}) diff --git a/pool/shard000/JavaScript/0001380_program_association.js b/pool/shard000/JavaScript/0001380_program_association.js new file mode 100644 index 0000000000000000000000000000000000000000..453d6cba458ab6d6b4a1e7ac4437c0b60719312d --- /dev/null +++ b/pool/shard000/JavaScript/0001380_program_association.js @@ -0,0 +1,107 @@ +"use strict"; + +const TsCrc32 = require("../crc32"); +const TsReader = require("../reader"); +const TsWriter = require("../writer"); +const TsSectionBase = require("./base"); + +class TsSectionProgramAssociation extends TsSectionBase { + constructor(buffer, pid) { + super(buffer, pid); + } + + decode() { + const reader = new TsReader(this._buffer); + const objSection = {}; + + objSection.table_id = reader.uimsbf(8); + objSection.section_syntax_indicator = reader.bslbf(1); + reader.next(1); // '0' + reader.next(2); // reserved + objSection.section_length = reader.uimsbf(12); + objSection.transport_stream_id = reader.uimsbf(16); + reader.next(2); // reserved + objSection.version_number = reader.uimsbf(5); + objSection.current_next_indicator = reader.bslbf(1); + objSection.section_number = reader.uimsbf(8); + objSection.last_section_number = reader.uimsbf(8); + + objSection.programs = []; + + for (const l = 3 + objSection.section_length - 4; reader.position >> 3 < l; ) { + const program = {}; + + program.program_number = reader.uimsbf(16); + reader.next(3); // reserved + if (program.program_number === 0) { + program.network_PID = reader.uimsbf(13); + } else { + program.program_map_PID = reader.uimsbf(13); + } + + objSection.programs.push(program); + } + + objSection.CRC_32 = reader.readBytes(4); + + return objSection; + } + + encode(objSection) { + const buffer = Buffer.alloc(0x400); + + const writer = new TsWriter(buffer); + + writer.uimsbf(8, objSection.table_id); + writer.bslbf(1, objSection.section_syntax_indicator); + writer.bslbf(1, 0); // '0' + writer.bslbf(2, 0b11); // reserved + writer.uimsbf(12, 5 + objSection.programs.length * 4 + 4); + writer.uimsbf(16, objSection.transport_stream_id); + writer.bslbf(2, 0b11); // reserved + writer.uimsbf(5, objSection.version_number); + writer.bslbf(1, objSection.current_next_indicator); + writer.uimsbf(8, objSection.section_number); + writer.uimsbf(8, objSection.last_section_number); + + objSection.programs.forEach(program => { + writer.uimsbf(16, program.program_number); + writer.bslbf(3, 0); // reserved + if (program.program_number === 0) { + writer.uimsbf(13, program.network_PID); + } else { + writer.uimsbf(13, program.program_map_PID); + } + }); + + writer.writeBytes(4, TsCrc32.calcToBuffer(buffer.slice(0, writer.position >> 3))); + + this._buffer = buffer.slice(0, writer.position >> 3); + } + + checkCrc32() { + return TsCrc32.calc(this._buffer) === 0; + } + + getTransportStreamId() { + return this._buffer[3] << 8 | this._buffer[4]; + } + + getVersionNumber() { + return (this._buffer[5] & 0x3E) >> 1; + } + + getCurrentNextIndicator() { + return this._buffer[5] & 0x01; + } + + getSectionNumber() { + return this._buffer[6]; + } + + getLastSectionNumber() { + return this._buffer[7]; + } +} + +module.exports = TsSectionProgramAssociation; diff --git a/pool/shard000/JavaScript/0001383_usersController.js b/pool/shard000/JavaScript/0001383_usersController.js new file mode 100644 index 0000000000000000000000000000000000000000..9436a4ba3a84fb416a68d338e5bf2b9d5f37ccc5 --- /dev/null +++ b/pool/shard000/JavaScript/0001383_usersController.js @@ -0,0 +1,82 @@ +var User = require('../models/usersModel'); +var jwt = require('jsonwebtoken'); +var secret = "A super secret key"; + +module.exports = { + userController: { + create: function (req, res) { + var user = new User(req.body); + + user.save(function (err, user) { + if (err) {res.json(err);} + else {res.json(user);} + }); + }, + all: function (req, res) { + User.find({}, function(err, users) { + if (err) res.json(err); + res.json(users); + }) + }, + single: function (req, res) { + var id = req.params.id; + + User.findOne({_id: id}, function (err, user) { + if (err) res.json(err); + res.json(user); + }) + }, + update: function (req, res) { + var id = req.params.id; + + User.findOne({_id: id}, function (err, user) { + if (err) res.json(err); + + if (req.body.email) {user.email = req.body.email;} + if (req.body.password) {user.password = req.body.password;} + + user.save(function (err, response) { + if (err) res.json(err); + res.json(response); + }) + }) + }, + destroy: function (req, res) { + var id = req.params.id; + + User.remove({_id: id}, function (err, user) { + if (err) res.json(err); + + res.json({message: "Deleted User!"}) + }) + }, + signIn: function (req, res) { + User.findOne({email: req.body.email}, function (err, user) { + // console.log("Going to sign in"); + if (err) res.json(err); + + if (user) { + console.log("Found user"); + if (user.comparePassword(req.body.password)) { + // console.log("Creating token"); + var token = jwt.sign({email: user.email, id: user._id, admin: user.admin}, + secret, + {expiresInMinutes: 1440}); + // console.log("Sending token"); + res.json({ + success: true, + message: 'Successfully logged in!', + token: token + }); + } else { + // console.log("Password does not match"); + res.json({message: "password does not match"}) + } + } else { + // console.log("Did not find user"); + res.json({message: "user does not exist"}) + } + }) + } + } +}; diff --git a/pool/shard000/JavaScript/0001387_dockerService.js b/pool/shard000/JavaScript/0001387_dockerService.js new file mode 100644 index 0000000000000000000000000000000000000000..a6e1323c6aee5f9e4de403ba78373bb13f0aa2f0 --- /dev/null +++ b/pool/shard000/JavaScript/0001387_dockerService.js @@ -0,0 +1,151 @@ +/* + * Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * docker/dockerService.js + * Main entrypoint for all controllers requesting Docker instance info. + */ + +var _ = require('lodash'); +var oboe = require('oboe'); + +function dockerService($http, actions, flux, alertService, configService) { + 'use strict'; + + // Utility for creating a Docker endpoint object + function ep(_verb, _template, _action) { + return { + verb: _verb, + template: _template, + action: _action + }; + } + + // Endpoint -> (verb, action) + var endpoints = { + 'containers': { + 'inspect': ep('GET', '/containers/{id}/json', actions.inspectContainer), + 'create': ep('POST', '/containers/create', actions.createContainer), + 'list': ep('GET', '/containers/json', actions.listContainers), + 'logs': ep('GET', '/containers/{id}/logs', actions.inspectContainerLogs), + 'start': ep('POST', '/containers/{id}/start', actions.startContainer), + 'stop': ep('POST', '/containers/{id}/stop', actions.stopContainer), + 'restart': ep('POST', '/containers/{id}/restart', actions.restartContainer), + 'pause': ep('POST', '/containers/{id}/pause', actions.pauseContainer), + 'unpause': ep('POST', '/containers/{id}/unpause', actions.unpauseContainer) + }, + 'images': { + 'list': ep('GET', '/images/json', actions.listImages), + 'search': ep('GET', '/images/search', actions.searchImages), + 'pull': ep('POST', '/images/create', actions.pullImage), + 'remove': ep('DELETE', '/images/{id}', actions.removeImage) + } + }; + + /* + * prepareUrl() + * @param {string, required} url: docker API call + * @param {string, required} host: targeted docker instance + * @param {string} id: container/image id located on host + */ + function prepareUrl(url, host, id) { + var request = [configService.api.base, 'd/', encodeURIComponent(host)]; + + if (id && (url.indexOf('{id}') > -1)) { + request.push(url.replace('{id}', id)); + } + else { + request.push(url); + } + + return request.join(''); + } + + /* + * docker() + * Main entrypoint. + * Prepares a Docker request and dispatches the appropriate flux action upon success. + * + * @param {string, required} namespace: namespace representation of a Docker API call (i.e. 'containers.inspect') + * @param {object, required} request: object representation of a Docker API call. + * Allowed keys: + * {string, required} host: lighthouse alias for targeted Docker instance + * {string} id: image or container id (generated by Docker) + * {object} query: map of query parameter keys and values + * {*} data: body data for POST/PUT requests + */ + function d(namespace, request) { + var ns = namespace.split('.'); + var endpoint = endpoints[ns[0]][ns[1]]; + + var config = { + method: endpoint.verb, + url: prepareUrl(endpoint.template, request.host, request.id), + params: request.query, + data: request.data ? {'Payload': request.data} : null, + responseType: request.responseType || 'json', + headers: { + 'Content-Type': 'application/json' + } + }; + + $http(config).then( + // success + function (response) { + flux.dispatch(endpoint.action, + {'id': request.id, 'host': request.host, 'response': response.data}); + } + ); + } + + function stream(namespace, request) { + var ns = namespace.split('.'); + var endpoint = endpoints[ns[0]][ns[1]]; + + var oboeStream = oboe({ + method: endpoint.verb, + url: prepareUrl(endpoint.template, request.host, request.id) + '?' + $.param(request.query), + body: request.body + }); + + _.reduce(request.patterns, function(stream, pattern) { + return stream.node(pattern, function(item) { + flux.dispatch(endpoint.action, { + 'id': request.id, + 'host': request.host, + 'response': item, + 'pattern': pattern, + 'meta': request + }); + }); + }, oboeStream); + + oboeStream.fail(function() { + alertService.create({ + message: namespace + ' call failed...', + type: 'danger' + }); + }); + } + + return { + 'd': d, + 'stream': stream + }; +} + +dockerService.$inject = ['$http', 'actions', 'flux', 'alertService', 'configService']; +module.exports = dockerService; diff --git a/pool/shard000/JavaScript/0001389_bundle.repository.js b/pool/shard000/JavaScript/0001389_bundle.repository.js new file mode 100644 index 0000000000000000000000000000000000000000..bdfb3e5c91fe4e309dacf70a98df303edd5b10c7 --- /dev/null +++ b/pool/shard000/JavaScript/0001389_bundle.repository.js @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2011-2013 Lp digital system + * + * This file is part of BackBee. + * + * BackBee is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * BackBee is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with BackBee. If not, see . + */ +define( + [ + 'Core/DriverHandler', + 'Core/RestDriver', + 'jquery', + 'jsclass' + ], + function (CoreDriverHandler, CoreRestDriver, jQuery) { + + 'use strict'; + + /** + * Bundle repository class + * @type {Object} JS.Class + */ + var BundleRepository = new JS.Class({ + + TYPE: 'bundle', + + DEFAULT_DRIVER_KEY: 'rest', + + /** + * Initialize of Bundle repository + */ + initialize: function () { + CoreDriverHandler.addDriver(this.DEFAULT_DRIVER_KEY, CoreRestDriver); + }, + + /** + * List bundles + * @param {Function} callback + */ + list: function () { + var self = this, + dfd = jQuery.Deferred(); + + if (this.bundleList === undefined) { + + CoreDriverHandler.read(this.TYPE).done(function (data) { + self.bundleList = data; + dfd.resolve(self.bundleList); + }); + } else { + dfd.resolve(this.bundleList); + } + + return dfd.promise(); + }, + + /** + * Set the activation of bundle + * @param {Boolean} active + * @param {String} bundleId + */ + active: function (active, bundleId) { + return CoreDriverHandler.patch(this.TYPE, {'enable': active}, {'id': bundleId}); + } + }); + + return new JS.Singleton(BundleRepository); + } +); diff --git a/pool/shard000/JavaScript/0001390_aql-queries-geo.js b/pool/shard000/JavaScript/0001390_aql-queries-geo.js new file mode 100644 index 0000000000000000000000000000000000000000..babf6d4ef8e2bae9f0f051e11867cde8ef9ff3df --- /dev/null +++ b/pool/shard000/JavaScript/0001390_aql-queries-geo.js @@ -0,0 +1,271 @@ +/*jshint globalstrict:false, strict:false, maxlen: 500 */ +/*global assertEqual */ + +//////////////////////////////////////////////////////////////////////////////// +/// @brief tests for query language, geo queries +/// +/// @file +/// +/// DISCLAIMER +/// +/// Copyright 2010-2012 triagens GmbH, Cologne, Germany +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// +/// Copyright holder is triAGENS GmbH, Cologne, Germany +/// +/// @author Jan Steemann +/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany +//////////////////////////////////////////////////////////////////////////////// + +var jsunity = require("jsunity"); +var db = require("@arangodb").db; +var errors = require("@arangodb").errors; +var helper = require("@arangodb/aql-helper"); +var getQueryResults = helper.getQueryResults; +var assertQueryError = helper.assertQueryError; + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test suite +//////////////////////////////////////////////////////////////////////////////// + +function ahuacatlGeoTestSuite () { + var locations = null; + var locationsNon = null; + + function runQuery (query) { + var result = getQueryResults(query); + + result = result.map(function(row) { + var r; + if (row !== null && typeof row === 'object') { + for (r in row) { + if (row.hasOwnProperty(r)) { + var value = row[r]; + if (typeof(value) === "number") { + if (value !== parseFloat(parseInt(value))) { + row[r] = Number(value).toFixed(5); + } + } + } + } + } + + return row; + }); + + return result; + } + + return { + +//////////////////////////////////////////////////////////////////////////////// +/// @brief set up +//////////////////////////////////////////////////////////////////////////////// + + setUp : function () { + var lat, lon; + db._drop("UnitTestsAhuacatlLocations"); + db._drop("UnitTestsAhuacatlLocationsNon"); + + locations = db._create("UnitTestsAhuacatlLocations"); + for (lat = -40; lat <= 40; ++lat) { + for (lon = -40; lon <= 40; ++lon) { + locations.save({"latitude" : lat, "longitude" : lon }); + } + } + + locations.ensureGeoIndex("latitude", "longitude"); + + locationsNon = db._create("UnitTestsAhuacatlLocationsNon"); + + for (lat = -40; lat <= 40; ++lat) { + for (lon = -40; lon <= 40; ++lon) { + locationsNon.save({"latitude" : lat, "longitude" : lon }); + } + } + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief tear down +//////////////////////////////////////////////////////////////////////////////// + + tearDown : function () { + db._drop("UnitTestsAhuacatlLocations"); + db._drop("UnitTestsAhuacatlLocationsNon"); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test near function +//////////////////////////////////////////////////////////////////////////////// + + testNear1 : function () { + var expected = [ { "distance" : "111194.92664", "latitude" : -1, "longitude" : 0 }, { "distance" : "111194.92664", "latitude" : 0, "longitude" : -1 }, { "distance" : "111194.92664", "latitude" : 0, "longitude" : 1 }, { "distance" : "111194.92664", "latitude" : 1, "longitude" : 0 }, { "distance" : 0, "latitude" : 0, "longitude" : 0 } ]; + var actual = runQuery("FOR x IN NEAR(" + locations.name() + ", 0, 0, 5, \"distance\") SORT x.distance DESC, x.latitude, x.longitude RETURN x"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test near function +//////////////////////////////////////////////////////////////////////////////// + + testNear2 : function () { + var expected = [ { "latitude" : -10, "longitude" : 24 }, { "latitude" : -10, "longitude" : 25 }, { "latitude" : -10, "longitude" : 26 } ]; + var actual = runQuery("FOR x IN NEAR(" + locations.name() + ", -10, 25, 3) SORT x.latitude, x.longitude RETURN x"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test near function +//////////////////////////////////////////////////////////////////////////////// + + testNear3 : function () { + var expected = [ { "distance" : "14891044.54146", "latitude" : 40, "longitude" : -40 }, { "distance" : "14853029.30724", "latitude" : 40, "longitude" : -39 }, { "distance" : "14815001.47646", "latitude" : 40, "longitude" : -38 } ]; + var actual = runQuery("FOR x IN NEAR(" + locations.name() + ", -70, 70, 10000, \"distance\") SORT x.distance DESC LIMIT 3 RETURN x"); + assertEqual(expected, actual); + + expected = [ {"distance" : "4487652.12954", "latitude" : -37, "longitude" : 26 }, { "distance" : "4485565.93668", "latitude" : -39, "longitude" : 20 }, { "distance" : "4484371.86154" , "latitude" : -38, "longitude" : 23 } ]; + actual = runQuery("FOR x IN NEAR(" + locations.name() + ", -70, 70, null, \"distance\") SORT x.distance DESC LIMIT 3 RETURN x"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test near function +//////////////////////////////////////////////////////////////////////////////// + + testNear4 : function () { + var expected = [ {"latitude" : -40, "longitude" : 40 }, { "latitude" : -40, "longitude" : 39 }, { "latitude" : -40, "longitude" : 38 } ]; + var actual = runQuery("FOR x IN NEAR(" + locations.name() + ", -70, 70, null) SORT x.latitude, x.longitude DESC LIMIT 3 RETURN x"); + assertEqual(expected, actual); + + expected = [ { "latitude" : -40, "longitude" : 40 }, { "latitude" : -40, "longitude" : 39 } ]; + actual = runQuery("FOR x IN NEAR(" + locations.name() + ", -70, 70, 2) SORT x.latitude, x.longitude DESC LIMIT 3 RETURN x"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test within function +//////////////////////////////////////////////////////////////////////////////// + + testWithin1 : function () { + var expected = [ { "distance" : 0, "latitude" : 0, "longitude" : 0 } ]; + var actual = runQuery("FOR x IN WITHIN(" + locations.name() + ", 0, 0, 10000, \"distance\") SORT x.latitude, x.longitude RETURN x"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test within function +//////////////////////////////////////////////////////////////////////////////// + + testWithin2 : function () { + var expected = [ { "distance" : "111194.92664", "latitude" : -1, "longitude" : 0 }, { "distance" : "111194.92664", "latitude" : 0, "longitude" : -1 }, { "distance" : 0, "latitude" : 0, "longitude" : 0 }, { "distance" : "111194.92664", "latitude" : 0, "longitude" : 1 }, { "distance" : "111194.92664", "latitude" : 1, "longitude" : 0 } ]; + var actual = runQuery("FOR x IN WITHIN(" + locations.name() + ", 0, 0, 150000, \"distance\") SORT x.latitude, x.longitude RETURN x"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test within function +//////////////////////////////////////////////////////////////////////////////// + + testWithin3 : function () { + var expected = [ { "latitude" : -10, "longitude" : 25 } ]; + var actual = runQuery("FOR x IN WITHIN(" + locations.name() + ", -10, 25, 10000) SORT x.latitude, x.longitude RETURN x"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test within function +//////////////////////////////////////////////////////////////////////////////// + + testWithin4 : function () { + var expected = [ + { "latitude" : -11, "longitude" : 25 }, + { "latitude" : -10, "longitude" : 24 }, + { "latitude" : -10, "longitude" : 25 }, + { "latitude" : -10, "longitude" : 26 }, + { "latitude" : -9, "longitude" : 25 } + ]; + + var actual = runQuery("FOR x IN WITHIN(" + locations.name() + ", -10, 25, 150000) SORT x.latitude, x.longitude RETURN x"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test within function +//////////////////////////////////////////////////////////////////////////////// + + testWithin5 : function () { + var expected = [ ]; + var actual = runQuery("FOR x IN WITHIN(" + locations.name() + ", -90, 90, 10000) SORT x.latitude, x.longitude RETURN x"); + assertEqual(expected, actual); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test without geo index available +//////////////////////////////////////////////////////////////////////////////// + + testNonIndexed : function () { + assertQueryError(errors.ERROR_QUERY_GEO_INDEX_MISSING.code, "RETURN NEAR(" + locationsNon.name() + ", 0, 0, 10)"); + assertQueryError(errors.ERROR_QUERY_GEO_INDEX_MISSING.code, "RETURN WITHIN(" + locationsNon.name() + ", 0, 0, 10)"); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test invalid NEAR arguments count +//////////////////////////////////////////////////////////////////////////////// + + testInvalidNearArgument : function () { + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN NEAR(\"" + locationsNon.name() + "\", 0, 0, \"foo\")"); + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN NEAR(\"" + locationsNon.name() + "\", 0, 0, true)"); + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN NEAR(\"" + locationsNon.name() + "\", 0, 0, 10, true)"); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test invalid WITHIN arguments count +//////////////////////////////////////////////////////////////////////////////// + + testInvalidWithinArgument : function () { + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN WITHIN(\"" + locationsNon.name() + "\", 0, 0, \"foo\")"); + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN WITHIN(\"" + locationsNon.name() + "\", 0, 0, true)"); + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN WITHIN(\"" + locationsNon.name() + "\", 0, 0, 0, true)"); + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN WITHIN(\"" + locationsNon.name() + "\", 0, 0, 0, [ ])"); + }, + +//////////////////////////////////////////////////////////////////////////////// +/// @brief test invalid collection parameter +//////////////////////////////////////////////////////////////////////////////// + + testInvalidCollectionArgument : function () { + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN WITHIN(1234, 0, 0, 10)"); + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN WITHIN(false, 0, 0, 10)"); + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN WITHIN(true, 0, 0, 10)"); + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN WITHIN([ ], 0, 0, 10)"); + assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH.code, "RETURN WITHIN({ }, 0, 0, 10)"); + assertQueryError(errors.ERROR_ARANGO_COLLECTION_NOT_FOUND.code, "RETURN WITHIN(@name, 0, 0, 10)", { name: "foobarbazcoll" }); + assertQueryError(errors.ERROR_QUERY_BIND_PARAMETER_MISSING.code, "RETURN WITHIN(@name, 0, 0, 10)"); + } + + }; +} + +//////////////////////////////////////////////////////////////////////////////// +/// @brief executes the test suite +//////////////////////////////////////////////////////////////////////////////// + +jsunity.run(ahuacatlGeoTestSuite); + +return jsunity.done(); + +// Local Variables: +// mode: outline-minor +// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)" +// End: diff --git a/pool/shard000/JavaScript/0001391_index.js b/pool/shard000/JavaScript/0001391_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4e7d26e47c5fd52c2982ecd892b725c64068c366 --- /dev/null +++ b/pool/shard000/JavaScript/0001391_index.js @@ -0,0 +1,37 @@ +import {parseHeaders, isUndefined, isFunction, XMLHttpRequest, Promise, Error, assign} from 'j0'; +import Request from '../../-request/j0polyfill/index.js'; +import Response from '../../-response/j0polyfill/index.js'; + +export default function fetch(input, init, cb) { + const xhr = new XMLHttpRequest(); + return assign( + new Promise((resolve, reject) => { + const request = new Request(input, init); + if (isFunction(cb)) { + cb(xhr); + } + assign(xhr, { + onload() { + const {status, statusText} = xhr; + const headers = parseHeaders(xhr.getAllResponseHeaders() || ''); + const url = 'responseURL' in xhr ? xhr.responseURL : headers.get('X-Request-URL'); + const body = 'response' in xhr ? xhr.response : xhr.responseText; + resolve(new Response(body, {status, statusText, headers, url})); + }, + onabort: (event) => reject(assign(event.error || event || new Error('Aborted'), {code: 'EABORTED'})), + onerror: (event) => reject(event.error || event || new Error('Network request failed')), + ontimeout: (event) => reject(assign(event.error || event || new Error('Timeout'), {code: 'ETIMEOUT'})), + }) + .open(request.method, request.url, true); + if (request.credentials === 'include') { + xhr.withCredentials = true; + } + xhr.responseType = 'blob'; + for (const [name, value] of request.headers.entries()) { + xhr.setRequestHeader(name, value); + } + xhr.send(isUndefined(request.bodyInit) ? null : request.bodyInit); + }), + {xhr, abort: () => xhr.abort()} + ); +} diff --git a/pool/shard000/JavaScript/0001392_mysqlModel.js b/pool/shard000/JavaScript/0001392_mysqlModel.js new file mode 100644 index 0000000000000000000000000000000000000000..7d9b72b116e2218e02e6fcf47fed943d74fb8f07 --- /dev/null +++ b/pool/shard000/JavaScript/0001392_mysqlModel.js @@ -0,0 +1,28 @@ +var graphlib = require('graphlib'); +var Promise = require('promise'); + +function Collection(node) +{ + this.select = '*'; + this.from = node.id; + this.where = null; + this.groupBy = null; + this.orderBy = null; +} + +Collection.prototype.with = function (params) +{ + +}; + +function MysqlModel(pool, nodes) +{ + this.context = pool; + this.tables = new graphlib.Graph(); + this.tables.nodes = nodes; + + nodes.forEach(function (n) + { + this[n.id] = new Collection(n); + }, this); +} diff --git a/pool/shard000/JavaScript/0001393_SettingsStore.js b/pool/shard000/JavaScript/0001393_SettingsStore.js new file mode 100644 index 0000000000000000000000000000000000000000..1dfb1dba0e6d314e7b1f3d1c6c4a1a34b74cf585 --- /dev/null +++ b/pool/shard000/JavaScript/0001393_SettingsStore.js @@ -0,0 +1,59 @@ +var AppDispatcher = require('../dispatcher/AppDispatcher'), + EventEmitter = require('events').EventEmitter, + assign = require('react/lib/Object.assign'), + Constants = require('../Constants'), + socket = require('socket'), + + CHANGE_EVENT = 'change', + API = { + GET_SETTINGS : 'plugins.ns-awards.getSettings', + SAVE_SETTINGS: 'plugins.ns-awards.saveSettings' + }, + _settings = {}; + +var SettingsStore = assign({}, EventEmitter.prototype, { + addChangeListener: function (listener) { + this.on(CHANGE_EVENT, listener); + }, + + emitChange: function () { + this.emit(CHANGE_EVENT); + }, + + getSettings: function () { + return _settings; + }, + + removeChangeListener: function (listener) { + this.removeListener(CHANGE_EVENT, listener); + } +}); + +AppDispatcher.register(function (action) { + switch (action.actionType) { + case Constants.EVENT_GET_SETTINGS: + socket.emit(API.GET_SETTINGS, {}, function (error, settings) { + if (error) { + console.error(error); + } + _settings = settings; + SettingsStore.emitChange(); + }); + break; + case Constants.EVENT_SAVE_SETTINGS: + socket.emit(API.SAVE_SETTINGS, { + settings: action.settings + }, function (error, settings) { + if (error) { + console.error(error); + } + _settings = settings; + SettingsStore.emitChange(); + }); + break; + default: + return true; + } +}); + +module.exports = SettingsStore; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0001398_smartphone.js b/pool/shard000/JavaScript/0001398_smartphone.js new file mode 100644 index 0000000000000000000000000000000000000000..c1659a83773c8825c37e63cbaae91b4f1ab53d6f --- /dev/null +++ b/pool/shard000/JavaScript/0001398_smartphone.js @@ -0,0 +1,32 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _pure = require('recompose/pure'); + +var _pure2 = _interopRequireDefault(_pure); + +var _SvgIcon = require('../../SvgIcon'); + +var _SvgIcon2 = _interopRequireDefault(_SvgIcon); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var HardwareSmartphone = function HardwareSmartphone(props) { + return _react2.default.createElement( + _SvgIcon2.default, + props, + _react2.default.createElement('path', { d: 'M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z' }) + ); +}; +HardwareSmartphone = (0, _pure2.default)(HardwareSmartphone); +HardwareSmartphone.displayName = 'HardwareSmartphone'; +HardwareSmartphone.muiName = 'SvgIcon'; + +exports.default = HardwareSmartphone; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0001400_PolylineComplex.js b/pool/shard000/JavaScript/0001400_PolylineComplex.js new file mode 100644 index 0000000000000000000000000000000000000000..456cf9941ee9e053ed6fb5be2ce73a610823f2d7 --- /dev/null +++ b/pool/shard000/JavaScript/0001400_PolylineComplex.js @@ -0,0 +1,100 @@ +import React from "react"; +import _ from "lodash"; +import PropTypes from "prop-types"; +import { FormProps, wrapWithForm } from "../../../../hocs/WrapWithForm"; +import { Polyline } from "../../../../../modules/polyline/Polyline"; +import { GoogleMap } from "../../../../../modules/google-map/GoogleMap"; + +export const pageName = "Complex Example"; + +const enhancer = wrapWithForm(); + +const getPath = _.flow( + x => _.get(x, ["routes", 0, "overview_path"]), + JSON.stringify, + JSON.parse, +); + +class PolylineComplex extends React.Component { + static contextTypes = { + maps: PropTypes.object.isRequired, + center: PropTypes.object.isRequired, + styles: PropTypes.object.isRequired, + }; + + static propTypes = { + origin: FormProps.oneOf("Origin", [ + "san jose, ca", + "palo alto, ca", + "gilroy, ca", + "salinas, ca", + "monterey, ca", + ]), + + destination: FormProps.oneOf("Destination", [ + "san jose, ca", + "palo alto, ca", + "gilroy, ca", + "salinas, ca", + "monterey, ca", + ]), + }; + + static defaultProps = { + origin: "san jose, ca", + destination: "gilroy, ca", + }; + + constructor(props, context) { + super(props, context); + + const { maps: { DirectionsService } } = context; + + this.state = { path: null }; + this.service = new DirectionsService(); + } + + componentDidMount() { + const { origin, destination } = this.props; + + this.fetchDirections(origin, destination); + } + + componentDidUpdate(prevProps) { + const { origin, destination } = this.props; + + if (origin !== prevProps.origin || destination !== prevProps.destination) { + this.fetchDirections(origin, destination); + } + } + + fetchDirections(origin, destination) { + if (origin && destination) { + this.setState({ path: null }); + + this.service.route( + { origin, destination, travelMode: "DRIVING" }, + (result, status) => { + if (status === "OK") { + this.setState({ path: getPath(result) }); + } else { + this.setState({ path: null }); + } + }, + ); + } + } + + render() { + const { path } = this.state; + const { maps, styles, center } = this.context; + + return ( + + {path && } + + ); + } +} + +export default enhancer(PolylineComplex); diff --git a/pool/shard000/JavaScript/0001411_newtonian.js b/pool/shard000/JavaScript/0001411_newtonian.js new file mode 100644 index 0000000000000000000000000000000000000000..98a173aa350db2ed438e591afe2531b46b174491 --- /dev/null +++ b/pool/shard000/JavaScript/0001411_newtonian.js @@ -0,0 +1,134 @@ +/** + * class NewtonianBehavior < Behavior + * + * `Physics.behavior('newtonian')`. + * + * Newtonian attraction between bodies (inverse square law). + * + * Additional options include: + * - strength: The strength of the interaction between bodies. (default: `1`) + * - max: The maximum distance between bodies at which to apply the behavior. (default: `false`... infinite) + * - min: The minimum distance between bodies at which to apply the behavior. (default: `false`... autocalculate) + **/ +Physics.behavior('newtonian', function( parent ){ + + var defaults = { + + strength: 1, + // max distance to apply it to + max: false, // infinite + // min distance to apply it to + min: false // auto calc + }; + + return { + + // extended + init: function( options ){ + + var self = this; + // call parent init method + parent.init.call( this ); + this.options.defaults( defaults ); + this.options.onChange(function( opts ){ + self._maxDistSq = opts.max === false ? Infinity : opts.max * opts.max; + self._minDistSq = opts.min ? opts.min * opts.min : 100 * opts.strength; + }); + this.options( options ); + }, + + calcPotential: function( posA, posB, out ){ + + var strength = this.options.strength + ,minDistSq = this._minDistSq + ,maxDistSq = this._maxDistSq + ,normsq + ,g + ,pos + ; + + pos = out || new Physics.vector(); + + // clone the position + pos.clone( posB ).vsub( posA ); + // get the square distance + normsq = pos.normSq(); + + if (normsq > minDistSq && normsq < maxDistSq){ + + g = strength / normsq; + return pos.normalize().mult( g ); + } + + return pos.zero(); + }, + + // extended + behave: function( data ){ + + var bodies = this.getTargets() + ,body + ,other + ,scratch = Physics.scratchpad() + ,potential = scratch.vector() + ,comp + ,bodyA + ,bodyB + ,posA = scratch.vector() + ,posB = scratch.vector() + ,i, j, k, m, l, ll, lll + ; + + for ( j = 0, l = bodies.length; j < l; j++ ){ + + body = bodies[ j ]; + + for ( i = j + 1; i < l; i++ ){ + + other = bodies[ i ]; + + if ( body.name === 'compound' ){ + comp = body; + } else if ( other.name === 'compound' ){ + comp = other; + other = body; + } + + if ( comp ){ + if ( other.name === 'compound' ){ + for ( k = 0, ll = comp.children.length; k < ll; k++ ){ + bodyA = comp.children[ k ]; + comp.toWorldCoords( posA.clone( bodyA.state.pos ).vadd( comp.offset ) ); + for ( m = 0, lll = other.children.length; m < lll; m++ ){ + bodyB = other.children[ m ]; + other.toWorldCoords( posB.clone( bodyB.state.pos ).vadd( other.offset ) ); + this.calcPotential( posA, posB, potential ); + comp.accelerate( potential.mult( bodyB.mass ) ); + other.accelerate( potential.mult( bodyA.mass/bodyB.mass ).negate() ); + } + } + } else { + for ( k = 0, ll = comp.children.length; k < ll; k++ ){ + bodyA = comp.children[ k ]; + comp.toWorldCoords( posA.clone( bodyA.state.pos ).vadd( comp.offset ) ); + this.calcPotential( posA, other.state.pos, potential ); + comp.accelerate( potential.mult( other.mass ) ); + other.accelerate( potential.mult( bodyA.mass/other.mass ).negate() ); + } + } + + } else { + + this.calcPotential( body.state.pos, other.state.pos, potential ); + body.accelerate( potential.mult( other.mass ) ); + other.accelerate( potential.mult( body.mass/other.mass ).negate() ); + } + + comp = null; + } + } + + scratch.done(); + } + }; +}); diff --git a/pool/shard000/JavaScript/0001412_alv-ch-ng.ui-core.directive.collapsible.unit.spec.js b/pool/shard000/JavaScript/0001412_alv-ch-ng.ui-core.directive.collapsible.unit.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..5fdd7610e10e6a015c7a1da6c4977d3204aec271 --- /dev/null +++ b/pool/shard000/JavaScript/0001412_alv-ch-ng.ui-core.directive.collapsible.unit.spec.js @@ -0,0 +1,21 @@ +;(function() { + + describe("collapsible directive", function() { + + beforeEach(module('alv-ch-ng.ui-core', function() { + + })); + + it('adds the necessary classes and attributes.', function() { + inject(function ($compile, $rootScope) { + var scope = $rootScope.$new(); + var elem = angular.element('
testContent
'); + $compile(elem)(scope); + expect(elem.html()).toEqual('
testContent
'); + }); + + }); + + }); + +}()); diff --git a/pool/shard000/JavaScript/0001417_2d.drawImage.9arg.destsize.worker.js b/pool/shard000/JavaScript/0001417_2d.drawImage.9arg.destsize.worker.js new file mode 100644 index 0000000000000000000000000000000000000000..780495f8c3c5663bfc01b7f6853a10414ce6b98c --- /dev/null +++ b/pool/shard000/JavaScript/0001417_2d.drawImage.9arg.destsize.worker.js @@ -0,0 +1,56 @@ +// DO NOT EDIT! This test has been generated by /offscreen-canvas/tools/gentest.py. +// OffscreenCanvas test in a worker:2d.drawImage.9arg.destsize +// Description: +// Note: + +importScripts("/resources/testharness.js"); +importScripts("/2dcontext/resources/canvas-tests.js"); + +var t = async_test(""); +var t_pass = t.done.bind(t); +var t_fail = t.step_func(function(reason) { + throw reason; +}); +t.step(function() { + +var offscreenCanvas = new OffscreenCanvas(100, 50); +var ctx = offscreenCanvas.getContext('2d'); + +ctx.fillStyle = '#f00'; +ctx.fillRect(0, 0, 100, 50); +var promise1 = new Promise(function(resolve, reject) { + var xhr = new XMLHttpRequest(); + xhr.open("GET", '/images/red.png'); + xhr.responseType = 'blob'; + xhr.send(); + xhr.onload = function() { + resolve(xhr.response); + }; +}); +var promise2 = new Promise(function(resolve, reject) { + var xhr = new XMLHttpRequest(); + xhr.open("GET", '/images/green.png'); + xhr.responseType = 'blob'; + xhr.send(); + xhr.onload = function() { + resolve(xhr.response); + }; +}); +Promise.all([promise1, promise2]).then(function(response1, response2) { + var promise3 = createImageBitmap(response1); + var promise4 = createImageBitmap(response2); + Promise.all([promise3, promise4]).then(function(bitmap1, bitmap2) { + ctx.drawImage(bitmap2, 1, 1, 1, 1, 0, 0, 100, 50); + ctx.drawImage(bitmap1, 0, 0, 100, 50, -50, 0, 50, 50); + ctx.drawImage(bitmap1, 0, 0, 100, 50, 100, 0, 50, 50); + ctx.drawImage(bitmap1, 0, 0, 100, 50, 0, -25, 100, 25); + ctx.drawImage(bitmap1, 0, 0, 100, 50, 0, 50, 100, 25); + _assertPixelApprox(offscreenCanvas, 0,0, 0,255,0,255, "0,0", "0,255,0,255", 2); + _assertPixelApprox(offscreenCanvas, 99,0, 0,255,0,255, "99,0", "0,255,0,255", 2); + _assertPixelApprox(offscreenCanvas, 0,49, 0,255,0,255, "0,49", "0,255,0,255", 2); + _assertPixelApprox(offscreenCanvas, 99,49, 0,255,0,255, "99,49", "0,255,0,255", 2); + }, t_fail); +}).then(t_pass, t_fail); + +}); +done(); diff --git a/pool/shard000/JavaScript/0001418_anim1.js b/pool/shard000/JavaScript/0001418_anim1.js new file mode 100644 index 0000000000000000000000000000000000000000..7154c1e0b2bc2caba903d2c8843a30477d802727 --- /dev/null +++ b/pool/shard000/JavaScript/0001418_anim1.js @@ -0,0 +1,34 @@ +engine.ImportExtension("qt.core"); +engine.ImportExtension("qt.gui"); + +var label = new QLabel(); +label.objectName = "InfoLabel"; +label.setStyleSheet("QLabel#InfoLabel { padding: 10px; background-color: rgba(230,230,230,10); border: 1px solid black; font-size: 16px; }"); +label.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\n\ +tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim\n\ +veniam, quis nostrudexercitation ullamco laboris nisi ut aliquip ex ea\n\ +commodo consequat. Duis aute irure dolor in reprehenderit in voluptate\n\ +velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint\n\ +occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit\n\ +anim id est laborum."; + +var proxy = ui.AddWidgetToScene(label); + +proxy.windowFlags = 0; +proxy.visible = true; +proxy.focusPolicy = Qt.NoFocus; +proxy.x = 400; +proxy.y = 300; + +frame.Updated.connect(OnFrameUpdate); +function OnFrameUpdate() +{ + var alpha = (Math.sin(frame.WallClockTime()*5)*0.5 + 0.5) * 255; +// label.setStyleSheet("QLabel#InfoLabel { padding: 10px; background-color: rgba(230,230,230," + alpha + "); border: 1px solid black; font-size: 16px; }"); + label.resize(600 + Math.sin(frame.WallClockTime()) * 30, 300 + Math.cos(frame.WallClockTime()) * 100); +} + +function OnScriptDestroyed() +{ + label.deleteLater(); +} diff --git a/pool/shard000/JavaScript/0001420_main.js b/pool/shard000/JavaScript/0001420_main.js new file mode 100644 index 0000000000000000000000000000000000000000..8c9ad1559c369659690484799129c99be64994f7 --- /dev/null +++ b/pool/shard000/JavaScript/0001420_main.js @@ -0,0 +1,49 @@ + var express = require('express'); + var app = express(); + + app.use(express.bodyParser()); // Populate req.body + + // // basic auth not enabled for this route + // app.get('/', function(req, res) { + // res.send('Unathorized request made'); + // }); + // // basic auth not enabled for this route + // app.get('/testget', function(req, res) { + // //res.send('Request made with get to test'); + // var Message = Parse.Object.extend("Message"); + // var message = new Message(); + // message.save({ + // text: req.body.text + // }).then(function(message) { + // res.send('Success saving the var' + req.body.text); + // }, function(error) { + // res.status(500); + // res.send('Error'); + // }); + // }); + + // basic auth is enabled for this route + app.post('/test', + // express.basicAuth('username', 'password'), + + function(req, res) { + console.log("Body is: "+req.body); + console.log("Body Name is: "+req.param('message')); + if (req.body.message == "hello") { + var Message = Parse.Object.extend("Message"); + var message = new Message(); + message.save({ + username: req.body.message + }).then(function(message) { + res.send('Success saving the user: ' +req.body.message); + }, function(error) { + res.status(500); + res.send('Error'); + }); + }else{ + res.status(406); + res.send('Bad username'); + } + }); + + app.listen(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0001425_event-schedule.js b/pool/shard000/JavaScript/0001425_event-schedule.js new file mode 100644 index 0000000000000000000000000000000000000000..6717d832539da5627700f2f23eb6d571757a054d --- /dev/null +++ b/pool/shard000/JavaScript/0001425_event-schedule.js @@ -0,0 +1,88 @@ +'use strict'; + +export default class Widget { + constructor(selector) { + this.$root = $(selector); + this.locals = this._getDom(); + + const $firstLink = this.locals.$links.first(); + this._setInitialValues(); + this.filterListByLink($firstLink); + this._assignEvents(); + } + + _getDom() { + return { + $links: this.$root.find('[data-upevent-link]'), + $total: this.$root.find('[data-upevent-total]'), + $now: this.$root.find('[data-upevent-now]'), + $items: this.$root.find('.b-eventfut'), + $text: this.$root.find('[data-upevent-text]'), + $switcher: this.$root.find('[data-schedule-switcher]') + }; + } + + _setInitialValues(){ + const locals = this.locals; + const currentCount = locals.$items.filter('.current').length; + + locals.$total.text(locals.$items.length); + locals.$now.text(locals.$items.filter('.current').length); + + switch (currentCount) { + case 0: + locals.$switcher.hide(); + break; + case 1: + locals.$text.text('is running now'); + break; + default: + locals.$text.text('are running now'); + break; + } + } + + _assignEvents() { + this.$root.on('click', '[data-upevent-link]', this._onClickFilter.bind(this)); + } + + _onClickFilter(e){ + e.preventDefault(); + const $link = $(e.target).closest('[data-upevent-link]'); + + if ($link.hasClass('state_active')) return; + this.filterListByLink($link); + } + + filterListByLink($el){ + const locals = this.locals; + const filterClass = $el.data('upevent-link'); + const $filtered = filterClass? locals.$items.filter('.' + filterClass): null ; + + locals.$items.removeClass('b-eventfut_state_disabled'); + if ($filtered) { + locals.$items.addClass('b-eventfut_state_disabled'); + $filtered.removeClass('b-eventfut_state_disabled'); + } + + locals.$links.removeClass('state_active'); + $el.addClass('state_active'); + } + + // static + static plugin(selector) { + const $elems = $(selector); + if (!$elems.length) return; + + return $elems.each(function (index, el) { + let $element = $(el); + let data = $element.data('hmt.events.upcoming'); + + if (!data) { + data = new Widget(el); + $element.data('widget', data); + } + }) + } +} + diff --git a/pool/shard000/JavaScript/0001428_userForgot.js b/pool/shard000/JavaScript/0001428_userForgot.js new file mode 100644 index 0000000000000000000000000000000000000000..d625524779ad203f276cf35515405ae598b02f64 --- /dev/null +++ b/pool/shard000/JavaScript/0001428_userForgot.js @@ -0,0 +1,235 @@ +function __processArg(obj, key) { + var arg = null; + if (obj) { + arg = obj[key] || null; + delete obj[key]; + } + return arg; +} + +function Controller() { + require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); + this.__controllerPath = "userForgot"; + if (arguments[0]) { + { + __processArg(arguments[0], "__parentSymbol"); + } + { + __processArg(arguments[0], "$model"); + } + { + __processArg(arguments[0], "__itemTemplate"); + } + } + var $ = this; + var exports = {}; + var __defers = {}; + $.__views.userForgot = Ti.UI.createWindow({ + backgroundColor: "#FFF", + opacity: 1, + width: Ti.UI.FILL, + height: Ti.UI.FILL, + layout: "vertical", + navBarHidden: true, + id: "userForgot" + }); + $.__views.userForgot && $.addTopLevelView($.__views.userForgot); + $.__views.__alloyId32 = Ti.UI.createView({ + height: Ti.UI.SIZE, + width: Ti.UI.FILL, + backgroundColor: Alloy.CFG.Colors.MainColor, + top: 0, + id: "__alloyId32" + }); + $.__views.userForgot.add($.__views.__alloyId32); + $.__views.AppWrapper = Ti.UI.createView({ + height: Ti.UI.SIZE, + id: "AppWrapper" + }); + $.__views.__alloyId32.add($.__views.AppWrapper); + $.__views.mainTitle = Ti.UI.createLabel({ + font: { + fontSize: 20, + fontFamily: "Monda-Regular" + }, + height: 44.4, + color: "#FFF", + left: "30", + id: "mainTitle", + text: "Forgot Password" + }); + $.__views.AppWrapper.add($.__views.mainTitle); + closeWindow ? $.__views.mainTitle.addEventListener("click", closeWindow) : __defers["$.__views.mainTitle!click!closeWindow"] = true; + $.__views.imgBack = Ti.UI.createImageView({ + left: 5, + width: 30, + height: 30, + right: 5, + id: "imgBack" + }); + $.__views.AppWrapper.add($.__views.imgBack); + closeWindow ? $.__views.imgBack.addEventListener("click", closeWindow) : __defers["$.__views.imgBack!click!closeWindow"] = true; + $.__views.forgotPasswordView = Ti.UI.createScrollView({ + layout: "vertical", + left: 15, + right: 15, + top: 5, + id: "forgotPasswordView" + }); + $.__views.userForgot.add($.__views.forgotPasswordView); + $.__views.__alloyId33 = Ti.UI.createView({ + layout: "horizontal", + width: Ti.UI.SIZE, + height: Ti.UI.SIZE, + top: 5, + left: "0", + id: "__alloyId33" + }); + $.__views.forgotPasswordView.add($.__views.__alloyId33); + $.__views.imgEmailForgot = Ti.UI.createImageView({ + top: 15, + width: 15, + height: 15, + left: 5, + right: 5, + id: "imgEmailForgot" + }); + $.__views.__alloyId33.add($.__views.imgEmailForgot); + $.__views.lblEmail = Ti.UI.createLabel({ + font: { + fontSize: 17, + fontFamily: "Monda-Regular", + fontWeight: "bold" + }, + height: Ti.UI.SIZE, + textAlign: "left", + text: "Email", + top: "9", + color: "#464646", + id: "lblEmail" + }); + $.__views.__alloyId33.add($.__views.lblEmail); + $.__views.txtEmailForgot = Ti.UI.createTextField({ + top: 5, + width: "98%", + left: "1%", + right: "1%", + borderWidth: 1, + borderColor: Alloy.CFG.Colors.MainColor, + backgroundColor: "#EEE", + color: "#222", + font: { + fontFamily: "Monda-Regular" + }, + borderRadius: 7, + id: "txtEmailForgot", + hintText: "Email" + }); + $.__views.forgotPasswordView.add($.__views.txtEmailForgot); + $.__views.btnRequest = Ti.UI.createButton({ + font: { + fontSize: 13, + fontFamily: "Monda-Regular" + }, + height: 33.3, + top: 20, + bottom: 10, + width: "98%", + left: "1%", + right: "1%", + backgroundColor: Alloy.CFG.Colors.MainColor, + backgroundSelectedColor: Alloy.CFG.Colors.MainColor_Dark, + borderColor: Alloy.CFG.Colors.MainPressedColor, + color: Alloy.CFG.Colors.TextColor, + backgroundImage: "null", + selectedColor: "#AAA", + id: "btnRequest", + title: " Request " + }); + $.__views.forgotPasswordView.add($.__views.btnRequest); + forgotProcess ? $.__views.btnRequest.addEventListener("click", forgotProcess) : __defers["$.__views.btnRequest!click!forgotProcess"] = true; + exports.destroy = function() {}; + _.extend($, $.__views); + arguments[0] || {}; + var __ = require("platformSupport"); + var myAnimation = require("animation"); + var loader = require("loader"); + var validation = require("validationRules"); + var dialogBox = require("psdialog"); + var changeFlag = 0; + var fontIconLoader = require("icomoonlib"); + var changeFlag = 0; + var loadingWindow = require("loadingWindow"); + loadingWindow.endLoading(); + __.isiOS7Plus() && ($.AppWrapper.top = 20); + var closeWindow = function() { + myAnimation.out($.userForgot); + }; + var forgotProcess = function() { + if (validationForgotChecking()) if (true == Titanium.Network.online) { + loadingWindow.startLoading(); + var loaderArgs = { + callbackFunction: forgotPasswordSent, + url: Alloy.CFG.Urls.BaseURL + ALloy.CFG.Urls.getForgotPassword + $.txtEmailForgot.value.toLowerCase() + }; + loader.get(loaderArgs); + } else dialogBox.loadCustomDialog("Forgot Password", Alloy.CFG.Languages.offlineMessage); + }; + var forgotPasswordSent = function(feeds) { + loadingWindow.endLoading(); + if (feeds.success) { + dialogBox.loadCustomDialog("Forgot Password", Alloy.CFG.Languages.forgotPasswordMessage); + closeWindow(); + } + }; + var validationForgotChecking = function() { + if ("" == $.txtEmailForgot.value) { + validation.validationFailAction($.txtEmailForgot); + changeFlag = 0; + return false; + } + if (!validation.validateEmail($.txtEmailForgot.value)) { + validation.validationFailAction($.txtEmailForgot); + changeFlag = 0; + return false; + } + return true; + }; + $.txtEmailForgot.addEventListener("change", function() { + if (0 == changeFlag) { + validation.backToNormal($.txtEmailForgot); + changeFlag = 1; + } + }); + var loadIcon = function() { + var emailIcon = fontIconLoader.getIcon("panacea", "envelope", 35, { + color: Alloy.CFG.Colors.IconColor + }); + $.imgEmailForgot.image = emailIcon; + var backIcon = fontIconLoader.getIcon("panacea", "back", 35, { + color: Alloy.CFG.Colors.IconWhite + }); + $.imgBack.image = backIcon; + }; + var loadLanguage = function() { + $.lblEmail.text = Alloy.CFG.Languages.lblEmail; + $.btnRequest.title = Alloy.CFG.Languages.btnRequest; + }; + var init = function() { + loadIcon(); + loadLanguage(); + myAnimation.slowlyAppear($.forgotPasswordView); + }; + $.userForgot.addEventListener("open", function() { + loadingWindow.endLoading(); + init(); + }); + __defers["$.__views.mainTitle!click!closeWindow"] && $.__views.mainTitle.addEventListener("click", closeWindow); + __defers["$.__views.imgBack!click!closeWindow"] && $.__views.imgBack.addEventListener("click", closeWindow); + __defers["$.__views.btnRequest!click!forgotProcess"] && $.__views.btnRequest.addEventListener("click", forgotProcess); + _.extend($, exports); +} + +var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; + +module.exports = Controller; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0001432_root.test.js b/pool/shard000/JavaScript/0001432_root.test.js new file mode 100644 index 0000000000000000000000000000000000000000..19b68971963d3b0009dd57725afe2544fe76e197 --- /dev/null +++ b/pool/shard000/JavaScript/0001432_root.test.js @@ -0,0 +1,31 @@ +import React from "react"; +import expect from "expect"; +import { shallow } from 'enzyme'; + +import Root from "./root"; +import Header from "./header"; + +describe("/components/root", () => { + + let root; + + beforeEach(() => { + root = shallow(); + }); + + it("should render", () => { + expect(root).toExist(); + }); + + it("should contains one Header element", () => { + const header = root.find(Header); + expect(header.length).toEqual(1); + }); + + it("should render children component", () => { + root = shallow(

any child

); + const question = root.find("p"); + expect(question.length).toEqual(1); + }); + +}); diff --git a/pool/shard000/JavaScript/0001433_profile.js b/pool/shard000/JavaScript/0001433_profile.js new file mode 100644 index 0000000000000000000000000000000000000000..bf8a6ca38f504c99f6f0a0e6801c713ad58956cb --- /dev/null +++ b/pool/shard000/JavaScript/0001433_profile.js @@ -0,0 +1,52 @@ +import React from 'react'; + +import { Button, Checkbox } from 'react-bootstrap'; + +import './styles.scss'; + +class Profile extends React.Component { + constructor(props) { + super(props); + this.state = { + showDetails: false, + count: 0, + }; + this.handleClick = this.handleClick.bind(this); + this.handleChangeSelection = this.handleChangeSelection.bind(this); + } + handleClick() { + global.console.log('button clicked'); + this.setState({ + showDetails: true, + }); + } + handleChangeSelection() { + this.setState({ + showDetails: !this.state.showDetails, + count: this.state.count + 1, + }); + } + render() { + const { showDetails } = this.state; + let name = this.props.name; + return ( +
+

{name}

+ + Mostrar detalhes ({this.state.count}) + + +
+ ); + } +} + +Profile.propTypes = { + name: React.PropTypes.string, +}; + +Profile.defaultProps = { + name: 'unnamed', +}; + +export default Profile; diff --git a/pool/shard000/JavaScript/0001434_table.row.js b/pool/shard000/JavaScript/0001434_table.row.js new file mode 100644 index 0000000000000000000000000000000000000000..345c913ba0f0e1997d8914d4022834e1760902b3 --- /dev/null +++ b/pool/shard000/JavaScript/0001434_table.row.js @@ -0,0 +1,89 @@ +'use strict'; + +// Register `phoneList` component, along with its associated controller and template +angular. +module('raceConditions').controller('tableRowController', function tableController($location,$scope,$rootScope,$timeout,$interval,$http) { + //INTERVAL + var init = function (){ + if(!$rootScope.registered){ + $location.url('/login'); + } + } + init(); + + var timer; + $scope.count = 0; + timer = $interval(getTableAsync,2500); + + var getTableSuccess = function(responseData){ + $scope.done=false; + console.log("getTableSuccess"); + console.log(responseData.data); + if(responseData.data.status == "error"){ + $rootScope.registered = false; + $location.url('/login'); + } + $scope.table = responseData.data.ret; + } + + var getTableError = function(error){ + console.log("getTableError"); + console.log(error); + } + + var getTableAsync= function () { + var data = JSON.stringify({ + "tableInfoKey": $rootScope.tableKey + }); + $http.post($rootScope.RCURL+"/tableAPI/v1/getTable",data,$rootScope.requestConfig).then(getTableSuccess,getTableError); + } + getTableAsync(); + + var inputChangedPromise; + $scope.inputChanged = function(){ + $interval.cancel(timer); + if(inputChangedPromise){ + $timeout.cancel(inputChangedPromise); + } + inputChangedPromise = $timeout(updateValues,1000); + } + + var updateValuesSuccess = function(responseData){ + + console.log("updateValuesSuccess"); + console.log(responseData.data); + if(responseData.data.status == "error"){ + $rootScope.registered = false; + $location.url('/login'); + } + timer = $interval(getTableAsync,2500); + } + + var updateValuesError = function(error){ + console.log("updateValuesError"); + console.log(error); + } + + var updateValues = function(){ + var data = JSON.stringify({ + "tableInfoKey": $scope.table.tableInfoKey, + "columnKey": $scope.id, + "columnNames": [ + $scope.table.columnNames[$scope.index] + ], + "columnValues": [ + $scope.model[$scope.id + $scope.index] + ] + }); + $http.post($rootScope.RCURL+"/tableAPI/v1/modifyRow",data,$rootScope.requestConfig).then(updateValuesSuccess,updateValuesError); + } + + $scope.eEditable= -1; + $scope.eElement; + $scope.model={}; + $scope.editing = function (id, index) { + $scope.id =id; + $scope.index =index; + $scope.eEditable = index; + } + }); diff --git a/pool/shard000/JavaScript/0001436_socket.js b/pool/shard000/JavaScript/0001436_socket.js new file mode 100644 index 0000000000000000000000000000000000000000..e4b7aeeada3ad9dccbbd6c29a4f56b934a0db5ba --- /dev/null +++ b/pool/shard000/JavaScript/0001436_socket.js @@ -0,0 +1,61 @@ +/** + * carcassonne-scoreboard-client + * + * @author Andrea Sonny + * @license MIT + * + * https://andreasonny.mit-license.org/ + * + */ +(function() { + 'use strict'; + + angular + .module('socket', []) + .factory('socket', factory); + + factory.$inject = ['$rootScope', 'serverApp']; + + /* @ngInject */ + function factory($rootScope, serverApp) { + // server url + var socket = io(serverApp.server + ':' + serverApp.port); + + function on(eventName, callback) { + // prevent creating multiple listeners + if ( socket._callbacks['$'+eventName] ) { + socket._callbacks['$'+eventName] = []; + } + + socket.on(eventName, function () { + var args = arguments; + + $rootScope.$apply(function () { + callback.apply(socket, args); + }); + }); + } + + function emit(eventName, data, callback) { + // prevent creating multiple listeners + if ( socket._callbacks['$'+eventName] ) { + socket._callbacks['$'+eventName] = []; + } + + socket.emit(eventName, data, function () { + var args = arguments; + + $rootScope.$apply(function () { + if (callback) { + callback.apply(socket, args); + } + }); + }); + } + + return { + on: on, + emit: emit + }; + } +})(); diff --git a/pool/shard000/JavaScript/0001439_partida.js b/pool/shard000/JavaScript/0001439_partida.js new file mode 100644 index 0000000000000000000000000000000000000000..fa105437b01e66ee88270dd39010e5a99a2945c7 --- /dev/null +++ b/pool/shard000/JavaScript/0001439_partida.js @@ -0,0 +1,25 @@ +"use strict"; + +module.exports = function(sequelize, DataTypes) { + var Partida = sequelize.define('partida', { + id: {type: DataTypes.BIGINT, primaryKey: true, autoIncrement: true, unique: true}, + data: DataTypes.DATE + }, { + freezeTableName: true, + underscored: true, + classMethods: { + associate: function(models) { + Partida.hasOne(models.time, { + as : 'timeA', + foreignKey : 'fk_partida_time_a' + }); + Partida.hasOne(models.time, { + as : 'timeB', + foreignKey : 'fk_partida_time_b' + }); + Partida.hasOne(models.local); + } + } + }); + return Partida; +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0001441_knockout-switch-case.js b/pool/shard000/JavaScript/0001441_knockout-switch-case.js new file mode 100644 index 0000000000000000000000000000000000000000..17631a3bbf6f605a0c9f3e3239be9ea98780da65 --- /dev/null +++ b/pool/shard000/JavaScript/0001441_knockout-switch-case.js @@ -0,0 +1,209 @@ +/** + * @license SWITCH/CASE binding for Knockout http://knockoutjs.com/ + * (c) Michael Best + * License: MIT (http://www.opensource.org/licenses/mit-license.php) + * Version 2.1.0 + */ + +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['knockout'], factory); + } else { + // Browser globals + factory(root.ko); + } +}(this, function (ko) { + + var undefined; + + if (!ko.virtualElements) + throw Error('Switch-case requires at least Knockout 2.1'); + + var ko_virtualElements = ko.virtualElements; + var ko_bindingFlags = ko.bindingFlags || {}; + var ko_bindingRewriteValidators = ko.bindingRewriteValidators || ko.jsonExpressionRewriting.bindingRewriteValidators; + var ko_unwrap = ko.utils.unwrapObservable; + var ko_bindingHandlers = ko.bindingHandlers; + + var defaultvalue = {}; + ko_bindingHandlers['switch'] = { + flags: ko_bindingFlags.contentBind | ko_bindingFlags.canUseVirtual | ko_bindingFlags.noValue, + init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { + var switchSkipNextArray = [], + switchBindings = { + // these properties are internal + $switchSkipNextArray: switchSkipNextArray, + $switchValueAccessor: valueAccessor, + $switchDefault: ko.observable(true), + // these properties are public + $default: defaultvalue, + $else: defaultvalue + }, + contexts = []; + + // Update $value in each context when it changes + ko.computed(function () { + var value = ko_unwrap(valueAccessor()); + switchBindings.$value = value; + ko.utils.arrayForEach(contexts, function (context) { + context.$value = value; + }); + }, null, { disposeWhenNodeIsRemoved: element }); + + // Each child element gets a new binding context so it can set its own $switchIndex property. + // The other properties will be shared since they're objects. + var node, nextInQueue = ko_virtualElements.firstChild(element); + while (node = nextInQueue) { + nextInQueue = ko_virtualElements.nextSibling(node); + switch (node.nodeType) { + case 1: case 8: + var newContext = bindingContext.extend(switchBindings); + // Set initial value of context.$switchIndex to undefined + newContext.$switchIndex = undefined; + ko.applyBindings(newContext, node); + // Add the context to the list to be updated if this section contained a case binding + if (newContext.$switchIndex !== undefined) { + contexts.push(newContext); + } + break; + } + } + + return { controlsDescendantBindings: true }; + }, + preprocess: function (value) { + return value || 'true'; + } + }; + ko_bindingRewriteValidators['switch'] = false; // Can't rewrite control flow bindings + ko_virtualElements.allowedBindings['switch'] = true; + + function checkCase(value, bindingContext) { + // Check value and determine result: + // If the control value is boolean, the result is the matching truthiness of the value + // If value is boolean, the result is the value (allows expressions instead of just simple matching) + // If value is an array, the result is true if the control value matches (strict) an item in the array + // Otherwise, the result is true if value matches the control value (loose) + var switchValue = ko_unwrap(bindingContext.$switchValueAccessor()); + return (typeof switchValue == 'boolean') + ? (value ? switchValue : !switchValue) + : (typeof value == 'boolean') + ? value + : (value instanceof Array) + ? (ko.utils.arrayIndexOf(value, switchValue) !== -1) + : (value == switchValue); + } + + function checkNotCase(value, bindingContext) { + return !checkCase(value, bindingContext); + } + + function defaultMakeValueAccessor(ifValue) { + return function () { return ifValue }; + } + + function makeCaseHandler(binding, isNot, makeValueAccessor) { + var checkFunction = isNot ? checkNotCase : checkCase; + binding || (binding = 'if'); + makeValueAccessor || (makeValueAccessor = defaultMakeValueAccessor); + + return { + // Inherit flags from the binding we're wrapping + flags: ko_bindingHandlers[binding].flags, + + init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { + if (!bindingContext.$switchSkipNextArray) + throw Error("case binding must only be used with a switch binding"); + if (bindingContext.$switchIndex !== undefined) + throw Error("case binding cannot be nested"); + // Initialize $switchIndex and push a new observable to $switchSkipNextArray + bindingContext.$switchIndex = bindingContext.$switchSkipNextArray.push(ko.observable(false)) - 1; + + bindingContext.$caseValue = ko.observable(); + + ko.computed(function () { + var index = bindingContext.$switchIndex, + isLast = (index === bindingContext.$switchSkipNextArray.length - 1), + result, skipNext, noDefault; + + if (index && bindingContext.$switchSkipNextArray[index - 1]()) { + // An earlier case binding matched: skip this one (and subsequent ones) + result = false; + skipNext = true; + } else { + var value = ko_unwrap(valueAccessor()); + if (value === bindingContext.$else) { + // If value is the special object $else, the result depends on the other case values. + // If we're the last *case* item, the value must be true. $switchDefault will get + // updated to *true* below, but that won't necessarily update us because it would + // require a recursive update. + result = bindingContext.$switchDefault() || isLast; + skipNext = false; + } else { + // If result is true, we will skip the subsequent cases (and any default cases) + noDefault = skipNext = result = checkFunction(value, bindingContext); + } + } + + // Set the observable used by the wrapped binding function + bindingContext.$caseValue(result); + + // Update the observable "skip next" value; if the value is changed, this will update the + // subsequent case item. + bindingContext.$switchSkipNextArray[index](skipNext); + + // Update $switchDefault to false if a non-default case item has matched. + // Update it to true if we're the last item and none of items have matched. + // (Initially, every item will be the last, but it doesn't matter.) + if (noDefault) + bindingContext.$switchDefault(false); + else if (!skipNext && isLast) + bindingContext.$switchDefault(true); + }, + null, { disposeWhenNodeIsRemoved: element }); + + // Call init with the observable result value + if (ko_bindingHandlers[binding].init) { + return ko_bindingHandlers[binding].init(element, + makeValueAccessor(bindingContext.$caseValue), allBindings, viewModel, bindingContext); + } + }, + + update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { + // Call update with the observable result value + if (ko_bindingHandlers[binding].update) { + return ko_bindingHandlers[binding].update(element, + makeValueAccessor(bindingContext.$caseValue), allBindings, viewModel, bindingContext); + } + } + }; + } + // Support dynamically creating new case binding when using Punches plugin + function getNamespacedHandler(bindingName, namespace, bindingKey) { + if (ko_virtualElements.allowedBindings[bindingName]) + ko_virtualElements.allowedBindings[bindingKey] = true; + return makeCaseHandler(bindingName, namespace === 'casenot'); + } + // Support dynamically creating new case binding when using key.subkey plugin + function makeSubkeyHandler(baseKey, subKey, bindingKey) { + return getNamespacedHandler(subKey, baseKey, bindingKey); + } + + function makeBaseHandler(name, isNot) { + ko_bindingHandlers[name] = makeCaseHandler('if', isNot); + ko_bindingRewriteValidators[name] = false; // Can't rewrite control flow bindings + ko_virtualElements.allowedBindings[name] = true; + ko_bindingHandlers[name].makeSubkeyHandler = makeSubkeyHandler; + ko_bindingHandlers[name].getNamespacedHandler = getNamespacedHandler; + } + + makeBaseHandler('case'); + makeBaseHandler('casenot', true /*isNot*/); + + ko_bindingHandlers['case.visible'] = makeCaseHandler('visible'); + ko_bindingHandlers['casenot.visible'] = makeCaseHandler('visible', true /*isNot*/); + + ko_bindingHandlers['switch'].makeCaseHandler = makeCaseHandler; + +})); diff --git a/pool/shard000/JavaScript/0001445_svg-painter.js b/pool/shard000/JavaScript/0001445_svg-painter.js new file mode 100644 index 0000000000000000000000000000000000000000..6a45c938474596d2e4d927128e4af797f89fc9c6 --- /dev/null +++ b/pool/shard000/JavaScript/0001445_svg-painter.js @@ -0,0 +1,200 @@ +;var svgPainter = ( function( $, window, document, undefined ) { + + 'use strict'; + + $(document).ready( function() { + + // detection for browser SVG capability + if ( document.implementation.hasFeature( 'http://www.w3.org/TR/SVG11/feature#Image', '1.1' ) ) { + document.body.className = document.body.className.replace( 'no-svg', 'svg' ); + } + + svgPainter.init(); + + }); + + return { + + elements : [], + + init : function() { + + this.adminMenu = $( '#adminmenu' ); + + this.setColors(); + this.findElements(); + this.paint(); + + }, + + setColors : function( colors ) { + + if ( typeof colors === 'undefined' && typeof mp6_color_scheme !== 'undefined' ) { + var colors = mp6_color_scheme; + } + + this.colorscheme = colors; + + }, + + findElements : function() { + + this.adminMenu.find( '.wp-menu-image' ).each(function() { + + var bgimg = $(this).css( 'background-image' ); + + if ( bgimg.indexOf( 'data:image/svg+xml;base64' ) != -1 ) { + svgPainter.elements.push( $(this) ); + } + + }); + + }, + + paint : function() { + + // loop through all elements + $.each( this.elements, function( index, $element ) { + + var $menuitem = $element.parent().parent(); + + if ( $menuitem.hasClass( 'current' ) || $menuitem.hasClass( 'wp-has-current-submenu' ) ) { + + // paint icon in 'current' color + svgPainter.paintElement( $element, svgPainter.colorscheme.icons.current ); + + } else { + + // paint icon in base color + svgPainter.paintElement( $element, svgPainter.colorscheme.icons.base ); + + // set hover callbacks + $menuitem.hover( + function() { svgPainter.paintElement( $element, svgPainter.colorscheme.icons.focus ); }, + function() { svgPainter.paintElement( $element, svgPainter.colorscheme.icons.base ); } + ); + + } + + }); + + }, + + paintElement : function( $element, color ) { + + // only accept hex colors: #101 or #101010 + if ( ! color.match( /^(#[0-9a-f]{3}|#[0-9a-f]{6})$/i ) ) + return; + + var xml = $element.data( 'mp6-svg-' + color ); + + if ( ! xml ) { + + var base64 = $element.css( 'background-image' ).match( /.+data:image\/svg\+xml;base64,(.+)\)/ ); + + if ( ! base64 ) + return; + + try { + var xml = window.atob( base64[1] ); + } catch ( e ) { + var xml = $.base64.atob( base64[1] ); + } + + // replace `fill` attributes + xml = xml.replace( /fill="(.+?)"/g, 'fill="' + color + '"'); + + // replace `style` attributes + xml = xml.replace( /style="(.+?)"/g, 'style="fill:' + color + '"'); + + // replace `fill` properties in ` Most commonly, a linear scale + * represents a 1-dimensional linear transformation from a numeric domain of + * input data [d0, d1] to a numeric range of + * pixels [r0, r1]. The equation for such a + * scale is: + * + *
f(x) = (x - d0) / (d1 - d0) * + * (r1 - r0) + r0
+ * + * For example, a linear scale from the domain [0, 100] to range [0, 640]: + * + *
f(x) = (x - 0) / (100 - 0) * (640 - 0) + 0
+ * f(x) = x / 100 * 640
+ * f(x) = x * 6.4
+ *
+ * + * Thus, saying + * + *
.height(function(d) d * 6.4)
+ * + * is identical to + * + *
.height(pv.Scale.linear(0, 100).range(0, 640))
+ * + * As you can see, scales do not always make code smaller, but they should make + * code more explicit and easier to maintain. In addition to readability, scales + * offer several useful features: + * + *

1. The range can be expressed in colors, rather than pixels. Changing the + * example above to + * + *

.fillStyle(pv.Scale.linear(0, 100).range("red", "green"))
+ * + * will cause it to fill the marks "red" on an input value of 0, "green" on an + * input value of 100, and some color in-between for intermediate values. + * + *

2. The domain and range can be subdivided for a "poly-linear" + * transformation. For example, you may want a diverging color scale that is + * increasingly red for negative values, and increasingly green for positive + * values: + * + *

.fillStyle(pv.Scale.linear(-1, 0, 1).range("red", "white", "green"))
+ * + * The domain can be specified as a series of n monotonically-increasing + * values; the range must also be specified as n values, resulting in + * n - 1 contiguous linear scales. + * + *

3. Linear scales can be inverted for interaction. The {@link #invert} + * method takes a value in the output range, and returns the corresponding value + * in the input domain. This is frequently used to convert the mouse location + * (see {@link pv.Mark#mouse}) to a value in the input domain. Note that + * inversion is only supported for numeric ranges, and not colors. + * + *

4. A scale can be queried for reasonable "tick" values. The {@link #ticks} + * method provides a convenient way to get a series of evenly-spaced rounded + * values in the input domain. Frequently these are used in conjunction with + * {@link pv.Rule} to display tick marks or grid lines. + * + *

5. A scale can be "niced" to extend the domain to suitable rounded + * numbers. If the minimum and maximum of the domain are messy because they are + * derived from data, you can use {@link #nice} to round these values down and + * up to even numbers. + * + * @param {number...} domain... domain values. + * @returns {pv.Scale.linear} a linear scale. + */ +pv.Scale.linear = function() { + var d = [0, 1], r = [0, 1], i = [pv.identity], precision = 0; + + /** @private */ + function scale(x) { + var j = pv.search(d, x); + if (j < 0) j = -j - 2; + j = Math.max(0, Math.min(i.length - 1, j)); + return i[j]((x - d[j]) / (d[j + 1] - d[j])); + } + + /** + * Sets or gets the input domain. This method can be invoked several ways: + * + *

1. domain(min, ..., max) + * + *

Specifying the domain as a series of numbers is the most explicit and + * recommended approach. Most commonly, two numbers are specified: the minimum + * and maximum value. However, for a diverging scale, or other subdivided + * poly-linear scales, multiple values can be specified. Values can be derived + * from data using {@link pv.min} and {@link pv.max}. For example: + * + *

.domain(0, pv.max(array))
+ * + * An alternative method for deriving minimum and maximum values from data + * follows. + * + *

2. domain(array, minf, maxf) + * + *

When both the minimum and maximum value are derived from data, the + * arguments to the domain method can be specified as the array of + * data, followed by zero, one or two accessor functions. For example, if the + * array of data is just an array of numbers: + * + *

.domain(array)
+ * + * On the other hand, if the array elements are objects representing stock + * values per day, and the domain should consider the stock's daily low and + * daily high: + * + *
.domain(array, function(d) d.low, function(d) d.high)
+ * + * The first method of setting the domain is preferred because it is more + * explicit; setting the domain using this second method should be used only + * if brevity is required. + * + *

3. domain() + * + *

Invoking the domain method with no arguments returns the + * current domain as an array of numbers. + * + * @function + * @name pv.Scale.linear.prototype.domain + * @param {number...} domain... domain values. + * @returns {pv.Scale.linear} this, or the current domain. + */ + scale.domain = function(array, min, max) { + if (arguments.length) { + if (array instanceof Array) { + if (arguments.length < 2) min = pv.identity; + if (arguments.length < 3) max = min; + d = [pv.min(array, min), pv.max(array, max)]; + } else { + d = Array.prototype.slice.call(arguments); + } + return this; + } + return d; + }; + + /** + * Sets or gets the output range. This method can be invoked several ways: + * + *

1. range(min, ..., max) + * + *

The range may be specified as a series of numbers or colors. Most + * commonly, two numbers are specified: the minimum and maximum pixel values. + * For a color scale, values may be specified as {@link pv.Color}s or + * equivalent strings. For a diverging scale, or other subdivided poly-linear + * scales, multiple values can be specified. For example: + * + *

.range("red", "white", "green")
+ * + *

Currently, only numbers and colors are supported as range values. The + * number of range values must exactly match the number of domain values, or + * the behavior of the scale is undefined. + * + *

2. range() + * + *

Invoking the range method with no arguments returns the current + * range as an array of numbers or colors. + * + * @function + * @name pv.Scale.linear.prototype.range + * @param {...} range... range values. + * @returns {pv.Scale.linear} this, or the current range. + */ + scale.range = function() { + if (arguments.length) { + r = Array.prototype.slice.call(arguments); + i = []; + for (var j = 0; j < r.length - 1; j++) { + i.push(pv.Scale.interpolator(r[j], r[j + 1])); + } + return this; + } + return r; + }; + + /** + * Inverts the specified value in the output range, returning the + * corresponding value in the input domain. This is frequently used to convert + * the mouse location (see {@link pv.Mark#mouse}) to a value in the input + * domain. Inversion is only supported for numeric ranges, and not colors. + * + *

Note that this method does not do any rounding or bounds checking. If + * the input domain is discrete (e.g., an array index), the returned value + * should be rounded. If the specified y value is outside the range, + * the returned value may be equivalently outside the input domain. + * + * @function + * @name pv.Scale.linear.prototype.invert + * @param {number} y a value in the output range (a pixel location). + * @returns {number} a value in the input domain. + */ + scale.invert = function(y) { + var j = pv.search(r, y); + if (j < 0) j = -j - 2; + j = Math.max(0, Math.min(i.length - 1, j)); + return (y - r[j]) / (r[j + 1] - r[j]) * (d[j + 1] - d[j]) + d[j]; + }; + + /** + * Returns an array of evenly-spaced, suitably-rounded values in the input + * domain. This method attempts to return between 5 and 10 tick values. These + * values are frequently used in conjunction with {@link pv.Rule} to display + * tick marks or grid lines. + * + * @function + * @name pv.Scale.linear.prototype.ticks + * @returns {number[]} an array input domain values to use as ticks. + */ + scale.ticks = function() { + var min = d[0], + max = d[d.length - 1], + span = max - min, + step = pv.logCeil(span / 10, 10); + if (span / step < 2) step /= 5; + else if (span / step < 5) step /= 2; + var start = Math.ceil(min / step) * step, + end = Math.floor(max / step) * step; + precision = Math.max(0, -Math.floor(pv.log(step, 10) + .01)); + return pv.range(start, end + step, step); + }; + + /** + * Formats the specified tick value using the appropriate precision, based on + * the step interval between tick marks. + * + * @function + * @name pv.Scale.linear.prototype.tickFormat + * @param {number} t a tick value. + * @return {string} a formatted tick value. + */ + scale.tickFormat = function(t) { + return t.toFixed(precision); + }; + + /** + * "Nices" this scale, extending the bounds of the input domain to + * evenly-rounded values. Nicing is useful if the domain is computed + * dynamically from data, and may be irregular. For example, given a domain of + * [0.20147987687960267, 0.996679553296417], a call to nice() might + * extend the domain to [0.2, 1]. + * + *

This method must be invoked each time after setting the domain. + * + * @function + * @name pv.Scale.linear.prototype.nice + * @returns {pv.Scale.linear} this. + */ + scale.nice = function() { + var min = d[0], + max = d[d.length - 1], + step = Math.pow(10, Math.round(Math.log(max - min) / Math.log(10)) - 1); + d = [Math.floor(min / step) * step, Math.ceil(max / step) * step]; + return this; + }; + + /** + * Returns a view of this scale by the specified accessor function f. + * Given a scale y, y.by(function(d) d.foo) is equivalent to + * function(d) y(d.foo). + * + *

This method is provided for convenience, such that scales can be + * succinctly defined inline. For example, given an array of data elements + * that have a score attribute with the domain [0, 1], the height + * property could be specified as: + * + *

.height(pv.Scale.linear().range(0, 480).by(function(d) d.score))
+ * + * This is equivalent to: + * + *
.height(function(d) d.score * 480)
+ * + * This method should be used judiciously; it is typically more clear to + * invoke the scale directly, passing in the value to be scaled. + * + * @function + * @name pv.Scale.linear.prototype.by + * @param {function} f an accessor function. + * @returns {pv.Scale.linear} a view of this scale by the specified accessor + * function. + */ + scale.by = function(f) { + function by() { return scale(f.apply(this, arguments)); } + for (var method in scale) by[method] = scale[method]; + return by; + }; + + scale.domain.apply(scale, arguments); + return scale; +}; diff --git a/pool/shard000/JavaScript/0002147_FileCollection.js b/pool/shard000/JavaScript/0002147_FileCollection.js new file mode 100644 index 0000000000000000000000000000000000000000..060381d223482a5915006f9a58b7d53b9ab19b41 --- /dev/null +++ b/pool/shard000/JavaScript/0002147_FileCollection.js @@ -0,0 +1,118 @@ +let concat = require('concat'); +let path = require('path'); +let fs = require('fs'); +let babel = require('@babel/core'); +let glob = require('glob'); +let Log = require('./Log'); +let File = require('./File'); + +class FileCollection { + /** + * Create a new FileCollection instance. + * + * @param {Array|string} files + */ + constructor(files = []) { + this.files = [].concat(files); + } + + /** + * Fetch the underlying files. + */ + get() { + return this.files; + } + + /** + * Merge all files in the collection into one. + * + * @param {object} output + * @param {object} wantsBabel + */ + merge(output, wantsBabel = false) { + return concat(this.files, output.makeDirectories().path()).then(contents => { + if (this.shouldCompileWithBabel(wantsBabel, output)) { + output.write(this.babelify(contents)); + } + + return new File(output.makeDirectories().path()); + }); + } + + /** + * Determine if we should add a Babel pass to the concatenated file. + * + * @param {Boolean} wantsBabel + * @param {Object} output + */ + shouldCompileWithBabel(wantsBabel, output) { + return wantsBabel && output.extension() === '.js'; + } + + /** + * Apply Babel to the given contents. + * + * @param {string} contents + */ + babelify(contents) { + let babelConfig = this.mix.config.babel(); + + delete babelConfig.cacheDirectory; + + return babel.transform(contents, babelConfig).code; + } + + /** + * Copy the src files to the given destination. + * + * @param {string} destination + * @param {string|array|null} src + */ + copyTo(destination, src = this.files) { + this.assets = this.assets || []; + + this.destination = destination; + + if (Array.isArray(src)) { + src.forEach(file => this.copyTo(destination, new File(file))); + + return; + } + + if (src.isDirectory()) { + src.copyTo(destination.path()); + + this.assets = fs.readdirSync(src.path()).map(file => { + return new File(path.resolve(destination.path(), file)); + }); + + return; + } + + if (src.contains('*')) { + let files = glob.sync(src.path(), { nodir: true }); + + if (!files.length) { + Log.feedback(`Notice: The ${src.path()} search produced no matches.`); + } + + return this.copyTo(destination, files); + } + + if (destination.isDirectory()) { + destination = destination.append(src.name()); + } + + src.copyTo(destination.path()); + + this.assets = this.assets.concat(destination); + + return destination.path(); + } + + get mix() { + return global.Mix; + } +} + +module.exports = FileCollection; diff --git a/pool/shard000/JavaScript/0002148_shape-fitting.js b/pool/shard000/JavaScript/0002148_shape-fitting.js new file mode 100644 index 0000000000000000000000000000000000000000..3bb669bd683225b139f8177732349b7e74f2e18c --- /dev/null +++ b/pool/shard000/JavaScript/0002148_shape-fitting.js @@ -0,0 +1,271 @@ +(function() { + 'use strict'; + + var optimizer = new pso.Optimizer(); + var iterationNMax = 20; + var initialPopulationSize; + + var domain; + var shapes; + var nShapes = 4; + var shapeGenerators = { + style: { + regular: function () { return 0.2; }, + star: function (i) { return (i % 2) * 0.15 + 0.05; }, + random: function () { return Math.random() * 0.2 + 0.05; } + }, + angles: { + triangle: function () { return 3; }, + tetragon: function () { return 4; }, + pentagon: function () { return 5; }, + hexagon: function () { return 6; }, + octogon: function () { return 8; }, + random: function () { return Math.floor(Math.random() * 5) + 3; } + } + }; + var currentGenerator = { + style: shapeGenerators.style.random, + angles: shapeGenerators.angles.random + }; + + var running = false; + + function repeat(n, fun) { + var ret = []; + + for (var i = 0; i < n; i++) { + ret.push(fun(i)); + } + + return ret; + } + + function getShape() { + var nPoints = currentGenerator.angles(); + return { + color: getRandomColor(), + points: repeat(nPoints, function (i) { + var angle = i / nPoints * Math.PI * 2; + var radius = currentGenerator.style(i); + return { + x: Math.cos(angle) * radius, + y: Math.sin(angle) * radius + }; + }) + }; + } + + function getShapes(n) { + return repeat(n, getShape); + } + + function getDomain(n) { + var domain = []; + repeat(n, function () { + domain.push( + new pso.Interval(0, 1), + new pso.Interval(0, 1), + new pso.Interval(0, Math.PI * 2), + new pso.Interval(0.2, 1.4) + ); + }); + return domain; + } + + var objectiveFunction = (function () { + var dim = 32; + var canvas = document.createElement('canvas'); + canvas.width = dim; + canvas.height = dim; + + var con2d = canvas.getContext('2d'); + con2d.clearStyle = '#FFF'; + con2d.fillStyle = 'rgba(16, 16, 16, 0.5)'; + con2d.scale(dim, dim); + + return function (x) { + // clear + con2d.clearRect(0, 0, dim, dim); + + // draw shapes + shapes.forEach(function (shape, i) { + var cx = x[i * 4 + 0]; + var cy = x[i * 4 + 1]; + var angle = x[i * 4 + 2]; + var scale = Math.min(x[i * 4 + 3], 1.4); + drawShape(con2d, shape.points, cx, cy, angle, scale); + }); + + // read back data and start counting + var overlapped = 0; + var empty = 0; + + var data = con2d.getImageData(0, 0, dim, dim).data; + for (var i = 0; i < data.length; i += 4) { + if (data[i] > 20) { + overlapped += data[i]; + } else if (data[i] === 0) { + empty++; + } + } + + return -(Math.pow(empty, 2) + Math.pow(overlapped, 2)); + }; + })(); + + function drawShape(con2d, shape, x, y, angle, scale) { + con2d.save(); + con2d.translate(x, y); + con2d.rotate(angle); + con2d.scale(scale, scale); + + con2d.beginPath(); + con2d.moveTo(shape[0].x, shape[0].y); + for (var i = 1; i < shape.length; i++) { + con2d.lineTo(shape[i].x, shape[i].y); + } + con2d.fill(); + + con2d.restore(); + } + + function getRandomColor() { + var angle = Math.random() * 2 * Math.PI; + var r = Math.floor((Math.sin(angle) + 1) / 2 * 255); + var g = Math.floor((Math.sin(angle + Math.PI * 2 / 3) + 1) / 4 * 255); + var b = Math.floor((Math.sin(angle + Math.PI * 4 / 3) + 1) / 16 * 255); + + return 'rgb(' + r + ',' + g + ',' + b + ')'; + } + + function reset() { + if (running) { return; } + + updateShapeParameters(); + shapes = getShapes(nShapes); + domain = getDomain(nShapes); + + Draw.clear(); + } + + function runningOn() { + running = true; + document.getElementById('but_reset').disabled = true; + document.getElementById('but_best').disabled = true; + } + + function runningOff() { + running = false; + document.getElementById('but_reset').disabled = false; + document.getElementById('but_best').disabled = false; + } + + function best() { + if (running) { return; } + + updatePsoParameters(); + + optimizer.init(initialPopulationSize, domain); + + var iteration = 1; + runningOn(); + + function loop() { + if (iteration < iterationNMax) { + requestAnimationFrame(loop); + iteration++; + } else { + runningOff(); + } + + optimizer.step(); + + var position = optimizer.getBestPosition(); + + Draw.clear(); + for (var i = 0; i < nShapes; i++) { + Draw.fillColor(shapes[i].color); + + var cx = position[i * 4 + 0]; + var cy = position[i * 4 + 1]; + var angle = position[i * 4 + 2]; + var scale = position[i * 4 + 3]; + + Draw.save(); + + Draw.translate(cx, cy); + Draw.rotate(angle); + Draw.scale(scale, scale); + + Draw.poly(shapes[i].points); + + Draw.restore(); + } + } + + loop(); + } + + function updatePsoParameters() { + iterationNMax = parseInt(document.getElementById('inp_niter').value); + + initialPopulationSize = parseInt(document.getElementById('inp_popinit').value); + var inertiaWeight = parseFloat(document.getElementById('inp_inertia').value); + var social = parseFloat(document.getElementById('inp_social').value); + var personal = parseFloat(document.getElementById('inp_personal').value); + + optimizer.setOptions({ + inertiaWeight: inertiaWeight, + social: social, + personal: personal + }); + } + + function updateShapeParameters() { + var shapeAngles = document.getElementById('shape-angles'); + var shapeStyle = document.getElementById('shape-style'); + + var angles = shapeAngles.options[shapeAngles.selectedIndex].value; + var style = shapeStyle.options[shapeStyle.selectedIndex].value; + + currentGenerator.style = shapeGenerators.style[style]; + currentGenerator.angles = shapeGenerators.angles[angles]; + } + + function setup() { + Draw.init(document.getElementById('canvascircles')); + + function createSliderPair(sliderId, inputId) { + associateSlider( + document.getElementById(sliderId), + document.getElementById(inputId) + ); + } + + [ + ['slider_niter', 'inp_niter'], + ['slider_popinit', 'inp_popinit'], + ['slider_inertia', 'inp_inertia'], + ['slider_social', 'inp_social'], + ['slider_personal', 'inp_personal'] + ].forEach(function (pair) { + createSliderPair.apply(null, pair); + }); + + document.getElementById('but_reset').addEventListener('click', reset); + document.getElementById('but_best').addEventListener('click', best); + + optimizer.setObjectiveFunction(objectiveFunction); + + Draw.clearColor('#FFF'); + Draw.lineColor('#000'); + + Draw.scale(500, 500); + + updateShapeParameters(); + shapes = getShapes(nShapes); + domain = getDomain(nShapes); + } + + setup(); +})(); diff --git a/pool/shard000/JavaScript/0002151_main.js b/pool/shard000/JavaScript/0002151_main.js new file mode 100644 index 0000000000000000000000000000000000000000..b0c3db86cb5355f561413ef085bbbe77bc193708 --- /dev/null +++ b/pool/shard000/JavaScript/0002151_main.js @@ -0,0 +1,28 @@ +/*jslint node: true */ +'use strict'; +var express = require('express'), + routes = require('./routes'), + app = express(); + +app.use(express.bodyParser()); + +app.get('/api/awesomeThings', routes.awesomeThings); + +app.get('/api/product/:id', routes.getProduct); +app.post('/api/product/:id', routes.setProduct); +app.get('/api/product_delete/:id', routes.removeProduct); +app.post('/api/product_new', routes.newProduct); +app.get('/api/all_products', routes.getAllProducts) + +app.get('/api/place/:id', routes.getPlace); +app.post('/api/place/:id', routes.setPlace); +app.get('/api/place_delete/:id', routes.removePlace); +app.post('/api/place_new', routes.newPlace); +app.get('/api/all_places', routes.getAllPlaces) + + +app.use(function (req, res) { + res.json({'ok': false, 'status': '404'}); +}); + +module.exports = app; diff --git a/pool/shard000/JavaScript/0002157_school-year.js b/pool/shard000/JavaScript/0002157_school-year.js new file mode 100644 index 0000000000000000000000000000000000000000..fcb9d6e785383f95165934409614eae6505cb4b5 --- /dev/null +++ b/pool/shard000/JavaScript/0002157_school-year.js @@ -0,0 +1,230 @@ +$(document).ready(function(){ + SCHOOLYEAR.initializeBindings(); + +}); + +var SCHOOLYEAR = {}; + +SCHOOLYEAR.initializeBindings = function(){ + SCHOOLYEAR.bindDeleteButton(); + SCHOOLYEAR.bindUpdateButton(); + SCHOOLYEAR.dialogs(); + +} + + +SCHOOLYEAR.dialogs = function(){ + var name = $( "#name" ), + email = $( "#email" ), + password = $( "#password" ), + allFields = $( [] ).add( name ).add( email ).add( password ), + tips = $( ".validateTips" ); + + $( "#dialog-form" ).dialog({ + autoOpen: false, + height: 300, + width: 350, + modal: true, + buttons: { + "Add School-Year": function() { + SCHOOLYEAR.addEntry(); + + var bValid = true; + allFields.removeClass( "ui-state-error" ); + + $( this ).dialog( "close" ); + + }, + + Cancel: function() { + $( this ).dialog( "close" ); + } + + }, + + close: function() { + allFields.val( "" ).removeClass( "ui-state-error" ); + } + }); + + + $( "#dialog-form-update" ).dialog({ + autoOpen: false, + height: 300, + width: 350, + modal: true, + buttons: { + "Update Record": function() { + + + var deptId = $('#selectedSchoolYearId').val(); + + SCHOOLYEAR.updateEntry(deptId); + + var bValid = true; + allFields.removeClass( "ui-state-error" ); + $( this ).dialog( "close" ); + + }, + + Cancel: function() { + $( this ).dialog( "close" ); + } + + }, + + close: function() { + allFields.val( "" ).removeClass( "ui-state-error" ); + } + }); + + + $( "#createSchoolyear" ).button().click(function() { + + + $( "#dialog-form" ).dialog( "open" ); + + // This will display the selected SCHOOLYEAR to the dialog box. + $('#schoolYearLbl').text($("#dwnDept>option:selected").html()); + }); +} + + +//BINDINGS + +/* + Bindings of SCHOOLYEAR +*/ + + +SCHOOLYEAR.bindDeleteButton = function(){ + + $('#schoolYearTable tbody tr').click( function () { + var schoolYearId = $(this).find('td:first').text(); + $('#selectedSchoolYearId').val(schoolYearId); + }); + + + $('.deleteButton').click(function(){ + if(confirm("Are you sure you want to delete this record? ")){ + $('#schoolYearTable tbody tr').click( function () { + + var schoolYearId = $('#selectedSchoolYearId').val(); + alert("schoolYearId :" + schoolYearId); + $.ajax ({ + datatype:'text', + type : "POST", + url: "/scheduler-app/index.php/Maintenance/SchoolYearController/deleteSchoolYear/" + schoolYearId, + success : function(rs) { + //console.log("HERE : " + rs); + $( "#schoolYearTable" ).html(''); + $( "#schoolYearTable" ).append( "

" + rs + "

" ); + + SCHOOLYEAR.bindDeleteButton(); + SCHOOLYEAR.bindUpdateButton(); + } + }); + } ); + } + }); +} + +SCHOOLYEAR.bindUpdateButton = function(){ + $('.updateButton').click(function(){ + + $('#schoolYearTable tbody tr').click( function () { + var schoolYearId = $(this).find('td:first').text(); + $('#selectedSchoolYearId').val(schoolYearId); + }); + + $( "#dialog-form-update" ).dialog( "open" ); // Update Button Dialog. + + // This will display the selected SCHOOLYEAR to the dialog box. + $('#schoolYearLbl').text($("#dwnDept>option:selected").html()); + + }); +} + + + +//END OF BINDINGS + +//CRUD SCHOOLYEAR +SCHOOLYEAR.addEntry = function(){ + + + var all = $('#addSchoolYear').serialize(); + var url = "/scheduler-app/index.php/Maintenance/SchoolYearController/addSchoolYear"; + + $.ajax + ({ + type : "POST", + url : url, + data : all, + success : function(rs) + { + if(rs != null) { + location = "/scheduler-app/index.php/Maintenance/SchoolYearController/schoolYear"; + } else { + alert("error : " + rs); + } + } + }); + +} + +SCHOOLYEAR.updateEntry = function(schoolYearId){ + + var all = $('#updateSchoolYear').serialize(); + var url = "/scheduler-app/index.php/Maintenance/SchoolYearController/updateSchoolYear/" + schoolYearId; + $.ajax + ({ + type : "POST", + url : url, + data : all, + success : function(rs) { + $( "#schoolYearTable" ).html(''); + $( "#schoolYearTable" ).append( "

" + rs + "

" ); + SCHOOLYEAR.bindUpdateButton(); + SCHOOLYEAR.bindDeleteButton(); + alert('Successfully Updated.'); + + } + }); + +} + +SCHOOLYEAR.schoolYearChange = function(){ + alert("#dwnDept").val(); +} + + +//MESSY function + function updateTips( t ) { + tips.text( t ).addClass( "ui-state-highlight" ); + setTimeout(function() { + tips.removeClass( "ui-state-highlight", 1500 ); + }, 500 ); + } + + function checkLength( o, n, min, max ) { + // if ( o.val().length > max || o.val().length < min ) { + // o.addClass( "ui-state-error" ); + // updateTips( "Length of " + n + " must be between " + + // min + " and " + max + "." ); + // return false; + // } else { + // return true; + // } + + return true; + } + function checkRegexp( o, regexp, n ) { + if ( !( regexp.test( o.val() ) ) ) { + o.addClass( "ui-state-error" ); + updateTips( n ); + return false; + } else { + return true; + } + } diff --git a/pool/shard000/JavaScript/0002160_labels.js b/pool/shard000/JavaScript/0002160_labels.js new file mode 100644 index 0000000000000000000000000000000000000000..8454b40988fb2666c63c78cff5d7f0e423a19f74 --- /dev/null +++ b/pool/shard000/JavaScript/0002160_labels.js @@ -0,0 +1,175 @@ +/* DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others. + Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except in compliance with the License. + You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and limitations under the License.*/ + +define.class('$ui/label', function (require) { + + this.position = 'absolute' + this.bgcolor = NaN + this.fgcolor = 'white' + this.drawtarget = 'color' + this.bold = true + + var ubuntufont = require('$resources/fonts/ubuntu_medium_256_baked.glf') + this.font = ubuntufont + + this.attributes = { + zoom: wire('this.parent.zoom'), + scroll: wire('this.parent.scroll') + } + + var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] + var DAYS = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', + '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st'] + var MONTH_COLLAPSE = 200.0 + + this.typeface = function(){ + this.update = function(){ + var view = this.view + var zoom = view.zoom + // hack to trigger update on scroll change + var scroll = view.scroll + var w = view.parent._layout.width + var h = view.parent._layout.height + + var mw = w / 11.774193548387096 * 365 / zoom + var dw = w / zoom + var hw = w / 24 / zoom + + var ts = view.parent.TIME_SCALE + + var mesh = this.newText() + if (view.font) mesh.font = view.font + if (view.align) mesh.align = view.align + if (view.fontsize) mesh.fontsize = view.fontsize + mesh.clear() + + var i, x, y, start, offset, date, text + + start = new Date(view.parent.getStart()) + first = new Date(view.parent.getRangeStart()) + + var firstYear = first.getFullYear() + var firstMonth = first.getMonth() + var firstDate = first.getDate() + var firstHour = first.getHours() + + function drawLabel(text, date, xoffset, yoffset) { + x = (date.getTime() - first) / ts / zoom * w + xoffset + 5 + y = yoffset - 5 + mesh.add_x = x + mesh.add_y = y + mesh.add(text, 0, 0, 0) + } + + function drawYears(yoffset) { + date = new Date("0") + date.setYear(firstYear) + xoffset = (date.getTime() - first) / ts / zoom * w + x = 0, i = -1 + while (x < w) { + date = new Date(first) + date.setYear(firstYear + i) + drawLabel(date.getFullYear().toString(), date, xoffset, yoffset) + i++ + } + } + + function drawMonths(yoffset) { + date = new Date("0") + date.setYear(firstYear) + date.setMonth(firstMonth) + xoffset = (date.getTime() - first) / ts / zoom * w + 1 + x = 0, i = -1 + while (x < w && i < 100) { + date = new Date(first) + date.setMonth(firstMonth + i) + text = MONTHS[date.getMonth() % 12] + if (mw > 220) { + text = text + ' ' + date.getFullYear() + } + drawLabel(text, date, xoffset, yoffset) + i++ + } + } + + function drawDays(yoffset) { + date = new Date("0") + date.setYear(firstYear) + date.setMonth(firstMonth) + date.setDate(firstDate) + xoffset = (date.getTime() - first) / ts / zoom * w + 5 + x = 0, i = -1 + while (x < w && i < 100) { + date = new Date(first) + date.setDate(firstDate + i) + text = DAYS[(date.getDate() - 1) % 31] + if (dw > 220) { + text = MONTHS[(date.getMonth()) % 12] + ' ' + text + ' ' + date.getFullYear() + } else if (dw > 120) { + text = MONTHS[(date.getMonth()) % 12] + ' ' + text + } + drawLabel(text, date, xoffset, yoffset) + i++ + } + } + + function drawHours(yoffset) { + date = new Date("0") + date.setYear(firstYear) + date.setMonth(firstMonth) + date.setDate(firstDate) + date.setHours(firstHour) + xoffset = (date.getTime() - first) / ts / zoom * w + var c = 24 / view.parent.hoursegs + x = 0, i = -1 + while (x < w && i < 100) { + var h = (firstHour + i) % 24 + date = new Date(first) + date.setHours(firstHour + i) + if (view.parent.format == 12) { + text = (h % 12 || 12) + ' ' + (h < 12 ? 'am' : 'pm') + } else { + text = h % 24 + ' h' + } + if (h % c == 0) { + drawLabel(text, date, xoffset, yoffset) + } + i++ + } + } + + mesh.fontsize = view.fontsize * 0.75 + + switch (view.parent.segments[0]) { + case 1: + drawYears(26) + break + case 2: + drawMonths(26) + break + case 4: + drawDays(26) + break + } + + mesh.fontsize = view.fontsize * 0.5 + + switch (view.parent.segments[1]) { + case 2: + drawMonths(42) + break + case 4: + drawDays(42) + break + case 5: + drawHours(42) + break + } + + this.mesh = mesh + } + } +}) diff --git a/pool/shard000/JavaScript/0002162_cache_browser.js b/pool/shard000/JavaScript/0002162_cache_browser.js new file mode 100644 index 0000000000000000000000000000000000000000..dffd84d6c9e3c731fa207dae8b318c80b85c6d32 --- /dev/null +++ b/pool/shard000/JavaScript/0002162_cache_browser.js @@ -0,0 +1,35 @@ +// $Id: cache_browser.js,v 1.1.2.1 2008/10/26 02:44:11 markuspetrux Exp $ + +if (Drupal.jsEnabled) { + $(document).ready(function () { + var cache_browser_icon_plus = new Image(); + cache_browser_icon_plus.src = cache_browser.icon_plus; + var cache_browser_icon_minus = new Image(); + cache_browser_icon_minus.src = cache_browser.icon_minus; + $(".cb-dump-hotspot-expand").bind("click", function() { + var id = $(this).attr("id").replace(/cb-dump-hotspot-expand-/, ""); + $(".cb-dump-block-"+ id).css("display", "inline"); + $(".cb-dump-hotspot-"+ id).attr("src", cache_browser_icon_minus.src); + this.blur(); + return false; + }); + $(".cb-dump-hotspot-collapse").bind("click", function() { + var id = $(this).attr("id").replace(/cb-dump-hotspot-collapse-/, ""); + $(".cb-dump-block-"+ id).css("display", "none"); + $(".cb-dump-hotspot-"+ id).attr("src", cache_browser_icon_plus.src); + this.blur(); + return false; + }); + $("pre.cb-dump img").bind("click", function() { + var id = $(this).attr("id").replace(/cb-dump-hotspot-/, ""); + if ($("#cb-dump-block-"+ id).css("display") != "none") { + $("#cb-dump-block-"+ id).hide("fast"); + $("#cb-dump-hotspot-"+ id).attr("src", cache_browser_icon_plus.src); + } + else { + $("#cb-dump-block-"+ id).show("fast", function() { $(this).css("display", "inline"); }); + $("#cb-dump-hotspot-"+ id).attr("src", cache_browser_icon_minus.src); + } + }); + }); +} diff --git a/pool/shard000/JavaScript/0002168_auction-controller.js b/pool/shard000/JavaScript/0002168_auction-controller.js new file mode 100644 index 0000000000000000000000000000000000000000..df55eeee3ba1682e79a25d255b5b30fbc97684a8 --- /dev/null +++ b/pool/shard000/JavaScript/0002168_auction-controller.js @@ -0,0 +1,51 @@ +function AuctionController($scope, $stateParams, $state, $interval) { + var ac = this; + + ac.timeLeft = 90; + + var promise = null; + var hasBidding = false; + + var unbind = $scope.$on('roll it', function() { + promise = $interval(function() { + ac.timeLeft -= 1; + + if (ac.timeLeft === 0) { + if (hasBidding) { + $scope.$emit('auction closed', ac.item); + } + ac.timeLeft = 90; + ac.auctionStarted = false; + stop(); + } + }, 1000); + }); + + // Clear events + $scope.$on('$destoy', function() { + stop(); + unbind(); + }); + /** + * @desc function that places new bid value in the ongoing item for auction + * @param {Object} item - contains item name, minimum bid value, and quantity + */ + ac.placeBid = function(item) { + hasBidding = true; + if (ac.placeBidValue === null || ac.placeBidValue === undefined || ac.placeBidValue === ac.item.value || ac.timeLeft === 0) { + return; + } + if (ac.timeLeft <= 10 && ac.timeLeft !== 0) { + ac.timeLeft = 10; + } + ac.item.value = ac.placeBidValue; + item.sellerName = ac.sellerName; + }; + + // Cancel $interval + function stop() { + $interval.cancel(promise); + } +} + +module.exports = AuctionController; diff --git a/pool/shard000/JavaScript/0002169_markdox.js b/pool/shard000/JavaScript/0002169_markdox.js new file mode 100644 index 0000000000000000000000000000000000000000..6d89630670a40f8460637008ca8cca433d0af5b5 --- /dev/null +++ b/pool/shard000/JavaScript/0002169_markdox.js @@ -0,0 +1,173 @@ +var markdox = require('markdox') + , program = require('commander') + , fs = require('fs') + , _ = require('lodash'); + +program + .version('0.0.1') + .option('-f, --file [file]', 'Process a single file', '') + .option('-a, --all', 'Process all files, generate index etc. (default if no options are specified') + .option('-c, --clean', 'Remove all generated markdown and HTML files') + .option('--html', 'Generate html files from the markdown ones (requires manual installation of the github-flavored-markdown package') + .parse(process.argv) + + +if (program.clean) { + fs.readdirSync('docs/').forEach(function (file) { + if (file.indexOf('.ejs') === -1 && file.indexOf('.js') === -1) { + fs.unlinkSync ('docs/' + file); + } + }) + + return +} + +if (program.html) { + var ghm = require('github-flavored-markdown') +} + +var getTag = function(tags, tagName) { + return _.find(tags, function (tag) { + return tag.type === tagName; + }); +}; + +var getTags = function(tags, tagName) { + return _.where(tags, function (tag) { + return tag.type === tagName; + }); +} + +var options = { + formatter: function (docfile) { + docfile = markdox.defaultFormatter(docfile); + + docfile.members = []; + docfile.javadoc.forEach(function(javadoc){ + // Find constructor tags + javadoc.isConstructor = getTag(javadoc.raw.tags, 'constructor') !== undefined; + javadoc.isMixin = getTag(javadoc.raw.tags, 'mixin') !== undefined; + javadoc.isProperty = getTag(javadoc.raw.tags, 'property') !== undefined + javadoc.private = getTag(javadoc.raw.tags, 'private') !== undefined + javadoc.since = getTag(javadoc.raw.tags, 'since'); + + // Only show params without a dot in them (dots means attributes of object, so no need to clutter the signature too much) + var params = [] + javadoc.paramTags.forEach(function (paramTag) { + if (paramTag.name.indexOf('.') === -1) { + params.push(paramTag.name); + } + + }); + javadoc.paramStr = (javadoc.isMethod || javadoc.isFunction) ? '(' + params.join(', ') + ')' : ''; + + // Convert | to | to be able to use github flavored md tables + if (javadoc.paramTags) { + javadoc.paramTags.forEach(function (paramTag) { + paramTag.joinedTypes = paramTag.joinedTypes.replace(/\|/g, '|') + }); + } + + // Handle aliases + javadoc.aliases = getTags(javadoc.raw.tags, 'alias').map(function (a) { + return a.string + }).join(', ') + + // Handle deprecation text + if (javadoc.deprecated) { + var deprecation = getTag(javadoc.raw.tags, 'deprecated') + javadoc.deprecated = deprecation.string + } + + // Handle linking in comments + javadoc.see = getTags(javadoc.raw.tags, 'see'); + javadoc.see.forEach(function (see, i, collection) { + collection[i] = {} + + if (see.local) { + collection[i].external = false + + if (see.local.indexOf('{') === 0){ + var _see = see.local.split('}') + _see[0] = _see[0].substring(1) + collection[i].url = 'API-Reference-' + _see[0] + + collection[i].text = see.local.replace(/{|}/g, '') + } else { + collection[i].url = false + collection[i].text = see.local + } + } else { + see.external = true + see.text = see.url + collection[i] = see + } + }) + + // Set a name for properties + if (!javadoc.name) { + var property = getTag(javadoc.raw.tags, 'property') + if (property) { + javadoc.name = property.string + } + } + if (javadoc.isMixin) { + javadoc.name = getTag(javadoc.raw.tags, 'mixin').string; + } + + javadoc.mixes = getTags(javadoc.raw.tags, 'mixes').map(function (mix) { + return { + text: mix.string, + link: (mix.string.indexOf('www') !== -1 || mix.string.indexOf('http') !== -1) ? mix.string: 'API-Reference-' + mix.string + } + }) + + if (!javadoc.isClass) { + if (!javadoc.isProperty) { + docfile.members.push({ + text: javadoc.name + javadoc.paramStr, + link: '#' + javadoc.name + }) + } else { + docfile.members.push({ + text: javadoc.name, + link: '#' + javadoc.name + }) + } + } + }); + + return docfile; + }, + template: 'docs/output.md.ejs' +}; + +var files; +if (program.file) { + files = [{file: program.file, output: 'tmp'}] +} else { + files = [ + {file:'lib/sequelize.js', output: 'API-Reference-Sequelize'}, + {file:'lib/dao.js', output: 'API-Reference-DAO'}, + {file:'lib/dao-factory.js', output: 'API-Reference-DAOFactory'}, + {file:'lib/query-chainer.js', output: 'API-Reference-QueryChainer'}, + {file:'lib/emitters/custom-event-emitter.js', output: 'API-Reference-EventEmitter'}, + {file:'lib/hooks.js', output: 'API-Reference-Hooks'}, + {file:'lib/associations/mixin.js', output: 'API-Reference-Associations'}, + {file:'lib/promise.js', output: 'API-Reference-Promise'}, + {file:'lib/transaction.js', output: 'API-Reference-Transaction'} + ]; +} + +files.forEach(function (file) { + var opts = _.clone(options) + , output = 'docs/' + file.output + '.md' + + opts.output = output + markdox.process(file.file, opts, function(){ + if (program.html) { + var md = fs.readFileSync(output).toString(); + fs.writeFileSync(output.replace('md', 'html'), ghm.parse(md)) + } + }); +}) \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002171_ArqueoCajasCtrl.js b/pool/shard000/JavaScript/0002171_ArqueoCajasCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..a65322062a0415a19133aa61372c3eb6cf8b5404 --- /dev/null +++ b/pool/shard000/JavaScript/0002171_ArqueoCajasCtrl.js @@ -0,0 +1,70 @@ +'use strict'; +angular + .module('softvApp') + .controller('ArqueoCajasCtrl', function (globalService, generalesSistemaFactory, $state, $rootScope, ngNotify, entregasFactory, arqueoFactory, $filter) { + + + this.$onInit = function () { + + generalesSistemaFactory.GetvalidaAccesoFacturacion().then(function (data) { + if (data.GetvalidaAccesoFacturacionResult === 0) { + $state.go('home.dashboard'); + ngNotify.set('Su máquina no esta registrada como una caja, por tal motivo no tiene acceso a facturación', 'warn'); + } + }); + + }; + + function initialData() { + entregasFactory.getPlazas().then(function (data) { + data.GetMuestraPlazasProcesosListResult.unshift({ + 'razon_social': '----------------', + 'id_compania': 0 + }); + vm.plazas = data.GetMuestraPlazasProcesosListResult; + vm.selectedPlaza = data.GetMuestraPlazasProcesosListResult[0]; + }); + } + + function changePlaza() { + arqueoFactory.getCajeros(vm.selectedPlaza.id_compania).then(function (data) { + data.GetMuestraCajerosArqueoListResult.unshift({ + 'Nombre': '----------------', + 'Clv_Usuario': 0 + }); + vm.cajeros = data.GetMuestraCajerosArqueoListResult; + vm.selectedCajero = data.GetMuestraCajerosArqueoListResult[0]; + }); + } + + function generarArqueo() { + if (vm.selectedPlaza.id_compania == 0) { + ngNotify.set('Por favor selecciona una plaza válida.', 'error'); + } else { + if (vm.selectedCajero.Clv_Usuario == 0) { + ngNotify.set('Por favor selecciona un cajero válido.', 'error'); + } else { + if (vm.fecha == '' || vm.fecha == undefined) { + ngNotify.set('Por favor selecciona un fecha válida.', 'error'); + } else { + vm.auxFecha = $filter('date')(vm.fecha, 'dd/MM/yyyy'); + arqueoFactory.reporteArqueo(vm.auxFecha, vm.selectedCajero.Clv_Usuario).then(function (data) { + if (data.GetT1RepArqueoListResult[0].Nombre == 'Sin Registros') { + ngNotify.set('No se encontraron registros.', 'error'); + } else { + var url = globalService.getUrlReportes() + '/Reportes/' + data.GetT1RepArqueoListResult[0].Nombre; + $('#reporteID').attr('src', url); + vm.showReporte = true; + } + }); + } + } + } + } + + var vm = this; + vm.changePlaza = changePlaza; + vm.generarArqueo = generarArqueo; + vm.showReporte = false; + initialData(); + }); diff --git a/pool/shard000/JavaScript/0002174_account_view.js b/pool/shard000/JavaScript/0002174_account_view.js new file mode 100644 index 0000000000000000000000000000000000000000..3ce9fa53fb3ea072008e734365f9f4eafeacc248 --- /dev/null +++ b/pool/shard000/JavaScript/0002174_account_view.js @@ -0,0 +1,240 @@ +// A tile view for previewing an Account in a listing. +dc.ui.AccountView = Backbone.View.extend({ + + AVATAR_SIZES : { + badge : 30, + row : 25, + admin : 25, + collaborator : 25, + reviewer : 25, + user : 150 + }, + + TAGS : { + badge : 'div', + row : 'tr', + admin : 'tr', + collaborator : 'tr', + reviewer : 'tr', + membership : 'div', + user : 'div', + organization_row : 'div' + }, + + events : { + 'click .edit_account': 'showEdit', + 'click .change_password': 'promptPasswordChange', + 'click .resend_welcome': 'resendWelcomeEmail', + 'click .admin_link': '_openAccounts', + 'click .save_changes': '_doneEditing', + 'click .cancel_changes': '_cancelEditing', // Where'd this go? + 'click .disable_account': '_disableAccount', + 'click .enable_account': '_enableAccount', + 'click .login_as .minibutton': '_loginAsAccount', + 'chosen': 'setDisplayLanguage' + }, + + constructor : function(options) { + this.modes = {}; + this.kind = options.kind; + this.tagName = this.TAGS[this.kind]; + this.className = 'account_view ' + this.kind + (this.tagName == 'tr' ? ' not_draggable' : ''); + this.dialog = options.dialog; + Backbone.View.call(this, options); + this.template = JST['account/' + this.kind]; + _.bindAll(this, '_onSuccess', '_onError'); + this._boundRender = _.bind(this.render, this, 'display'); + this.observe(this.model); + }, + + observe : function(model) { + if (this.model) this.model.unbind('change', this._boundRender); + this.model = model; + this.model.bind('change', this._boundRender); + }, + + render : function(viewMode, options) { + if (this.modes.view == 'edit') return; + viewMode = viewMode || 'display'; + options = options || {}; + var attrs = _.extend({ + account : this.model, + email : this.model.get('email'), + size : this.size(), + current : Accounts.current() + }, options); + if (this.isRow()) this.setMode(viewMode, 'view_mode'); + $(this.el).html(this.template(attrs)); + if (viewMode == 'edit') this.$('option.role_' + this.model.get('role')).attr({selected : 'selected'}); + if (this.model.isPending()) $(this.el).addClass('pending'); + this._loadAvatar(); + this._setPlaceholders(); + this.setMode(this.model.ROLE_NAMES[this.model.get('role')], 'role'); + return this; + }, + + size : function() { + return this.AVATAR_SIZES[this.kind]; + }, + + isUser: function() { + return this.kind == "user"; + }, + + isRow : function() { + return this.kind == 'row' || this.kind == 'admin' || this.kind == 'reviewer' || this.kind == 'organization_row'; + }, + + serialize : function() { + var attrs = this.$('input, select').serializeJSON(); + if (attrs.role) attrs.role = parseInt(attrs.role, 10); + return attrs; + }, + + showEdit : function() { + this.$('option.role_' + this.model.get('role')).attr({selected : 'selected'}); + this.setMode('edit', 'view_mode'); + }, + + setDisplayLanguage: function( ev, language ){ + var code = dc.language.NAMES[ language ]; + this.$el.next('tr.editing').find('.choice'). + html( dc.language.NAMES[ language ] ). + attr('data-language',language); + }, + + + promptPasswordChange : function() { + this.dialog.close(); + var dialog = dc.ui.Dialog.prompt(_.t('enter_new_password'), '', _.bind(function(password) { + if (password.length > 0) { + this.model.save({password : password}, { + success : _.bind(function() { + dc.ui.notifier.show({ + text : _.t('password_updated'), + duration : 5000, + mode : 'info' + }); + }, this) + }); + return true; + } else { + dc.ui.Dialog.alert(_.t('password_no_blank')); + } + }, this), {password : true, mode : 'short_prompt'}); + }, + + resendWelcomeEmail : function() { + dc.ui.spinner.show(); + var model = this.model; + model.resendWelcomeEmail({success : _.bind(function() { + dc.ui.spinner.hide(); + dc.ui.notifier.show({mode : 'info', text : _.t('welcome_message_sent_to', model.get('email') ) }); + }, this)}); + }, + + _setPlaceholders : function() { + this.$('input[name=first_name], input[name=last_name], input[name=email]').placeholder(); + }, + + _loadAvatar : function() { + var img = new Image(); + var src = this.model.gravatarUrl(this.size()); + img.onload = _.bind(function() { this.$('img.avatar').attr({src : src}); }, this); + img.src = src; + }, + + _openAccounts : function(e) { + e.preventDefault(); + dc.app.accounts.open(); + }, + + // When we're done editing an account, it's either a create or update. + // This method specializes to try and avoid server requests when nothing has + // changed. + _doneEditing : function() { + var attributes = this.serialize(); + var options = {success : this._onSuccess, error : this._onError}; + if (this.model.isNew()) { + if (!attributes.email){ return $(this.el).remove(); } + // the following will not work in a multi-organization paradigm: + if (Accounts.getValidByEmail(attributes.email)) { + this.dialog.error( _.t('already_has_account', attributes.email ) ); + return; + } + dc.ui.spinner.show(); + this.model.newRecord = true; + this.model.set(attributes); + Accounts.create(this.model, options); + } else if (!this.model.invalid && !this.model.changedAttributes(attributes)) { + this.setMode('display', 'view_mode'); + } else { + dc.ui.spinner.show(); + this.model.save(attributes, options); + } + }, + + _cancelEditing : function() { + this.setMode('display', 'view_mode'); + this.$el.next('tr.editing').remove(); + }, + + _disableAccount : function() { + if (this.dialog.isOpen()) this.dialog.close(); + var dialog = dc.ui.Dialog.confirm(null, _.bind(function() { + this.setMode('display', 'view_mode'); + this.$el.next('tr.editing').remove(); + this.model.save({'role': this.model.DISABLED}); + dc.ui.notifier.show({ + text : _.t('account_is_disabled',this.model.fullName() ), + duration : 5000, + mode : 'info' + }); + return true; + }, this), { + id : 'disable_account_confirm', + title : _.t('double_check_disable'), + description : _.t('explain_disable_account', this.model.fullName(), '','' ), + saveText : 'Disable' + }); + $('.contact_support', dialog.el).bind('click', function() { + dialog.close(); + dc.ui.Dialog.contact(); + }); + }, + + _enableAccount : function() { + this.setMode('display', 'view_mode'); + this.$el.next('tr.editing').remove(); + this.model.save({'role': this.model.CONTRIBUTOR}); + }, + + _loginAsAccount : function() { + window.location = "/admin/login_as?email=" + encodeURIComponent(this.model.get('email')); + }, + + _onSuccess : function(model, resp) { + this.model.invalid = false; + this.setMode('display', 'view_mode'); + this.$el.next('tr.editing').remove(); + this.model.trigger('change'); + dc.ui.spinner.hide(); + if (this.model.newRecord) { + this.model.newRecord = false; + dc.ui.notifier.show({ + text : _.t('signup_sent_to', model.get('email') ), + duration : 5000, + mode : 'info' + }); + } + }, + + _onError : function(model, resp) { + resp = JSON.parse(resp.responseText); + model.invalid = true; + dc.ui.spinner.hide(); + this.showEdit(); + this.dialog.error( resp.errors && resp.errors[0] || _.t('account_add_failure') ); + } + +}); diff --git a/pool/shard000/JavaScript/0002176_edit_actions_spec.js b/pool/shard000/JavaScript/0002176_edit_actions_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..b0c1894058e37b46b8a5cee199b32dfcd1e46537 --- /dev/null +++ b/pool/shard000/JavaScript/0002176_edit_actions_spec.js @@ -0,0 +1,134 @@ +import Vue from 'vue'; +import editActions from '~/issue_show/components/edit_actions.vue'; +import eventHub from '~/issue_show/event_hub'; +import Store from '~/issue_show/stores'; + +describe('Edit Actions components', () => { + let vm; + + beforeEach(done => { + const Component = Vue.extend(editActions); + const store = new Store({ + titleHtml: '', + descriptionHtml: '', + issuableRef: '', + }); + store.formState.title = 'test'; + + jest.spyOn(eventHub, '$emit').mockImplementation(() => {}); + + vm = new Component({ + propsData: { + canDestroy: true, + formState: store.formState, + issuableType: 'issue', + }, + }).$mount(); + + Vue.nextTick(done); + }); + + it('renders all buttons as enabled', () => { + expect(vm.$el.querySelectorAll('.disabled').length).toBe(0); + + expect(vm.$el.querySelectorAll('[disabled]').length).toBe(0); + }); + + it('does not render delete button if canUpdate is false', done => { + vm.canDestroy = false; + + Vue.nextTick(() => { + expect(vm.$el.querySelector('.btn-danger')).toBeNull(); + + done(); + }); + }); + + it('disables submit button when title is blank', done => { + vm.formState.title = ''; + + Vue.nextTick(() => { + expect(vm.$el.querySelector('.btn-success').getAttribute('disabled')).toBe('disabled'); + + done(); + }); + }); + + it('should not show delete button if showDeleteButton is false', done => { + vm.showDeleteButton = false; + + Vue.nextTick(() => { + expect(vm.$el.querySelector('.btn-danger')).toBeNull(); + done(); + }); + }); + + describe('updateIssuable', () => { + it('sends update.issauble event when clicking save button', () => { + vm.$el.querySelector('.btn-success').click(); + + expect(eventHub.$emit).toHaveBeenCalledWith('update.issuable'); + }); + + it('shows loading icon after clicking save button', done => { + vm.$el.querySelector('.btn-success').click(); + + Vue.nextTick(() => { + expect(vm.$el.querySelector('.btn-success .fa')).not.toBeNull(); + + done(); + }); + }); + + it('disabled button after clicking save button', done => { + vm.$el.querySelector('.btn-success').click(); + + Vue.nextTick(() => { + expect(vm.$el.querySelector('.btn-success').getAttribute('disabled')).toBe('disabled'); + + done(); + }); + }); + }); + + describe('closeForm', () => { + it('emits close.form when clicking cancel', () => { + vm.$el.querySelector('.btn-default').click(); + + expect(eventHub.$emit).toHaveBeenCalledWith('close.form'); + }); + }); + + describe('deleteIssuable', () => { + it('sends delete.issuable event when clicking save button', () => { + jest.spyOn(window, 'confirm').mockReturnValue(true); + vm.$el.querySelector('.btn-danger').click(); + + expect(eventHub.$emit).toHaveBeenCalledWith('delete.issuable', { destroy_confirm: true }); + }); + + it('shows loading icon after clicking delete button', done => { + jest.spyOn(window, 'confirm').mockReturnValue(true); + vm.$el.querySelector('.btn-danger').click(); + + Vue.nextTick(() => { + expect(vm.$el.querySelector('.btn-danger .fa')).not.toBeNull(); + + done(); + }); + }); + + it('does no actions when confirm is false', done => { + jest.spyOn(window, 'confirm').mockReturnValue(false); + vm.$el.querySelector('.btn-danger').click(); + + Vue.nextTick(() => { + expect(eventHub.$emit).not.toHaveBeenCalledWith('delete.issuable'); + + expect(vm.$el.querySelector('.btn-danger .fa')).toBeNull(); + + done(); + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0002179_FreeVariableChecker.js b/pool/shard000/JavaScript/0002179_FreeVariableChecker.js new file mode 100644 index 0000000000000000000000000000000000000000..58dd4134337e3ee0ecc195999cb8135f113f9786 --- /dev/null +++ b/pool/shard000/JavaScript/0002179_FreeVariableChecker.js @@ -0,0 +1,79 @@ +// Copyright 2011 Traceur Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +suite('FreeVariableChecker.traceur.js', function() { + + setup(function() { + traceur.options.freeVariableChecker = true; + }); + + teardown(function() { + traceur.options.reset(); + }); + + function compileAndReturnErrors(contents, name) { + var LoaderHooks = traceur.modules.LoaderHooks; + var Loader = traceur.modules.Loader; + var reporter = new traceur.util.ErrorReporter(); + var errors = []; + reporter.reportMessageInternal = function() { + errors.push(arguments); + }; + var url = 'http://www.test.com/'; + var loaderHooks = new LoaderHooks(reporter, url); + var loader = new Loader(loaderHooks); + loader.script(contents, url); + return errors; + } + + function assertErrorMessage(errors, expectedError, expectedErrorArg) { + assert.isTrue(errors.length > 0); + assert.equal(expectedError, errors[0][1]); + assert.equal(expectedErrorArg, errors[0][2][0]); + } + + function assertCompileError(contents, expectedError, expectedErrorArg) { + var errors = compileAndReturnErrors(contents, 'code'); + assertErrorMessage(errors, expectedError, expectedErrorArg); + } + + test('FreeVariables', function() { + traceur.options.experimental = true; + assertCompileError('var y = xxx;', '%s is not defined', 'xxx'); + assertCompileError('xxx(1,2,3);', '%s is not defined', 'xxx'); + assertCompileError('function foo() { return xxx; }', '%s is not defined', 'xxx'); + assertCompileError('if (true) { console.log(yyy); }', '%s is not defined', 'yyy'); + assertCompileError('function foo() { { let yyy = 5; }; return yyy; }', + '%s is not defined', 'yyy'); + assertCompileError('xxx = 42;', '%s is not defined', 'xxx'); + assertCompileError('xxx.y = 42;', '%s is not defined', 'xxx'); + assertCompileError('fff(42);', '%s is not defined', 'fff'); + assertCompileError('xxx.f(42);', '%s is not defined', 'xxx'); + // TODO(jmesserly): we shouldn't be putting traceur into the global scope + // assertCompileError('traceur.runtime = {};', '%s is not defined', 'traceur'); + }); + + test('FreeVariables2', function() { + // Make sure these don't cause an error + var x = [1, 2]; + var y = [0, ...x, 3]; + assert.equal('0,1,2,3', y.join(',')); + }); + + test('FreeVariables3', function() { + // Regression test. + assert.equal('function', typeof setTimeout); + }); + +}); diff --git a/pool/shard000/JavaScript/0002180_menuConfig.js b/pool/shard000/JavaScript/0002180_menuConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..3e3b2f098f048db9c64feab4ecec6238d4c43369 --- /dev/null +++ b/pool/shard000/JavaScript/0002180_menuConfig.js @@ -0,0 +1,32 @@ +/*jslint node: true */ +/*global module, require*/ +'use strict'; +var newCallback = require('./../construct/newCallback.js'), + newEvent = require('./../construct/newEvent.js'); +/** + * This method returns a {@link ScapeObject} object for schema entries where menu === 'menuConfig'. + * + * @function menuConfig + * @memberof socioscapes + * @param {Object} context - A context object sent by the a {@link ScapeMenu} call (this allows us to use the correct + * {@link ScapeObject} for our context). + * @param {string} command - Should correspond to a socioscapes.fn or soioscapes.fn.alias member name. + * @param {Object} [config] - A configuration object for the corresponding command function. + * @return {Object} context.that - A {@link socioscapes} {@link ScapeObject} object. + */ +function menuConfig(context, command, config) { + var callback = newCallback(arguments), + myCommand = (typeof command === 'function') ? command: false; + if (myCommand) { + myCommand(context.that, config, function (result) { + console.log('The results of your "' + myCommand.name + '" are ready.'); + newEvent('socioscapes.ready.' + myCommand.name, context); + callback(result); + }); + } else { + console.log('Sorry, "' + command + '" is not a valid function.'); + callback(false); + } + return context.that; +} +module.exports = menuConfig; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002181_createUpsertMutationField.js b/pool/shard000/JavaScript/0002181_createUpsertMutationField.js new file mode 100644 index 0000000000000000000000000000000000000000..b8d1499d0796c9ab1e4e54966a41168414e8fff1 --- /dev/null +++ b/pool/shard000/JavaScript/0002181_createUpsertMutationField.js @@ -0,0 +1,109 @@ +const GraphQL = require('graphql'); +const _ = require('lodash'); +const utils = require('../utils'); +const payloadInterface = require('./payloadInterface'); +const clientMutationId = require('./clientMutationId'); +const viewer = require('../queries/viewer'); +const connection = require('../queries/connection'); + +module.exports = { + createGraphQLInputType: createGraphQLInputType, + createGraphQLPayloadType: createGraphQLPayloadType, + createRelayInputType: createRelayInputType, + createRelayPayloadType: createRelayPayloadType, +}; + +function createGraphQLInputType(typeName, object_types) { + return new GraphQL.GraphQLInputObjectType({ + name: `${typeName}Input`, + description: `Locates the ${typeName} node to update and specifies some ` + + 'new field values. Primary key fields are required to be able to locate ' + + 'the node to update.', + fields: Object.assign({}, createInputTypeFields(typeName, object_types)) + }); +} + +function createGraphQLPayloadType(typeName, object_types) { + return new GraphQL.GraphQLObjectType({ + name: `Upsert${typeName}Payload`, + description: `Contains the ${typeName} node upserted by the mutation.`, + fields: { + [utils.lowerCaseFirstLetter(typeName)]: { + type: object_types[typeName], + description: `The upserted ${typeName}.`, + resolve: source => source + }, + [`upserted${typeName}Id`] : { + type: GraphQL.GraphQLID, + description: `The upserted ${typeName} id.`, + resolve: source => source.id, + }, + } + }); +} + +function createRelayInputType(typeName, object_types) { + return new GraphQL.GraphQLInputObjectType({ + name: `Upsert${typeName}Input`, + description: `Locates the ${typeName} node to update and specifies some ` + + 'new field values. Primary key fields are required to be able to locate ' + + 'the node to update.', + fields: Object.assign({clientMutationId: clientMutationId.forInput}, createInputTypeFields(typeName, object_types)), + }); +} + +function createRelayPayloadType(schemaName, typeName, object_types) { + return new GraphQL.GraphQLObjectType({ + name: `Upsert${typeName}Payload`, + description: `Contains the ${typeName} node upserted by the mutation.`, + interfaces: [payloadInterface.createPayloadInterface(schemaName, object_types)], + fields: { + [utils.lowerCaseFirstLetter(typeName)]: { + type: object_types[typeName], + description: `The upserted ${typeName}.`, + resolve: source => source, + }, + [`upserted${typeName}Id`] : { + type: GraphQL.GraphQLID, + description: `The upserted ${typeName} id.`, + resolve: source => source.id, + }, + [`${utils.lowerCaseFirstLetter(typeName)}Edge`]: { + type: connection.createConnectionType(schemaName, typeName, object_types).edgeType, + description: 'An edge to be inserted in a connection with help of the containing cursor.', + resolve: source => ({ + cursor: 0, + node: source, + }), + }, + clientMutationId: clientMutationId.forPayload, + viewer: viewer.createViewerField(schemaName, object_types), + } + }); +} + +function createInputTypeFields(typeName, object_types){ + const result = {}; + const currentFields = object_types[typeName]._typeConfig.fields; + for(const key in currentFields){ + const currentField = currentFields[key]; + if(currentField.type instanceof GraphQL.GraphQLNonNull + && currentField.type.ofType + && currentField.type.ofType instanceof GraphQL.GraphQLScalarType) { + const cloned = _.cloneDeep(currentField); + cloned.type = currentField.type.ofType; + result[currentField.name] = cloned; + } else if(currentField.type instanceof GraphQL.GraphQLList + && currentField.type.ofType + && currentField.type.ofType instanceof GraphQL.GraphQLScalarType) { + const cloned = _.cloneDeep(currentField); + cloned.args = undefined + cloned.resolve = undefined + cloned.type = currentField.type; + result[currentField.name] = cloned; + } else if(currentField.type instanceof GraphQL.GraphQLScalarType) { + result[currentField.name] = currentField; + } + } + return result; +} diff --git a/pool/shard000/JavaScript/0002184_github.dashboard-feed.js b/pool/shard000/JavaScript/0002184_github.dashboard-feed.js new file mode 100644 index 0000000000000000000000000000000000000000..6bf79ae0bf5cb66df17ce7257536e9b595bcd1b7 --- /dev/null +++ b/pool/shard000/JavaScript/0002184_github.dashboard-feed.js @@ -0,0 +1,57 @@ +;(async () => { + const { cheerio } = await importScripts('gloria-utils') + const html = await fetch('https://github.com/dashboard-feed').then(res => res.text()) + const $ = cheerio.load(html) + + const watch = $('.watch_started .body').map((i, el) => ({ + title: $(el).find('.width-full .d-flex > div').contents().not('span').text() + .replace(/^\s/g, '') + .replace(/\s$/g, '') + .replace(/\s+/g, ' ') + , url: 'https://github.com' + ($(el).find('.border').length > 0 + ? $(el).find('.border a').attr('href') + : $(el).find('.d-flex > div a:last-child').attr('href') + ) + , iconUrl: $(el).find('img.avatar').attr('src') + })).get() + + const create = $('.create .body').map((i, el) => ({ + title: $(el).find('.width-full .d-flex > div').contents().not('span').text() + .replace(/^\s/g, '') + .replace(/\s$/g, '') + .replace(/\s+/g, ' ') + , url: 'https://github.com' + ($(el).find('.border').length > 0 + ? $(el).find('.border a').attr('href') + : $(el).find('.d-flex > div a:last-child').attr('href') + ) + , iconUrl: $(el).find('img.avatar').attr('src') + })).get() + + const follow = $('.follow .body').map((i, el) => { + return { + title: $(el).find('.width-full > .d-flex > div').contents().not('span').text() + .replace(/^\s/g, '') + .replace(/\s$/g, '') + .replace(/\s+/g, ' ') + , url: 'https://github.com' + ($(el).find('.border').length > 0 + ? $(el).find('.border a').attr('href') + : $(el).find('.d-flex > div a:last-child').attr('href') + ) + , iconUrl: $(el).find('img.avatar').attr('src') + } + }).get() + + const fork = $('.fork .body').map((i, el) => ({ + title: $(el).find('.width-full .d-flex > div').contents().not('span').text() + .replace(/^\s/g, '') + .replace(/\s$/g, '') + .replace(/\s+/g, ' ') + , url: 'https://github.com' + ($(el).find('.border').length > 0 + ? $(el).find('.border a').attr('href') + : $(el).find('.d-flex > div a:last-child').attr('href') + ) + , iconUrl: $(el).find('img.avatar').attr('src') + })).get() + + return [...watch, ...create, ...follow, ...fork].filter(x => !!x.title) +})().then(commit) diff --git a/pool/shard000/JavaScript/0002186_max-length-exceeded-namePrefix.https.window.js b/pool/shard000/JavaScript/0002186_max-length-exceeded-namePrefix.https.window.js new file mode 100644 index 0000000000000000000000000000000000000000..8aee40fcd3b9d5d9b840101856c8f23805214815 --- /dev/null +++ b/pool/shard000/JavaScript/0002186_max-length-exceeded-namePrefix.https.window.js @@ -0,0 +1,19 @@ +// META: script=/resources/testharness.js +// META: script=/resources/testharnessreport.js +// META: script=/resources/testdriver.js +// META: script=/resources/testdriver-vendor.js +// META: script=/bluetooth/resources/bluetooth-test.js +// META: script=/bluetooth/resources/bluetooth-fake-devices.js +'use strict'; +const test_desc = 'A device name prefix longer than 248 must reject.'; +const expected = new DOMException( + 'Failed to execute \'requestDevice\' on \'Bluetooth\': A device ' + + 'name can\'t be longer than 248 bytes.', + new TypeError()); +const name_too_long = 'a'.repeat(249); + +bluetooth_test( + () => assert_promise_rejects_with_message( + requestDeviceWithTrustedClick({filters: [{namePrefix: name_too_long}]}), + expected, 'Device name longer than 248'), + test_desc); diff --git a/pool/shard000/JavaScript/0002189_failover.js b/pool/shard000/JavaScript/0002189_failover.js new file mode 100644 index 0000000000000000000000000000000000000000..d2bd4c3e53796c7e5c777b62b7035824c62d3626 --- /dev/null +++ b/pool/shard000/JavaScript/0002189_failover.js @@ -0,0 +1,70 @@ +/*! + * Filename: failover.js + * Author: Evan Lucas + * Copyright: 2012-2013 5060 + * Description: Failover module for DNSMadeEasy API V2.0 + * + * This file is part of dme2-node. + * + * dme2-node is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * dme2-node is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with dme2-node. If not, see . + * + */ + +/** + * Module depends + */ +var dnsmadeeasy = require('./core'), + utils = require('./utils'); + +/** + * Expose the ManagedDNS submodule + */ +var Failover = exports.Failover = function(client) { + if (!client) throw new Error('Failover must be constructed with a client'); + + this.client = client; +}; + + + +Failover.prototype = { + /** + * configureFailover + * + * @param {String} Record ID + * @param {Object} Failover config + * @param {Function} Callback function(err, data) + * @return {Object} Failover response + * @api public + */ + + configureFailover: function() { + var args = utils.getArgs(arguments), + cb = (typeof(args[args.length - 1]) === 'function') && args.pop(), + foconfig = (typeof(args[args.length - 1]) === 'object') && args.pop(), + recordid = (typeof(args[args.length - 1]) === 'string') && args.pop(), + self = this; + if (!recordid) { + return cb({status: 'error', message: 'Must pass a valid record ID.'}); + } + + if (!foconfig) { + return cb({status: 'error', message: 'Must pass a valid object for failover configuration.'}); + } + self.client.put('monitor', recordid, foconfig, function(err, data) { + if (err) return cb(err); + cb(null, data); + }); + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002191_manager.js b/pool/shard000/JavaScript/0002191_manager.js new file mode 100644 index 0000000000000000000000000000000000000000..36e673c7f0be31627671e87b9b9286e2cda8d3b4 --- /dev/null +++ b/pool/shard000/JavaScript/0002191_manager.js @@ -0,0 +1,283 @@ +var STOP = 1; +var FORCED_STOP = 2; + +/** + * Manager + * @param {HTMLElement} element + * @param {Object} [options] + * @constructor + */ +function Manager(element, options) { + options = options || {}; + + this.options = merge(options, Hammer.defaults); + this.options.inputTarget = this.options.inputTarget || element; + + this.handlers = {}; + this.session = {}; + this.recognizers = []; + + this.element = element; + this.input = createInputInstance(this); + this.touchAction = new TouchAction(this, this.options.touchAction); + + toggleCssProps(this, true); + + each(options.recognizers, function(item) { + var recognizer = this.add(new (item[0])(item[1])); + item[2] && recognizer.recognizeWith(item[2]); + item[3] && recognizer.requireFailure(item[3]); + }, this); +} + +Manager.prototype = { + /** + * set options + * @param {Object} options + * @returns {Manager} + */ + set: function(options) { + extend(this.options, options); + + // Options that need a little more setup + if (options.touchAction) { + this.touchAction.update(); + } + if (options.inputTarget) { + // Clean up existing event listeners and reinitialize + this.input.destroy(); + this.input.target = options.inputTarget; + this.input.init(); + } + return this; + }, + + /** + * stop recognizing for this session. + * This session will be discarded, when a new [input]start event is fired. + * When forced, the recognizer cycle is stopped immediately. + * @param {Boolean} [force] + */ + stop: function(force) { + this.session.stopped = force ? FORCED_STOP : STOP; + }, + + /** + * run the recognizers! + * called by the inputHandler function on every movement of the pointers (touches) + * it walks through all the recognizers and tries to detect the gesture that is being made + * @param {Object} inputData + */ + recognize: function(inputData) { + var session = this.session; + if (session.stopped) { + return; + } + + // run the touch-action polyfill + this.touchAction.preventDefaults(inputData); + + var recognizer; + var recognizers = this.recognizers; + + // this holds the recognizer that is being recognized. + // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED + // if no recognizer is detecting a thing, it is set to `null` + var curRecognizer = session.curRecognizer; + + // reset when the last recognizer is recognized + // or when we're in a new session + if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) { + curRecognizer = session.curRecognizer = null; + } + + var i = 0; + while (i < recognizers.length) { + recognizer = recognizers[i]; + + // find out if we are allowed try to recognize the input for this one. + // 1. allow if the session is NOT forced stopped (see the .stop() method) + // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one + // that is being recognized. + // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer. + // this can be setup with the `recognizeWith()` method on the recognizer. + if (session.stopped !== FORCED_STOP && ( // 1 + !curRecognizer || recognizer == curRecognizer || // 2 + recognizer.canRecognizeWith(curRecognizer))) { // 3 + recognizer.recognize(inputData); + } else { + recognizer.reset(); + } + + // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the + // current active recognizer. but only if we don't already have an active recognizer + if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) { + curRecognizer = session.curRecognizer = recognizer; + } + i++; + } + }, + + /** + * get a recognizer by its event name. + * @param {Recognizer|String} recognizer + * @returns {Recognizer|Null} + */ + get: function(recognizer) { + if (recognizer instanceof Recognizer) { + return recognizer; + } + + var recognizers = this.recognizers; + for (var i = 0; i < recognizers.length; i++) { + if (recognizers[i].options.event == recognizer) { + return recognizers[i]; + } + } + return null; + }, + + /** + * add a recognizer to the manager + * existing recognizers with the same event name will be removed + * @param {Recognizer} recognizer + * @returns {Recognizer|Manager} + */ + add: function(recognizer) { + if (invokeArrayArg(recognizer, 'add', this)) { + return this; + } + + // remove existing + var existing = this.get(recognizer.options.event); + if (existing) { + this.remove(existing); + } + + this.recognizers.push(recognizer); + recognizer.manager = this; + + this.touchAction.update(); + return recognizer; + }, + + /** + * remove a recognizer by name or instance + * @param {Recognizer|String} recognizer + * @returns {Manager} + */ + remove: function(recognizer) { + if (invokeArrayArg(recognizer, 'remove', this)) { + return this; + } + + var recognizers = this.recognizers; + recognizer = this.get(recognizer); + recognizers.splice(inArray(recognizers, recognizer), 1); + + this.touchAction.update(); + return this; + }, + + /** + * bind event + * @param {String} events + * @param {Function} handler + * @returns {EventEmitter} this + */ + on: function(events, handler) { + var handlers = this.handlers; + each(splitStr(events), function(event) { + handlers[event] = handlers[event] || []; + handlers[event].push(handler); + }); + return this; + }, + + /** + * unbind event, leave emit blank to remove all handlers + * @param {String} events + * @param {Function} [handler] + * @returns {EventEmitter} this + */ + off: function(events, handler) { + var handlers = this.handlers; + each(splitStr(events), function(event) { + if (!handler) { + delete handlers[event]; + } else { + handlers[event].splice(inArray(handlers[event], handler), 1); + } + }); + return this; + }, + + /** + * emit event to the listeners + * @param {String} event + * @param {Object} data + */ + emit: function(event, data) { + // we also want to trigger dom events + if (this.options.domEvents) { + triggerDomEvent(event, data); + } + + // no handlers, so skip it all + var handlers = this.handlers[event] && this.handlers[event].slice(); + if (!handlers || !handlers.length) { + return; + } + + data.type = event; + data.preventDefault = function() { + data.srcEvent.preventDefault(); + }; + + var i = 0; + while (i < handlers.length) { + handlers[i](data); + i++; + } + }, + + /** + * destroy the manager and unbinds all events + * it doesn't unbind dom events, that is the user own responsibility + */ + destroy: function() { + this.element && toggleCssProps(this, false); + + this.handlers = {}; + this.session = {}; + this.input.destroy(); + this.element = null; + } +}; + +/** + * add/remove the css properties as defined in manager.options.cssProps + * @param {Manager} manager + * @param {Boolean} add + */ +function toggleCssProps(manager, add) { + var element = manager.element; + if (!element.style) { + return; + } + each(manager.options.cssProps, function(value, name) { + element.style[prefixed(element.style, name)] = add ? value : ''; + }); +} + +/** + * trigger dom event + * @param {String} event + * @param {Object} data + */ +function triggerDomEvent(event, data) { + var gestureEvent = document.createEvent('Event'); + gestureEvent.initEvent(event, true, true); + gestureEvent.gesture = data; + data.target.dispatchEvent(gestureEvent); +} diff --git a/pool/shard000/JavaScript/0002192_plugin.js b/pool/shard000/JavaScript/0002192_plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..0c4455b757120650a214a08356a7e942fcfef87b --- /dev/null +++ b/pool/shard000/JavaScript/0002192_plugin.js @@ -0,0 +1,105 @@ +'use strict'; +/* jshint node: true */ + +var reQuote = /'/g; +var escapedQuote = '\\\''; +var reNewLine = /\r?\n/g; +var escapedNewLine = '\\n\' +\n \''; +var outputBlockTemplate = 'angular.module(%quotes%%name%%quotes%%newModule%);'; +var newModuleTemplate = ', []'; +var iife = '+(function() { %content% })();' + +function createModuleInjectionBlock(options) { + var useSingleQuotes = (options.useSingleQuotes); + var templates = transformTemplates(options.templates, options); + + var outputOptions = { + name: options.moduleName, + quotes: useSingleQuotes ? '\'' : '"', + newModule: '' + }; + + var existingModule = replaceVariables(outputBlockTemplate, outputOptions); + outputOptions.newModule = newModuleTemplate; + var newModule = replaceVariables(outputBlockTemplate, outputOptions); + + var output = replaceVariables('var m; try { m = %existingModule% } catch (e) { m = %newModule% } ', { + existingModule: existingModule, + newModule: newModule + }); + + output += 'm.run([\'$templateCache\', function(a) { ' + templates + ' }]);'; + + return replaceVariables(iife, { content: output}); +} + +module.exports = { + createModuleInjectionBlock: createModuleInjectionBlock +}; + + +function escapeHtmlContent(content) { + return content.replace(reQuote, escapedQuote).replace(reNewLine, escapedNewLine); +} + +function escapeTags(content) { + return content.replace(//mg, '>'); +} + +function replaceVariables(template, args) { + return template.replace(/(%([^%]+?)%)/g, function(a, b, match) { + return args[match] || ''; + }); +} + +function transformTemplates(templates, options) { + var cacheOutput = '', + i = templates.length; + + while (i--) { + cacheOutput += transformTemplateEntry(templates[i], options); + } + + return cacheOutput; +} + +function transformTemplateEntry(entry, options) { + var path = getFinalPath(entry.path, options); + var content = entry.content; + + if (options.minify !== false) { + content = minifyContent(content, {entry: entry, minify: options.minify}); + } + + content = escapeHtmlContent(content); + + return 'a.put(\'' + path + '\', \'' + content + '\');\n\t'; +} + +function minifyContent(content, options) { + var htmlMin = require('html-minifier').minify; + + try { + return htmlMin(content, options.minify); + } catch (e) { + return '

Invalid template: ' + options.entry.path + '

' + + '
' + escapeTags(String(e)) + '
'; + } +} + +function getFinalPath(path, options) { + var strip = options.stripFromPath; + + if (strip && path.indexOf(strip) === 0) { + path = path.slice(strip.length); + } + + // replace all backslashes with forward slash + path = path.replace(/\\/g, '/'); + + if (options.prependToPath) { + path = options.prependToPath + path; + } + + return path; +} diff --git a/pool/shard000/JavaScript/0002197_generate-bmc-password.js b/pool/shard000/JavaScript/0002197_generate-bmc-password.js new file mode 100644 index 0000000000000000000000000000000000000000..188c6bfaf76609623791501986c3a2f0d0a521a3 --- /dev/null +++ b/pool/shard000/JavaScript/0002197_generate-bmc-password.js @@ -0,0 +1,51 @@ +// Copyright 2016, EMC, Inc. + +'use strict'; + +var di = require('di'); + + +module.exports = bmcPasswordJobFactory; +di.annotate(bmcPasswordJobFactory, new di.Provide('Job.BMC.Password')); +di.annotate(bmcPasswordJobFactory, new di.Inject( + 'Job.Base', + 'Logger', + 'Util', + 'uuid', + 'Promise', + 'crypto' +)); +function bmcPasswordJobFactory(BaseJob, Logger, util, uuid, Promise,crypto) { + + var logger = Logger.initialize(bmcPasswordJobFactory); + + /** + * + * @param {Object} options + * @param {Object} context + * @param {String} taskId + * @constructor + */ + function BmcPasswordJob(options, context, taskId) { + BmcPasswordJob.super_.call(this, logger, options, context, taskId); + } + + util.inherits(BmcPasswordJob, BaseJob); + + /** + * @memberOf BmcPasswordJob + */ + BmcPasswordJob.prototype._run = function _run() { + var self = this; + //token is randomly generated password for the bmc credentials + var token = crypto.randomBytes(4).toString('hex'); + + //If the user doesn't enter a username and password, the default will be + //monorail for a user name and a random password(token) + this.context.password = this.options.password || this.context.password || token ; + this.context.user = this.options.user || '__rackhd__' ; + self._done(); + }; + + return BmcPasswordJob; +} diff --git a/pool/shard000/JavaScript/0002201_sync-animation.js b/pool/shard000/JavaScript/0002201_sync-animation.js new file mode 100644 index 0000000000000000000000000000000000000000..a990a752e534e0becc94ad543e415997c71d3059 --- /dev/null +++ b/pool/shard000/JavaScript/0002201_sync-animation.js @@ -0,0 +1,31 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public +* License, v. 2.0. If a copy of the MPL was not distributed with this +* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +var Mozilla = window.Mozilla || {}; + +(function($) { + 'use strict'; + + Mozilla.syncAnimation = function() { + var $syncAnim = $('.sync-anim'); + var $laptop = $syncAnim.find('.laptop'); + var $laptopScreen = $laptop.find('.inner'); + var $phone = $syncAnim.find('.phone'); + var $arrows = $laptop.find('.arrows'); + + $syncAnim.addClass('on'); + + $arrows.one('webkitAnimationStart MSAnimationStart animationstart', function () { + $laptopScreen.addClass('faded'); + }); + + $arrows.one('webkitAnimationEnd MSAnimationEnd animationend', function () { + $laptopScreen.removeClass('faded'); + }); + + $phone.one('webkitAnimationEnd MSAnimationEnd animationend', '.passwords', function () { + $syncAnim.addClass('complete'); + }); + }; +})(window.jQuery); diff --git a/pool/shard000/JavaScript/0002203_index.js b/pool/shard000/JavaScript/0002203_index.js new file mode 100644 index 0000000000000000000000000000000000000000..8f13346bfa73f9b630cf3a59763d8bbd7d260c4b --- /dev/null +++ b/pool/shard000/JavaScript/0002203_index.js @@ -0,0 +1,205 @@ +import Ember from 'ember'; + +var ProgressEventTarget = Ember.Mixin.create(Ember.PromiseProxyMixin, { + isAborted: false, + isErrored: false, + isLoaded: false, + isLoadStarted: false, + isTimedOut: false, + isLoadEnded: false, + + + deferred: Ember.computed(function() { + var deferred = Ember.RSVP.defer(); + this.set('promise', deferred.promise); + return deferred; + }).readOnly(), + + target: null, //required + + init: function() { + this._super.apply(this, arguments); + var object = this; + var target = this.get('target'); + var deferred = this.get('deferred'); + target.onabort = function() { + object.set('isAborted', true); + deferred.reject('aborted'); + }; + target.onerror = function() { + object.set('isErrored', true); + deferred.reject('error'); + }; + target.onload = function() { + object.set('isLoaded', true); + deferred.resolve(target); + }; + target.onloadstart = function() { + object.set('loadStartedAt', new Date()); + object.set('isLoadStarted', true); + }; + target.ontimeout = function() { + object.set('isTimedOut', true); + deferred.reject('timeout'); + }; + target.onloadend = function() { + object.set('loadEndedAt', new Date()); + object.set('isLoadEnded', true); + }; + target.onprogress = function(event) { + object.set('progress', Progress.create({ + target: object, + event: event, + at: new Date() + })); + }; + } +}); + +var Progress = Ember.Object.extend({ + target: null, + event: null, + lengthComputable: Ember.computed.readOnly('event.lengthComputable'), + loaded: Ember.computed.readOnly('event.loaded'), + total: Ember.computed.readOnly('event.total'), + ratio: Ember.computed('lengthComputable', 'loaded', 'total', function() { + if (this.get('lengthComputable')) { + return this.get('loaded') / this.get('total'); + } else { + return NaN; + } + }), + percentage: Ember.computed('ratio', function() { + var ratio = this.get('ratio'); + if (!!ratio) { + return Math.round(ratio * 100); + } else { + return NaN; + } + }), + averageSpeed: Ember.computed('loaded', 'totalTime', function() { + var durationMillis = this.get('totalTime'); + var durationSeconds = Math.round(durationMillis / 1000); + return this.get('loaded') / durationSeconds; + }), + totalTime: Ember.computed('target.loadStartedAt', 'at', function() { + return this.get('at').getTime() - this.get('target.loadStartedAt').getTime(); + }) +}); + +function delegateToXHR(method) { + return function() { + var target = this.get('target'); + return target[method].apply(target, arguments); + }; +} + +var XHR = Ember.Object.extend(ProgressEventTarget, { + target: Ember.computed(function() { + return new window.XMLHttpRequest(); + }).readOnly(), + + open: delegateToXHR('open'), + abort: delegateToXHR('abort'), + send: function() { + //materialize uploads + this.get('upload'); + return delegateToXHR("send").apply(this, arguments); + }, + setRequestHeader: delegateToXHR('setRequestHeader'), + getResponseHeader: delegateToXHR('getResponseHeader'), + overrideMimeType: delegateToXHR('overrideMimeType'), + + + status: Ember.computed.readOnly('state.status'), + readyState: Ember.computed.readOnly('state.readyState'), + + responseType: Ember.computed.alias('target.responseType'), + responseBinding: Ember.computed.oneWay('state.response'), + responseTextBinding: Ember.computed.oneWay('state.responseText'), + responseXMLBinding: Ember.computed.oneWay('state.responseXML'), + + timeout: Ember.computed.alias('target.timeout'), + upload: Ember.computed(function() { + return Upload.create({ + target: this.get('target.upload') + }); + }).readOnly(), + state: Ember.computed(function() { + return UnsentState.create({ + request: this.get('request') + }); + }), + init: Ember.observer(function() { + this._super.apply(this, arguments); + var object = this; + var target = this.get('target'); + target.onreadystatechange = function() { + if(target.readyState){ + var State = READY_STATES[target.readyState]; + object.set('state', State.create({request: target})); + } + }; + }) +}); + + +var Upload = Ember.Object.extend(ProgressEventTarget); + +var ReadyState = Ember.Object.extend({ + status: Ember.computed.readOnly('request.status'), + readyState: Ember.computed.readOnly('request.readyState'), + response: Ember.computed.readOnly('request.response'), + responseText: Ember.computed(function() { + var responseType = this.get('request.responseType'); + if (Ember.isEmpty(responseType) || responseType === 'text') { + return this.get('request.responseText'); + } else { + return this.undefined; + } + }).readOnly(), + responseXML: Ember.computed(function() { + var responseType = this.get('request.responseType'); + if (Ember.isEmpty(responseType) || responseType === 'document') { + return this.get('request.responseXML'); + } else { + return this.undefined; + } + }).readOnly() +}); + +var UnsentState = ReadyState.extend({ + value: 0, + name: 'UNSENT', + description: 'open() has not been called yet.' +}); + +var OpenedState = ReadyState.extend({ + value: 1, + name: 'OPENED', + description: 'send() has not been called yet.' +}); + +var HeadersReceivedState = ReadyState.extend({ + value: 2, + name: 'HEADERS_RECEIVED', + description: 'send() has been called, and headers and status are available.' +}); + +var LoadingState = ReadyState.extend({ + value: 3, + name: 'LOADING', + description: 'Downloading; responseText holds partial data.' +}); + +var DoneState = ReadyState.extend({ + value: 4, + name: 'DONE', + description: 'The operation is complete.' +}); + +var READY_STATES = [UnsentState, OpenedState, HeadersReceivedState, LoadingState, DoneState]; + +Ember.XHR = XHR; + +export default XHR; diff --git a/pool/shard000/JavaScript/0002205_query.js b/pool/shard000/JavaScript/0002205_query.js new file mode 100644 index 0000000000000000000000000000000000000000..b455d1793759342af003fd3f3bf8a7f4dc1dd6d5 --- /dev/null +++ b/pool/shard000/JavaScript/0002205_query.js @@ -0,0 +1,83 @@ +var mongoose = require("mongoose"); +var async = require("async"); +var jsonUtils = require("../../../utils/json"); +var MongooseStudentModel = mongoose.model('Student'); +var StudentModel = require('../../../studentModel') + +/** + * Queries for a single user given a mongodb query. + * @param {Object} query - a mongodb query to execute. + * @param {string[]} fields - Fields to query for. + * @param {function} next - Callback after query. + */ +var queryOne = module.exports.queryOne = function queryOne(query, req, res, fields, next){ + var rFields = StudentModel.fields(fields); + + // make a query for the given fields + MongooseStudentModel.findOne(query, function(err, doc){ + + if(err || !doc){ + next(err, doc); + return; + } + + doc.toRealObject(req, res, rFields, next); + return; + }); +}; + +var query = module.exports.query = function query(query, req, res, next){ + MongooseStudentModel.find(query, next); +}; + +var queryJoin = module.exports.queryJoin = function queryJoin(queries, skip, limit, fields, req, res, next){ + // fields to query for. + var rFields = StudentModel.fields(fields); + + // indexes to use eventually. + var startIndex = skip; + var endIndex = skip+limit; + + // asyncronously fetch all the results. + async.map(queries, function(sQuery, qNext){ + query(sQuery, req, res, qNext); + }, function(err, res){ + + // if there is an error + // we exit. + if(err){ + next(err, null, null); + return; + } + + // get all the results without doubles + // we use the eid property to uniquely identify people. + var allResults = jsonUtils.removeJSONDoubles( + Array.prototype.concat.apply([], res), + function(user){ + return user['eid']; + } + ); + + // we count and slice the results + // the user wanted. + var count = allResults.length; + allResults = allResults.splice(startIndex, endIndex); + + async.map(allResults, function(d, dNext){ + return d.toRealObject(req, res, rFields, dNext); + }, function(err, results){ + + if(err){ + next(err, null, null); + return; + } + + next(null, results, count); + }); + + // and return that. + + return; + }); +} diff --git a/pool/shard000/JavaScript/0002207_main.js b/pool/shard000/JavaScript/0002207_main.js new file mode 100644 index 0000000000000000000000000000000000000000..d2a796e3cf38721fc8eab9219e31c3a0c2660755 --- /dev/null +++ b/pool/shard000/JavaScript/0002207_main.js @@ -0,0 +1,74 @@ +var trimlines = require('../'); +var should = require('should'); +var assert = require('stream-assert'); +var testStream = require('./test-stream'); +var gulp = require('gulp'); + +require('mocha'); + +var test = function (src, dest, done, options) { + testStream(src) + .pipe(trimlines(options || {})) + .pipe(assert.first(function (d) { d.contents !== null ? d.contents.toString().should.eql(dest) : should.equal(src, d.contents); })) + .pipe(assert.end(done)); +}; + +describe('gulp-trimlines', function() { + describe('trimlines()', function() { + it('should handle empty files with default options', function (done) { + test('', '', done); + }); + + it('should handle empty files with explicit options', function (done) { + test('', '', done, {leading: true, trailing: true}); + }); + + it('should handle empty lines with default options', function (done) { + test('\n\n\n', '\n\n\n', done); + }); + + it('should handle empty lines with explicit options', function (done) { + test('\n\n\n', '\n\n\n', done, {leading: true, trailing: true}); + }); + + it('should handle both leading and trailing spaces and tabs', function (done) { + test(' \t foo \n \t bar \n', 'foo\nbar\n', done); + }); + + it('should ignore both leading and trailing spaces and tabs when both set to false', function (done) { + test(' \t foo \n \t bar \n', ' \t foo \n \t bar \n', done, {leading: false, trailing: false}); + }); + + it('should ignore both leading and trailing hashes without an explicit patterns', function (done) { + test('##foo##\n####bar####\n', '##foo##\n####bar####\n', done); + }); + + it('should handle both leading and trailing hashes with an explicit leading and trailing patterns', function (done) { + test('##foo##\n####bar####\n', 'foo\nbar\n', done, {leadingPattern: '#+', trailingPattern: '#+'}); + }); + + it('should handle both leading and trailing hashes with an explicit pattern', function (done) { + test('##foo##\n####bar####\n', 'foo\nbar\n', done, {pattern: '^#+|#+$'}); + }); + + it('should handle just leading spaces and tabs', function (done) { + test(' \t foo \t \n \t bar \t \n', 'foo \t \nbar \t \n', done, {trailing: false}); + }); + + it('should handle just leading hashes with an explicit leading pattern', function (done) { + test('##foo##\n####bar####\n', 'foo##\nbar####\n', done, {trailing: false, leadingPattern: '#+'}); + }); + + it('should handle just trailing spaces and tabs', function (done) { + test(' \t foo \t \n \t bar \t \n', ' \t foo\n \t bar\n', done, {leading: false}); + }); + + it('should handle just trailing hashes with an explicit trailing pattern', function (done) { + test('##foo##\n####bar####\n', '##foo\n####bar\n', done, {leading: false, trailingPattern: '#+'}); + }); + + it('should handle null buffer contents', function (done) { + test(null, null, done); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0002208_manage_page.js b/pool/shard000/JavaScript/0002208_manage_page.js new file mode 100644 index 0000000000000000000000000000000000000000..532fe47c0298830049400e7f2a146719c6d1d4d3 --- /dev/null +++ b/pool/shard000/JavaScript/0002208_manage_page.js @@ -0,0 +1,109 @@ +var j = jQuery.noConflict(); +//editor initialization +var doc; +var editorFuncs = new EditorFuncs(); +j(document).ready(function(){ + doc = j('textarea[data-uk-markdownarea]').data('markdownarea').editor.getDoc(); + j('#editor').hide(); + j('#save').addClass('disabled'); + + //Enable save button + j('#title').on('input', function(){ + j('#save').removeClass('disabled'); + }); + j('textarea[data-uk-markdownarea]').data('markdownarea').editor.on('change',function(){ + j('#save').removeClass('disabled'); + }); +}); + +//Add new Button action +j(document).on('click', '.button.add.new', function(){ + if(j('#editor').is(':hidden')){ + j('#editor').show(); + j('#editor').attr('page_id', 'new'); + j('#title').html(''); + doc.setValue(''); + } + var len = doc.getValue().length | j('#title').html().length | 0; + if(len!=0){ + j('.small.confirm.unsaved.modal').modal('setting', { + closable : false, + onDeny : function(){}, + onApprove : function() { + j('#editor').show(); + j('#editor').attr('page_id', 'new'); + j('#title').html(''); + doc.setValue(''); + } + }).modal('show'); + } +}); + +// Save function +j(document).on('click','#save',function(){ + editorFuncs.savePage(j('#editor').attr('page_id')); + j('#save').addClass('disabled'); +}); + +//Load full page while clicking item on the left panel +j(document).on('click', 'a.item.pageref', function(){ + var id = j(this).attr('id'); + var this_element = j(this); + j('.inverted.dimmer').addClass('active'); + j.ajax({ + url : '/page/load/'+id, + type : 'GET', + dataType : 'json', + success : function(data){ + j('.inverted.dimmer').removeClass('active'); + j('#editor').show(); + j('#editor').attr('page_id', data._id); + j('#title').html(data.title); + doc.setValue(data.content); + j('a.item.pageref.active').removeClass('active'); + j(this_element).addClass('active'); + if(data.published == true){ + j('#publish').html('Unpublish'); + j('#publish').addClass('red').removeClass('teal'); + j('#publish').attr('id','unpublish'); + } + else{ + j('#unpublish').html('Publish'); + j('#unpublish').addClass('teal').removeClass('red'); + j('#unpublish').attr('id','publish'); + } + }, + error : function(err){ + alert('Something went terribly wrong !! Please try again...'); + j('.inverted.dimmer').removeClass('active'); + } + + }); +}); +//Publish Action +j(document).on('click', '#publish, #unpublish', function(){ + var status = j(this).attr('id'); + var id = j('#editor').attr('page_id'); + editorFuncs.setStatusPage(id, status); +}) + +//Setting Page Attributes +j('#pageAttr').on('click',function(){ + j('.pageAttr.modal').modal('setting', { + closable : false, + onDeny : function(){}, + onApprove : function() { + var order = j('#order').val() | 0; + var parent_id = j('#parent').val(); + var id = j('#editor').attr('page_id'); + j.ajax({ + url : '/page/save-attribute', + type : 'GET', + data : {id : id, order : order, parent_id : parent_id}, + error : function(err){ + alert('Sorry. Something unexpected occured..'); + } + }); + } + }).modal('show'); +}) diff --git a/pool/shard000/JavaScript/0002217_helper.js b/pool/shard000/JavaScript/0002217_helper.js new file mode 100644 index 0000000000000000000000000000000000000000..b83a0a116e7f0f24ef1414ddd0b4d2f3b9a878c2 --- /dev/null +++ b/pool/shard000/JavaScript/0002217_helper.js @@ -0,0 +1,68 @@ +//returns true if user is on own page +function isOwner(user, owner){ + return user && user.username === owner.username; +} + +//returns age of user in years +function getAge(birthday){ + var difference = new Date() - new Date(birthday); + var year = 1000 * 60 * 60 * 24 * 365; + return Math.floor(difference / year); +} + +//cleans game name of edge case characters +function getCleanedGameName(name){ + var name = name + .toLowerCase() + .replace('é', 'e') + .replace('&', 'and'); + return name; +} + +//returns the index that the one up exists in the array +function getOneUppedIndex(oneUps, oneUpper){ + if (!oneUps || !oneUpper){ + return -1; + } + for (var i = 0; i < oneUps.length; i++){ + if (oneUps[i].one_upper === oneUpper.username){ + return i; + } + } + return -1; +} + +//returns whether or not user has oneUpped this object +function hasOneUpped(oneUps, oneUpper){ + return getOneUppedIndex(oneUps, oneUpper) >= 0; +} + +//returns list of game filtered by source +function getGames(list, source){ + var games = []; + for (var i = 0; i < list.length; i++) { + if (source !== list[i].source){ + continue; + } + var game = { + name: list[i].name, + uri: encodeURI(list[i].name) + }; + if (source === "steam"){ + game.appid = list[i].steam.appid; + game.img_logo_url = list[i].steam.img_logo_url; + game.playtime_forever = list[i].playtime_forever; + } + games.push(game); + } + return games; +} + +module.exports = { + isOwner: isOwner, + getAge: getAge, + getCleanedGameName: getCleanedGameName, + getOneUppedIndex: getOneUppedIndex, + hasOneUpped: hasOneUpped, + getGames: getGames +}; diff --git a/pool/shard000/JavaScript/0002218_post.js b/pool/shard000/JavaScript/0002218_post.js new file mode 100644 index 0000000000000000000000000000000000000000..ca58fe0e592df38725f0e5c46767ede37f9a6cde --- /dev/null +++ b/pool/shard000/JavaScript/0002218_post.js @@ -0,0 +1,34 @@ +var _ = require('lodash-node'); +var types = require('./types'); +var tagModel = require('./tag'); + +module.exports = {}; + +module.exports.schema = { + uuid: String, + id: Number, + title: String, + slug: String, + status: function (val) { expect(val).toMatch(/^(draft|published)$/) }, + markdown: String, + html: String, + tags: function (tags) { + return _.all(tags, function (t) { + return expect(t).toContainJsonTypes(tagModel.schema); + }); + }, + image: types.StringOrNull, + featured: Boolean, + page: Boolean, + language: 'en_US', + author: Number, + + created_by: Number, + updated_by: Number, + published_by: types.NumberOrNull, + created_at: types.DateString, + updated_at: types.DateString, + published_at: types.DateStringOrNull, + meta_title: types.StringOrNull, + meta_description: types.StringOrNull, +}; diff --git a/pool/shard000/JavaScript/0002219_numbers.js b/pool/shard000/JavaScript/0002219_numbers.js new file mode 100644 index 0000000000000000000000000000000000000000..058ebfbdcfd219427555b33903c68aea17779af7 --- /dev/null +++ b/pool/shard000/JavaScript/0002219_numbers.js @@ -0,0 +1,63 @@ +var settings = require("./settings"); +var templatePanel = require("./templates/numbers.html"); + +var _ = codebox.require("hr.utils"); +var View = codebox.require("hr.view"); +var $ = codebox.require("jquery"); +var rpc = codebox.require("core/rpc"); +var commands = codebox.require("core/commands"); + +var getSIPConfig = _.memoize(function() { + return rpc.execute('corvisa/sip'); +}); + +var Panel = View.Template.extend({ + template: templatePanel, + className: "component-panel-corvisa-numbers", + events: { + "click .number": "doCallNumber" + }, + + initialize: function(options) { + Panel.__super__.initialize.apply(this, arguments); + + this.numbers = []; + this.updateNumbers(); + }, + + templateContext: function() { + return { + numbers: this.numbers + }; + }, + + // Update list of numbers + updateNumbers: function() { + var that = this; + + return rpc.execute("corvisa/numbers") + .then(function(nb) { + that.numbers = nb; + that.update(); + }); + }, + + // Start a call + doCallNumber: function(e) { + var that = this; + var number = $(e.currentTarget).data("number"); + + e.preventDefault(); + + return getSIPConfig() + .then(function(config) { + codebox.sip.setConfig({ + // todo make config + }); + + return commands.run("sip.call", { number: number }); + }); + } +}); + +module.exports = Panel; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002224_modalityLUT.js b/pool/shard000/JavaScript/0002224_modalityLUT.js new file mode 100644 index 0000000000000000000000000000000000000000..7968661629e9b33036e06397eb013ec4ce165c04 --- /dev/null +++ b/pool/shard000/JavaScript/0002224_modalityLUT.js @@ -0,0 +1,48 @@ +/** + * This module generates a Modality LUT + */ + +(function (cornerstone) { + + "use strict"; + + + function generateLinearModalityLUT(slope, intercept) { + var localSlope = slope; + var localIntercept = intercept; + return function(sp) { + return sp * localSlope + localIntercept; + } + } + + function generateNonLinearModalityLUT(modalityLUT) { + var minValue = modalityLUT.lut[0]; + var maxValue = modalityLUT.lut[modalityLUT.lut.length -1]; + var maxValueMapped = modalityLUT.firstValueMapped + modalityLUT.lut.length; + return function(sp) { + if(sp < modalityLUT.firstValueMapped) { + return minValue; + } + else if(sp >= maxValueMapped) + { + return maxValue; + } + else + { + return modalityLUT.lut[sp]; + } + } + } + + function getModalityLUT(slope, intercept, modalityLUT) { + if (modalityLUT) { + return generateNonLinearModalityLUT(modalityLUT); + } else { + return generateLinearModalityLUT(slope, intercept); + } + } + + // Module exports + cornerstone.internal.getModalityLUT = getModalityLUT; + +}(cornerstone)); diff --git a/pool/shard000/JavaScript/0002227_forgotpassword.js b/pool/shard000/JavaScript/0002227_forgotpassword.js new file mode 100644 index 0000000000000000000000000000000000000000..032714756fcb87587c39e27011a6e7eb4cbef8f3 --- /dev/null +++ b/pool/shard000/JavaScript/0002227_forgotpassword.js @@ -0,0 +1,36 @@ +var Application; + +(function (_, Backbone, Application) { + var Models = Application.Models || (Application.Models = {}); + + Models.ForgotPassword = Backbone.Model.extend({ + urlRoot: function() { + return Application.serverUrlPrefix + '/passwords/forgot'; + }, + + defaults: function() { + return { + email: null + }; + }, + + validate: function (attributes) { + var Validation = Models.Validation; + var errors = {}; + + if (attributes.email) { + if (!Validation.isValidEmailFormat(attributes.email)) { + Validation.addError( + errors, + 'email', + 'Invalid email address format.'); + } + } else { + Validation.addError(errors, 'email', 'Email is required.'); + } + + return _.isEmpty(errors) ? void(0) : errors; + } + }); + +})(_, Backbone, Application || (Application = {})); diff --git a/pool/shard000/JavaScript/0002236_Agent.js b/pool/shard000/JavaScript/0002236_Agent.js new file mode 100644 index 0000000000000000000000000000000000000000..67ad3ee3eebf44511d4178617c7a9c6fd198d1dc --- /dev/null +++ b/pool/shard000/JavaScript/0002236_Agent.js @@ -0,0 +1,200 @@ + +var uid = require ('infosex').uid.craft; + +/** @module/class submergence:Agent + @root + Central controller for viewing or changing authentication status during an Action. An Agent that + is logged into the application will *always* have both a `user` and `client` id configured. The + minimum qualifications for an Agent may already be [configured] + (submergence:Action:Configuration#authentication) for the Action. +@member/String|undefined user + ID String of the current user, if any. +@member/String|undefined client + ID String of the current client, if any. +@member/Boolean isLoggedIn + Whether the user is currently logged in. An Action may occur with a `user` and `client` + without being an active session - this user presented a previously active session which + has not received any security flags. +@member/Boolean isDomestic + Whether the user copied their "domestication cookie" into the request to confirm the + request has same-origin priveleges for this domain. In a high-security app, this confirmation is + absolutely critical for any secure Action as it will prevent an XSS vulnerability in another + domain from affecting your users. The chief downside is that domestic requests cannot be + generated without using javascript. +@member/Number|undefined sessionCreated + Epoch time that the user's current session (if any) was initialized. This refers to a + [login](submergence+login) event, not an automatic session key change. +*/ +function Agent (parent, cookies, domain, user, client, isLoggedIn, isDomestic, rememberMe) { + this.parent = parent; + this.cookies = cookies; + this.domain = domain; + + if (arguments.length == 4) { + this.user = user.user; + this.client = user.client; + this.isLoggedIn = user.isLoggedIn; + this.isDomestic = user.isDomestic; + this.rememberMe = user.rememberMe; + } else { + this.user = user; + this.client = client; + this.isLoggedIn = Boolean (isLoggedIn); + this.isDomestic = Boolean (isDomestic); + this.rememberMe = Boolean (rememberMe); + } +} + + +/** @member/Function setActive + Set the user's login status to `active`. +@argument/String user + @optional + If the Agent is `idle` and has its User and Client already set, they do not need to be provided + again. +@argument/String client + @optional + If the Agent is `idle` and has its User and Client already set, they do not need to be provided + again. +@argument/Boolean rememberMe + A cookie management flag for browser clients. Whether the session credentials should be retained + beyond the end of the session. +@callback + @argument/Error|undefined err +*/ +Agent.prototype.setActive = function (/* user, client, rememberMe, callback */) { + var user, client, rememberMe, callback; + switch (arguments.length) { + case 1: + callback = arguments[0]; + break; + case 2: + rememberMe = arguments[0]; + callback = arguments[1]; + break; + case 3: + user = arguments[0]; + client = arguments[1]; + callback = arguments[2]; + break; + default: + user = arguments[0]; + client = arguments[1]; + rememberMe = arguments[2]; + callback = arguments[3]; + } + + if (user) + this.user = user; + if (client) + this.client = client; + + if (!this.client || !this.user) + return process.nextTick (function(){ + callback (new Error ('user and client ID required')) + }); + + this.parent.setActive (this.domain, this.user, this.client, rememberMe, this.cookies, callback); +}; + + +/** @member/Function setIdle + Set the user's login status to `idle`. If the user was a guest, they will receive credentials + for an expired session. If the user was `active` they will be downgraded to `idle`. +@argument/String user + @optional + If the Agent is `active` the User and Client do not need to be provided again. +@argument/String client + @optional + If the Agent is `active` the User and Client do not need to be provided again. +@argument/Boolean rememberMe + A cookie management flag for browser clients. Whether the session credentials should be retained + beyond the end of the session. +@callback + @argument/Error|undefined err +*/ +Agent.prototype.setIdle = function (/* user, client, rememberMe, callback */) { + var user, client, rememberMe, callback; + switch (arguments.length) { + case 1: + callback = arguments[0]; + break; + case 2: + rememberMe = arguments[0]; + callback = arguments[1]; + break; + case 3: + user = arguments[0]; + client = arguments[1]; + callback = arguments[2]; + break; + default: + user = arguments[0]; + client = arguments[1]; + rememberMe = arguments[2]; + callback = arguments[3]; + } + + if (user) + this.user = user; + if (client) + this.client = client; + + if (!this.client || !this.user) + return process.nextTick (function(){ + callback (new Error ('user and client ID required')) + }); + + this.parent.setIdle (this.domain, this.user, this.client, rememberMe, this.cookies, callback); +}; + + +/** @member/Function logout + Deactivate sessions belonging to a User or User/Client pair. Active `Socket.io` connections are + selected and terminated. +@argument/String client + @optional + Select only sessions and connections belonging to a specific User/Client pair. +@callback + @argument/Error|undefined err +*/ +Agent.prototype.logout = function (/* client, callback */) { + var client, callback; + if (arguments.length == 1) + callback = arguments[0]; + else { + client = arguments[0]; + callback = arguments[1]; + } + if (!this.client || !this.user) + return process.nextTick (callback); + + // local setup + this.isLoggedIn = false; + this.isDomestic = false; + var user = this.user; + delete this.user; + delete this.client; + + this.parent.logout (this.domain, user, client, this.cookies, callback); +}; + + +/** @member/Function export + Create a json-serializable expression of the Agent's login state. +@returns/json state +@member/String )state#user +@member/String )state#client +@member/Boolean )state#isLoggedIn +@member/Boolean )state#isDomestic +*/ +Agent.prototype.export = function(){ + return { + user: this.user, + client: this.client, + isLoggedIn: this.isLoggedIn, + isDomestic: this.isDomestic + }; +}; + +module.exports = Agent; diff --git a/pool/shard000/JavaScript/0002238_files.js b/pool/shard000/JavaScript/0002238_files.js new file mode 100644 index 0000000000000000000000000000000000000000..b0c788080926a0354d4ad3cd3284d5710a4d6018 --- /dev/null +++ b/pool/shard000/JavaScript/0002238_files.js @@ -0,0 +1,114 @@ +/** + * @ngdoc function + * @name fstepApp.controller:CommunityFilesCtrl + * @description + * # CommunityFilesCtrl + * Controller of the fstepApp + */ + +'use strict'; + +define(['../../../fstepmodules'], function (fstepmodules) { + + fstepmodules.controller('CommunityFilesCtrl', ['FileService', 'CommonService', '$scope', '$mdDialog', function (FileService, CommonService, $scope, $mdDialog) { + + /* Get stored Files details */ + $scope.fileParams = FileService.params.community; + $scope.fileOwnershipFilters = FileService.fileOwnershipFilters; + $scope.item = "File"; + $scope.filetypes = [ + { name: "Reference Data", value: "REFERENCE_DATA" }, + { name: "Output Products", value: "OUTPUT_PRODUCT" } + ]; + + /* Get files */ + FileService.refreshFstepFiles("community"); + + /* Update files when polling */ + $scope.$on('poll.fstepfiles', function (event, data) { + $scope.fileParams.files = data; + }); + + /* Stop Polling */ + $scope.$on("$destroy", function() { + FileService.stopPolling(); + }); + + /* Paging */ + $scope.getPage = function(url){ + FileService.getFstepFilesPage('community', url); + }; + + $scope.filter = function(){ + FileService.getFstepFilesByFilter('community'); + }; + + /* Select a File */ + $scope.selectFile = function (item) { + $scope.fileParams.selectedFile = item; + FileService.refreshSelectedFstepFile("community"); + }; + + /* Filters */ + $scope.toggleFilters = function () { + $scope.fileParams.displayFilters = !$scope.fileParams.displayFilters; + }; + + /* Add reference data */ + $scope.addReferenceFileDialog = function ($event) { + function AddReferenceFileDialog($scope, $mdDialog, FileService) { + + $scope.item = "File"; + $scope.fileParams = FileService.params.community; + $scope.newReference = {}; + $scope.validation = "Valid"; + + $scope.validateFile = function (file) { + if(!file) { + $scope.validation = "No file selected"; + } else if (file.name.indexOf(' ') >= 0) { + $scope.validation = "Filename cannot contain white space"; + } else if (file.size >= (1024*1024*1024*2)) { + $scope.validation = "Filesize cannot exceed 2GB"; + } else { + $scope.validation = "Valid"; + } + }; + + /* Upload the file */ + $scope.addReferenceFile = function () { + FileService.uploadFile("community", $scope.newReference).then(function (response) { + /* Get updated list of reference data */ + FileService.refreshFstepFiles("community"); + }); + }; + + $scope.closeDialog = function () { + $mdDialog.hide(); + }; + + } + AddReferenceFileDialog.$inject = ['$scope', '$mdDialog', 'FileService']; + $mdDialog.show({ + controller: AddReferenceFileDialog, + templateUrl: 'views/community/templates/addreferencedata.tmpl.html', + parent: angular.element(document.body), + targetEvent: $event, + clickOutsideToClose: true + }); + }; + + /* Remove File */ + $scope.removeItem = function (event, key, item) { + CommonService.confirm(event, 'Are you sure you want to delete this file?').then(function (confirmed) { + if (confirmed !== false) { + FileService.removeFstepFile(item).then(function (data) { + /* Update list of files */ + FileService.refreshFstepFiles("community", "Remove", item); + }); + } + }); + }; + + }]); +}); diff --git a/pool/shard000/JavaScript/0002239_entry.js b/pool/shard000/JavaScript/0002239_entry.js new file mode 100644 index 0000000000000000000000000000000000000000..f165152c757820d86615f4698dc04861aa9ad5c8 --- /dev/null +++ b/pool/shard000/JavaScript/0002239_entry.js @@ -0,0 +1,31 @@ +window.GLOB = {}; +window.GLOB.glob = {}; + + +window.trace = function (msg){ + console.log( "LOG: " + msg ); +} + +window.ss = require('socketstream'); + +ss.server.on('disconnect', function(){ + console.log('Connection down :-('); +}); + +ss.server.on('reconnect', function(){ + console.log('Connection back up :-)'); +}); + +ss.server.on('ready', function(){ + + jQuery(function(){ + + var glob = require("/globHammer/core/Glob")("Source"); + GLOB.awake( glob ); + }); + + + + + +}); diff --git a/pool/shard000/JavaScript/0002241_collapseToggle.directive.js b/pool/shard000/JavaScript/0002241_collapseToggle.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..44b44aa63efa7c52dfbe03bd5fd5ffd8f43799e4 --- /dev/null +++ b/pool/shard000/JavaScript/0002241_collapseToggle.directive.js @@ -0,0 +1,35 @@ +/*eslint-env node, mocha*/ +/*global inject*/ + +'use strict'; + +describe('Directive: collapseToggle', function () { + var $compile; + var scope; + var $; + + beforeEach(module('phoenixeye')); + beforeEach(module('phoenixeye')); + + beforeEach(inject(function ($injector) { + $compile = $injector.get('$compile'); + scope = $injector.get('$rootScope').$new(); + $ = $injector.get('$'); + })); + + it('should toggle "toggle" attr value in scope', function () { + var element = $compile('test')(scope); + + scope.$digest(); + $(element).find('i').click(); + scope.$digest(); + + scope.collapse.should.be.true; + + scope.$digest(); + $(element).find('i').click(); + scope.$digest(); + + scope.collapse.should.be.false; + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002243_app.js b/pool/shard000/JavaScript/0002243_app.js new file mode 100644 index 0000000000000000000000000000000000000000..0392160150c88ca270242645e58b9ca68d834a4b --- /dev/null +++ b/pool/shard000/JavaScript/0002243_app.js @@ -0,0 +1,66 @@ +import React from 'react'; +import {BrowserRouter} from 'react-router-dom'; +import Router from './config/router'; +import customFetch from './util/custom-fetch'; +import HtmlHead from './config/html-head'; +import I18nConfig from './config/i18n-config'; + +export let i18nComponentInstance; + +class App extends React.Component { + + state = { + i18nLoaded: false, + hostName: null, + googleTag: null + }; + + + componentDidMount = async () => { + let res = await customFetch(`/api/env`); + let config = await customFetch('/api/config'); + const googleTag = await customFetch('/api/config/googleTag'); + + localStorage.setItem('googleTag', googleTag); + this.setState({language: config.language, googleTag: googleTag}) + this.stockEnv(res); + + + //Change css var, depends on the domain name + const styleProperties = await customFetch('/api/config/style'); + styleProperties.map(cssVar => { + document.body.style.setProperty(cssVar.key, cssVar.value); + }); + }; + + stockEnv = (env) => { + localStorage.setItem('env', env); + this.setState({hostName: env}); + }; + + i18nLoaded = () => { + this.setState({i18nLoaded: true}) + }; + + + render() { + const {hostName, i18nLoaded, language, googleTag} = this.state; + return ( + i18nComponentInstance = ref}> + {i18nLoaded && googleTag ? + + + + + + + : null + } + + + ); + } + +} + +export default App; diff --git a/pool/shard000/JavaScript/0002244_controller.js b/pool/shard000/JavaScript/0002244_controller.js new file mode 100644 index 0000000000000000000000000000000000000000..0f86bee600e14daf1bf29a3a25c01f8ab82aacbd --- /dev/null +++ b/pool/shard000/JavaScript/0002244_controller.js @@ -0,0 +1,85 @@ +'use strict'; + +//RG 11 Oct 2018 - force the disable of the summernote helpDialog +// rendered but never displayed due to the custom summernote configs +$.summernote.options.modules.helpDialog = function(context) {}; + +var app = angular.module('wizardApp', ['summernote', 'googlechart', 'toastr']) + .value('googleChartApiConfig', { + version: '1', + optionalSettings: { + packages: ['gantt'] + }, + useGstaticLoader: true, + gstaticLoaderVersion: 'current' + }); + +//other directives +app.directive(convertToNumberDirective.name, convertToNumberDirective.directive); +app.directive(isolatedFormDirective.name, isolatedFormDirective.directive); + +//wizard directives +app.directive(rgWizardDirective.name, rgWizardDirective.directive); +app.directive(rgWizardStepDirective.name, rgWizardStepDirective.directive); + +//wizard components +// app.component(rgWizardComponent.name, rgWizardComponent.component); +// app.component(rgWizardStepComponent.name, rgWizardStepComponent.component); + +app.config(['$httpProvider', function ($httpProvider) { + $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest'; + $httpProvider.defaults.headers.common["Content-Type"] = 'application/json'; +}]); + +app.controller('wizardController', function ($scope, $http, $attrs, $timeout, $interval, $log, $q, toastr) { + $scope.model = {}; + $scope.options = summernoteConfigurator().defaults; + + $http.get('/load').then( + function (response) { + $scope.model = response.data; + }, + function () { + $log.error(arguments); + } + ); + + this.addHobby = function () { + $scope.model.hobbys.push({ name: '' }); + }; + + this.deleteHobby = function (index) { + $scope.model.hobbys.splice(index, 1); + }; + + this.save1 = function () { + return this.save('save 1', '/save'); + }; + + this.save2 = function () { + return this.save('save 2', '/fail'); + }; + + this.save = function (saveName, method) { + $log.info(saveName, method); + + var deferred = $q.defer(); + + $http.post(method, $scope.model).then( + function (response) { + $log.info(response); + toastr.info('Saving your changes', saveName); + + return deferred.resolve(true); + }, + function () { + $log.error(arguments); + toastr.error('There as a problem loading the submission form.', 'Error', { "timeOut": 0, "extendedTimeOut": 0 }); + + deferred.reject(arguments); + } + ); + + return deferred.promise; + }; +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002247_spaced-line-comment.js b/pool/shard000/JavaScript/0002247_spaced-line-comment.js new file mode 100644 index 0000000000000000000000000000000000000000..af5ba8cdb6a8cabe01d049765fb80f3f0ba52205 --- /dev/null +++ b/pool/shard000/JavaScript/0002247_spaced-line-comment.js @@ -0,0 +1,71 @@ +/** + * @fileoverview Enforces or disallows a space beginning a single-line comment. + * @author Greg Cochard + * @copyright 2014 Greg Cochard. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + // Unless the first option is never, require a space + var requireSpace = context.options[0] !== "never"; + + // Default to match anything, so all will fail if there are no exceptions + var exceptionMatcher = new RegExp(" "); + + // Grab the exceptions array and build a RegExp matcher for it + var hasExceptions = context.options.length === 2; + var unescapedExceptions = hasExceptions ? context.options[1].exceptions : []; + var exceptions; + + if (unescapedExceptions.length) { + exceptions = unescapedExceptions.map(function(s) { + return s.replace(/([.*+?${}()|\^\[\]\/\\])/g, "\\$1"); + }); + exceptionMatcher = new RegExp("(^(" + exceptions.join(")+$)|(^(") + ")+$)"); + } + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "LineComment": function checkCommentForSpace(node) { + + if (requireSpace) { + + // If length is zero, ignore it + if (node.value.length === 0) { + return; + } + + // Space expected and not found + if (node.value.indexOf(" ") !== 0 && node.value.indexOf("\t") !== 0) { + + /* + * Do two tests; one for space starting the line, + * and one for a comment comprised only of exceptions + */ + if (hasExceptions && !exceptionMatcher.test(node.value)) { + context.report(node, "Expected exception block, space or tab after // in comment."); + } else if (!hasExceptions) { + context.report(node, "Expected space or tab after // in comment."); + } + } + + } else { + + if (node.value.indexOf(" ") === 0 || node.value.indexOf("\t") === 0) { + context.report(node, "Unexpected space or tab after // in comment."); + } + } + } + + }; +}; diff --git a/pool/shard000/JavaScript/0002249_App.js b/pool/shard000/JavaScript/0002249_App.js new file mode 100644 index 0000000000000000000000000000000000000000..bde0c1e4245a3444b1c7370962e46a48b1347141 --- /dev/null +++ b/pool/shard000/JavaScript/0002249_App.js @@ -0,0 +1,79 @@ + + +/** Dynamic Loader **/ +// id, js, ui (htm) +// collection of apps... +// launch event/entry point +// + +Tritium.App = {}; + +Tritium.App.Registry = new (function() { + var _registry = {}; + + function load(def) { + // request both parts of app + // whichever one finishes last will call link() + + // get the ui + new Request({ + url: def.ui, + method: 'get', + async: true, + onSuccess: function(txt) { + def.tmpl = txt; + if(def.impl) link(def); + } + }).send(); + + // get the logic + new Request({ + url: def.js, + method: 'get', + async: true, + evalScripts: false, + evalResponse: false, + onSuccess: function(txt) { + def.impl = new Class(eval("x = "+txt+";x;")); + if(def.tmpl) link(def); + } + }).send(); + } + + function link(def) { + def.app = new Class({ + Extends: Tritium.UI.Window, + Implements: [Options,Events,def.impl], + options: { +// title: def.name, + def: def + }, + initialize: function(options) { + this.parent(options); + + if(this.renderUI) this.renderUI(); + else this.getContainer().set('html',def.tmpl); + + this.ui = this.getContainer().getUI(); + + if(this.start) this.start(); + else this.show(); + } + }); + + // deferred execution needed? + start(def.app); + } + + // wrapper... add options? + function start(app) { new app(); } + + this.register = function(def) { _registry[def.id] = def; }; + + this.instance = function(id) { + if(!_registry[id]) return false; + if(!_registry[id].app) load(_registry[id]); + else start(_registry[id].app); + return true; + }; +})(); diff --git a/pool/shard000/JavaScript/0002251_asap.js b/pool/shard000/JavaScript/0002251_asap.js new file mode 100644 index 0000000000000000000000000000000000000000..99c4d501e13de0a8fbaad2ffbffd40a5e7bd55ee --- /dev/null +++ b/pool/shard000/JavaScript/0002251_asap.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +/* ========================================= +* Copyright (c) 2015-present, Billgo. +* Copyright (c) 2015-present, Facebook, Inc. +* +* All rights reserved. +*======================================== */ + +var queue = []; +var capacity = 1024; +var hasSetImmediate = typeof setImmediate === "function"; +var flushing = false; +var index = 0; +var domain = false; + +function rawAsap(task) { + if (!queue.length) { + requestFlush(); + flushing = true; + } + queue[queue.length] = task; +} + +function flush() { + while (index < queue.length) { + var currentIndex = index; + index = index + 1; + queue[currentIndex].call(); + if (index > capacity) { + for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { + queue[scan] = queue[scan + index]; + } + queue.length -= index; + index = 0; + } + } + queue.length = 0; + index = 0; + flushing = false; +} + +rawAsap.requestFlush = requestFlush; +function requestFlush() { + var parentDomain = process.domain; + if (parentDomain) { + if (!domain) { + domain = require("domain"); //eslint-disable-line + } + domain.active = process.domain = null; + } + + if (flushing && hasSetImmediate) { + setImmediate(flush); + } else { + process.nextTick(flush); + } + + if (parentDomain) { + domain.active = process.domain = parentDomain; + } +} + +var freeTasks = []; + +function asap(task) { + var rawTask = void 0; + if (freeTasks.length) { + rawTask = freeTasks.pop(); + } else { + rawTask = new RawTask(); + } + rawTask.task = task; + rawTask.domain = process.domain; + rawAsap(rawTask); +} + +function RawTask() { + this.task = null; + this.domain = null; +} + +RawTask.prototype.call = function () { + if (this.domain) { + this.domain.enter(); + } + var threw = true; + try { + this.task.call(); + threw = false; + if (this.domain) { + this.domain.exit(); + } + } finally { + if (threw) { + rawAsap.requestFlush(); + } + this.task = null; + this.domain = null; + freeTasks.push(this); + } +}; + +exports.default = asap; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002253_notification-service.js b/pool/shard000/JavaScript/0002253_notification-service.js new file mode 100644 index 0000000000000000000000000000000000000000..26e60af3182e1fffb557f84d384986fad894f347 --- /dev/null +++ b/pool/shard000/JavaScript/0002253_notification-service.js @@ -0,0 +1,93 @@ +/* global moment */ +import Ember from 'ember'; +//http://www.programwitherik.com/ember-services-tutorial/ +export default Ember.Service.extend({ + socketService: Ember.inject.service('websockets'), + purecloud: Ember.inject.service(), + analyticsService: Ember.inject.service(), + + idList: [], + availableTopics: [], + websocketMessages: [], + socketRef: null, + channelId: null, + isPinned: false, + + init() { + this._super(...arguments); + + let self = this; + + var api = self.get('purecloud').notificationsApi(); + + api.postNotificationsChannels().then(function (channel) { + if (!(self.get('isDestroyed') || self.get('isDestroying'))) { + const socket = self.get('socketService').socketFor(channel.connectUri); + + socket.on('open', self.websocketOpenHandler, self); + socket.on('message', self.websocketMessageHandler, self); + + self.set('socketRef', socket); + self.set('channelId', channel.id); + } + }); + + api + .getNotificationsAvailabletopics({ + expand: ['transports,description,schema'], + }) + .then(function (topics) { + if (!(self.get('isDestroyed') || self.get('isDestroying'))) { + let updatedTopics = []; + if (topics.entities) { + updatedTopics = topics.entities.filter((t) => t.transports[0] !== 'EventBridge'); + } + self.set('availableTopics', updatedTopics); + } + }); + }, + subscribe(id) { + let versionlessId = id.replace('v2.', ''); + this.get('analyticsService').logNotificationRegistration(versionlessId.split('.')[0]); + + var that = this; + var api = this.get('purecloud').notificationsApi(); + api + .postNotificationsChannelSubscriptions(this.get('channelId'), [{ id: id }]) + .then(function () { + that.get('idList').pushObject(id); + }) + .catch(function (error) { + console.log(error); + }); + }, + unsubscribeAll() { + var that = this; + var api = this.get('purecloud').notificationsApi(); + api + .putNotificationsChannelSubscriptions(this.get('channelId'), []) + .then(function () { + that.get('idList').clear(); + }) + .catch(function (error) { + console.log(error); + }); + }, + + websocketOpenHandler(event) { + console.log('On open event has been called: ', event); + }, + + websocketMessageHandler(event) { + console.log(`Message: ${event.data}`); + var eventData = JSON.parse(event.data); + + eventData.bodyString = JSON.stringify(eventData.eventBody, null, ' '); + eventData.time = moment().format('h:mm:ss.SSS'); + + this.get('websocketMessages').pushObject(eventData); + }, + togglePin() { + this.toggleProperty('isPinned'); + }, +}); diff --git a/pool/shard000/JavaScript/0002263_adjust.js b/pool/shard000/JavaScript/0002263_adjust.js new file mode 100644 index 0000000000000000000000000000000000000000..1d9ba06aad31e1b9101b1bcf0b9f043f14c9021e --- /dev/null +++ b/pool/shard000/JavaScript/0002263_adjust.js @@ -0,0 +1,42 @@ +var _concat = /*#__PURE__*/require('./internal/_concat'); + +var _curry3 = /*#__PURE__*/require('./internal/_curry3'); + +/** + * Applies a function to the value at the given index of an array, returning a + * new copy of the array with the element at the given index replaced with the + * result of the function application. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig (a -> a) -> Number -> [a] -> [a] + * @param {Function} fn The function to apply. + * @param {Number} idx The index. + * @param {Array|Arguments} list An array-like object whose value + * at the supplied index will be replaced. + * @return {Array} A copy of the supplied array-like object with + * the element at index `idx` replaced with the value + * returned by applying `fn` to the existing element. + * @see R.update + * @example + * + * R.adjust(R.add(10), 1, [1, 2, 3]); //=> [1, 12, 3] + * R.adjust(R.add(10))(1)([1, 2, 3]); //=> [1, 12, 3] + * @symb R.adjust(f, -1, [a, b]) = [a, f(b)] + * @symb R.adjust(f, 0, [a, b]) = [f(a), b] + */ + + +var adjust = /*#__PURE__*/_curry3(function adjust(fn, idx, list) { + if (idx >= list.length || idx < -list.length) { + return list; + } + var start = idx < 0 ? list.length : 0; + var _idx = start + idx; + var _list = _concat(list); + _list[_idx] = fn(list[_idx]); + return _list; +}); +module.exports = adjust; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002266_tube.js b/pool/shard000/JavaScript/0002266_tube.js new file mode 100644 index 0000000000000000000000000000000000000000..10695e2bbfb5bb006b554baaad38146327fedf41 --- /dev/null +++ b/pool/shard000/JavaScript/0002266_tube.js @@ -0,0 +1,322 @@ + +/** Tube Constructor */ + +var Tube = function (options) { + var self = this; + + this.videos = []; + this.options = $.extend({}, Tube.defaults, options); + this.current = 0; + this.player = Player.create(this.player_options()); + + this.options.templates = $.extend({}, Video.templates, this.options.templates || {}); + + observable.apply(this); + + // Register Tube event handlers + $.each(Tube.events, function (idx, event) { + if (self.options.events[event]) { + self.on(event, self.options.events[event]); + } + }); + + // Register Player event proxies and handlers + $.each(Player.events, function (idx, event) { + + self.player.on(event, $.proxy(self.notify, self, event)); + + if (self.options.events[event]) { + self.on(event, self.options.events[event]); + } + }); + +}; + +Tube.constants = { + api: '//gdata.youtube.com/feeds/api/' +}; + +Tube.defaults = { + player: 'player', + autoload: false, // load the player automatically? + autoplay: false, + start: 0, + order: 'relevance', // 'published', 'rating', 'viewCount' + author: false, + hide: 2, // 0 = always visible, 1 = hide progress bar and controls, 2 = hide progress bar + controls: 1, + version: 2, + format: 5, + limit: 10, + key: false, + render: true, + truncate: false, + at: '\n', // pattern (truncate) + max: 140, // max length (truncate) + omission: '…', // omission string (truncate) + events: [], + load: false, // plugin callback when the playlist data has been loaded + complete: false, // plugin callback when the playlist html has been rendered + click: false // plugin callback +}; + +Tube.parameters = { + 'q': 'query', + 'max-results': 'limit', + 'key': 'key', + 'format': 'format', + 'orderby': 'order', + 'author': 'author', + 'v': 'version' +}; + +Tube.events = ['load', 'ready', 'stop', 'error']; + + +/** Static Tube Functions */ + +/* + * Encodes a set of parameters. Returns the encoded parameters as a string. + */ +Tube.serialize = function (parameters) { + var string; + + switch (typeof parameters) { + case 'string': + string = encodeURI(parameters); + break; + + case 'object': + if (parameters === null) { + string = ''; + } + else { + string = $.map(parameters, function (value, key) { + if (value) { + return [encodeURI(key), encodeURI(value)].join('='); + } + }).join('&'); + } + break; + + default: + string = ''; + break; + } + + return string; +}; + + + +/** Tube Instance Methods */ + +/* + * Populates the tube object with data from YouTube. If function is passed + * as an argument to this method, it will be called when the AJAX request(s) + * returns. The callback will be applied to the tube object and passed the + * number of videos that were fetched (i.e., a zero value indicates failure + * or no results). + * + * Returns the tube object (non-blocking). + */ +Tube.prototype.load = function (callback) { + var self = this, success = 0, proxy; + + if (this.options.list && this.options.list.length) { + + // Custom lists + + // Proxy to be called after each Video.load + proxy = function (status, error) { + if (status === 0) { + if (callback && $.isFunction(callback)) { + callback.apply(self, [success, error]); + } + self.notify('error'); + } + + // Call the fallback only when all videos have loaded + if (++success >= self.options.list.length) { + self.notify('load'); + + if (callback && $.isFunction(callback)) { + callback.apply(self, [success]); + } + + self.notify('ready'); + } + }; + + // Create video object for each element in the list and load it + this.videos = $.map(this.options.list, function (id) { + return (new Video()).load(id, proxy); + }); + } + else { + + // Regular YouTube queries + + $.getJSON(this.request(), function (data) { + try { + success = data.feed.entry.length; + + self.videos = $.map(data.feed.entry, function(item) { + return new Video().parse(item); + }); + + if (success && (self.options.autoload || self.options.start)) { + self.current = Math.min(self.videos.length - 1, Math.max(0, self.options.start - 1)); + self.player.load(self.videos[self.current]); + } + + self.notify('load'); + + if (callback && $.isFunction(callback)) { + callback.apply(self, [success]); + } + + self.notify('ready'); + } + catch (error) { + if (callback && $.isFunction(callback)) { + callback.apply(self, [0, error]); + } + + self.notify('error'); + } + }); + } + + return this; +}; + +/** Returns the tube's player options as a hash */ +Tube.prototype.player_options = function () { + return { + id: this.options.player, + playerVars: $.extend({}, Player.parameters, { + autoplay: this.options.autoplay, + autohide: this.options.hide, + controls: this.options.controls + }) + }; +}; + +/** Returns the tube's gdata parameters as a hash */ +Tube.prototype.parameters = function () { + var self = this, parameters = {}; + + $.each(Tube.parameters, function (key, value) { + if (self.options[value]) { + parameters[key] = self.options[value]; + } + }); + + // adapt playlist specific parameters + if (this.options.playlist) { + delete parameters.orderby; + } + else if (this.options.user) { + parameters.orderby = 'published'; + } + + parameters.alt = 'json-in-script'; + parameters.callback = '?'; + + return parameters; +}; + +/** Returns the tube's gdata request string */ +Tube.prototype.request = function (options) { + var api = Tube.constants.api; + + $.extend(this.options, options || {}); + + // distinguish between playlist selection and video query + if (this.options.playlist) { + api += 'playlists/' + this.options.playlist.replace(/^PL/, ''); + } + else if (this.options.user) { + api += ['users', this.options.user, 'uploads'].join('/'); + } + else { + api += 'videos'; + } + + return [api, '?', Tube.serialize(this.parameters())].join(''); +}; + +Tube.prototype.authenticate = function () { + return this; +}; + +/* + * Plays the video at the given index in the associated player. + * If no index is given, resumes the current video. + */ +Tube.prototype.play = function (index) { + if ($.isNumeric(index)) { + var k = index % this.videos.length; + this.current = (k < 0) ? this.videos.length - k : k; + + if (this.player && this.videos.length) { + this.player.play(this.videos[this.current]); + } + } + else { + this.player.resume(); + } + + return this; +}; + +/** Pauses playback of the current player */ +Tube.prototype.pause = function (index) { + if (this.player) { + this.player.pause(); + } + return this; +}; + +Tube.prototype.stop = function (index) { + if (this.player) { + this.player.stop(); + this.notify('stop'); + } + return this; +}; + +/** Plays the next video. */ +Tube.prototype.next = function () { + return this.advance(1).notify('next'); +}; + +/** Plays the previous video. */ +Tube.prototype.previous = function () { + return this.advance(-1).notify('previous'); +}; + +Tube.prototype.advance = function (by) { + return this.play(this.current + (by || 1)); +}; + +Tube.prototype.render_options = function (options) { + return $.extend({}, Video.defaults, this.options, options || {}); +}; + +/** Returns the video as an HTML string */ +Tube.prototype.render = function () { + var templates = this.options.templates, options = this.render_options(); + var elements = $.map(this.videos, function (video, index) { + options.index = index; + return '
  • ' + video.render(templates, options) + '
  • '; + }); + + return '
      ' + elements.join('') + '
    '; +}; + + +if (exports) { + exports.Tube = Tube; +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002268_files-handler.spec.js b/pool/shard000/JavaScript/0002268_files-handler.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..d9891686b326723bc58db47669d3a5b7aeae4c17 --- /dev/null +++ b/pool/shard000/JavaScript/0002268_files-handler.spec.js @@ -0,0 +1,31 @@ +var expect = require('chai').expect, + mockFs = require('mock-fs'), + proxyquire = require('proxyquire'), + sinon = require('sinon'), + sandbox = sinon.sandbox.create(), + filesHandler = require('../files-handler.js'), + fs = filesHandler.fs; + +describe("files-handler", function() { + describe("#readFiles", function() { + beforeEach(function() { + sandbox.stub(filesHandler, "file_dir", "files/"); + }); + + it("should return all files in files directory", function() { + mockFs({ + "files/" : { + "id_tracker" : "9023489345789345", + ".gitignore" : "", + "9" : "iowef", + "38" : "fweiofjo", + "757575" : "weoi" + } + }); + + let files = filesHandler.readFiles(); + + expect(files.length).to.equal(3); + }); + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002269_summaries.js b/pool/shard000/JavaScript/0002269_summaries.js new file mode 100644 index 0000000000000000000000000000000000000000..995af0d75945b4a9dc8b4b9180b6cd76f6a01775 --- /dev/null +++ b/pool/shard000/JavaScript/0002269_summaries.js @@ -0,0 +1,49 @@ +var expand = require("reducers/expand") +var delta = require("./state").delta + +summaries.type = Summary +summaries.isSummary = isSummary + +module.exports = summaries + +function Summary() {} + +function summaries(stream, initial) { + var previous = initial || {} + + return expand(stream, createSummary) + + function createSummary(current) { + var diff = current[delta] + + var list = Object.keys(diff) + .map(function (id) { + var value = diff[id] + var summary = new Summary() + var oldValue = previous[id] + + if (!oldValue) { + summary.type = "new" + } else if (value === null) { + summary.type = "deleted" + summary.oldValue = oldValue + } else { + summary.type = "updated" + summary.oldValue = oldValue + } + + summary.name = id + summary.value = value + + return summary + }) + + previous = current + + return list + } +} + +function isSummary(summary) { + return summary instanceof Summary +} diff --git a/pool/shard000/JavaScript/0002270_app.js b/pool/shard000/JavaScript/0002270_app.js new file mode 100644 index 0000000000000000000000000000000000000000..78218d770bca0e61ecabd676a6dfc18b4a1afcc2 --- /dev/null +++ b/pool/shard000/JavaScript/0002270_app.js @@ -0,0 +1,32 @@ +define([ + 'angular', + 'filters', + 'services', + 'directives', + 'controllers', + 'angularRoute', + ], function (angular, filters, services, directives, controllers) { + 'use strict'; + + // Declare app level module which depends on filters, and services + + var App = angular.module('app', [ + 'ngRoute', + 'app.controllers', + 'app.filters', + 'app.services', + 'app.directives' + ]); + + App.config(['$locationProvider', '$httpProvider', function($locationProvider, $httpProvider) { + $locationProvider.html5Mode(true); + $locationProvider.hashPrefix('!'); + + // Allow CORS + $httpProvider.defaults.useXDomain = true; + $httpProvider.defaults.withCredentials = true; + delete $httpProvider.defaults.headers.common['X-Requested-With']; + }]); + + return App; +}); diff --git a/pool/shard000/JavaScript/0002271_notAuthenticatedComponent.js b/pool/shard000/JavaScript/0002271_notAuthenticatedComponent.js new file mode 100644 index 0000000000000000000000000000000000000000..1f37471507b8bb1578d6a38c51ce5ebe6e25cae3 --- /dev/null +++ b/pool/shard000/JavaScript/0002271_notAuthenticatedComponent.js @@ -0,0 +1,94 @@ +import React from 'react'; +import { connect } from 'react-redux'; +import { bindActionCreators } from 'redux'; +import { browserHistory } from 'react-router'; +import * as actionCreators from '../actions/auth'; + +function mapStateToProps(state) { + return { + token: state.auth.token, + userName: state.auth.userName, + isAuthenticated: state.auth.isAuthenticated, + }; +} + +function mapDispatchToProps(dispatch) { + return bindActionCreators(actionCreators, dispatch); +} + + +export function requireNoAuthentication(Component) { + + class notAuthenticatedComponent extends React.Component { + + constructor(props) { + super(props); + this.state = { + loaded: false, + }; + } + + componentWillMount() { + this.checkAuth(); + } + + componentWillReceiveProps(nextProps) { + this.checkAuth(nextProps); + } + + checkAuth(props = this.props) { + if (props.isAuthenticated) { + browserHistory.push('/main'); + + } else { + const token = localStorage.getItem('token'); + if (token) { + fetch('/api/is_token_valid', { + method: 'post', + credentials: 'include', + headers: { + 'Accept': 'application/json', // eslint-disable-line quote-props + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ token }), + }) + .then(res => { + if (res.status === 200) { + this.props.loginUserSuccess(token); + browserHistory.push('/main'); + + } else { + this.setState({ + loaded: true, + }); + } + }); + } else { + this.setState({ + loaded: true, + }); + } + } + } + + render() { + return ( +
    + {!this.props.isAuthenticated && this.state.loaded + ? + : null + } +
    + ); + + } + } + + notAuthenticatedComponent.propTypes = { + loginUserSuccess: React.PropTypes.func, + isAuthenticated: React.PropTypes.bool, + }; + + return connect(mapStateToProps, mapDispatchToProps)(notAuthenticatedComponent); + +} diff --git a/pool/shard000/JavaScript/0002274_Parser.js b/pool/shard000/JavaScript/0002274_Parser.js new file mode 100644 index 0000000000000000000000000000000000000000..2693be1bd6f72c4048ee9fca6b11dba6b91bec17 --- /dev/null +++ b/pool/shard000/JavaScript/0002274_Parser.js @@ -0,0 +1,19 @@ +function Parser(input){ + var sResponse; + var lResponse; + sResponse = response.body().string(); + sResponse = sResponse.trim(); + sResponse = sResponse.replaceAll("^[{ \"content\":]+",""); + sResponse = sResponse.substring(1,sResponse.length()); + lResponse = sResponse.split("\"measures\""); + var result = []; + for (var i = 0; i < lResponse; i++) { + var temp = res.replaceAll("^[:{},]+", "").replaceAll("[,}]+$",""); + var location = temp.split(",")[0].replaceAll("^[\"locationUid\":\"LOCATION-]+", "").replaceAll("\"+$", ""); + result.push(location); + } + result.remove(result.size()- 1); + return result; + +} + diff --git a/pool/shard000/JavaScript/0002275_spies.js b/pool/shard000/JavaScript/0002275_spies.js new file mode 100644 index 0000000000000000000000000000000000000000..d8f0af4e068e9a797ea3abbc69c9a1e15de05019 --- /dev/null +++ b/pool/shard000/JavaScript/0002275_spies.js @@ -0,0 +1,68 @@ +/* global describe, it, expect, beforeEach, jasmine, toBeCustom, sinon, callXTimes, assert */ + +describe("Spies spy on function calls so we can assert that they were called as intended", function () { + "use strict"; + + it("sinon.spy() create an anonymous function which records calls upon it", function () { + + var callback = sinon.spy(); + var nonCallback = sinon.spy(); + + callback(); + + // We can use Spy API to assert it was called + expect(callback.called).toBe(true); + expect(nonCallback.called).toBe(false); + + // Or we can use sinon assertions + sinon.assert.called(callback); + sinon.assert.callCount(callback, 1); + + callback(); + sinon.assert.callCount(callback, 2); + }); + + it("sinon.spy() can be used to spy on an existing function. They wrap the function, allowing the functionality to be called, yet assertions to be made upon the spy", function () { + + var foo = function () { + return true; + }; + + var spy = sinon.spy(foo); + + expect(spy(2)).toBeTruthy(); + expect(spy.called).toBe(true); + }); + + it("sinon.spy() can be used to spy on an existing methods upon objects. Here we preserve the original method but wrap a spy around it", function () { + + var myClass = { + /** + * @return {number} + */ + Foo: function (value) { + return value * 10; + } + }; + + var aSpy = sinon.spy(myClass, "Foo"); + + expect(myClass.Foo(1)).toBe(10); + expect(myClass.Foo(2)).toBe(20); + expect(myClass.Foo(3)).toBe(30); + + // The spy has wrapped the function + sinon.assert.called(myClass.Foo); + + // The same spy was returned + sinon.assert.called(aSpy); + + // We can place an assertions upon the spy + sinon.assert.callCount(myClass.Foo, 3); + expect(myClass.Foo.getCall(0).args[0]).toBe(1); + + // If we need to restore the original function we can call restore upon the spy + myClass.Foo.restore(); + }); +}); + \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002276_task_routes.js b/pool/shard000/JavaScript/0002276_task_routes.js new file mode 100644 index 0000000000000000000000000000000000000000..6c4d67c004c29480b602d44277e5fdb626fa2eb9 --- /dev/null +++ b/pool/shard000/JavaScript/0002276_task_routes.js @@ -0,0 +1,80 @@ +module.exports = function(app){ + + + var TaskController = require(app.get("controllers")+"/TaskController.js"); + + + app.get('/',function(req,res){ + + res.sendFile("index.html"); + + }); + + app.get("/memos",function(req,res){ + + try{ + TaskController.findAll(function(result){ + res.json(result); + }); + }catch(exception){ + res.send(404); + } + }); + + app.get("/memos/:id",function(req,res){ + var id = req.params.id; + try{ + var task = TaskController.find(id,function(result){ + res.json(result); + }); + + }catch(exception){ + res.send(404); + } + }); + + app.delete("/memos/:id",function(req,res,next){ + var id = req.params.id; + try{ + TaskController.remove(id,function(result){ + res.send(200); + }); + }catch(exception){ + res.send(404); + } + }); + + app.post("/memos",function(req,res,next){ + + var task = req.body; + var files = req.files; + + try { + TaskController.save({ + title : task.title || "Default Title", + file : files.image.name, + desc : task.desc + },function(result){ + res.send(200); + }); + }catch(exception){ + res.send(404); + } + + }); + + app.put("/memos/:id",function(req,res){ + var id = req.params.id; + var task = req.body; + task.file = req.files.image.name; + try{ + TaskController.update(id,task,function(result){ + res.send(200); + }); + }catch(exception){ + res.send(404); + } + }); + +} + diff --git a/pool/shard000/JavaScript/0002277_glyphs-plugin.js b/pool/shard000/JavaScript/0002277_glyphs-plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..d92355c01a6689087c41e38bb05bc06597a12d40 --- /dev/null +++ b/pool/shard000/JavaScript/0002277_glyphs-plugin.js @@ -0,0 +1,41 @@ +//remarkable plugin for captions in wordpress +//@@asterisk +// +function glyphs_plugin(remarkable) { + + this.parse = function(state, silent) { + var max = state.posMax, + pos = state.pos; + + if (max - pos < 5) return false; + + if (state.src.charCodeAt(pos) !== 0x40/* @ */ + || state.src.charCodeAt(pos + 1) !== 0x40/* @ */) return false; + pos += 2; + + while (pos < max && (isAlphaNum(state.src.charCodeAt(pos)) + || state.src.charCodeAt(pos) === 0x2D/* - */)) { + pos++; + } + + if (pos - state.pos < 5) return false; + + if (!silent) { + var glyph = state.src.slice(state.pos + 2, pos); + state.push({ + type: 'glyph', + level: state.level, + icon: glyph + }); + } + state.pos = pos; + return true; + }; + + this.glyph = function(tokens, id, options, env) { + return ''; + }; + + remarkable.inline.ruler.push('glyph', this.parse.bind(this)); + remarkable.renderer.rules['glyph'] = this.glyph.bind(this); +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002280_test-iterator.js b/pool/shard000/JavaScript/0002280_test-iterator.js new file mode 100644 index 0000000000000000000000000000000000000000..4a594aea3a41548b7b93e37c6ab4cdf9a33ba90f --- /dev/null +++ b/pool/shard000/JavaScript/0002280_test-iterator.js @@ -0,0 +1,91 @@ +/*globals suite, test, setup, teardown */ + +var should = require("should"), + SysUtil = require("util"), + uglylib = require("uglify-js"), + jsp = uglylib.parser, + Iterator = require("../lib/iterator") +; + +suite("Iterator", function () { + var code = [ + "(function (exports) {", + "// My function...", + "var a = 1,b = 2,c = 3;", + "exports.fn = function () {", + "return a + b + c;", + "};", + "}(module.exports));" + ].join("\n"), + ast = jsp.parse(code, true, false), + iter + ; + + // console.log(SysUtil.inspect(ast, false, 100)); + + setup(function () { + iter = new Iterator(ast); + }); + + test("#next, #skipTo", function () { + iter.getCurrent().name.should.equal("toplevel"); + iter.next().next().next(); + iter.getCurrent().name.should.equal("call"); + iter.skipTo("assign"); + should.exist(iter.getCurrent()); + iter.getCurrent()[1].should.equal(true); + }); + + test("#skipTo, #rewindTo", function () { + iter.skipTo("stat").skipTo("stat"); + iter.getCurrent().name.should.equal("stat"); + iter.rewindTo("var"); + iter.getCurrent().name.should.equal("var"); + }); + + test("Iterator.contains", function () { + var parent, child; + + iter.skipTo("var"); + parent = iter.getCurrent(); + + iter.skipTo("b"); + child = iter.getCurrent(); + + Iterator.contains(parent, child).should.equal(true); + + iter.skipTo("assign"); + child = iter.getCurrent(); + + Iterator.contains(parent, child).should.equal(false); + }); + + test("#getParent", function () { + iter.skipTo("b"); + iter.getCurrent().name.should.equal("b"); + + iter.getParent(iter.getCurrent()).name.should.equal("var"); + }); + + test("#findAllNamesOf", function () { + var named = iter.findAllNamesOf("b"); + named[0][0].should.eql("name"); + named[0][1].should.eql("b"); + + named = iter.findAllNamesOf("exports"); + named[0][0].should.eql("name"); + named[0][1].should.eql("exports"); + }); + + test("#find exports.fn value", function () { + var exportsFn = iter.find(function (node) { + return node[0] === "dot" && + node[1][0] === "name" && + node[1][1] === "exports"&& + node[2] === "fn"; + }); + + exportsFn = iter.getParent(exportsFn)[3]; + exportsFn[0].should.eql("function"); + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002282_restaurants.client.controller.js b/pool/shard000/JavaScript/0002282_restaurants.client.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..2266b5050cbd384dbc7a74491263f895f7f1ae65 --- /dev/null +++ b/pool/shard000/JavaScript/0002282_restaurants.client.controller.js @@ -0,0 +1,119 @@ +'use strict'; + +// Restaurants controller +angular.module('restaurants').controller('RestaurantsController', + ['$scope', '$stateParams', '$location', 'Authentication', 'Restaurants', 'RMenus', + function($scope, $stateParams, $location, Authentication, Restaurants, RMenus ) { + $scope.authentication = Authentication; + + $scope.currentPage = $stateParams.pageNum; + + // Create new Restaurant + $scope.create = function() { + // Create new Restaurant object + console.log('creating restaurant..'); + var restaurant = new Restaurants ({ + name: this.name + }); + + console.log(restaurant); + // Redirect after save + restaurant.$save(function(response) { + $location.path('restaurants/' + response._id); + + // Clear form fields + $scope.name = ''; + }, function(errorResponse) { + $scope.error = errorResponse.data.message; + }); + }; + + // Remove existing Restaurant + $scope.remove = function( restaurant ) { + if ( restaurant ) { restaurant.$remove(); + + for (var i in $scope.restaurants ) { + if ($scope.restaurants [i] === restaurant ) { + $scope.restaurants.splice(i, 1); + } + } + } else { + $scope.restaurant.$remove(function() { + $location.path('restaurants'); + }); + } + }; + + // Update existing Restaurant + $scope.update = function() { + var restaurant = $scope.restaurant ; + + restaurant.$update(function() { + $location.path('restaurants/' + restaurant._id); + }, function(errorResponse) { + $scope.error = errorResponse.data.message; + }); + }; + + // Find a list of Restaurants + $scope.find = function() { + $scope.restaurants = Restaurants.query(); + }; + + // Find existing Restaurant + $scope.findOne = function() { + $scope.restaurant = Restaurants.get({ + restaurantId: $stateParams.restaurantId + }); + }; + + + $scope.createMenu = function() { + var menu = new RMenus({ + name: $scope.newMenuName + }); + + menu.$save({restaurantId: $stateParams.restaurantId}, function(menu) { + $scope.newMenuName = ''; + $scope.newSection = false; + + $scope.restaurant.menus.push(menu); + + }, function(errorResponse) { + $scope.error = errorResponse.data.message; + alert($scope.error); + }); + }; + + $scope.removeMenu = function(menu){ + + var m = new RMenus(menu); + + if ( menu ) { + m.$remove({ + restaurantId: $stateParams.restaurantId, + menuId: m._id + }, function(data){ + console.log('before data'); + console.log(data); + + for (var i in $scope.restaurant.menus ) { + if ($scope.restaurant.menus [i] === menu ) { + $scope.restaurant.menus.splice(i, 1); + } + } + }); + } + }; + + $scope.setAsActive = function(m){ + var res = RMenus.setactive({ + restaurantId: $stateParams.restaurantId, + menuId: m._id}); + + res.$promise.then(function(data) { + $scope.findOne(); // a changer !!! disappearanceMilliseconds) { + raddec.events = [ 4 ]; + handleEventCallbacks(raddec); + delete transmitters[transmitterSignature]; // TODO: delete only raddec? + } + else { + let purgeTime = raddec.timestamp + disappearanceMilliseconds; + if(purgeTime < nextPurgeTime) { + nextPurgeTime = purgeTime; + } + } + } + let timeoutMilliseconds = Math.max(nextPurgeTime - currentTime, 10); + purgeTimeout = setTimeout(purgeDisappearances, timeoutMilliseconds); + } + + // Listen on the given WebSocket + let listen = function(socket, printStatus) { + printStatus = printStatus || false; + + socket.on('raddec', handleRaddec); + + if(printStatus) { + socket.on('connect', function() { + console.log('beaver connected to socket'); + }); + socket.on('disconnect', function(message) { + console.log('beaver disconnected from socket:', message); + }); + } + + if(!purgeTimeout) { + purgeDisappearances(); + } + }; + + // Register a callback for the given event type(s) + let setEventCallback = function(events, callback) { + if(!(callback && (typeof callback === 'function'))) { + return; + } + if(!Array.isArray(events)) { + events = ALL_EVENTS_INDEX_LIST; + } + events.forEach(function(event) { + if(ALL_EVENTS_INDEX_LIST.includes(event)) { + eventCallbacks[event].push(callback); + } + }); + } + + // Expose the following functions and variables + return { + listen: listen, + on: setEventCallback, + transmitters: transmitters + } + +}()); diff --git a/pool/shard000/JavaScript/0002289_cuboid.js b/pool/shard000/JavaScript/0002289_cuboid.js new file mode 100644 index 0000000000000000000000000000000000000000..2f28a4952395757b2c7522996a0fe6bb1210a803 --- /dev/null +++ b/pool/shard000/JavaScript/0002289_cuboid.js @@ -0,0 +1,80 @@ +void function($) { + + $.fn.ES_Cuboid = function( width, height, depth ) { + return this.each( function() { + + width = (width || $(this).width()); + height = (height || $(this).height()); + + depth || (depth = width); + + var halfWidth = width / 2; + var halfHeight = height / 2; + var halfDepth = depth / 2; + var setback = 0; + + var $cube = $('.es-cuboid', this); + if (!$cube.length) { + $cube = $( '
    ' ) + .appendTo( this ) + .append( '
    ' ) + .append( '
    ' ) + .append( '
    ' ) + .append( '
    ' ) + .append( '
    ' ) + .append( '
    ' ) + } + var $front = $cube.children('.es-cuboid-front'); + var $back = $cube.children('.es-cuboid-back'); + var $left = $cube.children('.es-cuboid-left'); + var $right = $cube.children('.es-cuboid-right'); + var $top = $cube.children('.es-cuboid-top'); + var $bottom = $cube.children('.es-cuboid-bottom'); + + $cube.css( { + width: width + 'px', + height: height + 'px' + } ); + + $( this ).css( { + transform: 'translateZ(' + (-halfDepth) + 'px)' + } ) + + $front.css( { + transform: 'translateZ(' + setback + 'px) translateZ(' + (halfDepth) + 'px)', + width: width + 'px', + height: height + 'px' + } ); + $back.css( { + transform: 'translateZ(' + setback + 'px) rotateY(180deg) translateZ(' + (halfDepth) + 'px)', + width: width + 'px', + height: height + 'px' + } ); + $left.css( { + transform: 'translateZ(' + setback + 'px) rotateY(-90deg) translateZ(' + (halfWidth) + 'px)', + marginLeft: -halfDepth + 'px', + width: depth + 'px', + height: height + 'px' + } ); + $right.css( { + transform: 'translateZ(' + setback + 'px) rotateY(90deg) translateZ(' + (halfWidth) + 'px)', + marginLeft: -halfDepth + 'px', + width: depth + 'px', + height: height + 'px' + } ); + $top.css( { + transform: 'translateZ(' + setback + 'px) rotateX(90deg) translateZ(' + halfHeight + 'px)', + marginTop: -halfDepth + 'px', + width: width + 'px', + height: depth + 'px' + } ); + $bottom.css( { + transform: 'translateZ(' + setback + 'px) rotateX(-90deg) translateZ(' + halfHeight + 'px)', + marginTop: -halfDepth + 'px', + width: width + 'px', + height: depth + 'px' + } ); + } ); + }; + +}( jQuery ) \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002290_index.js b/pool/shard000/JavaScript/0002290_index.js new file mode 100644 index 0000000000000000000000000000000000000000..13fbfdb8ff5741b36cd0009d93fb1d97b8d11510 --- /dev/null +++ b/pool/shard000/JavaScript/0002290_index.js @@ -0,0 +1,94 @@ +'use strict'; + +var Service, Characteristic; + +module.exports = function (homebridge) { + Service = homebridge.hap.Service; + Characteristic = homebridge.hap.Characteristic; + + homebridge.registerAccessory('homebridge-commandgaragedoor', 'CommandGarageDoor', CommandGarageDoorAccessory); +}; + +class CommandGarageDoorAccessory { + constructor (log, config) { + this.log = log; + + this.command = config['command']; + this.lastOpened = new Date(); + + this.simulateTimeOpening = config['simulateTimeOpening']; + this.simulateTimeOpen = config['simulateTimeOpen']; + this.simulateTimeClosing = config['simulateTimeClosing']; + + var manufacturer = typeof config['manufacturer'] !== typeof undefined ? config['manufacturer'] : "default"; + var model = typeof config['model'] !== typeof undefined ? config['model'] : "default"; + var serialNumber = typeof config['serialnumber'] !== typeof undefined ? config['serialnumber'] : "default"; + + this.service = new Service.GarageDoorOpener(config['name'], config['name']); + this.setupOpenerService(this.service); + + this.informationService = new Service.AccessoryInformation(); + this.informationService + .setCharacteristic(Characteristic.Manufacturer, manufacturer) + .setCharacteristic(Characteristic.Model, model) + .setCharacteristic(Characteristic.SerialNumber, serialNumber); + } + + getServices () { + return [this.informationService, this.service]; + } + + setupOpenerService (service) { + this.service.setCharacteristic(Characteristic.TargetDoorState, Characteristic.TargetDoorState.CLOSED); + this.service.setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.CLOSED); + + var that = this; + service.getCharacteristic(Characteristic.TargetDoorState) + .on('get', + (callback) => { + var tds = service.getCharacteristic(Characteristic.TargetDoorState).value; + callback(null, tds); + }) + .on('set', + (value, callback) => { + if (value === Characteristic.TargetDoorState.OPEN) { + this.lastOpened = new Date(); + switch (service.getCharacteristic(Characteristic.CurrentDoorState).value) { + case Characteristic.CurrentDoorState.CLOSED: + case Characteristic.CurrentDoorState.CLOSING: + case Characteristic.CurrentDoorState.OPEN: + this.openDoor(callback); + break; + default: + callback(); + } + } else { + callback(); + } + }); + } + + openDoor (callback) { + this.simulateDoorOpening(); + var exec = require('child_process').exec; + var cmd = this.command; + exec(cmd, function(error, stdout, stderr) { + this.log(stdout); + }.bind(this)); + } + + simulateDoorOpening () { + this.service.setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.OPENING); + setTimeout(() => { + this.service.setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.OPEN); + setTimeout(() => { + this.log("closing"); + this.service.setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.CLOSING); + this.service.setCharacteristic(Characteristic.TargetDoorState, Characteristic.TargetDoorState.CLOSED); + setTimeout(() => { + this.service.setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.CLOSED); + }, this.simulateTimeClosing * 1000); + }, this.simulateTimeOpen * 1000); + }, this.simulateTimeOpening * 1000); + } +} diff --git a/pool/shard000/JavaScript/0002294_deletion.spec.js b/pool/shard000/JavaScript/0002294_deletion.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..9ddba85c2ca5023e91b5c5f710b9d4b689d50059 --- /dev/null +++ b/pool/shard000/JavaScript/0002294_deletion.spec.js @@ -0,0 +1,33 @@ +'use strict'; + +var chai = require('chai'); +var chaiAsPromised = require('chai-as-promised'); +var helpers = require('../helpers'); +var fixtures = require('../fixtures'); +var MyAccountPage = require('./pages/MyAccount.page'); +var LoginPage = require('./pages/Login.page'); +var ProjectsPage = require('../projects/pages/Projects.page'); + +chai.use(chaiAsPromised); +var expect = chai.expect; + +describe('User deletion', function() { + var myAccountPage = new MyAccountPage(), + loginPage = new LoginPage(), + projectsPage = new ProjectsPage(); + + beforeEach(function () { + loginPage.go(); + loginPage.login( + fixtures.deletableUser.email, + fixtures.deletableUser.code + ); + myAccountPage.go(); + }); + + it('Successful', function () { + browser.waitForAngular(); + myAccountPage.deleteAccount(); + expect(helpers.getUrlPath(browser.getCurrentUrl())).to.eventually.equal(projectsPage.url); + }); +}); diff --git a/pool/shard000/JavaScript/0002295_sticky-nav.js b/pool/shard000/JavaScript/0002295_sticky-nav.js new file mode 100644 index 0000000000000000000000000000000000000000..d0a7cedc35abb3f129efca8ad344b7aa7075899b --- /dev/null +++ b/pool/shard000/JavaScript/0002295_sticky-nav.js @@ -0,0 +1,19 @@ +function stickyNav() { + const header = document.querySelector('.site-header'); + const navbar = document.querySelector('.nav-container'); + const headerHeight = getComputedStyle(header).height.split('px')[0]; + const scrollValue = window.scrollY; + + if (scrollValue > headerHeight) { + navbar.classList.add('is-fixed'); + } else if (scrollValue < headerHeight) { + navbar.classList.remove('is-fixed'); + } + + if (window.pageYOffset > headerHeight) { + navbar.classList.add('is-fixed'); + } +} + +window.addEventListener('scroll', stickyNav); +window.addEventListener('DOMContentLoaded', stickyNav); diff --git a/pool/shard000/JavaScript/0002305_webpack.base.conf.js b/pool/shard000/JavaScript/0002305_webpack.base.conf.js new file mode 100644 index 0000000000000000000000000000000000000000..70beec2d22d9d3c6a424d975459ddb9c09e64603 --- /dev/null +++ b/pool/shard000/JavaScript/0002305_webpack.base.conf.js @@ -0,0 +1,79 @@ +var path = require('path') +var utils = require('./utils') +var config = require('../config') +var vueLoaderConfig = require('./vue-loader.conf') + +console.log(resolve('src')); + +function resolve (dir) { + return path.join(__dirname, '..', dir) +} + +module.exports = { + entry: { + app: './src/main.ts' + }, + output: { + path: config.build.assetsRoot, + filename: '[name].js', + publicPath: process.env.NODE_ENV === 'production' + ? config.build.assetsPublicPath + : config.dev.assetsPublicPath + }, + resolve: { + extensions: ['.ts', '.js', '.vue', '.json'], + modules: [ + resolve('src'), + resolve('node_modules') + ], + alias: { + 'vue$': 'vue/dist/vue.common.js', + 'src': resolve('src'), + 'assets': resolve('src/assets'), + 'components': resolve('src/components') + } + }, + module: { + rules: [ + { + test: /\.(js|vue)$/, + loader: 'eslint-loader', + enforce: "pre", + include: [resolve('src'), resolve('test')], + options: { + formatter: require('eslint-friendly-formatter') + } + }, + { + test: /\.vue$/, + loader: 'vue-loader', + options: vueLoaderConfig + }, + { + test: /\.ts$/, + loader: 'vue-ts-loader', + }, + { + test: /\.js$/, + loader: 'babel-loader', + include: [resolve('src'), resolve('test')] + }, + { + test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, + loader: 'url-loader', + query: { + limit: 10000, + name: utils.assetsPath('img/[name].[hash:7].[ext]') + } + }, + { + test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, + loader: 'url-loader', + query: { + limit: 10000, + name: utils.assetsPath('fonts/[name].[hash:7].[ext]') + } + } + ] + } +} diff --git a/pool/shard000/JavaScript/0002308_authentication.client.controller.js b/pool/shard000/JavaScript/0002308_authentication.client.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..f9eed4b5e48f89226085ddcdb020144efe34306b --- /dev/null +++ b/pool/shard000/JavaScript/0002308_authentication.client.controller.js @@ -0,0 +1,34 @@ +'use strict'; + +angular.module('mentors').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication', + function($scope, $http, $location, Authentication) { + $scope.authentication = Authentication; + + // If user is signed in then redirect back home + if ($scope.authentication.user) $location.path('/'); + + $scope.signup = function(role) { + $scope.credentials.role = role; + $http.post('/auth/signup', $scope.credentials).success(function(response) { + // If successful we assign the response to the global user model + $scope.authentication.user = response; + // And redirect to the index page + $location.path('/'); + }).error(function(response) { + $scope.error = response.message; + }); + }; + + $scope.signin = function() { + $http.post('/auth/signin', $scope.credentials).success(function(response) { + // If successful we assign the response to the global user model + $scope.authentication.user = response; + + // And redirect to the index page + $location.path('/'); + }).error(function(response) { + $scope.error = response.message; + }); + }; + } +]); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002309_notification-list.js b/pool/shard000/JavaScript/0002309_notification-list.js new file mode 100644 index 0000000000000000000000000000000000000000..db365be43098480d09a69e059303ba04921fdd61 --- /dev/null +++ b/pool/shard000/JavaScript/0002309_notification-list.js @@ -0,0 +1,19 @@ +export default class NotificationListController { + constructor(PortalService) { + this.notificationList = []; + + this.PortalService = PortalService; + + this.notificationClasses = ["message", "twitter", "envelope", "tasks", "upload"]; + } + + init() { + this.PortalService.getNotificationList().subscribe(notification => this.notificationList.push(notification)); + } + + alertClass(type) { + return "fa-" + type; + } +} + +NotificationListController.$inject = ["PortalService"]; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002310_palmProfile.js b/pool/shard000/JavaScript/0002310_palmProfile.js new file mode 100644 index 0000000000000000000000000000000000000000..3b6bd6e4d9a2da956f582d180218b51413421c53 --- /dev/null +++ b/pool/shard000/JavaScript/0002310_palmProfile.js @@ -0,0 +1,44 @@ +/*global enyo, preware */ + +//some IPKGService calls only working for Mojo.Environment.DeviceInfo.platformVersionMajor > 1. +//this is for two reasons: +//1. I don't know how to test for webOS 2.x without Mojo... +//2. It won't make any sense to use enyo2 preware on older devices.. +//see original preware => app => model => palmProfile.js for differences in the IPKGCalls for platformVersionMajor = 1. + + +enyo.singleton({ + name: "preware.PalmProfile", + palmProfile: false, + callback: false, + getPalmProfile: function(callback, reload) { + this.callback = callback; + + if (this.palmProfile && !reload) { //just send what we already have + this.doPalmProfileReady({success: true, palmProfile: this.palmProfile, message: ""}); + } else { //need to load palm profile.. + + //some cleanup + this.palmProfile = false; + preware.IPKGService.impersonate(this._gotPalmProfile.bind(this), + "com.palm.configurator", + "com.palm.db", + "get", {"ids":["com.palm.palmprofile.token"]}); + + } + }, + _gotPalmProfile: function(payload) { + if (payload.returnValue === true) { + this.palmProfile = payload.results[0]; + } + + this.doPalmProfileReady({success: payload.returnValue, palmProfile: this.palmProfile, message: ""}); + }, + doPalmProfileReady: function(payload) { + if (this.callback) { + this.callback(null, payload); + } + } +}); + + diff --git a/pool/shard000/JavaScript/0002313_express.js b/pool/shard000/JavaScript/0002313_express.js new file mode 100644 index 0000000000000000000000000000000000000000..1f24c55dac2e75ea38813ced28b46e2fcbb8e1f3 --- /dev/null +++ b/pool/shard000/JavaScript/0002313_express.js @@ -0,0 +1,107 @@ +const rp = require('request-promise'); +const _ = require('lodash'); + +module.exports = class extends think.Service { + async queryExpress(shipperCode, logisticCode, orderCode = '') { + let expressInfo = { + success: false, + shipperCode: shipperCode, + shipperName: '', + logisticCode: logisticCode, + isFinish: 0, + traces: [] + }; + const fromData = this.generateFromData(shipperCode, logisticCode, orderCode); + if (think.isEmpty(fromData)) { + return expressInfo; + } + + const sendOptions = { + method: 'POST', + url: think.config('express.request_url'), + headers: { + 'content-type': 'application/x-www-form-urlencoded' + }, + form: fromData + }; + + try { + const requestResult = await rp(sendOptions); + if (think.isEmpty(requestResult)) { + return expressInfo; + } + expressInfo = this.parseExpressResult(requestResult); + expressInfo.shipperCode = shipperCode; + expressInfo.logisticCode = logisticCode; + return expressInfo; + } catch (err) { + return expressInfo; + } + } + + parseExpressResult(requestResult) { + const expressInfo = { + success: false, + shipperCode: '', + shipperName: '', + logisticCode: '', + isFinish: 0, + traces: [] + }; + + if (think.isEmpty(requestResult)) { + return expressInfo; + } + + try { + if (_.isString(requestResult)) { + requestResult = JSON.parse(requestResult); + } + } catch (err) { + return expressInfo; + } + + if (think.isEmpty(requestResult.Success)) { + return expressInfo; + } + + // 判断是否已签收 + if (Number.parseInt(requestResult.State) === 3) { + expressInfo.isFinish = 1; + } + expressInfo.success = true; + if (!think.isEmpty(requestResult.Traces) && Array.isArray(requestResult.Traces)) { + expressInfo.traces = _.map(requestResult.Traces, item => { + return { datetime: item.AcceptTime, content: item.AcceptStation }; + }); + _.reverse(expressInfo.traces); + } + return expressInfo; + } + + generateFromData(shipperCode, logisticCode, orderCode) { + const requestData = this.generateRequestData(shipperCode, logisticCode, orderCode); + const fromData = { + RequestData: encodeURI(requestData), + EBusinessID: think.config('express.appid'), + RequestType: '1002', + DataSign: this.generateDataSign(requestData), + DataType: '2' + }; + return fromData; + } + + generateRequestData(shipperCode, logisticCode, orderCode = '') { + // 参数验证 + const requestData = { + OrderCode: orderCode, + ShipperCode: shipperCode, + LogisticCode: logisticCode + }; + return JSON.stringify(requestData); + } + + generateDataSign(requestData) { + return encodeURI(Buffer.from(think.md5(requestData + think.config('express.appkey'))).toString('base64')); + } +}; diff --git a/pool/shard000/JavaScript/0002319_columnWidth.spec.js b/pool/shard000/JavaScript/0002319_columnWidth.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..1273dc9c6fa2b50f8fa2d1a798c84a83946d6cfa --- /dev/null +++ b/pool/shard000/JavaScript/0002319_columnWidth.spec.js @@ -0,0 +1,103 @@ +import columnWidth, { percentage, isHidden, isAuto, display } from './columnWidth'; + +const mockProps = { xs: -1, sm: 2, md: 0, lg: 6 }; + +describe('percentage', () => { + test('should generate a percentage based on collumn size', () => { + expect(percentage(mockProps, 'lg')).toEqual(50); + expect(percentage(mockProps, 'md')).toEqual(0); + expect(percentage(mockProps, 'sm')).toEqual(16.666666666666664); + }); + + test('should normalise negative numbers', () => { + expect(percentage(mockProps, 'xs')).toEqual(8.333333333333332); + }); +}); + +describe('isHidden', () => { + test('should return hidden if a given breakpoint is explicitly "0" or "hidden"', () => { + expect(isHidden({ xs: 0 }, 'xs')).toEqual(true); + expect(isHidden({ xs: 'hidden' }, 'xs')).toEqual(true); + expect(isHidden({ xs: undefined }, 'xs')).toEqual(false); + expect(isHidden({ xs: 12 }, 'xs')).toEqual(false); + }); +}); + +describe('isAuto', () => { + test('should return flex: 1 if a given property is explicitly "auto" if a given breakpoint is explicitly set to auto', () => { + const autoGrowMockProps = { xs: -1, sm: 2, md: 'auto', lg: 6 }; + const width = columnWidth(autoGrowMockProps, 'md').join(''); + expect(isAuto({ xs: 'auto' }, 'xs')).toEqual(true); + expect(width).toContain('flex: 1'); + }); +}); + +describe('display', () => { + test('should return block if no display is set', () => { + const value = display(mockProps, 'lg').join(''); + expect(value).toContain('display: block'); + }); + + test('should return display prop if set as string', () => { + const value = display({ sm: 1, display: 'flex' }, 'sm').join(''); + expect(value).toContain('display: flex'); + }); + + test('should return null prop if display is set to current breakpoint', () => { + const value = display({ sm: 1, display: { sm: 'flex' } }, 'sm'); + expect(value).toEqual(null); + }); + + test('should return display prop if display does not have matching breakpoint', () => { + const value = display({ sm: 1, display: { md: 'flex' } }, 'sm').join(''); + expect(value).toContain('display: block'); + }); +}); + +describe('columnWidth', () => { + test('should generate column width css', () => { + const width = columnWidth(mockProps, 'sm').join(''); + expect(width).toContain('flex-basis: 16.666666666666664%;'); + expect(width).toContain('max-width: 16.666666666666664%;'); + }); + + test('should return nothing if breakpoint does not exist', () => { + const width = columnWidth(mockProps, 'xl'); + expect(width).toEqual(null); + }); + + test('should not return display:block', () => { + const displayProps = { xs: 1, display: 'flex' }; + const width = columnWidth(displayProps, 'xs'); + expect(width).not.toContain('display: block;'); + }); + + test('should only return display:block if display has not already been set', () => { + const displayProps = { xs: 1 }; + const width = columnWidth(displayProps, 'xs'); + expect(width).toContain('display: block;'); + }); + + test('should return "display:none" if breakpoint is explicity set to 0', () => { + const width = columnWidth(mockProps, 'md').join(''); + expect(width).toContain('display: none'); + }); + + test('should return "display:none" if breakpoint is explicity set to "hidden"', () => { + const hiddenMockProps = { xs: -1, sm: 2, md: 'hidden', lg: 6 }; + const width = columnWidth(hiddenMockProps, 'md').join(''); + expect(width).toContain('display: none'); + }); + + test('should return a fixed column', () => { + const hiddenMockProps = { xs: 12, sm: 5, md: 6, lg: '390px' }; + const width = columnWidth(hiddenMockProps, 'lg').join(''); + expect(width).toContain('max-width: 390px;'); + }); + + test('should return a fixed column with sibling responsive', () => { + const hiddenMockProps = { xs: 12, sm: 5, md: 6, lg: 'calc(100% - 390px)' }; + const width = columnWidth(hiddenMockProps, 'lg').join(''); + expect(width).toContain('calc(100% - 390px);'); + }); +}); diff --git a/pool/shard000/JavaScript/0002324_puredom.placeholder.js b/pool/shard000/JavaScript/0002324_puredom.placeholder.js new file mode 100644 index 0000000000000000000000000000000000000000..3e158664d2708f37fabe0c0c833d1016977eed7a --- /dev/null +++ b/pool/shard000/JavaScript/0002324_puredom.placeholder.js @@ -0,0 +1,32 @@ +puredom.addNodeSelectionPlugin('placeholder', + 'placeholder' in document.createElement('input') + ? function() { + this.attr('placeholder', this.attr('data-placeholder')); + } + : function() { + if (this.attr('data-placeholder-active')!=='1') { + this.attr('data-placeholder-active', '1'); + this.on('focus', function() { + var me = puredom(this); + if (me.value()===me.attr('data-placeholder')) { + me.declassify('placeHolderContent').value('', {fireChange:false}); + } + }); + this.on('blur,change', function() { + var me = puredom(this); + setTimeout(function() { + var val = me.value(); + if (!val || val.length<1) { + me.classify('placeHolderContent').value(me.attr('data-placeholder'), {fireChange:false}); + } + else { + me.declassify('placeHolderContent'); + } + me = null; + }, 10); + }); + this.fireEvent('change'); + } + return this; + } +); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002328_navController.js b/pool/shard000/JavaScript/0002328_navController.js new file mode 100644 index 0000000000000000000000000000000000000000..26d1eb22619b25d7370639d942dba8130574820f --- /dev/null +++ b/pool/shard000/JavaScript/0002328_navController.js @@ -0,0 +1,25 @@ +(function(module) { + var navController = {}; + + navController.revealAll = function() { + $('.navtab-content').hide(); + $('.navtab-content').fadeIn('slow'); + }; + + navController.revealProjects = function() { + $('.navtab-content').hide(); + $('#projects').fadeIn('slow'); + }; + + navController.revealAbout = function() { + $('.navtab-content').hide(); + $('#about').fadeIn('slow'); + }; + + navController.revealContact = function() { + $('.navtab-content').hide(); + $('#contact').fadeIn('slow'); + }; + + module.navController = navController; +})(window); diff --git a/pool/shard000/JavaScript/0002329_hook.js b/pool/shard000/JavaScript/0002329_hook.js new file mode 100644 index 0000000000000000000000000000000000000000..057642fe5f6310e19abc9c7ffb626eec34e645d8 --- /dev/null +++ b/pool/shard000/JavaScript/0002329_hook.js @@ -0,0 +1,76 @@ +var id = "a2"; +var reason = document.getElementById("reason"); +var body = document.body; +var verdict = document.getElementById("verdict"); + +function hook(id, result, message){}; + +function pass(message) +{ + hook(id, "pass", reason); + document.title = "PASS"; + body.style.background = "green"; + verdict.innerHTML = "PASS"; + reason.innerHTML = message; +} + +function fail(message) +{ + hook(id, "fail", reason); + document.title = "FAIL"; + body.style.background = "red"; + verdict.innerHTML = "FAIL"; + reason.innerHTML = message; +} + +var id = "c9"; +var reason = document.getElementById("reason"); +var body = document.body; +var verdict = document.getElementById("verdict"); + +function hook(id, result, message){}; + +function pass(message) +{ + hook(id, "pass", reason); + document.title = "PASS"; + body.style.background = "green"; + verdict.innerHTML = "PASS"; + reason.innerHTML = message; +} + +function fail(message) +{ + hook(id, "fail", reason); + document.title = "FAIL"; + body.style.background = "red"; + verdict.innerHTML = "FAIL"; + reason.innerHTML = message; +} + +function evalEquals(prop, value, comparison) +{ + if(window.widget){ + comparison = comparison || "equal"; + var particle = (comparison === "equal") ? " to " : " than "; + try + { + if ((comparison === "equal" && eval(prop) === value) || + (comparison === "greater" && eval(prop) > value) || + (comparison === "less" && eval(prop) < value) + ) + { + var msg = "Test "+id+" passed because property "+prop+" was "+comparison+particle+value + pass(msg); + return; + } + fail("Test "+id+" failed because property "+prop+" was not "+comparison+particle+value); + } catch (e) { + fail("Test "+id+" failed because "+e.message); + } + } +} + +evalEquals("widget.height", 0, "greater"); + + diff --git a/pool/shard000/JavaScript/0002332_buildHtml.js b/pool/shard000/JavaScript/0002332_buildHtml.js new file mode 100644 index 0000000000000000000000000000000000000000..d3a2440037718198f5944c131b569415ea91ad24 --- /dev/null +++ b/pool/shard000/JavaScript/0002332_buildHtml.js @@ -0,0 +1,39 @@ +// This script copies src/index.html into /dist/index.html +// and adds TrackJS error tracking code for use in production +// when useTrackJs is set to true below and a trackJsToken is provided. +// This is a good example of using Node and cheerio to do a simple file transformation. +// In this case, the transformation is useful since we only want to track errors in the built production code. + +// Allowing console calls below since this is a build file. +/*eslint-disable no-console */ + +var fs = require('fs'); +var colors = require('colors'); +var cheerio = require('cheerio'); +var useTrackJs = true; //If you choose not to use TrackJS, just set this to false and the build warning will go away. +var trackJsToken = ''; //If you choose to use TrackJS, insert your unique token here. To get a token, go to https://trackjs.com + +fs.readFile('src/index.html', 'utf8', function (err,data) { + if (err) { + return console.log(err); + } + + var trackJsCode = ''; + + if (useTrackJs) { + if (trackJsToken) { + trackJsCode = ""; + } else { + console.log('To track JavaScript errors, sign up for a free trial at TrackJS.com and enter your token in /tools/build.html on line 10.'.yellow); + } + } + + var $ = cheerio.load(data); + $('head').prepend(trackJsCode); //add TrackJS tracking code to the top of + + fs.writeFile('dist/index.html', $.html(), 'utf8', function (err) { + if (err) return console.log(err); + }); + + console.log('index.html written to /dist'.green); +}); diff --git a/pool/shard000/JavaScript/0002337_add_libs_to_project.properties.js b/pool/shard000/JavaScript/0002337_add_libs_to_project.properties.js new file mode 100644 index 0000000000000000000000000000000000000000..afbac51f293159a17ca702aaef3379010211f4b1 --- /dev/null +++ b/pool/shard000/JavaScript/0002337_add_libs_to_project.properties.js @@ -0,0 +1,53 @@ +#!/usr/bin/env node + +var regexp = /android.library.reference.([\d].*?)=(.*)/g; +var path = require('path'); +var root = path.resolve(__dirname+'/../../../'); +var fs = require('fs'); +var exec = require('child_process').exec; + +var mapping = { + android:android +}; +try{ + var depList = require(root+'/config/dependencies.json'); +}catch(e){ + return console.error(e); +} + +console.log("adding libs to project.properties"); + +Object.keys(depList).forEach(function(env){ + var dep = depList[env]; + mapping[env] && mapping[env](dep); +}); + +function android(dep){ + var projectSettingPath = root+'/platforms/android/project.properties'; + var setting = fs.readFileSync(projectSettingPath,'utf8'), lastIdx = 0, cmd = []; + setting.replace(regexp,function(ignore,idx,libPath){ + idx = +idx; + libPath = libPath.trim(); + lastIdx = idx > lastIdx?idx:lastIdx; + console.log(idx,libPath); + var tmpIdx = dep.indexOf(libPath); + if(tmpIdx !== -1){ + dep.splice(dep.indexOf(libPath),1); + } + + }); + console.log(dep,lastIdx); + if(!dep.length){ + return; + } + dep.forEach(function(libPath,i){ + cmd.push("echo 'android.library.reference."+(lastIdx+i+1)+"="+libPath+"' >> "+projectSettingPath); + }); + console.log(cmd); + + exec(cmd.join(' && '),function(){ + console.log(arguments); + }); + +} + diff --git a/pool/shard000/JavaScript/0002339_content.js b/pool/shard000/JavaScript/0002339_content.js new file mode 100644 index 0000000000000000000000000000000000000000..4feec721e4ce6bfc08ece1d8ab931d685a7dd79c --- /dev/null +++ b/pool/shard000/JavaScript/0002339_content.js @@ -0,0 +1,26 @@ +window.define(function (require) { + var Daft = window.Daft + var Content = new Daft.Namespace('content') + + // ON LOAD + Content.onload(function () { + var self = this + var data = self.domData + + Daft.info('Content namespace loaded') + + setTimeout(function () { + // data.message.value = 'message updated!!!' + }, 2000) + + // ON UPDATE FUNCTION FOR TITLE + Content.nameChange = function (response) { + console.log('response', response) + if (response.value !== '') { + data.greeting.value = 'Great, I shall call you...' + response.value + '!' + } else { + data.greeting.value = 'Please enter your name above so I know what to call you!' + } + } + }) +}) diff --git a/pool/shard000/JavaScript/0002340_gui.js b/pool/shard000/JavaScript/0002340_gui.js new file mode 100644 index 0000000000000000000000000000000000000000..5cfe8c83a7e5a580b2f801326e46f4c87aa52c5d --- /dev/null +++ b/pool/shard000/JavaScript/0002340_gui.js @@ -0,0 +1,163 @@ +/* +Copyright (C) 2011-2013 by Gregory Burlet, Alastair Porter + +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. +*/ + +/** + * Manages the GUI creation and interactions + * + * @class GUI handling + * @param {Object} guiToggles Boolean values toggling instantiation of GUI elements + */ +Toe.View.GUI = function(apiprefix, meipath, rendEng, guiToggles) { + var toggles = { + sldr_bgImgOpacity: true, + sldr_glyphOpacity: true, + initGlyphOpacity: 1.0, + initBgImgOpacity: 0.60 + }; + + $.extend(toggles, guiToggles); + + this.rendEng = rendEng; + this.apiprefix = apiprefix; + this.meipath = meipath; + + this.setupNavBar(); + + var parentDivId = "#gui-sidebar"; + this.setupSideBar(parentDivId, toggles); + + this.bindHotkeys(); +} + +Toe.View.GUI.prototype.constructor = Toe.View.GUI; + +/** + * Inject HTML navbar links + * + * @methodOf Toe.View.GUI + */ +Toe.View.GUI.prototype.setupNavBar = function() { + var gui = this; + + var nav_file_dropdown_parent = "#nav_file_dropdown"; + // check if the file menu is included in the template (avoid including bootstrap.js if possible) + if ($(nav_file_dropdown_parent).length) { + $(nav_file_dropdown_parent).append('
  • Revert
  • ' + + '
  • Get MEI
  • ' + + '
  • Get Score Image
  • '); + + + $("#nav_file_dropdown_revert").tooltip({animation: true, + placement: 'right', + title: 'Revert the current MEI file to the original version. ' + + 'Warning: this will revert all changes made in the editor.', + delay: 100}); + $("#nav_file_dropdown_revert").click(function() { + // move backup mei file to working directory + $.post(gui.apiprefix + "/revert", function(data) { + // when the backup file has been restored, reload the page + window.location.reload(); + }) + .error(function() { + // show alert to user + // replace text with error message + $("#alert > p").text("Server failed to restore backup MEI file."); + $("#alert").animate({opacity: 1.0}, 100); + }); + }); + + // MEI download + $("#nav_file_dropdown_getmei").tooltip({animation: true, + placement: 'right', + title: 'View the MEI file of the document being edited.', + delay: 100}); + // set the download path of the file + $("#nav_file_dropdown_getmei").attr("href", gui.meipath); + + // Document image rasterize + $("#nav_file_dropdown_getimg").tooltip({animation: true, + placement: 'right', + title: 'Download an image of the document being edited.', + delay: 100}); + $("#nav_file_dropdown_getimg").click(function() { + if (!fabric.Canvas.supports('toDataURL')) { + // show alert to user + $("#alert > p").text("The browser you are using does not support this feature."); + } + else { + window.open(gui.rendEng.canvas.toDataURL('png')); + } + }); + } +} + +Toe.View.GUI.prototype.setupSideBar = function(parentDivId, toggles) { + // cache instance variable + var gui = this; + + // create container for appearance sliders + if (toggles.sldr_bgImgOpacity || toggles.sldr_glyphOpacity) { + $(parentDivId).prepend('\n'); + + // create background image opacity slider + if (toggles.sldr_bgImgOpacity) { + $("#sidebar-app").append('
  • \n\n' + + '\n
  • '); + + $("#sldr_bgImgOpacity").bind("change", function() { + gui.rendEng.canvas.backgroundImageOpacity = $(this).val(); + gui.rendEng.repaint(); + }); + } + + // create glyph opacity slider + if (toggles.sldr_glyphOpacity) { + $("#sidebar-app").append('
  • \n\n' + + '\n
  • '); + + $("#sldr_glyphOpacity").bind("change", function() { + var opacity = $(this).val(); + gui.rendEng.canvas.forEachObject(function(obj) { + obj.setOpacity(opacity); + }); + + gui.rendEng.repaint(); + }); + } + } +} + +Toe.View.GUI.prototype.bindHotkeys = function() { + // edit mode hotkey + Mousetrap.bind(['e', 'Ctrl+e', 'Command+e'], function() { + $("#btn_edit").click(); + return false; + }); + + // insert mode hotkey + Mousetrap.bind(['i', 'Ctrl+i', 'Command+i'], function() { + $("#btn_insert").click(); + return false; + }); +} diff --git a/pool/shard000/JavaScript/0002341_assertNotNull.spec.js b/pool/shard000/JavaScript/0002341_assertNotNull.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..10c91b40f52113a6360fa4745aeb19c288c73b01 --- /dev/null +++ b/pool/shard000/JavaScript/0002341_assertNotNull.spec.js @@ -0,0 +1,48 @@ +import chai, {expect} from 'chai'; +import Assert, {notNull} from '../index'; +import {logError} from '../actions'; +import sinon from 'sinon' +import sinonChai from 'sinon-chai'; +import {NOT_NULL} from "../messages"; + +chai.use(sinonChai); + +describe('Assert notNull', () => { + + let sandbox; + + beforeEach(() => { + sandbox = sinon.sandbox.create(); + sandbox.stub(console, 'error'); + Assert.setAction(logError) + }); + + afterEach(() => { + sandbox.restore(); + }); + + it('should log info with default message', () => { + notNull(null); + expect(console.error).to.have.been.calledWith(NOT_NULL); + }); + + it('should log error with default message', () => { + notNull(null, undefined, logError); + expect(console.error).to.have.been.calledWith(NOT_NULL); + }); + + it('should log info with custom message', () => { + notNull(null, 'Custom message'); + expect(console.error).to.have.been.calledWith('Custom message'); + }); + + it('should not log anything for an empty string', () => { + notNull(''); + expect(console.error.calledOnce).to.be.false; + }); + + it('should not log anything for zero', () => { + notNull(0); + expect(console.error.calledOnce).to.be.false; + }); +}); diff --git a/pool/shard000/JavaScript/0002342_commander.js b/pool/shard000/JavaScript/0002342_commander.js new file mode 100644 index 0000000000000000000000000000000000000000..d6b5168deef9c4c6e530db4ac1ebd517cbd95093 --- /dev/null +++ b/pool/shard000/JavaScript/0002342_commander.js @@ -0,0 +1,239 @@ +/** + * Created by Tomasz on 7/16/2015. + */ +var CommanderFile = function () { + this.title = ""; + this.size = 0; + this.type = ""; + this.isFolder = false; + this.pId = ""; + this.downloadLink; + this.webLink; + + this.metaData = {}; +}; + +var Commander = function () { + var panel1 = new Panel("#panel_left"); + var panel2 = new Panel("#panel_right"); + var currentPanel = panel1; + var destinationPanel = panel2; + var that = this; + this.modalActive = false; + this.init = function (ds) { + panel1.dataService = ds; + panel2.dataService = ds; + that.refreshBoth(); + }; + + this.refreshBoth = function () { + panel1.refresh(); + panel2.refresh(); + }; + + var copySelected = function () { + var dialogData = { + dialogName: "copy", + focusOnSelector: "", + action: currentPanel.dataService.copyFile, + reaction: that.copyHandler, + params: { + src: currentPanel, + dst: destinationPanel, + dialogValues: {} + } + }; + createDialog(dialogData); + }; + + this.copyHandler = function (resp) { + console.log('Copy ID: ' + resp.id); + that.refreshBoth(); + }; + + var isPanelsLocationTheSame = function () { + return panel1.currentDir === panel2.currentDir; + }; + + var moveRename = function () { + //rename only... for now + var dialogData = { + dialogName: "rename", + focusOnSelector: "#renameInput", + action: currentPanel.dataService.rename, + reaction: that.refreshBoth, + params: { + src: currentPanel, + dst: destinationPanel, + dialogValues: {} + } + }; + createDialog(dialogData); + }; + + var createFolder = function () { + var dialogData = { + dialogName: "createFolder", + focusOnSelector: "#folderNameInput", + action: currentPanel.dataService.createFolder, + reaction: that.refreshBoth, + params: { + src: currentPanel, + dst: destinationPanel, + dialogValues: {} + } + }; + createDialog(dialogData); + }; + + var deleteSelected = function () { + var dialogData = { + dialogName: "delete", + focusOnSelector: "#permanentCheckbox", + action: currentPanel.dataService.delete, + reaction: that.refreshBoth, + params: { + src: currentPanel, + dst: destinationPanel, + dialogValues: {} + } + }; + createDialog(dialogData); + }; + + var createDialog = function (dialogData) { + if (that.modalActive) { + return; + } + + $("#" + dialogData.dialogName + "Dialog").on('show.bs.modal', function (event) { + that.modalActive = true; + var modal = $(this); + var confirmButton = modal.find('button[name="confirm"]'); + + var cleanup = modal.find("input"); + for (var i = 0; i < cleanup.length; i++) { + //exclude by name for now(default values will be stored in setting later) + if (cleanup[i].name == "permanently") { + continue; + } + cleanup[i].value = ""; + } + + confirmButton.on('keypress click', function (e) { + e.preventDefault(); + if (e.which === 13 || e.type === 'click') { + // get all input values from dialog + var dialoginputs = modal.find("input"); + for (var i = 0; i < dialoginputs.length; i++) { + dialogData.params.dialogValues[dialoginputs[i].name] = dialoginputs[i].value; + } + //execute command + console.log("creating a folder..."); + dialogData.action(dialogData.params, dialogData.reaction); + $("#" + dialogData.dialogName + "Dialog").modal('hide'); + } + }); + + if (dialogData.focusOnSelector == dialogData.focusOnSelector || dialogData.focusOnId) { + dialogData.focusOnSelector = 'button[name="confirm"]'; + } + $(dialogData.focusOnSelector).focus(); + }); + + $("#" + dialogData.dialogName + "Dialog").on('hide.bs.modal', function (event) { + that.modalActive = false; + //remove listeners + var modal = $(this); + var confirmButton = modal.find('button[name="confirm"]'); + confirmButton.off("keypress click"); + $("#" + dialogData.dialogName + "Dialog").off('show.bs.modal'); + }); + + + $("#" + dialogData.dialogName + "Dialog").modal(); + }; + + + this.keyboardActions = function (event) { + console.log(event.keyCode); + if (!that.modalActive) { + event.preventDefault(); + switch (event.keyCode) { + case 113://f2 + location.reload(); + case 9://tab + switchPanels(); + break; + case 116://f5 + copySelected(); + break; + case 117: //f6 rename/move + moveRename(); + break; + case 118: //f7 create folder + createFolder(); + break; + case 119: //f8 delete + deleteSelected(); + break; + case 46: //delete permanently + deleteSelected(); + break; + case 13: + openCurrentItem(); + break; + default : + currentPanel.command(event.keyCode); + break; + } + } + }; + + var openCurrentItem = function () { + var currentItem = currentPanel.getCurrentItem(); + //open parent + if (currentPanel.cursorPosition == 0) { + if (currentPanel.parentsDirs.length != 0) { + currentPanel.currentDir = currentPanel.parentsDirs.pop(); + currentPanel.refresh(); + } else { + alert('root folder'); + } + return; + } + //go inside folder + if (currentItem.isFolder) { + currentPanel.parentsDirs.push(currentPanel.currentDir); + currentPanel.currentDir = currentItem; + currentPanel.refresh(); + } else { + $("#downloadLink").attr("href", currentItem.webLink); + $("#openDialog").modal().on('hide.bs.modal', function (e) { + //TODO ? + }); + } + console.log(this.parentsDirs); + }; + + var switchPanels = function () { + if (currentPanel == panel1) { + currentPanel = panel2; + destinationPanel = panel1; + } else { + currentPanel = panel1; + destinationPanel = panel2; + } + }; + + this.keyUpHandler = function (event) { + event.preventDefault(); + }; + + this.keybind = function () { + $(document).keyup(this.keyUpHandler); + $(document).keydown(this.keyboardActions); + }; + + this.keybind(); +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002343_SidebarHeader.js b/pool/shard000/JavaScript/0002343_SidebarHeader.js new file mode 100644 index 0000000000000000000000000000000000000000..4c296ee018981869eae24bb83814992d7322efbb --- /dev/null +++ b/pool/shard000/JavaScript/0002343_SidebarHeader.js @@ -0,0 +1,24 @@ +import React from 'react'; + +import { getTheme } from '../Theme'; + +const SidebarHeader = ({ children }) => +
    + {children} +
    ; + +const styles = () => ({ + wrapper: { + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + width: '100%', + height: 100, + padding: 20, + backgroundColor: getTheme().palette.primary1Color, + color: 'white', + boxSizing: 'border-box', + }, +}); + +export default SidebarHeader; diff --git a/pool/shard000/JavaScript/0002344_comment-controller.js b/pool/shard000/JavaScript/0002344_comment-controller.js new file mode 100644 index 0000000000000000000000000000000000000000..f364469b20e7e8a71778fcc1597c8c92f6e74eb2 --- /dev/null +++ b/pool/shard000/JavaScript/0002344_comment-controller.js @@ -0,0 +1,23 @@ +const Hotel = require('mongoose').model('Hotel') + +module.exports = { + addComment:(req, res)=>{ + let currentHotel = req.params.id + let userId = req.user._id + let commentBody = req.body + + let commentObj = { + creator:userId, + title:commentBody.title, + decsription:commentBody.comment, + creationDate: Date.now() + } + + Hotel.findById(currentHotel).then(selectedHotel=>{ + selectedHotel.comments.push(commentObj) + selectedHotel.save().then(()=>{ + res.redirect('back') + }) + }) + } +} diff --git a/pool/shard000/JavaScript/0002348_scoreTest.js b/pool/shard000/JavaScript/0002348_scoreTest.js new file mode 100644 index 0000000000000000000000000000000000000000..9869a8873c25c839f0af7f7e7cbe32439a691728 --- /dev/null +++ b/pool/shard000/JavaScript/0002348_scoreTest.js @@ -0,0 +1,34 @@ +/*jshint expr: true*/ +var should = require("should"); +var mysql = require('mysql'); +var ds = require('../lib/datasource.js'); + +var Score = require('../lib/score.js').Score; + +describe("saveScore", function() { + describe("save", function() { + it('should save score', function(done) { + var repo = "repo 1"; + var score = new Score(repo); + score.score = 100; + var connection = mysql.createConnection(ds.get('score')); + + var initialCount = 0; + connection.query('SELECT count(*) as count FROM scores', function(err, rows, fields) { + (!err).should.be.true; + initialCount = rows[0].count; + }); + connection.end(); + score.save(function(err) { + (!err).should.be.true; + var connection = mysql.createConnection(ds.get('score')); + + connection.query('SELECT count(*) as count FROM scores', function(err, rows, fields) { + (!err).should.be.true; + rows[0].count.should.be.greaterThan(initialCount); + connection.end(done); + }); + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0002349_post-processors.js b/pool/shard000/JavaScript/0002349_post-processors.js new file mode 100644 index 0000000000000000000000000000000000000000..fc2bb5cb91dac37e6bf79778a5c5b76318253664 --- /dev/null +++ b/pool/shard000/JavaScript/0002349_post-processors.js @@ -0,0 +1,40 @@ +import _ from 'underscore'; +import $ from 'jquery'; + +import * as DOM from '../helpers/dom'; +import * as Settings from '../helpers/settings'; +import * as Storage from '../helpers/storage'; +import * as Tools from '../helpers/tools'; + +let preprocessors = []; +let postprocessors = []; + +export let registerPreprocessor = Tools.createRegisterFunction(preprocessors); +export let registerPostprocessor = Tools.createRegisterFunction(postprocessors); + +export async function applyPreprocessors(posts) { + if (!_(posts).isArray()) { + posts = [posts]; + } + await Tools.series(posts.filter(post => !!post), (post) => { + let list = preprocessors.filter((p) => { return Tools.testFilter(p, post); }).sort(Tools.priorityPredicate); + return Tools.series(list, (p) => { + return p.processor(post); + }); + }); + if (Settings.spellsEnabled()) { + await require('../core/hiding').applySpells(posts); + } +} + +export function applyPostprocessors(posts) { + if (!_(posts).isArray()) { + posts = [posts]; + } + return Tools.series(posts.filter(post => !!post), (post) => { + let list = postprocessors.filter((p) => { return Tools.testFilter(p, post); }).sort(Tools.priorityPredicate); + return Tools.series(list, (p) => { + return p.processor(post); + }); + }); +} diff --git a/pool/shard000/JavaScript/0002351_gulpfile.js b/pool/shard000/JavaScript/0002351_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..6ef837ea50053275b982a8db8f0264c651588706 --- /dev/null +++ b/pool/shard000/JavaScript/0002351_gulpfile.js @@ -0,0 +1,12 @@ +var gulpDocumentation = require('gulp-documentation'); +var gulp = require('gulp'); + +gulp.task('documentation-html', function () { + return gulp.src('./*.js') + .pipe(gulpDocumentation('html', {}, { + name: 'API CEP Node.js', + version: '1.0.0' + })).pipe(gulp.dest('docs')); +}); + +gulp.task('default', ['documentation-html']); diff --git a/pool/shard000/JavaScript/0002354_common.js b/pool/shard000/JavaScript/0002354_common.js new file mode 100644 index 0000000000000000000000000000000000000000..f65b8a348044337b7c33beee3d322344ac3394ec --- /dev/null +++ b/pool/shard000/JavaScript/0002354_common.js @@ -0,0 +1,55 @@ +CB.Controllers.Common = { + init() { + CB.Services.Browser.addUserAgentAttributeToHtmlTag(); + CB.Services.Browser.fixFlexboxIndicatorClass(); + + this._initElements(); + this._initEvents(); + this._removeEmptyParagraphTagsAddedByTheWpEditor(); + this._initPageBackgrounds(); + }, + + _initElements() { + this.$window = $(window); + + this.$siteHeader = $('#site-header'); + this.$siteMenu = $('.nav-primary'); + this.$scrollingAnchors = $('body').find('a[href^="#"]'); + this.$pages = $('#all-pages-as-single').children(); + }, + + _initEvents() { + this.$window.scroll(_.debounce(() => this._onScroll(), 15)); + + this.$scrollingAnchors.click(e => CB.Services.Animator.scrollTo(e, this.$siteMenu.outerHeight())); + }, + + _removeEmptyParagraphTagsAddedByTheWpEditor() { + $('p:empty').remove(); + }, + + _onScroll() { + const isScrolledDownEnough = this.$window.scrollTop() > 0; + + this.$siteHeader.toggleClass('scrolled-down', isScrolledDownEnough); + }, + + _initPageBackgrounds() { + _.forEach(this.$pages, page => { + const $page = $(page); + const dataUrlBgImgLarge = $page.data('urlBgImgLarge'); + const dataUrlBgImgSmall = $page.data('urlBgImgSmall'); + + if (!CB.Services.Browser.isLargeScreen() + && !window.matchMedia('(min-resolution: 2dppx)').matches + && dataUrlBgImgSmall) { + + $page.addClass('img-bg'); + $page.css('background-image', `url(${dataUrlBgImgSmall})`); + } else if (dataUrlBgImgLarge) { + $page.addClass('img-bg'); + $page.css('background-image', `url(${dataUrlBgImgLarge})`); + } + }); + } +}; diff --git a/pool/shard000/JavaScript/0002356_keyboard_commands.js b/pool/shard000/JavaScript/0002356_keyboard_commands.js new file mode 100644 index 0000000000000000000000000000000000000000..49a6d0da66d95d8156d00b598f32ca62d9288106 --- /dev/null +++ b/pool/shard000/JavaScript/0002356_keyboard_commands.js @@ -0,0 +1,133 @@ +import _ from 'lodash' + +import { showGallery, hideGallery } from '../gallery/view' +import { changeBuildingHeight } from '../segments/buildings' +import { + draggingType, + DRAGGING_TYPE_RESIZE, + DRAGGING_TYPE_MOVE, + handleSegmentMoveCancel +} from '../segments/drag_and_drop' +import { + handleSegmentResizeCancel, + incrementSegmentWidth +} from '../segments/resizing' +import { undo, redo } from '../streets/undo_stack' +import { getSignInData, isSignedIn } from '../users/authentication' +import { trackEvent } from './event_tracking' +import { isFocusOnBody } from './focus' +import { registerKeypress } from './keypress' +import { msg } from './messages' +import { showStatusMessage } from './status_message' + +export const KEYS = { + ENTER: 13, + ESC: 27, + Y: 89, + Z: 90, + EQUAL: 187, // = or + + EQUAL_ALT: 61, // Firefox + PLUS_KEYPAD: 107, + MINUS: 189, + MINUS_ALT: 173, // Firefox + MINUS_KEYPAD: 109 +} + +export function onGlobalKeyDown (event) { + if (isFocusOnBody()) { + onBodyKeyDown(event) + } + + switch (event.keyCode) { + case KEYS.ESC: + if (draggingType() === DRAGGING_TYPE_RESIZE) { + handleSegmentResizeCancel() + } else if (draggingType() === DRAGGING_TYPE_MOVE) { + handleSegmentMoveCancel() + } else if (document.body.classList.contains('gallery-visible')) { + hideGallery(false) + } else if (isSignedIn()) { + showGallery(getSignInData().userId, false) + } else { + return + } + + event.preventDefault() + break + } +} + +function onBodyKeyDown (event) { + switch (event.keyCode) { + case KEYS.EQUAL: + case KEYS.EQUAL_ALT: + case KEYS.PLUS_KEYPAD: + case KEYS.MINUS: + case KEYS.MINUS_ALT: + case KEYS.MINUS_KEYPAD: + if (event.metaKey || event.ctrlKey || event.altKey) { + return + } + + var negative = (event.keyCode === KEYS.MINUS) || + (event.keyCode === KEYS.MINUS_ALT) || + (event.keyCode === KEYS.MINUS_KEYPAD) + + var hoveredEl = getHoveredEl() + if (hoveredEl) { + if (hoveredEl.classList.contains('segment')) { + incrementSegmentWidth(hoveredEl, !negative, event.shiftKey) + } else if (hoveredEl.id === 'street-section-left-building') { + changeBuildingHeight(true, !negative) + } else if (hoveredEl.id === 'street-section-right-building') { + changeBuildingHeight(false, !negative) + } + event.preventDefault() + + trackEvent('INTERACTION', 'CHANGE_WIDTH', 'KEYBOARD', null, true) + } + break + case KEYS.Z: + if (!event.shiftKey && (event.metaKey || event.ctrlKey)) { + undo() + event.preventDefault() + } else if (event.shiftKey && (event.metaKey || event.ctrlKey)) { + redo() + event.preventDefault() + } + break + case KEYS.Y: + if (event.metaKey || event.ctrlKey) { + redo() + event.preventDefault() + } + break + } +} + +function getHoveredEl () { + var el = document.querySelector('.hover') + return el +} + +// In case anyone tries a save shortcut key out of reflex, +// we inform the user that it's not necessary. +registerKeypress('ctrl s', { + trackAction: 'Command-S or Ctrl-S save shortcut key pressed' +}, function () { + showStatusMessage(msg('STATUS_NO_NEED_TO_SAVE')) +}) + +// Catch-all for the Ctrl-S shortcut from ever trying to +// save the page contents +registerKeypress('ctrl s', { + preventDefault: true, + requireFocusOnBody: false +}, _.noop) + +// Catch-all for the backspace or delete buttons to prevent +// browsers from going back in history +registerKeypress(['backspace', 'delete'], { + preventDefault: true, + requireFocusOnBody: true +}, _.noop) diff --git a/pool/shard000/JavaScript/0002357_ai.js b/pool/shard000/JavaScript/0002357_ai.js new file mode 100644 index 0000000000000000000000000000000000000000..84f96a8d84ee27edc7dce2a1df99ea64f97a928c --- /dev/null +++ b/pool/shard000/JavaScript/0002357_ai.js @@ -0,0 +1,94 @@ +"use strict"; + +DC.AIManager = function() { + var m1 = new THREE.Matrix4(); + var v1 = new THREE.Vector3(); + var v2 = new THREE.Vector3(); + var turnGain = 10; + var maxTurnSpeed = Math.PI; + + function walkTowards(monster, pos, sq_thres) { + // Get monster's look vector in world space + monster.updateMatrixWorld(); + m1.extractRotation(monster.matrixWorld); + v1.set(0, 0, 1).applyMatrix4(m1); + // Calculate target vector + v2.copy(pos); + v2.sub(monster.position); + v2.y = 0; + v2.normalize(); + // Difference in angle + var angleDiff = Math.atan2(v1.z, v1.x) - Math.atan2(v2.z, v2.x); + if (angleDiff > Math.PI) angleDiff -= Math.PI * 2; + // Set angular speed + var turnSpeed = turnGain * angleDiff; + if (turnSpeed > maxTurnSpeed) turnSpeed = maxTurnSpeed; + if (turnSpeed < -maxTurnSpeed) turnSpeed = -maxTurnSpeed; + monster.setAngularVelocity(v1.set(0, turnSpeed, 0)); + // Linear speed and distance considerations + if (monster.position.distanceToSquared(pos) >= sq_thres) { + if (Math.abs(angleDiff) < Math.PI / 4) + monster.setLinearVelocity(v2.multiplyScalar(monster.speed)); + else monster.setLinearVelocity(v2.set(0, 0, 0)); + if (monster.mesh) monster.mesh.animate = true; + return false; + } else { + monster.setLinearVelocity(v2.set(0, 0, 0)); + if (monster.mesh) monster.mesh.animate = false; + return true; + } + } + + this.process = function() { + var i, j; + var gridSize = dungeon.level.gridSize; + // TODO: Should probably keep own collection + for (i = 0; i < dungeon.monsters.length; ++i) { + var monster = dungeon.monsters[i]; + if (monster.dead) continue; + + // Does the monster see player? + if (dungeon.level.map.raycast( + monster.position.x / gridSize, monster.position.z / gridSize, + pl.position.x / gridSize, pl.position.z / gridSize)) + { + // Mark as active + monster.activated = true; + monster.waypoints = null; // Clear waypoints + // Look at player + walkTowards(monster, pl.position, 12); + // Shoot? + //if (Math.random() < 0.333) { + // shoot(monster, "plain", monster.faction, v1.set(0, 0.11, 1.2)); + //} + + // Target lost? Let's find a path + } else if (monster.activated && !monster.waypoints) { + var path = dungeon.pathFinder.findPath( + (monster.position.x / gridSize)|0, (monster.position.z / gridSize)|0, + (pl.position.x / gridSize)|0, (pl.position.z / gridSize)|0, + dungeon.grid.clone()); + monster.waypoints = []; + //path = PF.Util.smoothenPath(dungeon.grid, path); + for (j = 0; j < path.length; ++j) { + v1.set((path[j][0] + 0.5) * gridSize, monster.position.y, (path[j][1] + 0.5) * gridSize); + monster.waypoints.push(v1.clone()); + } + } + + // Does the monster have waypoints? + if (monster.waypoints) { + if (!monster.waypoints.length) + monster.waypoints = null; + else if (walkTowards(monster, monster.waypoints[0], 1)) { + // Move on to the next waypoint + monster.waypoints.splice(0, 1); + } + } + } + }; + +}; + + + diff --git a/pool/shard000/JavaScript/0002369_pump.t.js b/pool/shard000/JavaScript/0002369_pump.t.js new file mode 100644 index 0000000000000000000000000000000000000000..7f7f56926dffc12f002587411e49198d9a4f53f2 --- /dev/null +++ b/pool/shard000/JavaScript/0002369_pump.t.js @@ -0,0 +1,36 @@ +require('proof')(2, prove) + +function prove (okay, callback) { + var Destructible = require('destructible') + var destructible = new Destructible('t/pump.t') + + destructible.completed.wait(callback) + + var Procession = require('..') + + var Pump = require('../pump') + + var cadence = require('cadence') + + cadence(function (async) { + async(function () { + var inbox = new Procession + var outbox = new Procession + var shifter = outbox.shifter() + new Pump(inbox.shifter(), outbox, 'enqueue').destroy() + shifter.dequeue(async()) + destructible.durable('enqueue', new Pump(inbox.shifter(), outbox, 'enqueue'), 'destructible', null) + inbox.push(1) + }, function (value) { + okay(value, 1, 'enqueued') + var inbox = new Procession + var outbox = new Procession + var shifter = outbox.shifter() + shifter.dequeue(async()) + destructible.durable('push', new Pump(inbox.shifter(), outbox, 'push'), 'destructible', null) + inbox.push(1) + }, function (value) { + okay(value, 1, 'pushed') + }) + })(destructible.durable('destructible')) +} diff --git a/pool/shard000/JavaScript/0002377_search_result_list.js b/pool/shard000/JavaScript/0002377_search_result_list.js new file mode 100644 index 0000000000000000000000000000000000000000..e157a768a6908b8e948aeb615e3b588c6eaaee4d --- /dev/null +++ b/pool/shard000/JavaScript/0002377_search_result_list.js @@ -0,0 +1,64 @@ +chorus.views.SearchResultList = chorus.views.Base.extend({ + constructorName: "SearchResultList", + templateName: "search_result_list", + + events: { + "click a.show_all": "showAll" + }, + + subviews: { + ".list": "list" + }, + + setup: function() { + this.search = this.options.search; + this.entityType = this.options.entityType; + this.selectedModels = this.options.selectedModels; + this.list = this.buildList(); + this.subscribePageEvent("selected", this.saveSearchSelection); + }, + + saveSearchSelection: function(model) { + this.search.selectedItem = model; + }, + + buildList: function() { + return new chorus.views.PageItemList({ + collection: this.collection, + entityViewType: chorus.views["Search" + _.classify(this.options.entityType)], + listItemOptions: { + workspaceIdForTagLink: this.options.search.get('workspaceId') + }, + selectedModels: this.selectedModels, + multiListMode: true + }); + }, + + additionalContext: function() { + return { + entityType: this.entityType, + shown: this.collection.models.length, + total: this.collection.pagination.records, + hideHeaders: this.search && this.search.isPaginated() && !this.search.workspace(), + moreResults: this.moreRecordsThanShown(), + title: this.title() + }; + }, + + title: function() { + return t("search.type." + this.entityType); + }, + + moreRecordsThanShown: function () { + var localModels = this.collection.models; + var remoteModelCount = this.collection.pagination.records; + return (localModels.length < remoteModelCount); + }, + + showAll: function(e) { + e.preventDefault(); + this.search.set({entityType: $(e.currentTarget).data("type")}); + delete this.search.attributes.workspaceId; + chorus.router.navigate(this.search.showUrl()); + } +}); diff --git a/pool/shard000/JavaScript/0002379_events.js b/pool/shard000/JavaScript/0002379_events.js new file mode 100644 index 0000000000000000000000000000000000000000..5c608ab5082e812785e87bd60fe7f2882ad52e2b --- /dev/null +++ b/pool/shard000/JavaScript/0002379_events.js @@ -0,0 +1,35 @@ +'use strict'; + +System.register(['./constants'], function (_export, _context) { + "use strict"; + + var constants; + function fireEvent(element, name) { + var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + var event = new CustomEvent(name, { + detail: data, + bubbles: true + }); + element.dispatchEvent(event); + + return event; + } + + _export('fireEvent', fireEvent); + + function fireMaterializeEvent(element, name) { + var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + return fireEvent(element, '' + constants.eventPrefix + name, data); + } + + _export('fireMaterializeEvent', fireMaterializeEvent); + + return { + setters: [function (_constants) { + constants = _constants.constants; + }], + execute: function () {} + }; +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002380_user-profile-roles-test.js b/pool/shard000/JavaScript/0002380_user-profile-roles-test.js new file mode 100644 index 0000000000000000000000000000000000000000..189f35c725e8b34cb6090597a4740cc25a6878de --- /dev/null +++ b/pool/shard000/JavaScript/0002380_user-profile-roles-test.js @@ -0,0 +1,118 @@ +import { module, test } from 'qunit'; +import { setupRenderingTest } from 'ember-qunit'; +import { render, click, findAll } from '@ember/test-helpers'; +import hbs from 'htmlbars-inline-precompile'; +import setupMirage from 'ember-cli-mirage/test-support/setup-mirage'; + +module('Integration | Component | user profile roles', function(hooks) { + setupRenderingTest(hooks); + setupMirage(hooks); + + hooks.beforeEach(async function () { + this.formerStudentRole = this.server.create('user-role', { + title: 'Former Student' + }); + this.studentRole = this.server.create('user-role', { + title: 'Student' + }); + }); + + test('it renders', async function (assert) { + const user = this.server.create('user', { + root: false, + roles: [this.studentRole], + }); + const userModel = await this.owner.lookup('service:store').find('user', user.id); + + this.set('user', userModel); + await render(hbs``); + const student = '[data-test-student] span'; + const formerStudent = '[data-test-former-student] span'; + const enabled = '[data-test-enabled] span'; + const syncIgnored = '[data-test-exclude-from-sync] span'; + const performsNonLearnerFunction = '[data-test-performs-non-learner-function] span'; + const learner = '[data-test-learner] span'; + const root = '[data-test-root] span'; + + assert.dom(student).hasText('Yes', 'student shows status'); + assert.dom(formerStudent).hasText('No', 'former student shows status'); + assert.dom(formerStudent).hasClass('no', 'former student has right class'); + assert.dom(enabled).hasText('Yes', 'enabled shows status'); + assert.dom(enabled).hasClass('yes', 'enabled has right class'); + assert.dom(syncIgnored).hasText('No', 'sync ignored shows status'); + assert.dom(syncIgnored).hasClass('no', 'sync ignored has right class'); + + assert.dom(performsNonLearnerFunction).hasText('No'); + assert.dom(performsNonLearnerFunction).hasClass('no'); + assert.dom(learner).hasText('No'); + assert.dom(learner).hasClass('no'); + assert.dom(root).hasText('No'); + assert.dom(root).hasClass('no'); + }); + + // @link https://github.com/ilios/frontend/issues/3899 + test('check root flag', async function(assert) { + const user = this.server.create('user', { + root: true, + roles: [this.studentRole], + }); + const userModel = await this.owner.lookup('service:store').find('user', user.id); + + this.set('user', userModel); + await render(hbs``); + const root = '[data-test-root] span'; + + assert.dom(root).hasText('Yes'); + assert.dom(root).hasClass('yes'); + }); + + test('clicking manage sends the action', async function(assert) { + assert.expect(1); + const user = this.server.create('user', { + root: true, + roles: [this.studentRole], + }); + const userModel = await this.owner.lookup('service:store').find('user', user.id); + this.set('user', userModel); + this.set('click', (what) =>{ + assert.ok(what, 'recieved boolean true value'); + }); + await render(hbs``); + const manage = 'button.manage'; + await click(manage); + }); + + test('can edit user roles', async function(assert) { + assert.expect(8); + const user = this.server.create('user', { + root: true, + roles: [this.studentRole], + }); + const userModel = await this.owner.lookup('service:store').find('user', user.id); + + this.set('user', userModel); + this.set('nothing', parseInt); + + await render(hbs``); + const inputs = findAll('input'); + const formerStudent = '[data-test-former-student] input'; + const enabled = '[data-test-enabled] input'; + const syncIgnored = '[data-test-exclude-from-sync] input'; + + assert.equal(inputs.length, 3); + assert.dom(formerStudent).isNotChecked(); + assert.dom(enabled).isChecked(); + assert.dom(syncIgnored).isNotChecked(); + + await click(formerStudent); + await click(enabled); + await click(syncIgnored); + + await click('.bigadd'); + + assert.ok(userModel.hasMany('roles').ids().includes(this.studentRole.id)); + assert.ok(userModel.hasMany('roles').ids().includes(this.formerStudentRole.id)); + assert.equal(userModel.get('enabled'), false, 'user is disabled'); + assert.equal(userModel.get('userSyncIgnore'), true, 'user is sync ignored'); + }); +}); diff --git a/pool/shard000/JavaScript/0002382_events.model.js b/pool/shard000/JavaScript/0002382_events.model.js new file mode 100644 index 0000000000000000000000000000000000000000..336f6f197cd04b29b9e1a5169695dfc2066c48a6 --- /dev/null +++ b/pool/shard000/JavaScript/0002382_events.model.js @@ -0,0 +1,54 @@ +"use strict"; + +require("rootpath")(); + +const mongoose = require("mongoose"); +const validate = require("mongoose-validator"); +const timestamps = require("mongoose-timestamp"); +const paginate = require("mongoose-paginate"); +const winston = require("winston"); + +let eventSchema = new mongoose.Schema({ + groupId: { + type: String, + index: true + }, + userId: { + type: String + }, + type: { + type: String, + index: true, + required: true + }, + text: { + type: String, + required: true + }, + success: { + type: Boolean + } +}); + +eventSchema.pre("save", function (next) { + var currentDate = new Date(); + this.updatedAt = currentDate; + if (!this.createdat) { + this.createdAt = currentDate; + } + next(); +}); + +eventSchema.set("toObject", { + virtuals: true, + getters: true +}); + +eventSchema.set("toJSON", { + virtuals: true +}); + +eventSchema.plugin(timestamps); +eventSchema.plugin(paginate); + +module.exports = mongoose.model("Event", eventSchema); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002384_StatController.js b/pool/shard000/JavaScript/0002384_StatController.js new file mode 100644 index 0000000000000000000000000000000000000000..52cb134bcc2f5e5d061c58effc80591179d4594b --- /dev/null +++ b/pool/shard000/JavaScript/0002384_StatController.js @@ -0,0 +1,57 @@ +/** + * Created by ALEX on 15.04.2017. + */ + +function _StatController() +{ + //current interval + var interval = {}; + var onIntervalChanged = $.Callbacks(); + //event, raised when value changed + this.onIntervalChanged = onIntervalChanged; + this.interval = function(val) + { + if(typeof val != "undefined") + { + //setter + interval = val; + onIntervalChanged.fire(val); + } + return interval; + }; + + var userId = "00000000-0000-0000-0000-000000000000"; + var onUserIdChanged = $.Callbacks(); + this.onUserIdChanged = onUserIdChanged; + this.userId = function (val, silent) { + if(typeof val != 'undefined') + { + //setter + userId = val; + console.log("user id changed to " + val); + if(!silent) + { + onUserIdChanged.fire(val); + } + } + return userId; + }; + var onAnyChanged = $.Callbacks(); + this.onAnyChanged = onAnyChanged; + onIntervalChanged.add(onAnyChanged.fire); + onUserIdChanged.add(onAnyChanged.fire); +} +//singleton XD +StatController = new _StatController(); +//Make user id persistent +function RestoreUserId(){ + var cookie = Cookies.get('stat_userid'); + if(typeof cookie != 'undefined') + { + StatController.userId(cookie, 1); + } + StatController.onUserIdChanged.add(function (value) { + Cookies.set('stat_userid',value); + }) +} +RestoreUserId(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002386_app.js b/pool/shard000/JavaScript/0002386_app.js new file mode 100644 index 0000000000000000000000000000000000000000..8c54ad35226a5c235f8e4250cf8e2d634aa9f8da --- /dev/null +++ b/pool/shard000/JavaScript/0002386_app.js @@ -0,0 +1,22 @@ +var express = require('express'); +var app = express(); +var request = require('request'); + +app.get('/', function (req, res) { + console.log('GET request for /'); + res.render('form.ejs'); +}); + +app.get('/search-results', function (req, res) { + var url = 'http://www.omdbapi.com/?s=' + req.query["term"]; + console.log('GET request for /search-results, s = ' + req.query["term"]); + request(url, function (error, response, body) { + if (!error && response.statusCode == 200) { + res.render('search-results.ejs', {results: JSON.parse(body)["Search"]}); + } + }); +}); + +app.listen(3000, function () { + console.log('movie-app listening on port 3000!'); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002389_clients_list.js b/pool/shard000/JavaScript/0002389_clients_list.js new file mode 100644 index 0000000000000000000000000000000000000000..b2384b016ff867ee5d7db6b5a76d3e515d640589 --- /dev/null +++ b/pool/shard000/JavaScript/0002389_clients_list.js @@ -0,0 +1,79 @@ +Template.clientsList.helpers({ + clients: function() { + return Clients.find({}, {sort: {name: 1}}); + } +}); + +Template.clientsList.events({ + 'click .add-new-client': function(e) { + e.preventDefault(); + $('#editmodal').modal('show'); + $('.form-control').val(''); + $('.form-group').removeClass('has-success'); + // Clear any previously stored clientId value. + $('#clientId').val(''); + }, + 'click .edit': function(e) { + e.preventDefault(); + client = $(e.target).closest('.client'); + clientId = client.attr('data-id'); + if (typeof clientId !== "undefined") { + var client = Clients.findOne(clientId); + $('#clientId').val(client._id); + $('#clientName').val(client.name); + $('#clientUrl').val(client.url); + } + $('.form-group').removeClass('has-success'); + ModalHelper.openModalFor(clientId); + } +}); + +Template.editModalClientTemplate.events({ + 'submit form': function(event) { + + event.preventDefault(); + + var client = { + name: $('#clientName').val(), + url: $('#clientUrl').val().replace(/\W+/g, '-').toLowerCase() + }; + + // Get the clientId from the hidden form field. This will have a value if + // the form was populated from the edit button. + var clientId = $('#clientId').val(); + + console.log(clientId); + + // Fall back to using the client name for the url. + if (client.url == '') { + client.url = client.name.replace(/\W+/g, '-').toLowerCase(); + } + + // Figure out whether this url is unique and if not append a digit to the end. + var searchContext = { + '_id': {$ne: clientId} + }; + client.url = client.url.uniqueUrl(Clients, searchContext); + + if (client.name != '') { + // Check if there is a clientId in which case this is a new Client. + if (!clientId) { + Meteor.call('addClient', client, function (error, result) { + if (error) { + alert(error); + } + }); + } + else { + _.extend(client, {id: clientId}); + Meteor.call('editClient', client, function(error, result) { + if (error) { + alert(error); + } + }); + } + + $('#editmodal').modal('hide'); + } + } +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002393_cli.js b/pool/shard000/JavaScript/0002393_cli.js new file mode 100644 index 0000000000000000000000000000000000000000..6b0da769e367ed1c6b7eb3fe3f152877699e9003 --- /dev/null +++ b/pool/shard000/JavaScript/0002393_cli.js @@ -0,0 +1,94 @@ +#!/usr/bin/env node + +"use strict"; + +const yargs = require("yargs"); +// TESTABILITY: makes yargs throws instead of exiting. +yargs.fail(function(msg) { + let help = yargs.help(); + + if (msg) { + help += "\n" + msg; + } + + throw help; +}); + +// -------------------------------------------------------------------- + +const hashy = require("./"); + +// ==================================================================== + +function main(argv) { + const options = yargs + .usage("Usage: hashy [
    '; + } + } + return str; +} + +// ToDo一覧を取得して表示する +function getList(){ + // すでに表示されている一覧を非表示にして削除する + var $list = $('.list'); + $list.fadeOut(function(){ + $list.children().remove(); + // /todo/data/todolist.name にGETアクセスする + $.get('/todo/data/'+title, function(todos){ + // 取得したToDoを追加していく + var str = taskHtml(todos); + $list.append(str); + // 一覧を表示する + $list.fadeIn(); + }); + }); +} + +function toggleTask(listname,tasktext){ + $.post('/todo/'+listname+'/'+tasktext, {}, function(res){}); +} + + +// フォームに入力されたToDoを追加する +function postTask(){ + // フォームに入力された値を取得 + var name = deldiv($('#text').val()); + var limitDate = new Date($('#limit').val()); + + //入力項目を空にする + $('#text').val(''); + $('#limit').val(''); + + // /todoにPOSTアクセスする + $.post('/todo/task', {list: title, name: name, limit: limitDate}, function(res){ + console.log(res); + //再度表示する + getList(); + }); +} diff --git a/pool/shard000/JavaScript/0002523_script.js b/pool/shard000/JavaScript/0002523_script.js new file mode 100644 index 0000000000000000000000000000000000000000..cefa7d09d968b3e3d1efde93ae425c2572d9700a --- /dev/null +++ b/pool/shard000/JavaScript/0002523_script.js @@ -0,0 +1,74 @@ +var stage = new Kinetic.Stage({ + container: 'canvas-div', + width: 500, + height: 350 +}); + +var canvasWrapper = document.getElementById('canvas-div').firstChild; +canvasWrapper.style.border = '1px solid black'; + +var layer = new Kinetic.Layer(); +var ballsCount = 13; +var balls = []; +var ballsProps = []; +for (var i = 0; i < ballsCount; i++) { + var ball = new Kinetic.Circle({ + x: 16 + Math.random() * (stage.getWidth() - 16), + y: 16 + Math.random() * (stage.getHeight() - 16), + radius: 15, + fill: 'yellow', + stroke: 'purple' + }); + balls.push(ball); + + ballsProps.push({ + dirX: 1, + dirY: 1, + speed: (Math.random() * 5) + }); + + layer.add(ball); +} + +function checkBallsCollision(ball, index) { + return balls.some(function(otherBall, otherIndex) { + var firstX = ball.getX(); + var secondX = otherBall.getX(); + var firstY = ball.getY(); + var secondY = otherBall.getY(); + return (firstX - secondX) * (firstX - secondX) + (firstY - secondY) * (firstY - secondY) - ball.getRadius() * ball.getRadius() * 4 <= 0.000001 && otherIndex !== index; + }); +} + +function animFrame() { + balls.forEach(function(ball, index) { + var x = ball.getX(); + var y = ball.getY(); + var deltaX = ballsProps[index].speed; + var deltaY = ballsProps[index].speed; + if (x > stage.getWidth() - ball.getRadius() || + x < 0 + ball.getRadius() || + checkBallsCollision(ball, index)) { + ballsProps[index].dirX *= -1; + } + if (y > stage.getHeight() - ball.getRadius() || + y < 0 + ball.getRadius() || + checkBallsCollision(ball, index)) { + ballsProps[index].dirY *= -1; + } + + var directionX = ballsProps[index].dirX; + var directionY = ballsProps[index].dirY; + var newX = x + deltaX * directionX; + var newY = y + deltaY * directionY; + + ball.setX(newX); + ball.setY(newY); + }); + layer.draw(); + setTimeout(animFrame, 10); +} + +animFrame(); + +stage.add(layer); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002525_MainFieldPlugin.js b/pool/shard000/JavaScript/0002525_MainFieldPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..66208fcd5c686a81d233a278340462ae37c53eae --- /dev/null +++ b/pool/shard000/JavaScript/0002525_MainFieldPlugin.js @@ -0,0 +1,66 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); + +module.exports = class MainFieldPlugin { + constructor(source, options, target) { + this.source = source; + this.options = options; + this.target = target; + } + + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => { + if (request.path !== request.descriptionFileRoot) return callback(); + if (request.alreadyTriedMainField === request.descriptionFilePath) + return callback(); + const content = request.descriptionFileData; + const filename = path.basename(request.descriptionFilePath); + let mainModule; + const field = this.options.name; + if (Array.isArray(field)) { + let current = content; + for (let j = 0; j < field.length; j++) { + if (current === null || typeof current !== "object") { + current = null; + break; + } + current = current[field[j]]; + } + if (typeof current === "string") { + mainModule = current; + } + } else { + if (typeof content[field] === "string") { + mainModule = content[field]; + } + } + if (!mainModule) return callback(); + if (this.options.forceRelative && !/^\.\.?\//.test(mainModule)) + mainModule = "./" + mainModule; + const obj = Object.assign({}, request, { + request: mainModule, + alreadyTriedMainField: request.descriptionFilePath + }); + return resolver.doResolve( + target, + obj, + "use " + + mainModule + + " from " + + this.options.name + + " in " + + filename, + resolveContext, + callback + ); + }); + } +}; diff --git a/pool/shard000/JavaScript/0002529_win4.js b/pool/shard000/JavaScript/0002529_win4.js new file mode 100644 index 0000000000000000000000000000000000000000..ba61a8fbb51243f38935a979d3d395717ad52ab2 --- /dev/null +++ b/pool/shard000/JavaScript/0002529_win4.js @@ -0,0 +1,104 @@ +var win = Ti.UI.currentWindow; + +win.orientationModes = [Ti.UI.PORTRAIT, Ti.UI.LANDSCAPE_RIGHT]; + +var scrollable = Ti.UI.createScrollableView({ + top:0, + bottom:0, + showPagingControl:true, + pagingControlHeight:20, + pagingControlColor:'#000', + minZoomScale:1.0, + maxZoomScale:3.0 +}); + +var info = [{image:1, urlTop:'', urlBottom:''}, + {image:2, urlTop:'http://www.enjoymagazine.net', urlBottom:'http://www.enjoymagazine.net', nameTop:'Enjoy Magazine', nameBottom:'Enjoy Magazine'}, + {image:3, urlTop:'http://www.bestchoicehome.net/', urlBottom:'http://artbyarmando.com/', nameTop:'Best Choice', nameBottom:'Art by Armando' }, + {image:4, urlTop:'http://www.celebrationredding.com', urlBottom:'http://www.sydneyann.com', nameTop:'Celebration', nameBottom:'Sydney Ann'}, + {image:5, urlTop:'http://www.kendraviolin.com', urlBottom:'http://www.acehardware.com/', nameTop:'Kendra Violin', nameBottom:'Valley Ace', typeTop:'mail'}, + {image:6, urlTop:'http://www.westsideperforming.com', urlBottom:'http://www.riverfrontplayhouse.com', nameTop:'Westside Performing', nameBottom:'Riverfront'}, + {image:7, urlTop:'http://www.cascadetheatre.org', urlBottom:'http://www.frontandcenterdance-spotlight.com/', nameTop:'Cascade Theatre', nameBottom:'Front & Center'}, + {image:8, urlTop:'http://www.copperridgecarecenter.com', urlBottom:'http://www.darlingaccounting.com', nameTop:'Copper Ridge', nameBottom:'Darling Accounting', typeTop:'tel', typeBottom:'mail'}, + {image:9, urlTop:'http://www.cascadetheatre.org', urlBottom:'http://www.cascadetheatre.org', nameTop:'Cascade Theatre', nameBottom:'Cascade Theatre'}, + {image:10, urlTop:'http://www.cascadetheatre.org/Calendar.asp?View=EVENT&EventID=1938&Date=04/06/2012&SectionID=-1', urlBottom:'http://www.cascadetheatre.org/Calendar.asp?View=EVENT&EventID=1938&Date=04/06/2012&SectionID=-1', nameTop:'Hairspray', nameBottom:'Hairspray'} +]; + +var views =[]; +for(var i = 0; i<10; i++){ + var view = Ti.UI.createImageView({ + image:'images/sponsors/'+info[i].image+'.jpg', + urlTop:info[i].urlTop, + urlBottom:info[i].urlBottom, + nameTop:info[i].nameTop, + nameBottom:info[i].nameBottom, + canScale:true, + width:Ti.Platform.displayCaps.platformWidth, + height:'auto' + }); + + + views.push(view); +} + +scrollable.views = views; +win.add(scrollable); + +scrollable.addEventListener('doubletap', function(e){ + + var srcUrl; + var srcName; + if(e.y { + let state; + beforeEach(() => { + state = fromJS({ + projectId: '', + title: 'project title', + description: 'project Description', + metadata: { + key1: 'value1', + key2: 'value2', + key3: { + key4: 'nested1Value1', + key5: 'nested1Value2', + key6: { + key7: 'nested2Value1', + }, + }, + }, + dataset: { + }, + }); + }); + it('returns the initial state', () => { + expect(projectPageReducer(undefined, {})).toEqual(state); + }); + it('modifies project title correctly', () => { + const mockProjectTitle = 'mockProjectTitle'; + const expectedResult = state.set('title', mockProjectTitle); + const receivedResult = projectPageReducer(state, makeProjectPageTitle(mockProjectTitle)).set('title', mockProjectTitle); + expect(receivedResult).toEqual(expectedResult); + }); + it('modifies project id correctly', () => { + const mockProjectId = '1'; + const expectedResult = state.set('projectId', mockProjectId); + expect(projectPageReducer(state, makeProjectPageId(mockProjectId)).set('projectId', mockProjectId)).toEqual(expectedResult); + }); + it('modifies project description correctly', () => { + const mockProjectDescription = 'mockProjectDescription'; + const expectedResult = state.set('description', mockProjectDescription); + expect(projectPageReducer(state, makeProjectPageDescription(mockProjectDescription)).set('description', mockProjectDescription)).toEqual(expectedResult); + }); + it('modifies project meta data correctly', () => { + const mockProjectMetaData = { + projectId: '', + title: 'project title', + description: 'project Description', + metadata: { + key1: 'keyValue 1 for testing', + key2: 'value2 key for testing', + key3: { + key4: 'nested1Value1 testing', + key5: 'nested1Value2 testing', + key6: { + key7: 'nested2Value1 testing', + }, + }, + }, + + }; + const expectedResult = state.set('metadata', mockProjectMetaData); + expect(projectPageReducer(state, makeProjectPageMetaData(mockProjectMetaData)).set('metadata', mockProjectMetaData)).toEqual(expectedResult); + }); + }); diff --git a/pool/shard000/JavaScript/0002536_bridge.js b/pool/shard000/JavaScript/0002536_bridge.js new file mode 100644 index 0000000000000000000000000000000000000000..beb1667685d35f2d64371d2ad8a91908adac4d00 --- /dev/null +++ b/pool/shard000/JavaScript/0002536_bridge.js @@ -0,0 +1,97 @@ +/** + * + * A bridge between a web browser and sclang + * ========================================= + * + * websockets <-> OSC + * + * Adds socket.io to an express app server + * + * Serves socket.io and scapi.js + * + * Connects with sclang using OSC + * + * Listens for websocket connections and relays + * calls to sclang, returns responses to the websocket client + * + * Usage:: + * bridge = require('supercolliderjs-browser').bridge; + * app = express(), + * server = http.createServer(app), + * bridge.listen(app, server); + * + * params: + * app: an express app + * server: an http server created by express + * io: optional socket.io connection + * You may pass in an already existing one + * that is shared with other parts of your application + * schost: host that sclang is listening on [default=localhost] + * scport: port that sclang is listenting on [default=57120] + * scapiJsUrl: the URL that your web page will use to retreive + * the browser version of scapi.js + * [default=/static/scapi.js] + */ + +var + join = require('path').join, + socketio = require('socket.io'), + express = require('express'), + SCAPI = require('./scapi'); + + +module.exports = {}; + +module.exports.listen = function(app, server, io, schost, scport, scapiJsUrl) { + + this.schost = schost ? schost : 'localhost'; + this.scport = scport ? scport : 57120; + + // hold these so you can unlisten + var self = this, + scapi = new SCAPI(this.schost, this.scport); + + + if (!io) { + io = socketio.listen(server); + } + + // connect to supercollider + scapi.connect(); + + // handle any errors outside of call/response requests + scapi.on('error', function(err) { + console.error('Out of band scapi error', err); + }); + + // serve the client side javascript + app.get(scapiJsUrl || '/static/js/scapi.js', function (req, res) { + res.sendFile(join(__dirname, '../browser/scapi.js')); + }); + + // serve socket.io directory which includes various resources + // like flash fallbacks + app.use('/socket.io', + express.static(__dirname + '../node_modules/socket.io/lib')); + + // listen to incoming websockets + io.sockets.on('connection', function(socket) { + socket.on('call', function (data) { + // communicate with sclang + var requestId = data['request_id']; + scapi.call(requestId, data.path, data.args) + .then(function(response) { + socket.emit('reply', { + 'request_id': requestId, + 'result': response.result + }); + }, function(err) { + socket.emit('scapi_error', { + 'request_id': requestId, + 'result': err.result + }); + }); + }); + }); + +}; diff --git a/pool/shard000/JavaScript/0002537_UADataItem.js b/pool/shard000/JavaScript/0002537_UADataItem.js new file mode 100644 index 0000000000000000000000000000000000000000..0311c020a502abd613b674711284ed595fb16b5f --- /dev/null +++ b/pool/shard000/JavaScript/0002537_UADataItem.js @@ -0,0 +1,74 @@ +"use strict"; +// Release 1.02 5 OPC Unified Architecture, Part 8 + +// HasProperty Variable Definition String PropertyType Optional +// HasProperty Variable ValuePrecision Double PropertyType Optional + +// Clients may read or write DataItems, or monitor them for value changes. The services needed for +// these operations are specified in Part 4. Changes are defined as a change in status (quality) or a +// change in value that exceeds a client - defined range called a Deadband. To detect the value change, +// the difference between the current value and the last reported value is compared to the Deadband. + + +// Definition is a vendor - specific, human readable string that specifies how the value of this DataItem is +// calculated. Definition is non - localized and will often contain an equation that can be parsed by +// certain clients. +// Example: Definition ::= “(TempA – 25) + TempB” + + +// ValuePrecision specifies the maximum precision that the server can maintain for the item based on +// restrictions in the target environment. +// ValuePrecision can be used for the following DataTypes: +// * For Float and Double values it specifies the number of digits after the decimal place. +// * For DateTime values it indicates the minimum time difference in nanoseconds. For example, +// a ValuePrecision of 20 000 000 defines a precision of 20 ms. +// The ValuePrecision Property is an approximation that is intended to prov ide guidance to a Client. A +// Server is expected to silently round any value with more precision that it supports. This implies that +// a Client may encounter cases where the value read back from a Server differs from the value that it +// wrote to the Server. This difference shall be no more than the difference suggested by this Property +require("requirish")._(module); +var assert = require("assert"); +var address_space = require("lib/address_space/address_space"); +var AddressSpace = address_space.AddressSpace; +var DataType = require("lib/datamodel/variant").DataType; +var Variant = require("lib/datamodel/variant").Variant; +var _ = require("underscore"); + +var definition_Description = "Definition is a vendor - specific, human readable string that specifies how the value of this DataItem is calculated."; +var valuePrecision_Description = ""; + + +function add_dataItem_stuff(variable,options) { + + var address_space = variable.__address_space; + assert(address_space instanceof AddressSpace); + + if (options.hasOwnProperty("definition")) { + + variable.$definition = new Variant({ dataType: DataType.String, value: options.definition}); + + address_space.addVariable(variable,{ + browseName:"Definition", + description: definition_Description, + dataType: "String", + typeDefinition: "PropertyType", + value: { get: function() { return variable.$definition; }} + }); + } + + if (options.hasOwnProperty("valuePrecision")) { + + assert(_.isNumber(options.valuePrecision)); + variable.$valuePrecision = new Variant({ dataType: DataType.Double, value: options.valuePrecision}); + + address_space.addVariable(variable,{ + browseName:"ValuePrecision", + description: valuePrecision_Description, + dataType: "Number", + typeDefinition: "PropertyType", + value: { get: function() { return variable.$valuePrecision; }} + }); + } +} +exports.add_dataItem_stuff = add_dataItem_stuff; + diff --git a/pool/shard000/JavaScript/0002539_attractor.js b/pool/shard000/JavaScript/0002539_attractor.js new file mode 100644 index 0000000000000000000000000000000000000000..beefb4112676118b2e2c5a9547b2be0201a1775d --- /dev/null +++ b/pool/shard000/JavaScript/0002539_attractor.js @@ -0,0 +1,126 @@ +/** + * PhysicsJS v0.6.0 - 2014-04-22 + * A modular, extendable, and easy-to-use physics engine for javascript + * http://wellcaffeinated.net/PhysicsJS + * + * Copyright (c) 2014 Jasper Palfree + * Licensed MIT + */ +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + define(['physicsjs'], factory); + } else if (typeof exports === 'object') { + module.exports = factory.apply(root, ['physicsjs'].map(require)); + } else { + factory.call(root, root.Physics); + } +}(this, function (Physics) { + 'use strict'; + /** + * class AttractorBehavior < Behavior + * + * `Physics.behavior('attractor')`. + * + * Attractor behavior attracts bodies to a specific point. + * + * Additional options include: + * - pos: The position of the attraction point + * - strength: How strong the attraction is (default: `1`) + * - order: The power of the inverse distance (default: `2` because that is newtonian gravity... inverse square) + * - max: The maximum distance in which to apply the attraction (default: Infinity) + * - min: The minimum distance above which to apply the attraction (default: very small non-zero) + **/ + Physics.behavior('attractor', function( parent ){ + + var defaults = { + + pos: null, // default to (0, 0) + // how strong the attraction is + strength: 1, + // power of the inverse distance (2 is inverse square) + order: 2, + // max distance to apply it to + max: false, // infinite + // min distance to apply it to + min: false // auto calc + }; + + return { + + // extended + init: function( options ){ + + var self = this; + this._pos = new Physics.vector(); + // call parent init method + parent.init.call( this ); + this.options.defaults( defaults ); + this.options.onChange(function( opts ){ + self._maxDist = opts.max === false ? Infinity : opts.max; + self._minDist = opts.min ? opts.min : 10; + self.position( opts.pos ); + }); + this.options( options ); + }, + + /** + * AttractorBehavior#position( [pos] ) -> this|Object + * - pos (Vectorish): The position to set + * + (Object): Returns the [[Vectorish]] position if no arguments provided + * + (this): For chaining + * + * Get or set the position of the attractor. + **/ + position: function( pos ){ + + var self = this; + + if ( pos ){ + this._pos.clone( pos ); + return self; + } + + return this._pos.values(); + }, + + // extended + behave: function( data ){ + + var bodies = this.getTargets() + ,body + ,order = this.options.order + ,strength = this.options.strength + ,minDist = this._minDist + ,maxDist = this._maxDist + ,scratch = Physics.scratchpad() + ,acc = scratch.vector() + ,norm + ,g + ; + + for ( var j = 0, l = bodies.length; j < l; j++ ){ + + body = bodies[ j ]; + + // clone the position + acc.clone( this._pos ); + acc.vsub( body.state.pos ); + // get the distance + norm = acc.norm(); + + if (norm > minDist && norm < maxDist){ + + g = strength / Math.pow(norm, order); + + body.accelerate( acc.normalize().mult( g ) ); + } + } + + scratch.done(); + } + }; + }); + + // end module: behaviors/attractor.js + return Physics; +}));// UMD \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002541_image_writer_private_custom_bindings.js b/pool/shard000/JavaScript/0002541_image_writer_private_custom_bindings.js new file mode 100644 index 0000000000000000000000000000000000000000..5ca3200a0b4a62264750d86cdd6904144b4be2db --- /dev/null +++ b/pool/shard000/JavaScript/0002541_image_writer_private_custom_bindings.js @@ -0,0 +1,20 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Custom binding for the image writer private API. + +var binding = require('binding').Binding.create('imageWriterPrivate'); + +binding.registerCustomHook(function(bindingsAPI) { + var apiFunctions = bindingsAPI.apiFunctions; + + apiFunctions.setUpdateArgumentsPostValidate( + 'writeFromFile', function(device, fileEntry, options, callback) { + var fileSystemName = fileEntry.filesystem.name; + var relativePath = $String.slice(fileEntry.fullPath, 1); + return [device, fileSystemName, relativePath, callback]; + }); +}); + +exports.binding = binding.generate(); diff --git a/pool/shard000/JavaScript/0002554_dashboard-form-data-resolve.js b/pool/shard000/JavaScript/0002554_dashboard-form-data-resolve.js new file mode 100644 index 0000000000000000000000000000000000000000..16586bd24b43daf61d23e3c43136d43ecf9e7161 --- /dev/null +++ b/pool/shard000/JavaScript/0002554_dashboard-form-data-resolve.js @@ -0,0 +1,71 @@ +/* + * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting. + * + * Copyright (C) 2015 John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4. + * + * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + */ +ResolveDashboardFormData = { + programsList : function($q, $timeout, $rootScope, UserSupervisedActivePrograms){ + var deferred = $q.defer(); + $timeout(function () { + + UserSupervisedActivePrograms.get(function(data){ + deferred.resolve(data.programs); + + }); + + },100); + + return deferred.promise; + + }, + formInputValue : function(messageService){ + return { + yearOptionAll : messageService.get('input.year.option.all'), + programOptionSelect : messageService.get('input.program.option.select'), + scheduleOptionSelect : messageService.get('input.schedule.option.select'), + geographicZoneNational : messageService.get('input.geographic.zone.national'), + facilityOptionSelect : messageService.get('input.facility.option.select'), + periodOptionSelect : messageService.get('input.period.option.select') + }; + }, + userPreferredFilters : function(GetPeriod,localStorageService){ + var date = new Date(); + var filterObject = {}; + var preferredFilterValues = {}; + for(var prefKey in localStorageKeys.PREFERENCE){ + preferredFilterValues[localStorageKeys.PREFERENCE[prefKey]] = localStorageService.get(localStorageKeys.PREFERENCE[prefKey]); + } + + filterObject.programId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PROGRAM]; + filterObject.periodId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PERIOD]; + + if(!isUndefined(filterObject.periodId)){ + + GetPeriod.get({id:filterObject.periodId}, function(period){ + if(!isUndefined(period.year)){ + filterObject.year = period.year; + }else{ + filterObject.year = date.getFullYear() - 1; + } + }); + } + filterObject.scheduleId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_SCHEDULE]; + + filterObject.zoneId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_GEOGRAPHIC_ZONE]; + + filterObject.productIdList = !isUndefined(preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PRODUCTS]) ? preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_PRODUCTS].split(',') : null; + + filterObject.facilityId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_FACILITY]; + + filterObject.facilityId = preferredFilterValues[localStorageKeys.PREFERENCE.DEFAULT_FACILITY]; + + + return filterObject; + } +}; diff --git a/pool/shard000/JavaScript/0002556_preventExtensions.js b/pool/shard000/JavaScript/0002556_preventExtensions.js new file mode 100644 index 0000000000000000000000000000000000000000..a32f71f376be7e832de04415c015966179806daa --- /dev/null +++ b/pool/shard000/JavaScript/0002556_preventExtensions.js @@ -0,0 +1,132 @@ +description( +"This test checks whether various seal/freeze/preventExtentions work on a regular object." +); + +function obj() +{ + // Add an accessor property to check 'isFrozen' returns the correct result for objects with accessors. + return Object.defineProperty({ a: 1, b: 2 }, 'g', { get: function() { return "getter"; } }); +} + +function test(obj) +{ + obj.c =3; + obj.b =4; + delete obj.a; + + var result = ""; + for (key in obj) + result += ("(" + key + ":" + obj[key] + ")"); + if (Object.isSealed(obj)) + result += "S"; + if (Object.isFrozen(obj)) + result += "F"; + if (Object.isExtensible(obj)) + result += "E"; + return result; +} + +function seal(obj) +{ + Object.seal(obj); + return obj; +} + +function freeze(obj) +{ + Object.freeze(obj); + return obj; +} + +function preventExtensions(obj) +{ + Object.preventExtensions(obj); + return obj; +} + +function inextensible(){} +function sealed(){} +function frozen(){}; +preventExtensions(inextensible); +seal(sealed); +freeze(frozen); +new inextensible; +new sealed; +new frozen; +inextensible.prototype.prototypeExists = true; +sealed.prototype.prototypeExists = true; +frozen.prototype.prototypeExists = true; + +shouldBeTrue("(new inextensible).prototypeExists"); +shouldBeTrue("(new sealed).prototypeExists"); +shouldBeTrue("(new frozen).prototypeExists"); + +shouldBe('test(obj())', '"(b:4)(c:3)E"'); // extensible, can delete a, can modify b, and can add c +shouldBe('test(preventExtensions(obj()))', '"(b:4)"'); // , can delete a, can modify b, and CANNOT add c +shouldBe('test(seal(obj()))', '"(a:1)(b:4)S"'); // sealed, CANNOT delete a, can modify b, and CANNOT add c +shouldBe('test(freeze(obj()))', '"(a:1)(b:2)SF"'); // sealed and frozen, CANNOT delete a, CANNOT modify b, and CANNOT add c + +// check that we can preventExtensions on a host function. +shouldBe('Object.preventExtensions(Math.sin)', 'Math.sin'); + +shouldThrow('var o = {}; Object.preventExtensions(o); o.__proto__ = { newProp: "Should not see this" }; o.newProp;'); +shouldThrow('"use strict"; var o = {}; Object.preventExtensions(o); o.__proto__ = { newProp: "Should not see this" }; o.newProp;'); + +// check that we can still access static properties on an object after calling preventExtensions. +shouldBe('Object.preventExtensions(Math); Math.sqrt(4)', '2'); + +// Should not be able to add properties to a preventExtensions array. +shouldBeUndefined('var arr = Object.preventExtensions([]); arr[0] = 42; arr[0]'); +shouldBe('var arr = Object.preventExtensions([]); arr[0] = 42; arr.length', '0'); +// In strict mode, this throws. +shouldThrow('"use strict"; var arr = Object.preventExtensions([]); arr[0] = 42; arr[0]'); + +// A read-only property on the prototype should prevent a [[Put]] . +function Constructor() {} +Constructor.prototype.foo = 1; +Object.freeze(Constructor.prototype); +var obj = new Constructor(); +obj.foo = 2; +shouldBe('obj.foo', '1'); + +// Check that freezing a function works correctly. +var func = freeze(function foo(){}); +shouldBeTrue('Object.isFrozen(func)') +func.prototype = 42; +shouldBeFalse('func.prototype === 42'); +shouldBeFalse('Object.getOwnPropertyDescriptor(func, "prototype").writable') + +// Check that freezing a strict function works correctly. +var strictFunc = freeze(function foo(){ "use strict"; }); +shouldBeTrue('Object.isFrozen(strictFunc)') +strictFunc.prototype = 42; +shouldBeFalse('strictFunc.prototype === 42'); +shouldBeFalse('Object.getOwnPropertyDescriptor(strictFunc, "prototype").writable') + +// Check that freezing array objects works correctly. +var array = freeze([0,1,2]); +shouldBeTrue('Object.isFrozen(array)') +array[0] = 3; +shouldBe('array[0]', '0'); +shouldBeFalse('Object.getOwnPropertyDescriptor(array, "length").writable') + +// Check that freezing arguments objects works correctly. +var args = freeze((function(){ return arguments; })(0,1,2)); +shouldBeTrue('Object.isFrozen(args)') +args[0] = 3; +shouldBe('args[0]', '0'); +shouldBeFalse('Object.getOwnPropertyDescriptor(args, "length").writable') +shouldBeFalse('Object.getOwnPropertyDescriptor(args, "callee").writable') + +// Check that freeze still works if preventExtensions has been called on the object. +function preventExtensionsFreezeIsFrozen(x) +{ + Object.preventExtensions(x); + Object.freeze(x); + return Object.isFrozen(x); +} +shouldBeTrue('preventExtensionsFreezeIsFrozen(function foo(){})') +shouldBeTrue('preventExtensionsFreezeIsFrozen(function foo(){ "use strict"; })') +shouldBeTrue('preventExtensionsFreezeIsFrozen([0,1,2])') +shouldBeTrue('preventExtensionsFreezeIsFrozen((function(){ return arguments; })(0,1,2))') + diff --git a/pool/shard000/JavaScript/0002562_HomeController.js b/pool/shard000/JavaScript/0002562_HomeController.js new file mode 100644 index 0000000000000000000000000000000000000000..7a308dbfa2449682e9f21f3d7ac861e4b8dc8a17 --- /dev/null +++ b/pool/shard000/JavaScript/0002562_HomeController.js @@ -0,0 +1,79 @@ +(function () { + 'use strict'; + angular.module('app').controller('ParentHomeController', [ + '$modal', 'ChildService', 'AdmissionService', + function ($modal, ChildService, AdmissionService) { + var self = this; + init(); + + self.action = function (actionName, childId) { + switch (actionName) { + case 'agenda': + showAgenda(); + break; + case 'absences': + showAbsences(childId || null); + break; + case 'admin': + showAdmin(); + break; + } + } + + function showAgenda() { + var modalInstance = $modal.open({ + animation: true, + templateUrl: 'WebApp/views/modal/agendaModal.html', + controller: 'AgendaModalController as modal', + }); + modalInstance.result.then(function (success) { + + }, function (error) { + }); + } + + function showAbsences(childId) { + var modalInstance = $modal.open({ + animation: true, + size: 'lg', + templateUrl: 'WebApp/views/modal/addAbsenceModal.html', + controller: 'AddAbsenceModalController as modal', + resolve: { + items: function () { + return { + childId: childId + }; + } + } + }); + modalInstance.result.then(function (success) { + + }, function (error) { + }); + + } + + function showAdmin() { + var modalInstance = $modal.open({ + animation: true, + templateUrl: 'WebApp/views/modal/parentAdministrationModal.html', + controller: 'ParentAdministrationModalController as modal', + }); + modalInstance.result.then(function (item) { + AdmissionService.save(item); + }, function (error) { + }); + } + + function init() { + + //self.children = ["Emmanuelle di Nicola", "Yves Cotton", "Mathieu Wautier"] + ChildService.getChildren().then(function (data) { + self.children = data.data; + }); + } + } + ]); +} + +)(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002563_lang.js b/pool/shard000/JavaScript/0002563_lang.js new file mode 100644 index 0000000000000000000000000000000000000000..9175cfa059fca0c52e1e27d402e48a51b5336e02 --- /dev/null +++ b/pool/shard000/JavaScript/0002563_lang.js @@ -0,0 +1,67 @@ +var Vue = require('vue'); +var VueI18n = require('vue-i18n'); + +const locales = { + en: { + message: { + name: 'HUE Alarm', + menu_status: 'Status', + menu_configuration: 'Configuration', + config_activation: 'Activation', + config_part_of_schedule_name: 'Trigger by part of schedule name', + config_username: 'HUE username', + config_primary_notification_settings: 'Primary notification settings', + config_primary_notification_url: 'Notification URL (GET)', + config_primary_notification_speed: 'Notification speed (seconds)', + config_primary_notification_test_mode: 'Test mode', + config_primary_notification_test: 'Test notification', + config_secondary_notification_settings: 'Secundary notification settings', + config_smtp_password: "SMTP password", + config_smtp_server_name: "SMTP server name", + config_smtp_port: "SMTP port", + config_from: "FROM email address", + config_to: "TO email address", + config_message: "Message", + enabled: "Enabled", + config_admin_password: "Admin password", + config_admin_username: "Admin username", + config_administration: "Administration" + } + }, + nl: { + message: { + name: 'HUE Alarm', + menu_status: 'Status', + menu_configuration: 'Instellingen', + config_activation: 'Activering', + config_part_of_schedule_name: 'Activeer door woord in routine naam', + config_username: 'HUE gebruikersnaam', + config_primary_notification_settings: 'Hoofd notificatie instellingen', + config_primary_notification_url: 'Notificatie URL (GET)', + config_primary_notification_speed: 'Notification snelheid (seconden)', + config_primary_notification_test_mode: 'Test modus', + config_primary_notification_test: 'Test notificatie', + config_secondary_notification_settings: 'Secundaire notificatie instellingen', + config_smtp_password: 'SMTP wachtwoord', + config_smtp_server_name: "SMTP server naam", + config_smtp_port: "SMTP poort", + config_from: "FROM email adres", + config_to: "TO email adres", + config_message: "Informatie", + enabled: "Enabled", + config_admin_password: "Admin wachtwoord", + config_admin_username: "Admin gebruikersnaam", + config_administration: "Beheer" + + } + } + }; + +export function activateLanguage() { + Vue.use(VueI18n); + Vue.config.lang = 'en'; + + Object.keys(locales).forEach(function (lang) { + Vue.locale(lang, locales[lang]) + }); +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002564_App.js b/pool/shard000/JavaScript/0002564_App.js new file mode 100644 index 0000000000000000000000000000000000000000..5882d227506add58c96c89805985bbec7a0bc0cd --- /dev/null +++ b/pool/shard000/JavaScript/0002564_App.js @@ -0,0 +1,93 @@ +import React, { Component, PropTypes } from 'react'; +import { connect } from 'react-redux'; + +import styles from 'styles/base.scss'; + +import { + ALL_ROUTES_PATH, + ROUTE_PATH, + DIRECTION_PATH, + SAVED_PATH, +} from 'constants/Paths'; + +import MapLayer from 'components/Map'; +import RouteList from 'components/RouteList'; +import StopList from 'components/StopList'; +import NavBar from 'components/NavBar'; +import Saved from 'components/Saved'; +import VehiclesLoading from 'components/VehiclesLoading'; + +import { getRoutes, getVehicles, initialVehiclesLoaded } from 'actions/oba'; +import { restoreSavedRoutes } from 'actions/saved'; + + +class App extends Component { + static propTypes = { + globalError: PropTypes.string, + route: PropTypes.object, + getRoutes: PropTypes.func, + getVehicles: PropTypes.func, + initialVehiclesLoaded: PropTypes.func, + restoreSavedRoutes: PropTypes.func.isRequired, + } + + componentDidMount() { + this.props.restoreSavedRoutes(); + + this.props.getVehicles().then(() => { + this.props.initialVehiclesLoaded(); + }); + this.watchVehicles = setInterval(this.props.getVehicles, 30000); + } + + componentWillUnmount() { + clearInterval(this.watchVehicles); + } + + _renderGlobalError = () =>
    {this.props.globalError}
    ; + + _renderGlobalError() { + return
    {this.props.globalError}
    ; + } + + _renderContext = () => { + const name = this.props.route.name; + switch (name) { + case ALL_ROUTES_PATH: + return ; + case ROUTE_PATH: + return ; + case DIRECTION_PATH: + return ; + case SAVED_PATH: + return ; + default: + return null; + } + } + + render() { + return ( +
    + + + + { this._renderContext() } +
    + ); + } +} + +const mapDispatchToProps = { + getRoutes, + getVehicles, + initialVehiclesLoaded, + restoreSavedRoutes, +}; + +const mapStateToProps = (state) => ({ + globalError: state.ui.globalError, + route: state.ui.route, +}); + +export default connect(mapStateToProps, mapDispatchToProps)(App); diff --git a/pool/shard000/JavaScript/0002565_serve.js b/pool/shard000/JavaScript/0002565_serve.js new file mode 100644 index 0000000000000000000000000000000000000000..53bc464b7822e0da0fb27644647e1637f1d0995d --- /dev/null +++ b/pool/shard000/JavaScript/0002565_serve.js @@ -0,0 +1,39 @@ +module.exports = function (gulp, plugins, config, env) { + const browserSync = require('browser-sync'); + + function getTask(task) { + return require('./tasks/' + task)(gulp, plugins, config, env); + } + + gulp.task('ws', () => + browserSync(config.browsersync) + ); + + gulp.task('watch:html', () => + gulp.watch(config.src.html, + gulp.parallel(getTask('html')) + ) + ); + + gulp.task('watch:javascript', () => + gulp.watch(config.src.javascript, + gulp.parallel(getTask('eslint'), getTask('javascript')) + ) + ); + + gulp.task('watch:styles', () => + gulp.watch(config.src.sass, + gulp.parallel(getTask('sasslint'), getTask('sass')) + ) + ); + + gulp.task('watch:json', () => + gulp.watch(config.src.json, + gulp.parallel(getTask('jsonMinify')) + ) + ); + + gulp.task('watch', + gulp.parallel('watch:html', 'watch:styles', 'watch:javascript', 'watch:json') + ); +}; diff --git a/pool/shard000/JavaScript/0002566_hexahedron.js b/pool/shard000/JavaScript/0002566_hexahedron.js new file mode 100644 index 0000000000000000000000000000000000000000..07bc5dd0d4ac4aeff5b61384777c744437fb2a8e --- /dev/null +++ b/pool/shard000/JavaScript/0002566_hexahedron.js @@ -0,0 +1,29 @@ +let Hexahedron = function () { + let _ = Object.create(Primitive); + + _.name = "cube"; + + _.getShapeBuilder = function () { + let builder = ShapeBuilder.new(); + + builder.addVertex([-1, -1, -1]); + builder.addVertex([-1, 1, -1]); + builder.addVertex([1, 1, -1]); + builder.addVertex([1, -1, -1]); + builder.addVertex([-1, -1, 1]); + builder.addVertex([-1, 1, 1]); + builder.addVertex([1, 1, 1]); + builder.addVertex([1, -1, 1]); + + builder.addFace([0, 1, 2, 0, 2, 3]); // Front face + builder.addFace([7, 6, 5, 7, 5, 4]); // Back face + builder.addFace([1, 5, 6, 1, 6, 2]); // Top face + builder.addFace([4, 0, 3, 4, 3, 7]); // Bottom face + builder.addFace([4, 5, 1, 4, 1, 0]); // Left face + builder.addFace([3, 2, 6, 3, 6, 7]); // Right face + + return builder; + }; + + return _; +}(); diff --git a/pool/shard000/JavaScript/0002567_AllocationTopbar.js b/pool/shard000/JavaScript/0002567_AllocationTopbar.js new file mode 100644 index 0000000000000000000000000000000000000000..7c7419fc5f4564a34f3b683353c405366158626b --- /dev/null +++ b/pool/shard000/JavaScript/0002567_AllocationTopbar.js @@ -0,0 +1,68 @@ +import FontIcon from 'material-ui/FontIcon' +import React, { PureComponent, PropTypes } from 'react' +import { BottomNavigation, BottomNavigationItem } from 'material-ui/BottomNavigation' +import { withRouter } from 'react-router' + +const infoIcon = info_outline +const filesIcon = storage +const logsIcon = subject +const rawIcon = code + +class _AllocationTopbar extends PureComponent { + + handleActive (tab) { + const path = ['nomad', this.props.router.params.region, 'allocations', this.props.allocation.ID, tab] + this.props.router.push(path.map(encodeURIComponent).join('/')) + } + + getActiveTab () { + const location = this.props.location + const end = location.pathname.split('/').pop() + + if (end.startsWith('info')) { + return 0 + } + + if (location.query.path && location.query.path.indexOf('alloc/logs') !== -1) { + return 2 + } + + if (end.startsWith('files')) { + return 1 + } + + if (end.startsWith('raw')) { + return 3 + } + + return 0 + } + + getStyle () { + return { + borderBottom: '1px solid #e0e0e0', + marginBottom: 10 + } + } + + render () { + return ( + + this.handleActive('info') } /> + this.handleActive('files') } /> + this.handleActive('logs') } /> + this.handleActive('raw') } /> + + ) + } +} + +_AllocationTopbar.propTypes = { + router: PropTypes.object.isRequired, + location: PropTypes.object.isRequired, + allocation: PropTypes.object.isRequired +} + +const AllocationTopbar = withRouter(_AllocationTopbar) + +export default AllocationTopbar diff --git a/pool/shard000/JavaScript/0002570_ChooseBaseLayoutWindow.js b/pool/shard000/JavaScript/0002570_ChooseBaseLayoutWindow.js new file mode 100644 index 0000000000000000000000000000000000000000..03387abb1d7d7a2084c6f051b9869d20d408836c --- /dev/null +++ b/pool/shard000/JavaScript/0002570_ChooseBaseLayoutWindow.js @@ -0,0 +1,100 @@ +Ext.ns('CMS.structureEditor'); + +/** + * @class CMS.structureEditor.ChooseBaseLayoutWindow + * @extends CMS.MainWindow + * Window for choosing the base layout + */ +CMS.structureEditor.ChooseBaseLayoutWindow = Ext.extend(CMS.MainWindow, { + cls: 'CMSchoosebaselayoutwindow', + modal: true, + border: false, + resizable: false, + closable: false, + maxWidth: 1100, + + callback: null, + + scope: null, + + baseLayouts: null, + + initComponent: function () { + this.title = CMS.i18n(null, 'templateStructureEditor.chooseBaseLayout.title'); + var store = new Ext.data.JsonStore({ + autoDestroy: true, + fields: [ + {name: 'id', type: 'string'}, + {name: 'name', type: 'string'}, + {name: 'previewImageUrl', type: 'string'}, + {name: 'type', type: 'string'} + ] + }); + store.sort([{ + field: 'type', + direction: 'DESC' + }, { + field: 'id', + direction: 'ASC' + }], 'ASC'); + store.loadData(this.baseLayouts); + var tpl = new Ext.XTemplate( + '', + '
    ', + '
    ', + '
    {[values.name]}
    ', + '
    ', + '
    ', + '' + ); + Ext.apply(this, { + layout: 'fit', + items: [{ + xtype: 'CMSthumbview', + itemSelector: 'div.baselayout-wrap', + overClass: 'hover', + selectedClass: 'selected', + singleSelect: true, + tpl: tpl, + store: store, + + ref: 'thumbView', + trackOver: true, + scrollOffset: 10, + listeners: { + click: this.clickHandler, + scope: this + } + }] + }); + CMS.structureEditor.ChooseBaseLayoutWindow.superclass.initComponent.apply(this, arguments); + }, + + clickHandler: function (dataView) { + var baseLayout = dataView.getSelectedRecords()[0].data; + this.executeCallback(baseLayout); + this.destroy(); + }, + + /** + * @private + * + * Executes the callback function if set with the given param + * + * @param {Object} baseLayout + */ + executeCallback: function (baseLayout) { + //execute handler function + if (this.callback) { + this.callback.call(this.scope || window, baseLayout, this); + } + }, + + destroy: function () { + this.templateSnippetStore = null; + + CMS.structureEditor.ChooseBaseLayoutWindow.superclass.destroy.apply(this, arguments); + } +}); + +Ext.reg('CMSchoosebaselayoutwindow', CMS.structureEditor.ChooseBaseLayoutWindow); diff --git a/pool/shard000/JavaScript/0002572_atom-alopex-view.js b/pool/shard000/JavaScript/0002572_atom-alopex-view.js new file mode 100644 index 0000000000000000000000000000000000000000..5d31c2771a1c07de12bc6c4cb9af3fe8b61fede8 --- /dev/null +++ b/pool/shard000/JavaScript/0002572_atom-alopex-view.js @@ -0,0 +1,29 @@ +'use babel'; + +export default class AtomAlopexView { + + constructor(serializedState) { + // Create root element + this.element = document.createElement('div'); + this.element.classList.add('atom-alopex'); + + // Create message element + const message = document.createElement('div'); + message.textContent = 'The AtomAlopex package is Alive! It\'s ALIVE!'; + message.classList.add('message'); + this.element.appendChild(message); + } + + // Returns an object that can be retrieved when package is activated + serialize() {} + + // Tear down any state and detach + destroy() { + this.element.remove(); + } + + getElement() { + return this.element; + } + +} diff --git a/pool/shard000/JavaScript/0002577_ionicUpdate.js b/pool/shard000/JavaScript/0002577_ionicUpdate.js new file mode 100644 index 0000000000000000000000000000000000000000..eb905b6e4f228bcf1eebcccd239d33baf64b877e --- /dev/null +++ b/pool/shard000/JavaScript/0002577_ionicUpdate.js @@ -0,0 +1,122 @@ +angular.module('ionic.services.update', ['ionic.services.common']) + +/** + * @ngdoc service + * @name $ionicUpdate + * @module ionic.services.update + * @description + * + * A simple way to push updates to your app. + * + * Initialize the service with your app id before calling other functions. + * Then, use the check, download, extract and load functions to update and/or load + * the updated version of your app. + * + * @usage + * ```javascript + * $ionicUpdate.initialize('8cdd99a2'); + * + * // Check for updates + * $ionicUpdate.check().then(function(response) { + * // response will be true/false + * if (response) { + * // Download the updates + * $ionicUpdate.download().then(function() { + * // Extract the updates + * $ionicUpdate.extract().then(function() { + * // Load the updated version + * $ionicTrack.load(); + * }, function(error) { + * // Error extracting + * }, function(progress) { + * // Do something with the zip extraction progress + * $scope.extraction_progress = progress; + * }); + * }, function(error) { + * // Error downloading the updates + * }, function(progress) { + * // Do something with the download progress + * $scope.download_progress = progress; + * }); + * } + * } else { + * // No updates, load the most up to date version of the app + * $ionicUpdate.load(); + * }, function(error) { + * // Error checking for updates + * }) + * ``` + */ +.factory('$ionicUpdate', [ + '$q', + function($q) { + return { + check: function() { + var deferred = $q.defer(); + + if (typeof IonicUpdate != "undefined") { + IonicUpdate.check(function(result) { + deferred.resolve(result === 'true'); + }, function(error) { + deferred.reject(error); + }); + } else { + deferred.reject("Plugin not loaded"); + } + + return deferred.promise; + }, + + download: function() { + var deferred = $q.defer(); + + if (typeof IonicUpdate != "undefined") { + IonicUpdate.download(function(result) { + if (result !== 'true' && result !== 'false') { + deferred.notify(result); + } else { + deferred.resolve(result === 'true'); + } + }, function(error) { + deferred.reject(error); + }); + } else { + deferred.reject("Plugin not loaded"); + } + + return deferred.promise; + }, + + extract: function() { + var deferred = $q.defer(); + + if (typeof IonicUpdate != "undefined") { + IonicUpdate.extract(function(result) { + if (result !== 'done') { + deferred.notify(result); + } else { + deferred.resolve(result); + } + }, function(error) { + deferred.reject(error); + }); + } else { + deferred.reject("Plugin not loaded"); + } + + return deferred.promise; + }, + + load: function() { + if (typeof IonicUpdate != "undefined") { + IonicUpdate.redirect(); + } + }, + + initialize: function(app_id) { + if (typeof IonicUpdate != "undefined") { + IonicUpdate.initialize(app_id); + } + } + } +}]) diff --git a/pool/shard000/JavaScript/0002580_EnvironmentController.js b/pool/shard000/JavaScript/0002580_EnvironmentController.js new file mode 100644 index 0000000000000000000000000000000000000000..8b6df800da7263c3b0b7d3866368e7fb1a9f5c6b --- /dev/null +++ b/pool/shard000/JavaScript/0002580_EnvironmentController.js @@ -0,0 +1,157 @@ +(function(){ + + define([], function(){ + + return function($scope, Environment, Api , $window, library){ + + $scope.environment = Environment + + //Initial folder get + Api.getFolder().$promise.then(function(data){ + + + $scope.environment.availableFolders = data.folders + + $scope.environment.allFiles = [] + $scope.environment.availableFolders.map(function(folder){ + + folder.files.map(function(file){ + $scope.environment.allFiles.push(file) + }) + }) + + $scope.environment.matchingDatasets = + $scope.environment.allFiles + + + }) + + $scope.$watch('environment.selectedFolder', function(newval, oldval){ + if (newval){ + $scope.environment.availableFiles = $scope.environment.selectedFolder.files + } + }) + + $scope.$watch('environment.searchTerm', function(newval, oldval){ + if (newval == "" || typeof newval == 'undefined'){ + $scope.environment.matchingDatasets = $scope.environment.allFiles + return + } + + if (newval.length > 2) { + var matchingTerms = library.search(newval, -80) + var matchingFiles = [] + + for (term in matchingTerms){ + + for (file in $scope.environment.allFiles) { + + var filetag = $scope.environment.allFiles[file].tag + + var matchingTag = matchingTerms[term].phrase.value + + if (filetag == matchingTag){ + matchingFiles.push($scope.environment.allFiles[file]) + } + } + } + + $scope.environment.matchingDatasets = matchingFiles + + } + }) + + $scope.$on('visualizeGraph', function(event, file){ + if (file && + $scope.environment.zScoreThreshold.max && + $scope.environment.zScoreThreshold.min){ + + var params = { + collection: file.collection, + format: "cytoscape", + interactionThreshold: 1, + zScoreThresholdMin: $scope.environment.zScoreThreshold.min, + zScoreThresholdMax: $scope.environment.zScoreThreshold.max, + } + + Api.getFile(params).$promise.then(function(data){ + $scope.environment.graph = data + $scope.environment.displayEdges = [].concat(data.elements.edges) + }) + } + }) + + $scope.$on('geneExplore', function(event, search){ + if(search.gene && + $scope.environment.zScoreThreshold && + $scope.environment.zScoreThreshold.max && + $scope.environment.zScoreThreshold.min){ + + var params = { + collection: search.collection, + gene: search.gene, + interactionThreshold: 1, + zScoreThresholdMin: $scope.environment.zScoreThreshold.min, + zScoreThresholdMax: $scope.environment.zScoreThreshold.max, + format: "cytoscape" + } + + Api.getNearby(params).$promise.then(function(data){ + $scope.environment.graph = data + $scope.environment.displayEdges = [].concat(data.elements.edges) + }) + } + }) + + $scope.$on('downloadGraph', function(event, file){ + if (file && + $scope.environment.zScoreThreshold.max && + $scope.environment.zScoreThreshold.min){ + + var params = { + collection: file.collection, + format: 'tsv', + interactionThreshold: 1, + zScoreThresholdMin: $scope.environment.zScoreThreshold.min, + zScoreThresholdMax: $scope.environment.zScoreThreshold.max, + file: true + } + + var string = "collection=" + params.collection + + "&file=true&format=tsv&interactionThreshold=1&zScoreThresholdMax=" + + params.zScoreThresholdMax + "&zScoreThresholdMin=" + + params.zScoreThresholdMin + + $window.open('/file?' + string) + } + }) + + $scope.visualizeGraph = function(file){ + if($scope.environment.selectedGene){ + $scope.$emit('geneExplore', { + gene: $scope.environment.selectedGene, + collection: file.collection + }) + } else { + + $scope.$emit('visualizeGraph', file) + } + } + + $scope.downloadGraph = function(file){ + $scope.$emit('downloadGraph', file) + } + + $scope.itemsByPage=15; + $scope.getters = { + source: function(value){ return value.data.source}, + target: function(value){ return value.data.target}, + interaction: function(value){ return value.data.interaction}, + zScore: function(value){ return value.data.zScore} + } + + } + + }) + +})() diff --git a/pool/shard000/JavaScript/0002582_toolbar.js b/pool/shard000/JavaScript/0002582_toolbar.js new file mode 100644 index 0000000000000000000000000000000000000000..a14d67184aea84dc146958e53645b841d953a316 --- /dev/null +++ b/pool/shard000/JavaScript/0002582_toolbar.js @@ -0,0 +1,244 @@ +/*! + * Angular Material Design + * https://github.com/angular/material + * @license MIT + * v1.1.0-rc4-master-2806ec8 + */ +goog.provide('ng.material.components.toolbar'); +goog.require('ng.material.components.content'); +goog.require('ng.material.core'); +/** + * @ngdoc module + * @name material.components.toolbar + */ +angular.module('material.components.toolbar', [ + 'material.core', + 'material.components.content' +]) + .directive('mdToolbar', mdToolbarDirective); + +/** + * @ngdoc directive + * @name mdToolbar + * @module material.components.toolbar + * @restrict E + * @description + * `md-toolbar` is used to place a toolbar in your app. + * + * Toolbars are usually used above a content area to display the title of the + * current page, and show relevant action buttons for that page. + * + * You can change the height of the toolbar by adding either the + * `md-medium-tall` or `md-tall` class to the toolbar. + * + * @usage + * + *
    + * + * + *
    + * My App's Title + * + * + * + * + * + * Right Bar Button + * + *
    + * + *
    + * + * Hello! + * + *
    + *
    + * + * @param {boolean=} md-scroll-shrink Whether the header should shrink away as + * the user scrolls down, and reveal itself as the user scrolls up. + * + * _**Note (1):** for scrollShrink to work, the toolbar must be a sibling of a + * `md-content` element, placed before it. See the scroll shrink demo._ + * + * _**Note (2):** The `md-scroll-shrink` attribute is only parsed on component + * initialization, it does not watch for scope changes._ + * + * + * @param {number=} md-shrink-speed-factor How much to change the speed of the toolbar's + * shrinking by. For example, if 0.25 is given then the toolbar will shrink + * at one fourth the rate at which the user scrolls down. Default 0.5. + */ + +function mdToolbarDirective($$rAF, $mdConstant, $mdUtil, $mdTheming, $animate) { + var translateY = angular.bind(null, $mdUtil.supplant, 'translate3d(0,{0}px,0)'); + + return { + template: '', + restrict: 'E', + + link: function(scope, element, attr) { + + element.addClass('_md'); // private md component indicator for styling + $mdTheming(element); + + if (angular.isDefined(attr.mdScrollShrink)) { + setupScrollShrink(); + } + + function setupScrollShrink() { + + var toolbarHeight; + var contentElement; + var disableScrollShrink = angular.noop; + + // Current "y" position of scroll + // Store the last scroll top position + var y = 0; + var prevScrollTop = 0; + var shrinkSpeedFactor = attr.mdShrinkSpeedFactor || 0.5; + + var debouncedContentScroll = $$rAF.throttle(onContentScroll); + var debouncedUpdateHeight = $mdUtil.debounce(updateToolbarHeight, 5 * 1000); + + // Wait for $mdContentLoaded event from mdContent directive. + // If the mdContent element is a sibling of our toolbar, hook it up + // to scroll events. + + scope.$on('$mdContentLoaded', onMdContentLoad); + + // If the toolbar is used inside an ng-if statement, we may miss the + // $mdContentLoaded event, so we attempt to fake it if we have a + // md-content close enough. + + attr.$observe('mdScrollShrink', onChangeScrollShrink); + + // If the toolbar has ngShow or ngHide we need to update height immediately as it changed + // and not wait for $mdUtil.debounce to happen + + if (attr.ngShow) { scope.$watch(attr.ngShow, updateToolbarHeight); } + if (attr.ngHide) { scope.$watch(attr.ngHide, updateToolbarHeight); } + + // If the scope is destroyed (which could happen with ng-if), make sure + // to disable scroll shrinking again + + scope.$on('$destroy', disableScrollShrink); + + /** + * + */ + function onChangeScrollShrink(shrinkWithScroll) { + var closestContent = element.parent().find('md-content'); + + // If we have a content element, fake the call; this might still fail + // if the content element isn't a sibling of the toolbar + + if (!contentElement && closestContent.length) { + onMdContentLoad(null, closestContent); + } + + // Evaluate the expression + shrinkWithScroll = scope.$eval(shrinkWithScroll); + + // Disable only if the attribute's expression evaluates to false + if (shrinkWithScroll === false) { + disableScrollShrink(); + } else { + disableScrollShrink = enableScrollShrink(); + } + } + + /** + * + */ + function onMdContentLoad($event, newContentEl) { + // Toolbar and content must be siblings + if (newContentEl && element.parent()[0] === newContentEl.parent()[0]) { + // unhook old content event listener if exists + if (contentElement) { + contentElement.off('scroll', debouncedContentScroll); + } + + contentElement = newContentEl; + disableScrollShrink = enableScrollShrink(); + } + } + + /** + * + */ + function onContentScroll(e) { + var scrollTop = e ? e.target.scrollTop : prevScrollTop; + + debouncedUpdateHeight(); + + y = Math.min( + toolbarHeight / shrinkSpeedFactor, + Math.max(0, y + scrollTop - prevScrollTop) + ); + + element.css($mdConstant.CSS.TRANSFORM, translateY([-y * shrinkSpeedFactor])); + contentElement.css($mdConstant.CSS.TRANSFORM, translateY([(toolbarHeight - y) * shrinkSpeedFactor])); + + prevScrollTop = scrollTop; + + $mdUtil.nextTick(function() { + var hasWhiteFrame = element.hasClass('md-whiteframe-z1'); + + if (hasWhiteFrame && !y) { + $animate.removeClass(element, 'md-whiteframe-z1'); + } else if (!hasWhiteFrame && y) { + $animate.addClass(element, 'md-whiteframe-z1'); + } + }); + + } + + /** + * + */ + function enableScrollShrink() { + if (!contentElement) return angular.noop; // no md-content + + contentElement.on('scroll', debouncedContentScroll); + contentElement.attr('scroll-shrink', 'true'); + + $$rAF(updateToolbarHeight); + + return function disableScrollShrink() { + contentElement.off('scroll', debouncedContentScroll); + contentElement.attr('scroll-shrink', 'false'); + + $$rAF(updateToolbarHeight); + } + } + + /** + * + */ + function updateToolbarHeight() { + toolbarHeight = element.prop('offsetHeight'); + // Add a negative margin-top the size of the toolbar to the content el. + // The content will start transformed down the toolbarHeight amount, + // so everything looks normal. + // + // As the user scrolls down, the content will be transformed up slowly + // to put the content underneath where the toolbar was. + var margin = (-toolbarHeight * shrinkSpeedFactor) + 'px'; + + contentElement.css({ + "margin-top": margin, + "margin-bottom": margin + }); + + onContentScroll(); + } + + } + + } + }; + +} +mdToolbarDirective.$inject = ["$$rAF", "$mdConstant", "$mdUtil", "$mdTheming", "$animate"]; + +ng.material.components.toolbar = angular.module("material.components.toolbar"); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002583_gen-async.js b/pool/shard000/JavaScript/0002583_gen-async.js new file mode 100644 index 0000000000000000000000000000000000000000..0b335c12e651b0eb9128e2b4f49cb289d224a1fb --- /dev/null +++ b/pool/shard000/JavaScript/0002583_gen-async.js @@ -0,0 +1,20 @@ +// Utility function to simulate async/await through generators +function gen_async(generatorFunc) { + function continuer(verb, arg) { + var result; + try { + result = generator[verb](arg); + } catch (err) { + return Promise.reject(err); + } + if (result.done) { + return result.value; + } else { + return Promise.resolve(result.value).then(onFulfilled, onRejected); + } + } + var generator = generatorFunc(); + var onFulfilled = continuer.bind(continuer, "next"); + var onRejected = continuer.bind(continuer, "throw"); + return onFulfilled(); +} diff --git a/pool/shard000/JavaScript/0002584_index.js b/pool/shard000/JavaScript/0002584_index.js new file mode 100644 index 0000000000000000000000000000000000000000..13dd8c23b6db052621d2da1244e0379a3abd4b17 --- /dev/null +++ b/pool/shard000/JavaScript/0002584_index.js @@ -0,0 +1,73 @@ +import isArray from './util/is-array'; +import isPlainObject from './util/is-plain-object'; +import isString from './util/is-string'; +import extend from './util/extend'; + +/** + * Converts an array of primitives or objects to a plain object. + * + * @param {Array} array The initial array to convert. + * @param {Object} [options] User defined options to override defaults. + * @param {String} [options.key] If `array` is an array of objects and each object has a property with the value of `key`, use those as the properties of the result object. By default the index of each item in array is used. + * @param {String} [options.keyPrefix=''] A string that prefixes the keys of the result object. If anything than string is provided, it takes the default value (''). + * @param {String} [options.keySuffix=''] A string that suffixes the keys of the result object. If anything than string is provided, it takes the default value (''). + * @param {Boolean} [options.deleteKey=false] Deletes the property of each item of the result object if `key` is specified and exists in current object. If `key` does not exist in current item or current item is not an object, leaves the property as is. + * @param {Boolean} [options.inheritProto=false] Determines if the result object should inherit from the `Object.prototype`. + * @throws {TypeError} Will throw if `array` is not an Array. + * @return {Object} The converted object. + */ +function arr2obj(array, options) { + if (!isArray(array)) { + throw new TypeError('arr2obj must be called on an Array'); + } + + /** + * Dictionary of default options + * @private + * @type {Object} + */ + const defaults = { + key: null, + keyPrefix: '', + keySuffix: '', + deleteKey: false, + inheritProto: false + }; + + /** + * Copy of default and user options + * @private + * @type {Object} + */ + const settings = isPlainObject(options) ? extend({}, defaults, options) : extend({}, defaults); + + // Extract data from `settings` into dinstict variables. + let {key, keyPrefix, keySuffix, deleteKey, inheritProto} = settings; + + // Failsafe if `keyPrefix` or `keySuffix` are not strings. + keyPrefix = isString(keyPrefix) ? keyPrefix : ''; + keySuffix = isString(keySuffix) ? keySuffix : ''; + + /** + * The converted result object + * @private + * @type {Object} + */ + const converted = array.reduce(function (accum, current, index) { + if (!key || !current[key]) { + accum[keyPrefix + index + keySuffix] = current; + } else { + accum[keyPrefix + current[key] + keySuffix] = current; + } + + if (deleteKey && key && isPlainObject(current)) { + delete current[key]; + } + + return accum; + }, inheritProto ? {} : Object.create(null)); + + return converted; +} + +export default arr2obj; diff --git a/pool/shard000/JavaScript/0002588_troubleshooterController.js b/pool/shard000/JavaScript/0002588_troubleshooterController.js new file mode 100644 index 0000000000000000000000000000000000000000..4d93994a4ba312687e9aa704024f8fbd42603acd --- /dev/null +++ b/pool/shard000/JavaScript/0002588_troubleshooterController.js @@ -0,0 +1,43 @@ +angular +.module( "networkTroubleshooter") +.controller( "troubleshooterController", function( $scope, $location ){ + + $scope.current_guide = { + show: false, + url: "", + name: "" + }; + + $scope.gotoNextPage = function (url) { + $location.path(url); + }; + + $scope.gotoNextEnquiry = function ( next ){ + if( next ){ + $scope.enquiry.historyList.push( $scope.enquiry.current ); + $scope.enquiry.currentID = next; + $scope.enquiry.current = model.issueList[ next ]; + setTimeout( function () { + window.componentHandler.upgradeDom(); + } , 100 ); + + } + }; + + $scope.historyBacktrack = function ( index ){ + $scope.enquiry.current = $scope.enquiry.historyList[index]; + $scope.enquiry.historyList = $scope.enquiry.historyList.slice( 0, index ); + window.setTimeout( window.componentHandler.upgradeDom, 100 ); + }; + + $scope.showGuide = function (_guide) { + + $scope.current_guide.url = 'partials/guides/' + _guide.url ; + $scope.current_guide.name = _guide.name; + $scope.current_guide.show = true; + + console.log("Guide URL: ", 'partials/guides/' + _guide.url ); + }; + +}); + diff --git a/pool/shard000/JavaScript/0002589_crudbits.angular.directive.js b/pool/shard000/JavaScript/0002589_crudbits.angular.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..b323d1f37375e3d489d930b991eaac8851313867 --- /dev/null +++ b/pool/shard000/JavaScript/0002589_crudbits.angular.directive.js @@ -0,0 +1,63 @@ +/** + * @aauthor Michael Cuccaro + * @see https://github.com/mvcuccaro + * + * directive to create a 4 checkbox input control for setting crud bits (search 1, insert 2, update 3, remove 4) + * The directive binds to an external value via the "bitvalue" attribute which will be the sum of all bits checked in the control + * + * @return {angular directive} { returns an angular directive} + */ +var directive_mvc_crudbits = function() { + //app.directive('crudBits', function() { + var static_bits = { + search: 1, + insert: 2, + update: 4, + remove: 8 + }; + + var controller = function($scope, $element, $attrs){ + /** + * Check the current bit value and see if it contains the bit of the type requested in arg_type + * + * @param {string} The type of the bit (search, insert, update or remove) + * @return {int} The contained bit or zero if bit value does not contain the bit + */ + $scope.checkBitValue = function(arg_type){ + return $scope.bitvalue & static_bits[arg_type]; + } + + /** + * Add up all the checked bits and set the bound bitvalue to the sum + */ + $scope.updateBitValue = function(){ + //sets the index to 0 if there is no index provided. + var rindex = angular.isUndefined($attrs.rindex) ? 0 : $attrs.rindex; + + //add up all the checked bits + var new_bit_value = $element.find('#crud_bits_search_checkbox_' + rindex).prop('checked') == true ? static_bits.search : 0; + new_bit_value += $element.find('#crud_bits_insert_checkbox_' + rindex).prop('checked') == true ? static_bits.insert : 0; + new_bit_value += $element.find('#crud_bits_update_checkbox_' + rindex).prop('checked') == true ? static_bits.update : 0; + new_bit_value += $element.find('#crud_bits_remove_checkbox_' + rindex).prop('checked') == true ? static_bits.remove : 0; + + //update the bound value + $scope.bitvalue = new_bit_value; + } + }; + + return { + restrict: 'AE', + replace: 'true', + scope: { + bitvalue: '=', + rindex: '@' + }, + template: '
    ' + + 'S:' + + 'I:' + + 'U:' + + 'R:' + + '
    ', + controller: controller + }; +}; diff --git a/pool/shard000/JavaScript/0002591_7060.js b/pool/shard000/JavaScript/0002591_7060.js new file mode 100644 index 0000000000000000000000000000000000000000..ff81682070a853ae99e07ba20227563baedc74fa --- /dev/null +++ b/pool/shard000/JavaScript/0002591_7060.js @@ -0,0 +1,32 @@ +{ + var imports = doc.querySelectorAll("link[rel=import]"); + var loaded = 0, + l = imports.length; + + function checkDone(d) { + if (loaded == l && callback) { + callback(); + } + } + + function loadedImport(e) { + markTargetLoaded(e); + loaded++; + checkDone(); + } + + if (l) { + for (var i = 0, imp; i < l && (imp = imports[i]); i++) { + if (isImportLoaded(imp)) { + loadedImport.call(imp, { + target: imp + }); + } else { + imp.addEventListener("load", loadedImport); + imp.addEventListener("error", loadedImport); + } + } + } else { + checkDone(); + } +} diff --git a/pool/shard000/JavaScript/0002593_Retrievable.js b/pool/shard000/JavaScript/0002593_Retrievable.js new file mode 100644 index 0000000000000000000000000000000000000000..49bdc7c34a563423749720009ff853c0ba310d45 --- /dev/null +++ b/pool/shard000/JavaScript/0002593_Retrievable.js @@ -0,0 +1,61 @@ +import { observable, extendObservable, computed, ObservableMap, IObservableArray, isObservableMap, isObservableArray, isObservableObject } from 'mobx'; + +import _editable from './_editable'; +const toggleBool = (self, propName) => (status) => { self[propName] = typeof status === "boolean" ? status : !self[propName] } + +class RetrievableArray { + + @observable noResults = false; + @observable showing = false; + @observable loading = false; + + constructor(initialData = []) { + extendObservable(this, _editable(this), { + data: initialData, + }); + } + + // TODO: Fix this + @computed + get length() { + return this.data.length; + } + + map = (fn) => this.data.map(fn); + filter = (fn) => this.data.filter(fn); + some = (fn) => this.data.some(fn); + unshift = (item) => { this.data.unshift(item) } + push = (item) => {this.data.push(item) } + replace = (data = []) => { this.data.replace(data) } + + toggleShow = toggleBool(this, "showing"); + toggleLoading = toggleBool(this, "loading"); +} + +class RetrievableMap extends ObservableMap { + + type; + @observable data; + @observable adding = false; + @observable loading = false; + @observable editing = false; + @observable removing = false; + @observable noResults = false; + @observable showing = false; + + constructor(initialData = {}) { + super(initialData); + } + + toggleAdding = toggleBool(this, "adding"); + toggleLoading = toggleBool(this, "loading"); + toggleEditing = toggleBool(this, "editing"); + toggleRemoving = toggleBool(this, "removing"); + toggleShow = toggleBool(this, "showing"); + toggleLoading = toggleBool(this, "loading"); +} + +export { + RetrievableArray, + RetrievableMap, +} diff --git a/pool/shard000/JavaScript/0002594_main.js b/pool/shard000/JavaScript/0002594_main.js new file mode 100644 index 0000000000000000000000000000000000000000..31eb3c589e3344ea48238bfd403efde212401acf --- /dev/null +++ b/pool/shard000/JavaScript/0002594_main.js @@ -0,0 +1,50 @@ +/* Calculator Omniplet */ + +function search(expr,a,b) { + var i = 0 + while (i != -1) { + i = expr.indexOf(a,i); + if (i>=0) { + if (i==0) { + expr = expr.substring(0,i)+b+expr.substring(i+a.length); + i += b.length + } else { + if (expr.substring(i-1,i) != "a") { + expr = expr.substring(0,i)+b+expr.substring(i+a.length); + i += b.length + } else {i++} + } + + } + } + return expr +} + +function calculate(f) { + var expr = f; + expr = search(expr,'cos','Math.cos'); + expr = search(expr,'sin','Math.sin'); + expr = search(expr,'tan','Math.tan'); + expr = search(expr,'acos','Math.acos'); + expr = search(expr,'asin','Math.asin'); + expr = search(expr,'atan','Math.atan'); + expr = search(expr,'ln','Math.log'); + expr = search(expr,'exp','Math.exp'); + expr = search(expr,'pow','Math.pow'); + expr = search(expr,'sqrt','Math.sqrt'); + expr = search(expr,'pi','Math.PI'); + return eval(expr); +} + +function onOmniBoxSearch(text){ + if(text.substring(0,1) === "=") { + liri.appendSearchSuggestion("Result : " + calculate(text.substring(1,text.length)), "action/code", "start"); + } +} + +function onLoad(){ + liri.print("Calculator Omniplet loaded"); +} + +liri.on("load", onLoad); +liri.on("omnibox.search", onOmniBoxSearch); diff --git a/pool/shard000/JavaScript/0002599_pixidemo2.js b/pool/shard000/JavaScript/0002599_pixidemo2.js new file mode 100644 index 0000000000000000000000000000000000000000..ab677389c3e0e75ec202ec19f2d7b9b07f749733 --- /dev/null +++ b/pool/shard000/JavaScript/0002599_pixidemo2.js @@ -0,0 +1,175 @@ +$(document).ready(function() { + + // pixi/display stuff + var screen = {}; + function initScreen() { + screen.width = window.innerWidth; + screen.height = window.innerHeight; + } + initScreen(); + + var stage = new PIXI.Stage(0x777777, false); // interactive + var renderer = PIXI.autoDetectRenderer( + screen.width, screen.height, null, true // transparency + ); + + $(window).resize(function() { + initScreen(); + renderer.resize(screen.width, screen.height); + }); + + $("body").append(renderer.view); + + function isChance(p, max) { + if (typeof max == "undefined") max = 32767; + var r = Math.random() * max; + return r < (max * p) + } + + var lastHeroSpawnTryTime = 0, currentTime = 0; + function animate() { + renderer.render(stage); + TWEEN.update(); + + currentTime = new Date().getTime(); + if (currentTime - lastHeroSpawnTryTime > 100) { + lastHeroSpawnTryTime = currentTime; + heroSpawnTry(); + } + moveHeroes(); + requestAnimFrame(function() { animate(); }); + } + requestAnimFrame(function() { animate(); }); + + // grid stuff + var gridSize = { width: 20, height: 20 }; + var gridFieldSize = { width: Math.round(screen.height/gridSize.width), height: Math.round(screen.height/gridSize.height) }; + var pathfindingGrid = new PF.Grid(gridSize.width, gridSize.height); + var grid = []; + for (var y = 0; y < gridSize.height; y++) { + grid[y] = []; + for (var x = 0; x < gridSize.width; x++) { + pathfindingGrid.setWalkableAt(x, y, true); + grid[y][x] = 0; + } + } + // special map positions + var spawnPoints = [ + { x: 0, y: 0 }, + { x: gridSize.width - 1, y: 0 }, + { x: gridSize.width - 1, y: gridSize.height - 1 }, + { x: 0, y: gridSize.height - 1 } + ]; + var middlePoint = {x: Math.round(gridSize.width/2), y: Math.round(gridSize.height/2)}; + + // heroes stuff + var heroes = [], maxHeroes = 10; + function heroSpawnTry() { + if (isChance(0.3 - (0.3 / maxHeroes * heroes.length))) { + var position = spawnPoints[Math.round(Math.random() * (spawnPoints.length-1))]; + heroes.push({ position: position }); + + var sprite = new PIXI.Sprite(PIXI.Texture.fromImage("hero.png")); + sprite.width = gridFieldSize.width; + sprite.height = gridFieldSize.height; + sprite.position = { + x: position.x * gridFieldSize.width, + y: position.y * gridFieldSize.height + }; + stage.addChild(sprite); + heroes[heroes.length-1].sprite = sprite; + heroes[heroes.length-1].movement = false; + } + } + + function moveHeroes() { + for (var i = 0; i < heroes.length; i++) { + if (heroes[i].movement == false) { + var behaviour = Math.round(Math.random() * 1); + if (behaviour == 0) { + // first behaviour, follow path to middle point + moveHero(heroes[i], middlePoint); + } else { + // second behaviour, follow path to random point + var distance = 10, angle = Math.round(Math.random() * 360), + cosAlpha = Math.cos(angle), sinAlpha = Math.sin(angle); + var targetPoint = { + x: Math.round(heroes[i].position.x - cosAlpha * distance), + y: Math.round(heroes[i].position.y - sinAlpha * distance) + }; + targetPoint.x = (targetPoint.x < 0) ? 0 : (targetPoint.x > gridSize.width-1) ? gridSize.width-1 : targetPoint.x; + targetPoint.y = (targetPoint.y < 0) ? 0 : (targetPoint.y > gridSize.height-1) ? gridSize.height-1 : targetPoint.y; + moveHero(heroes[i], targetPoint); + } + } + } + } + + function moveHero(hero, targetPosition) { + var path = getWalkablePath(hero.position, targetPosition); + + if (isChance(0.5)) { + // behaviour to reduce path length + var pathLength = Math.round(Math.random() * path.length-1)+1; + var newPath = []; + for (var i = 0; i < pathLength; i++) { + newPath.push(path[i]); + } + path = newPath; + } + + if (path.length > 0) { + var tweens = [], nextPosX = 0, nextPosY = 0, + lastPosX = hero.position.x * gridFieldSize.width, + lastPosY = hero.position.y * gridFieldSize.height; + + for (var j = 0; j < path.length; j++) { + nextPosX = path[j][0] * gridFieldSize.width; + nextPosY = path[j][1] * gridFieldSize.height; + var scope = this; + + tweens[j] = function(iJ, sourceX, sourceY, targetX, targetY, iFieldX, iFieldY, isLastField) { + var distance = Math.sqrt(Math.pow(sourceX - targetX, 2) + Math.pow(sourceY - targetY, 2)); + return new TWEEN.Tween( { x: sourceX, y: sourceY } ) + .to( + { x: targetX, y: targetY }, 1000 * distance / 10 + ) + .onUpdate( function () { + hero.sprite.position.x = this.x; + hero.sprite.position.y = this.y; + }) + .onComplete( function () { + hero.position.x = iFieldX; + hero.position.y = iFieldY; + if (isLastField) hero.movement = false; + }); + }( + j, lastPosX, lastPosY, nextPosX, nextPosY, path[j][0], path[j][1], (j == path.length - 1) ? true : false + ); + + lastPosX = nextPosX; + lastPosY = nextPosY; + + if (j > 0) { + tweens[j-1].chain(tweens[j]); + } + } + + tweens[0].start(); + hero.movement = true; + } + } + + function getWalkablePath(position, targetPosition) { + var gridBackup = pathfindingGrid.clone(); + var finder = new PF.BestFirstFinder({ + allowDiagonal: true, + dontCrossCorners: true + }); + var path = finder.findPath(position.x, position.y, targetPosition.x, targetPosition.y, pathfindingGrid); + path.splice(0, 1); + pathfindingGrid = gridBackup; + return path; + } + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002602_wysihtml5.js b/pool/shard000/JavaScript/0002602_wysihtml5.js new file mode 100644 index 0000000000000000000000000000000000000000..5475b72eb25ce3a192b73d9707ea59a8064af65e --- /dev/null +++ b/pool/shard000/JavaScript/0002602_wysihtml5.js @@ -0,0 +1,141 @@ +/** +Bootstrap wysihtml5 editor. Based on [bootstrap-wysihtml5](https://github.com/jhollingworth/bootstrap-wysihtml5). +You should include **manually** distributives of `wysihtml5` and `bootstrap-wysihtml5`: + + + + + +And also include `wysihtml5.js` from `inputs-ext` directory of x-editable: + + + +**Note:** It's better to use fresh bootstrap-wysihtml5 from it's [master branch](https://github.com/jhollingworth/bootstrap-wysihtml5/tree/master/src) as there is update for correct image insertion. + +@class wysihtml5 +@extends abstractinput +@final +@since 1.4.0 +@example +

    awesome

    comment!
    + +**/ +import jQuery from 'jquery' + +(function ($) { + "use strict"; + + var Wysihtml5 = function (options) { + this.init('wysihtml5', options, Wysihtml5.defaults); + + //extend wysihtml5 manually as $.extend not recursive + this.options.wysihtml5 = $.extend({}, Wysihtml5.defaults.wysihtml5, options.wysihtml5); + }; + + debugger + $.fn.editableutils.inherit(Wysihtml5, $.fn.editabletypes.abstractinput); + + $.extend(Wysihtml5.prototype, { + render: function () { + var deferred = $.Deferred(), + msieOld; + + //generate unique id as it required for wysihtml5 + this.$input.attr('id', 'textarea_'+(new Date()).getTime()); + + this.setClass(); + this.setAttr('placeholder'); + + //resolve deffered when widget loaded + $.extend(this.options.wysihtml5, { + events: { + load: function() { + deferred.resolve(); + } + } + }); + + this.$input.wysihtml5(this.options.wysihtml5); + + /* + In IE8 wysihtml5 iframe stays on the same line with buttons toolbar (inside popover). + The only solution I found is to add
    . If you fine better way, please send PR. + */ + msieOld = /msie\s*(8|7|6)/.test(navigator.userAgent.toLowerCase()); + if(msieOld) { + this.$input.before('

    '); + } + + return deferred.promise(); + }, + + value2html: function(value, element) { + $(element).html(value); + }, + + html2value: function(html) { + return html; + }, + + value2input: function(value) { + this.$input.data("wysihtml5").editor.setValue(value, true); + }, + + activate: function() { + this.$input.data("wysihtml5").editor.focus(); + }, + + isEmpty: function($element) { + if($.trim($element.html()) === '') { + return true; + } else if($.trim($element.text()) !== '') { + return false; + } else { + //e.g. '', '
    ', '

    ' + return !$element.height() || !$element.width(); + } + } + }); + + Wysihtml5.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { + /** + @property tpl + @default + **/ + tpl:'', + /** + @property inputclass + @default editable-wysihtml5 + **/ + inputclass: 'editable-wysihtml5', + /** + Placeholder attribute of input. Shown when input is empty. + + @property placeholder + @type string + @default null + **/ + placeholder: null, + /** + Wysihtml5 default options. + See https://github.com/jhollingworth/bootstrap-wysihtml5#options + + @property wysihtml5 + @type object + @default {stylesheets: false} + **/ + wysihtml5: { + stylesheets: false //see https://github.com/jhollingworth/bootstrap-wysihtml5/issues/183 + } + }); + + $.fn.editabletypes.wysihtml5 = Wysihtml5; + +}(jQuery)); diff --git a/pool/shard000/JavaScript/0002603_regularization.js b/pool/shard000/JavaScript/0002603_regularization.js new file mode 100644 index 0000000000000000000000000000000000000000..33bfdf30b72068e2915062ebb13a72ece77c1ca8 --- /dev/null +++ b/pool/shard000/JavaScript/0002603_regularization.js @@ -0,0 +1,50 @@ +var _ = require('lodash') + , AspectAnalysis = require('./aspect'); + +var RegularizationAnalysis = function (analysis, options) { + AspectAnalysis.call(this, analysis, { + step : 0.02, + start : 0, + stop : 1 + }); + + this.setOptions(options); +}; + +RegularizationAnalysis.prototype = new AspectAnalysis(); + +RegularizationAnalysis.prototype.getValues = function () { + return _.range( + this.options.start, + this.options.stop + this.options.step, + this.options.step + ); +}; + +RegularizationAnalysis.prototype.run = function () { + var analyses + , values + , value + , i + , l; + + analyses = []; + values = this.getValues(); + + for (i = 0, l = values.length; i < l; i++) { + value = values[i]; + + this.analysis.training.derivative.setOptions({ regularization: value }); + + analyses.push([value, this.analysis.run()]); + + this.report('analysis', { + iterations : i + 1, + value : value + }); + } + + return analyses; +}; + +exports = module.exports = RegularizationAnalysis; diff --git a/pool/shard000/JavaScript/0002608_blobhttp.js b/pool/shard000/JavaScript/0002608_blobhttp.js new file mode 100644 index 0000000000000000000000000000000000000000..a4ea1614d9d591e1bb4ca745a5d961ba243032f5 --- /dev/null +++ b/pool/shard000/JavaScript/0002608_blobhttp.js @@ -0,0 +1,153 @@ +/* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. */ + +/****************************************************************************** + * + * You may not use the identified files except in compliance with the Apache + * License, Version 2.0 (the "License.") + * + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + * NAME + * blobhttp.js + * + * DESCRIPTION + * Listens for an HTTP request and returns an image queried from a BLOB column + * Also shows the connection pool's caching using a 'default' pool. + * + * Start the listener with 'node blobhttp.js' and then use a browser + * to load http://localhost:7000/getimage + * + * This example uses Node 8's async/await syntax. + * + *****************************************************************************/ + +const url = require('url'); +const http = require('http'); +const oracledb = require('oracledb'); +const dbConfig = require('./dbconfig.js'); +const demoSetup = require('./demosetup.js'); + +const httpPort = 7000; + +// Main entry point. Creates a connection pool which becomes the +// 'default' pool, and then creates an HTTP server. +async function init() { + try { + await oracledb.createPool(dbConfig); + console.log('Connection pool started'); + + // create the demo table + const connection = await oracledb.getConnection(); + await demoSetup.setupLobs(connection, true); + await connection.close(); + + // Create HTTP server and listen on port httpPort + const server = http.createServer(); + server.on('error', (err) => { + throw err; + }); + server.on('request', (request, response) => { + handleRequest(request, response); + }); + await server.listen(httpPort); + console.log("Server is running. Try loading http://localhost:" + httpPort + "/getimage"); + + } catch (err) { + console.error('init() error: ' + err.message); + } +} + +// Handles each web request +async function handleRequest(request, response) { + + const requrl = url.parse(request.url, true); + const action = requrl.pathname; + + if (action == '/getimage') { + + let connection; + + try { + connection = await oracledb.getConnection(); // gets a connection from the 'default' connection pool + + const result = await connection.execute( + "SELECT b FROM no_lobs WHERE id = :id", // get the image + { id: 2 } + ); + if (result.rows.length === 0) { + throw new Error("No data selected from table."); + } + + const lob = result.rows[0][0]; + if (lob === null) { + throw new Error("BLOB was NULL"); + } + + const doStream = new Promise((resolve, reject) => { + lob.on('end', () => { + // console.log("lob.on 'end' event"); + response.end(); + }); + lob.on('close', () => { + // console.log("lob.on 'close' event"); + resolve(); + }); + lob.on('error', (err) => { + // console.log("lob.on 'error' event"); + reject(err); + }); + response.writeHead(200, {'Content-Type': 'image/jpeg' }); + lob.pipe(response); // write the image out + }); + + await doStream; + + } catch (err) { + console.error(err); + await closePoolAndExit(); + } finally { + if (connection) { + try { + await connection.close(); + } catch (err) { + console.error(err); + } + } + } + + } else { + response.writeHead(200, {'Content-Type': 'text/plain' }); + response.end("Try requesting: http://localhost:" + httpPort + "/getimage\n"); + } +} + +async function closePoolAndExit() { + console.log('\nTerminating'); + try { + // Get the pool from the pool cache and close it when no + // connections are in use, or force it closed after 2 seconds. + // If this hangs, you may need DISABLE_OOB=ON in a sqlnet.ora file. + // This setting should not be needed if both Oracle Client and Oracle + // Database are 19c (or later). + await oracledb.getPool().close(2); + console.log('Pool closed'); + process.exit(0); + } catch(err) { + console.error(err.message); + process.exit(1); + } +} + +process + .once('SIGTERM', closePoolAndExit) + .once('SIGINT', closePoolAndExit); + +init(); diff --git a/pool/shard000/JavaScript/0002610_score-test.js b/pool/shard000/JavaScript/0002610_score-test.js new file mode 100644 index 0000000000000000000000000000000000000000..7b0ef4a3c709bab79158d881d893b31f931d9894 --- /dev/null +++ b/pool/shard000/JavaScript/0002610_score-test.js @@ -0,0 +1,38 @@ +const chai = require('chai'); +const assert = chai.assert; + +const Board = require('../lib/board'); +const Meteor = require('../lib/meteor'); +const Score = require('../lib/score'); + +describe('Score', function() { + beforeEach(function() { + this.board = new Board(); + }); + + describe('Total score and meteors destroyed', function() { + it('should return a totalScore and meteorsDestroyed count of zero', function() { + let score = new Score(this.board); + assert.equal(score.results().totalScore, 0); + assert.equal(score.results().meteorsDestroyed, 0); + }); + + it('should return a totalScore of the meteor\'s pointValue and meteorsDestroyed count of one', function() { + let score = new Score(this.board); + let meteor = this.board.addMeteor(); + this.board.meteorsDestroyed.push(meteor); + assert.equal(score.results().totalScore, meteor.pointValue); + assert.equal(score.results().meteorsDestroyed, 1); + }); + + it('should return a totalScore summing two meteor\'s pointValues and meteorsDestroyed count of two', function() { + let score = new Score(this.board); + let meteor1 = this.board.addMeteor(); + let meteor2 = this.board.addMeteor(); + this.board.meteorsDestroyed.push(meteor1); + this.board.meteorsDestroyed.push(meteor2); + assert.equal(score.results().totalScore, meteor1.pointValue + meteor2.pointValue); + assert.equal(score.results().meteorsDestroyed, 2); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0002612_svgreindeer.js b/pool/shard000/JavaScript/0002612_svgreindeer.js new file mode 100644 index 0000000000000000000000000000000000000000..cb65b8f40c91e7d76d48d76e84165b7d0ebd386d --- /dev/null +++ b/pool/shard000/JavaScript/0002612_svgreindeer.js @@ -0,0 +1,51 @@ +/* + * grunt-svgreindeer + * https://github.com/bennyschudel/grunt-svgreindeer + * + * Copyright (c) 2014 Benny Schudel + * Licensed under the MIT license. + */ + +"use strict"; + +var Q = require('q'); + +var SvgReindeer = require('svgreindeer'); + +var log = console.log; + +module.exports = function(grunt) { + + grunt.registerMultiTask( + 'svgreindeer', + 'Renders SVG\'s to PNG\'s for a fallback in older IE\'s and email clients.', + function() { + + var _this = this; + var p = Q(); + var done = this.async(); + + this.files.forEach(function(item) { + + var options = _this.options({ + verbose : false, + scale : 1, + style : null, + input_src : item.src, + output_dir : item.dest, + base_dir : item.base || '', + }); + + p = p.then(function(data) { + return (new SvgReindeer(options)).run(); + }); + + }); + + p.done(function() { + done(); + }); + + }); + +}; diff --git a/pool/shard000/JavaScript/0002614_post.js b/pool/shard000/JavaScript/0002614_post.js new file mode 100644 index 0000000000000000000000000000000000000000..05b9cb07f83cac6505d1fc93245936f1ae015939 --- /dev/null +++ b/pool/shard000/JavaScript/0002614_post.js @@ -0,0 +1,55 @@ +var Tistory = require('../lib/tistory'), + logger = require('hbn-logger').tracer({level: 'all'}), + options = require('./example-options'); + +var tistory = new Tistory(options); + +var callback = function (err, body) { + if (err) { + logger.error(err); + } else { +// logger.debug(body); + var json = JSON.parse(body); + logger.info(json.tistory); + } +}; + +//tistory.post.list({ +// page: 1, //default:1 +// count: 10, //default:10, max:30 +//// categoryId: //default all categories +// sort: 'id' //default:id(글번호) , date(날짜) +//}, callback); +//tistory.post.list({page: 1, targetUrl: "blog.saltfactory.net"}, callback); +//tistory.post.read({postId: 12}, callback); +// + +//tistory.post.write({ +//// visibility: 0, //default: 0(비공개), 1(보호), 2(공개), 3(발행), 생략시 비공개 +////// published: //UNIX_TIMESTAMP() 값을 넣을 경우, 예약발행 +//// categoryId: 0, //default:0 (생략시 분류없음) +// tag: 'nodejs, node-tistory', +// title: 'test', +// content: '본문' +//}, callback); +// +//tistory.post.update({ +// postId: 11, +// visibility: 0, //default: 0(비공개), 1(보호), 2(공개), 3(발행), 생략시 비공개 +// categoryId: 0, //default:0 (생략시 분류없음) +// tag: 'nodejs, node-tistory', +// title: 'test', +// content: '본문 수정' +//}, callback); +// +tistory.post.attach({uploadedfile: '/Users/saltfactory/Downloads/square.png'}, callback); +// +//tistory.post.delete({postId: 11}, callback); + +//tistory.writeFromFile('/Users/saltfactory/Dropbox/Blog/output/2014-07-16-using-passport-tistory-in-express/2014-07-16-using-passport-tistory-in-express.md.html', +// { +// title:'' +// }, +// callback +//); + diff --git a/pool/shard000/JavaScript/0002620_admin-login.js b/pool/shard000/JavaScript/0002620_admin-login.js new file mode 100644 index 0000000000000000000000000000000000000000..30c1f3aa465eaf05f6d3a242bd233111fb103bf0 --- /dev/null +++ b/pool/shard000/JavaScript/0002620_admin-login.js @@ -0,0 +1,42 @@ + +$(document).ready(function() { + var submit_form = $("#loginSubmit"); + var login_form = $("#loginForm") + var email_error = $("#emailError"); + var password_error = $("#passwordError"); + var login_loading = $("#loginLoading"); + + login_loading.hide(); + + submit_form.click(function() { + email_error.text(""); + password_error.text(""); + + login_loading.show(); + $.ajax({ + type: "POST", + url: window.base_url + "AuthController/loginExec", + dataType: "json", + data: login_form.serialize(), + success: function(data){ + if (data.error == true) { + if (data.type == "required") { + email_error.text(data.message.email); + password_error.text(data.message.password); + } else if (data.type == "common") { + email_error.text(data.message); + } else { + console.log("[ERROR] : error type not set!"); + } + } else { + window.location.href = window.base_url + "DashboardController/index"; + } + login_loading.hide(); + }, + error: function(error){ + console.log(error); + } + }); + }); + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002621_carts-security.js b/pool/shard000/JavaScript/0002621_carts-security.js new file mode 100644 index 0000000000000000000000000000000000000000..1e4536f3af308091f8b8f12eb792bf8018d0062b --- /dev/null +++ b/pool/shard000/JavaScript/0002621_carts-security.js @@ -0,0 +1,27 @@ +Security.defineMethod("inShoppingState", { + fetch: [], + transform: null, + deny: function (type, arg, userId, doc, fields, modifier) { + // console.log("inShoppingState " + doc.state + " " + userId + " " + doc.userId) + return doc.state !== Mart.Cart.STATES.SHOPPING || userId !== doc.userId + } +}); + +Security.defineMethod("ownsCreditCard", { + fetch: [], + transform: null, + deny: function (type, arg, userId, doc, fields, modifier) { + if(type === "update") { + var cardId = modifier.$set.cardId + var card = Mart.Cards.findOne(cardId) + } + + return card === undefined || (card.userId !== userId) + } +}); + +Mart.Carts.permit(['update']) + .inShoppingState() + .ownsCreditCard() + .onlyProps(['cardId', 'contactName', 'contactEmail', 'contactPhone', 'contactEntity', 'referer']) + .apply() diff --git a/pool/shard000/JavaScript/0002622_variadic.js b/pool/shard000/JavaScript/0002622_variadic.js new file mode 100644 index 0000000000000000000000000000000000000000..7b3c9aa53a37f0cc6abe6174ba4b30a5a0a17073 --- /dev/null +++ b/pool/shard000/JavaScript/0002622_variadic.js @@ -0,0 +1,40 @@ +import flatten from './internal/flatten' + +const slice = Array.prototype.slice + +/** + * Converts a function to a variadic function. + * + * The last named parameter will be given an array of arguments. + * + * @param {Function} f The function. + * @returns {Function} A function that wraps the function `f` to accept any + * number of arguments. + * @example + * + * import { variadic } from 'fkit' + * function f (head, tail) { ... } + * variadic(f)(1, 2, 3) // f(1, [2, 3]) + */ +export default function variadic (f) { + const arity = f.length + + if (arity < 1) { + return f + } else if (arity === 1) { + return (...args) => { + const newArgs = (args.length === 1) ? flatten(args) : args + + return f.call(this, newArgs) + } + } else { + return (...args) => { + const numMissingArgs = Math.max(arity - args.length - 1, 0) + const missingArgs = new Array(numMissingArgs) + const namedArgs = slice.call(args, 0, arity - 1) + const variadicArgs = slice.call(args, f.length - 1) + + return f.apply(this, namedArgs.concat(missingArgs).concat([variadicArgs])) + } + } +} diff --git a/pool/shard000/JavaScript/0002624_index.js b/pool/shard000/JavaScript/0002624_index.js new file mode 100644 index 0000000000000000000000000000000000000000..dc3caa5c919d18e38a99aa02da0b1b6fb54c97e9 --- /dev/null +++ b/pool/shard000/JavaScript/0002624_index.js @@ -0,0 +1,22 @@ +import React, {Component} from 'react'; +import PropTypes from 'prop-types'; +import {connect} from 'react-redux'; +import cn from 'classnames'; + +@connect(({api}) => api) +export default class Loading extends Component { + render() { + const {requests} = this.props; + return ( +
    0})}> + {Object.keys(requests).map(id => { + const progress = requests[id].loaded / requests[id].total; + return
    ; + })} +
    + ); + } + static propTypes = { + requests: PropTypes.object.isRequired, + } +} diff --git a/pool/shard000/JavaScript/0002626_router.js b/pool/shard000/JavaScript/0002626_router.js new file mode 100644 index 0000000000000000000000000000000000000000..6b6ccf5f09ce4351ec806642d3d41ca2d8efa01d --- /dev/null +++ b/pool/shard000/JavaScript/0002626_router.js @@ -0,0 +1,73 @@ +// (c) Bantyev Alexander aka balsoft , 2017. This work is licensed under GPLv3, which can be found in the license file. +/* +/* This program routes requests from users to either +/* -- file system +/* -- requestHandlers.js +/* This program should not be modified. +*/ +var _response = { + 'code': 500, + 'content': '

    500 Internal server error

    ', + args: {} +} +const requestHandlers = require('./requestHandlers.js') + .requestHandlers +const fs = require('fs') +const auth = require('./auth.js') +const f = require('./f.js') +exports.route = (pathname, request, response, cookies, fields, files) => { + if (requestHandlers[pathname] !== undefined) { + try { + requestHandlers[pathname](response, request, fields, cookies, files) + } catch (err) { + response.writeHead(500, { + 'Content-Type': 'text/html' + }) + response.end(`

    Internal server error


    ${err}`) + f.log(err) + } + } else { + _response.args['Content-Type'] = f.getMIME(pathname) + auth.check(cookies.id, cookies.password, (result) => { + try { + try { + var content = fs.readFileSync('./loggedin' + pathname) + if (result) { + _response.code = 200 + _response.content = content + } else { + var error = { + code: 403 + } + throw error + } + } catch (e) { + try { + content = fs.readFileSync('./all' + pathname) + _response.code = 200 + _response.content = content + } catch (e) { + _response.code = 404 + _response.content = '

    404 Not Found

    ' + _response.args = { + 'Content-Type': 'text/html' + } + } + } + } catch (err) { + _response = { + 'code': 404, + 'content': '

    404 File not found

    ', + args: { + 'Content-Type': 'text/html' + } + } + f.log(err) + } + response.writeHead(_response.code, _response.args) + response.write((_response.args['Content-Type'] === 'text/html' ? ((result ? fs.readFileSync('./loggedin/header', 'utf8') : fs.readFileSync('./all/header', 'utf8')).toString() + _response.content.toString()) : (_response.content))) + response.end() + }) + + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002627_draggable.client.controller.js b/pool/shard000/JavaScript/0002627_draggable.client.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..15633d03c592ab007d76469b48d90d48daef6310 --- /dev/null +++ b/pool/shard000/JavaScript/0002627_draggable.client.controller.js @@ -0,0 +1,76 @@ +'use strict'; + +angular.module('template').controller('DraggableController', ['$scope','$element', + function($scope, $element) { + + var snap = angular.element(document.querySelector('#snap')), + liveSnap = angular.element(document.querySelector("#liveSnap")), + container = angular.element(document.querySelector("#container")), + gridWidth = 196, + gridHeight = 100, + gridRows = 6, + gridColumns = 5, + i, x, y; + + //loop through and create the grid (a div for each cell). Feel free to tweak the variables above + for (i = 0; i < gridRows * gridColumns; i++) { + y = Math.floor(i / gridColumns) * gridHeight; + x = (i * gridWidth) % (gridColumns * gridWidth); + /* + var changeDiv= $element.find("div") + .css({ + position:"absolute", + border:"1px solid #454545", + width:gridWidth-1, + height:gridHeight-1, + top:y, left:x}); + container.prepend(changeDiv);*/ + //$("
    ").css({position:"absolute", border:"1px solid #454545", width:gridWidth-1, height:gridHeight-1, top:y, left:x}).prependTo($container); + } + + //set the container's size to match the grid, and ensure that the box widths/heights reflect the variables above + TweenLite.set(container, {height: gridRows * gridHeight + 1, width: gridColumns * gridWidth + 1}); + TweenLite.set(".box", {width:gridWidth, height:gridHeight, lineHeight:gridHeight + "px"}); + + //the update() function is what creates the Draggable according to the options selected (snapping). + function update() { + //var snap = snap.prop("checked"), liveSnap = $liveSnap.prop("checked"); + Draggable.create(".box", { + bounds:container, + edgeResistance:0.65, + type:"x,y", + throwProps:true, + liveSnap:liveSnap, + snap:{ + x: function(endValue) { + return (snap || liveSnap) ? Math.round(endValue / gridWidth) * gridWidth : endValue; + }, + y: function(endValue) { + return (snap || liveSnap) ? Math.round(endValue / gridHeight) * gridHeight : endValue; + } + } + }); + } + /* + //when the user toggles one of the "snap" modes, make the necessary updates... + snap.on("change", applySnap); + liveSnap.on("change", applySnap); + + function applySnap() { + if (snap.prop("checked") || liveSnap.prop("checked")) { + angular.element(document.querySelector('.box')).each(function(index, element) { + TweenLite.to(element, 0.5, { + x:Math.round(element._gsTransform.x / gridWidth) * gridWidth, + y:Math.round(element._gsTransform.y / gridHeight) * gridHeight, + delay:0.1, + ease:Power2.easeInOut + }); + }); + } + update(); + } + */ + + update(); + } +]); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002628_feed.js b/pool/shard000/JavaScript/0002628_feed.js new file mode 100644 index 0000000000000000000000000000000000000000..00f6966dc67ba3c05b99439714141d4911bb5384 --- /dev/null +++ b/pool/shard000/JavaScript/0002628_feed.js @@ -0,0 +1,26 @@ +import uniqBy from 'lodash.uniqby' +import {request} from 'common/request' +import {clone, toSelector} from 'common/utils' + +export const loadFeed = (dao, {filter, limiter, loadFrom, selector}) => { + const cursor = dao.tree.select(toSelector(selector)) + cursor.set('isLoading', true) + + return request(dao, { + query: {limiter, period: filter}, + url: `/ycm/${loadFrom}` + }).then(({data, ids, items}) => data || ids || items) + .finally((res) => cursor.set('isLoading', false)) +} + +export const mergeFeed = (dao, {filter, items, selector}) => { + const cursor = dao.tree.select(toSelector(`${selector}.items.${filter}`)) + const _items = clone(cursor.get()).concat(items) + return cursor.set(uniqBy(_items, ({id}) => id)) +} + +export const setFeed = (dao, {filter, items, selector}) => + dao.tree.set(toSelector(`${selector}.items.${filter}`), items) + +export const setFilter = (dao, {id, selector}) => + dao.tree.set(toSelector(`${selector}.filter`), id) \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002632_participants.suggest_faq_answers.js b/pool/shard000/JavaScript/0002632_participants.suggest_faq_answers.js new file mode 100644 index 0000000000000000000000000000000000000000..a783ee27ccfccf8c1d46d409b394acef444a76c8 --- /dev/null +++ b/pool/shard000/JavaScript/0002632_participants.suggest_faq_answers.js @@ -0,0 +1,77 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent) { + // [START dialogflow_v2beta1_generated_Participants_SuggestFaqAnswers_async] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The name of the participant to fetch suggestion for. + * Format: `projects//locations//conversations//participants/`. + */ + // const parent = 'abc123' + /** + * Optional. The name of the latest conversation message to compile suggestion + * for. If empty, it will be the latest message of the conversation. + * Format: `projects//locations//conversations//messages/`. + */ + // const latestMessage = 'abc123' + /** + * Optional. Max number of messages prior to and including + * latest_message to use as context when compiling the + * suggestion. By default 20 and at most 50. + */ + // const contextSize = 1234 + /** + * Optional. Parameters for a human assist query. + */ + // const assistQueryParams = {} + + // Imports the Dialogflow library + const {ParticipantsClient} = require('@google-cloud/dialogflow').v2beta1; + + // Instantiates a client + const dialogflowClient = new ParticipantsClient(); + + async function callSuggestFaqAnswers() { + // Construct request + const request = { + parent, + }; + + // Run request + const response = await dialogflowClient.suggestFaqAnswers(request); + console.log(response); + } + + callSuggestFaqAnswers(); + // [END dialogflow_v2beta1_generated_Participants_SuggestFaqAnswers_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/pool/shard000/JavaScript/0002635_applyEnv.js b/pool/shard000/JavaScript/0002635_applyEnv.js new file mode 100644 index 0000000000000000000000000000000000000000..32a87df32777916169ad5c588e0f6925167da4f0 --- /dev/null +++ b/pool/shard000/JavaScript/0002635_applyEnv.js @@ -0,0 +1,47 @@ +'use strict' +const composeSections = require('./composeSections') +const coerce = require('coercer') + +/** + * Returns a new object where the environment + * values have been applied the given values. + * + * Additionally, composes sections as described by the wanted section's `compose` + * attribute. + * + * @param {Object} parsed + * The parsed object from the YAML-file. + * + * @param {String} opts.env + * The environment section we want to return. + * + * @param {Object} opts.envObject + * The environment object. + * @param {Object} opts.raw + * If `true`, formats values as strings, if `false`, uses `coercer`. + * + * @return {Object} + * The merged object + * + * @api private + */ +module.exports = function applyEnv(parsed, opts) { + const wantedSection = composeSections(parsed, [opts.env]) + + const result = Object.assign({}, wantedSection, opts.envObject) + return opts.raw ? raw(result) : coerce(result) +} + +/** + * Serializes env values as strings. + */ +function raw(obj) { + const result = {} + for (const key in obj) { + const value = obj[key] + if (value !== null && value !== undefined) { + result[key] = value.toString() + } + } + return result +} diff --git a/pool/shard000/JavaScript/0002636_index.js b/pool/shard000/JavaScript/0002636_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4b396d9e5eeaf10e0f1f1cb8f4bb52db14bdd2fc --- /dev/null +++ b/pool/shard000/JavaScript/0002636_index.js @@ -0,0 +1,34 @@ +'use strict'; + + +exports.blank = function($, _, gulp, mkdirp, rename){ + var _this = this; + + _.forEach(this.folders, function (f) { + mkdirp('./client/app/core/'+f); + mkdirp('./client/app/modules/messages/'+ f); + }) + + this.start('core', function(){ + gulp.src(_this.local.dirs()) + .pipe( $.template( _this._config.all() ) ) + .pipe( $.rename( rename )) + .pipe( gulp.dest( _this.cwd.root() ) ) + }) + +} +exports.skeleton = function($, _, gulp, mkdirp, rename){ + var _this = this; + _.forEach(this.folders, function (f) { + mkdirp('./client/app/core/'+f); + mkdirp('./client/app/modules/messages/'+ f); + }); + + this.start('core', function(){ + gulp.src(_this.local.use('./**/.*', './**/*')) + .pipe( $.template( _this._config.all() ) ) + .pipe( $.rename( rename )) + .pipe( gulp.dest( _this.cwd.root() ) ) + }); + +} diff --git a/pool/shard000/JavaScript/0002637_BitReader.js b/pool/shard000/JavaScript/0002637_BitReader.js new file mode 100644 index 0000000000000000000000000000000000000000..0331c3d4543f6e691e24135c75391aca3de7dd94 --- /dev/null +++ b/pool/shard000/JavaScript/0002637_BitReader.js @@ -0,0 +1,49 @@ + +/** + * Reads unsigned integers encoded in a variable amount of bits from the buffer. + * Bits are aligned into 32bit unsigned integers. + * for example, given 3 integers: + * x: 123 encoded in 11 bits, binary: 00001111011 + * y: 7945 encoded in 17 bits, binary: 00001111100001001 + * z: 12 encoded in 6 bits, binary: 001100 + * + * | --- 32 bits --- || --- 32 bits --- | + * |................................||................................| + * |00001111011000011111000010010011||00 + * | x || y || z | + * + * z does not fit fully into the first 32 bit integer. + * The first 4 bits of z are stored at the end of the first 32 bit integer + * and the remaining 2 bits at the next 32 bit integer. + * + */ +BitReader = function(buf){ + + var buffer = new Uint32Array(buf); + var bitOffset = 0; + + this.read = function(bits){ + var result; + + if((bitOffset % 32) + bits <= 32){ + var val = buffer[Math.floor(bitOffset / 32)]; + var leftGap = bitOffset % 32; + var rightGap = 32 - (leftGap + bits); + + result = (val << leftGap) >>> (leftGap + rightGap); + }else{ + var val = buffer[Math.floor(bitOffset / 32)]; + var leftGap = bitOffset % 32; + var rightGap = (leftGap + bits) - 32; + + result = (val << leftGap) >>> (leftGap - rightGap) + + val = buffer[Math.floor(bitOffset / 32)+1]; + result = result | val >>> (32 - rightGap); + } + + bitOffset += bits; + + return result; + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002639_models.js b/pool/shard000/JavaScript/0002639_models.js new file mode 100644 index 0000000000000000000000000000000000000000..ec7f8017ad1018a96901998fc5f33b108826d0c6 --- /dev/null +++ b/pool/shard000/JavaScript/0002639_models.js @@ -0,0 +1,131 @@ +sap.ui.define([ + "sap/ui/model/json/JSONModel", + "sap/ui/Device", + "sap/ui/model/odata/v2/ODataModel", + "sap/ui/model/resource/ResourceModel" +], function(JSONModel, Device, ODataModel, ResourceModel) { + "use strict"; + + function extendMetadataUrlParameters(aUrlParametersToAdd, oMetadataUrlParams, sServiceUrl) { + var oExtensionObject = {}, + oServiceUri = new URI(sServiceUrl); + + aUrlParametersToAdd.forEach(function(sUrlParam) { + var sLanguage, + oUrlParameters, + sParameterValue; + var fnGetuser = jQuery.sap.getObject("sap.ushell.Container.getUser"); + + // for sap-language we check if the launchpad can provide it. + if (sUrlParam === "sap-language") { + sLanguage = fnGetuser ? fnGetuser().getLanguage() : false; +// sLanguage = fnGetuser().getLanguage(); + + if (sLanguage) { + oMetadataUrlParams["sap-language"] = sLanguage; + return; + } + // Continue searching in the url + } + + oUrlParameters = jQuery.sap.getUriParameters(); + sParameterValue = oUrlParameters.get(sUrlParam); + if (sParameterValue) { + oMetadataUrlParams[sUrlParam] = sParameterValue; + oServiceUri.addSearch(sUrlParam, sParameterValue); + } + }); + + jQuery.extend(oMetadataUrlParams, oExtensionObject); + return oServiceUri.toString(); + } + + return { + /** + * + * @param {object} oOptions a map which contains the following parameter properties + * @param {string} oOptions.url see {@link sap.ui.model.odata.v2.ODataModel#constructor.sServiceUrl}. + * @param {object} [oOptions.urlParametersForEveryRequest] If the parameter is present in the URL or in case of language the UShell can provide it, + * it is added to the odata models metadataUrlParams {@link sap.ui.model.odata.v2.ODataModel#constructor.mParameters.metadataUrlParams}, and to the service url. + * If you provided a value in the config.metadataUrlParams this value will be overwritten by the value in the url. + * + * Example: the app is started with the url query, and the user has an us language set in the launchpad: + * + * ?sap-server=serverValue&sap-host=hostValue + * + * The createODataModel looks like this. + * + * models.createODataModel({ + * urlParametersToPassOn: [ + * "sap-server", + * "sap-language", + * "anotherValue" + * ], + * url : "my/Url" + * }); + * + * then the config will have the following metadataUrlParams: + * + * metadataUrlParams: { + * // retrieved from the url + * "sap-server" : "serverValue" + * // language is added from the launchpad + * "sap-language" : "us" + * // anotherValue is not present in the url and will not be added + * } + * + * @param {object} [oOptions.config] see {@link sap.ui.model.odata.v2.ODataModel#constructor.mParameters} it is the exact same object, the metadataUrlParams are enriched by the oOptions.urlParametersToPassOn + * @returns {sap.ui.model.odata.v2.ODataModel} + */ + createODataModel: function(oOptions) { + var aUrlParametersForEveryRequest, + oConfig, + sUrl; + + oOptions = oOptions || {}; + + if (!oOptions.url) { + jQuery.sap.log.error("Please provide a url when you want to create an ODataModel", "myDevRequests.model.models.createODataModel"); + return null; + } + + // create a copied instance since we modify the config + oConfig = jQuery.extend(true, {}, oOptions.config); + + aUrlParametersForEveryRequest = oOptions.urlParametersForEveryRequest || []; + oConfig.metadataUrlParams = oConfig.metadataUrlParams || {}; + + sUrl = extendMetadataUrlParameters(aUrlParametersForEveryRequest, oConfig.metadataUrlParams, oOptions.url); + + return this._createODataModel(sUrl, oConfig); + }, + + _createODataModel: function(sUrl, oConfig) { + return new ODataModel(sUrl, oConfig); + }, + + createDeviceModel: function() { + var oModel = new JSONModel(Device); + oModel.setDefaultBindingMode("OneWay"); + return oModel; + }, + + createFLPModel: function() { + var fnGetuser = jQuery.sap.getObject("sap.ushell.Container.getUser"), + bIsShareInJamActive = fnGetuser ? fnGetuser().isJamActive() : false, + oModel = new JSONModel({ + isShareInJamActive: bIsShareInJamActive + }); + oModel.setDefaultBindingMode("OneWay"); + return oModel; + }, + + createResourceModel: function(sBundleName) { + var oResourceModel = new ResourceModel({ + "bundleName": sBundleName + }); + return oResourceModel; + } + }; + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002640_audioMixers.js b/pool/shard000/JavaScript/0002640_audioMixers.js new file mode 100644 index 0000000000000000000000000000000000000000..369268552d1bcad34aeadcf1aaa57a57409b6cc7 --- /dev/null +++ b/pool/shard000/JavaScript/0002640_audioMixers.js @@ -0,0 +1,68 @@ +var _ = require('lodash'); +var native = require('../../build/Release/native.node'); + +module.exports = function(app) { + // Define the audio mixer type. + app.store.onCreate('audio-mixer', function(obj) { + obj._sources = []; + + obj.setSources = function(list) { + _.each(obj._sources, function(source) { + source._obj.unref(obj); + }); + + obj._sources = list || []; + + _.each(obj._sources, function(source) { + source._obj.ref(obj); + }); + + obj.emit('sourcesChanged', obj._sources); + }; + + obj.on('destroy', function() { + _.each(obj._sources, function(source) { + source._obj.unref(obj); + }); + }); + + obj.activation('native audio mixer', { + start: function(lg) { + obj._instance = new native.AudioMixer({ + onEvent: onEvent + }); + app.mark(); + + updateSources(obj._sources); + lg.listen(obj, 'sourcesChanged', updateSources); + function updateSources(list) { + obj._instance.setSources(list); + } + }, + stop: function() { + obj._instance.destroy(); + obj._instance = null; + app.mark(); + } + }); + + function onEvent(id, arg) { + switch (id) { + case native.EV_AUDIO_HEADERS: + obj._headers = arg; + app.mark(); + + obj.emit('headers', arg); + break; + + case native.EV_AUDIO_FRAME: + obj.emit('frame', arg); + break; + + default: + obj.handleNativeEvent(id, arg); + break; + } + } + }); +}; diff --git a/pool/shard000/JavaScript/0002641_gdcon.js b/pool/shard000/JavaScript/0002641_gdcon.js new file mode 100644 index 0000000000000000000000000000000000000000..ce88eff6d4ebbfe47acfd94163376409bea3b9e0 --- /dev/null +++ b/pool/shard000/JavaScript/0002641_gdcon.js @@ -0,0 +1,159 @@ +/** + * connect to Google Drive + * (c) 2013, Cybozu. + */ +goog.provide('main.gdcon'); + + +main.gdcon.startRealtime = function() { + realtimeLoader = new rtclient.RealtimeLoader(realtimeOptions); + realtimeLoader.start(); + setInterval(function() { + console.log('re-authorizing' + new Date()); + realtimeLoader.authorizer.authorize(); + console.log('re-authorized' + new Date()); + }, 1000 * 60 * 5); // do auth each 5 minute +}; + + + +/** + * This function is called the first time that the Realtime model is created + * for a file. This function should be used to initialize any values of the + * model. + * @param {gapi.drive.realtime.Model} model the Realtime root model object. + */ +main.gdcon.initializeModel = function(model) { + var field = model.createList(); + model.getRoot().set('my_list', field); +}; + + +/** + * This function is called when the Realtime file has been loaded. It should + * be used to initialize any user interface components and event handlers + * depending on the Realtime model. + * @param {gapi.drive.realtime.Document} doc the Realtime document. + */ +main.gdcon.onFileLoaded = function onFileLoaded(doc) { + /** + * @type {gapi.drive.realtime.CollaborativeList} + */ + main.gdcon._list = doc.getModel().getRoot().get('my_list'); + console.log('doc'); + console.log(doc); + $('#docid').text('OK'); + $('#docid').attr( + 'href', + '../grouping/' + + '#fileIds=' + rtclient.params['fileIds'] + + '&userId=' + realtimeLoader.authorizer.userId); + + // push local items into _list + console.log('merge'); + var _arr = main.gdcon._list.asArray(); + var saved_items = _arr.map(JSON.parse); + items.forEach(function(item){ + var s = JSON.stringify(item); + var found = false; + for(var i=0; i < saved_items.length; i++){ + if(saved_items[i].when == item.when){ + found = true; + console.log('found'); + break; + } + } + if(!found){ + // not saved yet + main.gdcon._list.push(s); + saved_items.push(item); + console.log('pushed'); + } + }); + items = saved_items; + updateJSON(); + updateUI(); + //main.gdcon.updateUI(); +}; + +main.gdcon.push = function(item){ + if(main.gdcon._list){ + main.gdcon._list.push(JSON.stringify(item)); + } +} + + +/** + * @this {rtclient.Authorizer} + */ +main.gdcon.onNeedAuth = function() { + var authorizer = this; + var b = $('#authButton'); + b.click(function(){ + authorizer.authorizeWithPopup(); + b.hide(); + }); + b.show(); +}; + + +/** + * Options for the Realtime loader. + */ +var realtimeOptions = { + appId: '240613571940', + /** + * Client ID from the APIs Console. + */ + clientId: '240613571940.apps.googleusercontent.com', + + /** + * The ID of the button to click to authorize. Must be a DOM element ID. + */ + authButtonElementId: 'authorizeButton', + + onNeedAuth: main.gdcon.onNeedAuth, + onNoNeedAuth: function() { + console.log('no need to auth'); + }, + + /** + * Function to be called when a Realtime model is first created. + */ + initializeModel: main.gdcon.initializeModel, + + /** + * Autocreate files right after auth automatically. + */ + autoCreate: true, + + /** + * The name of newly created Drive files. + */ + defaultTitle: 'My Idea', + + /** + * The MIME type of newly created Drive Files. By default the application + * specific MIME type will be used: + * application/vnd.google-apps.drive-sdk. + */ + newFileMimeType: null, // Using default. + + /** + * Function to be called every time a Realtime file is loaded. + */ + onFileLoaded: main.gdcon.onFileLoaded, + + /** + * Function to be called to inityalize custom Collaborative Objects types. + */ + registerTypes: null, // No action. + + /** + * Function to be called after authorization and before loading files. + */ + afterAuth: function(){ + console.log('after auth'); + console.log(realtimeLoader); + } +}; diff --git a/pool/shard000/JavaScript/0002643_subnav.js b/pool/shard000/JavaScript/0002643_subnav.js new file mode 100644 index 0000000000000000000000000000000000000000..0755340a8d0d898b51d313fd24dae866c95f01f5 --- /dev/null +++ b/pool/shard000/JavaScript/0002643_subnav.js @@ -0,0 +1,89 @@ +/** + * Subnavigation. Handles tab highlighting. + * Replaces most of the rowMark.js functionality. + * + * @author dirk.eschler + */ +var sub = { + + /** + * Highlights the first tab by default (div#navcontainer li#c_0 a) + * by setting the class to 'current'. Is called in subnavigation template. + */ + 'init': function() { + //console.log("init"); + if(document.getElementById('c_0') != null && document.getElementById('c_0').getElementsByTagName('a')) + { + document.getElementById('c_0').getElementsByTagName('a')[0].className = 'current'; + + if(top.frames[0].document.getElementById('help') != null) { + var sElClass = document.getElementById('c_0').getAttribute('class'); + var aElClass = sElClass.split(" "); + top.frames[0].document.getElementById('help').setAttribute('data', aElClass[1]); + } + } + }, + + /** + * Highlights the active tab. + * + * @param {Object} cElm Clicked a-element, resp. the tab to highlight. + * @todo Consider new name ("highlight"?) and rename remaining instances. + */ + 'clicked': function(cElm) { + //console.log("clicked"); + // first unhighlight all tabs + var ul = document.getElementById('navlist'); + var as = ul.getElementsByTagName('a'); + for (var i=0; i<=as.length; i++) { + if (as[i]) { + as[i].className = ''; + } + } + // then highlight the active tab + cElm.className = 'current'; + }, + + /** + * Highlights a tab by its element id. Useful for highlighting from an outer frame. + * + * @param {String} id Element id of tab to highlight + * @param {Object} frame Reference to frame hodling the subnavigation: + * top.content.right.right_top (when there is a left/right frameset) + * top.content.right_top (when there is no left/right frameset) + */ + 'highlightById': function(id, frame) { + var ul = frame.document.getElementById('navlist'); + var as = ul.getElementsByTagName('a'); + for (var i=0; i<=as.length; i++) { + if (as[i]) { + as[i].className = ''; + } + } + frame.document.getElementById(id).getElementsByTagName('a')[0].className = 'current'; + }, + + /** + * Unhighlights all tabs. + */ + /* + 'unhighlight': function() { + var ul = this.frame.document.getElementById('navlist'); + var as = ul.getElementsByTagName('a'); + for (var i=0; i<=as.length; i++) { + if (as[i]) { + as[i].className = ''; + } + } + },*/ + + /** + * Dummy method to avoid breakage. + * + * @todo Locate remaining inline calls to sub.click() and remove them + */ + 'click': function() { + //console.log("remove me"); + return; + } +}; diff --git a/pool/shard000/JavaScript/0002644_cpal.js b/pool/shard000/JavaScript/0002644_cpal.js new file mode 100644 index 0000000000000000000000000000000000000000..326b719e9188c4f2bd952adcebe04dd2daff09a7 --- /dev/null +++ b/pool/shard000/JavaScript/0002644_cpal.js @@ -0,0 +1,122 @@ +#!/usr/bin/env node + +/*********************** + * Wire up requirejs * + ***********************/ + +var requirejs = require('requirejs'); + +requirejs.config({ + baseUrl : __dirname + '/includes', + nodeRequire : require +}); + +/************* + * Imports * + *************/ + +var fs = require('fs'); +var Canvas = require('canvas'); +var rgb = requirejs('imgdata2rgb'); +var mcut = requirejs('mcut')(); +var formats = requirejs('formats'); + +var canvas_width = 128; +var canvas_height = 128; +var canvas = new Canvas(canvas_height, canvas_width); +var ctx = canvas.getContext('2d'); +var Image = Canvas.Image; + +var format; +var formats_string = Object.keys(formats); +formats_string = formats_string.join(', '); + +/**************************************** + * command line options with optimism! * + ****************************************/ + +var argv = require('optimist') + + .usage('Generate a color palette from an image! :)\nUSAGE: node cpal.js IMAGE') + + // -f or --fixed + .options('s', { + alias: 'size', + describe: 'Generate a fixed size palette; you specify the number of colors you want.' + }) + + // -d or --dynamic + .options('d', { + alias: 'dynamic', + describe: 'Generate a palette, sized dynamically based on the color diversity of the image; you can optionally specify a number from 0.0 to 1.0, where larger numbers increase the number of colors.' + }) + + // -d or --dynamic + .options('f', { + default: "json", + alias: 'format', + describe: 'Specify the output format. Available formats are: ' + formats_string + }) + + .demand(1) // at least 1 image must be specified + + .check(function (args) { + var d_num = args.d && typeof args.d === "number", + s_num = args.s && typeof args.s === "number"; + if (args.f && Object.keys(formats).indexOf(args.f) !== -1) { + format = formats[args.f]; + } + return d_num && s_num; + }) + + .argv; + +var palette_types = { + fixed: 'get_fixed_size_palette', + dynamic: 'get_dynamic_size_palette' +}; + +var images = argv._; +var src; +var num; +var i; +var type; + +if (argv.s) { + type = palette_types.fixed; + num = argv.s; +} else { + type = palette_types.dynamic; + num = argv.d || 0.4; // default dynamic scale 0.4 +} + +function get_colors (img) { + var data = rgb(img), + palette, + output; + mcut.init(data); + palette = mcut[type](num); + output = format(palette); + console.log(output); +} + +for (i = 0; i < images.length; i += 1) { + (function (image_name) { + fs.readFile(images[i], function(err, image_file){ + if (err) { + throw err; + } + + if (images.length > 1) { + console.log('\n' + image_name + '\n'); + } + + var img = new Image(); + var pixels; + img.src = image_file; + ctx.drawImage(img, 0, 0, canvas_height, canvas_width); + pixels = ctx.getImageData(0, 0, canvas_height, canvas_width); + get_colors(pixels.data); + }); + }(images[i])); +} diff --git a/pool/shard000/JavaScript/0002646_verpontos.js b/pool/shard000/JavaScript/0002646_verpontos.js new file mode 100644 index 0000000000000000000000000000000000000000..5cdb2c537f6e6a34c7663de3152c5071ebbf7060 --- /dev/null +++ b/pool/shard000/JavaScript/0002646_verpontos.js @@ -0,0 +1,57 @@ +//Throw this in your console tab, F12 at browser then console tab. Refresh your page to unload the script. +//commands = /uid @:name:, example: /uid @Isly | chat reply 'User @Isly statistics: djPoints: 10691 | listenerPoints: 11415 | fans: 289 | grabPoints: 513' +API.on(API.CHAT_COMMAND, command); +function command(value) { + + if(value.indexOf("/ver @") >=0) + { + userIdCommand(value); + } +} + + function userIdCommand(data) + { + var name = data.substr(6).trim(); + var pos = checkUsername(name); + if(pos != null){ + var id = getUserId(name); + var points = API.getUser(id).djPoints; + var listenerPoints = API.getUser(id).listenerPoints; + var fans = API.getUser(id).fans; + var curatorPoints = API.getUser(id).curatorPoints; + API.chatLog(" O Id do usuario " + name + " é : " + id); + API.chatLog("Usuario @" + name + " Pontos Tocando: " + points + " / Pontos Avaliando: " + listenerPoints + " / Fans: " + fans + " / Pontos de Grab: " + curatorPoints); + } + } + + function checkUsername(name) + { + var userlist = API.getUsers(); + + for(var i=0; i < userlist.length; i++) + { + if(userlist[i].username == name) + { + var pos = i; + break; + }else{ + var pos = null; + } + } + return pos; + } + + function getUserId(name) + { + var userlist = API.getUsers(); + + for(var i=0; i < userlist.length; i++) + { + if(userlist[i].username == name) + { + var userid = userlist[i].id; + break; + } + } + return userid; + } diff --git a/pool/shard000/JavaScript/0002650_redeyed-smoke.js b/pool/shard000/JavaScript/0002650_redeyed-smoke.js new file mode 100644 index 0000000000000000000000000000000000000000..cf6c81b38a36898b639b92ef53212f26098cfd72 --- /dev/null +++ b/pool/shard000/JavaScript/0002650_redeyed-smoke.js @@ -0,0 +1,57 @@ +'use strict'; +/*jshint asi: true*/ + +// applying redeyed to a bunch of files of contained libraries as a smoke test +var test = require('tap').test + , path = require('path') + , fs = require('fs') + , readdirp = require('readdirp') + , redeyed = require('..') + , node_modules = path.join(__dirname, '..', 'node_modules') + , tapdir = path.join(node_modules, 'tap') + , esprimadir = path.join(node_modules, 'esprima') + +test('tap', function (t) { + var invalidTapFiles = [ + 'async-map-ordered.js' + , 'prof.js' + ] + + readdirp({ root: tapdir, fileFilter: '*.js' }) + .on('data', function (entry) { + + if (~invalidTapFiles.indexOf(entry.name)) return + + var code = fs.readFileSync(entry.fullPath, 'utf-8') + , result = redeyed(code, { Keyword: { 'var': '+:-' } }).code + + t.assert(~result.indexOf('+var-') || !(~result.indexOf('var ')), 'redeyed ' + entry.path) + }) + .on('end', t.end.bind(t)) +}) + +test('esprima', function (t) { + + readdirp({ root: esprimadir, fileFilter: '*.js' }) + .on('data', function (entry) { + + var code = fs.readFileSync(entry.fullPath, 'utf-8') + , result = redeyed(code, { Keyword: { 'var': '+:-' } }).code + + t.assert(~result.indexOf('+var-') || !(~result.indexOf('var ')), 'redeyed ' + entry.path) + }) + .on('end', t.end.bind(t)) +}) + +test('redeyed', function (t) { + + readdirp({ root: path.join(__dirname, '..'), fileFilter: '*.js', directoryFilter: ['!.git', '!node_modules' ] }) + .on('data', function (entry) { + + var code = fs.readFileSync(entry.fullPath, 'utf-8') + , result = redeyed(code, { Keyword: { 'var': '+:-' } }).code + + t.assert(~result.indexOf('+var-') || !(~result.indexOf('var ')), 'redeyed ' + entry.path) + }) + .on('end', t.end.bind(t)) +}) diff --git a/pool/shard000/JavaScript/0002654_iscroll.js b/pool/shard000/JavaScript/0002654_iscroll.js new file mode 100644 index 0000000000000000000000000000000000000000..4b0fc71ac21f05c5925382e20171539dd0630daa --- /dev/null +++ b/pool/shard000/JavaScript/0002654_iscroll.js @@ -0,0 +1,10 @@ + +function infiniteLoad(callback) { + $(window).on('scroll', function () { + var h1 = $(document).height() - $(window).height(); + var h2 = $(window).scrollTop() + 350; // start loading before user can see the change + if (h2 >= h1) { + callback(); + } + }); +} diff --git a/pool/shard000/JavaScript/0002659_index.js b/pool/shard000/JavaScript/0002659_index.js new file mode 100644 index 0000000000000000000000000000000000000000..1a77d53bfd47aae6d4897a31ef23c9d93233db89 --- /dev/null +++ b/pool/shard000/JavaScript/0002659_index.js @@ -0,0 +1,206 @@ +var is = require('matthewp-is'); + +module.exports = Map; + +/** + * @param {any} element + * @return {Number} +**/ +function indexOf (element) { + for (var i = this.length; i-- && !is(this[i], element);) {} + return i; +} + + + + +/** + * @class Map + * @constructor + * @param {Array} iterable +**/ +function Map (iterable) { + this._keys = []; + this._values = []; + + if (iterable) { + for (var i = -1, l = iterable.length; ++i < l;) { + this.set(iterable[i][0], iterable[i][1]); + } + } +} + +/** + * get entry value associated with `key` + * @method get + * @param {any} key + * @return {any} +**/ +Map.prototype.get = function (key) { + return this._values[indexOf.call(this._keys, key)]; +}; + +/** + * set entry value associated with `key` + * @method set + * @chainable + * @param {any} key + * @param {any} value + * @return {Hash} +**/ +Map.prototype.set = function (key, value) { + var index = indexOf.call(this._keys, key); + + if (index > -1) { + this._values[index] = value; + } else { + this._keys.push(key); + this._values.push(value); + } + + return this; +}; + +/** + * remove entry key and value with `key` + * @method delete + * @param {any} key + * @return {Boolean} +**/ +Map.prototype.delete = function (key) { + var index = indexOf.call(this._keys, key); + + if (index > -1) { + this._keys.splice(index, 1); + this._values.splice(index, 1); + return true; + } + + return false; +}; + +/** + * entry existence + * @method has + * @param {any} key + * @return {Boolean} +**/ +Map.prototype.has = function (key) { + return indexOf.call(this._keys, key) > -1 ? true : false; +}; + + +/** + * remove all entries + * @method clear +**/ +Map.prototype.clear = function () { + this._keys.splice(0); + this._values.splice(0); +}; + +/** + * numbers of entries + * @readonly + * @property size + * @type {Number} + * @default 0 +**/ +Object.defineProperty(Map.prototype, 'size', { + configurable: true, + get: function () { + return this._keys.length; + } +}); + +/** + * call `callback` with `context` as this for all entries with (value, key, hash) + * @method forEach + * @param {Function} callback + * @param {Object} context +**/ +Map.prototype.forEach = function (callback, context) { + for (var i = -1, l = this._keys.length; ++i < l;) { + callback.call(context, this._values[i], this._keys[i], this); + } +}; + +/** + * iterator over `kind` + * @method iterator + * @param {String} kind + * @return {MapIterator} +**/ +Map.prototype.iterator = function (kind) { + return new MapIterator(this, kind); +}; + +/** + * iterator over keys + * @method keys + * @return {MapIterator} +**/ +Map.prototype.keys = function () { + return this.iterator('key'); +}; + +/** + * iterator over values + * @method values + * @return {MapIterator} +**/ +Map.prototype.values = function () { + return this.iterator('value'); +}; + +/** + * iterator over entries + * @method entries + * @return {MapIterator} +**/ +Map.prototype.entries = Map.prototype.__iterator__ = function () { + return this.iterator('key+value'); +}; + + + + +/** + * @class MapIterator + * @constructor + * @param {Map} map + * @param {String} kind + * @return {MapIterator} +**/ +function MapIterator (map, kind) { + this._index = 0; + this._keys = map._keys; + this._values = map._values; + this._kind = kind; +} + +/** + * iterate over key/value/entry + * @method next + * @return {any} +**/ +MapIterator.prototype.next = function () { + var key = this._keys[this._index] !== undefined ? this._keys[this._index] : null; + var value = this._values[this._index] !== undefined ? this._values[this._index] : null; + + this._index++; + + switch (this._kind) { + case 'key': + return key; + break; + + case 'value': + return value; + break; + + case 'key+value': + return key != null || value != null ? [key, value] : null; + break; + } +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002662_travel-manager.js b/pool/shard000/JavaScript/0002662_travel-manager.js new file mode 100644 index 0000000000000000000000000000000000000000..3e4e12f861304ccc1a2d4da04b7099612dfa074c --- /dev/null +++ b/pool/shard000/JavaScript/0002662_travel-manager.js @@ -0,0 +1,43 @@ +System.register(['./travel'], function(exports_1, context_1) { + "use strict"; + var __moduleName = context_1 && context_1.id; + var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + var travel_1; + var TravelManager, SampleTravelManager; + return { + setters:[ + function (travel_1_1) { + travel_1 = travel_1_1; + }], + execute: function() { + TravelManager = (function () { + function TravelManager() { + this.list = []; + } + TravelManager.prototype.find = function (id) { + return this.list.filter(function (c) { return c.id == id; })[0]; + }; + TravelManager.prototype.remove = function (travel) { + var index = this.list.indexOf(travel); + this.list.splice(index, 1); + }; + return TravelManager; + }()); + exports_1("TravelManager", TravelManager); + SampleTravelManager = (function (_super) { + __extends(SampleTravelManager, _super); + function SampleTravelManager() { + _super.call(this); + this.list.push(new travel_1.Travel("SF2015", "San Francisco", "USA", 2015, "sanfrancisco.jpg"), new travel_1.Travel("NA2014", "Nantes", "France", 2014, "nantes.jpg"), new travel_1.Travel("BX2014", "Bruxelles", "Belgique", 2014, "bruxelles.jpg"), new travel_1.Travel("YO2014", "Yosemite", "USA", 2014, "yosemite.jpg"), new travel_1.Travel("BT2013", "Bretagne", "France", 2013, "bretagne.jpg")); + } + return SampleTravelManager; + }(TravelManager)); + exports_1("SampleTravelManager", SampleTravelManager); + } + } +}); +//# sourceMappingURL=travel-manager.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002663_autosave.js b/pool/shard000/JavaScript/0002663_autosave.js new file mode 100644 index 0000000000000000000000000000000000000000..f61b59da933b5824d96a2275244ba481fb5114a0 --- /dev/null +++ b/pool/shard000/JavaScript/0002663_autosave.js @@ -0,0 +1,259 @@ +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see . +/* global NOTIFY_WARNING, NOTIFY_INFO */ +/* eslint-disable no-unused-vars */ + +/** + * A autosave function for the Atto editor. + * + * @module moodle-editor_atto-autosave + * @submodule autosave-base + * @package editor_atto + * @copyright 2014 Damyon Wiese + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +var SUCCESS_MESSAGE_TIMEOUT = 5000, + RECOVER_MESSAGE_TIMEOUT = 60000, + LOGNAME_AUTOSAVE = 'moodle-editor_atto-editor-autosave'; + +function EditorAutosave() {} + +EditorAutosave.ATTRS= { + /** + * Enable/Disable auto save for this instance. + * + * @attribute autosaveEnabled + * @type Boolean + * @writeOnce + */ + autosaveEnabled: { + value: true, + writeOnce: true + }, + + /** + * The time between autosaves (in seconds). + * + * @attribute autosaveFrequency + * @type Number + * @default 60 + * @writeOnce + */ + autosaveFrequency: { + value: 60, + writeOnce: true + }, + + /** + * Unique hash for this page instance. Calculated from $PAGE->url in php. + * + * @attribute pageHash + * @type String + * @writeOnce + */ + pageHash: { + value: '', + writeOnce: true + } +}; + +EditorAutosave.prototype = { + + /** + * The text that was auto saved in the last request. + * + * @property lastText + * @type string + */ + lastText: "", + + /** + * Autosave instance. + * + * @property autosaveInstance + * @type string + */ + autosaveInstance: null, + + /** + * Initialize the autosave process + * + * @method setupAutosave + * @chainable + */ + setupAutosave: function() { + var draftid = -1, + form, + optiontype = null, + options = this.get('filepickeroptions'), + params; + + if (!this.get('autosaveEnabled')) { + // Autosave disabled for this instance. + return; + } + + this.autosaveInstance = Y.stamp(this); + for (optiontype in options) { + if (typeof options[optiontype].itemid !== "undefined") { + draftid = options[optiontype].itemid; + } + } + + // First see if there are any saved drafts. + // Make an ajax request. + params = { + contextid: this.get('contextid'), + action: 'resume', + draftid: draftid, + elementid: this.get('elementid'), + pageinstance: this.autosaveInstance, + pagehash: this.get('pageHash') + }; + + this.autosaveIo(params, this, { + success: function(response) { + if (response === null) { + // This can happen when there is nothing to resume from. + return; + } else if (!response) { + Y.log('Invalid response received.', 'debug', LOGNAME_AUTOSAVE); + return; + } + + // Revert untouched editor contents to an empty string. + // Check for FF and Chrome. + if (response.result === '

    ' || response.result === '


    ' || + response.result === '
    ') { + response.result = ''; + } + + // Check for IE 9 and 10. + if (response.result === '

     

    ' || response.result === '


     

    ') { + response.result = ''; + } + + if (response.error || typeof response.result === 'undefined') { + Y.log('Error occurred recovering draft text: ' + response.error, 'debug', LOGNAME_AUTOSAVE); + this.showMessage(M.util.get_string('errortextrecovery', 'editor_atto'), + NOTIFY_WARNING, RECOVER_MESSAGE_TIMEOUT); + } else if (response.result !== this.textarea.get('value') && + response.result !== '') { + Y.log('Autosave text found - recover it.', 'debug', LOGNAME_AUTOSAVE); + this.recoverText(response.result); + } + this._fireSelectionChanged(); + + }, + failure: function() { + this.showMessage(M.util.get_string('errortextrecovery', 'editor_atto'), + NOTIFY_WARNING, RECOVER_MESSAGE_TIMEOUT); + } + }); + + // Now setup the timer for periodic saves. + var delay = parseInt(this.get('autosaveFrequency'), 10) * 1000; + Y.later(delay, this, this.saveDraft, false, true); + + // Now setup the listener for form submission. + form = this.textarea.ancestor('form'); + if (form) { + this.autosaveIoOnSubmit(form, { + action: 'reset', + contextid: this.get('contextid'), + elementid: this.get('elementid'), + pageinstance: this.autosaveInstance, + pagehash: this.get('pageHash') + }); + } + return this; + }, + + /** + * Recover a previous version of this text and show a message. + * + * @method recoverText + * @param {String} text + * @chainable + */ + recoverText: function(text) { + this.editor.setHTML(text); + this.saveSelection(); + this.updateOriginal(); + this.lastText = text; + + this.showMessage(M.util.get_string('textrecovered', 'editor_atto'), + NOTIFY_INFO, RECOVER_MESSAGE_TIMEOUT); + + return this; + }, + + /** + * Save a single draft via ajax. + * + * @method saveDraft + * @chainable + */ + saveDraft: function() { + var url, params; + // Only copy the text from the div to the textarea if the textarea is not currently visible. + if (!this.editor.get('hidden')) { + this.updateOriginal(); + } + var newText = this.textarea.get('value'); + + if (newText !== this.lastText) { + Y.log('Autosave text', 'debug', LOGNAME_AUTOSAVE); + + // Make an ajax request. + url = M.cfg.wwwroot + this.get('autosaveAjaxScript'); + params = { + sesskey: M.cfg.sesskey, + contextid: this.get('contextid'), + action: 'save', + drafttext: newText, + elementid: this.get('elementid'), + pagehash: this.get('pageHash'), + pageinstance: this.autosaveInstance + }; + + // Reusable error handler - must be passed the correct context. + var ajaxErrorFunction = function(response) { + var errorDuration = parseInt(this.get('autosaveFrequency'), 10) * 1000; + Y.log('Error while autosaving text', 'warn', LOGNAME_AUTOSAVE); + Y.log(response, 'warn', LOGNAME_AUTOSAVE); + this.showMessage(M.util.get_string('autosavefailed', 'editor_atto'), NOTIFY_WARNING, errorDuration); + }; + + this.autosaveIo(params, this, { + failure: ajaxErrorFunction, + success: function(response) { + if (response && response.error) { + Y.soon(Y.bind(ajaxErrorFunction, this, [response])); + } else { + // All working. + this.lastText = newText; + this.showMessage(M.util.get_string('autosavesucceeded', 'editor_atto'), + NOTIFY_INFO, SUCCESS_MESSAGE_TIMEOUT); + } + } + }); + } + return this; + } +}; + +Y.Base.mix(Y.M.editor_atto.Editor, [EditorAutosave]); diff --git a/pool/shard000/JavaScript/0002664_Shader.js b/pool/shard000/JavaScript/0002664_Shader.js new file mode 100644 index 0000000000000000000000000000000000000000..99343122db1d3640e9c3839605a1740a2cdcfe98 --- /dev/null +++ b/pool/shard000/JavaScript/0002664_Shader.js @@ -0,0 +1,63 @@ +module.exports = (function() { + /// + /// Pulls a shader script from the specified DOM element (script_id), and attempts to compile it as either a vertex or fragment shader. + /// + function buildShaderScript(gl, script_id) { + var script = document.getElementById(script_id); + + if (!script) { + throw("ERROR: Invalid shader script_id (" + script_id + ")"); + } + else { + if (script.type == "x-shader/x-vertex") { + //Compiles and returns a vertex shader from script. + return compile(gl, script.text, gl.VERTEX_SHADER); + } + else if (script.type == "x-shader/x-fragment") { + //Compiles and returns a fragment shader from script. + return compile(gl, script.text, gl.FRAGMENT_SHADER); + } + else { + throw("ERROR: Invalid shader type (" + script.type +")"); + } + } + } + + /// + /// Attempts to compile the supplied shader script into a WebGL shader object. + /// + function compile(gl, src, type) { + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + throw("ERROR: Unable to compile shader (" + gl.getShaderInfoLog(shader) + ")"); + } + return shader; + } + + /// + /// Attempts to attach both a vertex and fragment shader to a newly created WebGL program + /// + function newProgram(gl, vert, frag) { + var prog = gl.createProgram(); + + gl.attachShader(prog, vert); + gl.attachShader(prog, frag); + gl.linkProgram(prog); + + if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) { + throw("ERROR: Shader Program failed to link (" + gl.getProgramInfoLog(prog) + ")"); + } + + return prog; + } + + return { + buildShaderScript: buildShaderScript, + compile: compile, + newProgram: newProgram + }; +})(); diff --git a/pool/shard000/JavaScript/0002665_compiler.js b/pool/shard000/JavaScript/0002665_compiler.js new file mode 100644 index 0000000000000000000000000000000000000000..93371191aab6ca3b493367a6b2e183ead9f8473a --- /dev/null +++ b/pool/shard000/JavaScript/0002665_compiler.js @@ -0,0 +1,60 @@ +// MySQL Schema Compiler +// ------- +const inherits = require('inherits'); +const SchemaCompiler = require('../../../schema/compiler'); + +const some = require('lodash/some'); + +function SchemaCompiler_MySQL(client, builder) { + SchemaCompiler.call(this, client, builder); +} +inherits(SchemaCompiler_MySQL, SchemaCompiler); + +Object.assign(SchemaCompiler_MySQL.prototype, { + // Rename a table on the schema. + renameTable(tableName, to) { + this.pushQuery( + `rename table ${this.formatter.wrap(tableName)} to ${this.formatter.wrap( + to + )}` + ); + }, + + // Check whether a table exists on the query. + hasTable(tableName) { + let sql = 'select * from information_schema.tables where table_name = ?'; + const bindings = [tableName]; + + if (this.schema) { + sql += ' and table_schema = ?'; + bindings.push(this.schema); + } else { + sql += ' and table_schema = database()'; + } + + this.pushQuery({ + sql, + bindings, + output: function output(resp) { + return resp.length > 0; + }, + }); + }, + + // Check whether a column exists on the schema. + hasColumn(tableName, column) { + this.pushQuery({ + sql: `show columns from ${this.formatter.wrap(tableName)}`, + output(resp) { + return some(resp, (row) => { + return ( + this.client.wrapIdentifier(row.Field) === + this.client.wrapIdentifier(column) + ); + }); + }, + }); + }, +}); + +module.exports = SchemaCompiler_MySQL; diff --git a/pool/shard000/JavaScript/0002667_exercisesLib.js b/pool/shard000/JavaScript/0002667_exercisesLib.js new file mode 100644 index 0000000000000000000000000000000000000000..78ce0fdd6f804dc638878f3ff9bc1e5d05609273 --- /dev/null +++ b/pool/shard000/JavaScript/0002667_exercisesLib.js @@ -0,0 +1,100 @@ +/** + * Created by wizard on 11/14/16. + */ +const Promise = require('bluebird').Promise, + Punching = require('../models/punchingRecord'), + logger = require('../libs/ironmanLogger'); + +module.exports.punchingHomeworkForParent = function (user) { + if (user.linkedUserMails == undefined || user.linkedUserMails.length == 0) { + return new Promise(function (resolve) { + resolve([]); + }); + } + + const mails = user.linkedUserMails; + + let promises = mails.map((mail)=> { + let type = Punching.PunchingType.homework; + return Punching.PunchingRecordModel.find({mail, type}).exec(); + }); + + let datas = []; + + return Promise.all(promises) + .then((arrayOfRecords)=> { + + arrayOfRecords.map((records, index) => { + datas[index] = {mail: mails[index], count: records.length} + }); + + let ps = mails.map((mail)=> { + let type = Punching.PunchingType.homework; + return Punching.isPunchedToday(mail, type); + }); + + return Promise.all(ps); + }) + + .then((arrayOfIsPunched)=> { + arrayOfIsPunched.map((isPunched, index) => { + datas[index]["today"] = isPunched; + }); + + return new Promise(function (resolve) { + resolve(datas); + }); + }) + + .catch((e)=> { + logger.error(e.message); + throw e; + }) +}; + +function punchingRecords(user, type) { + if (user.isStudent) { + let mail = user.mail; + const promise = Punching.PunchingRecordModel.find({mail, type}).exec(); + return Promise.all([promise]); + } + + if (user.linkedUserMails == undefined || user.linkedUserMails.length == 0) { + return new Promise(function (resolve) { + resolve([]); + }); + } + + const mails = user.linkedUserMails; + + let promises = mails.map((mail)=> { + return Punching.PunchingRecordModel.find({mail, type}).exec(); + }); + + return Promise.all(promises) + .catch((e)=> { + logger.error(e.message); + throw e; + }) +} + +module.exports.homeworkPunchingRecords = function (user) { + return punchingRecords(user, Punching.PunchingType.homework); +}; + + +module.exports.wordPunchingRecords = function (user) { + return punchingRecords(user, Punching.PunchingType.word); +}; + +module.exports.punchForChild = function (user, childMail, type) { + return Punching.isPunchedToday(childMail, type) + .then((succeed)=> { + if (succeed) { + return Promise.resolve(succeed); + } + else { + return Punching.punchToday(childMail, type); + } + }); +}; diff --git a/pool/shard000/JavaScript/0002668_ArabicNumberMap.js b/pool/shard000/JavaScript/0002668_ArabicNumberMap.js new file mode 100644 index 0000000000000000000000000000000000000000..0d59c637d506d791f5d1c202e595bc329c70ddb4 --- /dev/null +++ b/pool/shard000/JavaScript/0002668_ArabicNumberMap.js @@ -0,0 +1,43 @@ +'use strict'; + +let should = require('chai').should(), + describe = require('mocha').describe, + it = require('mocha').it; + +describe('ArabicNumberMap class', function () { + + let ArabicNumberMap = require('../roman-numerals').ArabicNumberMap; + + it('should be an object', function () { + + ArabicNumberMap.should.be.a('object'); + + }); + + describe('should return the correct roman numeral values for given arabic number values', function () { + + function checkRomanValueForArabicNumber(arabicNumber, expectedRomanValue) { + let romanValue = ArabicNumberMap[arabicNumber]; + + romanValue.should.be.a('string'); + romanValue.should.equal(expectedRomanValue); + } + + it('should contain all necessary roman numerals for arabic numbers 1 through 1000', function () { + checkRomanValueForArabicNumber(1000,'M'); + checkRomanValueForArabicNumber(900,'CM'); + checkRomanValueForArabicNumber(500,'D'); + checkRomanValueForArabicNumber(400,'CD'); + checkRomanValueForArabicNumber(100,'C'); + checkRomanValueForArabicNumber(90,'XC'); + checkRomanValueForArabicNumber(50,'L'); + checkRomanValueForArabicNumber(40,'XL'); + checkRomanValueForArabicNumber(10,'X'); + checkRomanValueForArabicNumber(9,'IX'); + checkRomanValueForArabicNumber(5,'V'); + checkRomanValueForArabicNumber(4,'IV'); + }); + + }); + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002669_equation.js b/pool/shard000/JavaScript/0002669_equation.js new file mode 100644 index 0000000000000000000000000000000000000000..99fbe392f410a546569908f26d7c698baa26aec7 --- /dev/null +++ b/pool/shard000/JavaScript/0002669_equation.js @@ -0,0 +1,202 @@ +import assert from 'assert'; +import sinon from 'sinon'; +import Matrix from '../../src/recurrent/matrix'; +import OnesMatrix from '../../src/recurrent/matrix/ones-matrix'; +import Equation from '../../src/recurrent/matrix/equation'; + +function fourSquareMatrix(value) { + var result = new Matrix(4, 4); + result.weights.forEach((_, i) => { + result.weights[i] = value; + }); + return result; +} + +describe('equation', () => { + describe('run', () => { + it('calls all forwardFn properties', () => { + var equation = new Equation(); + for (var i = 0; i < 10; i++) { + equation.states.push({ + forwardFn: sinon.spy() + }) + } + equation.runIndex(); + equation.states.forEach((state) => { + assert(state.forwardFn.called); + }); + }); + }); + describe('runBack', () => { + it('calls all forwardFn properties', () => { + var equation = new Equation(); + for (var i = 0; i < 10; i++) { + equation.states.push({ + backpropagationFn: sinon.spy() + }) + } + equation.backpropagate(); + equation.states.forEach((state) => { + assert(state.backpropagationFn.called); + }); + }); + }); + describe('add', () => { + it('calls forwardFn', () => { + var equation = new Equation(); + var input = fourSquareMatrix(1); + equation.add(input, fourSquareMatrix(1)); + assert.equal(equation.states.length, 1); + sinon.spy(equation.states[0], 'forwardFn'); + equation.runIndex(); + assert(equation.states[0].forwardFn.called); + }); + }); + describe('multiply', () => { + it('calls forwardFn', () => { + var equation = new Equation(); + var input = fourSquareMatrix(1); + equation.multiply(input, fourSquareMatrix(1)); + assert.equal(equation.states.length, 1); + sinon.spy(equation.states[0], 'forwardFn'); + equation.runIndex(); + assert(equation.states[0].forwardFn.called); + }); + }); + describe('multiplyElement', () => { + it('calls forwardFn', () => { + var equation = new Equation(); + var input = fourSquareMatrix(1); + equation.add(input, fourSquareMatrix(1)); + assert.equal(equation.states.length, 1); + sinon.spy(equation.states[0], 'forwardFn'); + equation.runIndex(); + assert(equation.states[0].forwardFn.called); + }); + }); + describe('relu', () => { + it('calls forwardFn', () => { + var equation = new Equation(); + var input = fourSquareMatrix(1); + equation.add(input, fourSquareMatrix(1)); + assert.equal(equation.states.length, 1); + sinon.spy(equation.states[0], 'forwardFn'); + equation.runIndex(); + assert(equation.states[0].forwardFn.called); + }); + }); + describe('inputMatrixToRow', () => { + it('calls forwardFn', () => { + var equation = new Equation(); + var input = fourSquareMatrix(1); + equation.add(input, fourSquareMatrix(1)); + assert.equal(equation.states.length, 1); + sinon.spy(equation.states[0], 'forwardFn'); + equation.runIndex(); + assert(equation.states[0].forwardFn.called); + }); + }); + describe('sigmoid', () => { + it('calls forwardFn', () => { + var equation = new Equation(); + var input = fourSquareMatrix(1); + equation.add(input, fourSquareMatrix(1)); + assert.equal(equation.states.length, 1); + sinon.spy(equation.states[0], 'forwardFn'); + equation.runIndex(); + assert(equation.states[0].forwardFn.called); + }); + }); + describe('tanh', () => { + it('calls forwardFn', () => { + var equation = new Equation(); + var input = fourSquareMatrix(1); + equation.add(input, fourSquareMatrix(1)); + assert.equal(equation.states.length, 1); + sinon.spy(equation.states[0], 'forwardFn'); + equation.runIndex(); + assert(equation.states[0].forwardFn.called); + }); + }); + describe('nesting', () => { + it('can nest 3 deep and run forward', () => { + var equation = new Equation(); + var input = fourSquareMatrix(2); + equation.multiply(equation.multiply(equation.multiply(input, fourSquareMatrix(2)), fourSquareMatrix(2)), fourSquareMatrix(2)); + assert.equal(equation.states.length, 3); + sinon.spy(equation.states[0], 'forwardFn'); + sinon.spy(equation.states[1], 'forwardFn'); + sinon.spy(equation.states[2], 'forwardFn'); + equation.runIndex(); + equation.states.forEach((state) => { + assert(state.forwardFn.called); + }); + }); + it('can nest 3 deep and run backward', () => { + var equation = new Equation(); + var input = fourSquareMatrix(2); + equation.tanh(equation.multiply(equation.add(input, fourSquareMatrix(2)), fourSquareMatrix(2)), fourSquareMatrix(2)); + assert.equal(equation.states.length, 3); + sinon.spy(equation.states[0], 'backpropagationFn'); + sinon.spy(equation.states[1], 'backpropagationFn'); + sinon.spy(equation.states[2], 'backpropagationFn'); + equation.backpropagate(); + equation.states.forEach((state) => { + assert(state.backpropagationFn.called); + }); + }); + }); + describe('inputMatrixToRow', () => { + context('runIndex', () => { + it('can properly split up a matrix', () => { + var input = new Matrix(2, 2); + /** + * Matrix like: + * 1 1 + * 2 2 + */ + input.weights.forEach((w, i) => { + if (i < 2) { + input.weights[i] = 1; + } else { + input.weights[i] = 2; + } + }); + var equation = new Equation(); + equation.add(new OnesMatrix(1, 2), equation.inputMatrixToRow(input)); + var output = equation.runIndex(); + assert.equal(output.weights.length, 2); + assert.equal(output.weights[0], 2); + assert.equal(output.weights[1], 2); + + output = equation.runIndex(1); + assert.equal(output.weights.length, 2); + assert.equal(output.weights[0], 3); + assert.equal(output.weights[1], 3); + }); + }); + context('.backpropagate()', () => { + it('can properly split up a matrix', () => { + var input = new Matrix(2, 2); + /** + * Matrix like: + * 1 1 + * 2 2 + */ + input.weights.forEach((w, i) => { + if (i < 2) { + input.weights[i] = 1; + } else { + input.weights[i] = 2; + } + }); + var equation = new Equation(); + equation.add(new OnesMatrix(1, 2), equation.inputMatrixToRow(input)); + var output = equation.runIndex(); + assert.equal(output.weights.length, 2); + output = equation.runIndex(1); + assert.equal(output.weights.length, 2); + }); + }); + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002671_view-omic-overview-national.js b/pool/shard000/JavaScript/0002671_view-omic-overview-national.js new file mode 100644 index 0000000000000000000000000000000000000000..188f9277e0558abd65abae11d26e91b8c995f461 --- /dev/null +++ b/pool/shard000/JavaScript/0002671_view-omic-overview-national.js @@ -0,0 +1,119 @@ +const expect = require('chai').expect +const authenticationHelper = require('../helpers/routes/authentication-helper') +const workloadTypes = require('../../app/constants/workload-type') + +const nationalDefaultUrl = '/' + workloadTypes.OMIC + '/hmpps/0' + +describe('National Omic Overview', function () { + describe('Staff', function () { + before(async function () { + await authenticationHelper.login(authenticationHelper.users.Staff) + await browser.url(nationalDefaultUrl) + }) + + it('should show regional breakdown table', async function () { + const element = await $('.sln-table-org-level') + const text = await element.getText() + expect(text).to.equal('Region') + }) + + it('should allow the user to navigate down the org hierarchy from the national page', async function () { + await browser.url(nationalDefaultUrl + '/overview') + let pageTitle = await $('.govuk-caption-xl') + let text = await pageTitle.getText() + expect(text).to.equal('National') + + const activeRegion = await browser.findElements('xpath', '//*[@id="example"]/tbody/tr[position()=1]/td[position()=1]/a') + const viewRegionLink = await $(activeRegion[0]) + await viewRegionLink.click() + + pageTitle = await $('.govuk-caption-xl') + text = await pageTitle.getText() + expect(text).to.equal('Region') + + const activeLdu = await browser.findElements('xpath', '//*[@id="example"]/tbody/tr[position()=1]/td[position()=1]/a') + const viewLduLink = await $(activeLdu[0]) + + await viewLduLink.click() + + pageTitle = await $('.govuk-caption-xl') + text = await pageTitle.getText() + expect(text).to.equal('Probation Delivery Unit') + }) + + it('should contain breadcrumbs which allow the user to navigate up the org hierarchy', async function () { + const breadcrumbRegion = await browser.findElements('xpath', '//*[@class="govuk-breadcrumbs__list"]/li[position()=2]/a') + const breadcrumbRegionLink = await $(breadcrumbRegion[0]) + + await breadcrumbRegionLink.click() + + let pageTitle = await $('.govuk-caption-xl') + let text = await pageTitle.getText() + expect(text).to.equal('Region') + + const breadcrumbNational = await browser.findElements('xpath', '//*[@class="govuk-breadcrumbs__list"]/li[position()=1]/a') + const breadcrumbNationalLink = await $(breadcrumbNational[0]) + + await breadcrumbNationalLink.click() + + pageTitle = await $('.govuk-caption-xl') + text = await pageTitle.getText() + expect(text).to.equal('National') + }) + + after(function () { + authenticationHelper.logout() + }) + }) + + describe('Managers', function () { + before(async function () { + await authenticationHelper.login(authenticationHelper.users.Manager) + await browser.url(nationalDefaultUrl) + }) + + it('should show regional breakdown table', async function () { + const element = await $('.sln-table-org-level') + const text = await element.getText() + expect(text).to.equal('Region') + }) + + after(function () { + authenticationHelper.logout() + }) + }) + + describe('Application Support', function () { + before(async function () { + await authenticationHelper.login(authenticationHelper.users.ApplicationSupport) + await browser.url(nationalDefaultUrl) + }) + + it('should show regional breakdown table', async function () { + const element = await $('.sln-table-org-level') + const text = await element.getText() + expect(text).to.equal('Region') + }) + + after(function () { + authenticationHelper.logout() + }) + }) + + describe('Super User', function () { + before(async function () { + await authenticationHelper.login(authenticationHelper.users.SuperUser) + await browser.url(nationalDefaultUrl) + }) + + it('should show regional breakdown table', async function () { + const element = await $('.sln-table-org-level') + const text = await element.getText() + expect(text).to.equal('Region') + }) + + after(function () { + authenticationHelper.logout() + }) + }) +}) diff --git a/pool/shard000/JavaScript/0002672_index.modern.js b/pool/shard000/JavaScript/0002672_index.modern.js new file mode 100644 index 0000000000000000000000000000000000000000..d74edc08a5ae1456934771d7af4cc05b7399588d --- /dev/null +++ b/pool/shard000/JavaScript/0002672_index.modern.js @@ -0,0 +1,234 @@ +import React, { forwardRef, useRef, useMemo, useState, useImperativeHandle, useEffect } from 'react'; +import Chart$1 from 'chart.js/auto'; +import merge from 'lodash/merge'; +import assign from 'lodash/assign'; +import find from 'lodash/find'; +import { defaults as defaults$1, Chart as Chart$2 } from 'chart.js'; + +function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + return _extends.apply(this, arguments); +} + +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; +} + +var ChartComponent = forwardRef(function (props, ref) { + var id = props.id, + className = props.className, + _props$height = props.height, + height = _props$height === void 0 ? 150 : _props$height, + _props$width = props.width, + width = _props$width === void 0 ? 300 : _props$width, + _props$redraw = props.redraw, + redraw = _props$redraw === void 0 ? false : _props$redraw, + type = props.type, + data = props.data, + _props$options = props.options, + options = _props$options === void 0 ? {} : _props$options, + _props$plugins = props.plugins, + plugins = _props$plugins === void 0 ? [] : _props$plugins, + getDatasetAtEvent = props.getDatasetAtEvent, + getElementAtEvent = props.getElementAtEvent, + getElementsAtEvent = props.getElementsAtEvent, + fallbackContent = props.fallbackContent, + rest = _objectWithoutPropertiesLoose(props, ["id", "className", "height", "width", "redraw", "type", "data", "options", "plugins", "getDatasetAtEvent", "getElementAtEvent", "getElementsAtEvent", "fallbackContent"]); + + var canvas = useRef(null); + var computedData = useMemo(function () { + if (typeof data === 'function') { + return canvas.current ? data(canvas.current) : {}; + } else return merge({}, data); + }, [data, canvas.current]); + + var _useState = useState(), + chart = _useState[0], + setChart = _useState[1]; + + useImperativeHandle(ref, function () { + return chart; + }, [chart]); + + var renderChart = function renderChart() { + if (!canvas.current) return; + setChart(new Chart$1(canvas.current, { + type: type, + data: computedData, + options: options, + plugins: plugins + })); + }; + + var onClick = function onClick(e) { + if (!chart) return; + getDatasetAtEvent && getDatasetAtEvent(chart.getElementsAtEventForMode(e, 'dataset', { + intersect: true + }, false), e); + getElementAtEvent && getElementAtEvent(chart.getElementsAtEventForMode(e, 'nearest', { + intersect: true + }, false), e); + getElementsAtEvent && getElementsAtEvent(chart.getElementsAtEventForMode(e, 'index', { + intersect: true + }, false), e); + }; + + var updateChart = function updateChart() { + if (!chart) return; + + if (options) { + chart.options = _extends({}, options); + } + + if (!chart.config.data) { + chart.config.data = computedData; + chart.update(); + return; + } + + var _computedData$dataset = computedData.datasets, + newDataSets = _computedData$dataset === void 0 ? [] : _computedData$dataset, + newChartData = _objectWithoutPropertiesLoose(computedData, ["datasets"]); + + var _chart$config$data$da = chart.config.data.datasets, + currentDataSets = _chart$config$data$da === void 0 ? [] : _chart$config$data$da; + assign(chart.config.data, newChartData); + chart.config.data.datasets = newDataSets.map(function (newDataSet) { + var currentDataSet = find(currentDataSets, function (d) { + return d.label === newDataSet.label && d.type === newDataSet.type; + }); + if (!currentDataSet || !newDataSet.data) return _extends({}, newDataSet); + + if (!currentDataSet.data) { + currentDataSet.data = []; + } else { + currentDataSet.data.length = newDataSet.data.length; + } + + assign(currentDataSet.data, newDataSet.data); + assign(currentDataSet, _extends({}, newDataSet, { + data: currentDataSet.data + })); + return currentDataSet; + }); + chart.update(); + }; + + var destroyChart = function destroyChart() { + if (chart) chart.destroy(); + }; + + useEffect(function () { + renderChart(); + return function () { + return destroyChart(); + }; + }, []); + useEffect(function () { + if (redraw) { + destroyChart(); + setTimeout(function () { + renderChart(); + }, 0); + } else { + updateChart(); + } + }, [props, computedData]); + return React.createElement("canvas", Object.assign({}, rest, { + height: height, + width: width, + ref: canvas, + id: id, + className: className, + onClick: onClick, + "data-testid": 'canvas', + role: 'img' + }), fallbackContent); +}); + +var Line = forwardRef(function (props, ref) { + return React.createElement(ChartComponent, Object.assign({}, props, { + type: 'line', + ref: ref, + options: props.options || {} + })); +}); +var Bar = forwardRef(function (props, ref) { + return React.createElement(ChartComponent, Object.assign({}, props, { + type: 'bar', + ref: ref, + options: props.options || {} + })); +}); +var Radar = forwardRef(function (props, ref) { + return React.createElement(ChartComponent, Object.assign({}, props, { + type: 'radar', + ref: ref, + options: props.options || {} + })); +}); +var Doughnut = forwardRef(function (props, ref) { + return React.createElement(ChartComponent, Object.assign({}, props, { + type: 'doughnut', + ref: ref, + options: props.options || {} + })); +}); +var PolarArea = forwardRef(function (props, ref) { + return React.createElement(ChartComponent, Object.assign({}, props, { + type: 'polarArea', + ref: ref, + options: props.options || {} + })); +}); +var Bubble = forwardRef(function (props, ref) { + return React.createElement(ChartComponent, Object.assign({}, props, { + type: 'bubble', + ref: ref, + options: props.options || {} + })); +}); +var Pie = forwardRef(function (props, ref) { + return React.createElement(ChartComponent, Object.assign({}, props, { + type: 'pie', + ref: ref, + options: props.options || {} + })); +}); +var Scatter = forwardRef(function (props, ref) { + return React.createElement(ChartComponent, Object.assign({}, props, { + type: 'scatter', + ref: ref, + options: props.options || {} + })); +}); +var defaults = defaults$1; +var Chart = Chart$2; + +export default ChartComponent; +export { Bar, Bubble, Chart, Doughnut, Line, Pie, PolarArea, Radar, Scatter, defaults }; +//# sourceMappingURL=index.modern.js.map diff --git a/pool/shard000/JavaScript/0002673_config.js b/pool/shard000/JavaScript/0002673_config.js new file mode 100644 index 0000000000000000000000000000000000000000..882f94f29d84aa207eaef7dcdd1913773d3c70d8 --- /dev/null +++ b/pool/shard000/JavaScript/0002673_config.js @@ -0,0 +1,23 @@ +'use strict'; + +// Init the application configuration module for AngularJS application +var ApplicationConfiguration = (function () { + // Init module configuration options + var applicationModuleName = 'muncci'; + var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ui.router', 'ui.bootstrap', 'ui.utils']; + + // Add a new vertical module + var registerModule = function (moduleName, dependencies) { + // Create angular module + angular.module(moduleName, dependencies || []); + + // Add the module to the AngularJS configuration file + angular.module(applicationModuleName).requires.push(moduleName); + }; + + return { + applicationModuleName: applicationModuleName, + applicationModuleVendorDependencies: applicationModuleVendorDependencies, + registerModule: registerModule + }; +})(); diff --git a/pool/shard000/JavaScript/0002676_uamdatatables.js b/pool/shard000/JavaScript/0002676_uamdatatables.js new file mode 100644 index 0000000000000000000000000000000000000000..cef1501546a8f666df713d34630e1fd8075f9417 --- /dev/null +++ b/pool/shard000/JavaScript/0002676_uamdatatables.js @@ -0,0 +1,117 @@ +!function( $ ) { + $.fn.uamdatatables = function( method ) { + + var settings, + table; + + // Public methods + var methods = { + init: function( options ) { + settings = $.extend( true, {}, $.fn.uamdatatables.defaults, options ); + + return this.each(function() { + var $this = $( this ); + + $( ".filters input" ).keyup(function( event ) { + event.stopPropagation(); + table.api().draw(); + }); + + $( ".filters :checkbox" ).change(function( event ) { + event.stopPropagation(); + table.api().draw(); + }); + + $( ".filters input[type='date']" ).change(function( event ) { + console.log( this.value ); + event.stopPropagation(); + table.api().draw(); + }); + + $(".filters select").change(function( event ) { + event.stopPropagation(); + table.api().draw(); + }); + + table = $( "table.table", this ).dataTable( $.extend( + true, + { + ajax: { + data: function( data ) { + $( ".filters input, .filters select" ).each(function() { + var name = $( this ).attr( "name" ), + value = $( this ).val(); + + if ( "checkbox" == $( this ).attr( "type" ) ) { + value = $( this ).is( ":checked" ) ? $( this ).val() : 0; + } + + if ("date" == $( this ).attr( "type" ) ) { + value = $( this ).val(); + } + + data[name] = value; + } ); + } + }, + initComplete: function( settings, json ) { + $( this ).show(); + }, + language: { + url: "/bundles/uamdatatables/vendor/datatables-plugins/i18n/" + settings.locale + ".json" + }, + stateLoadParams: function( settings, data ) { + $( ".filters input, .filters select", $this ).each(function() { + var value = data[ $( this ).attr( "name" ) ]; + + if ( $( this ).attr( "type" ) == "checkbox" ) { + $( this ).attr( "checked", value ); + } else { + $( this ).val( value ); + } + }); + }, + stateSaveParams: function( settings, data ) { + $( ".filters input, .filters select", $this ).each(function() { + var name = $( this ).attr( "name" ), + value = $( this ).attr( "type" ) == "checkbox" + ? ($( this ).is( ":checked" ) ? $( this ).val() : 0) + : $( this ).val(); + + data[ name ] = value; + }); + } + }, + settings + ) ); + }); + } + }; + + if ( methods[ method ] ) { + return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ) ); + } + else if ( typeof method === "object" || !method ) { + return methods.init.apply( this, arguments ); + } + else { + $.error( "Method " + method + " does not exist in $.uamdatatables." ); + } + }; + + $.fn.uamdatatables.defaults = { + autoWidth: false, + locale: "en", + ordering: true, + orderCellsTop: true, + paging: true, + processing: true, + searching: true, + serverSide: true, + stripeClasses: [] + }; +} ( window.jQuery ); + +$( document ).ready(function() { + $( ".uamdatatables" ).uamdatatables( "undefined" === typeof uamdatatables ? {} : uamdatatables ); +}); diff --git a/pool/shard000/JavaScript/0002680_clidriver.js b/pool/shard000/JavaScript/0002680_clidriver.js new file mode 100644 index 0000000000000000000000000000000000000000..31dcc767b25f3a47b35071611d45fc591622f23d --- /dev/null +++ b/pool/shard000/JavaScript/0002680_clidriver.js @@ -0,0 +1,32 @@ +import fs from 'fs' +import path from 'path' +import {processFile} from './lib/payrollcsv' + +const outFilepath = (outDir, inFilepath) => { + const filename = path.basename(inFilepath) + return path.join(outDir, filename) +} + +export const main = ({input: inFiles, outDir, force}) => { + outDir = path.resolve(outDir) + + if (!fs.existsSync(outDir)) { + if(force) { + fs.mkdirSync(outDir) + } else { + console.error(`Error: no such directory ${outDir}`) + process.exit(1) + } + } + + inFiles + .map(inFile => path.resolve(inFile)) + .map(inFile => { + try { + processFile(inFile, outFilepath(outDir, inFile)) + } catch(err) { + console.error(err) + process.exit(1) + } + }) +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002682_admin.js b/pool/shard000/JavaScript/0002682_admin.js new file mode 100644 index 0000000000000000000000000000000000000000..ba6c560a3d52a62aa501c869b14c46f634b583fd --- /dev/null +++ b/pool/shard000/JavaScript/0002682_admin.js @@ -0,0 +1,89 @@ +/* + addAdmin + - makeAdmin 56b7b29b9b4ef7e0289ca293 + */ + + + +'use strict' + +const _ = require('lodash') +const set = require('setthings').set +const settings = require('setthings').settings +const MongoClient = require('mongodb').MongoClient +var ObjectId = require('mongodb').ObjectId +const DA = require(__dirname + '/data_access/DA') + +// settings +set('mongo.uri', 'mongodb://localhost:27017/restinpieces') +set('jwt.secret', 'doubledoubletoilandtrouble') + +// connect to database, create entity objects +let database = null +MongoClient.connect(settings.mongo.uri) + .then(db => { + database = db + console.log("successfully connected to mongo db") + // initialize data access objects + console.log("initializing data access objects") + DA.init(db) + // parse + return parse() + }) + .then(cmd => { + return cmd.run(cmd.value) + }) + .then((message) => { + console.log("message:", message) + database.close() + }) + .catch(err => { + console.error(err.message) + database.close() + }) + +function parse() { + return new Promise((resolve, reject) => { + let args = process.argv.slice(2) + if(args.length < 2) { + reject(new Error("not enough parameters")) + } + else { + + let funcs = {'makeAdmin': makeAdmin} + if(funcs.hasOwnProperty(args[0])) { + let command = { run: funcs[args[0]], value: args[1]} + resolve(command) + } + else { + reject(new Error(`unknown command '${args[0]}'`)) + } + } + }) +} + +function makeAdmin(user_id) { + + return new Promise((resolve, reject) => { + database.collection('users').find({'_id':ObjectId(user_id)}).limit(1).toArray() + .then(users => { + if(users.length > 0) { + if(new Set(users[0].roles).has("admin") === false ) { + users[0].roles.push("admin") + } + return database.collection('users').updateOne({'_id': ObjectId(user_id)}, {'$set': {roles:users[0].roles}}) + } + else { + reject(new Error("user not found")) + } + }) + .then(result => { + resolve("admin role added to user") + }) + .catch(err => { + reject(new Error(err.message)) + }) + }) + + //return DA.O.users.makeAdmin(user_id) +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002686_secret.js b/pool/shard000/JavaScript/0002686_secret.js new file mode 100644 index 0000000000000000000000000000000000000000..59b2fb96eac1390c9242b0707ed01d7c13f98bde --- /dev/null +++ b/pool/shard000/JavaScript/0002686_secret.js @@ -0,0 +1,14 @@ +var + assign = require('lodash.assign') +; + +var Secret = module.exports = function Secret(data) +{ + assign(this, data); +}; + +Secret.prototype.lease_id = null; +Secret.prototype.renewable = null; +Secret.prototype.lease_duration = false; +Secret.prototype.auth = null; +Secret.prototype.data = null; diff --git a/pool/shard000/JavaScript/0002688_profiles.js b/pool/shard000/JavaScript/0002688_profiles.js new file mode 100644 index 0000000000000000000000000000000000000000..0ee0271688ca6876f35a7bac8ffe989c1bab484c --- /dev/null +++ b/pool/shard000/JavaScript/0002688_profiles.js @@ -0,0 +1,29 @@ +var profiles = [{ + id: 1, + name: 'Denise', + phone: '+54 11 7894-1591', + gender: 'm', + locationId: 6 +}, { + id: 2, + name: 'Jessica', + phone: '+54 11 9879-4564', + gender: 'f', + locationId: 5 +}, { + id: 3, + name: 'Tatiana', + phone: '+54 11 1234-4789', + gender: 't', + locationId: 4 +}].map(profile => { + profile.avatar = '/assets/profiles/:id/avatar.png'.replace(':id', profile.id) + return profile +}) + +for (var i = 0; i < 4; i++) { + profiles.map(p => { + profiles.push(p) + }) +} +module.exports = profiles diff --git a/pool/shard000/JavaScript/0002692_js_basics.js b/pool/shard000/JavaScript/0002692_js_basics.js new file mode 100644 index 0000000000000000000000000000000000000000..6e8ca14969c849c903de3ef320b65c3c5813b71c --- /dev/null +++ b/pool/shard000/JavaScript/0002692_js_basics.js @@ -0,0 +1,50 @@ +//Write a function called squareNumber +function squareNumber(squnum) { + var squaredNumber = squnum * squnum; + //console output + console.log('The result of squaring the number ' + squnum + ' is ' + squaredNumber +"."); + + //user output + document.write("The result of squaring the number " + squnum + " is " + squaredNumber + ".
    "); +return squaredNumber; +} +//Write a function called halfNumber +function halfOf(halfnum) { + var half = halfnum / 2; + //console output + console.log('Half of ' + halfnum + ' is ' + half +"."); + + //user output + document.write("Half of " + halfnum + " is " + half + ".
    "); + return half; +} +//Write a function called percentOf, round numbers to 2 decimals +function percentOf(num1, num2) { + var percent = Math.round((num1/num2) * 100) ; + //console output + console.log(num1 + ' is ' + percent + '% of ' + num2 +"."); + + //user output + document.write(num1 + " is " + percent + "% of " + num2 + ".
    "); + return percent; +} +//Write a function called areaOfCircle, round numbers to 2 decimals +function areaOfCircle(radius) { + var area = Math.round(Math.PI * radius*radius *100) /100; + //console output + console.log('The area of circle with radius ' + radius + ' is ' + area +"."); + + //user output + document.write("The area of circle with radius " + radius + " is " + area + ".
    "); + return area; + +} +//console +console.log("All functions "); + +function all(num) { +halfOf(num); + squareNumber(num); + areaOfCircle(num); + percentOf(num, num); +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002695_shows.client.controller.js b/pool/shard000/JavaScript/0002695_shows.client.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..15472c4778d3d6a0148f1069b91bfc3dd07a1315 --- /dev/null +++ b/pool/shard000/JavaScript/0002695_shows.client.controller.js @@ -0,0 +1,113 @@ +'use strict'; + +// Shows controller +angular.module('shows').controller('ShowsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Shows', + function ($scope, $stateParams, $location, Authentication, Shows) { + $scope.authentication = Authentication; + + // Create new Show + $scope.create = function (isValid) { + $scope.error = null; + + if (!isValid) { + $scope.$broadcast('show-errors-check-validity', 'showForm'); + + return false; + } + + // Create new Show object + var show = new Shows({ + title: this.title, + profileImageURL: this.profileImageURL, + mixcloud: this.mixcloud, + categories: this.categories, + description: this.description, + hostID: this.hostID, + programID: this.programID, + dateTime: this.dateTime, + length: this.length + }); + + // Redirect after save + show.$save(function (response) { + + $location.path('shows/' + response._id); + + // Clear form fields + $scope.title = ''; + $scope.profileImageURL = ''; + $scope.mixcloud = ''; + $scope.categories = []; + $scope.description = {}; + $scope.hostID = {}; + $scope.programID = ''; + $scope.dateTime = ''; + $scope.length = ''; + + }, function (errorResponse) { + $scope.error = errorResponse.data.message; + }); + }; + + // Remove existing Show + $scope.remove = function (show) { + if (show) { + show.$remove(); + + for (var i in $scope.shows) { + if ($scope.shows[i] === show) { + $scope.shows.splice(i, 1); + } + } + } else { + $scope.show.$remove(function () { + $location.path('shows'); + }); + } + }; + + // Update existing Show + $scope.update = function (isValid) { + $scope.error = null; + + if (!isValid) { + $scope.$broadcast('show-errors-check-validity', 'showForm'); + + return false; + } + + var show = $scope.show; + + show.$update(function () { + + $location.path('shows/' + show._id); + + // Clear form fields + $scope.title = ''; + $scope.profileImageURL = ''; + $scope.mixcloud = ''; + $scope.categories = []; + $scope.description = {}; + $scope.hostID = {}; + $scope.programID = ''; + $scope.dateTime = ''; + $scope.length = ''; + + }, function (errorResponse) { + $scope.error = errorResponse.data.message; + }); + }; + + // Find a list of Shows + $scope.find = function () { + $scope.shows = Shows.query(); + }; + + // Find existing Show + $scope.findOne = function () { + $scope.show = Shows.get({ + showId: $stateParams.showId + }); + }; + } +]); diff --git a/pool/shard000/JavaScript/0002698_legendChart.test.js b/pool/shard000/JavaScript/0002698_legendChart.test.js new file mode 100644 index 0000000000000000000000000000000000000000..cbaeba2da9995e00bfc7a35ebb77b51d2288f075 --- /dev/null +++ b/pool/shard000/JavaScript/0002698_legendChart.test.js @@ -0,0 +1,159 @@ +import legendData from './legendChart.fixtures'; +import legendChart from './legendChart'; + +describe('legend Chart', () => { + let anchor; + + beforeEach(() => { + anchor = document.createElement('div'); + }); + + describe('create', () => { + + describe('when incorrect arguments are used', () => { + + describe('when the DOM element is not passed', () => { + it('should throw an error', () => { + expect(() => { + legendChart.create( + undefined, + legendData.with6Points(), + {} + ); + }).toThrow('A root container is required'); + }); + }); + + describe('when a non-supported method is passed', () => { + it('should throw an error', () => { + expect(() => { + legendChart.create( + anchor, + legendData.with6Points(), + { test: 'test' } + ); + }).toThrow('Method not supported by Britechart: test'); + }); + }); + }); + + describe('when proper arguments are passed', () => { + + it('should set data as a DOM property', () => { + const expected = legendData.with6Points().length; + + legendChart.create(anchor, legendData.with6Points()); + + const actual = anchor.__data__.length; + + expect(actual).toEqual(expected); + }); + + it('should set the width', () => { + const expected = 500; + + const chart = legendChart.create( + anchor, + legendData.with6Points(), + { width: expected } + ); + + const actual = chart.width(); + + expect(actual).toEqual(expected); + }); + + it('should set the height', () => { + const expected = 600; + + const chart = legendChart.create( + anchor, + legendData.with6Points(), + { height: expected } + ); + + const actual = chart.height(); + + expect(actual).toEqual(expected); + }); + + it('should set the margin', () => { + const expected = { + top: 0, + bottom: 1, + left: 2, + right: 3, + }; + + const chart = legendChart.create( + anchor, + legendData.with6Points(), + { margin: expected } + ); + + const actual = chart.margin(); + + expect(actual).toEqual(expected); + }); + }); + }); + + describe('update', () => { + + describe('when updating data', () => { + + describe('when new data is passed', () => { + it('should update the data in the container', () => { + const firstDataSet = legendData.with6Points(); + const secondDataSet = legendData.with6Points(); + + const chart = legendChart.create(anchor, firstDataSet, {}); + + legendChart.update(anchor, secondDataSet, {}, chart); + + const expected = secondDataSet.length; + const actual = anchor.__data__.length; + + expect(actual).toEqual(expected); + }); + }); + + describe('when new data is not passed', () => { + it('should keep the data in the container', () => { + const dataSet = legendData.with6Points(); + + const chart = legendChart.create(anchor, dataSet, {}); + + legendChart.update(anchor, [], {}, chart); + + const expected = dataSet.length; + const actual = anchor.__data__.length; + + expect(actual).toEqual(expected); + }); + }); + }); + + describe('when updating configuration', () => { + + describe('when new configuration is passed', () => { + it('should update the configuration in the chart', () => { + const expected = 500; + const firstWidth = 200; + const chart = legendChart.create( + anchor, + legendData.with6Points(), + { width: firstWidth } + ); + + legendChart.update(anchor, [], { width: expected }, chart); + + const actual = chart.width(); + + expect(actual).toEqual(expected); + }); + }); + }); + }); +}); + diff --git a/pool/shard000/JavaScript/0002699_HeroIcon.js b/pool/shard000/JavaScript/0002699_HeroIcon.js new file mode 100644 index 0000000000000000000000000000000000000000..556ee3e67d83c917199a41f07d58fecf477b8da4 --- /dev/null +++ b/pool/shard000/JavaScript/0002699_HeroIcon.js @@ -0,0 +1,158 @@ +/*eslint max-len: ["error", { "code": 800 }]*/ + +import React from 'react'; +import { + View, + asset, + VrButton, + NativeModules, + StyleSheet +} from 'react-360'; +import { ImageBackground } from 'react-native'; +import { connect } from 'react-redux'; +import LoadingBar from './../LoadingBar/LoadingBar'; +import { fetchHeroHover, fetchLoadingContent } from './../../../actions'; + +class HeroIcon extends React.Component { + + componentDidUpdate() { + const { webMode, heroHover, fetchLoadingContent, iconName } = this.props; + if (webMode === 'mobile-webvr') { + if (heroHover === iconName) fetchLoadingContent(heroHover); + else if (heroHover === '') fetchLoadingContent(''); + } + } + + iconStyle() { + if (this.props.iconName === 'centerLeftIcon') return styles.leftIcon; + return styles.rightIcon; + } + + iconHoverStyle() { + if (this.props.iconName === 'centerLeftIcon') return styles.leftIconHover; + return styles.rightIconHover; + } + + iconHitBoxStyle() { + if (this.props.iconName === 'centerLeftIcon') return styles.leftIconHitBox; + return styles.rightIconHitBox; + } + + iconImgStyle() { + if (this.props.iconName === 'centerLeftIcon') return styles.leftIconImage; + return styles.rightIconImage; + } + + modeCheck(webMode) { + if (webMode === 'web' || webMode === 'webvr') this.openLink(); + } + + openLink() { + const { iconUrl } = this.props; + NativeModules.LinkingManager.openURL(iconUrl); + } + + setLeftMargin() { + if (this.props.heroHover === 'centerRightIcon') return -50; + return -55; + } + + render() { + const { heroHover, iconName, iconUrl, webMode } = this.props; + return ( + + + + + + this.props.fetchHeroHover(iconName)} + onExit={() => this.props.fetchHeroHover('')} + onClick={() => this.modeCheck(webMode)} + style={this.iconHitBoxStyle()} + /> + + ); + } +} + +const mapStateToProps = ({ heroHover, webMode }) => ({ heroHover, webMode }); + +export default connect(mapStateToProps, { fetchHeroHover, fetchLoadingContent })(HeroIcon); + +const styles = StyleSheet.create({ + leftIcon: { + width: 100, + height: 100, + backgroundColor: '#7d7d7d', + position: 'absolute', + marginTop: 110, + marginLeft: 60, + borderRadius: 100 / 2 + }, + leftIconHover: { + width: 100, + height: 100, + backgroundColor: '#269a18', + position: 'absolute', + marginTop: 110, + borderRadius: 100 / 2, + }, + leftIconHitBox: { + width: 150, + height: 150, + marginLeft: 35, + // backgroundColor: '#ff0006', + marginTop: 90, + position: 'absolute', + borderRadius: 150 / 2 + }, + leftIconImage: { + height: 33, + width: 70, + marginTop: 33, + marginLeft: '15%' + }, + rightIcon: { + width: 100, + height: 100, + backgroundColor: '#7d7d7d', + position: 'absolute', + marginTop: 110, + marginLeft: 538, + borderRadius: 100 / 2, + }, + rightIconHover: { + width: 100, + height: 100, + backgroundColor: '#e3bb2a', + position: 'absolute', + marginTop: 110, + borderRadius: 100 / 2 + }, + rightIconImage: { + width: 70, + height: 33, + marginTop: 33, + marginLeft: '15%' + }, + rightIconHitBox: { + width: 150, + height: 150, + // backgroundColor: '#ff0006', + marginTop: 90, + position: 'absolute', + borderRadius: 150 / 2, + marginLeft: 515 + } +}); diff --git a/pool/shard000/JavaScript/0002701_mock-module.test.js b/pool/shard000/JavaScript/0002701_mock-module.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f033b2573258368b28c310925903904aef0fbf1e --- /dev/null +++ b/pool/shard000/JavaScript/0002701_mock-module.test.js @@ -0,0 +1,83 @@ +suite("mock module", function () { + "use strict"; + + var assert = require("assert"); + var MockModule = require("./mock-module"); + + test("tear does not fail when nothing mocked", function () { + var safe = MockModule.create(); + safe.teardown(); + }); + + test("replaces module property with noop", function () { + var Module = { + f: function () { + assert(false); + } + }; + + var safe = MockModule.create(); + safe.mock(Module, "f"); + + Module.f(); + }); + + test("replaces module property with mock", function (done) { + var Module = { + f: function () { + assert(false); + } + }; + + var safe = MockModule.create(); + safe.mock(Module, "f", done); + + Module.f(); + }); + + test("restores module", function (done) { + var Module = {f: done}; + var safe = MockModule.create(); + + safe.mock(Module, "f", function () { + assert(false); + }); + + safe.teardown(); + Module.f(); + }); + + test("uses latest mock", function (done) { + var Module = { + f: function () { + assert(false); + } + }; + + var safe = MockModule.create(); + + safe.mock(Module, "f", function () { + assert(false); + }); + + safe.mock(Module, "f", done); + + Module.f(); + }); + + test("restores module after multiple mocks", function (done) { + var Module = {f: done}; + var safe = MockModule.create(); + + safe.mock(Module, "f", function () { + assert(false); + }); + + safe.mock(Module, "f", function () { + assert(false); + }); + + safe.teardown(); + Module.f(); + }); +}); diff --git a/pool/shard000/JavaScript/0002702_intversion-abort-in-initial-upgradeneeded.js b/pool/shard000/JavaScript/0002702_intversion-abort-in-initial-upgradeneeded.js new file mode 100644 index 0000000000000000000000000000000000000000..8d4b7d4702a54386e70c0a368e4c7ed856443c61 --- /dev/null +++ b/pool/shard000/JavaScript/0002702_intversion-abort-in-initial-upgradeneeded.js @@ -0,0 +1,54 @@ +if (this.importScripts) { + importScripts('../../../resources/js-test.js'); + importScripts('shared.js'); +} + +description("Test that an abort in the initial upgradeneeded sets version back to 0"); + +function test() +{ + setDBNameFromPath(); + + request = evalAndLog("indexedDB.deleteDatabase(dbname)"); + request.onsuccess = deleteSuccess; + request.onerror = unexpectedErrorCallback; +} + +function deleteSuccess() { + request = evalAndLog("indexedDB.open(dbname, 2)"); + request.onsuccess = unexpectedSuccessCallback; + evalAndLog("request.onupgradeneeded = upgradeNeeded"); + evalAndLog("request.onerror = onError"); + request.onblocked = unexpectedBlockedCallback; +} + +function upgradeNeeded(evt) +{ + preamble(evt); + db = event.target.result; + shouldBe("db.version", "2"); + transaction = event.target.transaction; + transaction.oncomplete = unexpectedCompleteCallback; + transaction.onabort = onAbort; + evalAndLog("transaction.abort()"); +} + +function onAbort(evt) +{ + preamble(evt); + shouldBe("event.target.db.version", "0"); + shouldBeNonNull("request.transaction"); +} + +function onError(evt) +{ + preamble(evt); + shouldBe("request", "event.target"); + shouldBeUndefined("event.target.result"); + shouldBeNonNull("event.target.error"); + shouldBeEqualToString("event.target.error.name", "AbortError"); + shouldBeNull("request.transaction"); + finishJSTest(); +} + +test(); diff --git a/pool/shard000/JavaScript/0002703_roles.test.js b/pool/shard000/JavaScript/0002703_roles.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f5965914f34c242d9f0f790c741c9697c36ac3d9 --- /dev/null +++ b/pool/shard000/JavaScript/0002703_roles.test.js @@ -0,0 +1,151 @@ +import supertest from 'supertest'; +import chai from 'chai'; +import app from '../../../server'; +import { Role } from '../../models'; +import helper from '../test-helper'; + +const request = supertest.agent(app); +const expect = chai.expect; + +const userParams = helper.firstUser; + +let role, token; + +describe('Roles API', () => { + before((done) => { + Role.create(helper.adminRole) + .then((newRole) => { + userParams.roleId = newRole.id; + request.post('/users') + .send(userParams) + .end((err, res) => { + token = res.body.token; + done(); + }); + }); + }); + + after(() => Role.sequelize.sync({ force: true })); + + describe('CONTEXT: With existing role', () => { + beforeEach(() => + Role.create(helper.regularRole) + .then((newRole) => { + role = newRole; + })); + + afterEach(() => Role.destroy({ where: { id: role.id } })); + + describe('Get all GET: /roles', () => { + it('should return unauthorised for no token', (done) => { + request.get('/roles') + .end((err, res) => { + expect(res.status).to.equal(401); + done(); + }); + }); + + it('should return all roles', (done) => { + request.get('/roles') + .set({ Authorization: token }) + .end((err, res) => { + expect(res.status).to.equal(200); + expect(Array.isArray(res.body)).to.be.true; + expect(res.body.length).to.not.equal(0); + done(); + }); + }); + }); + + describe('Get role GET: /roles/:id', () => { + it('should get correct role', (done) => { + request.get(`/roles/${role.id}`) + .set({ Authorization: token }) + .end((err, res) => { + expect(res.status).to.equal(200); + expect(res.body.title).to.equal(role.title); + done(); + }); + }); + + it('should return NOT FOUND for invalid id', (done) => { + request.get('/roles/100') + .set({ Authorization: token }) + .expect(404, done); + }); + }); + + describe('Edit role PUT: /roles/:id', () => { + it('updates the role attributes', (done) => { + const newAttributes = { title: 'role' }; + + request.put(`/roles/${role.id}`) + .set({ Authorization: token }) + .send(newAttributes) + .end((err, res) => { + expect(res.status).to.equal(200); + expect(res.body.title).to.equal(newAttributes.title); + done(); + }); + }); + + it('should return NOT FOUND for invalid id', (done) => { + request.put('/roles/100') + .set({ Authorization: token }) + .expect(404, done); + }); + }); + + describe('Delete role DELETE: /roles/:id', () => { + it('deletes the role', (done) => { + request.delete(`/roles/${role.id}`) + .set({ Authorization: token }) + .end((err, res) => { + expect(res.status).to.equal(200); + Role.count().then((count) => { + expect(count).to.equal(1); + done(); + }); + }); + }); + + it('should return NOT FOUND for invalid id', (done) => { + request.delete('/roles/100') + .set({ Authorization: token }) + .expect(404, done); + }); + }); + }); + + describe('CONTEXT: without existing role', () => { + afterEach(() => Role.sequelize.sync({ force: true })); + + describe('Create role POST: /roles', () => { + it('creates a new role', (done) => { + request.post('/roles') + .set({ Authorization: token }) + .send({ title: 'authors' }) + .end((err, res) => { + expect(res.status).to.equal(201); + expect(res.body.title).to.equal('authors'); + done(); + }); + }); + + it('fails if user is not an admin', (done) => { + Role.create(helper.regularRole) + .then((newRole) => { + helper.secondUser.roleId = newRole.id; + request.post('/users') + .send(helper.secondUser) + .end((err, res) => { + request.post('/roles') + .set({ Authorization: res.body.token }) + .send({ title: 'other' }) + .expect(403, done); + }); + }); + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0002706_musicBox.js b/pool/shard000/JavaScript/0002706_musicBox.js new file mode 100644 index 0000000000000000000000000000000000000000..871d0b3023986bce3cfc2ff93ed52ba0144d395c --- /dev/null +++ b/pool/shard000/JavaScript/0002706_musicBox.js @@ -0,0 +1,105 @@ +import api from '../../axios' +import wyApi from '../../wyApi' +const state = { + show: false, + el: '', + url:'', + musicData: '', + autoPlay: true, + playlist: false, + songlist:[] +} +const mutations = { + deletePlaylist(state, payload) { + if (payload != undefined) { + if (state.playlist.length == 1) { + state.playlist = false + localStorage.removeItem('playlist') + } else { + state.playlist.splice(payload, 1) + localStorage.setItem('playlist', JSON.stringify(state.playlist)) + } + } else { + state.playlist = false + localStorage.removeItem('playlist') + } + }, + loadPlaylist(state, payload) { + state.playlist = payload + }, + addPlaylist(state,payload) { + if (state.playlist) { + let addFlag = true + state.playlist.forEach((item) => { + if (item.music.wyID == payload.music.wyID) { + addFlag = false + } + }) + if (addFlag) { + state.playlist.push(payload) + localStorage.setItem('playlist', JSON.stringify(state.playlist)) + } + } else { + state.playlist = [] + state.playlist.push(payload) + } + }, + playMusic(state, payload) { + state.musicData = payload + state.onPlay = false + state.currTime = 0 + state.totalTime = 0 + state.playProgress = 0 + if (payload.hasOwnProperty('local')) { + state.autoPlay = false + } else { + state.autoPlay = true + if (state.playlist) { + let addFlag = true + state.playlist.forEach((item) => { + if (item.music.wyID == payload.music.wyID) { + addFlag = false + } + }) + if (addFlag) { + state.playlist.push(payload) + } + } else { + state.playlist = [] + state.playlist.push(payload) + } + } + localStorage.setItem('playlist', JSON.stringify(state.playlist)) + localStorage.setItem('musicData', JSON.stringify(payload)) + state.show = true + }, + setEl(state, payload) { + state.el = payload + }, + hideMusicBox(state) { + state.show = false + } +} + +const actions = { + playMusic({ + commit + }, payload) { + // if(payload.url){ + // commit('playMusic', payload) + // }else{ + return wyApi.getMusicUrl(payload.music.wyID).then((result) => { + if (result.code == 200) { + payload.url = result.data[0].url + commit('playMusic', payload) + } + }) + // } + } +} + +export default { + state, + mutations, + actions +} diff --git a/pool/shard000/JavaScript/0002707_InputLabel.js b/pool/shard000/JavaScript/0002707_InputLabel.js new file mode 100644 index 0000000000000000000000000000000000000000..71231ba2b2cb924fb6cb375a7cac031393a47016 --- /dev/null +++ b/pool/shard000/JavaScript/0002707_InputLabel.js @@ -0,0 +1,229 @@ +"use strict"; + +var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")); + +var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); + +var React = _interopRequireWildcard(require("react")); + +var _propTypes = _interopRequireDefault(require("prop-types")); + +var _unstyled = require("@material-ui/unstyled"); + +var _formControlState = _interopRequireDefault(require("../FormControl/formControlState")); + +var _useFormControl = _interopRequireDefault(require("../FormControl/useFormControl")); + +var _FormLabel = _interopRequireWildcard(require("../FormLabel")); + +var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps")); + +var _experimentalStyled = _interopRequireWildcard(require("../styles/experimentalStyled")); + +var _inputLabelClasses = require("./inputLabelClasses"); + +var _jsxRuntime = require("react/jsx-runtime"); + +const useUtilityClasses = styleProps => { + const { + classes, + formControl, + size, + shrink, + disableAnimation, + variant + } = styleProps; + const slots = { + root: ['root', formControl && 'formControl', !disableAnimation && 'animated', shrink && 'shrink', size === 'small' && 'sizeSmall', variant] + }; + const composedClasses = (0, _unstyled.unstable_composeClasses)(slots, _inputLabelClasses.getInputLabelUtilityClasses, classes); + return (0, _extends2.default)({}, classes, composedClasses); +}; + +const InputLabelRoot = (0, _experimentalStyled.default)(_FormLabel.default, { + shouldForwardProp: prop => (0, _experimentalStyled.rootShouldForwardProp)(prop) || prop === 'classes', + name: 'MuiInputLabel', + slot: 'Root', + overridesResolver: (props, styles) => { + const { + styleProps + } = props; + return (0, _extends2.default)({ + [`& .${_FormLabel.formLabelClasses.asterisk}`]: styles.asterisk + }, styles.root, !styleProps.formControl && styles.formControl, styleProps.size === 'small' && styles.sizeSmall, styleProps.shrink && styles.shrink, !styleProps.disableAnimation && styles.animated, styles[styleProps.variant]); + } +})(({ + theme, + styleProps +}) => (0, _extends2.default)({ + display: 'block', + transformOrigin: 'top left', + whiteSpace: 'nowrap', + overflow: 'hidden', + textOverflow: 'ellipsis', + maxWidth: '100%' +}, styleProps.formControl && { + position: 'absolute', + left: 0, + top: 0, + // slight alteration to spec spacing to match visual spec result + transform: 'translate(0, 20px) scale(1)' +}, styleProps.size === 'small' && { + // Compensation for the `Input.inputSizeSmall` style. + transform: 'translate(0, 17px) scale(1)' +}, styleProps.shrink && { + transform: 'translate(0, -1.5px) scale(0.75)', + transformOrigin: 'top left', + maxWidth: '133%' +}, !styleProps.disableAnimation && { + transition: theme.transitions.create(['color', 'transform', 'max-width'], { + duration: theme.transitions.duration.shorter, + easing: theme.transitions.easing.easeOut + }) +}, styleProps.variant === 'filled' && (0, _extends2.default)({ + // Chrome's autofill feature gives the input field a yellow background. + // Since the input field is behind the label in the HTML tree, + // the input field is drawn last and hides the label with an opaque background color. + // zIndex: 1 will raise the label above opaque background-colors of input. + zIndex: 1, + pointerEvents: 'none', + transform: 'translate(12px, 16px) scale(1)', + maxWidth: 'calc(100% - 24px)' +}, styleProps.size === 'small' && { + transform: 'translate(12px, 13px) scale(1)' +}, styleProps.shrink && (0, _extends2.default)({ + transform: 'translate(12px, 7px) scale(0.75)', + maxWidth: 'calc(133% - 24px)' +}, styleProps.size === 'small' && { + transform: 'translate(12px, 4px) scale(0.75)' +})), styleProps.variant === 'outlined' && (0, _extends2.default)({ + // see comment above on filled.zIndex + zIndex: 1, + pointerEvents: 'none', + transform: 'translate(14px, 16px) scale(1)', + maxWidth: 'calc(100% - 24px)' +}, styleProps.size === 'small' && { + transform: 'translate(14px, 9px) scale(1)' +}, styleProps.shrink && { + maxWidth: 'calc(133% - 24px)', + transform: 'translate(14px, -9px) scale(0.75)' +}))); +const InputLabel = /*#__PURE__*/React.forwardRef(function InputLabel(inProps, ref) { + const props = (0, _useThemeProps.default)({ + name: 'MuiInputLabel', + props: inProps + }); + const { + disableAnimation = false, + shrink: shrinkProp + } = props, + other = (0, _objectWithoutPropertiesLoose2.default)(props, ["disableAnimation", "margin", "shrink", "variant"]); + const muiFormControl = (0, _useFormControl.default)(); + let shrink = shrinkProp; + + if (typeof shrink === 'undefined' && muiFormControl) { + shrink = muiFormControl.filled || muiFormControl.focused || muiFormControl.adornedStart; + } + + const fcs = (0, _formControlState.default)({ + props, + muiFormControl, + states: ['size', 'variant'] + }); + const styleProps = (0, _extends2.default)({}, props, { + disableAnimation, + formControl: muiFormControl, + shrink, + size: fcs.size, + variant: fcs.variant + }); + const classes = useUtilityClasses(styleProps); + return /*#__PURE__*/(0, _jsxRuntime.jsx)(InputLabelRoot, (0, _extends2.default)({ + "data-shrink": shrink, + styleProps: styleProps, + ref: ref + }, other, { + classes: classes + })); +}); +process.env.NODE_ENV !== "production" ? InputLabel.propTypes +/* remove-proptypes */ += { + // ----------------------------- Warning -------------------------------- + // | These PropTypes are generated from the TypeScript type definitions | + // | To update them edit the d.ts file and run "yarn proptypes" | + // ---------------------------------------------------------------------- + + /** + * The content of the component. + */ + children: _propTypes.default.node, + + /** + * Override or extend the styles applied to the component. + */ + classes: _propTypes.default.object, + + /** + * The color of the component. It supports those theme colors that make sense for this component. + */ + color: _propTypes.default.oneOf(['primary', 'secondary']), + + /** + * If `true`, the transition animation is disabled. + * @default false + */ + disableAnimation: _propTypes.default.bool, + + /** + * If `true`, the component is disabled. + */ + disabled: _propTypes.default.bool, + + /** + * If `true`, the label is displayed in an error state. + */ + error: _propTypes.default.bool, + + /** + * If `true`, the `input` of this label is focused. + */ + focused: _propTypes.default.bool, + + /** + * If `dense`, will adjust vertical spacing. This is normally obtained via context from + * FormControl. + */ + margin: _propTypes.default.oneOf(['dense']), + + /** + * if `true`, the label will indicate that the `input` is required. + */ + required: _propTypes.default.bool, + + /** + * If `true`, the label is shrunk. + */ + shrink: _propTypes.default.bool, + + /** + * The system prop that allows defining system overrides as well as additional CSS styles. + */ + sx: _propTypes.default.object, + + /** + * The variant to use. + */ + variant: _propTypes.default.oneOf(['filled', 'outlined', 'standard']) +} : void 0; +var _default = InputLabel; +exports.default = _default; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002710_connectFunctions.js b/pool/shard000/JavaScript/0002710_connectFunctions.js new file mode 100644 index 0000000000000000000000000000000000000000..8769053e8c40b4973f5b1fa7b83c6f8e786d9876 --- /dev/null +++ b/pool/shard000/JavaScript/0002710_connectFunctions.js @@ -0,0 +1,36 @@ +(function(){var __modFun = function(__require, promiseland){ __modFun = undefined; + +if (promiseland._hasModule({ hashStr: "68b329da9893e34099c7d8ad5cb9c940" })){ return promiseland._getModule("68b329da9893e34099c7d8ad5cb9c940"); }; +var PL$1 = (function(){ +"use strict"; + + ; + ;})(); +;return PL$1; +}; + + if (typeof exports == "object" && typeof module == "object"){ // CommonJS + module.exports = __modFun(function(modulesAr, callback, errBack){ + // the require function for CommonJs + var args = []; + try{ + var i = 0; + var l = modulesAr.length; + for (i; i < l; ++i){ + args.push(require(modulesAr[i])); + }; + }catch(e){ + errBack(e); + return; + }; + callback.apply(callback, args); + }, require("promiseland")); + + }else if (typeof define == "function" && define.amd){ // AMD + define(["require", "promiseland"], __modFun); + + }else{ // Plain browser env + __modFun(function(){ throw { msg: "require not possible in non loader mode" }; }); + + }; +})(); diff --git a/pool/shard000/JavaScript/0002712_threejsboilerplate.js b/pool/shard000/JavaScript/0002712_threejsboilerplate.js new file mode 100644 index 0000000000000000000000000000000000000000..b3fc9c7a37cd51fcc648ec648dbc6b958f36dc59 --- /dev/null +++ b/pool/shard000/JavaScript/0002712_threejsboilerplate.js @@ -0,0 +1,15 @@ +var express = require('express'); +var chalk = require('chalk'); +var fs = require('fs'); +var app = express(); +var port = 8080; + +app.use(express.static(__dirname + '/public')); + + +app.listen(port); +console.log("listening port " + port); + +app.get('/', function(req, res) { + res.sendfile(__dirname + '/public/index.html'); +}); diff --git a/pool/shard000/JavaScript/0002713_store-component.js b/pool/shard000/JavaScript/0002713_store-component.js new file mode 100644 index 0000000000000000000000000000000000000000..1380a46a2aee2f0567b676693b37137877d767e0 --- /dev/null +++ b/pool/shard000/JavaScript/0002713_store-component.js @@ -0,0 +1,63 @@ +'use babel' +/** @jsx etch.dom */ + +import etch from 'etch' +import { CompositeDisposable } from 'atom' + +import UiComponent from './component' +import { shallowEqual } from '../helpers' + +export default class UiStoreComponent extends UiComponent { + constructor (props, children) { + // all props except the "Component" will be passed through to the component + props.passThrough = Object.keys(props).filter((key) => key !== 'Component') + + super(props, children) + } + + init () { + this._subscriptions = new CompositeDisposable( + { dispose: this.props.store.subscribe(this.handleStoreChange.bind(this)) } + ) + + this.updateComponentProps() + + super.init() + } + + dispose () { + this._subscriptions.dispose() + this._subscriptions = null + + super.dispose() + } + + render () { + const props = {} + this.props.passThrough.forEach((key) => { props[key] = this.props[key] }) + Object.assign(props, this.props.storeProps) + return + } + + handleStoreChange () { + this.updateComponentProps() + } + + updateComponentProps () { + const storeProps = this.storeToProps(this.props.store.getState()) + if (this.props.storeProps && shallowEqual(this.props.storeProps, storeProps)) { + return + } + this.update({ storeProps: storeProps }) + } + + static create (Component, storeToProps) { + return class UiContainer extends UiStoreComponent { + init () { + this.Component = Component + this.storeToProps = storeToProps + super.init() + } + } + } +} diff --git a/pool/shard000/JavaScript/0002719_find-key.js b/pool/shard000/JavaScript/0002719_find-key.js new file mode 100644 index 0000000000000000000000000000000000000000..682c62c6607dc978f0cfe1908966ec8b4a45835e --- /dev/null +++ b/pool/shard000/JavaScript/0002719_find-key.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = findKey; +function findKey(object, predicate) { + var resultKey = void 0; + + Object.keys(object).some(function (key) { + var isKey = predicate(object[key], key, object); + + if (isKey) { + resultKey = key; + return true; + } + + return false; + }); + + return resultKey; +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002724_http.js b/pool/shard000/JavaScript/0002724_http.js new file mode 100644 index 0000000000000000000000000000000000000000..c44c2146380d12c23af89938bd5b0338b331df90 --- /dev/null +++ b/pool/shard000/JavaScript/0002724_http.js @@ -0,0 +1,16 @@ +/** + * jsonp request. + * Copied from http://stackoverflow.com/a/22780569/3408818 + */ +function jsonp(url, callback) { + var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random()); + window[callbackName] = function(data) { + delete window[callbackName]; + document.body.removeChild(script); + callback(data); + }; + + var script = document.createElement('script'); + script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName; + document.body.appendChild(script); +} diff --git a/pool/shard000/JavaScript/0002726_password-strength-bar.directive.js b/pool/shard000/JavaScript/0002726_password-strength-bar.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..d7ffa769ef1a7904dc8fe5eb004f46dcbd0fa7fa --- /dev/null +++ b/pool/shard000/JavaScript/0002726_password-strength-bar.directive.js @@ -0,0 +1,95 @@ +/* globals $ */ +(function() { + 'use strict'; + + angular + .module('helloJhipsterApp') + .directive('passwordStrengthBar', passwordStrengthBar); + + function passwordStrengthBar () { + var directive = { + replace: true, + restrict: 'E', + template: '
    ' + + 'Password strength:' + + '
      ' + + '
    • ' + + '
    ' + + '
    ', + scope: { + passwordToCheck: '=' + }, + link: linkFunc + }; + + return directive; + + /* private helper methods*/ + + function linkFunc(scope, iElement) { + var strength = { + colors: ['#F00', '#F90', '#FF0', '#9F0', '#0F0'], + mesureStrength: function (p) { + + var _force = 0; + var _regex = /[$-/:-?{-~!"^_`\[\]]/g; // " + + var _lowerLetters = /[a-z]+/.test(p); + var _upperLetters = /[A-Z]+/.test(p); + var _numbers = /[0-9]+/.test(p); + var _symbols = _regex.test(p); + + var _flags = [_lowerLetters, _upperLetters, _numbers, _symbols]; + var _passedMatches = $.grep(_flags, function (el) { + return el === true; + }).length; + + _force += 2 * p.length + ((p.length >= 10) ? 1 : 0); + _force += _passedMatches * 10; + + // penalty (short password) + _force = (p.length <= 6) ? Math.min(_force, 10) : _force; + + // penalty (poor variety of characters) + _force = (_passedMatches === 1) ? Math.min(_force, 10) : _force; + _force = (_passedMatches === 2) ? Math.min(_force, 20) : _force; + _force = (_passedMatches === 3) ? Math.min(_force, 40) : _force; + + return _force; + + }, + getColor: function (s) { + + var idx; + if (s <= 10) { + idx = 0; + } + else if (s <= 20) { + idx = 1; + } + else if (s <= 30) { + idx = 2; + } + else if (s <= 40) { + idx = 3; + } + else { + idx = 4; + } + + return { idx: idx + 1, col: this.colors[idx] }; + } + }; + scope.$watch('passwordToCheck', function (password) { + if (password) { + var c = strength.getColor(strength.mesureStrength(password)); + iElement.removeClass('ng-hide'); + iElement.find('ul').children('li') + .css({ 'background-color': '#DDD' }) + .slice(0, c.idx) + .css({ 'background-color': c.col }); + } + }); + } + } +})(); diff --git a/pool/shard000/JavaScript/0002727_EnlightenedWarrior.spec.js b/pool/shard000/JavaScript/0002727_EnlightenedWarrior.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..5f07bccfc329fa5972b1e419f63d7e946da4a5d8 --- /dev/null +++ b/pool/shard000/JavaScript/0002727_EnlightenedWarrior.spec.js @@ -0,0 +1,53 @@ +describe('Enlightened Warrior', function() { + integration(function() { + describe('Enlightened Warrior\'s ability', function() { + beforeEach(function() { + this.setupTest({ + phase: 'conflict', + player1: { + inPlay: ['doji-whisperer'] + }, + player2: { + inPlay: ['enlightened-warrior'] + } + }); + + this.dojiWhisperer = this.player1.findCardByName('doji-whisperer'); + this.enlightenedWarrior = this.player2.findCardByName('enlightened-warrior'); + + this.game.rings.water.fate = 1; + }); + + it('should trigger when your opponent selects a ring with fate on it (during conflict declaration)', function() { + this.noMoreActions(); + this.initiateConflict({ + attackers: [this.dojiWhisperer], + ring: 'water' + }); + expect(this.player2).toHavePrompt('Triggered Abilities'); + expect(this.player2).toBeAbleToSelect(this.enlightenedWarrior); + }); + + it('should not trigger when your opponent selects a ring with no fate on it (during conflict declaration)', function() { + this.noMoreActions(); + this.initiateConflict({ + attackers: [this.dojiWhisperer], + ring: 'fire' + }); + expect(this.player2).not.toHavePrompt('Triggered Abilities'); + expect(this.player2).toHavePrompt('Choose defenders'); + }); + + it('should place 1 fate on Enlightened Warrior', function() { + let fate = this.enlightenedWarrior.fate; + this.noMoreActions(); + this.initiateConflict({ + attackers: [this.dojiWhisperer], + ring: 'water' + }); + this.player2.clickCard(this.enlightenedWarrior); + expect(this.enlightenedWarrior.fate).toBe(fate + 1); + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0002728_okshadowSpec.js b/pool/shard000/JavaScript/0002728_okshadowSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..df4f3fa0f3516795e24c2073c68ab49a70f79120 --- /dev/null +++ b/pool/shard000/JavaScript/0002728_okshadowSpec.js @@ -0,0 +1,61 @@ + describe('okshadow', function() { + var testDiv; + + beforeEach(function(){ + + this.addMatchers({ + toHaveBoxShadow: function() { + if (this.actual.css('boxShadow') && this.actual.css('boxShadow') !== 'none') return true; + }, + toHaveTextShadow: function() { + if (this.actual.css('text-shadow') && this.actual.css('textShadow') !== 'none') return true; + } + }); + }); + + describe('with default options', function () { + beforeEach(function(){ + jasmine.getFixtures().set('
    '); + testDiv = $('#test').okshadow(); + }); + + it('adds box-shadow', function () { + expect(testDiv).toHaveBoxShadow(); + }); + + }); + + describe('allows developers to control options', function() { + beforeEach(function(){ + jasmine.getFixtures().set('

    OKFocus.

    '); + }); + + it('text shadow', function() { + testDiv = $('#test p').okshadow({ + textShadow: true + }); + expect(testDiv).toHaveTextShadow(); + }); + + + it('color', function(){ + testText = $('#test p').okshadow({ + color: 'rgb(4,2,0)' + }); + expect(/4, 2, 0/.test(testText.css('box-shadow'))).toBe(true); + }); + + it('transparency', function(){ + testText = $('#test p').okshadow({ + transparent: true + }); + + expect(/0, 0, 0, 0/.test(testText.css('color'))).toBe(true); + + }); + + + + }); + + }); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002731_app_module.js b/pool/shard000/JavaScript/0002731_app_module.js new file mode 100644 index 0000000000000000000000000000000000000000..c47556821722f6fb635145cab4437eed24e742c5 --- /dev/null +++ b/pool/shard000/JavaScript/0002731_app_module.js @@ -0,0 +1,141 @@ +var app_module = function(){ + var TimeSlot = function(){ + this.agenda = null; + this.unparsedString = null; + } + + TimeSlot.prototype.isDefined = function(){ + return this.unparsedString!=null && this.unparsedString.trim().length>0; + } + + var timeSlotArg = null; + var apptDetails = null; + + var redirectWindow = function(path){ + window.location.replace(path); + } + + var openDialog = function(){ + //this will force creation of new object + timeSlotArg = null; + $("#listing-add-new").show(); + + } + + var onDateTimeChange = function(e){ + if(timeSlotArg == null){ + timeSlotArg = new TimeSlot(); + } + timeSlotArg.unparsedString = e.detail.target.value; + } + + var onAgendaChange = function(e){ + if(timeSlotArg == null){ + timeSlotArg = new TimeSlot(); + } + timeSlotArg.agenda = e.detail.target.value; + } + + + var onSubmit = function(){ + if(timeSlotArg!=null && timeSlotArg.isDefined()){ + dataOut = JSON.stringify(timeSlotArg); + $.ajax({ + url: "/group/"+getCurrentGroupId()+"/schedule/new.json", + data: {timeslot: dataOut}, + type: "POST", + dataType: "json", + success: onSucess, + error: onError + }); + } + } + + var getCurrentGroupId = function(){ + // get this as data attribute from the page + var id = $("#listing-header").attr("data-group-id"); + return id; + } + + var addAvialability = function(){ + + if (!$("#listing-add-new").is(':visible')){ + $("#add_button").text("Hide Availability Form"); + openDialog(); + }else{ + $("#listing-add-new").hide(); + $("#add_button").text("Add Your Availabilty"); + } + + + } + + var onError = function(response){ + console.log(response); + if (response.error){ + alert("Your operation HAS FAILED. Error: " + response.error); + }else{ + alert("Your operation HAS FAILED. Contact DBC for help."); + } + + } + + var onSucess = function(response){ + if (response.error){ + onError(response); + }else{ + if(apptDetails!=null){ + alert("You have accepted the following appointment:\n" + apptDetails); + apptDetails = null; + } + + redirectWindow(response.path); + } + + } + + var getScheduleIfFromEvent = function(e){ + var target = $(e.detail.currentTarget).closest(".calendar-listing"); + return target.attr("data-id"); + } + + var getDetailsForId = function(id){ + return $("#calendar-listing-"+id).attr("data-details"); + } + + //TODO move this into a helper delete/accept module + var acceptSchedule = function(e){ + var id = getScheduleIfFromEvent(e); + apptDetails = getDetailsForId(id); + $.ajax({ + url: "/group/"+getCurrentGroupId()+"/schedule/accept.json/" +id, + type: "POST", + dataType: "json", + success: onSucess, + error: onError + }); + } + + var deleteSchedule = function(e){ + var id = getScheduleIfFromEvent(e); + $.ajax({ + url: "/group/"+getCurrentGroupId()+"/schedule/delete.json/" +id, + type: "POST", + dataType: "json", + success: onSucess, + error: onError + }); + } + + + addEventListener("add_button_clicked", addAvialability); + addEventListener("accept_schedule_clicked", acceptSchedule); + addEventListener("delete_schedule_clicked", deleteSchedule); + addEventListener("submit_clicked", onSubmit); + addEventListener("datetime_changed", onDateTimeChange); + addEventListener("agenda_changed", onAgendaChange); + //no public API - event bus architecture + return { + + } +}(); diff --git a/pool/shard000/JavaScript/0002732_common.js b/pool/shard000/JavaScript/0002732_common.js new file mode 100644 index 0000000000000000000000000000000000000000..d30c4964eb18a4598cc0182055322ff4345c92f0 --- /dev/null +++ b/pool/shard000/JavaScript/0002732_common.js @@ -0,0 +1,61 @@ +window.onload = function() { + window.scrollTo(0,document.body.scrollHeight); +}; + +function docHeight() { + var body = document.body.scrollHeight; + return body; +} + +function scrollHeight() { + var top = document.body.scrollTop; + var viewport = window.innerHeight; + return top + viewport; +} + +function imageLoad(ev, img) { + img.style.display = "none"; + var scrollBefore = scrollHeight(); + var heightBefore = docHeight(); + img.style.display = "initial"; + + scroll(scrollBefore, heightBefore, docHeight()); +} + +function scroll(scrollBefore, heightBefore, heightAfter) { + if(scrollBefore >= heightBefore) + { //scroll to bot + window.scrollTo(0, heightAfter); + } +} + +var n = 0; +function addPost(post, nick) { + var scrollBefore = scrollHeight(); + var heightBefore = docHeight(); + + var elemPost = document.createElement("div"); + elemPost.className = "app-post"+(n%2); + elemPost.innerHTML = post; + var images = elemPost.getElementsByTagName("img"); + for(var i = 0; i < images.length; i++) + images[i].onload = function(ev) { imageLoad(ev, this); }; + document.getElementById("app-contents").appendChild(elemPost); + + scroll(scrollBefore, heightBefore, docHeight()); + + n++; + onNewPost(elemPost); +} + +function clearPosts(max) { + var posts = document.getElementsByClassName("app-post"); + if(posts.length > max && posts.length > 2) //Minimum post limit + { //Clear second post + document.getElementById("app-contents").removeChild(posts[1]); + //To get this function working, app-post classes MUST be children of + //app-contents div. Do not ever put app-contents in another parent + + clearPosts(max); + } +} diff --git a/pool/shard000/JavaScript/0002733_vat.js b/pool/shard000/JavaScript/0002733_vat.js new file mode 100644 index 0000000000000000000000000000000000000000..ef84a3d31ed7032993d73a0c0ed6cfc748dcc464 --- /dev/null +++ b/pool/shard000/JavaScript/0002733_vat.js @@ -0,0 +1,40 @@ +/** + * Created by Daniel Dimmick on 24/03/15. + */ +function VAT(successbox,errorbox){ + this.vatNumber=null; + this.message=null; + + var parent = this; + + this.getVatNumber=function(){ + return this.vatNumber; + } + this.setVatNumber=function(vatNumber){ + this.vatNumber=vatNumber; + } + + this.save= function (){ + $.when(this.ajaxCall()).then(function(data){ + if(data.status=='success'){ + errorbox.stop().hide(); + successbox.find('#message').html(data.message); + successbox.stop().fadeOut('fast').fadeIn('fast'); + } + else{ + successbox.stop().hide(); + errorbox.find('#message').html(data.message); + errorbox.stop().fadeOut('fast').fadeIn('fast'); + } + }) + } + + this.ajaxCall= function(){ + return $.ajax({ + url: "/payment/vat/", + type: 'post', + dataType: 'json', + data: {"vatnumber":this.getVatNumber(),'CSRF_SESSION_TOKEN': CSRF_SESSION_TOKEN} + }); + } +} diff --git a/pool/shard000/JavaScript/0002735_PrivateMessage.js b/pool/shard000/JavaScript/0002735_PrivateMessage.js new file mode 100644 index 0000000000000000000000000000000000000000..3006ac4a9b48cb67e4c7467dcafbc8eeef0e1f65 --- /dev/null +++ b/pool/shard000/JavaScript/0002735_PrivateMessage.js @@ -0,0 +1,50 @@ +var { + mongoose, + defaultOptions, + modifySchema, + defaultSchema +} = require('../index.js'); + +// Define the document Schema +var schema = new mongoose.Schema( + Object.assign({}, defaultSchema, { + creator: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true + }, + members: [ + { + user: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true + }, + muted: { + type: Boolean, + default: false + }, + notifications_enabled: { + type: Boolean, + default: true + } + } + ] + }), + defaultOptions +); + +schema.query.byMember = function(user) { + return this.find({ 'members.user': user }); +}; + +schema.query.byCreator = function(user) { + return this.find({ creator: user }); +}; + +modifySchema(schema); + +// Initialize the model with the schema, and export it +var model = mongoose.model('PrivateMessages', schema); + +module.exports = model; diff --git a/pool/shard000/JavaScript/0002736_mostrar_lei.js b/pool/shard000/JavaScript/0002736_mostrar_lei.js new file mode 100644 index 0000000000000000000000000000000000000000..9bb1c2115d81ac80386f55eaed487744b4870b08 --- /dev/null +++ b/pool/shard000/JavaScript/0002736_mostrar_lei.js @@ -0,0 +1,22 @@ +'use strict'; + +describe('Controller: MostrarLeiCtrl', function () { + + // load the controller's module + beforeEach(module('vigiaPoliticoApp')); + + var MostrarLeiCtrl, + scope; + + // Initialize the controller and a mock scope + beforeEach(inject(function ($controller, $rootScope) { + scope = $rootScope.$new(); + MostrarLeiCtrl = $controller('MostrarLeiCtrl', { + $scope: scope + }); + })); + + it('should attach a list of awesomeThings to the scope', function () { + expect(scope.awesomeThings.length).toBe(3); + }); +}); diff --git a/pool/shard000/JavaScript/0002737_gulpfile.js b/pool/shard000/JavaScript/0002737_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..834e350b851950de31eb677beeaa8d4d2ecde636 --- /dev/null +++ b/pool/shard000/JavaScript/0002737_gulpfile.js @@ -0,0 +1,178 @@ +// generated on 2017-03-18 using generator-webapp 2.4.1 +const gulp = require('gulp'); +const gulpLoadPlugins = require('gulp-load-plugins'); +const browserSync = require('browser-sync').create(); +const del = require('del'); +const wiredep = require('wiredep').stream; +const runSequence = require('run-sequence'); + +const $ = gulpLoadPlugins(); +const reload = browserSync.reload; + +var dev = true; + +gulp.task('styles', () => { + return gulp.src('app/styles/*.scss') + .pipe($.plumber()) + .pipe($.if(dev, $.sourcemaps.init())) + .pipe($.sass.sync({ + outputStyle: 'expanded', + precision: 10, + includePaths: ['.'] + }).on('error', $.sass.logError)) + .pipe($.autoprefixer({browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']})) + .pipe($.if(dev, $.sourcemaps.write())) + .pipe(gulp.dest('.tmp/styles')) + .pipe(reload({stream: true})); +}); + +gulp.task('scripts', () => { + return gulp.src('app/scripts/**/*.js') + .pipe($.plumber()) + .pipe($.if(dev, $.sourcemaps.init())) + .pipe($.babel()) + .pipe($.if(dev, $.sourcemaps.write('.'))) + .pipe(gulp.dest('.tmp/scripts')) + .pipe(reload({stream: true})); +}); + +function lint(files) { + return gulp.src(files) + .pipe($.eslint({ fix: true })) + .pipe(reload({stream: true, once: true})) + .pipe($.eslint.format()) + .pipe($.if(!browserSync.active, $.eslint.failAfterError())); +} + +gulp.task('lint', () => { + return lint('app/scripts/**/*.js') + .pipe(gulp.dest('app/scripts')); +}); +gulp.task('lint:test', () => { + return lint('test/spec/**/*.js') + .pipe(gulp.dest('test/spec')); +}); + +gulp.task('html', ['styles', 'scripts'], () => { + return gulp.src('app/*.html') + .pipe($.useref({searchPath: ['.tmp', 'app', '.']})) + .pipe($.if(/\.js$/, $.uglify({compress: {drop_console: true}}))) + .pipe($.if(/\.css$/, $.cssnano({safe: true, autoprefixer: false}))) + .pipe($.if(/\.html$/, $.htmlmin({ + collapseWhitespace: true, + minifyCSS: true, + minifyJS: {compress: {drop_console: true}}, + processConditionalComments: true, + removeComments: true, + removeEmptyAttributes: true, + removeScriptTypeAttributes: true, + removeStyleLinkTypeAttributes: true + }))) + .pipe(gulp.dest('dist')); +}); + +gulp.task('images', () => { + return gulp.src('app/images/**/*') + .pipe($.cache($.imagemin())) + .pipe(gulp.dest('dist/images')); +}); + +gulp.task('fonts', () => { + return gulp.src(require('main-bower-files')('**/*.{eot,svg,ttf,woff,woff2}', function (err) {}) + .concat('app/fonts/**/*')) + .pipe($.if(dev, gulp.dest('.tmp/fonts'), gulp.dest('dist/fonts'))); +}); + +gulp.task('extras', () => { + return gulp.src([ + 'app/*', + '!app/*.html' + ], { + dot: true + }).pipe(gulp.dest('dist')); +}); + +gulp.task('clean', del.bind(null, ['.tmp', 'dist'])); + +gulp.task('serve', () => { + runSequence(['clean', 'wiredep'], ['styles', 'scripts', 'fonts'], () => { + browserSync.init({ + notify: false, + port: 9000, + server: { + baseDir: ['.tmp', 'app'], + routes: { + '/bower_components': 'bower_components' + } + } + }); + + gulp.watch([ + 'app/*.html', + 'app/images/**/*', + '.tmp/fonts/**/*' + ]).on('change', reload); + + gulp.watch('app/styles/**/*.scss', ['styles']); + gulp.watch('app/scripts/**/*.js', ['scripts']); + gulp.watch('app/fonts/**/*', ['fonts']); + gulp.watch('bower.json', ['wiredep', 'fonts']); + }); +}); + +gulp.task('serve:dist', ['default'], () => { + browserSync.init({ + notify: false, + port: 9000, + server: { + baseDir: ['dist'] + } + }); +}); + +gulp.task('serve:test', ['scripts'], () => { + browserSync.init({ + notify: false, + port: 9000, + ui: false, + server: { + baseDir: 'test', + routes: { + '/scripts': '.tmp/scripts', + '/bower_components': 'bower_components' + } + } + }); + + gulp.watch('app/scripts/**/*.js', ['scripts']); + gulp.watch(['test/spec/**/*.js', 'test/index.html']).on('change', reload); + gulp.watch('test/spec/**/*.js', ['lint:test']); +}); + +// inject bower components +gulp.task('wiredep', () => { + gulp.src('app/styles/*.scss') + .pipe($.filter(file => file.stat && file.stat.size)) + .pipe(wiredep({ + ignorePath: /^(\.\.\/)+/ + })) + .pipe(gulp.dest('app/styles')); + + gulp.src('app/*.html') + .pipe(wiredep({ + exclude: ['bootstrap-sass'], + ignorePath: /^(\.\.\/)*\.\./ + })) + .pipe(gulp.dest('app')); +}); + +gulp.task('build', ['lint', 'html', 'images', 'fonts', 'extras'], () => { + return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true})); +}); + +gulp.task('default', () => { + return new Promise(resolve => { + dev = false; + runSequence(['clean', 'wiredep'], 'build', resolve); + }); +}); diff --git a/pool/shard000/JavaScript/0002739_role.js b/pool/shard000/JavaScript/0002739_role.js new file mode 100644 index 0000000000000000000000000000000000000000..053d3c1c162dc039cd8393907543259e07823323 --- /dev/null +++ b/pool/shard000/JavaScript/0002739_role.js @@ -0,0 +1,35 @@ +var express = require('express'); +var router = express.Router(); +var core = require('../../libs/core'); +var role = require('../../controllers/server/role'); + +//权限判断 +router.use(function(req, res, next) { + console.log('角色页: ' + Date.now()); + res.locals.Path = 'role'; + if(!req.session.user) { + var path = core.translateAdminDir('/user/login'); + return res.redirect(path); + } + if(!req.Roles || (req.Roles.indexOf('admin') < 0 && req.Actions && req.Actions.indexOf('role') < 0)) { + var path = core.translateAdminDir('/'); + return res.redirect(path); + } + next(); +}); +//内容列表 +router.route('/').get(role.list); +//添加内容 +router.route('/add').all(role.add); +//单条信息 +router.route('/:id').get(role.one); +//更新信息 +router.route('/:id/edit').all(role.edit); +//删除信息 +router.route('/:id/del').all(role.del); + + +module.exports = function(app) { + var path = core.translateAdminDir('/role'); + app.use(path, router); +}; diff --git a/pool/shard000/JavaScript/0002740_Callback.js b/pool/shard000/JavaScript/0002740_Callback.js new file mode 100644 index 0000000000000000000000000000000000000000..5deaacf18f3e102e16b1619ca16348540351c696 --- /dev/null +++ b/pool/shard000/JavaScript/0002740_Callback.js @@ -0,0 +1,124 @@ +/** + * Created by kgrube on 4/3/2019 + * @private + */ +const request = require('request'); +const crypto = require('crypto'); + +/** + * @typedef {Object} CallbackPayload + * @property Action + * @property CompanyId + * @property Entity json string + * @property FromUrl + * @property ID + * @property MemberId + * @property {object} Metadata + * @property Metadata.key_url + * @property Type + */ + +/** + * @typedef {object} CWCallback + * @property verifyCallback + * @property verifyMessage + * @property middleware + * + */ + +/** + * Load signing key and verify the message + * @param {CallbackPayload} callbackBody + * @param {string} contentSignature base64 content signature req.headers[x-content-signature] + * @return {Promise} + */ +function verifyCallback(callbackBody, contentSignature) { + return new Promise((resolve, reject) => { + if (!callbackBody || !contentSignature) { + throw new Error('callbackBody and contentSignature must be defined.'); + } + + const key_url = callbackBody.Metadata && callbackBody.Metadata.key_url; + + request(key_url, (err, res, body) => { + if (err) throw err; + try { + const parsed = JSON.parse(body); + const signingKey = parsed.signing_key; + + return resolve(verifyMessage(callbackBody, contentSignature, signingKey)); + } catch (parseErr) { + throw parseErr; + } + }); + }); +} + +/** + * Validate a callback body against signed key + * @param {CallbackPayload} callbackBody + * @param {string} contentSignature + * @param {string} signingKey + * @returns {boolean} + */ +function verifyMessage(callbackBody, contentSignature, signingKey) { + const hash = crypto.createHash('sha256').update(signingKey).digest(); + const hmac = crypto.createHmac('sha256', hash); + + return contentSignature === hmac.update(JSON.stringify(callbackBody)).digest('base64'); +} + +/** + * Express style middleware + * @example + * app.post('/your/api', cw.utils.middleware((err, req, res, verified, payload) => { + * if (err) { + * //handle error + * res.status(500).end(); + * } else if (!verified) { + * // send 403 on verification failure + * res.status(403).end(); + * } else { + * res.status(200).end() + * } + * const {action, id} = req.query; + * // do something with the payload + * })); + * + * @param {function} cb callback(err, req, res, verified, payload) + */ +function middleware(cb) { + if (!cb || typeof cb !== 'function') { + throw new Error('callback must be a function.'); + } + + return (req, res) => { + if (!req || !req.body || !req.body.Metadata) { + return cb(new Error('callback payload is invalid.'), req, res, false); + } + + const contentSignature = req.headers['x-content-signature']; + const callbackBody = req.body; + + let parsedEntity; + try { + parsedEntity = JSON.parse(callbackBody.Entity); + } catch (parseErr) { + return cb(parseErr, req, res, false); + } + + verifyCallback(callbackBody, contentSignature) + .then(verified => { + return cb(null, req, res, verified, Object.assign(callbackBody, {Entity: parsedEntity})); + }) + .catch(err => { + return cb(err, req, res, false); + }); + }; +} + +module.exports = { + verifyMessage, + verifyCallback, + middleware, +}; diff --git a/pool/shard000/JavaScript/0002742_sv.js b/pool/shard000/JavaScript/0002742_sv.js new file mode 100644 index 0000000000000000000000000000000000000000..bde95daa653b5cd5852a319b6089442160c51c0c --- /dev/null +++ b/pool/shard000/JavaScript/0002742_sv.js @@ -0,0 +1,54 @@ +(function () { + var lang = { + months : "januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"), + monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"), + weekdays : "söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"), + weekdaysShort : "sön_mån_tis_ons_tor_fre_lör".split("_"), + longDateFormat : { + LT : "HH:mm", + L : "YYYY-MM-DD", + LL : "D MMMM YYYY", + LLL : "D MMMM YYYY LT", + LLLL : "dddd D MMMM YYYY LT" + }, + calendar : { + sameDay: '[Idag klockan] LT', + nextDay: '[Imorgon klockan] LT', + lastDay: '[Igår klockan] LT', + nextWeek: 'dddd [klockan] LT', + lastWeek: '[Förra] dddd [en klockan] LT', + sameElse: 'L' + }, + relativeTime : { + future : "om %s", + past : "för %s sen", + s : "några sekunder", + m : "en minut", + mm : "%d minuter", + h : "en timme", + hh : "%d timmar", + d : "en dag", + dd : "%d dagar", + M : "en månad", + MM : "%d månader", + y : "ett år", + yy : "%d år" + }, + ordinal : function (number) { + var b = number % 10; + return (~~ (number % 100 / 10) === 1) ? 'e' : + (b === 1) ? 'a' : + (b === 2) ? 'a' : + (b === 3) ? 'e' : 'e'; + } + }; + + // Node + if (typeof module !== 'undefined') { + module.exports = lang; + } + // Browser + if (typeof window !== 'undefined' && this.moment && this.moment.lang) { + this.moment.lang('sv', lang); + } +}()); diff --git a/pool/shard000/JavaScript/0002743_autoprefixer-test.js b/pool/shard000/JavaScript/0002743_autoprefixer-test.js new file mode 100644 index 0000000000000000000000000000000000000000..716bdad46c9ec5bf4d19b2106c74d1b4839dada5 --- /dev/null +++ b/pool/shard000/JavaScript/0002743_autoprefixer-test.js @@ -0,0 +1,55 @@ +var vows = require('vows'), + assert = require('assert'), + AssetGraph = require('../lib/AssetGraph'); + +vows.describe('transforms.autoprefixer').addBatch({ + 'After loading an unprefixed test case': { + topic: function () { + new AssetGraph({root: __dirname + '/autoprefixer/'}) + .loadAssets('index.html') + .populate() + .run(this.callback); + }, + 'the graph should contain 2 HtmlStyle relations': function (assetGraph) { + assert.equal(assetGraph.findRelations({type: 'HtmlStyle'}).length, 2); + }, + 'the graph should contain 1 CssImage relation': function (assetGraph) { + assert.equal(assetGraph.findRelations({type: 'CssImage'}).length, 1); + }, + 'then running the autoprefixer transform': { + topic: function (assetGraph) { + assetGraph + .autoprefixer() + .run(this.callback); + }, + 'the graph should contain 2 HtmlStyle relations': function (assetGraph) { + assert.equal(assetGraph.findRelations({type: 'HtmlStyle'}).length, 2); + }, + 'the graph should contain 3 CssImage relation': function (assetGraph) { + assert.equal(assetGraph.findRelations({type: 'CssImage'}).length, 3); + } + } + }, + 'After loading an test case using prefixfree.js': { + topic: function () { + new AssetGraph({root: __dirname + '/autoprefixer/'}) + .loadAssets('prefixfree.html') + .populate() + .run(this.callback); + }, + 'the graph should contain 2 HtmlScript relations': function (assetGraph) { + assert.equal(assetGraph.findRelations({type: 'HtmlScript'}).length, 2); + }, + 'then running the autoprefixer transform': { + topic: function (assetGraph) { + assetGraph + .autoprefixer() + .run(this.callback); + }, + 'the graph should contain 0 HtmlScript relations': function (assetGraph) { + assert.equal(assetGraph.findRelations({type: 'HtmlScript'}).length, 0); + } + } + } + +})['export'](module); diff --git a/pool/shard000/JavaScript/0002748_nativeBridge.js b/pool/shard000/JavaScript/0002748_nativeBridge.js new file mode 100644 index 0000000000000000000000000000000000000000..cacda30e861544d0ae88bfe62e736b7548b9595f --- /dev/null +++ b/pool/shard000/JavaScript/0002748_nativeBridge.js @@ -0,0 +1,214 @@ +(function (mw, $) { + "use strict"; + var NativeBridge = { + callbacksCount: 1, + callbacks: {}, + + // Automatically called by native layer when a result is available + resultForCallback: function resultForCallback(callbackId, resultArray) { + try { + var callback = NativeBridge.callbacks[callbackId]; + if (!callback) { + return; + } + + callback.apply(null, resultArray); + } catch (e) { + alert(e); + } + }, + + // Use this in javascript to request native objective-c code + // functionName : string (I think the name is explicit :p) + // args : array of arguments + // callback : function with n-arguments that is going to be called when the native code returned + call: function call(functionName, args, callback) { + + var hasCallback = callback && typeof callback == "function"; + var callbackId = hasCallback ? NativeBridge.callbacksCount++ : 0; + + if (hasCallback) { + NativeBridge.callbacks[callbackId] = callback; + } + + var iframe = document.createElement("IFRAME"); + iframe.setAttribute("src", "js-frame:" + functionName + ":" + callbackId + ":" + encodeURIComponent(JSON.stringify(args))); + document.documentElement.appendChild(iframe); + iframe.parentNode.removeChild(iframe); + iframe = null; + } + }; + + NativeBridge.videoPlayer = NativeBridge.videoPlayer || { + proxyElement: null, + embedPlayer: null, + isJsCallbackReady: false, + bindPostfix: ".nativeBridge", + subscribed: [], + playerMethods: [ + 'stop', 'play', 'pause', 'replay', 'setPlayerSource', 'bindPlayerEvents', 'showNativePlayer', 'hideNativePlayer', 'toggleFullscreen', 'notifyKPlayerEvent', 'notifyKPlayerEvaluated', 'notifyJsReady', 'showChromecastDeviceList', 'notifyLayoutReady', + 'doneFSBtnPressed', 'addNativeAirPlayButton', 'showNativeAirPlayButton', 'hideNativeAirPlayButton', 'doNativeAction', 'textTracksReceived', 'loadEmbeddedCaptions', 'flavorsListChanged', 'switchFlavor' ], + + registePlayer: function (proxyElement) { + var _this = this; + this.proxyElement = proxyElement; + + this.proxyElement.attr = function (attributeName, attributeValue) { + if (attributeName && attributeValue === undefined) { + return _this.proxyElement[ attributeName ]; + } else if (attributeName && attributeValue) { + _this.proxyElement[attributeName] = attributeValue; + _this.execute('setAttribute', [ attributeName, attributeValue ]); + _this.proxyElement['language'] = mw.getConfig('localizationCode'); + _this.execute('setAttribute', [ 'language', mw.getConfig('localizationCode') ]); + } + } + + for (var i = 0; i < this.playerMethods.length; i++) { + (function (method) { + _this.proxyElement[method] = function (arg) { + _this.execute(method, arg); + } + })(this.playerMethods[i]); + } + + + //TODO support more than 1 subscribe? + this.proxyElement.subscribe = function (callback, eventName) { + _this.subscribed[eventName] = callback; + } + + this.proxyElement.unsubscribe = function (eventName) { + _this.subscribed[eventName] = undefined; + } + + this.bindNativeEvents(); + }, + + notifyJsReadyFunc: function () { + if (this.isJsCallbackReady && this.proxyElement) { + this.proxyElement.notifyJsReady([]); + } + }, + + registerEmbedPlayer: function (embedPlayer) { + this.embedPlayer = embedPlayer; + this.notifyJsReadyFunc(); + }, + sendNotification: function (eventName, eventValue) { + this.embedPlayer.sendNotification(eventName, JSON.parse(eventValue)); + }, + /** + * + * @param object + * @returns String rerpesantation of given object + */ + getObjectString: function (object) { + var stringValue = object; + if (typeof object === "object") { + stringValue = JSON.stringify(object); + } + return stringValue; + }, + addJsListener: function (eventName) { + var _this = this; + this.embedPlayer.addJsListener(eventName + this.bindPostfix, function (val) { + _this.embedPlayer.getPlayerElement().notifyKPlayerEvent([ eventName, _this.getObjectString(val) ]); + }); + }, + removeJsListener: function (eventName) { + this.embedPlayer.removeJsListener(eventName + this.bindPostfix); + }, + setKDPAttribute: function (host, prop, value) { + this.embedPlayer.setKDPAttribute(host, prop, value); + }, + /** + * will evaluate given expression and send the resulted value back to native code with the given callbackName + * @param expression + * @param callbackName + */ + asyncEvaluate: function (expression, callbackName) { + var result = this.embedPlayer.evaluate(expression); + this.embedPlayer.getPlayerElement().notifyKPlayerEvaluated([ callbackName, this.getObjectString(result) ]); + }, + //this function should be called from IOS/Andorid + trigger: function (eventName, eventValue) { + // mw.log('nativeBridge.js --> trigger:' + eventName + ' ' + eventValue); + + if (eventValue === "(null)") { + //set undefined + eventValue = void(0); + } + + if (eventValue != undefined) { + var jsEventValue = this.stringConvertion(eventValue); + } + + if (eventName == 'timeupdate') { + this.proxyElement['currentTime'] = jsEventValue; + } else if (eventName == 'progress') { + this.proxyElement['progress'] = jsEventValue; + } else if (eventName == 'visible') { + this.proxyElement['visible'] = jsEventValue; + } else if (eventName == 'durationchange') { + this.proxyElement['duration'] = jsEventValue; + } else if (eventName == 'nativeAction') { + this.proxyElement['nativeAction'] = jsEventValue; + } else if (eventName == 'play') { + this.proxyElement['paused'] = false; + } else if (eventName == 'pause') { + this.proxyElement['paused'] = true; + } + + $(this.proxyElement).trigger(eventName, [jsEventValue]); + + if (this.subscribed[eventName]) { + this.subscribed[eventName](jsEventValue); + } + }, + execute: function (command, args) { + args = args || []; + console.log(command); + console.log(args); + NativeBridge.call(command, args); + }, + bindNativeEvents: function () { + console.log('bindNativeEvents'); + this.proxyElement.bindPlayerEvents([]); + }, + log: function (message, arg) { + console.log(message, arg); + }, + getVideoHolderHeight: function () { + return this.embedPlayer.getVideoHolder().height(); + }, + getControlBarHeight: function () { + return this.embedPlayer.getControlBarContainer().height(); + }, + stringConvertion: function (str) { + var value = parseFloat(str); + + if (isNaN(value)) { + if (value == 'true') { + return true; + } else if (value == 'false') { + return false; + } else { + return str; + } + } + + return value; + } + }; + + + if (mw.getConfig('EmbedPlayer.ForceNativeComponent') === true) { + window["NativeBridge"] = NativeBridge; + kWidget.addReadyCallback(function () { + NativeBridge.videoPlayer.isJsCallbackReady = true; + NativeBridge.videoPlayer.notifyJsReadyFunc(); + }); + } + +})(window.mw, window.jQuery); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002749_filter.js b/pool/shard000/JavaScript/0002749_filter.js new file mode 100644 index 0000000000000000000000000000000000000000..d8e8e9234df3a5bf5ce0e9d814e71d512e31e3a0 --- /dev/null +++ b/pool/shard000/JavaScript/0002749_filter.js @@ -0,0 +1,41 @@ +const symbols = require('../../../symbols'); +const createToken = require('../../../create-token'); +const callFunction = require('./call-function'); + +const lelPromise = require('../../../util/lel-promise'); +const lelSeries = require('../../../util/lel-series'); + +const getFilteringFunction = + (resolve, reject, evaluateExpr, scope, expr) => + (list) => { + if (list.type !== symbols.LIST) { + reject(new Error(`Invalid list passed to filter. Got ${expr}`)); + } + + evaluateExpr(scope, expr[2]) + .then(performFiltering(resolve, reject, evaluateExpr, scope, expr, list)); + }; + +const performFiltering = + (resolve, reject, evaluateExpr, scope, expr, list) => + (filteringFunction) => { + if (filteringFunction.type !== symbols.FUNCTION_REFERENCE) { + reject(new Error(`Invalid function passed to filter. Got ${expr}`)); + } + + const mapCalls = list.value.map( + (listElement, i) => + () => callFunction(evaluateExpr, scope, [listElement, createToken(symbols.NUMBER, i)], filteringFunction.value) + ); + lelSeries(mapCalls) + .then(values => { + const newList = list.value.filter((element, index) => values[index].value); + resolve(createToken(symbols.LIST, newList)) + }); + }; + +module.exports = (evaluateExpr, scope, expr) => + lelPromise((resolve, reject) => + evaluateExpr(scope, expr[1]) + .then(getFilteringFunction(resolve, reject, evaluateExpr, scope, expr)) + ); diff --git a/pool/shard000/JavaScript/0002750_listener.js b/pool/shard000/JavaScript/0002750_listener.js new file mode 100644 index 0000000000000000000000000000000000000000..7d39d81b924dd0d0eeacf95e1b8af32717a4a5c5 --- /dev/null +++ b/pool/shard000/JavaScript/0002750_listener.js @@ -0,0 +1,173 @@ +// Copyright 2005 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview Listener object. + * @see ../demos/events.html + */ + +goog.provide('goog.events.Listener'); + +goog.require('goog.events.ListenableKey'); + + + +/** + * Simple class that stores information about a listener + * @implements {goog.events.ListenableKey} + * @constructor + */ +goog.events.Listener = function() { + if (goog.events.Listener.ENABLE_MONITORING) { + this.creationStack = new Error().stack; + } +}; + + +/** + * @define {boolean} Whether to enable the monitoring of the + * goog.events.Listener instances. Switching on the monitoring is only + * recommended for debugging because it has a significant impact on + * performance and memory usage. If switched off, the monitoring code + * compiles down to 0 bytes. + */ +goog.events.Listener.ENABLE_MONITORING = false; + + +/** + * Whether the listener is a function or an object that implements handleEvent. + * @type {boolean} + * @private + */ +goog.events.Listener.prototype.isFunctionListener_; + + +/** + * Call back function or an object with a handleEvent function. + * @type {Function|Object|null} + */ +goog.events.Listener.prototype.listener; + + +/** + * Proxy for callback that passes through {@link goog.events#HandleEvent_} + * @type {Function} + */ +goog.events.Listener.prototype.proxy; + + +/** + * Object or node that callback is listening to + * @type {Object|goog.events.EventTarget} + */ +goog.events.Listener.prototype.src; + + +/** + * Type of event + * @type {string} + */ +goog.events.Listener.prototype.type; + + +/** + * Whether the listener is being called in the capture or bubble phase + * @type {boolean} + */ +goog.events.Listener.prototype.capture; + + +/** + * Optional object whose context to execute the listener in + * @type {Object|undefined} + */ +goog.events.Listener.prototype.handler; + + +/** + * The key of the listener. + * @type {number} + * @override + */ +goog.events.Listener.prototype.key = 0; + + +/** + * Whether the listener has been removed. + * @type {boolean} + */ +goog.events.Listener.prototype.removed = false; + + +/** + * Whether to remove the listener after it has been called. + * @type {boolean} + */ +goog.events.Listener.prototype.callOnce = false; + + +/** + * If monitoring the goog.events.Listener instances is enabled, stores the + * creation stack trace of the Disposable instance. + * @type {string} + */ +goog.events.Listener.prototype.creationStack; + + +/** + * Initializes the listener. + * @param {Function|Object} listener Callback function, or an object with a + * handleEvent function. + * @param {Function} proxy Wrapper for the listener that patches the event. + * @param {Object} src Source object for the event. + * @param {string} type Event type. + * @param {boolean} capture Whether in capture or bubble phase. + * @param {Object=} opt_handler Object in whose context to execute the callback. + */ +goog.events.Listener.prototype.init = function(listener, proxy, src, type, + capture, opt_handler) { + // we do the test of the listener here so that we do not need to + // continiously do this inside handleEvent + if (goog.isFunction(listener)) { + this.isFunctionListener_ = true; + } else if (listener && listener.handleEvent && + goog.isFunction(listener.handleEvent)) { + this.isFunctionListener_ = false; + } else { + throw Error('Invalid listener argument'); + } + + this.listener = listener; + this.proxy = proxy; + this.src = src; + this.type = type; + this.capture = !!capture; + this.handler = opt_handler; + this.callOnce = false; + this.key = goog.events.ListenableKey.reserveKey(); + this.removed = false; +}; + + +/** + * Calls the internal listener + * @param {Object} eventObject Event object to be passed to listener. + * @return {boolean} The result of the internal listener call. + */ +goog.events.Listener.prototype.handleEvent = function(eventObject) { + if (this.isFunctionListener_) { + return this.listener.call(this.handler || this.src, eventObject); + } + return this.listener.handleEvent.call(this.listener, eventObject); +}; diff --git a/pool/shard000/JavaScript/0002753_release.js b/pool/shard000/JavaScript/0002753_release.js new file mode 100644 index 0000000000000000000000000000000000000000..7fa79b847b94929e796f82d49a6754990f0a674a --- /dev/null +++ b/pool/shard000/JavaScript/0002753_release.js @@ -0,0 +1,35 @@ +'use strict'; + +const Command = require('cmnd').Command; +const UpCommand = require('./up.js'); + +const fs = require('fs'); +const inquirer = require('inquirer'); + +class ReleaseCommand extends Command { + + constructor() { + + super('release'); + + } + + help() { + + return { + description: 'Pushes release of Autocode package to registry and cloud (Alias of `lib up -r`)' + }; + + } + + run(params, callback) { + + params.flags.r = []; + params.args = []; + UpCommand.prototype.run.call(this, params, callback); + + } + +} + +module.exports = ReleaseCommand; diff --git a/pool/shard000/JavaScript/0002754_index.js b/pool/shard000/JavaScript/0002754_index.js new file mode 100644 index 0000000000000000000000000000000000000000..3221131c6380653a2204b5f423de3fa4f55ad9ff --- /dev/null +++ b/pool/shard000/JavaScript/0002754_index.js @@ -0,0 +1,71 @@ +#!/usr/bin/env node + +// # node rename.js +// node shell scripting + +// Ensure that files are able to be modified +// Possible chmod needs to happen too + +const colors = require('colors'); +const program = require('commander'); +const fs = require('fs'); +const path = require('path'); +let folder = 'Path/to/directory'; // Folder the script reads to replace text +let regex = /\(.+\) |\(.+\)|[^a-zA-Z0-9.\s\&\,]/gi; // rename.js finds `regex` to replace with `replaceWith`, which replaces with whatever +let replace = ''; + +let massRename; + +program + .version('0.0.1') + .usage('[options] ') + .option('-c --copy ', 'Makes a copy') + .parse(process.argv); + +massRename = (folder, regex, replace) => { + let files = fs.readdirSync(folder); + console.dir(files); + for (let i = 0; i < files.length; i++) { + let check = fs.readdirSync(folder); // Updates per cycle + let prev = path.join(folder, files[i]); + let stat = fs.statSync(prev); + // console.log(prev) + if (stat.isFile()) { + if (files[i].match(regex) && files[i].charAt(0) != '.') { + + let ext = path.extname(files[i]); // Extension + let basename = path.basename(files[i], ext) + .replace(/\&/, 'and') + .replace(/_/g, ' ') // Replaces _ with ' ' + .replace(regex, replace) // basename with regex applied + .replace(/\s\s+/g, ' '); // Condenses double spaces + if (basename.charAt(basename.length - 1) == ' ') { + basename = basename.slice(0, -1) + ext; // Removes ' ' + } else { + basename = basename + ext; + }; + let next = path.join(folder, basename); + if (check.indexOf(basename) > -1) { + console.log(`:: Err! Program would overwrite existing file.\n:: File: ${prev}\n:: Dir: ${folder}`.red); + break; + } else { + // fs.renameSync(prev, next); + console.log(`${files[i]} => ${basename}`); + } + } + } else if (stat.isDirectory() && files[i] != '.yacreaderlibrary') { + let newPath = path.join(folder, files[i]); + // console.log(`: Switching to folder ${newPath}`.green); + massRename(newPath, regex, replace); + // console.log(`: Returning to ${folder}`.green) + } else { + console.log(`No valid target file for ${files[i]}.`); + } + }; +}; + +massRename(folder, regex, replace); + +exports.module = (folder, regex, replace) => { + massRename(folder, regex, replace); +}; diff --git a/pool/shard000/JavaScript/0002758_actions.js b/pool/shard000/JavaScript/0002758_actions.js new file mode 100644 index 0000000000000000000000000000000000000000..7bcd7a0aae8173796bc975cf0065dc4163251803 --- /dev/null +++ b/pool/shard000/JavaScript/0002758_actions.js @@ -0,0 +1,29 @@ +const playbackStates = require("../../../backend/player/Player").playbackStates; +const actions = require("../../../actions"); +const SearchPanel = require("../SearchPanel"); +const errors = require("./errors"); +const QueuePanel = require("../QueuePanel"); +const UserPlaylistsPanel = require("../UserPlaylistsPanel"); +const AppConfiguration = require("../../../backend/Configuration/App"); +const appConfiguration = new AppConfiguration().getConfig(); + +module.exports = { + loginRequired: { + [appConfiguration["INPUT_BAR_ACTIONS"]["PAUSE"]]: store => store.dispatch(actions.player.setPlaybackState(playbackStates.PAUSED)), + [appConfiguration["INPUT_BAR_ACTIONS"]["RESUME"]]: store => store.dispatch(actions.player.setPlaybackState(playbackStates.PLAYING)), + [appConfiguration["INPUT_BAR_ACTIONS"]["SEARCH"]]: (store, searchValue) => { + if (!searchValue) { + return errors.undefinedSearchValue; + } + store.dispatch(actions.ui.setCurrentActivity(SearchPanel, {searchValue})); + }, + [appConfiguration["INPUT_BAR_ACTIONS"]["PLAYLISTS"]]: store => store.dispatch(actions.ui.setCurrentActivity(UserPlaylistsPanel, {})), + [appConfiguration["INPUT_BAR_ACTIONS"]["QUEUE"]]: store => store.dispatch(actions.ui.setCurrentActivity(QueuePanel, {})), + [appConfiguration["INPUT_BAR_ACTIONS"]["NEXT"]]: store => store.dispatch(actions.player.skipTracks(1)), + [appConfiguration["INPUT_BAR_ACTIONS"]["SKIP"]]: (store, amount = 1) => store.dispatch(actions.player.skipTracks(amount)), + [appConfiguration["INPUT_BAR_ACTIONS"]["SHUFFLE"]]: store => store.dispatch(actions.player.shuffleTracksQueue()), + }, + loginNotRequired: { + [appConfiguration["INPUT_BAR_ACTIONS"]["QUIT"]]: store => store.dispatch(actions.basic.exit()) + } +}; \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002760_main.js b/pool/shard000/JavaScript/0002760_main.js new file mode 100644 index 0000000000000000000000000000000000000000..c5c60eb5c08984d5ec9b49f81e247d56e68bef97 --- /dev/null +++ b/pool/shard000/JavaScript/0002760_main.js @@ -0,0 +1,254 @@ +/* gallery.js v1.0.0 | GNU GENERAL PUBLIC LICENSE + Author: Jean Frank Arias Sanchez + Description: Site Form Scripts +*/ + +$(document).ready(function() { + slider(); + scroller(); + dropDownMenu(); + Menu(); + fixedMenu(); + menuSlider(); +}); + +$(window).resize(function() { + scroller(); + Menu(); +}); + +/* gallery.js v1.0.0 | GNU GENERAL PUBLIC LICENSE + Author: Jean Frank Arias Sanchez + Description: Simple Fade Gallery +*/ + +function slider(){ + + // Variables + + var gallery = $('.slider'); + var slides = $('.slider li'); + var activeSlide = 1; // Set to 1 since the slides animation must start in the second slide + + // Function to remove the .active class from all the slides + + function resetGallery() { + for (var slide = 0; slide < slides.length; slide++){ + $(slides[slide]).removeClass('active'); + } + } + + // Function to add the .active class to the current slide + + function setActiveSlide() { + $(slides[activeSlide]).addClass('active'); + activeSlide++; + if (activeSlide >= slides.length){ + activeSlide = 0; + }; + } + + // Running the gallery + + setInterval(function(){ + resetGallery(); + setActiveSlide(); + }, + 4000); // Slides time in mili seconds. 4000 = 4 seconds + +} + +/* gallery.js v1.0.0 | GNU GENERAL PUBLIC LICENSE + Author: Jean Frank Arias Sanchez + Description: Paralax Fixed Menu +*/ + +function fixedMenu(){ + + $(document).scroll(function(){ + + var menuItems = $('.main-menu li'); + var homePos = $('#Home').offset().top; + var aboutPos = $('#About').offset().top; + var menuPos = $('#Menu').offset().top; + var reservationPos = $('#Reservation').offset().top; + var contactPos = $('#Contact').offset().top; + + var docWidth = $(document).width(); + var scrollPos = $(document).scrollTop(); + var contentOffset = 0; + + if (docWidth >= 623){ + contentOffset = 50; + }else{ + contentOffset = 100; + } + + if (scrollPos >= ( aboutPos - contentOffset)){ + activeReset(); + menuItems.eq(1).addClass('active'); + }else{ + activeReset(); + menuItems.eq(0).addClass('active'); + } + if (scrollPos >= ( menuPos - contentOffset)){ + activeReset(); + menuItems.eq(2).addClass('active'); + } + if (scrollPos >= ( reservationPos - contentOffset)){ + activeReset(); + menuItems.eq(3).addClass('active'); + } + if (scrollPos >= ( contactPos - contentOffset)){ + activeReset(); + menuItems.eq(4).addClass('active'); + } + + function activeReset(){ + menuItems.each(function(){ + $(this).removeClass('active'); + }); + } + + var docOffsetTop = $(document).scrollTop(); + var menuHeight = 0; + + if (docWidth >= 975){ + menuHeight = 155; + }else { + menuHeight = 50; + } + + if (docOffsetTop >= menuHeight ) { + + $('.logo').addClass('fixed'); + $('.main-menu').addClass('fixed'); + $('.social-menu').addClass('fixed'); + + }else{ + + $('.logo').removeClass('fixed'); + $('.main-menu').removeClass('fixed'); + $('.social-menu').removeClass('fixed'); + + } + + }); + +} + + +function collapseReset(){ + $('.collapse-btn i').removeClass('fa-angle-up'); + $('.collapse-btn i').addClass('fa-angle-down'); +} + +function Menu() { + + var screenWidth = $(document).width(); + + if (screenWidth >= 975){ + + showMenu(); + + }else{ + + hideMenu(); + collapseReset(); + + $('.main-menu li').not('.active').click(function(){ + hideMenu(); + }); + $('.main-menu li').click(function(){ + collapseReset(); + }); + } + +} + +function dropDownMenu() { + + $('.collapse-btn').click(function(e){ + e.preventDefault(); + var isCollapsed = $('.main-menu li').not('.active').hasClass('collapsed'); + if ( isCollapsed == true ){ + showMenu(); + $('.collapse-btn i').removeClass('fa-angle-down'); + $('.collapse-btn i').addClass('fa-angle-up'); + }else{ + hideMenu(); + $('.collapse-btn i').removeClass('fa-angle-up'); + $('.collapse-btn i').addClass('fa-angle-down'); + } + }); + +} + +function showMenu(){ + $('.main-menu li').not('.active').removeClass('collapsed').addClass('visible'); +} + +function hideMenu(){ + $('.main-menu li').not('.active').removeClass('visible').addClass('collapsed'); +} + +/* gallery.js v1.0.0 | GNU GENERAL PUBLIC LICENSE + Author: Jean Frank Arias Sanchez + Description: Manu Slider Fixed Menu +*/ + +function menuSlider(){ + + $('.slider-Item a').click(function(e){ + e.preventDefault(); + imgSrc = $(this).attr("href"); + imgCaption = $(this).attr("title"); + sliderItem = $(this).parent(); + sliderSelectors = sliderItem.parent(); + sliderContainer = sliderSelectors.parent(); + + $(sliderSelectors).find('.slider-Item').each(function(){ + $(this).removeClass('active'); + }); + + $(sliderItem).addClass('active'); + + $(sliderContainer).find('.slider-activeItem img').attr('src', imgSrc); + $(sliderContainer).find('.slider-activeItem .slider-caption').text(imgCaption); + + }); + +} + +/* scroll.js v1.0.0 | GNU GENERAL PUBLIC LICENSE + Author: Jean Frank Arias Sanchez + Description: Section Scroller +*/ + +function scroller(){ + + var menuItems = $('.main-menu li'); + var contentOffset; + var documentWidth = $(document).width(); + + if (documentWidth >= 623){ + contentOffset = 48; + }else{ + contentOffset = 100; + } + + $(menuItems).find('a').click(function(e) { + e.preventDefault(); + var section = $(this).attr("href"); + var scrollTo = ($(section).offset().top) - contentOffset; + $("html, body").animate({ + scrollTop: scrollTo + }); + }); + + $('.logo a').click(function(e) { + e.preventDefault(); + $("html, body").animate({scrollTop: 0}); + }); + +} diff --git a/pool/shard000/JavaScript/0002762_controller.js b/pool/shard000/JavaScript/0002762_controller.js new file mode 100644 index 0000000000000000000000000000000000000000..265f7bd76835459b9345917e6a9271a200de63ad --- /dev/null +++ b/pool/shard000/JavaScript/0002762_controller.js @@ -0,0 +1,111 @@ +/** + * Copyright (c) 2014 brian@bevey.org + * + * 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. + */ + +/** + * @author brian@bevey.org + * @fileoverview Unit test for devices/geiger/controller.js + */ + +exports.geigerControllerTest = { + fragments : function (test) { + 'use strict'; + + var geigerController = require(__dirname + '/../../../../devices/geiger/controller'), + fragments = geigerController.fragments(); + + test.strictEqual(typeof fragments.report, 'string', 'Fragment verified'); + test.strictEqual(typeof fragments.graph, 'string', 'Fragment verified'); + + test.done(); + }, + + postPrepare : function (test) { + 'use strict'; + + var geigerController = require(__dirname + '/../../../../devices/geiger/controller'), + config = { host : 'example.com', + port : '80', + path : '/test/', + method : 'POST', + badData : 'FAILURE', + postRequest : 'hello :)'}, + testPost = geigerController.postPrepare(config); + + test.deepEqual(testPost, { host : 'example.com', + port : '80', + path : '/test/', + method : 'POST', + headers : { + 'Accept' : 'application/json', + 'Accept-Charset' : 'utf-8', + 'User-Agent' : 'node-switchBoard', + 'Content-Type' : 'application/x-www-form-urlencoded', + 'Content-Length' : 8 + } + }, 'Additional params are filtered out.'); + + test.done(); + }, + + postData : function (test) { + 'use strict'; + + var geigerController = require(__dirname + '/../../../../devices/geiger/controller'), + geigerData = { username: 'bar', password: 'baz', maxCount: 5 }, + postData = geigerController.postData(geigerData); + + test.equal(postData, 'type=geiger&user=bar&pass=baz&count=5'); + + test.done(); + }, + + getReadings : function (test) { + 'use strict'; + + var geigerController = require(__dirname + '/../../../../devices/geiger/controller'), + geigerData = [ { + aid : "123456", + gid : "2", + cpm : "21.0123", + acpm : "20.1234", + usv : "0.075", + name : "Ghandi", + time : 1234567890 + }, + { + aid : "123457", + gid : "2", + cpm : "21.0126", + acpm : "20.1237", + usv : "0.077", + name : "Ghandi", + time : 1234569890 + } ], + testGeigerData = geigerController.getReadings(geigerData, 1), + testBadData = geigerController.getReadings({}, 10); + + test.equal(testGeigerData.report.length, 1, 'One reading should be found for data feeds'); + test.deepEqual(testBadData, { report : [] }, 'Nothing should be returned for bad data'); + + test.done(); + } +}; diff --git a/pool/shard000/JavaScript/0002764_wrap.js b/pool/shard000/JavaScript/0002764_wrap.js new file mode 100644 index 0000000000000000000000000000000000000000..9c82d4ed647220528db17938a36150ac9dbbedf0 --- /dev/null +++ b/pool/shard000/JavaScript/0002764_wrap.js @@ -0,0 +1,328 @@ +/* + * @Author: cungen + * @Date: 2017-09-25 15:32:29 + * @Last Modified by: cungen + * @Last Modified time: 2017-05-22 11:16:44 + * updating time 2017-9-25 +*/ + +'use strict'; +(function (global){ + +typeof defaults === 'undefined' ? false : defaults; + + +var defaults = { + g: global, + step: 0, + stamp: 0, + wrap: global.wrap || {} +}; + + +global.wrap = defaults.wrap; + + +// init wrap lib +defaults.wrap = function (){ + this.absoluteObject = []; + this.relativeObject = []; +} + + +// 一、AJAX封装 +// 1、封裝AJAX函數 +defaults.wrap.prototype.nativeAjax = function (success, error) { + + // 定义domain,方便环境切换 + var domain = 'https://' + global.location.host + '/'; + + var url = domain + this.relativeObject.URL; + var type = this.relativeObject.TYPE; + var data = this.relativeObject.data; + var xhrRequest = null; + var _this = this; + var str = ''; + + if (global.XMLHttpRequest) xhrRequest = new XMLHttpRequest(); + else xhrRequest = new ActiveXObject('Microsoft.XMLHTTP'); + + xhrRequest.open(type, url, true); + + if (type === "POST" && data != null) { + xhrRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); + for (var key in data) { + str += '&'+key+'='+data[key]; + str = str.slice(1); + } + } + + xhrRequest.onreadystatechange = function() { + + if (xhrRequest.readyState == 4) { + + if (xhrRequest.status == 200) { + + var obj = { + statu: xhrRequest.status, + textData: xhrRequest.responseText + } + + var responseData = _this.resolveData(obj); + + _this.validateSuccess(success,[responseData],true) + + } else error(xhrRequest.status); + + } + + } + + xhrRequest.send(str); + ++defaults.step +} + + +defaults.wrap.prototype.resolveData = function (options){ + var responseTextData = options.textData; + + (options.statu === 200) && !0; + + var text; + if(typeof responseTextData === 'string'){ + var _search = responseTextData.search(' '); + if(_search >= 0){ + text = this.trim(responseTextData) + } + else text = responseTextData; + } + + return this.compileParse(text); +} + + + +defaults.wrap.prototype.validateSuccess = function (isComplate,options,bool){ + var turn = [{ + bool: bool, + msg:'查询成功', + count: options.length, + result: options + }]; + + isComplate(turn) +} + + + +defaults.wrap.prototype.compileStringify = function (options){ + return typeof options === 'object' ? JSON.stringify(options) : false; +} + + +defaults.wrap.prototype.compileParse = function (options){ + return typeof options === 'string' ? JSON.parse(options) : false; +} + + +// call fallback method +defaults.wrap.prototype.resolveComplexFallback = function resolveComplexFallback(options){ + var bindCall = [options]; + var _this = this; + return { + custom : function (){ + var callAjaxMehtod = bindCall; + + for(;;){ + if( callAjaxMehtod instanceof Array ){ + callAjaxMehtod = callAjaxMehtod.pop(); + continue; + } + break; + } + + _this.absoluteObject = callAjaxMehtod; + + return this + }, + bind : function (){ + console.log([bindCall?bindCall:false]) + } + } +} + + +defaults.wrap.prototype.trim = function(options){ + return options.replace(/^\s+|\S|\n$/,''); +} + + +defaults.wrap.prototype.toUppCase = function(options){ + return options.toUpperCase(); +} + + +defaults.wrap.prototype.toLowCase = function(options){ + return options.toLowerCase(); +} + + +defaults.wrap.prototype.setType = function(options){ + this.relativeObject[this.toUppCase(options)] = this.toUppCase(this.absoluteObject[options]); +} + + +defaults.wrap.prototype.getType = function(options){ + // please return a debug log + var takeUpper = this.relativeObject[this.toUppCase(options)]; + if(takeUpper === 'GET' || takeUpper === 'POST') return takeUpper; + return false +} + + +defaults.wrap.prototype.setUrl = function(options){ + // please return a debug log + this.relativeObject[this.toUppCase(options)] = this.toLowCase(this.absoluteObject[options]); +} + + +defaults.wrap.prototype.getUrl = function(options){ + return this.relativeObject[this.toUppCase(options)]; +} + + +defaults.wrap.prototype.setData = function(options){ + // please return a debug log + if(options in this.absoluteObject) this.relativeObject[this.toUppCase(options)] = this.toLowCase(this.absoluteObject[options]); + else this.relativeObject[this.toUppCase(options)] = null; +} + + +defaults.wrap.prototype.getData = function(options){ + return this.relativeObject[this.toUppCase(options)]; +} + + +defaults.wrap.prototype.setSuccess = function(options){ + this.relativeObject[this.toUppCase(options)] = [this.absoluteObject[options]]; +} + + +defaults.wrap.prototype.getSuccess = function(options){ + return this.relativeObject[this.toUppCase(options)]; +} + + +defaults.wrap.prototype.setError = function(options){ + this.relativeObject[this.toUppCase(options)] = [this.absoluteObject[options]]; +} + + +defaults.wrap.prototype.getError = function(options){ + return this.relativeObject[this.toUppCase(options)]; +} + + +defaults.wrap.prototype.validateKeyForLowerCase = function (){ + var lower; + + for(var k in this.absoluteObject){ + lower = this.toLowCase(k); + + if(lower !== k){ + this.absoluteObject[lower] = this.absoluteObject[k]; + delete this.absoluteObject[k]; + } + + } + return 1 +} + + +// return procssing ajax +defaults.wrap.fn = function bindObjectGroup(opt,fallback){ + var bindCall = new defaults.wrap(true); + var empty = []; + + if(typeof opt === 'string'){ + + if(opt === 'ajax'){ + empty.length = 0; + defaults.wrap.chain; + defaults.wrap.module = opt; + } + else return false; + } + + + if(typeof fallback === 'function'){ + + if(empty.length) empty.length = 0; + else empty.push(fallback); + + defaults.wrap.chain = function (options){ + return [(new empty[0])] + } + + } + + + var resolveComplexFallback = bindCall.resolveComplexFallback(defaults.wrap.chain()); + var _customMethod = resolveComplexFallback.custom(); + + + + if(typeof _customMethod === 'object'){ + // return boolean true + var isTruth = bindCall.validateKeyForLowerCase(); + + bindCall.setType('type'); + bindCall.setUrl('url'); + bindCall.setData('data'); + bindCall.getType('type'); + bindCall.getUrl('url'); + bindCall.getData('data'); + bindCall.setSuccess('success'); + bindCall.setError('error'); + } + + var getSuccess = bindCall.getSuccess('success'); + var getError = bindCall.getError('error'); + + // dist property bound to this pointer + var print = bindCall.nativeAjax(getSuccess.pop(), getError.pop()); + + return print ? 'request json data success' : false +} + + +global.wrap['service'] = defaults.wrap.fn; + +})(this); + + + + + + + + +/* +合并其他分支上指定的文件或者文件夹到当前分支 + +git checkout branchName folderName +git checkout branchName path + +注:一下都是在主分支master上执行的命令 +1 把dev1 分支上app下所有的文件合并到主分支master上. +git checkout dev app + +2 部分更新,如单独合并app/css/index.css到master主分支上. +git checkout dev app/css/index.css + +3 部分文件夹dev分支上app的js文件夹下有多个JS文件都更新了. +git checkout dev app/js + +合并过来的文件或者文件夹在主分支master上都是默认add过的, +然后需要在master分支上commit,再push即可完成合并更新! +*/ \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002765_video-js.jquery.js b/pool/shard000/JavaScript/0002765_video-js.jquery.js new file mode 100644 index 0000000000000000000000000000000000000000..cb43320b6a68adcdff8d6a40975577074527ffd1 --- /dev/null +++ b/pool/shard000/JavaScript/0002765_video-js.jquery.js @@ -0,0 +1,24 @@ +/* jQuery Plugin +================================================================================ */ +if (window.jQuery) { + (function($) { + + $.fn.setupPlayer = function(options) { + return VideoJS.setup(this[0], options); + }; + + // Deprecated + $.fn.VideoJS = function(options) { + this.each(function() { + VideoJS.setup(this, options); + }); + return this; + }; + + $.fn.player = function() { + return this[0].player; + }; + + })(jQuery); +} + diff --git a/pool/shard000/JavaScript/0002766_index.js b/pool/shard000/JavaScript/0002766_index.js new file mode 100644 index 0000000000000000000000000000000000000000..3b60782bffa4c567568d4550ed1545f0b6635faa --- /dev/null +++ b/pool/shard000/JavaScript/0002766_index.js @@ -0,0 +1,38 @@ +import { select } from "d3-selection"; + +const svg = select("svg"); + +function render(data){ + const circles = svg.selectAll("circle").data(data); + circles.exit().remove(); + circles + .enter().append("circle") + .attr("fill", "rgba(255, 0, 0, 0.3)") + .attr("stroke", "black") + .merge(circles) + .attr("cx", d => d.x) + .attr("cy", d => d.y) + .attr("r", d => d.r); +} + +render([ + { x: 300, y:150, r: 44 }, + { x: 500, y:350, r: 51 }, + { x: 700, y:200, r: 33 }, + { x: 583, y:114, r: 77 }, + { x: 844, y:218, r: 74 }, + { x: 257, y:316, r: 44 }, + { x: 466, y:200, r: 31 }, + { x: 179, y:414, r: 50 }, + { x: 179, y:231, r: 36 }, + { x: 376, y:326, r: 26 }, + { x: 676, y:118, r: 68 }, + { x: 626, y:199, r: 68 }, + { x: 510, y:269, r: 15 }, + { x: 510, y:419, r: 15 }, + { x: 311, y:388, r: 15 }, + { x: 50, y:388, r: 6 }, + { x: 90, y:431, r: 6 }, + { x: 90, y:287, r: 11 }, + { x: 630, y:145, r: 11 } +]); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002768_prettify.js b/pool/shard000/JavaScript/0002768_prettify.js new file mode 100644 index 0000000000000000000000000000000000000000..50a3385ba800367b3383947851ee09d5181a73b1 --- /dev/null +++ b/pool/shard000/JavaScript/0002768_prettify.js @@ -0,0 +1,27 @@ +// +// Google Prettify +// A showdown extension to add Google Prettify (http://code.google.com/p/google-code-prettify/) +// hints to showdown's HTML output. +// + +(function(){ + + var prettify = function(converter) { + return [{ + type: 'output', + filter: function(source) { + return source + .replace(/

    /mig, function (match, pre) { + return '

    '; + }) + .replace(/<\/p>/mig, '
    '); + } + }]; + }; + + // Client-side export + if (typeof window !== 'undefined' && window.Showdown && window.Showdown.extensions) { window.Showdown.extensions.prettify = prettify; } + // Server-side export + if (typeof module !== 'undefined') module.exports = prettify; + +}()); diff --git a/pool/shard000/JavaScript/0002769_EventWithin.js b/pool/shard000/JavaScript/0002769_EventWithin.js new file mode 100644 index 0000000000000000000000000000000000000000..a09681c0445b94edb17e71a2a8dcd164010a80d1 --- /dev/null +++ b/pool/shard000/JavaScript/0002769_EventWithin.js @@ -0,0 +1,26 @@ +var _ = require("lodash"); + +var time_period_in_ms = { + second: 1000, + minute: 1000 * 60, + hour : 1000 * 60 * 60, + day : 1000 * 60 * 60 * 24, + week : 1000 * 60 * 60 * 24 * 7, + month : 1000 * 60 * 60 * 24 * 30, + year : 1000 * 60 * 60 * 24 * 365, +}; + +module.exports = function(ast, comp, e){ + var multiplier = 1; + if(_.has(time_period_in_ms, ast.time_period)){ + multiplier = time_period_in_ms[ast.time_period]; + }else{ + var key = ast.time_period.replace(/s$/i, ""); + if(_.has(time_period_in_ms, key)){ + multiplier = time_period_in_ms[key]; + } + } + return e("genfn", ["ctx"], [ + e("return", e("*", comp(ast.expression), e("num", multiplier))) + ]); +}; diff --git a/pool/shard000/JavaScript/0002770_raf-debounce.js b/pool/shard000/JavaScript/0002770_raf-debounce.js new file mode 100644 index 0000000000000000000000000000000000000000..59431b21b37f95592de732215b48187e464fd154 --- /dev/null +++ b/pool/shard000/JavaScript/0002770_raf-debounce.js @@ -0,0 +1,25 @@ +export function rafDebounce (fn) { + let args, context, requestID; + + function later () { + fn.apply(context, args); + args = context = requestID = null; + } + + function debounced () { + if (fn == null) { + throw new Error('raf debounced function is already disposed.'); + } + args = arguments; + context = this; + window.cancelAnimationFrame(requestID); + requestID = window.requestAnimationFrame(later); + } + + debounced.dispose = () => { + window.cancelAnimationFrame(requestID); + fn = args = context = requestID = null; + }; + + return debounced; +} diff --git a/pool/shard000/JavaScript/0002773_secureScriptTestController.js b/pool/shard000/JavaScript/0002773_secureScriptTestController.js new file mode 100644 index 0000000000000000000000000000000000000000..8562c9a4c61b85255af7123915c9bf61348aff29 --- /dev/null +++ b/pool/shard000/JavaScript/0002773_secureScriptTestController.js @@ -0,0 +1,30 @@ +({ + testScriptSrcExposed: function(cmp) { + var testUtils = cmp.get("v.testUtils"); + var script = document.createElement("script"); + + script.src = "foo.js"; + testUtils.assertEquals("foo.js", script.src, "Unexpected script source"); + testUtils.assertEquals("foo.js", script.getAttribute("src"), "Unexpected script source"); + + script.setAttribute("src", "foo2.js"); + testUtils.assertEquals("foo2.js", script.src, "Unexpected script source"); + testUtils.assertEquals("foo2.js", script.getAttribute("src"), "Unexpected script source"); + }, + + testGetSetAttribute: function(cmp, event, helper) { + var testUtils = cmp.get("v.testUtils"); + + var script = document.createElement("script"); + + testUtils.assertUndefined(script.getAttribute("data-foo"), "Unexpected unset attribute value"); + script.setAttribute("data-foo", "bar"); + testUtils.assertEquals("bar", script.getAttribute("data-foo"), "Unexpected attribute value"); + + script.setAttribute("data-foo", null); + testUtils.assertEquals(null, script.getAttribute("data-foo"), "Unexpected attribute value, should be null"); + + script.setAttribute("data-foo", undefined); + testUtils.assertUndefined(script.getAttribute("data-foo"), "Unexpected attribute value, should be undefined"); + } +}) \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002774_mongo-connection.js b/pool/shard000/JavaScript/0002774_mongo-connection.js new file mode 100644 index 0000000000000000000000000000000000000000..b811909357365fe91cd7874598074d41e7acd741 --- /dev/null +++ b/pool/shard000/JavaScript/0002774_mongo-connection.js @@ -0,0 +1,231 @@ +/** + * Interface for abstracting over a database connection + */ +var Connection = require('../connection'); +var mongoose = require('mongoose'); +var Promise = require('bluebird'); + +var Version = require('./mongo/version'); +var Application = require('./mongo/application'); + +function MongoConnection() { + this.connected = false; + this.client = null; +} + +MongoConnection.prototype = Object.create(Connection.prototype); + +MongoConnection.prototype.connect = function(env, callback) { + Connection.prototype.connect.apply(this, arguments); + var connectionString = + "mongodb://" + + this.env.get('stores:mongo:host') + + ':' + + this.env.get('stores:mongo:port') + + '/' + + this.env.get('stores:mongo:collection') + ; + + this.client = mongoose.connection; + this.client.on('error', function() { + if (typeof callback === 'function') { + callback({ + message: 'unable to connect to mongo', + store: 'mongo', + connectionString: connectionString + }, null); + } + }); + this.client.on('open', function() { + if (typeof callback === 'function') { + callback(null, { + store: 'mongo', + connectionString: connectionString + }); + } + }); + mongoose.connect(connectionString, { + user: this.env.get('stores:mongo:username'), + pass: this.env.get('stores:mongo:password') + }); + return this; +}; + +MongoConnection.prototype.disconnect = function(callback) { + Connection.prototype.disconnect.apply(this, arguments); + this.connected = false; + return this; +}; + +MongoConnection.prototype.getLatestContent = function(urlSlug, callback) { + var _findOneApplication = Promise.promisify(Application.findOne).bind(Application); + var _findOneVersion = Promise.promisify(Version.findOne).bind(Version); + _findOneApplication({urlSlug: urlSlug}, 'applicationId') + .then(function(data) { + if (!data) { + callback(null, null); + return; + } + return _findOneVersion({applicationId: data.applicationId, isLatest: true}, 'contents'); + }) + .then(function(data) { + callback(null, data.contents); + }) + .catch(function(err) { + callback(err); + }) + ; +}; + +MongoConnection.prototype.getLatestVersion = function(appId, callback) { + Version.findOne({ + applicationId: appId, + isLatest: true + }, callback); +}; + +MongoConnection.prototype.updateLatestContent = function(appId, versionId, callback) { + var _findOneAndUpdate = Promise.promisify(Version.findOneAndUpdate).bind(Version); + var _getLatestVersion = Promise.promisify(this.getLatestVersion).bind(this); + + // Order of operations, in sequence: + // - Get the previous `latest` version so we know which one it was + // - Set the desired one as the `latest` + // - Unset the previous `latest` version + // This way, we briefly have dual versions released, but there is never a + // moment when there is no `latest` version to serve. + + var previousLatestQuery = { + applicationId: appId + }; + + var hadPreviousLatest = false; + var versionAlreadyDeployed = false; + + var newLatestQuery = { + applicationId: appId, + versionId: versionId + }; + + var setLatest = { isLatest: true }; + var unsetLatest = { isLatest: false }; + + _getLatestVersion(appId) + .then(function(previousLatestData) { + if (previousLatestData) { + hadPreviousLatest = true; + previousLatestQuery.versionId = previousLatestData.versionId; + + // Version being deployed is already deployed! + if (previousLatestData.versionId === versionId) { + versionAlreadyDeployed = true; + return previousLatestData; + } + } + return _findOneAndUpdate(newLatestQuery, setLatest); + }) + .then(function(data) { + if (hadPreviousLatest && !versionAlreadyDeployed) { + return _findOneAndUpdate(previousLatestQuery, unsetLatest); + } else { + return data; + } + }) + .then(function(data) { + callback(null, data); + }) + .catch(function(err) { + callback(err); + }) + ; +}; + +MongoConnection.prototype.getContent = function(urlSlug, versionId, callback) { + var _findOneApplication = Promise.promisify(Application.findOne).bind(Application); + var _findOneVersion = Promise.promisify(Version.findOne).bind(Version); + _findOneApplication({urlSlug: urlSlug}, 'applicationId') + .then(function(data) { + if (!data) { + callback(null, null); + return; + } + return _findOneVersion({applicationId: data.applicationId, versionId: versionId}, 'contents'); + }) + .then(function(data) { + callback(null, data.contents); + }) + .catch(function(err) { + callback(err); + }) + ; +}; + +MongoConnection.prototype.getVersion = function(appId, versionId, callback) { + Version.findOne({ + applicationId: appId, + versionId: versionId + }, callback); +}; + +MongoConnection.prototype.getVersions = function(appId, limit, offset, callback) { + if (offset == null) { + offset = 0; + } + + if (limit <= 0) { + limit = 20; + } + + Version + .find({ + applicationId: appId + }) + .limit(limit) + .skip(offset) + .exec(callback) + ; +}; + +MongoConnection.prototype.updateVersion = function(appId, versionId, params, callback) { + Version.findOneAndUpdate({ + applicationId: appId, + versionId: versionId + }, + params, { + upsert: true + }, callback); +}; + +MongoConnection.prototype.getApplications = function(limit, offset, callback) { + if (offset == null) { + offset = 0; + } + + if (limit <= 0) { + limit = 20; + } + + Application + .find({}) + .limit(limit) + .skip(offset) + .exec(callback) + ; +}; + +MongoConnection.prototype.getApplication = function(appId, callback) { + Application.findOne({ + applicationId: appId + }, callback); +}; + +MongoConnection.prototype.updateApplication = function(appId, params, callback) { + Application.findOneAndUpdate({ + applicationId: appId + }, + params, { + upsert: true + }, callback); +}; + +module.exports = MongoConnection; diff --git a/pool/shard000/JavaScript/0002776_local.js b/pool/shard000/JavaScript/0002776_local.js new file mode 100644 index 0000000000000000000000000000000000000000..3e69f36084e56305917f8206ccdecfd843ae32d7 --- /dev/null +++ b/pool/shard000/JavaScript/0002776_local.js @@ -0,0 +1,436 @@ +'use strict'; + +var Q = require('q'); /* jshint ignore:line */ +var _ = require('lodash'); /* jshint ignore:line */ +var Page = require('../../../../../base/Page'); /* jshint ignore:line */ +var deserialize = require( + '../../../../../base/deserialize'); /* jshint ignore:line */ +var values = require('../../../../../base/values'); /* jshint ignore:line */ + +var LocalList; +var LocalPage; +var LocalInstance; + +/* jshint ignore:start */ +/** + * @constructor Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalList + * @description Initialize the LocalList + * + * @param {Twilio.Api.V2010} version - Version of the resource + * @param {string} accountSid - + * The 34 character string that uniquely identifies your account. + * @param {string} countryCode - The ISO Country code to lookup phone numbers for. + */ +/* jshint ignore:end */ +LocalList = function LocalList(version, accountSid, countryCode) { + /* jshint ignore:start */ + /** + * @function local + * @memberof Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext + * @instance + * + * @param {string} sid - sid of instance + * + * @returns {Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalContext} + */ + /* jshint ignore:end */ + function LocalListInstance(sid) { + return LocalListInstance.get(sid); + } + + LocalListInstance._version = version; + // Path Solution + LocalListInstance._solution = { + accountSid: accountSid, + countryCode: countryCode + }; + LocalListInstance._uri = _.template( + '/Accounts/<%= accountSid %>/AvailablePhoneNumbers/<%= countryCode %>/Local.json' // jshint ignore:line + )(LocalListInstance._solution); + /* jshint ignore:start */ + /** + * Streams LocalInstance records from the API. + * + * This operation lazily loads records as efficiently as possible until the limit + * is reached. + * + * The results are passed into the callback function, so this operation is memory efficient. + * + * If a function is passed as the first argument, it will be used as the callback function. + * + * @function each + * @memberof Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalList + * @instance + * + * @param {object|function} opts - ... + * @param {number} [opts.areaCode] - The area_code + * @param {string} [opts.contains] - The contains + * @param {string} [opts.smsEnabled] - The sms_enabled + * @param {string} [opts.mmsEnabled] - The mms_enabled + * @param {string} [opts.voiceEnabled] - The voice_enabled + * @param {string} [opts.excludeAllAddressRequired] - + * The exclude_all_address_required + * @param {string} [opts.excludeLocalAddressRequired] - + * The exclude_local_address_required + * @param {string} [opts.excludeForeignAddressRequired] - + * The exclude_foreign_address_required + * @param {string} [opts.beta] - The beta + * @param {string} [opts.nearNumber] - The near_number + * @param {string} [opts.nearLatLong] - The near_lat_long + * @param {number} [opts.distance] - The distance + * @param {string} [opts.inPostalCode] - The in_postal_code + * @param {string} [opts.inRegion] - The in_region + * @param {string} [opts.inRateCenter] - The in_rate_center + * @param {string} [opts.inLata] - The in_lata + * @param {number} [opts.limit] - + * Upper limit for the number of records to return. + * each() guarantees never to return more than limit. + * Default is no limit + * @param {number} [opts.pageSize=50] - + * Number of records to fetch per request, + * when not set will use the default value of 50 records. + * If no pageSize is defined but a limit is defined, + * each() will attempt to read the limit with the most efficient + * page size, i.e. min(limit, 1000) + * @param {Function} [opts.callback] - + * Function to process each record. If this and a positional + * callback are passed, this one will be used + * @param {Function} [opts.done] - + * Function to be called upon completion of streaming + * @param {Function} [callback] - Function to process each record + */ + /* jshint ignore:end */ + LocalListInstance.each = function each(opts, callback) { + opts = opts || {}; + if (_.isFunction(opts)) { + opts = { callback: opts }; + } else if (_.isFunction(callback) && !_.isFunction(opts.callback)) { + opts.callback = callback; + } + + if (_.isUndefined(opts.callback)) { + throw new Error('Callback function must be provided'); + } + + var done = false; + var currentPage = 1; + var currentResource = 0; + var limits = this._version.readLimits({ + limit: opts.limit, + pageSize: opts.pageSize + }); + + function onComplete(error) { + done = true; + if (_.isFunction(opts.done)) { + opts.done(error); + } + } + + function fetchNextPage(fn) { + var promise = fn(); + if (_.isUndefined(promise)) { + onComplete(); + return; + } + + promise.then(function(page) { + _.each(page.instances, function(instance) { + if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) { + done = true; + return false; + } + + currentResource++; + opts.callback(instance, onComplete); + }); + + if ((limits.pageLimit && limits.pageLimit <= currentPage)) { + onComplete(); + } else if (!done) { + currentPage++; + fetchNextPage(_.bind(page.nextPage, page)); + } + }); + + promise.catch(onComplete); + } + + fetchNextPage(_.bind(this.page, this, _.merge(opts, limits))); + }; + + /* jshint ignore:start */ + /** + * @description Lists LocalInstance records from the API as a list. + * + * If a function is passed as the first argument, it will be used as the callback function. + * + * @function list + * @memberof Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalList + * @instance + * + * @param {object|function} opts - ... + * @param {number} [opts.areaCode] - The area_code + * @param {string} [opts.contains] - The contains + * @param {string} [opts.smsEnabled] - The sms_enabled + * @param {string} [opts.mmsEnabled] - The mms_enabled + * @param {string} [opts.voiceEnabled] - The voice_enabled + * @param {string} [opts.excludeAllAddressRequired] - + * The exclude_all_address_required + * @param {string} [opts.excludeLocalAddressRequired] - + * The exclude_local_address_required + * @param {string} [opts.excludeForeignAddressRequired] - + * The exclude_foreign_address_required + * @param {string} [opts.beta] - The beta + * @param {string} [opts.nearNumber] - The near_number + * @param {string} [opts.nearLatLong] - The near_lat_long + * @param {number} [opts.distance] - The distance + * @param {string} [opts.inPostalCode] - The in_postal_code + * @param {string} [opts.inRegion] - The in_region + * @param {string} [opts.inRateCenter] - The in_rate_center + * @param {string} [opts.inLata] - The in_lata + * @param {number} [opts.limit] - + * Upper limit for the number of records to return. + * list() guarantees never to return more than limit. + * Default is no limit + * @param {number} [opts.pageSize] - + * Number of records to fetch per request, + * when not set will use the default value of 50 records. + * If no page_size is defined but a limit is defined, + * list() will attempt to read the limit with the most + * efficient page size, i.e. min(limit, 1000) + * @param {function} [callback] - Callback to handle list of records + * + * @returns {Promise} Resolves to a list of records + */ + /* jshint ignore:end */ + LocalListInstance.list = function list(opts, callback) { + if (_.isFunction(opts)) { + callback = opts; + opts = {}; + } + opts = opts || {}; + var deferred = Q.defer(); + var allResources = []; + opts.callback = function(resource, done) { + allResources.push(resource); + + if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) { + done(); + } + }; + + opts.done = function(error) { + if (_.isUndefined(error)) { + deferred.resolve(allResources); + } else { + deferred.reject(error); + } + }; + + if (_.isFunction(callback)) { + deferred.promise.nodeify(callback); + } + + this.each(opts); + return deferred.promise; + }; + + /* jshint ignore:start */ + /** + * Retrieve a single page of LocalInstance records from the API. + * Request is executed immediately + * + * If a function is passed as the first argument, it will be used as the callback function. + * + * @function page + * @memberof Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalList + * @instance + * + * @param {object|function} opts - ... + * @param {number} [opts.areaCode] - The area_code + * @param {string} [opts.contains] - The contains + * @param {string} [opts.smsEnabled] - The sms_enabled + * @param {string} [opts.mmsEnabled] - The mms_enabled + * @param {string} [opts.voiceEnabled] - The voice_enabled + * @param {string} [opts.excludeAllAddressRequired] - + * The exclude_all_address_required + * @param {string} [opts.excludeLocalAddressRequired] - + * The exclude_local_address_required + * @param {string} [opts.excludeForeignAddressRequired] - + * The exclude_foreign_address_required + * @param {string} [opts.beta] - The beta + * @param {string} [opts.nearNumber] - The near_number + * @param {string} [opts.nearLatLong] - The near_lat_long + * @param {number} [opts.distance] - The distance + * @param {string} [opts.inPostalCode] - The in_postal_code + * @param {string} [opts.inRegion] - The in_region + * @param {string} [opts.inRateCenter] - The in_rate_center + * @param {string} [opts.inLata] - The in_lata + * @param {string} [opts.pageToken] - PageToken provided by the API + * @param {number} [opts.pageNumber] - + * Page Number, this value is simply for client state + * @param {number} [opts.pageSize] - Number of records to return, defaults to 50 + * @param {function} [callback] - Callback to handle list of records + * + * @returns {Promise} Resolves to a list of records + */ + /* jshint ignore:end */ + LocalListInstance.page = function page(opts, callback) { + if (_.isFunction(opts)) { + callback = opts; + opts = {}; + } + opts = opts || {}; + + var deferred = Q.defer(); + var data = values.of({ + 'AreaCode': _.get(opts, 'areaCode'), + 'Contains': _.get(opts, 'contains'), + 'SmsEnabled': _.get(opts, 'smsEnabled'), + 'MmsEnabled': _.get(opts, 'mmsEnabled'), + 'VoiceEnabled': _.get(opts, 'voiceEnabled'), + 'ExcludeAllAddressRequired': _.get(opts, 'excludeAllAddressRequired'), + 'ExcludeLocalAddressRequired': _.get(opts, 'excludeLocalAddressRequired'), + 'ExcludeForeignAddressRequired': _.get(opts, 'excludeForeignAddressRequired'), + 'Beta': _.get(opts, 'beta'), + 'NearNumber': _.get(opts, 'nearNumber'), + 'NearLatLong': _.get(opts, 'nearLatLong'), + 'Distance': _.get(opts, 'distance'), + 'InPostalCode': _.get(opts, 'inPostalCode'), + 'InRegion': _.get(opts, 'inRegion'), + 'InRateCenter': _.get(opts, 'inRateCenter'), + 'InLata': _.get(opts, 'inLata'), + 'PageToken': opts.pageToken, + 'Page': opts.pageNumber, + 'PageSize': opts.pageSize + }); + + var promise = this._version.page({ + uri: this._uri, + method: 'GET', + params: data + }); + + promise = promise.then(function(payload) { + deferred.resolve(new LocalPage( + this._version, + payload, + this._solution + )); + }.bind(this)); + + promise.catch(function(error) { + deferred.reject(error); + }); + + if (_.isFunction(callback)) { + deferred.promise.nodeify(callback); + } + + return deferred.promise; + }; + + return LocalListInstance; +}; + + +/* jshint ignore:start */ +/** + * @constructor Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalPage + * @augments Page + * @description Initialize the LocalPage + * + * @param {Twilio.Api.V2010} version - Version of the resource + * @param {object} response - Response from the API + * @param {object} solution - Path solution + * + * @returns LocalPage + */ +/* jshint ignore:end */ +LocalPage = function LocalPage(version, response, solution) { + // Path Solution + this._solution = solution; + + Page.prototype.constructor.call(this, version, response, this._solution); +}; + +_.extend(LocalPage.prototype, Page.prototype); +LocalPage.prototype.constructor = LocalPage; + +/* jshint ignore:start */ +/** + * Build an instance of LocalInstance + * + * @function getInstance + * @memberof Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalPage + * @instance + * + * @param {object} payload - Payload response from the API + * + * @returns LocalInstance + */ +/* jshint ignore:end */ +LocalPage.prototype.getInstance = function getInstance(payload) { + return new LocalInstance( + this._version, + payload, + this._solution.accountSid, + this._solution.countryCode + ); +}; + + +/* jshint ignore:start */ +/** + * @constructor Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryContext.LocalInstance + * @description Initialize the LocalContext + * + * @property {string} friendlyName - The friendly_name + * @property {string} phoneNumber - The phone_number + * @property {string} lata - The lata + * @property {string} rateCenter - The rate_center + * @property {number} latitude - The latitude + * @property {number} longitude - The longitude + * @property {string} region - The region + * @property {string} postalCode - The postal_code + * @property {string} isoCountry - The iso_country + * @property {string} addressRequirements - The address_requirements + * @property {string} beta - The beta + * @property {string} capabilities - The capabilities + * + * @param {Twilio.Api.V2010} version - Version of the resource + * @param {object} payload - The instance payload + */ +/* jshint ignore:end */ +LocalInstance = function LocalInstance(version, payload, accountSid, + countryCode) { + this._version = version; + + // Marshaled Properties + this.friendlyName = payload.friendly_name; // jshint ignore:line + this.phoneNumber = payload.phone_number; // jshint ignore:line + this.lata = payload.lata; // jshint ignore:line + this.rateCenter = payload.rate_center; // jshint ignore:line + this.latitude = deserialize.decimal(payload.latitude); // jshint ignore:line + this.longitude = deserialize.decimal(payload.longitude); // jshint ignore:line + this.region = payload.region; // jshint ignore:line + this.postalCode = payload.postal_code; // jshint ignore:line + this.isoCountry = payload.iso_country; // jshint ignore:line + this.addressRequirements = payload.address_requirements; // jshint ignore:line + this.beta = payload.beta; // jshint ignore:line + this.capabilities = payload.capabilities; // jshint ignore:line + + // Context + this._context = undefined; + this._solution = { + accountSid: accountSid, + countryCode: countryCode, + }; +}; + +module.exports = { + LocalList: LocalList, + LocalPage: LocalPage, + LocalInstance: LocalInstance +}; diff --git a/pool/shard000/JavaScript/0002779_transactions.js b/pool/shard000/JavaScript/0002779_transactions.js new file mode 100644 index 0000000000000000000000000000000000000000..29996d7f6732cc5c96bef2325f1b929850ef7783 --- /dev/null +++ b/pool/shard000/JavaScript/0002779_transactions.js @@ -0,0 +1,28 @@ +import * as types from '../constants/ActionTypes'; +import checkStatus from '../utils/checkStatus'; + +export function fetchTransactions(accessToken, accountId) { + return dispatch => { + fetch(`https://api.getmondo.co.uk/transactions?expand[]=merchant&account_id=${accountId}`, { + headers: { 'Authorization': `Bearer ${accessToken}` } + }) + .then(checkStatus) + .then(response => response.json()) + .then(json => { + const transactions = json.transactions + .map(transaction => { + transaction.created = new Date(transaction.created); + transaction.updated = new Date(transaction.updated); + if (transaction.settled) { + transaction.settled = new Date(transaction.settled); + } + return transaction; + }); + dispatch(receiveTransactions(transactions)); + }); + }; +} + +function receiveTransactions(transactions) { + return { type: types.RECEIVE_TRANSACTIONS, transactions }; +} diff --git a/pool/shard000/JavaScript/0002783_treeDataCreator.js b/pool/shard000/JavaScript/0002783_treeDataCreator.js new file mode 100644 index 0000000000000000000000000000000000000000..17246a405776453dcf5c95fd7167e5022d999c86 --- /dev/null +++ b/pool/shard000/JavaScript/0002783_treeDataCreator.js @@ -0,0 +1,94 @@ +/* scenarioo-client + * Copyright (C) 2014, scenarioo.org Development Team + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * Transforms any nested object and array structure into a tree structure that can be used by our tree directive. + */ +angular.module('scenarioo.filters').filter('scTreeDataCreator', function () { + + function createTreeData(data) { + if (angular.isUndefined(data)) { + return undefined; + } + + if (angular.isString(data)) { + return {nodeLabel: data}; + } + + return transformNode(data, ''); + } + + function transformNode(node, nodeTitle) { + var transformedNode = { + nodeLabel: nodeTitle + }; + + if (angular.isArray(node)) { + transformedNode.childNodes = createArrayChildNodes(node); + } else if (angular.isObject(node)) { + transformedNode.childNodes = createObjectChildNodes(node); + } else if (angular.isString(node)) { + transformedNode = node; + } + + return transformedNode; + } + + function createObjectChildNodes(node) { + var childNodes = []; + angular.forEach(node, function (value, key) { + if (angular.isArray(value)) { + childNodes.push({ + nodeLabel: key, + childNodes: createArrayChildNodes(value) + }); + } else if (angular.isObject(value)) { + childNodes.push({ + nodeLabel: key, + childNodes: createObjectChildNodes(value) + }); + } else { + childNodes.push({ + nodeLabel: key, + nodeValue: value + }); + } + }); + + return childNodes; + } + + function createArrayChildNodes(array) { + var childNodes = []; + angular.forEach(array, function (element) { + if (angular.isString(element)) { + childNodes.push({ + nodeLabel: element + }); + } else { + childNodes.push({ + nodeLabel: '', + childNodes: createObjectChildNodes(element) + }); + } + }); + + return childNodes; + } + + return createTreeData; +}); diff --git a/pool/shard000/JavaScript/0002784_runtimeshow.js b/pool/shard000/JavaScript/0002784_runtimeshow.js new file mode 100644 index 0000000000000000000000000000000000000000..4a41983f3f30cbc04d3eff086ca896db3c90c62b --- /dev/null +++ b/pool/shard000/JavaScript/0002784_runtimeshow.js @@ -0,0 +1,16 @@ +// get user config +var start_date = document.getElementById("runtionshow").getAttribute("start_date") + +function show_date_time() { + window.setTimeout("show_date_time()", 1000); + BirthDay=new Date(start_date); + today=new Date(); + timeold=(today.getTime()-BirthDay.getTime()); + msPerDay=24*60*60*1000 + e_daysold=timeold/msPerDay + daysold=Math.floor(e_daysold); + webinfo_runtime_count.innerHTML= daysold + " " + GLOBAL_CONFIG.runtime_unit +} + +show_date_time() + diff --git a/pool/shard000/JavaScript/0002787_fs_test.js b/pool/shard000/JavaScript/0002787_fs_test.js new file mode 100644 index 0000000000000000000000000000000000000000..ef496f01a3fbf00b10c7d51f0bbc4c0e03ea3d0d --- /dev/null +++ b/pool/shard000/JavaScript/0002787_fs_test.js @@ -0,0 +1,55 @@ +// Copyright 2011 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +goog.provide('goog.testing.fsTest'); +goog.setTestOnly('goog.testing.fsTest'); + +goog.require('goog.testing.AsyncTestCase'); +goog.require('goog.testing.fs'); +goog.require('goog.testing.fs.Blob'); +goog.require('goog.testing.jsunit'); + +var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall(); + +function testObjectUrls() { + var blob = goog.testing.fs.getBlob('foo'); + var url = goog.testing.fs.createObjectUrl(blob); + assertTrue(goog.testing.fs.isObjectUrlGranted(blob)); + goog.testing.fs.revokeObjectUrl(url); + assertFalse(goog.testing.fs.isObjectUrlGranted(blob)); +} + +function testGetBlob() { + assertEquals( + new goog.testing.fs.Blob('foobarbaz').toString(), + goog.testing.fs.getBlob('foo', 'bar', 'baz').toString()); + assertEquals( + new goog.testing.fs.Blob('foobarbaz').toString(), + goog.testing.fs.getBlob('foo', new goog.testing.fs.Blob('bar'), 'baz'). + toString()); +} + +function testBlobToString() { + goog.testing.fs.blobToString(new goog.testing.fs.Blob('foobarbaz')). + addCallback(goog.partial(assertEquals, 'foobarbaz')). + addCallback(goog.bind(asyncTestCase.continueTesting, asyncTestCase)); + asyncTestCase.waitForAsync('testBlobToString'); +} + +function testGetBlobWithProperties() { + assertEquals( + 'data:spam/eggs;base64,Zm9vYmFy', + new goog.testing.fs.getBlobWithProperties( + ['foo', new goog.testing.fs.Blob('bar')], 'spam/eggs').toDataUrl()); +} diff --git a/pool/shard000/JavaScript/0002798_OverlayContainerRenderer-dbg.js b/pool/shard000/JavaScript/0002798_OverlayContainerRenderer-dbg.js new file mode 100644 index 0000000000000000000000000000000000000000..3788d0f43359119ce8cbdfbec7061066e578c4fc --- /dev/null +++ b/pool/shard000/JavaScript/0002798_OverlayContainerRenderer-dbg.js @@ -0,0 +1,72 @@ +/*! + * UI development toolkit for HTML5 (OpenUI5) + * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. + * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. + */ + +// Provides default renderer for the sap.ui.ux3.OverlayContainer +sap.ui.define(['jquery.sap.global', 'sap/ui/core/Renderer', './OverlayRenderer'], + function(jQuery, Renderer, OverlayRenderer) { + "use strict"; + +/** + * OverlayContainer renderer. + * @namespace + */ + var OverlayContainerRenderer = Renderer.extend(OverlayRenderer); + + /** + * Renders the Overlay content + * + * @param {sap.ui.core.RenderManager} + * oRenderManager the RenderManager that can be used for writing to + * the Render-Output-Buffer + * @param {sap.ui.core.Control} + * oControl an object representation of the control that should be + * rendered + */ + OverlayContainerRenderer.renderContent = function(oRenderManager, oControl) { + var rm = oRenderManager; + rm.write("
    "); + var content = oControl.getContent(); + for (var i = 0; i < content.length; i++) { + var control = content[i]; + rm.renderControl(control); + } + rm.write("
    "); + }; + + /** + * Add root class to Overlay + * + * @param {sap.ui.core.RenderManager} + * oRenderManager the RenderManager that can be used for writing to + * the Render-Output-Buffer + * @param {sap.ui.core.Control} + * oControl an object representation of the control that should be + * rendered + */ + OverlayContainerRenderer.addRootClasses = function(oRenderManager, oControl) { + var rm = oRenderManager; + rm.addClass("sapUiUx3OC"); + }; + + /** + * Add class to Overlay + * + * @param {sap.ui.core.RenderManager} + * oRenderManager the RenderManager that can be used for writing to + * the Render-Output-Buffer + * @param {sap.ui.core.Control} + * oControl an object representation of the control that should be + * rendered + */ + OverlayContainerRenderer.addOverlayClasses = function(oRenderManager, oControl) { + var rm = oRenderManager; + rm.addClass("sapUiUx3OCOverlay"); + }; + + + return OverlayContainerRenderer; + +}, /* bExport= */ true); diff --git a/pool/shard000/JavaScript/0002803_index.js b/pool/shard000/JavaScript/0002803_index.js new file mode 100644 index 0000000000000000000000000000000000000000..de9d51dfa261dd1a57da7cbf55b092fdd63855a4 --- /dev/null +++ b/pool/shard000/JavaScript/0002803_index.js @@ -0,0 +1,101 @@ +"use strict"; +var fs = require("fs"); +var insert = require("insert-css"); + +var Ractive = require("ractive"); + +var getSize = require("bounding-client-rect"); +var getScrollbarWidth = require("scrollbar-width"); +var hasScrollbar = require("has-scrollbar"); +var debounce = require("debounce"); + +var template = fs.readFileSync(__dirname + "/template.html", "utf8"); +var style = fs.readFileSync(__dirname + "/style.css", "utf8"); + +insert(style); + +module.exports = Ractive.extend({ + isolated: false, + template: template, + data: { + gridClass: "", + gridItems: [], + gridRows: 1, + gridColumns: 1, + + gridSize: "0px", + gridMarginX: "0px", + gridMarginY: "0px", + }, + oncomplete: oncomplete, + + recalculate: recalculate, +}); + +function recalculate() { + // Get raw information about the state + var container = this.find(".rm-grid-container"); + var size = getSize(container); + var gridRows = this.get("gridRows"); + var gridColumns = this.get("gridColumns"); + var isScrolling = gridRows === "scroll"; + + // Get certain dimensions + var containerWidth = size.width; + var containerHeight = size.height; + var itemWidth = containerWidth / +(gridColumns); + var itemHeight = containerHeight / +(gridRows); + + if (isScrolling) { + // Calculate for vertical scrolling + var gridSize = itemWidth; + if (hasScrollbar(container)) + gridSize = itemWidth - (getScrollbarWidth() / gridColumns); + + this.set({ + gridSize: gridSize + "px", + gridMarginX: "0px", + gridMarginY: "0px" + }); + } else { + // Calculate for fitting perfectly + var padding = "0px"; + if (gridRows === "scroll") {} else if (itemWidth > itemHeight) { + // Will pad on the sides + padding = (itemWidth - itemHeight) / 2; + this.set({ + gridSize: itemHeight + "px", + gridMarginY: "0px", + gridMarginX: padding + "px" + }); + } else { + // Will pad on top/bottom + padding = (itemHeight - itemWidth) / 2; + this.set({ + gridSize: itemWidth + "px", + gridMarginY: padding + "px", + gridMarginX: "0px" + }); + } + } +} + +function oncomplete() { + listenResize(this); + this.on("teardown", unlistenResize.bind(null, this)); + + this.recalculate(); +} + +function unlistenResize(component) { + window.removeEventListener("resize", component._recalculate); +} + +function listenResize(component) { + var listener = component._recalculate = debounce(recalculate.bind(component), 50); + window.addEventListener("resize", listener); + component.observe("gridRows", listener); + component.observe("gridColumns", listener); + component.observe("gridClass", listener); + component.observe("gridItems", listener); +} diff --git a/pool/shard000/JavaScript/0002806_cv-controller.js b/pool/shard000/JavaScript/0002806_cv-controller.js new file mode 100644 index 0000000000000000000000000000000000000000..91f37c6f8956f13d6e63c09e1a917a58ca1db92f --- /dev/null +++ b/pool/shard000/JavaScript/0002806_cv-controller.js @@ -0,0 +1,25 @@ +angular.module('bitvagas.users.controllers') +.controller('FreelancerController', FreelancerController) +.controller('CVController', CVController); + +FreelancerController.$inject = ['$scope', 'FreelancerService']; +CVController.$inject = ['$scope', '$state', '$stateParams', 'FreelancerService']; +function CVController($scope, $state, $stateParams, FreelancerService){ + + var id = $stateParams.id || $scope.currentUser.id; + FreelancerService.findById(id).then(function(user){ + $scope.user = user.data; + var linkedIn = user.data.LINKEDIN_TOKEN; + if(linkedIn) { + FreelancerService.getCV({ token : linkedIn}).then(function(data){ + $scope.user.cv = data.data; + }); + } + }); +} + +function FreelancerController ($scope, FreelancerService) { + FreelancerService.findAll().then(function(data){ + $scope.freelancers = data.data; + }); +} diff --git a/pool/shard000/JavaScript/0002811_friendlyDates.js b/pool/shard000/JavaScript/0002811_friendlyDates.js new file mode 100644 index 0000000000000000000000000000000000000000..7d5ca24d39414dff47063483a7f76227916db1be --- /dev/null +++ b/pool/shard000/JavaScript/0002811_friendlyDates.js @@ -0,0 +1,87 @@ +function makeFriendlyDates(arr) { + const months = [ + 'January', + 'February', + 'March', + 'April', + 'May', + 'June', + 'July', + 'August', + 'September', + 'October', + 'November', + 'December' + ]; + + let date1 = arr[0].split('-'), + date2 = arr[1].split('-'), + year1 = parseInt(date1[0]), + year2 = parseInt(date2[0]), + month1 = parseInt(date1[1]), + month2 = parseInt(date2[1]), + day1 = parseInt(date1[2]), + day2 = parseInt(date2[2]), + curYear = 2016; + + // eliminate redundancy + if(JSON.stringify(date1) === JSON.stringify(date2)) { + return [buildString(date1)]; + } else if(year1 === curYear && year2 === curYear) { + if(month1 === month2) { + return [buildString(date1, true, false), buildString(date2, false, false)]; + } + return [buildString(date1, true, false), buildString(date2, true, false)]; + } else if (year2 - year1 < 1) { + if(month1 === month2) { + return [buildString(date1, true, false), buildString(date2, false, false)]; + } + return [buildString(date1), buildString(date2, true, false)]; + } else { + if(year1 === curYear && year2 === curYear + 1) { + if(month2 < month1) { + return [buildString(date1, true, false), buildString(date2, true, false)]; + } + } + if(year2 - year1 === 1) { + if(month1 === month2 && day2 < day1) { + return [buildString(date1), buildString(date2, true, false)]; + } + } + } + + // default + return [buildString(date1), buildString(date2)]; + + function buildString(date, showMonth = true, showYear = true) { + let year = date[0], + month = months[parseInt(date[1]) - 1], + day = parseInt(date[2]), + ending = '', + lastDigit = parseInt(date[2][date[2].length - 1]); + + switch(lastDigit) { //generate appropriate date ending + case 1: + ending += 'st'; + break; + case 2: + if(day === 12) ending += 'th'; + else ending += 'nd'; + break; + case 3: + if(day === 13) ending += 'th'; + else ending += 'rd'; + break; + default: + ending += 'th'; + } + + if (!showMonth) { + return `${day}${ending}`; + } else if (!showYear) { + return `${month} ${day}${ending}`; + } else { + return `${month} ${day}${ending}, ${year}`; + } + } +} diff --git a/pool/shard000/JavaScript/0002813_hashchange.js b/pool/shard000/JavaScript/0002813_hashchange.js new file mode 100644 index 0000000000000000000000000000000000000000..d3ed1adfe3faba4524d17ffcff62d24648f99a42 --- /dev/null +++ b/pool/shard000/JavaScript/0002813_hashchange.js @@ -0,0 +1,247 @@ +/*! + * jQuery hashchange event - v1.2 - 2/11/2010 + * http://benalman.com/projects/jquery-hashchange-plugin/ + * + * Copyright (c) 2010 "Cowboy" Ben Alman + * Dual licensed under the MIT and GPL licenses. + * http://benalman.com/about/license/ + */ + +// Script: jQuery hashchange event +// +// *Version: 1.2, Last updated: 2/11/2010* +// +// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ +// GitHub - http://github.com/cowboy/jquery-hashchange/ +// Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js +// (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (1.1kb) +// +// About: License +// +// Copyright (c) 2010 "Cowboy" Ben Alman, +// Dual licensed under the MIT and GPL licenses. +// http://benalman.com/about/license/ +// +// About: Examples +// +// This working example, complete with fully commented code, illustrate one way +// in which this plugin can be used. +// +// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ +// +// About: Support and Testing +// +// Information about what version or versions of jQuery this plugin has been +// tested with, what browsers it has been tested in, and where the unit tests +// reside (so you can test it yourself). +// +// jQuery Versions - 1.3.2, 1.4.1, 1.4.2pre +// Browsers Tested - Internet Explorer 6-8, Firefox 2-3.7, Safari 3-4, Chrome, Opera 9.6-10.1. +// Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ +// +// About: Known issues +// +// While this jQuery hashchange event implementation is quite stable and robust, +// there are a few unfortunate browser bugs surrounding expected hashchange +// event-based behaviors, independent of any JavaScript window.onhashchange +// abstraction. See the following examples for more information: +// +// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ +// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ +// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ +// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ +// +// About: Release History +// +// 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin +// from a page on another domain would cause an error in Safari 4. Also, +// IE6/7 Iframe is now inserted after the body (this actually works), +// which prevents the page from scrolling when the event is first bound. +// Event can also now be bound before DOM ready, but it won't be usable +// before then in IE6/7. +// 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug +// where browser version is incorrectly reported as 8.0, despite +// inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. +// 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special +// window.onhashchange functionality into a separate plugin for users +// who want just the basic event & back button support, without all the +// extra awesomeness that BBQ provides. This plugin will be included as +// part of jQuery BBQ, but also be available separately. + +(function($,window,undefined){ + '$:nomunge'; // Used by YUI compressor. + + + +var is_old_ie = (function(){ + if(!jQuery.support.leadingWhitespace){ + oldIE = true; + } + })(); + + // Method / object references. + var fake_onhashchange, + jq_event_special = $.event.special, + + // Reused strings. + str_location = 'location', + str_hashchange = 'hashchange', + str_href = 'href', + + + // Does the browser support window.onhashchange? Test for IE version, since + // IE8 incorrectly reports this when in "IE7" or "IE8 Compatibility View"! + supports_onhashchange = 'on' + str_hashchange in window && !is_old_ie; + + // Get location.hash (or what you'd expect location.hash to be) sans any + // leading #. Thanks for making this necessary, Firefox! + function get_fragment( url ) { + url = url || window[ str_location ][ str_href ]; + return url.replace( /^[^#]*#?(.*)$/, '$1' ); + }; + + // Property: jQuery.hashchangeDelay + // + // The numeric interval (in milliseconds) at which the + // polling loop executes. Defaults to 100. + + $[ str_hashchange + 'Delay' ] = 100; + + // Event: hashchange event + // + // Fired when location.hash changes. In browsers that support it, the native + // window.onhashchange event is used (IE8, FF3.6), otherwise a polling loop is + // initialized, running every milliseconds to see if + // the hash has changed. In IE 6 and 7, a hidden Iframe is created to allow + // the back button and hash-based history to work. + // + // Usage: + // + // > $(window).bind( 'hashchange', function(e) { + // > var hash = location.hash; + // > ... + // > }); + // + // Additional Notes: + // + // * The polling loop and Iframe are not created until at least one callback + // is actually bound to 'hashchange'. + // * If you need the bound callback(s) to execute immediately, in cases where + // the page 'state' exists on page load (via bookmark or page refresh, for + // example) use $(window).trigger( 'hashchange' ); + // * The event can be bound before DOM ready, but since it won't be usable + // before then in IE6/7 (due to the necessary Iframe), recommended usage is + // to bind it inside a $(document).ready() callback. + + jq_event_special[ str_hashchange ] = $.extend( jq_event_special[ str_hashchange ], { + + // Called only when the first 'hashchange' event is bound to window. + setup: function() { + // If window.onhashchange is supported natively, there's nothing to do.. + if ( supports_onhashchange ) { return false; } + + // Otherwise, we need to create our own. And we don't want to call this + // until the user binds to the event, just in case they never do, since it + // will create a polling loop and possibly even a hidden Iframe. + $( fake_onhashchange.start ); + }, + + // Called only when the last 'hashchange' event is unbound from window. + teardown: function() { + // If window.onhashchange is supported natively, there's nothing to do.. + if ( supports_onhashchange ) { return false; } + + // Otherwise, we need to stop ours (if possible). + $( fake_onhashchange.stop ); + } + + }); + + // fake_onhashchange does all the work of triggering the window.onhashchange + // event for browsers that don't natively support it, including creating a + // polling loop to watch for hash changes and in IE 6/7 creating a hidden + // Iframe to enable back and forward. + fake_onhashchange = (function(){ + var self = {}, + timeout_id, + iframe, + set_history, + get_history; + + // Initialize. In IE 6/7, creates a hidden Iframe for history handling. + function init(){ + // Most browsers don't need special methods here.. + set_history = get_history = function(val){ return val; }; + + // But IE6/7 do! + if ( is_old_ie ) { + + // Create hidden Iframe after the end of the body to prevent initial + // page load from scrolling unnecessarily. + iframe = $(' + *
    + * 使用示例: + *
    + * var bmp = new Bitmap({image:img});
    + * Hilo.copy(bmp, Hilo.drag);
    + * bmp.startDrag([0, 0, 550, 400]);
    + * 
    + * @class drag是一个包含拖拽功能的mixin。可以通过 Class.mix(view, drag)或Hilo.copy(view, drag)来为view增加拖拽功能。 + * @mixin + * @static + * @module hilo/util/drag + * @requires hilo/core/Class + * @requires hilo/core/Hilo + */ +var drag = { + /** + * 开始拖拽 + * @param {Array} bounds 拖拽范围,基于父容器坐标系,[x, y, width, height], 默认无限制 + */ + startDrag:function(bounds){ + var that = this; + var stage; + var bounds = bounds||[-Infinity, -Infinity, Infinity, Infinity]; + var mouse = { + x:0, + y:0, + preX:0, + preY:0 + }; + var minX = bounds[0]; + var minY = bounds[1]; + var maxX = bounds[2] == Infinity?Infinity:minX + bounds[2]; + var maxY = bounds[3] == Infinity?Infinity:minY + bounds[3]; + + function onStart(e){ + e.stopPropagation(); + updateMouse(e); + that.off(Hilo.event.POINTER_START, onStart); + + that.fire("dragStart", mouse); + + that.__dragX = that.x - mouse.x; + that.__dragY = that.y - mouse.y; + + if(!stage){ + stage = this.getStage(); + } + stage.on(Hilo.event.POINTER_MOVE, onMove); + document.addEventListener(Hilo.event.POINTER_END, onStop); + } + + function onStop(e){ + document.removeEventListener(Hilo.event.POINTER_END, onStop); + stage && stage.off(Hilo.event.POINTER_MOVE, onMove); + + that.fire("dragEnd", mouse); + that.on(Hilo.event.POINTER_START, onStart); + } + + function onMove(e){ + updateMouse(e); + + that.fire("dragMove", mouse); + + var x = mouse.x + that.__dragX; + var y = mouse.y + that.__dragY; + + that.x = Math.max(minX, Math.min(maxX, x)); + that.y = Math.max(minY, Math.min(maxY, y)); + } + + function updateMouse(e){ + mouse.preX = mouse.x; + mouse.preY = mouse.y; + mouse.x = e.stageX; + mouse.y = e.stageY; + } + + function stopDrag(){ + document.removeEventListener(Hilo.event.POINTER_END, onStop); + stage && stage.off(Hilo.event.POINTER_MOVE, onMove); + that.off(Hilo.event.POINTER_START, onStart); + } + that.on(Hilo.event.POINTER_START, onStart); + + that.stopDrag = stopDrag; + }, + /** + * 停止拖拽 + */ + stopDrag:function(){ + + } +}; + +return drag; + +}, { + requires: ['hilo/core/Class', 'hilo/core/Hilo'] +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002896_Game.js b/pool/shard000/JavaScript/0002896_Game.js new file mode 100644 index 0000000000000000000000000000000000000000..9d713ea53c7b47c27e66849196655f01fa8737f5 --- /dev/null +++ b/pool/shard000/JavaScript/0002896_Game.js @@ -0,0 +1,73 @@ +"use strict" + +const Ball = require("./Ball") +const Paddle = require("./Paddle") +const SAT = require("sat") +const fond = require("../..") +const { Canvas2d, Keyboard } = fond + +class Game +{ + constructor () + { + this.ball = new Ball() + this.paddles = [ + new Paddle({ x: 0, y: 250 }, { up: "w", down: "s" }), + new Paddle({ x: 475, y: 250 }, { up: "ArrowUp", down: "ArrowDown" }), + ] + } + enter () + { + this.canvas2d = new Canvas2d() + this.canvas2d.resize(500, 500) + this.canvas2d.addToDom() + Keyboard.addEvents() + } + leave () + { + this.canvas2d.removeFromDom() + Keyboard.removeEvents() + } + update (dt) + { + this.paddles.forEach((paddle) => paddle.update(dt)) + this.ball.update(dt) + const ballShape = this.ball.getShape() + const response = new SAT.Response() + const collision = this.paddles.some((paddle) => + { + const paddleShape = paddle.getShape() + response.clear() + return SAT.testPolygonCircle(paddleShape, ballShape, response) + }) + if (collision) + { + this.ball.position.x += response.overlapV.x + this.ball.position.y += response.overlapV.y + } + if (collision && response.overlapV.y === 0) + { + this.ball.paddleBounce() + } + else if (collision && response.overlapV.y !== 0) + { + this.ball.wallBounce() + } + if (this.ball.position.y < 0 + this.ball.radius) + { + this.ball.wallBounce() + } + else if (this.ball.position.y > 500 - this.ball.radius) + { + this.ball.wallBounce() + } + } + draw () + { + this.canvas2d.clear() + this.ball.draw(this.canvas2d) + this.paddles.forEach((paddle) => paddle.draw(this.canvas2d)) + } +} + +module.exports = Game diff --git a/pool/shard000/JavaScript/0002905_15.9.3.2-1.js b/pool/shard000/JavaScript/0002905_15.9.3.2-1.js new file mode 100644 index 0000000000000000000000000000000000000000..ae0502be64a6ed21bd74a25333baef2ea283226c --- /dev/null +++ b/pool/shard000/JavaScript/0002905_15.9.3.2-1.js @@ -0,0 +1,151 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +gTestfile = '15.9.3.2-1.js'; + +/** + File Name: 15.9.3.1.js + ECMA Section: 15.9.3.1 new Date (year, month, date, hours, minutes, seconds, ms) + Description: The [[Prototype]] property of the newly constructed + object is set to the original Date prototype object, + the one that is the initial value of Date.prototype. + + The [[Class]] property of the newly constructed object + is set as follows: + 1. Call ToNumber(year) + 2. Call ToNumber(month) + 3. Call ToNumber(date) + 4. Call ToNumber(hours) + 5. Call ToNumber(minutes) + 6. Call ToNumber(seconds) + 7. Call ToNumber(ms) + 8. If Result(1)is NaN and 0 <= ToInteger(Result(1)) <= + 99, Result(8) is 1900+ToInteger(Result(1)); otherwise, + Result(8) is Result(1) + 9. Compute MakeDay(Result(8), Result(2), Result(3) + 10. Compute MakeTime(Result(4), Result(5), Result(6), + Result(7) + 11. Compute MakeDate(Result(9), Result(10)) + 12. Set the [[Value]] property of the newly constructed + object to TimeClip(UTC(Result(11))). + + + This tests the returned value of a newly constructed + Date object. + + Author: christine@netscape.com + Date: 7 july 1997 +*/ + +var TIME = 0; +var UTC_YEAR = 1; +var UTC_MONTH = 2; +var UTC_DATE = 3; +var UTC_DAY = 4; +var UTC_HOURS = 5; +var UTC_MINUTES = 6; +var UTC_SECONDS = 7; +var UTC_MS = 8; + +var YEAR = 9; +var MONTH = 10; +var DATE = 11; +var DAY = 12; +var HOURS = 13; +var MINUTES = 14; +var SECONDS = 15; +var MS = 16; + +// for TCMS, the gTestcases array must be global. +var SECTION = "15.9.3.1"; +var TITLE = "Date( year, month, date, hours, minutes, seconds )"; +startTest(); + +writeHeaderToLog( SECTION+" " +TITLE ); + +// Dates around 1970 + +addNewTestCase( new Date( 1969,11,31,15,59,59), + "new Date( 1969,11,31,15,59,59)", + [-1000,1969,11,31,3,23,59,59,0,1969,11,31,3,15,59,59,0] ); + +addNewTestCase( new Date( 1969,11,31,16,0,0), + "new Date( 1969,11,31,16,0,0)", + [0,1970,0,1,4,0,0,0,0,1969,11,31,3,16,0,0,0] ); + +addNewTestCase( new Date( 1969,11,31,23,59,59), + "new Date( 1969,11,31,23,59,59)", + [28799000,1970,0,1,4,7,59,59,0,1969,11,31,3,23,59,59,0] ); + +addNewTestCase( new Date( 1970, 0, 1, 0, 0, 0), + "new Date( 1970, 0, 1, 0, 0, 0)", + [28800000,1970,0,1,4,8,0,0,0,1970,0,1,4,0,0,0,0] ); + +addNewTestCase( new Date( 1969,11,31,16,0,0), + "new Date( 1969,11,31,16,0,0)", + [0,1970,0,1,4,0,0,0,0,1969,11,31,3,16,0,0,0] ); + +test(); + +function addNewTestCase( DateCase, DateString, ResultArray ) { + //adjust hard-coded ResultArray for tester's timezone instead of PST + adjustResultArray(ResultArray); + + + new TestCase( SECTION, DateString+".getTime()", ResultArray[TIME], DateCase.getTime() ); + new TestCase( SECTION, DateString+".valueOf()", ResultArray[TIME], DateCase.valueOf() ); + + new TestCase( SECTION, DateString+".getUTCFullYear()", ResultArray[UTC_YEAR], DateCase.getUTCFullYear() ); + new TestCase( SECTION, DateString+".getUTCMonth()", ResultArray[UTC_MONTH], DateCase.getUTCMonth() ); + new TestCase( SECTION, DateString+".getUTCDate()", ResultArray[UTC_DATE], DateCase.getUTCDate() ); + new TestCase( SECTION, DateString+".getUTCDay()", ResultArray[UTC_DAY], DateCase.getUTCDay() ); + new TestCase( SECTION, DateString+".getUTCHours()", ResultArray[UTC_HOURS], DateCase.getUTCHours() ); + new TestCase( SECTION, DateString+".getUTCMinutes()", ResultArray[UTC_MINUTES],DateCase.getUTCMinutes() ); + new TestCase( SECTION, DateString+".getUTCSeconds()", ResultArray[UTC_SECONDS],DateCase.getUTCSeconds() ); + new TestCase( SECTION, DateString+".getUTCMilliseconds()", ResultArray[UTC_MS], DateCase.getUTCMilliseconds() ); + + new TestCase( SECTION, DateString+".getFullYear()", ResultArray[YEAR], DateCase.getFullYear() ); + new TestCase( SECTION, DateString+".getMonth()", ResultArray[MONTH], DateCase.getMonth() ); + new TestCase( SECTION, DateString+".getDate()", ResultArray[DATE], DateCase.getDate() ); + new TestCase( SECTION, DateString+".getDay()", ResultArray[DAY], DateCase.getDay() ); + new TestCase( SECTION, DateString+".getHours()", ResultArray[HOURS], DateCase.getHours() ); + new TestCase( SECTION, DateString+".getMinutes()", ResultArray[MINUTES], DateCase.getMinutes() ); + new TestCase( SECTION, DateString+".getSeconds()", ResultArray[SECONDS], DateCase.getSeconds() ); + new TestCase( SECTION, DateString+".getMilliseconds()", ResultArray[MS], DateCase.getMilliseconds() ); + +} diff --git a/pool/shard000/JavaScript/0002906_mf-v2-h-event-justaname.js b/pool/shard000/JavaScript/0002906_mf-v2-h-event-justaname.js new file mode 100644 index 0000000000000000000000000000000000000000..be3a5335dbe9ef9e9d60b15d06993dd753ecf049 --- /dev/null +++ b/pool/shard000/JavaScript/0002906_mf-v2-h-event-justaname.js @@ -0,0 +1,27 @@ +/* +Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24 +Mocha integration test from: microformats-v2/h-event/justaname +The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST) +*/ + +assert = chai.assert; + + +describe('h-event', function() { + var htmlFragment = "

    IndieWebCamp 2012

    "; + var expected = {"items":[{"type":["h-event"],"properties":{"name":["IndieWebCamp 2012"]}}],"rels":{},"rel-urls":{}}; + + it('justaname', function(){ + var doc, dom, node, options, parser, found; + dom = new DOMParser(); + doc = dom.parseFromString( htmlFragment, 'text/html' ); + options ={ + 'document': doc, + 'node': doc, + 'baseUrl': 'http://example.com', + 'dateFormat': 'html5' + }; + found = Microformats.get( options ); + assert.deepEqual(found, expected); + }); +}); diff --git a/pool/shard000/JavaScript/0002910_index.js b/pool/shard000/JavaScript/0002910_index.js new file mode 100644 index 0000000000000000000000000000000000000000..a09cad37f2cb65a5aeffa976f376dabb14b0772b --- /dev/null +++ b/pool/shard000/JavaScript/0002910_index.js @@ -0,0 +1,57 @@ +const { + Nuxt, + Builder, +} = require('nuxt') + + +/* API server start */ +require('./models') +const express = require('express') + +const app = express() +const bodyParser = require('body-parser') +const cookieParser = require('cookie-parser') +const path = require('path') +const cors = require('cors') +const staticServer = express.static(path.resolve(__dirname, '../public'), { maxAge: 1000 * 60 * 60 * 24 }) +const globalConfig = require('./config/global.config') +const handle = require('./middlewares/handle.middleware') +const validate = require('./middlewares/validate.middleware') +const domain = require('./middlewares/domain.middleware') +const router = require('./router') + +app.enable('trust proxy') +app.use(cors({ origin: globalConfig.app.domain, credentials: true })) + .use(domain) + .use(bodyParser.json({ limit: '50mb' })) + .use(cookieParser()) + .use('/public', staticServer) + .use(handle) + .use(validate) + .use(router) + +/* API server end */ + +// Import and Set Nuxt.js options +let config = require('../nuxt.config.js') +config.dev = !(process.env.NODE_ENV === 'production') + +async function start() { + // Init Nuxt.js + const nuxt = new Nuxt(config) + + // Build only in dev mode + if (config.dev) { + const builder = new Builder(nuxt) + await builder.build() + } + + // Give nuxt middleware to express + app.use(nuxt.render) + + // Listen the server + app.listen(3025, () => { + console.log(`server started at ${globalConfig.app.domain}`) + }) +} +start() diff --git a/pool/shard000/JavaScript/0002911_lowercase_pipe.js b/pool/shard000/JavaScript/0002911_lowercase_pipe.js new file mode 100644 index 0000000000000000000000000000000000000000..a14d3686a072943eb7c410be539fb71fd73c03db --- /dev/null +++ b/pool/shard000/JavaScript/0002911_lowercase_pipe.js @@ -0,0 +1,51 @@ +/** + * @license + * Copyright Google Inc. All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.io/license + */ +import { Pipe } from '@angular/core'; +import { isBlank } from '../facade/lang'; +import { InvalidPipeArgumentError } from './invalid_pipe_argument_error'; +/** + * * + * Converts value into a lowercase string using `String.prototype.toLowerCase()`. + * * + * ### Example + * * + * {@example common/pipes/ts/lowerupper_pipe.ts region='LowerUpperPipe'} + * * + */ +export var LowerCasePipe = (function () { + function LowerCasePipe() { + } + /** + * @param {?} value + * @return {?} + */ + LowerCasePipe.prototype.transform = function (value) { + if (isBlank(value)) + return value; + if (typeof value !== 'string') { + throw new InvalidPipeArgumentError(LowerCasePipe, value); + } + return value.toLowerCase(); + }; + LowerCasePipe.decorators = [ + { type: Pipe, args: [{ name: 'lowercase' },] }, + ]; + /** @nocollapse */ + LowerCasePipe.ctorParameters = function () { return []; }; + return LowerCasePipe; +}()); +function LowerCasePipe_tsickle_Closure_declarations() { + /** @type {?} */ + LowerCasePipe.decorators; + /** + * @nocollapse + * @type {?} + */ + LowerCasePipe.ctorParameters; +} +//# sourceMappingURL=lowercase_pipe.js.map \ No newline at end of file diff --git a/pool/shard000/JavaScript/0002914_usemin.js b/pool/shard000/JavaScript/0002914_usemin.js new file mode 100644 index 0000000000000000000000000000000000000000..bc0d5bbf9b85438f22f3fd60031bc34f5bae7c77 --- /dev/null +++ b/pool/shard000/JavaScript/0002914_usemin.js @@ -0,0 +1,34 @@ +/** + * usemin + * ====== + * + * Performs rewrites based on rev and the useminPrepare configuration. + * + * Link: https://github.com/yeoman/grunt-usemin + */ + +'use strict'; + +module.exports = function (grunt) { + return { + html: ['<%= pkg.config.public %>/{,*/}*.html'], + css: ['<%= pkg.config.public %>/styles/{,*/}*.css'], + options: { + assetsDirs: ['<%= pkg.config.public %>'], + blockReplacements: { + js: function (block) { + + var asyncScripts = [ + 'scripts/all.js' + ]; + + var isAsync = block.async || asyncScripts.indexOf(block.dest) > -1; + + return isAsync ? + ''); + jsCount++; + jsSize += js.length; + } + + if (options.css) { + $(':not(noscript) > link[rel="stylesheet"]').each(function() { + var regex = /([,\s,:]url\(['"]?(?!data:))([^\)'"]+)(?=['"]?\))/gi; + var href = $(this).attr('href'); + + if (options.baseDir) { + baseDir = path.resolve(options.baseDir); + } + + var stylePath = path.resolve(baseDir, href); + + if (url.parse(href).hostname || /^\/\//.test(href)) { + + if (options.remote) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', href, false); + xhr.send(null); + + if (xhr.readyState === 4) { + injectStyle($(this), xhr.responseText); + } + } else { + grunt.log.warn('Remote stylesheet "' + href + '" found. Skipping.'); + return; + } + + } else if (href) { + + if (!grunt.file.exists(stylePath)) { + grunt.log.warn('Stylesheet "' + href + '" not found.'); + return; + } + + var css = grunt.file.read(stylePath); + + if (options.rebase) { + css = css.replace(regex, function(whole, front, href) { + if (url.parse(href).hostname) { + return whole; + } + return front + path.relative(baseDir, path.resolve(path.dirname(stylePath), href)).replace(/\\/g, '/'); + }); + } + + injectStyle($(this), css); + + } + + }); + } + + if (options.js) { + $('head script[src]').each(function() { + var href = $(this).attr('src'); + + if (options.baseDir) { + baseDir = path.resolve(options.baseDir); + } + + var stylePath = path.resolve(baseDir, href); + + var scriptPath = path.resolve(baseDir, href); + + if (url.parse(href).hostname || /^\/\//.test(href)) { + + if (options.remote) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', href, false); + xhr.send(null); + + if (xhr.readyState === 4) { + injectScript($(this), xhr.responseText); + } + } else { + grunt.log.warn('Remote script "' + href + '" found. Skipping.'); + return; + } + + } else if (href) { + + if (!grunt.file.exists(scriptPath)) { + grunt.log.warn('Script "' + href + '" not found.'); + return; + } + + var js = grunt.file.read(scriptPath); + + injectScript($(this), js); + + } + + }); + } + + if (jsCount || cssCount) { + grunt.file.write(f.dest, $.html()); + if (options.css) { + grunt.log.writeln(cssCount + ' stylesheet' + (cssCount > 1 ? 's' : '') + ' of size ' + filesize(cssSize) + ' inlined into "' + f.dest + '".'); + } + if (options.js) { + grunt.log.writeln(jsCount + ' script' + (jsCount > 1 ? 's' : '') + ' of size ' + filesize(jsSize) + ' inlined into "' + f.dest + '".'); + } + } + + }); + + }); + +}; diff --git a/pool/shard000/JavaScript/0003637_index.js b/pool/shard000/JavaScript/0003637_index.js new file mode 100644 index 0000000000000000000000000000000000000000..32bc15ad9ff413d17cf1d29fc9fa28280e2a7208 --- /dev/null +++ b/pool/shard000/JavaScript/0003637_index.js @@ -0,0 +1,17 @@ +(function () { + 'use strict'; + + var Static = require('node-static'); + + module.exports = function (dir, port) { + var fileServer = new Static.Server(dir || './'); + + return require('http').createServer(function (req, res) { + req.addListener('end', function () { + fileServer.serve(req, res); + }).resume(); + }).listen(port || 8080); + + }; + +})(); diff --git a/pool/shard000/JavaScript/0003638_server.js b/pool/shard000/JavaScript/0003638_server.js new file mode 100644 index 0000000000000000000000000000000000000000..af53860a0d50096da0ad0e08c2c51cb48a4b3c25 --- /dev/null +++ b/pool/shard000/JavaScript/0003638_server.js @@ -0,0 +1,25 @@ +// Dependencias +var express = require('express'); +var MongoClient = require('mongodb').MongoClient; +var bodyParser = require('body-parser'); +var logger = require('morgan'); + +// Instancia aplicación +var app = module.exports = express(); +var port = process.env.PORT || 80; + +MongoClient.connect('mongodb://localhost:27017/planetasDB', function(err, db) { + if(err) throw err; + + //Middleware + app.use(bodyParser.json()); + app.use(logger('dev')); + + // Rutas + var Planetas = require('./routes/planetas'); + var planetasRouter = new Planetas(db).router; + app.use('/planetas', planetasRouter); + + app.listen(port); + console.log('Servidor iniciado en el puerto ' + port); +}); diff --git a/pool/shard000/JavaScript/0003639_index.js b/pool/shard000/JavaScript/0003639_index.js new file mode 100644 index 0000000000000000000000000000000000000000..e8c341de68fab65f9de74d4fca29e8a3a2411155 --- /dev/null +++ b/pool/shard000/JavaScript/0003639_index.js @@ -0,0 +1,131 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const fs = require("fs"); +const CachedInputFileSystem = require("./CachedInputFileSystem"); +const ResolverFactory = require("./ResolverFactory"); + +/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./ResolverFactory").Plugin} Plugin */ +/** @typedef {import("./ResolverFactory").UserResolveOptions} ResolveOptions */ + +const nodeFileSystem = new CachedInputFileSystem(fs, 4000); + +const nodeContext = { + environments: ["node+es3+es5+process+native"] +}; + +const asyncResolver = ResolverFactory.createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + fileSystem: nodeFileSystem +}); +function resolve(context, path, request, resolveContext, callback) { + if (typeof context === "string") { + callback = resolveContext; + resolveContext = request; + request = path; + path = context; + context = nodeContext; + } + if (typeof callback !== "function") { + callback = resolveContext; + } + asyncResolver.resolve(context, path, request, resolveContext, callback); +} + +const syncResolver = ResolverFactory.createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + useSyncFileSystemCalls: true, + fileSystem: nodeFileSystem +}); +function resolveSync(context, path, request) { + if (typeof context === "string") { + request = path; + path = context; + context = nodeContext; + } + return syncResolver.resolveSync(context, path, request); +} + +function create(options) { + options = { + fileSystem: nodeFileSystem, + ...options + }; + const resolver = ResolverFactory.createResolver(options); + return function (context, path, request, resolveContext, callback) { + if (typeof context === "string") { + callback = resolveContext; + resolveContext = request; + request = path; + path = context; + context = nodeContext; + } + if (typeof callback !== "function") { + callback = resolveContext; + } + resolver.resolve(context, path, request, resolveContext, callback); + }; +} + +function createSync(options) { + options = { + useSyncFileSystemCalls: true, + fileSystem: nodeFileSystem, + ...options + }; + const resolver = ResolverFactory.createResolver(options); + return function (context, path, request) { + if (typeof context === "string") { + request = path; + path = context; + context = nodeContext; + } + return resolver.resolveSync(context, path, request); + }; +} + +/** + * @template A + * @template B + * @param {A} obj input a + * @param {B} exports input b + * @returns {A & B} merged + */ +const mergeExports = (obj, exports) => { + const descriptors = Object.getOwnPropertyDescriptors(exports); + Object.defineProperties(obj, descriptors); + return /** @type {A & B} */ (Object.freeze(obj)); +}; + +module.exports = mergeExports(resolve, { + get sync() { + return resolveSync; + }, + create: mergeExports(create, { + get sync() { + return createSync; + } + }), + ResolverFactory, + CachedInputFileSystem, + get CloneBasenamePlugin() { + return require("./CloneBasenamePlugin"); + }, + get LogInfoPlugin() { + return require("./LogInfoPlugin"); + }, + get forEachBail() { + return require("./forEachBail"); + } +}); diff --git a/pool/shard000/JavaScript/0003640_plugin.js b/pool/shard000/JavaScript/0003640_plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..f4320f4e52e609743a762f544ff5de200dd45470 --- /dev/null +++ b/pool/shard000/JavaScript/0003640_plugin.js @@ -0,0 +1,201 @@ +/* +Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. +For licensing, see LICENSE.html or http://ckeditor.com/license +*/ + +/** + * @fileOverview The "elementspath" plugin. It shows all elements in the DOM + * parent tree relative to the current selection in the editing area. + */ + +(function() +{ + var commands = + { + toolbarFocus : + { + exec : function( editor ) + { + var idBase = editor._.elementsPath.idBase; + var element = CKEDITOR.document.getById( idBase + '0' ); + + // Make the first button focus accessible for IE. (#3417) + // Adobe AIR instead need while of delay. + element && element.focus( CKEDITOR.env.ie || CKEDITOR.env.air ); + } + } + }; + + var emptyHtml = ' '; + + CKEDITOR.plugins.add( 'elementspath', + { + requires : [ 'selection' ], + + init : function( editor ) + { + var spaceId = 'cke_path_' + editor.name; + var spaceElement; + var getSpaceElement = function() + { + if ( !spaceElement ) + spaceElement = CKEDITOR.document.getById( spaceId ); + return spaceElement; + }; + + var idBase = 'cke_elementspath_' + CKEDITOR.tools.getNextNumber() + '_'; + + editor._.elementsPath = { idBase : idBase, filters : [] }; + + editor.on( 'themeSpace', function( event ) + { + if ( event.data.space == 'bottom' ) + { + event.data.html += + '' + editor.lang.elementsPath.eleLabel + '' + + '
    ' + emptyHtml + '
    '; + } + }); + + function onClick( elementIndex ) + { + editor.focus(); + var element = editor._.elementsPath.list[ elementIndex ]; + if ( element.is( 'body' ) ) + { + var range = new CKEDITOR.dom.range( editor.document ); + range.selectNodeContents( element ); + range.select(); + } + else + editor.getSelection().selectElement( element ); + } + + var onClickHanlder = CKEDITOR.tools.addFunction( onClick ); + + var onKeyDownHandler = CKEDITOR.tools.addFunction( function( elementIndex, ev ) + { + var idBase = editor._.elementsPath.idBase, + element; + + ev = new CKEDITOR.dom.event( ev ); + + var rtl = editor.lang.dir == 'rtl'; + switch ( ev.getKeystroke() ) + { + case rtl ? 39 : 37 : // LEFT-ARROW + case 9 : // TAB + element = CKEDITOR.document.getById( idBase + ( elementIndex + 1 ) ); + if ( !element ) + element = CKEDITOR.document.getById( idBase + '0' ); + element.focus(); + return false; + + case rtl ? 37 : 39 : // RIGHT-ARROW + case CKEDITOR.SHIFT + 9 : // SHIFT + TAB + element = CKEDITOR.document.getById( idBase + ( elementIndex - 1 ) ); + if ( !element ) + element = CKEDITOR.document.getById( idBase + ( editor._.elementsPath.list.length - 1 ) ); + element.focus(); + return false; + + case 27 : // ESC + editor.focus(); + return false; + + case 13 : // ENTER // Opera + case 32 : // SPACE + onClick( elementIndex ); + return false; + } + return true; + }); + + editor.on( 'selectionChange', function( ev ) + { + var env = CKEDITOR.env, + selection = ev.data.selection, + element = selection.getStartElement(), + html = [], + editor = ev.editor, + elementsList = editor._.elementsPath.list = [], + filters = editor._.elementsPath.filters; + + while ( element ) + { + var ignore = 0; + for ( var i = 0; i < filters.length; i++ ) + { + if ( filters[ i ]( element ) === false ) + { + ignore = 1; + break; + } + } + + if ( !ignore ) + { + var index = elementsList.push( element ) - 1; + var name; + if ( element.data( 'cke-real-element-type' ) ) + name = element.data( 'cke-real-element-type' ); + else + name = element.getName(); + + // Use this variable to add conditional stuff to the + // HTML (because we are doing it in reverse order... unshift). + var extra = ''; + + // Some browsers don't cancel key events in the keydown but in the + // keypress. + // TODO: Check if really needed for Gecko+Mac. + if ( env.opera || ( env.gecko && env.mac ) ) + extra += ' onkeypress="return false;"'; + + // With Firefox, we need to force the button to redraw, otherwise it + // will remain in the focus state. + if ( env.gecko ) + extra += ' onblur="this.style.cssText = this.style.cssText;"'; + + var label = editor.lang.elementsPath.eleTitle.replace( /%1/, name ); + html.unshift( + '', + name, + '' + label + '', + '' ); + + } + + if ( name == 'body' ) + break; + + element = element.getParent(); + } + + var space = getSpaceElement(); + space.setHtml( html.join('') + emptyHtml ); + editor.fire( 'elementsPathUpdate', { space : space } ); + }); + + editor.on( 'contentDomUnload', function() + { + // If the spaceElement hasn't been initialized, don't try to do it at this time + // Only reuse existing reference. + spaceElement && spaceElement.setHtml( emptyHtml ); + }); + + editor.addCommand( 'elementsPathFocus', commands.toolbarFocus ); + } + }); +})(); diff --git a/pool/shard000/JavaScript/0003642_test.js b/pool/shard000/JavaScript/0003642_test.js new file mode 100644 index 0000000000000000000000000000000000000000..adf72aeadfa1350fa6732e9a2386c7e5a8febaf6 --- /dev/null +++ b/pool/shard000/JavaScript/0003642_test.js @@ -0,0 +1,281 @@ +'use strict'; + +const test = require('ava'); +const fs = require('fs'); +const gutil = require('gulp-util'); +const image = require('..'); + +test('should minify PNG images with pngquant', t => { + const stream = image({ + pngquant : true, + optipng : false, + zopflipng : false + }); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.png').size; + const after = file.contents.length; + t.true(after < before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.png`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.png`) + })); + + stream.end(); +}); + +test('should minify PNG images with optipng', t => { + const stream = image({ + pngquant : false, + optipng : true, + zopflipng : false + }); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.png').size; + const after = file.contents.length; + t.true(after < before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.png`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.png`) + })); + + stream.end(); +}); + +test('should minify PNG images with zopflipng', t => { + const stream = image({ + pngquant : false, + optipng : false, + zopflipng : true + }); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.png').size; + const after = file.contents.length; + t.true(after < before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.png`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.png`) + })); + + stream.end(); +}); + +test('should not minify PNG images when related options are disabled', t => { + const stream = image({ + pngquant : false, + optipng : false, + zopflipng : false + }); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.png').size; + const after = file.contents.length; + t.true(after === before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.png`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.png`) + })); + + stream.end(); +}); + +test('should minify JPG images with jpegRecompress', t => { + const stream = image({ + jpegRecompress : true, + jpegoptim : false, + mozjpeg : false, + guetzli : false + }); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.jpg').size; + const after = file.contents.length; + t.true(after < before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.jpg`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.jpg`) + })); + + stream.end(); +}); + +test('should minify JPG images with jpegoptim', t => { + const stream = image({ + jpegRecompress : false, + jpegoptim : true, + mozjpeg : false, + guetzli : false + }); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.jpg').size; + const after = file.contents.length; + t.true(after < before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.jpg`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.jpg`) + })); + + stream.end(); +}); + +test('should minify JPG images with mozjpeg', t => { + const stream = image({ + jpegRecompress : false, + jpegoptim : false, + mozjpeg : true, + guetzli : false + }); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.jpg').size; + const after = file.contents.length; + t.true(after < before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.jpg`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.jpg`) + })); + + stream.end(); +}); + +test('should minify JPG images with guetzli', t => { + const stream = image({ + jpegRecompress : false, + jpegoptim : false, + mozjpeg : false, + guetzli : true + }); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.jpg').size; + const after = file.contents.length; + t.true(after < before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.jpg`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.jpg`) + })); + + stream.end(); +}); + +test('should not minify JPG images when related options are disabled', t => { + const stream = image({ + jpegRecompress : false, + jpegoptim : false, + mozjpeg : false + }); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.jpg').size; + const after = file.contents.length; + t.true(after === before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.jpg`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.jpg`) + })); + + stream.end(); +}); + +test('should minify GIF images', t => { + const stream = image(); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.gif').size; + const after = file.contents.length; + t.true(after < before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.gif`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.gif`) + })); + + stream.end(); +}); + +test('should not minify GIF images when related options are disabled', t => { + const stream = image({ + gifsicle : false + }); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.gif').size; + const after = file.contents.length; + t.true(after === before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.gif`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.gif`) + })); + + stream.end(); +}); + +test('should minify SVG images', t => { + const stream = image(); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.svg').size; + const after = file.contents.length; + t.true(after < before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.svg`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.svg`) + })); +}); + +test('should not minify SVG images when related options are disabled', t => { + const stream = image({ + svgo : false + }); + + stream.on('data', file => { + const before = fs.statSync('test/fixtures/test.svg').size; + const after = file.contents.length; + t.true(after < before); + }); + + stream.write(new gutil.File({ + path : `${__dirname}/fixtures/test.svg`, + contents : fs.readFileSync(`${__dirname}/fixtures/test.svg`) + })); +}); + +test('should skip unsupported images', t => { + const stream = image(); + + stream.on('data', file => { + t.is(file.contents, null); + }); + + stream.write(new gutil.File({ + path : `${__dirname}fixtures/test.bmp` + })); + + stream.end(); +}); diff --git a/pool/shard000/JavaScript/0003643_utils.js b/pool/shard000/JavaScript/0003643_utils.js new file mode 100644 index 0000000000000000000000000000000000000000..edd9c77d58a114c448cdc50fe7f00fc9f88df834 --- /dev/null +++ b/pool/shard000/JavaScript/0003643_utils.js @@ -0,0 +1,68 @@ +'use strict'; + +/** + * @ngdoc service + * @name sdcApp.Utils + * @description + * # Utils + * Service in the sdcApp. + */ +angular.module('Sdc') + .factory('Utils', function () { + var service = { + /** + * Macro for checking if things are defined or null. + * Help from: http://stackoverflow.com/a/17910655/687274 + * @param obj + * @returns {boolean} + */ + isUndefinedOrNull: function(obj) { + return !angular.isDefined(obj) || obj===null; + }, + + /** + * obj.toLocalString() replacement, as its unreliable across different web renderers. + * Help from: http://stackoverflow.com/a/16157942 + * @param x + * @param sep + * @param grp + * @returns {*} + */ + localeString: function(x, sep, grp) { + var sx = (''+x).split('.'), s = '', i, j; + sep = sep || (sep = ','); // default seperator + grp = grp || grp === 0 || (grp = 3); // default grouping + i = sx[0].length; + while (i > grp) { + j = i - grp; + s = sep + sx[0].slice(j, i) + s; + i = j; + } + s = sx[0].slice(0, i) + s; + sx[0] = s; + return sx.join('.'); + } + }; + + return service; + }) + +/** + * localstorage service, as per: http://learn.ionicframework.com/formulas/localstorage/# + */ + .factory('$localstorage', function($window) { + return { + set: function(key, value) { + $window.localStorage[key] = value; + }, + get: function(key, defaultValue) { + return $window.localStorage[key] || defaultValue; + }, + setObject: function(key, value) { + $window.localStorage[key] = JSON.stringify(value); + }, + getObject: function(key) { + return JSON.parse($window.localStorage[key] || '{}'); + } + }; + }); diff --git a/pool/shard000/JavaScript/0003644_user.js b/pool/shard000/JavaScript/0003644_user.js new file mode 100644 index 0000000000000000000000000000000000000000..908b70d4a639e0784982b63c499c31a3978a64e4 --- /dev/null +++ b/pool/shard000/JavaScript/0003644_user.js @@ -0,0 +1,113 @@ +/** + * Stack Rank + * Copyright (C) 2016 Mule Dojo + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * @category Code + * @package models + * @author Ignacio R. Galieri + * @copyright 2016 Mule Dojo + * @license GPL-3.0 + * @link https://github.com/MuleDojo/stackrank + */ +"use strict"; + +var crypto = require('crypto'); + +class User { + /** + * Constructor + * + * @constructor + * @api public + */ + constructor () { + this.firstname = ''; + this.lastname = ''; + this.email = ''; + this.tasks = []; + this._id = null; + } + /** + * addTask + * + * Add a New Task. + * + * @param {Task} task A new Task + * + * @return void + * @api public + */ + addTask(task) { + task._id = crypto.createHash('md5').update(JSON.stringify(task)).digest("hex"); + this.tasks.push(task); + } + /** + * deleteTask + * + * Delete a Task. + * + * @param {Task} task Task for delete + * + * @return void + * @api public + */ + deleteTask(task) { + let index = this.tasks.findIndex(function (obj) { + return obj._id == task._id; + }); + + if (index > -1) { + this.tasks.splice(index, 1); + } + } + /** + * sortTasks + * + * Order task by urgency, importance and dateAdmission + * + * @param {Function} callback Callback + * + * @return void + * @api public + */ + sortTasks(callback) { + var orderByProperty = function orderByProperty(prop) { + var args = Array.prototype.slice.call(arguments, 1); + return function (b, a) { + var value1 = a[prop]; + if (a[prop] instanceof Date) { + value1 = a[prop].getTime(); + } + var value2 = b[prop]; + if (b[prop] instanceof Date) { + value2 = b[prop].getTime(); + } + + var equality = value1 - value2; + if (equality === 0 && arguments.length > 1) { + return orderByProperty.apply(null, args)(b, a); + } + return equality; + }; + }; + + this.tasks.sort(orderByProperty('urgency', 'importance', 'dateAdmission')); + + callback(false); + } +} + +module.exports = User; diff --git a/pool/shard000/JavaScript/0003646_PluginCache.js b/pool/shard000/JavaScript/0003646_PluginCache.js new file mode 100644 index 0000000000000000000000000000000000000000..5debe7827eecefca0a4c84bcb003710f15bafc01 --- /dev/null +++ b/pool/shard000/JavaScript/0003646_PluginCache.js @@ -0,0 +1,177 @@ +/** + * @author Richard Davey + * @copyright 2018 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +// Contains the plugins that Phaser uses globally and locally. +// These are the source objects, not instantiated. +var corePlugins = {}; + +// Contains the plugins that the dev has loaded into their game +// These are the source objects, not instantiated. +var customPlugins = {}; + +/** + * @typedef {object} CorePluginContainer + * + * @property {string} key - The unique name of this plugin in the core plugin cache. + * @property {function} plugin - The plugin to be stored. Should be the source object, not instantiated. + * @property {string} [mapping] - If this plugin is to be injected into the Scene Systems, this is the property key map used. + * @property {boolean} [custom=false] - Core Scene plugin or a Custom Scene plugin? + */ + +/** + * @typedef {object} CustomPluginContainer + * + * @property {string} key - The unique name of this plugin in the custom plugin cache. + * @property {function} plugin - The plugin to be stored. Should be the source object, not instantiated. + */ + +var PluginCache = {}; + +/** + * Static method called directly by the Core internal Plugins. + * Key is a reference used to get the plugin from the plugins object (i.e. InputPlugin) + * Plugin is the object to instantiate to create the plugin + * Mapping is what the plugin is injected into the Scene.Systems as (i.e. input) + * + * @method Phaser.Plugins.PluginCache.register + * @since 3.8.0 + * + * @param {string} key - A reference used to get this plugin from the plugin cache. + * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. + * @param {string} mapping - If this plugin is to be injected into the Scene Systems, this is the property key map used. + * @param {boolean} [custom=false] - Core Scene plugin or a Custom Scene plugin? + */ +PluginCache.register = function (key, plugin, mapping, custom) +{ + if (custom === undefined) { custom = false; } + + corePlugins[key] = { plugin: plugin, mapping: mapping, custom: custom }; +}; + +/** + * Stores a custom plugin in the global plugin cache. + * The key must be unique, within the scope of the cache. + * + * @method Phaser.Plugins.PluginCache.registerCustom + * @since 3.8.0 + * + * @param {string} key - A reference used to get this plugin from the plugin cache. + * @param {function} plugin - The plugin to be stored. Should be the core object, not instantiated. + * @param {string} mapping - If this plugin is to be injected into the Scene Systems, this is the property key map used. + */ +PluginCache.registerCustom = function (key, plugin, mapping) +{ + customPlugins[key] = { plugin: plugin, mapping: mapping }; +}; + +/** + * Checks if the given key is already being used in the core plugin cache. + * + * @method Phaser.Plugins.PluginCache.hasCore + * @since 3.8.0 + * + * @param {string} key - The key to check for. + * + * @return {boolean} `true` if the key is already in use in the core cache, otherwise `false`. + */ +PluginCache.hasCore = function (key) +{ + return corePlugins.hasOwnProperty(key); +}; + +/** + * Checks if the given key is already being used in the custom plugin cache. + * + * @method Phaser.Plugins.PluginCache.hasCustom + * @since 3.8.0 + * + * @param {string} key - The key to check for. + * + * @return {boolean} `true` if the key is already in use in the custom cache, otherwise `false`. + */ +PluginCache.hasCustom = function (key) +{ + return customPlugins.hasOwnProperty(key); +}; + +/** + * Returns the core plugin object from the cache based on the given key. + * + * @method Phaser.Plugins.PluginCache.getCore + * @since 3.8.0 + * + * @param {string} key - The key of the core plugin to get. + * + * @return {CorePluginContainer} The core plugin object. + */ +PluginCache.getCore = function (key) +{ + return corePlugins[key]; +}; + +/** + * Returns the custom plugin object from the cache based on the given key. + * + * @method Phaser.Plugins.PluginCache.getCustom + * @since 3.8.0 + * + * @param {string} key - The key of the custom plugin to get. + * + * @return {CustomPluginContainer} The custom plugin object. + */ +PluginCache.getCustom = function (key) +{ + return customPlugins[key]; +}; + +/** + * Returns an object from the custom cache based on the given key that can be instantiated. + * + * @method Phaser.Plugins.PluginCache.getCustomClass + * @since 3.8.0 + * + * @param {string} key - The key of the custom plugin to get. + * + * @return {function} The custom plugin object. + */ +PluginCache.getCustomClass = function (key) +{ + return (customPlugins.hasOwnProperty(key)) ? customPlugins[key].plugin : null; +}; + +/** + * Removes a core plugin based on the given key. + * + * @method Phaser.Plugins.PluginCache.remove + * @since 3.8.0 + * + * @param {string} key - The key of the core plugin to remove. + */ +PluginCache.remove = function (key) +{ + if (corePlugins.hasOwnProperty(key)) + { + delete corePlugins[key]; + } +}; + +/** + * Removes a custom plugin based on the given key. + * + * @method Phaser.Plugins.PluginCache.removeCustom + * @since 3.8.0 + * + * @param {string} key - The key of the custom plugin to remove. + */ +PluginCache.removeCustom = function (key) +{ + if (customPlugins.hasOwnProperty(key)) + { + delete customPlugins[key]; + } +}; + +module.exports = PluginCache; diff --git a/pool/shard000/JavaScript/0003653_mongoDBClient.js b/pool/shard000/JavaScript/0003653_mongoDBClient.js new file mode 100644 index 0000000000000000000000000000000000000000..cd35e24874a490596b1f4c41a41f6e932b0318df --- /dev/null +++ b/pool/shard000/JavaScript/0003653_mongoDBClient.js @@ -0,0 +1,35 @@ +/** + * Created by jude on 28/11/2016. + */ +var mongoose = require('mongoose'); + +mongoose.connect('mongodb://localhost/piData'); + +var db = mongoose.connection; + +// data structure +var venueSchema = mongoose.Schema( + { + _id: String, + distance : String, + mac_short : String, + mac : String, + venueid : String, + samples : Number, + captime : Number + } +); + +mongoose.model('venueinfo', venueSchema, 'venueinfo'); + +db.on('error', console.error.bind(console, 'connection error.....')); +db.once('open', function callback(){ + console.log('Pi database is now open!') +}); + +module.exports = { + mongoose: function () { + return mongoose; + } +}; + diff --git a/pool/shard000/JavaScript/0003654_static.js b/pool/shard000/JavaScript/0003654_static.js new file mode 100644 index 0000000000000000000000000000000000000000..d9d32f4a7c4dc6bcc7f20132199217b65065b239 --- /dev/null +++ b/pool/shard000/JavaScript/0003654_static.js @@ -0,0 +1,31 @@ +var B = require('../').Buffer +var test = require('tape') +if (process.env.OBJECT_IMPL) B.TYPED_ARRAY_SUPPORT = false + +test('Buffer.isEncoding', function (t) { + t.equal(B.isEncoding('HEX'), true) + t.equal(B.isEncoding('hex'), true) + t.equal(B.isEncoding('bad'), false) + t.end() +}) + +test('Buffer.isBuffer', function (t) { + t.equal(B.isBuffer(new B('hey', 'utf8')), true) + t.equal(B.isBuffer(new B([1, 2, 3], 'utf8')), true) + t.equal(B.isBuffer('hey'), false) + t.end() +}) + +test('Buffer.toArrayBuffer', function (t) { + var data = [1, 2, 3, 4, 5, 6, 7, 8] + if (typeof Uint8Array !== 'undefined') { + var result = new B(data).toArrayBuffer() + var expected = new Uint8Array(data).buffer + for (var i = 0; i < expected.byteLength; i++) { + t.equal(result[i], expected[i]) + } + } else { + t.pass('No toArrayBuffer() method provided in old browsers') + } + t.end() +}) diff --git a/pool/shard000/JavaScript/0003655_compartments.client.controller.tests.js b/pool/shard000/JavaScript/0003655_compartments.client.controller.tests.js new file mode 100644 index 0000000000000000000000000000000000000000..d30bc147580514839030618ee5fbb904f65da641 --- /dev/null +++ b/pool/shard000/JavaScript/0003655_compartments.client.controller.tests.js @@ -0,0 +1,163 @@ +'use strict'; + +(function() { + // Compartments Controller Spec + describe('Compartments Controller Tests', function() { + // Initialize global variables + var CompartmentsController, + scope, + $httpBackend, + $stateParams, + $location; + + // The $resource service augments the response object with methods for updating and deleting the resource. + // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match + // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. + // When the toEqualData matcher compares two objects, it takes only object properties into + // account and ignores methods. + beforeEach(function() { + jasmine.addMatchers({ + toEqualData: function(util, customEqualityTesters) { + return { + compare: function(actual, expected) { + return { + pass: angular.equals(actual, expected) + }; + } + }; + } + }); + }); + + // Then we can start by loading the main application module + beforeEach(module(ApplicationConfiguration.applicationModuleName)); + + // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). + // This allows us to inject a service but then attach it to a variable + // with the same name as the service. + beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { + // Set a new global scope + scope = $rootScope.$new(); + + // Point global variables to injected services + $stateParams = _$stateParams_; + $httpBackend = _$httpBackend_; + $location = _$location_; + + // Initialize the Compartments controller. + CompartmentsController = $controller('CompartmentsController', { + $scope: scope + }); + })); + + it('$scope.find() should create an array with at least one Compartment object fetched from XHR', inject(function(Compartments) { + // Create sample Compartment using the Compartments service + var sampleCompartment = new Compartments({ + name: 'New Compartment' + }); + + // Create a sample Compartments array that includes the new Compartment + var sampleCompartments = [sampleCompartment]; + + // Set GET response + $httpBackend.expectGET('api/compartments').respond(sampleCompartments); + + // Run controller functionality + scope.find(); + $httpBackend.flush(); + + // Test scope value + expect(scope.compartments).toEqualData(sampleCompartments); + })); + + it('$scope.findOne() should create an array with one Compartment object fetched from XHR using a compartmentId URL parameter', inject(function(Compartments) { + // Define a sample Compartment object + var sampleCompartment = new Compartments({ + name: 'New Compartment' + }); + + // Set the URL parameter + $stateParams.compartmentId = '525a8422f6d0f87f0e407a33'; + + // Set GET response + $httpBackend.expectGET(/api\/compartments\/([0-9a-fA-F]{24})$/).respond(sampleCompartment); + + // Run controller functionality + scope.findOne(); + $httpBackend.flush(); + + // Test scope value + expect(scope.compartment).toEqualData(sampleCompartment); + })); + + it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Compartments) { + // Create a sample Compartment object + var sampleCompartmentPostData = new Compartments({ + name: 'New Compartment' + }); + + // Create a sample Compartment response + var sampleCompartmentResponse = new Compartments({ + _id: '525cf20451979dea2c000001', + name: 'New Compartment' + }); + + // Fixture mock form input values + scope.name = 'New Compartment'; + + // Set POST response + $httpBackend.expectPOST('api/compartments', sampleCompartmentPostData).respond(sampleCompartmentResponse); + + // Run controller functionality + scope.create(); + $httpBackend.flush(); + + // Test form inputs are reset + expect(scope.name).toEqual(''); + + // Test URL redirection after the Compartment was created + expect($location.path()).toBe('/compartments/' + sampleCompartmentResponse._id); + })); + + it('$scope.update() should update a valid Compartment', inject(function(Compartments) { + // Define a sample Compartment put data + var sampleCompartmentPutData = new Compartments({ + _id: '525cf20451979dea2c000001', + name: 'New Compartment' + }); + + // Mock Compartment in scope + scope.compartment = sampleCompartmentPutData; + + // Set PUT response + $httpBackend.expectPUT(/api\/compartments\/([0-9a-fA-F]{24})$/).respond(); + + // Run controller functionality + scope.update(); + $httpBackend.flush(); + + // Test URL location to new object + expect($location.path()).toBe('/compartments/' + sampleCompartmentPutData._id); + })); + + it('$scope.remove() should send a DELETE request with a valid compartmentId and remove the Compartment from the scope', inject(function(Compartments) { + // Create new Compartment object + var sampleCompartment = new Compartments({ + _id: '525a8422f6d0f87f0e407a33' + }); + + // Create new Compartments array and include the Compartment + scope.compartments = [sampleCompartment]; + + // Set expected DELETE response + $httpBackend.expectDELETE(/api\/compartments\/([0-9a-fA-F]{24})$/).respond(204); + + // Run controller functionality + scope.remove(sampleCompartment); + $httpBackend.flush(); + + // Test array after successful delete + expect(scope.compartments.length).toBe(0); + })); + }); +}()); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003656_status.js b/pool/shard000/JavaScript/0003656_status.js new file mode 100644 index 0000000000000000000000000000000000000000..a33c7ae09c53e1ebc0b314cf0344f8b594679724 --- /dev/null +++ b/pool/shard000/JavaScript/0003656_status.js @@ -0,0 +1,29 @@ +angular.module('bhima.controllers') + .controller('RequisitionStatusModalController', RequisitionStatusModalController); + +RequisitionStatusModalController.$inject = [ + '$uibModalInstance', 'NotifyService', 'StockService', 'data', +]; + +function RequisitionStatusModalController(Instance, Notify, Stock, Data) { + const vm = this; + + // global variables + vm.requisition = Data; + + // expose to view + vm.close = Instance.close; + vm.submit = submit; + + // submit the choice + function submit() { + const data = { status_id : vm.status }; + + Stock.stockRequisition.update(vm.requisition.uuid, data) + .then(() => { + Instance.close(); + }) + .catch(Notify.handleError); + } + +} diff --git a/pool/shard000/JavaScript/0003660_DistinguishedDojo.js b/pool/shard000/JavaScript/0003660_DistinguishedDojo.js new file mode 100644 index 0000000000000000000000000000000000000000..50f921c7e7940b3336f60a664b8694353806a9e2 --- /dev/null +++ b/pool/shard000/JavaScript/0003660_DistinguishedDojo.js @@ -0,0 +1,37 @@ +const DrawCard = require('../../drawcard'); +const AbilityDsl = require('../../abilitydsl'); +const { TargetModes, TokenTypes } = require('../../Constants'); + +class DistinguishedDojo extends DrawCard { + setupCardAbilities() { + this.reaction({ + title: 'Place an honor token', + when: { + afterDuel: (event, context) => event.winner && event.winner.controller === context.source.controller + }, + limit: AbilityDsl.limit.perRound(3), + gameAction: AbilityDsl.actions.addToken(), + then: context => ({ + target: { + mode: TargetModes.Select, + activePromptTitle: 'Sacrifice ' + context.source.name + '?', + choices: { + 'Yes': AbilityDsl.actions.sacrifice({ target: context.source }), + 'No': () => true + } + }, + message: '{0} chooses {3}to sacrifice {1}', + messageArgs: context => context.select === 'No' ? 'not ' : '', + then: subThenContext => ({ + gameAction: AbilityDsl.actions.gainHonor({ amount: subThenContext.source.getTokenCount(TokenTypes.Honor) }), + message: '{0} uses {1} to gain {3} honor', + messageArgs: [subThenContext.source.getTokenCount(TokenTypes.Honor)] + }) + }) + }); + } +} + +DistinguishedDojo.id = 'distinguished-dojo'; + +module.exports = DistinguishedDojo; diff --git a/pool/shard000/JavaScript/0003663_main.js b/pool/shard000/JavaScript/0003663_main.js new file mode 100644 index 0000000000000000000000000000000000000000..1321e682550a3e3d6b8e2f6982acab456bdf4ffa --- /dev/null +++ b/pool/shard000/JavaScript/0003663_main.js @@ -0,0 +1,106 @@ +var input1, input2, button, configInput, configEnable, configDisable, results; + +var validity = {aspect1: false, aspect2: false};//Stores whether the users's aspect names are valid or not + +$(initLib); + +$(function(){//When the page is loaded, do the following. + //These lines locate and save the page elements that are important for the script: + input1 = $('#aspect1');//The starting aspect textbox, + input2 = $('#aspect2');//the ending aspect textbox, + button = $('#connect');//the "Connect" button, + configInput = $('#config-input'); configEnable = $('#config-enable'); configDisable = $('#config-disable');//the configuration section's fields, + results = $('#results');//and the column where the connection is displayed. + + input1.add(input2).on('propertychange change keyup input paste', {showErrors: false}, validate) + .on('focusout', {showErrors: true}, validate) + .each(function(index){ + if(aspects.selected[this.value]){ + $(this).prev().addClass('w3-text-green'); + validity[this.id] = true; + }else button.addClass('w3-disabled'); + }); + if(validity.aspect1 && validity.aspect2) makeConnection(); + + configInput.on('propertychange change keyup input paste', function(){ + var node = nodes[this.value.toLowerCase()]; + configEnable.toggleClass('w3-disabled', !node || node.active); + configDisable.toggleClass('w3-disabled', !node || !node.active); + }); + configEnable.on('click', function(){ + if(!$(this).hasClass('w3-disabled')) nodes[configInput.val().toLowerCase()].active = true; + configEnable.addClass('w3-disabled'); + configDisable.removeClass('w3-disabled'); + $('#disabled-list > li[data-aspect=' + configInput.val().toLowerCase() + ']').remove(); + }); + configDisable.on('click', function(){ + if(!$(this).hasClass('w3-disabled')) nodes[configInput.val().toLowerCase()].active = false; + configEnable.removeClass('w3-disabled'); + configDisable.addClass('w3-disabled'); + var aspect = aspects.selected[configInput.val().toLowerCase()]; + $('
  • ').attr('data-aspect', aspect.name).append("").append(aspect.displayName).appendTo('#disabled-list'); + }); + + button.on('click', function(){//When the "Connect" button is clicked, + if(!button.hasClass('w3-disabled')) makeConnection();//If the button is active (two valid aspects have been inputted), make and display the connection. + }); + + $('#results-header').append(removeButton(function(){ + results.empty(); + })); +}); + +function validate(event){ + var asp = (this.value || '').toLowerCase(); + validity[this.id] = aspects.selected[asp] ? true : false;//If an aspect exists with the name inputted into this field, mark this field valid. + $(this).prev().toggleClass('w3-text-green', validity[this.id]);//If the aspect is valid, make the label text green; + $(this).prev().toggleClass('w3-text-red', !validity[this.id]);//otherwise, make it red. + button.toggleClass('w3-disabled', !validity.aspect1 || !validity.aspect2);//If either aspect is invalid, disable the "Connect" button. + + if(event.data.showErrors){ + var errorBox = $('#error' + this.id.slice(-1)); + if(validity[this.id]) errorBox.empty(); + else errorBox.text("Unknown aspect '" + asp.slice(0, 1).toUpperCase() + asp.slice(1) + "'."); + } +} + +function makeConnection(){ + var asp1 = input1.val().toLowerCase(), asp2 = input2.val().toLowerCase();//Get aspect names from the two input fields. + + var row = $('
    ').addClass('chain'); + + var chain = nodes.connect(asp1, asp2);//Find the connection between the two aspects (returns an array of aspect names from start to end). + + for(var i=0; i
    ').addClass('chain-element w3-tooltip'); + $('').attr('src', chain[i].aspect.iconURL).appendTo(container); + + var tooltip = $('').addClass('w3-text w3-tag w3-round-large').css('padding-bottom', '8px').appendTo(container); + tooltip.append("" + chain[i].aspect.displayName + "") + .append("" + chain[i].aspect.displayDescription+ ""); + if(!chain[i].aspect.isPrimal()){ + tooltip.append('
    '); + var comps = chain[i].aspect.components; + for(var j=0; j"); + if(j+1 < comps.length) tooltip.append("add"); + } + } + container.appendTo(row); + if(i+1 < chain.length) row.append("keyboard_arrow_right"); + } + row.append(removeButton(function(event){ + $(this).parent().remove(); + })) + results.append(row); +} + +function removeButton(handler){ + return $('').addClass('w3-btn w3-red remove').append("delete").on('click', handler); +} + +function updateVersion(){ + for(var name in nodes) delete nodes[name]; + initLib(); + results.empty(); +} diff --git a/pool/shard000/JavaScript/0003667_counterStore.js b/pool/shard000/JavaScript/0003667_counterStore.js new file mode 100644 index 0000000000000000000000000000000000000000..50defcea989777b3f8b20d80570678fee05535b8 --- /dev/null +++ b/pool/shard000/JavaScript/0003667_counterStore.js @@ -0,0 +1,31 @@ +import { createStore } from 'fluxible/addons'; +import constants from './constants'; + +export default createStore({ + storeName: 'Counter', + + handlers: { + [constants.SET_VALUE]: 'setValue', + [constants.INCREMENT]: 'increment' + }, + + setValue(value = 0) { + this.value = value; + this.emitChange(); + }, + + increment(count = 1) { + this.value += count; + this.emitChange(); + }, + + dehydrate() { + return { + value: this.value + }; + }, + + rehydrate(state) { + this.value = state.value; + } +}); diff --git a/pool/shard000/JavaScript/0003669_reset.finish.controller.js b/pool/shard000/JavaScript/0003669_reset.finish.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..dfb13a8f6378fd634e37b7351124431b133f03a9 --- /dev/null +++ b/pool/shard000/JavaScript/0003669_reset.finish.controller.js @@ -0,0 +1,39 @@ +(function() { + 'use strict'; + + angular + .module('coocotteApp') + .controller('ResetFinishController', ResetFinishController); + + ResetFinishController.$inject = ['$stateParams', '$timeout', 'Auth', 'LoginService']; + + function ResetFinishController ($stateParams, $timeout, Auth, LoginService) { + var vm = this; + + vm.keyMissing = angular.isUndefined($stateParams.key); + vm.confirmPassword = null; + vm.doNotMatch = null; + vm.error = null; + vm.finishReset = finishReset; + vm.login = LoginService.open; + vm.resetAccount = {}; + vm.success = null; + + $timeout(function (){angular.element('#password').focus();}); + + function finishReset() { + vm.doNotMatch = null; + vm.error = null; + if (vm.resetAccount.password !== vm.confirmPassword) { + vm.doNotMatch = 'ERROR'; + } else { + Auth.resetPasswordFinish({key: $stateParams.key, newPassword: vm.resetAccount.password}).then(function () { + vm.success = 'OK'; + }).catch(function () { + vm.success = null; + vm.error = 'ERROR'; + }); + } + } + } +})(); diff --git a/pool/shard000/JavaScript/0003672_mongodb.js b/pool/shard000/JavaScript/0003672_mongodb.js new file mode 100644 index 0000000000000000000000000000000000000000..563bb3aa70fc5c0b9a86cc65342de5bf35ba5cc1 --- /dev/null +++ b/pool/shard000/JavaScript/0003672_mongodb.js @@ -0,0 +1,31 @@ +/* +@title Write docusment to MongoDB +*/ + +var MongoClient = require('mongodb').MongoClient; + +module.exports = function(req, res, next){ + req + .app + .mongodb + .creds() + .then((cred) => { + MongoClient.connect(cred.connection_string, function(err, db) { + if (err) { + return res.status(500).send(err); + } + + var collection = db.collection('people'); + collection.insert({ name : 'john smith' }, (err, result) => { + if (err) { + return res.status(500).send(err); + } + + res.send(result); + + db.close(); + }); + }); + }) + .catch((err) => res.status(err.statusCode || 500).send(err.error || err)); +}; diff --git a/pool/shard000/JavaScript/0003673_wsserver.js b/pool/shard000/JavaScript/0003673_wsserver.js new file mode 100644 index 0000000000000000000000000000000000000000..50684f4abbdf72438cfafae6335ae39abd02aa7a --- /dev/null +++ b/pool/shard000/JavaScript/0003673_wsserver.js @@ -0,0 +1,31 @@ +#!/usr/bin/env node +var WebSocketServer = require('websocket').server; +var http = require('http'); + +var server = http.createServer(function(request, response) { + console.log(request.url); + response.writeHead(404); + response.end(); +}); + +server.listen(5050, function() { + console.log('Server is listening on port 5050'); +}); + +wsServer = new WebSocketServer({ + httpServer: server, + autoAcceptConnections: false +}); + +wsServer.on('request', function(request) { + var connection = request.accept('echo-protocol', request.origin); + + connection.on('message', function(message) { + connection.sendUTF(message.utf8Data); + console.log('message: ' + message.utf8Data); + }); + + connection.on('close', function(reasonCode, description) { + console.log('closed'); + }); +}); diff --git a/pool/shard000/JavaScript/0003674_index.js b/pool/shard000/JavaScript/0003674_index.js new file mode 100644 index 0000000000000000000000000000000000000000..bcd2a68ed37ec43e825c14fb7a221383a56b6419 --- /dev/null +++ b/pool/shard000/JavaScript/0003674_index.js @@ -0,0 +1,56 @@ +// Uji Coba + +var spawn = require('child_process').spawn; +var async = require('async'); +var moment = require('moment'); +var fs = require('fs'); + +require('events').EventEmitter.prototype._maxListeners = 1000000; + + +// Configuration +var server = process.argv[2]; +var mountPoint = process.argv[3]; +var instancesPerServer = process.argv[4]; +var timePerRequest = process.argv[5]; + +var success = 0; +var fail = 0; + +// Create array with instancePerServer times element for the sake of async library +var arr = [] +for(var i=0; i < instancesPerServer; i++) { + arr.push(i); +} +async.each(arr, function(i, callback) { + // Do a curl + var stdout = ""; + var start = moment(new Date()); + var ps = spawn('curl', ['-o', '/dev/null', '-m', timePerRequest, '-s', + '-w', "%{size_download}", 'http://' + server + mountPoint]); + + + ps.stdout.on('data', function(data) { + stdout += data.toString(); + }); + + ps.stderr.pipe(process.stdout); + + ps.on('exit', function() { + var end = moment(new Date()); + var result = parseFloat(stdout) / 1024; + var diff = moment.duration(end.diff(start)); + + if(diff.asSeconds() < timePerRequest) { + fail++; + } else { + success++; + } + + callback(); + }); + + +}, function(err) { + console.log(success) +}); diff --git a/pool/shard000/JavaScript/0003677_get-random-value-test.js b/pool/shard000/JavaScript/0003677_get-random-value-test.js new file mode 100644 index 0000000000000000000000000000000000000000..475973333b7bf111f84a21f09c12f62af4ce54b2 --- /dev/null +++ b/pool/shard000/JavaScript/0003677_get-random-value-test.js @@ -0,0 +1,25 @@ +describe("get random value", () => { + let mockGetRandomValues, getRandomValue; + + beforeEach(() => { + mockGetRandomValues = jest.fn(() => [2]); + + jest.mock("../../../source/iml/global.js", () => ({ + crypto: { + getRandomValues: mockGetRandomValues + } + })); + + getRandomValue = require("../../../source/iml/get-random-value.js").default; + }); + + it("should be called with a Uint32Array", () => { + getRandomValue(); + + expect(mockGetRandomValues).toHaveBeenCalledOnceWith(new Uint32Array(1)); + }); + + it("should return the result of crypto.getRandomValues", () => { + expect(getRandomValue()).toBe(2); + }); +}); diff --git a/pool/shard000/JavaScript/0003678_html_comment_spec.js b/pool/shard000/JavaScript/0003678_html_comment_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..e66af1d4d8c980359bca8d1b70d828de444b87b5 --- /dev/null +++ b/pool/shard000/JavaScript/0003678_html_comment_spec.js @@ -0,0 +1,67 @@ +'use strict'; + +var HTMLCommentWidget = require('../../../../src/template/widgets/html_comment.js'); + +describe('html_comment.js public API', function() { + it('should be a function', function() { + expect(HTMLCommentWidget).to.be.a('function'); + expect(HTMLCommentWidget).to.have.length(1); + }); + describe('html_comment prototype', function() { + var comment, text; + beforeEach(function() { + text = 'comment'; + comment = new HTMLCommentWidget(text); + }); + it('should have a property text', function() { + expect(comment.text).to.equal(text); + }); + it('should have a property type', function() { + expect(comment.type).to.equal('Widget'); + }); + describe('HtmlComment.init', function() { + it('should have an init function', function() { + expect(comment.init).to.be.a('function'); + expect(comment.init).to.have.length(0); + expect(comment.init).to.equal(HTMLCommentWidget.prototype.init); + }); + it('should create an HTML comment node', function() { + var output = comment.init(); + expect(output.nodeType).to.equal(document.COMMENT_NODE); + expect(output.nodeValue).to.equal(text); + }); + }); + describe('HtmlComment.update', function() { + it('should have an update function', function() { + expect(comment.update).to.be.a('function'); + expect(comment.update).to.have.length(2); + expect(comment.update).to.equal(HTMLCommentWidget.prototype.update); + }); + it('should update a node', function() { + var prev = new HTMLCommentWidget('old value'); + var elem = prev.init(); + comment.update(prev, elem); + expect(elem.nodeValue).to.equal(text); + }); + it('should not a node if the values match', function() { + var oldValue = 'old value'; + var prev = new HTMLCommentWidget(oldValue); + var elem = prev.init(); + comment.update(comment, elem); + expect(elem.nodeValue).to.equal(oldValue); + }); + }); + if (typeof TUNGSTENJS_DEBUG_MODE !== 'undefined') { + describe('HtmlComment.templateToString', function() { + it('should have a templateToString function', function() { + expect(comment.templateToString).to.be.a('function'); + expect(comment.templateToString).to.have.length(0); + expect(comment.templateToString).to.equal(HTMLCommentWidget.prototype.templateToString); + }); + it('should be able to create a debugger html block', function() { + expect(comment.templateToString()).to.equal('<!-- ' + text + ' -->'); + }); + }); + } + }); +}); diff --git a/pool/shard000/JavaScript/0003680_user.js b/pool/shard000/JavaScript/0003680_user.js new file mode 100644 index 0000000000000000000000000000000000000000..73cb91db92e20478915c0e57d953d1163f4d7eb5 --- /dev/null +++ b/pool/shard000/JavaScript/0003680_user.js @@ -0,0 +1,203 @@ +describe("mtapi", function () { + 'use strict'; + + beforeEach(function () { + var flag; + require(['js/mtapi/user', 'js/cache'], function () { + flag = true; + }); + waitsFor(function () { + return flag; + }); + }); + + describe("user", function () { + beforeEach(function () { + window.Mock.alwaysFail = null; + window.Mock.returnFailRequest = null; + window.Mock.failPermission = null; + + window.Mock.throwUserItem = { + displayName: "Yutaka Yamaguchi", + email: "yyamaguchi@sixapart.com", + id: "1", + language: "ja", + name: "yyamaguchi", + updatable: true, + url: "", + userpicUrl: "" + }; + + window.Mock.throwPermissionItems = [{ + "permissions": ["administer", "create_blog", "create_website", "edit_templates", "manage_plugins", "view_log"], + "blog": null + }, { + "permissions": ["administer_blog", "administer_website", "comment", "create_post", "edit_all_posts", "edit_assets", "edit_categories", "edit_config", "edit_notifications", "edit_tags", "edit_templates", "manage_feedback", "manage_member_blogs", "manage_pages", "manage_themes", "manage_users", "publish_post", "rebuild", "save_image_defaults", "send_notifications", "set_publish_paths", "upload", "view_blog_log"], + "blog": { + "id": "1" + } + }]; + + require('js/cache').clearAll(); + }); + + it("get user", function () { + var cache = require('js/cache'); + var getUser = require('js/mtapi/user'); + var dfd = getUser(); + var user, flag, permCollection; + runs(function () { + dfd.done(function (resp) { + user = resp; + permCollection = cache.get('user', 'perms'); + flag = true; + }); + }); + + waitsFor(function () { + return flag; + }, 'get user with js/mtapi/user', 3000); + + runs(function () { + expect(user).toBeDefined(); + expect(user.id).toEqual(window.Mock.throwUserItem.id); + expect(user.language).toEqual(window.Mock.throwUserItem.language); + expect(user.displayName).toEqual(window.Mock.throwUserItem.displayName); + expect(user.permissions).toBeDefined(); + var expectedSystemPerm = window.Mock.throwPermissionItems[0].permissions; + expect(user.permissions.length).toEqual(expectedSystemPerm.length); + _.forEach(user.permissions, function (perm) { + var find = _.find(expectedSystemPerm, function (expectPerm) { + return perm === expectPerm; + }); + expect(find).not.toBeNull(); + }); + + expect(permCollection).toBeDefined(); + expect(permCollection.totalResults).toEqual(window.Mock.throwPermissionItems.length); + }); + }); + + it("when user request failed, return failed", function () { + window.Mock.returnFailRequest = 'get User request failed'; + + var mtapi = require('js/mtapi'); + spyOn(mtapi.api, 'listPermissionsForUser').andCallThrough(); + + var cache = require('js/cache'); + var getUser = require('js/mtapi/user'); + var dfd = getUser(); + spyOn(dfd, 'fail').andCallThrough(); + + var user, flag, permCollection; + runs(function () { + dfd.done(function (resp) { + user = resp; + permCollection = cache.get('user', 'perms'); + flag = true; + }); + dfd.fail(function (resp) { + user = resp; + permCollection = cache.get('user', 'perms'); + flag = true; + }) + }); + + waitsFor(function () { + return flag; + }, 'get user with js/mtapi/user', 3000); + + runs(function () { + expect(dfd.fail).toHaveBeenCalled(); + expect(mtapi.api.listPermissionsForUser).not.toHaveBeenCalled(); + expect(user.error).toBeDefined(); + expect(user.error.message).toEqual(window.Mock.returnFailRequest); + expect(user.id).not.toBeDefined(); + expect(user.permissions).not.toBeDefined(); + + expect(permCollection).toBeNull(); + }); + }); + + it("when user only has blog permissions, user.permissions should be null", function () { + window.Mock.throwPermissionItems = [{ + "permissions": ["administer_blog", "administer_website", "comment", "create_post", "edit_all_posts", "edit_assets", "edit_categories", "edit_config", "edit_notifications", "edit_tags", "edit_templates", "manage_feedback", "manage_member_blogs", "manage_pages", "manage_themes", "manage_users", "publish_post", "rebuild", "save_image_defaults", "send_notifications", "set_publish_paths", "upload", "view_blog_log"], + "blog": { + "id": "1" + } + }]; + + var cache = require('js/cache'); + var getUser = require('js/mtapi/user'); + var dfd = getUser(); + var user, flag, permCollection; + runs(function () { + dfd.done(function (resp) { + user = resp; + permCollection = cache.get('user', 'perms'); + flag = true; + }); + }); + + waitsFor(function () { + return flag; + }, 'get user with js/mtapi/user', 3000); + + runs(function () { + expect(user).toBeDefined(); + expect(user.id).toEqual(window.Mock.throwUserItem.id); + expect(user.language).toEqual(window.Mock.throwUserItem.language); + expect(user.displayName).toEqual(window.Mock.throwUserItem.displayName); + expect(user.permissions).toBeNull(); + + expect(permCollection).toBeDefined(); + expect(permCollection.totalResults).toEqual(window.Mock.throwPermissionItems.length); + }); + }); + + it("when permission request failed, get user request should be failed", function () { + window.Mock.failPermission = 'Failed to get permissions'; + + var cache = require('js/cache'); + var getUser = require('js/mtapi/user'); + var dfd = getUser(); + spyOn(dfd, 'fail').andCallThrough(); + + var user, flag, permCollection; + runs(function () { + dfd.done(function (resp) { + user = resp; + permCollection = cache.get('user', 'perms'); + flag = true; + }); + dfd.fail(function (resp) { + user = resp; + permCollection = cache.get('user', 'perms'); + flag = true; + }) + }); + + waitsFor(function () { + return flag; + }, 'get user with js/mtapi/user', 3000); + + runs(function () { + expect(dfd.fail).toHaveBeenCalled(); + expect(user.error).toBeDefined(); + expect(user.error.message).toEqual(window.Mock.failPermission) + expect(user.id).not.toBeDefined(); + expect(user.permissions).not.toBeDefined(); + + expect(permCollection).toBeNull(); + }); + }); + }); + + afterEach(function () { + window.Mock.throwUserItem = null; + window.Mock.throwPermissionItems = null; + window.Mock.returnFailRequest = null; + window.Mock.alwaysFail = null; + window.Mock.failPermission = null; + }); +}); diff --git a/pool/shard000/JavaScript/0003681_Application.js b/pool/shard000/JavaScript/0003681_Application.js new file mode 100644 index 0000000000000000000000000000000000000000..cd8287c9739e2267ea0e5f0ab42fd475a66c0cba --- /dev/null +++ b/pool/shard000/JavaScript/0003681_Application.js @@ -0,0 +1,146 @@ +var React = require('react'); +var assign = require('object-assign'); + +var Constants = require('./constants/AppConstants'); + +var NAVIGATOR = Constants.Types.NAVIGATOR; +var SETTINGS = Constants.Types.SETTINGS; +var AUTH = Constants.Types.AUTH; +var USERS = Constants.Types.USERS; +var GUEST_ID = Constants.DataStates.GUEST_ID; + + +/* Constructor */ +function App(props, context) { + React.Component.call(this, props); + + this.handleChange = this.handleChange.bind(this); + this.navigate = this.navigate.bind(this); + this.buildHref = this.buildHref.bind(this); + + this.state = this.selectState(props, context); +} +App.prototype = Object.create(React.Component.prototype); +App.prototype.constructor = App; + + +/* Statics */ +App.propTypes = { + api: React.PropTypes.object, + action: React.PropTypes.object.isRequired, + router: React.PropTypes.object.isRequired, + container: React.PropTypes.object.isRequired +}; + +App.childContextTypes = { + api: React.PropTypes.object, + navigate: React.PropTypes.func, + buildHref: React.PropTypes.func, + container: React.PropTypes.object +}; + + +/* Members */ +assign(App.prototype, { + getChildContext: function() { + return { + api: this.props.api, + navigate: this.navigate, + buildHref: this.buildHref, + container: this.props.container + } + }, + + componentDidMount: function() { + this.subKey = this.props.container.subscribe([AUTH, SETTINGS], this.handleChange); + }, + + componentWillUnmount: function() { + this.props.container.unsubscribe(this.subKey); + }, + + handleChange: function() { + this.setState(this.selectState(this.props, this.context)); + }, + + selectState: function(props, context) { + var state = props.container.getState([SETTINGS, AUTH, USERS]); + var currentUser; + + if (state[AUTH].get('loginStatus')) { + currentUser = state[USERS][state[AUTH].get('currentUser')]; + } + else { + currentUser = { _id: GUEST_ID }; + } + + return { + settings: state[SETTINGS], + currentUser: currentUser + }; + }, + + render: function() { + var action = this.props.action; + var handler = React.createElement(getHandler(action), action); + var Layout = getLayout(action); + + return React.createElement("div", {className: "app-root"}, + React.createElement(Layout, { + action: action, + settings: this.state.settings, + currentUser: this.state.currentUser + }, handler) + ); + }, + + navigate: function(target, reload) { + if (typeof target === 'string') { + this.props.container.action(NAVIGATOR, 'gotoUrl', [target, reload]); + } + else if (target && target.action) { + var href = this.buildHref(target); + + this.props.container.action(NAVIGATOR, 'gotoUrl', [href, reload]); + } + }, + + buildHref: function(config) { + return this.props.router.buildHref(config); + } +}); + +module.exports = App; + +function getHandler(action) { + // Not found page pls + var handler = require('./pages/MainPage'); + + switch(action.action) { + case 'MainPage': + handler = require('./pages/MainPage'); + break; + case 'ArticlePage': + handler = require('./pages/ArticlePage'); + break; + case 'LoginPage': + handler = require('./pages/LoginPage'); + break; + case 'RegisterPage': + handler = require('./pages/RegisterPage'); + break; + case 'LogoutPage': + handler = require('./pages/LogoutPage'); + break; + } + + return handler; +} + +var getLayout = function(action) { + var Layout = require('./layouts/MainLayout'); + + // Switch by action layout + + return Layout; +} diff --git a/pool/shard000/JavaScript/0003682_search-list.js b/pool/shard000/JavaScript/0003682_search-list.js new file mode 100644 index 0000000000000000000000000000000000000000..171d542be4a0717047a3f126a490881ddc0ee003 --- /dev/null +++ b/pool/shard000/JavaScript/0003682_search-list.js @@ -0,0 +1,159 @@ +/** + * 绑定搜索列表 + * .binder-search-list + * 表单里面支持配置数据: + * data-target :数据显示区域,jquery selector,,默认就是当前的binder-search-lis + * data-tpl : 对应模板文件 + * data-key : 对应的数据key,默认就是data + * data-callback :默认的操作执行完毕之后所需要的执行的callback方法。 + * data-first-load : false | true , 第一页页面出现后是否加载。默认不加载 + * + * 表单里面输入框支持的class属性 + * .binder-enter-key: 绑定回车事件 + * .no-binder : 不绑定change事件 + */ +var G_BIND_SEARCH_LIST_BEFORE_LOADING = 'G_BIND_SEARCH_LIST_BEFORE_LOADING'; +var G_BIND_SEARCH_LIST_LOAD_SUCC = 'G_BIND_SEARCH_LIST_LOAD_SUCC'; + +(function(){ + var defaultOptions = { + firstLoad : false, + key : 'data', + emptyTip : '没有合适数据' + } + var searchIdKey = "binder-search-id"; + var id = 0; + /** + * + * @param options + * { + * form : // 对应的表单 + * } + * @constructor + */ + var SearchListBinder = function(obj,options){ + Q.extend(options,defaultOptions); + + this.jDom = $(obj); + this.jDom.data(searchIdKey,searchIdKey + (id++)); // 记住id + this.options = options; + this.jTarget = $(options.target); + if(this.jTarget.length==0) + this.jTarget = this.jDom; + + this.jTemplate = this.jTarget.find('.binder-template'); + this.tplId = options.tpl; + this.showPage = this.jTarget.find('.binder-pager').length>0; + this.key = options.key; + this.callback = options.callback; + + + var that = this; + this.jTemplate.css('position','relative'); + + this.jDom.submit(function(){ + var formDataStr = that.jDom.serialize(); + + var url = window.encodeURIComponent(that.jDom.attr('action')); +console.log(that.jDom.attr('action')); + // 广播 + Q.notify.broadcast(G_BIND_SEARCH_LIST_BEFORE_LOADING,{ + jDom : this.jDom + }); + that.jTemplate.append('
    '); + Q.proxy(url,formDataStr,that.tplId,function(data){ + that.jTarget.find('.absolute-loading').remove(); + + var renderData = {} + renderData[that.key] = data.data; + // 后台返回数据有分页则返回record字段,否则只有data字段 + if((data.data.record && data.data.record.length == 0) || (data.data && data.data.length == 0)){ + // 没有数据 + that.jTemplate.html('
    '+that.options.emptyTip+'
    '); + that.jTarget.find('.binder-pager').html(''); + }else { + var html = template.render(that.tplId, renderData); + that.jTemplate.html(html); + + // 刷新分页 + if (that.showPage) { + that.jTarget.find('.binder-pager').html(Q.widget.page.createPage(data.data)); + // 绑定1个id + that.jTarget.find('.binder-pager').data(searchIdKey,that.jDom.data(searchIdKey)); + } + } + + // 重设当前页分页隐藏域的值,这样在重新搜索的时候才能从第一页开始 + that.jDom.find('input[name="pageno"]').val(1); + + // 广播 + Q.notify.broadcast(G_BIND_SEARCH_LIST_LOAD_SUCC,{ + jDom : that.jDom, + "data" : data + }); + if(that.callback) + window[that.callback](renderData) + },function(){ + that.jTemplate.find('.absolute-loading').remove(); + }); + + //拦截submit表单提交 + return false; + }); + + this.jDom.find('input,select,textarea').live('change',function(){ + var jThis = $(this); + // no-binder。binder-enter-key 2个样式不直接引发sumbit + if(jThis.hasClass("no-binder") || jThis.hasClass("binder-enter-key")){ + return; + } + + //延迟300毫秒,可能会有其他的时间对form进行操作。确保提交时候form是最终形态 + var tmp = function(){ + return function(){ + that.jDom.submit(); + } + }(); + + setTimeout(tmp, 300) + }); + + // 如果分页组件不在jDom中,需要绑定分页组件 + if(this.jDom.find('input[name="pageno"]').length == 0){ + // 创建1个分页隐藏域 + this.jDom.append(''); + // 监听组件 + that.jTarget.find('.binder-pager input[name="pageno"]').live('change',function(e){ + if(that.jTarget.find('.binder-pager').data(searchIdKey) != that.jDom.data(searchIdKey)){ + // 非当前表单 + return; + } + // 组织冒泡,防止其他的绑定了该事件 + e.stopPropagation(); + that.jDom.find('input[name="pageno"]').val(this.value).change(); + }); + } + // 监听回车事件 + this.jDom.find('.binder-enter-key').bind('keyup',function(e){ + if(e.keyCode == 13){ + that.jDom.submit(); + return false; + } + }); + + // 是否需要第一次加载 + if(options.firstLoad){ + this.jDom.submit(); + } + return this; + }; + + $(document).ready(function(){ + // 自动绑定所有列表 + $('.binder-search-list').each(function(){ + var options = Q.attrWrapOptions(this); + new SearchListBinder(this,options); + }); + }); + +})(); diff --git a/pool/shard000/JavaScript/0003683_jsonpPromise.js b/pool/shard000/JavaScript/0003683_jsonpPromise.js new file mode 100644 index 0000000000000000000000000000000000000000..0120afd9c83d652cb4f85cef18cbc1a4e769352b --- /dev/null +++ b/pool/shard000/JavaScript/0003683_jsonpPromise.js @@ -0,0 +1,43 @@ +const defaultOpts = { + prefix: '__jp', + param: 'callback', + timeout: 30 * 1000 +}; + +const randomID = () => { + return Math.random().toString(16).replace('.', ''); +}; + +const enc = encodeURIComponent; + +function jsonp (url, opts = {}) { + return new Promise((resolve, reject) => { + opts = Object.assign({ name: randomID() }, defaultOpts, opts); + console.log(opts); + + const timer = setTimeout(() => { + reject(new Error('Request timeout.')); + }, opts.timeout); + + const success = (data) => { + clearTimeout(timer); + resolve(data); + }; + + const funcName = opts.prefix + opts.name; + window[ funcName ] = success; + + const script = document.createElement('script'); + script.addEventListener('error', (err) => { + clearTimeout(timer); + console.log(err); + reject(err); + }); + const reqUrl = + url + ( (!url.match(/\?/)) ? '?' : '&' ) + `${ opts.param }=${ enc(funcName) }`; + script.setAttribute('src', reqUrl); + document.head.appendChild(script); + }); +} + +export default jsonp; diff --git a/pool/shard000/JavaScript/0003690_blockgraph.js b/pool/shard000/JavaScript/0003690_blockgraph.js new file mode 100644 index 0000000000000000000000000000000000000000..e7b933b31f92c34910b2c15a94a7ae9d3cdd8d3c --- /dev/null +++ b/pool/shard000/JavaScript/0003690_blockgraph.js @@ -0,0 +1,295 @@ +(function () { + 'use strict'; + + /** + * desc: functions for square blocks created by neighbouring dots + * @author: Vishal Kumar + * E-mail: vishal.rgiit@gmail.com + * Github: vishalok12 + */ + + /** + * contains information about the blocks + */ + function BlockGraph(dotMap) { + var i, j; + var blocks = []; + var upLayerLength, downLayerLength; + + for (i = 0; i < dotMap.length - 1; i++) { + upLayerLength = dotMap[i].length; + downLayerLength = dotMap[i+1].length; + blocks[i] = []; + + for (j = 0; j < Math.min(upLayerLength, downLayerLength) - 1; j++) { + blocks[i][j] = new Block(i, j); + } + } + this.blocks = blocks; + } + + /** + * a square area covered by 4 individual edges + */ + function Block(i, j) { + var attr = {}; + attr.top = null; + attr.bottom = null; + attr.left = null; + attr.right = null; + attr.selected = 0; + attr.userAcquired = null; + this._attr = attr; + this._row = i; + this._column = j; + } + + /** + * get the attribute value + * @param {String} attr + * @return {*} value of attr + */ + Block.prototype.get = function(attr) { + if (this._attr.hasOwnProperty(attr)) { + return this._attr[attr]; + } + }; + + /** + * set the value of the block attribute + * @param {String} attr + * @param {*} value + */ + Block.prototype.set = function(attr, value) { + if (this._attr.hasOwnProperty(attr)) { + if (this._row === 0 && this._column === 1) console.log(attr); + this._attr[attr] = value; + if (['top', 'bottom', 'left', 'right'].indexOf(attr) > -1) { + this._attr.selected += 1; + } + } else { + throw new Error(attr + ' is not defined in object'); + } + }; + + /** + * get whether the block has all the edges selected + * @return {Boolean} acquired + */ + Block.prototype.acquired = function() { + if (this.get('selected') === 4) { + return true; + } + + return false; + } + + /** + * get whether the edge is selected + * @param {Object|Number} row1 {row: row1, column: coln1} in case of object + * @param {Object|Number} coln1 {row: row2, column: coln2} in case of object + * @param {Number|undefined} row2 + * @param {Number|undefined} coln2 + * @return {Boolean} selected + */ + BlockGraph.prototype.isEdgeSelected = function(row1, coln1, row2, coln2) { + if (typeof row1 === 'object') { + var sourceIndex = row1; + var destIndex = coln1; + row1 = sourceIndex.row; + coln1 = sourceIndex.column; + row2 = destIndex.row; + coln2 = destIndex.column; + } + var minRow = Math.min(row1, row2); + var minColn = Math.min(coln1, coln2); + var blocks = this.blocks; + + // find the block the edge belongs to + if (minRow < blocks.length) { + var blocksRow = blocks[minRow]; + if (minColn < blocksRow.length) { + if (row1 - row2) { + return blocks[minRow][minColn].get('left'); + } else { + return blocks[minRow][minColn].get('top'); + } + } else { + return blocks[minRow][minColn - 1].get('right'); + } + } else { + return blocks[minRow - 1][minColn].get('bottom'); + } + }; + + /** + * mark the edge as selected + * @param {Object} sourceIndex {row: rowIndex, column: columnIndex} + * @param {Object} destIndex + * @return {Boolean} acquired true if a block is captured by player + */ + BlockGraph.prototype.addToBlockData = function(sourceIndex, destIndex) { + var row, column; + var blocks = this.blocks; + var numOfBlocksAquired = 0; + + // get the blocks the edge belongs to + if (sourceIndex.row === destIndex.row) { + row = sourceIndex.row; + column = Math.min(sourceIndex.column, destIndex.column); + if (row < blocks.length) { + blocks[row][column].set('top', 1); + if (blocks[row][column].acquired()) { + numOfBlocksAquired++; + blocks[row][column].set('userAcquired', vApp.moveEnabled); + } + } + if (row > 0) { + blocks[row - 1][column].set('bottom', 1); + if (blocks[row - 1][column].acquired()) { + numOfBlocksAquired++; + blocks[row - 1][column].set('userAcquired', vApp.moveEnabled); + } + } + } else if (sourceIndex.column === destIndex.column) { + row = Math.min(sourceIndex.row, destIndex.row); + column = sourceIndex.column; + if (column < blocks[row].length) { + blocks[row][column].set('left', 1); + if (blocks[row][column].acquired()) { + numOfBlocksAquired++; + blocks[row][column].set('userAcquired', vApp.moveEnabled); + } + } + if (column > 0) { + blocks[row][column - 1].set('right', 1); + if (blocks[row][column - 1].acquired()) { + numOfBlocksAquired++; + blocks[row][column - 1].set('userAcquired', vApp.moveEnabled); + } + } + } + + // log the last turn + vApp.lastTurn = { + sourceIndex: sourceIndex, + destIndex: destIndex + } + + return numOfBlocksAquired; + }; + + /** + * returns the blocks which contains the edge passed in parameter + * @param {Object} dotIndex1 + * @param {Object} dotIndex2 + * @param {Boolean} options.acquired + * @return {Array.} blocks + */ + BlockGraph.prototype.getNeighbourBlocks = function(dotIndex1, dotIndex2, options) { + var nBlocks = []; + var blocks = this.blocks; + var minRow = Math.min(dotIndex1.row, dotIndex2.row); + var minColn = Math.min(dotIndex1.column, dotIndex2.column); + + if (minRow < blocks.length && minColn < blocks[minRow].length) { + nBlocks.push(blocks[minRow][minColn]); + } + if (dotIndex1.row === dotIndex2.row && // rows of the two dots are same + minRow > 0) { + nBlocks.push(blocks[minRow - 1][minColn]); + } else if (dotIndex1.column === dotIndex2.column && // columns of the two dots are same + minColn > 0) { + nBlocks.push(blocks[minRow][minColn - 1]); + } + + if (options) { + if(!options.acquired) { + nBlocks = nBlocks.filter(function(block) { + return !block.acquired(); + }); + } + if (options.otherThan) { + nBlocks = nBlocks.filter(function(block) { + return !(_.isEqual(block, options.otherThan)); + }); + } + } + + return nBlocks; + }; + + /** + * get all the unselected edges of a block + * @param {Block} block + * @param {Array.} edges + */ + BlockGraph.prototype.unselectedEdges = function(block) { + var edges = []; + // get all the edges with the value null + if (block.get('top') === null) { + edges.push({ + sourceIndex: {row: block._row, column: block._column}, + destIndex: {row: block._row, column: block._column + 1} + }); + } + if (block.get('bottom') === null) { + edges.push({ + sourceIndex: {row: block._row + 1, column: block._column}, + destIndex: {row: block._row + 1, column: block._column + 1} + }); + } + if (block.get('left') === null) { + edges.push({ + sourceIndex: {row: block._row, column: block._column}, + destIndex: {row: block._row + 1, column: block._column} + }); + } + if (block.get('right') === null) { + edges.push({ + sourceIndex: {row: block._row, column: block._column + 1}, + destIndex: {row: block._row + 1, column: block._column + 1} + }); + } + return edges; + } + + /** + * get the sides in the graph which follows the condition passed + * @param {Integer} minDrawnEdges minimum selected edge in block + * @param {Integer} maxDrawnEdges maximum selected edge in block + */ + BlockGraph.prototype.sidesInBlock = function(minDrawnEdges, maxDrawnEdges) { + var blocks = this.blocks; + var row, column; + var blocksRow, block; + var drawnSidesCount; + var acceptedEdges = [], unselectedEdges; + var that = this; + + for (row = 0; row < blocks.length; row++) { + blocksRow = blocks[row]; + + for (column = 0; column < blocksRow.length; column++) { + block = blocksRow[column]; + drawnSidesCount = block.get('selected'); + + if (drawnSidesCount <= maxDrawnEdges && drawnSidesCount >= minDrawnEdges) { + unselectedEdges = this.unselectedEdges(block); + acceptedEdges = acceptedEdges.concat(unselectedEdges.filter(function(edge) { + var nBlocks = that.getNeighbourBlocks(edge.sourceIndex, edge.destIndex); + return nBlocks.every(function(block) { + var selectedEdges = block.get('selected'); + return selectedEdges <= maxDrawnEdges && + selectedEdges >= minDrawnEdges; + }); + })); + } + } + } + return acceptedEdges; + }; + + window.vBlockGraph = BlockGraph; + +})(); diff --git a/pool/shard000/JavaScript/0003693_browsersync.js b/pool/shard000/JavaScript/0003693_browsersync.js new file mode 100644 index 0000000000000000000000000000000000000000..f6932ba882185af7cf2041d80a387448e3842238 --- /dev/null +++ b/pool/shard000/JavaScript/0003693_browsersync.js @@ -0,0 +1,73 @@ + + +// IN THE DOGBOX AS WAS KILLING THE BROWSER +var gulp = require('gulp'); +var browserSync = require('browser-sync'); +var reload = browserSync.reload; + + +var cfg = require('../config/gulp'); + +// Watch Files For Changes & Reload +gulp.task('serve', ['scriptsAngular'], function () { + browserSync({ + notify: false, + // Run as an https by uncommenting 'https: true' + // Note: this uses an unsigned certificate which on first access + // will present a certificate warning in the browser. + // https: true, + server: { + baseDir: ['build'] + } + }); + + // gulp.watch('build/assets/js/**').on('change', function(file) { + // server.changed(file.path); + // watch for browserify change app.js + gulp.watch( + cfg.uri[cfg.siteBuild].watchJS, + { maxListeners: 999999 }, + ['browserifyAngular', reload] + ); + + // Watch for new styles + gulp.watch(cfg.common.styles, { maxListeners: 999999 }, ['styles', reload ]); + + // Watch src js files should be updated with watchify + // gulp.watch(cfg.common.appScripts, ['scripts', reload]); + // Watch test.spec.js files + // gulp.watch('./build/assets/js/app.js', [reload]); + // Watch templates + gulp.watch(cfg.common.html, { maxListeners: 999999 }, ['scriptsAngular', reload]); + // Watch images + gulp.watch(cfg.common.images, { maxListeners: 999999 }, ['images', reload]); + // Watch others assets, pretty fast so grouped + gulp.watch([ + cfg.uri[cfg.siteBuild].fonts, + cfg.uri[cfg.siteBuild].meta, + cfg.uri[cfg.siteBuild].icons + ], + { maxListeners: 999999 }, + ['assets']); + + gulp.watch(cfg.uri[cfg.siteBuild].indexHtml, ['indexHtml', reload]); + + // Watch for new content + gulp.watch( + cfg.uri[cfg.siteBuild].contentDir + '/**/*', + { maxListeners: 999999 }, + ['fetchContent', 'sheets', reload] + ); + + // Watch for new content + gulp.watch([ + cfg.common.markdown, + cfg.common.buildHelpers, + cfg.uri[cfg.siteBuild].templates + '**/*' + ], + [ + 'metalsmith', reload + ] + ); + +}); diff --git a/pool/shard000/JavaScript/0003696_sidebar.controller.spec.js b/pool/shard000/JavaScript/0003696_sidebar.controller.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..4a088ea70f0614f795f40989eeebf8f16af68343 --- /dev/null +++ b/pool/shard000/JavaScript/0003696_sidebar.controller.spec.js @@ -0,0 +1,43 @@ +/* jshint -W117, -W030 */ +describe('layout', function () { + describe('SidebarController', function () { + var controller, + di, + view1 = 'app/products/products.html'; + + beforeEach(function() { + module('app', specHelper.fakeLogger); + specHelper.injector(function($controller, $httpBackend, $location, $rootScope, + $state, $templateCache, productsService) {}); + di = function di() { + $rootScope.$digest(); + }; + }); + + beforeEach(function () { + controller = $controller('SidebarController'); + $templateCache.put(view1, ''); + }); + + // it('should have a base attribute for / to return `true`', function () { + // $location.path('/'); + // di(); + // expect(controller.isCurrent($state.current)).to.be.true; + // }); + + // it('should have isCurrent() for non route not return `current`', function () { + // $location.path('/invalid'); + // di(); + // expect(controller.isCurrent({title: 'invalid'})).to.be.false; + // }); + + // it('$broadcast and $stateChangeStart event', function () { + // var toState = { + // hideSidebar: true + // }; + // controller.isCurrent($state.current); + // $rootScope.$broadcast('$stateChangeStart', {}, toState); + // di(); + // }); + }); +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003697_identity.js b/pool/shard000/JavaScript/0003697_identity.js new file mode 100644 index 0000000000000000000000000000000000000000..39350caf49ecdb2042c5cb2ded17ed889fb60ceb --- /dev/null +++ b/pool/shard000/JavaScript/0003697_identity.js @@ -0,0 +1,23 @@ +(function () { + + function identityService($window, UsersResource) { + var user; + if ($window.bootstrappedUserObject) { + user = new UsersResource(); + angular.extend(user, $window.bootstrappedUserObject); + } + return { + currentUser: user, + isAuthenticated: function() { + return !!this.currentUser; + }, + isAuthorizedForRole: function(role) { + return !!this.currentUser && this.currentUser.roles.indexOf(role) > -1; + } + } + } + + angular + .module('app.services') + .factory('identity', ['$window', 'UsersResource', identityService]); +}()); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003700_controller.js b/pool/shard000/JavaScript/0003700_controller.js new file mode 100644 index 0000000000000000000000000000000000000000..aa06ad8a64470077ff5826e95c36145b138c692c --- /dev/null +++ b/pool/shard000/JavaScript/0003700_controller.js @@ -0,0 +1,39 @@ +(function () { + + // Main module + var app = angular.module('odalic-app'); + + // Controller + var currentFolder = $.getPathForRelativePath(''); + app.controller('odalic-chngpasswdcnf-ctrl', function ($scope, rest, $routeParams, $auth) { + + // Initialization + $scope.dataload = {}; + $scope.status = 'default'; + $scope.confirmation = { + alertSuccess: {}, + alertFailure: {} + }; + + // Actions to take upon page load + var token = $routeParams['token']; + + // Send the token + rest.users.password.confirm(token).exec( + // Success + function (response) { + $auth.logout(); + $scope.status = 'success'; + $scope.dataload.show = true; + }, + + // Failure + function (response) { + $scope.status = 'failure'; + $scope.dataload.show = true; + } + ); + + }); + +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003708_gl-group-members-map.js b/pool/shard000/JavaScript/0003708_gl-group-members-map.js new file mode 100644 index 0000000000000000000000000000000000000000..a4d76bc85ad6c9ffd5c9e6da6fb307c96bfb4776 --- /dev/null +++ b/pool/shard000/JavaScript/0003708_gl-group-members-map.js @@ -0,0 +1,94 @@ +jQuery(window).ready(function($){ + + $('#gmw-gl-group-members-map-wrapper').slideToggle('fast', function() { + var glgmMap = new google.maps.Map(document.getElementById('gmw-gl-group-members-map'), { + zoom: 8, + panControl: true, + zoomControl: true, + mapTypeControl: true, + center: new google.maps.LatLng(glgmMapArgs.your_lat, glgmMapArgs.your_lng), + mapTypeId: google.maps.MapTypeId['ROADMAP'] + }); + + var latlngbounds = new google.maps.LatLngBounds(); + + if ( glgmMapArgs.your_lat && glgmMapArgs.your_lng ) { + var yourLocation = new google.maps.LatLng(glgmMapArgs.your_lat, glgmMapArgs.your_lng); + latlngbounds.extend(yourLocation); + + marker = new google.maps.Marker({ + position: new google.maps.LatLng(glgmMapArgs.your_lat, glgmMapArgs.your_lng), + map: glgmMap, + icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png', + }); + } + + var i; + var gmiw = false; + gmMarkers = []; + + for (i = 0; i < glgmGroups.length; i++) { + console.log(glgmGroups[i]); + if ( glgmGroups[i]['latLng'] != undefined ) { + var mapIcon, shadow; + + var groupLocation = new google.maps.LatLng(glgmGroups[i]['latLng'][0]['lat'], glgmGroups[i]['latLng'][0]['long']); + latlngbounds.extend(groupLocation); + + mapIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='+ glgmGroups[i]['mc'] +'|FF776B|000000'; + shadow = 'https://chart.googleapis.com/chart?chst=d_map_pin_shadow'; + + gmMarkers[i] = new google.maps.Marker({ + position: groupLocation, + icon:mapIcon, + map:glgmMap, + shadow: shadow, + id:i + }); + + with ({ gmMarker: gmMarkers[i] }) { + google.maps.event.addListener(gmMarker, 'click', function() { + if (gmiw) { + gmiw.close(); + gmiw = null; + } + gmiw = new google.maps.InfoWindow({ + content: getGMWIContent(gmMarker.id), + }); + gmiw.open(glgmMap, gmMarker); + }); + } + } + } + + glgmMap.fitBounds(latlngbounds); + + if ( glgmGroups.length == 1 && !glgmMapArgs.your_lat ) { + blistener = google.maps.event.addListener( ( glgmMap ), 'bounds_changed', function(event) { + this.setZoom(11); + google.maps.event.removeListener(blistener); + }); + } + + function getGMWIContent(i) { + + var content = ""; + content += '
    '; + content += '
    ' + glgmGroups[i]['avatar'] + '
    '; + content += '
    '; + content += ''; + content += ''; + content += ''; + //if ( glgmMapArgs.units_array != false ) + //content += ''; + content += '
    Address: ' + glgmGroups[i]['latLng'][0]['address'] + '
    Distance: ' + glgmGroups[i]['distance'] + ' ' + glgmMapArgs.units_array['name'] + '
    '; + content += '
    '; + content += '
    '; + return content; + } + }); +}); + + + + \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003709_PluginManager.js b/pool/shard000/JavaScript/0003709_PluginManager.js new file mode 100644 index 0000000000000000000000000000000000000000..def86a36650df9a96c9f50a2d29522adf062ce88 --- /dev/null +++ b/pool/shard000/JavaScript/0003709_PluginManager.js @@ -0,0 +1,146 @@ +/*globals define*/ +/* + * All functions not prepended with an '_' are considered actions callable + * from the commandline. The name of the file is considered the name of the + * item. + * + * This convention is most important bc of the addition of a preprocessing + * function to all these functions in the ComponentManager constructor. + */ + +"use strict"; +var _ = require("lodash"), + R = require("ramda"), + path = require("path"), + exists = require("exists-file"), + rm_rf = require("rimraf"), + fs = require("fs"), + childProcess = require("child_process"), + utils = require("./utils"), + ComponentManager = require("./ComponentManager"), + PluginGenerator = require("./shim/PluginGenerator"), + PluginHelpers = require("./shim/PluginHelpers"), + metadata = require("webgme-engine/src/plugin/coreplugins/PluginGenerator/metadata.json"), + RAW_CONFIG = metadata.configStructure; + +var PluginManager = function (logger) { + ComponentManager.call(this, "plugin", logger); +}; + +_.extend(PluginManager.prototype, ComponentManager.prototype); + +/** + * Functions to create the config flag from the WebGME's + * PluginGenerator options. They are organized by type. + * + * @return {undefined} + */ +PluginManager.prototype._getOptions = function () { + return RAW_CONFIG.map(function (config) { + return PluginHelpers.getConfigValue[config.valueType](config); + }).filter(function (opt) { + return opt.name.indexOf("meta") === -1; + }); +}; + +PluginManager.prototype._parseConfig = function (options) { + var config = PluginHelpers.getConfig(RAW_CONFIG, options); + + // We don't support the meta flag as we don't provide access to any project + config.meta = false; + + // If pluginName was not set in the options, set it to the pluginId + config.pluginName = options.pluginName || options.pluginID; + + return config; +}; + +/** + * Create a new plugin + * + * @param args + * @return {undefined} + */ +PluginManager.prototype.new = function (options, callback) { + // Set the config options from the command line flags + var self = this, + config = this._parseConfig(options), + pluginGenerator = new PluginGenerator(this._logger, config); + + pluginGenerator.main((e) => { + if (e) { + return callback(e); + } + + // Get the src, test paths + var paths = R.mapObjIndexed( + function (empty, type) { + return `${type}/plugins/${config.pluginID}`; + }, + { src: null, test: null } + ); + + // Store the plugin info in the webgme-setup.json file + var pluginConfig = { + src: paths.src, + test: paths.test, + }; + this._register(config.pluginID, pluginConfig); + this._logger.write("Created new plugin at " + paths.src); + // If templates were generated, run `combine_templates` + this._combineTemplates(paths.src, function (err) { + if (err) { + callback(err); + } else { + if ( + options.language && + options.language.toLowerCase() !== "javascript" + ) { + var packageJSON = utils.getPackageJSON(); + + if (!packageJSON.dependencies["webgme-bindings"]) { + packageJSON.dependencies["webgme-bindings"] = "latest"; + utils.writePackageJSON(packageJSON); + } + + self._logger.write( + "Added webgme-bindings to dependencies - do npm install" + ); + } + + callback(null); + } + }); + }); +}; + +PluginManager.prototype._combineTemplates = function (srcPath, callback) { + var root = utils.getRootPath(), + scriptDir = path.join(root, srcPath, "Templates"), + scriptPath = path.join(scriptDir, "combine_templates.js"), + job; + + if (exists(scriptPath)) { + job = childProcess.fork(scriptPath, [], { + cwd: scriptDir, + silent: true, + }); + this._logger.write('running "combine_templates"...'); + this._logger.writeStream(job.stdout); + this._logger.errorStream(job.stderr); + + job.on("close", (code) => { + var err = null; + if (code !== 0) { + // Failure... + err = `Could not combine templates for plugin`; + this._logger.error(err); + } + callback(err); + }); + } else { + callback(null); + } +}; + +module.exports = PluginManager; diff --git a/pool/shard000/JavaScript/0003710_reader_send_email.js b/pool/shard000/JavaScript/0003710_reader_send_email.js new file mode 100644 index 0000000000000000000000000000000000000000..9bedaf7840e674a0ac336d524cc74e0777ee86d6 --- /dev/null +++ b/pool/shard000/JavaScript/0003710_reader_send_email.js @@ -0,0 +1,257 @@ +NEWSBLUR.ReaderSendEmail = function(story, options) { + var defaults = {}; + + _.bindAll(this, 'close', 'save_callback', 'error'); + + this.options = $.extend({}, defaults, options); + this.model = NEWSBLUR.assets; + this.story = story; + this.feed_id = this.story.get('story_feed_id'); + this.feed = this.model.get_feed(this.feed_id); + + this.runner(); +}; + +NEWSBLUR.ReaderSendEmail.prototype = new NEWSBLUR.Modal; + +_.extend(NEWSBLUR.ReaderSendEmail.prototype, { + + runner: function() { + _.bindAll(this, 'save'); + this.options.onOpen = _.bind(function() { + $('input[name=to]', this.$modal).focus(); + }, this); + this.make_modal(); + this.open_modal(); + this.existing_emails = $.evalJSON($.cookie('NB:email:addresses')) || []; + this.autocomplete_emails(); + + if (!NEWSBLUR.Globals.is_authenticated) { + this.save_callback({'code': -1, 'message': '你必须登录之后才能通过邮件发送文章。'}); + } + + this.$modal.bind('click', $.rescope(this.handle_click, this)); + $('input, textarea', this.$modal).bind('keydown', 'ctrl+return', this.save); + $('input, textarea', this.$modal).bind('keydown', 'meta+return', this.save); + }, + + make_modal: function() { + var self = this; + + this.$modal = $.make('div', { className: 'NB-modal-email NB-modal' }, [ + $.make('span', { className: 'NB-modal-loading NB-spinner'}), + $.make('div', { className: 'NB-modal-error'}), + $.make('h2', { className: 'NB-modal-title' }, '通过邮件发送文章'), + $.make('h2', { className: 'NB-modal-subtitle' }, [ + (this.feed && $.make('div', { className: 'NB-modal-email-feed' }, [ + $.make('img', { className: 'NB-modal-feed-image feed_favicon', src: $.favicon(this.feed) }), + $.make('div', { className: 'NB-modal-feed-title' }, this.feed.get('feed_title')) + ])), + $.make('div', { className: 'NB-modal-email-story-title' }, this.story.story_title), + $.make('div', { className: 'NB-modal-email-story-permalink' }, this.story.story_permalink) + ]), + $.make('div', { className: 'NB-modal-email-to-container' }, [ + $.make('label', { 'for': 'NB-send-email-to' }, [ + ' 接收方邮件地址:' + ]), + $.make('input', { className: 'NB-input NB-modal-to', name: 'to', id: 'NB-send-email-to', value: + ($.cookie('NB:email:to') || "") }) + ]), + $.make('div', { className: 'NB-modal-email-explanation' }, [ + "您可以选择添加一段评论,此评论会显示在文章的上方。" + ]), + $.make('div', { className: 'NB-modal-email-comments-container' }, [ + $.make('textarea', { className: 'NB-modal-email-comments' }) + ]), + $.make('div', { className: 'NB-modal-email-from-container' }, [ + $.make('div', [ + $.make('label', { 'for': 'NB-send-email-from-name' }, [ + ' 你的姓名:' + ]), + $.make('input', { className: 'NB-input NB-modal-email-from', name: 'from_name', id: 'NB-send-email-from-name', value: this.model.preference('full_name') || NEWSBLUR.Globals.username || '' }) + ]), + $.make('div', { style: 'margin-top: 8px' }, [ + $.make('label', { 'for': 'NB-send-email-from-email' }, [ + ' 你的邮箱:' + ]), + $.make('input', { className: 'NB-input NB-modal-email-from', name: 'from_email', id: 'NB-send-email-from-email', value: NEWSBLUR.Globals.email || this.model.preference('email') || '' }) + ]), + $.make('div', { style: 'margin-top: 8px' }, [ + $.make('label', { 'for': 'NB-send-email-cc' }, [ + ' CC 我:' + ]), + $.make('div', { className: 'NB-modal-email-cc-wrapper' }, [ + $.make('input', { className: 'NB-modal-email-cc', name: 'email_cc', id: 'NB-send-email-cc', type: "checkbox", checked: this.model.preference('email_cc') }), + $.make('label', { 'for': 'NB-send-email-cc' }, [ + "给我发送一封此邮件的拷贝" + ]) + ]) + ]) + ]), + $.make('form', { className: 'NB-recommend-form' }, [ + $.make('div', { className: 'NB-error' }), + $.make('div', { className: 'NB-modal-submit' }, [ + $.make('input', { type: 'submit', className: 'NB-modal-submit-button NB-modal-submit-green', value: '发送文章' }), + ' 或 ', + $.make('a', { href: '#', className: 'NB-modal-emailclient' }, '在邮件客户端中打开') + ]) + ]) + ]); + }, + + save: function(e) { + var from_name = $('input[name=from_name]', this.$modal).val(); + var from_email = $('input[name=from_email]', this.$modal).val(); + var to = $('input[name=to]', this.$modal).val(); + var email_cc = $('input[name=email_cc]', this.$modal).is(":checked"); + var comments = $('textarea', this.$modal).val(); + var $save = $('input[type=submit]', this.$modal); + var $error = $('.NB-modal-error', this.$modal); + + $error.hide(); + $save.addClass('NB-disabled').val('Sending...'); + $('.NB-modal-loading', this.$modal).addClass('NB-active'); + this.model.preference('full_name', from_name); + this.model.preference('email', from_email); + this.model.preference('email_cc', email_cc); + $('.NB-error', this.$modal).fadeOut(500); + + this.model.send_story_email({ + story_id : this.story.id, + feed_id : this.feed_id, + from_name : from_name, + from_email : from_email, + email_cc : email_cc, + to : to, + comments : comments + }, this.save_callback, this.error); + }, + + save_callback: function(data) { + var $save = $('input[type=submit]', this.$modal); + if (!data || data.code < 0) { + $('.NB-error', this.$modal).html(data.message).fadeIn(500); + $('.NB-modal-loading', this.$modal).removeClass('NB-active'); + $save.removeClass('NB-disabled').val('Send this story'); + } else { + $save.val('Sent!'); + $.cookie('NB:email:to', $('input[name=to]', this.$modal).val()); + var emails = $('input[name=to]', this.$modal).val(); + emails = emails.replace(/[, ]+/g, ' ').split(' '); + emails = _.uniq(this.existing_emails.concat(emails)); + emails = _.map(emails, function(e) { return _.string.trim(e); }); + emails = _.compact(emails); + $.cookie('NB:email:addresses', $.toJSON(emails), {expires: 365*10}); + this.close(); + } + }, + + error: function(data) { + var $error = $('.NB-modal-error', this.$modal); + var $save = $('input[type=submit]', this.$modal); + $error.show(); + if (!data) { + $error.text("There was a issue on the backend with sending your email. Sorry about this! It has been noted and will be fixed soon. You should probably send this manually now."); + } else { + $('.NB-error', this.$modal).html(data.message).fadeIn(500); + } + $save.removeClass('NB-disabled').val('Send this story'); + $('.NB-modal-loading', this.$modal).removeClass('NB-active'); + }, + + open_email_client: function() { + var from_name = $('input[name=from_name]', this.$modal).val(); + var from_email = $('input[name=from_email]', this.$modal).val(); + var to = $('input[name=to]', this.$modal).val(); + var comments = $('textarea', this.$modal).val(); + + var url = [ + 'mailto:', + to, + '?subject=', + from_name, + ' 给您共享了一篇文章:', + this.story.story_title, + '&body=', + comments, + '%0D%0A%0D%0A--%0D%0A%0D%0A', + this.story.story_permalink, + '%0D%0A%0D%0A', + $(this.story.story_content).text(), + '%0D%0A%0D%0A', + '--', + '%0D%0A%0D%0A', + '通过 NewsZeit.com 共享' + ].join(''); + window.open(url); + }, + + autocomplete_emails: function() { + var $to = $('input[name=to]', this.$modal); + var existing_emails = this.existing_emails; + + var split = function(val) { + return val.split( /,\s*/ ); + }; + var extractLast = function(term) { + return split( term ).pop(); + }; + + $to + // don't navigate away from the field on tab when selecting an item + .bind( "keydown", function( event ) { + if ( event.keyCode === $.ui.keyCode.TAB && + $( this ).data( "ui-autocomplete" ).menu.active ) { + event.preventDefault(); + } + }) + .autocomplete({ + delay: 0, + minLength: 0, + appendTo: '.NB-modal-email', + source: function( request, response ) { + // delegate back to autocomplete, but extract the last term + console.log(["autocomplete", request, request.term, existing_emails]); + response( $.ui.autocomplete.filter( + existing_emails, extractLast( request.term ) ) ); + }, + focus: function() { + // prevent value inserted on focus + return false; + }, + select: function( event, ui ) { + var terms = split( this.value ); + // remove the current input + terms.pop(); + // add the selected item + terms.push( ui.item.value ); + // add placeholder to get the comma-and-space at the end + terms.push( "" ); + this.value = terms.join( ", " ); + return false; + } + }); + }, + + // =========== + // = Actions = + // =========== + + handle_click: function(elem, e) { + var self = this; + + $.targetIs(e, { tagSelector: '.NB-modal-submit-button' }, function($t, $p) { + e.preventDefault(); + + self.save(); + return false; + }); + $.targetIs(e, { tagSelector: '.NB-modal-emailclient' }, function($t, $p) { + e.preventDefault(); + + self.open_email_client(); + return false; + }); + } + +}); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003713_participants.js b/pool/shard000/JavaScript/0003713_participants.js new file mode 100644 index 0000000000000000000000000000000000000000..434bdeb9c89377da89ee0f11ebac412657139044 --- /dev/null +++ b/pool/shard000/JavaScript/0003713_participants.js @@ -0,0 +1,71 @@ +/* + * The MIT License + * Copyright (c) 2014-2016 Nick Guletskii + * + * 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. + */ +const controller = + /* @ngInject*/ + ($scope, $stateParams, $rootScope, $q, users, userCount, ContestService) => { + const updateParticipants = () => { + $q.all({ + users: ContestService.getContestParticipantsPage($stateParams.contestId, + $stateParams.page), + count: ContestService.countContestParticipants($stateParams.contestId) + }) + .then(({ + users, + count + }) => { + $scope.users = users; + $scope.userCount = count; + }); + }; + $rootScope.$on("userTimeExtendedInContest", updateParticipants); + $scope.page = $stateParams.page; + $scope.users = users; + $scope.userCount = userCount; + }; + +export default { + "name": "contestParticipantsList", + "url": "/contest/{contestId:[0-9]+}/participants?userId", + "templateUrl": "/partials/contests/contest/participants.html", + controller, + "params": { + "page": "1" + }, + "resolve": { + "users": (ContestService, $stateParams) => + ContestService.getContestParticipantsPage( + $stateParams.contestId, + $stateParams.page), + "userCount": (ContestService, $stateParams) => + ContestService.countContestParticipants($stateParams.contestId) + }, + "data": { + canAccess: + /* @ngInject*/ + ($refStateParams, PromiseUtils, SecurityService) => + PromiseUtils.and( + SecurityService.hasPermission("approved"), + SecurityService.hasContestPermission($refStateParams.contestId, + "view_participants")) + } +}; diff --git a/pool/shard000/JavaScript/0003717_extensionSvc.js b/pool/shard000/JavaScript/0003717_extensionSvc.js new file mode 100644 index 0000000000000000000000000000000000000000..2eb6d35f5a751aca71f3c6e8050bea49f4d2e55b --- /dev/null +++ b/pool/shard000/JavaScript/0003717_extensionSvc.js @@ -0,0 +1,37 @@ +const getOptionsListeners = []; +const initConverterListeners = []; +const sectionPreviewListeners = []; + +export default { + onGetOptions(listener) { + getOptionsListeners.push(listener); + }, + + onInitConverter(priority, listener) { + initConverterListeners[priority] = listener; + }, + + onSectionPreview(listener) { + sectionPreviewListeners.push(listener); + }, + + getOptions(properties, isCurrentFile) { + return getOptionsListeners.reduce((options, listener) => { + listener(options, properties, isCurrentFile); + return options; + }, {}); + }, + + initConverter(markdown, options) { + // Use forEach as it's a sparsed array + initConverterListeners.forEach((listener) => { + listener(markdown, options); + }); + }, + + sectionPreview(elt, options) { + sectionPreviewListeners.forEach((listener) => { + listener(elt, options); + }); + }, +}; diff --git a/pool/shard000/JavaScript/0003723_Shell.js b/pool/shard000/JavaScript/0003723_Shell.js new file mode 100644 index 0000000000000000000000000000000000000000..8ef004aacf4a39bec089415b6d5c638155b83c0b --- /dev/null +++ b/pool/shard000/JavaScript/0003723_Shell.js @@ -0,0 +1,65 @@ +const Interpreter = require('./Interpreter') +const Filesystem = require('./Filesystem') + +const ENV = require('../configs/environment') + +/** + * Shell Class inherits from Interpreter + * Options: + * - filesystem {Object} + * - commands {Object} + * - env {Object} all extra mocked variables + */ +class Shell extends Interpreter{ + constructor({ filesystem = undefined, commands = undefined, env = {} } = {}) { + super() + + this.polyfills() + + this.Classes = { + Command: require('./Command'), + File: require('./File') + } + + /** + * Create the virtual filesystem + * @return reference to instance of @class Filesystem + */ + this.fs = new Filesystem(filesystem, this) + this.env = { + ...ENV, + ...env + } + + // Init builtin commands, @method in parent + // pass shell reference + this.ShellCommands = this.registerCommands(this) + this.ShellCommands = { + ...this.ShellCommands, + ...this.registerCommands(this, commands), + } + } + + polyfills() { + if (!global.Promise) { + global.Promise = require('promise-polyfill').Promise + } + if (!global.fetch) { + global.fetch = require('whatwg-fetch') + } + return true + } + + /** + * Pass control to Interpreter + * @return [String] OR {Promise} to resolve from your wrapper. + */ + run(cmd) { + return this.exec(cmd) + } +} + +// Object.defineProperty(Shell.prototype, 'fs', { writable: true, enumerable: false }) +// Object.defineProperty(Shell.prototype, 'ShellCommands', { writable: true, enumerable: false }) + +module.exports = Shell diff --git a/pool/shard000/JavaScript/0003727_startup.js b/pool/shard000/JavaScript/0003727_startup.js new file mode 100644 index 0000000000000000000000000000000000000000..9882b477a723435049d184316c8b4aa9f97188e4 --- /dev/null +++ b/pool/shard000/JavaScript/0003727_startup.js @@ -0,0 +1,25 @@ +Meteor.startup(function () { + // Add hosts features for testing + if (Hosts.find().count() === 0 ) { + _.each(hostFixtures, function (host) { + Hosts.insert(host); + }); + } + if (Notifications.find().count() === 0 ) { + _.each(notificationsFixtures, function (notification) { + Notifications.insert(notification); + }); + } + + if (Meteor.isServer) { + Meteor.methods({ + updateHostStatus: function (hostname) { + var url = 'http://' + hostname, + result = Meteor.http.get(url, {timeout: 30000}); + if (result.statusCode === 200) { + return 'ok'; + } + } + }); + } +}); diff --git a/pool/shard000/JavaScript/0003728_toRedshift.js b/pool/shard000/JavaScript/0003728_toRedshift.js new file mode 100644 index 0000000000000000000000000000000000000000..6705d85ca518b2cfe939918a83c1077c8aa3f692 --- /dev/null +++ b/pool/shard000/JavaScript/0003728_toRedshift.js @@ -0,0 +1,125 @@ +var + pg = require('pg'), + AWS = require('aws-sdk'), + uuid = require('uuid'), + src_path = process.env.MODULE_PATH || ".", + readTable = require(src_path+"/readTable"), + rs_username = process.env.RSDB_USERNAME || "imagedb", + rs_password = process.env.RSDB_PASSWORD || "ImageDbuser7", + rs_database = process.env.RSDB_DATABASE || "defaultdb", + debug = "true" == (process.env.APP_DEBUG || "false"), + rs_port = process.env.RSDB_PORT || 5439, + cage = process.env.CAGE || "ci", + customer = process.env.CUSTOMER || "shoppertrak", + rs_host = process.env.RSDB_HOST || "redshift."+cage+"."+customer+".47lining.com", + rsCopy = new Object(); + +function writeDynamoToRedshift(table, callback) { + writeToRedshift("'dynamodb://"+table+"'", "READRATIO 100", callback); +} + +function writeS3ToRedshift(bucketName, key, callback) { + writeToRedshift("'s3://"+bucketName+"/"+key+"'", " JSON 'auto'", callback); +} + +function writeToRedshift(from_str, args, callback) { + var accessKeyId = "", secretAccessKey = ""; + if (AWS.config.credentials == undefined) { + // Now set temporary credentials seeded from the master credentials + AWS.config.credentials = new AWS.EC2MetadataCredentials({ + httpOptions: { timeout: 5000 } // 5 second timeout + }); + AWS.config.credentials.refresh(); + } + accessKeyId = AWS.config.credentials.accessKeyId; + secretAccessKey = AWS.config.credentials.secretAccessKey; + var query = "COPY imageprocessingtable from "+ from_str + +" credentials 'aws_access_key_id="+accessKeyId+";aws_secret_access_key="+secretAccessKey+"' " + + args + +" TIMEFORMAT AS 'YYYY:MM:DD HH:MI:SS' " + ; + var outer_callback = callback; + console.log("Connecting to "+rs_database+" on "+rs_host); + var conString = "postgres://"+rs_username+":"+rs_password+"@"+ + rs_host+":"+rs_port+"/"+rs_database; + + var client = new pg.Client( + { + user: rs_username, + database: rs_database, + password: rs_password, + port: rs_port, + host: rs_host + } + ); + client.connect(function(err) { + if(err) { + return console.error('could not connect to postgres', err); + } + if (debug) console.log("About to run Query: "+query); + client.query(query, "", + function(err, result) { + if (debug) console.log(">>> query callback.. "); + client.end(); + if (err) { + console.log("ERROR: "+err); + } + if (outer_callback) { + if (debug) console.log(">>> outer callback.. "); + outer_callback(err, "All done - don't write database"); + if (debug) console.log("<<< outer callback.. "); + } + if (debug) console.log("<<< query callback.. "); + } + ); + if (debug) console.log("<<< connect callback.. "); + }); + + if (debug) console.log("<<< writeToRedshift"); +} + +function writeToS3(dynamo_data, callback) { + // N.B. this might take a wad of memory all items and strings - + // TODO look at stream implementation + bucketName = 'dynamo-archive-'+uuid.v4(); + console.log(">>> writingTo S3 bucket "+bucketName+", rows: "+dynamo_data.length); + var output_data = ""; + for (i = 0; i < dynamo_data.length; i++) { + output_data = output_data + JSON.stringify(dynamo_data[i].attrs); + } + var s3 = new AWS.S3(); + s3.createBucket({Bucket: bucketName}, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else { + // console.log(">>> s3.upload.. "); + s3.putObject({Bucket: bucketName, Body: output_data, Key: 'imageproc.json'}, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else { + writeToRedshift(bucketName, 'imageproc.json', callback); + } + }); + } + }); +} + +rsCopy.copyDynamoToRedshiftViaS3 = function(region, dyn_tablename, query_data, callback) { + if (debug) console.log(">>> copyToRedshiftViaS3: "+dyn_tablename); + AWS.config.update({ region: region }); + readTable.scanMetadata(dyn_tablename, + function(err, data) { + if (err) { + console.log(err); + callback(err); + return; + } + writeToS3(data.Items, callback); + } + ); +}; + +rsCopy.copyDynamoToRedshift = function(region, dyn_tablename, query_data, callback) { + if (debug) console.log(">>> copyToRedshift: "+dyn_tablename); + AWS.config.update({ region: region }); + writeDynamoToRedshift(dyn_tablename, callback); +}; +module.exports=rsCopy; diff --git a/pool/shard000/JavaScript/0003730_projectClassifyCtrl.js b/pool/shard000/JavaScript/0003730_projectClassifyCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..c442202be5960ea983428f79dfb61772e56acd8d --- /dev/null +++ b/pool/shard000/JavaScript/0003730_projectClassifyCtrl.js @@ -0,0 +1,87 @@ +app.controller('ProjectClassifyCtrl', function($scope, $state, $stateParams, bugPage, DiffService) { + angular.extend($scope, bugPage); + $scope.changedFiles = []; + $scope.currentBug = null; + $scope.bugKeyUrl = null; + $scope.classificationHasChanged = false; + $scope.classification = { + 'bug': null, + 'user': null, + 'lineChangeClassifications': [] + }; + $scope.sendClassificationFn = debounce(function() { + console.log('about to send classification'); + }, 500); + + if ($stateParams.bug) { + $scope.bugKeyUrl = $stateParams.bug; + for (var i = 0; i < $scope.bugs.length; i++) { + if ($scope.bugs[i].key == $scope.bugKeyUrl) { + var bug = $scope.bugs[i]; + $scope.currentBug = bug; + + DiffService.computeDiff(bug, function(result) { + angular.extend($scope, result); + }); + } + } + } + + $scope.classify = function(change, classificationForm) { + console.log('in classify'); + var elementFound = false; + var lineChange; + + if (change.deletion !== null) { + lineChange = change.deletion; + } else { + lineChange = change.addition; + } + + var newLineChangeClassification = { + 'lineChange': lineChange, + 'classification': null, + 'lineChangeClassificationForm': classificationForm + }; + + for (var i = 0; i < $scope.classification.lineChangeClassifications.length; i++) { + var lineChangeClassification = $scope.classification.lineChangeClassifications[i]; + + if (lineChangeClassification.lineChange.oldLineNumber == lineChange.oldLineNumber) { + elementFound = true; + $scope.classification.lineChangeClassifications[i] = newLineChangeClassification; + } + } + + if (!elementFound) { + $scope.classification.lineChangeClassifications.push(newLineChangeClassification); + } + + $scope.sendClassificationFn(); + }; + + $scope.$watch('data.currentPage', function(newPage, oldPage) { + if (newPage !== oldPage) { + $state.transitionTo('project.classify', {name: $stateParams.name, page: $scope.data.currentPage}, {reload: true}); + } + }); + + $scope.setCurrentBug = function(bug) { + $state.transitionTo('project.classify', {name: $stateParams.name, page: $scope.data.currentPage, bug: bug.key}, {reload: true}); + }; + + function debounce(func, wait, immediate) { + var timeout; + return function() { + var context = this, args = arguments; + var later = function() { + timeout = null; + if (!immediate) func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) func.apply(context, args); + }; + } +}); diff --git a/pool/shard000/JavaScript/0003732_deals.js b/pool/shard000/JavaScript/0003732_deals.js new file mode 100644 index 0000000000000000000000000000000000000000..033b8cd3edcd89a3dfb1a9024653e9c6f31d627b --- /dev/null +++ b/pool/shard000/JavaScript/0003732_deals.js @@ -0,0 +1,213 @@ +var pageSize = DEFAULT_PAGE_SIZE; +var currPageNumber = 0; + +var dealSortDirection = false; +var dealOrderBy = DEFAULT_DEALS_SORT_FIELD; + +$(document).ready(function() { + $('#endDate, #create_tender_enddate').datepicker({ + format: 'mm-dd-yyyy', + startDate: '-5y' + }); + + $('#pagination_dealsnum').on('change', function() { + pageSize = this.value; + currPageNumber = 0; + showDealsPage(currPageNumber); + }); + + showDeals(); + $('#search_deals').keypress(function(e) { + if (e.keyCode == ENTER_BUTTON_CODE) { + pageSize = $('#pagination_dealsnum').val(); + currPageNumber = 0; + showDealsPage(currPageNumber); + return false; + } + }); + + $("#deal_title").click(function(){ + sortDeals("proposal.tender.title","deal_title"); + }); + + $("#deal_date").click(function(){ + sortDeals("date","deal_date"); + }); + + $("#deal_status").click(function(){ + sortDeals("status.name","deal_status"); + }); + + $("#deal_sum").click(function(){ + sortDeals("sum","deal_sum"); + }); +}); + +function showDeals() { + var queryParams = ''; + if(getCookie("userRole") != "undefined") { + var userRole = getCookie("userRole"); + queryParams += (queryParams.length==0)?"userRole=" + userRole : "&userRole=" + userRole; + } + + if($('#search_deals').val()!=""){ + queryParams += (queryParams.length==0)?"searchParam="+$('#search_deals').val():"&searchParam="+$('#search_deals').val(); + } + + showDealsPagination(queryParams); + + queryParams += (queryParams.length==0)?"pageSize="+pageSize:"&pageSize="+pageSize; + queryParams += "&pageNumber=" + currPageNumber + "&sortDirection=" + + ((!dealSortDirection)?"desc":"asc") + "&orderBy=" + dealOrderBy; + + $.ajax({ + url: DEALS_URL, + type: "GET", + data: queryParams, + async: false, + dataType:'json', + + success: function(data) { + var html = ''; + var dataSize = data.length; + + if(dataSize > 0) { + for (var i = 0; i < dataSize; i++) { + html += '' + data[i].title + '' + + '' + unixTimeConverter(data[i].date) + '' + + '' + data[i].businessPartner + '' + + '' + data[i].status + '' + + '' + data[i].sum + '' + + '' + + '
    ' + + '' + + '' + + '
    ' + + ''; + } + + $('#deals_user_message').html(''); + $('#deal_items').show(); + $('#deals').html(html); + $('#pagination').show(); + $('.new_deal_notification').html(""); + } else { + $('#deals_user_message').html('

    No deals found

    ').show(); + $('#deal_items').hide(); + $('#pagination').hide(); + } + }, + error:function(){ + alert("ERROR"); + } + }); + + $.ajax({ + url: MYDEALS_DATE_URL, + type: "PUT", + dataType: "json", + async: false, + success:function(data) { + $('.new_deal_notification').html(""); + } + }); +} + +function unixTimeConverter(timestamp){ + var date = new Date(timestamp); + var year = date.getFullYear(); + var month = date.getMonth(); + var day = date.getDate(); + + if(day <= 9) day = "0" + day; + if(month <= 9) month = "0" + month; + + return day + "/" + month + "/" + year; +} + +function closeDeal() { + var str = ''; + str += "statusName=" + DEAL_STATUS; + $.ajax({ + url: DEALS_URL+"/" + $('#close_deal_id').val() + "?" + str, + type: "PUT", + + success: function(data){ + closeDealModalWindow('close_deal_mod_wind'); + showDeals()}, + error: function(){ + alert("Can't close this deal") + } + }) +} + +function writeCloseDealId(id) { + document.getElementById('close_deal_id').value = id; +} + +function closeDealModalWindow(id) { + $('#' + id).modal('hide'); +} + +function showDealsPagination(queryParams) { + $.ajax({ + url: DEALS_NUMBER_URL, + async: false, + type: "GET", + data: queryParams, + dataType:'json', + + success: function(data) { + var dataSize = data; + var pageNumber = Math.ceil(dataSize / pageSize); + + if(dataSize > 0 && pageSize < dataSize) { + var html = ''; + html += '
  • «
  • '; + for(var z=1;z<=pageNumber;z++) { + html += '
  • '+z+'
  • '; + } + html += '
  • »
  • '; + + $('.page_pagination').html(html).show(); + $('#pagination').show(); + + if(currPageNumber != 0) { + document.getElementById('prev_page').setAttribute("onclick", "showDealsPage("+(currPageNumber-1)+");"); + } + + if(currPageNumber != pageNumber-1) { + document.getElementById('next_page').setAttribute("onclick", "showDealsPage("+(currPageNumber+1)+");"); + } + } else { + $('.page_pagination').hide(); + } + }, + error:function(){ + $('#pagination').hide(); + } + }); +} + +function showDealsPage(pageNumber) { + currPageNumber = pageNumber; + showDeals(); +} + +function sortDeals(orderByField, elementId) { + dealSortDirection = (dealOrderBy == orderByField) ? !dealSortDirection : false; + dealOrderBy = orderByField; + + $('#deal_items .sortable').removeClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down'); + if(dealSortDirection == false) { + $('#'+elementId+' .sortable').addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down'); + } else { + $('#'+elementId+' .sortable').addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up'); + } + + showDeals(); +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003735_group-repertories.js b/pool/shard000/JavaScript/0003735_group-repertories.js new file mode 100644 index 0000000000000000000000000000000000000000..fc111aa01fcb3d4541c3a6a4af66c56d08a1029a --- /dev/null +++ b/pool/shard000/JavaScript/0003735_group-repertories.js @@ -0,0 +1,69 @@ +import Component from '@ember/component'; +import { inject as service } from '@ember/service'; +import { sort} from '@ember/object/computed'; +import { computed} from '@ember/object'; +import { task, timeout } from 'ember-concurrency'; +import { denodeify } from 'rsvp' + +export default Component.extend({ + store: service(), + algolia: service(), + currentUser: service(), + customCollapsed: true, + customCollapsed2: true, + customCollapsed4: true, + customCollapsed5: true, + sortedRepertoriesProperties: [ + 'chartTitle', + ], + group: computed( + 'model', function() { + return this.store.findRecord('group', this.model.groupId); + }), + sortedRepertories: sort( + 'group.repertories', + 'sortedRepertoriesProperties' + ), + flashMessages: service(), + searchChart: task(function* (term){ + yield timeout(600); + let func = denodeify(this.algolia.search.bind(this.algolia)) + let res = yield func({ indexName: 'Chart', query: term}) + return res.hits + }), + deleteRepertory: task(function *(repertory) { + try { + yield repertory.destroyRecord(); + this.flashMessages.success("Deleted!"); + } catch(e) { + this.flashMessages.danger("Problem!"); + } + }).drop(), + createRepertoryModal: false, + createRepertoryModalError: false, + saveRepertory: task(function* (c){ + try { + let chart = yield this.store.findRecord('chart', c.objectID) + let repertory = yield this.store.createRecord('repertory', { + chart: chart, + group: this.group, + }).save(); + yield repertory.activate({ + 'by': this.get('currentUser.user.id'), + }); + this.set('createRepertoryModal', false); + this.set('createRepertoryModalError', false); + this.flashMessages.success("Created!"); + } catch(e) { + e.errors.forEach((e) => { + this.set('createRepertoryModalError', true); + this.flashMessages.danger(e.detail); + }) + } + }).drop(), + actions: { + cancelRepertory(repertory){ + repertory.deleteRecord(); + }, + } +}); diff --git a/pool/shard000/JavaScript/0003739_86print.js b/pool/shard000/JavaScript/0003739_86print.js new file mode 100644 index 0000000000000000000000000000000000000000..2fa17a005aee799c66b074ddac5fa261466f591e --- /dev/null +++ b/pool/shard000/JavaScript/0003739_86print.js @@ -0,0 +1,60 @@ +/* +// +// HELP for Alasql.js +// Date: 03.11.2014 +// (c) 2014, Andrey Gershun +// +*/ + +/** + Print statement + @class + @param {object} params Initial setup properties +*/ + +yy.Print = function (params) { return yy.extend(this, params); } + +/** + Generate SQL string + @this Print statement object +*/ +yy.Print.prototype.toString = function() { + var s = 'PRINT'; + if(this.statement) s += ' '+this.statement.toString(); + return s; +} + + +/** + Print result of select statement or expression + @param {string} databaseid Database identificator + @param {object} params Query parameters + @param {statement-callback} cb Callback function + @this Print statement object +*/ +yy.Print.prototype.execute = function (databaseid,params,cb) { +// console.log(this.url); + var self = this; + var res = 1; +//console.log(this); + alasql.precompile(this,databaseid,params); /** @todo Change from alasql to this */ + + if(this.exprs && this.exprs.length >0) { + var rs = this.exprs.map(function(expr){ + +// console.log('var y;return '+expr.toJS('({})','', null)); + var exprfn = new Function("params,alasql,p",'var y;return '+expr.toJS('({})','', null)).bind(self); + var r = exprfn(params,alasql); + return JSONtoString(r); + }); + console.log.apply(console,rs); + } else if(this.select) { + var r = this.select.execute(databaseid,params); + console.log(JSONtoString(r)); + } else { + console.log(); + } + + if(cb) res = cb(res); + return res; +}; diff --git a/pool/shard000/JavaScript/0003740_events.js b/pool/shard000/JavaScript/0003740_events.js new file mode 100644 index 0000000000000000000000000000000000000000..e8888a7f2283ac6e27389aa6492a0645aedaa982 --- /dev/null +++ b/pool/shard000/JavaScript/0003740_events.js @@ -0,0 +1,43 @@ +define([ + 'assert', 'sinon', 'underscore', 'fossil/module', 'fossil/services/events' +], function (assert, sinon, _, Module, Events) { + "use strict"; + suite('services/events', function () { + var methods = ['on', 'off', 'once', 'trigger']; + var events, module, fooSpy; + + setup(function () { + fooSpy = sinon.spy(); + events = new Events(); + module = new Module(); + events.on('foo', fooSpy); + module.use('events', events); + }); + + suite('#use', function () { + test('should add app! modifier', function () { + module.trigger('app!foo'); + + assert.ok(fooSpy.calledOnce); + }); + }); + + suite('#dispose', function () { + test('should remove app! modifier', function () { + module.dispose('events', events); + module.trigger('app!foo'); + + assert.ok(!fooSpy.called); + }); + }); + + suite('app! modifier', function () { + test('should pass arguments', function () { + module.trigger('app!foo', 'bar', 'baz'); + + assert.ok(fooSpy.calledOnce); + assert.ok(fooSpy.calledWith('bar', 'baz')); + }); + }); + }); +}); diff --git a/pool/shard000/JavaScript/0003746_expander.js b/pool/shard000/JavaScript/0003746_expander.js new file mode 100644 index 0000000000000000000000000000000000000000..49f22674dedb10366ed4ced6c8a294298cb1b582 --- /dev/null +++ b/pool/shard000/JavaScript/0003746_expander.js @@ -0,0 +1,134 @@ +// TODO: opts.pre||post : does that actor run before or after the evals + +module.exports = Expander; + +var promise = require('when').promise; +var sequence = require('when/sequence'); +var compiler = require('./compiler'); +var path = require('path'); + +function Expander() {} + +Expander.perform = function(opts, inArgs, arg) { + return promise(function(resolve, reject, notify) { + + var template = arg.actions[0].expansion; + if (!template) return resolve(arg); + + var expansions = []; + var embedded; + var origPaths; + var part = ''; + var parts = []; + + for (var i = template.length - 1; i >= 0; i--) { + if (template[i]+template[i-1] == '}}') { + i--; + embedded = ''; + parts.unshift(part); + part = ''; + continue; + } + if (template[i]+template[i-1] == '{{') { + expansions.push({eval:embedded}); + embedded = undefined + i--; + continue; + } + if (typeof embedded !== 'undefined') { + embedded = template[i] + embedded.toString(); + } + else { + part = template[i] + part; + } + } + + parts.unshift(part); // ? + + if (expansions.length > 0) { + + // update module require paths to the callers perspective + + origPaths = module.paths; + module.paths = Expander.callerPaths(opts.$$caller.FileName, []); + + arg.actions[0].expansion = ''; // rebuilding it + var first = parts.pop(); + return sequence(expansions.map(function(expansion){ + return function() { + return promise(function(resolve, reject, notify) { + compiler.perform(opts, arg, inArgs, expansion).then( + function(result) { + + + var part = parts.pop(); + var copy = arg.actions; + + if (part.match(/^(in\.|out\.)/)) part = ''; // ? + + if (result instanceof Array && result.length > 0) { + + arg.actions = []; + arg.asArray = true; + + copy.forEach(function(action) { + result.forEach(function(result) { + var newAction = {}; + Object.keys(action).forEach(function(key) { + newAction[key] = action[key]; + }); + + if (first == '' && part == '' && + (typeof action.expansion == 'undefined' + || action.expansion == '')) { + newAction.expansion = result; + } + else newAction.expansion = part + result + action.expansion + first; + arg.actions.push(newAction); + }); + }) + return resolve(); + } + + arg.actions.forEach(function(action) { + if (first == '' && part == '' && + (typeof action.expansion == 'undefined' + || action.expansion == '')) { + action.expansion = result + } else { + action.expansion = part + result + action.expansion + first; + } + }); + + first = ''; + resolve(); + }, + reject, + notify + ) + }); + } + })).then( + function() { + module.paths = origPaths; + resolve(arg); + }, + function(e) { + module.paths = origPaths; + reject(e); + }, + notify + ); + } else { + arg.asArray = false; + resolve(arg); + } + }); +} + +Expander.callerPaths = function(filename, paths) { + var dirname = path.dirname(filename); + if (dirname == filename) return paths; + paths.push(path.normalize(dirname + path.sep + 'node_modules')); + return Expander.callerPaths(dirname, paths); +} diff --git a/pool/shard000/JavaScript/0003757_events.spec.js b/pool/shard000/JavaScript/0003757_events.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..e9fc11d64364497cbff71fc141f32f0cf3354ad7 --- /dev/null +++ b/pool/shard000/JavaScript/0003757_events.spec.js @@ -0,0 +1,44 @@ +'use strict'; + +describe('DOM-related events', function() { + var $tree; + var tree; + + before(function() { + helpers.createTreeContainer(); + + $tree = $('.tree'); + + tree = new InspireTree({ + data: [{ + text: 'A' + }] + }); + + new InspireTreeDOM(tree, { + target: $tree + }); + }); + + it('provides a preventTreeDefault method', function(done) { + tree.on('node.click', function(event) { + expect(event.preventTreeDefault).to.be.a('function'); + done(); + }); + + // Inferno doesn't like jquery's click + $tree.find('a.title')[0].click(); + }); + + it('passes handler as an argument', function(done) { + tree.on('node.click', function(event, node, handler) { + expect(handler).to.be.a('function'); + done(); + }); + + // Inferno doesn't like jquery's click + $tree.find('a.title')[0].click(); + }); + + after(helpers.clearDOM); +}); diff --git a/pool/shard000/JavaScript/0003759_mtof.js b/pool/shard000/JavaScript/0003759_mtof.js new file mode 100644 index 0000000000000000000000000000000000000000..c46fc89089141ce3b32391be24d92675b4c7a2bd --- /dev/null +++ b/pool/shard000/JavaScript/0003759_mtof.js @@ -0,0 +1,36 @@ +'use strict' + +let gen = require('./gen.js') + +let proto = { + name:'mtof', + + gen() { + let out, + inputs = gen.getInputs( this ) + + if( isNaN( inputs[0] ) ) { + gen.closures.add({ [ this.name ]: Math.exp }) + + out = `( ${this.tuning} * gen.exp( .057762265 * (${inputs[0]} - 69) ) )` + + } else { + out = this.tuning * Math.exp( .057762265 * ( inputs[0] - 69) ) + } + + return out + } +} + +module.exports = ( x, props ) => { + let ugen = Object.create( proto ), + defaults = { tuning:440 } + + if( props !== undefined ) Object.assign( props.defaults ) + + Object.assign( ugen, defaults ) + ugen.inputs = [ x ] + + + return ugen +} diff --git a/pool/shard000/JavaScript/0003762_Gulpfile.js b/pool/shard000/JavaScript/0003762_Gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..3ddd822f64c5d87fd4fc61a738187985591cceaf --- /dev/null +++ b/pool/shard000/JavaScript/0003762_Gulpfile.js @@ -0,0 +1,98 @@ +require('es6-promise').polyfill(); + +var gulp = require('gulp'), + sass = require('gulp-sass'), + postcss = require('gulp-postcss'), + autoprefixer = require('autoprefixer'), + minifyCss = require('gulp-minify-css'), + uglify = require('gulp-uglify') + rename = require('gulp-rename') + del = require('del') +; + +var CSS_BUILDDIR = './assets/css/'; +var JS_BUILDDIR = './assets/js/'; + +gulp.task('build', function() { + + // Generate CSS + gulp.src(['./assets/css/src/main.scss']) + .pipe(sass({precision: 8}).on('error', sass.logError)) + .pipe(postcss([ + autoprefixer({browsers: [ + "Android 2.3", + "Android >= 4", + "Chrome >= 20", + "Firefox >= 24", + "Explorer >= 8", + "iOS >= 6", + "Opera >= 12", + "Safari >= 6" + ]}) + ])) + .pipe(gulp.dest(CSS_BUILDDIR)) + .pipe(minifyCss({keepSpecialComments: 0})) + .pipe(rename({extname: '.min.css'})) + .pipe(gulp.dest(CSS_BUILDDIR)) + ; + + // Minify Bootstrap Javascript files + gulp.src('./node_modules/bootstrap-sass/assets/javascripts/bootstrap.js') + .pipe(rename({basename: "main"})) + .pipe(gulp.dest(JS_BUILDDIR)) + .pipe(uglify().on('error', function (e) { console.log(e); })) + .pipe(rename({extname: '.min.js'})) + .pipe(gulp.dest(JS_BUILDDIR)) + ; + + // Minify Theme Customizer file + gulp.src('./assets/js/src/theme-customizer.js') + .pipe(gulp.dest(JS_BUILDDIR)) + .pipe(uglify().on('error', function (e) { console.log(e); })) + .pipe(rename({extname: '.min.js'})) + .pipe(gulp.dest(JS_BUILDDIR)) + ; + + // Minify html5shiv + gulp.src('./node_modules/html5shiv/src/html5shiv.js') + .pipe(gulp.dest(JS_BUILDDIR)) + .pipe(uglify().on('error', function (e) { console.log(e); })) + .pipe(rename({extname: '.min.js'})) + .pipe(gulp.dest(JS_BUILDDIR)) + ; + + // Minify respond.js + gulp.src('./node_modules/respond.js/src/respond.js') + .pipe(gulp.dest(JS_BUILDDIR)) + .pipe(uglify().on('error', function (e) { console.log(e); })) + .pipe(rename({extname: '.min.js'})) + .pipe(gulp.dest(JS_BUILDDIR)) + ; + + // Copy fonts + gulp.src(['./node_modules/font-awesome/fonts/**/*']) + .pipe(gulp.dest('./assets/fonts/')) + ; + + return gulp.src([ + './assets/css/*.css', + './assets/fonts/**/*', + './assets/js/*.js', + './includes/**/*', + './languages/**/*', + './page-templates/**/*', + './templates/**/*', + './*.php', + './LICENSE.txt', + './README.txt', + './screenshot.png', + './style.css' + ], {base:"."}) + .pipe(gulp.dest('./ltk-foundation/')); + +}); + +gulp.task('clean', function() { + del('./ltk-foundation/**/*'); + return del('./ltk-foundation'); +}); diff --git a/pool/shard000/JavaScript/0003764_wysiwyg.js b/pool/shard000/JavaScript/0003764_wysiwyg.js new file mode 100644 index 0000000000000000000000000000000000000000..be76cf1cac81d13d689ac31de82c93f6b542aca0 --- /dev/null +++ b/pool/shard000/JavaScript/0003764_wysiwyg.js @@ -0,0 +1,143 @@ +window.Wy = { + split: function(){ + var sel, range; + if (window.getSelection){ + // IE9 and non-IE + sel = window.getSelection(); + if (sel.getRangeAt && sel.rangeCount) { + range = sel.getRangeAt(0); + C.log(range); + + var node = range.startContainer.parentNode, + text = range.startContainer.textContent, + start = range.startOffset; + + var time = $(node).data('time'); + + var $t1 = $(''+text.substr(0, start)+'').data('time', time), + $t2 = $(''+text.substr(start)+'').data('time', time + 0.1); + + if(node.tagName == 'I'){ + $t2.insertAfter(node).blink('yellow'); + $t1.insertAfter(node).blink('orange'); + $(node).remove(); + } + else{ + $(node).empty().append($t1).append($t2); + } + + return $t2; + } + } else if (document.selection && document.selection.type != "Control") { + // IE < 9 + //document.selection.createRange().pasteHTML(html); + } + }, + + tagSelection: function(){ + if(window.getSelection){ + var sel = window.getSelection(); + if(sel.getRangeAt && sel.rangeCount){ + var range = sel.getRangeAt(0).cloneRange(); + + var node = range.startContainer.parentNode, + text = range.startContainer.textContent, + start = range.startOffset; + + var node = document.createElement('span'); + $(node).addClass('mark'); + range.surroundContents(node); + + //sel.removeAllRanges(); + //sel.addRange(range); + + return node; + } + } + }, + + paste: function(html){ + var sel, range; + if (window.getSelection){ + sel = window.getSelection(); + if(sel.getRangeAt && sel.rangeCount){ + range = sel.getRangeAt(0); + + var node = range.startContainer.parentNode; + + return $(html).insertAfter(node); + } + } + }, + + getSelection: function(){ + var sel, range; + if(window.getSelection){ + sel = window.getSelection(); + if(sel.getRangeAt && sel.rangeCount){ + range = sel.getRangeAt(0); + + C.log(range); + + var startNode = range.startContainer.parentNode, + endNode = range.endContainer.parentNode, + start = range.startOffset; + + if(startNode == endNode) return false; + return $(startNode).nextUntil(endNode).add(startNode).add(endNode); + } + } + }, + + space: function(){ + var sel, range; + if (window.getSelection){ + // IE9 and non-IE + sel = window.getSelection(); + if(sel.getRangeAt && sel.rangeCount){ + range = sel.getRangeAt(0); + C.log(range); + + var node = range.startContainer.parentNode, + text = range.startContainer.textContent, + start = range.startOffset; + + var time = $(node).data('time'); + + var $t2 = Wy.split(); + $t2.before(' '); + + return $t2; + } + } + }, + + placeCaret: function(node, l){ + if(window.getSelection){ + var range = document.createRange(); + + if(!l) l = 0; + if(l == 0 && !node.innerHTML){ + node.innerHTML = '​'; + l++; + } + + range.setStart(node, l); + range.collapse(true); + + var sel = window.getSelection(); + sel.removeAllRanges(); + sel.addRange(range); + } + }, + + increase: function(string, by){ + return string.replace( + /[-]?((0|[1-9][0-9]*)(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?/g, + function(str, p1, p2, p3, p4, offset, s){ + if(by < 1) return (Math.round((parseFloat(str) + by) * 100) / 100).toFixed(2); + return parseFloat(str) + by; + } + ); + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003765_filter.js b/pool/shard000/JavaScript/0003765_filter.js new file mode 100644 index 0000000000000000000000000000000000000000..708c76b6c9bec7d2ab3622c8bde0527dee6bd823 --- /dev/null +++ b/pool/shard000/JavaScript/0003765_filter.js @@ -0,0 +1,96 @@ +var renderer = PIXI.autoDetectRenderer(800, 600); +document.body.appendChild(renderer.view); + +// create the root of the scene graph +var stage = new PIXI.Container(); + +stage.interactive = true; + +var bg = PIXI.Sprite.fromImage('_assets/BGrotate.jpg'); +bg.anchor.set(0.5); + +bg.position.x = renderer.width / 2; +bg.position.y = renderer.height / 2; + +var filter = new PIXI.filters.ColorMatrixFilter(); + +var container = new PIXI.Container(); +container.position.x = renderer.width / 2; +container.position.y = renderer.height / 2; + +var bgFront = PIXI.Sprite.fromImage('_assets/SceneRotate.jpg'); +bgFront.anchor.set(0.5); + +container.addChild(bgFront); + +var light2 = PIXI.Sprite.fromImage('_assets/LightRotate2.png'); +light2.anchor.set(0.5); +container.addChild(light2); + +var light1 = PIXI.Sprite.fromImage('_assets/LightRotate1.png'); +light1.anchor.set(0.5); +container.addChild(light1); + +var panda = PIXI.Sprite.fromImage('_assets/panda.png'); +panda.anchor.set(0.5); + +container.addChild(panda); + +stage.addChild(container); + +stage.filters = [filter]; + +var count = 0; +var switchy = false; + +stage.on('click', onClick); +stage.on('tap', onClick); + +function onClick() +{ + switchy = !switchy; + + if (!switchy) + { + stage.filters = [filter]; + } + else + { + stage.filters = null; + } +} + +var help = new PIXI.Text('Click to turn filters on / off.', { font: 'bold 12pt Arial', fill: 'white' }); +help.position.y = renderer.height - 25; +help.position.x = 10; + +stage.addChild(help); + +requestAnimationFrame(animate); + +function animate() { + bg.rotation += 0.01; + bgFront.rotation -= 0.01; + + light1.rotation += 0.02; + light2.rotation += 0.01; + + panda.scale.x = 1 + Math.sin(count) * 0.04; + panda.scale.y = 1 + Math.cos(count) * 0.04; + + count += 0.1; + + var matrix = filter.matrix; + + matrix[1] = Math.sin(count) * 3; + matrix[2] = Math.cos(count); + matrix[3] = Math.cos(count) * 1.5; + matrix[4] = Math.sin(count / 3) * 2; + matrix[5] = Math.sin(count / 2); + matrix[6] = Math.sin(count / 4); + + renderer.render(stage); + requestAnimationFrame(animate); +} + + diff --git a/pool/shard000/JavaScript/0003771_main.js b/pool/shard000/JavaScript/0003771_main.js new file mode 100644 index 0000000000000000000000000000000000000000..17736ef86227243db18a42538bed8c9470eb35dd --- /dev/null +++ b/pool/shard000/JavaScript/0003771_main.js @@ -0,0 +1,230 @@ +/* globals toolbarSearch, menu, isRtl, fireGlobalEvent, CachedChatSubscription, DynamicCss */ +import Clipboard from 'clipboard'; +import s from 'underscore.string'; + +RocketChat.settings.collection.find({_id:/theme-color-rc/i}, {fields:{ value: 1 }}).observe({changed: () => { DynamicCss.run(true); }}); + +this.isFirefox = navigator.userAgent.match(/Firefox\/(\d+)\.\d/); + +Template.body.onRendered(function() { + new Clipboard('.clipboard'); + + $(document.body).on('keydown', function(e) { + if ((e.keyCode === 80 || e.keyCode === 75) && (e.ctrlKey === true || e.metaKey === true) && e.shiftKey === false) { + e.preventDefault(); + e.stopPropagation(); + toolbarSearch.focus(true); + } + const unread = Session.get('unread'); + if (e.keyCode === 27 && e.shiftKey === true && (unread != null) && unread !== '') { + e.preventDefault(); + e.stopPropagation(); + modal.open({ + title: t('Clear_all_unreads_question'), + type: 'warning', + confirmButtonText: t('Yes_clear_all'), + showCancelButton: true, + cancelButtonText: t('Cancel'), + confirmButtonColor: '#DD6B55' + }, function() { + const subscriptions = ChatSubscription.find({ + open: true + }, { + fields: { + unread: 1, + alert: 1, + rid: 1, + t: 1, + name: 1, + ls: 1 + } + }); + + subscriptions.forEach((subscription) =>{ + if (subscription.alert || subscription.unread > 0) { + Meteor.call('readMessages', subscription.rid); + } + }); + }); + } + }); + + $(document.body).on('keydown', function(e) { + const target = e.target; + if (e.ctrlKey === true || e.metaKey === true) { + return; + } + if (!(e.keyCode > 45 && e.keyCode < 91 || e.keyCode === 8)) { + return; + } + if (/input|textarea|select/i.test(target.tagName)) { + return; + } + if (target.id === 'pswp') { + return; + } + const inputMessage = $('.rc-message-box__textarea'); + if (inputMessage.length === 0) { + return; + } + inputMessage.focus(); + }); + + $(document.body).on('click', function(e) { + if (e.target.tagName === 'A') { + const link = e.currentTarget; + if (link.origin === s.rtrim(Meteor.absoluteUrl(), '/') && /msg=([a-zA-Z0-9]+)/.test(link.search)) { + e.preventDefault(); + e.stopPropagation(); + if (RocketChat.Layout.isEmbedded()) { + return fireGlobalEvent('click-message-link', { + link: link.pathname + link.search + }); + } + return FlowRouter.go(link.pathname + link.search, null, FlowRouter.current().queryParams); + } + } + }); + + Tracker.autorun(function(c) { + const w = window; + const d = document; + const script = 'script'; + const l = 'dataLayer'; + const i = RocketChat.settings.get('GoogleTagManager_id'); + if (Match.test(i, String) && i.trim() !== '') { + c.stop(); + return (function(w, d, s, l, i) { + w[l] = w[l] || []; + w[l].push({ + 'gtm.start': new Date().getTime(), + event: 'gtm.js' + }); + const f = d.getElementsByTagName(s)[0]; + const j = d.createElement(s); + const dl = l !== 'dataLayer' ? `&l=${ l }` : ''; + j.async = true; + j.src = `//www.googletagmanager.com/gtm.js?id=${ i }${ dl }`; + return f.parentNode.insertBefore(j, f); + }(w, d, script, l, i)); + } + }); + if (Meteor.isCordova) { + return $(document.body).addClass('is-cordova'); + } +}); + +RocketChat.mainReady = new ReactiveVar(false); +Template.main.helpers({ + removeSidenav() { + const { modal } = this; + return (modal || typeof modal === 'function' ? modal() : modal) || RocketChat.Layout.isEmbedded(); + }, + siteName() { + return RocketChat.settings.get('Site_Name'); + }, + logged() { + if (Meteor.userId() != null || (RocketChat.settings.get('Accounts_AllowAnonymousRead') === true && Session.get('forceLogin') !== true)) { + $('html').addClass('noscroll').removeClass('scroll'); + return true; + } else { + $('html').addClass('scroll').removeClass('noscroll'); + return false; + } + }, + useIframe() { + const iframeEnabled = typeof RocketChat.iframeLogin !== 'undefined'; + return iframeEnabled && RocketChat.iframeLogin.reactiveEnabled.get(); + }, + iframeUrl() { + const iframeEnabled = typeof RocketChat.iframeLogin !== 'undefined'; + return iframeEnabled && RocketChat.iframeLogin.reactiveIframeUrl.get(); + }, + subsReady() { + const routerReady = FlowRouter.subsReady('userData', 'activeUsers'); + const subscriptionsReady = CachedChatSubscription.ready.get(); + const settingsReady = RocketChat.settings.cachedCollection.ready.get(); + const ready = (Meteor.userId() == null) || (routerReady && subscriptionsReady && settingsReady); + RocketChat.CachedCollectionManager.syncEnabled = ready; + Meteor.defer(() => { + RocketChat.mainReady.set(ready); + }); + return ready; + }, + hasUsername() { + return (Meteor.userId() != null && Meteor.user().username != null) || (Meteor.userId() == null && RocketChat.settings.get('Accounts_AllowAnonymousRead') === true); + }, + requirePasswordChange() { + const user = Meteor.user(); + return user && user.requirePasswordChange === true; + }, + CustomScriptLoggedOut() { + const script = RocketChat.settings.get('Custom_Script_Logged_Out') || ''; + if (script.trim()) { + eval(script);//eslint-disable-line + } + }, + CustomScriptLoggedIn() { + const script = RocketChat.settings.get('Custom_Script_Logged_In') || ''; + if (script.trim()) { + eval(script);//eslint-disable-line + } + }, + embeddedVersion() { + if (RocketChat.Layout.isEmbedded()) { + return 'embedded-view'; + } + }, + showSetupWizard() { + const userId = Meteor.userId(); + const Show_Setup_Wizard = RocketChat.settings.get('Show_Setup_Wizard'); + + return (!userId && Show_Setup_Wizard === 'pending') || (userId && RocketChat.authz.hasRole(userId, 'admin') && Show_Setup_Wizard === 'in_progress'); + } +}); + +Template.main.events({ + 'click .burger'() { + return menu.toggle(); + } +}); + +Template.main.onRendered(function() { + document.body.classList[(isRtl(localStorage.getItem('userLanguage'))? 'add': 'remove')]('rtl'); + $('#initial-page-loading').remove(); + window.addEventListener('focus', function() { + return Meteor.setTimeout(function() { + if (!$(':focus').is('INPUT,TEXTAREA')) { + return $('.input-message').focus(); + } + }, 100); + }); + return Tracker.autorun(function() { + const userId = Meteor.userId(); + const Show_Setup_Wizard = RocketChat.settings.get('Show_Setup_Wizard'); + + if ((!userId && Show_Setup_Wizard === 'pending') || (userId && RocketChat.authz.hasRole(userId, 'admin') && Show_Setup_Wizard === 'in_progress')) { + FlowRouter.go('setup-wizard'); + } + if (RocketChat.getUserPreference(userId, 'hideUsernames')) { + $(document.body).on('mouseleave', 'button.thumb', function() { + return RocketChat.tooltip.hide(); + }); + return $(document.body).on('mouseenter', 'button.thumb', function(e) { + const avatarElem = $(e.currentTarget); + const username = avatarElem.attr('data-username'); + if (username) { + e.stopPropagation(); + return RocketChat.tooltip.showElement($('').text(username), avatarElem); + } + }); + } else { + $(document.body).off('mouseenter', 'button.thumb'); + return $(document.body).off('mouseleave', 'button.thumb'); + } + }); +}); + +Meteor.startup(function() { + return fireGlobalEvent('startup', true); +}); diff --git a/pool/shard000/JavaScript/0003772_ForkTool.js b/pool/shard000/JavaScript/0003772_ForkTool.js new file mode 100644 index 0000000000000000000000000000000000000000..58a6e8cd533a5b277d189d0cc1d245c2007fa679 --- /dev/null +++ b/pool/shard000/JavaScript/0003772_ForkTool.js @@ -0,0 +1,120 @@ +/** + * Created by Jacky.Gao on 2017-07-10. + */ +import BaseTool from './BaseTool.js'; +import ForkNode from './ForkNode.js'; +import EventSelectDialog from './dialog/EventSelectDialog.js'; + +export default class ForkTool extends BaseTool{ + getType(){ + return '分支'; + } + getIcon(){ + return `` + } + newNode(){ + return new ForkNode(); + } + getConfigs(){ + return { + in:-1, + out:-1, + single:false + }; + } + getPropertiesProducer(){ + const _this=this; + return function (){ + const g=$(`
    `); + g.append(_this.getCommonProperties(this)); + return g; + } + } + + buildConnectionCondition(target){ + const group=$(`
    + 连线条件配置
    `); + + const noneConditionRadio=$(`
    无条件
    `); + group.append(noneConditionRadio); + + const exprGroup=$(`
    `); + group.append(exprGroup); + const exprConditionRadio=$(`表达式条件`); + exprGroup.append(exprConditionRadio); + const exprEditor=$(``); + exprGroup.append(exprEditor); + exprEditor.val(target.expression || ''); + exprEditor.change(function(){ + target.expression=$(this).val(); + }); + + const beanGroup=$(`
    `); + group.append(beanGroup); + const beanConditionRadio=$(`条件Bean`); + beanGroup.append(beanConditionRadio); + const tip='一个实现了com.bstek.uflo.process.handler.ConditionHandler接口,配置在Spring中的Bean Id'; + const beanEditor=$(``); + beanGroup.append(beanEditor); + beanEditor.change(function(){ + target.handlerBean=$(this).val(); + }); + const beanSelectButton=$(``); + beanGroup.append(beanSelectButton); + exprEditor.prop('readOnly',true); + beanEditor.prop('readOnly',true); + beanSelectButton.attr('disabled',true); + if(target.conditionType==='Expression'){ + exprEditor.prop('readOnly',false); + exprConditionRadio.children('input').attr('checked',true); + }else if(target.conditionType==='Handler'){ + beanEditor.prop('readOnly',false); + beanConditionRadio.children('input').attr('checked',true); + }else{ + noneConditionRadio.children('input').attr('checked',true); + } + + const dialog=new EventSelectDialog(`选择${tip}`); + beanSelectButton.click(()=>{ + dialog.show('ConditionHandler',function(beanId){ + beanEditor.val(beanId); + target.handlerBean=beanId; + }); + }); + noneConditionRadio.children('input').click(function(){ + exprEditor.prop('readOnly',true); + beanEditor.prop('readOnly',true); + beanSelectButton.attr('disabled',true); + target.conditionType=null; + target.handlerBean=null; + target.expression=null; + }); + + exprConditionRadio.children('input').click(function(){ + exprEditor.prop('readOnly',false); + beanEditor.prop('readOnly',true); + beanSelectButton.attr('disabled',true); + target.conditionType='Expression'; + target.handlerBean=null; + }); + + beanConditionRadio.children('input').click(function(){ + exprEditor.prop('readOnly',true); + beanEditor.prop('readOnly',false); + beanSelectButton.attr('disabled',false); + target.conditionType='Handler'; + target.expression=null; + }); + + return group; + } + + getConnectionPropertiesProducer(){ + const _this=this; + return function (target){ + const g=$(`
    `); + g.append(_this.buildConnectionCondition(this)); + return g; + } + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003773_update-controller.js b/pool/shard000/JavaScript/0003773_update-controller.js new file mode 100644 index 0000000000000000000000000000000000000000..cbea696cd98be4a97ad79a7e5b23bd1e588b7d3a --- /dev/null +++ b/pool/shard000/JavaScript/0003773_update-controller.js @@ -0,0 +1,35 @@ +(function($) { + var ngmod = angular.module("framework.controllers", ["framework.systemParamService"]); + + ngmod.controller("systemParamUpdateCtrl",function($scope,systemParamRES,systemParamTRES){ + systemParamRES.get({ + method:"detail", + id :$.query.get("id") + }, function(detailPproject) { + $scope.project = detailPproject.model; + }); + + + systemParamTRES.get({ + method:"tlist", + category : "SIMPLE" + }, function(project) { + $scope.typeList = project.models; + }); + $scope.save = function(invalid) { + if(invalid){ + alert('错误!必填信息不能为空,请检查表单项!'); + return; + } + systemParamRES.save({'method':"update"},$scope.project, function(project) { + if(project.respCode=="00"){ + alert('操作成功'); + window.location.href="systemParamList.shtml"; + }else { + alert('操作失败'+project.respDesc); + } + }); + }; + }); + +})(jQuery); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003774_svg-collection.js b/pool/shard000/JavaScript/0003774_svg-collection.js new file mode 100644 index 0000000000000000000000000000000000000000..73d1fe838a9a137208b4443351ace1cf37cdfac1 --- /dev/null +++ b/pool/shard000/JavaScript/0003774_svg-collection.js @@ -0,0 +1,32 @@ +import _ from "underscore"; +import {Collection} from "backbone"; +import FileModel from "./svg-model.js"; +import Colorfy from "./../utils/colorfy.js"; + +export default class FileCollection extends Collection { + initialize(models, options) { + this.model = FileModel; + this.config = options.config; + } + + /** + * split the file into multiple files if it has colors, then add it to the collection + * @param {File} file A svg that was dropped + */ + addFile(file) { + var name = file.name.split(".svg")[0]; + var extraColors = this.config.get("colors"); + var colorfy = new Colorfy(name, extraColors, this.config.toJSON()); + + // build files for each color + _.each(colorfy.colors, (color, colorName) => { + let name = `${colorfy.originalFilepath}-${colorName}`; + this.add({ file, color, name }) + }); + + // don't add base SVG if it had colors and the dynamicColorOnly option was true + if (_.isEmpty(colorfy.colors) || !this.config.get("dynamicColorOnly")) { + this.add({ file, name: colorfy.originalFilepath }); + } + } +} \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003776_server.js b/pool/shard000/JavaScript/0003776_server.js new file mode 100644 index 0000000000000000000000000000000000000000..4abd9b209471cfc674cd4ecfa7b2859e56bda890 --- /dev/null +++ b/pool/shard000/JavaScript/0003776_server.js @@ -0,0 +1,25 @@ +const cluster = require('cluster'); +const http = require('http'); +const os = require('os'); +const _ = require('lodash'); + +const appFactory = require('./app'); + + +async function main() { + + if (cluster.isMaster) { + console.log(`Master ${process.pid} is running`); + _.times(os.cpus().length, () => cluster.fork()); + cluster.on('exit', (worker, code, signal) => { + console.log(`Worker ${worker.process.pid} died`); + }); + } else { + const app = await appFactory.create(); + const port = _.get(app.cfg, 'listen.port', 3030); + app.listen(port); + console.log(`Worker ${process.pid} started`); + } +} + +main().catch(ex => console.error(ex)); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003777_migrateHistoricalPricing.js b/pool/shard000/JavaScript/0003777_migrateHistoricalPricing.js new file mode 100644 index 0000000000000000000000000000000000000000..4ebad4956040a612a219124bdfdbbb64b31d0a0c --- /dev/null +++ b/pool/shard000/JavaScript/0003777_migrateHistoricalPricing.js @@ -0,0 +1,40 @@ +var cycleRepository = require('../CARLI/Entity/CycleRepository'); +var historicalPricingMigration = require('./historicalPricing'); +var Q = require('q'); + +/** + * This script goes through all of the cycles and fills in historical pricing for all of the offerings in each. + */ + +migrateHistoricalPricingForAllCyclesSerially(); + + +function migrateHistoricalPricingForAllCyclesSerially() { + return cycleRepository.listActiveCycles() + .then(function (cycles) { + var cycleList = cycles; + return migrateHistoricalPricingForNextCycle(); + + function migrateHistoricalPricingForNextCycle() { + var cycle = cycleList.pop(); + + if (!cycle) { + return; + } + + return historicalPricingMigration.populateHistoricalPricingForCycle(cycle.id) + .then(migrateHistoricalPricingForNextCycle) + .catch(function (e) { + Logger.log(e); + }); + } + }) + .done(); +} + +function populateOneCycle(cycleId){ + return historicalPricingMigration.populateHistoricalPricingForCycle(cycleId) + .catch(function (e) { + Logger.log(e); + }); +} diff --git a/pool/shard000/JavaScript/0003778_appVersion.js b/pool/shard000/JavaScript/0003778_appVersion.js new file mode 100644 index 0000000000000000000000000000000000000000..b563a3b54d5a3c50a6a828a1dbe3006905a175b5 --- /dev/null +++ b/pool/shard000/JavaScript/0003778_appVersion.js @@ -0,0 +1,15 @@ +function AppVersion() { } + +AppVersion.prototype.getVersionNumber = function(successCallback, errorCallback) { + cordova.exec(successCallback, errorCallback, "AppVersion", "getVersionNumber", []); +}; + +AppVersion.prototype.getBuildNumber = function(successCallback, errorCallback) { + cordova.exec(successCallback, errorCallback, "AppVersion", "getBuildNumber", []); +}; + +AppVersion.prototype.geAlbumPermission = function(successCallback, errorCallback) { + cordova.exec(successCallback, errorCallback, "AppVersion", "geAlbumPermission", []); +}; + +module.exports = new AppVersion(); diff --git a/pool/shard000/JavaScript/0003780_webpack.config.js b/pool/shard000/JavaScript/0003780_webpack.config.js new file mode 100644 index 0000000000000000000000000000000000000000..2323f8300e6b9383715304744b1303954db65cb1 --- /dev/null +++ b/pool/shard000/JavaScript/0003780_webpack.config.js @@ -0,0 +1,218 @@ +// @AngularClass + +// Helper +var sliceArgs = Function.prototype.call.bind(Array.prototype.slice); +var NODE_ENV = process.env.NODE_ENV || 'development'; + +// Node +var webpack = require('webpack'); +var path = require('path'); +var pkg = require('./package.json'); + +// Webpack Plugins +var OccurenceOrderPlugin = webpack.optimize.OccurenceOrderPlugin; +var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; +var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin; +var DedupePlugin = webpack.optimize.DedupePlugin; +var DefinePlugin = webpack.DefinePlugin; +var BannerPlugin = webpack.BannerPlugin; + + +/* + * Config + */ + +var config = { + devtool: 'source-map', + // devtool: 'eval', + + debug: true, + cache: true, + // our Development Server configs + devServer: { + inline: true, + colors: true, + historyApiFallback: true, + contentBase: 'src/public', + publicPath: '/__build__' + }, + + // + entry: { + 'angular2': [ + // Angular 2 Deps + 'zone.js', + 'reflect-metadata', + 'rtts_assert/rtts_assert', + 'angular2/angular2' + ], + 'app': [ + // App + + /* + * include any 3rd party js lib here + */ + + './src/app/bootstrap' + ] + }, + + // Config for our build files + output: { + path: root('__build__'), + filename: '[name].js', + // filename: '[name].[hash].js', + sourceMapFilename: '[name].js.map', + chunkFilename: '[id].chunk.js' + // publicPath: 'http://mycdn.com/' + }, + + resolve: { + root: __dirname, + extensions: ['','.ts','.js','.json'], + alias: { + // we can switch between development and production + // 'angular2': 'node_modules/angular2/ts', + // 'angular2': 'angular2/ts/dev', + + 'app': 'src/app', + 'common': 'src/common', + + // 'components': 'src/app/components' + // 'services': '/app/services/*.js', + // 'stores/*': '/app/stores/*.js' + // 'angular2': 'angular2/es6/dev' + } + }, + + /* + * When using `templateUrl` and `styleUrls` please use `__filename` + * rather than `module.id` for `moduleId` in `@View` + */ + node: { + __filename: true + }, + + module: { + loaders: [ + // Support for *.json files. + { test: /\.json$/, loader: 'json' }, + + // Support for CSS as raw text + { test: /\.css$/, loader: 'raw' }, + + // support for .html as raw text + { test: /\.html$/, loader: 'raw' }, + + // Support for .ts files. + { test: /\.ts$/, loader: 'typescript-simple?&ignoreWarnings[]=2300&ignoreWarnings[]=2309', exclude: [ + /\.spec\.ts$/, + /\.e2e\.ts$/, + /web_modules/, + /test/, + /node_modules/ + ] + } + ], + noParse: [ + /rtts_assert\/src\/rtts_assert/ + ] + }, + + // plugins: plugins, // see below + context: __dirname, + stats: { colors: true, reasons: true } +}; + + +var commons_chunks_plugins = [ + { + name: 'angular2', + minChunks: Infinity, + filename: 'angular2.js' + }, + { + name: 'common', + filename: 'common.js' + } +] + + +// +var environment_plugins = { + + all: [ + new DefinePlugin({ + 'process.env.NODE_ENV': JSON.stringify(NODE_ENV), + 'VERSION': pkg.version + }), + new OccurenceOrderPlugin(), + new DedupePlugin(), + ], + + production: [ + new UglifyJsPlugin({ + compress: { + warnings: false, + drop_debugger: false + }, + output: { + comments: false + }, + beautify: false + }), + new BannerPlugin(getBanner(), {entryOnly: true}) + ], + + development: [ + /* Dev Plugin */ + // new webpack.HotModuleReplacementPlugin(), + ] + +}//env + + + + + + + + + +if (NODE_ENV === 'production') { + // replace filename `.js` with `.min.js` + config.output.filename = config.output.filename.replace('.js', '.min.js'); + config.output.sourceMapFilename = config.output.sourceMapFilename.replace('.js', '.min.js'); + commons_chunks_plugins = commons_chunks_plugins.map(function(chunk) { + return chunk.filename.replace('.js', '.min.js'); + }); +} +else if (NODE_ENV === 'development') { + // any development actions here +} + +// create CommonsChunkPlugin instance for each config +var combine_common_chunks = commons_chunks_plugins.map(function(config) { + return new CommonsChunkPlugin(config); +}); + +// conbine everything +config.plugins = [].concat(combine_common_chunks, environment_plugins.all, environment_plugins[NODE_ENV]); + + +module.exports = config; + +// Helper functions +function getBanner() { + return 'Angular2 Webpack Starter v'+ pkg.version +' by @gdi2990 from @AngularClass'; +} + +function root(args) { + args = sliceArgs(arguments, 0); + return path.join.apply(path, [__dirname].concat(args)); +} +function rootNode(args) { + args = sliceArgs(arguments, 0); + return root.apply(path, ['node_modules'].concat(args)); +} + diff --git a/pool/shard000/JavaScript/0003783_index.js b/pool/shard000/JavaScript/0003783_index.js new file mode 100644 index 0000000000000000000000000000000000000000..fbd8f5ce3413a1c3cd5d970e7b854e2d20503da7 --- /dev/null +++ b/pool/shard000/JavaScript/0003783_index.js @@ -0,0 +1,50 @@ +'use strict'; + +var path = require('path'); +var _ = require('lodash'); + +function requiredProcessEnv(name) { + if (!process.env[name]) { + throw new Error('You must set the ' + name + ' environment variable'); + } + return process.env[name]; +} + +// All configurations will extend these options +// ============================================ +var all = { + env: process.env.NODE_ENV, + + // Root path of server + root: path.normalize(__dirname + '/../../..'), + + // Server port + port: process.env.PORT || 9000, + + // Server IP + ip: process.env.IP || '0.0.0.0', + + // Should we populate the DB with sample data? + seedDB: false, + + // Secret for session, you will want to change this and make it an environment variable + secrets: { + session: 'wsproto1-secret' + }, + + // MongoDB connection options + mongo: { + options: { + db: { + safe: true + } + } + } +}; + +// Export the config object based on the NODE_ENV +// ============================================== +module.exports = _.merge( + all, + require('./shared'), + require('./' + process.env.NODE_ENV + '.js') || {}); diff --git a/pool/shard000/JavaScript/0003786_x-list.js b/pool/shard000/JavaScript/0003786_x-list.js new file mode 100644 index 0000000000000000000000000000000000000000..faa612e5c2ed43c5dd8b2ef197ce78787b8e5a33 --- /dev/null +++ b/pool/shard000/JavaScript/0003786_x-list.js @@ -0,0 +1,272 @@ +import Component from '@ember/component'; +import { run, scheduleOnce } from '@ember/runloop'; +import { task, timeout } from 'ember-concurrency'; +import ResizableColumns from 'ember-inspector/libs/resizable-columns'; +import LocalStorageService from 'ember-inspector/services/storage/local'; +import { inject as service } from '@ember/service'; +import { readOnly, reads } from '@ember/object/computed'; + +const CHECK_HTML = '✓'; + +export default Component.extend({ + /** + * @property classNames + * @type {Array} + */ + classNames: ['list'], + + /** + * Class to pass to each row in `vertical-collection`. + * + * @property itemClass + * @type {String} + * @default '' + */ + itemClass: '', + + /** + * Layout service used to listen to changes to the application + * layout such as resizing of the main nav or object inspector. + * + * @property layoutService + * @type {Service} + */ + layoutService: service('layout'), + + /** + * Indicate the table's header's height in pixels. + * Set this to `0` when there's no header. + * + * @property headerHeight + * @type {Number} + * @default 31 + */ + headerHeight: 31, + + /** + * The name of the list. Used for `js-` classes added + * to elements of the list. Also used as the default + * key for schema caching. + * + * @property name + * @type {String} + */ + name: null, + + /** + * Service used for storage. Storage is + * needed for caching of widths and visibility of columns. + * The default storage service is local storage however we + * fall back to memory storage if local storage is disabled (For + * example as a security setting in Chrome). + * + * @property storage + * @return {Service} + */ + storage: service(`storage/${LocalStorageService.STORAGE_TYPE_TO_USE}`), + + + /** + * The key used to cache the current schema. Defaults + * to the list's name. + * + * @property storageKey + * @type {String} + */ + storageKey: reads('name'), + + /** + * The schema that contains the list's columns, + * their ids, names, and default visibility. + * + * @property schema + * @type {Object} + */ + schema: null, + + /** + * The array of columns including their ids, names, + * and widths. This array only contains the currently + * visible columns. + * + * @property columns + * @type {Array} + */ + columns: readOnly('resizableColumns.columns'), + + /** + * Hook called whenever attributes are updated. + * We use this to listen to changes to the schema. + * If the schema changes for an existing `x-list` component + * (happens when switching model types for example), we need + * to rebuild the columns from scratch. + * + * @method didUpdateAttrs + * @param {Object} newAttrs and oldAttrs + */ + didUpdateAttrs() { + let oldSchema = this.get('oldSchema'); + let newSchema = this.get('schema'); + if (newSchema && newSchema !== oldSchema) { + scheduleOnce('actions', this, this.setupColumns); + } + this.set('oldSchema', newSchema); + return this._super(...arguments); + }, + + /** + * The instance responsible for building the `columns` + * array. This means that this instance controls + * the widths of the columns as well as their visibility. + * + * @property resizableColumns + * @type {ResizableColumn} + */ + resizableColumns: null, + + /** + * The minimum width a column can be resized to. + * It should be high enough so that the column is still + * visible and resizable. + * + * @property minWidth + * @type {Number} + * @default 10 + */ + minWidth: 10, + + didInsertElement() { + scheduleOnce('afterRender', this, this.setupColumns); + this.onResize = () => { + this.get('debounceColumnWidths').perform(); + }; + window.addEventListener(`resize.${this.get('elementId')}`, this.onResize); + this.get('layoutService').on('resize', this.onResize); + return this._super(...arguments); + }, + + /** + * Setup the context menu which allows the user + * to toggle the visibility of each column. + * + * The context menu opened by right clicking on the table's + * header. + * + * @method setupContextMenu + */ + setupContextMenu() { + let menu = this.resizableColumns.getColumnVisibility().reduce((arr, { id, name, visible }) => { + let check = `${CHECK_HTML}`; + if (!visible) { + check = `${check}`; + } + name = `${check} ${name}`; + arr.push({ + name, + title: name, + fn: run.bind(this, this.toggleColumnVisibility, id) + }); + return arr; + }, []); + + this.showBasicContext = (e) => { + basicContext.show(menu, e); + }; + + const listHeader = this.element.querySelector('.list__header'); + if (listHeader) { + listHeader.addEventListener('contextmenu', this.showBasicContext); + } + }, + + /** + * Toggle a column's visibility. This is called + * when a user clicks on a specific column in the context + * menu. After toggling visibility it destroys the current + * context menu and rebuilds it with the updated column data. + * + * @method toggleColumnVisibility + * @param {String} id The column's id + */ + toggleColumnVisibility(id) { + this.resizableColumns.toggleVisibility(id); + const listHeader = this.element.querySelector('.list__header'); + if (listHeader) { + listHeader.removeEventListener('contextmenu', this.showBasicContext); + } + this.setupContextMenu(); + }, + + /** + * Restartable `ember-concurrency` task called whenever + * the table widths need to be recalculated due to some + * resizing of the window or application. + * + * @property debounceColumnWidths + * @type {Object} Ember Concurrency task + */ + debounceColumnWidths: task(function* () { + yield timeout(100); + this.resizableColumns.setTableWidth(this.getTableWidth()); + }).restartable(), + + /** + * Hook called when the component element will be destroyed. + * Clean up everything. + * + * @method willDestroyElement + */ + willDestroyElement() { + window.removeEventListener(`.${this.elementId}`, this.onResize); + const listHeader = this.element.querySelector('.list__header'); + if (listHeader) { + listHeader.removeEventListener('contextmenu', this.showBasicContext); + } + this.get('layoutService').off('resize', this.onResize); + return this._super(...arguments); + }, + + /** + * Returns the table's width in pixels. + * + * @method getTableWidth + * @return {Number} The width in pixels + */ + getTableWidth() { + return this.element.querySelector('.list__table-container').clientWidth; + }, + + /** + * Creates a new `ResizableColumns` instance which + * will calculate the columns' width and visibility. + * + * @method setupColumns + */ + setupColumns() { + let resizableColumns = new ResizableColumns({ + key: this.get('storageKey'), + tableWidth: this.getTableWidth(), + minWidth: this.get('minWidth'), + storage: this.get('storage'), + columnSchema: this.get('schema.columns') || [] + }); + resizableColumns.build(); + this.set('resizableColumns', resizableColumns); + this.setupContextMenu(); + }, + + actions: { + /** + * Called whenever a column is resized using the draggable handle. + * It is responsible for updating the column info by notifying + * `resizableColumns` about the update. + * + * @method didResize + * @param {String} id The column's id + * @param {Number} width The new width + */ + didResize(id, width) { + this.resizableColumns.updateColumnWidth(id, width); + } + } +}); diff --git a/pool/shard000/JavaScript/0003787_ReviewRow.test.js b/pool/shard000/JavaScript/0003787_ReviewRow.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6cfdd4bc9c0e5e638d1ebf8f9fdd24173b1b5796 --- /dev/null +++ b/pool/shard000/JavaScript/0003787_ReviewRow.test.js @@ -0,0 +1,47 @@ +/* + * Copyright 2020 Verizon Media + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { render } from '@testing-library/react'; +import ReviewRow from '../../../components/review/ReviewRow'; +import { colors } from '../../../components/denali/styles'; + +describe('ReviewRow', () => { + it('should render', () => { + let details = { + memberName: 'user.member', + }; + let domain = 'domain'; + let role = 'roleName'; + let color = colors.row; + let idx = '50'; + const { getByTestId } = render( + + + + +
    + ); + const reviewRow = getByTestId('review-row'); + + expect(reviewRow).toMatchSnapshot(); + }); +}); diff --git a/pool/shard000/JavaScript/0003789_keyboard.js b/pool/shard000/JavaScript/0003789_keyboard.js new file mode 100644 index 0000000000000000000000000000000000000000..54403e4a6ed73e7349b2317872bed55f48ee43d2 --- /dev/null +++ b/pool/shard000/JavaScript/0003789_keyboard.js @@ -0,0 +1,133 @@ +/* + Keyboard + Keyboard class + By Luke Nickerson, 2016 +*/ +(function(){ + var Keyboard = function(){ + this.keyDownActions = {}; + this.keyUpActions = {}; + this._keyCodeMap = { + "9": "TAB", + + "13": "ENTER", + + "27": "ESC", + + "32": "SPACE", + + "37": "LEFT", + "38": "UP", + "39": "RIGHT", + "40": "DOWN", + + "48": "0", + "49": "1", + "50": "2", + "51": "3", + "52": "4", + "53": "5", + "54": "6", + "55": "7", + "56": "8", + "57": "9", + + "65": "a", + + "68": "d", + "69": "e", + + "81": "q", + + "83": "s", + + "87": "w", + "88": "x", + + "90": "z", + + "112": "F1", + "113": "F2", + "114": "F3", + "115": "F4", + "116": "F5", + "117": "F6", + "118": "F7", + "119": "F8", + "120": "F9", + "121": "F10", + "122": "F11", + "123": "F12", + + }; + }; + + Keyboard.prototype.getKeyFromKeyCode = function (keyCode) { + return this._keyCodeMap[keyCode]; + }; + + Keyboard.prototype._isFunctionKey = function (keyCode) { + keyCode = parseInt(keyCode); + return (keyCode >= 112 && keyCode <= 123) ? true : false; + } + + Keyboard.prototype.tap = function (key) { + this._fireAction(key, this.keyDownActions); + this._fireAction(key, this.keyUpActions); + }; + + Keyboard.prototype._fireAction = function (key, keyActions) { + var action = this.keyDownActions[key]; + if (typeof action === 'function') { + action(key); + return true; + } else { + console.warn("KB action not found", key); + return false; + } + }; + + Keyboard.prototype.setup = function (options) { + var kb = this; + options = options || {}; + options.keyDownActions = options.keyDownActions || {}; + if (options.wasd) { + if (typeof options.keyDownActions["w"] !== 'function') { + options.keyDownActions["w"] = options.keyDownActions["UP"]; + } + if (typeof options.keyDownActions["a"] !== 'function') { + options.keyDownActions["a"] = options.keyDownActions["LEFT"]; + } + if (typeof options.keyDownActions["s"] !== 'function') { + options.keyDownActions["s"] = options.keyDownActions["DOWN"]; + } + if (typeof options.keyDownActions["d"] !== 'function') { + options.keyDownActions["d"] = options.keyDownActions["RIGHT"]; + } + } + kb.keyDownActions = options.keyDownActions; + //console.log(kb.keyDownActions); + kb.clear(); + + $(document).on('keydown', function(e){ + kb._fireAction(kb.getKeyFromKeyCode(e.which), options.keyDownActions); + //console.log(e.which); + if (!kb._isFunctionKey(e.which)) { + e.preventDefault(); + } + }).on('keyup', function(e){ + // *** + }); + return kb; + }; + + Keyboard.prototype.clear = function () { + $(document).off('keydown').off('keyup'); + }; + + + + if (typeof RocketBoots == "object") { + RocketBoots.installComponent("keyboard", "Keyboard", Keyboard); + } else window.Keyboard = Keyboard; +})(); \ No newline at end of file diff --git a/pool/shard000/JavaScript/0003793_index.js b/pool/shard000/JavaScript/0003793_index.js new file mode 100644 index 0000000000000000000000000000000000000000..b652090cd51d3a2d5ededb89739f17c5ef9652a7 --- /dev/null +++ b/pool/shard000/JavaScript/0003793_index.js @@ -0,0 +1,17 @@ +import { bindActionCreators } from 'redux'; +import { connect } from 'react-redux'; +import { withRouter } from 'react-router'; +import reducer from './ModuleStreamDetailsReducer'; +import * as moduleStreamDetailsActions from './ModuleStreamDetailsActions'; +import ModuleStreamDetails from './ModuleStreamDetails'; + +const mapStateToProps = state => ({ + moduleStreamDetails: state.katello.moduleStreamDetails, +}); + +const actions = { ...moduleStreamDetailsActions }; +const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch); + +export const moduleStreamDetails = reducer; + +export default connect(mapStateToProps, mapDispatchToProps)(withRouter(ModuleStreamDetails)); diff --git a/pool/shard000/JavaScript/0003794_json_task_request_translator_spec.js b/pool/shard000/JavaScript/0003794_json_task_request_translator_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..cc7d87abac5952069aecb575cc803831a3f63aa4 --- /dev/null +++ b/pool/shard000/JavaScript/0003794_json_task_request_translator_spec.js @@ -0,0 +1,23 @@ +var JsonTaskRequestTranslator = require("../../../lib/engine/common/json_task_request_translator"); +var TaskRequest = require("../../../lib/engine/common/task_request"); + +describe("JsonTaskRequestTranslator", function(){ + beforeEach(function(){ + this.raw_task_request = JSON.stringify({ + task_id: "123", + context: "foo", + locals: "bar", + code: "baz" + }); + this.translator = JsonTaskRequestTranslator.create(); + }); + + it("translates a JSON string into a TaskRequest object", function(){ + var translated_task_request = this.translator.translate(this.raw_task_request); + expect(translated_task_request instanceof TaskRequest).toBeTruthy(); + expect(translated_task_request.getTaskId()).toBe("123"); + expect(translated_task_request.getContext()).toBe("foo"); + expect(translated_task_request.getLocals()).toBe("bar"); + expect(translated_task_request.getCode()).toBe("baz"); + }); +}); \ No newline at end of file